blockchain

package
v0.0.0-...-29cdea6 Latest Latest
Warning

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

Go to latest
Published: May 9, 2024 License: ISC Imports: 41 Imported by: 0

README

blockchain

Build Status ISC License Doc

Package blockchain implements Decred block handling and chain selection rules.

The Decred block handling and chain selection rules are an integral, and quite likely the most important, part of Decred. At its core, Decred is a distributed consensus of which blocks are valid and which ones will comprise the main block chain (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 chain according to the aforementioned rules. It includes functionality such as rejecting duplicate blocks, ensuring blocks and transactions follow all rules, and best chain selection along with reorganization.

Since this package does not deal with other Decred specifics such as network communication or wallets, 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 newly connected main chain blocks which might result in wallet updates.

A comprehensive suite of tests is provided to ensure proper functionality.

Decred Chain Processing Overview

Before a block is allowed into the block chain, 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
  • Compare the block against predetermined checkpoints for expected timestamps and difficulty based on elapsed time since the checkpoint
  • Perform a series of more thorough checks that depend on the block's position within the block chain 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 chain and perform different actions accordingly in order to ensure any side chains which have higher difficulty than the main chain become the new main chain
  • When a block is being connected to the main chain (either through reorganization of a side chain to the main chain or just extending the main chain), 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

Processing Order

This package supports headers-first semantics such that block data can be processed out of order so long as the associated header is already known.

The headers themselves, however, must be processed in the correct order since headers that do not properly connect are rejected. In other words, orphan headers are not allowed.

The processing code always maintains the best chain as the branch tip that has the most cumulative proof of work, so it is important to keep that in mind when considering errors returned from processing blocks.

Notably, due to the ability to process blocks out of order, and the fact blocks can only be fully validated once all of their ancestors have the block data available, it is to be expected that no error is returned immediately for blocks that are valid enough to make it to the point they require the remaining ancestor block data to be fully validated even though they might ultimately end up failing validation. Similarly, because the data for a block becoming available makes any of its direct descendants that already have their data available eligible for validation, an error being returned does not necessarily mean the block being processed is the one that failed validation.

Errors

Errors returned by this package have full support for the standard library errors.Is and errors.As methods and are either the raw errors provided by underlying calls or of type blockchain.RuleError, possibly wrapped in a blockchain.MultiError. This allows the caller to differentiate between unexpected errors, such as database errors, versus errors due to rule violations through errors.As. In addition, callers can programmatically determine the specific rule violation by making use of errors.Is with any of the wrapped error kinds.

Installation and Updating

This package is internal and therefore is neither directly installed nor needs to be manually updated.

Examples

  • ProcessBlock Example Demonstrates how to create a new chain instance and use ProcessBlock to attempt to add a block to the chain. This example intentionally attempts to insert a duplicate genesis block to illustrate how an invalid block is handled.

License

Package blockchain is licensed under the copyfree ISC License.

Documentation

Overview

Package blockchain implements Decred block handling and chain selection rules.

Index

Examples

Constants

View Source
const (
	// ErrDuplicateBlock indicates a block with the same hash already
	// exists.
	ErrDuplicateBlock = ErrorKind("ErrDuplicateBlock")

	// ErrMissingParent indicates that the block was an orphan.
	ErrMissingParent = ErrorKind("ErrMissingParent")

	// ErrNoBlockData indicates an attempt to perform an operation on a block
	// that requires all data to be available does not have the data.  This is
	// typically because the header is known, but the full data has not been
	// received yet.
	ErrNoBlockData = ErrorKind("ErrNoBlockData")

	// ErrBlockTooBig indicates the serialized block size exceeds the
	// maximum allowed size.
	ErrBlockTooBig = ErrorKind("ErrBlockTooBig")

	// ErrWrongBlockSize indicates that the block size in the header is not
	// the actual serialized size of the block.
	ErrWrongBlockSize = ErrorKind("ErrWrongBlockSize")

	// 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 = ErrorKind("ErrBlockVersionTooOld")

	// ErrBadStakeVersion indicates the block version is too old and is no
	// longer accepted since the majority of the network has upgraded to a
	// newer version.
	ErrBadStakeVersion = ErrorKind("ErrBadStakeVersion")

	// ErrInvalidTime indicates the time in the passed block has a precision
	// that is more than one second.  The chain consensus rules require
	// timestamps to have a maximum precision of one second.
	ErrInvalidTime = ErrorKind("ErrInvalidTime")

	// ErrTimeTooOld indicates the time is either before the median time of the
	// last several blocks per the chain consensus rules or prior to the time
	// that is required by max difficulty limitations on the test network.
	ErrTimeTooOld = ErrorKind("ErrTimeTooOld")

	// ErrTimeTooNew indicates the time is too far in the future as compared
	// the current time.
	ErrTimeTooNew = ErrorKind("ErrTimeTooNew")

	// ErrUnexpectedDifficulty indicates specified bits do not align with
	// the expected value either because it doesn't match the calculated
	// value based on difficulty regarding the rules or it is out of the
	// valid range.
	ErrUnexpectedDifficulty = ErrorKind("ErrUnexpectedDifficulty")

	// ErrHighHash indicates the block does not hash to a value which is
	// lower than the required target difficultly.
	ErrHighHash = ErrorKind("ErrHighHash")

	// ErrBadMerkleRoot indicates the calculated merkle root does not match
	// the expected value.
	ErrBadMerkleRoot = ErrorKind("ErrBadMerkleRoot")

	// ErrBadCommitmentRoot indicates the calculated commitment root does
	// not match the expected value.
	ErrBadCommitmentRoot = ErrorKind("ErrBadCommitmentRoot")

	// ErrForkTooOld indicates a block is attempting to fork the block chain
	// before the fork rejection checkpoint.
	ErrForkTooOld = ErrorKind("ErrForkTooOld")

	// ErrBadMaxDiffCheckpoint indicates a block on the version 3 test network
	// at the height used to activate maximum difficulty semantics does not
	// match the expected one.
	ErrBadMaxDiffCheckpoint = ErrorKind("ErrBadMaxDiffCheckpoint")

	// ErrNoTransactions indicates the block does not have at least one
	// transaction.  A valid block must have at least the coinbase transaction.
	ErrNoTransactions = ErrorKind("ErrNoTransactions")

	// ErrNoTxInputs indicates a transaction does not have any inputs.  A
	// valid transaction must have at least one input.
	ErrNoTxInputs = ErrorKind("ErrNoTxInputs")

	// ErrNoTxOutputs indicates a transaction does not have any outputs.  A
	// valid transaction must have at least one output.
	ErrNoTxOutputs = ErrorKind("ErrNoTxOutputs")

	// ErrTxTooBig indicates a transaction exceeds the maximum allowed size
	// when serialized.
	ErrTxTooBig = ErrorKind("ErrTxTooBig")

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

	// ErrDuplicateTxInputs indicates a transaction references the same
	// input more than once.
	ErrDuplicateTxInputs = ErrorKind("ErrDuplicateTxInputs")

	// ErrTxVersionTooHigh indicates a transaction version is higher than the
	// maximum version allowed by the active consensus rules.
	ErrTxVersionTooHigh = ErrorKind("ErrTxVersionTooHigh")

	// 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 = ErrorKind("ErrBadTxInput")

	// ErrScriptVersionTooHigh indicates a transaction script version is higher
	// than the maximum version allowed by the active consensus rules.
	ErrScriptVersionTooHigh = ErrorKind("ErrScriptVersionTooHigh")

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

	// ErrUnfinalizedTx indicates a transaction has not been finalized.
	// A valid block may only contain finalized transactions.
	ErrUnfinalizedTx = ErrorKind("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 = ErrorKind("ErrDuplicateTx")

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

	// ErrImmatureSpend indicates a transaction is attempting to spend a
	// coinbase that has not yet reached the required maturity.
	ErrImmatureSpend = ErrorKind("ErrImmatureSpend")

	// ErrSpendTooHigh indicates a transaction is attempting to spend more
	// value than the sum of all of its inputs.
	ErrSpendTooHigh = ErrorKind("ErrSpendTooHigh")

	// ErrBadFees indicates the total fees for a block are invalid due to
	// exceeding the maximum possible value.
	ErrBadFees = ErrorKind("ErrBadFees")

	// ErrTooManySigOps indicates the total number of signature operations
	// for a transaction or block exceed the maximum allowed limits.
	ErrTooManySigOps = ErrorKind("ErrTooManySigOps")

	// ErrFirstTxNotCoinbase indicates the first transaction in a block
	// is not a coinbase transaction.
	ErrFirstTxNotCoinbase = ErrorKind("ErrFirstTxNotCoinbase")

	// ErrCoinbaseHeight indicates that the encoded height in the coinbase
	// is incorrect.
	ErrCoinbaseHeight = ErrorKind("ErrCoinbaseHeight")

	// ErrMultipleCoinbases indicates a block contains more than one
	// coinbase transaction.
	ErrMultipleCoinbases = ErrorKind("ErrMultipleCoinbases")

	// ErrStakeTxInRegularTree indicates a stake transaction was found in
	// the regular transaction tree.
	ErrStakeTxInRegularTree = ErrorKind("ErrStakeTxInRegularTree")

	// ErrRegTxInStakeTree indicates that a regular transaction was found in
	// the stake transaction tree.
	ErrRegTxInStakeTree = ErrorKind("ErrRegTxInStakeTree")

	// ErrBadCoinbaseScriptLen indicates the length of the signature script
	// for a coinbase transaction is not within the valid range.
	ErrBadCoinbaseScriptLen = ErrorKind("ErrBadCoinbaseScriptLen")

	// ErrBadCoinbaseValue indicates the amount of a coinbase value does
	// not match the expected value of the subsidy plus the sum of all fees.
	ErrBadCoinbaseValue = ErrorKind("ErrBadCoinbaseValue")

	// ErrBadCoinbaseOutpoint indicates that the outpoint used by a coinbase
	// as input was non-null.
	ErrBadCoinbaseOutpoint = ErrorKind("ErrBadCoinbaseOutpoint")

	// ErrBadCoinbaseFraudProof indicates that the fraud proof for a coinbase
	// input was non-null.
	ErrBadCoinbaseFraudProof = ErrorKind("ErrBadCoinbaseFraudProof")

	// ErrBadCoinbaseAmountIn indicates that the AmountIn (=subsidy) for a
	// coinbase input was incorrect.
	ErrBadCoinbaseAmountIn = ErrorKind("ErrBadCoinbaseAmountIn")

	// ErrBadStakebaseAmountIn indicates that the AmountIn (=subsidy) for a
	// stakebase input was incorrect.
	ErrBadStakebaseAmountIn = ErrorKind("ErrBadStakebaseAmountIn")

	// ErrBadStakebaseScriptLen indicates the length of the signature script
	// for a stakebase transaction is not within the valid range.
	ErrBadStakebaseScriptLen = ErrorKind("ErrBadStakebaseScriptLen")

	// ErrBadStakebaseScrVal indicates the signature script for a stakebase
	// transaction was not set to the network consensus value.
	ErrBadStakebaseScrVal = ErrorKind("ErrBadStakebaseScrVal")

	// 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 = ErrorKind("ErrScriptMalformed")

	// ErrScriptValidation indicates the result of executing a transaction
	// script failed.  The error covers any failure when executing scripts
	// such as signature verification failures and execution past the end
	// of the stack.
	ErrScriptValidation = ErrorKind("ErrScriptValidation")

	// ErrNotEnoughStake indicates that there was for some SStx in a given block,
	// the given SStx did not have enough stake to meet the network target.
	ErrNotEnoughStake = ErrorKind("ErrNotEnoughStake")

	// ErrStakeBelowMinimum indicates that for some SStx in a given block,
	// the given SStx had an amount of stake below the minimum network target.
	ErrStakeBelowMinimum = ErrorKind("ErrStakeBelowMinimum")

	// ErrNonstandardStakeTx indicates that a block contained a stake tx that
	// was not one of the allowed types of a stake transactions.
	ErrNonstandardStakeTx = ErrorKind("ErrNonstandardStakeTx")

	// ErrNotEnoughVotes indicates that a block contained less than a majority
	// of voters.
	ErrNotEnoughVotes = ErrorKind("ErrNotEnoughVotes")

	// ErrTooManyVotes indicates that a block contained more than the maximum
	// allowable number of votes.
	ErrTooManyVotes = ErrorKind("ErrTooManyVotes")

	// ErrFreshStakeMismatch indicates that a block's header contained a different
	// number of SStx as compared to what was found in the block.
	ErrFreshStakeMismatch = ErrorKind("ErrFreshStakeMismatch")

	// ErrTooManySStxs indicates that more than the allowed number of SStx was
	// found in a block.
	ErrTooManySStxs = ErrorKind("ErrTooManySStxs")

	// ErrInvalidEarlyStakeTx indicates that a tx type other than SStx was found
	// in the stake tx tree before the period when stake validation begins, or
	// before the stake tx type could possibly be included in the block.
	ErrInvalidEarlyStakeTx = ErrorKind("ErrInvalidEarlyStakeTx")

	// ErrTicketUnavailable indicates that a vote in the block spent a ticket
	// that could not be found.
	ErrTicketUnavailable = ErrorKind("ErrTicketUnavailable")

	// ErrVotesOnWrongBlock indicates that an SSGen voted on a block that is not
	// the block's parent, and so was ineligible for inclusion into that block.
	ErrVotesOnWrongBlock = ErrorKind("ErrVotesOnWrongBlock")

	// ErrVotesMismatch indicates that the number of SSGen in the block was not
	// equivalent to the number of votes provided in the block header.
	ErrVotesMismatch = ErrorKind("ErrVotesMismatch")

	// ErrIncongruentVotebit indicates that the first votebit in votebits was not
	// the same as that determined by the majority of voters in the SSGen tx
	// included in the block.
	ErrIncongruentVotebit = ErrorKind("ErrIncongruentVotebit")

	// ErrInvalidSSRtx indicates than an SSRtx in a block could not be found to
	// have a valid missed sstx input as per the stake ticket database.
	ErrInvalidSSRtx = ErrorKind("ErrInvalidSSRtx")

	// ErrInvalidRevNum indicates that the number of revocations from the
	// header was not the same as the number of SSRtx included in the block.
	ErrRevocationsMismatch = ErrorKind("ErrRevocationsMismatch")

	// ErrTooManyRevocations indicates more revocations were found in a block
	// than were allowed.
	ErrTooManyRevocations = ErrorKind("ErrTooManyRevocations")

	// ErrTicketCommitment indicates that a ticket commitment contains an amount
	// that does not coincide with the associated ticket input amount.
	ErrTicketCommitment = ErrorKind("ErrTicketCommitment")

	// ErrInvalidVoteInput indicates that an input to a vote transaction is
	// either not a stake ticket submission or is not a supported version.
	ErrInvalidVoteInput = ErrorKind("ErrInvalidVoteInput")

	// ErrBadNumPayees indicates that either a vote or revocation transaction
	// does not make the correct number of payments per the associated ticket
	// commitments.
	ErrBadNumPayees = ErrorKind("ErrBadNumPayees")

	// ErrBadPayeeScriptVersion indicates that either a vote or revocation
	// transaction output that corresponds to a ticket commitment does not use
	// a supported script version.
	ErrBadPayeeScriptVersion = ErrorKind("ErrBadPayeeScriptVersion")

	// ErrBadPayeeScriptType indicates that either a vote or revocation
	// transaction output that corresponds to a ticket commitment does not pay
	// to the same script type required by the commitment.
	ErrBadPayeeScriptType = ErrorKind("ErrBadPayeeScriptType")

	// ErrBadPayeeScriptType indicates that either a vote or revocation
	// transaction output that corresponds to a ticket commitment does not pay
	// to the hash required by the commitment.
	ErrMismatchedPayeeHash = ErrorKind("ErrMismatchedPayeeHash")

	// ErrBadPayeeValue indicates that either a vote or revocation transaction
	// output that corresponds to a ticket commitment does not pay the expected
	// amount required by the commitment.
	ErrBadPayeeValue = ErrorKind("ErrBadPayeeValue")

	// ErrSSGenSubsidy indicates that there was an error in the amount of subsidy
	// generated in the vote.
	ErrSSGenSubsidy = ErrorKind("ErrSSGenSubsidy")

	// ErrImmatureTicketSpend indicates that a vote or revocation is attempting
	// to spend a ticket submission output that has not yet reached the required
	// maturity.
	ErrImmatureTicketSpend = ErrorKind("ErrImmatureTicketSpend")

	// ErrTicketInputScript indicates that a ticket input is not one of the
	// supported script forms or versions.
	ErrTicketInputScript = ErrorKind("ErrTicketInputScript")

	// ErrInvalidRevokeInput indicates that an input to a revocation transaction
	// is either not a stake ticket submission or is not a supported version.
	ErrInvalidRevokeInput = ErrorKind("ErrInvalidRevokeInput")

	// ErrTxSStxOutSpend indicates that a non SSGen or SSRtx tx attempted to spend
	// an OP_SSTX tagged output from an SStx.
	ErrTxSStxOutSpend = ErrorKind("ErrTxSStxOutSpend")

	// ErrRegTxCreateStakeOut indicates that a regular tx attempted to create
	// a stake tagged output.
	ErrRegTxCreateStakeOut = ErrorKind("ErrRegTxCreateStakeOut")

	// ErrInvalidFinalState indicates that the final state of the PRNG included
	// in the block differed from the calculated final state.
	ErrInvalidFinalState = ErrorKind("ErrInvalidFinalState")

	// ErrPoolSize indicates an error in the ticket pool size for this block.
	ErrPoolSize = ErrorKind("ErrPoolSize")

	// ErrForceReorgSameBlock indicates that a reorganization  was attempted to
	// be forced to the same block.
	ErrForceReorgSameBlock = ErrorKind("ErrForceReorgSameBlock")

	// ErrForceReorgWrongChain indicates that a reorganization  was attempted
	// to be forced, but the chain indicated was not mirrored by b.bestChain.
	ErrForceReorgWrongChain = ErrorKind("ErrForceReorgWrongChain")

	// ErrForceReorgMissingChild indicates that a reorganization  was attempted
	// to be forced, but the child node to reorganize to could not be found.
	ErrForceReorgMissingChild = ErrorKind("ErrForceReorgMissingChild")

	// ErrBadStakebaseValue indicates that a block's stake tx tree has spent
	// more than it is allowed.
	ErrBadStakebaseValue = ErrorKind("ErrBadStakebaseValue")

	// ErrStakeFees indicates an error with the fees found in the stake
	// transaction tree.
	ErrStakeFees = ErrorKind("ErrStakeFees")

	// ErrNoStakeTx indicates there were no stake transactions found in a
	// block after stake validation height.
	ErrNoStakeTx = ErrorKind("ErrNoStakeTx")

	// ErrBadBlockHeight indicates that a block header's embedded block height
	// was different from where it was actually embedded in the block chain.
	ErrBadBlockHeight = ErrorKind("ErrBadBlockHeight")

	// ErrBlockOneTx indicates that block height 1 failed to correctly generate
	// the block one initial payout transaction.
	ErrBlockOneTx = ErrorKind("ErrBlockOneTx")

	// ErrBlockOneInputs indicates that block height 1 coinbase transaction
	// input zero was incorrect in some way.
	ErrBlockOneInputs = ErrorKind("ErrBlockOneInputs")

	// ErrBlockOneOutputs indicates that block height 1 failed to incorporate
	// the ledger addresses correctly into the transaction's outputs.
	ErrBlockOneOutputs = ErrorKind("ErrBlockOneOutputs")

	// ErrNoTreasury indicates that there was no treasury payout present in the
	// coinbase of a block after height 1 and prior to the activation of the
	// decentralized treasury.
	ErrNoTreasury = ErrorKind("ErrNoTreasury")

	// ErrExpiredTx indicates that the transaction is currently expired.
	ErrExpiredTx = ErrorKind("ErrExpiredTx")

	// ErrExpiryTxSpentEarly indicates that an output from a transaction
	// that included an expiry field was spent before coinbase maturity
	// many blocks had passed in the blockchain.
	ErrExpiryTxSpentEarly = ErrorKind("ErrExpiryTxSpentEarly")

	// ErrFraudAmountIn indicates the witness amount given was fraudulent.
	ErrFraudAmountIn = ErrorKind("ErrFraudAmountIn")

	// ErrFraudBlockHeight indicates the witness block height given was
	// fraudulent.
	ErrFraudBlockHeight = ErrorKind("ErrFraudBlockHeight")

	// ErrFraudBlockIndex indicates the witness block index given was
	// fraudulent.
	ErrFraudBlockIndex = ErrorKind("ErrFraudBlockIndex")

	// ErrZeroValueOutputSpend indicates that a transaction attempted to spend a
	// zero value output.
	ErrZeroValueOutputSpend = ErrorKind("ErrZeroValueOutputSpend")

	// ErrInvalidEarlyVoteBits indicates that a block before stake validation
	// height had an unallowed vote bits value.
	ErrInvalidEarlyVoteBits = ErrorKind("ErrInvalidEarlyVoteBits")

	// ErrInvalidEarlyFinalState indicates that a block before stake validation
	// height had a non-zero final state.
	ErrInvalidEarlyFinalState = ErrorKind("ErrInvalidEarlyFinalState")

	// ErrKnownInvalidBlock indicates that this block has previously failed
	// validation.
	ErrKnownInvalidBlock = ErrorKind("ErrKnownInvalidBlock")

	// ErrInvalidAncestorBlock indicates that an ancestor of this block has
	// failed validation.
	ErrInvalidAncestorBlock = ErrorKind("ErrInvalidAncestorBlock")

	// ErrInvalidTemplateParent indicates that a block template builds on a
	// block that is either not the current best chain tip or its parent.
	ErrInvalidTemplateParent = ErrorKind("ErrInvalidTemplateParent")

	// ErrUnknownPiKey indicates that the provided public Pi Key is not
	// a well known key.
	ErrUnknownPiKey = ErrorKind("ErrUnknownPiKey")

	// ErrInvalidPiSignature indicates that a treasury spend transaction
	// was not properly signed.
	ErrInvalidPiSignature = ErrorKind("ErrInvalidPiSignature")

	// ErrInvalidTVoteWindow indicates that a treasury spend transaction
	// appeared in a block that is prior to a valid treasury vote window.
	ErrInvalidTVoteWindow = ErrorKind("ErrInvalidTVoteWindow")

	// ErrNotTVI indicates that a treasury spend transaction appeared in a
	// block that is not at a TVI interval.
	ErrNotTVI = ErrorKind("ErrNotTVI")

	// ErrInvalidTSpendWindow indicates that this treasury spend
	// transaction is outside of the allowed window.
	ErrInvalidTSpendWindow = ErrorKind("ErrInvalidTSpendWindow")

	// ErrNotEnoughTSpendVotes indicates that a treasury spend transaction
	// does not have enough votes to be included in block.
	ErrNotEnoughTSpendVotes = ErrorKind("ErrNotEnoughTSpendVotes")

	// ErrInvalidTSpendValueIn indicates that a treasury spend transaction
	// ValueIn does not match the encoded copy in the first TxOut.
	ErrInvalidTSpendValueIn = ErrorKind("ErrInvalidTSpendValueIn")

	// ErrTSpendExists indicates that a duplicate treasury spend
	// transaction has been mined on a TVI in the current best chain.
	ErrTSpendExists = ErrorKind("ErrTSpendExists")

	// ErrInvalidExpenditure indicates that a treasury spend transaction
	// expenditure is out of range.
	ErrInvalidExpenditure = ErrorKind("ErrInvalidExpenditure")

	// ErrFirstTxNotTreasurybase indicates the first transaction in a block
	// is not a treasurybase transaction.
	ErrFirstTxNotTreasurybase = ErrorKind("ErrFirstTxNotTreasurybase")

	// ErrBadTreasurybaseOutpoint indicates that the outpoint used by a
	// treasurybase as input was non-null.
	ErrBadTreasurybaseOutpoint = ErrorKind("ErrBadTreasurybaseOutpoint")

	// ErrBadTreasurybaseFraudProof indicates that the fraud proof for a
	// treasurybase input was non-null.
	ErrBadTreasurybaseFraudProof = ErrorKind("ErrBadTreasurybaseFraudProof")

	// ErrBadTreasurybaseScriptLen indicates the length of the signature script
	// for a treasurybase transaction is not within the valid range.
	ErrBadTreasurybaseScriptLen = ErrorKind("ErrBadTreasurybaseScriptLen")

	// ErrTreasurybaseTxNotOpReturn indicates the second output of a
	// treasury base transaction is not an OP_RETURN.
	ErrTreasurybaseTxNotOpReturn = ErrorKind("ErrTreasurybaseTxNotOpReturn")

	// ErrTreasurybaseHeight indicates that the encoded height in the
	// treasurybase is incorrect.
	ErrTreasurybaseHeight = ErrorKind("ErrTreasurybaseHeight")

	// ErrInvalidTreasurybaseTxOutputs indicates that the transaction does
	// not have the correct number of outputs.
	ErrInvalidTreasurybaseTxOutputs = ErrorKind("ErrInvalidTreasurybaseTxOutputs")

	// ErrInvalidTreasurybaseVersion indicates that the transaction output
	// has the wrong version.
	ErrInvalidTreasurybaseVersion = ErrorKind("ErrInvalidTreasurybaseVersion")

	// ErrInvalidTreasurybaseScript indicates that the transaction output
	// script is invalid.
	ErrInvalidTreasurybaseScript = ErrorKind("ErrInvalidTreasurybaseScript")

	// ErrTreasurybaseOutValue ensures that the OP_TADD value of a
	// treasurybase is not the expected amount.
	ErrTreasurybaseOutValue = ErrorKind("ErrTreasurybaseOutValue")

	// ErrMultipleTreasurybases indicates a block contains more than one
	// treasurybase transaction.
	ErrMultipleTreasurybases = ErrorKind("ErrMultipleTreasurybases")

	// ErrBadTreasurybaseAmountIn indicates that a block contains an
	// invalid treasury contribution.
	ErrBadTreasurybaseAmountIn = ErrorKind("ErrBadTreasurybaseAmountIn")

	// ErrBadTSpendOutpoint indicates that the outpoint used by a
	// treasury spend as input was non-null.
	ErrBadTSpendOutpoint = ErrorKind("ErrBadTSpendOutpoint")

	// ErrBadTSpendFraudProof indicates that the fraud proof for a treasury
	// spend transaction input was non-null.
	ErrBadTSpendFraudProof = ErrorKind("ErrBadTSpendFraudProof")

	// ErrBadTSpendScriptLen indicates the length of the signature script
	// for a treasury spend transaction is not within the valid range.
	ErrBadTSpendScriptLen = ErrorKind("ErrBadTSpendScriptLen")

	// ErrInvalidTAddChange indicates the change output of a TAdd is zero.
	ErrInvalidTAddChange = ErrorKind("ErrInvalidTAddChange")

	// ErrTooManyTAdds indicates the number of treasury adds in a given
	// block is larger than the maximum allowed.
	ErrTooManyTAdds = ErrorKind("ErrTooManyTAdds")

	// ErrTicketExhaustion indicates extending a given block with another one
	// would result in an unrecoverable chain due to ticket exhaustion.
	ErrTicketExhaustion = ErrorKind("ErrTicketExhaustion")

	// ErrDBTooOldToUpgrade indicates the database version is prior to the
	// minimum supported version for which upgrades are supported.
	ErrDBTooOldToUpgrade = ErrorKind("ErrDBTooOldToUpgrade")

	// ErrUnknownBlock indicates a requested block does not exist.
	ErrUnknownBlock = ErrorKind("ErrUnknownBlock")

	// ErrNoFilter indicates a filter for a given block hash does not exist.
	ErrNoFilter = ErrorKind("ErrNoFilter")

	// ErrNoTreasuryBalance indicates the treasury balance for a given block
	// hash does not exist.
	ErrNoTreasuryBalance = ErrorKind("ErrNoTreasuryBalance")

	// ErrInvalidateGenesisBlock indicates an attempt to invalidate the genesis
	// block which is not allowed.
	ErrInvalidateGenesisBlock = ErrorKind("ErrInvalidateGenesisBlock")

	// ErrSerializeHeader indicates an attempt to serialize a block header failed.
	ErrSerializeHeader = ErrorKind("ErrSerializeHeader")

	// ErrUtxoBackend indicates that a general error was encountered when
	// accessing the UTXO backend.
	ErrUtxoBackend = ErrorKind("ErrUtxoBackend")

	// ErrUtxoBackendCorruption indicates that underlying data being accessed in
	// the UTXO backend is corrupted.
	ErrUtxoBackendCorruption = ErrorKind("ErrUtxoBackendCorruption")

	// ErrUtxoBackendNotOpen indicates that the UTXO backend was accessed before
	// it was opened or after it was closed.
	ErrUtxoBackendNotOpen = ErrorKind("ErrUtxoBackendNotOpen")

	// ErrUtxoBackendTxClosed indicates an attempt was made to commit or rollback
	// a UTXO backend transaction that has already had one of those operations
	// performed.
	ErrUtxoBackendTxClosed = ErrorKind("ErrUtxoBackendTxClosed")

	// ErrInvalidRevocationTxVersion indicates that the revocation is the wrong
	// transaction version.
	ErrInvalidRevocationTxVersion = ErrorKind("ErrInvalidRevocationTxVersion")

	// ErrNoExpiredTicketRevocation indicates that the block does not contain a
	// revocation for a ticket that is becoming expired as of that block.
	ErrNoExpiredTicketRevocation = ErrorKind("ErrNoExpiredTicketRevocation")

	// ErrNoMissedTicketRevocation indicates that the block does not contain a
	// revocation for a ticket that is becoming missed as of that block.
	ErrNoMissedTicketRevocation = ErrorKind("ErrNoMissedTicketRevocation")

	// ErrUnknownDeploymentID indicates a deployment id does not exist.
	ErrUnknownDeploymentID = ErrorKind("ErrUnknownDeploymentID")

	// ErrUnknownDeploymentVersion indicates a version for a given deployment id
	// was specified that does not exist.
	ErrUnknownDeploymentVersion = ErrorKind("ErrUnknownDeploymentVersion")

	// ErrDuplicateDeployment indicates a duplicate deployment id exists in the
	// network parameter deployment definitions.
	ErrDuplicateDeployment = ErrorKind("ErrDuplicateDeployment")

	// ErrUnknownDeploymentChoice indicates a choice id for a deployment does
	// not exist.
	ErrUnknownDeploymentChoice = ErrorKind("ErrUnknownDeploymentChoice")

	// ErrDeploymentBadMask indicates the mask for a deployment is invalid in
	// some way.  For example, if it is equal to zero or does not consist of
	// only consecutive bits set.
	ErrDeploymentBadMask = ErrorKind("ErrDeploymentBadMask")

	// ErrDeploymentTooManyChoices indicates there are more choices defined for
	// a deployment that its mask can represent.
	ErrDeploymentTooManyChoices = ErrorKind("ErrDeploymentTooManyChoices")

	// ErrDeploymentMissingChoiceID indicates a choice id is not set.
	ErrDeploymentMissingChoiceID = ErrorKind("ErrDeploymentMissingChoiceID")

	// ErrDeploymentBadChoiceBits indicates the choice bits that represent a
	// deployment vote choice are invalid in some way.  For example, when they
	// are all zero and the choice is not also marked as abstain or they are not
	// covered by the mask.
	ErrDeploymentBadChoiceBits = ErrorKind("ErrDeploymentBadChoiceBits")

	// ErrDeploymentNonExclusiveFlags indicates a deployment choice has an
	// invalid flag combination.
	ErrDeploymentNonExclusiveFlags = ErrorKind("ErrDeploymentNonExclusiveFlags")

	// ErrDeploymentDuplicateChoice indicates a duplicate deployment choice id
	// exists.
	ErrDeploymentDuplicateChoice = ErrorKind("ErrDeploymentDuplicateChoice")

	// ErrDeploymentMissingAbstain indicates a deployment vote does not have a
	// choice that is marked as abstain.
	ErrDeploymentMissingAbstain = ErrorKind("ErrDeploymentMissingAbstain")

	// ErrDeploymentTooManyAbstain indicates a deployment vote has more than one
	// choice that is marked as the abstaining choice.
	ErrDeploymentTooManyAbstain = ErrorKind("ErrDeploymentTooManyAbstain")

	// ErrDeploymentMissingNo indicates a deployment vote does not have a choice
	// that is marked as the no choice.
	ErrDeploymentMissingNo = ErrorKind("ErrDeploymentMissingNo")

	// ErrDeploymentTooManyNo indicates a deployment vote has more than one
	// choice that is marked as the no choice.
	ErrDeploymentTooManyNo = ErrorKind("ErrDeploymentTooManyNo")

	// ErrDeploymentChoiceAbstain indicates the forced choice id for a
	// deployment is the unusable abstaining choice.
	ErrDeploymentChoiceAbstain = ErrorKind("ErrDeploymentChoiceAbstain")

	// ErrForcedMainNetChoice indicates a forced choice id is configured for a
	// deployment on the main network.
	ErrForcedMainNetChoice = ErrorKind("ErrForcedMainNetChoice")
)

These constants are used to identify a specific ErrorKind.

View Source
const (
	// MaxSigOpsPerBlock is the maximum number of signature operations
	// allowed for a block.  This really should be based upon the max
	// allowed block size for a network and any votes that might change it,
	// however, since it was not updated to be based upon it before
	// release, it will require a hard fork and associated vote agenda to
	// change it.  The original max block size for the protocol was 1MiB,
	// so that is what this is based on.
	MaxSigOpsPerBlock = 1000000 / 200

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

	// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
	MinCoinbaseScriptLen = 2

	// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
	MaxCoinbaseScriptLen = 100

	// MaxTAddsPerBlock is the maximum number of treasury add txs that are
	// allowed per block.
	MaxTAddsPerBlock = 20
)
View Source
const (
	// HeaderCmtFilterIndex is the proof index for the filter header commitment.
	HeaderCmtFilterIndex = 0
)

Variables

This section is empty.

Functions

func CalcCommitmentRootV1

func CalcCommitmentRootV1(filterHash chainhash.Hash) chainhash.Hash

CalcCommitmentRootV1 calculates and returns the required v1 block commitment root from the filter hash it commits to.

This function is safe for concurrent access.

func CheckBlockSanity

func CheckBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, chainParams *chaincfg.Params) 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 CheckDBTooOldToUpgrade

func CheckDBTooOldToUpgrade(db database.DB) error

CheckDBTooOldToUpgrade returns an ErrDBTooOldToUpgrade error if the provided database can no longer be upgraded due to being too old.

func CheckProofOfStake

func CheckProofOfStake(block *dcrutil.Block, posLimit int64) error

CheckProofOfStake ensures that all ticket purchases in the block pay at least the amount required by the block header stake bits which indicate the target stake difficulty (aka ticket price) as claimed.

func CheckTransaction

func CheckTransaction(tx *wire.MsgTx, params *chaincfg.Params, flags AgendaFlags) error

CheckTransaction performs several validation checks on a transaction that include both preliminary sanity checks that are context free as well as those which depend on whether or not an agenda is active.

The flags may be used to specify which agendas should be considered as active in order to change how the validation rules are applied accordingly.

func CheckTransactionInputs

func CheckTransactionInputs(subsidyCache *standalone.SubsidyCache,
	tx *dcrutil.Tx, txHeight int64, view *UtxoViewpoint, checkFraudProof bool,
	chainParams *chaincfg.Params, prevHeader *wire.BlockHeader,
	isTreasuryEnabled, isAutoRevocationsEnabled bool,
	subsidySplitVariant standalone.SubsidySplitVariant) (int64, 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 Decred and therefore allowed to spend them. 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 standalone.CheckTransactionSanity function prior to calling this function.

func CountP2SHSigOps

func CountP2SHSigOps(tx *dcrutil.Tx, isCoinBaseTx bool, isStakeBaseTx bool, view *UtxoViewpoint, isTreasuryEnabled bool) (int, error)

CountP2SHSigOps returns the number of signature operations for all input transactions which are of the pay-to-script-hash type. This uses the precise, signature operation counting mechanism from the script engine which requires access to the input transaction scripts.

func CountSigOps

func CountSigOps(tx *dcrutil.Tx, isCoinBaseTx bool, isSSGen bool, isTreasuryEnabled bool) 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 IsExpired

func IsExpired(tx *dcrutil.Tx, blockHeight int64) bool

IsExpired returns where or not the passed transaction is expired according to the given block height.

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

func IsExpiredTx

func IsExpiredTx(tx *wire.MsgTx, blockHeight int64) bool

IsExpiredTx returns where or not the passed transaction is expired according to the given block height.

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

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *dcrutil.Tx, blockHeight int64, blockTime time.Time) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func LoadUtxoDB

func LoadUtxoDB(ctx context.Context, params *chaincfg.Params, dataDir string) (*leveldb.DB, error)

LoadUtxoDB loads (or creates when needed) the UTXO database and returns a handle to it. It also contains additional logic such as ensuring the regression test database is clean when in regression test mode.

func LockTimeToSequence

func LockTimeToSequence(isSeconds bool, lockTime uint32) (uint32, error)

LockTimeToSequence converts the passed relative lock time to a sequence number in accordance with DCP0003.

A sequence number is defined as follows:

  • bit 31 is the disable bit
  • the next 8 bits are reserved
  • bit 22 is the relative lock type (unset = block height, set = seconds)
  • the next 6 bits are reserved
  • the least significant 16 bits represent the value
  • value has a granularity of 512 when interpreted as seconds (bit 22 set)

Diagram

---------------------------------------------------
| Disable | Reserved |  Type | Reserved |  Value  |
|-------------------------------------------------|
|  1 bit  |  8 bits  | 1 bit |  6 bits  | 16 bits |
|-------------------------------------------------|
|   [31]  |  [30-23] |  [22] |  [21-16] | [15-0]  |
---------------------------------------------------

The above implies that the maximum relative block height that can be encoded is 65535 and the maximum relative number of seconds that can be encoded is 65535*512 = 33,553,920 seconds (~1.06 years). It also means that seconds are truncated to the nearest granularity towards 0 (e.g. 536 seconds will end up round tripping as 512 seconds and 1500 seconds will end up round tripping as 1024 seconds).

An error will be returned for values that are larger than can be represented.

func SequenceLockActive

func SequenceLockActive(lock *SequenceLock, blockHeight int64, medianTime time.Time) bool

SequenceLockActive determines if all of the inputs to a given transaction have achieved a relative age that surpasses the requirements specified by their respective sequence locks as calculated by CalcSequenceLock. A single sequence lock is sufficient because the calculated lock selects the minimum required time and block height from all of the non-disabled inputs after which the transaction can be included.

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

func UseTreasuryLogger

func UseTreasuryLogger(logger slog.Logger)

UseTreasuryLogger uses a specified Logger to output treasury logging info.

func ValidateTransactionScripts

func ValidateTransactionScripts(tx *dcrutil.Tx, prevScripts PrevScripter,
	flags txscript.ScriptFlags, sigCache *txscript.SigCache,
	isAutoRevocationsEnabled bool) error

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

func VerifyTSpendSignature

func VerifyTSpendSignature(msgTx *wire.MsgTx, signature, pubKey []byte) error

VerifyTSpendSignature verifies that the provided signature and public key were the ones that signed the provided message transaction.

Note: This function should only be called with a valid TSpend.

Types

type AgendaFlags

type AgendaFlags uint32

AgendaFlags is a bitmask defining additional agendas to consider as active when checking transactions. This can be useful for callers who are able to accurately determine what agendas are active or otherwise desire any additional validation checks associated with a given agenda being active.

const (
	// AFTreasuryEnabled may be set to indicate that the treasury agenda should
	// be considered as active when checking a transaction so that any
	// additional checks which depend on the agenda being active are applied.
	AFTreasuryEnabled AgendaFlags = 1 << iota

	// AFExplicitVerUpgrades may be set to indicate that the explicit version
	// upgrades agenda should be considered as active when checking a
	// transaction so that any additional checks which depend on the agenda
	// being active are applied.
	AFExplicitVerUpgrades

	// AFAutoRevocationsEnabled may be set to indicate that the automatic ticket
	// revocations agenda should be considered as active when checking a
	// transaction so that any additional checks which depend on the agenda
	// being active are applied.
	AFAutoRevocationsEnabled

	// AFSubsidySplitEnabled may be set to indicate that the modified subsidy
	// split agenda defined in DCP00010 should be considered as active when
	// checking a transaction so that any additional checks which depend on the
	// agenda being active are applied.
	AFSubsidySplitEnabled

	// AFSubsidySplitR2Enabled may be set to indicate that the modified subsidy
	// split agenda defined in DCP00012 should be considered as active when
	// checking a transaction so that any additional checks which depend on the
	// agenda being active are applied.
	AFSubsidySplitR2Enabled

	// AFNone is a convenience value to specifically indicate no flags.
	AFNone AgendaFlags = 0
)

func (AgendaFlags) IsAutoRevocationsEnabled

func (flags AgendaFlags) IsAutoRevocationsEnabled() bool

IsAutoRevocationsEnabled returns whether the flags indicate that the automatic ticket revocations agenda is enabled.

func (AgendaFlags) IsExplicitVerUpgradesEnabled

func (flags AgendaFlags) IsExplicitVerUpgradesEnabled() bool

IsExplicitVerUpgradesEnabled returns whether the flags indicate that the explicit version upgrades agenda is enabled.

func (AgendaFlags) IsSubsidySplitEnabled

func (flags AgendaFlags) IsSubsidySplitEnabled() bool

IsSubsidySplitEnabled returns whether the flags indicate that the modified subsidy split agenda defined in DCP0010 is enabled.

func (AgendaFlags) IsSubsidySplitR2Enabled

func (flags AgendaFlags) IsSubsidySplitR2Enabled() bool

IsSubsidySplitR2Enabled returns whether the flags indicate that the modified subsidy split agenda defined in DCP0012 is enabled.

func (AgendaFlags) IsTreasuryEnabled

func (flags AgendaFlags) IsTreasuryEnabled() bool

IsTreasuryEnabled returns whether the flags indicate that the treasury agenda is enabled.

type AssertError

type AssertError string

AssertError identifies an error that indicates an internal code consistency issue and should be treated as a critical and unrecoverable error.

func (AssertError) Error

func (e AssertError) Error() string

Error returns the assertion error as a human-readable string and satisfies the error interface.

func (AssertError) Is

func (e AssertError) Is(target error) bool

Is implements the interface to work with the standard library's errors.Is.

It returns true in the following cases: - The target is AssertError

type BehaviorFlags

type BehaviorFlags uint32

BehaviorFlags is a bitmask defining tweaks to the normal behavior when performing chain 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 chain due to
	// already proving it correctly links into the chain up to an assumed valid
	// block.  This is primarily used for headers-first mode.
	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

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

type BestState

type BestState struct {
	Hash                chainhash.Hash   // The hash of the block.
	PrevHash            chainhash.Hash   // The previous block hash.
	Height              int64            // The height of the block.
	Bits                uint32           // The difficulty bits of the block.
	NextPoolSize        uint32           // The ticket pool size.
	NextStakeDiff       int64            // The next stake difficulty.
	BlockSize           uint64           // The size of the block.
	NumTxns             uint64           // The number of txns in the block.
	TotalTxns           uint64           // The total number of txns in the chain.
	MedianTime          time.Time        // Median time as per CalcPastMedianTime.
	TotalSubsidy        int64            // The total subsidy for the chain.
	NextExpiringTickets []chainhash.Hash // The tickets set to expire next block.
	NextWinningTickets  []chainhash.Hash // The eligible tickets to vote on the next block.
	MissedTickets       []chainhash.Hash // The missed tickets set to be revoked.
	NextFinalState      [6]byte          // The calculated state of the lottery for the next block.
}

BestState houses information about the current best block and other info related to the state of the main chain as it exists from the point of view of the current best block.

The BestSnapshot method can be used to obtain access to this information in a concurrent safe manner and the data will not be changed out from under the caller when chain state changes occur as the function name implies. However, the returned snapshot must be treated as immutable since it is shared by all callers.

type BlockAcceptedNtfnsData

type BlockAcceptedNtfnsData struct {
	// BestHeight is the height of the current best chain.  Since the accepted
	// block might be on a side chain, this is not necessarily the same as the
	// height of the accepted block.
	BestHeight int64

	// ForkLen is the length of the side chain the block extended or zero in the
	// case the block extended the main chain.
	//
	// This can be used in conjunction with the height of the accepted block to
	// determine the height at which the side chain the block created or
	// extended forked from the best chain.
	ForkLen int64

	// Block is the block that was accepted into the chain.
	Block *dcrutil.Block
}

BlockAcceptedNtfnsData is the structure for data indicating information about an accepted block. Note that this does not necessarily mean the block that was accepted extended the best chain as it might have created or extended a side chain.

type BlockChain

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

BlockChain provides functions for working with the Decred block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, checkpoint handling, and best chain selection with reorganization.

func New

func New(ctx context.Context, config *Config) (*BlockChain, error)

New returns a BlockChain instance using the provided configuration details.

func (*BlockChain) BestHeader

func (b *BlockChain) BestHeader() (chainhash.Hash, int64)

BestHeader returns the header with the most cumulative work that is NOT known to be invalid.

This function is safe for concurrent access.

func (*BlockChain) BestInvalidHeader

func (b *BlockChain) BestInvalidHeader() chainhash.Hash

BestInvalidHeader returns the header with the most cumulative work that is known to be invalid. It will be a hash of all zeroes if there is no such header.

This function is safe for concurrent access.

func (*BlockChain) BestSnapshot

func (b *BlockChain) BestSnapshot() *BestState

BestSnapshot returns information about the current best chain block and related state as of the current point in time. The returned instance must be treated as immutable since it is shared by all callers.

This function is safe for concurrent access.

func (*BlockChain) BlockByHash

func (b *BlockChain) BlockByHash(hash *chainhash.Hash) (*dcrutil.Block, error)

BlockByHash searches the internal chain block stores and the database in an attempt to find the requested block and returns it. This function returns blocks regardless of whether or not they are part of the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockByHeight

func (b *BlockChain) BlockByHeight(height int64) (*dcrutil.Block, error)

BlockByHeight returns the block at the given height in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockHashByHeight

func (b *BlockChain) BlockHashByHeight(height int64) (*chainhash.Hash, error)

BlockHashByHeight returns the hash of the block at the given height in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockHeightByHash

func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int64, error)

