Skip to content

Commit b3e7de7

Browse files
committed
refactor: Reduce number of LoadChainstate return values
1 parent 3b91d4b commit b3e7de7

File tree

5 files changed

+65
-137
lines changed

5 files changed

+65
-137
lines changed

src/bitcoin-chainstate.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,13 @@ int main(int argc, char* argv[])
9090
cache_sizes.coins = (450 << 20) - (2 << 20) - (2 << 22);
9191
node::ChainstateLoadOptions options;
9292
options.check_interrupt = [] { return false; };
93-
auto rv = node::LoadChainstate(chainman, cache_sizes, options);
94-
if (rv.has_value()) {
93+
auto [status, error] = node::LoadChainstate(chainman, cache_sizes, options);
94+
if (status != node::ChainstateLoadStatus::SUCCESS) {
9595
std::cerr << "Failed to load Chain state from your datadir." << std::endl;
9696
goto epilogue;
9797
} else {
98-
auto maybe_verify_error = node::VerifyLoadedChainstate(chainman, options);
99-
if (maybe_verify_error.has_value()) {
98+
std::tie(status, error) = node::VerifyLoadedChainstate(chainman, options);
99+
if (status != node::ChainstateLoadStatus::SUCCESS) {
100100
std::cerr << "Failed to verify loaded Chain state from your datadir." << std::endl;
101101
goto epilogue;
102102
}

src/init.cpp

Lines changed: 20 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,6 @@ using kernel::DumpMempool;
108108

109109
using node::CacheSizes;
110110
using node::CalculateCacheSizes;
111-
using node::ChainstateLoadVerifyError;
112-
using node::ChainstateLoadingError;
113111
using node::DEFAULT_PERSIST_MEMPOOL;
114112
using node::DEFAULT_PRINTPRIORITY;
115113
using node::DEFAULT_STOPAFTERBLOCKIMPORT;
@@ -1452,8 +1450,6 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14521450
node.chainman = std::make_unique<ChainstateManager>(chainman_opts);
14531451
ChainstateManager& chainman = *node.chainman;
14541452

1455-
bilingual_str strLoadError;
1456-
14571453
node::ChainstateLoadOptions options;
14581454
options.mempool = Assert(node.mempool.get());
14591455
options.reindex = node::fReindex;
@@ -1470,87 +1466,38 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14701466

14711467
uiInterface.InitMessage(_("Loading block index…").translated);
14721468
const int64_t load_block_index_start_time = GetTimeMillis();
1473-
std::optional<ChainstateLoadingError> maybe_load_error;
1474-
try {
1475-
maybe_load_error = LoadChainstate(chainman, cache_sizes, options);
1476-
} catch (const std::exception& e) {
1477-
LogPrintf("%s\n", e.what());
1478-
maybe_load_error = ChainstateLoadingError::ERROR_GENERIC_BLOCKDB_OPEN_FAILED;
1479-
}
1480-
if (maybe_load_error.has_value()) {
1481-
switch (maybe_load_error.value()) {
1482-
case ChainstateLoadingError::ERROR_LOADING_BLOCK_DB:
1483-
strLoadError = _("Error loading block database");
1484-
break;
1485-
case ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK:
1486-
// If the loaded chain has a wrong genesis, bail out immediately
1487-
// (we're likely using a testnet datadir, or the other way around).
1488-
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1489-
case ChainstateLoadingError::ERROR_PRUNED_NEEDS_REINDEX:
1490-
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1491-
break;
1492-
case ChainstateLoadingError::ERROR_LOAD_GENESIS_BLOCK_FAILED:
1493-
strLoadError = _("Error initializing block database");
1494-
break;
1495-
case ChainstateLoadingError::ERROR_CHAINSTATE_UPGRADE_FAILED:
1496-
return InitError(_("Unsupported chainstate database format found. "
1497-
"Please restart with -reindex-chainstate. This will "
1498-
"rebuild the chainstate database."));
1499-
case ChainstateLoadingError::ERROR_REPLAYBLOCKS_FAILED:
1500-
strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1501-
break;
1502-
case ChainstateLoadingError::ERROR_LOADCHAINTIP_FAILED:
1503-
strLoadError = _("Error initializing block database");
1504-
break;
1505-
case ChainstateLoadingError::ERROR_GENERIC_BLOCKDB_OPEN_FAILED:
1506-
strLoadError = _("Error opening block database");
1507-
break;
1508-
case ChainstateLoadingError::ERROR_BLOCKS_WITNESS_INSUFFICIENTLY_VALIDATED:
1509-
strLoadError = strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
1510-
chainman.GetConsensus().SegwitHeight);
1511-
break;
1512-
case ChainstateLoadingError::SHUTDOWN_PROBED:
1513-
break;
1514-
}
1515-
} else {
1516-
std::optional<ChainstateLoadVerifyError> maybe_verify_error;
1469+
auto catch_exceptions = [](auto&& f) {
15171470
try {
1518-
uiInterface.InitMessage(_("Verifying blocks…").translated);
1519-
if (chainman.m_blockman.m_have_pruned && options.check_blocks > MIN_BLOCKS_TO_KEEP) {
1520-
LogPrintfCategory(BCLog::PRUNE, "pruned datadir may not have more than %d blocks; only checking available blocks\n",
1521-
MIN_BLOCKS_TO_KEEP);
1522-
}
1523-
maybe_verify_error = VerifyLoadedChainstate(chainman, options);
1471+
return f();
15241472
} catch (const std::exception& e) {
15251473
LogPrintf("%s\n", e.what());
1526-
maybe_verify_error = ChainstateLoadVerifyError::ERROR_GENERIC_FAILURE;
1474+
return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error opening block database"));
15271475
}
1528-
if (maybe_verify_error.has_value()) {
1529-
switch (maybe_verify_error.value()) {
1530-
case ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE:
1531-
strLoadError = _("The block database contains a block which appears to be from the future. "
1532-
"This may be due to your computer's date and time being set incorrectly. "
1533-
"Only rebuild the block database if you are sure that your computer's date and time are correct");
1534-
break;
1535-
case ChainstateLoadVerifyError::ERROR_CORRUPTED_BLOCK_DB:
1536-
strLoadError = _("Corrupted block database detected");
1537-
break;
1538-
case ChainstateLoadVerifyError::ERROR_GENERIC_FAILURE:
1539-
strLoadError = _("Error opening block database");
1540-
break;
1541-
}
1542-
} else {
1476+
};
1477+
auto [status, error] = catch_exceptions([&]{ return LoadChainstate(chainman, cache_sizes, options); });
1478+
if (status == node::ChainstateLoadStatus::SUCCESS) {
1479+
uiInterface.InitMessage(_("Verifying blocks…").translated);
1480+
if (chainman.m_blockman.m_have_pruned && options.check_blocks > MIN_BLOCKS_TO_KEEP) {
1481+
LogPrintfCategory(BCLog::PRUNE, "pruned datadir may not have more than %d blocks; only checking available blocks\n",
1482+
MIN_BLOCKS_TO_KEEP);
1483+
}
1484+
std::tie(status, error) = catch_exceptions([&]{ return VerifyLoadedChainstate(chainman, options);});
1485+
if (status == node::ChainstateLoadStatus::SUCCESS) {
15431486
fLoaded = true;
15441487
LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
15451488
}
15461489
}
15471490

1491+
if (status == node::ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB) {
1492+
return InitError(error);
1493+
}
1494+
15481495
if (!fLoaded && !ShutdownRequested()) {
15491496
// first suggest a reindex
15501497
if (!options.reindex) {
15511498
bool fRet = uiInterface.ThreadSafeQuestion(
1552-
strLoadError + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"),
1553-
strLoadError.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1499+
error + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"),
1500+
error.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
15541501
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
15551502
if (fRet) {
15561503
fReindex = true;
@@ -1560,7 +1507,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
15601507
return false;
15611508
}
15621509
} else {
1563-
return InitError(strLoadError);
1510+
return InitError(error);
15641511
}
15651512
}
15661513
}

src/node/chainstate.cpp

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
#include <vector>
2424

2525
namespace node {
26-
std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes,
27-
const ChainstateLoadOptions& options)
26+
ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes,
27+
const ChainstateLoadOptions& options)
2828
{
2929
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
3030
return options.reindex || options.reindex_chainstate || chainstate->CoinsTip().GetBestBlock().IsNull();
@@ -49,34 +49,36 @@ std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman
4949
}
5050
}
5151

52-
if (options.check_interrupt && options.check_interrupt()) return ChainstateLoadingError::SHUTDOWN_PROBED;
52+
if (options.check_interrupt && options.check_interrupt()) return {ChainstateLoadStatus::INTERRUPTED, {}};
5353

5454
// LoadBlockIndex will load m_have_pruned if we've ever removed a
5555
// block file from disk.
5656
// Note that it also sets fReindex global based on the disk flag!
5757
// From here on, fReindex and options.reindex values may be different!
5858
if (!chainman.LoadBlockIndex()) {
59-
if (options.check_interrupt && options.check_interrupt()) return ChainstateLoadingError::SHUTDOWN_PROBED;
60-
return ChainstateLoadingError::ERROR_LOADING_BLOCK_DB;
59+
if (options.check_interrupt && options.check_interrupt()) return {ChainstateLoadStatus::INTERRUPTED, {}};
60+
return {ChainstateLoadStatus::FAILURE, _("Error loading block database")};
6161
}
6262

6363
if (!chainman.BlockIndex().empty() &&
6464
!chainman.m_blockman.LookupBlockIndex(chainman.GetConsensus().hashGenesisBlock)) {
65-
return ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK;
65+
// If the loaded chain has a wrong genesis, bail out immediately
66+
// (we're likely using a testnet datadir, or the other way around).
67+
return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Incorrect or no genesis block found. Wrong datadir for network?")};
6668
}
6769

6870
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
6971
// in the past, but is now trying to run unpruned.
7072
if (chainman.m_blockman.m_have_pruned && !options.prune) {
71-
return ChainstateLoadingError::ERROR_PRUNED_NEEDS_REINDEX;
73+
return {ChainstateLoadStatus::FAILURE, _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain")};
7274
}
7375

7476
// At this point blocktree args are consistent with what's on disk.
7577
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
7678
// (otherwise we use the one already on disk).
7779
// This is called again in ThreadImport after the reindex completes.
7880
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
79-
return ChainstateLoadingError::ERROR_LOAD_GENESIS_BLOCK_FAILED;
81+
return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
8082
}
8183

8284
// At this point we're either in reindex or we've loaded a useful
@@ -95,12 +97,14 @@ std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman
9597
// Refuse to load unsupported database format.
9698
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
9799
if (chainstate->CoinsDB().NeedsUpgrade()) {
98-
return ChainstateLoadingError::ERROR_CHAINSTATE_UPGRADE_FAILED;
100+
return {ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB, _("Unsupported chainstate database format found. "
101+
"Please restart with -reindex-chainstate. This will "
102+
"rebuild the chainstate database.")};
99103
}
100104

101105
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
102106
if (!chainstate->ReplayBlocks()) {
103-
return ChainstateLoadingError::ERROR_REPLAYBLOCKS_FAILED;
107+
return {ChainstateLoadStatus::FAILURE, _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.")};
104108
}
105109

106110
// The on-disk coinsdb is now in a good state, create the cache
@@ -110,7 +114,7 @@ std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman
110114
if (!is_coinsview_empty(chainstate)) {
111115
// LoadChainTip initializes the chain based on CoinsTip()'s best block
112116
if (!chainstate->LoadChainTip()) {
113-
return ChainstateLoadingError::ERROR_LOADCHAINTIP_FAILED;
117+
return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
114118
}
115119
assert(chainstate->m_chain.Tip() != nullptr);
116120
}
@@ -120,15 +124,15 @@ std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman
120124
auto chainstates{chainman.GetAll()};
121125
if (std::any_of(chainstates.begin(), chainstates.end(),
122126
[](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
123-
return ChainstateLoadingError::ERROR_BLOCKS_WITNESS_INSUFFICIENTLY_VALIDATED;
124-
}
127+
return {ChainstateLoadStatus::FAILURE, strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
128+
chainman.GetConsensus().SegwitHeight)};
129+
};
125130
}
126131

127-
return std::nullopt;
132+
return {ChainstateLoadStatus::SUCCESS, {}};
128133
}
129134

130-
std::optional<ChainstateLoadVerifyError> VerifyLoadedChainstate(ChainstateManager& chainman,
131-
const ChainstateLoadOptions& options)
135+
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const ChainstateLoadOptions& options)
132136
{
133137
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
134138
return options.reindex || options.reindex_chainstate || chainstate->CoinsTip().GetBestBlock().IsNull();
@@ -140,18 +144,20 @@ std::optional<ChainstateLoadVerifyError> VerifyLoadedChainstate(ChainstateManage
140144
if (!is_coinsview_empty(chainstate)) {
141145
const CBlockIndex* tip = chainstate->m_chain.Tip();
142146
if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
143-
return ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE;
147+
return {ChainstateLoadStatus::FAILURE, _("The block database contains a block which appears to be from the future. "
148+
"This may be due to your computer's date and time being set incorrectly. "
149+
"Only rebuild the block database if you are sure that your computer's date and time are correct")};
144150
}
145151

146152
if (!CVerifyDB().VerifyDB(
147153
*chainstate, chainman.GetConsensus(), chainstate->CoinsDB(),
148154
options.check_level,
149155
options.check_blocks)) {
150-
return ChainstateLoadVerifyError::ERROR_CORRUPTED_BLOCK_DB;
156+
return {ChainstateLoadStatus::FAILURE, _("Corrupted block database detected")};
151157
}
152158
}
153159
}
154160

