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.
1001SteadyClock::duration GUARDED_BY(::cs_main) time_flush{};1002SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{};1003SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{};1005protected:1006CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};1008public:1009using Options = kernel::ChainstateManagerOpts;1011explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);1013//! Function to restart active indexes; set dynamically to avoid a circular1014//! dependency on `base/index.cpp`.1015std::function<void()> snapshot_download_completed = std::function<void()>();1017const CChainParams& GetParams() const { return m_options.chainparams; }1018const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }1019bool ShouldCheckBlockIndex() const;1020const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }1021const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }1022kernel::Notifications& GetNotifications() const { return m_options.notifications; };1024/**1025* Make various assertions about the state of the block index.1026*1027* By default this only executes fully when using the Regtest chain; see: m_options.check_block_index.1028*/1029void CheckBlockIndex() const;1031/**1032* Alias for ::cs_main.1033* Should be used in new code to make it easier to make ::cs_main a member1034* of this class.1035* Generally, methods of this class should be annotated to require this1036* mutex. This will make calling code more verbose, but also help to:1037* - Clarify that the method will acquire a mutex that heavily affects1038* overall performance.1039* - Force call sites to think how long they need to acquire the mutex to1040* get consistent results.1041*/1042RecursiveMutex& GetMutex() const LOCK_RETURNED(::cs_main) { return ::cs_main; }1044const util::SignalInterrupt& m_interrupt;1045const Options m_options;1046//! A single BlockManager instance is shared across each constructed1047//! chainstate to avoid duplicating block metadata.1048node::BlockManager m_blockman;1050ValidationCache m_validation_cache;1052/**1053* Whether initial block download (IBD) is ongoing.1054*1055* This value is used for lock-free IBD checks, and latches from true to1056* false once block loading has finished and the current chain tip has1057* enough work and is recent.1058*/1059std::atomic_bool m_cached_is_ibd{true};1061/**1062* Every received block is assigned a unique and increasing identifier, so we1063* know which one to give priority in case of a fork.1064*/1065/** Blocks loaded from disk are assigned id SEQ_ID_INIT_FROM_DISK{1}1066* (SEQ_ID_BEST_CHAIN_FROM_DISK{0} if they belong to the best chain loaded from disk),1067* so start the counter after that. **/1068int32_t nBlockSequenceId GUARDED_BY(::cs_main) = SEQ_ID_INIT_FROM_DISK + 1;1069/** Decreasing counter (used by subsequent preciousblock calls). */1070int32_t nBlockReverseSequenceId = -1;1071/** chainwork for the last block that preciousblock has been applied to. */1072arith_uint256 nLastPreciousChainwork = 0;1074// Reset the memory-only sequence counters we use to track block arrival1075// (used by tests to reset state)1076void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)1077{1078AssertLockHeld(::cs_main);1079nBlockSequenceId = SEQ_ID_INIT_FROM_DISK + 1;1080nBlockReverseSequenceId = -1;1081}1084/** Best header we've seen so far for which the block is not known to be invalid1085(used, among others, for getheaders queries' starting points).1086In case of multiple best headers with the same work, it could point to any1087because CBlockIndexWorkComparator tiebreaker rules are not applied. */1088CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};1090//! The total number of bytes available for us to use across all in-memory1091//! coins caches. This will be split somehow across chainstates.1092size_t m_total_coinstip_cache{0};1093//1094//! The total number of bytes available for us to use across all leveldb1095//! coins databases. This will be split somehow across chainstates.1096size_t m_total_coinsdb_cache{0};1098/// Ensures a genesis block is in the block tree, possibly writing one to disk.1099[[nodiscard]] bool LoadGenesisBlock();1101//! Instantiate a new chainstate.1102//!1103//! @param[in] mempool The mempool to pass to the chainstate1104// constructor1105Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);1107//! Construct and activate a Chainstate on the basis of UTXO snapshot data.1108//!1109//! Steps:1110//!1111//! - Initialize an unused Chainstate.1112//! - Load its `CoinsViews` contents from `coins_file`.1113//! - Verify that the hash of the resulting coinsdb matches the expected hash1114//! per assumeutxo chain parameters.1115//! - Wait for our headers chain to include the base block of the snapshot.1116//! - "Fast forward" the tip of the new chainstate to the base of the snapshot.1117//! - Construct the new Chainstate and add it to m_chainstates.1118[[nodiscard]] util::Result<CBlockIndex*> ActivateSnapshot(1119AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);1121//! Try to validate an assumeutxo snapshot by using a validated historical1122//! chainstate targeted at the snapshot block. When the target block is1123//! reached, the UTXO hash is computed and saved to1124//! `validated_cs.m_target_utxohash`, and `unvalidated_cs.m_assumeutxo` will1125//! be updated from UNVALIDATED to either VALIDATED or INVALID depending on1126//! whether the hash matches. The INVALID case should not happen in practice1127//! because the software should refuse to load unrecognized snapshots, but1128//! if it does happen, it is a fatal error.1129SnapshotCompletionResult MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);1131//! Return current chainstate targeting the most-work, network tip.1132Chainstate& CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())1133{1134for (auto& cs : m_chainstates) {1135if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && !cs->TargetBlockHash()) return *cs;1136}1137abort();1138}1140//! Return historical chainstate targeting a specific block, if any.1141Chainstate* HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())1142{1143for (auto& cs : m_chainstates) {1144if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && cs->TargetBlockHash() && !cs->m_target_utxohash) return cs.get();1145}1146return nullptr;1147}1149//! Return fully validated chainstate that should be used for indexing, to1150//! support indexes that need to index blocks in order and can't start from1151//! the snapshot block.1152Chainstate& ValidatedChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())1153{1154for (auto* cs : {&CurrentChainstate(), HistoricalChainstate()}) {1155if (cs && cs->m_assumeutxo == Assumeutxo::VALIDATED) return *cs;1156}1157abort();1158}1160//! Remove a chainstate.1161std::unique_ptr<Chainstate> RemoveChainstate(Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())1162{1163auto it{std::find_if(m_chainstates.begin(), m_chainstates.end(), [&](auto& cs) { return cs.get() == &chainstate; })};1164if (it != m_chainstates.end()) {1165auto ret{std::move(*it)};1166m_chainstates.erase(it);1167return ret;1168}1169return nullptr;1170}1172//! Alternatives to CurrentChainstate() used by older code to query latest1173//! chainstate information without locking cs_main. Newer code should avoid1174//! querying ChainstateManager and use Chainstate objects directly, or1175//! should use CurrentChainstate() instead.1176//! @{1177Chainstate& ActiveChainstate() const;1178CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }1179int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }1180CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }1181//! @}1183/**1184* Update and possibly latch the IBD status.1185*1186* If block loading has finished and the current chain tip has enough work1187* and is recent, set `m_cached_is_ibd` to false. This function never sets1188* the flag back to true.1189*1190* This should be called after operations that may affect IBD exit1191* conditions (e.g. after updating the active chain tip, or after1192* `ImportBlocks()` finishes).1193*/1194void UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main);1196node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)1197{1198AssertLockHeld(::cs_main);1199return m_blockman.m_block_index;1200}1202/**1203* Track versionbit status1204*/1205mutable VersionBitsCache m_versionbitscache;1207/** Check whether we are doing an initial block download (synchronizing from disk or network) */1208bool IsInitialBlockDownload() const noexcept;1210/** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).1211* This is also the case in the assumeutxo context, meaning that the progress reported for1212* the snapshot chainstate may suggest that all historical blocks have already been verified1213* even though that may not actually be the case. */1214double GuessVerificationProgress(const CBlockIndex* pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());1216/** Guess background verification progress in case assume-utxo was used (as a fraction between 0.0=genesis and 1.0=snapshot blocks). */1217double GetBackgroundVerificationProgress(const CBlockIndex& pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());1219/**1220* Import blocks from an external file1221*1222* During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat).1223* It reads all blocks contained in the given file and attempts to process them (add them to the1224* block index). The blocks may be out of order within each file and across files. Often this1225* function reads a block but finds that its parent hasn't been read yet, so the block can't be1226* processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is1227* passed as an argument), so that when the block's parent is later read and processed, this1228* function can re-read the child block from disk and process it.1229*1230* Because a block's parent may be in a later file, not just later in the same file, the1231* blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap,1232* rather than just a map, because multiple blocks may have the same parent (when chain splits1233* or stale blocks exist). It maps from parent-hash to child-disk-position.1234*1235* This function can also be used to read blocks from user-specified block files using the1236* -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted.1237*1238*1239* @param[in] file_in File containing blocks to read1240* @param[in] dbp (optional) Disk block position (only for reindex)1241* @param[in,out] blocks_with_unknown_parent (optional) Map of disk positions for blocks with1242* unknown parent, key is parent block hash1243* (only used for reindex)1244* */1245void LoadExternalBlockFile(1246AutoFile& file_in,1247FlatFilePos* dbp = nullptr,1248std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);1250/**
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.