Bitcoin ABC  0.24.10
P2P Digital Currency
Classes | Macros | Functions | Variables
validation.cpp File Reference
#include <validation.h>
#include <arith_uint256.h>
#include <avalanche/avalanche.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 <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...
 

Macros

#define MICRO   0.000001
 
#define MILLI   0.001
 

Functions

CChainStateChainstateActive ()
 Please prefer the identical ChainstateManager::ActiveChainstate. More...
 
CChainChainActive ()
 Please prefer the identical ChainstateManager::ActiveChain. More...
 
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 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)
 
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, bool test_accept, Amount *fee_out=nullptr) 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, bool test_accept, Amount *fee_out)
 (try to) add transaction to memory pool More...
 
CTransactionRef GetTransaction (const CBlockIndex *const block_index, const CTxMemPool *const mempool, const TxId &txid, const Consensus::Params &consensusParams, BlockHash &hashBlock)
 Return transaction from the block at block_index. More...
 
static bool WriteBlockToDisk (const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart)
 
Amount GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams)
 
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 FlushUndoFile (int block_file, bool finalize=false)
 
static void FlushBlockFile (bool fFinalize=false, bool finalize_undo=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 (CTxMemPool &mempool, 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 (CTxMemPool *mempool, ChainstateManager &chainman)
 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...
 
void 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

static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL {1}
 Time to wait between writing blocks/block index to disk. More...
 
static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL {24}
 Time to wait between flushing chainstate to disk. More...
 
const std::vector< std::string > CHECKLEVEL_DOC
 Documentation for argument 'checklevel'. More...
 
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
 
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...
 
std::unique_ptr< CBlockTreeDBpblocktree
 Global variable that points to the active block tree (protected by cs_main) More...
 
static const CBlockIndexpindexBestForkTip = nullptr
 
static const CBlockIndexpindexBestForkBase = 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
 

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 ( BlockValidationState state,
const std::string &  strMessage,
const bilingual_str userMessage = bilingual_str() 
)
static

Definition at line 1313 of file validation.cpp.

Here is the call graph for this function:

◆ AbortNode() [2/2]

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

Abort with a message.

Definition at line 1300 of file validation.cpp.

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

◆ AcceptToMemoryPool()

bool AcceptToMemoryPool ( const Config config,
CTxMemPool pool,
TxValidationState state,
const CTransactionRef tx,
bool  bypass_limits,
bool  test_accept = false,
Amount fee_out = nullptr 
)

(try to) add transaction to memory pool

Parameters
[out]fee_outoptional argument to return tx fee to the caller

Definition at line 779 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,
bool  test_accept,
Amount fee_out = nullptr 
)
static

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

Definition at line 748 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 3125 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 927 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 1374 of file validation.cpp.

Here is the call graph for this function:
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 4493 of file validation.cpp.

Here is the caller graph for this function:

◆ ChainActive()

CChain& ChainActive ( )

Please prefer the identical ChainstateManager::ActiveChain.

Definition at line 86 of file validation.cpp.

Here is the call graph for this function:

◆ ChainstateActive()

m_mempool check & ChainstateActive ( )

Please prefer the identical ChainstateManager::ActiveChainstate.

Definition at line 80 of file validation.cpp.

Here is the caller graph for this function:

◆ 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 3753 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 3739 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 949 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 1000 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 1132 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 292 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,
bool  useExistingLockPoints 
)

Definition at line 200 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 1508 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 3967 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 3851 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 3922 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 5915 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 3645 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 2472 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 156 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 3707 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,
bool  finalize_undo = false 
)
static

Definition at line 1443 of file validation.cpp.

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

◆ FlushUndoFile()

static void FlushUndoFile ( int  block_file,
bool  finalize = false 
)
static

Definition at line 1435 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 5772 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 1530 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 1126 of file validation.cpp.

Here is the call graph for this function:

◆ GetSynchronizationState()

static SynchronizationState GetSynchronizationState ( bool  init)
static

Definition at line 2945 of file validation.cpp.

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

◆ GetTransaction()

CTransactionRef GetTransaction ( const CBlockIndex *const  block_index,
const CTxMemPool *const  mempool,
const TxId txid,
const Consensus::Params consensusParams,
BlockHash hashBlock 
)

Return transaction from the block at block_index.

If block_index is not provided, fall back to mempool. If mempool is not provided or the tx couldn't be found in mempool, fall back to g_txindex.

Parameters
[in]block_indexThe block to read from disk, or nullptr
[in]mempoolIf block_index is not provided, look in the mempool, if provided
[in]txidThe txid
[in]consensusParamsThe params
[out]hashBlockThe hash of block_index, if the tx was found via block_index
Returns
The tx if found, otherwise nullptr

Definition at line 786 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 5989 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 5980 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,
const CBlockIndex pindexPrev 
)
static

Definition at line 281 of file validation.cpp.

Here is the call graph for this function:

◆ IsReplayProtectionEnabled() [2/2]

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

Definition at line 275 of file validation.cpp.

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

◆ LimitValidationInterfaceQueue()

static void LimitValidationInterfaceQueue ( )
static

Definition at line 2980 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 4758 of file validation.cpp.

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

◆ LoadExternalBlockFile()

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

Import blocks from an external file.

Definition at line 5245 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 5241 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 5813 of file validation.cpp.

Here is the call graph for this function:

◆ LookupBlockIndex()

CBlockIndex* LookupBlockIndex ( const BlockHash hash)

