 |
Bitcoin Core
22.99.0
P2P Digital Currency
|
Go to the documentation of this file.
6 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
9 #if defined(HAVE_CONFIG_H)
52 class SnapshotMetadata;
239 std::map<const uint256, const MempoolAcceptResult>&& results)
261 int64_t accept_time,
bool bypass_limits,
bool test_accept)
273 const Package& txns,
bool test_accept)
311 bool useExistingLockPoints = false);
336 std::swap(ptxTo, check.
ptxTo);
337 std::swap(m_tx_out, check.
m_tx_out);
338 std::swap(nIn, check.
nIn);
339 std::swap(nFlags, check.
nFlags);
342 std::swap(txdata, check.
txdata);
362 bool fCheckPOW =
true,
430 CoinsViews(std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
bool should_wipe);
512 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
521 size_t cache_size_bytes,
524 std::string leveldb_name =
"chainstate");
601 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
605 void LoadExternalBlockFile(FILE* fileIn,
FlatFilePos* dbp =
nullptr)
622 int nManualPruneHeight = 0);
646 bool ActivateBestChain(
648 std::shared_ptr<const
CBlock> pblock =
nullptr)
693 bool IsInitialBlockDownload() const;
717 size_t max_coins_cache_size_bytes,
902 const std::optional<uint256>& snapshot_blockhash = std::nullopt)
1025 #endif // BITCOIN_VALIDATION_H
CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
CCoinsView backed by the coin database (chainstate/)
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams ¶ms)
Return the expected assumeutxo value for a given height, if one exists.
std::set< CBlockIndex * > m_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
static const unsigned int DEFAULT_CHECKLEVEL
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees)
Constructor for success case.
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
const TxValidationState m_state
Contains information about why the transaction failed.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
FILE * fopen(const fs::path &p, const char *mode)
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
@ CRITICAL
The coins cache is in immediate need of a flush.
Holds configuration for use during UTXO snapshot load and validation.
const ResultType m_result_type
Result type.
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
256-bit unsigned big integer.
void CheckBlockIndex()
Make various assertions about the state of the block index.
const CTransaction * ptxTo
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
@ LARGE
The cache is at >= 90% capacity.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
bool m_snapshot_validated
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
CChainState & ActiveChainstate() const
The most-work chain.
std::shared_ptr< const CTransaction > CTransactionRef
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees)
void InitScriptExecutionCache()
Initializes the script-execution cache.
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
bool PopulateAndValidateSnapshot(CChainState &snapshot_chainstate, CAutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
Fee rate in satoshis per kilobyte: CAmount / kB.
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dictates whether we need to flush the cache to disk or not.
ResultType
Used to indicate the results of mempool validation.
The basic transaction that is broadcasted on the network and contained in blocks.
enum ScriptError_t ScriptError
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
CChain & ActiveChain() const
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Abstract view on the open txout dataset.
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
Non-refcounted RAII wrapper for FILE*.
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
#define Assume(val)
Assume is the identity function.
Parameters that influence chain consensus.
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
void swap(CScriptCheck &check)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
bool IsSnapshotActive() const
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
CTxMemPool * GetMempool()
std::function< FILE *(const fs::path &, const char *)> FopenFn
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
ScriptError GetScriptError() const
An output of a transaction.
Transaction validation functions.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
CBlockIndex * ActiveTip() const
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
static constexpr bool DEFAULT_COINSTATSINDEX
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
std::optional< uint256 > SnapshotBlockhash() const
static const bool DEFAULT_CHECKPOINTS_ENABLED
const CChainParams & m_params
Chain parameters for this chainstate.
CBlockIndex * m_best_invalid
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
@ INVALID
Fully validated, valid.
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Holds various statistics on transactions within a chain.
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
static const int64_t DEFAULT_MAX_TIP_AGE
Validation result for package mempool acceptance.
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Access to the block database (blocks/index/)
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
int64_t CAmount
Amount in satoshis (Can be negative)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(ChainstateManager &chainman) EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndex(const Consensus::Params &consensus_params, ChainstateManager &chainman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
const PackageValidationState m_state
CChainState stores and provides an API to update our local knowledge of the current best chain.
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW=true, bool fCheckMerkleRoot=true) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block)
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
static constexpr uint32_t MAX_PACKAGE_COUNT
Default maximum number of transactions in a package.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
int Height() const
Return the maximal height in the chain.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
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.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
An in-memory indexed chain of blocks.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
#define LOCKS_EXCLUDED(...)
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
CCoinsView that adds a memory cache for transactions to another CCoinsView.
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static MempoolAcceptResult Failure(TxValidationState state)
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
int32_t nBlockSequenceId GUARDED_BY(::cs_main)
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
const std::optional< uint256 > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness.
std::condition_variable g_best_block_cv
Validation result for a single transaction mempool acceptance.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
const CChainParams & Params()
Return the currently selected parameters.
Closure representing one script verification Note that this stores references to the spending transac...
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
bool LoadMempool(CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function=fsbridge::fopen)
Load the mempool from disk.
static const char *const DEFAULT_BLOCKFILTERINDEX
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
SynchronizationState
Current sync state passed to tip changed callbacks.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
static const bool DEFAULT_TXINDEX
bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
bool error(const char *fmt, const Args &... args)
static constexpr uint32_t MAX_PACKAGE_SIZE
Default maximum total virtual size of transactions in a package in KvB.
bool ActivateSnapshot(CAutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
bool CheckFinalTx(const CBlockIndex *active_chain_tip, const CTransaction &tx, int flags=-1) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Transaction validation functions.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
The block chain is a tree shaped structure starting with the genesis block at the root,...
@ SCRIPT_ERR_UNKNOWN_ERROR
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
@ DIFFERENT_WITNESS
Valid, transaction was already in the mempool.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
PrecomputedTransactionData * txdata
std::unique_ptr< CChainState > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
CChainState(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
bool CheckSequenceLocks(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, int flags, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
CChain m_chain
The current chain of blockheaders we consult and build on.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function=fsbridge::fopen, bool skip_file_commit=false)
Dump the mempool to disk.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
@ PERIODIC
Called by RandAddPeriodic()
static const signed int DEFAULT_CHECKBLOCKS
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...
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)