Skip to content

Commit 44f4bcd

Browse files
committed
Merge #20749: [Bundle 1/n] Prune g_chainman usage related to ::LookupBlockIndex
67c9a83 style-only: Remove redundant sentence in ActivateBestChain comment (Carl Dong) b8e9565 style-only: Make TestBlockValidity signature readable (Carl Dong) 0cdad75 validation: Use accessible chainstate in ChainstateManager::ProcessNewBlock (Carl Dong) ea4fed9 validation: Use existing chainstate in ChainstateManager::ProcessNewBlockHeaders (Carl Dong) e0dc305 validation: Move LoadExternalBlockFile to CChainState (Carl Dong) 5f8cd7b validation: Remove global ::ActivateBestChain (Carl Dong) 2a69647 validation: Pass in chainstate to ::NotifyHeaderTip (Carl Dong) 9c300cc validation: Pass in chainstate to TestBlockValidity (Carl Dong) 0e17c83 validation: Make CChainState.m_blockman public (Carl Dong) d363d06 validation: Pass in blockman to ContextualCheckBlockHeader (Carl Dong) f11d116 validation: Move GetLastCheckpoint to BlockManager (Carl Dong) e4b95ee validation: Move GetSpendHeight to BlockManager (Carl Dong) b026e31 validation: Move FindForkInGlobalIndex to BlockManager (Carl Dong) 3664a15 validation: Remove global LookupBlockIndex (Carl Dong) eae54e6 scripted-diff: Use BlockManager::LookupBlockIndex (Carl Dong) 15d20f4 validation: Move LookupBlockIndex to BlockManager (Carl Dong) f92dc65 validation: Guard the active_chainstate with cs_main (Carl Dong) Pull request description: Overall PR: #20158 (tree-wide: De-globalize ChainstateManager) Note to reviewers: 1. This bundle may _apparently_ introduce usage of `g_chainman` or `::Chain(state|)Active()` globals, but these are resolved later on in the overall PR. [Commits of overall PR](https://github.com/bitcoin/bitcoin/pull/20158/commits) 2. There may be seemingly obvious local references to `ChainstateManager` or other validation objects which are not being used in callers of the current function in question, this is done intentionally to **_keep each commit centered around one function/method_** to ease review and to make the overall change systematic. We don't assume anything about our callers. Rest assured that once we are considering that particular caller in later commits, we will use the obvious local references. [Commits of overall PR](https://github.com/bitcoin/bitcoin/pull/20158/commits) 3. When changing a function/method that has many callers (e.g. `LookupBlockIndex` with 55 callers), it is sometimes easier (and less error-prone) to use a scripted-diff. When doing so, there will be 3 commits in sequence so that every commit compiles like so: 1. Add `new_function`, make `old_function` a wrapper of `new_function`, divert all calls to `old_function` to `new_function` **in the local module only** 2. Scripted-diff to divert all calls to `old_function` to `new_function` **in the rest of the codebase** 3. Remove `old_function` ACKs for top commit: jnewbery: utACK 67c9a83 laanwj: re-ACK 67c9a83 ryanofsky: Code review ACK 67c9a83. Changes since last review: Tree-SHA512: 8744aba2dd57a40cd2fedca809b0fe24d771bc60da1bffde89601999384aa0df428057a86644a3f72fbeedbc8b04db6c4fd264ea0db2e73c279e5acc6d056cbf
2 parents 636e754 + 67c9a83 commit 44f4bcd

17 files changed

+170
-143
lines changed

src/index/base.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ bool BaseIndex::Init()
6262
if (locator.IsNull()) {
6363
m_best_block_index = nullptr;
6464
} else {
65-
m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator);
65+
m_best_block_index = g_chainman.m_blockman.FindForkInGlobalIndex(::ChainActive(), locator);
6666
}
6767
m_synced = m_best_block_index.load() == ::ChainActive().Tip();
6868
return true;
@@ -239,7 +239,7 @@ void BaseIndex::ChainStateFlushed(const CBlockLocator& locator)
239239
const CBlockIndex* locator_tip_index;
240240
{
241241
LOCK(cs_main);
242-
locator_tip_index = LookupBlockIndex(locator_tip_hash);
242+
locator_tip_index = g_chainman.m_blockman.LookupBlockIndex(locator_tip_hash);
243243
}
244244

