Skip to content

Commit bec86ae

Browse files
committed
blockstorage: Make m_block_index own CBlockIndex's
Instead of having CBlockIndex's live on the heap, which requires manual memory management, have them be owned by m_block_index. This means that they will live and die with BlockManager. A change to BlockManager::LookupBlockIndex: - Previously, it was a const member function returning a non-const CBlockIndex* - Now, there's are const and non-const versions of BlockManager::LookupBlockIndex returning a CBlockIndex with the same const-ness as the member function: (e.g. const CBlockIndex* LookupBlockIndex(...) const) See next commit for some weirdness that this eliminates. The range based for-loops are modernize (using auto + destructuring) in a future commit.
1 parent c44e734 commit bec86ae

File tree

5 files changed

+58
-47
lines changed

5 files changed

+58
-47
lines changed

src/node/blockstorage.cpp

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,18 @@ static FILE* OpenUndoFile(const FlatFilePos& pos, bool fReadOnly = false);
3232
static FlatFileSeq BlockFileSeq();
3333
static FlatFileSeq UndoFileSeq();
3434

35-
CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
35+
CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash)
36+
{
37+
AssertLockHeld(cs_main);
38+
BlockMap::iterator it = m_block_index.find(hash);
39+
return it == m_block_index.end() ? nullptr : &it->second;
40+
}
41+
42+
const CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
3643
{
3744
AssertLockHeld(cs_main);
3845
BlockMap::const_iterator it = m_block_index.find(hash);
39-
return it == m_block_index.end() ? nullptr : it->second;
46+
return it == m_block_index.end() ? nullptr : &it->second;
4047
}
4148

4249
CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
@@ -47,20 +54,22 @@ CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
4754
uint256 hash = block.GetHash();
4855
BlockMap::iterator it = m_block_index.find(hash);
4956
if (it != m_block_index.end()) {
50-
return it->second;
57+
return &it->second;
5158
}
5259

5360
// Construct new block index object
54-
CBlockIndex* pindexNew = new CBlockIndex(block);
61+
CBlockIndex new_index{block};
5562
// We assign the sequence id to blocks only when the full data is available,
5663
// to avoid miners withholding blocks but broadcasting headers, to get a
5764
// competitive advantage.
58-
pindexNew->nSequenceId = 0;
59-
BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
65+
new_index.nSequenceId = 0;
66+
BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, std::move(new_index))).first;
67+
68+
CBlockIndex* pindexNew = &(*mi).second;
6069
pindexNew->phashBlock = &((*mi).first);
6170
BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
6271
if (miPrev != m_block_index.end()) {
63-
pindexNew->pprev = (*miPrev).second;
72+
pindexNew->pprev = &(*miPrev).second;
6473
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
6574
pindexNew->BuildSkip();
6675
}
@@ -80,8 +89,8 @@ void BlockManager::PruneOneBlockFile(const int fileNumber)
8089
AssertLockHeld(cs_main);
8190
LOCK(cs_LastBlockFile);
8291

