Skip to content

Commit cb64af9

Browse files
committed
node: Extract chainstate loading sequence
I strongly recommend reviewing with the following git-diff flags: --color-moved=dimmed_zebra --color-moved-ws=allow-indentation-change [META] This commit is intended to be as close to a move-only commit as possible, and lingering ugliness will be resolved in subsequent commits. A few variables that are passed in by value instead of by reference deserve explanation: - fReset and fReindexChainstate are both local variables in AppInitMain and are not modified in the sequence - fPruneMode, despite being a global, is only modified in AppInitParameterInteraction, long before LoadChainstate is called ---- [META] This semantic will change in a future commit named "node/chainstate: Decouple from stringy errors"
1 parent 786ffb3 commit cb64af9

File tree

4 files changed

+268
-173
lines changed

4 files changed

+268
-173
lines changed

src/Makefile.am

+2
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ BITCOIN_CORE_H = \
174174
netbase.h \
175175
netmessagemaker.h \
176176
node/blockstorage.h \
177+
node/chainstate.h \
177178
node/coin.h \
178179
node/coinstats.h \
179180
node/context.h \
@@ -339,6 +340,7 @@ libbitcoin_server_a_SOURCES = \
339340
net.cpp \
340341
net_processing.cpp \
341342
node/blockstorage.cpp \
343+
node/chainstate.cpp \
342344
node/coin.cpp \
343345
node/coinstats.cpp \
344346
node/context.cpp \

src/init.cpp

+14-173
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include <net_processing.h>
3535
#include <netbase.h>
3636
#include <node/blockstorage.h>
37+
#include <node/chainstate.h> // for LoadChainstate
3738
#include <node/context.h>
3839
#include <node/miner.h>
3940
#include <node/ui_interface.h>
@@ -1414,183 +1415,23 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14141415
bool fLoaded = false;
14151416
while (!fLoaded && !ShutdownRequested()) {
14161417
const bool fReset = fReindex;
1417-
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1418-
return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1419-
};
14201418
bilingual_str strLoadError;
14211419

14221420
uiInterface.InitMessage(_("Loading block index…").translated);
14231421

