blockdag

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2020 License: ISC Imports: 39 Imported by: 0

README

blockchain

ISC License GoDoc

Package blockdag implements Kaspa block handling, organization of the blockDAG, block sorting and UTXO-set maintenance. The test coverage is currently only around 75%, but will be increasing over time.

Kaspad BlockDAG Processing Overview

Before a block is allowed into the block DAG, it must go through an intensive series of validation rules. The following list serves as a general outline of those rules to provide some intuition into what is going on under the hood, but is by no means exhaustive:

  • Reject duplicate blocks
  • Perform a series of sanity checks on the block and its transactions such as verifying proof of work, timestamps, number and character of transactions, transaction amounts, script complexity, and merkle root calculations
  • Save the most recent orphan blocks for a limited time in case their parent blocks become available.
  • Save blocks from the future for delayed processing
  • Stop processing if the block is an orphan or delayed as the rest of the processing depends on the block's position within the block chain
  • Make sure the block does not violate finality rules
  • Perform a series of more thorough checks that depend on the block's position within the blockDAG such as verifying block difficulties adhere to difficulty retarget rules, timestamps are after the median of the last several blocks, all transactions are finalized, checkpoint blocks match, and block versions are in line with the previous blocks
  • Determine how the block fits into the DAG and perform different actions accordingly
  • Run the transaction scripts to verify the spender is allowed to spend the coins
  • Run GhostDAG to fit the block in a canonical sorting
  • Build the block's UTXO Set, as well as update the global UTXO Set accordingly
  • Insert the block into the block database

Documentation

Overview

Package blockdag implements kaspa block handling and DAG selection rules.

The kaspa block handling and DAG selection rules are an integral, and quite likely the most important, part of kaspa. At its core, kaspa is a distributed consensus of which blocks are valid and which ones will comprise the DAG (public ledger) that ultimately determines accepted transactions, so it is extremely important that fully validating nodes agree on all rules.

At a high level, this package provides support for inserting new blocks into the block DAG according to the aforementioned rules. It includes functionality such as rejecting duplicate blocks, ensuring blocks and transactions follow all rules, orphan handling, and DAG order along with reorganization.

Since this package does not deal with other kaspa specifics such as network communication, it provides a notification system which gives the caller a high level of flexibility in how they want to react to certain events such as orphan blocks which need their parents requested and newly connected DAG blocks.

Kaspa DAG Processing Overview

Before a block is allowed into the block DAG, it must go through an intensive series of validation rules. The following list serves as a general outline of those rules to provide some intuition into what is going on under the hood, but is by no means exhaustive:

  • Reject duplicate blocks
  • Perform a series of sanity checks on the block and its transactions such as verifying proof of work, timestamps, number and character of transactions, transaction amounts, script complexity, and merkle root calculations
  • Save the most recent orphan blocks for a limited time in case their parent blocks become available
  • Stop processing if the block is an orphan as the rest of the processing depends on the block's position within the block DAG
  • Perform a series of more thorough checks that depend on the block's position within the block DAG such as verifying block difficulties adhere to difficulty retarget rules, timestamps are after the median of the last several blocks, all transactions are finalized, and block versions are in line with the previous blocks
  • When a block is being connected to the DAG, perform further checks on the block's transactions such as verifying transaction duplicates, script complexity for the combination of connected scripts, coinbase maturity, double spends, and connected transaction values
  • Run the transaction scripts to verify the spender is allowed to spend the coins
  • Insert the block into the block database

Errors

Errors returned by this package are either the raw errors provided by underlying calls or of type blockdag.RuleError. This allows the caller to differentiate between unexpected errors, such as database errors, versus errors due to rule violations through type assertions. In addition, callers can programmatically determine the specific rule violation by examining the ErrorCode field of the type asserted blockdag.RuleError.

Index

Constants

View Source
const (
	// MaxCoinbasePayloadLen is the maximum length a coinbase payload can be.
	MaxCoinbasePayloadLen = 150

	// MassPerTxByte is the number of grams that any byte
	// adds to a transaction.
	MassPerTxByte = 1

	// MassPerScriptPubKeyByte is the number of grams that any
	// scriptPubKey byte adds to a transaction.
	MassPerScriptPubKeyByte = 10

	// MassPerSigOp is the number of grams that any
	// signature operation adds to a transaction.
	MassPerSigOp = 10000
)
View Source
const (
	// UnacceptedBlueScore is the blue score used for the "block" blueScore
	// field of the contextual transaction information provided in a
	// transaction store when it has not yet been accepted by a block.
	UnacceptedBlueScore uint64 = math.MaxUint64
)

Variables

View Source
var ErrInvalidParameter = errors.New("invalid parameter")

ErrInvalidParameter signifies that an invalid parameter has been supplied to one of the BlockDAG functions.

View Source
var OpTrueScript = []byte{txscript.OpTrue}

OpTrueScript is script returning TRUE

Functions

func CalcBlockMass

func CalcBlockMass(pastUTXO UTXOSet, transactions []*util.Tx) (uint64, error)

CalcBlockMass sums up and returns the "mass" of a block. See CalcTxMass for further details.

func CalcBlockSubsidy

func CalcBlockSubsidy(blueScore uint64, dagParams *dagconfig.Params) uint64

CalcBlockSubsidy returns the subsidy amount a block at the provided blue score 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 SubsidyReductionInterval blocks. Mathematically this is: baseSubsidy / 2^(blueScore/SubsidyReductionInterval)

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

func CalcTxMass

func CalcTxMass(tx *util.Tx, previousScriptPubKeys [][]byte) uint64

CalcTxMass sums up and returns the "mass" of a transaction. This number is an approximation of how many resources (CPU, RAM, etc.) it would take to process the transaction. The following properties are considered in the calculation: * The transaction length in bytes * The length of all output scripts in bytes * The count of all input sigOps

func CalcTxMassFromUTXOSet

func CalcTxMassFromUTXOSet(tx *util.Tx, utxoSet UTXOSet) (uint64, error)

CalcTxMassFromUTXOSet calculates the transaction mass based on the UTXO set in its past.

See CalcTxMass for more details.

func CheckTransactionInputsAndCalulateFee

func CheckTransactionInputsAndCalulateFee(tx *util.Tx, txBlueScore uint64, utxoSet UTXOSet, dagParams *dagconfig.Params, fastAdd bool) (
	txFeeInSompi uint64, err error)

CheckTransactionInputsAndCalulateFee 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 block reward 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. As it checks the inputs, it also calculates the total fees for the transaction and returns that value.

NOTE: The transaction MUST have already been sanity checked with the CheckTransactionSanity function prior to calling this function.

func CheckTransactionSanity

func CheckTransactionSanity(tx *util.Tx, subnetworkID *subnetworkid.SubnetworkID) error

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

func CoinbasePayloadExtraData

func CoinbasePayloadExtraData(extraNonce uint64, coinbaseFlags string) ([]byte, error)

CoinbasePayloadExtraData returns coinbase payload extra data parameter which is built from extra nonce and coinbase flags.

func ExtractGasLimit

func ExtractGasLimit(tx *domainmessage.MsgTx) uint64

ExtractGasLimit extracts the gas limit from the transaction payload

func FileExists

func FileExists(name string) bool

FileExists returns whether or not the named file or directory exists.

func HashMerkleBranches

func HashMerkleBranches(left *daghash.Hash, right *daghash.Hash) *daghash.Hash

HashMerkleBranches takes two hashes, treated as the left and right tree nodes, and returns the hash of their concatenation. This is a helper function used to aid in the generation of a merkle tree.

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *util.Tx, blockBlueScore uint64, blockTime mstime.Time) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func IsNotInDAGErr

func IsNotInDAGErr(err error) bool

IsNotInDAGErr returns whether or not the passed error is an ErrNotInDAG error.

func LoadBlocks

func LoadBlocks(filename string) (blocks []*util.Block, err error)

LoadBlocks reads files containing kaspa gzipped block data from disk and returns them as an array of util.Block.

func LockTimeToSequence

func LockTimeToSequence(isMilliseconds bool, locktime uint64) uint64

LockTimeToSequence converts the passed relative locktime to a sequence number.

func PrepareAndProcessBlockForTest

func PrepareAndProcessBlockForTest(t *testing.T, dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*domainmessage.MsgTx) *domainmessage.MsgBlock

PrepareAndProcessBlockForTest prepares a block that points to the given parent hashes and process it.

func PrepareBlockForTest

func PrepareBlockForTest(dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*domainmessage.MsgTx) (*domainmessage.MsgBlock, error)

PrepareBlockForTest generates a block with the proper merkle roots, coinbase transaction etc. This function is used for test purposes only

func SequenceLockActive

func SequenceLockActive(sequenceLock *SequenceLock, blockBlueScore uint64,
	medianTimePast mstime.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 blue score or time sufficient for their relative lock-time maturity.

func TxToSubnetworkID

func TxToSubnetworkID(tx *domainmessage.MsgTx) (*subnetworkid.SubnetworkID, error)

TxToSubnetworkID creates a subnetwork ID from a subnetwork registry transaction

func ValidateTransactionScripts

func ValidateTransactionScripts(tx *util.Tx, utxoSet UTXOSet, flags txscript.ScriptFlags, sigCache *txscript.SigCache) error

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

func ValidateTxMass

func ValidateTxMass(tx *util.Tx, utxoSet UTXOSet) error

ValidateTxMass makes sure that the given transaction's mass does not exceed the maximum allowed limit. Currently, it is equivalent to the block mass limit. See CalcTxMass for further details.

Types

type BehaviorFlags

type BehaviorFlags uint32

BehaviorFlags is a bitmask defining tweaks to the normal behavior when performing DAG processing and consensus rules checks.

const (
	// BFFastAdd may be set to indicate that several checks can be avoided
	// for the block since it is already known to fit into the DAG due to
	// already proving it correct links into the DAG.
	BFFastAdd BehaviorFlags = 1 << iota

	// BFNoPoWCheck may be set to indicate the proof of work check which
	// ensures a block hashes to a value less than the required target will
	// not be performed.
	BFNoPoWCheck

	// BFWasUnorphaned may be set to indicate that a block was just now
	// unorphaned
	BFWasUnorphaned

	// BFAfterDelay may be set to indicate that a block had timestamp too far
	// in the future, just finished the delay
	BFAfterDelay

	// BFIsSync may be set to indicate that the block was sent as part of the
	// netsync process
	BFIsSync

	// BFWasStored is set to indicate that the block was previously stored
	// in the block index but was never fully processed
	BFWasStored

	// BFDisallowDelay is set to indicate that a delayed block should be rejected.
	// This is used for the case where a block is submitted through RPC.
	BFDisallowDelay

	// BFDisallowOrphans is set to indicate that an orphan block should be rejected.
	// This is used for the case where a block is submitted through RPC.
	BFDisallowOrphans

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

type BlockAddedNotificationData

type BlockAddedNotificationData struct {
	Block         *util.Block
	WasUnorphaned bool
}

BlockAddedNotificationData defines data to be sent along with a BlockAdded notification

type BlockDAG

type BlockDAG struct {
	// The following fields are set when the instance is created and can't
	// be changed afterwards, so there is no need to protect them with a
	// separate mutex.
	Params *dagconfig.Params

	TimestampDeviationTolerance uint64
	// contains filtered or unexported fields
}

BlockDAG provides functions for working with the kaspa block DAG. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, and orphan handling.

func DAGSetup

func DAGSetup(dbName string, openDb bool, config Config) (*BlockDAG, func(), error)

DAGSetup is used to create a new db and DAG instance with the genesis block already inserted. In addition to the new DAG instance, it returns a teardown function the caller should invoke when done testing to clean up. The openDB parameter instructs DAGSetup whether or not to also open the database. Setting it to false is useful in tests that handle database opening/closing by themselves.

func New

func New(config *Config) (*BlockDAG, error)

New returns a BlockDAG instance using the provided configuration details.

func (*BlockDAG) AntiPastHashesBetween

func (dag *BlockDAG) AntiPastHashesBetween(lowHash, highHash *daghash.Hash, maxHashes uint64) ([]*daghash.Hash, error)

AntiPastHashesBetween returns the hashes of the blocks between the lowHash's antiPast and highHash's antiPast, or up to the provided max number of block hashes.

This function is safe for concurrent access.

func (*BlockDAG) AntiPastHeadersBetween

func (dag *BlockDAG) AntiPastHeadersBetween(lowHash, highHash *daghash.Hash, maxHeaders uint64) ([]*domainmessage.BlockHeader, error)

AntiPastHeadersBetween returns the headers of the blocks between the lowHash's antiPast and highHash's antiPast, or up to domainmessage.MaxBlockHeadersPerMsg block headers.

This function is safe for concurrent access.

func (*BlockDAG) AreKnownBlocks

func (dag *BlockDAG) AreKnownBlocks(hashes []*daghash.Hash) bool

AreKnownBlocks returns whether or not the DAG instances has all blocks represented by the passed hashes. This includes checking the various places a block can be in, like part of the DAG or the orphan pool.

This function is safe for concurrent access.

func (*BlockDAG) BlockByHash

func (dag *BlockDAG) BlockByHash(hash *daghash.Hash) (*util.Block, error)

BlockByHash returns the block from the DAG with the given hash.

This function is safe for concurrent access.

func (*BlockDAG) BlockConfirmationsByHash

func (dag *BlockDAG) BlockConfirmationsByHash(hash *daghash.Hash) (uint64, error)

BlockConfirmationsByHash returns the confirmations number for a block with the given hash. See blockConfirmations for further details.

This function is safe for concurrent access

func (*BlockDAG) BlockConfirmationsByHashNoLock

func (dag *BlockDAG) BlockConfirmationsByHashNoLock(hash *daghash.Hash) (uint64, error)

BlockConfirmationsByHashNoLock is lock free version of BlockConfirmationsByHash

This function is unsafe for concurrent access.

func (*BlockDAG) BlockCount

func (dag *BlockDAG) BlockCount() uint64

BlockCount returns the number of blocks in the DAG

func (*BlockDAG) BlockForMining

func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*domainmessage.MsgBlock, error)

BlockForMining returns a block with the given transactions that points to the current DAG tips, that is valid from all aspects except proof of work.

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

func (*BlockDAG) BlockHashesFrom

func (dag *BlockDAG) BlockHashesFrom(lowHash *daghash.Hash, limit int) ([]*daghash.Hash, error)

BlockHashesFrom returns a slice of blocks starting from lowHash ordered by blueScore. If lowHash is nil then the genesis block is used.

This method MUST be called with the DAG lock held

func (*BlockDAG) BlockLocatorFromHashes

func (dag *BlockDAG) BlockLocatorFromHashes(highHash, lowHash *daghash.Hash) (BlockLocator, error)

BlockLocatorFromHashes returns a block locator from high and low hash. See BlockLocator for details on the algorithm used to create a block locator.

This function is safe for concurrent access.

func (*BlockDAG) BlueScoreByBlockHash

func (dag *BlockDAG) BlueScoreByBlockHash(hash *daghash.Hash) (uint64, error)

BlueScoreByBlockHash returns the blue score of a block with the given hash.

func (*BlockDAG) BluesByBlockHash

func (dag *BlockDAG) BluesByBlockHash(hash *daghash.Hash) ([]*daghash.Hash, error)

BluesByBlockHash returns the blues of the block for the given hash.

func (*BlockDAG) CalcNextBlockVersion

func (dag *BlockDAG) CalcNextBlockVersion() (int32, error)

CalcNextBlockVersion calculates the expected version of the block after the end of the current selected tip based on the state of started and locked in rule change deployments.

This function is safe for concurrent access.

func (*BlockDAG) CalcPastMedianTime

func (dag *BlockDAG) CalcPastMedianTime() mstime.Time

CalcPastMedianTime returns the past median time of the DAG.

func (*BlockDAG) CalcSequenceLock

func (dag *BlockDAG) CalcSequenceLock(tx *util.Tx, utxoSet UTXOSet, mempool bool) (*SequenceLock, error)

CalcSequenceLock computes a relative lock-time SequenceLock for the passed transaction using the passed UTXOSet 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 (*BlockDAG) CalcSequenceLockNoLock

func (dag *BlockDAG) CalcSequenceLockNoLock(tx *util.Tx, utxoSet UTXOSet, mempool bool) (*SequenceLock, error)

CalcSequenceLockNoLock is lock free version of CalcSequenceLockWithLock This function is unsafe for concurrent access.

func (*BlockDAG) CheckConnectBlockTemplate

func (dag *BlockDAG) CheckConnectBlockTemplate(block *util.Block) error

CheckConnectBlockTemplate fully validates that connecting the passed block to the DAG does not violate any consensus rules, aside from the proof of work requirement.

This function is safe for concurrent access.

func (*BlockDAG) CheckConnectBlockTemplateNoLock

func (dag *BlockDAG) CheckConnectBlockTemplateNoLock(block *util.Block) error

CheckConnectBlockTemplateNoLock fully validates that connecting the passed block to the DAG does not violate any consensus rules, aside from the proof of work requirement. The block must connect to the current tip of the main dag.

func (*BlockDAG) ChildHashesByHash

func (dag *BlockDAG) ChildHashesByHash(hash *daghash.Hash) ([]*daghash.Hash, error)

ChildHashesByHash returns the child hashes of the block with the given hash in the DAG.

This function is safe for concurrent access.

func (*BlockDAG) CurrentBits

func (dag *BlockDAG) CurrentBits() uint32

CurrentBits returns the bits of the tip with the lowest bits, which also means it has highest difficulty.

func (*BlockDAG) FinalityInterval

func (dag *BlockDAG) FinalityInterval() uint64

FinalityInterval is the interval that determines the finality window of the DAG.

func (*BlockDAG) FindNextLocatorBoundaries

func (dag *BlockDAG) FindNextLocatorBoundaries(locator BlockLocator) (highHash, lowHash *daghash.Hash)

FindNextLocatorBoundaries returns the lowest unknown block locator, hash and the highest known block locator hash. This is used to create the next block locator to find the highest shared known chain block with the sync peer.

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

func (*BlockDAG) ForEachHash

func (dag *BlockDAG) ForEachHash(fn func(hash daghash.Hash) error) error

ForEachHash runs the given fn on every hash that's currently known to the DAG.

This function is NOT safe for concurrent access. It is meant to be used either on initialization or when the dag lock is held for reads.

func (*BlockDAG) GasLimit

func (dag *BlockDAG) GasLimit(subnetworkID *subnetworkid.SubnetworkID) (uint64, error)

GasLimit returns the gas limit of a registered subnetwork. If the subnetwork does not exist this method returns an error.

func (*BlockDAG) GetOrphanMissingAncestorHashes

func (dag *BlockDAG) GetOrphanMissingAncestorHashes(orphanHash *daghash.Hash) []*daghash.Hash

GetOrphanMissingAncestorHashes returns all of the missing parents in the orphan's sub-DAG

This function is safe for concurrent access.

func (*BlockDAG) GetTopHeaders

func (dag *BlockDAG) GetTopHeaders(highHash *daghash.Hash, maxHeaders uint64) ([]*domainmessage.BlockHeader, error)

GetTopHeaders returns the top domainmessage.MaxBlockHeadersPerMsg block headers ordered by blue score.

func (*BlockDAG) GetUTXOEntry

func (dag *BlockDAG) GetUTXOEntry(outpoint domainmessage.Outpoint) (*UTXOEntry, bool)

GetUTXOEntry returns the requested unspent transaction output. The returned instance must be treated as immutable since it is shared by all callers.

This function is safe for concurrent access. However, the returned entry (if any) is NOT.

func (*BlockDAG) HeaderByHash

func (dag *BlockDAG) HeaderByHash(hash *daghash.Hash) (*domainmessage.BlockHeader, error)

HeaderByHash returns the block header identified by the given hash or an error if it doesn't exist.

func (*BlockDAG) IsDeploymentActive

func (dag *BlockDAG) IsDeploymentActive(deploymentID uint32) (bool, error)

IsDeploymentActive returns true if the target deploymentID is active, and false otherwise.

This function is safe for concurrent access.

func (*BlockDAG) IsInDAG

func (dag *BlockDAG) IsInDAG(hash *daghash.Hash) bool

IsInDAG determines whether a block with the given hash exists in the DAG.

This function is safe for concurrent access.

func (*BlockDAG) IsInSelectedParentChain

func (dag *BlockDAG) IsInSelectedParentChain(blockHash *daghash.Hash) (bool, error)

IsInSelectedParentChain returns whether or not a block hash is found in the selected parent chain. Note that this method returns an error if the given blockHash does not exist within the block index.

This method MUST be called with the DAG lock held

func (*BlockDAG) IsKnownBlock

func (dag *BlockDAG) IsKnownBlock(hash *daghash.Hash) bool

IsKnownBlock returns whether or not the DAG instance has the block represented by the passed hash. This includes checking the various places a block can be in, like part of the DAG or the orphan pool.

This function is safe for concurrent access.

func (*BlockDAG) IsKnownFinalizedBlock

func (dag *BlockDAG) IsKnownFinalizedBlock(blockHash *daghash.Hash) bool

IsKnownFinalizedBlock returns whether the block is below the finality point. IsKnownFinalizedBlock might be false-negative because node finality status is updated in a separate goroutine. To get a definite answer if a block is finalized or not, use dag.checkFinalityViolation.

func (*BlockDAG) IsKnownInvalid

func (dag *BlockDAG) IsKnownInvalid(hash *daghash.Hash) bool

IsKnownInvalid returns whether the passed hash is known to be an invalid block. Note that if the block is not found this method will return false.

This function is safe for concurrent access.

func (*BlockDAG) IsKnownOrphan

func (dag *BlockDAG) IsKnownOrphan(hash *daghash.Hash) bool

IsKnownOrphan returns whether the passed hash is currently a known orphan. Keep in mind that only a limited number of orphans are held onto for a limited amount of time, so this function must not be used as an absolute way to test if a block is an orphan block. A full block (as opposed to just its hash) must be passed to ProcessBlock for that purpose. However, calling ProcessBlock with an orphan that already exists results in an error, so this function provides a mechanism for a caller to intelligently detect *recent* duplicate orphans and react accordingly.

This function is safe for concurrent access.

func (*BlockDAG) IsSyncRateBelowThreshold

func (dag *BlockDAG) IsSyncRateBelowThreshold(maxDeviation float64) bool

IsSyncRateBelowThreshold checks whether the sync rate is below the expected threshold.

func (*BlockDAG) IsSynced

func (dag *BlockDAG) IsSynced() bool

IsSynced returns whether or not the DAG believes it is synced. Several factors are used to guess, but the key factors that allow the DAG to believe it is synced are:

  • Latest block has a timestamp newer than 24 hours ago

This function is safe for concurrent access.

func (*BlockDAG) LastFinalityPointHash

func (dag *BlockDAG) LastFinalityPointHash() *daghash.Hash

LastFinalityPointHash returns the hash of the last finality point

func (*BlockDAG) Lock

func (dag *BlockDAG) Lock()

Lock locks the DAG's UTXO set for writing.

func (*BlockDAG) NextAcceptedIDMerkleRootNoLock

func (dag *BlockDAG) NextAcceptedIDMerkleRootNoLock() (*daghash.Hash, error)

NextAcceptedIDMerkleRootNoLock prepares the acceptedIDMerkleRoot for the next mined block

This function MUST be called with the DAG read-lock held

func (*BlockDAG) NextBlockCoinbaseTransaction

func (dag *BlockDAG) NextBlockCoinbaseTransaction(scriptPubKey []byte, extraData []byte) (*util.Tx, error)

NextBlockCoinbaseTransaction prepares the coinbase transaction for the next mined block

This function CAN'T be called with the DAG lock held.

func (*BlockDAG) NextBlockCoinbaseTransactionNoLock

func (dag *BlockDAG) NextBlockCoinbaseTransactionNoLock(scriptPubKey []byte, extraData []byte) (*util.Tx, error)

NextBlockCoinbaseTransactionNoLock prepares the coinbase transaction for the next mined block

This function MUST be called with the DAG read-lock held

func (*BlockDAG) NextBlockMinimumTime

func (dag *BlockDAG) NextBlockMinimumTime() mstime.Time

NextBlockMinimumTime returns the minimum allowed timestamp for a block building on the end of the DAG. In particular, it is one second after the median timestamp of the last several blocks per the DAG consensus rules.

func (*BlockDAG) NextBlockMultiset

func (dag *BlockDAG) NextBlockMultiset() (*secp256k1.MultiSet, error)

NextBlockMultiset returns the multiset of an assumed next block built on top of the current tips.

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

func (*BlockDAG) NextBlockTime

func (dag *BlockDAG) NextBlockTime() mstime.Time

NextBlockTime returns a valid block time for the next block that will point to the existing DAG tips.

func (*BlockDAG) NextCoinbaseFromAddress

func (dag *BlockDAG) NextCoinbaseFromAddress(payToAddress util.Address, extraData []byte) (*util.Tx, error)

NextCoinbaseFromAddress returns a coinbase transaction for the next block with the given address and extra data in its payload.

func (*BlockDAG) NextRequiredDifficulty

func (dag *BlockDAG) NextRequiredDifficulty(timestamp mstime.Time) uint32

NextRequiredDifficulty calculates the required difficulty for a block that will be built on top of the current tips.

This function is safe for concurrent access.

func (*BlockDAG) Now

func (dag *BlockDAG) Now() mstime.Time

Now returns the adjusted time according to dag.timeSource. See TimeSource.Now for more details.

func (*BlockDAG) ProcessBlock

func (dag *BlockDAG) ProcessBlock(block *util.Block, flags BehaviorFlags) (isOrphan bool, isDelayed bool, err error)

ProcessBlock is the main workhorse for handling insertion of new blocks into the block DAG. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, and insertion into the block DAG.

When no errors occurred during processing, the first return value indicates whether or not the block is an orphan.

This function is safe for concurrent access.

func (*BlockDAG) RLock

func (dag *BlockDAG) RLock()

RLock locks the DAG's UTXO set for reading.

func (*BlockDAG) RUnlock

func (dag *BlockDAG) RUnlock()

RUnlock unlocks the DAG's UTXO set for reading.

func (*BlockDAG) SelectedParentChain

func (dag *BlockDAG) SelectedParentChain(blockHash *daghash.Hash) ([]*daghash.Hash, []*daghash.Hash, error)

SelectedParentChain returns the selected parent chain starting from blockHash (exclusive) up to the virtual (exclusive). If blockHash is nil then the genesis block is used. If blockHash is not within the select parent chain, go down its own selected parent chain, while collecting each block hash in removedChainHashes, until reaching a block within the main selected parent chain.

This method MUST be called with the DAG lock held

func (*BlockDAG) SelectedParentHash

func (dag *BlockDAG) SelectedParentHash(blockHash *daghash.Hash) (*daghash.Hash, error)

SelectedParentHash returns the selected parent hash of the block with the given hash in the DAG.

This function is safe for concurrent access.

func (*BlockDAG) SelectedTipBlueScore

func (dag *BlockDAG) SelectedTipBlueScore() uint64

SelectedTipBlueScore returns the blue score of the selected tip.

func (*BlockDAG) SelectedTipHash

func (dag *BlockDAG) SelectedTipHash() *daghash.Hash

SelectedTipHash returns the hash of the current selected tip for the DAG. It will return nil if there is no tip.

This function is safe for concurrent access.

func (*BlockDAG) SelectedTipHeader

func (dag *BlockDAG) SelectedTipHeader() *domainmessage.BlockHeader

SelectedTipHeader returns the header of the current selected tip for the DAG. It will return nil if there is no tip.

This function is safe for concurrent access.

func (*BlockDAG) SubnetworkID

func (dag *BlockDAG) SubnetworkID() *subnetworkid.SubnetworkID

SubnetworkID returns the node's subnetwork ID

func (*BlockDAG) Subscribe

func (dag *BlockDAG) Subscribe(callback NotificationCallback)

Subscribe to block DAG notifications. Registers a callback to be executed when various events take place. See the documentation on Notification and NotificationType for details on the types and contents of notifications.

func (*BlockDAG) ThresholdState

func (dag *BlockDAG) ThresholdState(deploymentID uint32) (ThresholdState, error)

ThresholdState returns the current rule change threshold state of the given deployment ID for the block AFTER the blueScore of the current DAG.

This function is safe for concurrent access.

func (*BlockDAG) TipHashes

func (dag *BlockDAG) TipHashes() []*daghash.Hash

TipHashes returns the hashes of the DAG's tips

func (*BlockDAG) TxsAcceptedByBlockHash

func (dag *BlockDAG) TxsAcceptedByBlockHash(blockHash *daghash.Hash) (MultiBlockTxsAcceptanceData, error)

TxsAcceptedByBlockHash retrieves transactions accepted by the given block

This function MUST be called with the DAG read-lock held

func (*BlockDAG) TxsAcceptedByVirtual

func (dag *BlockDAG) TxsAcceptedByVirtual() (MultiBlockTxsAcceptanceData, error)

TxsAcceptedByVirtual retrieves transactions accepted by the current virtual block

This function MUST be called with the DAG read-lock held

func (*BlockDAG) UTXOConfirmations

func (dag *BlockDAG) UTXOConfirmations(outpoint *domainmessage.Outpoint) (uint64, bool)

UTXOConfirmations returns the confirmations for the given outpoint, if it exists in the DAG's UTXO set.

This function is safe for concurrent access.

func (*BlockDAG) UTXOSet

func (dag *BlockDAG) UTXOSet() *FullUTXOSet

UTXOSet returns the DAG's UTXO set

func (*BlockDAG) Unlock

func (dag *BlockDAG) Unlock()

Unlock unlocks the DAG's UTXO set for writing.

func (*BlockDAG) VirtualBlueScore

func (dag *BlockDAG) VirtualBlueScore() uint64

VirtualBlueScore returns the blue score of the current virtual block

type BlockLocator

type BlockLocator []*daghash.Hash

BlockLocator is used to help locate a specific block. The algorithm for building the block locator is to add block hashes in reverse order on the block's selected parent chain until the desired stop block is reached. In order to keep the list of locator hashes to a reasonable number of entries, the step between each entry is doubled each loop iteration to exponentially decrease the number of hashes as a function of the distance from the block being located.

For example, assume a selected parent chain with IDs as depicted below, and the stop block is genesis:

genesis -> 1 -> 2 -> ... -> 15 -> 16  -> 17  -> 18

The block locator for block 17 would be the hashes of blocks:

[17 16 14 11 7 2 genesis]

type BlockTxsAcceptanceData

type BlockTxsAcceptanceData struct {
	BlockHash        daghash.Hash
	TxAcceptanceData []TxAcceptanceData
}

BlockTxsAcceptanceData stores all transactions in a block with an indication if they were accepted or not by some other block

type ChainChangedNotificationData

type ChainChangedNotificationData struct {
	RemovedChainBlockHashes []*daghash.Hash
	AddedChainBlockHashes   []*daghash.Hash
}

ChainChangedNotificationData defines data to be sent along with a ChainChanged notification

type Config

type Config struct {
	// Interrupt specifies a channel the caller can close to signal that
	// long running operations, such as catching up indexes or performing
	// database migrations, should be interrupted.
	//
	// This field can be nil if the caller does not desire the behavior.
	Interrupt <-chan struct{}

	// DAGParams identifies which DAG parameters the DAG is associated
	// with.
	//
	// This field is required.
	DAGParams *dagconfig.Params

	// TimeSource defines the time source to use for things such as
	// block processing and determining whether or not the DAG is current.
	TimeSource TimeSource

	// SigCache defines a signature cache to use when when validating
	// signatures. This is typically most useful when individual
	// transactions are already being validated prior to their inclusion in
	// a block such as what is usually done via a transaction memory pool.
	//
	// This field can be nil if the caller is not interested in using a
	// signature cache.
	SigCache *txscript.SigCache

	// IndexManager defines an index manager to use when initializing the
	// DAG and connecting blocks.
	//
	// This field can be nil if the caller does not wish to make use of an
	// index manager.
	IndexManager IndexManager

	// SubnetworkID identifies which subnetwork the DAG is associated
	// with.
	//
	// This field is required.
	SubnetworkID *subnetworkid.SubnetworkID

	// DatabaseContext is the context in which all database queries related to
	// this DAG are going to run.
	DatabaseContext *dbaccess.DatabaseContext
}

Config is a descriptor which specifies the blockDAG instance configuration.

type DiffUTXOSet

type DiffUTXOSet struct {
	UTXODiff *UTXODiff
	// contains filtered or unexported fields
}

DiffUTXOSet represents a utxoSet with a base fullUTXOSet and a UTXODiff

func NewDiffUTXOSet

func NewDiffUTXOSet(base *FullUTXOSet, diff *UTXODiff) *DiffUTXOSet

NewDiffUTXOSet Creates a new utxoSet based on a base fullUTXOSet and a UTXODiff

func (*DiffUTXOSet) AddTx

func (dus *DiffUTXOSet) AddTx(tx *domainmessage.MsgTx, blockBlueScore uint64) (bool, error)

AddTx adds a transaction to this utxoSet and returns true iff it's valid in this UTXO's context.

If dus.UTXODiff.useMultiset is true, this function MUST be called with the DAG lock held.

func (*DiffUTXOSet) Get

func (dus *DiffUTXOSet) Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool)

Get returns the UTXOEntry associated with provided outpoint in this UTXOSet. Returns false in second output if this UTXOEntry was not found

func (*DiffUTXOSet) String

func (dus *DiffUTXOSet) String() string

func (*DiffUTXOSet) WithDiff

func (dus *DiffUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error)

WithDiff return a new utxoSet which is a diffFrom between this and another utxoSet

type ErrNotInDAG

type ErrNotInDAG string

ErrNotInDAG signifies that a block hash that is not in the DAG was requested.

func (ErrNotInDAG) Error

func (e ErrNotInDAG) Error() string

Error implements the error interface.

type ErrorCode

type ErrorCode int

ErrorCode identifies a kind of error.

const (
	// ErrDuplicateBlock indicates a block with the same hash already
	// exists.
	ErrDuplicateBlock ErrorCode = iota

	// ErrBlockMassTooHigh indicates the mass of a block exceeds the maximum
	// allowed limits.
	ErrBlockMassTooHigh

	// ErrBlockVersionTooOld indicates the block version is too old and is
	// no longer accepted since the majority of the network has upgraded
	// to a newer version.
	ErrBlockVersionTooOld

	// ErrTimeTooOld indicates the time is either before the median time of
	// the last several blocks per the DAG consensus rules.
	ErrTimeTooOld

	// ErrTimeTooNew indicates the time is too far in the future as compared
	// the current time.
	ErrTimeTooNew

	// ErrNoParents indicates that the block is missing parents
	ErrNoParents

	// ErrWrongParentsOrder indicates that the block's parents are not ordered by hash, as expected
	ErrWrongParentsOrder

	// ErrDifficultyTooLow indicates the difficulty for the block is lower
	// than the difficulty required.
	ErrDifficultyTooLow

	// ErrUnexpectedDifficulty indicates specified bits do not align with
	// the expected value either because it doesn't match the calculated
	// valued based on difficulty regarted rules or it is out of the valid
	// range.
	ErrUnexpectedDifficulty

	// ErrHighHash indicates the block does not hash to a value which is
	// lower than the required target difficultly.
	ErrHighHash

	// ErrBadMerkleRoot indicates the calculated merkle root does not match
	// the expected value.
	ErrBadMerkleRoot

	// ErrBadUTXOCommitment indicates the calculated UTXO commitment does not match
	// the expected value.
	ErrBadUTXOCommitment

	// ErrInvalidSubnetwork indicates the subnetwork is now allowed.
	ErrInvalidSubnetwork

	// ErrFinalityPointTimeTooOld indicates a block has a timestamp before the
	// last finality point.
	ErrFinalityPointTimeTooOld

	// ErrNoTransactions indicates the block does not have a least one
	// transaction. A valid block must have at least the coinbase
	// transaction.
	ErrNoTransactions

	// ErrNoTxInputs indicates a transaction does not have any inputs. A
	// valid transaction must have at least one input.
	ErrNoTxInputs

	// ErrTxMassTooHigh indicates the mass of a transaction exceeds the maximum
	// allowed limits.
	ErrTxMassTooHigh

	// ErrBadTxOutValue indicates an output value for a transaction is
	// invalid in some way such as being out of range.
	ErrBadTxOutValue

	// ErrDuplicateTxInputs indicates a transaction references the same
	// input more than once.
	ErrDuplicateTxInputs

	// ErrBadTxInput indicates a transaction input is invalid in some way
	// such as referencing a previous transaction outpoint which is out of
	// range or not referencing one at all.
	ErrBadTxInput

	// ErrMissingTxOut indicates a transaction output referenced by an input
	// either does not exist or has already been spent.
	ErrMissingTxOut

	// ErrDoubleSpendInSameBlock indicates a transaction
	// that spends an output that was already spent by another
	// transaction in the same block.
	ErrDoubleSpendInSameBlock

	// ErrUnfinalizedTx indicates a transaction has not been finalized.
	// A valid block may only contain finalized transactions.
	ErrUnfinalizedTx

	// ErrDuplicateTx indicates a block contains an identical transaction
	// (or at least two transactions which hash to the same value). A
	// valid block may only contain unique transactions.
	ErrDuplicateTx

	// ErrOverwriteTx indicates a block contains a transaction that has
	// the same hash as a previous transaction which has not been fully
	// spent.
	ErrOverwriteTx

	// ErrImmatureSpend indicates a transaction is attempting to spend a
	// coinbase that has not yet reached the required maturity.
	ErrImmatureSpend

	// ErrSpendTooHigh indicates a transaction is attempting to spend more
	// value than the sum of all of its inputs.
	ErrSpendTooHigh

	// ErrBadFees indicates the total fees for a block are invalid due to
	// exceeding the maximum possible value.
	ErrBadFees

	// ErrTooManySigOps indicates the total number of signature operations
	// for a transaction or block exceed the maximum allowed limits.
	ErrTooManySigOps

	// ErrFirstTxNotCoinbase indicates the first transaction in a block
	// is not a coinbase transaction.
	ErrFirstTxNotCoinbase

	// ErrMultipleCoinbases indicates a block contains more than one
	// coinbase transaction.
	ErrMultipleCoinbases

	// ErrBadCoinbasePayloadLen indicates the length of the payload
	// for a coinbase transaction is too high.
	ErrBadCoinbasePayloadLen

	// ErrBadCoinbaseTransaction indicates that the block's coinbase transaction is not build as expected
	ErrBadCoinbaseTransaction

	// ErrScriptMalformed indicates a transaction script is malformed in
	// some way. For example, it might be longer than the maximum allowed
	// length or fail to parse.
	ErrScriptMalformed

	// ErrScriptValidation indicates the result of executing transaction
	// script failed. The error covers any failure when executing scripts
	// such signature verification failures and execution past the end of
	// the stack.
	ErrScriptValidation

	// ErrParentBlockUnknown indicates that the parent block is not known.
	ErrParentBlockUnknown

	// ErrInvalidAncestorBlock indicates that an ancestor of this block has
	// already failed validation.
	ErrInvalidAncestorBlock

	// ErrParentBlockNotCurrentTips indicates that the block's parents are not the
	// current tips. This is not a block validation rule, but is required
	// for block proposals submitted via getblocktemplate RPC.
	ErrParentBlockNotCurrentTips

	// ErrWithDiff indicates that there was an error with UTXOSet.WithDiff
	ErrWithDiff

	// ErrFinality indicates that a block doesn't adhere to the finality rules
	ErrFinality

	// ErrTransactionsNotSorted indicates that transactions in block are not
	// sorted by subnetwork
	ErrTransactionsNotSorted

	// ErrInvalidGas transaction wants to use more GAS than allowed
	// by subnetwork
	ErrInvalidGas

	// ErrInvalidPayload transaction includes a payload in a subnetwork that doesn't allow
	// a Payload
	ErrInvalidPayload

	// ErrInvalidPayloadHash invalid hash of transaction's payload
	ErrInvalidPayloadHash

	// ErrSubnetwork indicates that a block doesn't adhere to the subnetwork
	// registry rules
	ErrSubnetworkRegistry

	// ErrInvalidParentsRelation indicates that one of the parents of a block
	// is also an ancestor of another parent
	ErrInvalidParentsRelation

	// ErrDelayedBlockIsNotAllowed indicates that a block with a delayed timestamp was
	// submitted with BFDisallowDelay flag raised.
	ErrDelayedBlockIsNotAllowed

	// ErrOrphanBlockIsNotAllowed indicates that an orphan block was submitted with
	// BFDisallowOrphans flag raised.
	ErrOrphanBlockIsNotAllowed
)

These constants are used to identify a specific RuleError.

func (ErrorCode) String

func (e ErrorCode) String() string

String returns the ErrorCode as a human-readable name.

type FullUTXOSet

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

FullUTXOSet represents a full list of transaction outputs and their values

func NewFullUTXOSet

func NewFullUTXOSet() *FullUTXOSet

NewFullUTXOSet creates a new utxoSet with full list of transaction outputs and their values

func (*FullUTXOSet) AddTx

func (fus *FullUTXOSet) AddTx(tx *domainmessage.MsgTx, blueScore uint64) (isAccepted bool, err error)

AddTx adds a transaction to this utxoSet and returns isAccepted=true iff it's valid in this UTXO's context. It returns error if something unexpected happens, such as serialization error (isAccepted=false doesn't necessarily means there's an error).

This function MUST be called with the DAG lock held.

func (*FullUTXOSet) Get

func (fus *FullUTXOSet) Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool)

Get returns the UTXOEntry associated with the given Outpoint, and a boolean indicating if such entry was found

func (FullUTXOSet) String

func (uc FullUTXOSet) String() string

func (*FullUTXOSet) WithDiff

func (fus *FullUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error)

WithDiff returns a utxoSet which is a diff between this and another utxoSet

type IndexManager

type IndexManager interface {
	// Init is invoked during DAG initialize in order to allow the index
	// manager to initialize itself and any indexes it is managing.
	Init(*BlockDAG, *dbaccess.DatabaseContext) error

	// ConnectBlock is invoked when a new block has been connected to the
	// DAG.
	ConnectBlock(dbContext *dbaccess.TxContext, blockHash *daghash.Hash, acceptedTxsData MultiBlockTxsAcceptanceData) error
}