155-
return std::nullopt;
161+
return {ChainstateLoadStatus::SUCCESS, {}};
156162
}
157163
} // namespace node

src/node/chainstate.h

Lines changed: 12 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -31,18 +31,14 @@ struct ChainstateLoadOptions {
3131
std::function<void()> coins_error_cb;
3232
};
3333

34-
enum class ChainstateLoadingError {
35-
ERROR_LOADING_BLOCK_DB,
36-
ERROR_BAD_GENESIS_BLOCK,
37-
ERROR_PRUNED_NEEDS_REINDEX,
38-
ERROR_LOAD_GENESIS_BLOCK_FAILED,
39-
ERROR_CHAINSTATE_UPGRADE_FAILED,
40-
ERROR_REPLAYBLOCKS_FAILED,
41-
ERROR_LOADCHAINTIP_FAILED,
42-
ERROR_GENERIC_BLOCKDB_OPEN_FAILED,
43-
ERROR_BLOCKS_WITNESS_INSUFFICIENTLY_VALIDATED,
44-
SHUTDOWN_PROBED,
45-
};
34+
//! Chainstate load status. Simple applications can just check for the success
35+
//! case, and treat other cases as errors. More complex applications may want to
36+
//! try reindexing in the generic failure case, and pass an interrupt callback
37+
//! and exit cleanly in the interrupted case.
38+
enum class ChainstateLoadStatus { SUCCESS, FAILURE, FAILURE_INCOMPATIBLE_DB, INTERRUPTED };
39+
40+
//! Chainstate load status code and optional error string.
41+
using ChainstateLoadResult = std::tuple<ChainstateLoadStatus, bilingual_str>;
4642

