Version: v0.0.9 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 41 Imported by: 0




View Source
const (

	// maximum number of binding evidence(recommended)
	MaxBindingNum = 10

	PriorityProposalSize = wire.MaxBlockPayload / 20
View Source
const (
	// MaxSigOpsPerBlock is the maximum number of signature operations
	// allowed for a block.  It is a fraction of the max block payload size.
	MaxSigOpsPerBlock = wire.MaxBlockPayload / 150 * txscript.MaxPubKeysPerMultiSig

	// MaxTimeOffsetSeconds is the maximum number of seconds a block time
	// is allowed to be ahead of the current time.  This is currently 2
	// hours.
	MaxTimeOffsetSeconds = 2 * 60 * 60
View Source
const BlockCacheFileName = "blocks.cache"
View Source
const CheckpointConfirmations = 10000


View Source
var (
	ErrInvalidTime           = errors.New("block timestamp has a higher precsion the one second")
	ErrTimeTooOld            = errors.New("block timestamp is not after expected prevNode")
	ErrTimeTooNew            = errors.New("block timestamp of uinx is too far in the future")
	ErrUnexpectedDifficulty  = errors.New("block difficulty is not the expected value")
	ErrUnexpectedChallenge   = errors.New("block challenge is not the expected value")
	ErrInvalidMerkleRoot     = errors.New("block transaction merkle root is invalid")
	ErrInvalidProposalRoot   = errors.New("block proposal merkle root is invalid")
	ErrTooManyTransactions   = errors.New("block contains too many transactions")
	ErrNoTxOutputs           = errors.New("transaction has no outputs")
	ErrDuplicateTxInputs     = errors.New("transaction contains duplicate inputs")
	ErrConnectGenesis        = errors.New("genesis block should not be connected")
	ErrOverwriteTx           = errors.New("tried to overwrite not fully spent transaction")
	ErrTooManySigOps         = errors.New("too many signature operations")
	ErrFirstTxNotCoinbase    = errors.New("first transaction in block is not a coinbase")
	ErrMultipleCoinbases     = errors.New("block contains other coinbase")
	ErrLowQuality            = errors.New("block's proof quality is lower than expected min target")
	ErrTimestampFormat       = errors.New("wrong timestamp format")
	ErrBadBlockHeight        = errors.New("block height does not match the expected height")
	ErrChainID               = errors.New("block's chainID is not equal to expected chainID")
	ErrBlockSIG              = errors.New("block signature verify failed")
	ErrInvalidBlockVersion   = errors.New("block's version is not valid")
	ErrInvalidBitLength      = errors.New("block's bitLength is smaller than the last submission of this public key")
	ErrMismatchedBindingRoot = errors.New("block binding root mismatched")
	ErrNoValidBinding        = errors.New("no valid binding")
	ErrInvalidProofType      = errors.New("invalid proof type")
	ErrCheckpointTimeTooOld  = errors.New("ErrCheckpointTimeTooOld")
	ErrBadCheckpoint         = errors.New("ErrBadCheckpoint")
	ErrForkTooOld            = errors.New("ErrForkTooOld")

	// BanList
	ErrBannedPk      = errors.New("block builder puKey has been banned")
	ErrBanSelfPk     = errors.New("block's pubKey is banned in header banList")
	ErrBanList       = errors.New("invalid banList")
	ErrCheckBannedPk = errors.New("invalid faultPk")

	// TxPool
	ErrTxPoolNil           = errors.New("the txpool is nil")
	ErrTxExsit             = errors.New("transaction is not in the pool")
	ErrFindTxByAddr        = errors.New("address does not have any transactions in the pool")
	ErrCoinbaseTx          = errors.New("transaction is an individual coinbase")
	ErrProhibitionOrphanTx = errors.New("Do not accept orphan transactions")
	ErrInvalidTxVersion    = errors.New("transaction version is invalid")

	// Coinbase
	ErrCoinbaseTxInWitness = errors.New("coinbaseTx txIn`s witness size must be 0")
	ErrBadCoinbaseValue    = errors.New("coinbase transaction for block pays is more than expected value")
	ErrBadCoinbaseHeight   = errors.New("the coinbase payload serialized block height does not equal expected height")
	ErrCoinbaseOutputValue = errors.New("the coinbaseTx output value is not correct")
	ErrCoinbaseOutputNum   = errors.New("incorrect coinbase output number")
	ErrUnexpectedCoinbase  = errors.New("unexpected coinbase")
	ErrNilChiaPoolPk       = errors.New("nil chia pool pk")

	// StakingTx & BindingTx
	ErrStandardBindingTx     = errors.New("input and output of the transaction are all binding transactions")
	ErrInvalidStakingTxValue = errors.New("invalid staking tx value")
	ErrInvalidFrozenPeriod   = errors.New("invalid frozen period")
	ErrStakingRewardNum      = errors.New("incorrect staking reward number")
	ErrBindingPubKey         = errors.New("binding pubkey does not match miner pubkey")
	ErrBindingInputMissing   = errors.New("input of binding missing")
	ErrDuplicateStaking      = errors.New("duplicate staking")
	ErrPlotPKAlreadyBound    = errors.New("plot pk already bound")
	ErrPlotPKNotBound        = errors.New("plot pk not bound")
	ErrBindingValueNotEnough = errors.New("binding value not enough")
	ErrInvalidBindingScript  = errors.New("invalid binding script")
	ErrFeeForPoolPkCoinbase  = errors.New("fee for setting pool_pk coinbase not enough")
	ErrPayloadNonce          = errors.New("invalid payload nonce")

	// TxIn
	ErrFindReferenceInput = errors.New("unable find reference transaction ")
	ErrBadTxInput         = errors.New("transaction input refers to previous output is invalid")
	ErrMissingTx          = errors.New("unable to find input transaction")
	ErrNoTxInputs         = errors.New("transaction has no inputs")

	// LockTime
	ErrSequenceNotSatisfied = errors.New("transaction's sequence locks on inputs not met")
	ErrImmatureSpend        = errors.New("try to spend immature coins")
	ErrUnfinalizedTx        = errors.New("transaction is not finalized")

	// Value
	ErrDoubleSpend   = errors.New("the transaction has been spent")
	ErrDuplicateTx   = errors.New("the transaction is duplicate")
	ErrBadTxOutValue = errors.New("transaction output value is invalid")
	ErrSpendTooHigh  = errors.New("total value of all transaction inputs  is less than the spent value of output")

	// Fee
	ErrBadFees              = errors.New("total fees for block overflows accumulator")
	ErrInsufficientFee      = errors.New("transaction`s fees is under the required amount")
	ErrInsufficientPriority = errors.New("transaction`s Priority is under the required amount")
	ErrDust                 = errors.New("transaction output payment is dust")

	// Size
	ErrNonStandardTxSize = errors.New("transaction size is larger than max allowed size")
	ErrWitnessSize       = errors.New("transaction input witness size is large than max allowed size")
	ErrTxTooBig          = errors.New("transaction size is too big")
	ErrBlockTooBig       = errors.New("block size more than MaxBlockPayload")
	ErrTxMsgPayloadSize  = errors.New("transaction payload size is large than max allowed size")

	// TxScript
	ErrSignaturePushOnly   = errors.New("transaction input witness is not push only")
	ErrNuLLDataScript      = errors.New("more than one transaction output in a nulldata script")
	ErrNonStandardType     = errors.New("non-standard script form")
	ErrParseInputScript    = errors.New("failed to parse transaction input script")
	ErrExpectedSignInput   = errors.New("transaction expected input signature not satisfied")
	ErrMultiSigScriptPKNum = errors.New("multi-signature script with wrong pubkey number ")
	ErrMultiSigNumSign     = errors.New("multi-signature script with wrong signature number ")
	ErrScriptMalformed     = errors.New("failed to construct vm engine")
	ErrScriptValidation    = errors.New("failed to validate signature")
	ErrWitnessLength       = errors.New("invalid witness length")


func CalcBlockSubsidy

func CalcBlockSubsidy(height uint64, chainParams *config.Params, hasValidBinding, hasStaking bool) (miner, superNode massutil.Amount, err error)

CalcBlockSubsidy returns the subsidy amount a block at the provided height should have. This is mainly used for determining how much the coinbase for newly generated blocks awards as well as validating the coinbase for blocks has the expected value.

The subsidy is halved every SubsidyHalvingInterval blocks. Mathematically this is: BaseSubsidy / 2^(height/subsidyHalvingInterval)

At the Target block generation rate for the main network, this is approximately every 4 years.

func CalcMinRequiredTxRelayFee

func CalcMinRequiredTxRelayFee(serializedSize int64, minTxRelayFee massutil.Amount) (massutil.Amount, error)

CalcMinRequiredTxRelayFee returns the minimum transaction fee required for a transaction with the passed serialized size to be accepted into the memory pool and relayed.

func CheckBlockSanity

func CheckBlockSanity(block *massutil.Block, chainID wire.Hash, pocLimit *big.Int) error

CheckBlockSanity performs some preliminary checks on a block to ensure it is sane before continuing with block processing. These checks are context free.

func CheckCoinbaseHeight

func CheckCoinbaseHeight(block *massutil.Block) error

CheckCoinbaseHeight checks whether block height in coinbase matches block height in header. We do not check *block's existence because this func is called in another func that *block exists.

func CheckNonceAndSetPoolPkCoinbase

func CheckNonceAndSetPoolPkCoinbase(trie state.Trie, payload []byte) error

func CheckProofOfCapacity

func CheckProofOfCapacity(block *massutil.Block, pocLimit *big.Int) error

CheckProofOfWork ensures the block header bits which indicate the Target difficulty is in min/max range and that the block's proof quality is less than the Target difficulty as claimed.

func CheckTransactionInputs

func CheckTransactionInputs(tx *massutil.Tx, txHeight uint64, txStore TxStore) (massutil.Amount, error)

CheckTransactionInputs performs a series of checks on the inputs to a transaction to ensure they are valid. An example of some of the checks include verifying all inputs exist, ensuring the coinbase seasoning requirements are met, detecting double spends, validating all values and fees are in the legal range and the total output amount doesn't exceed the input amount, and verifying the signatures to prove the spender was the owner of the masses and therefore allowed to spend them. As it checks the inputs, it also calculates the total fees for the transaction and returns that value.

func CheckTransactionSanity

func CheckTransactionSanity(tx *massutil.Tx) error

CheckTransactionSanity performs some preliminary checks on a transaction to ensure it is sane. These checks are context free.

func CountSigOps

func CountSigOps(tx *massutil.Tx) int

CountSigOps returns the number of signature operations for all transaction // input and output scripts in the provided transaction. This uses the // quicker, but imprecise, signature operation counting mechanism from // txscript.

func EncodePayload

func EncodePayload(payload *TransactionPayload) []byte

func EqualPublicKeys

func EqualPublicKeys(a, b interfaces.PublicKey) bool

func GetBindingState

func GetBindingState(bc *Blockchain, root common.Hash) (state.Trie, error)

func GetMaxStandardTxSize

func GetMaxStandardTxSize() int

func GetNetworkBinding

func GetNetworkBinding(bindingState state.Trie) (massutil.Amount, error)

func GetPoolPkCoinbase

func GetPoolPkCoinbase(trie state.Trie, poolPk []byte) ([]byte, uint32, error)

func IsCoinBase

func IsCoinBase(tx *massutil.Tx) bool

IsCoinBase determines whether or not a transaction is a coinbase. A coinbase is a special transaction created by miners that has no inputs. This is represented in the block chain by a transaction with a single input that has a previous output transaction index set to the maximum value along with a zero hash.

This function only differs from IsCoinBaseTx in that it works with a higher level util transaction as opposed to a raw wire transaction.

func IsCoinBaseTx

func IsCoinBaseTx(msgTx *wire.MsgTx) bool

IsCoinBaseTx determines whether or not a transaction is a coinbase. A coinbase is a special transaction created by miners that has no inputs. This is represented in the block chain by a transaction with a single input that has a previous output transaction index set to the maximum value along with a zero hash.

This function only differs from IsCoinBase in that it works with a raw wire transaction as opposed to a higher level util transaction.

func IsDBNotFound

func IsDBNotFound(err error) bool

func IsDust

func IsDust(txOut *wire.TxOut, minRelayTxFee massutil.Amount) (bool, error)

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *massutil.Tx, blockHeight uint64, blockTime time.Time) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func LockTimeToSequence

func LockTimeToSequence(isSeconds bool, locktime uint64) uint64

LockTimeToSequence converts the passed relative locktime to a sequence number in accordance to BIP-68. See:

  • (Compatibility)

func PutNetworkBinding

func PutNetworkBinding(bindingState state.Trie, totalBinding massutil.Amount) error

func SequenceLockActive

func SequenceLockActive(sequenceLock *SequenceLock, blockHeight uint64,
	medianTimePast time.Time) bool

SequenceLockActive determines if a transaction's sequence locks have been met, meaning that all the inputs of a given transaction have reached a height or time sufficient for their relative lock-time maturity.

func SignPoolPkPayload

func SignPoolPkPayload(poolSk *chiapos.PrivateKey, coinbaseScriptAddress []byte, nonce uint32) (*chiapos.G2Element, error)

func TryParserBindingPK

func TryParserBindingPK(pkScript []byte) ([]byte, error)

Returns nil if not a binding script

func ValidateTransactionScripts

func ValidateTransactionScripts(bc *Blockchain, tx *massutil.Tx, txStore TxStore, flags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) error

ValidateTransactionScripts validates the scripts for the passed transaction using multiple goroutines.

func VerifyBytes

func VerifyBytes(data []byte, sig *pocec.Signature, pubkey *pocec.PublicKey) (bool, error)

Verify Signature

func VerifyPoolPkPayload

func VerifyPoolPkPayload(poolPk *chiapos.G1Element, signature *chiapos.G2Element, coinbaseScriptAddress []byte, nonce uint32) (bool, error)


type AddrIndexer

type AddrIndexer struct {
	// contains filtered or unexported fields

AddrIndexer provides a concurrent service for indexing the transactions of target blocks based on the addresses involved in the transaction.

func NewAddrIndexer

func NewAddrIndexer(db database.Db, stateBindingDb state.Database) (*AddrIndexer, error)

newAddrIndexer creates a new block address indexer. Use Start to begin processing incoming index jobs.

func (*AddrIndexer) SyncAttachBlock

func (a *AddrIndexer) SyncAttachBlock(bindingState state.Trie, block *massutil.Block, txStore TxStore) error

SyncAttachBlock synchronously queues a newly solved block to have its transactions indexed by address.

func (*AddrIndexer) SyncDetachBlock

func (a *AddrIndexer) SyncDetachBlock(block *massutil.Block) error

type BehaviorFlags

type BehaviorFlags uint32
const (
	// TODO: add FastMode
	BFFastAdd BehaviorFlags = 1 << iota


	// BFNone is a convenience value to specifically indicate no flags.
	BFNone BehaviorFlags = 0

type BindPoolCoinbaseParams

type BindPoolCoinbaseParams struct {
	PoolPK                *chiapos.G1Element
	Signature             *chiapos.G2Element
	CoinbaseScriptAddress []byte // address.ScriptAddress()
	Nonce                 uint32 // start at 1, 0 means not bound


func (*BindPoolCoinbaseParams) Decode

func (params *BindPoolCoinbaseParams) Decode(data []byte) (err error)

data structure:

[0:48]    - public key
[48:144]  - signature
[144:148] - nonce
[148:]    - witness script hash, length zero to delete

func (*BindPoolCoinbaseParams) Encode

func (params *BindPoolCoinbaseParams) Encode() []byte

func (*BindPoolCoinbaseParams) String

func (p *BindPoolCoinbaseParams) String() string

type BlockNode

type BlockNode struct {
	InMainChain     bool
	Parent          *BlockNode
	Hash            *wire.Hash
	CapSum          *big.Int
	ChainID         wire.Hash
	Version         uint64
	Height          uint64
	Timestamp       time.Time
	Previous        wire.Hash
	TransactionRoot wire.Hash
	WitnessRoot     wire.Hash
	ProposalRoot    wire.Hash
	Target          *big.Int
	Challenge       wire.Hash
	Quality         *big.Int
	// contains filtered or unexported fields

func NewBlockNode

func NewBlockNode(header *wire.BlockHeader, blockHash *wire.Hash, flags BehaviorFlags) *BlockNode

func (*BlockNode) Ancestor

func (node *BlockNode) Ancestor(height uint64) *BlockNode

Ancestor returns the ancestor block node at the provided height by following the chain backwards from this node. The returned block will be nil when a height is requested that is after the height of the passed node or is less than zero.

func (*BlockNode) BannedPublicKeys

func (node *BlockNode) BannedPublicKeys() []interfaces.PublicKey

func (*BlockNode) BindingState

func (node *BlockNode) BindingState(stateDb state.Database) (state.Trie, error)

func (*BlockNode) BitLength

func (node *BlockNode) BitLength() int

func (*BlockNode) BlockHeader

func (node *BlockNode) BlockHeader() *wire.BlockHeader

func (*BlockNode) ParentBindingState

func (node *BlockNode) ParentBindingState(stateDb state.Database) (state.Trie, error)

Returns a copy of parent state.

func (*BlockNode) PublicKey

func (node *BlockNode) PublicKey() interfaces.PublicKey

func (*BlockNode) SetBindingState

func (node *BlockNode) SetBindingState(state state.Trie) error

Set nil to clear state

type BlockProgressLogger

type BlockProgressLogger struct {
	// contains filtered or unexported fields

BlockProgressLogger provides periodic logging for other services in order to show users progress of certain "actions" involving some or all current blocks. Ex: syncing to best chain, indexing all blocks, etc.

func NewBlockProgressLogger

func NewBlockProgressLogger(progressMessage string) *BlockProgressLogger

NewBlockProgressLogger returns a new block progress logger. The progress message is templated as follows:

{progressAction} {numProcessed} {blocks|block} in the last {timePeriod}
({numTxs}, height {lastBlockHeight}, {lastBlockTimeStamp})

func (*BlockProgressLogger) LogBlockHeight

func (b *BlockProgressLogger) LogBlockHeight(block *massutil.Block)

LogBlockHeight logs a new block height as an information message to show progress to the user. In order to prevent spam, it limits logging to one message every 10 seconds with duration and totals included.

func (*BlockProgressLogger) SetLastLogTime

func (b *BlockProgressLogger) SetLastLogTime(time time.Time)

func (*BlockProgressLogger) Start

func (b *BlockProgressLogger) Start()

func (*BlockProgressLogger) Stop

func (b *BlockProgressLogger) Stop() error

type BlockTemplate

type BlockTemplate struct {
	Block              *wire.MsgBlock
	TotalFee           massutil.Amount
	SigOpCounts        []int64
	Height             uint64
	ValidPayAddress    bool
	MerkleCache        []*wire.Hash
	WitnessMerkleCache []*wire.Hash
	Err                error

type BlockTree

type BlockTree struct {
	// contains filtered or unexported fields

func NewBlockTree

func NewBlockTree() *BlockTree

type Blockchain

type Blockchain struct {
	// contains filtered or unexported fields

func NewBlockchain

func NewBlockchain(config *Config) (*Blockchain, error)

func (*Blockchain) BestBlockHash

func (chain *Blockchain) BestBlockHash() *wire.Hash

func (*Blockchain) BestBlockHeader

func (chain *Blockchain) BestBlockHeader() *wire.BlockHeader

func (*Blockchain) BestBlockHeight

func (chain *Blockchain) BestBlockHeight() uint64

func (*Blockchain) BestBlockNode

func (chain *Blockchain) BestBlockNode() *BlockNode

func (*Blockchain) BlockWaiter

func (chain *Blockchain) BlockWaiter(height uint64) (<-chan *BlockNode, error)

func (*Blockchain) CalcNextChallenge

func (chain *Blockchain) CalcNextChallenge() (*wire.Hash, error)

CalcNextChallenge calculates the required challenge for the block after the end of the current best chain based on the challenge adjustment rules.

func (*Blockchain) CalcNextTarget

func (chain *Blockchain) CalcNextTarget(newBlockTime time.Time) (*big.Int, error)

func (*Blockchain) CalcPastMedianTime

func (chain *Blockchain) CalcPastMedianTime() (time.Time, error)

CalcPastMedianTime calculates the median time of the previous few blocks prior to, and including, the end of the current best chain. It is primarily used to ensure new blocks have sane timestamps.

This function is NOT safe for concurrent access.

func (*Blockchain) CalcSequenceLock

func (chain *Blockchain) CalcSequenceLock(tx *massutil.Tx, txStore TxStore) (*SequenceLock, error)

CalcSequenceLock computes a relative lock-time SequenceLock for the passed transaction using the passed UtxoViewpoint to obtain the past median time for blocks in which the referenced inputs of the transactions were included within. The generated SequenceLock lock can be used in conjunction with a block height, and adjusted median block time to determine if all the inputs referenced within a transaction have reached sufficient maturity allowing the candidate transaction to be included in a block.

This function is safe for concurrent access.

func (*Blockchain) ChainID

func (chain *Blockchain) ChainID() *wire.Hash

func (*Blockchain) Checkpoints

func (b *Blockchain) Checkpoints() []config.Checkpoint

Checkpoints returns a slice of checkpoints (regardless of whether they are already known). When there are no checkpoints for the chain, it will return nil.

This function is safe for concurrent access.

func (*Blockchain) CurrentIndexHeight

func (chain *Blockchain) CurrentIndexHeight() uint64

func (*Blockchain) FetchMinedBlocks

func (chain *Blockchain) FetchMinedBlocks(pubKey interfaces.PublicKey) ([]uint64, error)

func (*Blockchain) FetchOldBinding

func (chain *Blockchain) FetchOldBinding(scriptHash []byte) ([]*database.BindingTxReply, error)

func (*Blockchain) FetchTransactionStore

func (chain *Blockchain) FetchTransactionStore(tx *massutil.Tx, includeSpent bool) TxStore

FetchTransactionStore fetches the input transactions referenced by the passed transaction from the point of view of the end of the main chain. It also attempts to fetch the transaction itself so the returned TxStore can be examined for duplicate transactions.

func (*Blockchain) GetBlockByHash

func (chain *Blockchain) GetBlockByHash(hash *wire.Hash) (*massutil.Block, error)

func (*Blockchain) GetBlockByHeight

func (chain *Blockchain) GetBlockByHeight(height uint64) (*massutil.Block, error)

func (*Blockchain) GetBlockHashByHeight

func (chain *Blockchain) GetBlockHashByHeight(height uint64) (*wire.Hash, error)

func (*Blockchain) GetBlockStakingRewardRankOnList

func (chain *Blockchain) GetBlockStakingRewardRankOnList(height uint64) ([]database.Rank, error)

GetBlockStakingRewardRankOnList returns staking reward list at any height.

func (*Blockchain) GetHeaderByHash

func (chain *Blockchain) GetHeaderByHash(hash *wire.Hash) (*wire.BlockHeader, error)

func (*Blockchain) GetHeaderByHeight

func (chain *Blockchain) GetHeaderByHeight(height uint64) (*wire.BlockHeader, error)

func (*Blockchain) GetNetworkBinding

func (chain *Blockchain) GetNetworkBinding(height uint64) (massutil.Amount, error)

func (*Blockchain) GetNewBinding

func (chain *Blockchain) GetNewBinding(script []byte) (massutil.Amount, error)

func (*Blockchain) GetPoolPkCoinbase

func (chain *Blockchain) GetPoolPkCoinbase(poolPks [][]byte) (map[string]string, map[string]uint32, error)

func (*Blockchain) GetTransaction

func (chain *Blockchain) GetTransaction(hash *wire.Hash) (*wire.MsgTx, error)

func (*Blockchain) GetTransactionInDB

func (chain *Blockchain) GetTransactionInDB(hash *wire.Hash) ([]*database.TxReply, error)

func (*Blockchain) GetTxPool

func (chain *Blockchain) GetTxPool() *TxPool

func (*Blockchain) GetUnexpiredStakingRank

func (chain *Blockchain) GetUnexpiredStakingRank(height uint64) ([]database.Rank, error)

GetUnexpiredStakingRank returns all the unexpired staking rank.

func (*Blockchain) HasCheckpoints

func (b *Blockchain) HasCheckpoints() bool

HasCheckpoints returns whether this BlockChain has checkpoints defined.

This function is safe for concurrent access.

func (*Blockchain) InMainChain

func (chain *Blockchain) InMainChain(hash wire.Hash) bool

func (*Blockchain) InsertChain

func (chain *Blockchain) InsertChain(block *massutil.Block) (isOrphan bool, err error)

for importchain

func (*Blockchain) IsCheckpointCandidate

func (b *Blockchain) IsCheckpointCandidate(block *massutil.Block) (bool, error)

IsCheckpointCandidate returns whether or not the passed block is a good checkpoint candidate.

The factors used to determine a good checkpoint are:

  • The block must be in the main chain
  • The block must be at least 'CheckpointConfirmations' blocks prior to the current end of the main chain
  • The timestamps for the blocks before and after the checkpoint must have timestamps which are also before and after the checkpoint, respectively (due to the median time allowance this is not always the case)
  • The block must not contain any strange transaction such as those with nonstandard scripts

The intent is that candidates are reviewed by a developer to make the final decision and then manually added to the list of checkpoints for a network.

This function is safe for concurrent access.

func (*Blockchain) LatestCheckpoint

func (b *Blockchain) LatestCheckpoint() *config.Checkpoint

LatestCheckpoint returns the most recent checkpoint (regardless of whether it is already known). When there are no defined checkpoints for the active chain instance, it will return nil.

This function is safe for concurrent access.

func (*Blockchain) NewBlockTemplate

func (chain *Blockchain) NewBlockTemplate(payoutAddresses []massutil.Address, templateCh chan interface{}) error

func (*Blockchain) ProcessBlock

func (chain *Blockchain) ProcessBlock(block *massutil.Block) (bool, error)

ProcessBlock is the entry for chain update

func (*Blockchain) ProcessTx

func (chain *Blockchain) ProcessTx(tx *massutil.Tx) (bool, error)

func (*Blockchain) RegisterListener

func (chain *Blockchain) RegisterListener(listener Listener)

func (*Blockchain) RetrieveFaultPks

func (chain *Blockchain) RetrieveFaultPks()

func (*Blockchain) RetrievePunishment

func (chain *Blockchain) RetrievePunishment() ([]*wire.FaultPubKey, error)

RetrievePunishment retrieves faultPks from database, sending them to memPool.

func (*Blockchain) TstFetchInputTransactions

func (chain *Blockchain) TstFetchInputTransactions(node *BlockNode, block *massutil.Block) (TxStore, error)

func (*Blockchain) TstgetPrevNodeFromBlock

func (chain *Blockchain) TstgetPrevNodeFromBlock(block *massutil.Block) (*BlockNode, error)

func (*Blockchain) UnregisterListener

func (chain *Blockchain) UnregisterListener(listener Listener)

type CoinbasePayload

type CoinbasePayload struct {
	// contains filtered or unexported fields


coinbase payload


func NewCoinbasePayload

func NewCoinbasePayload() *CoinbasePayload

func (*CoinbasePayload) Bytes

func (p *CoinbasePayload) Bytes() []byte

func (*CoinbasePayload) NumStakingReward

func (p *CoinbasePayload) NumStakingReward() uint32

func (*CoinbasePayload) SetBytes

func (p *CoinbasePayload) SetBytes(data []byte) error

type Config

type Config struct {
	DB             database.Db
	StateBindingDb state.Database
	ChainParams    *chaincfg.Params
	Checkpoints    []chaincfg.Checkpoint
	CachePath      string

type DoubleMiningDetector

type DoubleMiningDetector struct {
	// contains filtered or unexported fields

func NewDoubleMiningDetector

func NewDoubleMiningDetector(db database.Db) *DoubleMiningDetector

type Listener

type Listener interface {
	OnBlockConnected(*wire.MsgBlock) error
	OnTransactionReceived(tx *wire.MsgTx) error

type OrphanBlockPool

type OrphanBlockPool struct {
	// contains filtered or unexported fields

type OrphanTxPool

type OrphanTxPool struct {
	// contains filtered or unexported fields

type PayloadMethod

type PayloadMethod uint16
const (
	BindPoolCoinbase PayloadMethod = 1 + iota // for chia

type PayloadParams

type PayloadParams interface {
	Encode() []byte
	String() string

type PoCTemplate

type PoCTemplate struct {
	Height        uint64
	Timestamp     time.Time
	Previous      wire.Hash
	Challenge     wire.Hash
	GetTarget     func(time.Time) *big.Int
	RewardAddress []database.Rank
	GetCoinbase   func(Proof, massutil.Amount) (*massutil.Tx, error)
	PassBinding   func(Proof) bool
	Err           error

type Proof

type Proof interface {
	// Returns PublicKey.SerializeCompressed()
	PlotPublicKey() []byte
	ProofType() poc.ProofType
	ProofBitLength() int
	// Returns PublicKey.SerializeCompressed()
	ChiaPoolPublicKey() []byte
	ChiaPlotID() [32]byte

type ProposalPool

type ProposalPool struct {
	// contains filtered or unexported fields

func NewProposalPool

func NewProposalPool(faults []*wire.FaultPubKey) *ProposalPool

func (*ProposalPool) InsertFaultPubKey

func (pp *ProposalPool) InsertFaultPubKey(fpk *wire.FaultPubKey)

func (*ProposalPool) PunishmentProposals

func (pp *ProposalPool) PunishmentProposals() []*PunishmentProposal

PunishmentProposals returns proposals with the same bitlength each call.

func (*ProposalPool) SyncAttachBlock

func (pp *ProposalPool) SyncAttachBlock(block *massutil.Block)

func (*ProposalPool) SyncDetachBlock

func (pp *ProposalPool) SyncDetachBlock(block *massutil.Block)

type PunishmentProposal

type PunishmentProposal struct {
	BitLength int
	Height    uint64
	Size      int

PunishmentProposal warps wire.FaultPubKey

func NewPunishmentProposal

func NewPunishmentProposal(fpk *wire.FaultPubKey) *PunishmentProposal

func (*PunishmentProposal) LessThan

func (p *PunishmentProposal) LessThan(other *PunishmentProposal) bool

type SequenceLock

type SequenceLock struct {
	Seconds     int64
	BlockHeight uint64

SequenceLock represents the converted relative lock-time in seconds, and absolute block-height for a transaction input's relative lock-times. According to SequenceLock, after the referenced input has been confirmed within a block, a transaction spending that input can be included into a block either after 'seconds' (according to past median time), or once the 'BlockHeight' has been reached.

type Server

type Server interface {
	Stop() error

type TransactionPayload

type TransactionPayload struct {
	Method PayloadMethod
	Params PayloadParams

func DecodePayload

func DecodePayload(payload []byte) *TransactionPayload

DecodePayload return nil if decoding failed or verify sig failed, regarding it as meaningless payload.

func NewBindPoolCoinbasePayload

func NewBindPoolCoinbasePayload(ppk *chiapos.G1Element, sig *chiapos.G2Element, coinbase []byte, nonce uint32) *TransactionPayload

func (*TransactionPayload) String

func (p *TransactionPayload) String() string

type TxData

type TxData struct {
	Tx          *massutil.Tx
	Hash        *wire.Hash
	BlockHeight uint64
	Spent       []bool
	Err         error

TxData contains contextual information about transactions such as which block they were found in and whether or not the outputs are spent.

type TxDesc

type TxDesc struct {
	Tx     *massutil.Tx // Transaction.
	Added  time.Time    // Time when added to pool.
	Height uint64       // Block height when added to pool.

	Fee massutil.Amount // Transaction fees.
	// contains filtered or unexported fields

TxDesc is a descriptor containing a transaction in the mempool and the metadata we store about it.

func (*TxDesc) CurrentPriority

func (txD *TxDesc) CurrentPriority(txStore TxStore, nextBlockHeight uint64) (float64, error)

func (*TxDesc) StartingPriority

func (txD *TxDesc) StartingPriority() (float64, error)

TODO: should lazily update txD.totalInputValue, but that costs a lot.

func (*TxDesc) TotalInputAge

func (txD *TxDesc) TotalInputAge() (massutil.Amount, error)

TODO: should lazily update txD.totalInputValue, but that costs a lot.

type TxPool

type TxPool struct {

	NewTxCh chan *massutil.Tx
	// contains filtered or unexported fields

TxPool is used as a source of transactions that need to be mined into blocks and relayed to other peers. It is safe for concurrent access from multiple peers.

func NewTxPool

func NewTxPool(chain *Blockchain, sigCache *txscript.SigCache, hashCache *txscript.HashCache) *TxPool

NewTxPool returns a new memory pool for validating and storing standalone transactions until they are mined into a block.

func (*TxPool) CheckPoolOutPointSpend

func (tp *TxPool) CheckPoolOutPointSpend(op *wire.OutPoint) bool

func (*TxPool) Count

func (tp *TxPool) Count() int

Count returns the number of transactions in the main pool. It does not include the orphan pool.

This function is safe for concurrent access.

func (*TxPool) FetchInputTransactions

func (tp *TxPool) FetchInputTransactions(tx *massutil.Tx, includeSpent bool) TxStore

FetchInputTransactions fetches the input transactions referenced by the passed transaction. First, it fetches from the main chain, then it tries to fetch any missing inputs from the transaction pool.

This function MUST be called with the mempool lock held (for reads).

func (*TxPool) FetchTransaction

func (tp *TxPool) FetchTransaction(txHash *wire.Hash) (*massutil.Tx, error)

FetchTransaction returns the requested transaction from the transaction pool. This only fetches from the main transaction pool and does not include orphans.

This function is safe for concurrent access.

func (*TxPool) FilterTransactionsByAddress

func (tp *TxPool) FilterTransactionsByAddress(addr massutil.Address) ([]*massutil.Tx, error)

FilterTransactionsByAddress returns all transactions currently in the mempool that either create an output to the passed address or spend a previously created ouput to the address.

func (*TxPool) HaveTransaction

func (tp *TxPool) HaveTransaction(hash *wire.Hash) bool

HaveTransaction returns whether or not the passed transaction already exists in the main pool or in the orphan pool.

This function is safe for concurrent access.

func (*TxPool) IsOrphanInPool

func (tp *TxPool) IsOrphanInPool(hash *wire.Hash) bool

IsOrphanInPool returns whether or not the passed transaction already exists in the orphan pool.

This function is safe for concurrent access.

func (*TxPool) IsTransactionInPool

func (tp *TxPool) IsTransactionInPool(hash *wire.Hash) bool

IsTransactionInPool returns whether or not the passed transaction already exists in the main pool.

This function is safe for concurrent access.

func (*TxPool) LastUpdated

func (tp *TxPool) LastUpdated() time.Time

LastUpdated returns the last time a transaction was added to or removed from the main pool. It does not include the orphan pool.

This function is safe for concurrent access.

func (*TxPool) MaybeAcceptTransaction

func (tp *TxPool) MaybeAcceptTransaction(tx *massutil.Tx, isNew, rateLimit bool) ([]*wire.Hash, error)

MaybeAcceptTransaction is the main workhorse for handling insertion of new free-standing transactions into a memory pool. It includes functionality such as rejecting duplicate transactions, ensuring transactions follow all rules, detecting orphan transactions, and insertion into the memory pool.

If the transaction is an orphan (missing Parent transactions), the transaction is NOT added to the orphan pool, but each unknown referenced Parent is returned. Use ProcessTransaction instead if new orphans should be added to the orphan pool.

This function is safe for concurrent access.

func (*TxPool) OrphanTxs

func (tp *TxPool) OrphanTxs() []*massutil.Tx

func (*TxPool) ProcessOrphans

func (tp *TxPool) ProcessOrphans(hash *wire.Hash)

ProcessOrphans determines if there are any orphans which depend on the passed transaction hash (it is possible that they are no longer orphans) and potentially accepts them to the memory pool. It repeats the process for the newly accepted transactions (to detect further orphans which may no longer be orphans) until there are no more.

This function is safe for concurrent access.

func (*TxPool) ProcessTransaction

func (tp *TxPool) ProcessTransaction(tx *massutil.Tx, allowOrphan, rateLimit bool) (bool, error)

ProcessTransaction is the main workhorse for handling insertion of new free-standing transactions into the memory pool. It includes functionality such as rejecting duplicate transactions, ensuring transactions follow all rules, orphan transaction handling, and insertion into the memory pool.

This function is safe for concurrent access.

func (*TxPool) RemoveDoubleSpends

func (tp *TxPool) RemoveDoubleSpends(tx *massutil.Tx)

RemoveDoubleSpends removes all transactions which spend outputs spent by the passed transaction from the memory pool. Removing those transactions then leads to removing all transactions which rely on them, recursively. This is necessary when a block is connected to the main chain because the block may contain transactions which were previously unknown to the memory pool

This function is safe for concurrent access.

func (*TxPool) RemoveOrphan

func (tp *TxPool) RemoveOrphan(txHash *wire.Hash)

RemoveOrphan removes the passed orphan transaction from the orphan pool and previous orphan index.

This function is safe for concurrent access.

func (*TxPool) RemoveTransaction

func (tp *TxPool) RemoveTransaction(tx *massutil.Tx, removeRedeemers bool)

RemoveTransaction removes the passed transaction from the mempool. If removeRedeemers flag is set, any transactions that redeem outputs from the removed transaction will also be removed recursively from the mempool, as they would otherwise become orphan.

This function is safe for concurrent access.

func (*TxPool) SetNewTxCh

func (tp *TxPool) SetNewTxCh(ch chan *massutil.Tx)

func (*TxPool) SyncAttachBlock

func (tp *TxPool) SyncAttachBlock(block *massutil.Block)

func (*TxPool) SyncDetachBlock

func (tp *TxPool) SyncDetachBlock(block *massutil.Block)

func (*TxPool) TxDescs

func (tp *TxPool) TxDescs() []*TxDesc

TxDescs returns a slice of descriptors for all the transactions in the pool. The descriptors are to be treated as read only.

This function is safe for concurrent access.

func (*TxPool) TxShas

func (tp *TxPool) TxShas() []*wire.Hash

TxShas returns a slice of hashes for all of the transactions in the memory pool.

This function is safe for concurrent access.

type TxStore

type TxStore map[wire.Hash]*TxData

TxStore is used to store transactions needed by other transactions for things such as script validation and double spend prevention. This also allows the transaction data to be treated as a view since it can contain the information from the point-of-view of different points in the chain.


Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL