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.
1// Copyright (c) 2021-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <node/chainstate.h>7#include <arith_uint256.h>8#include <chain.h>9#include <coins.h>10#include <consensus/params.h>11#include <kernel/caches.h>12#include <node/blockstorage.h>13#include <sync.h>14#include <tinyformat.h>15#include <txdb.h>16#include <uint256.h>17#include <util/byte_units.h>18#include <util/fs.h>19#include <util/log.h>20#include <util/signalinterrupt.h>21#include <util/time.h>22#include <util/translation.h>23#include <validation.h>25#include <algorithm>26#include <cassert>27#include <vector>29using kernel::CacheSizes;31namespace node {32// Complete initialization of chainstates after the initial call has been made33// to ChainstateManager::InitializeChainstate().34static ChainstateLoadResult CompleteChainstateInitialization(35ChainstateManager& chainman,36const ChainstateLoadOptions& options) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)37{38if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};40// LoadBlockIndex will load m_have_pruned if we've ever removed a41// block file from disk.42// Note that it also sets m_blockfiles_indexed based on the disk flag!43if (!chainman.LoadBlockIndex()) {44if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};45return {ChainstateLoadStatus::FAILURE, _("Error loading block database")};46}48if (!chainman.BlockIndex().empty() &&49!chainman.m_blockman.LookupBlockIndex(chainman.GetConsensus().hashGenesisBlock)) {50// If the loaded chain has a wrong genesis, bail out immediately51// (we're likely using a testnet datadir, or the other way around).52return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Incorrect or no genesis block found. Wrong datadir for network?")};53}55// Check for changed -prune state. What we are concerned about is a user who has pruned blocks56// in the past, but is now trying to run unpruned.57if (chainman.m_blockman.m_have_pruned && !options.prune) {58return {ChainstateLoadStatus::FAILURE, _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain")};59}61// At this point blocktree args are consistent with what's on disk.62// If we're not mid-reindex (based on disk + args), add a genesis block on disk63// (otherwise we use the one already on disk).64// This is called again in ImportBlocks after the reindex completes.65if (chainman.m_blockman.m_blockfiles_indexed && !chainman.LoadGenesisBlock()) {66return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};67}69auto is_coinsview_empty = [&](Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {70return options.wipe_chainstate_db || chainstate.CoinsTip().GetBestBlock().IsNull();71};73assert(chainman.m_total_coinstip_cache > 0);74assert(chainman.m_total_coinsdb_cache > 0);76// If running with multiple chainstates, limit the cache sizes with a77// discount factor. If discounted the actual cache size will be78// recalculated by `chainman.MaybeRebalanceCaches()`. The discount factor79// is conservatively chosen such that the sum of the caches does not exceed80// the allowable amount during this temporary initialization state.81double init_cache_fraction = chainman.HistoricalChainstate() ? 0.2 : 1.0;83// At this point we're either in reindex or we've loaded a useful84// block tree into BlockIndex()!86for (const auto& chainstate : chainman.m_chainstates) {87LogInfo("Initializing chainstate %s", chainstate->ToString());89try {90chainstate->InitCoinsDB(91/*cache_size_bytes=*/chainman.m_total_coinsdb_cache * init_cache_fraction,92/*in_memory=*/options.coins_db_in_memory,93/*should_wipe=*/options.wipe_chainstate_db);94} catch (dbwrapper_error& err) {95LogError("%s\n", err.what());96return {ChainstateLoadStatus::FAILURE, _("Error opening coins database")};97}99if (options.coins_error_cb) {100chainstate->CoinsErrorCatcher().AddReadErrCallback(options.coins_error_cb);101}103// Refuse to load unsupported database format.104// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate105if (chainstate->CoinsDB().NeedsUpgrade()) {106return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Unsupported chainstate database format found. "107"Please restart with -reindex-chainstate. This will "108"rebuild the chainstate database.")};109}111// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate112if (!chainstate->ReplayBlocks()) {113return {ChainstateLoadStatus::FAILURE, _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.")};114}116// The on-disk coinsdb is now in a good state, create the cache117chainstate->InitCoinsCache(chainman.m_total_coinstip_cache * init_cache_fraction);118assert(chainstate->CanFlushToDisk());120if (!is_coinsview_empty(*chainstate)) {121// LoadChainTip initializes the chain based on CoinsTip()'s best block122if (!chainstate->LoadChainTip()) {123return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};124}125assert(chainstate->m_chain.Tip() != nullptr);126}127}129// Populate setBlockIndexCandidates in a separate loop, after all LoadChainTip()130// calls have finished modifying nSequenceId. Because nSequenceId is used in the131// set's comparator, changing it while blocks are in the set would be UB.132for (const auto& chainstate : chainman.m_chainstates) {133chainstate->PopulateBlockIndexCandidates();134}136const auto& chainstates{chainman.m_chainstates};137if (std::any_of(chainstates.begin(), chainstates.end(),138[](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {139return {ChainstateLoadStatus::FAILURE, strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),140chainman.GetConsensus().SegwitHeight)};141};143// Now that chainstates are loaded and we're able to flush to144// disk, rebalance the coins caches to desired levels based145// on the condition of each chainstate.146chainman.MaybeRebalanceCaches();148return {ChainstateLoadStatus::SUCCESS, {}};149}151ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes,152const ChainstateLoadOptions& options)153{154if (!chainman.AssumedValidBlock().IsNull()) {155LogInfo("Assuming ancestors of block %s have valid signatures.", chainman.AssumedValidBlock().GetHex());156} else {157LogInfo("Validating signatures for all blocks.");158}159LogInfo("Setting nMinimumChainWork=%s", chainman.MinimumChainWork().GetHex());160if (chainman.MinimumChainWork() < UintToArith256(chainman.GetConsensus().nMinimumChainWork)) {161LogWarning("nMinimumChainWork set below default value of %s", chainman.GetConsensus().nMinimumChainWork.GetHex());162}163if (chainman.m_blockman.GetPruneTarget() == BlockManager::PRUNE_TARGET_MANUAL) {164LogInfo("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.");165} else if (chainman.m_blockman.GetPruneTarget()) {166LogInfo("Prune configured to target %u MiB on disk for block and undo files.",167chainman.m_blockman.GetPruneTarget() / 1_MiB);168}170LOCK(cs_main);172chainman.m_total_coinstip_cache = cache_sizes.coins;173chainman.m_total_coinsdb_cache = cache_sizes.coins_db;175// Load the fully validated chainstate.176Chainstate& validated_cs{chainman.InitializeChainstate(options.mempool)};178// Load a chain created from a UTXO snapshot, if any exist.179Chainstate* assumeutxo_cs{chainman.LoadAssumeutxoChainstate()};181if (assumeutxo_cs && options.wipe_chainstate_db) {182// Reset chainstate target to network tip instead of snapshot block.183validated_cs.SetTargetBlock(nullptr);184LogInfo("[snapshot] deleting snapshot chainstate due to reindexing");185if (!chainman.DeleteChainstate(*assumeutxo_cs)) {186return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated("Couldn't remove snapshot chainstate.")};187}188assumeutxo_cs = nullptr;189}191auto [init_status, init_error] = CompleteChainstateInitialization(chainman, options);192if (init_status != ChainstateLoadStatus::SUCCESS) {193return {init_status, init_error};194}196// If a snapshot chainstate was fully validated by a background chainstate during197// the last run, detect it here and clean up the now-unneeded background198// chainstate.199//200// Why is this cleanup done here (on subsequent restart) and not just when the201// snapshot is actually validated? Because this entails unusual202// filesystem operations to move leveldb data directories around, and that seems203// too risky to do in the middle of normal runtime.204auto snapshot_completion{assumeutxo_cs205? chainman.MaybeValidateSnapshot(validated_cs, *assumeutxo_cs)206: SnapshotCompletionResult::SKIPPED};208if (snapshot_completion == SnapshotCompletionResult::SKIPPED) {209// do nothing; expected case210} else if (snapshot_completion == SnapshotCompletionResult::SUCCESS) {211LogInfo("[snapshot] cleaning up unneeded background chainstate, then reinitializing");212if (!chainman.ValidatedSnapshotCleanup(validated_cs, *assumeutxo_cs)) {213return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated("Background chainstate cleanup failed unexpectedly.")};214}216// Because ValidatedSnapshotCleanup() has torn down chainstates with217// ChainstateManager::ResetChainstates(), reinitialize them here without218// duplicating the blockindex work above.219assert(chainman.m_chainstates.empty());221chainman.InitializeChainstate(options.mempool);223// A reload of the block index is required to recompute setBlockIndexCandidates224// for the fully validated chainstate.225chainman.ActiveChainstate().ClearBlockIndexCandidates();227auto [init_status, init_error] = CompleteChainstateInitialization(chainman, options);228if (init_status != ChainstateLoadStatus::SUCCESS) {229return {init_status, init_error};230}231} else {232return {ChainstateLoadStatus::FAILURE_FATAL, _(233"UTXO snapshot failed to validate. "234"Restart to resume normal initial block download, or try loading a different snapshot.")};235}237return {ChainstateLoadStatus::SUCCESS, {}};238}240ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const ChainstateLoadOptions& options)241{242auto is_coinsview_empty = [&](Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {243return options.wipe_chainstate_db || chainstate.CoinsTip().GetBestBlock().IsNull();244};246LOCK(cs_main);248for (auto& chainstate : chainman.m_chainstates) {249if (!is_coinsview_empty(*chainstate)) {250const CBlockIndex* tip = chainstate->m_chain.Tip();