Merge bitcoin/bitcoin#35168: validation: Don't add pruned blocks to m_blocks_unlinked on startup

3f44f9aef7 test: Add coverage for m_blocks_unlinked invariant in LoadBlockIndex (marcofleon)
0e4b0bacec validation: Don't add pruned blocks to m_blocks_unlinked on startup (marcofleon)

Pull request description:

  Fixes https://github.com/bitcoin/bitcoin/issues/35050

  The `m_blocks_unlinked` map keeps track of blocks that have transactions but whose parent (or any ancestor) does not. This happens when a block is received before its parent, or during a reorg, when `FindMostWorkChain()` encounters a block whose ancestors were pruned.

  The bug this PR addresses is a rare interaction of these two cases, which happens on startup when `BlockManager::LoadBlockIndex()` rebuilds `m_blocks_unlinked`. The check there only considers whether a block has transactions, and pruned blocks keep `nTx > 0` but clear `BLOCK_HAVE_DATA`. So if there's a pruned block on a stale fork whose parent has no transactions, that block is added to `m_blocks_unlinked` without having data on disk. This violates an [assertion](ad3f73862b/src/validation.cpp (L5352)) in `CheckBlockIndex()`.

  Get rid of this unintended case by gating on `BLOCK_HAVE_DATA` before adding to `m_blocks_unlinked`.

ACKs for top commit:
  achow101:
    ACK 3f44f9aef7
  sedited:
    Re-ACK 3f44f9aef7
  stratospher:
    ACK 3f44f9a. nice!

Tree-SHA512: 275d0f8588524c01c4e701c8635973cd4a086d31c10d252a498c1ef668bdb3895ba1cae265dbe88f8983ca7ddbe32247824753c7c1f49e59c8bce0df377b784c
This commit is contained in:
Ava Chow
2026-06-10 11:30:50 -07:00
3 changed files with 43 additions and 1 deletions

View File

@@ -486,7 +486,9 @@ bool BlockManager::LoadBlockIndex(const std::optional<uint256>& snapshot_blockha
pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
} else {
pindex->m_chain_tx_count = 0;
m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
if (pindex->nStatus & BLOCK_HAVE_DATA) {
m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
}
}
} else {
pindex->m_chain_tx_count = pindex->nTx;