Bitcoin Core  24.99.0
P2P Digital Currency
chainstate.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <node/chainstate.h>
6 
7 #include <arith_uint256.h>
8 #include <chain.h>
9 #include <coins.h>
10 #include <consensus/params.h>
11 #include <logging.h>
12 #include <node/blockstorage.h>
13 #include <node/caches.h>
14 #include <sync.h>
15 #include <threadsafety.h>
16 #include <tinyformat.h>
17 #include <txdb.h>
18 #include <uint256.h>
19 #include <util/time.h>
20 #include <util/translation.h>
21 #include <validation.h>
22 
23 #include <algorithm>
24 #include <atomic>
25 #include <cassert>
26 #include <limits>
27 #include <memory>
28 #include <vector>
29 
30 namespace node {
32  const ChainstateLoadOptions& options)
33 {
34  auto is_coinsview_empty = [&](Chainstate* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
35  return options.reindex || options.reindex_chainstate || chainstate->CoinsTip().GetBestBlock().IsNull();
36  };
37 
38  if (!chainman.AssumedValidBlock().IsNull()) {
39  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", chainman.AssumedValidBlock().GetHex());
40  } else {
41  LogPrintf("Validating signatures for all blocks.\n");
42  }
43  LogPrintf("Setting nMinimumChainWork=%s\n", chainman.MinimumChainWork().GetHex());
44  if (chainman.MinimumChainWork() < UintToArith256(chainman.GetConsensus().nMinimumChainWork)) {
45  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainman.GetConsensus().nMinimumChainWork.GetHex());
46  }
47  if (chainman.m_blockman.GetPruneTarget() == std::numeric_limits<uint64_t>::max()) {
48  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
49  } else if (chainman.m_blockman.GetPruneTarget()) {
50  LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", chainman.m_blockman.GetPruneTarget() / 1024 / 1024);
51  }
52 
53  LOCK(cs_main);
54  chainman.m_total_coinstip_cache = cache_sizes.coins;
55  chainman.m_total_coinsdb_cache = cache_sizes.coins_db;
56 
57  // Load the fully validated chainstate.
58  chainman.InitializeChainstate(options.mempool);
59 
60  // Load a chain created from a UTXO snapshot, if any exist.
61  chainman.DetectSnapshotChainstate(options.mempool);
62 
63  auto& pblocktree{chainman.m_blockman.m_block_tree_db};
64  // new CBlockTreeDB tries to delete the existing file, which
65  // fails if it's still open from the previous loop. Close it first:
66  pblocktree.reset();
67  pblocktree.reset(new CBlockTreeDB(cache_sizes.block_tree_db, options.block_tree_db_in_memory, options.reindex));
68 
69  if (options.reindex) {
70  pblocktree->WriteReindexing(true);
71  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
72  if (options.prune) {
74  }
75  }
76 
77  if (options.check_interrupt && options.check_interrupt()) return {ChainstateLoadStatus::INTERRUPTED, {}};
78 
79  // LoadBlockIndex will load m_have_pruned if we've ever removed a
80  // block file from disk.
81  // Note that it also sets fReindex global based on the disk flag!
82  // From here on, fReindex and options.reindex values may be different!
83  if (!chainman.LoadBlockIndex()) {
84  if (options.check_interrupt && options.check_interrupt()) return {ChainstateLoadStatus::INTERRUPTED, {}};
85  return {ChainstateLoadStatus::FAILURE, _("Error loading block database")};
86  }
87 
88  if (!chainman.BlockIndex().empty() &&
90  // If the loaded chain has a wrong genesis, bail out immediately
91  // (we're likely using a testnet datadir, or the other way around).
92  return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Incorrect or no genesis block found. Wrong datadir for network?")};
93  }
94 
95  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
96  // in the past, but is now trying to run unpruned.
97  if (chainman.m_blockman.m_have_pruned && !options.prune) {
98  return {ChainstateLoadStatus::FAILURE, _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain")};
99  }
100 
101  // At this point blocktree args are consistent with what's on disk.
102  // If we're not mid-reindex (based on disk + args), add a genesis block on disk
103  // (otherwise we use the one already on disk).
104  // This is called again in ThreadImport after the reindex completes.
105  if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
106  return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
107  }
108 
109  // Conservative value which is arbitrarily chosen, as it will ultimately be changed
110  // by a call to `chainman.MaybeRebalanceCaches()`. We just need to make sure
111  // that the sum of the two caches (40%) does not exceed the allowable amount
112  // during this temporary initialization state.
113  double init_cache_fraction = 0.2;
114 
115  // At this point we're either in reindex or we've loaded a useful
116  // block tree into BlockIndex()!
117 
118  for (Chainstate* chainstate : chainman.GetAll()) {
119  LogPrintf("Initializing chainstate %s\n", chainstate->ToString());
120 
121  chainstate->InitCoinsDB(
122  /*cache_size_bytes=*/chainman.m_total_coinsdb_cache * init_cache_fraction,
123  /*in_memory=*/options.coins_db_in_memory,
124  /*should_wipe=*/options.reindex || options.reindex_chainstate);
125 
126  if (options.coins_error_cb) {
127  chainstate->CoinsErrorCatcher().AddReadErrCallback(options.coins_error_cb);
128  }
129 
130  // Refuse to load unsupported database format.
131  // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
132  if (chainstate->CoinsDB().NeedsUpgrade()) {
133  return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Unsupported chainstate database format found. "
134  "Please restart with -reindex-chainstate. This will "
135  "rebuild the chainstate database.")};
136  }
137 
138  // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
139  if (!chainstate->ReplayBlocks()) {
140  return {ChainstateLoadStatus::FAILURE, _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.")};
141  }
142 
143  // The on-disk coinsdb is now in a good state, create the cache
144  chainstate->InitCoinsCache(chainman.m_total_coinstip_cache * init_cache_fraction);
145  assert(chainstate->CanFlushToDisk());
146 
147  if (!is_coinsview_empty(chainstate)) {
148  // LoadChainTip initializes the chain based on CoinsTip()'s best block
149  if (!chainstate->LoadChainTip()) {
150  return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
151  }
152  assert(chainstate->m_chain.Tip() != nullptr);
153  }
154  }
155 
156  if (!options.reindex) {
157  auto chainstates{chainman.GetAll()};
158  if (std::any_of(chainstates.begin(), chainstates.end(),
159  [](const Chainstate* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
160  return {ChainstateLoadStatus::FAILURE, strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
161  chainman.GetConsensus().SegwitHeight)};
162  };
163  }
164 
165  // Now that chainstates are loaded and we're able to flush to
166  // disk, rebalance the coins caches to desired levels based
167  // on the condition of each chainstate.
168  chainman.MaybeRebalanceCaches();
169 
170  return {ChainstateLoadStatus::SUCCESS, {}};
171 }
172 
174 {
175  auto is_coinsview_empty = [&](Chainstate* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
176  return options.reindex || options.reindex_chainstate || chainstate->CoinsTip().GetBestBlock().IsNull();
177  };
178 
179  LOCK(cs_main);
180 
181  for (Chainstate* chainstate : chainman.GetAll()) {
182  if (!is_coinsview_empty(chainstate)) {
183  const CBlockIndex* tip = chainstate->m_chain.Tip();
184  if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
185  return {ChainstateLoadStatus::FAILURE, _("The block database contains a block which appears to be from the future. "
186  "This may be due to your computer's date and time being set incorrectly. "
187  "Only rebuild the block database if you are sure that your computer's date and time are correct")};
188  }
189 
190  if (!CVerifyDB().VerifyDB(
191  *chainstate, chainman.GetConsensus(), chainstate->CoinsDB(),
192  options.check_level,
193  options.check_blocks)) {
194  return {ChainstateLoadStatus::FAILURE, _("Corrupted block database detected")};
195  }
196  }
197  }
198 
199  return {ChainstateLoadStatus::SUCCESS, {}};
200 }
201 } // namespace node
arith_uint256 UintToArith256(const uint256 &a)
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current network-adjusted time ...
Definition: chain.h:24
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
uint32_t nTime
Definition: chain.h:205
Access to the block database (blocks/index/)
Definition: txdb.h:81
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:353
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:441
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:802
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:928
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:880
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:932
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:965
Chainstate & ActiveChainstate() const
The most-work chain.
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
const uint256 & AssumedValidBlock() const
Definition: validation.h:881
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:941
const Consensus::Params & GetConsensus() const
Definition: validation.h:878
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:900
bool IsNull() const
Definition: uint256.h:34
std::string GetHex() const
Definition: uint256.cpp:20
std::string GetHex() const
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Find the first block that is not pruned.
Definition: blockstorage.h:197
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
Definition: blockstorage.h:180
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
#define LogPrintf(...)
Definition: logging.h:236
static void pool cs
Definition: init.h:25
std::tuple< ChainstateLoadStatus, bilingual_str > ChainstateLoadResult
Chainstate load status code and optional error string.
Definition: chainstate.h:41
void CleanupBlockRevFiles()
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
This sequence can have 4 types of outcomes:
Definition: chainstate.cpp:31
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:173
std::atomic_bool fReindex
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:95
uint256 hashGenesisBlock
Definition: params.h:74
uint256 nMinimumChainWork
The best chain should have at least this much work.
Definition: params.h:119
int64_t coins
Definition: caches.h:17
int64_t block_tree_db
Definition: caches.h:15
int64_t coins_db
Definition: caches.h:16
std::function< void()> coins_error_cb
Definition: chainstate.h:31
std::function< bool()> check_interrupt
Definition: chainstate.h:30
#define LOCK(cs)
Definition: sync.h:258
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTime()
Definition: time.cpp:115
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:65
assert(!tx.IsCoinBase())