IndexManager provides a generic interface that is called when blocks are connected to the DAG for the purpose of supporting optional indexes.

type MerkleTree

type MerkleTree []*daghash.Hash

MerkleTree holds the hashes of a merkle tree

func BuildHashMerkleTreeStore

func BuildHashMerkleTreeStore(transactions []*util.Tx) MerkleTree

BuildHashMerkleTreeStore creates a merkle tree from a slice of transactions, based on their hash. See `buildMerkleTreeStore` for more info.

func BuildIDMerkleTreeStore

func BuildIDMerkleTreeStore(transactions []*util.Tx) MerkleTree

BuildIDMerkleTreeStore creates a merkle tree from a slice of transactions, based on their ID. See `buildMerkleTreeStore` for more info.

func (MerkleTree) Root

func (mt MerkleTree) Root() *daghash.Hash

Root returns the root of the merkle tree

type MultiBlockTxsAcceptanceData

type MultiBlockTxsAcceptanceData []BlockTxsAcceptanceData

MultiBlockTxsAcceptanceData stores data about which transactions were accepted by a block It's a slice of the block's blues block IDs and their transaction acceptance data

func (MultiBlockTxsAcceptanceData) FindAcceptanceData

func (data MultiBlockTxsAcceptanceData) FindAcceptanceData(blockHash *daghash.Hash) (*BlockTxsAcceptanceData, bool)

