7#include <chainparams.h>
13#include <validation.h>
23 auto &pblocktree{chainman.m_blockman.m_block_tree_db};
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});
34 if (options.reindex) {
35 pblocktree->WriteReindexing(
true);
39 chainman.m_blockman.CleanupBlockRevFiles();
46 if (!pblocktree->Upgrade()) {
48 _(
"Error upgrading block index database")};
51 if (options.check_interrupt && options.check_interrupt()) {
59 if (!chainman.LoadBlockIndex()) {
60 if (options.check_interrupt && options.check_interrupt()) {
65 _(
"Error loading block database")};
68 if (!chainman.BlockIndex().empty() &&
69 !chainman.m_blockman.LookupBlockIndex(
70 chainman.GetConsensus().hashGenesisBlock)) {
74 _(
"Incorrect or no genesis block found. Wrong datadir for "
81 if (chainman.m_blockman.m_have_pruned && !options.prune) {
84 _(
"You need to rebuild the database using -reindex to go back to "
85 "unpruned mode. This will redownload the entire blockchain")};
92 if (!
fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
94 _(
"Error initializing block database")};
97 auto is_coinsview_empty =
99 return options.reindex || options.reindex_chainstate ||
100 chainstate->CoinsTip().GetBestBlock().IsNull();
103 assert(chainman.m_total_coinstip_cache > 0);
104 assert(chainman.m_total_coinsdb_cache > 0);
110 double init_cache_fraction = 0.2;
115 for (
Chainstate *chainstate : chainman.GetAll()) {
116 LogPrintf(
"Initializing chainstate %s\n", chainstate->ToString());
118 chainstate->InitCoinsDB(
119 chainman.m_total_coinsdb_cache *
121 options.coins_db_in_memory,
122 options.reindex || options.reindex_chainstate);
124 if (options.coins_error_cb) {
125 chainstate->CoinsErrorCatcher().AddReadErrCallback(
126 options.coins_error_cb);
132 if (chainstate->CoinsDB().NeedsUpgrade()) {
134 _(
"Unsupported chainstate database format found. "
135 "Please restart with -reindex-chainstate. This will "
136 "rebuild the chainstate database.")};
141 if (!chainstate->ReplayBlocks()) {
143 _(
"Unable to replay blocks. You will need to rebuild the "
144 "database using -reindex-chainstate.")};
148 chainstate->InitCoinsCache(chainman.m_total_coinstip_cache *
149 init_cache_fraction);
150 assert(chainstate->CanFlushToDisk());
152 if (!is_coinsview_empty(chainstate)) {
155 if (!chainstate->LoadChainTip()) {
157 _(
"Error initializing block database")};
159 assert(chainstate->m_chain.Tip() !=
nullptr);
166 chainman.MaybeRebalanceCaches();
175 LogPrintf(
"Assuming ancestors of block %s have valid signatures.\n",
178 LogPrintf(
"Validating signatures for all blocks.\n");
180 LogPrintf(
"Setting nMinimumChainWork=%s\n",
184 LogPrintf(
"Warning: nMinimumChainWork set below default value of %s\n",
190 "Block pruning enabled. Use RPC call pruneblockchain(height) to "
191 "manually prune block and undo files.\n");
193 LogPrintf(
"Prune configured to target %u MiB on disk for block and "
203 chainman.InitializeChainstate(options.
mempool);
206 bool has_snapshot = chainman.DetectSnapshotChainstate(options.
mempool);
210 "[snapshot] deleting snapshot chainstate due to reindexing\n");
211 if (!chainman.DeleteSnapshotChainstate()) {
218 auto [init_status, init_error] =
221 return {init_status, init_error};
233 auto snapshot_completion = chainman.MaybeCompleteSnapshotValidation();
238 LogPrintf(
"[snapshot] cleaning up unneeded background chainstate, then "
240 if (!chainman.ValidatedSnapshotCleanup()) {
243 "Background chainstate cleanup failed unexpectedly.")};
253 chainman.InitializeChainstate(options.
mempool);
259 auto [init_status, init_error] =
262 return {init_status, init_error};
266 _(
"UTXO snapshot failed to validate. "
267 "Restart to resume normal initial block download, or try "
268 "loading a different snapshot.")};
277 auto is_coinsview_empty =
280 chainstate->CoinsTip().GetBestBlock().IsNull();
286 if (!is_coinsview_empty(chainstate)) {
287 const CBlockIndex *tip = chainstate->m_chain.Tip();
290 _(
"The block database contains a block which appears "
291 "to be from the future. "
292 "This may be due to your computer's date and time "
293 "being set incorrectly. "
294 "Only rebuild the block database if you are sure "
295 "that your computer's date and time are correct")};
300 .
VerifyDB(*chainstate, chainstate->CoinsDB(),
308 _(
"Block verification was interrupted")};
311 _(
"Corrupted block database detected")};
316 _(
"Insufficient dbcache for block verification")};
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 ...
The block chain is a tree shaped structure starting with the genesis block at the root,...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
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.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
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...
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
kernel::Notifications & GetNotifications() const
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
bool IsSnapshotActive() const
const Consensus::Params & GetConsensus() const
const arith_uint256 & MinimumChainWork() const
const BlockHash & AssumedValidBlock() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
std::string GetHex() const
std::string GetHex() const
static constexpr auto PRUNE_TARGET_MANUAL
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
@ FAILURE_INCOMPATIBLE_DB
@ FAILURE_FATAL
Fatal error which should not prompt to reindex.
@ FAILURE
Generic failure which reindexing may fix.
@ FAILURE_INSUFFICIENT_DBCACHE
std::tuple< ChainstateLoadStatus, bilingual_str > ChainstateLoadResult
Chainstate load status code and optional error string.
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options) EXCLUSIVE_LOCKS_REQUIRED(
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
std::atomic_bool fReindex
uint256 nMinimumChainWork
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
bool require_full_verification
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.