blockchain

package
v0.0.0-...-163fc3c Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2021 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// GovernSupperClass Update other govern address
	GovernSupperClass uint16 = 0x0001 // 1
	// GovernVersionClass Minimum version requirement
	GovernVersionClass uint16 = 0x0002 // 2
	// GovernSenateClass Update senate node information
	GovernSenateClass uint16 = 0x0003 // 3
)

govern config Govern Config Class zero as undeclared identifier

View Source
const (
	GovernSupperConfigValueLen  = 34
	GovernVersionConfigValueLen = 4
	GovernSenateConfigValueLen  = 40
)
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
)

Variables

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")
	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")

	// 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")

	// StakingTx & BindingTx
	ErrStandardBindingTx     = errors.New("input and output of the transaction are all binding transactions")
	ErrNotAllowedTx          = errors.New("A transaction that is not allowed")
	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")
	ErrPoolTxNum             = errors.New("excessive pool trading")
	ErrStandardPoolingTx     = errors.New("pooling tx script hash not equal pool type")
	ErrInvalidPoolType       = errors.New("invalid pool type")

	// 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")
	ErrUnfinishedTx         = 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")

	// Payload
	ErrPayloadExtendFormat    = errors.New("error extend payload format")
	ErrPayloadUnsupportedType = errors.New("unsupported payload extend type")
)

Functions

func CalcBlockSubsidy

func CalcBlockSubsidy(height uint64, chainParams *config.Params, totalBinding chainutil.Amount, bitLength int) (
	miner, poolNode, senateNode chainutil.Amount, err error)

CalcBlockSubsidy +-----------+------------+ | | poolNode | | coinbase |------------| | | senateNode | | |------------| | | miner | +-----------+------------+

func CalcCoinbaseSubsidy

func CalcCoinbaseSubsidy(subsidyHalvingInterval uint64, height uint64) (*safetype.Uint128, error)

func CalcMinRequiredTxRelayFee

