Skip to content

Commit bcafa28

Browse files
kwvgPastaPastaPasta
authored andcommitted
merge bitcoin#24909: Move and rename pindexBestHeader, fHavePruned
1 parent 70485cb commit bcafa28

14 files changed

+121
-115
lines changed

src/bench/rpc_blockchain.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ static void BlockToJsonVerbose(benchmark::Bench& bench)
4545
TestBlockAndIndex data;
4646
const LLMQContext& llmq_ctx = *data.testing_setup->m_node.llmq_ctx;
4747
bench.run([&] {
48-
auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, *llmq_ctx.clhandler, *llmq_ctx.isman, /*verbose*/ true);
48+
auto univalue = blockToJSON(data.testing_setup->m_node.chainman->m_blockman, data.block, &data.blockindex, &data.blockindex, *llmq_ctx.clhandler, *llmq_ctx.isman, /*verbose*/ true);
4949
ankerl::nanobench::doNotOptimizeAway(univalue);
5050
});
5151
}
@@ -56,7 +56,7 @@ static void BlockToJsonVerboseWrite(benchmark::Bench& bench)
5656
{
5757
TestBlockAndIndex data;
5858
const LLMQContext& llmq_ctx = *data.testing_setup->m_node.llmq_ctx;
59-
auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, *llmq_ctx.clhandler, *llmq_ctx.isman, /*verbose*/ true);
59+
auto univalue = blockToJSON(data.testing_setup->m_node.chainman->m_blockman, data.block, &data.blockindex, &data.blockindex, *llmq_ctx.clhandler, *llmq_ctx.isman, /*verbose*/ true);
6060
bench.run([&] {
6161
auto str = univalue.write();
6262
ankerl::nanobench::doNotOptimizeAway(str);

src/dsnotificationinterface.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, con
7979
if (pindexNew == pindexFork) // blocks were disconnected without any new ones
8080
return;
8181

82-
m_mn_sync.UpdatedBlockTip(pindexNew, fInitialDownload);
82+
m_mn_sync.UpdatedBlockTip(m_chainman.m_best_header, pindexNew, fInitialDownload);
8383

8484
// Update global DIP0001 activation status
8585
fDIP0001ActiveAtTip = pindexNew->nHeight >= Params().GetConsensus().DIP0001Height;

src/init.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,7 +1890,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
18901890

18911891
if (ShutdownRequested()) break;
18921892

1893-
// LoadBlockIndex will load fHavePruned if we've ever removed a
1893+
// LoadBlockIndex will load m_have_pruned if we've ever removed a
18941894
// block file from disk.
18951895
// Note that it also sets fReindex based on the disk flag!
18961896
// From here on out fReindex and fReset mean something different!
@@ -1936,7 +1936,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
19361936

19371937
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
19381938
// in the past, but is now trying to run unpruned.
1939-
if (fHavePruned && !fPruneMode) {
1939+
if (chainman.m_blockman.m_have_pruned && !fPruneMode) {
19401940
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
19411941
break;
19421942
}
@@ -2022,7 +2022,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
20222022
for (CChainState* chainstate : chainman.GetAll()) {
20232023
if (!is_coinsview_empty(chainstate)) {
20242024
uiInterface.InitMessage(_("Verifying blocks…").translated);
2025-
if (fHavePruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
2025+
if (chainman.m_blockman.m_have_pruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
20262026
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
20272027
MIN_BLOCKS_TO_KEEP);
20282028
}
@@ -2328,9 +2328,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
23282328
tip_info->block_hash = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockHash() : Params().GenesisBlock().GetHash();
23292329
tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip());
23302330
}
2331-
if (tip_info && ::pindexBestHeader) {
2332-
tip_info->header_height = ::pindexBestHeader->nHeight;
2333-
tip_info->header_time = ::pindexBestHeader->GetBlockTime();
2331+
if (tip_info && chainman.m_best_header) {
2332+
tip_info->header_height = chainman.m_best_header->nHeight;
2333+
tip_info->header_time = chainman.m_best_header->GetBlockTime();
23342334
}
23352335
}
23362336
LogPrintf("nBestHeight = %d\n", chain_active_height);

src/masternode/sync.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ void CMasternodeSync::NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitia
329329
}
330330
}
331331

332-
void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload)
332+
void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexTip, const CBlockIndex *pindexNew, bool fInitialDownload)
333333
{
334334
LogPrint(BCLog::MNSYNC, "CMasternodeSync::UpdatedBlockTip -- pindexNew->nHeight: %d fInitialDownload=%d\n", pindexNew->nHeight, fInitialDownload);
335335
nTimeLastUpdateBlockTip = GetTime<std::chrono::seconds>().count();
@@ -353,7 +353,6 @@ void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitia
353353
}
354354