BlockHeightByHash returns the height of the block with the given hash in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockLocatorFromHash

func (b *BlockChain) BlockLocatorFromHash(hash *chainhash.Hash) BlockLocator

BlockLocatorFromHash returns a block locator for the passed block hash. See BlockLocator for details on the algorithm used to create a block locator.

In addition to the general algorithm referenced above, this function will return the block locator for the latest known tip of the main (best) chain if the passed hash is not currently known.

This function is safe for concurrent access.

func (*BlockChain) CalcNextRequiredDifficulty

func (b *BlockChain) CalcNextRequiredDifficulty(hash *chainhash.Hash, timestamp time.Time) (uint32, error)

CalcNextRequiredDifficulty calculates the required difficulty for the block AFTER the given block based on the active difficulty retarget rules.

This function is safe for concurrent access.

func (*BlockChain) CalcNextRequiredStakeDifficulty

func (b *BlockChain) CalcNextRequiredStakeDifficulty(hash *chainhash.Hash) (int64, error)

CalcNextRequiredStakeDifficulty calculates the required stake difficulty for the block after the given block based on the active stake difficulty retarget rules.

This function is safe for concurrent access.

func (*BlockChain) CalcSequenceLock

func (b *BlockChain) CalcSequenceLock(tx *dcrutil.Tx, view *UtxoViewpoint) (*SequenceLock, error)

