Bitcoin Core 31.99.0
P2P Digital Currency
chainstate.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-present 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 <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/fs.h>
18#include <util/log.h>
20#include <util/time.h>
21#include <util/translation.h>
22#include <validation.h>
23
24#include <algorithm>
25#include <cassert>
26#include <vector>
27
29
30namespace node {
31// Complete initialization of chainstates after the initial call has been made
32// to ChainstateManager::InitializeChainstate().
34 ChainstateManager& chainman,
36{
37 if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};
38
39 // LoadBlockIndex will load m_have_pruned if we've ever removed a
40 // block file from disk.
41 // Note that it also sets m_blockfiles_indexed based on the disk flag!
42 if (!chainman.LoadBlockIndex()) {
43 if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};
44 return {ChainstateLoadStatus::FAILURE, _("Error loading block database")};
45 }
46
47 if (!chainman.BlockIndex().empty() &&
48 !chainman.m_blockman.LookupBlockIndex(chainman.GetConsensus().hashGenesisBlock)) {
49 // If the loaded chain has a wrong genesis, bail out immediately
50 // (we're likely using a testnet datadir, or the other way around).
51 return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Incorrect or no genesis block found. Wrong datadir for network?")};
52 }
53
54 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
55 // in the past, but is now trying to run unpruned.
56 if (chainman.m_blockman.m_have_pruned && !options.prune) {
57 return {ChainstateLoadStatus::FAILURE, _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain")};
58 }
59
60 // At this point blocktree args are consistent with what's on disk.
61 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
62 // (otherwise we use the one already on disk).
63 // This is called again in ImportBlocks after the reindex completes.
64 if (chainman.m_blockman.m_blockfiles_indexed && !chainman.ActiveChainstate().LoadGenesisBlock()) {
65 return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
66 }
67
68 auto is_coinsview_empty = [&](Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
69 return options.wipe_chainstate_db || chainstate.CoinsTip().GetBestBlock().IsNull();
70 };
71
72 assert(chainman.m_total_coinstip_cache > 0);
73 assert(chainman.m_total_coinsdb_cache > 0);
74
75 // If running with multiple chainstates, limit the cache sizes with a
76 // discount factor. If discounted the actual cache size will be
77 // recalculated by `chainman.MaybeRebalanceCaches()`. The discount factor
78 // is conservatively chosen such that the sum of the caches does not exceed
79 // the allowable amount during this temporary initialization state.
80 double init_cache_fraction = chainman.HistoricalChainstate() ? 0.2 : 1.0;
81
82 // At this point we're either in reindex or we've loaded a useful
83 // block tree into BlockIndex()!
84
85 for (const auto& chainstate : chainman.m_chainstates) {
86 LogInfo("Initializing chainstate %s", chainstate->ToString());
87
88 try {
89 chainstate->InitCoinsDB(
90 /*cache_size_bytes=*/chainman.m_total_coinsdb_cache * init_cache_fraction,
91 /*in_memory=*/options.coins_db_in_memory,
92 /*should_wipe=*/options.wipe_chainstate_db);
93 } catch (dbwrapper_error& err) {
94 LogError("%s\n", err.what());
95 return {ChainstateLoadStatus::FAILURE, _("Error opening coins database")};
96 }
97
98 if (options.coins_error_cb) {
99 chainstate->CoinsErrorCatcher().AddReadErrCallback(options.coins_error_cb);
100 }
101
102 // Refuse to load unsupported database format.
103 // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
104 if (chainstate->CoinsDB().NeedsUpgrade()) {
105 return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Unsupported chainstate database format found. "
106 "Please restart with -reindex-chainstate. This will "
107 "rebuild the chainstate database.")};
108 }
109
110 // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
111 if (!chainstate->ReplayBlocks()) {
112 return {ChainstateLoadStatus::FAILURE, _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.")};
113 }
114
115 // The on-disk coinsdb is now in a good state, create the cache
116 chainstate->InitCoinsCache(chainman.m_total_coinstip_cache * init_cache_fraction);
117 assert(chainstate->CanFlushToDisk());
118
119 if (!is_coinsview_empty(*chainstate)) {
120 // LoadChainTip initializes the chain based on CoinsTip()'s best block
121 if (!chainstate->LoadChainTip()) {
122 return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
123 }
124 assert(chainstate->m_chain.Tip() != nullptr);
125 }
126 }
127
128 // Populate setBlockIndexCandidates in a separate loop, after all LoadChainTip()
129 // calls have finished modifying nSequenceId. Because nSequenceId is used in the
130 // set's comparator, changing it while blocks are in the set would be UB.
131 for (const auto& chainstate : chainman.m_chainstates) {
132 chainstate->PopulateBlockIndexCandidates();
133 }
134
135 const auto& chainstates{chainman.m_chainstates};
136 if (std::any_of(chainstates.begin(), chainstates.end(),
137 [](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
138 return {ChainstateLoadStatus::FAILURE, strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
139 chainman.GetConsensus().SegwitHeight)};
140 };
141
142 // Now that chainstates are loaded and we're able to flush to
143 // disk, rebalance the coins caches to desired levels based
144 // on the condition of each chainstate.
145 chainman.MaybeRebalanceCaches();
146
148}
149
151 const ChainstateLoadOptions& options)
152{
153 if (!chainman.AssumedValidBlock().IsNull()) {
154 LogInfo("Assuming ancestors of block %s have valid signatures.", chainman.AssumedValidBlock().GetHex());
155 } else {
156 LogInfo("Validating signatures for all blocks.");
157 }
158 LogInfo("Setting nMinimumChainWork=%s", chainman.MinimumChainWork().GetHex());
159 if (chainman.MinimumChainWork() < UintToArith256(chainman.GetConsensus().nMinimumChainWork)) {
160 LogWarning("nMinimumChainWork set below default value of %s", chainman.GetConsensus().nMinimumChainWork.GetHex());
161 }
163 LogInfo("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.");
164 } else if (chainman.m_blockman.GetPruneTarget()) {
165 LogInfo("Prune configured to target %u MiB on disk for block and undo files.",
166 chainman.m_blockman.GetPruneTarget() / 1024 / 1024);
167 }
168
169 LOCK(cs_main);
170
171 chainman.m_total_coinstip_cache = cache_sizes.coins;
172 chainman.m_total_coinsdb_cache = cache_sizes.coins_db;
173
174 // Load the fully validated chainstate.
175 Chainstate& validated_cs{chainman.InitializeChainstate(options.mempool)};
176
177 // Load a chain created from a UTXO snapshot, if any exist.
178 Chainstate* assumeutxo_cs{chainman.LoadAssumeutxoChainstate()};
179
180 if (assumeutxo_cs && options.wipe_chainstate_db) {
181 // Reset chainstate target to network tip instead of snapshot block.
182 validated_cs.SetTargetBlock(nullptr);
183 LogInfo("[snapshot] deleting snapshot chainstate due to reindexing");
184 if (!chainman.DeleteChainstate(*assumeutxo_cs)) {
185 return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated("Couldn't remove snapshot chainstate.")};
186 }
187 assumeutxo_cs = nullptr;
188 }
189
190 auto [init_status, init_error] = CompleteChainstateInitialization(chainman, options);
191 if (init_status != ChainstateLoadStatus::SUCCESS) {
192 return {init_status, init_error};
193 }
194
195 // If a snapshot chainstate was fully validated by a background chainstate during
196 // the last run, detect it here and clean up the now-unneeded background
197 // chainstate.
198 //
199 // Why is this cleanup done here (on subsequent restart) and not just when the
200 // snapshot is actually validated? Because this entails unusual
201 // filesystem operations to move leveldb data directories around, and that seems
202 // too risky to do in the middle of normal runtime.
203 auto snapshot_completion{assumeutxo_cs
204 ? chainman.MaybeValidateSnapshot(validated_cs, *assumeutxo_cs)
206
207 if (snapshot_completion == SnapshotCompletionResult::SKIPPED) {
208 // do nothing; expected case
209 } else if (snapshot_completion == SnapshotCompletionResult::SUCCESS) {
210 LogInfo("[snapshot] cleaning up unneeded background chainstate, then reinitializing");
211 if (!chainman.ValidatedSnapshotCleanup(validated_cs, *assumeutxo_cs)) {
212 return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated("Background chainstate cleanup failed unexpectedly.")};
213 }
214
215 // Because ValidatedSnapshotCleanup() has torn down chainstates with
216 // ChainstateManager::ResetChainstates(), reinitialize them here without
217 // duplicating the blockindex work above.
218 assert(chainman.m_chainstates.empty());
219
220 chainman.InitializeChainstate(options.mempool);
221
222 // A reload of the block index is required to recompute setBlockIndexCandidates
223 // for the fully validated chainstate.
224 chainman.ActiveChainstate().ClearBlockIndexCandidates();
225
226 auto [init_status, init_error] = CompleteChainstateInitialization(chainman, options);
227 if (init_status != ChainstateLoadStatus::SUCCESS) {
228 return {init_status, init_error};
229 }
230 } else {
232 "UTXO snapshot failed to validate. "
233 "Restart to resume normal initial block download, or try loading a different snapshot.")};
234 }
235
237}
238
240{
241 auto is_coinsview_empty = [&](Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
242 return options.wipe_chainstate_db || chainstate.CoinsTip().GetBestBlock().IsNull();
243 };
244
245 LOCK(cs_main);
246
247 for (auto& chainstate : chainman.m_chainstates) {
248 if (!is_coinsview_empty(*chainstate)) {
249 const CBlockIndex* tip = chainstate->m_chain.Tip();
250 if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
251 return {ChainstateLoadStatus::FAILURE, _("The block database contains a block which appears to be from the future. "
252 "This may be due to your computer's date and time being set incorrectly. "
253 "Only rebuild the block database if you are sure that your computer's date and time are correct")};
254 }
255
257 *chainstate, chainman.GetConsensus(), chainstate->CoinsDB(),
258 options.check_level,
259 options.check_blocks);
260 switch (result) {
263 break;
265 return {ChainstateLoadStatus::INTERRUPTED, _("Block verification was interrupted")};
267 return {ChainstateLoadStatus::FAILURE, _("Corrupted block database detected")};
269 if (options.require_full_verification) {
270 return {ChainstateLoadStatus::FAILURE_INSUFFICIENT_DBCACHE, _("Insufficient dbcache for block verification")};
271 }
272 break;
273 } // no default case, so the compiler can warn about missing cases
274 }
275 }
276
278}
279} // namespace node
arith_uint256 UintToArith256(const uint256 &a)
static void pool cs
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current time before the block ...
Definition: chain.h:29
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
uint32_t nTime
Definition: chain.h:142
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:436
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, 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:551
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:940
const uint256 & AssumedValidBlock() const
Definition: validation.h:1011
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:1082
kernel::Notifications & GetNotifications() const
Definition: validation.h:1012
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1086
const Consensus::Params & GetConsensus() const
Definition: validation.h:1008
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1010
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1038
constexpr bool IsNull() const
Definition: uint256.h:49
std::string GetHex() const
Definition: uint256.cpp:11
std::string GetHex() const
Hex encoding of the number (with the most significant digits first).
static constexpr auto PRUNE_TARGET_MANUAL
Definition: blockstorage.h:409
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
Definition: blockstorage.h:408
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define LogWarning(...)
Definition: log.h:98
#define LogInfo(...)
Definition: log.h:97
#define LogError(...)
Definition: log.h:99
Definition: messages.h:21
@ 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:54
static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager &chainman, const ChainstateLoadOptions &options) EXCLUSIVE_LOCKS_REQUIRED(
Definition: chainstate.cpp:33
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:150
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:239
uint256 nMinimumChainWork
The best chain should have at least this much work.
Definition: params.h:131
bool require_full_verification
Setting require_full_verification to true will require all checks at check_level (below) to succeed f...
Definition: chainstate.h:34
#define LOCK(cs)
Definition: sync.h:268
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:87
assert(!tx.IsCoinBase())
VerifyDBResult
Definition: validation.h:426