Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
251std::map<Wtxid, MempoolAcceptResult>&& results)252: m_state{state}, m_tx_results(std::move(results)) {}254/** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */255explicit PackageMempoolAcceptResult(const Wtxid& wtxid, const MempoolAcceptResult& result)256: m_tx_results{ {wtxid, result} } {}257};259/**260* Try to add a transaction to the mempool. This is an internal function and is exposed only for testing.261* Client code should use ChainstateManager::ProcessTransaction()262*263* @param[in] active_chainstate Reference to the active chainstate.264* @param[in] tx The transaction to submit for mempool acceptance.265* @param[in] accept_time The timestamp for adding the transaction to the mempool.266* It is also used to determine when the entry expires.267* @param[in] bypass_limits When true, don't enforce mempool fee and capacity limits,268* and set entry_sequence to zero.269* @param[in] test_accept When true, run validation checks but don't submit to mempool.270*271* @returns a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason.272*/273MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,274int64_t accept_time, bool bypass_limits, bool test_accept)275EXCLUSIVE_LOCKS_REQUIRED(cs_main);277/**278* Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details279* on package validation rules.280* @param[in] test_accept When true, run validation checks but don't submit to mempool.281* @param[in] client_maxfeerate If exceeded by an individual transaction, rest of (sub)package evaluation is aborted.282* Only for sanity checks against local submission of transactions.283* @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction.284* If a transaction fails, validation will exit early and some results may be missing. It is also285* possible for the package to be partially submitted.286*/287PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,288const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)289EXCLUSIVE_LOCKS_REQUIRED(cs_main);291/* Mempool validation helper functions */293/**294* Check if transaction will be final in the next block to be created.295*/296bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);298/**299* Calculate LockPoints required to check if transaction will be BIP68 final in the next block300* to be created on top of tip.301*302* @param[in] tip Chain tip for which tx sequence locks are calculated. For303* example, the tip of the current active chain.304* @param[in] coins_view Any CCoinsView that provides access to the relevant coins for305* checking sequence locks. For example, it can be a CCoinsViewCache306* that isn't connected to anything but contains all the relevant307* coins, or a CCoinsViewMemPool that is connected to the308* mempool and chainstate UTXO set. In the latter case, the caller309* is responsible for holding the appropriate locks to ensure that310* calls to GetCoin() return correct coins.311* @param[in] tx The transaction being evaluated.312*313* @returns The resulting height and time calculated and the hash of the block needed for314* calculation, or std::nullopt if there is an error.315*/316std::optional<LockPoints> CalculateLockPointsAtTip(317CBlockIndex* tip,318const CCoinsView& coins_view,319const CTransaction& tx);321/**322* Check if transaction will be BIP68 final in the next block to be created on top of tip.323* @param[in] tip Chain tip to check tx sequence locks against. For example,324* the tip of the current active chain.325* @param[in] lock_points LockPoints containing the height and time at which this326* transaction is final.327* Simulates calling SequenceLocks() with data from the tip passed in.328* The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false.329*/330bool CheckSequenceLocksAtTip(CBlockIndex* tip,331const LockPoints& lock_points);333/**334* Closure representing one script verification335* Note that this stores references to the spending transaction336*/337class CScriptCheck338{339private:340CTxOut m_tx_out;341const CTransaction *ptxTo;342unsigned int nIn;343script_verify_flags m_flags;344bool cacheStore;345PrecomputedTransactionData *txdata;346SignatureCache* m_signature_cache;348public:349CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, SignatureCache& signature_cache, unsigned int nInIn, script_verify_flags flags, bool cacheIn, PrecomputedTransactionData* txdataIn) :350m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), m_flags(flags), cacheStore(cacheIn), txdata(txdataIn), m_signature_cache(&signature_cache) { }352CScriptCheck(const CScriptCheck&) = delete;353CScriptCheck& operator=(const CScriptCheck&) = delete;354CScriptCheck(CScriptCheck&&) = default;355CScriptCheck& operator=(CScriptCheck&&) = default;357std::optional<std::pair<ScriptError, std::string>> operator()();358};360// CScriptCheck is used a lot in std::vector, make sure that's efficient361static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);362static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);363static_assert(std::is_nothrow_destructible_v<CScriptCheck>);365/**366* Convenience class for initializing and passing the script execution cache367* and signature cache.368*/369class ValidationCache370{371private:372//! Pre-initialized hasher to avoid having to recreate it for every hash calculation.373CSHA256 m_script_execution_cache_hasher;375public:376CuckooCache::cache<uint256, SignatureCacheHasher> m_script_execution_cache;377SignatureCache m_signature_cache;379ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes);381ValidationCache(const ValidationCache&) = delete;382ValidationCache& operator=(const ValidationCache&) = delete;384//! Return a copy of the pre-initialized hasher.385CSHA256 ScriptExecutionCacheHasher() const { return m_script_execution_cache_hasher; }386};388/** Functions for validating blocks and updating the block tree */390/** Context-independent validity checks */391bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);393/**394* Verify a block, including transactions.395*396* @param[in] block The block we want to process. Must connect to the397* current tip.398* @param[in] chainstate The chainstate to connect to.399* @param[in] check_pow perform proof-of-work check, nBits in the header400* is always checked401* @param[in] check_merkle_root check the merkle root402*403* @return Valid or Invalid state. This doesn't currently return an Error state,404* and shouldn't unless there is something wrong with the existing405* chainstate. (This is different from functions like AcceptBlock which406* can fail trying to save new data.)407*408* For signets the challenge verification is skipped when check_pow is false.409*/410BlockValidationState TestBlockValidity(411Chainstate& chainstate,412const CBlock& block,413bool check_pow,414bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main);416/** Check that the proof of work on each blockheader matches the value in nBits */417bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams);419/** Check if a block has been mutated (with respect to its merkle root and witness commitments). */420bool IsBlockMutated(const CBlock& block, bool check_witness_root);422/** Return the sum of the claimed work on a given set of headers. No verification of PoW is done. */423arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers);425enum class VerifyDBResult {426SUCCESS,427CORRUPTED_BLOCK_DB,428INTERRUPTED,429SKIPPED_L3_CHECKS,430SKIPPED_MISSING_BLOCKS,431};433/** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */434class CVerifyDB435{436private:437kernel::Notifications& m_notifications;439public:440explicit CVerifyDB(kernel::Notifications& notifications);441~CVerifyDB();442[[nodiscard]] VerifyDBResult VerifyDB(443Chainstate& chainstate,444const Consensus::Params& consensus_params,445CCoinsView& coinsview,446int nCheckLevel,447int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);448};450enum DisconnectResult451{452DISCONNECT_OK, // All good.453DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.454DISCONNECT_FAILED // Something else went wrong.455};457struct ConnectedBlock;459/** @see Chainstate::FlushStateToDisk */460inline constexpr std::array FlushStateModeNames{"NONE", "IF_NEEDED", "PERIODIC", "FORCE_FLUSH", "FORCE_SYNC"};461enum class FlushStateMode: uint8_t {462NONE,463IF_NEEDED,464PERIODIC,465FORCE_FLUSH,466FORCE_SYNC,467};469/**470* A convenience class for constructing the CCoinsView* hierarchy used471* to facilitate access to the UTXO set.472*473* This class consists of an arrangement of layered CCoinsView objects,474* preferring to store and retrieve coins in memory via `m_cacheview` but475* ultimately falling back on cache misses to the canonical store of UTXOs on476* disk, `m_dbview`.477*/478class CoinsViews {480public:481//! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.482//! All unspent coins reside in this store.483CCoinsViewDB m_dbview GUARDED_BY(cs_main);485//! This view wraps access to the leveldb instance and handles read errors gracefully.486CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);488//! This is the top layer of the cache hierarchy - it keeps as many coins in memory as489//! can fit per the dbcache setting.490std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);492//! Reused CoinsViewOverlay layered on top of m_cacheview and passed to ConnectBlock().493//! Reset between calls and flushed only on success, so invalid blocks don't pollute the underlying cache.494std::unique_ptr<CoinsViewOverlay> m_connect_block_view GUARDED_BY(cs_main);496//! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it497//! *does not* create a CCoinsViewCache instance by default. This is done separately because the498//! presence of the cache has implications on whether or not we're allowed to flush the cache's499//! state to disk, which should not be done until the health of the database is verified.500//!
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.