CalcSequenceLock computes the minimum block height and time after which the passed transaction can be included into a block while satisfying the relative lock times of all of its input sequence numbers. The passed view is used to obtain the past median time and block heights of the blocks in which the referenced outputs of the inputs to the transaction were included. The generated sequence lock can be used in conjunction with a block height and median time to determine if all inputs to the transaction have reached the required maturity allowing it to be included in a block.

NOTE: This will calculate the sequence locks regardless of the state of the agenda which conditionally activates it. This is acceptable for standard transactions, however, callers which are intending to perform any type of consensus checking must check the status of the agenda first.

This function is safe for concurrent access.

func (*BlockChain) CalcStakeVersionByHash

func (b *BlockChain) CalcStakeVersionByHash(hash *chainhash.Hash) (uint32, error)

CalcStakeVersionByHash calculates the expected stake version for the block AFTER the provided block hash.

This function is safe for concurrent access.

func (*BlockChain) CalcWantHeight

func (b *BlockChain) CalcWantHeight(interval, height int64) int64

CalcWantHeight calculates the height of the final block of the previous interval given a block height.

func (*BlockChain) ChainTips

func (b *BlockChain) ChainTips() []ChainTipInfo

ChainTips returns information, in JSON-RPC format, about all of the currently known chain tips in the block index.

