6 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
9 #if defined(HAVE_CONFIG_H)
114 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher>
BlockMap;
203 std::list<CTransactionRef>* plTxnReplaced,
271 std::swap(ptxTo, check.
ptxTo);
272 std::swap(m_tx_out, check.
m_tx_out);
273 std::swap(nIn, check.
nIn);
274 std::swap(nFlags, check.
nFlags);
277 std::swap(txdata, check.
txdata);
361 void FindFilesToPruneManual(std::set<int>& setFilesToPrune,
int nManualPruneHeight,
int chain_tip_height);
378 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight,
int chain_tip_height,
bool is_ibd);
420 std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
477 CoinsViews(std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
bool should_wipe);
515 int32_t nBlockSequenceId = 1;
517 int32_t nBlockReverseSequenceId = -1;
533 mutable std::atomic<bool> m_cached_finished_ibd{
false};
556 size_t cache_size_bytes,
559 std::string leveldb_name =
"chainstate");
568 return m_coins_views && m_coins_views->m_cacheview;
592 assert(m_coins_views->m_cacheview);
593 return *m_coins_views->m_cacheview.get();
599 return m_coins_views->m_dbview;
606 return m_coins_views->m_catcherview;
613 size_t m_coinsdb_cache_size_bytes{0};
616 size_t m_coinstip_cache_size_bytes{0};
620 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
634 bool FlushStateToDisk(
638 int nManualPruneHeight = 0);
641 void ForceFlushStateToDisk();
645 void PruneAndFlush();
686 void PruneBlockIndexCandidates();
691 bool IsInitialBlockDownload() const;
714 size_t max_coins_cache_size_bytes,
831 bool m_snapshot_validated{
false};
844 int64_t m_total_coinstip_cache{0};
848 int64_t m_total_coinsdb_cache{0};
865 CChain& ActiveChain()
const {
return ActiveChainstate().m_chain; }
871 return m_blockman.m_block_index;
874 bool IsSnapshotActive()
const;
883 bool IsBackgroundIBD(
CChainState* chainstate)
const;
914 bool ProcessNewBlock(
const CChainParams& chainparams,
const std::shared_ptr<const CBlock> pblock,
bool fForceProcessing,
bool* fNewBlock)
LOCKS_EXCLUDED(
cs_main);
int64_t CAmount
Amount in satoshis (Can be negative)
@ BLOCK_HAVE_DATA
full block available in blk*.dat
const CChainParams & Params()
Return the currently selected parameters.
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 * 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...
BlockMap m_block_index GUARDED_BY(cs_main)
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
bool LoadBlockIndex(const Consensus::Params &consensus_params, CBlockTreeDB &blocktree, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
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)
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_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...
The block chain is a tree shaped structure starting with the genesis block at the root,...
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Access to the block database (blocks/index/)
Undo information for a CBlock.
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.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
RecursiveMutex cs_nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
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 BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and a...
CTxMemPool & m_mempool
mempool that is kept in sync with the chain
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.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
CChain m_chain
The current chain of blockheaders we consult and build on.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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.
Check if transaction will be BIP 68 final in the next block to be created.
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 ...
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...
CChain & ValidatedChain() const
std::unique_ptr< CChainState > m_snapshot_chainstate
A chainstate initialized on the basis of a UTXO snapshot.
CBlockIndex * ActiveTip() const
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
CBlockIndex * ValidatedTip() const
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.
static uint64_t ReadLE64(const unsigned char *ptr)
Transaction validation functions.
boost::optional< T > Optional
Substitute for C++17 std::optional.
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.
Display status of an in-progress BIP9 softfork.
size_t operator()(const uint256 &hash) const
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.
BIP 9 allows multiple softforks to be deployed in parallel.
bool error(const char *fmt, const Args &... args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
ChainstateManager g_chainman
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
CBlockPolicyEstimator feeEstimator
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.
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
std::atomic_bool fReindex
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
static const bool DEFAULT_CHECKPOINTS_ENABLED
BIP9Stats VersionBitsTipStatistics(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip.
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
std::condition_variable g_best_block_cv
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
VersionBitsCache versionbitscache
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool fHavePruned
Pruning-related variables and constants.
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)
bool ActivateBestChain(BlockValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock=std::shared_ptr< const CBlock >())
Find the best known block, and make it the tip of the block chain.
std::atomic_bool fImporting
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool TestLockPointValidity(const LockPoints *lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
bool LoadMempool(CTxMemPool &pool)
Load the mempool from disk.
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 ChainActive().Tip() will not be pr...
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
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.
bool AcceptToMemoryPool(CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, bool test_accept=false, CAmount *fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
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 int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
static const char *const DEFAULT_BLOCKFILTERINDEX
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
void InitScriptExecutionCache()
Initializes the script-execution cache.
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
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.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
bool PreciousBlock(BlockValidationState &state, const CChainParams ¶ms, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
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.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, 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)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
Return transaction from the block at block_index.
bool fPruneMode
True if we're running in -prune mode.
@ 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 bool DEFAULT_FEEFILTER
Default for using fee filter.
bool CheckFinalTx(const CTransaction &tx, int flags=-1) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Transaction validation functions.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
static const int64_t DEFAULT_MAX_TIP_AGE
int VersionBitsTipStateSinceHeight(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147...
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
static const signed int DEFAULT_CHECKBLOCKS
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool InvalidateBlock(BlockValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
static const bool DEFAULT_TXINDEX
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.