6 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
45 #include <type_traits>
58 class SnapshotMetadata;
64 class SignalInterrupt;
170 const std::vector<Wtxid>& wtxids_fee_calculations) {
178 const std::vector<Wtxid>& wtxids_fee_calculations) {
180 effective_feerate, wtxids_fee_calculations);
204 const std::vector<Wtxid>& wtxids_fee_calculations)
215 const std::vector<Wtxid>& wtxids_fee_calculations)
245 std::map<uint256, MempoolAcceptResult>&& results)
249 std::map<uint256, MempoolAcceptResult>&& results)
272 int64_t accept_time,
bool bypass_limits,
bool test_accept)
286 const Package& txns,
bool test_accept,
const std::optional<CFeeRate>& client_maxfeerate)
362 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
363 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
364 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
380 ValidationCache(
size_t script_execution_cache_bytes,
size_t signature_cache_bytes);
400 bool fCheckPOW =
true,
559 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
574 size_t cache_size_bytes,
577 fs::path leveldb_name = "chainstate");
588 return m_coins_views && m_coins_views->m_cacheview;
623 return *
Assert(m_coins_views->m_cacheview);
630 return Assert(m_coins_views)->m_dbview;
644 return Assert(m_coins_views)->m_catcherview;
654 size_t m_coinsdb_cache_size_bytes{0};
657 size_t m_coinstip_cache_size_bytes{0};
661 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
675 bool FlushStateToDisk(
678 int nManualPruneHeight = 0);
681 void ForceFlushStateToDisk();
685 void PruneAndFlush();
708 bool ActivateBestChain(
710 std::shared_ptr<const CBlock> pblock =
nullptr)
746 bool LoadGenesisBlock();
750 void PruneBlockIndexCandidates();
766 size_t max_coins_cache_size_bytes,
774 return m_mempool ? &m_mempool->
cs :
nullptr;
802 void MaybeUpdateMempoolForReorg(
811 SteadyClock::time_point m_last_flush{};
921 [[nodiscard]]
bool PopulateAndValidateSnapshot(
924 const
node::SnapshotMetadata& metadata);
933 bool AcceptBlockHeader(
951 return cs && !
cs->m_disabled;
979 std::function<void()> restart_indexes = std::function<void()>();
983 bool ShouldCheckBlockIndex()
const;
1024 mutable std::atomic<bool> m_cached_finished_ibd{
false};
1033 int32_t nBlockReverseSequenceId = -1;
1042 nBlockSequenceId = 1;
1043 nBlockReverseSequenceId = -1;
1073 int64_t m_total_coinstip_cache{0};
1077 int64_t m_total_coinsdb_cache{0};
1124 return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
1129 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() :
nullptr;
1135 return m_blockman.m_block_index;
1145 bool IsSnapshotActive()
const;
1147 std::optional<uint256> SnapshotBlockhash()
const;
1152 return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
1156 bool IsInitialBlockDownload()
const;
1187 std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent =
nullptr);
1213 bool ProcessNewBlock(
const std::shared_ptr<const CBlock>& block,
bool force_processing,
bool min_pow_checked,
bool* new_block)
LOCKS_EXCLUDED(
cs_main);
1268 void UpdateUncommittedBlockStructures(
CBlock& block, const
CBlockIndex* pindexPrev) const;
1271 std::vector<
unsigned char> GenerateCoinbaseCommitment(
CBlock& block, const
CBlockIndex* pindexPrev) const;
1277 void ReportHeadersPresync(const
arith_uint256& work, int64_t height, int64_t timestamp);
1317 std::pair<
int,
int> GetPruneRange(
1330 template<
typename DEP>
1336 template<
typename DEP>
1342 template<
typename DEP>
int64_t CAmount
Amount in satoshis (Can be negative)
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
static void CheckBlockIndex(benchmark::Bench &bench)
Non-refcounted RAII wrapper for FILE*.
The block chain is a tree shaped structure starting with the genesis block at the root,...
An in-memory indexed chain of blocks.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
CCoinsView backed by the coin database (chainstate/)
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Abstract view on the open txout dataset.
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
A hasher class for SHA-256.
Closure representing one script verification Note that this stores references to the spending transac...
CScriptCheck & operator=(CScriptCheck &&)=default
ScriptError GetScriptError() const
SignatureCache * m_signature_cache
CScriptCheck(const CScriptCheck &)=delete
PrecomputedTransactionData * txdata
CScriptCheck(CScriptCheck &&)=default
CScriptCheck & operator=(const CScriptCheck &)=delete
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, SignatureCache &signature_cache, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
const CTransaction * ptxTo
The basic transaction that is broadcasted on the network and contained in blocks.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
An output of a transaction.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
CVerifyDB(kernel::Notifications ¬ifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CTxMemPool * GetMempool()
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
CChain m_chain
The current chain of blockheaders we consult and build on.
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total
std::array< ThresholdConditionCache, VERSIONBITS_NUM_BITS > m_warningcache GUARDED_BY(::cs_main)
ValidationCache m_validation_cache
std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
int64_t GUARDED_BY(::cs_main) num_blocks_total
SteadyClock::duration GUARDED_BY(::cs_main) time_undo
SteadyClock::duration GUARDED_BY(::cs_main) time_index
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
const CChainParams & GetParams() const
const arith_uint256 & MinimumChainWork() const
SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect
std::thread m_thread_load
SteadyClock::duration GUARDED_BY(::cs_main) time_check
Timers and counters used for benchmarking validation in both background and active chainstates.
SteadyClock::duration GUARDED_BY(::cs_main) time_total
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
SteadyClock::duration GUARDED_BY(::cs_main) time_forks
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
const util::SignalInterrupt & m_interrupt
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
VersionBitsCache m_versionbitscache
Track versionbit status.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
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...
SteadyClock::duration GUARDED_BY(::cs_main) time_verify
const uint256 & AssumedValidBlock() const
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex())
The last header for which a headerTip notification was issued.
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
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...
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
kernel::Notifications & GetNotifications() const
SteadyClock::duration GUARDED_BY(::cs_main) time_connect
bool IsUsable(const Chainstate *const cs) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
const Consensus::Params & GetConsensus() const
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
SteadyClock::duration GUARDED_BY(::cs_main) time_flush
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
std::unique_ptr< CCoinsViewCache > m_cacheview GUARDED_BY(cs_main)
This is the top layer of the cache hierarchy - it keeps as many coins in memory as can fit per the db...
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main)
This view wraps access to the leveldb instance and handles read errors gracefully.
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
DisconnectedBlockTransactions.
Different type to mark Mutex at global scope.
Valid signature cache, to avoid doing expensive ECDSA signature checking twice for every transaction ...
Convenience class for initializing and passing the script execution cache and signature cache.
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
CuckooCache::cache< uint256, SignatureCacheHasher > m_script_execution_cache
ValidationCache(const ValidationCache &)=delete
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
SignatureCache m_signature_cache
ValidationCache & operator=(const ValidationCache &)=delete
BIP 9 allows multiple softforks to be deployed in parallel.
256-bit unsigned big integer.
A base class defining functions for notifying about certain kernel events.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
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.
Transaction validation functions.
Filesystem operations and types.
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
std::shared_ptr< const CTransaction > CTransactionRef
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
@ OK
The message verification was successful.
Holds configuration for use during UTXO snapshot load and validation.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Holds various statistics on transactions within a chain.
User-controlled performance and debug options.
Parameters that influence chain consensus.
Application-specific storage settings.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
const ResultType m_result_type
Result type.
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
const TxValidationState m_state
Contains information about why the transaction failed.
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
ResultType
Used to indicate the results of mempool validation.
@ DIFFERENT_WITNESS
Valid, transaction was already in the mempool.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for success case.
const std::optional< uint256 > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness.
const std::list< CTransactionRef > m_replaced_transactions
Mempool transactions replaced by the tx.
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for fee-related failure case.
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
Validation result for package mempool acceptance.
PackageValidationState m_state
PackageMempoolAcceptResult(PackageValidationState state, std::map< uint256, MempoolAcceptResult > &&results)
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
std::map< uint256, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< uint256, MempoolAcceptResult > &&results)
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
std::chrono::steady_clock SteadyClock
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
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).
GlobalMutex g_best_block_mutex
std::condition_variable g_best_block_cv
static constexpr int DEFAULT_CHECKLEVEL
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
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 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.
bool FatalError(kernel::Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
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...
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.
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.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
@ BASE_BLOCKHASH_MISMATCH
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
SynchronizationState
Current sync state passed to tip changed callbacks.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
bool IsBIP30Unspendable(const CBlockIndex &block_index)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
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.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &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)
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static const signed int DEFAULT_CHECKBLOCKS
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.