This function is safe for concurrent access.

func (*BlockChain) ChainWork

func (b *BlockChain) ChainWork(hash *chainhash.Hash) (uint256.Uint256, error)

ChainWork returns the total work up to and including the block of the provided block hash.

func (*BlockChain) CheckConnectBlockTemplate

func (b *BlockChain) CheckConnectBlockTemplate(block *dcrutil.Block) error

CheckConnectBlockTemplate fully validates that connecting the passed block to either the tip of the main chain or its parent does not violate any consensus rules, aside from the proof of work requirement. The block must connect to the current tip of the main chain or its parent.

This function is safe for concurrent access.

func (*BlockChain) CheckLiveTicket

func (b *BlockChain) CheckLiveTicket(hash chainhash.Hash) bool

CheckLiveTicket returns whether or not a ticket exists in the live ticket treap of the best node.

This function is safe for concurrent access.

func (*BlockChain) CheckLiveTickets

func (b *BlockChain) CheckLiveTickets(hashes []chainhash.Hash) []bool

CheckLiveTickets returns a slice of bools representing whether each ticket exists in the live ticket treap of the best node.

This function is safe for concurrent access.

func (*BlockChain) CheckTSpendExists

func (b *BlockChain) CheckTSpendExists(prevHash, tspend chainhash.Hash) error

CheckTSpendExists verifies that the provided TSpend has not been mined in a block on the chain of the provided block hash.

func (*BlockChain) CheckTSpendHasVotes

func (b *BlockChain) CheckTSpendHasVotes(prevHash chainhash.Hash, tspend *dcrutil.Tx) error

CheckTSpendHasVotes checks whether the given tspend has enough votes to be included in a block _after_ the specified prevHash block.

Such child block MUST be on a TVI, otherwise the result of this function may not correspond to the behavior of the consensus rules.

This function is safe for concurrent access.

func (*BlockChain) CheckTicketExhaustion

func (b *BlockChain) CheckTicketExhaustion(hash *chainhash.Hash, ticketPurchases uint8) error

CheckTicketExhaustion ensures that extending the block associated with the provided hash with a block that contains the specified number of ticket purchases will not result in a chain that is unrecoverable due to inevitable ticket exhaustion. This scenario happens when the number of live tickets drops below the number of tickets that is needed to reach the next block at which any outstanding immature ticket purchases that would provide the necessary live tickets mature.

This function is safe for concurrent access.

func (*BlockChain) CountVoteVersion

func (b *BlockChain) CountVoteVersion(version uint32) (uint32, error)

CountVoteVersion returns the total number of version votes for the current rule change activation interval.

This function is safe for concurrent access.

func (*BlockChain) EnableBulkImportMode

func (b *BlockChain) EnableBulkImportMode(bulkImportMode bool)

EnableBulkImportMode provides a mechanism to indicate that several validation checks can be avoided when bulk importing blocks already known to be valid. This must NOT be enabled in any other circumstance where blocks need to be fully validated.

This function is safe for concurrent access.

func (*BlockChain) EstimateNextStakeDifficulty

func (b *BlockChain) EstimateNextStakeDifficulty(hash *chainhash.Hash, newTickets int64, useMaxTickets bool) (int64, error)

EstimateNextStakeDifficulty estimates the next stake difficulty by pretending the provided number of tickets will be purchased in the remainder of the interval unless the flag to use max tickets is set in which case it will use the max possible number of tickets that can be purchased in the remainder of the interval.

This function is safe for concurrent access.

func (*BlockChain) FetchTSpend

func (b *BlockChain) FetchTSpend(tspend chainhash.Hash) ([]chainhash.Hash, error)

FetchTSpend returns the blocks a treasury spend tx was included in.

func (*BlockChain) FetchUtxoEntry

func (b *BlockChain) FetchUtxoEntry(outpoint wire.OutPoint) (*UtxoEntry, error)

FetchUtxoEntry loads and returns the requested unspent transaction output from the point of view of the main chain tip.

NOTE: Requesting an output for which there is no data will NOT return an error. Instead both the entry and the error will be nil. This is done to allow pruning of spent transaction outputs. In practice this means the caller must check if the returned entry is nil before invoking methods on it.

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

func (*BlockChain) FetchUtxoStats

func (b *BlockChain) FetchUtxoStats() (*UtxoStats, error)

FetchUtxoStats returns statistics on the current utxo set.

func (*BlockChain) FetchUtxoView

func (b *BlockChain) FetchUtxoView(tx *dcrutil.Tx, includeRegularTxns bool) (*UtxoViewpoint, error)

FetchUtxoView loads unspent transaction outputs for the inputs referenced by the passed transaction from the point of view of the main chain tip while taking into account whether or not the transactions in the regular tree of the current tip block should be included or not depending on the provided flag. It also attempts to fetch the utxos for the outputs of the transaction itself so the returned view can be examined for duplicate transactions.

