7 #ifndef BITCOIN_VALIDATION_H
8 #define BITCOIN_VALIDATION_H
10 #if defined(HAVE_CONFIG_H)
11 #include <config/bitcoin-config.h>
61 class SnapshotMetadata;
68 #define MIN_TRANSACTION_SIZE \
69 (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
166 bool _checkPow =
true,
167 bool _checkMerkleRoot =
true)
213 int nManualPruneHeight);
290 std::map<const TxId, const MempoolAcceptResult> &&results)
326 bool bypass_limits,
bool test_accept =
false)
357 auto newvalue = (remaining -= consumed);
358 return newvalue >= 0;
361 bool check() {
return remaining >= 0; }
419 bool sigCacheStore,
bool scriptCacheStore,
423 std::vector<CScriptCheck> *pvChecks)
432 bool sigCacheStore,
bool scriptCacheStore,
437 scriptCacheStore, txdata, nSigChecksOut,
438 nSigChecksTxLimiter,
nullptr,
nullptr);
473 bool useExistingLockPoints =
false);
502 unsigned int nInIn, uint32_t nFlagsIn,
bool cacheIn,
516 std::swap(
nIn, check.
nIn);
575 CCoinsView &coinsview,
int nCheckLevel,
int nCheckDepth)
613 CoinsViews(std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
655 std::atomic<int32_t> nBlockSequenceId{1};
657 int32_t nBlockReverseSequenceId = -1;
667 mutable std::atomic<bool> m_cached_finished_ibd{
false};
705 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
713 void InitCoinsDB(
size_t cache_size_bytes,
bool in_memory,
bool should_wipe,
714 std::string leveldb_name =
"chainstate");
718 void InitCoinsCache(
size_t cache_size_bytes)
726 return m_coins_views && m_coins_views->m_cacheview;
739 const std::optional<BlockHash> m_from_snapshot_blockhash{};
744 return m_from_snapshot_blockhash.has_value();
759 assert(m_coins_views->m_cacheview);
760 return *m_coins_views->m_cacheview.get();
766 return m_coins_views->m_dbview;
777 return m_coins_views->m_catcherview;
784 size_t m_coinsdb_cache_size_bytes{0};
787 size_t m_coinstip_cache_size_bytes{0};
791 bool ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
795 void LoadExternalBlockFile(
const Config &config, FILE *fileIn,
811 int nManualPruneHeight = 0);
814 void ForceFlushStateToDisk();
818 void PruneAndFlush();
836 std::shared_ptr<const
CBlock> pblock =
nullptr)
839 bool AcceptBlock(const
Config &config,
840 const std::shared_ptr<const
CBlock> &pblock,
886 void ClearAvalancheFinalizedBlock();
891 bool IsBlockAvalancheFinalized(const
CBlockIndex *pindex) const;
896 template <typename F>
899 template <typename F, typename C, typename AC>
901 C fChild, AC fAncestorWasChanged)
918 bool LoadGenesisBlock();
920 void PruneBlockIndexCandidates();
928 bool IsInitialBlockDownload() const;
940 void CheckBlockIndex();
956 GetCoinsCacheSizeState(
size_t max_coins_cache_size_bytes,
957 size_t max_mempool_size_bytes)
963 bool ActivateBestChainStep(const
Config &config,
966 const std::shared_ptr<const
CBlock> &pblock,
971 const std::shared_ptr<const
CBlock> &pblock,
979 FindMostWorkChain(std::vector<const
CBlockIndex *> &blocksToReconcile)
988 void UnparkBlockImpl(
CBlockIndex *pindex,
bool fClearChildren)
996 void CheckForkWarningConditionsOnNewFork(
CBlockIndex *pindexNewForkTip)
1007 return m_mempool ? &m_mempool->
cs :
nullptr;
1096 PopulateAndValidateSnapshot(
CChainState &snapshot_chainstate,
1144 int64_t m_total_coinstip_cache{0};
1148 int64_t m_total_coinsdb_cache{0};
1159 const std::optional<BlockHash> &snapshot_blockhash =
1179 [[nodiscard]]
bool ActivateSnapshot(
CAutoFile &coins_file,
1191 return m_blockman.m_block_index;
1196 bool IsSnapshotActive()
const;
1198 std::optional<BlockHash> SnapshotBlockhash()
const;
1202 return m_snapshot_validated;
1228 bool ProcessNewBlock(
const Config &config,
1229 const std::shared_ptr<const CBlock> &block,
1230 bool force_processing,
bool *new_block)
1247 bool ProcessNewBlockHeaders(
const Config &config,
1248 const std::vector<CBlockHeader> &block,
1262 ProcessTransaction(const
CTransactionRef &tx,
bool test_accept = false)
static constexpr Amount SATOSHI
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
uint64_t getExcessiveBlockSize() const
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
BlockValidationOptions(const Config &config)
bool shouldValidatePoW() const
uint64_t excessiveBlockSize
bool shouldValidateMerkleRoot() const
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.
CChainState stores and provides an API to update our local knowledge of the current best chain.
Mutex m_chainstate_mutex
The ChainState Mutex.
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
const CChainParams & m_params
Chain parameters for this chainstate.
CTxMemPool * GetMempool()
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
const CBlockIndex *m_avalancheFinalizedBlockIndex GUARDED_BY(cs_avalancheFinalizedBlockIndex)
The best block via avalanche voting.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
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)
CChain m_chain
The current chain of blockheaders we consult and build on.
Mutex cs_avalancheFinalizedBlockIndex
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
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: Amount / kB.
Closure representing one script verification.
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
ScriptError GetScriptError() const
ScriptExecutionMetrics GetScriptExecutionMetrics() const
TxSigCheckLimiter * pTxLimitSigChecks
ScriptExecutionMetrics metrics
void swap(CScriptCheck &check)
PrecomputedTransactionData txdata
const CTransaction * ptxTo
CheckInputsLimiter * pBlockLimitSigChecks
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.
Restore the UTXO in a Coin at a given COutPoint.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool VerifyDB(CChainState &chainstate, const Config &config, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
std::unique_ptr< CChainState > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
bool m_snapshot_validated GUARDED_BY(::cs_main)
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< BlockHash > &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.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
CBlockIndex * ActiveTip() const
CChain & ActiveChain() const
CBlockIndex *m_best_invalid GUARDED_BY(::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...
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
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...
static TxSigCheckLimiter getDisabled()
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
256-bit unsigned big integer.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
std::shared_ptr< const CTransaction > CTransactionRef
@ PERIODIC
Called by RandAddPeriodic()
std::string ToString(const T &t)
Locale-independent version of std::to_string.
static constexpr Amount zero()
Holds configuration for use during UTXO snapshot load and validation.
A BlockHash is a unqiue identifier for a block.
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 std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
const ResultType m_result_type
static MempoolAcceptResult Success(int64_t vsize, Amount fees)
Constructor for success case.
MempoolAcceptResult(ResultType result_type, int64_t vsize, Amount fees)
Generic constructor for success cases.
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
const TxValidationState m_state
ResultType
Used to indicate the results of mempool validation.
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Validation result for package mempool acceptance.
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
std::map< const TxId, const MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
PackageMempoolAcceptResult(PackageValidationState state, std::map< const TxId, const MempoolAcceptResult > &&results)
const PackageValidationState m_state
Precompute sighash midstate to avoid quadratic hashing.
Struct for holding cumulative results from executing a script or a sequence of scripts.
A TxId is the identifier of a transaction.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(boo TestBlockValidity)(BlockValidationState &state, const CChainParams ¶ms, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
static const bool DEFAULT_CHECKPOINTS_ENABLED
PackageMempoolAcceptResult ProcessNewPackage(const Config &config, CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
MempoolAcceptResult AcceptToMemoryPool(const Config &config, CChainState &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
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
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
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.
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 Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams ¶ms)
Return the expected assumeutxo value for a given height, if one exists.
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
SynchronizationState
Current sync state passed to tip changed callbacks.
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 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.
static constexpr bool DEFAULT_COINSTATSINDEX
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params ¶ms, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
RecursiveMutex cs_main
Global state.
static const int64_t DEFAULT_MAX_TIP_AGE
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static const signed int DEFAULT_CHECKBLOCKS
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
bool LoadMempool(const Config &config, CTxMemPool &pool, CChainState &active_chainstate)
Load the mempool from disk.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
static const bool DEFAULT_PEERBLOOMFILTERS
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