0
0
Fork 0
mirror of https://github.com/bitcoin/bitcoin.git synced 2025-02-08 10:31:50 -05:00

refactor: Rewrite AddToBlockIndex with try_emplace

This commit is contained in:
Carl Dong 2022-01-19 13:55:40 -05:00
parent c05cf7aa1e
commit 6c23c41561

View file

@ -50,22 +50,17 @@ CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
{ {
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
// Check for duplicate auto [mi, inserted] = m_block_index.try_emplace(block.GetHash(), block);
uint256 hash = block.GetHash(); if (!inserted) {
BlockMap::iterator it = m_block_index.find(hash); return &mi->second;
if (it != m_block_index.end()) {
return &it->second;
} }
CBlockIndex* pindexNew = &(*mi).second;
// Construct new block index object
CBlockIndex new_index{block};
// We assign the sequence id to blocks only when the full data is available, // We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a // to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage. // competitive advantage.
new_index.nSequenceId = 0; pindexNew->nSequenceId = 0;
BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, std::move(new_index))).first;
CBlockIndex* pindexNew = &(*mi).second;
pindexNew->phashBlock = &((*mi).first); pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock); BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
if (miPrev != m_block_index.end()) { if (miPrev != m_block_index.end()) {