This function is safe for concurrent access however the returned view is NOT.

func (*BlockChain) FetchUtxoViewParentTemplate

func (b *BlockChain) FetchUtxoViewParentTemplate(block *wire.MsgBlock) (*UtxoViewpoint, error)

FetchUtxoViewParentTemplate loads utxo details from the point of view of just having connected the given block, which must be a block template that connects to the parent of the tip of the main chain. In other words, the given block must be a sibling of the current tip of the main chain.

This should typically only be used by mining code when it is unable to generate a template that extends the current tip due to being unable to acquire the minimum required number of votes to extend it.

This function is safe for concurrent access however the returned view is NOT.

func (*BlockChain) FilterByBlockHash

func (b *BlockChain) FilterByBlockHash(hash *chainhash.Hash) (*gcs.FilterV2, *HeaderProof, error)

FilterByBlockHash returns the version 2 GCS filter for the given block hash along with a header commitment inclusion proof when they exist. This function returns the filters regardless of whether or not their associated block is part of the main chain.

An error that wraps ErrNoFilter will be returned when the filter for the given block hash does not exist.

This function is safe for concurrent access.

func (*BlockChain) ForceHeadReorganization

func (b *BlockChain) ForceHeadReorganization(formerBest chainhash.Hash, newBest chainhash.Hash) error

ForceHeadReorganization forces a reorganization of the block chain to the block hash requested, so long as it matches up with the current organization of the best chain.

This function is safe for concurrent access.

func (*BlockChain) GetStakeVersions

func (b *BlockChain) GetStakeVersions(hash *chainhash.Hash, count int32) ([]StakeVersions, error)

GetStakeVersions returns a cooked array of StakeVersions. We do this in order to not bloat memory by returning raw blocks.

func (*BlockChain) GetVoteCounts

func (b *BlockChain) GetVoteCounts(version uint32, deploymentID string) (VoteCounts, error)

GetVoteCounts returns the vote counts for the specified version and deployment identifier for the current rule change activation interval.

This function is safe for concurrent access.

func (*BlockChain) GetVoteInfo

func (b *BlockChain) GetVoteInfo(hash *chainhash.Hash, version uint32) (*VoteInfo, error)

GetVoteInfo returns information on consensus deployment agendas and their respective states at the provided hash, for the provided deployment version.

func (*BlockChain) HaveBlock

func (b *BlockChain) HaveBlock(hash *chainhash.Hash) bool

HaveBlock returns whether or not the chain instance has the block represented by the passed hash. This includes checking the various places a block can be like part of the main chain or on a side chain.

This function is safe for concurrent access.

func (*BlockChain) HaveHeader

func (b *BlockChain) HaveHeader(hash *chainhash.Hash) bool

HaveHeader returns whether or not the chain instance has the block header represented by the passed hash. Note that this will return true for both the main chain and any side chains.

This function is safe for concurrent access.

func (*BlockChain) HeaderByHash

func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error)

HeaderByHash returns the block header identified by the given hash or an error if it doesn't exist. Note that this will return headers from both the main chain and any side chains.

This function is safe for concurrent access.

func (*BlockChain) HeaderByHeight

func (b *BlockChain) HeaderByHeight(height int64) (wire.BlockHeader, error)

HeaderByHeight returns the block header at the given height in the main chain.

This function is safe for concurrent access.

func (*BlockChain) HeightRange

func (b *BlockChain) HeightRange(startHeight, endHeight int64) ([]chainhash.Hash, error)

HeightRange returns a range of block hashes for the given start and end heights. It is inclusive of the start height and exclusive of the end height. In other words, it is the half open range [startHeight, endHeight).

The end height will be limited to the current main chain height.

This function is safe for concurrent access.

func (*BlockChain) InvalidateBlock

func (b *BlockChain) InvalidateBlock(hash *chainhash.Hash) error

InvalidateBlock manually invalidates the provided block as if the block had violated a consensus rule and marks all of its descendants as having a known invalid ancestor. It then reorganizes the chain as necessary so the branch with the most cumulative proof of work that is still valid becomes the main chain.

func (*BlockChain) IsAutoRevocationsAgendaActive

func (b *BlockChain) IsAutoRevocationsAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsAutoRevocationsAgendaActive returns whether or not the automatic ticket revocations agenda vote, as defined in DCP0009, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsBlake3PowAgendaActive

func (b *BlockChain) IsBlake3PowAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsBlake3PowAgendaActive returns whether or not the agenda to change the proof of work hash function to blake3, as defined in DCP0011, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsCurrent

func (b *BlockChain) IsCurrent() bool

IsCurrent returns whether or not the chain believes it is current based on the current latched state and an additional check which returns false in the case no new blocks have been seen for an extended period of time.

The initial factors that are used to latch the state to current are:

  • Total amount of cumulative work is more than the minimum known work specified by the parameters for the network
  • The best chain is synced to the header with the most cumulative work that is not known to be invalid
  • Latest block has a timestamp newer than 24 hours ago

This function is safe for concurrent access.

func (*BlockChain) IsExplicitVerUpgradesAgendaActive

func (b *BlockChain) IsExplicitVerUpgradesAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsExplicitVerUpgradesAgendaActive returns whether or not the explicit version upgrades agenda, as defined in DCP0008, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsHeaderCommitmentsAgendaActive

func (b *BlockChain) IsHeaderCommitmentsAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsHeaderCommitmentsAgendaActive returns whether or not the header commitments agenda vote, as defined in DCP0005 has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsKnownInvalidBlock

func (b *BlockChain) IsKnownInvalidBlock(hash *chainhash.Hash) bool

IsKnownInvalidBlock returns whether either the provided block is itself known to be invalid or to have an invalid ancestor. A return value of false in no way implies the block is valid or only has valid ancestors. Thus, this will return false for invalid blocks that have not been proven invalid yet as well as return false for blocks with invalid ancestors that have not been proven invalid yet.

It will also return false when the provided block is unknown.

This function is safe for concurrent access.

func (*BlockChain) IsLNFeaturesAgendaActive

func (b *BlockChain) IsLNFeaturesAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsLNFeaturesAgendaActive returns whether or not the LN features agenda vote, as defined in DCP0002 and DCP0003 has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsRevertTreasuryPolicyActive

func (b *BlockChain) IsRevertTreasuryPolicyActive(prevHash *chainhash.Hash) (bool, error)

IsRevertTreasuryPolicyActive returns whether or not the revert treasury expenditure policy agenda vote, as defined in DCP0007, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsSubsidySplitAgendaActive

func (b *BlockChain) IsSubsidySplitAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsSubsidySplitAgendaActive returns whether or not the agenda to change the block reward subsidy split to 10/80/10, as defined in DCP0010, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsSubsidySplitR2AgendaActive

func (b *BlockChain) IsSubsidySplitR2AgendaActive(prevHash *chainhash.Hash) (bool, error)

IsSubsidySplitR2AgendaActive returns whether or not the agenda to change the block reward subsidy split to 1/89/10, as defined in DCP0012, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) IsTreasuryAgendaActive

func (b *BlockChain) IsTreasuryAgendaActive(prevHash *chainhash.Hash) (bool, error)

IsTreasuryAgendaActive returns whether or not the treasury agenda vote, as defined in DCP0006, has passed and is now active for the block AFTER the given block.

This function is safe for concurrent access.

func (*BlockChain) LiveTickets

func (b *BlockChain) LiveTickets() ([]chainhash.Hash, error)

LiveTickets returns all currently live tickets from the stake database.

This function is safe for concurrent access.

func (*BlockChain) LocateBlocks

func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash

LocateBlocks returns the hashes of the blocks after the first known block in the locator until the provided stop hash is reached, or up to the provided max number of block hashes.

In addition, there are two special cases:

  • When no locators are provided, the stop hash is treated as a request for that block, so it will either return the stop hash itself if it is known, or nil if it is unknown
  • When locators are provided, but none of them are known, hashes starting after the genesis block will be returned

This function is safe for concurrent access.

func (*BlockChain) LocateHeaders

func (b *BlockChain) LocateHeaders(locator BlockLocator, hashStop *chainhash.Hash) []wire.BlockHeader

LocateHeaders returns the headers of the blocks after the first known block in the locator until the provided stop hash is reached, or up to a max of wire.MaxBlockHeadersPerMsg headers.

In addition, there are two special cases:

  • When no locators are provided, the stop hash is treated as a request for that header, so it will either return the header for the stop hash itself if it is known, or nil if it is unknown
  • When locators are provided, but none of them are known, headers starting after the genesis block will be returned

This function is safe for concurrent access.

func (*BlockChain) LotteryDataForBlock

func (b *BlockChain) LotteryDataForBlock(hash *chainhash.Hash) ([]chainhash.Hash, int, [6]byte, error)

LotteryDataForBlock returns lottery data for a given block in the block chain, including side chain blocks.

It is safe for concurrent access.

func (*BlockChain) MainChainHasBlock

func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool

MainChainHasBlock returns whether or not the block with the given hash is in the main chain.

This function is safe for concurrent access.

func (*BlockChain) MaxBlockSize

func (b *BlockChain) MaxBlockSize(hash *chainhash.Hash) (int64, error)

MaxBlockSize returns the maximum permitted block size for the block AFTER the provided block hash.

This function is safe for concurrent access.

func (*BlockChain) MaxTreasuryExpenditure

func (b *BlockChain) MaxTreasuryExpenditure(preTVIBlock *chainhash.Hash) (int64, error)

MaxTreasuryExpenditure is the maximum amount of funds that can be spent from the treasury by a set of TSpends for a block that extends the given block hash. Function will return 0 if it is called on an invalid TVI.

func (*BlockChain) MaybeUpdateIsCurrent

func (b *BlockChain) MaybeUpdateIsCurrent()

MaybeUpdateIsCurrent potentially updates whether or not the chain believes it is current.

It makes use of a latching approach such that once the chain becomes current it will only switch back to false in the case no new blocks have been seen for an extended period of time.

This function is safe for concurrent access.

func (*BlockChain) MedianTimeByHash

func (b *BlockChain) MedianTimeByHash(hash *chainhash.Hash) (time.Time, error)

MedianTimeByHash returns the median time of a block by the given hash or an error if it doesn't exist. Note that this will return times from both the main chain and any side chains.

This function is safe for concurrent access.

func (*BlockChain) NextThresholdState

func (b *BlockChain) NextThresholdState(hash *chainhash.Hash, deploymentID string) (ThresholdStateTuple, error)

NextThresholdState returns the current rule change threshold state of the given deployment ID for the block AFTER the provided block hash.

This function is safe for concurrent access.

func (*BlockChain) ProcessBlock

func (b *BlockChain) ProcessBlock(block *dcrutil.Block) (int64, error)

ProcessBlock is the main workhorse for handling insertion of new blocks into the block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, and insertion into the block chain along with best chain selection and reorganization.

This function permits blocks to be processed out of order so long as their header has already been successfully processed via ProcessBlockHeader which itself requires the headers to properly connect. In other words, orphan blocks are rejected and thus is up to the caller to either ensure that the blocks are processed in order or that the headers for the blocks have already been successfully processed.

Upon return, the best chain tip will be whatever branch tip has the most proof of work and also passed all validation checks. Due to this, it is also worth noting that the best chain tip might be updated even in the case of processing a block that ultimately fails validation.

Additionally, due to the ability to process blocks out of order, and the fact blocks can only be fully validated once all of their ancestors have the block data available, it is to be expected that no error is returned immediately for blocks that are valid enough to make it to the point they require the remaining ancestor block data to be fully validated even though they might ultimately end up failing validation. Similarly, because the data for a block becoming available makes any of its direct descendants that already have their data available eligible for validation, an error being returned does not necessarily mean the block being processed is the one that failed validation.

When no errors occurred during processing, the first return value indicates the length of the fork the block extended. In the case it either extended the best chain or is now the tip of the best chain due to causing a reorganize, the fork length will be 0.

This function is safe for concurrent access.

Example

This example demonstrates how to create a new chain instance and use ProcessBlock to attempt to add a block to the chain. As the package overview documentation describes, this includes all of the Decred consensus rules. This example intentionally attempts to insert a duplicate genesis block to illustrate how an invalid block is handled.

// Create a new database to store the accepted blocks into.  Typically
// this would be opening an existing database and would not be deleting
// and creating a new database like this, but it is done here so this is
// a complete working example and does not leave temporary files laying
// around.
mainNetParams := chaincfg.MainNetParams()
dbPath := filepath.Join(os.TempDir(), "exampleprocessblock")
_ = os.RemoveAll(dbPath)
db, err := database.Create("ffldb", dbPath, mainNetParams.Net)
if err != nil {
	fmt.Printf("Failed to create database: %v\n", err)
	return
}
defer os.RemoveAll(dbPath)
defer db.Close()

// Additionally, create a new database to store the UTXO set.
utxoDbPath := filepath.Join(os.TempDir(), "exampleprocessblockutxodb")
_ = os.RemoveAll(utxoDbPath)
opts := opt.Options{
	Strict:      opt.DefaultStrict,
	Compression: opt.NoCompression,
	Filter:      filter.NewBloomFilter(10),
}
utxoDb, err := leveldb.OpenFile(utxoDbPath, &opts)
if err != nil {
	fmt.Printf("Failed to create UTXO database: %v\n", err)
	return
}
defer os.RemoveAll(utxoDbPath)
defer utxoDb.Close()