func CalcMinRequiredTxRelayFee(serializedSize int64, minTxRelayFee chainutil.Amount) (chainutil.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 *chainutil.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 *chainutil.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 CheckProofOfCapacity

func CheckProofOfCapacity(block *chainutil.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 *chainutil.Tx, txHeight uint64, txStore TxStore) (chainutil.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 utxos 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 *chainutil.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 *chainutil.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 GetFeeAfterBurnGas

func GetFeeAfterBurnGas(fees chainutil.Amount) (chainutil.Amount, error)

func GetMaxStandardTxSize

func GetMaxStandardTxSize() int

func GetMinerRewardTxOutFromCoinbase

func GetMinerRewardTxOutFromCoinbase(coinbase *wire.MsgTx) (*wire.TxOut, error)

GetMinerRewardTxOutFromCoinbase Miner Reward Tx Out +--------------+ | staking pool | +--------------+ | senate Reward| +--------------+ | Miner Reward | +--------------+

func IsCoinBase

func IsCoinBase(tx *chainutil.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 IsCoinBaseTxOutPoint

func IsCoinBaseTxOutPoint(outPoint *wire.OutPoint) bool

func IsDust

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

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *chainutil.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: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki

  • (Compatibility)

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 ValidateTransactionScripts

func ValidateTransactionScripts(tx *chainutil.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 VerifyHash

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

Types

type AddrIndexer

type AddrIndexer struct {
	sync.Mutex
	// 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, server Server) (*AddrIndexer, error)

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

func (*AddrIndexer) SyncAttachBlock

func (a *AddrIndexer) SyncAttachBlock(block *chainutil.Block, txStore TxStore) error

func (*AddrIndexer) SyncDetachBlock

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

type BehaviorFlags

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

	BFNoPoCCheck

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

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
	PubKey          *pocec.PublicKey
	Proof           *poc.Proof
	Quality         *big.Int
	Signature       *pocec.Signature
	BanList         []*pocec.PublicKey
}

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) BlockHeader

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

type BlockProgressLogger

type BlockProgressLogger struct {
	sync.Mutex
	// 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 *chainutil.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   // block
	TotalFee           chainutil.Amount // total fee  |  fee + burn gas
	BurnGas            chainutil.Amount // burn gas
	SigOpCounts        []int64
	Height             uint64
	ValidPayAddress    bool
	MerkleCache        []*wire.Hash
	WitnessMerkleCache []*wire.Hash
	Err                error
}

type BlockTemplateGenerator

type BlockTemplateGenerator struct {
	// contains filtered or unexported fields
}

BlockTemplateGenerator provides a type that can be used to generate block templates based on a given mining policy and source of transactions to choose from. It also houses additional state required in order to ensure the templates are built on top of the current best chain and adhere to the consensus rules.

type BlockTree

type BlockTree struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewBlockTree

func NewBlockTree() *BlockTree

type Blockchain

type Blockchain struct {
	// contains filtered or unexported fields
}

func NewBlockchain

func NewBlockchain(db database.DB, dbPath string, server Server) (*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 *chainutil.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) CurrentIndexHeight

func (chain *Blockchain) CurrentIndexHeight() uint64

func (*Blockchain) FetchEnabledGovernConfig

func (chain *Blockchain) FetchEnabledGovernConfig(class uint16) (GovernConfig, error)

FetchEnabledGovernConfig fetch current enable config

func (*Blockchain) FetchGovernConfig

func (chain *Blockchain) FetchGovernConfig(class uint32, includeShadow bool) ([]GovernConfig, error)

func (*Blockchain) FetchMinedBlocks

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

func (*Blockchain) FetchScriptHashRelatedBindingTx

func (chain *Blockchain) FetchScriptHashRelatedBindingTx(scriptHash []byte, chainParams *config.Params) ([]*database.BindingTxReply, error)

func (*Blockchain) FetchTransactionStore

func (chain *Blockchain) FetchTransactionStore(tx *chainutil.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) (*chainutil.Block, error)

func (*Blockchain) GetBlockByHeight

func (chain *Blockchain) GetBlockByHeight(height uint64) (*chainutil.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) 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) InMainChain

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

func (*Blockchain) NewBlockTemplate

func (chain *Blockchain) NewBlockTemplate(payoutAddress chainutil.Address, templateCh chan interface{}) error

func (*Blockchain) ProcessBlock

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

ProcessBlock is the entry for chain update

func (*Blockchain) ProcessTx

func (chain *Blockchain) ProcessTx(tx *chainutil.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) UnregisterListener

func (chain *Blockchain) UnregisterListener(listener Listener)

type ChainGovern

type ChainGovern struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewChainGovern

func NewChainGovern(db database.DB, server Server) (*ChainGovern, error)

func (*ChainGovern) CheckTransactionGovernPayload

func (g *ChainGovern) CheckTransactionGovernPayload(tx *chainutil.Tx, txStore TxStore) error

func (*ChainGovern) FetchEnabledGovernConfig

func (g *ChainGovern) FetchEnabledGovernConfig(class uint16, height uint64) (GovernConfig, error)

FetchEnabledGovernConfig fetch next block height enable config Only one version is enabled at a time

func (*ChainGovern) SyncAttachBlock

func (g *ChainGovern) SyncAttachBlock(block *chainutil.Block, txStore TxStore) error

func (*ChainGovern) SyncDetachBlock

func (g *ChainGovern) SyncDetachBlock(block *chainutil.Block) error

type CoinbasePayload

type CoinbasePayload struct {
	// contains filtered or unexported fields
}

CoinbasePayload BIP34 fix duplicate coinbase transactions potentially causing two coinbase transactions becoming invalid

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 DoubleMiningDetector

type DoubleMiningDetector struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewDoubleMiningDetector

func NewDoubleMiningDetector(db database.DB) *DoubleMiningDetector

type EmptyGovernConfigError

type EmptyGovernConfigError uint16

EmptyGovernConfigError The EmptyGovernConfigError error is thrown when the govern configuration cannot be found

func (EmptyGovernConfigError) Error

func (e EmptyGovernConfigError) Error() string

type GovernConfig

type GovernConfig interface {
	// GovernClass return govern class
	GovernClass() uint16
	// BlockHeight return block height
	BlockHeight() uint64
	// ActiveHeight return active height , active height >= block height
	ActiveHeight() uint64
	// IsShadow shadow
	IsShadow() bool
	// TxSha return tx sha
	TxSha() *wire.Hash
	// String return string format
	String() string
	// ConfigData return config in database format
	// include: only special config
	ConfigData() []byte
}

func DecodeGovernConfig

func DecodeGovernConfig(class uint16, blockHeight uint64, txSha *wire.Hash, payload []byte) (GovernConfig, error)

DecodeGovernConfig Decode configuration information from the transaction's payload

func DecodeGovernConfigFromData

func DecodeGovernConfigFromData(configData *database.GovernConfigData) (GovernConfig, error)

type GovernProposal

type GovernProposal struct {
	Id uint16
	// contains filtered or unexported fields
}

GovernProposal

current                        future
  \|/           shadow          \|/

+--------+ +--------+ +--------+ | config | --> | config | --->| config | +--------+ +--------+ +--------+

type GovernSenateConfig

type GovernSenateConfig struct {
	// contains filtered or unexported fields
}

GovernSenateConfig Senate Node Information

func (*GovernSenateConfig) ActiveHeight

func (gs *GovernSenateConfig) ActiveHeight() uint64

func (*GovernSenateConfig) BlockHeight

func (gs *GovernSenateConfig) BlockHeight() uint64

func (*GovernSenateConfig) ConfigData

func (gs *GovernSenateConfig) ConfigData() []byte

func (*GovernSenateConfig) GetNodes

func (gs *GovernSenateConfig) GetNodes() []*database.SenateWeight

func (*GovernSenateConfig) GovernClass

func (gs *GovernSenateConfig) GovernClass() uint16

func (*GovernSenateConfig) IsShadow

func (gs *GovernSenateConfig) IsShadow() bool

func (*GovernSenateConfig) String

func (gs *GovernSenateConfig) String() string

func (*GovernSenateConfig) TxSha

func (gs *GovernSenateConfig) TxSha() *wire.Hash

type GovernSenateJson

type GovernSenateJson struct {
	// contains filtered or unexported fields
}

type GovernSupperAddressJson

type GovernSupperAddressJson struct {
	// contains filtered or unexported fields
}

type GovernSupperConfig

type GovernSupperConfig struct {
	// contains filtered or unexported fields
}

GovernSupperConfig Supper address

func (*GovernSupperConfig) ActiveHeight

func (gsc *GovernSupperConfig) ActiveHeight() uint64

func (*GovernSupperConfig) BlockHeight

func (gsc *GovernSupperConfig) BlockHeight() uint64

func (*GovernSupperConfig) ConfigData

func (gsc *GovernSupperConfig) ConfigData() []byte

func (*GovernSupperConfig) GetAddresses

func (gsc *GovernSupperConfig) GetAddresses() map[wire.Hash]uint16

func (*GovernSupperConfig) GovernClass

func (gsc *GovernSupperConfig) GovernClass() uint16

func (*GovernSupperConfig) IsShadow

func (gsc *GovernSupperConfig) IsShadow() bool

func (*GovernSupperConfig) String

func (gsc *GovernSupperConfig) String() string

func (*GovernSupperConfig) TxSha

func (gsc *GovernSupperConfig) TxSha() *wire.Hash

type GovernVersionConfig

type GovernVersionConfig struct {
	// contains filtered or unexported fields
}

GovernVersionConfig Minimum version

func (*GovernVersionConfig) ActiveHeight

func (gv *GovernVersionConfig) ActiveHeight() uint64

func (*GovernVersionConfig) BlockHeight

func (gv *GovernVersionConfig) BlockHeight() uint64

func (*GovernVersionConfig) ConfigData

func (gv *GovernVersionConfig) ConfigData() []byte

func (*GovernVersionConfig) GetVersion

func (gv *GovernVersionConfig) GetVersion() *version.Version

func (*GovernVersionConfig) GovernClass

func (gv *GovernVersionConfig) GovernClass() uint16

func (*GovernVersionConfig) IsShadow

func (gv *GovernVersionConfig) IsShadow() bool

func (*GovernVersionConfig) String

func (gv *GovernVersionConfig) String() string

func (*GovernVersionConfig) TxSha

func (gv *GovernVersionConfig) TxSha() *wire.Hash

type GovernVersionJson

type GovernVersionJson struct {
	// contains filtered or unexported fields
}

type InvalidGovernConfigFormatError

type InvalidGovernConfigFormatError uint16

InvalidGovernConfigFormatError Invalid data format

func (InvalidGovernConfigFormatError) Error

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 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(*pocec.PublicKey, chainutil.Amount, int) (*chainutil.Tx, error)
	Err           error
}

type ProposalPool

type ProposalPool struct {
	sync.RWMutex
	// 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

func (*ProposalPool) SyncAttachBlock

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

func (*ProposalPool) SyncDetachBlock

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

type PunishmentProposal

type PunishmentProposal struct {
	*wire.FaultPubKey
	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 TxData

type TxData struct {
	Tx          *chainutil.Tx // Tx
	Hash        *wire.Hash    // TxSha
	BlockHeight uint64        // block height
	Spent       []bool        // spent status
	Err         error         // error info
}

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     *chainutil.Tx // Transaction.
	Added  time.Time     // Time when added to pool.
	Height uint64        // Block height when added to pool.

	Fee chainutil.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() (chainutil.Amount, error)

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

type TxPool

type TxPool struct {
	sync.RWMutex

	NewTxCh chan *chainutil.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) 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 *chainutil.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) (*chainutil.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 chainutil.Address) ([]*chainutil.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(txSha *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 *chainutil.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() []*chainutil.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 *chainutil.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 *chainutil.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 *chainutil.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 *chainutil.Tx)

func (*TxPool) SyncAttachBlock

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

func (*TxPool) SyncDetachBlock

func (tp *TxPool) SyncDetachBlock(block *chainutil.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.

type UnsupportedGovernClassError

type UnsupportedGovernClassError uint16

UnsupportedGovernClassError describes an error where a govern config decoded has an unsupported class.

func (UnsupportedGovernClassError) Error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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