Merge bitcoin/bitcoin#32875: index: handle case where pindex_prev equals chain tip in NextSyncBlock()

db3c25cfae index: add explicit early exit in NextSyncBlock() when the input is the chain tip (Hao Xu)

Pull request description:

  When `pindex_prev` is the chain tip, `NextSyncBlock()` should return `nullptr` (there's no next block to sync). Currently this works, but relies on the fork/reorg path to produce the result: `chain.Next(tip)` returns `nullptr`, falling through to `FindFork(tip)` which returns `tip` itself, then `chain.Next(tip)` returns `nullptr` again.
  Add an explicit early return for this case. This makes `NextSyncBlock()`'s three cases self-documenting:

  1. next block exists on the active chain — return it
  2. at the chain tip — return `nullptr`
  3. on a stale branch — find the fork point and return the block after it

  It also makes the existing comment ("Since block is not in the chain") accurate — the tip is in the chain, so it shouldn't reach that path.

ACKs for top commit:
  optout21:
    crACK db3c25cfae
  furszy:
    ACK db3c25cfae
  stickies-v:
    ACK db3c25cfae

Tree-SHA512: c1633bb3d3ffed2643c8e174c2b2283deaeffd0a06eb3fb2cf03eed097bfdc5cf6fbd7ebdcdb44fd56f712be8004ad46c730a33990fb1fc6cfa629c9b14f8cd9
This commit is contained in:
merge-script
2026-03-30 20:01:40 +08:00

View File

@@ -155,11 +155,15 @@ static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain&
return chain.Genesis();
}
const CBlockIndex* pindex = chain.Next(pindex_prev);
if (pindex) {
if (const auto* pindex{chain.Next(pindex_prev)}) {
return pindex;
}
// If there is no next block, we might be synced
if (pindex_prev == chain.Tip()) {
return nullptr;
}
// Since block is not in the chain, return the next block in the chain AFTER the last common ancestor.
// Caller will be responsible for rewinding back to the common ancestor.
return chain.Next(chain.FindFork(pindex_prev));