Bitcoin ABC 0.30.5
P2P Digital Currency
|
#include <validation.h>
#include <kernel/chainparams.h>
#include <kernel/coinstats.h>
#include <kernel/disconnected_transactions.h>
#include <kernel/mempool_entry.h>
#include <kernel/mempool_persist.h>
#include <arith_uint256.h>
#include <avalanche/avalanche.h>
#include <avalanche/processor.h>
#include <blockvalidity.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <checkqueue.h>
#include <common/args.h>
#include <config.h>
#include <consensus/activation.h>
#include <consensus/amount.h>
#include <consensus/merkle.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <hash.h>
#include <kernel/notifications_interface.h>
#include <logging.h>
#include <logging/timer.h>
#include <minerfund.h>
#include <node/blockstorage.h>
#include <node/utxo_snapshot.h>
#include <policy/block/minerfund.h>
#include <policy/block/preconsensus.h>
#include <policy/block/rtt.h>
#include <policy/block/stakingrewards.h>
#include <policy/policy.h>
#include <policy/settings.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 <tinyformat.h>
#include <txdb.h>
#include <txmempool.h>
#include <undo.h>
#include <util/check.h>
#include <util/fs.h>
#include <util/fs_helpers.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/time.h>
#include <util/trace.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
#include <deque>
#include <numeric>
#include <optional>
#include <string>
#include <thread>
Go to the source code of this file.
Classes | |
struct | StopHashingException |
Macros | |
#define | MICRO 0.000001 |
#define | MILLI 0.001 |
Functions | |
static uint32_t | GetNextBlockScriptFlags (const CBlockIndex *pindex, const ChainstateManager &chainman) |
std::optional< LockPoints > | CalculateLockPointsAtTip (CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx) |
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be created on top of tip. More... | |
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 bool | IsReplayProtectionEnabled (const Consensus::Params ¶ms, int64_t nMedianTimePast) |
static bool | IsReplayProtectionEnabled (const Consensus::Params ¶ms, 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, 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, nSigChecksOut) |
MempoolAcceptResult | AcceptToMemoryPool (Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept, unsigned int heightOverride) |
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... | |
Amount | GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams) |
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) |
Apply the effects of this transaction on the UTXO set represented by view. 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... | |
bool | AbortNode (BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage) |
DisconnectResult | UndoCoinSpend (Coin &&undo, CCoinsViewCache &view, const COutPoint &out) |
Restore the UTXO in a Coin at a given COutPoint. More... | |
DisconnectResult | ApplyBlockUndo (CBlockUndo &&blockUndo, const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) |
Undo a block from the block and the undoblock data. 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 void | UpdateTipLog (const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams ¶ms, const std::string &func_name, const std::string &prefix) 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 ¶ms, BlockValidationOptions validationOptions) |
Return true if the provided block header is valid. More... | |
bool | CheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params ¶ms, BlockValidationOptions validationOptions) |
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, ChainstateManager &chainman, const CBlockIndex *pindexPrev, NodeClock::time_point now, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED( |
Context-dependent validity checks. More... | |
bool | ContextualCheckTransactionForCurrentBlock (const CBlockIndex &active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state) |
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 ¶ms, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) |
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 the chain's transaction count might be unset) This conditional lock requirement might be confusing, see: https://github.com/bitcoin/bitcoin/issues/15994. 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... | |
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... | |
static constexpr int | PRUNE_LOCK_BUFFER {10} |
The number of blocks to keep below the deepest prune lock. More... | |
static constexpr uint64_t | HEADERS_TIME_VERSION {1} |
GlobalMutex | g_best_block_mutex |
std::condition_variable | g_best_block_cv |
const CBlockIndex * | g_best_block |
Used to notify getblocktemplate RPC of new tips. More... | |
static bool pool | cs |
static CCheckQueue< CScriptCheck > | scriptcheckqueue (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 | 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 |
#define MICRO 0.000001 |
Definition at line 91 of file validation.cpp.
#define MILLI 0.001 |
Definition at line 92 of file validation.cpp.
bool AbortNode | ( | BlockValidationState & | state, |
const std::string & | strMessage, | ||
const bilingual_str & | userMessage | ||
) |
Definition at line 1852 of file validation.cpp.
MempoolAcceptResult AcceptToMemoryPool | ( | Chainstate & | active_chainstate, |
const CTransactionRef & | tx, | ||
int64_t | accept_time, | ||
bool | bypass_limits, | ||
bool | test_accept = false , |
||
unsigned int | heightOverride = 0 |
||
) |
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. |
[in] | heightOverride | Override the block height of the transaction. Used only upon reorg. |
Definition at line 1422 of file validation.cpp.
DisconnectResult ApplyBlockUndo | ( | 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 1913 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 4238 of file validation.cpp.
std::optional< LockPoints > CalculateLockPointsAtTip | ( | CBlockIndex * | tip, |
const CCoinsView & | coins_view, | ||
const CTransaction & | tx | ||
) |
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be created on top of tip.
[in] | tip | Chain tip for which tx sequence locks are calculated. For example, the tip of the current active chain. |
[in] | coins_view | Any CCoinsView that provides access to the relevant coins for checking sequence locks. For example, it can be a CCoinsViewCache that isn't connected to anything but contains all the relevant coins, or a CCoinsViewMemPool that is connected to the mempool and chainstate UTXO set. In the latter case, the caller is responsible for holding the appropriate locks to ensure that calls to GetCoin() return correct coins. |
[in] | tx | The transaction being evaluated. |
Definition at line 183 of file validation.cpp.
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 4141 of file validation.cpp.
|
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 4127 of file validation.cpp.
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:
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 1747 of file validation.cpp.
return CheckInputScripts | ( | tx | , |
state | , | ||
view | , | ||
flags | , | ||
true | , | ||
true | , | ||
txdata | , | ||
nSigChecksOut | |||
) |
|
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. |
Definition at line 207 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 4372 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 4257 of file validation.cpp.
bool ContextualCheckTransactionForCurrentBlock | ( | const CBlockIndex & | active_chain_tip, |
const Consensus::Params & | params, | ||
const CTransaction & | tx, | ||
TxValidationState & | state | ||
) |
|
static |
Definition at line 6279 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 6268 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 6886 of file validation.cpp.
|
static |
Definition at line 6438 of file validation.cpp.
for | ( | const CTxIn &txin :tx. | vin | ) |
Amount GetBlockSubsidy | ( | int | nHeight, |
const Consensus::Params & | consensusParams | ||
) |
Definition at line 1496 of file validation.cpp.
|
static |
Definition at line 1987 of file validation.cpp.
|
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 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 6216 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 4229 of file validation.cpp.
|
static |
|
static |
Definition at line 226 of file validation.cpp.
|
static |
Definition at line 3444 of file validation.cpp.
|
static |
Definition at line 3419 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 detailson package validation rules.
[in] | test_accept | When true, run validation checks but don't submit to mempool. |
Definition at line 1456 of file validation.cpp.
void PruneBlockFilesManual | ( | Chainstate & | active_chainstate, |
int | nManualPruneHeight | ||
) |
Prune block files up to a given height.
Definition at line 4947 of file validation.cpp.
|
static |
Definition at line 6456 of file validation.cpp.
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 1705 of file validation.cpp.
void StartScriptCheckWorkerThreads | ( | int | threads_num | ) |
Run instances of script checking worker threads.
Definition at line 1977 of file validation.cpp.
void StopScriptCheckWorkerThreads | ( | ) |
Stop all of the script checking worker threads.
Definition at line 1981 of file validation.cpp.
bool TestBlockValidity | ( | BlockValidationState & | state, |
const CChainParams & | params, | ||
Chainstate & | chainstate, | ||
const CBlock & | block, | ||
CBlockIndex * | pindexPrev, | ||
const std::function< NodeClock::time_point()> & | adjusted_time_callback, | ||
BlockValidationOptions | validationOptions | ||
) |
DisconnectResult UndoCoinSpend | ( | 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 1859 of file validation.cpp.
void UpdateCoins | ( | CCoinsViewCache & | view, |
const CTransaction & | tx, | ||
CTxUndo & | txundo, | ||
int | nHeight | ||
) |
Apply the effects of this transaction on the UTXO set represented by view.
Definition at line 1720 of file validation.cpp.
|
static |
const std::vector<std::string> CHECKLEVEL_DOC |
Documentation for argument 'checklevel'.
Definition at line 98 of file validation.cpp.
bool pool cs |
Definition at line 250 of file validation.cpp.
|
staticconstexpr |
Time to wait between flushing chainstate to disk.
Definition at line 97 of file validation.cpp.
|
staticconstexpr |
Time to wait between writing blocks/block index to disk.
Definition at line 95 of file validation.cpp.
const CBlockIndex* g_best_block |
Used to notify getblocktemplate RPC of new tips.
Definition at line 118 of file validation.cpp.
std::condition_variable g_best_block_cv |
Definition at line 117 of file validation.cpp.
GlobalMutex g_best_block_mutex |
Definition at line 116 of file validation.cpp.
|
staticconstexpr |
Definition at line 114 of file validation.cpp.
|
static |
Definition at line 2061 of file validation.cpp.
|
static |
Definition at line 2881 of file validation.cpp.
|
static |
Definition at line 2055 of file validation.cpp.
|
static |
Definition at line 2058 of file validation.cpp.
|
static |
Definition at line 2879 of file validation.cpp.
|
static |
Definition at line 2880 of file validation.cpp.
|
static |
Definition at line 2056 of file validation.cpp.
|
static |
Definition at line 2059 of file validation.cpp.
|
static |
Definition at line 2882 of file validation.cpp.
|
static |
Definition at line 2878 of file validation.cpp.
|
static |
Definition at line 2060 of file validation.cpp.
|
static |
Definition at line 2057 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 112 of file validation.cpp.
|
static |