package
1.2.0
Repository: https://github.com/chappjc/dcrd.git
Documentation: pkg.go.dev

# README

blockchain

Build Status ISC License GoDoc

Package blockchain implements Decred block handling and chain selection rules. The test coverage is currently only around 60%, but will be increasing over time. See test_coverage.txt for the gocov coverage report. Alternatively, if you are running a POSIX OS, you can run the cov_report.sh script for a real-time report. Package blockchain is licensed under the liberal ISC license.

There is an associated blog post about the release of this package here.

This package has intentionally been designed so it can be used as a standalone package for any projects needing to handle processing of blocks into the decred block chain.

Installation and Updating

$ go get -u github.com/decred/dcrd/blockchain

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
  • Save the most recent orphan blocks for a limited time in case their parent blocks become available
  • Stop processing if the block is an orphan as the rest of the processing depends on the block's position within the block chain
  • 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

Examples

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

  • CompactToBig Example
    Demonstrates how to convert the compact "bits" in a block header which represent the target difficulty to a big integer and display it using the typical hex notation.

  • BigToCompact Example
    Demonstrates how to convert how to convert a target difficulty into the compact "bits" in a block header which represent that target difficulty.

License

Package blockchain is licensed under the copyfree ISC License.

# Packages

Package chaingen provides facilities for generating a full chain of blocks.
Package fullblocktests provides a set of block consensus validation tests.
Package indexers implements optional block chain indexes.
Package stake contains code for all of dcrd's stake transaction chain handling and other portions related to the Proof-of-Stake (PoS) system.

# Functions

BigToCompact converts a whole number N to a compact representation using an unsigned 32-bit number.
BlockOneCoinbasePaysTokens checks to see if the first block coinbase pays out to the network initial token ledger.
BuildMerkleTreeStore creates a merkle tree from a slice of transactions, stores it using a linear array, and returns a slice of the backing array.
CalcBlockTaxSubsidy calculates the subsidy for the organization address in the coinbase.
CalcBlockWorkSubsidy calculates the proof of work subsidy for a block as a proportion of the total subsidy.
CalcStakeVoteSubsidy calculates the subsidy for a stake vote based on the height of its input SStx.
CalculateAddedSubsidy calculates the amount of subsidy added by a block and its parent.
CalcWork calculates a work value from difficulty bits.
CheckBlockSanity performs some preliminary checks on a block to ensure it is sane before continuing with block processing.
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.
CheckProofOfWork ensures the block header bits which indicate the target difficulty is in min/max range and that the block hash is less than the target difficulty as claimed.
CheckTransactionInputs performs a series of checks on the inputs to a transaction to ensure they are valid.
CheckTransactionSanity performs some preliminary checks on a transaction to ensure it is sane.
CheckWorklessBlockSanity performs some preliminary checks on a block to ensure it is sane before continuing with block processing.
CoinbasePaysTax checks to see if a given block's coinbase correctly pays tax to the developer organization.
CompactToBig converts a compact representation of a whole number N to an unsigned 32-bit number.
ConvertUtxosToMinimalOutputs converts the contents of a UTX to a series of minimal outputs.
CountP2SHSigOps returns the number of signature operations for all input transactions which are of the pay-to-script-hash type.
CountSigOps returns the number of signature operations for all transaction input and output scripts in the provided transaction.
DBFetchBlockByHeight is the exported version of dbFetchBlockByHeight.
DBFetchHeaderByHeight is the exported version of dbFetchHeaderByHeight.
DBMainChainHasBlock is the exported version of dbMainChainHasBlock.
DisableLog disables all library log output.
HashMerkleBranches takes two hashes, treated as the left and right tree nodes, and returns the hash of their concatenation.
HashToBig converts a chainhash.Hash into a big.Int that can be used to perform math comparisons.
IsCoinBase determines whether or not a transaction is a coinbase.
IsCoinBaseTx determines whether or not a transaction is a coinbase.
IsFinalizedTransaction determines whether or not a transaction is finalized.
LockTimeToSequence converts the passed relative lock time to a sequence number in accordance with DCP0003.
New returns a BlockChain instance using the provided configuration details.
NewMedianTime returns a new instance of concurrency-safe implementation of the MedianTimeSource interface.
NewSubsidyCache initializes a new subsidy cache for a given height.
NewUtxoViewpoint returns a new empty unspent transaction output view.
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.
UseLogger uses a specified Logger to output package logging info.
ValidateTransactionScripts validates the scripts for the passed transaction using multiple goroutines.

