6 #ifndef BITCOIN_VALIDATION_H 7 #define BITCOIN_VALIDATION_H 9 #if defined(HAVE_CONFIG_H) 46 #include <type_traits> 59 class SnapshotMetadata;
65 class SignalInterrupt;
166 const std::vector<uint256>& wtxids_fee_calculations) {
168 effective_feerate, wtxids_fee_calculations);
192 const std::vector<uint256>& wtxids_fee_calculations)
224 std::map<uint256, MempoolAcceptResult>&& results)
228 std::map<uint256, MempoolAcceptResult>&& results)
251 int64_t accept_time,
bool bypass_limits,
bool test_accept)
263 const Package& txns,
bool test_accept)
338 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
339 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
340 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
357 bool fCheckPOW =
true,
516 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
531 size_t cache_size_bytes,
534 fs::path leveldb_name = "chainstate");
617 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
631 bool FlushStateToDisk(
634 int nManualPruneHeight = 0);
664 bool ActivateBestChain(
666 std::shared_ptr<const CBlock> pblock =
nullptr)
722 size_t max_coins_cache_size_bytes,
867 [[nodiscard]]
bool PopulateAndValidateSnapshot(
879 bool AcceptBlockHeader(
887 std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update
GUARDED_BY(::
cs_main) {};
889 std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache
GUARDED_BY(::
cs_main);
897 return cs && !
cs->m_disabled;
907 std::function<void()> restart_indexes = std::function<void()>();
921 void CheckBlockIndex();
950 mutable std::atomic<bool> m_cached_finished_ibd{
false};
959 int32_t nBlockReverseSequenceId = -1;
968 nBlockSequenceId = 1;
969 nBlockReverseSequenceId = -1;
999 int64_t m_total_coinstip_cache{0};
1003 int64_t m_total_coinsdb_cache{0};
1027 [[nodiscard]]
bool ActivateSnapshot(
1050 return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
1055 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() :
nullptr;
1071 bool IsSnapshotActive()
const;
1073 std::optional<uint256> SnapshotBlockhash()
const;
1078 return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
1082 bool IsInitialBlockDownload()
const;
1113 std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent =
nullptr);
1139 bool ProcessNewBlock(
const std::shared_ptr<const CBlock>& block,
bool force_processing,
bool min_pow_checked,
bool* new_block)
LOCKS_EXCLUDED(
cs_main);
1194 void UpdateUncommittedBlockStructures(
CBlock& block, const
CBlockIndex* pindexPrev) const;
1197 std::vector<
unsigned char> GenerateCoinbaseCommitment(
CBlock& block, const
CBlockIndex* pindexPrev) const;
1203 void ReportHeadersPresync(const
arith_uint256& work, int64_t height, int64_t timestamp);
1243 std::pair<
int,
int> GetPruneRange(
1254 template<typename DEP>
1257 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1260 template<
typename DEP>
1266 template<
typename DEP>
1278 #endif // BITCOIN_VALIDATION_H std::shared_ptr< const CTransaction > CTransactionRef
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
std::thread m_thread_load
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from. ...
const uint256 & AssumedValidBlock() const
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
CScriptCheck & operator=(const CScriptCheck &)=delete
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
std::chrono::time_point< NodeClock > time_point
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
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=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) ...
SteadyClock::time_point m_last_flush
SynchronizationState
Current sync state passed to tip changed callbacks.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
enum ScriptError_t ScriptError
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< uint256 > &wtxids_fee_calculations)
Constructor for success case.
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
GlobalMutex g_best_block_mutex
Valid, transaction was already in the mempool.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances...
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
An in-memory indexed chain of blocks.
bool ShouldCheckBlockIndex() const
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx.
PackageMempoolAcceptResult(PackageValidationState state, std::map< uint256, MempoolAcceptResult > &&results)
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
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::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
static constexpr int DEFAULT_CHECKLEVEL
ResultType
Used to indicate the results of mempool validation.
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
std::chrono::time_point< std::chrono::steady_clock > m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
The coins cache is in immediate need of a flush.
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
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.
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops. ...
const TxValidationState m_state
Contains information about why the transaction failed.
std::map< uint256, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
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...
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
User-controlled performance and debug options.
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.
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...
const ResultType m_result_type
Result type.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
CChain m_chain
The current chain of blockheaders we consult and build on.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
Non-refcounted RAII wrapper for FILE*.
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Filesystem operations and types.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< uint256, MempoolAcceptResult > &&results)
Called by RandAddPeriodic()
const util::SignalInterrupt & m_interrupt
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
CVerifyDB(kernel::Notifications ¬ifications)
Transaction validation functions.
VersionBitsCache m_versionbitscache
Track versionbit status.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
bool IsUsable(const Chainstate *const cs) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
int64_t CAmount
Amount in satoshis (Can be negative)
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned...
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(SteadyClock::time_poin m_last_write)
Check warning conditions and do some notifications on new chain tip set.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
util::Result< void > InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(friend ChainstateManager
In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for iss...
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Chainstate stores and provides an API to update our local knowledge of the current best chain...
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) ...
std::chrono::steady_clock SteadyClock
Abstract view on the open txout dataset.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
Validation result for package mempool acceptance.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(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)
Find the best known block, and make it the tip of the block chain.
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...
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
kernel::Notifications & GetNotifications() const
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Holds various statistics on transactions within a chain.
const Consensus::Params & GetConsensus() const
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Try to make some progress towards making pindexMostWork the active block.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< uint256 > &wtxids_fee_calculations)
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
An output of a transaction.
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
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...
Parameters that influence chain consensus.
A base class defining functions for notifying about certain kernel events.
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Check if transaction will be final in the next block to be created.
MempoolAcceptResult AcceptToMemoryPool(Chainstate &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.
DisconnectedBlockTransactions.
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Validation result for a single transaction mempool acceptance.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
#define Assume(val)
Assume is the identity function.
256-bit unsigned big integer.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::optional< uint256 > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness...
BIP 9 allows multiple softforks to be deployed in parallel.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Closure representing one script verification Note that this stores references to the spending transac...
const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The base of the snapshot this chainstate was created from.
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.
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
std::condition_variable g_best_block_cv
const CChainParams & GetParams() const
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
PackageValidationState m_state
const CTransaction * ptxTo
const arith_uint256 & MinimumChainWork() const
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bool FatalError(kernel::Notifications ¬ifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage={})
kernel::Notifications & m_notifications
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
#define LOCKS_EXCLUDED(...)
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
static const signed int DEFAULT_CHECKBLOCKS
CCoinsView backed by the coin database (chainstate/)
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Application-specific storage settings.
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Holds configuration for use during UTXO snapshot load and validation.
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
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.
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
const std::optional< std::vector< uint256 > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
static MempoolAcceptResult Failure(TxValidationState state)
The basic transaction that is broadcasted on the network and contained in blocks. ...
Different type to mark Mutex at global scope.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsBIP30Unspendable(const CBlockIndex &block_index)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) ...
CCoinsView that adds a memory cache for transactions to another CCoinsView.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
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.
ScriptError GetScriptError() const
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
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...
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
CTxMemPool * GetMempool()
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
#define Assert(val)
Identity function.
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
bool IsBlockMutated(const CBlock &block, bool check_witness_root)
Check if a block has been mutated (with respect to its merkle root and witness commitments).
PrecomputedTransactionData * txdata