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

Open
mzumsande wants to merge 5 commits from 202609_fix_cbi_pruning_unlinked into master AGit
mzumsande commented 2026-09-02 14:33:49 +00:00 (Migrated from github.com)

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

`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
DrahtBot commented 2026-09-02 14:33:58 +00:00 (Migrated from github.com)

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

External sites

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 <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #36621 (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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36149 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36149.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36149#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/36149#pullrequestreview-5136147146), [enochaz](https://github.com/bitcoin/bitcoin/pull/36149#pullrequestreview-5936936421), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36149#pullrequestreview-5952745439) | | Stale ACK | [marcofleon](https://github.com/bitcoin/bitcoin/pull/36149#pullrequestreview-5153355230) | 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](https://github.com/bitcoin/bitcoin/pull/36990) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36990.svg"></sub> (test: replace hard-coded RPC error codes by l0rinc) * [#36621](https://github.com/bitcoin/bitcoin/pull/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-->
l0rinc commented 2026-09-02 17:29:54 +00:00 (Migrated from github.com)

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

Concept ACK, thanks for fixing it. I will try to review it a bit later.
jeanpablojp (Migrated from github.com) reviewed 2026-09-08 00:32:58 +00:00
jeanpablojp (Migrated from github.com) left a comment

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.

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.
jeanpablojp (Migrated from github.com) commented 2026-09-08 00:32:58 +00:00

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
nit (feel free to ignore): `predecessors` appears only here in `src/`, and `ancestors` sounds to be the preference, including the comment this line replaces. ```suggestion * but B is not a candidate for connection, because for A or one of its ancestors ```
jeanpablojp (Migrated from github.com) commented 2026-09-08 00:32:58 +00:00

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?

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?
marcofleon (Migrated from github.com) reviewed 2026-09-09 11:24:29 +00:00
marcofleon (Migrated from github.com) left a comment

ACK 40a31d97ab

The main fix in 7c7ccc9cc0 looks correct to me. Ran the fuzz test for a while, no issues. Commit 80477ba978 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!

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!
marcofleon (Migrated from github.com) commented 2026-09-09 11:01:04 +00:00

We could also test submitting a missing parent of a pruned child before restarting, as in https://github.com/bitcoin/bitcoin/issues/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?

We could also test submitting a missing parent of a pruned child before restarting, as in https://github.com/bitcoin/bitcoin/issues/36021. This test currently passes with the old behavior of [removing](https://github.com/bitcoin/bitcoin/blob/fb26bc9cfefeacda5df08c36a3b2e9f1086e3e48/src/node/blockstorage.cpp#L288-L295) 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 (Migrated from github.com) reviewed 2026-09-09 21:50:29 +00:00
mzumsande (Migrated from github.com) left a comment

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.

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.
mzumsande (Migrated from github.com) commented 2026-09-09 21:49:07 +00:00

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.

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.
mzumsande (Migrated from github.com) reviewed 2026-11-02 17:31:55 +00:00
mzumsande (Migrated from github.com) commented 2026-11-02 17:31:55 +00:00

done

done
mzumsande (Migrated from github.com) reviewed 2026-11-02 17:34:10 +00:00
mzumsande (Migrated from github.com) commented 2026-11-02 17:34:10 +00:00

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

Makes sense - since there were two other spots in the vicinity that had a similar issue I added a separate commit that changes these.
mzumsande (Migrated from github.com) reviewed 2026-11-02 17:40:07 +00:00
mzumsande (Migrated from github.com) commented 2026-11-02 17:40:07 +00:00

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

I added a `generate()` call before the restart, so that CheckBlockIndex is invoked. I think that should cover the situation, too.
mzumsande commented 2026-11-02 17:59:45 +00:00 (Migrated from github.com)

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().

[40a31d9](https://github.com/bitcoin/bitcoin/commit/40a31d97ab118cb030af7d560aedbade3ae4cd36) to [532ffaa](https://github.com/bitcoin/bitcoin/commit/532ffaa26d0557c149d7efee544f163fdcf84006): 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()`.
First-time contributor

🔵 Suggestion · Fuzz re-downloads bypass the known-invalid block guard

Off-chain pruning lets the fuzz target re-download an index still marked BLOCK_FAILED_VALID, a receipt transition that production rejects before ReceivedBlockTransactions.

Location: src/test/fuzz/block_index_tree.cpp:156 (head).

🔵 Suggestion · Sequence-ID re-receipt fix lacks a direct regression oracle

The added functional test never re-receives an existing candidate, and the fuzz target lacks ordering and pointer-uniqueness checks for the repaired sequence-ID invariant.

Location: src/validation.cpp:3821 (head).

🔵 Suggestion · Fuzz pruning duplicates the production retention rule

The fuzz target applies its own copy of the new HaveNumChainTxs() retention condition, so later production changes can leave it exercising a different pruning rule.

Location: src/test/fuzz/block_index_tree.cpp:164 (head).

Review coverage was incomplete.