Definition at line 150 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 2955 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 3170 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 4575 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 3501 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 4208 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 1071 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 4447 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 181 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 1501 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.

Parameters
undoThe Coin to be restored.
viewThe coins view to which to apply the changes.
outThe out point that corresponds to the tx input.
Returns
A DisconnectResult

Definition at line 1321 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 1267 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 1237 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 4537 of file validation.cpp.

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

◆ UnloadBlockIndex()

void UnloadBlockIndex ( CTxMemPool mempool,
ChainstateManager chainman 
)

Unload database information.

Definition at line 5170 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 3526 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 3522 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 1086 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 1092 of file validation.cpp.

Here is the call graph for this function:

◆ UpdateTip()

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

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

Definition at line 2284 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 5791 of file validation.cpp.

Here is the call graph for this function:

◆ VersionBitsStateImpl()

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

Definition at line 5778 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 5785 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 5804 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 5798 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 1462 of file validation.cpp.

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

Variable Documentation

◆ CHECKLEVEL_DOC

const std::vector<std::string> CHECKLEVEL_DOC
Initial value:
{
"level 0 reads the blocks from disk",
"level 1 verifies block validity",
"level 2 verifies undo data",
"level 3 checks disconnection of tip blocks",
"level 4 tries to reconnect the blocks",
"each level includes the checks of the previous levels",
}

Documentation for argument 'checklevel'.

Definition at line 69 of file validation.cpp.

◆ 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 103 of file validation.cpp.

◆ DATABASE_FLUSH_INTERVAL

constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL {24}
staticconstexpr

Time to wait between flushing chainstate to disk.

Definition at line 68 of file validation.cpp.

◆ DATABASE_WRITE_INTERVAL

constexpr std::chrono::hours DATABASE_WRITE_INTERVAL {1}
staticconstexpr

Time to wait between writing blocks/block index to disk.

Definition at line 66 of file validation.cpp.

◆ fCheckBlockIndex

bool fCheckBlockIndex = false

Definition at line 114 of file validation.cpp.

◆ fCheckpointsEnabled

bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED

Definition at line 115 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 111 of file validation.cpp.

◆ fPruneMode

bool fPruneMode = false

True if we're running in -prune mode.

Definition at line 112 of file validation.cpp.

◆ fRequireStandard

bool fRequireStandard = true

Definition at line 113 of file validation.cpp.

◆ g_best_block

uint256 g_best_block

Definition at line 108 of file validation.cpp.

◆ g_best_block_cv

std::condition_variable g_best_block_cv

Definition at line 107 of file validation.cpp.

◆ g_best_block_mutex

Mutex g_best_block_mutex

Definition at line 106 of file validation.cpp.

◆ g_chainman

ChainstateManager g_chainman

Definition at line 78 of file validation.cpp.

◆ hashAssumeValid

BlockHash hashAssumeValid

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

Definition at line 119 of file validation.cpp.

◆ MEMPOOL_DUMP_VERSION

const uint64_t MEMPOOL_DUMP_VERSION = 1
static

Definition at line 5811 of file validation.cpp.

◆ minRelayTxFee

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

Definition at line 122 of file validation.cpp.

◆ nBlocksTotal

int64_t nBlocksTotal = 0
static

Definition at line 1604 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 117 of file validation.cpp.

◆ nMinimumChainWork

arith_uint256 nMinimumChainWork

Minimum work we will assume exists on some valid chain.

Definition at line 120 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 116 of file validation.cpp.

◆ nTimeCallbacks

int64_t nTimeCallbacks = 0
static

Definition at line 1602 of file validation.cpp.

◆ nTimeChainState

int64_t nTimeChainState = 0
static

Definition at line 2396 of file validation.cpp.

◆ nTimeCheck

int64_t nTimeCheck = 0
static

Definition at line 1597 of file validation.cpp.

◆ nTimeConnect

int64_t nTimeConnect = 0
static

Definition at line 1600 of file validation.cpp.

◆ nTimeConnectTotal

int64_t nTimeConnectTotal = 0
static

Definition at line 2394 of file validation.cpp.

◆ nTimeFlush

int64_t nTimeFlush = 0
static

Definition at line 2395 of file validation.cpp.

◆ nTimeForks

int64_t nTimeForks = 0
static

Definition at line 1598 of file validation.cpp.

◆ nTimeIndex

int64_t nTimeIndex = 0
static

Definition at line 1601 of file validation.cpp.

◆ nTimePostConnect

int64_t nTimePostConnect = 0
static

Definition at line 2397 of file validation.cpp.

◆ nTimeReadFromDisk

int64_t nTimeReadFromDisk = 0
static

Definition at line 2393 of file validation.cpp.

◆ nTimeTotal

int64_t nTimeTotal = 0
static

Definition at line 1603 of file validation.cpp.

◆ nTimeVerify

int64_t nTimeVerify = 0
static

Definition at line 1599 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 176 of file validation.cpp.

◆ pindexBestForkBase

const CBlockIndex* pindexBestForkBase = nullptr
static

Definition at line 925 of file validation.cpp.

◆ pindexBestForkTip

const CBlockIndex* pindexBestForkTip = nullptr
static

Definition at line 924 of file validation.cpp.

◆ pindexBestHeader

CBlockIndex* pindexBestHeader = nullptr

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

Definition at line 105 of file validation.cpp.

◆ scriptcheckqueue

CCheckQueue<CScriptCheck> scriptcheckqueue(128)
static