![]() |
Bitcoin Core
25.99.0
P2P Digital Currency
|
#include <validation.h>
#include <kernel/coinstats.h>
#include <kernel/mempool_persist.h>
#include <arith_uint256.h>
#include <chain.h>
#include <checkqueue.h>
#include <common/args.h>
#include <consensus/amount.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 <kernel/chainparams.h>
#include <kernel/mempool_entry.h>
#include <kernel/notifications_interface.h>
#include <logging.h>
#include <logging/timer.h>
#include <node/blockstorage.h>
#include <node/utxo_snapshot.h>
#include <policy/policy.h>
#include <policy/rbf.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 <tinyformat.h>
#include <txdb.h>
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
#include <util/check.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
#include <util/hasher.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/time.h>
#include <util/trace.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <deque>
#include <numeric>
#include <optional>
#include <string>
#include <utility>
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... | |
struct | StopHashingException |
Functions | |
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... | |
bool | CheckFinalTxAtTip (const CBlockIndex &active_chain_tip, const CTransaction &tx) |
std::optional< LockPoints > | CalculateLockPointsAtTip (CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx) |
bool | CheckSequenceLocksAtTip (CBlockIndex *tip, const LockPoints &lock_points) |
Check if transaction will be BIP68 final in the next block to be created on top of tip. More... | |
static unsigned int | GetBlockScriptFlags (const CBlockIndex &block_index, const ChainstateManager &chainman) |
static void | LimitMempoolSize (CTxMemPool &pool, CCoinsViewCache &coins_cache) EXCLUSIVE_LOCKS_REQUIRED( |
static bool | IsCurrentForFeeEstimation (Chainstate &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main) |
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) |
MempoolAcceptResult | AcceptToMemoryPool (Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED( |
Try to add a transaction to the mempool. More... | |
PackageMempoolAcceptResult | ProcessNewPackage (Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept) |
Validate (and maybe submit) a package to the mempool. More... | |
CAmount | GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams) |
void | UpdateCoins (const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight) |
bool | InitScriptExecutionCache (size_t max_size_bytes) |
Initializes the script-execution cache. More... | |
bool | AbortNode (BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage) |
int | ApplyTxInUndo (Coin &&undo, CCoinsViewCache &view, const COutPoint &out) |
Restore the UTXO in a Coin at a given COutPoint. More... | |
void | StartScriptCheckWorkerThreads (int threads_num) |
Run instances of script checking worker threads. More... | |
void | StopScriptCheckWorkerThreads () |
Stop all of the script checking worker threads. More... | |
static std::array< ThresholdConditionCache, VERSIONBITS_NUM_BITS > warningcache | GUARDED_BY (cs_main) |
static void | AppendWarning (bilingual_str &res, const bilingual_str &warn) |
Private helper function that concatenates warning messages. More... | |
static void | UpdateTipLog (const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams ¶ms, const std::string &func_name, const std::string &prefix, const std::string &warning_messages) EXCLUSIVE_LOCKS_REQUIRED( |
static SynchronizationState | GetSynchronizationState (bool init) |
static bool | NotifyHeaderTip (Chainstate &chainstate) LOCKS_EXCLUDED(cs_main) |
static void | LimitValidationInterfaceQueue () LOCKS_EXCLUDED(cs_main) |
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 | HasValidProofOfWork (const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams) |
Check with the proof of work on each blockheader matches the value in nBits. More... | |
arith_uint256 | CalculateHeadersWork (const std::vector< CBlockHeader > &headers) |
Return the sum of the work on a given set of headers. More... | |
static bool | ContextualCheckBlockHeader (const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, const ChainstateManager &chainman, const CBlockIndex *pindexPrev, NodeClock::time_point now) EXCLUSIVE_LOCKS_REQUIRED( |
Context-dependent validity checks. More... | |
static bool | ContextualCheckBlock (const CBlock &block, BlockValidationState &state, const ChainstateManager &chainman, 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, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, bool fCheckPOW, bool fCheckMerkleRoot) |
Check a block is completely valid from start to finish (only works on top of our current best block) More... | |
void | PruneBlockFilesManual (Chainstate &active_chainstate, int nManualPruneHeight) |
Prune block files up to a given height. 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 AssumeutxoData * | ExpectedAssumeutxo (const int height, const CChainParams &chainparams) |
Return the expected assumeutxo value for a given height, if one exists. More... | |
static bool | DeleteCoinsDBFromDisk (const fs::path db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED( |
static void | FlushSnapshotToDisk (CCoinsViewCache &coins_cache, bool snapshot_loaded) |
static void | SnapshotUTXOHashBreakpoint () |
static ChainstateManager::Options && | Flatten (ChainstateManager::Options &&opts) |
Apply default chain params to nullopt members. More... | |
bool | IsBIP30Repeat (const CBlockIndex &block_index) |
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) More... | |
bool | IsBIP30Unspendable (const CBlockIndex &block_index) |
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) More... | |
Variables | |
static const unsigned int | MAX_DISCONNECTED_TX_POOL_SIZE = 20000 |
Maximum kilobytes for transactions to store for processing during reorg. 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... | |
static constexpr int | PRUNE_LOCK_BUFFER {10} |
The number of blocks to keep below the deepest prune lock. More... | |
GlobalMutex | g_best_block_mutex |
std::condition_variable | g_best_block_cv |
uint256 | g_best_block |
Used to notify getblocktemplate RPC of new tips. More... | |
static bool pool | cs |
static CuckooCache::cache< uint256, SignatureCacheHasher > | g_scriptExecutionCache |
static CSHA256 | g_scriptExecutionCacheHasher |
static CCheckQueue< CScriptCheck > | scriptcheckqueue (128) |
static SteadyClock::duration | time_check {} |
static SteadyClock::duration | time_forks {} |
static SteadyClock::duration | time_connect {} |
static SteadyClock::duration | time_verify {} |
static SteadyClock::duration | time_undo {} |
static SteadyClock::duration | time_index {} |
static SteadyClock::duration | time_total {} |
static int64_t | num_blocks_total = 0 |
static SteadyClock::duration | time_connect_total {} |
static SteadyClock::duration | time_flush {} |
static SteadyClock::duration | time_chainstate {} |
static SteadyClock::duration | time_post_connect {} |
bool AbortNode | ( | BlockValidationState & | state, |
const std::string & | strMessage, | ||
const bilingual_str & | userMessage | ||
) |
Definition at line 1845 of file validation.cpp.
MempoolAcceptResult AcceptToMemoryPool | ( | Chainstate & | active_chainstate, |
const CTransactionRef & | tx, | ||
int64_t | accept_time, | ||
bool | bypass_limits, | ||
bool | test_accept | ||
) |
Try to add a transaction to the mempool.
This is an internal function and is exposed only for testing. Client code should use ChainstateManager::ProcessTransaction()
[in] | active_chainstate | Reference to the active chainstate. |
[in] | tx | The transaction to submit for mempool acceptance. |
[in] | accept_time | The timestamp for adding the transaction to the mempool. It is also used to determine when the entry expires. |
[in] | bypass_limits | When true, don't enforce mempool fee and capacity limits. |
[in] | test_accept | When true, run validation checks but don't submit to mempool. |
Definition at line 1487 of file validation.cpp.
|
static |
Private helper function that concatenates warning messages.
Definition at line 2583 of file validation.cpp.
int ApplyTxInUndo | ( | Coin && | undo, |
CCoinsViewCache & | view, | ||
const COutPoint & | out | ||
) |
Restore the UTXO in a Coin at a given COutPoint.
undo | The Coin to be restored. |
view | The coins view to which to apply the changes. |
out | The out point that corresponds to the tx input. |
Definition at line 1858 of file validation.cpp.
assert | ( | !tx. | IsCoinBase() | ) |
AssertLockHeld | ( | pool. | cs | ) |
arith_uint256 CalculateHeadersWork | ( | const std::vector< CBlockHeader > & | headers | ) |
Return the sum of the work on a given set of headers.
Definition at line 3584 of file validation.cpp.
std::optional<LockPoints> CalculateLockPointsAtTip | ( | CBlockIndex * | tip, |
const CCoinsView & | coins_view, | ||
const CTransaction & | tx | ||
) |
Definition at line 195 of file validation.cpp.
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 3465 of file validation.cpp.
|
static |
Definition at line 3456 of file validation.cpp.
bool CheckFinalTxAtTip | ( | const CBlockIndex & | active_chain_tip, |
const CTransaction & | tx | ||
) |
Definition at line 137 of file validation.cpp.
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 1758 of file validation.cpp.
|
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.
bool CheckSequenceLocksAtTip | ( | CBlockIndex * | tip, |
const LockPoints & | lock_points | ||
) |
Check if transaction will be BIP68 final in the next block to be created on top of tip.
[in] | tip | Chain tip to check tx sequence locks against. For example, the tip of the current active chain. |
[in] | lock_points | LockPoints containing the height and time at which this transaction is final. Simulates calling SequenceLocks() with data from the tip passed in. The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false. |
Definition at line 240 of file validation.cpp.
|
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 3652 of file validation.cpp.
|
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 3603 of file validation.cpp.
|
static |
Definition at line 4997 of file validation.cpp.
const AssumeutxoData* ExpectedAssumeutxo | ( | const int | height, |
const CChainParams & | params | ||
) |
Return the expected assumeutxo value for a given height, if one exists.
[in] | height | Get the assumeutxo value for this height. |
Definition at line 4985 of file validation.cpp.
|
static |
Apply default chain params to nullopt members.
This helps to avoid coding errors around the accidental use of the compare operators that accept nullopt, thus ignoring the intended default value.
Definition at line 5573 of file validation.cpp.
|
static |
Definition at line 5143 of file validation.cpp.
for | ( | const CTxIn &txin :tx. | vin | ) |
|
static |
CAmount GetBlockSubsidy | ( | int | nHeight, |
const Consensus::Params & | consensusParams | ||
) |
|
static |
|
static |
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 4935 of file validation.cpp.
bool HasValidProofOfWork | ( | const std::vector< CBlockHeader > & | headers, |
const Consensus::Params & | consensusParams | ||
) |
Check with the proof of work on each blockheader matches the value in nBits.
Definition at line 3578 of file validation.cpp.
bool InitScriptExecutionCache | ( | size_t | max_size_bytes | ) |
Initializes the script-execution cache.
Definition at line 1720 of file validation.cpp.
bool IsBIP30Repeat | ( | const CBlockIndex & | block_index | ) |
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
Definition at line 5626 of file validation.cpp.
bool IsBIP30Unspendable | ( | const CBlockIndex & | block_index | ) |
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
Definition at line 5632 of file validation.cpp.
|
static |
|
static |
Definition at line 261 of file validation.cpp.
|
static |
|
static |
Definition at line 3051 of file validation.cpp.
PackageMempoolAcceptResult ProcessNewPackage | ( | Chainstate & | active_chainstate, |
CTxMemPool & | pool, | ||
const Package & | txns, | ||
bool | test_accept | ||
) |
Validate (and maybe submit) a package to the mempool.
See doc/policy/packages.md for full details on package validation rules.
[in] | test_accept | When true, run validation checks but don't submit to mempool. |
Definition at line 1518 of file validation.cpp.
void PruneBlockFilesManual | ( | Chainstate & | active_chainstate, |
int | nManualPruneHeight | ||
) |
Prune block files up to a given height.
Definition at line 4072 of file validation.cpp.
|
static |
Definition at line 5162 of file validation.cpp.
void StartScriptCheckWorkerThreads | ( | int | threads_num | ) |
Run instances of script checking worker threads.
Definition at line 1961 of file validation.cpp.
void StopScriptCheckWorkerThreads | ( | ) |
Stop all of the script checking worker threads.
Definition at line 1966 of file validation.cpp.
bool TestBlockValidity | ( | BlockValidationState & | state, |
const CChainParams & | chainparams, | ||
Chainstate & | chainstate, | ||
const CBlock & | block, | ||
CBlockIndex * | pindexPrev, | ||
const std::function< NodeClock::time_point()> & | adjusted_time_callback, | ||
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 4038 of file validation.cpp.
void UpdateCoins | ( | const CTransaction & | tx, |
CCoinsViewCache & | inputs, | ||
CTxUndo & | txundo, | ||
int | nHeight | ||
) |
Definition at line 1696 of file validation.cpp.
|
static |
const std::vector<std::string> CHECKLEVEL_DOC |
Documentation for argument 'checklevel'.
Definition at line 92 of file validation.cpp.
bool pool cs |
Definition at line 392 of file validation.cpp.
|
staticconstexpr |
Time to wait between flushing chainstate to disk.
Definition at line 89 of file validation.cpp.
|
staticconstexpr |
Time to wait between writing blocks/block index to disk.
Definition at line 87 of file validation.cpp.
uint256 g_best_block |
Used to notify getblocktemplate RPC of new tips.
Definition at line 109 of file validation.cpp.
std::condition_variable g_best_block_cv |
Definition at line 108 of file validation.cpp.
GlobalMutex g_best_block_mutex |
Definition at line 107 of file validation.cpp.
|
static |
Definition at line 1717 of file validation.cpp.
|
static |
Definition at line 1718 of file validation.cpp.
|
static |
Maximum kilobytes for transactions to store for processing during reorg.
Definition at line 85 of file validation.cpp.
|
staticconstexpr |
Maximum age of our tip for us to be considered current for fee estimation.
Definition at line 91 of file validation.cpp.
|
static |
Definition at line 2048 of file validation.cpp.
|
staticconstexpr |
The number of blocks to keep below the deepest prune lock.
There is nothing special about this number. It is higher than what we expect to see in regular mainnet reorgs, but not so high that it would noticeably interfere with the pruning mechanism.
Definition at line 105 of file validation.cpp.
|
static |
|
static |
Definition at line 2735 of file validation.cpp.
|
static |
Definition at line 2041 of file validation.cpp.
|
static |
Definition at line 2043 of file validation.cpp.
|
static |
Definition at line 2733 of file validation.cpp.
|
static |
Definition at line 2734 of file validation.cpp.
|
static |
Definition at line 2042 of file validation.cpp.
|
static |
Definition at line 2046 of file validation.cpp.
|
static |
Definition at line 2736 of file validation.cpp.
|
static |
Definition at line 2047 of file validation.cpp.
|
static |
Definition at line 2045 of file validation.cpp.
|
static |
Definition at line 2044 of file validation.cpp.