# Constants

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 correct links into the chain up to a known checkpoint.
BFNone is a convenience value to specifically indicate no flags.
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.
CheckpointConfirmations is the number of blocks before the end of the current best block chain that a good checkpoint candidate must be.
ErrBadBlockHeight indicates that a block header's embedded block height was different from where it was actually embedded in the block chain.
ErrBadCheckpoint indicates a block that is expected to be at a checkpoint height does not match the expected one.
ErrBadCoinbaseAmountIn indicates that the AmountIn (=subsidy) for a coinbase input was incorrect.
ErrBadCoinbaseFraudProof indicates that the fraud proof for a coinbase input was non-null.
ErrBadCoinbaseOutpoint indicates that the outpoint used by a coinbase as input was non-null.
ErrBadCoinbaseScriptLen indicates the length of the signature script for a coinbase transaction is not within the valid range.
ErrBadCoinbaseValue indicates the amount of a coinbase value does not match the expected value of the subsidy plus the sum of all fees.
ErrBadFees indicates the total fees for a block are invalid due to exceeding the maximum possible value.
ErrBadMerkleRoot indicates the calculated merkle root does not match the expected value.
ErrBadStakebaseAmountIn indicates that the AmountIn (=subsidy) for a stakebase input was incorrect.
ErrBadStakebaseScriptLen indicates the length of the signature script for a stakebase transaction is not within the valid range.
ErrBadStakebaseScrVal indicates the signature script for a stakebase transaction was not set to the network consensus value.
ErrBadStakebaseValue indicates that a block's stake tx tree has spent more than it is allowed.
ErrBadStakeVersionindicates the block version is too old and is no longer accepted since the majority of the network has upgraded to a newer version.
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.
ErrBadTxOutValue indicates an output value for a transaction is invalid in some way such as being out of range.
ErrBlockOneTx indicates that block height 1 coinbase transaction in zero was incorrect in some way.
ErrBlockOneOutputs indicates that block height 1 failed to incorporate the ledger addresses correctly into the transaction's outputs.
ErrBlockOneTx indicates that block height 1 failed to correct generate the block one premine transaction.
ErrBlockTooBig indicates the serialized block size exceeds the maximum allowed size.
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.
ErrCheckpointTimeTooOld indicates a block has a timestamp before the most recent checkpoint.
ErrCoinbaseHeight indicates that the encoded height in the coinbase is incorrect.
ErrDifficultyTooLow indicates the difficulty for the block is lower than the difficulty required by the most recent checkpoint.
ErrDiscordantTxTree specifies that a given origin tx's content indicated that it should exist in a different tx tree than the one given in the TxIn outpoint.
ErrDuplicateBlock indicates a block with the same hash already exists.
ErrDuplicateTx indicates a block contains an identical transaction (or at least two transactions which hash to the same value).
ErrDuplicateTxInputs indicates a transaction references the same input more than once.
ErrExpiredTx indicates that the transaction is currently expired.
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.
ErrFirstTxNotCoinbase indicates the first transaction in a block is not a coinbase transaction.
ErrForceReorgMissingChild indicates that a reroganization was attempted to be forced, but the child node to reorganize to could not be found.
ErrForceReorgWrongChain indicates that a reroganization was attempted to be forced, but the chain indicated was not mirrored by b.bestChain.
ErrForkTooOld indicates a block is attempting to fork the block chain before the most recent checkpoint.
ErrFraudAmountIn indicates the witness amount given was fraudulent.
ErrFraudBlockHeight indicates the witness block height given was fraudulent.
ErrFraudBlockIndex indicates the witness block index given was fraudulent.
ErrFreshStakeMismatch indicates that a block's header contained a different number of SStx as compared to what was found in the block.
ErrHighHash indicates the block does not hash to a value which is lower than the required target difficultly.
ErrImmatureSpend indicates a transaction is attempting to spend a coinbase that has not yet reached the required maturity.
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.
ErrInvalidAncestorBlock indicates that an ancestor of this block has failed validation.
ErrInvalidEarlyFinalState indicates that a block before stake validation height had a non-zero final state.
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.
ErrInvalidEarlyVoteBits indicates that a block before stake validation height had an unallowed vote bits value.
ErrInvalidFinalState indicates that the final state of the PRNG included in the the block differed from the calculated final state.
ErrInvalidSSGenInput indicates that the input SStx to the SSGen tx was invalid because it was not an SStx.
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.
ErrInvalidSSRtxInput indicates that the input for the SSRtx was not from an SStx.
ErrInvalidTime indicates the time in the passed block has a precision that is more than one second.
ErrMissingParent indicates that the block was an orphan.
ErrMissingTxOut indicates a transaction output referenced by an input either does not exist or has already been spent.
ErrMultipleCoinbases indicates a block contains more than one coinbase transaction.
ErrNonstandardStakeTx indicates that a block contained a stake tx that was not one of the allowed types of a stake transactions.
ErrNoStakeTx indicates there were no stake transactions found in a block after stake validation height.
ErrNoTax indicates that there was no tax present in the coinbase of a block after height 1.
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.
ErrNotEnoughVotes indicates that a block contained less than a majority of voters.
ErrNoTransactions indicates the block does not have a least one transaction.
ErrNoTxInputs indicates a transaction does not have any inputs.
ErrNoTxOutputs indicates a transaction does not have any outputs.
ErrOverwriteTx indicates a block contains a transaction that has the same hash as a previous transaction which has not been fully spent.
ErrPoolSize indicates an error in the ticket pool size for this block.
ErrRegTxInStakeTree indicates that a regular transaction was found in the stake transaction tree.
ErrRegTxSpendStakeOut indicates that a regular tx attempted to spend to outputs tagged with stake tags, e.g.
ErrInvalidRevNum indicates that the number of revocations from the header was not the same as the number of SSRtx included in the block.
ErrScriptMalformed indicates a transaction script is malformed in some way.
ErrScriptValidation indicates the result of executing transaction script failed.
ErrSpendTooHigh indicates a transaction is attempting to spend more value than the sum of all of its inputs.
ErrSSGenPayeeNum indicates that the number of payees from the referenced SSGen's SStx was not the same as the number of the payees in the outputs of the SSGen tx.
ErrSSGenPayeeOuts indicates that the SSGen payee outputs were either not the values that would be expected given the rewards and input amounts of the original SStx, or that the SSGen addresses did not correctly correspond to the null data outputs given in the originating SStx.
ErrSSGenSubsidy indicates that there was an error in the amount of subsidy generated in the vote.
ErrSSRtxPayees indicates that the SSRtx failed to pay out to the committed addresses or amounts from the originating SStx.
ErrSSRtxPayeesMismatch means that the number of payees in an SSRtx was not the same as the number of payees in the outputs of the input SStx.
ErrSStxCommitment indicates that the propotional amounts from the inputs of an SStx did not match those found in the commitment outputs.
ErrSStxInImmature indicates that the OP_SSTX tagged output used as input was not yet TicketMaturity many blocks old.
ErrSStxInScrType indicates that the input used in an sstx was not pay-to-pubkeyhash or pay-to-script-hash, which is required.
ErrStakeBelowMinimum indicates that for some SStx in a given block, the given SStx had an amount of stake below the minimum network target.
ErrStakeFees indicates an error with the fees found in the stake transaction tree.
ErrStakeTxInRegularTree indicates a stake transaction was found in the regular transaction tree.
ErrTicketUnavailable indicates that a vote in the block spent a ticket that could not be found.
ErrTimeTooNew indicates the time is too far in the future as compared the current time.
ErrTimeTooOld indicates the time is either before the median time of the last several blocks per the chain consensus rules or prior to the most recent checkpoint.
ErrTooManyRevocations indicates more revocations were found in a block than were allowed.
ErrTooManySigOps indicates the total number of signature operations for a transaction or block exceed the maximum allowed limits.
ErrTooManySStxs indicates that more than the allowed number of SStx was found in a block.
ErrTooManyTransactions indicates the block has more transactions than are allowed.
ErrTooManyVotes indicates that a block contained more than the maximum allowable number of votes.
ErrTxSStxOutSpend indicates that a non SSGen or SSRtx tx attempted to spend an OP_SSTX tagged output from an SStx.
ErrTxTooBig indicates a transaction exceeds the maximum allowed size when serialized.
ErrUnexpectedDifficulty indicates specified bits do not align with the expected value either because it doesn't match the calculated valued based on difficulty regarted rules or it is out of the valid range.
ErrUnfinalizedTx indicates a transaction has not been finalized.
ErrVotesMismatch indicates that the number of SSGen in the block was not equivalent to the number of votes provided in the block header.
ErrVotesOnWrongBlock indicates that an SSGen voted on a block not the block's parent, and so was ineligible for inclusion into that block.
ErrWrongBlockSize indicates that the block size from the header was not the actual serialized size of the block.
ErrZeroValueOutputSpend indicates that a transaction attempted to spend a zero value output.
MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
MaxSigOpsPerBlock is the maximum number of signature operations allowed for a block.
MaxTimeOffsetSeconds is the maximum number of seconds a block time is allowed to be ahead of the current time.
MinCoinbaseScriptLen is the minimum length a coinbase script can be.
NTBlockAccepted indicates the associated block was accepted into the block chain.
NTBlockConnected indicates the associated block was connected to the main chain.
NTBlockDisconnected indicates the associated block was disconnected from the main chain.
NTSpentAndMissedTickets indicates newly maturing tickets from a newly accepted block.
NTReorganization indicates that a blockchain reorganization is in progress.
NTSpentAndMissedTickets indicates spent or missed tickets from a newly accepted block.
ThresholdActive is the state for a deployment for all blocks after a retarget period in which the deployment was in the ThresholdLockedIn state.
ThresholdDefined is the first state for each deployment and is the state for the genesis block has by definition for all deployments.
ThresholdFailed is the state for a deployment once its expiration time has been reached and it did not reach the ThresholdLockedIn state.
ThresholdInvalid is a deployment that does not exist.
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.
ThresholdStarted is the state for a deployment once its start time has been reached.
ViewpointPrevInvalidRegular is the viewpoint from the perspective of the everything up the the previous block's TxTreeRegular minus the contents of the TxTreeRegular and TxTreeStake of current block, to validate TxTreeRegular of the current block.
ViewpointPrevInvalidStake is the viewpoint from the perspective of the everything up the the previous block's TxTreeRegular but without the contents of the TxTreeRegular, to validate TxTreeStake.
ViewpointPrevValidInitial is the viewpoint from the perspective of the everything up the the previous block's TxTreeRegular, used to validate that tx tree regular.
ViewpointPrevValidRegular is the viewpoint from the perspective of the everything up the the previous block's TxTreeRegular plus the contents of the TxTreeRegular and TxTreeStake of current block, to validate TxTreeRegular of the current block.
ViewpointPrevValidStake is the viewpoint from the perspective of the everything up the the previous block's TxTreeRegular plus the contents of the TxTreeRegular, to validate TxTreeStake.

