Skip to content

Commit 9a28843

Browse files
author
MarcoFalke
committed
Merge bitcoin/bitcoin#26900: refactor: Add BlockManager getters
faf7b4f Add BlockManager::IsPruneMode() (MarcoFalke) fae71fe Add BlockManager::GetPruneTarget() (MarcoFalke) fa0f043 Add BlockManager::LoadingBlocks() (MarcoFalke) Pull request description: Requested in bitcoin/bitcoin#25781 (comment), but adding getters seems unrelated from removing globals, so I split it out for now. ACKs for top commit: dergoegge: Code review ACK faf7b4f brunoerg: crACK faf7b4f Tree-SHA512: 204d0e9a0e8b78175482f89b4ce620fba0e65d8e49ad845d187af44d3843f4c733a01bac1ffe5a5319f524d8346123693a456778b69d6c75268c447eb8839642
2 parents 835212c + faf7b4f commit 9a28843

File tree

9 files changed

+52
-44
lines changed

9 files changed

+52
-44
lines changed

src/index/base.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -415,8 +415,9 @@ IndexSummary BaseIndex::GetSummary() const
415415
return summary;
416416
}
417417

418-
void BaseIndex::SetBestBlockIndex(const CBlockIndex* block) {
419-
assert(!node::fPruneMode || AllowPrune());
418+
void BaseIndex::SetBestBlockIndex(const CBlockIndex* block)
419+
{
420+
assert(!m_chainstate->m_blockman.IsPruneMode() || AllowPrune());
420421

421422
if (AllowPrune() && block) {
422423
node::PruneLockInfo prune_lock;

src/init.cpp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,7 +1499,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14991499
options.mempool = Assert(node.mempool.get());
15001500
options.reindex = node::fReindex;
15011501
options.reindex_chainstate = fReindexChainState;
1502-
options.prune = node::fPruneMode;
1502+
options.prune = chainman.m_blockman.IsPruneMode();
15031503
options.check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
15041504
options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
15051505
options.check_interrupt = ShutdownRequested;
@@ -1609,7 +1609,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16091609

16101610
// if pruning, perform the initial blockstore prune
16111611
// after any wallet rescanning has taken place.
1612-
if (fPruneMode) {
1612+
if (chainman.m_blockman.IsPruneMode()) {
16131613
if (!fReindex) {
16141614
LOCK(cs_main);
16151615
for (Chainstate* chainstate : chainman.GetAll()) {
@@ -1637,8 +1637,10 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16371637

16381638
// On first startup, warn on low block storage space
16391639
if (!fReindex && !fReindexChainState && chain_active_height <= 1) {
1640-
uint64_t additional_bytes_needed = fPruneMode ? nPruneTarget
1641-
: chainparams.AssumedBlockchainSize() * 1024 * 1024 * 1024;
1640+
uint64_t additional_bytes_needed{
1641+
chainman.m_blockman.IsPruneMode() ?
1642+
chainman.m_blockman.GetPruneTarget() :
1643+
chainparams.AssumedBlockchainSize() * 1024 * 1024 * 1024};
16421644

16431645
if (!CheckDiskSpace(args.GetBlocksDirPath(), additional_bytes_needed)) {
16441646
InitWarning(strprintf(_(

src/net_processing.cpp

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,6 @@
5353

5454
using node::ReadBlockFromDisk;
5555
using node::ReadRawBlockFromDisk;
56-
using node::fImporting;
57-
using node::fPruneMode;
58-
using node::fReindex;
5956

6057
/** How long to cache transactions in mapRelay for normal relay */
6158
static constexpr auto RELAY_TX_CACHE_TIME = 15min;
@@ -1739,8 +1736,7 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
17391736

17401737
std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
17411738
{
1742-
if (fImporting) return "Importing...";
1743-
if (fReindex) return "Reindexing...";
1739+
if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ...";
17441740

17451741
// Ensure this peer exists and hasn't been disconnected
17461742
PeerRef peer = GetPeerRef(peer_id);
@@ -3697,7 +3693,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
36973693
LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
36983694

36993695
UpdateBlockAvailability(pfrom.GetId(), inv.hash);
3700-
if (!fAlreadyHave && !fImporting && !fReindex && !IsBlockRequested(inv.hash)) {
3696+
if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) {
37013697
// Headers-first is the primary method of announcement on
37023698
// the network. If a node fell back to sending blocks by
37033699
// inv, it may be for a re-org, or because we haven't
@@ -3830,8 +3826,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
38303826
// If pruning, don't inv blocks unless we have on disk and are likely to still have
38313827
// for some reasonable time window (1 hour) that block relay might require.
38323828
const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
3833-
if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
3834-
{
3829+
if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) {
38353830
LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
38363831
break;
38373832
}
@@ -3907,7 +3902,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
39073902
return;
39083903
}
39093904

3910-
if (fImporting || fReindex) {
3905+
if (m_chainman.m_blockman.LoadingBlocks()) {
39113906
LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId());
39123907
return;
39133908
}
@@ -4186,7 +4181,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
41864181
if (msg_type == NetMsgType::CMPCTBLOCK)
41874182
{
41884183
// Ignore cmpctblock received while importing
4189-
if (fImporting || fReindex) {
4184+
if (m_chainman.m_blockman.LoadingBlocks()) {
41904185
LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
41914186
return;
41924187
}
@@ -4402,7 +4397,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
44024397
if (msg_type == NetMsgType::BLOCKTXN)
44034398
{
44044399
// Ignore blocktxn received while importing
4405-
if (fImporting || fReindex) {
4400+
if (m_chainman.m_blockman.LoadingBlocks()) {
44064401
LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
44074402
return;
44084403
}
@@ -4477,7 +4472,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
44774472
if (msg_type == NetMsgType::HEADERS)
44784473
{
44794474
// Ignore headers received while importing
4480-
if (fImporting || fReindex) {
4475+
if (m_chainman.m_blockman.LoadingBlocks()) {
44814476
LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
44824477
return;
44834478
}
@@ -4522,7 +4517,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
45224517
if (msg_type == NetMsgType::BLOCK)
45234518
{
45244519
// Ignore block received while importing
4525-
if (fImporting || fReindex) {
4520+
if (m_chainman.m_blockman.LoadingBlocks()) {
45264521
LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
45274522
return;
45284523
}
@@ -5109,7 +5104,7 @@ void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
51095104
if (now > m_stale_tip_check_time) {
51105105
// Check whether our tip is stale, and if so, allow using an extra
51115106
// outbound peer
5112-
if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
5107+
if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
51135108
LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
51145109
count_seconds(now - m_last_tip_update.load()));
51155110
m_connman.SetTryNewOutboundPeer(true);
@@ -5416,7 +5411,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
54165411
}
54175412
}
54185413

5419-
if (!state.fSyncStarted && CanServeBlocks(*peer) && !fImporting && !fReindex) {
5414+
if (!state.fSyncStarted && CanServeBlocks(*peer) && !m_chainman.m_blockman.LoadingBlocks()) {
54205415
// Only actively request headers from a single peer, unless we're close to today.
54215416
if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) {
54225417
const CBlockIndex* pindexStart = m_chainman.m_best_header;

src/node/blockstorage.h

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,7 @@ static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE = CMessageHeader::MESSAG
4848

4949
extern std::atomic_bool fImporting;
5050
extern std::atomic_bool fReindex;
51-
/** Pruning-related variables and constants */
52-
/** True if we're running in -prune mode. */
5351
extern bool fPruneMode;
54-
/** Number of bytes of block files that we're trying to stay below. */
5552
extern uint64_t nPruneTarget;
5653

5754
// Because validation code takes pointers to the map's CBlockIndex objects, if
@@ -176,6 +173,17 @@ class BlockManager
176173
/** Store block on disk. If dbp is not nullptr, then it provides the known position of the block within a block file on disk. */
177174
FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, CChain& active_chain, const CChainParams& chainparams, const FlatFilePos* dbp);
178175

176+
/** Whether running in -prune mode. */
177+
[[nodiscard]] bool IsPruneMode() const { return fPruneMode; }
178+
179+
/** Attempt to stay below this number of bytes of block files. */
180+
[[nodiscard]] uint64_t GetPruneTarget() const { return nPruneTarget; }
181+
182+
[[nodiscard]] bool LoadingBlocks() const
183+
{
184+
return fImporting || fReindex;
185+
}
186+
179187
/** Calculate the amount of disk space the block & undo files currently use */
180188
uint64_t CalculateCurrentUsage();
181189

src/node/chainstate.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,10 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize
4444
if (chainman.MinimumChainWork() < UintToArith256(chainman.GetConsensus().nMinimumChainWork)) {
4545
LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainman.GetConsensus().nMinimumChainWork.GetHex());
4646
}
47-
if (nPruneTarget == std::numeric_limits<uint64_t>::max()) {
47+
if (chainman.m_blockman.GetPruneTarget() == std::numeric_limits<uint64_t>::max()) {
4848
LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
49-
} else if (nPruneTarget) {
50-
LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
49+
} else if (chainman.m_blockman.GetPruneTarget()) {
50+
LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", chainman.m_blockman.GetPruneTarget() / 1024 / 1024);
5151
}
5252

5353
LOCK(cs_main);

src/node/interfaces.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -711,8 +711,9 @@ class ChainImpl : public Chain
711711
LOCK(::cs_main);
712712
return chainman().m_blockman.m_have_pruned;
713713
}
714-
bool isReadyToBroadcast() override { return !node::fImporting && !node::fReindex && !isInitialBlockDownload(); }
715-
bool isInitialBlockDownload() override {
714+
bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
715+
bool isInitialBlockDownload() override
716+
{
716717
return chainman().ActiveChainstate().IsInitialBlockDownload();
717718
}
718719
bool shutdownRequested() override { return ShutdownRequested(); }

src/rpc/blockchain.cpp

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ static RPCHelpMan getblockfrompeer()
460460

461461
// Fetching blocks before the node has syncing past their height can prevent block files from
462462
// being pruned, so we avoid it if the node is in prune mode.
463-
if (node::fPruneMode && index->nHeight > WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()->nHeight)) {
463+
if (chainman.m_blockman.IsPruneMode() && index->nHeight > WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()->nHeight)) {
464464
throw JSONRPCError(RPC_MISC_ERROR, "In prune mode, only blocks that the node has already synced previously can be fetched from a peer");
465465
}
466466

@@ -775,10 +775,11 @@ static RPCHelpMan pruneblockchain()
775775
},
776776
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
777777
{
778-
if (!node::fPruneMode)
778+
ChainstateManager& chainman = EnsureAnyChainman(request.context);
779+
if (!chainman.m_blockman.IsPruneMode()) {
779780
throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
781+
}
780782

781-
ChainstateManager& chainman = EnsureAnyChainman(request.context);
782783
LOCK(cs_main);
783784
Chainstate& active_chainstate = chainman.ActiveChainstate();
784785
CChain& active_chain = active_chainstate.m_chain;
@@ -1266,15 +1267,15 @@ RPCHelpMan getblockchaininfo()
12661267
obj.pushKV("initialblockdownload", active_chainstate.IsInitialBlockDownload());
12671268
obj.pushKV("chainwork", tip.nChainWork.GetHex());
12681269
obj.pushKV("size_on_disk", chainman.m_blockman.CalculateCurrentUsage());
1269-
obj.pushKV("pruned", node::fPruneMode);
1270-
if (node::fPruneMode) {
1270+
obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
1271+
if (chainman.m_blockman.IsPruneMode()) {
12711272
obj.pushKV("pruneheight", chainman.m_blockman.GetFirstStoredBlock(tip)->nHeight);
12721273

12731274
// if 0, execution bypasses the whole if block.
12741275
bool automatic_pruning{args.GetIntArg("-prune", 0) != 1};
12751276
obj.pushKV("automatic_pruning", automatic_pruning);
12761277
if (automatic_pruning) {
1277-
obj.pushKV("prune_target_size", node::nPruneTarget);
1278+
obj.pushKV("prune_target_size", chainman.m_blockman.GetPruneTarget());
12781279
}
12791280
}
12801281

src/test/util/setup_common.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,23 +208,24 @@ ChainTestingSetup::~ChainTestingSetup()
208208

209209
void TestingSetup::LoadVerifyActivateChainstate()
210210
{
211+
auto& chainman{*Assert(m_node.chainman)};
211212
node::ChainstateLoadOptions options;
212213
options.mempool = Assert(m_node.mempool.get());
213214
options.block_tree_db_in_memory = m_block_tree_db_in_memory;
214215
options.coins_db_in_memory = m_coins_db_in_memory;
215216
options.reindex = node::fReindex;
216217
options.reindex_chainstate = m_args.GetBoolArg("-reindex-chainstate", false);
217-
options.prune = node::fPruneMode;
218+
options.prune = chainman.m_blockman.IsPruneMode();
218219
options.check_blocks = m_args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
219220
options.check_level = m_args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
220-
auto [status, error] = LoadChainstate(*Assert(m_node.chainman), m_cache_sizes, options);
221+
auto [status, error] = LoadChainstate(chainman, m_cache_sizes, options);
221222
assert(status == node::ChainstateLoadStatus::SUCCESS);
222223

223-
std::tie(status, error) = VerifyLoadedChainstate(*Assert(m_node.chainman), options);
224+
std::tie(status, error) = VerifyLoadedChainstate(chainman, options);
224225
assert(status == node::ChainstateLoadStatus::SUCCESS);
225226

226227
BlockValidationState state;
227-
if (!m_node.chainman->ActiveChainstate().ActivateBestChain(state)) {
228+
if (!chainman.ActiveChainstate().ActivateBestChain(state)) {
228229
throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString()));
229230
}
230231
}

src/validation.cpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,6 @@ using node::BlockManager;
7676
using node::BlockMap;
7777
using node::CBlockIndexHeightOnlyComparator;
7878
using node::CBlockIndexWorkComparator;
79-
using node::fImporting;
80-
using node::fPruneMode;
8179
using node::fReindex;
8280
using node::ReadBlockFromDisk;
8381
using node::SnapshotMetadata;
@@ -1573,8 +1571,9 @@ bool Chainstate::IsInitialBlockDownload() const
15731571
LOCK(cs_main);
15741572
if (m_cached_finished_ibd.load(std::memory_order_relaxed))
15751573
return false;
1576-
if (fImporting || fReindex)
1574+
if (m_chainman.m_blockman.LoadingBlocks()) {
15771575
return true;
1576+
}
15781577
if (m_chain.Tip() == nullptr)
15791578
return true;
15801579
if (m_chain.Tip()->nChainWork < m_chainman.MinimumChainWork()) {
@@ -2411,7 +2410,7 @@ bool Chainstate::FlushStateToDisk(
24112410

24122411
CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
24132412
LOCK(m_blockman.cs_LastBlockFile);
2414-
if (fPruneMode && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !fReindex) {
2413+
if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !fReindex) {
24152414
// make sure we don't prune above any of the prune locks bestblocks
24162415
// pruning is height-based
24172416
int last_prune{m_chain.Height()}; // last height we can prune
@@ -4097,7 +4096,7 @@ bool CVerifyDB::VerifyDB(
40974096
if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
40984097
break;
40994098
}
4100-
if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4099+
if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
41014100
// If pruning or running under an assumeutxo snapshot, only go
41024101
// back as far as we have data.
41034102
LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);

0 commit comments

Comments
 (0)