Bitcoin ABC  0.22.12
P2P Digital Currency
Classes | Macros | Functions | Variables
validation.cpp File Reference
#include <validation.h>
#include <arith_uint256.h>
#include <avalanche/processor.h>
#include <blockdb.h>
#include <blockvalidity.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <checkqueue.h>
#include <config.h>
#include <consensus/activation.h>
#include <consensus/merkle.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <hash.h>
#include <index/txindex.h>
#include <logging.h>
#include <logging/timer.h>
#include <minerfund.h>
#include <node/ui_interface.h>
#include <policy/fees.h>
#include <policy/mempool.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <pow/aserti32d.h>
#include <pow/pow.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <random.h>
#include <reverse_iterator.h>
#include <script/script.h>
#include <script/scriptcache.h>
#include <script/sigcache.h>
#include <shutdown.h>
#include <timedata.h>
#include <tinyformat.h>
#include <txdb.h>
#include <txmempool.h>
#include <undo.h>
#include <util/check.h>
#include <util/moneystr.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#include <optional>
#include <string>
#include <thread>

Go to the source code of this file.

Classes

struct  PerBlockConnectTrace
 
class  ConnectTrace
 Used to track blocks whose transactions were applied to the UTXO state as a part of a single ActivateBestChainStep call. More...
 
class  CMainCleanup
 

Macros

#define MICRO   0.000001
 
#define MILLI   0.001
 

Functions

CChainStateChainstateActive ()
 
CChainChainActive ()
 
std::atomic_bool fImporting (false)
 
std::atomic_bool fReindex (false)
 
CBlockIndexLookupBlockIndex (const BlockHash &hash)
 
CBlockIndexFindForkInGlobalIndex (const CChain &chain, const CBlockLocator &locator)
 Find the last common block between the parameter chain and a locator. More...
 
static void FindFilesToPruneManual (ChainstateManager &chainman, std::set< int > &setFilesToPrune, int nManualPruneHeight)
 Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain. More...
 