// Create a new BlockChain instance using the underlying database for
// the main bitcoin network.  This example does not demonstrate some
// of the other available configuration options such as specifying a
// notification callback and signature cache.  Also, the caller would
// ordinarily keep a reference to the median time source and add time
// values obtained from other peers on the network so the local time is
// adjusted to be in agreement with other peers.
chain, err := blockchain.New(context.Background(),
	&blockchain.Config{
		DB:          db,
		ChainParams: mainNetParams,
		TimeSource:  blockchain.NewMedianTime(),
		UtxoCache: blockchain.NewUtxoCache(&blockchain.UtxoCacheConfig{
			Backend: blockchain.NewLevelDbUtxoBackend(utxoDb),
			FlushBlockDB: func() error {
				return nil
			},
			MaxSize: 100 * 1024 * 1024, // 100 MiB
		}),
	})
if err != nil {
	fmt.Printf("Failed to create chain instance: %v\n", err)
	return
}

// Process a block.  For this example, intentionally cause an error by
// trying to process the genesis block which already exists.
genesisBlock := dcrutil.NewBlock(mainNetParams.GenesisBlock)
forkLen, err := chain.ProcessBlock(genesisBlock)
if err != nil {
	fmt.Printf("Failed to create chain instance: %v\n", err)
	return
}
isMainChain := forkLen == 0
fmt.Printf("Block accepted. Is it on the main chain?: %v", isMainChain)

// This output is dependent on the genesis block, and needs to be
// updated if the mainnet genesis block is updated.
Output:

func (*BlockChain) ProcessBlockHeader

func (b *BlockChain) ProcessBlockHeader(header *wire.BlockHeader) error

ProcessBlockHeader is the main workhorse for handling insertion of new block headers into the block chain using headers-first semantics. It includes functionality such as rejecting headers that do not connect to an existing known header, ensuring headers follow all rules that do not depend on having all ancestor block data available, and insertion into the block index.

Block headers that have already been inserted are ignored, unless they have subsequently been marked invalid, in which case an appropriate error is returned.

It should be noted that this function intentionally does not accept block headers that do not connect to an existing known header or to headers which are already known to be a part of an invalid branch. This means headers must be processed in order.

This function is safe for concurrent access.

func (*BlockChain) PutNextNeededBlocks

func (b *BlockChain) PutNextNeededBlocks(out []chainhash.Hash) []chainhash.Hash

PutNextNeededBlocks populates the provided slice with hashes for the next blocks after the current best chain tip that are needed to make progress towards the current best known header skipping any blocks that already have their data available.

The provided slice will be populated with either as many hashes as it will fit per its length or as many hashes it takes to reach best header, whichever is smaller.

It returns a sub slice of the provided one with its bounds adjusted to the number of entries populated.

This function is safe for concurrent access.

func (*BlockChain) ReconsiderBlock

func (b *BlockChain) ReconsiderBlock(hash *chainhash.Hash) error

ReconsiderBlock removes the known invalid status of the provided block and all of its ancestors along with the known invalid ancestor status from all of its descendants that are neither themselves marked as having failed validation nor descendants of another such block. Therefore, it allows the affected blocks to be reconsidered under the current consensus rules. It then potentially reorganizes the chain as necessary so the block with the most cumulative proof of work that is valid becomes the tip of the main chain.

func (*BlockChain) ShutdownUtxoCache

func (b *BlockChain) ShutdownUtxoCache()

ShutdownUtxoCache flushes the utxo cache to the backend on shutdown. Since the cache is flushed periodically during initial block download and flushed after every block is connected after initial block download is complete, this flush that occurs during shutdown should finish relatively quickly.

Note that if an unclean shutdown occurs, the cache will still be initialized properly when restarted as during initialization it will replay blocks to catch up to the tip block if it was not fully flushed before shutting down. However, it is still preferred to flush when shutting down versus always recovering on startup since it is faster.

This function should only be called during shutdown.

func (*BlockChain) StateLastChangedHeight

func (b *BlockChain) StateLastChangedHeight(hash *chainhash.Hash, deploymentID string) (int64, error)

StateLastChangedHeight returns the height at which the provided consensus deployment agenda last changed state. Note that, unlike the NextThresholdState function, this function returns the information as of the passed block hash.

This function is safe for concurrent access.

func (*BlockChain) TSpendCountVotes

func (b *BlockChain) TSpendCountVotes(blockHash *chainhash.Hash, tspend *dcrutil.Tx) (yesVotes, noVotes int64, err error)

TSpendCountVotes tallies the votes given for the specified tspend during its voting interval, up to the specified block. It returns the number of yes and no votes found between the passed block's height and the start of voting.

Note that this function errors if the block _after_ the specified block is outside the tpsend voting window. In particular, calling this function for the TVI block that ends the voting interval for a given tspend fails, since the next block is outside the voting interval.

This function is safe for concurrent access.

func (*BlockChain) TicketPoolValue

func (b *BlockChain) TicketPoolValue() (dcrutil.Amount, error)

TicketPoolValue returns the current value of all the locked funds in the ticket pool.

This function is safe for concurrent access. All live tickets are at least 256 blocks deep on mainnet, so the UTXO set should generally always have the asked for transactions.

func (*BlockChain) TicketsWithAddress

func (b *BlockChain) TicketsWithAddress(address stdaddr.StakeAddress) ([]chainhash.Hash, error)

TicketsWithAddress returns a slice of ticket hashes that are currently live corresponding to the given address.

This function is safe for concurrent access.

func (*BlockChain) TipGeneration

func (b *BlockChain) TipGeneration() []chainhash.Hash

TipGeneration returns the entire generation of blocks stemming from the parent of the current tip.

The function is safe for concurrent access.

func (*BlockChain) TreasuryBalance

func (b *BlockChain) TreasuryBalance(hash *chainhash.Hash) (*TreasuryBalanceInfo, error)

TreasuryBalance returns treasury balance information as of the given block.

func (*BlockChain) VerifyProgress

func (b *BlockChain) VerifyProgress() float64

VerifyProgress returns a percentage that is a guess of the progress of the chain verification process.

This function is safe for concurrent access.

type BlockConnectedNtfnsData

type BlockConnectedNtfnsData struct {
	// Block is the block that was connected to the main chain.
	Block *dcrutil.Block

	// ParentBlock is the parent block of the one that was connected to the main
	// chain.
	ParentBlock *dcrutil.Block

	// CheckTxFlags represents the agendas to consider as active when checking
	// transactions for the block that was connected.
	CheckTxFlags AgendaFlags
}

BlockConnectedNtfnsData is the structure for data indicating information about a connected block.

type BlockDisconnectedNtfnsData

type BlockDisconnectedNtfnsData struct {
	// Block is the block that was disconnected from the main chain.
	Block *dcrutil.Block

	// ParentBlock is the parent block of the one that was disconnected from the
	// main chain meaning this block is now the tip of the main chain.
	ParentBlock *dcrutil.Block

	// CheckTxFlags represents the agendas to consider as active when checking
	// transactions for the block that was **disconnected**.
	CheckTxFlags AgendaFlags
}

BlockDisconnectedNtfnsData is the structure for data indicating information about a disconnected block.

type BlockLocator

type BlockLocator []*chainhash.Hash

BlockLocator is used to help locate a specific block. The algorithm for building the block locator is to add the hashes in reverse order until the genesis block is reached. In order to keep the list of locator hashes to a reasonable number of entries, first the most recent previous 12 block hashes are added, then the step 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 block chain with a side chain as depicted below:

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

The block locator for block 17a would be the hashes of blocks: [17a 16a 15 14 13 12 11 10 9 8 7 6 4 genesis]

type ChainQueryerAdapter

type ChainQueryerAdapter struct {
	*BlockChain
}

ChainQueryerAdapter provides an adapter from a BlockChain instance to the indexers.ChainQueryer interface.

func (*ChainQueryerAdapter) Best

func (q *ChainQueryerAdapter) Best() (int64, *chainhash.Hash)

Best returns the height and hash of the current best chain tip.

This is part of the indexers.ChainQueryer interface.

func (*ChainQueryerAdapter) BestHeight

func (q *ChainQueryerAdapter) BestHeight() int64

BestHeight returns the height of the current best block. It is equivalent to the Height field of the BestSnapshot method, however, it is needed to satisfy the indexers.ChainQueryer interface.

It is defined via a separate internal struct to avoid polluting the public API of the BlockChain type itself.

func (*ChainQueryerAdapter) BlockHeaderByHash

func (q *ChainQueryerAdapter) BlockHeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error)

BlockHeaderByHash returns the block header identified by the given hash.

func (*ChainQueryerAdapter) ChainParams

func (q *ChainQueryerAdapter) ChainParams() *chaincfg.Params

ChainParams returns the network parameters of the chain.

This is part of the indexers.ChainQueryer interface.

func (*ChainQueryerAdapter) IsTreasuryEnabled

func (q *ChainQueryerAdapter) IsTreasuryEnabled(hash *chainhash.Hash) (bool, error)

IsTreasuryEnabled returns true if the treasury agenda is enabled as of the provided block.

type ChainTipInfo

type ChainTipInfo struct {
	// Height specifies the block height of the chain tip.
	Height int64

	// Hash specifies the block hash of the chain tip.
	Hash chainhash.Hash

	// BranchLen specifies the length of the branch that connects the chain tip
	// to the main chain.  It will be zero for the main chain tip.
	BranchLen int64

	// Status specifies the validation status of chain formed by the chain tip.
	//
	// active:
	//   The current best chain tip.
	//
	// invalid:
	//   The block or one of its ancestors is invalid.
	//
	// headers-only:
	//   The block or one of its ancestors does not have the full block data
	//   available which also means the block can't be validated or connected.
	//
	// valid-fork:
	//   The block is fully validated which implies it was probably part of the
	//   main chain at one point and was reorganized.
	//
	// valid-headers:
	//   The full block data is available and the header is valid, but the block
	//   was never validated which implies it was probably never part of the
	//   main chain.
	Status string
}

ChainTipInfo models information about a chain tip.

type Config

type Config struct {
	// DB defines the database which houses the blocks and will be used to
	// store all metadata created by this package outside of the UTXO set, which
	// is stored in a separate database.
	//
	// This field is required.
	DB database.DB

	// UtxoBackend defines the backend which houses the UTXO set.
	//
	// This field is required.
	UtxoBackend UtxoBackend

	// ChainParams identifies which chain parameters the chain is associated
	// with.
	//
	// This field is required.
	ChainParams *chaincfg.Params

	// AllowOldForks enables processing of blocks that are forks deep in the
	// chain history.  This should realistically never need to be enabled in
	// practice, however, it is provided for testing purposes as well as a
	// recovery mechanism in the extremely unlikely case that a node were to
	// somehow get stuck on a bad fork and be unable to reorg to the good one
	// due to the old fork rejection semantics.
	AllowOldForks bool

	// AssumeValid is the hash of a block that has been externally verified to
	// be valid.  It allows several validation checks to be skipped for blocks
	// that are both an ancestor of the assumed valid block and an ancestor of
	// the best header.
	//
	// This field may not be set for networks that do not require it.
	AssumeValid chainhash.Hash

	// TimeSource defines the median time source to use for things such as
	// block processing and determining whether or not the chain is current.
	//
	// The caller is expected to keep a reference to the time source as well
	// and add time samples from other peers on the network so the local
	// time is adjusted to be in agreement with other peers.
	TimeSource MedianTimeSource

	// Notifications defines a callback to which notifications will be sent
	// when various events take place.  See the documentation for
	// Notification and NotificationType for details on the types and
	// contents of notifications.
	//
	// This field can be nil if the caller is not interested in receiving
	// notifications.
	Notifications NotificationCallback

	// SigCache defines a signature cache to use 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

	// SubsidyCache defines a subsidy cache to use when calculating and
	// validating block and vote subsidies.
	//
	// This field can be nil if the caller is not interested in using a
	// subsidy cache.
	SubsidyCache *standalone.SubsidyCache

	// IndexSubscriber defines a subscriber for relaying updates
	// concerning connected and disconnected blocks to subscribed index clients.
	IndexSubscriber *indexers.IndexSubscriber

	// UtxoCache defines a utxo cache that sits on top of the utxo set database.
	// All utxo reads and writes go through the cache, and never read or write to
	// the database directly.
	//
	// This field is required.
	UtxoCache UtxoCacher
}

Config is a descriptor which specifies the blockchain instance configuration.

type ContextError

type ContextError struct {
	Err         error
	Description string
	RawErr      error
}

ContextError wraps an error with additional context. It has full support for errors.Is and errors.As, so the caller can ascertain the specific wrapped error.

RawErr contains the original error in the case where an error has been converted.

func (ContextError) Error

func (e ContextError) Error() string

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

func (ContextError) Unwrap

func (e ContextError) Unwrap() error

Unwrap returns the underlying wrapped error.

type ErrorKind

type ErrorKind string

ErrorKind identifies a kind of error. It has full support for errors.Is and errors.As, so the caller can directly check against an error kind when determining the reason for an error.

func (ErrorKind) Error

func (e ErrorKind) Error() string

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

type HeaderProof

type HeaderProof struct {
	ProofIndex  uint32
	ProofHashes []chainhash.Hash
}

HeaderProof houses a merkle tree inclusion proof and associated proof index for a header commitment. This information allows clients to efficiently prove whether or not the commitment root of a block header commits to specific data at the given index.

type MedianTimeSource

type MedianTimeSource interface {
	// AdjustedTime returns the current time adjusted by the median time
	// offset as calculated from the time samples added by AddTimeSample.
	AdjustedTime() time.Time

	// AddTimeSample adds a time sample that is used when determining the
	// median time of the added samples.
	AddTimeSample(id string, timeVal time.Time)

	// Offset returns the number of seconds to adjust the local clock based
	// upon the median of the time samples added by AddTimeData.
	Offset() time.Duration
}