1424-
do {
1425-
const int64_t load_block_index_start_time = GetTimeMillis();
1426-
try {
1427-
LOCK(cs_main);
1428-
chainman.InitializeChainstate(Assert(node.mempool.get()));
1429-
chainman.m_total_coinstip_cache = nCoinCacheUsage;
1430-
chainman.m_total_coinsdb_cache = nCoinDBCache;
1431-
1432-
UnloadBlockIndex(node.mempool.get(), chainman);
1433-
1434-
auto& pblocktree{chainman.m_blockman.m_block_tree_db};
1435-
// new CBlockTreeDB tries to delete the existing file, which
1436-
// fails if it's still open from the previous loop. Close it first:
1437-
pblocktree.reset();
1438-
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1439-
1440-
if (fReset) {
1441-
pblocktree->WriteReindexing(true);
1442-
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1443-
if (fPruneMode)
1444-
CleanupBlockRevFiles();
1445-
}
1446-
1447-
if (ShutdownRequested()) break;
1448-
1449-
// LoadBlockIndex will load fHavePruned if we've ever removed a
1450-
// block file from disk.
1451-
// Note that it also sets fReindex based on the disk flag!
1452-
// From here on out fReindex and fReset mean something different!
1453-
if (!chainman.LoadBlockIndex()) {
1454-
if (ShutdownRequested()) break;
1455-
strLoadError = _("Error loading block database");
1456-
break;
1457-
}
1458-
1459-
// If the loaded chain has a wrong genesis, bail out immediately
1460-
// (we're likely using a testnet datadir, or the other way around).
1461-
if (!chainman.BlockIndex().empty() &&
1462-
!chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1463-
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1464-
}
1465-
1466-
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1467-
// in the past, but is now trying to run unpruned.
1468-
if (fHavePruned && !fPruneMode) {
1469-
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1470-
break;
1471-
}
1472-
1473-
// At this point blocktree args are consistent with what's on disk.
1474-
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
1475-
// (otherwise we use the one already on disk).
1476-
// This is called again in ThreadImport after the reindex completes.
1477-
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
1478-
strLoadError = _("Error initializing block database");
1479-
break;
1480-
}
1481-
1482-
// At this point we're either in reindex or we've loaded a useful
1483-
// block tree into BlockIndex()!
1484-
1485-
bool failed_chainstate_init = false;
1486-
1487-
for (CChainState* chainstate : chainman.GetAll()) {
1488-
chainstate->InitCoinsDB(
1489-
/* cache_size_bytes */ nCoinDBCache,
1490-
/* in_memory */ false,
1491-
/* should_wipe */ fReset || fReindexChainState);
1492-
1493-
chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1494-
uiInterface.ThreadSafeMessageBox(
1495-
_("Error reading from database, shutting down."),
1496-
"", CClientUIInterface::MSG_ERROR);
1497-
});
1498-
1499-
// If necessary, upgrade from older database format.
1500-
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1501-
if (!chainstate->CoinsDB().Upgrade()) {
1502-
strLoadError = _("Error upgrading chainstate database");
1503-
failed_chainstate_init = true;
1504-
break;
1505-
}
1506-
1507-
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1508-
if (!chainstate->ReplayBlocks()) {
1509-
strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1510-
failed_chainstate_init = true;
1511-
break;
1512-
}
1513-
1514-
// The on-disk coinsdb is now in a good state, create the cache
1515-
chainstate->InitCoinsCache(nCoinCacheUsage);
1516-
assert(chainstate->CanFlushToDisk());
1517-
1518-
if (!is_coinsview_empty(chainstate)) {
1519-
// LoadChainTip initializes the chain based on CoinsTip()'s best block
1520-
if (!chainstate->LoadChainTip()) {
1521-
strLoadError = _("Error initializing block database");
1522-
failed_chainstate_init = true;
1523-
break; // out of the per-chainstate loop
1524-
}
1525-
assert(chainstate->m_chain.Tip() != nullptr);
1526-
}
1527-
}
1528-
1529-
if (failed_chainstate_init) {
1530-
break; // out of the chainstate activation do-while
1531-
}
1532-
} catch (const std::exception& e) {
1533-
LogPrintf("%s\n", e.what());
1534-
strLoadError = _("Error opening block database");
1535-
break;
1536-
}
1537-
1538-
if (!fReset) {
1539-
LOCK(cs_main);
1540-
auto chainstates{chainman.GetAll()};
1541-
if (std::any_of(chainstates.begin(), chainstates.end(),
1542-
[](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
1543-
strLoadError = strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
1544-
chainparams.GetConsensus().SegwitHeight);
1545-
break;
1546-
}
1547-
}
1548-
1549-
bool failed_verification = false;
1550-
1551-
try {
1552-
LOCK(cs_main);
1553-
1554-
for (CChainState* chainstate : chainman.GetAll()) {
1555-
if (!is_coinsview_empty(chainstate)) {
1556-
uiInterface.InitMessage(_("Verifying blocks…").translated);
1557-
if (fHavePruned && args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1558-
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1559-
MIN_BLOCKS_TO_KEEP);
1560-
}
1561-
1562-
const CBlockIndex* tip = chainstate->m_chain.Tip();
1563-
RPCNotifyBlockChange(tip);
1564-
if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
1565-
strLoadError = _("The block database contains a block which appears to be from the future. "
1566-
"This may be due to your computer's date and time being set incorrectly. "
1567-
"Only rebuild the block database if you are sure that your computer's date and time are correct");
1568-
failed_verification = true;
1569-
break;
1570-
}
1571-
1572-
if (!CVerifyDB().VerifyDB(
1573-
*chainstate, chainparams, chainstate->CoinsDB(),
1574-
args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL),
1575-
args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1576-
strLoadError = _("Corrupted block database detected");
1577-
failed_verification = true;
1578-
break;
1579-
}
1580-
}
1581-
}
1582-
} catch (const std::exception& e) {
1583-
LogPrintf("%s\n", e.what());
1584-
strLoadError = _("Error opening block database");
1585-
failed_verification = true;
1586-
break;
1587-
}
1588-
1589-
if (!failed_verification) {
1590-
fLoaded = true;
1591-
LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1592-
}
1593-
} while(false);
1422+
bool rv = LoadChainstate(fLoaded,
1423+
strLoadError,
1424+
fReset,
1425+
chainman,
1426+
node,
1427+
fPruneMode,
1428+
chainparams,
1429+
args,
1430+
fReindexChainState,
1431+
nBlockTreeDBCache,
1432+
nCoinDBCache,
1433+
nCoinCacheUsage);
1434+
if (!rv) return false;
15941435

15951436
if (!fLoaded && !ShutdownRequested()) {
15961437
// first suggest a reindex

0 commit comments

Comments
 (0)