245245
if (!locator_tip_index) {

src/init.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -705,7 +705,7 @@ static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImp
705705
if (!file)
706706
break; // This error is logged in OpenBlockFile
707707
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
708-
LoadExternalBlockFile(chainparams, file, &pos);
708+
::ChainstateActive().LoadExternalBlockFile(chainparams, file, &pos);
709709
if (ShutdownRequested()) {
710710
LogPrintf("Shutdown requested. Exit %s\n", __func__);
711711
return;
@@ -724,7 +724,7 @@ static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImp
724724
FILE *file = fsbridge::fopen(path, "rb");
725725
if (file) {
726726
LogPrintf("Importing blocks file %s...\n", path.string());
727-
LoadExternalBlockFile(chainparams, file);
727+
::ChainstateActive().LoadExternalBlockFile(chainparams, file);
728728
if (ShutdownRequested()) {
729729
LogPrintf("Shutdown requested. Exit %s\n", __func__);
730730
return;
@@ -1611,7 +1611,7 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
16111611
// If the loaded chain has a wrong genesis, bail out immediately
16121612
// (we're likely using a testnet datadir, or the other way around).
16131613
if (!chainman.BlockIndex().empty() &&
1614-
!LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1614+
!g_chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
16151615
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
16161616
}
16171617

src/miner.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ void RegenerateCommitments(CBlock& block)
4545
tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
4646
block.vtx.at(0) = MakeTransactionRef(tx);
4747

48-
GenerateCoinbaseCommitment(block, WITH_LOCK(cs_main, return LookupBlockIndex(block.hashPrevBlock)), Params().GetConsensus());
48+
GenerateCoinbaseCommitment(block, WITH_LOCK(cs_main, return g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)), Params().GetConsensus());
4949

5050
block.hashMerkleRoot = BlockMerkleRoot(block);
5151
}
@@ -176,7 +176,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
176176
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
177177

178178
BlockValidationState state;
179-
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
179+
if (!TestBlockValidity(state, chainparams, ::ChainstateActive(), *pblock, pindexPrev, false, false)) {
180180
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
181181
}
182182
int64_t nTime2 = GetTimeMicros();

src/net_processing.cpp

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ static void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_
676676
assert(state != nullptr);
677677

678678
if (!state->hashLastUnknownBlock.IsNull()) {
679-
const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
679+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
680680
if (pindex && pindex->nChainWork > 0) {
681681
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
682682
state->pindexBestKnownBlock = pindex;
@@ -693,7 +693,7 @@ static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) EXCLUSIV
693693

694694
ProcessBlockAvailability(nodeid);
695695

696-
const CBlockIndex* pindex = LookupBlockIndex(hash);
696+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hash);
697697
if (pindex && pindex->nChainWork > 0) {
698698
// An actually better block was announced.
699699
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
@@ -1596,7 +1596,7 @@ bool static AlreadyHaveTx(const GenTxid& gtxid, const CTxMemPool& mempool) EXCLU
15961596

15971597
bool static AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
15981598
{
1599-
return LookupBlockIndex(block_hash) != nullptr;
1599+
return g_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
16001600
}
16011601

16021602
void RelayTransaction(const uint256& txid, const uint256& wtxid, const CConnman& connman)
@@ -1686,7 +1686,7 @@ void static ProcessGetBlockData(CNode& pfrom, Peer& peer, const CChainParams& ch
16861686
bool need_activate_chain = false;
16871687
{
16881688
LOCK(cs_main);
1689-
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1689+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(inv.hash);
16901690
if (pindex) {
16911691
if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
16921692
pindex->IsValid(BLOCK_VALID_TREE)) {
@@ -1701,13 +1701,13 @@ void static ProcessGetBlockData(CNode& pfrom, Peer& peer, const CChainParams& ch
17011701
} // release cs_main before calling ActivateBestChain
17021702
if (need_activate_chain) {
17031703
BlockValidationState state;
1704-
if (!ActivateBestChain(state, chainparams, a_recent_block)) {
1704+
if (!::ChainstateActive().ActivateBestChain(state, chainparams, a_recent_block)) {
17051705
LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
17061706
}
17071707
}
17081708

17091709
LOCK(cs_main);
1710-
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1710+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(inv.hash);
17111711
if (pindex) {
17121712
send = BlockRequestAllowed(pindex, consensusParams);
17131713
if (!send) {
@@ -1997,7 +1997,7 @@ void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
19971997
// don't connect before giving DoS points
19981998
// - Once a headers message is received that is valid and does connect,
19991999
// nUnconnectingHeaders gets reset back to 0.
2000-
if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
2000+
if (!g_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
20012001
nodestate->nUnconnectingHeaders++;
20022002
m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256()));
20032003
LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
@@ -2027,7 +2027,7 @@ void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
20272027

20282028
// If we don't have the last header, then they'll have given us
20292029
// something new (if these headers are valid).
2030-
if (!LookupBlockIndex(hashLastBlock)) {
2030+
if (!g_chainman.m_blockman.LookupBlockIndex(hashLastBlock)) {
20312031
received_new_header = true;
20322032
}
20332033
}
@@ -2279,7 +2279,7 @@ static bool PrepareBlockFilterRequest(CNode& peer, const CChainParams& chain_par
22792279

22802280
{
22812281
LOCK(cs_main);
2282-
stop_index = LookupBlockIndex(stop_hash);
2282+
stop_index = g_chainman.m_blockman.LookupBlockIndex(stop_hash);
22832283

22842284
// Check that the stop block exists and the peer would be allowed to fetch it.
22852285
if (!stop_index || !BlockRequestAllowed(stop_index, chain_params.GetConsensus())) {
@@ -2974,15 +2974,15 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
29742974
a_recent_block = most_recent_block;
29752975
}
29762976
BlockValidationState state;
2977-
if (!ActivateBestChain(state, m_chainparams, a_recent_block)) {
2977+
if (!::ChainstateActive().ActivateBestChain(state, m_chainparams, a_recent_block)) {
29782978
LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
29792979
}
29802980
}
29812981

29822982
LOCK(cs_main);
29832983

29842984
// Find the last block the caller has in the main chain
2985-
const CBlockIndex* pindex = FindForkInGlobalIndex(::ChainActive(), locator);
2985+
const CBlockIndex* pindex = g_chainman.m_blockman.FindForkInGlobalIndex(::ChainActive(), locator);
29862986

29872987
// Send the rest of the chain
29882988
if (pindex)
@@ -3035,7 +3035,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
30353035
{
30363036
LOCK(cs_main);
30373037

3038-
const CBlockIndex* pindex = LookupBlockIndex(req.blockhash);
3038+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(req.blockhash);
30393039
if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
30403040
LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
30413041
return;
@@ -3089,7 +3089,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
30893089
if (locator.IsNull())
30903090
{
30913091
// If locator is null, return the hashStop block
3092-
pindex = LookupBlockIndex(hashStop);
3092+
pindex = g_chainman.m_blockman.LookupBlockIndex(hashStop);
30933093
if (!pindex) {
30943094
return;
30953095
}
@@ -3102,7 +3102,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
31023102
else
31033103
{
31043104
// Find the last block the caller has in the main chain
3105-
pindex = FindForkInGlobalIndex(::ChainActive(), locator);
3105+
pindex = g_chainman.m_blockman.FindForkInGlobalIndex(::ChainActive(), locator);
31063106
if (pindex)
31073107
pindex = ::ChainActive().Next(pindex);
31083108
}
@@ -3366,14 +3366,14 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
33663366
{
33673367
LOCK(cs_main);
33683368

3369-
if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
3369+
if (!g_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
33703370
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
33713371
if (!::ChainstateActive().IsInitialBlockDownload())
33723372
m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256()));
33733373
return;
33743374
}
33753375

3376-
if (!LookupBlockIndex(cmpctblock.header.GetHash())) {
3376+
if (!g_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.GetHash())) {
33773377
received_new_header = true;
33783378
}
33793379
}
@@ -4442,7 +4442,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
44424442
// then send all headers past that one. If we come across any
44434443
// headers that aren't on ::ChainActive(), give up.
44444444
for (const uint256& hash : peer->m_blocks_for_headers_relay) {
4445-
const CBlockIndex* pindex = LookupBlockIndex(hash);
4445+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hash);
44464446
assert(pindex);
44474447
if (::ChainActive()[pindex->nHeight] != pindex) {
44484448
// Bail out if we reorged away from this block
@@ -4534,7 +4534,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
45344534
// in the past.
45354535
if (!peer->m_blocks_for_headers_relay.empty()) {
45364536
const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
4537-
const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce);
4537+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
45384538
assert(pindex);
45394539

45404540
// Warn if we're announcing a block that is not on the main chain.

src/node/coinstats.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ static bool GetUTXOStats(CCoinsView* view, CCoinsStats& stats, T hash_obj, const
6363
stats.hashBlock = pcursor->GetBestBlock();
6464
{
6565
LOCK(cs_main);
66-
stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;
66+
stats.nHeight = g_chainman.m_blockman.LookupBlockIndex(stats.hashBlock)->nHeight;
6767
}
6868

6969
PrepareHash(hash_obj, stats);

src/node/interfaces.cpp

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ class ChainImpl : public Chain
447447
{
448448
LOCK(cs_main);
449449
const CChain& active = Assert(m_node.chainman)->ActiveChain();
450-
if (CBlockIndex* fork = FindForkInGlobalIndex(active, locator)) {
450+
if (CBlockIndex* fork = g_chainman.m_blockman.FindForkInGlobalIndex(active, locator)) {
451451
return fork->nHeight;
452452
}
453453
return nullopt;
@@ -456,7 +456,7 @@ class ChainImpl : public Chain
456456
{
457457
WAIT_LOCK(cs_main, lock);
458458
const CChain& active = Assert(m_node.chainman)->ActiveChain();
459-
return FillBlock(LookupBlockIndex(hash), block, lock, active);
459+
return FillBlock(g_chainman.m_blockman.LookupBlockIndex(hash), block, lock, active);
460460
}
461461
bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
462462
{
@@ -468,7 +468,7 @@ class ChainImpl : public Chain
468468
{
469469
WAIT_LOCK(cs_main, lock);
470470
const CChain& active = Assert(m_node.chainman)->ActiveChain();
471-
if (const CBlockIndex* block = LookupBlockIndex(block_hash)) {
471+
if (const CBlockIndex* block = g_chainman.m_blockman.LookupBlockIndex(block_hash)) {
472472
if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
473473
return FillBlock(ancestor, ancestor_out, lock, active);
474474
}
@@ -479,17 +479,17 @@ class ChainImpl : public Chain
479479
{
480480
WAIT_LOCK(cs_main, lock);
481481
const CChain& active = Assert(m_node.chainman)->ActiveChain();
482-
const CBlockIndex* block = LookupBlockIndex(block_hash);
483-
const CBlockIndex* ancestor = LookupBlockIndex(ancestor_hash);
482+
const CBlockIndex* block = g_chainman.m_blockman.LookupBlockIndex(block_hash);
483+
const CBlockIndex* ancestor = g_chainman.m_blockman.LookupBlockIndex(ancestor_hash);
484484
if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
485485
return FillBlock(ancestor, ancestor_out, lock, active);
486486
}
487487
bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
488488
{
489489
WAIT_LOCK(cs_main, lock);
490490
const CChain& active = Assert(m_node.chainman)->ActiveChain();
491-
const CBlockIndex* block1 = LookupBlockIndex(block_hash1);
492-
const CBlockIndex* block2 = LookupBlockIndex(block_hash2);
491+
const CBlockIndex* block1 = g_chainman.m_blockman.LookupBlockIndex(block_hash1);
492+
const CBlockIndex* block2 = g_chainman.m_blockman.LookupBlockIndex(block_hash2);
493493
const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
494494
// Using & instead of && below to avoid short circuiting and leaving
495495
// output uninitialized.
@@ -499,7 +499,7 @@ class ChainImpl : public Chain
499499
double guessVerificationProgress(const uint256& block_hash) override
500500
{
501501
LOCK(cs_main);
502-
return GuessVerificationProgress(Params().TxData(), LookupBlockIndex(block_hash));
502+
return GuessVerificationProgress(Params().TxData(), g_chainman.m_blockman.LookupBlockIndex(block_hash));
503503
}
504504
bool hasBlocks(const uint256& block_hash, int min_height, Optional<int> max_height) override
505505
{
@@ -511,7 +511,7 @@ class ChainImpl : public Chain
511511
// used to limit the range, and passing min_height that's too low or
512512
// max_height that's too high will not crash or change the result.
513513
LOCK(::cs_main);
514-
if (CBlockIndex* block = LookupBlockIndex(block_hash)) {
514+
if (CBlockIndex* block = g_chainman.m_blockman.LookupBlockIndex(block_hash)) {
515515
if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
516516
for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
517517
// Check pprev to not segfault if min_height is too low

src/rest.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ static bool rest_headers(const util::Ref& context,
179179
{
180180
LOCK(cs_main);
181181
tip = ::ChainActive().Tip();
182-
const CBlockIndex* pindex = LookupBlockIndex(hash);
182+
const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hash);
183183
while (pindex != nullptr && ::ChainActive().Contains(pindex)) {
184184
headers.push_back(pindex);
185185
if (headers.size() == (unsigned long)count)
@@ -247,7 +247,7 @@ static bool rest_block(HTTPRequest* req,
247247
{
248248
LOCK(cs_main);
249249
tip = ::ChainActive().Tip();
250-
pblockindex = LookupBlockIndex(hash);
250+
pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash);
251251
if (!pblockindex) {
252252
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
253253
}

0 commit comments

Comments
 (0)