MedianTimeSource provides a mechanism to add several time samples which are used to determine a median time which is then used as an offset to the local clock.

func NewMedianTime

func NewMedianTime() MedianTimeSource

NewMedianTime returns a new instance of concurrency-safe implementation of the MedianTimeSource interface. The returned implementation contains the rules necessary for proper time handling in the chain consensus rules and expects the time samples to be added from the timestamp field of the version message received from remote peers that successfully connect and negotiate.

type MultiError

type MultiError []error

MultiError houses several errors as a single error that provides full support for errors.Is and errors.As so the caller can easily determine if any of the errors match any specific error or error type. Note that this differs from typical wrapped error chains which only represent a single error.

func (MultiError) As

func (e MultiError) As(target interface{}) bool

As implements the interface to work with the standard library's errors.As.

It iterates each of the errors in the multi error and calls errors.As on it until the first one that matches target is found, in which case it returns true. Otherwise, it returns false.

This means it keeps all of the same semantics typically provided by As in terms of unwrapping error chains and setting the target to the matched error.

func (MultiError) Error

func (e MultiError) Error() string

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

func (MultiError) Is

func (e MultiError) Is(target error) bool

Is implements the interface to work with the standard library's errors.Is.

It iterates each of the errors in the multi error and calls errors.Is on it until the first one that matches target is found, in which case it returns true. Otherwise, it returns false.

This means it keeps all of the same semantics typically provided by Is in terms of unwrapping error chains.

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:

  • NTNewTipBlockChecked: *dcrutil.Block
  • NTBlockAccepted: *BlockAcceptedNtfnsData
  • NTBlockConnected: *BlockConnectedNtfnsData
  • NTBlockDisconnected: *BlockDisconnectedNtfnsData
  • NTChainReorgStarted: nil
  • NTChainReorgDone: nil
  • NTReorganization: *ReorganizationNtfnsData
  • NTNewTickets: *TicketNotificationsData

type NotificationCallback

type NotificationCallback func(*Notification)

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

type NotificationType

type NotificationType int

NotificationType represents the type of a notification message.

const (
	// NTNewTipBlockChecked indicates the associated block intends to extend
	// the current main chain and has passed all of the sanity and
	// contextual checks such as having valid proof of work, valid merkle
	// and stake roots, and only containing allowed votes and revocations.
	//
	// It should be noted that the block might still ultimately fail to
	// become the new main chain tip if it contains invalid scripts, double
	// spends, etc.  However, this is quite rare in practice because a lot
	// of work was expended to create a block which satisfies the proof of
	// work requirement.
	//
	// Finally, this notification is only sent if the chain is believed
	// to be current and the chain lock is NOT released, so consumers must
	// take care to avoid calling blockchain functions to avoid potential
	// deadlock.
	//
	// Typically, a caller would want to use this notification to relay the
	// block to the rest of the network without needing to wait for the more
	// time consuming full connection to take place.
	NTNewTipBlockChecked NotificationType = iota

	// NTBlockAccepted indicates the associated block was accepted into
	// the block chain.  Note that this does not necessarily mean it was
	// added to the main chain.  For that, use NTBlockConnected.
	NTBlockAccepted

	// NTBlockConnected indicates the associated block was connected to the
	// main chain.
	NTBlockConnected

	// NTBlockDisconnected indicates the associated block was disconnected
	// from the main chain.
	NTBlockDisconnected

	// NTChainReorgStarted indicates that a chain reorganization has commenced.
	NTChainReorgStarted

	// NTChainReorgDone indicates that a chain reorganization has concluded.
	NTChainReorgDone

	// NTReorganization indicates that a blockchain reorganization has taken
	// place.
	NTReorganization

	// NTNewTickets indicates newly maturing tickets from a newly accepted
	// block.
	NTNewTickets
)

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 PrevScripter

type PrevScripter interface {
	PrevScript(*wire.OutPoint) (uint16, []byte, bool)
}

PrevScripter defines an interface that provides access to scripts and their associated version keyed by an outpoint. The boolean return indicates whether or not the script and version for the provided outpoint was found.

type ReorganizationNtfnsData

type ReorganizationNtfnsData struct {
	OldHash   chainhash.Hash
	OldHeight int64
	NewHash   chainhash.Hash
	NewHeight int64
}

ReorganizationNtfnsData is the structure for data indicating information about a reorganization.

type RuleError

type RuleError struct {
	Err         error
	Description string
}

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. It has full support for errors.Is and errors.As, so the caller can 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.

func (RuleError) Unwrap

func (e RuleError) Unwrap() error

Unwrap returns the underlying wrapped error.

type SequenceLock

type SequenceLock struct {
	MinHeight int64
	MinTime   int64
}

SequenceLock represents the minimum timestamp and minimum block height after which a transaction can be included into a block while satisfying the relative lock times of all of its input sequence numbers. It is calculated via the CalcSequenceLock function. Each field may be -1 if none of the input sequence numbers require a specific relative lock time for the respective type. Since all valid heights and times are larger than -1, this implies that it will not prevent a transaction from being included due to the sequence lock, which is the desired behavior.

type StakeVersions

type StakeVersions struct {
	Hash         chainhash.Hash
	Height       int64
	BlockVersion int32
	StakeVersion uint32
	Votes        []stake.VoteVersionTuple
}

StakeVersions is a condensed form of a dcrutil.Block that is used to prevent using gigabytes of memory.

type ThresholdState

type ThresholdState byte

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

