validation: Leave some pruned blocks in `m_blocks_unlinked`, fix another `nSequenceId` issue #36149

pull mzumsande wants to merge 5 commits into bitcoin:master from mzumsande:202609_fix_cbi_pruning_unlinked changing 6 files +106 −40
  1. mzumsande commented at 2:33 PM on September 2, 2026: contributor

    m_blocks_unlinked serves two purposes:

    1. finding blocks to setBlockIndexCandidates once their parents are received
    2. setting m_chain_tx_count once the parents are received

    In case the parent block of a previously pruned block is received, 2. is currently not being done, because pruning removed the entries from m_blocks_unlinked. This can result in CheckBlockIndex failures (#31512, #36021) and incorrect rpc results, plus we are in a temporarily inconsistent state (m_chain_tx_count is currently not set, but would get set if we restarted).

    This scenario is unlikely to happen during normal node operation unless there are huge reorgs, but it can happen, for example, in getblockfrompeer scenarios. Fix this by leaving pruned blocks in m_blocks_unlinked that don't have m_chain_tx_count set, and also adding them on restart.

    This was one of two reasons, the fuzz target block_index_tree couldn't cover pruning of blocks not in the main chain.

    The other one is similar to #34521 and #35070 - if we receive a block a second time (after pruning), we could change nSequenceId while the block is in setBlockIndexCandidates - fix this by attempting to remove it from the set before re-adding it.

    After the two issues are fixed, the restriction from block_index_tree fuzz target is removed.

    Fixes #36021 Fixes #31512

  2. DrahtBot added the label Validation on Sep 2, 2026
  3. DrahtBot commented at 2:33 PM on September 2, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

    See the guideline and AI policy for information on the review process.

    Type Reviewers
    Concept ACK jeanpablojp, enochaz, l0rinc
    Stale ACK marcofleon

    If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36990 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36990.svg"></sub> (test: replace hard-coded RPC error codes by l0rinc)
    • #36621 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36621.svg"></sub> (node: batch block file pruning in a single pass over block index by mutatrum)

    If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  4. mzumsande force-pushed on Sep 2, 2026
  5. DrahtBot added the label CI failed on Sep 2, 2026
  6. DrahtBot removed the label CI failed on Sep 2, 2026
  7. l0rinc commented at 5:29 PM on September 2, 2026: contributor

    Concept ACK, thanks for fixing it. I will try to review it a bit later.

  8. mzumsande marked this as ready for review on Sep 2, 2026
  9. jeanpablojp commented at 12:32 AM on September 8, 2026: contributor

    Concept ACK

    Taking out the setBlockIndexCandidates erase, the extended block_index_tree target breaks on an input that is already in the qa-assets corpus.

  10. in src/node/blockstorage.h:355 in 40a31d97ab
     350 | @@ -351,7 +351,16 @@ class BlockManager
     351 |      std::vector<CBlockIndex*> GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     352 |  
     353 |      /**
     354 | -     * All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
     355 | +     * Pairs A->B, where the transactions of B have been received at some point,
     356 | +     * but B is not a candidate for connection, because for A or one of its predecessors
    


    jeanpablojp commented at 12:32 AM on September 8, 2026:

    nit (feel free to ignore): predecessors appears only here in src/, and ancestors sounds to be the preference, including the comment this line replaces.

         * but B is not a candidate for connection, because for A or one of its ancestors
    

    mzumsande commented at 5:31 PM on November 2, 2026:

    done

  11. in test/functional/feature_prune_stale_fork.py:64 in 40a31d97ab outdated
      59 | +        node.submitblock(side_parent.serialize().hex())
      60 | +        assert_equal(node.getblockheader(side_parent.hash_hex)["nTx"], 1)
      61 | +        # The child's block data is still gone, but its transactions were received at some
      62 | +        # point, so the grandchild is no longer waiting for transactions the node has.
      63 | +        assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, side_child.hash_hex)
      64 | +        assert_equal(self.tip_status(node, side_grandchild.hash_hex), "valid-headers")
    


    jeanpablojp commented at 12:32 AM on September 8, 2026:

    Pre-existing, so feel free to ignore. This assertion is what made me look.

    The getchaintips help calls valid-headers "All blocks are available for this branch", but the only availability test behind the status is HaveNumChainTxs(), whose own doc says it "Does not imply the transactions are still stored on disk". I get the same on master with a stale fork received in full and then pruned, where getblock on those blocks fails with "Block not available (pruned data)".

    Would "received at some point" be closer than "are available" there?


    mzumsande commented at 5:34 PM on November 2, 2026:

    Makes sense - since there were two other spots in the vicinity that had a similar issue I added a separate commit that changes these.

  12. in test/functional/feature_prune_stale_fork.py:48 in 5d5af40fcb outdated
      47 | @@ -34,6 +48,26 @@ def run_test(self):
      48 |          self.restart_node(0)
    


    marcofleon commented at 11:01 AM on September 9, 2026:

    We could also test submitting a missing parent of a pruned child before restarting, as in #36021. This test currently passes with the old behavior of removing a pruned block from m_blocks_unlinked, because it gets added back on start up. Could add a separate 2-block fork to cover the no restart case?


    mzumsande commented at 5:40 PM on November 2, 2026:

    I added a generate() call before the restart, so that CheckBlockIndex is invoked. I think that should cover the situation, too.


    l0rinc commented at 9:51 AM on November 18, 2026:

    Could we submit the parent before restarting and check that the pruned child gets its transaction count? The extra generate() in the functional test already checks that the child stays in m_blocks_unlinked.

    <details> <summary>Check linking before restart</summary>

    diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
    index e150f317f4..64aac97480 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -4,17 +4,21 @@
     //
     #include <chainparams.h>
     #include <consensus/validation.h>
    +#include <flatfile.h>
     #include <kernel/disconnected_transactions.h>
     #include <node/block_template_manager.h>
    +#include <node/blockstorage.h>
     #include <node/chainstatemanager_args.h>
     #include <node/kernel_notifications.h>
     #include <node/utxo_snapshot.h>
    +#include <primitives/block.h>
     #include <random.h>
     #include <rpc/blockchain.h>
     #include <sync.h>
     #include <test/util/chainstate.h>
     #include <test/util/common.h>
     #include <test/util/logging.h>
    +#include <test/util/mining.h>
     #include <test/util/random.h>
     #include <test/util/setup_common.h>
     #include <test/util/validation.h>
    @@ -27,6 +31,7 @@
     
     #include <tinyformat.h>
     
    +#include <map>
     #include <vector>
     
     #include <boost/test/unit_test.hpp>
    @@ -631,6 +636,29 @@ BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
         BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
     }
     
    +BOOST_FIXTURE_TEST_CASE(pruned_unlinked_retention, RegTestingSetup)
    +{
    +    auto& chainman{*m_node.chainman};
    +    auto& blockman{chainman.m_blockman};
    +    LOCK(cs_main);
    +    const auto blocks{CreateBlockChain(/*total_height=*/2, chainman.GetParams())};
    +    auto* parent{blockman.AddToBlockIndex(*blocks[0], chainman.m_best_header)};
    +    auto* child{blockman.AddToBlockIndex(*blocks[1], chainman.m_best_header)};
    +
    +    const FlatFilePos pos{/*nFileIn=*/1, /*nPosIn=*/0};
    +    blockman.UpdateBlockInfo(*blocks[1], child->nHeight, pos);
    +    chainman.ReceivedBlockTransactions(*blocks[1], child, pos);
    +    blockman.m_have_pruned = true;
    +    blockman.PruneOneBlockFile(pos.nFile);
    +    BOOST_CHECK(blockman.m_blocks_unlinked.contains(parent));
    +
    +    chainman.CheckBlockIndex();
    +
    +    chainman.ReceivedBlockTransactions(*blocks[0], parent, /*pos=*/{});
    +    BOOST_CHECK(child->HaveNumChainTxs());
    +    BOOST_CHECK(blockman.m_blocks_unlinked.empty());
    +}
    +
     //! Verify that ReconsiderBlock clears failure flags for the target block, its ancestors, and descendants,
     //! but not for sibling forks that diverge from a shared ancestor.
     BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
    

    </details>

  13. marcofleon commented at 11:24 AM on September 9, 2026: contributor

    ACK 40a31d97ab118cb030af7d560aedbade3ae4cd36

    The main fix in 7c7ccc9cc0939e00f060b49ec476a761f2c1c85e looks correct to me. Ran the fuzz test for a while, no issues. Commit 80477ba97820485c8371f71d0b46b7bb23325cf2 fixes previously existing (potential) UB in setBlockIndexCandidates that is now caught by the fuzz target. Nice.

    In the PR description,

    Fix this by leaving pruned blocks in m_chain_tx_count

    should be m_blocks_unlinked instead.

    Also, left a non-blocking comment on the functional test.

    Thanks for fixing this cleanly!

  14. DrahtBot requested review from jeanpablojp on Sep 9, 2026
  15. DrahtBot requested review from l0rinc on Sep 9, 2026
  16. in src/node/blockstorage.cpp:284 in 7c7ccc9cc0
     291 | -                range.first++;
     292 | -                if (_it->second == pindex) {
     293 | -                    m_blocks_unlinked.erase(_it);
     294 | -                }
     295 | -            }
     296 | +            // Note that the block is deliberately left in m_blocks_unlinked:
    


    mzumsande commented at 9:49 PM on September 9, 2026:

    A slightly different approach here (suggested by @l0rinc) would be to remove conditionally on m_chain_tx being set. I will explore this next week.

  17. mzumsande commented at 9:50 PM on September 9, 2026: contributor

    Thanks for the reviews! I will address the comments (and also most likely rework the PR a little bit, see other comment) next week, putting into draft until then.

  18. mzumsande marked this as a draft on Sep 9, 2026
  19. validation: keep pruned blocks in m_blocks_unlinked
    m_blocks_unlinked serves two purposes:
    1. finding blocks to SetBlockIndexCandidates once their parents are
       received
    2. Setting m_chain_tx_count once the parents are received
    
    In case that a parent of a pruned block is received,
    2. is currently not being done, because pruning removed the entries.
    This can result in CheckBlockIndex failures, and an inconsistent state
    (because in case of a restart, m_chain_tx would be set).
    This is unlikely to happen during normal node operation unless
    there are huge reorgs, but it can happen, for example, in getblockfrompeer scenarios.
    
    Fix this by keeping pruned blocks in m_blocks_unlinked as long as they
    don't have their m_chain_tx_count yet, and also removing the
    BLOCK_HAVE_DATA requirement during startup. Also don't add pruned blocks
    to setBlockIndexCandidates when linking them, since they can't be
    connected before being downloaded again.
    
    Co-authored-by: Lőrinc <pap.lorinc@gmail.com>
    12208a02ff
  20. test: add functional test for parents of pruned blocks
    This test would lead to a CheckBlockIndex assertion fail without
    the changes of the previous commit.
    0522e7beba
  21. validation: don't change nSequenceId of a block that is a chain candidate
    nSequenceId is one of the sort keys of setBlockIndexCandidates, so changing it
    for a block that currently is in one of these sets corrupts their ordering,
    after which lookups for other entries can fail.
    
    This is also necessary for the block_index_tree fuzz test extension in the
    following commit, which would otherwise trip on this.
    92c02d4221
  22. fuzz: allow to prune out-of-chain blocks in block_index_tree
    After the issues with m_blocks_unlinked and
    setBlockIndexCandidates have been resolved in previous commits,
    the previous restriction to the fuzz test does no longer apply,
    and we can also prune out-of-chain blocks.
    07ee4b98c6
  23. doc: clarify getchaintips status descriptions
    Whether a branch is "headers-only" or "valid-headers" depends on whether
    the transactions of all its blocks have been received at some point, not
    on whether the block data is currently available - blocks may have been
    pruned since.
    532ffaa26d
  24. mzumsande force-pushed on Nov 2, 2026
  25. mzumsande commented at 5:59 PM on November 2, 2026: contributor

    40a31d9 to 532ffaa: In addition to addressing review comments, I changed the approach of the first commit, taking some things of a branch from @l0rinc (thanks, added you as coauthor).

    In the previous PR branch, pruning never removed anything from m_blocks_unlinked. Now, a pruned block is only kept there if it doesn't have its m_chain_tx_count yet, i.e. if it is still waiting for an ancestor's transactions. Blocks that are already linked are removed on pruning, as on master. Also, blocks without data are no longer added to setBlockIndexCandidates when they get linked.

    The approaches are very similar, the main functional difference is for the (admittedly far-fetched) case that a block is pruned, downloaded again (e.g. via getblockfrompeer) and then pruned again. Another advantage is that we can now have slightly stricter checks in CheckBlockIndex().

  26. mzumsande marked this as ready for review on Nov 2, 2026
  27. mzumsande renamed this:
    validation: Leave pruned blocks in `m_blocks_unlinked`, fix another `nSequenceId` issue
    validation: Leave some pruned blocks in `m_blocks_unlinked`, fix another `nSequenceId` issue
    on Nov 2, 2026
  28. sedited referenced this in commit 92690e11fe on Nov 9, 2026
  29. sedited referenced this in commit 80de8c2647 on Nov 9, 2026
  30. sedited referenced this in commit 9adfc7a8b2 on Nov 9, 2026
  31. sedited referenced this in commit 14224b5e60 on Nov 10, 2026
  32. sedited referenced this in commit 165c3ef4ba on Nov 10, 2026
  33. sedited referenced this in commit 765d80aa85 on Nov 11, 2026
  34. sedited referenced this in commit 0173cd88d9 on Nov 11, 2026
  35. sedited referenced this in commit 3e5494bd63 on Nov 11, 2026
  36. sedited referenced this in commit e1da1d1a1f on Nov 11, 2026
  37. sedited referenced this in commit 4dfbb745de on Nov 12, 2026
  38. sedited referenced this in commit 0e95c753ee on Nov 12, 2026
  39. sedited referenced this in commit c03b1170ae on Nov 12, 2026
  40. sedited referenced this in commit cf4d0fa738 on Nov 12, 2026
  41. sedited referenced this in commit 6e063cf69d on Nov 13, 2026
  42. sedited referenced this in commit 89376e4665 on Nov 13, 2026
  43. sedited referenced this in commit e8b36f4180 on Nov 14, 2026
  44. sedited referenced this in commit c2b225cbd8 on Nov 15, 2026
  45. sedited referenced this in commit 8ad89ab050 on Nov 16, 2026
  46. sedited referenced this in commit 81c7f3f07c on Nov 16, 2026
  47. sedited referenced this in commit 08d9fa1272 on Nov 16, 2026
  48. sedited referenced this in commit df77086373 on Nov 16, 2026
  49. sedited referenced this in commit f38cd35b77 on Nov 16, 2026
  50. in src/node/blockstorage.cpp:262 in 12208a02ff
     258 | @@ -259,14 +259,29 @@ void BlockManager::AddUnlinkedBlock(CBlockIndex* block)
     259 |  {
     260 |      AssertLockHeld(cs_main);
     261 |      Assume(block != nullptr);
     262 | -    Assume(block->nStatus & BLOCK_HAVE_DATA);
     263 | +    Assume(block->pprev != nullptr);
    


    enochaz commented at 10:39 AM on November 17, 2026:

    In commit https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d: validation: keep pruned blocks in m_blocks_unlinked

    This still checks for pprev here:

    https://github.com/enochaz/bitcoin/blob/532ffaa26d0557c149d7efee544f163fdcf84006/src/validation.cpp#L3840-L3843

    But the else branch already guarantees pprev is non-null, and AddUnlinkedBlock now checks it as a precondition. I think it can be removed here. Leaving it is fine, but it feels redundant and might obscure the BLOCK_VALID_TREE condition for someone reading the code.

    index 35bcb640a1..c3714add58 100644
    --- a/src/validation.cpp
    +++ b/src/validation.cpp
    @@ -3838,7 +3838,7 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd
                 }
             }
         } else {
    -        if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
    +        if (pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
                 m_blockman.AddUnlinkedBlock(pindexNew);
             }
         }
    
  51. in src/validation.cpp:5380 in 12208a02ff
    5376 | @@ -5446,11 +5377,15 @@ void ChainstateManager::CheckBlockIndex() const
    5377 |                  foundInUnlinked = true;
    5378 |              }
    5379 |          }
    5380 | -        if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
    5381 | -            // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
    5382 | +        if (foundInUnlinked) assert(pindex->nTx > 0); // Only blocks whose transactions were received belong in m_blocks_unlinked
    


    enochaz commented at 10:57 AM on November 17, 2026:

    In commit 12208a02ff5f795369fb2ab28884dc37b2db245d: validation: keep pruned blocks in m_blocks_unlinked

    This confused me a bit. I’d prefer these assertions grouped together, since both check whether a block can be in m_blocks_unlinked.

    index 35bcb640a1..a516a8956d 100644
    --- a/src/validation.cpp
    +++ b/src/validation.cpp
    @@ -3838,7 +3838,7 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd
                 }
             }
         } else {
    -        if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
    +        if (indexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
                 m_blockman.AddUnlinkedBlock(pindexNew);
             }
         }
    @@ -5384,15 +5384,17 @@ void ChainstateManager::CheckBlockIndex() const
                     foundInUnlinked = true;
                 }
             }
    -        if (foundInUnlinked) assert(pindex->nTx > 0); // Only blocks whose transactions were received belong in m_blocks_unlinked
    +        if (foundInUnlinked) {
    +            assert(pindex->nTx > 0); // Only blocks whose transactions were received belong in m_blocks_unlinked
    +            // A pruned block stays unlinked only while its chain transaction count is unknown.
    +            assert((pindex->nStatus & BLOCK_HAVE_DATA) || !pindex->HaveNumChainTxs());
    +        }
             if (pindex->pprev && pindex->nTx > 0 && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
                 // If the transactions of this block were received, some parent was never received, and it has no
                 // invalid parents, it must be in m_blocks_unlinked. Note that this holds whether or not the block
                 // data is still available, because pruning doesn't remove entries that lack m_chain_tx_count.
                 assert(foundInUnlinked);
             }
    -        // Can't be in m_blocks_unlinked if we don't HAVE_DATA, unless it still lacks m_chain_tx_count.
    -        if (!(pindex->nStatus & BLOCK_HAVE_DATA) && pindex->HaveNumChainTxs()) assert(!foundInUnlinked);
             if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
             if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
                 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
    
  52. in src/validation.cpp:3822 in 92c02d4221
    3813 | @@ -3814,6 +3814,13 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd
    3814 |                     pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
    3815 |              }
    3816 |              pindex->m_chain_tx_count = prev_tx_sum(*pindex);
    3817 | +            // nSequenceId is one of the sort keys of setBlockIndexCandidates, so pindex must
    3818 | +            // not be in any of them while it is changed - doing so would corrupt their
    3819 | +            // ordering. pindex can be a candidate here if we receive the block data of a block
    3820 | +            // that already is one, which happens when it is downloaded again after being pruned.
    3821 | +            for (const auto& c : m_chainstates) {
    3822 | +                c->setBlockIndexCandidates.erase(pindex);
    


    enochaz commented at 11:45 AM on November 17, 2026:

    In commit https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d: validation: don't change nSequenceId of a block that is a chain candidate

    Could we have a deterministic regression test for this, something like the unit test below? This would let us check that redownloading a block already in setBlockIndexCandidates preserves the set’s ordering, rather than relying on the fuzzer to hit the same sequence again.

    index e150f317f4..112ea1fe0b 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -4,11 +4,13 @@
     //
     #include <chainparams.h>
     #include <consensus/validation.h>
    +#include <flatfile.h>
     #include <kernel/disconnected_transactions.h>
     #include <node/block_template_manager.h>
     #include <node/chainstatemanager_args.h>
     #include <node/kernel_notifications.h>
     #include <node/utxo_snapshot.h>
    +#include <primitives/block.h>
     #include <random.h>
     #include <rpc/blockchain.h>
     #include <sync.h>
    @@ -27,6 +29,7 @@
    
     #include <tinyformat.h>
    
    +#include <algorithm>
     #include <vector>
    
     #include <boost/test/unit_test.hpp>
    @@ -37,6 +40,38 @@ using node::SnapshotMetadata;
    
     BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
    
    +BOOST_FIXTURE_TEST_CASE(redownload_candidate_preserves_order, TestChain100Setup)
    +{
    +    auto& chainman = *Assert(m_node.chainman);
    +    LOCK(::cs_main);
    +    auto& candidates = chainman.ActiveChainstate().setBlockIndexCandidates;
    +    CBlockIndex* tip = chainman.ActiveChain().Tip();
    +
    +    CBlockHeader header = tip->GetBlockHeader();
    +    header.hashPrevBlock = tip->GetBlockHash();
    +    header.nTime = tip->nTime + 1;
    +    CBlock block;
    +    block.vtx.resize(1);
    +
    +    header.nNonce = 1;
    +    CBlockIndex* first = chainman.m_blockman.AddToBlockIndex(header, chainman.m_best_header);
    +    chainman.ReceivedBlockTransactions(block, first, FlatFilePos{0, 1});
    +    header.nNonce = 2;
    +    CBlockIndex* second = chainman.m_blockman.AddToBlockIndex(header, chainman.m_best_header);
    +    chainman.ReceivedBlockTransactions(block, second, FlatFilePos{0, 2});
    +    BOOST_REQUIRE(candidates.contains(first));
    +    BOOST_REQUIRE(candidates.contains(second));
    +    BOOST_REQUIRE(first->nSequenceId < second->nSequenceId);
    +    const size_t candidate_count = candidates.size();
    +
    +    // Redownload the earlier candidate, changing its sequence ID relative to the other one.
    +    first->nStatus &= ~BLOCK_HAVE_DATA;
    +    chainman.ReceivedBlockTransactions(block, first, FlatFilePos{0, 3});
    +
    +    BOOST_CHECK_EQUAL(candidates.size(), candidate_count);
    +    BOOST_CHECK(std::is_sorted(candidates.begin(), candidates.end(), candidates.value_comp()));
    +}
    +
    

    l0rinc commented at 12:03 PM on November 18, 2026:

    Alternatively we could reuse the existing fork test - the erase in the next commit will let us flip the last check.

    <details> <summary>Show the ordering before the fix</summary>

    diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
    index e150f317f4..19a484ff70 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -4,11 +4,14 @@
     //
     #include <chainparams.h>
     #include <consensus/validation.h>
    +#include <flatfile.h>
     #include <kernel/disconnected_transactions.h>
     #include <node/block_template_manager.h>
    +#include <node/blockstorage.h>
     #include <node/chainstatemanager_args.h>
     #include <node/kernel_notifications.h>
     #include <node/utxo_snapshot.h>
    +#include <primitives/block.h>
     #include <random.h>
     #include <rpc/blockchain.h>
     #include <sync.h>
    @@ -27,6 +30,7 @@
     
     #include <tinyformat.h>
     
    +#include <algorithm>
     #include <vector>
     
     #include <boost/test/unit_test.hpp>
    @@ -717,6 +721,25 @@ BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
             BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
             BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
         }
    +
    +    // Let both branches compete, then redownload the older candidate.
    +    BOOST_REQUIRE(chainstate.InvalidateBlock(state, block99));
    +    LOCK(chainman.GetMutex());
    +    chainstate.ResetBlockFailureFlags(block98);
    +    chainman.RecalculateBestHeader();
    +    auto& blockman{chainman.m_blockman};
    +    CBlock block;
    +    BOOST_REQUIRE(blockman.ReadBlock(block, *block100));
    +    const auto pos{block100->GetBlockPos()};
    +    BOOST_REQUIRE_LT(block100->nSequenceId, fork_block100->nSequenceId);
    +    blockman.m_have_pruned = true;
    +    block100->nStatus &= ~BLOCK_HAVE_MASK; // Simulate pruning this block
    +    auto& candidates{chainstate.setBlockIndexCandidates};
    +    BOOST_REQUIRE(candidates.contains(block100));
    +    BOOST_REQUIRE(candidates.contains(fork_block100));
    +    chainman.ReceivedBlockTransactions(block, block100, pos);
    +    BOOST_CHECK(std::ranges::find(candidates, block100) != candidates.end());
    +    BOOST_CHECK(!std::ranges::is_sorted(candidates, candidates.value_comp())); // TODO: Redownloading must preserve candidate ordering
     }
     
     //! Ensure that snapshot chainstate can be loaded when found on disk after a
    

    </details>


    enochaz commented at 1:57 PM on November 18, 2026:

    That works as well, reusing the fork test gives us a deterministic regression case. Once the last check is flipped to is_sorted, could we also check that block100 is still a candidate after the redownload?

    BOOST_CHECK(candidates.contains(block100));

    Since the fix now erases block100 before readding it, is_sorted alone wouldn't notice if a future change dropped it from the set.

  53. enochaz commented at 11:54 AM on November 17, 2026: contributor

    Concept ACK

    As I understand it, m_blocks_unlinked is used both to reconsider blocks for setBlockIndexCandidates when a missing ancestor arrives and to set m_chain_tx_count for their descendants. If B's transactions were received but an ancestor’s were not, pruning B clears BLOCK_HAVE_DATA without clearing nTx.

    Removing B from the map at that point means that when the ancestor arrives, we no longer reach B or any blocks waiting behind it. This seems unlikely in normal sync, but the stale fork case shows it can happen.

    So I think it makes sense to keep B in the map while its m_chain_tx_count is still unknown, and to reconstruct that state on restart. B still shouldn’t become a chain candidate while its block data is missing.

    The nSequenceId change also seems justified since it affects the candidate set’s ordering, though that feels like a separate implementation detail.

    Left some nits and suggestions below

  54. sedited referenced this in commit 78ef6adfc9 on Nov 17, 2026
  55. sedited referenced this in commit e090cd9d37 on Nov 17, 2026
  56. sedited referenced this in commit 5269dc8b54 on Nov 17, 2026
  57. sedited referenced this in commit 8b59df084f on Nov 18, 2026
  58. in src/node/blockstorage.cpp:271 in 12208a02ff outdated
     267 |          if (it->second == block) return;  // don't insert duplicates
     268 |      }
     269 |      m_blocks_unlinked.emplace(block->pprev, block);
     270 |  }
     271 |  
     272 | +void BlockManager::RemoveUnlinkedBlock(CBlockIndex* block)
    


    l0rinc commented at 8:22 AM on November 18, 2026:

    12208a0 validation: keep pruned blocks in m_blocks_unlinked:

    We could pull the metadata updates and the conditional RemoveUnlinkedBlock call into one PruneBlock helper, so PruneOneBlockFile and the fuzz test share the same pruning logic. The suggestion below squashes BLOCK_HAVE_DATA and BLOCK_HAVE_UNDO into BLOCK_HAVE_MASK and marks pruned entries dirty in the fuzzer (which won't have any effect there as far as I can tell, but should be more realistic regardless).

    <details> <summary>Extract PruneBlock and reuse it in the fuzz test</summary>

    diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
    index fd95214abb..06f7a855b5 100644
    --- a/src/node/blockstorage.cpp
    +++ b/src/node/blockstorage.cpp
    @@ -268,14 +268,24 @@ void BlockManager::AddUnlinkedBlock(CBlockIndex* block)
         m_blocks_unlinked.emplace(block->pprev, block);
     }
     
    -void BlockManager::RemoveUnlinkedBlock(CBlockIndex* block)
    +void BlockManager::PruneBlock(CBlockIndex& block)
     {
         AssertLockHeld(cs_main);
    -    Assume(block != nullptr);
    -    if (block->pprev == nullptr) return; // genesis is never in m_blocks_unlinked, but can be pruned
    -    auto range = m_blocks_unlinked.equal_range(block->pprev);
    -    for (auto it = range.first; it != range.second; ++it) {
    -        if (it->second == block) {
    +    block.nStatus &= ~BLOCK_HAVE_MASK;
    +    block.nFile = 0;
    +    block.nDataPos = 0;
    +    block.nUndoPos = 0;
    +    m_dirty_blockindex.insert(&block);
    +
    +    // A block still lacking m_chain_tx_count stays in m_blocks_unlinked so a missing ancestor can still supply it
    +    if (!block.HaveNumChainTxs()) return;
    +    // Prune any other block from m_blocks_unlinked -- it would have
    +    // to be downloaded again in order to consider its chain, at which
    +    // point it would be considered as a candidate for
    +    // m_blocks_unlinked or setBlockIndexCandidates.
    +    auto range{m_blocks_unlinked.equal_range(block.pprev)};
    +    for (auto it{range.first}; it != range.second; ++it) {
    +        if (it->second == &block) {
                 m_blocks_unlinked.erase(it);
                 return; // AddUnlinkedBlock doesn't insert duplicates
             }
    @@ -289,24 +299,7 @@ void BlockManager::PruneOneBlockFile(const int fileNumber)
         for (auto& entry : m_block_index) {
             CBlockIndex* pindex = &entry.second;
             if (pindex->nFile == fileNumber) {
    -            pindex->nStatus &= ~BLOCK_HAVE_DATA;
    -            pindex->nStatus &= ~BLOCK_HAVE_UNDO;
    -            pindex->nFile = 0;
    -            pindex->nDataPos = 0;
    -            pindex->nUndoPos = 0;
    -            m_dirty_blockindex.insert(pindex);
    -
    -            // Prune from m_blocks_unlinked only if the block already has its
    -            // m_chain_tx_count: it would have to be downloaded again in order
    -            // to consider its chain, at which point it would be considered as
    -            // a candidate for m_blocks_unlinked or setBlockIndexCandidates.
    -            // A block still lacking m_chain_tx_count is deliberately left in
    -            // there: otherwise, if a missing ancestor arrives,
    -            // ReceivedBlockTransactions() would no longer find it and never
    -            // compute its m_chain_tx_count.
    -            if (pindex->HaveNumChainTxs()) {
    -                RemoveUnlinkedBlock(pindex);
    -            }
    +            PruneBlock(*pindex);
             }
         }
     
    diff --git a/src/node/blockstorage.h b/src/node/blockstorage.h
    index 55ac2c8f64..43793b17dd 100644
    --- a/src/node/blockstorage.h
    +++ b/src/node/blockstorage.h
    @@ -364,7 +364,6 @@ public:
          */
         std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
         void AddUnlinkedBlock(CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    -    void RemoveUnlinkedBlock(CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     
         std::unique_ptr<BlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
     
    @@ -383,6 +382,9 @@ public:
         /** Create a new block index entry for a given block hash */
         CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     
    +    //! Mark one block as pruned, without updating its block file info (see PruneOneBlockFile)
    +    void PruneBlock(CBlockIndex& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    +
         //! Mark one block file as pruned (modify associated database entries)
         void PruneOneBlockFile(int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     
    diff --git a/src/test/fuzz/block_index_tree.cpp b/src/test/fuzz/block_index_tree.cpp
    index e0d3a71c0b..c6b042bbba 100644
    --- a/src/test/fuzz/block_index_tree.cpp
    +++ b/src/test/fuzz/block_index_tree.cpp
    @@ -156,14 +156,7 @@ FUZZ_TARGET(block_index_tree, .init = initialize_block_index_tree)
                     CBlockIndex* prune_block{PickValue(fuzzed_data_provider, blocks)};
                     if (prune_block != chainman.ActiveChain().Tip() && (prune_block->nStatus & BLOCK_HAVE_DATA)) {
                         blockman.m_have_pruned = true;
    -                    prune_block->nStatus &= ~BLOCK_HAVE_DATA;
    -                    prune_block->nStatus &= ~BLOCK_HAVE_UNDO;
    -                    prune_block->nFile = 0;
    -                    prune_block->nDataPos = 0;
    -                    prune_block->nUndoPos = 0;
    -                    if (prune_block->HaveNumChainTxs()) {
    -                        blockman.RemoveUnlinkedBlock(prune_block);
    -                    }
    +                    blockman.PruneBlock(*prune_block);
                         pruned_blocks.push_back(prune_block);
                     }
                 },
    

    </details>

  59. in src/validation.cpp:3817 in 92c02d4221 outdated
    3813 | @@ -3814,9 +3814,20 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd
    3814 |                     pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
    3815 |              }
    3816 |              pindex->m_chain_tx_count = prev_tx_sum(*pindex);
    3817 | -            pindex->nSequenceId = nBlockSequenceId++;
    3818 | +            // nSequenceId is one of the sort keys of setBlockIndexCandidates, so pindex must
    


    l0rinc commented at 8:24 AM on November 18, 2026:

    92c02d4 validation: don't change nSequenceId of a block that is a chain candidate:

    The erase here also makes the old comment above AddUnlinkedBlock in FindMostWorkChain obsolete. If a duplicate were to make ReceivedBlockTransactions visit the same block twice, the erase would still run before each sequence ID change. I'd drop that explanation (but I hate verbose comments in general, so maybe an update would be more approriate :p).

    <details> <summary>Drop the obsolete duplicate-entry rationale</summary>

    diff --git a/src/validation.cpp b/src/validation.cpp
    index 08c20aaadb..4d4976c271 100644
    --- a/src/validation.cpp
    +++ b/src/validation.cpp
    @@ -3233,10 +3233,6 @@ CBlockIndex* Chainstate::FindMostWorkChain()
                         // then add back to m_blocks_unlinked, so that if the block arrives in the future
                         // we can try adding to setBlockIndexCandidates again.
                         if (fMissingData && !fFailedChain) {
    -                        // Avoid duplicate entries in m_blocks_unlinked. If the same entry is
    -                        // processed twice in ReceivedBlockTransactions(), it may be re-added to
    -                        // setBlockIndexCandidates with a modified nSequenceId, breaking ordering
    -                        // guarantees and leading to undefined behavior.
                             m_blockman.AddUnlinkedBlock(pindexFailed);
                         }
                         setBlockIndexCandidates.erase(pindexFailed);
    

    </details>

  60. in src/validation.cpp:3820 in 12208a02ff outdated
    3814 | @@ -3815,8 +3815,12 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd
    3815 |              }
    3816 |              pindex->m_chain_tx_count = prev_tx_sum(*pindex);
    3817 |              pindex->nSequenceId = nBlockSequenceId++;
    3818 | -            for (const auto& c : m_chainstates) {
    3819 | -                c->TryAddBlockIndexCandidate(pindex);
    3820 | +            // A descendant taken from m_blocks_unlinked may have been pruned,
    3821 | +            // in which case it can't be a candidate until it is downloaded again.
    3822 | +            if (pindex->nStatus & BLOCK_HAVE_DATA) {
    


    l0rinc commented at 12:05 PM on November 18, 2026:

    12208a0 validation: keep pruned blocks in m_blocks_unlinked:

    We could add a check that shows what happens before the BLOCK_HAVE_DATA guard here: the child also enters the candidate set.

    <details> <summary>Show candidate membership before the data check</summary>

    diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
    index c0259bc7e1..e030825e84 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -658,6 +658,7 @@ BOOST_FIXTURE_TEST_CASE(pruned_unlinked_retention, RegTestingSetup)
         chainman.ReceivedBlockTransactions(*blocks[0], parent, /*pos=*/{});
         BOOST_CHECK(child->HaveNumChainTxs());
         BOOST_CHECK(blockman.m_blocks_unlinked.empty());
    +    BOOST_CHECK(chainman.ActiveChainstate().setBlockIndexCandidates.contains(child)); // TODO: Leave the pruned child out of the candidate set
     }
     
     //! Verify that ReconsiderBlock clears failure flags for the target block, its ancestors, and descendants,
    

    </details>

  61. in src/node/blockstorage.cpp:263 in 12208a02ff outdated
     258 | @@ -259,14 +259,29 @@ void BlockManager::AddUnlinkedBlock(CBlockIndex* block)
     259 |  {
     260 |      AssertLockHeld(cs_main);
     261 |      Assume(block != nullptr);
     262 | -    Assume(block->nStatus & BLOCK_HAVE_DATA);
     263 | +    Assume(block->pprev != nullptr);
     264 | +    Assume(block->nTx > 0); // Not BLOCK_HAVE_DATA: the data of the block may have been pruned
    


    l0rinc commented at 12:21 PM on November 18, 2026:

    12208a0 validation: keep pruned blocks in m_blocks_unlinked:

    A lot is happening here, could we split this part into three commits?

    1. Let AddUnlinkedBlock accept pruned blocks with a parent and received transactions.
    2. Rebuild their waiting entries in LoadBlockIndex.
    3. Have CheckBlockIndex require those entries even after pruning.
  62. in src/node/blockstorage.cpp:515 in 12208a02ff outdated
     511 | @@ -498,9 +512,7 @@ bool BlockManager::LoadBlockIndex(const std::optional<uint256>& snapshot_blockha
     512 |                      pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
     513 |                  } else {
     514 |                      pindex->m_chain_tx_count = 0;
     515 | -                    if (pindex->nStatus & BLOCK_HAVE_DATA) {
     516 | -                        AddUnlinkedBlock(pindex);
     517 | -                    }
     518 | +                    AddUnlinkedBlock(pindex);
    


    l0rinc commented at 12:21 PM on November 18, 2026:

    12208a0 validation: keep pruned blocks in m_blocks_unlinked:

    I'd reload before the missing parent arrives and check that submitting it fills in the pruned child's count right away.

    <details> <summary>Check linking after reload</summary>

    diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
    index e150f317f4..8fe785275f 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -4,17 +4,21 @@
     //
     #include <chainparams.h>
     #include <consensus/validation.h>
    +#include <flatfile.h>
     #include <kernel/disconnected_transactions.h>
     #include <node/block_template_manager.h>
    +#include <node/blockstorage.h>
     #include <node/chainstatemanager_args.h>
     #include <node/kernel_notifications.h>
     #include <node/utxo_snapshot.h>
    +#include <primitives/block.h>
     #include <random.h>
     #include <rpc/blockchain.h>
     #include <sync.h>
     #include <test/util/chainstate.h>
     #include <test/util/common.h>
     #include <test/util/logging.h>
    +#include <test/util/mining.h>
     #include <test/util/random.h>
     #include <test/util/setup_common.h>
     #include <test/util/validation.h>
    @@ -27,6 +31,7 @@
     
     #include <tinyformat.h>
     
    +#include <map>
     #include <vector>
     
     #include <boost/test/unit_test.hpp>
    @@ -631,6 +636,36 @@ BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
         BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
     }
     
    +BOOST_FIXTURE_TEST_CASE(reload_pruned_child, RegTestingSetup)
    +{
    +    auto& chainman{static_cast<TestChainstateManager&>(*m_node.chainman)};
    +    auto& blockman{chainman.m_blockman};
    +    LOCK(cs_main);
    +    const auto blocks{CreateBlockChain(/*total_height=*/2, chainman.GetParams())};
    +    auto* parent{blockman.AddToBlockIndex(*blocks[0], chainman.m_best_header)};
    +    auto* child{blockman.AddToBlockIndex(*blocks[1], chainman.m_best_header)};
    +    const FlatFilePos pos{/*nFileIn=*/2, /*nPosIn=*/0};
    +    blockman.UpdateBlockInfo(*blocks[1], child->nHeight, pos);
    +    chainman.ReceivedBlockTransactions(*blocks[1], child, pos);
    +    blockman.m_have_pruned = true;
    +    blockman.PruneOneBlockFile(pos.nFile);
    +
    +    BOOST_REQUIRE(blockman.IsBlockPruned(*child));
    +    blockman.m_blocks_unlinked.clear(); // Check reconstruction from the block index
    +    BOOST_REQUIRE(chainman.LoadBlockIndex());
    +    BOOST_CHECK(!blockman.m_blocks_unlinked.contains(parent)); // TODO: Reload must reconstruct waiting entries even after their data was pruned
    +
    +    chainman.CheckBlockIndex();
    +
    +    const auto parent_pos{blockman.WriteBlock(*blocks[0], parent->nHeight)};
    +    BOOST_REQUIRE(!parent_pos.IsNull());
    +    chainman.ReceivedBlockTransactions(*blocks[0], parent, parent_pos);
    +    BOOST_CHECK(!child->HaveNumChainTxs()); // TODO: Receiving the parent after reload must update the pruned child without another reload
    +    BOOST_REQUIRE(chainman.LoadBlockIndex());
    +    BOOST_CHECK(blockman.m_blocks_unlinked.empty());
    +    BOOST_CHECK(child->HaveNumChainTxs());
    +}
    +
     //! Verify that ReconsiderBlock clears failure flags for the target block, its ancestors, and descendants,
     //! but not for sibling forks that diverge from a shared ancestor.
     BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
    

    </details>

  63. in test/functional/feature_prune_stale_fork.py:46 in 0522e7beba outdated
      42 | @@ -29,11 +43,33 @@ def run_test(self):
      43 |          self.generate(node, 500)
      44 |          node.pruneblockchain(node.getblockcount() - 100)
      45 |          assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, side_child.hash_hex)
      46 | +        # Mine a block to run CheckBlockIndex(), which requires the pruned child to still be in m_blocks_unlinked
    


    l0rinc commented at 12:21 PM on November 18, 2026:

    0522e7b test: add functional test for parents of pruned blocks:

    We can probably simplify this if we submit the grandchild before restarting.

    <details> <summary>Exercise pruning and linking with one restart</summary>

    diff --git a/test/functional/feature_prune_stale_fork.py b/test/functional/feature_prune_stale_fork.py
    index 22f98c5421..4984f3f930 100755
    --- a/test/functional/feature_prune_stale_fork.py
    +++ b/test/functional/feature_prune_stale_fork.py
    @@ -2,19 +2,11 @@
     # Copyright (c) 2026-present The Bitcoin Core developers
     # Distributed under the MIT software license, see the accompanying
     # file COPYING or http://www.opensource.org/licenses/mit-license.php.
    -"""Test pruned stale-fork blocks whose parent has no transactions.
    -
    -A stale-fork block whose parent's transactions were never received cannot be
    -connected, so it is tracked in m_blocks_unlinked until they are. Pruning removes
    -its block data, but not the fact that its own transactions were received, so it
    -has to stay listed there. Otherwise the arrival of the parent no longer reaches
    -it, and neither it nor its descendants - which may well still have their own
    -block data - ever get their m_chain_tx_count, which trips CheckBlockIndex().
    -"""
    +"""Test node restart with a pruned stale-fork block whose parent has no transactions."""
     
     from test_framework.blocktools import create_empty_fork
     from test_framework.test_framework import BitcoinTestFramework
    -from test_framework.util import assert_equal, assert_raises_rpc_error
    +from test_framework.util import assert_array_result, assert_equal, assert_raises_rpc_error
     
     
     class FeaturePruneStaleForkTest(BitcoinTestFramework):
    @@ -22,12 +14,6 @@ class FeaturePruneStaleForkTest(BitcoinTestFramework):
             self.num_nodes = 1
             self.extra_args = [["-prune=1", "-fastprune"]]
     
    -    def tip_status(self, node, block_hash):
    -        """Return the getchaintips status of block_hash, which must be a tip."""
    -        tips = [tip for tip in node.getchaintips() if tip["hash"] == block_hash]
    -        assert_equal(len(tips), 1)
    -        return tips[0]["status"]
    -
         def run_test(self):
             node = self.nodes[0]
     
    @@ -43,32 +29,19 @@ class FeaturePruneStaleForkTest(BitcoinTestFramework):
             self.generate(node, 500)
             node.pruneblockchain(node.getblockcount() - 100)
             assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, side_child.hash_hex)
    -        # Mine a block to run CheckBlockIndex(), which requires the pruned child to still be in m_blocks_unlinked
    -        self.generate(node, 1)
    +        # Accepting the grandchild runs CheckBlockIndex(), which requires the pruned child to stay in m_blocks_unlinked
    +        node.submitblock(side_grandchild.serialize().hex())
     
             self.log.info("Restart and mine; node must reload cleanly after the stale-fork child was pruned")
             self.restart_node(0)
             self.generate(node, 1)
     
    -        # The child is now only listed in m_blocks_unlinked if the restart put it back there
    -        # without its block data, so what follows also covers reloading the block index.
    -        self.log.info("Submit the grandchild of the pruned child; it keeps its own block data")
    -        node.submitblock(side_grandchild.serialize().hex())
    -        node.getblock(side_grandchild.hash_hex)
    -        assert_equal(self.tip_status(node, side_grandchild.hash_hex), "headers-only")
    +        assert_array_result(node.getchaintips(), {"hash": side_grandchild.hash_hex}, {"status": "headers-only"})
     
    -        self.log.info("Submit the parent's block; the whole fork must be linked up")
    +        self.log.info("Submit the parent to link the fork through the pruned child")
             node.submitblock(side_parent.serialize().hex())
    -        assert_equal(node.getblockheader(side_parent.hash_hex)["nTx"], 1)
    -        # The child's block data is still gone, but its transactions were received at some
    -        # point, so the grandchild is no longer waiting for transactions the node has.
             assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, side_child.hash_hex)
    -        assert_equal(self.tip_status(node, side_grandchild.hash_hex), "valid-headers")
    -
    -        self.log.info("Restart again; the reloaded node must agree with the running one")
    -        self.restart_node(0)
    -        assert_equal(self.tip_status(node, side_grandchild.hash_hex), "valid-headers")
    -        self.generate(node, 1)
    +        assert_array_result(node.getchaintips(), {"hash": side_grandchild.hash_hex}, {"status": "valid-headers"})
     
     
     if __name__ == '__main__':
    

    </details>

  64. l0rinc changes_requested
  65. l0rinc commented at 12:58 PM on November 18, 2026: contributor

    Concept ACK

    Keeping the block index and candidate ordering reliable after pruning matters before we add more indexes or start batching and parallelizing this work. The distinction between knowing a block’s transactions and having its data on disk will probably matter for pruneassumevalid too.

    Did a first pass, I’d prefer smaller commits that show the old behavior in a test, then flip the relevant check with the fix to prove why each change is needed - I left a few examples inline. The PR description could also use a minor reformatting pass.

  66. sedited referenced this in commit 5d8811d2d7 on Nov 19, 2026
  67. sedited referenced this in commit 371fe89da0 on Nov 19, 2026
  68. sedited referenced this in commit 6ea4b4989e on Nov 19, 2026
  69. sedited referenced this in commit 065f64eb77 on Nov 20, 2026
  70. sedited referenced this in commit 1706ee53b9 on Nov 21, 2026
  71. sedited referenced this in commit d879473503 on Nov 22, 2026
  72. sedited referenced this in commit 18a38aa431 on Nov 22, 2026
  73. sedited referenced this in commit b7def489df on Nov 22, 2026
  74. sedited referenced this in commit 82e9173433 on Nov 23, 2026
  75. sedited referenced this in commit 92c0abb162 on Nov 24, 2026
  76. sedited referenced this in commit f4155c3ee8 on Nov 25, 2026
  77. sedited referenced this in commit 1d657ed696 on Nov 25, 2026
  78. sedited referenced this in commit bfaa1ef725 on Nov 26, 2026
  79. sedited referenced this in commit 755daf6169 on Nov 26, 2026
  80. sedited referenced this in commit d4c5f7cfb2 on Nov 26, 2026
  81. sedited referenced this in commit 29eefede3f on Nov 26, 2026
  82. sedited referenced this in commit dda925dfe1 on Nov 26, 2026
  83. sedited referenced this in commit 08e4fd539d on Nov 28, 2026
  84. sedited referenced this in commit 71534fa681 on Nov 28, 2026
  85. sedited referenced this in commit 1df77c464a on Nov 28, 2026
  86. sedited referenced this in commit a6f8d8dd2a on Nov 28, 2026
  87. sedited referenced this in commit 5665b31291 on Nov 28, 2026
  88. sedited referenced this in commit 49e8f7267c on Nov 29, 2026
  89. in src/validation.cpp:3824 in 532ffaa26d
    3821 | +            // that already is one, which happens when it is downloaded again after being pruned.
    3822 |              for (const auto& c : m_chainstates) {
    3823 | -                c->TryAddBlockIndexCandidate(pindex);
    3824 | +                c->setBlockIndexCandidates.erase(pindex);
    3825 | +            }
    3826 | +            pindex->nSequenceId = nBlockSequenceId++;
    


    sedited commented at 10:40 PM on December 3, 2026:

    I think I can still produce a crash with the following scenario:

    diff --git a/test/functional/feature_prune_stale_fork.py b/test/functional/feature_prune_stale_fork.py
    index 22f98c54210..67e6e899657 100755
    --- a/test/functional/feature_prune_stale_fork.py
    +++ b/test/functional/feature_prune_stale_fork.py
    @@ -15 +15 @@ block data - ever get their m_chain_tx_count, which trips CheckBlockIndex().
    -from test_framework.blocktools import create_empty_fork
    +from test_framework.blocktools import create_block, create_empty_fork
    @@ -43,2 +43,2 @@ class FeaturePruneStaleForkTest(BitcoinTestFramework):
    -        self.generate(node, 500)
    -        node.pruneblockchain(node.getblockcount() - 100)
    +        raw_blocks = {blockhash: node.getblock(blockhash, 0) for blockhash in self.generate(node, 500)}
    +        last_pruned = node.pruneblockchain(node.getblockcount() - 100)
    @@ -72,0 +73,10 @@ class FeaturePruneStaleForkTest(BitcoinTestFramework):
    +        # make the last pruned block the tip, then add a fork block along side it with a higher sequence id
    +        tip_hash = node.getblockhash(last_pruned)
    +        assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, tip_hash)
    +        node.invalidateblock(node.getblockhash(last_pruned + 1))
    +        stale = create_block(int(node.getblockhash(last_pruned - 1), 16), height=last_pruned, ntime=node.getblockheader(tip_hash)["time"])
    +        stale.solve()
    +        node.submitblock(stale.serialize().hex())
    +        assert_equal(node.getbestblockhash(), tip_hash)
    +        # on re-submission, an assert will be raised, since it will now assign the tip a higher sequence id and then expect the stale in blocks unlinked.
    +        node.submitblock(raw_blocks[tip_hash])
    

    Maybe we should check that a previously received block is not given a new sequence id? Found this after telling claude to model the chain and block index transitions with TLA+.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-12-04 01:52 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me