Skip to content

Commit 058af75

Browse files
committed
Merge bitcoin/bitcoin#29817: kernel: De-globalize fReindex
b47bd95 kernel: De-globalize fReindex (TheCharlatan) Pull request description: fReindex is one of the last remaining globals exposed by the kernel library, so move it into the blockstorage class to reduce the amount of global mutable state and make the kernel library a bit less awkward to use. --- This pull request is part of the [libbitcoinkernel project](bitcoin/bitcoin#27587). ACKs for top commit: achow101: ACK b47bd95 ryanofsky: Code review ACK b47bd95. I rereviewed the whole PR, but the only change since last review was reverting the bugfix bitcoin/bitcoin#29817 (comment) and make the change a pure refactoring. mzumsande: Code Review ACK b47bd95 stickies-v: ACK b47bd95 Tree-SHA512: f7399d01f93bc0c0c7428fe95d19b9d29b4ed00a4f1deabca78fb0c4fecb434ec971e890feecb105938b5247c926850b1b7b4a4a9caa333a061e40777d0c8463
2 parents 4877fcd + b47bd95 commit 058af75

File tree

9 files changed

+40
-35
lines changed

9 files changed

+40
-35
lines changed

src/bitcoin-chainstate.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ int main(int argc, char* argv[])
151151
{
152152
LOCK(chainman.GetMutex());
153153
std::cout
154-
<< "\t" << "Reindexing: " << std::boolalpha << node::fReindex.load() << std::noboolalpha << std::endl
154+
<< "\t" << "Reindexing: " << std::boolalpha << chainman.m_blockman.m_reindexing.load() << std::noboolalpha << std::endl
155155
<< "\t" << "Snapshot Active: " << std::boolalpha << chainman.IsSnapshotActive() << std::noboolalpha << std::endl
156156
<< "\t" << "Active Height: " << chainman.ActiveHeight() << std::endl
157157
<< "\t" << "Active IBD: " << std::boolalpha << chainman.IsInitialBlockDownload() << std::noboolalpha << std::endl;

src/init.cpp

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,6 @@ using node::CalculateCacheSizes;
126126
using node::DEFAULT_PERSIST_MEMPOOL;
127127
using node::DEFAULT_PRINTPRIORITY;
128128
using node::DEFAULT_STOPATHEIGHT;
129-
using node::fReindex;
130129
using node::KernelNotifications;
131130
using node::LoadChainstate;
132131
using node::MempoolPath;
@@ -1483,7 +1482,6 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14831482

14841483
node.notifications = std::make_unique<KernelNotifications>(*Assert(node.shutdown), node.exit_status);
14851484
ReadNotificationArgs(args, *node.notifications);
1486-
fReindex = args.GetBoolArg("-reindex", false);
14871485
bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
14881486
ChainstateManager::Options chainman_opts{
14891487
.chainparams = chainparams,
@@ -1560,7 +1558,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
15601558

15611559
node::ChainstateLoadOptions options;
15621560
options.mempool = Assert(node.mempool.get());
1563-
options.reindex = node::fReindex;
1561+
options.reindex = chainman.m_blockman.m_reindexing;
15641562
options.reindex_chainstate = fReindexChainState;
15651563
options.prune = chainman.m_blockman.IsPruneMode();
15661564
options.check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
@@ -1608,7 +1606,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16081606
error.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
16091607
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
16101608
if (fRet) {
1611-
fReindex = true;
1609+
chainman.m_blockman.m_reindexing = true;
16121610
if (!Assert(node.shutdown)->reset()) {
16131611
LogPrintf("Internal error: failed to reset shutdown signal.\n");
16141612
}
@@ -1641,17 +1639,17 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16411639
// ********************************************************* Step 8: start indexers
16421640

16431641
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1644-
g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), cache_sizes.tx_index, false, fReindex);
1642+
g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), cache_sizes.tx_index, false, chainman.m_blockman.m_reindexing);
16451643
node.indexes.emplace_back(g_txindex.get());
16461644
}
16471645

16481646
for (const auto& filter_type : g_enabled_filter_types) {
1649-
InitBlockFilterIndex([&]{ return interfaces::MakeChain(node); }, filter_type, cache_sizes.filter_index, false, fReindex);
1647+
InitBlockFilterIndex([&]{ return interfaces::MakeChain(node); }, filter_type, cache_sizes.filter_index, false, chainman.m_blockman.m_reindexing);
16501648
node.indexes.emplace_back(GetBlockFilterIndex(filter_type));
16511649
}
16521650