Reviewed: 532ffaa26d05 · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:965af1044d9e41839565702e4d9bd0a751eda81f6e8b6402747fa296ef84ebea:7efd3c3ba41667382004cfa7a7db56605da7d8f9b7ab69bc483f27117390ba48 --> <!-- ralph-base:ddea9196493d3b8fd841a36a6c53efd85dac7a05 --> <!-- ralph-head:532ffaa26d0557c149d7efee544f163fdcf84006 --> <!-- ralph-case:69f5c837ffedba52e1ee112b267c5b9c8c37d95f136aef446b06ac700913b5a9 --> **🔵 Suggestion · Fuzz re-downloads bypass the known-invalid block guard** Off-chain pruning lets the fuzz target re-download an index still marked `BLOCK_FAILED_VALID`, a receipt transition that production rejects before `ReceivedBlockTransactions`. Location: [`src/test/fuzz/block_index_tree.cpp:156`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/532ffaa26d0557c149d7efee544f163fdcf84006/src/test/fuzz/block_index_tree.cpp#L156>) (head). **🔵 Suggestion · Sequence-ID re-receipt fix lacks a direct regression oracle** The added functional test never re-receives an existing candidate, and the fuzz target lacks ordering and pointer-uniqueness checks for the repaired sequence-ID invariant. Location: [`src/validation.cpp:3821`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/532ffaa26d0557c149d7efee544f163fdcf84006/src/validation.cpp#L3821>) (head). **🔵 Suggestion · Fuzz pruning duplicates the production retention rule** The fuzz target applies its own copy of the new `HaveNumChainTxs()` retention condition, so later production changes can leave it exercising a different pruning rule. Location: [`src/test/fuzz/block_index_tree.cpp:164`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/532ffaa26d0557c149d7efee544f163fdcf84006/src/test/fuzz/block_index_tree.cpp#L164>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`532ffaa26d05`](<https://git.fish.foo/bitcoin/bitcoin/commit/532ffaa26d0557c149d7efee544f163fdcf84006>) · [Full review report](<https://review.fish.foo/traces/36149-532ffaa26d0557c149d7efee544f163fdcf84006-2001-1.html>) · [Previous reports](<https://review.fish.foo/traces/36149/>) [permalink](<https://review.fish.foo/traces/36149-532ffaa26d0557c149d7efee544f163fdcf84006-2001-1.html>)
enochaz (Migrated from github.com) reviewed 2026-11-17 11:54:56 +00:00
enochaz (Migrated from github.com) left a comment

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

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
enochaz (Migrated from github.com) commented 2026-11-17 10:39:54 +00:00

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:

github.com/enochaz/bitcoin@532ffaa26d/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);
         }
     }
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. ```diff --git a/src/validation.cpp b/src/validation.cpp 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); } } ```
enochaz (Migrated from github.com) commented 2026-11-17 11:45:25 +00:00

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()));
+}
+
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. ```diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp 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())); +} + ```
enochaz (Migrated from github.com) commented 2026-11-17 10:57:55 +00:00

In commit 12208a02ff: 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.
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`. ```diff --git a/src/validation.cpp b/src/validation.cpp 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. ```
l0rinc (Migrated from github.com) requested changes 2026-11-18 12:58:02 +00:00
l0rinc (Migrated from github.com) left a comment

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.

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.
l0rinc (Migrated from github.com) commented 2026-11-18 12:21:31 +00:00

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.
> [12208a0](https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d) _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.
l0rinc (Migrated from github.com) commented 2026-11-18 08:22:24 +00:00

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).

Extract PruneBlock and reuse it in the fuzz test
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);
                 }
             },
> [12208a0](https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d) _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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 12:21:39 +00:00

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.

Check linking after reload
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)
> [12208a0](https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d) _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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 08:24:47 +00:00

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).

Drop the obsolete duplicate-entry rationale
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);
> [92c02d4](https://github.com/bitcoin/bitcoin/pull/36149/changes/92c02d42212b721e75bda5ee6454dec545e8fc85) _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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 12:03:25 +00:00

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

Show the ordering before the fix
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
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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 12:05:39 +00:00

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.

Show candidate membership before the data check
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,
> [12208a0](https://github.com/bitcoin/bitcoin/pull/36149/changes/12208a02ff5f795369fb2ab28884dc37b2db245d) _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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 12:21:48 +00:00

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

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

Exercise pruning and linking with one restart
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__':
> [0522e7b](https://github.com/bitcoin/bitcoin/pull/36149/changes/0522e7bebaa3fbb7b278923eab28e7de5dbcda44) _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> ```patch 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>
l0rinc (Migrated from github.com) commented 2026-11-18 09:51:14 +00:00

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.

Check linking before restart
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)
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> ```patch 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>
enochaz (Migrated from github.com) reviewed 2026-11-18 13:57:28 +00:00
enochaz (Migrated from github.com) commented 2026-11-18 13:57:28 +00:00

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.

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.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36149
No description provided.