83-
for (const auto& entry : m_block_index) {
84-
CBlockIndex* pindex = entry.second;
92+
for (auto& entry : m_block_index) {
93+
CBlockIndex* pindex = &entry.second;
8594
if (pindex->nFile == fileNumber) {
8695
pindex->nStatus &= ~BLOCK_HAVE_DATA;
8796
pindex->nStatus &= ~BLOCK_HAVE_UNDO;
@@ -202,12 +211,13 @@ CBlockIndex* BlockManager::InsertBlockIndex(const uint256& hash)
202211
// Return existing
203212
BlockMap::iterator mi = m_block_index.find(hash);
204213
if (mi != m_block_index.end()) {
205-
return (*mi).second;
214+
return &(*mi).second;
206215
}
207216

208217
// Create new
209-
CBlockIndex* pindexNew = new CBlockIndex();
210-
mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
218+
CBlockIndex new_index{};
219+
mi = m_block_index.insert(std::make_pair(hash, std::move(new_index))).first;
220+
CBlockIndex* pindexNew = &(*mi).second;
211221
pindexNew->phashBlock = &((*mi).first);
212222

213223
return pindexNew;
@@ -224,8 +234,8 @@ bool BlockManager::LoadBlockIndex(
224234
// Calculate nChainWork
225235
std::vector<std::pair<int, CBlockIndex*>> vSortedByHeight;
226236
vSortedByHeight.reserve(m_block_index.size());
227-
for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index) {
228-
CBlockIndex* pindex = item.second;
237+
for (std::pair<const uint256, CBlockIndex>& item : m_block_index) {
238+
CBlockIndex* pindex = &item.second;
229239
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
230240
}
231241
sort(vSortedByHeight.begin(), vSortedByHeight.end());
@@ -327,10 +337,6 @@ void BlockManager::Unload()
327337
{
328338
m_blocks_unlinked.clear();
329339

330-
for (const BlockMap::value_type& entry : m_block_index) {
331-
delete entry.second;
332-
}
333-
334340
m_block_index.clear();
335341

336342
m_blockfile_info.clear();
@@ -386,8 +392,8 @@ bool BlockManager::LoadBlockIndexDB(ChainstateManager& chainman)
386392
// Check presence of blk files
387393
LogPrintf("Checking all blk files are present...\n");
388394
std::set<int> setBlkDataFiles;
389-
for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index) {
390-
CBlockIndex* pindex = item.second;
395+
for (const std::pair<const uint256, CBlockIndex>& item : m_block_index) {
396+
const CBlockIndex* pindex = &item.second;
391397
if (pindex->nStatus & BLOCK_HAVE_DATA) {
392398
setBlkDataFiles.insert(pindex->nFile);
393399
}

src/node/blockstorage.h

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#ifndef BITCOIN_NODE_BLOCKSTORAGE_H
66
#define BITCOIN_NODE_BLOCKSTORAGE_H
77

8+
#include <chain.h>
89
#include <fs.h>
910
#include <protocol.h> // For CMessageHeader::MessageStartChars
1011
#include <sync.h>
@@ -20,7 +21,6 @@ class ArgsManager;
2021
class BlockValidationState;
2122
class CBlock;
2223
class CBlockFileInfo;
23-
class CBlockIndex;
2424
class CBlockUndo;
2525
class CChain;
2626
class CChainParams;
@@ -52,7 +52,11 @@ extern bool fPruneMode;
5252
/** Number of MiB of block files that we're trying to stay below. */
5353
extern uint64_t nPruneTarget;
5454

55-
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
55+
// Because validation code takes pointers to the map's CBlockIndex objects, if
56+
// we ever switch to another associative container, we need to either use a
57+
// container that has stable addressing (true of all std associative
58+
// containers), or make the key a `std::unique_ptr<CBlockIndex>`
59+
typedef std::unordered_map<uint256, CBlockIndex, BlockHasher> BlockMap;
5660

5761
struct CBlockIndexWorkComparator {
5862
bool operator()(const CBlockIndex* pa, const CBlockIndex* pb) const;
@@ -144,7 +148,8 @@ class BlockManager
144148
//! Mark one block file as pruned (modify associated database entries)
145149
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
146150

147-
CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
151+
CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
152+
const CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
148153

149154
/** Get block file info entry for one block file */
150155
CBlockFileInfo* GetBlockFileInfo(size_t n);

src/rpc/blockchain.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1753,10 +1753,10 @@ static RPCHelpMan getchaintips()
17531753
std::set<const CBlockIndex*> setOrphans;
17541754
std::set<const CBlockIndex*> setPrevs;
17551755

1756-
for (const std::pair<const uint256, CBlockIndex*>& item : chainman.BlockIndex()) {
1757-
if (!active_chain.Contains(item.second)) {
1758-
setOrphans.insert(item.second);
1759-
setPrevs.insert(item.second->pprev);
1756+
for (const std::pair<const uint256, CBlockIndex>& item : chainman.BlockIndex()) {
1757+
if (!active_chain.Contains(&item.second)) {
1758+
setOrphans.insert(&item.second);
1759+
setPrevs.insert(item.second.pprev);
17601760
}
17611761
}
17621762

src/validation.cpp

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1978,7 +1978,7 @@ bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state,
19781978
// effectively caching the result of part of the verification.
19791979
BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
19801980
if (it != m_blockman.m_block_index.end()) {
1981-
if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1981+
if (it->second.GetAncestor(pindex->nHeight) == pindex &&
19821982
pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
19831983
pindexBestHeader->nChainWork >= nMinimumChainWork) {
19841984
// This block is a member of the assumed verified chain and an ancestor of the best header.
@@ -3035,8 +3035,8 @@ bool CChainState::InvalidateBlock(BlockValidationState& state, CBlockIndex* pind
30353035

30363036
{
30373037
LOCK(cs_main);
3038-
for (const auto& entry : m_blockman.m_block_index) {
3039-
CBlockIndex *candidate = entry.second;
3038+
for (auto& entry : m_blockman.m_block_index) {
3039+
CBlockIndex* candidate = &entry.second;
30403040
// We don't need to put anything in our active chain into the
30413041
// multimap, because those candidates will be found and considered
30423042
// as we disconnect.
@@ -3135,8 +3135,8 @@ bool CChainState::InvalidateBlock(BlockValidationState& state, CBlockIndex* pind
31353135
// to setBlockIndexCandidates.
31363136
BlockMap::iterator it = m_blockman.m_block_index.begin();
31373137
while (it != m_blockman.m_block_index.end()) {
3138-
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
3139-
setBlockIndexCandidates.insert(it->second);
3138+
if (it->second.IsValid(BLOCK_VALID_TRANSACTIONS) && it->second.HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(&it->second, m_chain.Tip())) {
3139+
setBlockIndexCandidates.insert(&it->second);
31403140
}
31413141
it++;
31423142
}
@@ -3159,17 +3159,17 @@ void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
31593159
// Remove the invalidity flag from this block and all its descendants.
31603160
BlockMap::iterator it = m_blockman.m_block_index.begin();
31613161
while (it != m_blockman.m_block_index.end()) {
3162-
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3163-
it->second->nStatus &= ~BLOCK_FAILED_MASK;
3164-
m_blockman.m_dirty_blockindex.insert(it->second);
3165-
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
3166-
setBlockIndexCandidates.insert(it->second);
3162+
if (!it->second.IsValid() && it->second.GetAncestor(nHeight) == pindex) {
3163+
it->second.nStatus &= ~BLOCK_FAILED_MASK;
3164+
m_blockman.m_dirty_blockindex.insert(&it->second);
3165+
if (it->second.IsValid(BLOCK_VALID_TRANSACTIONS) && it->second.HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), &it->second)) {
3166+
setBlockIndexCandidates.insert(&it->second);
31673167
}
3168-
if (it->second == m_chainman.m_best_invalid) {
3168+
if (&it->second == m_chainman.m_best_invalid) {
31693169
// Reset invalid block marker if it was pointing to one of those.
31703170
m_chainman.m_best_invalid = nullptr;
31713171
}
3172-
m_chainman.m_failed_blocks.erase(it->second);
3172+
m_chainman.m_failed_blocks.erase(&it->second);
31733173
}
31743174
it++;
31753175
}
@@ -3500,7 +3500,7 @@ bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValida
35003500
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
35013501
if (miSelf != m_blockman.m_block_index.end()) {
35023502
// Block header is already known.
3503-
CBlockIndex* pindex = miSelf->second;
3503+
CBlockIndex* pindex = &(miSelf->second);
35043504
if (ppindex)
35053505
*ppindex = pindex;
35063506
if (pindex->nStatus & BLOCK_FAILED_MASK) {
@@ -3522,7 +3522,7 @@ bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValida
35223522
LogPrint(BCLog::VALIDATION, "%s: %s prev block not found\n", __func__, hash.ToString());
35233523
return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
35243524
}
3525-
pindexPrev = (*mi).second;
3525+
pindexPrev = &((*mi).second);
35263526
if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
35273527
LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
35283528
return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
@@ -3988,13 +3988,13 @@ bool CChainState::ReplayBlocks()
39883988
if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
39893989
return error("ReplayBlocks(): reorganization to unknown block requested");
39903990
}
3991-
pindexNew = m_blockman.m_block_index[hashHeads[0]];
3991+
pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
39923992

39933993
if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
39943994
if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
39953995
return error("ReplayBlocks(): reorganization from unknown block requested");
39963996
}
3997-
pindexOld = m_blockman.m_block_index[hashHeads[1]];
3997+
pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
39983998
pindexFork = LastCommonAncestor(pindexOld, pindexNew);
39993999
assert(pindexFork != nullptr);
40004000
}
@@ -4261,8 +4261,8 @@ void CChainState::CheckBlockIndex()
42614261

42624262
// Build forward-pointing map of the entire block tree.
42634263
std::multimap<CBlockIndex*,CBlockIndex*> forward;
4264-
for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
4265-
forward.insert(std::make_pair(entry.second->pprev, entry.second));
4264+
for (std::pair<const uint256, CBlockIndex>& entry : m_blockman.m_block_index) {
4265+
forward.insert(std::make_pair(entry.second.pprev, &entry.second));
42664266
}
42674267

42684268
assert(forward.size() == m_blockman.m_block_index.size());

src/wallet/test/wallet_tests.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,10 +367,10 @@ static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lock
367367
CBlockIndex* block = nullptr;
368368
if (blockTime > 0) {
369369
LOCK(cs_main);
370-
auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
370+
auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
371371
assert(inserted.second);
372372
const uint256& hash = inserted.first->first;
373-
block = inserted.first->second;
373+
block = &inserted.first->second;
374374
block->nTime = blockTime;
375375
block->phashBlock = &hash;
376376
state = TxStateConfirmed{hash, block->nHeight, /*position_in_block=*/0};

0 commit comments

Comments
 (0)