16531651
if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1654-
g_coin_stats_index = std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*cache_size=*/0, false, fReindex);
1652+
g_coin_stats_index = std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*cache_size=*/0, false, chainman.m_blockman.m_reindexing);
16551653
node.indexes.emplace_back(g_coin_stats_index.get());
16561654
}
16571655

@@ -1670,7 +1668,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16701668
// if pruning, perform the initial blockstore prune
16711669
// after any wallet rescanning has taken place.
16721670
if (chainman.m_blockman.IsPruneMode()) {
1673-
if (!fReindex) {
1671+
if (!chainman.m_blockman.m_reindexing) {
16741672
LOCK(cs_main);
16751673
for (Chainstate* chainstate : chainman.GetAll()) {
16761674
uiInterface.InitMessage(_("Pruning blockstore…").translated);
@@ -1696,7 +1694,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16961694
int chain_active_height = WITH_LOCK(cs_main, return chainman.ActiveChain().Height());
16971695

16981696
// On first startup, warn on low block storage space
1699-
if (!fReindex && !fReindexChainState && chain_active_height <= 1) {
1697+
if (!chainman.m_blockman.m_reindexing && !fReindexChainState && chain_active_height <= 1) {
17001698
uint64_t assumed_chain_bytes{chainparams.AssumedBlockchainSize() * 1024 * 1024 * 1024};
17011699
uint64_t additional_bytes_needed{
17021700
chainman.m_blockman.IsPruneMode() ?

src/kernel/blockmanager_opts.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ struct BlockManagerOpts {
2424
bool fast_prune{false};
2525
const fs::path blocks_dir;
2626
Notifications& notifications;
27+
bool reindex{false};
2728
};
2829

2930
} // namespace kernel

src/node/blockmanager_args.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ util::Result<void> ApplyArgsManOptions(const ArgsManager& args, BlockManager::Op
3333

3434
if (auto value{args.GetBoolArg("-fastprune")}) opts.fast_prune = *value;
3535

36+
if (auto value{args.GetBoolArg("-reindex")}) opts.reindex = *value;
37+
3638
return {};
3739
}
3840
} // namespace node

src/node/blockstorage.cpp

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,6 @@ bool BlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, s
150150
} // namespace kernel
151151

152152
namespace node {
153-
std::atomic_bool fReindex(false);
154153

155154
bool CBlockIndexWorkComparator::operator()(const CBlockIndex* pa, const CBlockIndex* pb) const
156155
{
@@ -552,7 +551,7 @@ bool BlockManager::LoadBlockIndexDB(const std::optional<uint256>& snapshot_block
552551
// Check whether we need to continue reindexing
553552
bool fReindexing = false;
554553
m_block_tree_db->ReadReindexing(fReindexing);
555-
if (fReindexing) fReindex = true;
554+
if (fReindexing) m_reindexing = true;
556555

557556
return true;
558557
}
@@ -1183,7 +1182,7 @@ void ImportBlocks(ChainstateManager& chainman, std::vector<fs::path> vImportFile
11831182
ImportingNow imp{chainman.m_blockman.m_importing};
11841183

11851184
// -reindex
1186-
if (fReindex) {
1185+
if (chainman.m_blockman.m_reindexing) {
11871186
int nFile = 0;
11881187
// Map of disk positions for blocks with unknown parent (only used for reindex);
11891188
// parent hash -> child disk position, multiple children can have the same parent.
@@ -1206,7 +1205,7 @@ void ImportBlocks(ChainstateManager& chainman, std::vector<fs::path> vImportFile
12061205
nFile++;
12071206
}
12081207
WITH_LOCK(::cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1209-
fReindex = false;
1208+
chainman.m_blockman.m_reindexing = false;
12101209
LogPrintf("Reindexing finished\n");
12111210
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
12121211
chainman.ActiveChainstate().LoadGenesisBlock();

src/node/blockstorage.h

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,6 @@ static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
7676
/** Size of header written by WriteBlockToDisk before a serialized CBlock */
7777
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE = std::tuple_size_v<MessageStartChars> + sizeof(unsigned int);
7878

79-
extern std::atomic_bool fReindex;
80-
8179
// Because validation code takes pointers to the map's CBlockIndex objects, if
8280
// we ever switch to another associative container, we need to either use a
8381
// container that has stable addressing (true of all std associative
@@ -269,11 +267,19 @@ class BlockManager
269267
explicit BlockManager(const util::SignalInterrupt& interrupt, Options opts)
270268
: m_prune_mode{opts.prune_target > 0},
271269
m_opts{std::move(opts)},
272-
m_interrupt{interrupt} {};
270+
m_interrupt{interrupt},
271+
m_reindexing{m_opts.reindex} {};
273272

274273
const util::SignalInterrupt& m_interrupt;
275274
std::atomic<bool> m_importing{false};
276275

276+
/**
277+
* Tracks if a reindex is currently in progress. Set to true when a reindex
278+
* is requested and false when reindexing completes. Its value is persisted
279+
* in the BlockTreeDB across restarts.
280+
*/
281+
std::atomic_bool m_reindexing;
282+
277283
BlockMap m_block_index GUARDED_BY(cs_main);
278284

279285
/**
@@ -353,7 +359,7 @@ class BlockManager
353359
[[nodiscard]] uint64_t GetPruneTarget() const { return m_opts.prune_target; }
354360
static constexpr auto PRUNE_TARGET_MANUAL{std::numeric_limits<uint64_t>::max()};
355361

356-
[[nodiscard]] bool LoadingBlocks() const { return m_importing || fReindex; }
362+
[[nodiscard]] bool LoadingBlocks() const { return m_importing || m_reindexing; }
357363

358364
/** Calculate the amount of disk space the block & undo files currently use */
359365
uint64_t CalculateCurrentUsage();

src/node/chainstate.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ static ChainstateLoadResult CompleteChainstateInitialization(
6060

6161
// LoadBlockIndex will load m_have_pruned if we've ever removed a
6262
// block file from disk.
63-
// Note that it also sets fReindex global based on the disk flag!
64-
// From here on, fReindex and options.reindex values may be different!
63+
// Note that it also sets m_reindexing based on the disk flag!
64+
// From here on, m_reindexing and options.reindex values may be different!
6565
if (!chainman.LoadBlockIndex()) {
6666
if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};
6767
return {ChainstateLoadStatus::FAILURE, _("Error loading block database")};
@@ -84,7 +84,7 @@ static ChainstateLoadResult CompleteChainstateInitialization(
8484
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
8585
// (otherwise we use the one already on disk).
8686
// This is called again in ImportBlocks after the reindex completes.
87-
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
87+
if (!chainman.m_blockman.m_reindexing && !chainman.ActiveChainstate().LoadGenesisBlock()) {
8888
return {ChainstateLoadStatus::FAILURE, _("Error initializing block database")};
8989
}
9090

src/test/util/setup_common.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ void ChainTestingSetup::LoadVerifyActivateChainstate()
276276
options.mempool = Assert(m_node.mempool.get());
277277
options.block_tree_db_in_memory = m_block_tree_db_in_memory;
278278
options.coins_db_in_memory = m_coins_db_in_memory;
279-
options.reindex = node::fReindex;
279+
options.reindex = chainman.m_blockman.m_reindexing;
280280
options.reindex_chainstate = m_args.GetBoolArg("-reindex-chainstate", false);
281281
options.prune = chainman.m_blockman.IsPruneMode();
282282
options.check_blocks = m_args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);

src/validation.cpp

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ using node::BlockManager;
8383
using node::BlockMap;
8484
using node::CBlockIndexHeightOnlyComparator;
8585
using node::CBlockIndexWorkComparator;
86-
using node::fReindex;
8786
using node::SnapshotMetadata;
8887

8988
/** Time to wait between writing blocks/block index to disk. */
@@ -2642,7 +2641,7 @@ bool Chainstate::FlushStateToDisk(
26422641

26432642
CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
26442643
LOCK(m_blockman.cs_LastBlockFile);
2645-
if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !fReindex) {
2644+
if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !m_chainman.m_blockman.m_reindexing) {
26462645
// make sure we don't prune above any of the prune locks bestblocks
26472646
// pruning is height-based
26482647
int last_prune{m_chain.Height()}; // last height we can prune
@@ -3255,10 +3254,10 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex*
32553254
return true;
32563255
}
32573256

3258-
static SynchronizationState GetSynchronizationState(bool init)
3257+
static SynchronizationState GetSynchronizationState(bool init, bool reindexing)
32593258
{
32603259
if (!init) return SynchronizationState::POST_INIT;
3261-
if (::fReindex) return SynchronizationState::INIT_REINDEX;
3260+
if (reindexing) return SynchronizationState::INIT_REINDEX;
32623261
return SynchronizationState::INIT_DOWNLOAD;
32633262
}
32643263

@@ -3280,7 +3279,7 @@ static bool NotifyHeaderTip(ChainstateManager& chainman) LOCKS_EXCLUDED(cs_main)
32803279
}
32813280
// Send block tip changed notifications without cs_main
32823281
if (fNotify) {
3283-
chainman.GetNotifications().headerTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader->nHeight, pindexHeader->nTime, false);
3282+
chainman.GetNotifications().headerTip(GetSynchronizationState(fInitialBlockDownload, chainman.m_blockman.m_reindexing), pindexHeader->nHeight, pindexHeader->nTime, false);
32843283
}
32853284
return fNotify;
32863285
}
@@ -3399,7 +3398,7 @@ bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr<
33993398
}
34003399

34013400
// Always notify the UI if a new block tip was connected
3402-
if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(GetSynchronizationState(still_in_ibd), *pindexNewTip))) {
3401+
if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(GetSynchronizationState(still_in_ibd, m_chainman.m_blockman.m_reindexing), *pindexNewTip))) {
34033402
// Just breaking and returning success for now. This could
34043403
// be changed to bubble up the kernel::Interrupted value to
34053404
// the caller so the caller could distinguish between
@@ -3625,7 +3624,7 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde
36253624
// parameter indicating the source of the tip change so hooks can
36263625
// distinguish user-initiated invalidateblock changes from other
36273626
// changes.
3628-
(void)m_chainman.GetNotifications().blockTip(GetSynchronizationState(m_chainman.IsInitialBlockDownload()), *to_mark_failed->pprev);
3627+
(void)m_chainman.GetNotifications().blockTip(GetSynchronizationState(m_chainman.IsInitialBlockDownload(), m_chainman.m_blockman.m_reindexing), *to_mark_failed->pprev);
36293628
}
36303629
return true;
36313630
}
@@ -4264,7 +4263,7 @@ void ChainstateManager::ReportHeadersPresync(const arith_uint256& work, int64_t
42644263
m_last_presync_update = now;
42654264
}
42664265
bool initial_download = IsInitialBlockDownload();
4267-
GetNotifications().headerTip(GetSynchronizationState(initial_download), height, timestamp, /*presync=*/true);
4266+
GetNotifications().headerTip(GetSynchronizationState(initial_download, m_blockman.m_reindexing), height, timestamp, /*presync=*/true);
42684267
if (initial_download) {
42694268
int64_t blocks_left{(NodeClock::now() - NodeSeconds{std::chrono::seconds{timestamp}}) / GetConsensus().PowTargetSpacing()};
42704269
blocks_left = std::max<int64_t>(0, blocks_left);
@@ -4791,8 +4790,8 @@ bool ChainstateManager::LoadBlockIndex()
47914790
{
47924791
AssertLockHeld(cs_main);
47934792
// Load block index from databases
4794-
bool needs_init = fReindex;
4795-
if (!fReindex) {
4793+
bool needs_init = m_blockman.m_reindexing;
4794+
if (!m_blockman.m_reindexing) {
47964795
bool ret{m_blockman.LoadBlockIndexDB(SnapshotBlockhash())};
47974796
if (!ret) return false;
47984797

@@ -4829,8 +4828,8 @@ bool ChainstateManager::LoadBlockIndex()
48294828

48304829
if (needs_init) {
48314830
// Everything here is for *new* reindex/DBs. Thus, though
4832-
// LoadBlockIndexDB may have set fReindex if we shut down
4833-
// mid-reindex previously, we don't check fReindex and
4831+
// LoadBlockIndexDB may have set m_reindexing if we shut down
4832+
// mid-reindex previously, we don't check m_reindexing and
48344833
// instead only check it prior to LoadBlockIndexDB to set
48354834
// needs_init.
48364835

@@ -4975,7 +4974,7 @@ void ChainstateManager::LoadExternalBlockFile(
49754974
}
49764975
}
49774976

4978-
if (m_blockman.IsPruneMode() && !fReindex && pblock) {
4977+
if (m_blockman.IsPruneMode() && !m_blockman.m_reindexing && pblock) {
49794978
// must update the tip for pruning to work while importing with -loadblock.
49804979
// this is a tradeoff to conserve disk space at the expense of time
49814980
// spent updating the tip to be able to prune.

0 commit comments

Comments
 (0)