Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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. |
6902730 to
40a31d9
Compare
|
Concept ACK, thanks for fixing it. I will try to review it a bit later. |
jeanpablojp
left a comment
There was a problem hiding this 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.
| # 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") |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Makes sense - since there were two other spots in the vicinity that had a similar issue I added a separate commit that changes these.
marcofleon
left a comment
There was a problem hiding this comment.
ACK 40a31d9
The main fix in 7c7ccc9 looks correct to me. Ran the fuzz test for a while, no issues. Commit 80477ba 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!
| @@ -34,6 +48,26 @@ def run_test(self): | |||
| self.restart_node(0) | |||
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
I added a generate() call before the restart, so that CheckBlockIndex is invoked. I think that should cover the situation, too.
There was a problem hiding this comment.
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)
mzumsande
left a comment
There was a problem hiding this 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.
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 <[email protected]>
This test would lead to a CheckBlockIndex assertion fail without the changes of the previous commit.
…date 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.
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.
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.
40a31d9 to
532ffaa
Compare
|
40a31d9 to 532ffaa: In the previous PR branch, pruning never removed anything from 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 |
m_blocks_unlinked, fix another nSequenceId issuem_blocks_unlinked, fix another nSequenceId issue
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates, OnUndoWritten), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. CBlockIndex gains a typed state, BlockIndexState, derived from nStatus (which stays the stored representation, so nothing on disk changes), and HaveUndo() for the orthogonal undo bit. CheckBlockIndex checks that the typed state agrees with the flags, that HaveUndo implies a valid undo position and a connected block, in addition to its existing invariants. Unit tests cover the state mapping and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The other known bug classes of the plan are covered by invariants the checker already has: bitcoin#36702 by the snapshot-base m_chain_tx_count checks, bitcoin#36452 by CheckBlockDataAvailability and the HAVE_DATA/nTx relations, bitcoin#34254 by the failed-flag propagation checks.
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates, OnUndoWritten), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. CBlockIndex gains a typed state, BlockIndexState, derived from nStatus (which stays the stored representation, so nothing on disk changes), and HaveUndo() for the orthogonal undo bit. CheckBlockIndex checks that the typed state agrees with the flags, that HaveUndo implies a valid undo position and a connected block, in addition to its existing invariants. Unit tests cover the state mapping and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The other known bug classes of the plan are covered by invariants the checker already has: bitcoin#36702 by the snapshot-base m_chain_tx_count checks, bitcoin#36452 by CheckBlockDataAvailability and the HAVE_DATA/nTx relations, bitcoin#34254 by the failed-flag propagation checks.
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates, OnUndoWritten), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. CBlockIndex gains a typed state, BlockIndexState, derived from nStatus (which stays the stored representation, so nothing on disk changes), and HaveUndo() for the orthogonal undo bit. CheckBlockIndex checks that the typed state agrees with the flags, that HaveUndo implies a valid undo position and a connected block, in addition to its existing invariants. Unit tests cover the state mapping and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The other known bug classes of the plan are covered by invariants the checker already has: bitcoin#36702 by the snapshot-base m_chain_tx_count checks, bitcoin#36452 by CheckBlockDataAvailability and the HAVE_DATA/nTx relations, bitcoin#34254 by the failed-flag propagation checks.
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates, OnUndoWritten), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. CBlockIndex gains a typed state, BlockIndexState, derived from nStatus (which stays the stored representation, so nothing on disk changes), and HaveUndo() for the orthogonal undo bit. CheckBlockIndex checks that the typed state agrees with the flags, that HaveUndo implies a valid undo position and a connected block, in addition to its existing invariants. Unit tests cover the state mapping and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The other known bug classes of the plan are covered by invariants the checker already has: bitcoin#36702 by the snapshot-base m_chain_tx_count checks, bitcoin#36452 by CheckBlockDataAvailability and the HAVE_DATA/nTx relations, bitcoin#34254 by the failed-flag propagation checks.
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates, OnUndoWritten), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. CBlockIndex gains a typed state, BlockIndexState, derived from nStatus (which stays the stored representation, so nothing on disk changes), and HaveUndo() for the orthogonal undo bit. CheckBlockIndex checks that the typed state agrees with the flags, that HaveUndo implies a valid undo position and a connected block, in addition to its existing invariants. Unit tests cover the state mapping and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The other known bug classes of the plan are covered by invariants the checker already has: bitcoin#36702 by the snapshot-base m_chain_tx_count checks, bitcoin#36452 by CheckBlockDataAvailability and the HAVE_DATA/nTx relations, bitcoin#34254 by the failed-flag propagation checks.
The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Unit tests cover that a failed block takes no validity raise and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. Both unit tests pass before this commit too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the thirteen transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
l0rinc
left a comment
There was a problem hiding this 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.
| m_blocks_unlinked.emplace(block->pprev, block); | ||
| } | ||
|
|
||
| void BlockManager::RemoveUnlinkedBlock(CBlockIndex* block) |
There was a problem hiding this comment.
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);
}
},| } | ||
| pindex->m_chain_tx_count = prev_tx_sum(*pindex); | ||
| pindex->nSequenceId = nBlockSequenceId++; | ||
| // nSequenceId is one of the sort keys of setBlockIndexCandidates, so pindex must |
There was a problem hiding this comment.
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);| @@ -34,6 +48,26 @@ def run_test(self): | |||
| self.restart_node(0) | |||
There was a problem hiding this comment.
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)| // ordering. pindex can be a candidate here if we receive the block data of a block | ||
| // that already is one, which happens when it is downloaded again after being pruned. | ||
| for (const auto& c : m_chainstates) { | ||
| c->setBlockIndexCandidates.erase(pindex); |
There was a problem hiding this comment.
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| c->TryAddBlockIndexCandidate(pindex); | ||
| // A descendant taken from m_blocks_unlinked may have been pruned, | ||
| // in which case it can't be a candidate until it is downloaded again. | ||
| if (pindex->nStatus & BLOCK_HAVE_DATA) { |
There was a problem hiding this comment.
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,| Assume(block != nullptr); | ||
| Assume(block->nStatus & BLOCK_HAVE_DATA); | ||
| Assume(block->pprev != nullptr); | ||
| Assume(block->nTx > 0); // Not BLOCK_HAVE_DATA: the data of the block may have been pruned |
There was a problem hiding this comment.
12208a0 validation: keep pruned blocks in m_blocks_unlinked:
A lot is happening here, could we split this part into three commits?
- Let
AddUnlinkedBlockaccept pruned blocks with a parent and received transactions. - Rebuild their waiting entries in
LoadBlockIndex. - Have
CheckBlockIndexrequire those entries even after pruning.
| if (pindex->nStatus & BLOCK_HAVE_DATA) { | ||
| AddUnlinkedBlock(pindex); | ||
| } | ||
| AddUnlinkedBlock(pindex); |
There was a problem hiding this comment.
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)| 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 |
There was a problem hiding this comment.
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__':… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the thirteen transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the thirteen transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the thirteen transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the thirteen transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: Prune is defined on every state with data and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, that a failed block takes no validity raise, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. The two block index cases pass on master too: they pin what the named transitions must keep (RaiseValidity() refusing a failed block, PruneOneBlockFile() clearing the set), not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
… machines util/machine.h: a machine is an enum of states, an enum of events and a constexpr table of edges. TransitionTable::Next() takes a state by value and an event and returns the next state, or nothing when the table has no edge for the pair. Two edges for one (state, event) pair fail to compile. The table holds no state and has no effects: the caller keeps the state and acts on what Next() returns. The block index was already driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. Where a block stands between "its header is known" and "it is part of a chain" was implicit in BLOCK_HAVE_DATA, BLOCK_FAILED_VALID and chain membership. node::BlockStoreState names the six combinations the node produces, node::BLOCK_STORE_TABLE the ten transitions between them, and BlockStoreStateOf() derives the state from the block index; nothing new is stored. Each site that makes a transition (InvalidBlockFound, DisconnectTip, ConnectTip, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, ReceivedBlockTransactions) reads the state before and after and checks the pair against the table with Assume. A block the machine has no state for, a block in a chain that is marked failed, is not checked: a crash can leave one (the comment in CheckBlockIndex says how), and a transition out of a state outside the machine says nothing about the table. Loading the block index and activating a snapshot establish states wholesale and are not checked. PruneOneBlockFile is not checked either: pruning is no event of the table (it takes a block's data, from whichever state has it) and the block manager has no chain to derive the state from. Unit tests cover the table (every edge, and pairs without one), that the block storage state is derived, the sites that make a transition, and the sequence behind bitcoin#36149 (a block in m_blocks_unlinked whose file is pruned must leave the set), which the checker's "no data implies not unlinked" invariant also guards. That last case passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change in a release build.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
The block index is driven by a small set of functions that write nStatus and the derived sets (AddToBlockIndex, ReceivedBlockTransactions, InvalidBlockFound, InvalidateBlock, SetBlockFailureFlags, ResetBlockFailureFlags, PruneOneBlockFile, TryAddBlockIndexCandidate, PruneBlockIndexCandidates), with CheckBlockIndex as the invariant checker and the block_index_tree fuzz target driving event sequences against it. Two writers were still inline and move into named transitions: - the validity raise after a block is connected becomes ChainstateManager::MarkBlockScriptsValid; - the removal of an unusable candidate chain inside FindMostWorkChain becomes Chainstate::DropUnusableCandidateChain. blockindex_machine_tests pins the sequence behind bitcoin#36149: a block in m_blocks_unlinked whose file is pruned must leave the set, which the checker's "no data implies not unlinked" invariant also guards. It passes on master too: it pins what PruneOneBlockFile() must keep, clearing the set, not code this commit adds. No behaviour change.
| c->TryAddBlockIndexCandidate(pindex); | ||
| c->setBlockIndexCandidates.erase(pindex); | ||
| } | ||
| pindex->nSequenceId = nBlockSequenceId++; |
There was a problem hiding this comment.
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+.

m_blocks_unlinkedserves two purposes:setBlockIndexCandidatesonce their parents arereceived
m_chain_tx_countonce the parents are receivedIn 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
CheckBlockIndexfailures (#31512, #36021) and incorrect rpc results, plus we are in a temporarily inconsistent state (m_chain_tx_countis 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
getblockfrompeerscenarios.Fix this by leaving pruned blocks in
m_blocks_unlinkedthat don't havem_chain_tx_countset, and also adding them on restart.This was one of two reasons, the fuzz target
block_index_treecouldn'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
nSequenceIdwhile the block is insetBlockIndexCandidates- 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_treefuzz target is removed.Fixes #36021
Fixes #31512