Skip to content

Commit 92fabcd

Browse files
committed
Add LookupBlockIndex function
1 parent 43a32b7 commit 92fabcd

14 files changed

+139
-133
lines changed

src/checkpoints.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@ namespace Checkpoints {
2121
for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
2222
{
2323
const uint256& hash = i.second;
24-
BlockMap::const_iterator t = mapBlockIndex.find(hash);
25-
if (t != mapBlockIndex.end())
26-
return t->second;
24+
CBlockIndex* pindex = LookupBlockIndex(hash);
25+
if (pindex) {
26+
return pindex;
27+
}
2728
}
2829
return nullptr;
2930
}

src/checkpoints.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ struct CCheckpointData;
1919
namespace Checkpoints
2020
{
2121

22-
//! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint
22+
//! Returns last CBlockIndex* that is a checkpoint
2323
CBlockIndex* GetLastCheckpoint(const CCheckpointData& data);
2424

2525
} //namespace Checkpoints

src/init.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1459,8 +1459,9 @@ bool AppInitMain()
14591459

14601460
// If the loaded chain has a wrong genesis, bail out immediately
14611461
// (we're likely using a testnet datadir, or the other way around).
1462-
if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1462+
if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
14631463
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1464+
}
14641465

14651466
// Check for changed -txindex state
14661467
if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {

src/net_processing.cpp

Lines changed: 41 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -374,10 +374,11 @@ void ProcessBlockAvailability(NodeId nodeid) {
374374
assert(state != nullptr);
375375

376376
if (!state->hashLastUnknownBlock.IsNull()) {
377-
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
378-
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
379-
if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
380-
state->pindexBestKnownBlock = itOld->second;
377+
const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
378+
if (pindex && pindex->nChainWork > 0) {
379+
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
380+
state->pindexBestKnownBlock = pindex;
381+
}
381382
state->hashLastUnknownBlock.SetNull();
382383
}
383384
}
@@ -390,11 +391,12 @@ void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
390391

391392
ProcessBlockAvailability(nodeid);
392393

393-
BlockMap::iterator it = mapBlockIndex.find(hash);
394-
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
394+
const CBlockIndex* pindex = LookupBlockIndex(hash);
395+
if (pindex && pindex->nChainWork > 0) {
395396
// An actually better block was announced.
396-
if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
397-
state->pindexBestKnownBlock = it->second;
397+
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
398+
state->pindexBestKnownBlock = pindex;
399+
}
398400
} else {
399401
// An unknown block was announced; just assume that the latest one is the best one.
400402
state->hashLastUnknownBlock = hash;
@@ -989,7 +991,7 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
989991
}
990992
case MSG_BLOCK:
991993
case MSG_WITNESS_BLOCK:
992-
return mapBlockIndex.count(inv.hash);
994+
return LookupBlockIndex(inv.hash) != nullptr;
993995
}
994996
// Don't know what it is, just say we already got one
995997
return true;
@@ -1056,11 +1058,10 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
10561058
bool need_activate_chain = false;
10571059
{
10581060
LOCK(cs_main);
1059-
BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1060-
if (mi != mapBlockIndex.end())
1061-
{
1062-
if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1063-
mi->second->IsValid(BLOCK_VALID_TREE)) {
1061+
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1062+
if (pindex) {
1063+
if (pindex->nChainTx && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
1064+
pindex->IsValid(BLOCK_VALID_TREE)) {
10641065
// If we have the block and all of its parents, but have not yet validated it,
10651066
// we might be in the middle of connecting it (ie in the unlock of cs_main
10661067
// before ActivateBestChain but after AcceptBlock).
@@ -1076,17 +1077,17 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
10761077
}
10771078

10781079
LOCK(cs_main);
1079-
BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1080-
if (mi != mapBlockIndex.end()) {
1081-
send = BlockRequestAllowed(mi->second, consensusParams);
1080+
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1081+
if (pindex) {
1082+
send = BlockRequestAllowed(pindex, consensusParams);
10821083
if (!send) {
10831084
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
10841085
}
10851086
}
10861087
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
10871088
// disconnect node in case we have reached the outbound limit for serving historical blocks
10881089
// never disconnect whitelisted nodes
1089-
if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1090+
if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
10901091
{
10911092
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
10921093

@@ -1096,7 +1097,7 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
10961097
}
10971098
// Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
10981099
if (send && !pfrom->fWhitelisted && (
1099-
(((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - mi->second->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
1100+
(((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
11001101
)) {
11011102
LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId());
11021103

@@ -1106,15 +1107,15 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
11061107
}
11071108
// Pruned nodes may have deleted the block, so check whether
11081109
// it's available before trying to send.
1109-
if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1110+
if (send && (pindex->nStatus & BLOCK_HAVE_DATA))
11101111
{
11111112
std::shared_ptr<const CBlock> pblock;
1112-
if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1113+
if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
11131114
pblock = a_recent_block;
11141115
} else {
11151116
// Send block from disk
11161117
std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1117-
if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1118+
if (!ReadBlockFromDisk(*pblockRead, pindex, consensusParams))
11181119
assert(!"cannot load block from disk");
11191120
pblock = pblockRead;
11201121
}
@@ -1156,8 +1157,8 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
11561157
// instead we respond with the full, non-compact block.
11571158
bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
11581159
int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1159-
if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1160-
if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1160+
if (CanDirectFetch(consensusParams) && pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1161+
if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
11611162
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
11621163
} else {
11631164
CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
@@ -1297,7 +1298,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
12971298
// don't connect before giving DoS points
12981299
// - Once a headers message is received that is valid and does connect,
12991300
// nUnconnectingHeaders gets reset back to 0.
1300-
if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1301+
if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
13011302
nodestate->nUnconnectingHeaders++;
13021303
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
13031304
LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
@@ -1327,7 +1328,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
13271328

13281329
// If we don't have the last header, then they'll have given us
13291330
// something new (if these headers are valid).
1330-
if (mapBlockIndex.find(hashLastBlock) == mapBlockIndex.end()) {
1331+
if (!LookupBlockIndex(hashLastBlock)) {
13311332
received_new_header = true;
13321333
}
13331334
}
@@ -1343,7 +1344,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
13431344
} else {
13441345
LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId());
13451346
}
1346-
if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
1347+
if (punish_duplicate_invalid && LookupBlockIndex(first_invalid_header.GetHash())) {
13471348
// Goal: don't allow outbound peers to use up our outbound
13481349
// connection slots if they are on incompatible chains.
13491350
//
@@ -2024,13 +2025,13 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
20242025

20252026
LOCK(cs_main);
20262027

2027-
BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
2028-
if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
2028+
const CBlockIndex* pindex = LookupBlockIndex(req.blockhash);
2029+
if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
20292030
LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
20302031
return true;
20312032
}
20322033

2033-
if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
2034+
if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
20342035
// If an older block is requested (should never happen in practice,
20352036
// but can happen in tests) send a block response instead of a
20362037
// blocktxn response. Sending a full block response instead of a
@@ -2048,7 +2049,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
20482049
}
20492050

20502051
CBlock block;
2051-
bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
2052+
bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus());
20522053
assert(ret);
20532054

20542055
SendBlockTransactions(block, req, pfrom, connman);
@@ -2072,10 +2073,10 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
20722073
if (locator.IsNull())
20732074
{
20742075
// If locator is null, return the hashStop block
2075-
BlockMap::iterator mi = mapBlockIndex.find(hashStop);
2076-
if (mi == mapBlockIndex.end())
2076+
pindex = LookupBlockIndex(hashStop);
2077+
if (!pindex) {
20772078
return true;
2078-
pindex = (*mi).second;
2079+
}
20792080

20802081
if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
20812082
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
@@ -2314,14 +2315,14 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
23142315
{
23152316
LOCK(cs_main);
23162317

2317-
if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
2318+
if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
23182319
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
23192320
if (!IsInitialBlockDownload())
23202321
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
23212322
return true;
23222323
}
23232324

2324-
if (mapBlockIndex.find(cmpctblock.header.GetHash()) == mapBlockIndex.end()) {
2325+
if (!LookupBlockIndex(cmpctblock.header.GetHash())) {
23252326
received_new_header = true;
23262327
}
23272328
}
@@ -3303,9 +3304,8 @@ bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptM
33033304
// then send all headers past that one. If we come across any
33043305
// headers that aren't on chainActive, give up.
33053306
for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3306-
BlockMap::iterator mi = mapBlockIndex.find(hash);
3307-
assert(mi != mapBlockIndex.end());
3308-
const CBlockIndex *pindex = mi->second;
3307+
const CBlockIndex* pindex = LookupBlockIndex(hash);
3308+
assert(pindex);
33093309
if (chainActive[pindex->nHeight] != pindex) {
33103310
// Bail out if we reorged away from this block
33113311
fRevertToInv = true;
@@ -3396,9 +3396,8 @@ bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptM
33963396
// in the past.
33973397
if (!pto->vBlockHashesToAnnounce.empty()) {
33983398
const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3399-
BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3400-
assert(mi != mapBlockIndex.end());
3401-
const CBlockIndex *pindex = mi->second;
3399+
const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce);
3400+
assert(pindex);
34023401

34033402
// Warn if we're announcing a block that is not on the main chain.
34043403
// This should be very rare and could be optimized out.

src/qt/transactionrecord.cpp

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,7 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx)
167167
// Determine transaction status
168168

169169
// Find the block the tx is in
170-
CBlockIndex* pindex = nullptr;
171-
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
172-
if (mi != mapBlockIndex.end())
173-
pindex = (*mi).second;
170+
const CBlockIndex* pindex = LookupBlockIndex(wtx.hashBlock);
174171

175172
// Sort order, unrecorded transactions sort to the top
176173
status.sortKey = strprintf("%010d-%01d-%010u-%03d",

src/rest.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,7 @@ static bool rest_headers(HTTPRequest* req,
147147
headers.reserve(count);
148148
{
149149
LOCK(cs_main);
150-
BlockMap::const_iterator it = mapBlockIndex.find(hash);
151-
const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : nullptr;
150+
const CBlockIndex* pindex = LookupBlockIndex(hash);
152151
while (pindex != nullptr && chainActive.Contains(pindex)) {
153152
headers.push_back(pindex);
154153
if (headers.size() == (unsigned long)count)
@@ -212,10 +211,11 @@ static bool rest_block(HTTPRequest* req,
212211
CBlockIndex* pblockindex = nullptr;
213212
{
214213
LOCK(cs_main);
215-
if (mapBlockIndex.count(hash) == 0)
214+
pblockindex = LookupBlockIndex(hash);
215+
if (!pblockindex) {
216216
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
217+
}
217218

218-
pblockindex = mapBlockIndex[hash];
219219
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
220220
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
221221

0 commit comments

Comments
 (0)