6#ifndef BITCOIN_VALIDATION_H
7#define BITCOIN_VALIDATION_H
9#if defined(HAVE_CONFIG_H)
100typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher>
BlockMap;
200 std::map<const uint256, const MempoolAcceptResult>&& results)
229 const
Package& txns,
bool test_accept)
272 bool useExistingLockPoints = false);
297 std::swap(ptxTo, check.
ptxTo);
298 std::swap(m_tx_out, check.
m_tx_out);
299 std::swap(nIn, check.
nIn);
300 std::swap(nFlags, check.
nFlags);
303 std::swap(txdata, check.
txdata);
323 bool fCheckPOW =
true,
380 void FindFilesToPruneManual(std::set<int>& setFilesToPrune,
int nManualPruneHeight,
int chain_tip_height);
397 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight,
int chain_tip_height,
int prune_height,
bool is_ibd);
442 std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
514 CoinsViews(std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
bool should_wipe);
553 int32_t nBlockReverseSequenceId = -1;
569 mutable std::atomic<bool> m_cached_finished_ibd{
false};
594 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
603 size_t cache_size_bytes,
606 std::string leveldb_name =
"chainstate");
615 return m_coins_views && m_coins_views->m_cacheview;
640 assert(m_coins_views->m_cacheview);
641 return *m_coins_views->m_cacheview.get();
647 return m_coins_views->m_dbview;
654 return m_coins_views->m_catcherview;
661 size_t m_coinsdb_cache_size_bytes{0};
664 size_t m_coinstip_cache_size_bytes{0};
668 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
672 void LoadExternalBlockFile(FILE* fileIn,
FlatFilePos* dbp =
nullptr);
685 bool FlushStateToDisk(
688 int nManualPruneHeight = 0);
691 void ForceFlushStateToDisk();
695 void PruneAndFlush();
712 bool ActivateBestChain(
743 bool LoadGenesisBlock();
745 void PruneBlockIndexCandidates();
750 bool IsInitialBlockDownload() const;
757 void CheckBlockIndex();
771 size_t max_coins_cache_size_bytes,
792 return m_mempool ? &m_mempool->
cs :
nullptr;
808 void MaybeUpdateMempoolForReorg(
890 bool m_snapshot_validated{
false};
893 [[nodiscard]]
bool PopulateAndValidateSnapshot(
906 int64_t m_total_coinstip_cache{0};
910 int64_t m_total_coinsdb_cache{0};
921 const std::optional<uint256>& snapshot_blockhash = std::nullopt)
940 [[nodiscard]]
bool ActivateSnapshot(
951 return m_blockman.m_block_index;
956 bool IsSnapshotActive()
const;
958 std::optional<uint256> SnapshotBlockhash()
const;
982 bool ProcessNewBlock(
const CChainParams& chainparams,
const std::shared_ptr<const CBlock>& block,
bool force_processing,
bool* new_block)
LOCKS_EXCLUDED(
cs_main);
int64_t CAmount
Amount in satoshis (Can be negative)
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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...
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
BlockMap m_block_index GUARDED_BY(cs_main)
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
std::unique_ptr< CBlockTreeDB > m_block_tree_db GUARDED_BY(::cs_main)
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...
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
bool LoadBlockIndexDB(std::set< CBlockIndex *, CBlockIndexWorkComparator > &setBlockIndexCandidates) EXCLUSIVE_LOCKS_REQUIRED(boo LoadBlockIndex)(const Consensus::Params &consensus_params, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
int GetSpendHeight(const CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the spend height, which is one more than the inputs.GetBestBlock().
std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block between the parameter chain and a locator.
Non-refcounted RAII wrapper for FILE*.
The block chain is a tree shaped structure starting with the genesis block at the root,...
Access to the block database (blocks/index/)
An in-memory indexed chain of blocks.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
CChainState stores and provides an API to update our local knowledge of the current best chain.
const CChainParams & m_params
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(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...
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
CChain m_chain
The current chain of blockheaders we consult and build on.
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
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 kilobyte: CAmount / kB.
Closure representing one script verification Note that this stores references to the spending transac...
ScriptError GetScriptError() const
PrecomputedTransactionData * txdata
void swap(CScriptCheck &check)
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, 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.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
BlockManager m_blockman GUARDED_BY(::cs_main)
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
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.
std::unique_ptr< CChainState > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
CChain & ActiveChain() const
CBlockIndex * ActiveTip() const
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
std::unique_ptr< CChainState > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
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(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...
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
256-bit unsigned big integer.
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Transaction validation functions.
FILE * fopen(const fs::path &p, const char *mode)
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
std::shared_ptr< const CTransaction > CTransactionRef
@ PERIODIC
Called by RandAddPeriodic()
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Holds configuration for use during UTXO snapshot load and validation.
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
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.
Parameters that influence chain consensus.
Validation result for a single transaction mempool acceptance.
const ResultType m_result_type
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
const TxValidationState m_state
ResultType
Used to indicate the results of mempool validation.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Constructor for success case.
Validation result for package mempool acceptance.
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
const PackageValidationState m_state
bool error(const char *fmt, const Args &... args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
static const bool DEFAULT_CHECKPOINTS_ENABLED
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)
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.
std::condition_variable g_best_block_cv
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
std::function< FILE *(const fs::path &, const char *)> FopenFn
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
static const unsigned int DEFAULT_CHECKLEVEL
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
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...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
SynchronizationState
Current sync state passed to tip changed callbacks.
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
static const char *const DEFAULT_BLOCKFILTERINDEX
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
void InitScriptExecutionCache()
Initializes the script-execution cache.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
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.
static constexpr bool DEFAULT_COINSTATSINDEX
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function=fsbridge::fopen, bool skip_file_commit=false)
Dump the mempool to disk.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
static const int64_t DEFAULT_MAX_TIP_AGE
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
static const signed int DEFAULT_CHECKBLOCKS
bool LoadMempool(CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function=fsbridge::fopen)
Load the mempool from disk.
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams ¶ms)
Return the expected assumeutxo value for a given height, if one exists.
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Atomically test acceptance of a package.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
bool TestLockPointValidity(CChain &active_chain, const LockPoints *lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(Try to) add a transaction to the memory pool.
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...
static const bool DEFAULT_TXINDEX
bool CheckFinalTx(const CBlockIndex *active_chain_tip, const CTransaction &tx, int flags=-1) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Transaction validation functions.