Bitcoin Core  21.99.0
P2P Digital Currency
Classes | Macros | Functions | Variables
validation.cpp File Reference
#include <validation.h>
#include <arith_uint256.h>
#include <chain.h>
#include <chainparams.h>
#include <checkqueue.h>
#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <cuckoocache.h>
#include <flatfile.h>
#include <hash.h>
#include <index/blockfilterindex.h>
#include <index/txindex.h>
#include <logging.h>
#include <logging/timer.h>
#include <node/blockstorage.h>
#include <node/coinstats.h>
#include <node/ui_interface.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <pow.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <random.h>
#include <reverse_iterator.h>
#include <script/script.h>
#include <script/sigcache.h>
#include <shutdown.h>
#include <signet.h>
#include <timedata.h>
#include <tinyformat.h>
#include <txdb.h>
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
#include <util/check.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <optional>
#include <string>
#include <boost/algorithm/string/replace.hpp>
Include dependency graph for validation.cpp:

Go to the source code of this file.

Classes

class  WarningBitsConditionChecker
 Threshold condition checker that triggers when unknown versionbits are seen on the network. More...
 
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)
 
bool CheckInputScripts (const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks)
 Check whether all of this transaction's input scripts succeed. More...
 
static FILE * OpenUndoFile (const FlatFilePos &pos, bool fReadOnly)
 Open an undo file (rev?????.dat) More...
 
static FlatFileSeq BlockFileSeq ()
 
static FlatFileSeq UndoFileSeq ()
 
bool CheckFinalTx (const CBlockIndex *active_chain_tip, const CTransaction &tx, int flags)
 Transaction validation functions. More...
 
bool TestLockPointValidity (CChain &active_chain, const LockPoints *lp)
 Test whether the LockPoints height and time are still valid on the current chain. More...
 
