Bitcoin ABC 0.33.11
P2P Digital Currency
chainstate.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 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 <chainparams.h>
8#include <config.h>
9#include <consensus/params.h>
10#include <kernel/caches.h>
11#include <node/blockstorage.h>
12#include <util/fs.h>
13#include <validation.h>
14
16
17namespace node {
18// Complete initialization of chainstates after the initial call has been made
19// to ChainstateManager::InitializeChainstate().
21 ChainstateManager &chainman, const CacheSizes &cache_sizes,
23 auto &pblocktree{chainman.m_blockman.m_block_tree_db};
24 // new CBlockTreeDB tries to delete the existing file, which
25 // fails if it's still open from the previous loop. Close it first:
26 pblocktree.reset();
27 pblocktree = std::make_unique<CBlockTreeDB>(
28 DBParams{.path = chainman.m_options.datadir / "blocks" / "index",
29 .cache_bytes = cache_sizes.block_tree_db,
30 .memory_only = options.block_tree_db_in_memory,
31 .wipe_data = options.reindex,
32 .options = chainman.m_options.block_tree_db});
33
34 if (options.reindex) {
35 pblocktree->WriteReindexing(true);
36 // If we're reindexing in prune mode, wipe away unusable block
37 // files and all undo data files
38 if (options.prune) {
39 chainman.m_blockman.CleanupBlockRevFiles();
40 }
41 }
42
43 // If necessary, upgrade from older database format.
44 // This is a no-op if we cleared the block tree db with -reindex
45 // or -reindex-chainstate
46 if (!pblocktree->Upgrade()) {
48 _("Error upgrading block index database")};
49 }
50
51 if (options.check_interrupt && options.check_interrupt()) {
53 }
54
55 // LoadBlockIndex will load m_have_pruned if we've ever removed a
56 // block file from disk.
57 // Note that it also sets m_reindexing based on the disk flag!
58 // From here on, m_reindexing and options.reindex values may be different!
59 if (!chainman.LoadBlockIndex()) {
60 if (options.check_interrupt && options.check_interrupt()) {
62 }
63
65 _("Error loading block database")};
66 }
67
68 if (!chainman.BlockIndex().empty() &&
69 !chainman.m_blockman.LookupBlockIndex(
70 chainman.GetConsensus().hashGenesisBlock)) {
71 // If the loaded chain has a wrong genesis, bail out immediately
72 // (we're likely using a testnet datadir, or the other way around).
74 _("Incorrect or no genesis block found. Wrong datadir for "
75 "network?")};
76 }
77
78 // Check for changed -prune state. What we are concerned about is a
79 // user who has pruned blocks in the past, but is now trying to run
80 // unpruned.
81 if (chainman.m_blockman.m_have_pruned && !options.prune) {
82 return {
84 _("You need to rebuild the database using -reindex to go back to "
85 "unpruned mode. This will redownload the entire blockchain")};
86 }
87
88 // At this point blocktree args are consistent with what's on disk.
89 // If we're not mid-reindex (based on disk + args), add a genesis
90 // block on disk (otherwise we use the one already on disk). This is
91 // called again in ImportBlocks after the reindex completes.
92 if (!chainman.m_blockman.m_reindexing &&
93 !chainman.ActiveChainstate().LoadGenesisBlock()) {
95 _("Error initializing block database")};
96 }
97
98 auto is_coinsview_empty =
100 return options.reindex || options.reindex_chainstate ||
101 chainstate->CoinsTip().GetBestBlock().IsNull();
102 };
103
104 assert(chainman.m_total_coinstip_cache > 0);
105 assert(chainman.m_total_coinsdb_cache > 0);
106
107 // Conservative value which is arbitrarily chosen, as it will ultimately be
108 // changed by a call to `chainman.MaybeRebalanceCaches()`. We just need to
109 // make sure that the sum of the two caches (40%) does not exceed the
110 // allowable amount during this temporary initialization state.
111 double init_cache_fraction = 0.2;
112
113 // At this point we're either in reindex or we've loaded a useful
114 // block tree into BlockIndex()!
115
116 for (Chainstate *chainstate : chainman.GetAll()) {
117 LogPrintf("Initializing chainstate %s\n", chainstate->ToString());
118
119 chainstate->InitCoinsDB(
120 /* cache_size_bytes */ chainman.m_total_coinsdb_cache *
121 init_cache_fraction,
122 /* in_memory */ options.coins_db_in_memory,
123 /* should_wipe */ options.reindex || options.reindex_chainstate);
124
125 if (options.coins_error_cb) {
126 chainstate->CoinsErrorCatcher().AddReadErrCallback(
127 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
132 // or -reindex-chainstate
133 if (chainstate->CoinsDB().NeedsUpgrade()) {
135 _("Unsupported chainstate database format found. "
136 "Please restart with -reindex-chainstate. This will "
137 "rebuild the chainstate database.")};
138 }
139
140 // ReplayBlocks is a no-op if we cleared the coinsviewdb with
141 // -reindex or -reindex-chainstate
142 if (!chainstate->ReplayBlocks()) {
144 _("Unable to replay blocks. You will need to rebuild the "
145 "database using -reindex-chainstate.")};
146 }
147
148 // The on-disk coinsdb is now in a good state, create the cache
149 chainstate->InitCoinsCache(chainman.m_total_coinstip_cache *
150 init_cache_fraction);
151 assert(chainstate->CanFlushToDisk());
152
153 if (!is_coinsview_empty(chainstate)) {
154 // LoadChainTip initializes the chain based on CoinsTip()'s
155 // best block
156 if (!chainstate->LoadChainTip()) {
158 _("Error initializing block database")};
159 }
160 assert(chainstate->m_chain.Tip() != nullptr);
161 }
162 }
163
164 // Now that chainstates are loaded and we're able to flush to
165 // disk, rebalance the coins caches to desired levels based
166 // on the condition of each chainstate.
167 chainman.MaybeRebalanceCaches();
168
170}
171
173 const CacheSizes &cache_sizes,
174 const ChainstateLoadOptions &options) {
175 if (!chainman.AssumedValidBlock().IsNull()) {
176 LogPrintf("Assuming ancestors of block %s have valid signatures.\n",
177 chainman.AssumedValidBlock().GetHex());
178 } else {
179 LogPrintf("Validating signatures for all blocks.\n");
180 }
181 LogPrintf("Setting nMinimumChainWork=%s\n",
182 chainman.MinimumChainWork().GetHex());
183 if (chainman.MinimumChainWork() <
185 LogPrintf("Warning: nMinimumChainWork set below default value of %s\n",
187 }
188 if (chainman.m_blockman.GetPruneTarget() ==
190 LogPrintf(
191 "Block pruning enabled. Use RPC call pruneblockchain(height) to "
192 "manually prune block and undo files.\n");
193 } else if (chainman.m_blockman.GetPruneTarget()) {
194 LogPrintf("Prune configured to target %u MiB on disk for block and "
195 "undo files.\n",
196 chainman.m_blockman.GetPruneTarget() / 1024 / 1024);
197 }
198
199 LOCK(cs_main);
200 chainman.m_total_coinstip_cache = cache_sizes.coins;
201 chainman.m_total_coinsdb_cache = cache_sizes.coins_db;
202
203 // Load the fully validated chainstate.
204 chainman.InitializeChainstate(options.mempool);
205
206 // Load a chain created from a UTXO snapshot, if any exist.
207 bool has_snapshot = chainman.DetectSnapshotChainstate(options.mempool);
208
209 if (has_snapshot && (options.reindex || options.reindex_chainstate)) {
210 LogPrintf(
211 "[snapshot] deleting snapshot chainstate due to reindexing\n");
212 if (!chainman.DeleteSnapshotChainstate()) {
214 Untranslated("Couldn't remove snapshot chainstate.")};
215 }
216 }
217
218 {
219 auto [init_status, init_error] =
220 CompleteChainstateInitialization(chainman, cache_sizes, options);
221 if (init_status != ChainstateLoadStatus::SUCCESS) {
222 return {init_status, init_error};
223 }
224 }
225
226 // If a snapshot chainstate was fully validated by a background chainstate
227 // during the last run, detect it here and clean up the now-unneeded
228 // background chainstate.
229 //
230 // Why is this cleanup done here (on subsequent restart) and not just when
231 // the snapshot is actually validated? Because this entails unusual
232 // filesystem operations to move leveldb data directories around, and that
233 // seems too risky to do in the middle of normal runtime.
234 auto snapshot_completion = chainman.MaybeCompleteSnapshotValidation();
235
236 if (snapshot_completion == SnapshotCompletionResult::SKIPPED) {
237 // do nothing; expected case
238 } else if (snapshot_completion == SnapshotCompletionResult::SUCCESS) {
239 LogPrintf("[snapshot] cleaning up unneeded background chainstate, then "
240 "reinitializing\n");
241 if (!chainman.ValidatedSnapshotCleanup()) {
244 "Background chainstate cleanup failed unexpectedly.")};
245 }
246
247 // Because ValidatedSnapshotCleanup() has torn down chainstates with
248 // ChainstateManager::ResetChainstates(), reinitialize them here without
249 // duplicating the blockindex work above.
250 assert(chainman.GetAll().empty());
251 assert(!chainman.IsSnapshotActive());
252 assert(!chainman.IsSnapshotValidated());
253
254 chainman.InitializeChainstate(options.mempool);
255
256 // A reload of the block index is required to recompute
257 // setBlockIndexCandidates for the fully validated chainstate.
258 chainman.ActiveChainstate().ClearBlockIndexCandidates();
259
260 auto [init_status, init_error] =
261 CompleteChainstateInitialization(chainman, cache_sizes, options);
262 if (init_status != ChainstateLoadStatus::SUCCESS) {
263 return {init_status, init_error};
264 }
265 } else {
267 _("UTXO snapshot failed to validate. "
268 "Restart to resume normal initial block download, or try "
269 "loading a different snapshot.")};
270 }
271
273}
274
277 const ChainstateLoadOptions &options) {
278 auto is_coinsview_empty =
280 return options.reindex || options.reindex_chainstate ||
281 chainstate->CoinsTip().GetBestBlock().IsNull();
282 };
283
284 LOCK(cs_main);
285
286 for (Chainstate *chainstate : chainman.GetAll()) {
287 if (!is_coinsview_empty(chainstate)) {
288 const CBlockIndex *tip = chainstate->m_chain.Tip();
289 if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
291 _("The block database contains a block which appears "
292 "to be from the future. "
293 "This may be due to your computer's date and time "
294 "being set incorrectly. "
295 "Only rebuild the block database if you are sure "
296 "that your computer's date and time are correct")};
297 }
298
299 VerifyDBResult result =
300 CVerifyDB(chainman.GetNotifications())
301 .VerifyDB(*chainstate, chainstate->CoinsDB(),
302 options.check_level, options.check_blocks);
303 switch (result) {
306 break;
309 _("Block verification was interrupted")};
312 _("Corrupted block database detected")};
314 if (options.require_full_verification) {
315 return {
317 _("Insufficient dbcache for block verification")};
318 }
319 break;
320 } // no default case, so the compiler can warn about missing cases
321 }
322 }
323
325}
326} // 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:28
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
uint32_t nTime
Definition: blockindex.h:76
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:641
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:725
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1174
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1428
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:1380
kernel::Notifications & GetNotifications() const
Definition: validation.h:1286
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1466
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1384
bool IsSnapshotActive() const
const Consensus::Params & GetConsensus() const
Definition: validation.h:1274
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1280
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1283
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1394
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1318
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
std::string GetHex() const
static constexpr auto PRUNE_TARGET_MANUAL
Definition: blockstorage.h:361
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
Definition: blockstorage.h:358
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:424
Definition: messages.h:12
@ FAILURE_FATAL
Fatal error which should not prompt to reindex.
@ FAILURE
Generic failure which reindexing may fix.
std::tuple< ChainstateLoadStatus, bilingual_str > ChainstateLoadResult
Chainstate load status code and optional error string.
Definition: chainstate.h:58
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:172
static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options) EXCLUSIVE_LOCKS_REQUIRED(
Definition: chainstate.cpp:20
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:276
uint256 nMinimumChainWork
Definition: params.h:93
Application-specific storage settings.
Definition: dbwrapper.h:32
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:34
#define LOCK(cs)
Definition: sync.h:306
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:80
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
assert(!tx.IsCoinBase())
VerifyDBResult
Definition: validation.h:629