Skip to content

Commit 682a1d0

Browse files
committed
refactoring: remove mapBlockIndex global
in lieu of ::BlockIndex().
1 parent 55d525a commit 682a1d0

File tree

6 files changed

+48
-39
lines changed

6 files changed

+48
-39
lines changed

src/init.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ void SetupServerArgs()
492492
"and level 4 tries to reconnect the blocks, "
493493
"each level includes the checks of the previous levels "
494494
"(0-4, default: %u)", DEFAULT_CHECKLEVEL), true, OptionsCategory::DEBUG_TEST);
495-
gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, ::ChainActive() and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
495+
gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for the block tree, setBlockIndexCandidates, ::ChainActive() and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
496496
gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
497497
gArgs.AddArg("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), true, OptionsCategory::DEBUG_TEST);
498498
gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", true, OptionsCategory::DEBUG_TEST);
@@ -1517,7 +1517,8 @@ bool AppInitMain(InitInterfaces& interfaces)
15171517

15181518
// If the loaded chain has a wrong genesis, bail out immediately
15191519
// (we're likely using a testnet datadir, or the other way around).
1520-
if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1520+
if (!::BlockIndex().empty() &&
1521+
!LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
15211522
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
15221523
}
15231524

@@ -1538,7 +1539,7 @@ bool AppInitMain(InitInterfaces& interfaces)
15381539
}
15391540

15401541
// At this point we're either in reindex or we've loaded a useful
1541-
// block tree into mapBlockIndex!
1542+
// block tree into BlockIndex()!
15421543

