7#include <chainparams.h>
13#include <validation.h>
21 auto &pblocktree{chainman.m_blockman.m_block_tree_db};
25 pblocktree = std::make_unique<CBlockTreeDB>(
26 DBParams{.
path = chainman.m_options.datadir /
"blocks" /
"index",
27 .cache_bytes =
static_cast<size_t>(cache_sizes.block_tree_db),
28 .memory_only = options.block_tree_db_in_memory,
29 .wipe_data = options.reindex,
30 .options = chainman.m_options.block_tree_db});
32 if (options.reindex) {
33 pblocktree->WriteReindexing(
true);
37 chainman.m_blockman.CleanupBlockRevFiles();
44 if (!pblocktree->Upgrade()) {
46 _(
"Error upgrading block index database")};
49 if (options.check_interrupt && options.check_interrupt()) {
57 if (!chainman.LoadBlockIndex()) {
58 if (options.check_interrupt && options.check_interrupt()) {
63 _(
"Error loading block database")};
66 if (!chainman.BlockIndex().empty() &&
67 !chainman.m_blockman.LookupBlockIndex(
68 chainman.GetConsensus().hashGenesisBlock)) {
72 _(
"Incorrect or no genesis block found. Wrong datadir for "
79 if (chainman.m_blockman.m_have_pruned && !options.prune) {
82 _(
"You need to rebuild the database using -reindex to go back to "
83 "unpruned mode. This will redownload the entire blockchain")};
90 if (!
fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
92 _(
"Error initializing block database")};
95 auto is_coinsview_empty =
97 return options.reindex || options.reindex_chainstate ||
98 chainstate->CoinsTip().GetBestBlock().IsNull();
101 assert(chainman.m_total_coinstip_cache > 0);
102 assert(chainman.m_total_coinsdb_cache > 0);
108 double init_cache_fraction = 0.2;
113 for (
Chainstate *chainstate : chainman.GetAll()) {
114 LogPrintf(
"Initializing chainstate %s\n", chainstate->ToString());
116 chainstate->InitCoinsDB(
117 chainman.m_total_coinsdb_cache *
119 options.coins_db_in_memory,
120 options.reindex || options.reindex_chainstate);
122 if (options.coins_error_cb) {
123 chainstate->CoinsErrorCatcher().AddReadErrCallback(
124 options.coins_error_cb);
130 if (!chainstate->CoinsDB().Upgrade()) {
132 _(
"Error upgrading chainstate database")};
137 if (!chainstate->ReplayBlocks()) {
139 _(
"Unable to replay blocks. You will need to rebuild the "
140 "database using -reindex-chainstate.")};
144 chainstate->InitCoinsCache(chainman.m_total_coinstip_cache *
145 init_cache_fraction);
146 assert(chainstate->CanFlushToDisk());
148 if (!is_coinsview_empty(chainstate)) {
151 if (!chainstate->LoadChainTip()) {
153 _(
"Error initializing block database")};
155 assert(chainstate->m_chain.Tip() !=
nullptr);
162 chainman.MaybeRebalanceCaches();
171 LogPrintf(
"Assuming ancestors of block %s have valid signatures.\n",
174 LogPrintf(
"Validating signatures for all blocks.\n");
176 LogPrintf(
"Setting nMinimumChainWork=%s\n",
180 LogPrintf(
"Warning: nMinimumChainWork set below default value of %s\n",
186 "Block pruning enabled. Use RPC call pruneblockchain(height) to "
187 "manually prune block and undo files.\n");
189 LogPrintf(
"Prune configured to target %u MiB on disk for block and "
199 chainman.InitializeChainstate(options.
mempool);
202 chainman.DetectSnapshotChainstate(options.
mempool);
205 auto [init_status, init_error] =
208 return {init_status, init_error};
220 auto snapshot_completion = chainman.MaybeCompleteSnapshotValidation();
225 LogPrintf(
"[snapshot] cleaning up unneeded background chainstate, then "
227 if (!chainman.ValidatedSnapshotCleanup()) {
230 "Background chainstate cleanup failed unexpectedly.")};
240 chainman.InitializeChainstate(options.
mempool);
246 auto [init_status, init_error] =
249 return {init_status, init_error};
253 _(
"UTXO snapshot failed to validate. "
254 "Restart to resume normal initial block download, or try "
255 "loading a different snapshot.")};
264 auto is_coinsview_empty =
267 chainstate->CoinsTip().GetBestBlock().IsNull();
273 if (!is_coinsview_empty(chainstate)) {
274 const CBlockIndex *tip = chainstate->m_chain.Tip();
277 _(
"The block database contains a block which appears "
278 "to be from the future. "
279 "This may be due to your computer's date and time "
280 "being set incorrectly. "
281 "Only rebuild the block database if you are sure "
282 "that your computer's date and time are correct")};
287 .
VerifyDB(*chainstate, chainstate->CoinsDB(),
295 _(
"Block verification was interrupted")};
298 _(
"Corrupted block database detected")};
303 _(
"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...
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
kernel::Notifications & GetNotifications() const
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
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)
This sequence can have 4 types of outcomes:
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.