7 #ifndef BITCOIN_VALIDATION_H 8 #define BITCOIN_VALIDATION_H 10 #if defined(HAVE_CONFIG_H) 11 #include <config/bitcoin-config.h> 65 #define MIN_TRANSACTION_SIZE \ 66 (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION)) 133 typedef std::unordered_map<BlockHash, CBlockIndex *, BlockHasher>
BlockMap;
190 bool _checkPow =
true,
191 bool _checkMerkleRoot =
true)
192 : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
193 checkMerkleRoot(_checkMerkleRoot) {}
250 std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
278 bool bypass_limits,
const Amount nAbsurdFee,
279 bool test_accept =
false)
294 auto newvalue = (remaining -= consumed);
295 return newvalue >= 0;
298 bool check() {
return remaining >= 0; }
356 bool sigCacheStore,
bool scriptCacheStore,
360 std::vector<CScriptCheck> *pvChecks)
369 bool sigCacheStore,
bool scriptCacheStore,
374 scriptCacheStore, txdata, nSigChecksOut,
375 nSigChecksTxLimiter,
nullptr,
nullptr);
437 bool useExistingLockPoints =
false)
462 : ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false),
464 pBlockLimitSigChecks(nullptr) {}
467 unsigned int nInIn, uint32_t nFlagsIn,
bool cacheIn,
471 : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
473 pTxLimitSigChecks(pTxLimitSigChecksIn),
474 pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
479 std::swap(ptxTo, check.
ptxTo);
480 std::swap(m_tx_out, check.
m_tx_out);
481 std::swap(nIn, check.
nIn);
482 std::swap(nFlags, check.
nFlags);
484 std::swap(error, check.
error);
485 std::swap(metrics, check.
metrics);
486 std::swap(txdata, check.
txdata);
555 extern std::unique_ptr<CCoinsViewCache>
pcoinsTip;
606 std::set<CBlockIndex *, CBlockIndexWorkComparator>
607 &block_index_candidates)
611 void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
614 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
617 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
626 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
650 std::unique_ptr<CCoinsViewCache> m_cacheview
GUARDED_BY(cs_main);
660 CoinsViews(std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
703 std::atomic<int32_t> nBlockSequenceId{1};
705 int32_t nBlockReverseSequenceId = -1;
715 mutable std::atomic<bool> m_cached_finished_ibd{
false};
742 void InitCoinsDB(
size_t cache_size_bytes,
bool in_memory,
bool should_wipe,
743 std::string leveldb_name =
"chainstate");
747 void InitCoinsCache(
size_t cache_size_bytes)
753 bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
754 return m_coins_views && m_coins_views->m_cacheview;
779 assert(m_coins_views->m_cacheview);
780 return *m_coins_views->m_cacheview.get();
789 EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
790 return m_coins_views->m_catcherview;
797 size_t m_coinsdb_cache_size_bytes{0};
800 size_t m_coinstip_cache_size_bytes{0};
804 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
820 int nManualPruneHeight = 0);
823 void ForceFlushStateToDisk();
827 void PruneAndFlush();
845 std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>())
848 bool AcceptBlock(
const Config &config,
849 const std::shared_ptr<const CBlock> &pblock,
867 EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.
cs);
875 LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
879 LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
887 LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
890 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
894 bool IsBlockFinalized(const
CBlockIndex *pindex) const
895 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
898 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
899 template <typename F>
901 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
902 template <typename F, typename C, typename AC>
904 C fChild, AC fAncestorWasChanged)
905 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
907 void UnparkBlockImpl(
CBlockIndex *pindex,
bool fClearChildren)
908 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
914 void PruneBlockIndexCandidates();
922 bool IsInitialBlockDownload() const;
935 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
941 EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
944 const
CTxMemPool &tx_pool,
size_t max_coins_cache_size_bytes,
945 size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
947 std::
string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
950 bool ActivateBestChainStep(const
Config &config,
953 const
std::shared_ptr<const
CBlock> &pblock,
955 EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs);
958 const
std::shared_ptr<const
CBlock> &pblock,
961 EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs);
964 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
966 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
967 CBlockIndex *FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
970 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
973 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
977 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
980 EXCLUSIVE_LOCKS_REQUIRED(m_cs_chainstate);
995 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
999 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1037 class ChainstateManager {
1086 bool m_snapshot_validated{
false};
1099 int64_t m_total_coinstip_cache{0};
1103 int64_t m_total_coinsdb_cache{0};
1124 return m_blockman.m_block_index;
1127 bool IsSnapshotActive()
const;
1129 std::optional<BlockHash> SnapshotBlockhash()
const;
1136 bool IsBackgroundIBD(
CChainState *chainstate)
const;
1170 bool ProcessNewBlock(
const Config &config,
1171 const std::shared_ptr<const CBlock> pblock,
1172 bool fForceProcessing,
bool *fNewBlock)
1189 bool ProcessNewBlockHeaders(
const Config &config,
1190 const std::vector<CBlockHeader> &block,
1196 void PruneOneBlockFile(
const int fileNumber)
1233 extern std::unique_ptr<CBlockTreeDB>
pblocktree;
1261 #endif // BITCOIN_VALIDATION_H std::shared_ptr< const CTransaction > CTransactionRef
bool shouldValidatePoW() const
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
Display status of an in-progress BIP9 softfork.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download...
static constexpr Amount zero()
SynchronizationState
Current sync state passed to tip changed callbacks.
bool shouldValidateMerkleRoot() const
std::unordered_map< BlockHash, CBlockIndex *, BlockHasher > BlockMap
CChain m_chain
The current chain of blockheaders we consult and build on.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
uint64_t getExcessiveBlockSize() const
void swap(CScriptCheck &check)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
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.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block.
static const int64_t DEFAULT_MAX_TIP_AGE
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
Inv(ventory) message data.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
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...
Precompute sighash midstate to avoid quadratic hashing.
CChain & ValidatedChain() const
uint64_t excessiveBlockSize
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp=nullptr, bool useExistingLockPoints=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check if transaction will be BIP 68 final in the next block to be created.
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
CChainState stores and provides an API to update our local knowledge of the current best chain...
static constexpr Amount SATOSHI
bool AcceptToMemoryPool(const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, bool bypass_limits, const Amount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
void LoadExternalBlockFile(const Config &config, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
bool LoadMempool(const Config &config, CTxMemPool &pool)
Load the mempool from disk.
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...
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Called by RandAddPeriodic()
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CheckInputsLimiter * pBlockLimitSigChecks
std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
static const int64_t DEFAULT_MIN_FINALIZATION_DELAY
Default for -finalizationdelay This is the minimum time between a block header reception and the bloc...
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and a...
static const Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Struct for holding cumulative results from executing a script or a sequence of scripts.
static const bool DEFAULT_PEERBLOOMFILTERS
static TxSigCheckLimiter getDisabled()
bool ContextualCheckTransactionForCurrentBlock(const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state, int flags=-1)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Access to the block database (blocks/index/)
Abstract view on the open txout dataset.
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
bool fHavePruned
Pruning-related variables and constants.
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
bool ActivateBestChain(const Config &config, BlockValidationState &state, 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.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
bool TestLockPointValidity(const LockPoints *lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain. ...
ThresholdState VersionBitsBlockState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos, const CBlockIndex *pindex)
Get the BIP9 state for a given deployment at a given block.
Holds various statistics on transactions within a chain.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params ¶ms, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
ChainstateManager g_chainman
bool PreciousBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
An output of a transaction.
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
std::atomic_bool fImporting
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Parameters that influence chain consensus.
static const char *const DEFAULT_BLOCKFILTERINDEX
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
256-bit unsigned big integer.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
PrecomputedTransactionData txdata
Closure representing one script verification.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
std::condition_variable g_best_block_cv
std::atomic_bool fReindex
const CTransaction * ptxTo
static const bool DEFAULT_CHECKPOINTS_ENABLED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
#define LOCKS_EXCLUDED(...)
RecursiveMutex cs_main
Global state.
A BlockHash is a unqiue identifier for a block.
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
Undo information for a CBlock.
std::unique_ptr< CChainState > m_snapshot_chainstate
A chainstate initialized on the basis of a UTXO snapshot.
static const signed int DEFAULT_CHECKBLOCKS
Restore the UTXO in a Coin at a given COutPoint.
A TxId is the identifier of a transaction.
ChainstateManager g_chainman GUARDED_BY(::cs_main)
DEPRECATED! Please use node.chainman instead.
CCoinsView backed by the coin database (chainstate/)
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
CChainState &InitializeChainstate(const BlockHash &snapshot_blockhash=BlockHash()) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * > GetAll()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
Fee rate in satoshis per kilobyte: Amount / kB.
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
static const int DEFAULT_MAX_REORG_DEPTH
Default for -maxreorgdepth.
CBlockIndex * ValidatedTip() const
bool GetTransaction(const TxId &txid, CTransactionRef &txOut, const Consensus::Params ¶ms, BlockHash &hashBlock, const CBlockIndex *const blockIndex=nullptr)
Retrieve a transaction (from memory pool, or from disk, if possible).
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
bool TestBlockValidity(BlockValidationState &state, const CChainParams ¶ms, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
The basic transaction that is broadcasted on the network and contained in blocks. ...
ScriptExecutionMetrics GetScriptExecutionMetrics() const
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
bool fPruneMode
True if we're running in -prune mode.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev...
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
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 LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
ScriptExecutionMetrics metrics
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...
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
ScriptError GetScriptError() const
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
TxSigCheckLimiter * pTxLimitSigChecks
bool error(const char *fmt, const Args &... args)
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
static const bool DEFAULT_TXINDEX
void UnloadBlockIndex()
Unload database information.
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
CChain & ActiveChain() const
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
static const unsigned int DEFAULT_CHECKLEVEL
BlockMap & BlockIndex()
Please prefer the identical ChainstateManager::BlockIndex.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
CBlockIndex * ActiveTip() const
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(