Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
Classes | Namespaces | Macros | Enumerations | Functions | Variables
validation.h File Reference
#include <arith_uint256.h>
#include <attributes.h>
#include <blockfileinfo.h>
#include <blockindexcomparators.h>
#include <chain.h>
#include <common/bloom.h>
#include <config.h>
#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <deploymentstatus.h>
#include <disconnectresult.h>
#include <flatfile.h>
#include <kernel/chainparams.h>
#include <kernel/chainstatemanager_opts.h>
#include <kernel/cs_main.h>
#include <node/blockstorage.h>
#include <policy/packages.h>
#include <script/script_error.h>
#include <script/script_metrics.h>
#include <shutdown.h>
#include <sync.h>
#include <txdb.h>
#include <txmempool.h>
#include <uint256.h>
#include <util/check.h>
#include <util/fs.h>
#include <util/result.h>
#include <util/translation.h>
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
Include dependency graph for validation.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  BlockValidationOptions
 
struct  MempoolAcceptResult
 Validation result for a transaction evaluated by MemPoolAccept (single or package). More...
 
struct  PackageMempoolAcceptResult
 Validation result for package mempool acceptance. More...
 
class  CheckInputsLimiter
 Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck), atomic so as to be compatible with parallel validation. More...
 
class  TxSigCheckLimiter
 
class  CScriptCheck
 Closure representing one script verification. More...
 
class  CVerifyDB
 RAII wrapper for VerifyDB: Verify consistency of the block and coin databases. More...
 
class  CoinsViews
 A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO set. More...
 
class  Chainstate
 Chainstate stores and provides an API to update our local knowledge of the current best chain. More...
 
class  ChainstateManager
 Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate generated by downloading blocks, and an optional snapshot chainstate loaded from a UTXO snapshot. More...
 

Namespaces

namespace  node
 
namespace  Consensus
 
namespace  avalanche
 

Macros

#define MIN_TRANSACTION_SIZE    (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
 

Enumerations

enum class  SynchronizationState { INIT_REINDEX , INIT_DOWNLOAD , POST_INIT }
 Current sync state passed to tip changed callbacks. More...
 
enum class  VerifyDBResult {
  SUCCESS , CORRUPTED_BLOCK_DB , INTERRUPTED , SKIPPED_L3_CHECKS ,
  SKIPPED_MISSING_BLOCKS
}
 
enum class  FlushStateMode { NONE , IF_NEEDED , PERIODIC , ALWAYS }
 
enum class  CoinsCacheSizeState { CRITICAL = 2 , LARGE = 1 , OK = 0 }
 
enum class  SnapshotCompletionResult {
  SUCCESS , SKIPPED , MISSING_CHAINPARAMS , STATS_FAILED ,
  HASH_MISMATCH , BASE_BLOCKHASH_MISMATCH
}
 

Functions

void StartScriptCheckWorkerThreads (int threads_num)
 Run instances of script checking worker threads.
 
void StopScriptCheckWorkerThreads ()
 Stop all of the script checking worker threads.
 
Amount GetBlockSubsidy (int nHeight, const Consensus::Params &consensusParams)
 
