Skip to content

Commit 6c23c41

Browse files
committed
refactor: Rewrite AddToBlockIndex with try_emplace
1 parent c05cf7a commit 6c23c41

File tree

1 file changed

+5
-10
lines changed

1 file changed

+5
-10
lines changed

src/node/blockstorage.cpp

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,22 +50,17 @@ CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
5050
{
5151
AssertLockHeld(cs_main);
5252

53-
// Check for duplicate
54-
uint256 hash = block.GetHash();
55-
BlockMap::iterator it = m_block_index.find(hash);
56-
if (it != m_block_index.end()) {
57-
return &it->second;
53+
auto [mi, inserted] = m_block_index.try_emplace(block.GetHash(), block);
54+
if (!inserted) {
55+
return &mi->second;
5856
}
57+
CBlockIndex* pindexNew = &(*mi).second;
5958

60-
// Construct new block index object
61-
CBlockIndex new_index{block};
6259
// We assign the sequence id to blocks only when the full data is available,
6360
// to avoid miners withholding blocks but broadcasting headers, to get a
6461
// competitive advantage.
65-
new_index.nSequenceId = 0;
66-
BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, std::move(new_index))).first;
62+
pindexNew->nSequenceId = 0;
6763

68-
CBlockIndex* pindexNew = &(*mi).second;
6964
pindexNew->phashBlock = &((*mi).first);
7065
BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
7166
if (miPrev != m_block_index.end()) {

0 commit comments

Comments
 (0)