FindAcceptanceData finds the BlockTxsAcceptanceData that matches blockHash

type Notification

type Notification struct {
	Type NotificationType
	Data interface{}
}

Notification defines notification that is sent to the caller via the callback function provided during the call to New and consists of a notification type as well as associated data that depends on the type as follows:

  • Added: *util.Block

type NotificationCallback

type NotificationCallback func(*Notification)

NotificationCallback is used for a caller to provide a callback for notifications about various blockDAG events.

type NotificationType

type NotificationType int

NotificationType represents the type of a notification message.

const (
	// NTBlockAdded indicates the associated block was added into
	// the blockDAG.
	NTBlockAdded NotificationType = iota

	// NTChainChanged indicates that selected parent
	// chain had changed.
	NTChainChanged
)

Constants for the type of a notification message.

func (NotificationType) String

func (n NotificationType) String() string

String returns the NotificationType in human-readable form.

type RuleError

type RuleError struct {
	ErrorCode   ErrorCode // Describes the kind of error
	Description string    // Human readable description of the issue
}

RuleError identifies a rule violation. It is used to indicate that processing of a block or transaction failed due to one of the many validation rules. The caller can use type assertions to determine if a failure was specifically due to a rule violation and access the ErrorCode field to ascertain the specific reason for the rule violation.