bool AbortNode (BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
 
double GuessVerificationProgress (const ChainTxData &data, const CBlockIndex *pindex)
 Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
 
void PruneBlockFilesManual (Chainstate &active_chainstate, int nManualPruneHeight)
 Prune block files up to a given height.
 
MempoolAcceptResult AcceptToMemoryPool (Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false, unsigned int heightOverride=0) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Try to add a transaction to the mempool.
 
PackageMempoolAcceptResult ProcessNewPackage (Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Validate (and maybe submit) a package to the mempool.
 
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) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Check whether all of this transaction's input scripts succeed.
 
static bool CheckInputScripts (const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Handy shortcut to full fledged CheckInputScripts call.
 
void SpendCoins (CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
 Mark all the coins corresponding to a given transaction inputs as spent.
 
void UpdateCoins (CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
 Apply the effects of this transaction on the UTXO set represented by view.
 
std::optional< LockPointsCalculateLockPointsAtTip (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.
 
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.
 
bool CheckBlock (const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
 Functions for validating blocks and updating the block tree.
 
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.
 
arith_uint256 CalculateHeadersWork (const std::vector< CBlockHeader > &headers)
 Return the sum of the work on a given set of headers.
 
template<typename DEP >
bool DeploymentActiveAfter (const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
 Deployment* info via ChainstateManager.
 
template<typename DEP >
bool DeploymentActiveAt (const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
 
const AssumeutxoDataExpectedAssumeutxo (const int height, const CChainParams &params)
 Return the expected assumeutxo value for a given height, if one exists.
 

Variables

static const int MAX_SCRIPTCHECK_THREADS = 15
 Maximum number of dedicated script-checking threads allowed.
 
static const int DEFAULT_SCRIPTCHECK_THREADS = 0
 -par default (number of script-checking threads, 0 = auto)
 
static const bool DEFAULT_PEERBLOOMFILTERS = true
 
static const int DEFAULT_STOPATHEIGHT = 0
 Default for -stopatheight.
 
static const unsigned int MIN_BLOCKS_TO_KEEP = 288
 Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned.
 
static const signed int DEFAULT_CHECKBLOCKS = 6
 
static constexpr int DEFAULT_CHECKLEVEL {3}
 
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024
 Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat) At 1MB per block, 288 blocks = 288MB.
 
GlobalMutex g_best_block_mutex
 
std::condition_variable g_best_block_cv
 
const CBlockIndexg_best_block
 Used to notify getblocktemplate RPC of new tips.
 
const std::vector< std::string > CHECKLEVEL_DOC
 Documentation for argument 'checklevel'.
 
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(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) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction based on the chain tip.
 

Macro Definition Documentation

◆ MIN_TRANSACTION_SIZE

#define MIN_TRANSACTION_SIZE    (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))

Definition at line 79 of file validation.h.

Enumeration Type Documentation

◆ CoinsCacheSizeState

Enumerator
CRITICAL 

The coins cache is in immediate need of a flush.

LARGE 

The cache is at >= 90% capacity.

OK 

Definition at line 677 of file validation.h.

◆ FlushStateMode

See also
Chainstate::FlushStateToDisk
Enumerator
NONE 
IF_NEEDED 
PERIODIC 
ALWAYS 

Definition at line 638 of file validation.h.

◆ SnapshotCompletionResult

Enumerator
SUCCESS 
SKIPPED 
MISSING_CHAINPARAMS 
STATS_FAILED 
HASH_MISMATCH 
BASE_BLOCKHASH_MISMATCH 

Definition at line 1171 of file validation.h.

◆ SynchronizationState

Current sync state passed to tip changed callbacks.

Enumerator
INIT_REINDEX 
INIT_DOWNLOAD 
POST_INIT 

Definition at line 114 of file validation.h.

◆ VerifyDBResult

Enumerator
SUCCESS 
CORRUPTED_BLOCK_DB 
INTERRUPTED 
SKIPPED_L3_CHECKS 
SKIPPED_MISSING_BLOCKS 

Definition at line 608 of file validation.h.

Function Documentation

◆ AbortNode()

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

Definition at line 1852 of file validation.cpp.

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

◆ AcceptToMemoryPool()

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()

Parameters
[in]active_chainstateReference to the active chainstate.
[in]txThe transaction to submit for mempool acceptance.
[in]accept_timeThe timestamp for adding the transaction to the mempool. It is also used to determine when the entry expires.
[in]bypass_limitsWhen true, don't enforce mempool fee and capacity limits.
[in]test_acceptWhen true, run validation checks but don't submit to mempool.
[in]heightOverrideOverride the block height of the transaction. Used only upon reorg.
Returns
a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason.

Definition at line 1422 of file validation.cpp.

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

◆ CalculateHeadersWork()

arith_uint256 CalculateHeadersWork ( const std::vector< CBlockHeader > &  headers)

Return the sum of the work on a given set of headers.

Definition at line 4255 of file validation.cpp.

Here is the call graph for this function:

◆ CalculateLockPointsAtTip()

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.

Parameters
[in]tipChain tip for which tx sequence locks are calculated. For example, the tip of the current active chain.
[in]coins_viewAny 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]txThe transaction being evaluated.
Returns
The resulting height and time calculated and the hash of the block needed for calculation, or std::nullopt if there is an error.

Definition at line 183 of file validation.cpp.

Here is the call 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 4158 of file validation.cpp.

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

◆ CheckInputScripts() [1/2]

static bool CheckInputScripts ( const CTransaction tx,
TxValidationState state,
const CCoinsViewCache view,
const uint32_t  flags,
bool  sigCacheStore,
bool  scriptCacheStore,
const PrecomputedTransactionData txdata,
int nSigChecksOut 
)
inlinestatic

Handy shortcut to full fledged CheckInputScripts call.

Definition at line 462 of file validation.h.

Here is the call graph for this function:

◆ CheckInputScripts() [2/2]

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

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

◆ CheckSequenceLocksAtTip()

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.

Parameters
[in]tipChain tip to check tx sequence locks against. For example, the tip of the current active chain.
[in]lock_pointsLockPoints 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.

Here is the call graph for this function:

◆ DeploymentActiveAfter()

template<typename DEP >
bool DeploymentActiveAfter ( const CBlockIndex pindexPrev,
const ChainstateManager chainman,
DEP  dep 
)

Deployment* info via ChainstateManager.

Definition at line 1573 of file validation.h.

Here is the call graph for this function:

◆ DeploymentActiveAt()

template<typename DEP >
bool DeploymentActiveAt ( const CBlockIndex index,
const ChainstateManager chainman,
DEP  dep 
)

Definition at line 1579 of file validation.h.

Here is the call 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 6302 of file validation.cpp.

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

◆ GetBlockSubsidy()

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

Definition at line 1496 of file validation.cpp.

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

◆ GuessVerificationProgress()

double GuessVerificationProgress ( const ChainTxData data,
const CBlockIndex pindex 
)

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

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

Definition at line 6250 of file validation.cpp.

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

◆ HasValidProofOfWork()

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

Here is the call graph for this function:

◆ ProcessNewPackage()

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.

Parameters
[in]test_acceptWhen true, run validation checks but don't submit to mempool.
Returns
a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction. If a transaction fails, validation will exit early and some results may be missing. It is also possible for the package to be partially submitted.

Definition at line 1456 of file validation.cpp.

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

◆ PruneBlockFilesManual()

void PruneBlockFilesManual ( Chainstate active_chainstate,
int  nManualPruneHeight 
)

Prune block files up to a given height.

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

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

◆ StartScriptCheckWorkerThreads()

void StartScriptCheckWorkerThreads ( int  threads_num)

Run instances of script checking worker threads.

Definition at line 1977 of file validation.cpp.

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

◆ StopScriptCheckWorkerThreads()

void StopScriptCheckWorkerThreads ( )

Stop all of the script checking worker threads.

Definition at line 1981 of file validation.cpp.

Here is the caller graph for this function:

◆ UpdateCoins()

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.

Here is the call graph for this function:

Variable Documentation

◆ CHECKLEVEL_DOC

const std::vector<std::string> CHECKLEVEL_DOC
extern

Documentation for argument 'checklevel'.

Definition at line 98 of file validation.cpp.

◆ DEFAULT_CHECKBLOCKS

const signed int DEFAULT_CHECKBLOCKS = 6
static

Definition at line 96 of file validation.h.

◆ DEFAULT_CHECKLEVEL

constexpr int DEFAULT_CHECKLEVEL {3}
staticconstexpr

Definition at line 97 of file validation.h.

◆ DEFAULT_PEERBLOOMFILTERS

const bool DEFAULT_PEERBLOOMFILTERS = true
static

Definition at line 87 of file validation.h.

◆ DEFAULT_SCRIPTCHECK_THREADS

const int DEFAULT_SCRIPTCHECK_THREADS = 0
static

-par default (number of script-checking threads, 0 = auto)

Definition at line 85 of file validation.h.

◆ DEFAULT_STOPATHEIGHT

const int DEFAULT_STOPATHEIGHT = 0
static

Default for -stopatheight.

Definition at line 90 of file validation.h.

◆ g_best_block

const CBlockIndex* g_best_block
extern

Used to notify getblocktemplate RPC of new tips.

Definition at line 118 of file validation.cpp.

◆ g_best_block_cv

std::condition_variable g_best_block_cv
extern

Definition at line 117 of file validation.cpp.

◆ g_best_block_mutex

GlobalMutex g_best_block_mutex
extern

Definition at line 116 of file validation.cpp.

◆ MAX_SCRIPTCHECK_THREADS

const int MAX_SCRIPTCHECK_THREADS = 15
static

Maximum number of dedicated script-checking threads allowed.

Definition at line 83 of file validation.h.

◆ MIN_BLOCKS_TO_KEEP

const unsigned int MIN_BLOCKS_TO_KEEP = 288
static

Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned.

Definition at line 95 of file validation.h.

◆ MIN_DISK_SPACE_FOR_BLOCK_FILES

const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024
static

Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat) At 1MB per block, 288 blocks = 288MB.

Add 15% for Undo data = 331MB Add 20% for Orphan block rate = 397MB We want the low water mark after pruning to be at least 397 MB and since we prune in full block file chunks, we need the high water mark which triggers the prune to be one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB Setting the target to >= 550 MiB will make it likely we can respect the target.

Definition at line 111 of file validation.h.

◆ TestBlockValidity

bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(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) EXCLUSIVE_LOCKS_REQUIRED(cs_main) ( BlockValidationState state,
const CChainParams params,
Chainstate chainstate,
const CBlock block,
CBlockIndex pindexPrev,
const std::function< NodeClock::time_point()> &  adjusted_time_callback,
BlockValidationOptions  validationOptions 
)

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. Check a block is completely valid from start to finish (only works on top of our current best block)

Definition at line 593 of file validation.h.