bool CheckSequenceLocks (CChainState &active_chainstate, const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
 
static unsigned int GetBlockScriptFlags (const CBlockIndex *pindex, const Consensus::Params &chainparams)
 
static void LimitMempoolSize (CTxMemPool &pool, CCoinsViewCache &coins_cache, size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(pool.cs
 
 if (expired !=0)
 
pool TrimToSize (limit, &vNoSpendsRemaining)
 
 assert (std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
 
 for (const COutPoint &removed :vNoSpendsRemaining) coins_cache.Uncache(removed)
 
static bool IsCurrentForFeeEstimation (CChainState &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
static void UpdateMempoolForReorg (CChainState &active_chainstate, CTxMemPool &mempool, DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 
 AssertLockHeld (mempool.cs)
 
 assert (std::addressof(::ChainstateActive())==std::addressof(active_chainstate))
 
 while (it !=disconnectpool.queuedTx.get< insertion_order >().rend())
 
disconnectpool queuedTx clear ()
 
mempool UpdateTransactionsFromBlock (vHashUpdate)
 
mempool removeForReorg (active_chainstate, STANDARD_LOCKTIME_VERIFY_FLAGS)
 
 LimitMempoolSize (mempool, active_chainstate.CoinsTip(), gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) *1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)})
 
static bool CheckInputsFromMempoolAndCache (const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, unsigned int flags, PrecomputedTransactionData &txdata, CCoinsViewCache &coins_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 Checks to avoid mempool polluting consensus critical paths since cached signature and script validity results will be reused if we validate this transaction again during block validation. More...
 
 AssertLockHeld (pool.cs)
 
 assert (!tx.IsCoinBase())
 
 for (const CTxIn &txin :tx.vin)
 
return CheckInputScripts (tx, state, view, flags, true, true, txdata)
 
static MempoolAcceptResult AcceptToMemoryPoolWithTime (const CChainParams &chainparams, CTxMemPool &pool, CChainState &active_chainstate, const CTransactionRef &tx, int64_t nAcceptTime, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 (try to) add transaction to memory pool with a specified acceptance time More...
 
MempoolAcceptResult AcceptToMemoryPool (CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept)
 (Try to) add a transaction to the memory pool. More...
 
CTransactionRef GetTransaction (const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
 Return transaction from the block at block_index. More...
 
CAmount GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams)
 
static void AlertNotify (const std::string &strMessage)
 
void UpdateCoins (const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
 
void UpdateCoins (const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
 Apply the effects of this transaction on the UTXO set represented by view. More...
 
void InitScriptExecutionCache ()
 Initializes the script-execution cache. More...
 
static bool UndoWriteToDisk (const CBlockUndo &blockundo, FlatFilePos &pos, const uint256 &hashBlock, const CMessageHeader::MessageStartChars &messageStart)
 
bool UndoReadFromDisk (CBlockUndo &blockundo, const CBlockIndex *pindex)
 
static bool AbortNode (BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str())
 
int ApplyTxInUndo (Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
 Restore the UTXO in a Coin at a given COutPoint. 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 StartScriptCheckWorkerThreads (int threads_num)
 Run instances of script checking worker threads. More...
 
void StopScriptCheckWorkerThreads ()
 Stop all of the script checking worker threads. 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 bool IsScriptWitnessEnabled (const Consensus::Params &params)
 
static void DoWarning (const bilingual_str &warning)
 
static void AppendWarning (bilingual_str &res, const bilingual_str &warn)
 Private helper function that concatenates warning messages. More...
 
static void UpdateTip (CTxMemPool &mempool, const CBlockIndex *pindexNew, const CChainParams &chainParams, CChainState &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(
 Check warning conditions and do some notifications on new chain tip set. More...
 
static SynchronizationState GetSynchronizationState (bool init)
 
static bool NotifyHeaderTip (CChainState &chainstate) LOCKS_EXCLUDED(cs_main)
 
static void LimitValidationInterfaceQueue () LOCKS_EXCLUDED(cs_main)
 
bool FindBlockPos (FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, CChain &active_chain, uint64_t nTime, bool fKnown=false)
 
static bool CheckBlockHeader (const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
 
bool CheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
 Functions for validating blocks and updating the block tree. More...
 
bool IsWitnessEnabled (const CBlockIndex *pindexPrev, const Consensus::Params &params)
 Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147) rules. More...
 
void UpdateUncommittedBlockStructures (CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
 Update uncommitted block structures (currently: only the witness reserved value). More...
 
std::vector< unsigned char > GenerateCoinbaseCommitment (CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
 Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). More...
 
static bool ContextualCheckBlockHeader (const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, const CChainParams &params, const CBlockIndex *pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Context-dependent validity checks. More...
 
static bool ContextualCheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, 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...
 
bool TestBlockValidity (BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
 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 (CChainState &active_chainstate, int nManualPruneHeight)
 Prune block files up to a given height. More...
 
FILE * OpenBlockFile (const FlatFilePos &pos, bool fReadOnly)
 Open a block file (blk?????.dat) More...
 
fs::path GetBlockPosFilename (const FlatFilePos &pos)
 Translation to a filesystem path. More...
 
void UnloadBlockIndex (CTxMemPool *mempool, ChainstateManager &chainman)
 Unload database information. More...
 
CBlockFileInfoGetBlockFileInfo (size_t n)
 Get block file info entry for one block file. More...
 
bool LoadMempool (CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function)
 Load the mempool from disk. More...
 
bool DumpMempool (const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
 Dump the mempool to disk. 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 nChainTx might be unset) More...
 
const AssumeutxoDataExpectedAssumeutxo (const int height, const CChainParams &chainparams)
 Return the expected assumeutxo value for a given height, if one exists. More...
 

Variables

static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000
 An extra transaction can be added to a package, as long as it only has one ancestor and is no larger than this. More...
 
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000
 Maximum kilobytes for transactions to store for processing during reorg. More...
 
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000
 The pre-allocation chunk size for blk?????.dat files (since 0.8) More...
 
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000
 The pre-allocation chunk size for rev?????.dat files (since 0.8) More...
 
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...
 
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE {3}
 Maximum age of our tip for us to be considered current for fee estimation. More...
 
const std::vector< std::string > CHECKLEVEL_DOC
 Documentation for argument 'checklevel'. More...
 
ChainstateManager g_chainman
 
RecursiveMutex cs_main
 Mutex to guard access to validation specific variables, such as reading or changing the chainstate. 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 g_parallel_script_checks {false}
 Whether there are dedicated script-checking threads running. More...
 
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...
 
uint256 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)
 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...
 
std::vector< COutPointvNoSpendsRemaining
 
static void mempool cs
 
std::vector< uint256vHashUpdate
 
auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin()
 
static CuckooCache::cache< uint256, SignatureCacheHasherg_scriptExecutionCache
 
static CSHA256 g_scriptExecutionCacheHasher
 
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 58 of file validation.cpp.

◆ MILLI

#define MILLI   0.001

Definition at line 59 of file validation.cpp.

Function Documentation

◆ AbortNode()

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

Definition at line 1523 of file validation.cpp.

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

◆ AcceptToMemoryPool()

MempoolAcceptResult AcceptToMemoryPool ( CChainState active_chainstate,
CTxMemPool pool,
const CTransactionRef tx,
bool  bypass_limits,
bool  test_accept = false 
)

(Try to) add a transaction to the memory pool.

Parameters
[in]bypass_limitsWhen true, don't enforce mempool fee limits.
[in]test_acceptWhen true, run validation checks but don't submit to mempool.

Definition at line 1118 of file validation.cpp.

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

◆ AcceptToMemoryPoolWithTime()

static MempoolAcceptResult AcceptToMemoryPoolWithTime ( const CChainParams chainparams,
CTxMemPool pool,
CChainState active_chainstate,
const CTransactionRef tx,
int64_t  nAcceptTime,
bool  bypass_limits,
bool  test_accept 
)
static

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

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

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

◆ AppendWarning()

static void AppendWarning ( bilingual_str res,
const bilingual_str warn 
)
static

Private helper function that concatenates warning messages.

Definition at line 2304 of file validation.cpp.

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

◆ ApplyTxInUndo()

int ApplyTxInUndo ( 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 as an int

Definition at line 1536 of file validation.cpp.

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

◆ assert() [1/3]

assert ( !tx.  IsCoinBase())

◆ assert() [2/3]

assert ( std::addressof(::ChainstateActive())  = =std::addressof(active_chainstate))

◆ assert() [3/3]

assert ( std::addressof(::ChainstateActive().CoinsTip())  = =std::addressof(coins_cache))

◆ AssertLockHeld() [1/2]

AssertLockHeld ( mempool.  cs)
Here is the caller graph for this function:

◆ AssertLockHeld() [2/2]

AssertLockHeld ( pool.  cs)

◆ BlockFileSeq()

static FlatFileSeq BlockFileSeq ( )
static

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

Here is the caller graph for this function:

◆ ChainActive()

CChain& ChainActive ( )

Please prefer the identical ChainstateManager::ActiveChain.

Definition at line 115 of file validation.cpp.

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

◆ ChainstateActive()

CChainState& ChainstateActive ( )

Please prefer the identical ChainstateManager::ActiveChainstate.

Definition at line 108 of file validation.cpp.

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

◆ CheckBlock()

bool CheckBlock ( const CBlock block,
BlockValidationState state,
const Consensus::Params consensusParams,
bool  fCheckPOW = true,
bool  fCheckMerkleRoot = true 
)

Functions for validating blocks and updating the block tree.

Context-independent validity checks

Definition at line 3192 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 consensusParams,
bool  fCheckPOW = true 
)
static

Definition at line 3183 of file validation.cpp.

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

◆ CheckFinalTx()

bool CheckFinalTx ( const CBlockIndex active_chain_tip,
const CTransaction tx,
int  flags = -1 
)

Transaction validation functions.

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

Calls IsFinalTx() with current block height and appropriate block time.

See consensus/consensus.h for flag definitions.

Definition at line 212 of file validation.cpp.

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

◆ CheckInputScripts() [1/2]

bool CheckInputScripts ( const CTransaction tx,
TxValidationState state,
const CCoinsViewCache inputs,
unsigned int  flags,
bool  cacheSigStore,
bool  cacheFullScriptStore,
PrecomputedTransactionData txdata,
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.

Setting cacheSigStore/cacheFullScriptStore 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.

Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking callers should probably reset it to CONSENSUS in such cases.

Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp

Definition at line 1377 of file validation.cpp.

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

◆ CheckInputScripts() [2/2]

return CheckInputScripts ( tx  ,
state  ,
view  ,
flags  ,
true  ,
true  ,
txdata   
)

◆ CheckInputsFromMempoolAndCache()

static bool CheckInputsFromMempoolAndCache ( const CTransaction tx,
TxValidationState state,
const CCoinsViewCache view,
const CTxMemPool pool,
unsigned int  flags,
PrecomputedTransactionData txdata,
CCoinsViewCache coins_tip 
)
static

Checks to avoid mempool polluting consensus critical paths since cached signature and script validity results will be reused if we validate this transaction again during block validation.

◆ CheckSequenceLocks()

bool CheckSequenceLocks ( CChainState active_chainstate,
const CTxMemPool pool,
const CTransaction tx,
int  flags,
LockPoints lp,
bool  useExistingLockPoints 
)

Definition at line 265 of file validation.cpp.

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

◆ clear()

disconnectpool queuedTx clear ( )
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 1686 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 consensusParams,
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 3386 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 CBlockHeader block,
BlockValidationState state,
BlockManager blockman,
const CChainParams params,
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 3338 of file validation.cpp.

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

◆ DoWarning()

static void DoWarning ( const bilingual_str warning)
static

Definition at line 2293 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,
FopenFn  mockable_fopen_function,
bool  skip_file_commit 
)

Dump the mempool to disk.

Definition at line 4956 of file validation.cpp.

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

◆ ExpectedAssumeutxo()

const AssumeutxoData* ExpectedAssumeutxo ( const int  height,
const CChainParams params 
)

Return the expected assumeutxo value for a given height, if one exists.

Parameters
[in]heightGet the assumeutxo value for this height.
Returns
empty if no assumeutxo configuration exists for the given height.

Definition at line 5084 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()

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

Definition at line 3106 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 3161 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 1631 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 1623 of file validation.cpp.

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

◆ for() [1/2]

for ( const COutPoint &removed :vNoSpendsRemaining  )

◆ for() [2/2]

for ( const CTxIn &txin :tx.  vin)

Definition at line 440 of file validation.cpp.

Here is the call graph for this function:

◆ fReindex()

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

◆ GenerateCoinbaseCommitment()

std::vector<unsigned char> GenerateCoinbaseCommitment ( CBlock block,
const CBlockIndex pindexPrev,
const Consensus::Params consensusParams 
)

Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks).

Definition at line 3284 of file validation.cpp.

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

Here is the caller graph for this function:

◆ GetBlockPosFilename()

fs::path GetBlockPosFilename ( const FlatFilePos pos)

Translation to a filesystem path.

Definition at line 3910 of file validation.cpp.

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

◆ GetBlockScriptFlags()

static unsigned int GetBlockScriptFlags ( const CBlockIndex pindex,
const Consensus::Params chainparams 
)
static

Definition at line 1737 of file validation.cpp.

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

◆ GetBlockSubsidy()

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

Definition at line 1152 of file validation.cpp.

Here is the caller graph for this function:

◆ GetSynchronizationState()

static SynchronizationState GetSynchronizationState ( bool  init)
static

Definition at line 2682 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 uint256 hash,
const Consensus::Params consensusParams,
uint256 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]hashThe 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 1125 of file validation.cpp.

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

◆ GUARDED_BY()

◆ 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 nChainTx might be unset)

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

Definition at line 5019 of file validation.cpp.

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

◆ if()

if ( expired !  = 0)

Definition at line 350 of file validation.cpp.

Here is the caller graph for this function:

◆ InitScriptExecutionCache()

void InitScriptExecutionCache ( )

Initializes the script-execution cache.

Definition at line 1342 of file validation.cpp.

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

◆ IsCurrentForFeeEstimation()

static bool IsCurrentForFeeEstimation ( CChainState active_chainstate)
static

Definition at line 361 of file validation.cpp.

Here is the call graph for this function:

◆ IsScriptWitnessEnabled()

static bool IsScriptWitnessEnabled ( const Consensus::Params params)
static

Definition at line 1732 of file validation.cpp.

Here is the caller graph for this function:

◆ IsWitnessEnabled()

bool IsWitnessEnabled ( const CBlockIndex pindexPrev,
const Consensus::Params params 
)

Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147) rules.

Note that transaction witness validation rules are always enforced when P2SH is enforced.

Definition at line 3266 of file validation.cpp.

Here is the caller graph for this function:

◆ LimitMempoolSize() [1/2]

static void LimitMempoolSize ( CTxMemPool pool,
CCoinsViewCache coins_cache,
size_t  limit,
std::chrono::seconds  age 
)
static

◆ LimitMempoolSize() [2/2]

LimitMempoolSize ( mempool  ,
active_chainstate.  CoinsTip(),
gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) *  1000000,
std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}   
)

◆ LimitValidationInterfaceQueue()

static void LimitValidationInterfaceQueue ( )
static

Definition at line 2712 of file validation.cpp.

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

◆ LoadMempool()

bool LoadMempool ( CTxMemPool pool,
CChainState active_chainstate,
FopenFn  mockable_fopen_function 
)

Load the mempool from disk.

Definition at line 4871 of file validation.cpp.

Here is the call graph for this function:

◆ NotifyHeaderTip()

static bool NotifyHeaderTip ( CChainState chainstate)
static

Definition at line 2689 of file validation.cpp.

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

◆ OpenBlockFile()

FILE* OpenBlockFile ( const FlatFilePos pos,
bool  fReadOnly 
)

Open a block file (blk?????.dat)

Definition at line 3901 of file validation.cpp.

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

◆ OpenUndoFile()

static FILE * OpenUndoFile ( const FlatFilePos pos,
bool  fReadOnly = false 
)
static

Open an undo file (rev?????.dat)

Definition at line 3906 of file validation.cpp.

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

◆ PruneBlockFilesManual()

void PruneBlockFilesManual ( CChainState active_chainstate,
int  nManualPruneHeight 
)

Prune block files up to a given height.

Definition at line 3821 of file validation.cpp.

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

◆ removeForReorg()

mempool removeForReorg ( active_chainstate  ,
STANDARD_LOCKTIME_VERIFY_FLAGS   
)

◆ StartScriptCheckWorkerThreads()

void StartScriptCheckWorkerThreads ( int  threads_num)

Run instances of script checking worker threads.

Definition at line 1674 of file validation.cpp.

Here is the caller graph for this function:

◆ StopScriptCheckWorkerThreads()

void StopScriptCheckWorkerThreads ( )

Stop all of the script checking worker threads.

Definition at line 1679 of file validation.cpp.

Here is the caller graph for this function:

◆ TestBlockValidity()

bool TestBlockValidity ( BlockValidationState state,
const CChainParams chainparams,
CChainState chainstate,
const CBlock block,
CBlockIndex pindexPrev,
bool  fCheckPOW,
bool  fCheckMerkleRoot 
)

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

Definition at line 3703 of file validation.cpp.

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

◆ TestLockPointValidity()

bool TestLockPointValidity ( CChain active_chain,
const LockPoints lp 
)

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

Definition at line 246 of file validation.cpp.

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

◆ TrimToSize()

pool TrimToSize ( limit  ,
vNoSpendsRemaining 
)

◆ UndoFileSeq()

static FlatFileSeq UndoFileSeq ( )
static

Definition at line 3896 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 1492 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 uint256 hashBlock,
const CMessageHeader::MessageStartChars messageStart 
)
static

Definition at line 1465 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 3787 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 4439 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 ( const CTransaction tx,
CCoinsViewCache inputs,
CTxUndo txundo,
int  nHeight 
)

Definition at line 1303 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 ( const CTransaction tx,
CCoinsViewCache inputs,
int  nHeight 
)

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

Definition at line 1318 of file validation.cpp.

Here is the call graph for this function:

◆ UpdateMempoolForReorg()

static void UpdateMempoolForReorg ( CChainState active_chainstate,
CTxMemPool mempool,
DisconnectedBlockTransactions disconnectpool,
bool  fAddToMempool 
)
static
Here is the caller graph for this function:

◆ UpdateTip()

static void UpdateTip ( CTxMemPool mempool,
const CBlockIndex pindexNew,
const CChainParams chainParams,
CChainState active_chainstate 
)
static

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

Definition at line 2311 of file validation.cpp.

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

◆ UpdateTransactionsFromBlock()

mempool UpdateTransactionsFromBlock ( vHashUpdate  )

◆ UpdateUncommittedBlockStructures()

void UpdateUncommittedBlockStructures ( CBlock block,
const CBlockIndex pindexPrev,
const Consensus::Params consensusParams 
)

Update uncommitted block structures (currently: only the witness reserved value).

This is safe for submitted blocks.

Definition at line 3272 of file validation.cpp.

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

◆ while()

while ( it = disconnectpool.queuedTx.get<insertion_order>().rend())

Definition at line 400 of file validation.cpp.

Here is the call graph for this function:

◆ WriteUndoDataForBlock()

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

Definition at line 1645 of file validation.cpp.

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

Variable Documentation

◆ BLOCKFILE_CHUNK_SIZE

const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000
static

The pre-allocation chunk size for blk?????.dat files (since 0.8)

Definition at line 70 of file validation.cpp.

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

◆ cs

bool pool cs
Initial value:

Definition at line 388 of file validation.cpp.

◆ cs_main

RecursiveMutex cs_main

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 131 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 76 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 74 of file validation.cpp.

◆ EXTRA_DESCENDANT_TX_SIZE_LIMIT

const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000
static

An extra transaction can be added to a package, as long as it only has one ancestor and is no larger than this.

Not really any reason to make this configurable as it doesn't materially change DoS parameters.

Definition at line 66 of file validation.cpp.

◆ fCheckBlockIndex

bool fCheckBlockIndex = false

Definition at line 143 of file validation.cpp.

◆ fCheckpointsEnabled

bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED

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

◆ fPruneMode

bool fPruneMode = false

True if we're running in -prune mode.

Definition at line 141 of file validation.cpp.

◆ fRequireStandard

bool fRequireStandard = true

Definition at line 142 of file validation.cpp.

◆ g_best_block

uint256 g_best_block

Definition at line 136 of file validation.cpp.

◆ g_best_block_cv

std::condition_variable g_best_block_cv

Definition at line 135 of file validation.cpp.

◆ g_best_block_mutex

Mutex g_best_block_mutex

Definition at line 134 of file validation.cpp.

◆ g_chainman

ChainstateManager g_chainman

Definition at line 106 of file validation.cpp.

◆ g_parallel_script_checks

bool g_parallel_script_checks {false}

Whether there are dedicated script-checking threads running.

False indicates all script checking is done on the main threadMessageHandler thread.

Definition at line 137 of file validation.cpp.

◆ g_scriptExecutionCache

CuckooCache::cache<uint256, SignatureCacheHasher> g_scriptExecutionCache
static

Definition at line 1339 of file validation.cpp.

◆ g_scriptExecutionCacheHasher

CSHA256 g_scriptExecutionCacheHasher
static

Definition at line 1340 of file validation.cpp.

◆ hashAssumeValid

uint256 hashAssumeValid

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

Definition at line 148 of file validation.cpp.

◆ it

auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin()

Definition at line 399 of file validation.cpp.

◆ MAX_DISCONNECTED_TX_POOL_SIZE

const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000
static

Maximum kilobytes for transactions to store for processing during reorg.

Definition at line 68 of file validation.cpp.

◆ MAX_FEE_ESTIMATION_TIP_AGE

constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE {3}
staticconstexpr

Maximum age of our tip for us to be considered current for fee estimation.

Definition at line 78 of file validation.cpp.

◆ MEMPOOL_DUMP_VERSION

const uint64_t MEMPOOL_DUMP_VERSION = 1
static

Definition at line 4869 of file validation.cpp.

◆ minRelayTxFee

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

Definition at line 151 of file validation.cpp.

◆ nBlocksTotal

int64_t nBlocksTotal = 0
static

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

◆ nMinimumChainWork

arith_uint256 nMinimumChainWork

Minimum work we will assume exists on some valid chain.

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

◆ nTimeCallbacks

int64_t nTimeCallbacks = 0
static

Definition at line 1795 of file validation.cpp.

◆ nTimeChainState

int64_t nTimeChainState = 0
static

Definition at line 2411 of file validation.cpp.

◆ nTimeCheck

int64_t nTimeCheck = 0
static

Definition at line 1790 of file validation.cpp.

◆ nTimeConnect

int64_t nTimeConnect = 0
static

Definition at line 1793 of file validation.cpp.

◆ nTimeConnectTotal

int64_t nTimeConnectTotal = 0
static

Definition at line 2409 of file validation.cpp.

◆ nTimeFlush

int64_t nTimeFlush = 0
static

Definition at line 2410 of file validation.cpp.

◆ nTimeForks

int64_t nTimeForks = 0
static

Definition at line 1791 of file validation.cpp.

◆ nTimeIndex

int64_t nTimeIndex = 0
static

Definition at line 1794 of file validation.cpp.

◆ nTimePostConnect

int64_t nTimePostConnect = 0
static

Definition at line 2412 of file validation.cpp.

◆ nTimeReadFromDisk

int64_t nTimeReadFromDisk = 0
static

Definition at line 2408 of file validation.cpp.

◆ nTimeTotal

int64_t nTimeTotal = 0
static

Definition at line 1796 of file validation.cpp.

◆ nTimeVerify

int64_t nTimeVerify = 0
static

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

◆ pindexBestHeader

CBlockIndex* pindexBestHeader = nullptr

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

Definition at line 133 of file validation.cpp.

◆ scriptcheckqueue

CCheckQueue<CScriptCheck> scriptcheckqueue(128)
static

◆ UNDOFILE_CHUNK_SIZE

const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000
static

The pre-allocation chunk size for rev?????.dat files (since 0.8)

Definition at line 72 of file validation.cpp.

◆ vHashUpdate

std::vector<uint256> vHashUpdate

Definition at line 392 of file validation.cpp.

◆ vNoSpendsRemaining

std::vector<COutPoint> vNoSpendsRemaining

Definition at line 354 of file validation.cpp.

cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:131
AssertLockHeld
AssertLockHeld(mempool.cs)