func (RuleError) Error

func (e RuleError) Error() string

Error satisfies the error interface and prints human-readable errors.

type SequenceLock

type SequenceLock struct {
	Milliseconds   int64
	BlockBlueScore int64
}

SequenceLock represents the converted relative lock-time in seconds, and absolute block-blue-score 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 'BlockBlueScore' has been reached.

type ThresholdState

type ThresholdState byte

ThresholdState define the various threshold states used when voting on consensus changes.

const (
	// ThresholdDefined is the first state for each deployment and is the
	// state for the genesis block has by definition for all deployments.
	ThresholdDefined ThresholdState = iota

	// ThresholdStarted is the state for a deployment once its start time
	// has been reached.
	ThresholdStarted

	// ThresholdLockedIn is the state for a deployment during the retarget
	// period which is after the ThresholdStarted state period and the
	// number of blocks that have voted for the deployment equal or exceed
	// the required number of votes for the deployment.
	ThresholdLockedIn

	// ThresholdActive is the state for a deployment for all blocks after a
	// retarget period in which the deployment was in the ThresholdLockedIn
	// state.
	ThresholdActive

	// ThresholdFailed is the state for a deployment once its expiration
	// time has been reached and it did not reach the ThresholdLockedIn
	// state.
	ThresholdFailed
)

These constants are used to identify specific threshold states.

func (ThresholdState) String

func (t ThresholdState) String() string

String returns the ThresholdState as a human-readable name.

type TimeSource

type TimeSource interface {
	// Now returns the current time.
	Now() mstime.Time
}

TimeSource is the interface to access time.

func NewTimeSource

func NewTimeSource() TimeSource

NewTimeSource returns a new instance of a TimeSource

type TxAcceptanceData

type TxAcceptanceData struct {
	Tx         *util.Tx
	IsAccepted bool
}

TxAcceptanceData stores a transaction together with an indication if it was accepted or not by some block

type UTXODiff

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

UTXODiff represents a diff between two UTXO Sets.

func NewUTXODiff

func NewUTXODiff() *UTXODiff

NewUTXODiff creates a new, empty utxoDiff without a multiset.

func (*UTXODiff) AddEntry

func (d *UTXODiff) AddEntry(outpoint domainmessage.Outpoint, entry *UTXOEntry) error

AddEntry adds a UTXOEntry to the diff

If d.useMultiset is true, this function MUST be called with the DAG lock held.

func (*UTXODiff) RemoveEntry

func (d *UTXODiff) RemoveEntry(outpoint domainmessage.Outpoint, entry *UTXOEntry) error

RemoveEntry removes a UTXOEntry from the diff.

If d.useMultiset is true, this function MUST be called with the DAG lock held.

func (UTXODiff) String

func (d UTXODiff) String() string

func (*UTXODiff) WithDiff

func (d *UTXODiff) WithDiff(diff *UTXODiff) (*UTXODiff, error)

WithDiff applies provided diff to this diff, creating a new utxoDiff, that would be the result if first d, and than diff were applied to some base

type UTXOEntry

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

UTXOEntry houses details about an individual transaction output in a utxo set such as whether or not it was contained in a coinbase tx, the blue score of the block that accepts the tx, its public key script, and how much it pays.

func NewUTXOEntry

func NewUTXOEntry(txOut *domainmessage.TxOut, isCoinbase bool, blockBlueScore uint64) *UTXOEntry

NewUTXOEntry creates a new utxoEntry representing the given txOut

func (*UTXOEntry) Amount

func (entry *UTXOEntry) Amount() uint64

Amount returns the amount of the output.

func (*UTXOEntry) BlockBlueScore

func (entry *UTXOEntry) BlockBlueScore() uint64

BlockBlueScore returns the blue score of the block accepting the output.

func (*UTXOEntry) IsCoinbase

func (entry *UTXOEntry) IsCoinbase() bool

IsCoinbase returns whether or not the output was contained in a block reward transaction.

func (*UTXOEntry) IsUnaccepted

func (entry *UTXOEntry) IsUnaccepted() bool

IsUnaccepted returns true iff this UTXOEntry has been included in a block but has not yet been accepted by any block.

func (*UTXOEntry) ScriptPubKey

func (entry *UTXOEntry) ScriptPubKey() []byte

ScriptPubKey returns the public key script for the output.

type UTXOSet

type UTXOSet interface {
	fmt.Stringer

	WithDiff(utxoDiff *UTXODiff) (UTXOSet, error)
	AddTx(tx *domainmessage.MsgTx, blockBlueScore uint64) (ok bool, err error)

	Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool)
	// contains filtered or unexported methods
}

UTXOSet represents a set of unspent transaction outputs Every DAG has exactly one fullUTXOSet. When a new block arrives, it is validated and applied to the fullUTXOSet in the following manner: 1. Get the block's PastUTXO: 2. Add all the block's transactions to the block's PastUTXO 3. For each of the block's parents, 3.1. Rebuild their utxoDiff 3.2. Set the block as their diffChild 4. Create and initialize a new virtual block 5. Get the new virtual's PastUTXO 6. Rebuild the utxoDiff for all the tips 7. Convert (meld) the new virtual's diffUTXOSet into a fullUTXOSet. This updates the DAG's fullUTXOSet

type VirtualForTest

type VirtualForTest *virtualBlock

VirtualForTest is an exported version for virtualBlock, so that it can be returned by exported test_util methods

func GetVirtualFromParentsForTest

func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) (VirtualForTest, error)

GetVirtualFromParentsForTest generates a virtual block with the given parents.

func SetVirtualForTest

func SetVirtualForTest(dag *BlockDAG, virtual VirtualForTest) VirtualForTest

SetVirtualForTest replaces the dag's virtual block. This function is used for test purposes only

Directories

Path Synopsis
Package indexers implements optional block DAG indexes.
Package indexers implements optional block DAG indexes.

Jump to

Keyboard shortcuts

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