4743
/** This sequence can have 4 types of outcomes:
4844
*
@@ -55,32 +51,11 @@ enum class ChainstateLoadingError {
5551
* 4. Hard failure
5652
* - a failure that definitively cannot be recovered from with a reindex
5753
*
58-
* Currently, LoadChainstate returns a std::optional<ChainstateLoadingError>
59-
* which:
60-
*
61-
* - if has_value()
62-
* - Either "Soft failure", "Hard failure", or "Shutdown requested",
63-
* differentiable by the specific enumerator.
64-
*
65-
* Note that a return value of SHUTDOWN_PROBED means ONLY that "during
66-
* this sequence, when we explicitly checked shutdown_requested() at
67-
* arbitrary points, one of those calls returned true". Therefore, a
68-
* return value other than SHUTDOWN_PROBED does not guarantee that
69-
* shutdown hasn't been called indirectly.
70-
* - else
71-
* - Success!
54+
* LoadChainstate returns a (status code, error string) tuple.
7255
*/
73-
std::optional<ChainstateLoadingError> LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes,
74-
const ChainstateLoadOptions& options);
75-
76-
enum class ChainstateLoadVerifyError {
77-
ERROR_BLOCK_FROM_FUTURE,
78-
ERROR_CORRUPTED_BLOCK_DB,
79-
ERROR_GENERIC_FAILURE,
80-
};
81-
82-
std::optional<ChainstateLoadVerifyError> VerifyLoadedChainstate(ChainstateManager& chainman,
83-
const ChainstateLoadOptions& options);
56+
ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes,
57+
const ChainstateLoadOptions& options);
58+
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const ChainstateLoadOptions& options);
8459
} // namespace node
8560

8661
#endif // BITCOIN_NODE_CHAINSTATE_H

src/test/util/setup_common.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -225,11 +225,11 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const
225225
options.prune = node::fPruneMode;
226226
options.check_blocks = m_args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
227227
options.check_level = m_args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
228-
auto maybe_load_error = LoadChainstate(*Assert(m_node.chainman), m_cache_sizes, options);
229-
assert(!maybe_load_error.has_value());
228+
auto [status, error] = LoadChainstate(*Assert(m_node.chainman), m_cache_sizes, options);
229+
assert(status == node::ChainstateLoadStatus::SUCCESS);
230230

231-
auto maybe_verify_error = VerifyLoadedChainstate(*Assert(m_node.chainman), options);
232-
assert(!maybe_verify_error.has_value());
231+
std::tie(status, error) = VerifyLoadedChainstate(*Assert(m_node.chainman), options);
232+
assert(status == node::ChainstateLoadStatus::SUCCESS);
233233

234234
BlockValidationState state;
235235
if (!m_node.chainman->ActiveChainstate().ActivateBestChain(state)) {

0 commit comments

Comments
 (0)