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.
501//! All arguments forwarded onto CCoinsViewDB.502CoinsViews(DBParams db_params, CoinsViewOptions options);504//! Initialize the CCoinsViewCache member.505void InitCache(int32_t prevoutfetch_threads) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);506};508enum class CoinsCacheSizeState509{510//! The coins cache is in immediate need of a flush.511CRITICAL = 2,512//! The cache is at >= 90% capacity.513LARGE = 1,514OK = 0515};517constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept518{519// No periodic flush needed if at least this much space is free520constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES{int64_t(10_MiB)};521return std::max((total_space * 9) / 10,522total_space - MAX_BLOCK_COINSDB_USAGE_BYTES);523}525//! Chainstate assumeutxo validity.526enum class Assumeutxo {527//! Every block in the chain has been validated.528VALIDATED,529//! Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validated.530UNVALIDATED,531//! The assumeutxo snapshot failed validation.532INVALID,533};535/**536* Chainstate stores and provides an API to update our local knowledge of the537* current best chain.538*539* Eventually, the API here is targeted at being exposed externally as a540* consumable library, so any functions added must only call541* other class member functions, pure functions in other parts of the consensus542* library, callbacks via the validation interface, or read/write-to-disk543* functions (eventually this will also be via callbacks).544*545* Anything that is contingent on the current tip of the chain is stored here,546* whereas block information and metadata independent of the current tip is547* kept in `BlockManager`.548*/549class Chainstate550{551protected:552/**553* The ChainState Mutex554* A lock that must be held when modifying this ChainState - held in ActivateBestChain() and555* InvalidateBlock()556*/557Mutex m_chainstate_mutex;559//! Optional mempool that is kept in sync with the chain.560//! Only the active chainstate has a mempool.561CTxMemPool* m_mempool;563//! Manages the UTXO set, which is a reflection of the contents of `m_chain`.564std::unique_ptr<CoinsViews> m_coins_views;566//! Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)567mutable const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};569//! Target block for this chainstate. If this is not set, chainstate will570//! target the most-work, valid block. If this is set, ChainstateManager571//! considers this a "historical" chainstate since it will only contain old572//! blocks up to the target block, not newer blocks.573std::optional<uint256> m_target_blockhash GUARDED_BY(::cs_main);575//! Cached result of LookupBlockIndex(*m_target_blockhash)576mutable const CBlockIndex* m_cached_target_block GUARDED_BY(::cs_main){nullptr};578std::optional<const char*> m_last_script_check_reason_logged GUARDED_BY(::cs_main){};580public:581//! Reference to a BlockManager instance which itself is shared across all582//! Chainstate instances.583node::BlockManager& m_blockman;585//! The chainstate manager that owns this chainstate. The reference is586//! necessary so that this instance can check whether it is the active587//! chainstate within deeply nested method calls.588ChainstateManager& m_chainman;590explicit Chainstate(591CTxMemPool* mempool,592node::BlockManager& blockman,593ChainstateManager& chainman,594std::optional<uint256> from_snapshot_blockhash = std::nullopt);596//! Return path to chainstate leveldb directory.597fs::path StoragePath() const;599//! Return the current role of the chainstate. See `ChainstateManager`600//! documentation for a description of the different types of chainstates.601//!602//! @sa ChainstateRole603kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);605/**606* Initialize the CoinsViews UTXO set database management data structures. The in-memory607* cache is initialized separately.608*609* All parameters forwarded to CoinsViews.610*/611void InitCoinsDB(612size_t cache_size_bytes,613bool in_memory,614bool should_wipe);616//! Initialize the in-memory coins cache (to be done after the health of the on-disk database617//! is verified).618void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);620//! @returns whether or not the CoinsViews object has been fully initialized and we can621//! safely flush this object to disk.622bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)623{624AssertLockHeld(::cs_main);625return m_coins_views && m_coins_views->m_cacheview;626}628//! The current chain of blockheaders we consult and build on.629//! @see CChain, CBlockIndex.630CChain m_chain;632//! Assumeutxo state indicating whether all blocks in the chain were633//! validated, or if the chainstate is based on an assumeutxo snapshot and634//! the snapshot has not been validated.635Assumeutxo m_assumeutxo GUARDED_BY(::cs_main);637/**638* The blockhash which is the base of the snapshot this chainstate was created from.639*640* std::nullopt if this chainstate was not created from a snapshot.641*/642const std::optional<uint256> m_from_snapshot_blockhash;644//! Hash of the UTXO set at the target block, computed when the chainstate645//! reaches the target block, and null before then.646std::optional<AssumeutxoHash> m_target_utxohash GUARDED_BY(::cs_main);648/**649* The base of the snapshot this chainstate was created from.650*651* nullptr if this chainstate was not created from a snapshot.652*/653const CBlockIndex* SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);655//! Return target block which chainstate tip is expected to reach, if this656//! is a historic chainstate being used to validate a snapshot, or null if657//! chainstate targets the most-work block. Requires the block index to be658//! loaded, so prefer TargetBlockHash() when the block itself is not needed.659const CBlockIndex* TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);660//! Return hash of the target block, or nullopt if chainstate targets the661//! most-work block. Unlike TargetBlock(), does not require the block index662//! to be loaded.663std::optional<uint256> TargetBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)664{665AssertLockHeld(::cs_main);666return m_target_blockhash;667}668//! Set target block for this chainstate. If null, chainstate will target669//! the most-work valid block. If non-null chainstate will be a historic670//! chainstate and target the specified block.671void SetTargetBlock(CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);672//! Set target block for this chainstate using just a block hash. Useful673//! when the block database has not been loaded yet.674void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);676//! Return true if chainstate reached target block.677bool ReachedTarget() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)678{679const CBlockIndex* target_block{TargetBlock()};680assert(!target_block || target_block->GetAncestor(m_chain.Height()) == m_chain.Tip());681return target_block && target_block == m_chain.Tip();682}684/**685* The set of all CBlockIndex entries that have as much work as our current686* tip or more, and transaction data needed to be validated (with687* BLOCK_VALID_TRANSACTIONS for each block and its parents back to the688* genesis block or an assumeutxo snapshot block). Entries may be failed,689* though, and pruning nodes may be missing the data for the block.690*/691std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;693//! @returns A reference to the in-memory cache of the UTXO set.694CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)695{696AssertLockHeld(::cs_main);697Assert(m_coins_views);698return *Assert(m_coins_views->m_cacheview);699}701//! @returns A reference to the on-disk UTXO set database.702CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)703{704AssertLockHeld(::cs_main);705return Assert(m_coins_views)->m_dbview;706}708//! @returns A pointer to the mempool.709CTxMemPool* GetMempool()710{711return m_mempool;712}714//! @returns A reference to a wrapped view of the in-memory UTXO set that715//! handles disk read errors gracefully.716CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)717{718AssertLockHeld(::cs_main);719return Assert(m_coins_views)->m_catcherview;720}722//! Destructs all objects related to accessing the UTXO set.723void ResetCoinsViews() { m_coins_views.reset(); }725//! The cache size of the on-disk coins view.726size_t m_coinsdb_cache_size_bytes{0};728//! The cache size of the in-memory coins view.729size_t m_coinstip_cache_size_bytes{0};731//! Resize the CoinsViews caches dynamically and flush state to disk.732//! @returns true unless an error occurred during the flush.733bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)734EXCLUSIVE_LOCKS_REQUIRED(::cs_main);736/**737* Update the on-disk chain state.738* The caches and indexes are flushed depending on the mode we're called with739* if they're too large, if it's been a while since the last write,740* or always and in all cases if we're in prune mode and are deleting files.741*742* If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything743* besides checking if we need to prune.744*745* @returns true unless a system error occurred746*/747bool FlushStateToDisk(748BlockValidationState& state,749FlushStateMode mode,750int nManualPruneHeight = 0);
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.