static void FindFilesToPrune (ChainstateManager &chainman, std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
 Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target. More...
 
static uint32_t GetNextBlockScriptFlags (const Consensus::Params &params, const CBlockIndex *pindex)
 
bool TestLockPointValidity (const LockPoints *lp)
 Test whether the LockPoints height and time are still valid on the current chain. More...
 
bool CheckSequenceLocks (const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
 Check if transaction will be BIP 68 final in the next block to be created. More...
 
static bool IsReplayProtectionEnabled (const Consensus::Params &params, int64_t nMedianTimePast)
 
static bool IsReplayProtectionEnabled (const Consensus::Params &params, const CBlockIndex *pindexPrev)
 
static bool CheckInputsFromMempoolAndCache (const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags, PrecomputedTransactionData &txdata, int &nSigChecksOut) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
static bool AcceptToMemoryPoolWithTime (const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, int64_t nAcceptTime, bool bypass_limits, const Amount nAbsurdFee, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 (try to) add transaction to memory pool with a specified acceptance time. More...
 
bool AcceptToMemoryPool (const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, bool bypass_limits, const Amount nAbsurdFee, bool test_accept)
 (try to) add transaction to memory pool More...
 
bool GetTransaction (const TxId &txid, CTransactionRef &txOut, const Consensus::Params &params, BlockHash &hashBlock, const CBlockIndex *const block_index)
 Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock. More...
 
static bool WriteBlockToDisk (const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart)
 
Amount GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams)
 
BlockMapBlockIndex ()
 
static void AlertNotify (const std::string &strMessage)
 
static void CheckForkWarningConditions () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
static void CheckForkWarningConditionsOnNewFork (CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void SpendCoins (CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
 Mark all the coins corresponding to a given transaction inputs as spent. More...
 
void UpdateCoins (CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
 
void UpdateCoins (CCoinsViewCache &view, const CTransaction &tx, int nHeight)
 Apply the effects of this transaction on the UTXO set represented by view. More...
 
int GetSpendHeight (const CCoinsViewCache &inputs)
 Return the spend height, which is one more than the inputs.GetBestBlock(). More...
 
bool CheckInputScripts (const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks)
 Check whether all of this transaction's input scripts succeed. More...
 
static bool UndoWriteToDisk (const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock, const CMessageHeader::MessageMagic &messageStart)
 
bool UndoReadFromDisk (CBlockUndo &blockundo, const CBlockIndex *pindex)
 
static bool AbortNode (const std::string &strMessage, bilingual_str user_message=bilingual_str())
 Abort with a message. More...
 
static bool AbortNode (BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str())
 
DisconnectResult UndoCoinSpend (const Coin &undo, CCoinsViewCache &view, const COutPoint &out)
 Restore the UTXO in a Coin at a given COutPoint. More...
 
DisconnectResult ApplyBlockUndo (const CBlockUndo &blockUndo, const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
 Undo a block from the block and the undoblock data. More...
 
static void FlushBlockFile (bool fFinalize=false)
 
static bool FindUndoPos (BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
 
static bool WriteUndoDataForBlock (const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
 
void ThreadScriptCheck (int worker_num)
 Run an instance of the script checking thread. More...
 
VersionBitsCache versionbitscache GUARDED_BY (cs_main)
 
int32_t ComputeBlockVersion (const CBlockIndex *pindexPrev, const Consensus::Params &params)
 Determine what nVersion a new block should use. More...
 
static void UpdateTip (const CChainParams &params, CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(
 Check warning conditions and do some notifications on new chain tip set. More...
 
static const CBlockIndexFindBlockToFinalize (CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
static SynchronizationState GetSynchronizationState (bool init)
 
static bool NotifyHeaderTip () LOCKS_EXCLUDED(cs_main)
 
static void LimitValidationInterfaceQueue () LOCKS_EXCLUDED(cs_main)
 
bool ActivateBestChain (const Config &config, BlockValidationState &state, std::shared_ptr< const CBlock > pblock)
 Find the best known block, and make it the tip of the block chain. More...
 
bool PreciousBlock (const Config &config, BlockValidationState &state, CBlockIndex *pindex)
 Mark a block as precious and reorganize. More...
 
void ResetBlockFailureFlags (CBlockIndex *pindex)
 Remove invalidity status from a block and its descendants. More...
 
void UnparkBlockAndChildren (CBlockIndex *pindex)
 Remove parked status from a block and its descendants. More...
 
void UnparkBlock (CBlockIndex *pindex)
 Remove parked status from a block. More...
 
static bool FindBlockPos (FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
 
static bool CheckBlockHeader (const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
 Return true if the provided block header is valid. More...
 
bool CheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
 Functions for validating blocks and updating the block tree. More...
 
static bool ContextualCheckBlockHeader (const CChainParams &params, const CBlockHeader &block, BlockValidationState &state, const CBlockIndex *pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Context-dependent validity checks. More...
 
bool ContextualCheckTransactionForCurrentBlock (const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int flags)
 This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction based on the chain tip. More...
 
static bool ContextualCheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params &params, const CBlockIndex *pindexPrev)
 NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues if we change which consensus rules are enforced in this function (eg by adding a new consensus rule). More...
 
static FlatFilePos SaveBlockToDisk (const CBlock &block, int nHeight, const CChainParams &chainparams, const FlatFilePos *dbp)
 Store block on disk. More...
 
bool TestBlockValidity (BlockValidationState &state, const CChainParams &params, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions)
 Check a block is completely valid from start to finish (only works on top of our current best block) More...
 
uint64_t CalculateCurrentUsage ()
 BLOCK PRUNING CODE. More...
 
void UnlinkPrunedFiles (const std::set< int > &setFilesToPrune)
 Actually unlink the specified files. More...
 
void PruneBlockFilesManual (int nManualPruneHeight)
 Prune block files up to a given height. More...
 
static bool LoadBlockIndexDB (ChainstateManager &chainman, const Consensus::Params &params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void UnloadBlockIndex ()
 Unload database information. More...
 
bool LoadGenesisBlock (const CChainParams &chainparams)
 Ensures we have a genesis block in the block tree, possibly writing one to disk. More...
 
bool LoadExternalBlockFile (const Config &config, FILE *fileIn, FlatFilePos *dbp)
 Import blocks from an external file. More...
 
CBlockFileInfoGetBlockFileInfo (size_t n)
 Get block file info entry for one block file. More...
 
static ThresholdState VersionBitsStateImpl (const Consensus::Params &params, Consensus::DeploymentPos pos, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
ThresholdState VersionBitsTipState (const Consensus::Params &params, Consensus::DeploymentPos pos)
 Get the BIP9 state for a given deployment at the current tip. More...
 
ThresholdState VersionBitsBlockState (const Consensus::Params &params, Consensus::DeploymentPos pos, const CBlockIndex *pindex)
 Get the BIP9 state for a given deployment at a given block. More...
 
BIP9Stats VersionBitsTipStatistics (const Consensus::Params &params, Consensus::DeploymentPos pos)
 Get the numerical statistics for the BIP9 state for a given deployment at the current tip. More...
 
int VersionBitsTipStateSinceHeight (const Consensus::Params &params, Consensus::DeploymentPos pos)
 Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip. More...
 
bool LoadMempool (const Config &config, CTxMemPool &pool)
 Load the mempool from disk. More...
 
bool DumpMempool (const CTxMemPool &pool)
 Dump the mempool to disk. More...
 
bool IsBlockPruned (const CBlockIndex *pblockindex)
 Check whether the block associated with this index entry is pruned or not. More...
 
double GuessVerificationProgress (const ChainTxData &data, const CBlockIndex *pindex)
 Guess how far we are in the verification process at the given block index require cs_main if pindex has not been validated yet (because the chain's transaction count might be unset) This conditional lock requirement might be confusing, see: https://github.com/bitcoin/bitcoin/issues/15994. More...
 

Variables

ChainstateManager g_chainman
 
RecursiveMutex cs_main
 Global state. More...
 
CBlockIndexpindexBestHeader = nullptr
 Best header we've seen so far (used for getheaders queries' starting points). More...
 
Mutex g_best_block_mutex
 
std::condition_variable g_best_block_cv
 
uint256 g_best_block
 
bool fHavePruned = false
 Pruning-related variables and constants. More...
 
bool fPruneMode = false
 True if we're running in -prune mode. More...
 
bool fRequireStandard = true
 
bool fCheckBlockIndex = false
 
bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED
 
size_t nCoinCacheUsage = 5000 * 300
 
uint64_t nPruneTarget = 0
 Number of MiB of block files that we're trying to stay below. More...
 
int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE
 If the tip is older than this (in seconds), the node is considered to be in initial block download. More...
 
BlockHash hashAssumeValid
 Block hash whose ancestors we will assume to have valid scripts without checking them. More...
 
arith_uint256 nMinimumChainWork
 Minimum work we will assume exists on some valid chain. More...
 
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE_PER_KB)
 A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) More...
 
CTxMemPool g_mempool
 
std::unique_ptr< CBlockTreeDBpblocktree
 Global variable that points to the active block tree (protected by cs_main) More...
 
static CBlockIndex const * pindexBestForkTip = nullptr
 
static CBlockIndex const * pindexBestForkBase = nullptr
 
static CCheckQueue< CScriptCheckscriptcheckqueue (128)
 
static int64_t nTimeCheck = 0
 
static int64_t nTimeForks = 0
 
static int64_t nTimeVerify = 0
 
static int64_t nTimeConnect = 0
 
static int64_t nTimeIndex = 0
 
static int64_t nTimeCallbacks = 0
 
static int64_t nTimeTotal = 0
 
static int64_t nBlocksTotal = 0
 
static int64_t nTimeReadFromDisk = 0
 
static int64_t nTimeConnectTotal = 0
 
static int64_t nTimeFlush = 0
 
static int64_t nTimeChainState = 0
 
static int64_t nTimePostConnect = 0
 
static const uint64_t MEMPOOL_DUMP_VERSION = 1
 
static CMainCleanup instance_of_cmaincleanup
 

Macro Definition Documentation

◆ MICRO

#define MICRO   0.000001

Definition at line 62 of file validation.cpp.

◆ MILLI

#define MILLI   0.001

Definition at line 63 of file validation.cpp.

Function Documentation

◆ AbortNode() [1/2]

static bool AbortNode ( const std::string &  strMessage,
bilingual_str  user_message = bilingual_str() 
)
static

Abort with a message.

Definition at line 1304 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ AbortNode() [2/2]

static bool AbortNode ( BlockValidationState state,
const std::string &  strMessage,
const bilingual_str userMessage = bilingual_str() 
)
static

Definition at line 1317 of file validation.cpp.

Here is the call graph for this function:

◆ AcceptToMemoryPool()

bool AcceptToMemoryPool ( const Config config,
CTxMemPool pool,
TxValidationState state,
const CTransactionRef tx,
bool  bypass_limits,
const Amount  nAbsurdFee,
bool  test_accept 
)

(try to) add transaction to memory pool

Definition at line 776 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ AcceptToMemoryPoolWithTime()

static bool AcceptToMemoryPoolWithTime ( const Config config,
CTxMemPool pool,
TxValidationState state,
const CTransactionRef tx,
int64_t  nAcceptTime,
bool  bypass_limits,
const Amount  nAbsurdFee,
bool  test_accept 
)
static

(try to) add transaction to memory pool with a specified acceptance time.

Definition at line 745 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ActivateBestChain()

bool ActivateBestChain ( const Config config,
BlockValidationState state,
std::shared_ptr< const CBlock pblock = std::shared_ptr< const CBlock >() 
)

Find the best known block, and make it the tip of the block chain.

May not be called with cs_main held. May not be called in a validationinterface callback.

Definition at line 3081 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ AlertNotify()

static void AlertNotify ( const std::string &  strMessage)
static

Definition at line 931 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ApplyBlockUndo()

DisconnectResult ApplyBlockUndo ( const CBlockUndo blockUndo,
const CBlock block,
const CBlockIndex pindex,
CCoinsViewCache coins 
)

Undo a block from the block and the undoblock data.

See DisconnectBlock for more details.

Definition at line 1377 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BlockIndex()

BlockMap& BlockIndex ( )
Returns
the global block index map.

Definition at line 926 of file validation.cpp.

Here is the caller graph for this function:

◆ CalculateCurrentUsage()

uint64_t CalculateCurrentUsage ( )

BLOCK PRUNING CODE.

Calculate the amount of disk space the block & undo files currently use.

Definition at line 4440 of file validation.cpp.

Here is the caller graph for this function:

◆ ChainActive()

CChain& ChainActive ( )
Returns
the most-work chain.

Definition at line 73 of file validation.cpp.

Here is the call graph for this function:

◆ ChainstateActive()

CChainState& ChainstateActive ( )
Returns
the most-work valid chainstate.

Definition at line 67 of file validation.cpp.

◆ CheckBlock()

bool CheckBlock ( const CBlock block,
BlockValidationState state,
const Consensus::Params params,
BlockValidationOptions  validationOptions 
)

Functions for validating blocks and updating the block tree.

Context-independent validity checks.

Returns true if the provided block is valid (has valid header, transactions are valid, block is a valid size, etc.)

Definition at line 3702 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckBlockHeader()

static bool CheckBlockHeader ( const CBlockHeader block,
BlockValidationState state,
const Consensus::Params params,
BlockValidationOptions  validationOptions 
)
static

Return true if the provided block header is valid.

Only verify PoW if blockValidationOptions is configured to do so. This allows validation of headers on which the PoW hasn't been done. For example: to validate template handed to mining software. Do not call this for any check that depends on the context. For context-dependent calls, see ContextualCheckBlockHeader.

Definition at line 3688 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckForkWarningConditions()

static void CheckForkWarningConditions ( )
static

Definition at line 953 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckForkWarningConditionsOnNewFork()

static void CheckForkWarningConditionsOnNewFork ( CBlockIndex pindexNewForkTip)
static

Definition at line 1004 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckInputScripts()

bool CheckInputScripts ( const CTransaction tx,
TxValidationState state,
const CCoinsViewCache view,
const uint32_t  flags,
bool  sigCacheStore,
bool  scriptCacheStore,
const PrecomputedTransactionData txdata,
int &  nSigChecksOut,
TxSigCheckLimiter txLimitSigChecks,
CheckInputsLimiter pBlockLimitSigChecks,
std::vector< CScriptCheck > *  pvChecks 
)

Check whether all of this transaction's input scripts succeed.

This involves ECDSA signature checks so can be computationally intensive. This function should only be called after the cheap sanity checks in CheckTxInputs passed.

If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any script checks which are not necessary (eg due to script execution cache hits) are, obviously, not pushed onto pvChecks/run.

Upon success nSigChecksOut will be filled in with either:

  • correct total for all inputs, or,
  • 0, in the case when checks were pushed onto pvChecks (i.e., a cache miss with pvChecks non-null), in which case the total can be found by executing pvChecks and adding the results.

Setting sigCacheStore/scriptCacheStore to false will remove elements from the corresponding cache which are matched. This is useful for checking blocks where we will likely never need the cache entry again.

pLimitSigChecks can be passed to limit the sigchecks count either in parallel or serial validation. With pvChecks null (serial validation), breaking the pLimitSigChecks limit will abort evaluation early and return false. With pvChecks not-null (parallel validation): the cached nSigChecks may itself break the limit in which case false is returned, OR, each entry in the returned pvChecks must be executed exactly once in order to probe the limit accurately.

Definition at line 1136 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckInputsFromMempoolAndCache()

static bool CheckInputsFromMempoolAndCache ( const CTransaction tx,
TxValidationState state,
const CCoinsViewCache view,
const CTxMemPool pool,
const uint32_t  flags,
PrecomputedTransactionData txdata,
int &  nSigChecksOut 
)
static

Definition at line 289 of file validation.cpp.

Here is the call graph for this function:

◆ CheckSequenceLocks()

bool CheckSequenceLocks ( const CTxMemPool pool,
const CTransaction tx,
int  flags,
LockPoints lp = nullptr,
bool  useExistingLockPoints = false 
)

Check if transaction will be BIP 68 final in the next block to be created.

Simulates calling SequenceLocks() with data from the tip of the current active chain. Optionally stores in LockPoints the resulting height and time calculated and the hash of the block needed for calculation or skips the calculation and uses the LockPoints passed in for evaluation. The LockPoints should not be considered valid if CheckSequenceLocks returns false.

See consensus/consensus.h for flag definitions.

Definition at line 197 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeBlockVersion()

int32_t ComputeBlockVersion ( const CBlockIndex pindexPrev,
const Consensus::Params params 
)

Determine what nVersion a new block should use.

Definition at line 1492 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ContextualCheckBlock()

static bool ContextualCheckBlock ( const CBlock block,
BlockValidationState state,
const Consensus::Params params,
const CBlockIndex pindexPrev 
)
static

NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues if we change which consensus rules are enforced in this function (eg by adding a new consensus rule).

See comment in ConnectBlock(). Note that -reindex-chainstate skips the validation that happens here!

Definition at line 3916 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ContextualCheckBlockHeader()

static bool ContextualCheckBlockHeader ( const CChainParams params,
const CBlockHeader block,
BlockValidationState state,
const CBlockIndex pindexPrev,
int64_t  nAdjustedTime 
)
static

Context-dependent validity checks.

By "context", we mean only the previous block headers, but not the UTXO set; UTXO-related validity checks are done in ConnectBlock(). NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues if we change which consensus rules are enforced in this function (eg by adding a new consensus rule). See comment in ConnectBlock(). Note that -reindex-chainstate skips the validation that happens here!

Definition at line 3800 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ContextualCheckTransactionForCurrentBlock()

bool ContextualCheckTransactionForCurrentBlock ( const Consensus::Params params,
const CTransaction tx,
TxValidationState state,
int  flags = -1 
)

This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction based on the chain tip.

See consensus/consensus.h for flag definitions.

Definition at line 3871 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ DumpMempool()

bool DumpMempool ( const CTxMemPool pool)

Dump the mempool to disk.

Definition at line 5833 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ fImporting()

std::atomic_bool fImporting ( false  )
Here is the caller graph for this function:

◆ FindBlockPos()

static bool FindBlockPos ( FlatFilePos pos,
unsigned int  nAddSize,
unsigned int  nHeight,
uint64_t  nTime,
bool  fKnown = false 
)
static

Definition at line 3601 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindBlockToFinalize()

static const CBlockIndex* FindBlockToFinalize ( CBlockIndex pindexNew)
static

Definition at line 2427 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindFilesToPrune()

static void FindFilesToPrune ( ChainstateManager chainman,
std::set< int > &  setFilesToPrune,
uint64_t  nPruneAfterHeight 
)
static

Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.

The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex (which in this case means the blockchain must be re-downloaded.)

Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set. Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.). Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest). Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip. The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files. A db flag records the fact that at least some block files have been pruned.

Parameters
[out]setFilesToPruneThe set of file indices that can be unlinked will be returned

Definition at line 4559 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindFilesToPruneManual()

static void FindFilesToPruneManual ( ChainstateManager chainman,
std::set< int > &  setFilesToPrune,
int  nManualPruneHeight 
)
static

Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain.

Definition at line 4498 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindForkInGlobalIndex()

CBlockIndex* FindForkInGlobalIndex ( const CChain chain,
const CBlockLocator locator 
)

Find the last common block between the parameter chain and a locator.

Definition at line 146 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindUndoPos()

static bool FindUndoPos ( BlockValidationState state,
int  nFile,
FlatFilePos pos,
unsigned int  nAddSize 
)
static

Definition at line 3656 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FlushBlockFile()

static void FlushBlockFile ( bool  fFinalize = false)
static

Definition at line 1438 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ fReindex()

std::atomic_bool fReindex ( false  )
Here is the caller graph for this function:

◆ GetBlockFileInfo()

CBlockFileInfo* GetBlockFileInfo ( size_t  n)

Get block file info entry for one block file.

Definition at line 5708 of file validation.cpp.

Here is the caller graph for this function:

◆ GetBlockSubsidy()

Amount GetBlockSubsidy ( int  nHeight,
const Consensus::Params consensusParams 
)

Definition at line 849 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetNextBlockScriptFlags()

static uint32_t GetNextBlockScriptFlags ( const Consensus::Params params,
const CBlockIndex pindex 
)
static

Definition at line 1514 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetSpendHeight()

int GetSpendHeight ( const CCoinsViewCache inputs)

Return the spend height, which is one more than the inputs.GetBestBlock().

While checking, GetBestBlock() refers to the parent block. (protected by cs_main) This is also true for mempool checks.

Definition at line 1130 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetSynchronizationState()

static SynchronizationState GetSynchronizationState ( bool  init)
static

Definition at line 2900 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetTransaction()

bool GetTransaction ( const TxId txid,
CTransactionRef txOut,
const Consensus::Params params,
BlockHash hashBlock,
const CBlockIndex *const  block_index 
)

Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.

Retrieve a transaction (from memory pool, or from disk, if possible).

If blockIndex is provided, the transaction is fetched from the corresponding block.

Definition at line 789 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GUARDED_BY()

VersionBitsCache versionbitscache GUARDED_BY ( cs_main  )

◆ GuessVerificationProgress()

double GuessVerificationProgress ( const ChainTxData data,
const CBlockIndex pindex 
)

Guess how far we are in the verification process at the given block index require cs_main if pindex has not been validated yet (because the chain's transaction count might be unset) This conditional lock requirement might be confusing, see: https://github.com/bitcoin/bitcoin/issues/15994.

Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).

Definition at line 5898 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsBlockPruned()

bool IsBlockPruned ( const CBlockIndex pblockindex)

Check whether the block associated with this index entry is pruned or not.

Definition at line 5889 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsReplayProtectionEnabled() [1/2]

static bool IsReplayProtectionEnabled ( const Consensus::Params params,
int64_t  nMedianTimePast 
)
static

Definition at line 272 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsReplayProtectionEnabled() [2/2]

static bool IsReplayProtectionEnabled ( const Consensus::Params params,
const CBlockIndex pindexPrev 
)
static

Definition at line 278 of file validation.cpp.

Here is the call graph for this function:

◆ LimitValidationInterfaceQueue()

static void LimitValidationInterfaceQueue ( )
static

Definition at line 2935 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadBlockIndexDB()

static bool LoadBlockIndexDB ( ChainstateManager chainman,
const Consensus::Params params 
)
static

Definition at line 4733 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadExternalBlockFile()

bool LoadExternalBlockFile ( const Config config,
FILE *  fileIn,
FlatFilePos dbp 
)

Import blocks from an external file.

Definition at line 5211 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadGenesisBlock()

bool LoadGenesisBlock ( const CChainParams chainparams)

Ensures we have a genesis block in the block tree, possibly writing one to disk.

Definition at line 5207 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadMempool()

bool LoadMempool ( const Config config,
CTxMemPool pool 
)

Load the mempool from disk.

Definition at line 5749 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LookupBlockIndex()

CBlockIndex* LookupBlockIndex ( const BlockHash hash)

Definition at line 140 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ NotifyHeaderTip()

static bool NotifyHeaderTip ( )
static

Definition at line 2910 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreciousBlock()

bool PreciousBlock ( const Config config,
BlockValidationState state,
CBlockIndex pindex 
)

Mark a block as precious and reorganize.

May not be called in a validationinterface callback.

Definition at line 3126 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ PruneBlockFilesManual()

void PruneBlockFilesManual ( int  nManualPruneHeight)

Prune block files up to a given height.

Definition at line 4528 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResetBlockFailureFlags()

void ResetBlockFailureFlags ( CBlockIndex pindex)

Remove invalidity status from a block and its descendants.

Definition at line 3457 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SaveBlockToDisk()

static FlatFilePos SaveBlockToDisk ( const CBlock block,
int  nHeight,
const CChainParams chainparams,
const FlatFilePos dbp 
)
static

Store block on disk.

If dbp is non-nullptr, the file is known to already reside on disk.

Definition at line 4155 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SpendCoins()

void SpendCoins ( CCoinsViewCache view,
const CTransaction tx,
CTxUndo txundo,
int  nHeight 
)

Mark all the coins corresponding to a given transaction inputs as spent.

Definition at line 1075 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestBlockValidity()

bool TestBlockValidity ( BlockValidationState state,
const CChainParams params,
const CBlock block,
CBlockIndex pindexPrev,
BlockValidationOptions  validationOptions 
)

Check a block is completely valid from start to finish (only works on top of our current best block)

Definition at line 4394 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestLockPointValidity()

bool TestLockPointValidity ( const LockPoints lp)

Test whether the LockPoints height and time are still valid on the current chain.

Definition at line 178 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ThreadScriptCheck()

void ThreadScriptCheck ( int  worker_num)

Run an instance of the script checking thread.

Definition at line 1485 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UndoCoinSpend()

DisconnectResult UndoCoinSpend ( const Coin undo,
CCoinsViewCache view,
const COutPoint out 
)

Restore the UTXO in a Coin at a given COutPoint.

Definition at line 1325 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UndoReadFromDisk()

bool UndoReadFromDisk ( CBlockUndo blockundo,
const CBlockIndex pindex 
)

Definition at line 1271 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UndoWriteToDisk()

static bool UndoWriteToDisk ( const CBlockUndo blockundo,
FlatFilePos pos,
const BlockHash hashBlock,
const CMessageHeader::MessageMagic messageStart 
)
static

Definition at line 1241 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UnlinkPrunedFiles()

void UnlinkPrunedFiles ( const std::set< int > &  setFilesToPrune)

Actually unlink the specified files.

Definition at line 4485 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UnloadBlockIndex()

void UnloadBlockIndex ( )

Unload database information.

Definition at line 5138 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UnparkBlock()

void UnparkBlock ( CBlockIndex pindex)

Remove parked status from a block.

Definition at line 3482 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UnparkBlockAndChildren()

void UnparkBlockAndChildren ( CBlockIndex pindex)

Remove parked status from a block and its descendants.

Definition at line 3478 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateCoins() [1/2]

void UpdateCoins ( CCoinsViewCache view,
const CTransaction tx,
CTxUndo txundo,
int  nHeight 
)

Definition at line 1090 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateCoins() [2/2]

void UpdateCoins ( CCoinsViewCache view,
const CTransaction tx,
int  nHeight 
)

Apply the effects of this transaction on the UTXO set represented by view.

Definition at line 1096 of file validation.cpp.

Here is the call graph for this function:

◆ UpdateTip()

static void UpdateTip ( const CChainParams params,
CBlockIndex pindexNew 
)
static

Check warning conditions and do some notifications on new chain tip set.

Definition at line 2241 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ VersionBitsBlockState()

ThresholdState VersionBitsBlockState ( const Consensus::Params params,
Consensus::DeploymentPos  pos,
const CBlockIndex pindex 
)

Get the BIP9 state for a given deployment at a given block.

Definition at line 5727 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ VersionBitsStateImpl()

static ThresholdState VersionBitsStateImpl ( const Consensus::Params params,
Consensus::DeploymentPos  pos,
const CBlockIndex pindex 
)
static

Definition at line 5714 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ VersionBitsTipState()

ThresholdState VersionBitsTipState ( const Consensus::Params params,
Consensus::DeploymentPos  pos 
)

Get the BIP9 state for a given deployment at the current tip.

Definition at line 5721 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ VersionBitsTipStateSinceHeight()

int VersionBitsTipStateSinceHeight ( const Consensus::Params params,
Consensus::DeploymentPos  pos 
)

Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip.

Definition at line 5740 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ VersionBitsTipStatistics()

BIP9Stats VersionBitsTipStatistics ( const Consensus::Params params,
Consensus::DeploymentPos  pos 
)

Get the numerical statistics for the BIP9 state for a given deployment at the current tip.

Definition at line 5734 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteBlockToDisk()

static bool WriteBlockToDisk ( const CBlock block,
FlatFilePos pos,
const CMessageHeader::MessageMagic messageStart 
)
static

Definition at line 825 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteUndoDataForBlock()

static bool WriteUndoDataForBlock ( const CBlockUndo blockundo,
BlockValidationState state,
CBlockIndex pindex,
const CChainParams chainparams 
)
static

Definition at line 1458 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

Variable Documentation

◆ cs_main

RecursiveMutex cs_main

Global state.

Mutex to guard access to validation specific variables, such as reading or changing the chainstate.

This may also need to be locked when updating the transaction pool, e.g. on AcceptToMemoryPool. See CTxMemPool::cs comment for details.

The transaction pool has a separate lock to allow reading from it and the chainstate at the same time.

Definition at line 90 of file validation.cpp.

◆ fCheckBlockIndex

bool fCheckBlockIndex = false

Definition at line 101 of file validation.cpp.

◆ fCheckpointsEnabled

bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED

Definition at line 102 of file validation.cpp.

◆ fHavePruned

bool fHavePruned = false

Pruning-related variables and constants.

True if any block files have ever been pruned.

Definition at line 98 of file validation.cpp.

◆ fPruneMode

bool fPruneMode = false

True if we're running in -prune mode.

Definition at line 99 of file validation.cpp.

◆ fRequireStandard

bool fRequireStandard = true

Definition at line 100 of file validation.cpp.

◆ g_best_block

uint256 g_best_block

Definition at line 95 of file validation.cpp.

◆ g_best_block_cv

std::condition_variable g_best_block_cv

Definition at line 94 of file validation.cpp.

◆ g_best_block_mutex

Mutex g_best_block_mutex

Definition at line 93 of file validation.cpp.

◆ g_chainman

ChainstateManager g_chainman

Definition at line 65 of file validation.cpp.

◆ g_mempool

CTxMemPool g_mempool

Definition at line 112 of file validation.cpp.

◆ hashAssumeValid

BlockHash hashAssumeValid

Block hash whose ancestors we will assume to have valid scripts without checking them.

Definition at line 107 of file validation.cpp.

◆ instance_of_cmaincleanup

CMainCleanup instance_of_cmaincleanup
static

Definition at line 5929 of file validation.cpp.

◆ MEMPOOL_DUMP_VERSION

const uint64_t MEMPOOL_DUMP_VERSION = 1
static

Definition at line 5747 of file validation.cpp.

◆ minRelayTxFee

A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)

Definition at line 110 of file validation.cpp.

◆ nBlocksTotal

int64_t nBlocksTotal = 0
static

Definition at line 1588 of file validation.cpp.

◆ nCoinCacheUsage

size_t nCoinCacheUsage = 5000 * 300

Definition at line 103 of file validation.cpp.

◆ nMaxTipAge

int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE

If the tip is older than this (in seconds), the node is considered to be in initial block download.

Definition at line 105 of file validation.cpp.

◆ nMinimumChainWork

arith_uint256 nMinimumChainWork

Minimum work we will assume exists on some valid chain.

Definition at line 108 of file validation.cpp.

◆ nPruneTarget

uint64_t nPruneTarget = 0

Number of MiB of block files that we're trying to stay below.

Definition at line 104 of file validation.cpp.

◆ nTimeCallbacks

int64_t nTimeCallbacks = 0
static

Definition at line 1586 of file validation.cpp.

◆ nTimeChainState

int64_t nTimeChainState = 0
static

Definition at line 2351 of file validation.cpp.

◆ nTimeCheck

int64_t nTimeCheck = 0
static

Definition at line 1581 of file validation.cpp.

◆ nTimeConnect

int64_t nTimeConnect = 0
static

Definition at line 1584 of file validation.cpp.

◆ nTimeConnectTotal

int64_t nTimeConnectTotal = 0
static

Definition at line 2349 of file validation.cpp.

◆ nTimeFlush

int64_t nTimeFlush = 0
static

Definition at line 2350 of file validation.cpp.

◆ nTimeForks

int64_t nTimeForks = 0
static

Definition at line 1582 of file validation.cpp.

◆ nTimeIndex

int64_t nTimeIndex = 0
static

Definition at line 1585 of file validation.cpp.

◆ nTimePostConnect

int64_t nTimePostConnect = 0
static

Definition at line 2352 of file validation.cpp.

◆ nTimeReadFromDisk

int64_t nTimeReadFromDisk = 0
static

Definition at line 2348 of file validation.cpp.

◆ nTimeTotal

int64_t nTimeTotal = 0
static

Definition at line 1587 of file validation.cpp.

◆ nTimeVerify

int64_t nTimeVerify = 0
static

Definition at line 1583 of file validation.cpp.

◆ pblocktree

std::unique_ptr<CBlockTreeDB> pblocktree

Global variable that points to the active block tree (protected by cs_main)

Definition at line 166 of file validation.cpp.

◆ pindexBestForkBase

CBlockIndex const* pindexBestForkBase = nullptr
static

Definition at line 924 of file validation.cpp.

◆ pindexBestForkTip

CBlockIndex const* pindexBestForkTip = nullptr
static

Definition at line 923 of file validation.cpp.

◆ pindexBestHeader

CBlockIndex* pindexBestHeader = nullptr

Best header we've seen so far (used for getheaders queries' starting points).

Definition at line 92 of file validation.cpp.

◆ scriptcheckqueue

CCheckQueue<CScriptCheck> scriptcheckqueue(128)
static