# Structs

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.
BlockAcceptedNtfnsData is the structure for data indicating information about a block being accepted.
BlockChain provides functions for working with the Decred block chain.
Config is a descriptor which specifies the blockchain instance configuration.
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: - NTBlockAccepted: *BlockAcceptedNtfnsData - NTBlockConnected: []*dcrutil.Block of len 2 - NTBlockDisconnected: []*dcrutil.Block of len 2 - NTReorganization: *ReorganizationNtfnsData - NTSpentAndMissedTickets: *TicketNotificationsData - NTNewTickets: *TicketNotificationsData.
ReorganizationNtfnsData is the structure for data indicating information about a reorganization.
RuleError identifies a rule violation.
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.
StakeVersions is a condensed form of a dcrutil.Block that is used to prevent using gigabytes of memory.
SubsidyCache is a structure that caches calculated values of subsidy so that they're not constantly recalculated.
ThresholdStateTuple contains the current state and the activated choice, when valid.
TicketNotificationsData is the structure for new/spent/missed ticket notifications at blockchain HEAD that are outgoing from chain.
UtxoEntry contains contextual information about an unspent transaction such as whether or not it is a coinbase transaction, which block it was found in, and the spent status of its outputs.
UtxoViewpoint represents a view into the set of unspent transaction outputs from a specific point of view in the chain.
VoteCounts is a compacted struct that is used to message vote counts.
No description provided by the author

# Interfaces

IndexManager provides a generic interface that the is called when blocks are connected and disconnected to and from the tip of the main chain for the purpose of supporting optional indexes.
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.

# Type aliases

AssertError identifies an error that indicates an internal code consistency issue and should be treated as a critical and unrecoverable error.
BehaviorFlags is a bitmask defining tweaks to the normal behavior when performing chain processing and consensus rules checks.
BlockLocator is used to help locate a specific block.
DeploymentError identifies an error that indicates a deployment ID was specified that does not exist.
ErrorCode identifies a kind of error.
HashError identifies an error that indicates a hash was specified that does not exist.
NotificationCallback is used for a caller to provide a callback for notifications about various chain events.
NotificationType represents the type of a notification message.
StakeViewpoint is the viewpoint of the blockchain depending on stake validation.
ThresholdState define the various threshold states used when voting on consensus changes.
VoteVersionError identifies an error that indicates a vote version was specified that does not exist.