355355
// Note: since we sync headers first, it should be ok to use this
356-
CBlockIndex* pindexTip = WITH_LOCK(cs_main, return pindexBestHeader);
357356
if (pindexTip == nullptr) return;
358357
bool fReachedBestHeaderNew = pindexNew->GetBlockHash() == pindexTip->GetBlockHash();
359358

src/masternode/sync.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ class CMasternodeSync
7575

7676
void AcceptedBlockHeader(const CBlockIndex *pindexNew);
7777
void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload);
78-
void UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload);
78+
void UpdatedBlockTip(const CBlockIndex *pindexTip, const CBlockIndex *pindexNew, bool fInitialDownload);
7979

8080
void DoMaintenance();
8181
};

src/net_processing.cpp

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1856,9 +1856,9 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
18561856
{
18571857
AssertLockHeld(cs_main);
18581858
if (m_chainman.ActiveChain().Contains(pindex)) return true;
1859-
return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
1860-
(pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
1861-
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
1859+
return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) &&
1860+
(m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
1861+
(GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
18621862
}
18631863

18641864
std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
@@ -2434,7 +2434,7 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
24342434
const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
24352435
// disconnect node in case we have reached the outbound limit for serving historical blocks
24362436
if (m_connman.OutboundTargetReached(true) &&
2437-
(((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
2437+
(((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
24382438
!pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
24392439
) {
24402440
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId());
@@ -2824,13 +2824,13 @@ void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
28242824
if (!m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
28252825
nodestate->nUnconnectingHeaders++;
28262826
std::string msg_type = (pfrom.nServices & NODE_HEADERS_COMPRESSED) ? NetMsgType::GETHEADERS2 : NetMsgType::GETHEADERS;
2827-
m_connman.PushMessage(&pfrom, msgMaker.Make(msg_type, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
2827+
m_connman.PushMessage(&pfrom, msgMaker.Make(msg_type, m_chainman.ActiveChain().GetLocator(m_chainman.m_best_header), uint256()));
28282828
LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending %s (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2829-
headers[0].GetHash().ToString(),
2830-
headers[0].hashPrevBlock.ToString(),
2831-
msg_type,
2832-
pindexBestHeader->nHeight,
2833-
pfrom.GetId(), nodestate->nUnconnectingHeaders);
2829+
headers[0].GetHash().ToString(),
2830+
headers[0].hashPrevBlock.ToString(),
2831+
msg_type,
2832+
m_chainman.m_best_header->nHeight,
2833+
pfrom.GetId(), nodestate->nUnconnectingHeaders);
28342834
// Set hashLastUnknownBlock for this peer, so that if we
28352835
// eventually get the headers - even from a different peer -
28362836
// we can use this peer to download.
@@ -2887,7 +2887,7 @@ void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
28872887

28882888
if (nCount == MAX_HEADERS_RESULTS) {
28892889
// Headers message had its maximum size; the peer may have more headers.
2890-
// TODO: optimize: if pindexLast is an ancestor of m_chainman.ActiveChain().Tip or pindexBestHeader, continue
2890+
// TODO: optimize: if pindexLast is an ancestor of m_chainman.ActiveChain().Tip or m_chainman.m_best_header, continue
28912891
// from there instead.
28922892
std::string msg_type = (pfrom.nServices & NODE_HEADERS_COMPRESSED) ? NetMsgType::GETHEADERS2 : NetMsgType::GETHEADERS;
28932893
LogPrint(BCLog::NET, "more %s (%d) to end to peer=%d (startheight:%d)\n",
@@ -3819,15 +3819,15 @@ void PeerManagerImpl::ProcessMessage(
38193819
// Download if this is a nice peer, or we have no nice peers and this one might do.
38203820
bool fFetch = state->fPreferredDownload || (nPreferredDownload == 0 && !pfrom.IsAddrFetchConn());
38213821
// Only actively request headers from a single peer, unless we're close to end of initial download.
3822-
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) {
3822+
if ((nSyncStarted == 0 && fFetch) || m_chainman.m_best_header->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) {
38233823
// Make sure to mark this peer as the one we are currently syncing with etc.
38243824
state->fSyncStarted = true;
38253825
state->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
38263826
(
38273827
// Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
38283828
// to maintain precision
38293829
std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
3830-
(GetAdjustedTime() - pindexBestHeader->GetBlockTime()) / m_chainparams.GetConsensus().nPowTargetSpacing
3830+
(GetAdjustedTime() - m_chainman.m_best_header->GetBlockTime()) / m_chainparams.GetConsensus().nPowTargetSpacing
38313831
);
38323832
nSyncStarted++;
38333833
// Headers-first is the primary method of announcement on
@@ -3872,8 +3872,8 @@ void PeerManagerImpl::ProcessMessage(
38723872
}
38733873
if (best_block != nullptr) {
38743874
std::string msg_type = (pfrom.nServices & NODE_HEADERS_COMPRESSED) ? NetMsgType::GETHEADERS2 : NetMsgType::GETHEADERS;
3875-
m_connman.PushMessage(&pfrom, msgMaker.Make(msg_type, m_chainman.ActiveChain().GetLocator(pindexBestHeader), *best_block));
3876-
LogPrint(BCLog::NET, "%s (%d) %s to peer=%d\n", msg_type, pindexBestHeader->nHeight, best_block->ToString(), pfrom.GetId());
3875+
m_connman.PushMessage(&pfrom, msgMaker.Make(msg_type, m_chainman.ActiveChain().GetLocator(m_chainman.m_best_header), *best_block));
3876+
LogPrint(BCLog::NET, "%s (%d) %s to peer=%d\n", msg_type, m_chainman.m_best_header->nHeight, best_block->ToString(), pfrom.GetId());
38773877
}
38783878

38793879
return;
@@ -4289,7 +4289,7 @@ void PeerManagerImpl::ProcessMessage(
42894289
if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
42904290
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
42914291
if (!m_chainman.ActiveChainstate().IsInitialBlockDownload())
4292-
m_connman.PushMessage(&pfrom, msgMaker.Make((pfrom.nServices & NODE_HEADERS_COMPRESSED) ? NetMsgType::GETHEADERS2 : NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
4292+
m_connman.PushMessage(&pfrom, msgMaker.Make((pfrom.nServices & NODE_HEADERS_COMPRESSED) ? NetMsgType::GETHEADERS2 : NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(m_chainman.m_best_header), uint256()));
42934293
return;
42944294
}
42954295

@@ -5445,28 +5445,29 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
54455445
CNodeState &state = *State(pto->GetId());
54465446

54475447
// Start block sync
5448-
if (pindexBestHeader == nullptr)
5449-
pindexBestHeader = m_chainman.ActiveChain().Tip();
5448+
if (m_chainman.m_best_header == nullptr) {
5449+
m_chainman.m_best_header = m_chainman.ActiveChain().Tip();
5450+
}
54505451
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->IsAddrFetchConn()); // Download if this is a nice peer, or we have no nice peers and this one might do.
54515452
if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex && pto->CanRelay()) {
54525453
// Only actively request headers from a single peer, unless we're close to end of initial download.
5453-
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) {
5454+
if ((nSyncStarted == 0 && fFetch) || m_chainman.m_best_header->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) {
54545455
state.fSyncStarted = true;
54555456
state.m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
54565457
(
54575458
// Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
54585459
// to maintain precision
54595460
std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
5460-
(GetAdjustedTime() - pindexBestHeader->GetBlockTime()) / consensusParams.nPowTargetSpacing
5461+
(GetAdjustedTime() - m_chainman.m_best_header->GetBlockTime()) / consensusParams.nPowTargetSpacing
54615462
);
54625463
nSyncStarted++;
5463-
const CBlockIndex *pindexStart = pindexBestHeader;
5464+
const CBlockIndex* pindexStart = m_chainman.m_best_header;
54645465
/* If possible, start at the block preceding the currently
54655466
best known header. This ensures that we always get a
54665467
non-empty list of headers back as long as the peer
54675468
is up-to-date. With a non-empty response, we can initialise
54685469
the peer's known best block. This wouldn't be possible
5469-
if we requested starting at pindexBestHeader and
5470+
if we requested starting at m_chainman.m_best_header and
54705471
got back an empty response. */
54715472
if (pindexStart->pprev)
54725473
pindexStart = pindexStart->pprev;
@@ -5835,7 +5836,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
58355836
// Check for headers sync timeouts
58365837
if (state.fSyncStarted && state.m_headers_sync_timeout < std::chrono::microseconds::max()) {
58375838
// Detect whether this is a stalling initial-headers-sync peer
5838-
if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - nMaxTipAge) {
5839+
if (m_chainman.m_best_header->GetBlockTime() <= GetAdjustedTime() - nMaxTipAge) {
58395840
if (current_time > state.m_headers_sync_timeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
58405841
// Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
58415842
// and we have others we could be using instead.

src/node/blockstorage.cpp

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525

2626
std::atomic_bool fImporting(false);
2727
std::atomic_bool fReindex(false);
28-
bool fHavePruned = false;
2928
bool fPruneMode = false;
3029
uint64_t nPruneTarget = 0;
3130

@@ -86,7 +85,8 @@ const CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
8685
return it == m_block_index.end() ? nullptr : &it->second;
8786
}
8887

89-
CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block, const uint256& hash, enum BlockStatus nStatus)
88+
CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block, const uint256& hash, CBlockIndex*& best_header,
89+
enum BlockStatus nStatus)
9090
{
9191
assert(!(nStatus & BLOCK_FAILED_MASK)); // no failed blocks allowed
9292
AssertLockHeld(cs_main);
@@ -113,8 +113,8 @@ CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block, const uint
113113
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
114114
if (nStatus & BLOCK_VALID_MASK) {
115115
pindexNew->RaiseValidity(nStatus);
116-
if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork) {
117-
pindexBestHeader = pindexNew;
116+
if (best_header == nullptr || best_header->nChainWork < pindexNew->nChainWork) {
117+
best_header = pindexNew;
118118
}
119119
} else {
120120
pindexNew->RaiseValidity(BLOCK_VALID_TREE); // required validity level
@@ -309,8 +309,6 @@ bool BlockManager::LoadBlockIndex(const Consensus::Params& consensus_params)
309309
if (pindex->pprev) {
310310
pindex->BuildSkip();
311311
}
312-
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
313-
pindexBestHeader = pindex;
314312
}
315313

316314
return true;
@@ -327,6 +325,8 @@ void BlockManager::Unload()
327325
m_last_blockfile = 0;
328326
m_dirty_blockindex.clear();
329327
m_dirty_fileinfo.clear();
328+
329+
m_have_pruned = false;
330330
}
331331

332332
bool BlockManager::WriteBlockIndexDB()
@@ -389,8 +389,8 @@ bool BlockManager::LoadBlockIndexDB()
389389
}
390390

391391
// Check whether we have ever pruned block & undo files
392-
m_block_tree_db->ReadFlag("prunedblockfiles", fHavePruned);
393-
if (fHavePruned) {
392+
m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
393+
if (m_have_pruned) {
394394
LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
395395
}
396396

@@ -428,10 +428,10 @@ const CBlockIndex* BlockManager::GetLastCheckpoint(const CCheckpointData& data)
428428
return nullptr;
429429
}
430430

431-
bool IsBlockPruned(const CBlockIndex* pblockindex)
431+
bool BlockManager::IsBlockPruned(const CBlockIndex* pblockindex)
432432
{
433433
AssertLockHeld(::cs_main);
434-
return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
434+
return (m_have_pruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
435435
}
436436

437437
// If we're using -prune with -reindex, then delete block files that will be ignored by the

0 commit comments

Comments
 (0)