Inside Bitcoin
Opening the selected file…
Inside Bitcoin
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.
752//! Flush all changes to disk.753void ForceFlushStateToDisk(bool wipe_cache = true);755//! Prune blockfiles from the disk if necessary and then flush chainstate changes756//! if we pruned.757void PruneAndFlush();759/**760* Find the best known block, and make it the tip of the block chain. The761* result is either failure or an activated best chain. pblock is either762* nullptr or a pointer to a block that is already loaded (to avoid loading763* it again from disk).764*765* ActivateBestChain is split into steps (see ActivateBestChainStep) so that766* we avoid holding cs_main for an extended period of time; the length of this767* call may be quite long during reindexing or a substantial reorg.768*769* May not be called with cs_main held. May not be called in a770* validationinterface callback.771*772* Note that if this is called while a snapshot chainstate is active, and if773* it is called on a validated chainstate whose tip has reached the base774* block of the snapshot, its execution will take *MINUTES* while it hashes775* the UTXO set to verify the assumeutxo value the snapshot was activated776* with. `cs_main` will be held during this time.777*778* @returns true unless a system error occurred779*/780bool ActivateBestChain(781BlockValidationState& state,782std::shared_ptr<const CBlock> pblock = nullptr)783EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)784LOCKS_EXCLUDED(::cs_main);786// Block (dis)connection on a given view:787DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)788EXCLUSIVE_LOCKS_REQUIRED(::cs_main);789bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,790CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);792// Apply the effects of a block disconnection on the UTXO set.793bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);795// Manual block validity manipulation:796/** Mark a block as precious and reorganize.797*798* May not be called in a validationinterface callback.799*/800bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)801EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)802LOCKS_EXCLUDED(::cs_main);804/** Mark a block as invalid. */805bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)806EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)807LOCKS_EXCLUDED(::cs_main);809/** Set invalidity status to all descendants of a block */810void SetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);812/** Remove invalidity status from a block, its descendants and ancestors and reconsider them for activation */813void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);815/** Replay blocks that aren't fully applied to the database. */816bool ReplayBlocks();818/** Whether the chain state needs to be redownloaded due to lack of witness data */819[[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);821/** Add a block to the candidate set if it has as much work as the current tip. */822void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);824void PruneBlockIndexCandidates();826void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);828/** Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices. */829void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);831/** Find the last common block of this chain and a locator. */832const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);834/** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */835bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);837//! Dictates whether we need to flush the cache to disk or not.838//!839//! @return the state of the size of the coins cache.840CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);842CoinsCacheSizeState GetCoinsCacheSizeState(843size_t max_coins_cache_size_bytes,844size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);846std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);848//! Get the last block that was flushed to disk.849const CBlockIndex* GetLastFlushedBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_last_flushed_block; }851//! Indirection necessary to make lock annotations work with an optional mempool.852RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)853{854return m_mempool ? &m_mempool->cs : nullptr;855}857//! Return the [start, end] (inclusive) of block heights we can prune.858//!859//! start > end is possible, meaning no blocks can be pruned.860std::pair<int, int> GetPruneRange(int last_height_can_prune) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);862protected:863bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex& index_most_work, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, std::vector<ConnectedBlock>& connected_blocks) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);864bool ConnectTip(865BlockValidationState& state,866CBlockIndex* pindexNew,867std::shared_ptr<const CBlock> block_to_connect,868std::vector<ConnectedBlock>& connected_blocks,869DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);871void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);872CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);874bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);876void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);877void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);879/**880* Make mempool consistent after a reorg, by re-adding or recursively erasing881* disconnected block transactions from the mempool, and also removing any882* other transactions from the mempool that are no longer valid given the new883* tip/height.884*885* Note: we assume that disconnectpool only contains transactions that are NOT886* confirmed in the current chain nor already in the mempool (otherwise,887* in-mempool descendants of such transactions would be removed).888*889* Passing fAddToMempool=false will skip trying to add the transactions back,890* and instead just erase from the mempool as needed.891*/892void MaybeUpdateMempoolForReorg(893DisconnectedBlockTransactions& disconnectpool,894bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);896/** Check warning conditions and do some notifications on new chain tip set. */897void UpdateTip(const CBlockIndex* pindexNew)898EXCLUSIVE_LOCKS_REQUIRED(::cs_main);900NodeClock::time_point m_next_write{NodeClock::time_point::max()};901const CBlockIndex* m_last_flushed_block GUARDED_BY(::cs_main){nullptr};903/**904* In case of an invalid snapshot, rename the coins leveldb directory so905* that it can be examined for issue diagnosis.906*/907[[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);909friend ChainstateManager;910};912enum class SnapshotCompletionResult {913SUCCESS,914SKIPPED,916// Expected assumeutxo configuration data is not found for the height of the917// base block.918MISSING_CHAINPARAMS,920// Failed to generate UTXO statistics (to check UTXO set hash) for the921// validated chainstate.922STATS_FAILED,924// The UTXO set hash of the validated chainstate does not match the one925// expected by assumeutxo chainparams.926HASH_MISMATCH,927};929/**930* Interface for managing multiple \ref Chainstate objects, where each931* chainstate is associated with chainstate* subdirectory in the data directory932* and contains a database of UTXOs existing at a different point in history.933* (See \ref Chainstate class for more information.)934*935* Normally there is exactly one Chainstate, which contains the UTXO set of936* chain tip if syncing is completed, or the UTXO set the most recent validated937* block if the initial sync is still in progress.938*939* However, if an assumeutxo snapshot is loaded before syncing is completed,940* there will be two chainstates. The original fully validated chainstate will941* continue to exist and download new blocks in the background. But the new942* snapshot which is loaded will become a second chainstate. The second943* chainstate will be used as the chain tip for the wallet and RPCs even though944* it is only assumed to be valid. When the initial chainstate catches up to the945* snapshot height and confirms that the assumeutxo snapshot is actually valid,946* the second chainstate will be marked validated and become the only chainstate947* again.948*/949class ChainstateManager950{951private:953/** The last header for which a headerTip notification was issued. */954CBlockIndex* m_last_notified_header GUARDED_BY(GetMutex()){nullptr};956bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex());958//! Internal helper for ActivateSnapshot().959//!960//! De-serialization of a snapshot that is created with961//! the dumptxoutset RPC.962//! To reduce space the serialization format of the snapshot avoids963//! duplication of tx hashes. The code takes advantage of the guarantee by964//! leveldb that keys are lexicographically sorted.965[[nodiscard]] util::Result<void> PopulateAndValidateSnapshot(966Chainstate& snapshot_chainstate,967AutoFile& coins_file,968const node::SnapshotMetadata& metadata);970/**971* If a block header hasn't already been seen, call CheckBlockHeader on it, ensure972* that it doesn't descend from an invalid block, and then add it to m_block_index.973* Caller must set min_pow_checked=true in order to add a new header to the974* block index (permanent memory storage), indicating that the header is975* known to be part of a sufficiently high-work chain (anti-dos check).976*/977bool AcceptBlockHeader(978const CBlockHeader& block,979BlockValidationState& state,980CBlockIndex** ppindex,981bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);982friend Chainstate;984/** Most recent headers presync progress update, for rate-limiting. */985MockableSteadyClock::time_point m_last_presync_update GUARDED_BY(GetMutex()){};987//! A queue for script verifications that have to be performed by worker threads.988CCheckQueue<CScriptCheck> m_script_check_queue;990//! Timers and counters used for benchmarking validation in both background991//! and active chainstates.992SteadyClock::duration GUARDED_BY(::cs_main) time_check{};993SteadyClock::duration GUARDED_BY(::cs_main) time_forks{};994SteadyClock::duration GUARDED_BY(::cs_main) time_connect{};995SteadyClock::duration GUARDED_BY(::cs_main) time_verify{};996SteadyClock::duration GUARDED_BY(::cs_main) time_undo{};997SteadyClock::duration GUARDED_BY(::cs_main) time_index{};998SteadyClock::duration GUARDED_BY(::cs_main) time_total{};999int64_t GUARDED_BY(::cs_main) num_blocks_total{0};1000SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{};
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.