const (
	// ThresholdInvalid is an invalid state and exists for use as the zero value
	// in error paths.
	ThresholdInvalid ThresholdState = iota

	// ThresholdDefined is the initial state for each deployment and is the
	// state for the genesis block has by definition for all deployments.
	ThresholdDefined

	// 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 ThresholdStateTuple

type ThresholdStateTuple struct {
	// State contains the current ThresholdState.
	State ThresholdState

	// Choice is the specific choice that received the majority vote for the
	// ThresholdLockedIn and ThresholdActive states.
	//
	// IMPORTANT: It will only be set to the majority no choice for the
	// ThresholdFailed state if the vote failed as the result of a majority no
	// vote.  Otherwise, it will be nil for the ThresholdFailed state if the
	// vote failed due to the voting period expiring before any majority is
	// reached.  This distinction allows callers to differentiate between a vote
	// failing due to a majority no vote versus due to expiring, but it does
	// mean the caller must check for nil before using it for the state.
	//
	// It is nil for all other states.
	Choice *chaincfg.Choice
}

ThresholdStateTuple contains the current state and the activated choice, when valid.

func (ThresholdStateTuple) String

func (t ThresholdStateTuple) String() string

String returns the ThresholdStateTuple as a human-readable tuple.

type TicketNotificationsData

type TicketNotificationsData struct {
	Hash            chainhash.Hash
	Height          int64
	StakeDifficulty int64
	TicketsNew      []chainhash.Hash
}

TicketNotificationsData is the structure for data indicating information about new tickets in a connected block.

type TreasuryBalanceInfo

type TreasuryBalanceInfo struct {
	// BlockHeight is the height of the requested block.
	BlockHeight int64

	// Balance is the balance of the treasury as of the requested block.
	Balance uint64

	// Updates specifies all additions to and spends from the treasury in
	// the requested block.
	Updates []int64
}

TreasuryBalanceInfo models information about the treasury balance as of a given block.

type UtxoBackend

type UtxoBackend interface {
	// FetchEntry returns the specified transaction output from the UTXO set.
	//
	// When there is no entry for the provided output, nil will be returned for
	// both the entry and the error.
	FetchEntry(outpoint wire.OutPoint) (*UtxoEntry, error)

	// FetchInfo returns versioning and creation information for the UTXO
	// backend.
	FetchInfo() (*UtxoBackendInfo, error)

	// FetchState returns the current state of the UTXO set.
	FetchState() (*UtxoSetState, error)

	// FetchStats returns statistics on the current UTXO set.
	FetchStats() (*UtxoStats, error)

	// Get returns the value for the given key.  It returns nil if the key does
	// not exist.  An empty slice is returned for keys that exist but have no
	// value assigned.
	//
	// The returned slice is safe to modify.  Additionally, it is safe to modify
	// the slice passed as an argument after Get returns.
	Get(key []byte) ([]byte, error)

	// InitInfo loads (or creates if necessary) the UTXO backend info.
	InitInfo(blockDBVersion uint32) error

	// NewIterator returns an iterator over the key/value pairs in the UTXO
	// backend.  The returned iterator is NOT safe for concurrent use, but it is
	// safe to use multiple iterators concurrently, with each in a dedicated
	// goroutine.
	//
	// The prefix parameter allows for slicing the iterator to only contain keys
	// with the given prefix.  A nil prefix is treated as a key BEFORE all keys.
	//
	// NOTE: The contents of any slice returned by the iterator should NOT be
	// modified unless noted otherwise.
	//
	// The iterator must be released after use, by calling the Release method.
	NewIterator(prefix []byte) UtxoBackendIterator

	// PutInfo sets the versioning and creation information for the UTXO
	// backend.
	PutInfo(info *UtxoBackendInfo) error

	// PutUtxos atomically updates the UTXO set with the entries from the
	// provided map along with the current state.
	PutUtxos(utxos map[wire.OutPoint]*UtxoEntry, state *UtxoSetState) error

	// Update invokes the passed function in the context of a UTXO Backend
	// transaction.  Any errors returned from the user-supplied function will
	// cause the transaction to be rolled back and are returned from this
	// function.  Otherwise, the transaction is committed when the user-supplied
	// function returns a nil error.
	Update(fn func(tx UtxoBackendTx) error) error

	// Upgrade upgrades the UTXO backend by applying all possible upgrades
	// iteratively as needed.
	Upgrade(ctx context.Context, b *BlockChain) error
}

UtxoBackend represents a persistent storage layer for the UTXO set.

The interface contract requires that all of these methods are safe for concurrent access.

func NewLevelDbUtxoBackend

func NewLevelDbUtxoBackend(db *leveldb.DB) UtxoBackend

NewLevelDbUtxoBackend returns a new instance of a backend that uses the provided leveldb database for its underlying storage.

type UtxoBackendInfo

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

UtxoBackendInfo is the structure that holds the versioning and date information for the UTXO backend.

type UtxoBackendIterator

type UtxoBackendIterator interface {
	// First moves the iterator to the first key/value pair.  If the iterator
	// only contains one key/value pair then First and Last would move to the
	// same key/value pair.  It returns whether the pair that is moved to
	// exists.
	First() bool

	// Last moves the iterator to the last key/value pair.  If the iterator only
	// contains one key/value pair then First and Last would move to the same
	// key/value pair.  It returns whether the pair that is moved to exists.
	Last() bool

	// Seek moves the iterator to the first key/value pair whose key is greater
	// than or equal to the given key.  It returns whether the pair that is
	// moved to exists.
	//
	// It is safe to modify the contents of the argument after Seek returns.
	Seek(key []byte) bool

	// Next moves the iterator to the next key/value pair.  It returns false if
	// the iterator is exhausted.
	Next() bool

	// Prev moves the iterator to the previous key/value pair.  It returns false
	// if the iterator is exhausted.
	Prev() bool

	// Error returns any accumulated error.  Exhausting all of the key/value
	// pairs is not considered to be an error.
	Error() error

	// Key returns the key of the current key/value pair, or nil if done.  The
	// caller should not modify the contents of the returned slice, and its
	// contents may change on the next call to any iteration method.
	Key() []byte

	// Value returns the value of the current key/value pair, or nil if done.
	// The caller should not modify the contents of the returned slice, and its
	// contents may change on the next call to any iteration method.
	Value() []byte

	// Release releases the iterator.  An iterator must always be released after
	// use, but it is not necessary to read an iterator until exhaustion before
	// releasing it.
	Release()
}

UtxoBackendIterator represents an iterator over the key/value pairs in a UtxoBackend in key order.

When an error is encountered, any iteration method will return false and will yield no key/value pair. The error can be queried by calling the Error method.

Release must always be called on the iterator after use whether an error occurred or not.

The interface contract does NOT require that these methods are safe for concurrent access.

type UtxoBackendTx

type UtxoBackendTx interface {
	// Get returns the value for the given key.  It returns nil if the key does
	// not exist.  An empty slice is returned for keys that exist but have no
	// value assigned.
	//
	// The returned slice is safe to modify.  Additionally, it is safe to modify
	// the slice passed as an argument after Get returns.
	Get(key []byte) ([]byte, error)

	// Has returns true if the key exists.
	//
	// It is safe to modify the slice passed as an argument after Has returns.
	Has(key []byte) (bool, error)

	// Put sets the value for the given key.  It overwrites any previous value
	// for that key.
	//
	// It is safe to modify the slice passed as an argument after Put returns.
	Put(key, value []byte) error

	// Delete removes the given key.
	//
	// It is safe to modify the slice passed as an argument after Delete
	// returns.
	Delete(key []byte) error

	// NewIterator returns an iterator for the latest snapshot of the
	// transaction.  The returned iterator is NOT safe for concurrent use, but
	// it is safe to use multiple iterators concurrently, with each in a
	// dedicated goroutine.
	//
	// The prefix parameter allows for slicing the iterator to only contain keys
	// with the given prefix.  A nil prefix is treated as a key BEFORE all keys.
	//
	// NOTE: The contents of any slice returned by the iterator should NOT be
	// modified unless noted otherwise.
	//
	// The iterator must be released after use, by calling the Release method.
	NewIterator(prefix []byte) UtxoBackendIterator

	// Commit commits the transaction.  If the returned error is not nil, then
	// the transaction is not committed and can either be retried or discarded.
	//
	// Other methods should not be called after the transaction has been
	// committed.
	Commit() error

	// Discard discards the transaction.  This method is a noop if the
	// transaction is already closed (either committed or discarded).
	//
	// Other methods should not be called after the transaction has been
	// discarded.
	Discard()
}

UtxoBackendTx represents a UtxoBackend transaction.

As would be expected with a transaction, no changes will be saved to the underlying UtxoBackend until it has been committed. The transaction will only provide a view of the database at the time it was created. Transactions should not be long running operations.

The interface contract requires that these methods are safe for concurrent access.

type UtxoCache

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

UtxoCache is an unspent transaction output cache that sits on top of the utxo set backend and provides significant runtime performance benefits at the cost of some additional memory usage. It drastically reduces the amount of reading and writing to disk, especially during initial block download when a very large number of blocks are being processed in quick succession.

The UtxoCache is a read-through cache. All utxo reads go through the cache. When there is a cache miss, the cache loads the missing data from the backend, caches it, and returns it to the caller.

The UtxoCache is a write-back cache. Writes to the cache are acknowledged by the cache immediately but are only periodically flushed to the backend. This allows intermediate steps to effectively be skipped. For example, a utxo that is created and then spent in between flushes never needs to be written to the utxo set in the backend.

Due to the write-back nature of the cache, at any given time the backend may not be in sync with the cache, and therefore all utxo reads and writes MUST go through the cache, and never read or write to the backend directly.

func NewUtxoCache

func NewUtxoCache(config *UtxoCacheConfig) *UtxoCache

NewUtxoCache returns a UtxoCache instance using the provided configuration details.

func (*UtxoCache) Commit

func (c *UtxoCache) Commit(view *UtxoViewpoint) error

Commit updates the cache based on the state of each entry in the provided view.

All entries in the provided view that are marked as modified and spent are removed from the view. Additionally, all entries that are added to the cache are removed from the provided view.

This function is safe for concurrent access.

func (*UtxoCache) FetchBackendState

func (c *UtxoCache) FetchBackendState() (*UtxoSetState, error)

FetchBackendState returns the current state of the UTXO set in the backend.

func (*UtxoCache) FetchEntries

func (c *UtxoCache) FetchEntries(filteredSet ViewFilteredSet, view *UtxoViewpoint) error

FetchEntries adds the requested transaction outputs to the provided view. It first checks the cache for each output, and if an output does not exist in the cache, it will fetch it from the backend.

Upon completion of this function, the view will contain an entry for each requested outpoint. Spent outputs, or those which otherwise don't exist, will result in a nil entry in the view.

This function is safe for concurrent access.

func (*UtxoCache) FetchEntry

func (c *UtxoCache) FetchEntry(outpoint wire.OutPoint) (*UtxoEntry, error)

FetchEntry returns the specified transaction output from the utxo set. If the output exists in the cache, it is returned immediately. Otherwise, it fetches the output from the backend, caches it, and returns it to the caller. A cloned copy of the entry is returned so it can safely be mutated by the caller without invalidating the cache.

When there is no entry for the provided output, nil will be returned for both the entry and the error.

This function is safe for concurrent access.

func (*UtxoCache) FetchStats

func (c *UtxoCache) FetchStats(bestHash *chainhash.Hash, bestHeight uint32) (*UtxoStats, error)

FetchStats returns statistics on the current utxo set.

func (*UtxoCache) Initialize

func (c *UtxoCache) Initialize(ctx context.Context, b *BlockChain) error

Initialize initializes the utxo cache and underlying utxo backend. This entails running any database migrations as well as ensuring that the utxo set is caught up to the tip of the best chain.

Since the cache is only flushed to the backend periodically, the utxo set may not be caught up to the tip of the best chain. This function catches the utxo set up by replaying all blocks from the block after the block that was last flushed to the tip block through the cache.

This function should only be called during initialization.

func (*UtxoCache) MaybeFlush

func (c *UtxoCache) MaybeFlush(bestHash *chainhash.Hash, bestHeight uint32,
	forceFlush bool, logFlush bool) error

MaybeFlush conditionally flushes the cache to the backend.

If the maximum size of the cache has been reached, or if the periodic flush interval has been reached, then a flush is required. Additionally, a flush can be forced by setting the force flush parameter.

This function is safe for concurrent access.

type UtxoCacheConfig

type UtxoCacheConfig struct {
	// Backend defines the backend which houses the utxo set.
	//
	// This field is required.
	Backend UtxoBackend

	// FlushBlockDB defines the function to use to flush the block database to
	// disk.  The block database is always flushed to disk before the UTXO cache
	// writes to disk in order to maintain a recoverable state in the event of
	// an unclean shutdown.
	//
	// This field is required.
	FlushBlockDB func() error

	// MaxSize defines the maximum allowed size of the utxo cache, in bytes.
	//
	// This field is required.
	MaxSize uint64
}

UtxoCacheConfig is a descriptor which specifies the utxo cache instance configuration.

type UtxoCacher

type UtxoCacher interface {
	// Commit updates the cache based on the state of each entry in the provided
	// view.
	//
	// All entries in the provided view that are marked as modified and spent
	// are removed from the view.  Additionally, all entries that are added to
	// the cache are removed from the provided view.
	Commit(view *UtxoViewpoint) error

	// FetchBackendState returns the current state of the UTXO set in the
	// backend.
	FetchBackendState() (*UtxoSetState, error)

	// FetchEntries adds the requested transaction outputs to the provided view.
	// It first checks the cache for each output, and if an output does not
	// exist in the cache, it will fetch it from the backend.
	//
	// Upon completion of this function, the view will contain an entry for each
	// requested outpoint.  Spent outputs, or those which otherwise don't exist,
	// will result in a nil entry in the view.
	FetchEntries(filteredSet ViewFilteredSet, view *UtxoViewpoint) error

	// FetchEntry returns the specified transaction output from the utxo set.
	// If the output exists in the cache, it is returned immediately.
	// Otherwise, it fetches the output from the backend, caches it, and returns
	// it to the caller.  The entry that is returned can safely be mutated by
	// the caller without invalidating the cache.
	//
	// When there is no entry for the provided output, nil will be returned for
	// both the entry and the error.
	FetchEntry(outpoint wire.OutPoint) (*UtxoEntry, error)

	// FetchStats returns statistics on the current utxo set.
	FetchStats(bestHash *chainhash.Hash, bestHeight uint32) (*UtxoStats, error)

	// Initialize initializes the utxo cache and underlying utxo backend.  This
	// entails running any database migrations as well as ensuring that the utxo
	// set is caught up to the tip of the best chain.
	Initialize(ctx context.Context, b *BlockChain) error

	// MaybeFlush conditionally flushes the cache to the backend.  A flush can
	// be forced by setting the force flush parameter.
	MaybeFlush(bestHash *chainhash.Hash, bestHeight uint32, forceFlush bool,
		logFlush bool) error
}

UtxoCacher represents a utxo cache that sits on top of a utxo set backend.

The interface contract requires that all of these methods are safe for concurrent access.

type UtxoEntry

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

UtxoEntry houses details about an individual transaction output in a utxo view such as whether or not it was contained in a coinbase tx, the height of the block that contains the tx, whether or not it is spent, its public key script, and how much it pays.

The struct is aligned for memory efficiency.

func (*UtxoEntry) Amount

func (entry *UtxoEntry) Amount() int64

Amount returns the amount of the output.

func (*UtxoEntry) BlockHeight

func (entry *UtxoEntry) BlockHeight() int64

BlockHeight returns the height of the block containing the output.

func (*UtxoEntry) BlockIndex

func (entry *UtxoEntry) BlockIndex() uint32

BlockIndex returns the index of the transaction that the output is contained in.

func (*UtxoEntry) Clone

func (entry *UtxoEntry) Clone() *UtxoEntry

Clone returns a copy of the utxo entry. It performs a deep copy for any fields that are mutable. Specifically, the script and ticket minimal outputs are NOT deep copied since they are immutable.

func (*UtxoEntry) HasExpiry

func (entry *UtxoEntry) HasExpiry() bool

HasExpiry returns whether or not the output was contained in a transaction that included an expiry.

func (*UtxoEntry) IsCoinBase

func (entry *UtxoEntry) IsCoinBase() bool

IsCoinBase returns whether or not the output was contained in a coinbase transaction.

func (*UtxoEntry) IsSpent

func (entry *UtxoEntry) IsSpent() bool

IsSpent returns whether or not the output has been spent based upon the current state of the unspent transaction output view it was obtained from.

func (*UtxoEntry) PkScript

func (entry *UtxoEntry) PkScript() []byte

PkScript returns the public key script for the output.

func (*UtxoEntry) ScriptVersion

func (entry *UtxoEntry) ScriptVersion() uint16

ScriptVersion returns the public key script version for the output.

func (*UtxoEntry) Spend

func (entry *UtxoEntry) Spend()

Spend marks the output as spent. Spending an output that is already spent has no effect.

func (*UtxoEntry) TicketMinimalOutputs

func (entry *UtxoEntry) TicketMinimalOutputs() []*stake.MinimalOutput

TicketMinimalOutputs returns the minimal outputs for the ticket transaction that the output is contained in. Note that the ticket minimal outputs are only stored in ticket submission outputs and nil will be returned for all other output types.

func (*UtxoEntry) TransactionType

func (entry *UtxoEntry) TransactionType() stake.TxType

TransactionType returns the type of the transaction that the output is contained in.

type UtxoSetState

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

UtxoSetState represents the current state of the utxo set. In particular, it tracks the block height and block hash of the last completed flush.

type UtxoStats

type UtxoStats struct {
	Utxos          int64
	Transactions   int64
	Size           int64
	Total          int64
	SerializedHash chainhash.Hash
}

UtxoStats represents unspent output statistics on the current utxo set.

type UtxoViewpoint

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

UtxoViewpoint represents a view into the set of unspent transaction outputs from a specific point of view in the chain. For example, it could be for the end of the main chain, some point in the history of the main chain, or down a side chain.

The unspent outputs are needed by other transactions for things such as script validation and double spend prevention.

func NewUtxoViewpoint

func NewUtxoViewpoint(cache UtxoCacher) *UtxoViewpoint

NewUtxoViewpoint returns a new empty unspent transaction output view.

func (*UtxoViewpoint) AddTxOut

func (view *UtxoViewpoint) AddTxOut(tx *dcrutil.Tx, txOutIdx uint32,
	blockHeight int64, blockIndex uint32, isTreasuryEnabled bool)

AddTxOut adds the specified output of the passed transaction to the view if it exists and is not provably unspendable. When the view already has an entry for the output, it will be marked unspent. All fields will be updated for existing entries since it's possible it has changed during a reorg.

func (*UtxoViewpoint) AddTxOuts

func (view *UtxoViewpoint) AddTxOuts(tx *dcrutil.Tx, blockHeight int64,
	blockIndex uint32, isTreasuryEnabled bool)

AddTxOuts adds all outputs in the passed transaction which are not provably unspendable to the view. When the view already has entries for any of the outputs, they are simply marked unspent. All fields will be updated for existing entries since it's possible it has changed during a reorg.

func (*UtxoViewpoint) BestHash

func (view *UtxoViewpoint) BestHash() *chainhash.Hash

BestHash returns the hash of the best block in the chain the view currently represents.

func (*UtxoViewpoint) Entries

func (view *UtxoViewpoint) Entries() map[wire.OutPoint]*UtxoEntry

Entries returns the underlying map that stores of all the utxo entries.

func (*UtxoViewpoint) LookupEntry

func (view *UtxoViewpoint) LookupEntry(outpoint wire.OutPoint) *UtxoEntry

LookupEntry returns information about a given transaction output according to the current state of the view. It will return nil if the passed output does not exist in the view or is otherwise not available such as when it has been disconnected during a reorg.

func (*UtxoViewpoint) PrevScript

func (view *UtxoViewpoint) PrevScript(prevOut *wire.OutPoint) (uint16, []byte, bool)

PrevScript returns the script and script version associated with the provided previous outpoint along with a bool that indicates whether or not the requested entry exists. This ensures the caller is able to distinguish between missing entries and empty v0 scripts.

func (*UtxoViewpoint) PriorityInput

func (view *UtxoViewpoint) PriorityInput(prevOut *wire.OutPoint) (int64, int64, bool)

PriorityInput returns the block height and amount associated with the provided previous outpoint along with a bool that indicates whether or not the requested entry exists. This ensures the caller is able to distinguish missing entries from zero values.

func (*UtxoViewpoint) RemoveEntry

func (view *UtxoViewpoint) RemoveEntry(outpoint wire.OutPoint)

RemoveEntry removes the given transaction output from the current state of the view. It will have no effect if the passed output does not exist in the view.

func (*UtxoViewpoint) SetBestHash

func (view *UtxoViewpoint) SetBestHash(hash *chainhash.Hash)

SetBestHash sets the hash of the best block in the chain the view currently represents.

type ViewFilteredSet

type ViewFilteredSet map[wire.OutPoint]struct{}

ViewFilteredSet represents a set of utxos to fetch from the cache/backend that are not already in a view.

type VoteCounts

type VoteCounts struct {
	Total        uint32
	TotalAbstain uint32
	VoteChoices  []uint32
}

VoteCounts is a compacted struct that is used to message vote counts.

type VoteInfo

type VoteInfo struct {
	Agendas      []chaincfg.ConsensusDeployment
	AgendaStatus []ThresholdStateTuple
}

VoteInfo represents information on agendas and their respective states for a consensus deployment.

Directories

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

Jump to

Keyboard shortcuts

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