15431544
pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
15441545
pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));
@@ -1577,7 +1578,7 @@ bool AppInitMain(InitInterfaces& interfaces)
15771578
if (!fReset) {
15781579
// Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
15791580
// It both disconnects blocks based on ::ChainActive(), and drops block data in
1580-
// mapBlockIndex based on lack of available witness data.
1581+
// BlockIndex() based on lack of available witness data.
15811582
uiInterface.InitMessage(_("Rewinding blocks..."));
15821583
if (!RewindBlockIndex(chainparams)) {
15831584
strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
@@ -1749,7 +1750,7 @@ bool AppInitMain(InitInterfaces& interfaces)
17491750
//// debug print
17501751
{
17511752
LOCK(cs_main);
1752-
LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1753+
LogPrintf("block tree size = %u\n", ::BlockIndex().size());
17531754
chain_active_height = ::ChainActive().Height();
17541755
}
17551756
LogPrintf("nBestHeight = %d\n", chain_active_height);

src/rpc/blockchain.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,15 +1456,15 @@ static UniValue getchaintips(const JSONRPCRequest& request)
14561456
/*
14571457
* Idea: the set of chain tips is ::ChainActive().tip, plus orphan blocks which do not have another orphan building off of them.
14581458
* Algorithm:
1459-
* - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
1459+
* - Make one pass through g_blockman.m_block_index, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
14601460
* - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
14611461
* - add ::ChainActive().Tip()
14621462
*/
14631463
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
14641464
std::set<const CBlockIndex*> setOrphans;
14651465
std::set<const CBlockIndex*> setPrevs;
14661466

1467-
for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
1467+
for (const std::pair<const uint256, CBlockIndex*>& item : ::BlockIndex())
14681468
{
14691469
if (!::ChainActive().Contains(item.second)) {
14701470
setOrphans.insert(item.second);

src/txdb.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams,
250250

251251
pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
252252

253-
// Load mapBlockIndex
253+
// Load m_block_index
254254
while (pcursor->Valid()) {
255255
boost::this_thread::interruption_point();
256256
if (ShutdownRequested()) return false;

src/validation.cpp

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ CChain& ChainActive() { return g_chainstate.m_chain; }
9999
*/
100100
RecursiveMutex cs_main;
101101

102-
BlockMap& mapBlockIndex = g_blockman.m_block_index;
103102
CBlockIndex *pindexBestHeader = nullptr;
104103
Mutex g_best_block_mutex;
105104
std::condition_variable g_best_block_cv;
@@ -147,6 +146,13 @@ namespace {
147146
std::set<int> setDirtyFileInfo;
148147
} // anon namespace
149148

149+
CBlockIndex* LookupBlockIndex(const uint256& hash)
150+
{
151+
AssertLockHeld(cs_main);
152+
BlockMap::const_iterator it = g_blockman.m_block_index.find(hash);
153+
return it == g_blockman.m_block_index.end() ? nullptr : it->second;
154+
}
155+
150156
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
151157
{
152158
AssertLockHeld(cs_main);
@@ -1046,6 +1052,11 @@ bool CChainState::IsInitialBlockDownload() const
10461052

10471053
static CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
10481054

1055+
BlockMap& BlockIndex()
1056+
{
1057+
return g_blockman.m_block_index;
1058+
}
1059+
10491060
static void AlertNotify(const std::string& strMessage)
10501061
{
10511062
uiInterface.NotifyAlertChanged();
@@ -3117,7 +3128,7 @@ static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationSta
31173128
if (fCheckpointsEnabled) {
31183129
// Don't accept any forks from the main chain prior to last checkpoint.
31193130
// GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3120-
// MapBlockIndex.
3131+
// g_blockman.m_block_index.
31213132
CBlockIndex* pcheckpoint = GetLastCheckpoint(params.Checkpoints());
31223133
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
31233134
return state.Invalid(ValidationInvalidReason::BLOCK_CHECKPOINT, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
@@ -3715,8 +3726,8 @@ bool BlockManager::LoadBlockIndex(
37153726

37163727
// Calculate nChainWork
37173728
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3718-
vSortedByHeight.reserve(mapBlockIndex.size());
3719-
for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
3729+
vSortedByHeight.reserve(m_block_index.size());
3730+
for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
37203731
{
37213732
CBlockIndex* pindex = item.second;
37223733
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
@@ -3797,7 +3808,7 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams) EXCLUSIVE_LOCKS_RE
37973808
// Check presence of blk files
37983809
LogPrintf("Checking all blk files are present...\n");
37993810
std::set<int> setBlkDataFiles;
3800-
for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
3811+
for (const std::pair<const uint256, CBlockIndex*>& item : g_blockman.m_block_index)
38013812
{
38023813
CBlockIndex* pindex = item.second;
38033814
if (pindex->nStatus & BLOCK_HAVE_DATA) {
@@ -3996,16 +4007,16 @@ bool CChainState::ReplayBlocks(const CChainParams& params, CCoinsView* view)
39964007
const CBlockIndex* pindexNew; // New tip during the interrupted flush.
39974008
const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
39984009

3999-
if (mapBlockIndex.count(hashHeads[0]) == 0) {
4010+
if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
40004011
return error("ReplayBlocks(): reorganization to unknown block requested");
40014012
}
4002-
pindexNew = mapBlockIndex[hashHeads[0]];
4013+
pindexNew = m_blockman.m_block_index[hashHeads[0]];
40034014

40044015
if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4005-
if (mapBlockIndex.count(hashHeads[1]) == 0) {
4016+
if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
40064017
return error("ReplayBlocks(): reorganization from unknown block requested");
40074018
}
4008-
pindexOld = mapBlockIndex[hashHeads[1]];
4019+
pindexOld = m_blockman.m_block_index[hashHeads[1]];
40094020
pindexFork = LastCommonAncestor(pindexOld, pindexNew);
40104021
assert(pindexFork != nullptr);
40114022
}
@@ -4094,7 +4105,7 @@ bool CChainState::RewindBlockIndex(const CChainParams& params)
40944105
// blocks will be dealt with below (releasing cs_main in between).
40954106
{
40964107
LOCK(cs_main);
4097-
for (const auto& entry : mapBlockIndex) {
4108+
for (const auto& entry : m_blockman.m_block_index) {
40984109
if (IsWitnessEnabled(entry.second->pprev, params.GetConsensus()) && !(entry.second->nStatus & BLOCK_OPT_WITNESS) && !m_chain.Contains(entry.second)) {
40994110
EraseBlockData(entry.second);
41004111
}
@@ -4234,7 +4245,7 @@ bool LoadBlockIndex(const CChainParams& chainparams)
42344245
if (!fReindex) {
42354246
bool ret = LoadBlockIndexDB(chainparams);
42364247
if (!ret) return false;
4237-
needs_init = mapBlockIndex.empty();
4248+
needs_init = g_blockman.m_block_index.empty();
42384249
}
42394250

42404251
if (needs_init) {
@@ -4254,10 +4265,10 @@ bool CChainState::LoadGenesisBlock(const CChainParams& chainparams)
42544265
LOCK(cs_main);
42554266

42564267
// Check whether we're already initialized by checking for genesis in
4257-
// mapBlockIndex. Note that we can't use m_chain here, since it is
4268+
// m_blockman.m_block_index. Note that we can't use m_chain here, since it is
42584269
// set based on the coins db, not the block index db, which is the only
42594270
// thing loaded at this point.
4260-
if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
4271+
if (m_blockman.m_block_index.count(chainparams.GenesisBlock().GetHash()))
42614272
return true;
42624273

42634274
try {
@@ -4410,20 +4421,20 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
44104421
LOCK(cs_main);
44114422

44124423
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4413-
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4414-
// iterating the block tree require that m_chain has been initialized.)
4424+
// so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
4425+
// tests when iterating the block tree require that m_chain has been initialized.)
44154426
if (m_chain.Height() < 0) {
4416-
assert(mapBlockIndex.size() <= 1);
4427+
assert(m_blockman.m_block_index.size() <= 1);
44174428
return;
44184429
}
44194430

44204431
// Build forward-pointing map of the entire block tree.
44214432
std::multimap<CBlockIndex*,CBlockIndex*> forward;
4422-
for (const std::pair<const uint256, CBlockIndex*>& entry : mapBlockIndex) {
4433+
for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
44234434
forward.insert(std::make_pair(entry.second->pprev, entry.second));
44244435
}
44254436

4426-
assert(forward.size() == mapBlockIndex.size());
4437+
assert(forward.size() == m_blockman.m_block_index.size());
44274438

44284439
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
44294440
CBlockIndex *pindex = rangeGenesis.first->second;
@@ -4477,7 +4488,7 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
44774488
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
44784489
assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
44794490
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4480-
assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4491+
assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
44814492
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
44824493
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
44834494
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
@@ -4772,10 +4783,10 @@ class CMainCleanup
47724783
CMainCleanup() {}
47734784
~CMainCleanup() {
47744785
// block headers
4775-
BlockMap::iterator it1 = mapBlockIndex.begin();
4776-
for (; it1 != mapBlockIndex.end(); it1++)
4786+
BlockMap::iterator it1 = g_blockman.m_block_index.begin();
4787+
for (; it1 != g_blockman.m_block_index.end(); it1++)
47774788
delete (*it1).second;
4778-
mapBlockIndex.clear();
4789+
g_blockman.m_block_index.clear();
47794790
}
47804791
};
47814792
static CMainCleanup instance_of_cmaincleanup;

src/validation.h

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,6 @@ extern CCriticalSection cs_main;
144144
extern CBlockPolicyEstimator feeEstimator;
145145
extern CTxMemPool mempool;
146146
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
147-
extern BlockMap& mapBlockIndex GUARDED_BY(cs_main);
148147
extern Mutex g_best_block_mutex;
149148
extern std::condition_variable g_best_block_cv;
150149
extern uint256 g_best_block;
@@ -406,12 +405,7 @@ class CVerifyDB {
406405
/** Replay blocks that aren't fully applied to the database. */
407406
bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
408407

409-
inline CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
410-
{
411-
AssertLockHeld(cs_main);
412-
BlockMap::const_iterator it = mapBlockIndex.find(hash);
413-
return it == mapBlockIndex.end() ? nullptr : it->second;
414-
}
408+
CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
415409

416410
/** Find the last common block between the parameter chain and a locator. */
417411
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
@@ -498,7 +492,7 @@ class BlockManager {
498492

499493
/**
500494
* If a block header hasn't already been seen, call CheckBlockHeader on it, ensure
501-
* that it doesn't descend from an invalid block, and then add it to mapBlockIndex.
495+
* that it doesn't descend from an invalid block, and then add it to m_block_index.
502496
*/
503497
bool AcceptBlockHeader(
504498
const CBlockHeader& block,
@@ -658,6 +652,9 @@ CChainState& ChainstateActive();
658652
/** @returns the most-work chain. */
659653
CChain& ChainActive();
660654

655+
/** @returns the global block index map. */
656+
BlockMap& BlockIndex();
657+
661658
/** Global variable that points to the coins database (protected by cs_main) */
662659
extern std::unique_ptr<CCoinsViewDB> pcoinsdbview;
663660

src/wallet/test/wallet_tests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64
272272
if (blockTime > 0) {
273273
auto locked_chain = wallet.chain().lock();
274274
LockAssertion lock(::cs_main);
275-
auto inserted = mapBlockIndex.emplace(GetRandHash(), new CBlockIndex);
275+
auto inserted = ::BlockIndex().emplace(GetRandHash(), new CBlockIndex);
276276
assert(inserted.second);
277277
const uint256& hash = inserted.first->first;
278278
block = inserted.first->second;

0 commit comments

Comments
 (0)