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 ConflictsNo conflicts as of last run. |
|
ACK 73e0bab7adb0b16b2ac4d13c9d601a04b7184749 |
There was a problem hiding this comment.
This looks good, going to think about it more. I think the noticeable changes here are that:
InvalidateBlockwon't have warnings anymore sinceCheckForkWarningConditionsis no longer called (this seems fine, the warnings mention falling out of consensus which is irrelevant here imo)ActivateBestChainStepdoes not duplicate logging / work (also fine)
| @@ -3733,7 +3734,10 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde | |||
| } | |||
| } | |||
|
|
|||
| InvalidChainFound(to_mark_failed); | |||
| UpdateBestInvalid(to_mark_failed); | |||
There was a problem hiding this comment.
I think this can fail to set m_best_invalid properly since to_mark_failed walks backwards (if pindex is in the main chain) and then UpdateBestInvalid is called after looping?
There was a problem hiding this comment.
good observation, I think that's correct - it should be a preexisting issue though that is not changed by this PR.
It should be possible to fix this by calling UpdateBestInvalid also earlier in the process (which we could do more easily after this PR, because unlike old InvalidChainFound, we no longer iterate over the block index).
On the other hand, m_best_invalid is only used for logging of out-of-consensus warnings, and I'm not sure if these logged warnings are really helpful if the consensus failure is self-inflicted through RPC. What do you think?
There was a problem hiding this comment.
Brain-dump of what I think happens (haven't written a test) with InvalidateBlock calling InvalidChainFound in master:
InvalidChainFound will:
- update m_best_invalid
- call SetBlockFailureFlags which updates children to set BLOCK_FAILED_CHILD
- call RecalculateBestHeader
- call CheckForkWarningConditions
to_mark_failed can either be in-chain or out-of-chain. If it's in-chain, then it will be set to the
last disconnected block. If it's out-of-chain, it will be unchanged.
If to_mark_failed was in-chain:
- m_best_invalid might be changed to to_mark_failed. Since to_mark_failed was changed, m_best_invalid might not change when it should (what I mentioned above in the previous comment).
- SetBlockFailureFlags: Unnecessary because all of the children have been marked
BLOCK_FAILED_CHILD in the loop. - RecalculateBestHeader: Unnecessary. If the best header was in-chain, then the
loop already updated it. If the best header is out-of-chain, it was not invalidated. - CheckForkWarningConditions: Necessary because the tip definitely changed and
m_best_invalid may or may not have changed. Either way, the fork condition may be hit.
Else (to_mark_failed is out-of-chain):
- m_best_invalid might be changed to to_mark_failed. Even here, there may be children that could be
marked as m_best_invalid instead of to_mark_failed, depending on what block the user calls InvalidateBlock on. - SetBlockFailureFlags: Necessary because if there are children, they need to be marked BLOCK_FAILED_CHILD.
- RecalculateBestHeader: Necessary because the loop above did not run.
- CheckForkWarningConditions: Necessary because m_best_invalid may have changed.
This PR changes things by only updating m_best_invalid and calling CheckForkWarningConditions. This is
fine for the in-chain case, but for the case where to_mark_failed is out-of-chain, I think it's missing
SetBlockFailureFlags & RecalculateBestHeader?
It should be possible to fix this by calling UpdateBestInvalid also earlier in the process (which we could do more easily after this PR, because unlike old InvalidChainFound, we no longer iterate over the block index).
For the in-chain case of setting m_best_invalid improperly, we could call UpdateBestInvalid where it is and change the argument such that it's either the old tip or to_mark_failed, depending on pindex_was_in_chain = true?
On the other hand, m_best_invalid is only used for logging of out-of-consensus warnings, and I'm not sure if these logged warnings are really helpful if the consensus failure is self-inflicted through RPC. What do you think?
If the logged warnings aren't helpful, should they be removed? I don't have a strong opinion here, I did find it a little confusing that m_best_invalid was being updated improperly in master, maybe a comment could suffice that it's not being set to the actual best invalid? I didn't mean to imply that this PR introduced that either btw.
There was a problem hiding this comment.
This PR changes things by only updating m_best_invalid and calling CheckForkWarningConditions. This is
fine for the in-chain case, but for the case where to_mark_failed is out-of-chain, I think it's missing
SetBlockFailureFlags & RecalculateBestHeader?
Good catch! I think it should be possible to add these back to the !pindex_was_in_chain conditional, which already has a bunch of extra logic for this case. I will do that soon, but I also want to add a scenario for this invalidateblock on out-of-chain blocks scenario to rpc_invalidateblock, because since ed764ea, CheckBlockIndex has a check to fail in these situations.
Will update the PR in a couple of day, and also think about the logging a bit more.
There was a problem hiding this comment.
I updated this now and added the missing calls back (plus added a test in the first commit, that would have failed on my earlier branch). I think it's safer to not make these conditional on !pindex_was_in_chain since during the earlier chain disconnecting we release cs_main, and if any blocks would have been added by another thread, these could have been missed otherwise.
There was a problem hiding this comment.
I think it's safer to not make these conditional on !pindex_was_in_chain since during the earlier chain disconnecting we release cs_main, and if any blocks would have been added by another thread, these could have been missed otherwise.
Good point. I mistakenly thought locking m_chainstate_mutex prevented another block from being added, but that's not right. I think examining the guarantees this function has while another thread simultaneously adds blocks to the index is probably worthwhile...
frankomosh
left a comment
There was a problem hiding this comment.
Concept ACK on the overall refactoring approach.
73e0bab to
f789d4f
Compare
There was a problem hiding this comment.
Concept ACK. nice cleanup!
Therefore move of all logic but the m_best_invalid update into InvalidBlockFound, avoiding duplicate logging and unnecessary work (the loops over the block index in SetBlockFailureFlags and RecalculateBestHeader were done twice before).
wondering if it’s also possible to avoid looping over the block index twice and instead combine this into a single pass?
- 1st iteration through block index to set
BLOCK_FAILED_VALID - 2nd iteration through block index to update
m_best_header
i guess doing it this way would make m_best_header temporarily inconsistent (for this chain: 1 ←2 ←3 ← 4 ← 5, intermediate states during the loop could have 3 still marked as invalid and 5 as the m_best_header) but after the loop finishes it should be consistent.
thinking of something like:
void Chainstate::SetBlockFailureFlagsAndBestHeader(CBlockIndex* invalid_block, bool recalculate_best_header)
{
AssertLockHeld(cs_main);
if (recalculate_best_header) {
m_chainman.m_best_header = m_chain.Tip();
}
for (auto& [_, block_index] : m_blockman.m_block_index) {
if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
block_index.nStatus |= BLOCK_FAILED_VALID;
m_blockman.m_dirty_blockindex.insert(&block_index);
}
if (recalculate_best_header && !(block_index.nStatus & BLOCK_FAILED_VALID) && m_chainman.m_best_header->nChainWork < block_index.nChainWork) {
m_chainman.m_best_header = &block_index;
}
}
}
also sinceRecalculateBestHeader originally existed for reconsiderblock RPC before #30666, we should update the comment in validation.h that this is no longer the case!
EDIT: In case anyone else also found the block invalidity handling a bit tricky to follow - different operations (marking BLOCK_FAILED_VALID, sometimes updating m_best_header, sometimes m_best_invalid, and sometimes removing from setBlockIndexCandidates) being performed from different places across the code, I have a summary sheet here - hopefully it 's not too hard to follow and makes things easier to reason about.
| @@ -3720,7 +3734,10 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde | |||
| } | |||
| } | |||
|
|
|||
| InvalidChainFound(to_mark_failed); | |||
| UpdateBestInvalid(to_mark_failed); | |||
| LogInfo("Invalidated block: hash=%s height=%d\n", | |||
There was a problem hiding this comment.
Ran both master and this branch on regtest with -debug=validation to confirm what changed in the invalidateblock logging.
master:
InvalidChainFound: invalid block=4579db92... height=5 log2_work=3.584963 date=2026-05-18T06:30:51Z
InvalidChainFound: current best=763f0c07... height=4 log2_work=3.321928 date=2026-05-18T06:30:51Z
This branch:
Invalidated block: hash=5fe0ec84... height=5
log2_work, date, and the current best line are gone. Also, the prefix changes from InvalidChainFound: to Invalidated block:, which to my thinking, might silently break any log monitoring on the old string.
Not sure if this has been raised elsewhere, but just posting it in case it’s useful context.
There was a problem hiding this comment.
thanks - I mentioned the log change in the commit message. I think it's better to have a separate logging for a rpc, so that the two situations can be distinguished. Since logs are not a guaranteed stable interface, I don't think log monitoring is an issue - especially here, because this is only ever triggered by a user.
|
Ping @mzumsande for a rebase and some unaddressed review. |
|
Thanks for the reminder, I'll update soon! |
f789d4f to
ff06c05
Compare
|
f789d4f to ff06c05:
I didn't do that here - I feel like it's not really necessary to optimize too much, since this can all only be triggered by creating an invalid block with valid PoW which is very costly (or using a hidden rpc not meant to be used regularly), so the few milliseconds we'd save likely won't matter much. |
|
crACK ff06c05 I still am confused by how |
|
|
||
| // Called both upon regular invalid block discovery *and* InvalidateBlock | ||
| // Update m_best_invalid to track the invalid block with the most work | ||
| void Chainstate::InvalidChainFound(CBlockIndex* pindexNew) |
There was a problem hiding this comment.
Nit: Calling the block index entry new is a bit confusing in my eyes. Maybe call this invalid_block or something along the lines?
There was a problem hiding this comment.
added a commit do to this. Did it by hand instead of a scripted diff because pindexNew is very common.
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, 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, 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.
l0rinc
left a comment
There was a problem hiding this comment.
Concept ACK
The approach looks sound to me, but I’d like the assumptions behind removing the repeated work to be explicit and backed by a sanity check - so that they don't depend on call order (which is admittedly unlikely to change, but still...)
| pindex->nStatus |= BLOCK_FAILED_VALID; | ||
| m_blockman.m_dirty_blockindex.insert(pindex); | ||
| setBlockIndexCandidates.erase(pindex); | ||
| SetBlockFailureFlags(pindex); |
There was a problem hiding this comment.
b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:
After splitting this locally (as suggested in #34254 (comment)), I can see the two callers where the removed logic is added back, but the saving (the goal of this PR) is in the third caller, which isn't visible.
Besides being hidden, it's also a bit worrying, since correctness now depends on call order. Could we add an assertion here that the highest block in the failed batch is already marked invalid? It would be a cheap and shallow sanity check, but it would at least catch the case where the invalidation was skipped and the batch tip wasn't marked.
That would make the third caller visible in the diff and reassure us that the earlier failure handling ran.
Assert the failed batch tip is already marked invalid
diff --git a/src/validation.cpp b/src/validation.cpp
index 44b35c6d5f..ff9a4fa79e 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3252,6 +3252,7 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex&
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
+ Assert(vpindexToConnect.front()->nStatus & BLOCK_FAILED_VALID);
InvalidChainFound(vpindexToConnect.front());
}
state = BlockValidationState();There was a problem hiding this comment.
did it, but used Assume instead to lower (future) risk. This should be recoverable, since FindMostWorkChain can deal with indexes that were not marked invalid.
| m_blockman.m_dirty_blockindex.insert(pindex); | ||
| setBlockIndexCandidates.erase(pindex); | ||
| SetBlockFailureFlags(pindex); | ||
| if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) { |
There was a problem hiding this comment.
b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:
InvalidBlockFound() and InvalidateBlock() both call SetBlockFailureFlags() and then update the best header if it points into the invalid branch.
We could put that header update at the end of the helper, since marking a branch invalid can also make the current best header unusable.
The flags still need to be set first so RecalculateBestHeader() excludes the invalid blocks.
If we inlcude the header update in that method, it should be renamed of course to reflect its new purpose.
InvalidChainFound() can stay separate, since it only tracks the invalid block with the most work.
I’d also call InvalidChainFound() before logging in InvalidBlockFound(), so the two callers follow the same order.
Propagate invalidity and update the best header
diff --git a/src/validation.cpp b/src/validation.cpp
index 7df03b6d29..0e1f575874 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -1972,10 +1972,8 @@ void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationSta
pindex->nStatus |= BLOCK_FAILED_VALID;
m_blockman.m_dirty_blockindex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
- SetBlockFailureFlags(pindex);
- if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) {
- m_chainman.RecalculateBestHeader();
- }
+ PropagateBlockInvalidity(pindex);
+ UpdateBestInvalid(pindex);
LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
pindex->GetBlockHash().ToString(), pindex->nHeight,
@@ -1985,7 +1983,6 @@ void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationSta
LogInfo("%s: current best=%s height=%d log2_work=%f date=%s", __func__,
tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble()) / log(2.0),
FormatISO8601DateTime(tip->GetBlockTime()));
- UpdateBestInvalid(pindex);
CheckForkWarningConditions();
}
}
@@ -3753,13 +3750,10 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
}
}
- // Flag the remaining descendants as invalid: The marking in the disconnect loop only
- // covers blocks that were already present in highpow_outofchain_headers when it was
- // built, and it doesn't run at all if pindex never was in the active chain.
- SetBlockFailureFlags(to_mark_failed);
- if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(to_mark_failed->nHeight) == to_mark_failed) {
- m_chainman.RecalculateBestHeader();
- }
+ // Flag the remaining descendants as invalid and update the best header: The marking in the disconnect
+ // loop only covers blocks that were already present in highpow_outofchain_headers when
+ // it was built, and it doesn't run at all if pindex never was in the active chain.
+ PropagateBlockInvalidity(to_mark_failed);
UpdateBestInvalid(to_mark_failed);
LogInfo("Invalidated block: hash=%s height=%d",
@@ -3790,7 +3784,7 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
return true;
}
-void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block)
+void Chainstate::PropagateBlockInvalidity(CBlockIndex* invalid_block)
{
AssertLockHeld(cs_main);
@@ -3800,6 +3794,9 @@ void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block)
m_blockman.m_dirty_blockindex.insert(&block_index);
}
}
+ if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(invalid_block->nHeight) == invalid_block) {
+ m_chainman.RecalculateBestHeader();
+ }
}
void Chainstate::ResetBlockFailureFlags(CBlockIndex *pindex) {
diff --git a/src/validation.h b/src/validation.h
index 995dffab06..d3a8166623 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -806,8 +806,8 @@ public:
EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
LOCKS_EXCLUDED(::cs_main);
- /** Set invalidity status to all descendants of a block */
- void SetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
+ /** Set invalidity status to all descendants of an already invalid block, and recalculate the best header if it was in that subtree */
+ void PropagateBlockInvalidity(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
/** Remove invalidity status from a block, its descendants and ancestors and reconsider them for activation */
void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);There was a problem hiding this comment.
done in 44de389
also added an Assume that the block is invalid.
| // Called both upon regular invalid block discovery *and* InvalidateBlock | ||
| void Chainstate::InvalidChainFound(CBlockIndex* pindexNew) | ||
| // Update m_best_invalid to track the invalid block with the most work | ||
| void Chainstate::UpdateBestInvalid(CBlockIndex* pindexNew) |
There was a problem hiding this comment.
ff06c05 validation: rename InvalidChainFound to UpdateBestInvalid:
Could this be a scripted diff instead?
Scripted rename commit
scripted-diff: Rename InvalidChainFound to UpdateBestInvalid
It's a more descriptive name after most of the logic was moved into InvalidBlockFound.
-BEGIN VERIFY SCRIPT-
git grep -q 'UpdateBestInvalid' -- src && echo 'Error: UpdateBestInvalid already exists in src' && exit 1
perl -pi -e 's/InvalidChainFound/UpdateBestInvalid/g' $(git grep -l 'InvalidChainFound' -- src)
-END VERIFY SCRIPT-There was a problem hiding this comment.
done, but I used sed for the scripted diff, which seems the more common choice.
| tip_height = node.getblockcount() | ||
| # Submit two headers building on the tip | ||
| block_time = node.getblock(tip_hash)["time"] + 1 | ||
| header1 = create_block(int(tip_hash, 16), height=tip_height + 1, ntime=block_time) |
There was a problem hiding this comment.
3c16dc5 test: functional test for invalidateblock of blocks not in chain:
We could simplify this setup to use create_empty_fork(node, fork_length=2), which already builds and solves two blocks extending the active tip.
Reuse the existing fork helper
diff --git a/test/functional/rpc_invalidateblock.py b/test/functional/rpc_invalidateblock.py
index fd00312b63..928076926c 100755
--- a/test/functional/rpc_invalidateblock.py
+++ b/test/functional/rpc_invalidateblock.py
@@ -8,6 +8,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.address import ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR
from test_framework.blocktools import (
create_block,
+ create_empty_fork,
)
from test_framework.util import (
assert_equal,
@@ -139,14 +140,9 @@ class InvalidateTest(BitcoinTestFramework):
node = self.nodes[1]
tip_hash = node.getbestblockhash()
tip_height = node.getblockcount()
- # Submit two headers building on the tip
- block_time = node.getblock(tip_hash)["time"] + 1
- header1 = create_block(int(tip_hash, 16), height=tip_height + 1, ntime=block_time)
- header1.solve()
- node.submitheader(header1.serialize().hex())
- header2 = create_block(header1.hash_int, height=tip_height + 2, ntime=block_time + 1)
- header2.solve()
- node.submitheader(header2.serialize().hex())
+ header1, header2 = create_empty_fork(node, fork_length=2)
+ for header in (header1, header2):
+ node.submitheader(header.serialize().hex())
assert_equal(node.getblockchaininfo()["headers"], tip_height + 2)
# Invalidating the first header must also mark its descendant as invalid and move the| chainman.InvalidBlockFound(block, state); | ||
| // This results in duplicate calls to InvalidChainFound, but mirrors the behavior in validation | ||
| chainman.InvalidChainFound(to_connect.front()); | ||
| // This results in duplicate calls to UpdateBestInvalid, but mirrors the behavior in validation |
There was a problem hiding this comment.
ff06c05 validation: rename InvalidChainFound to UpdateBestInvalid:
The fuzz comment calls these duplicate calls, but the second call can track a different block: the highest one in the failed batch.
The to_mark_failed comment also needs updating, since that block is used to set failure flags, update the best header, log the invalidation and notify about the tip.
Refresh the invalid-chain names and comments
diff --git a/src/test/fuzz/block_index_tree.cpp b/src/test/fuzz/block_index_tree.cpp
index f3c9c4e329..302a5b101d 100644
--- a/src/test/fuzz/block_index_tree.cpp
+++ b/src/test/fuzz/block_index_tree.cpp
@@ -133,7 +133,7 @@ FUZZ_TARGET(block_index_tree, .init = initialize_block_index_tree)
BlockValidationState state;
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "consensus-invalid");
chainman.InvalidBlockFound(block, state);
- // This results in duplicate calls to UpdateBestInvalid, but mirrors the behavior in validation
+ // Mirror ActivateBestChainStep by also considering the highest block of the failed batch
chainman.UpdateBestInvalid(to_connect.front());
break;
} else {
diff --git a/src/validation.cpp b/src/validation.cpp
index 0e1f575874..475d740b26 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3717,7 +3717,7 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
++candidate_it;
}
- // Track the last disconnected block to call UpdateBestInvalid on it.
+ // Track the last disconnected block for the final invalidation updates and tip notification
to_mark_failed = disconnected_tip;
}
There was a problem hiding this comment.
changed the comments as suggested (in the main commit)
| // Flag the remaining descendants as invalid: The marking in the disconnect loop only | ||
| // covers blocks that were already present in highpow_outofchain_headers when it was | ||
| // built, and it doesn't run at all if pindex never was in the active chain. | ||
| SetBlockFailureFlags(to_mark_failed); |
There was a problem hiding this comment.
b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:
Small optional optimization: descendants must have a greater height, so we can use block_index.nHeight > invalid_block->nHeight instead of the pointer comparison in SetBlockFailureFlags().
This still scans the whole index, but avoids calling GetAncestor() for entries at or below the invalidated height.
This patch assumes the PropagateBlockInvalidity() rename from my other suggestion.
Skip ancestor lookups at lower heights
diff --git a/src/validation.cpp b/src/validation.cpp
index 475d740b26..b219d9f2c2 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3789,7 +3789,7 @@ void Chainstate::PropagateBlockInvalidity(CBlockIndex* invalid_block)
AssertLockHeld(cs_main);
for (auto& [_, block_index] : m_blockman.m_block_index) {
- if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
+ if (block_index.nHeight > invalid_block->nHeight && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
block_index.nStatus |= BLOCK_FAILED_VALID;
m_blockman.m_dirty_blockindex.insert(&block_index);
}There was a problem hiding this comment.
decided not to do this here – since this can only be triggered by an invalid block with correct PoW, optimization doesn’t seem so important and I don't want to expand the scope further.
| LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__, | ||
| pindex->GetBlockHash().ToString(), pindex->nHeight, | ||
| log(pindex->nChainWork.getdouble()) / log(2.0), FormatISO8601DateTime(pindex->GetBlockTime())); | ||
| CBlockIndex* tip = m_chain.Tip(); |
There was a problem hiding this comment.
b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:
The tip lookup and assertion can be one line using Assert(m_chain.Tip()) and brace initialization.
We can also use std::log2(...) instead of log(...) / log(2.0).
Use Assert and log2 in the log code
diff --git a/src/validation.cpp b/src/validation.cpp
index b219d9f2c2..172de1c87a 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -69,6 +69,7 @@
#include <algorithm>
#include <cassert>
#include <chrono>
+#include <cmath>
#include <deque>
#include <numeric>
#include <optional>
@@ -1977,11 +1978,10 @@ void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationSta
LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
pindex->GetBlockHash().ToString(), pindex->nHeight,
- log(pindex->nChainWork.getdouble()) / log(2.0), FormatISO8601DateTime(pindex->GetBlockTime()));
- CBlockIndex* tip = m_chain.Tip();
- assert(tip);
+ std::log2(pindex->nChainWork.getdouble()), FormatISO8601DateTime(pindex->GetBlockTime()));
+ CBlockIndex* tip{Assert(m_chain.Tip())};
LogInfo("%s: current best=%s height=%d log2_work=%f date=%s", __func__,
- tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble()) / log(2.0),
+ tip->GetBlockHash().ToString(), m_chain.Height(), std::log2(tip->nChainWork.getdouble()),
FormatISO8601DateTime(tip->GetBlockTime()));
CheckForkWarningConditions();
}There was a problem hiding this comment.
didn't do this here, since this is just being copied, and the std::log2 suggestion should then also be applied elsewhere (UpdateTip)
| setBlockIndexCandidates.erase(pindex); | ||
| SetBlockFailureFlags(pindex); | ||
| if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) { | ||
| m_chainman.RecalculateBestHeader(); |
There was a problem hiding this comment.
b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:
As an optional cleanup in RecalculateBestHeader(), we can use std::views::values to access each CBlockIndex directly instead of entry.second.
We can also use (~val.nStatus & BLOCK_FAILED_VALID) for the single-flag check.
Simplify the best-header loop
diff --git a/src/validation.cpp b/src/validation.cpp
index 172de1c87a..f48c25604e 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -6359,9 +6359,9 @@ void ChainstateManager::RecalculateBestHeader()
{
AssertLockHeld(cs_main);
m_best_header = ActiveChain().Tip();
- for (auto& entry : m_blockman.m_block_index) {
- if (!(entry.second.nStatus & BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
- m_best_header = &entry.second;
+ for (auto& val : m_blockman.m_block_index | std::views::values) {
+ if ((~val.nStatus & BLOCK_FAILED_VALID) && m_best_header->nChainWork < val.nChainWork) {
+ m_best_header = &val;
}
}
}There was a problem hiding this comment.
also didn’t do this here to not extend the scope of this PR further.
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. Other known bug classes 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.
Since both failure flags and best header need to be recalculated after a block is marked as invalid, combine them. Also add an Assume that the block passed in is already marked as invalid. Co-authored-by: Lőrinc <[email protected]>
…ound InvalidChainFound is called from 3 spots: 1. from InvalidBlockFound 2. from ActivateBestChain, with the highest connectable block of the chain as an arg (after having called InvalidBlockFound already for the block that actually failed) 3. from InvalidateBlock Most of the logic in InvalidChainFound is not required for 2): In ActivateBestChain, we already called InvalidChainFound before via InvalidBlockFound, so only m_best_invalid needs updating. This would also result in duplicate log entries. Therefore move of all logic but the m_best_invalid update into InvalidBlockFound, avoiding duplicate logging and unnecessary work (the loop over the block index in PropagateBlockInvalidity was done twice before). Add it back to InvalidateBlock, which is only reachable via rpc. Add an Assume to ActivateBestChainStep to document that the highest block of the failed batch has already been marked as invalid by InvalidBlockFound. CheckForkWarningConditions is still called at the end of ActivateBestChainStep, after m_best_invalid has been updated. Co-authored-by: Lőrinc <[email protected]>
Instead of the messages for invalid block discovery, log a message specific to the invalidateblock rpc, so that the two situations can be distinguished in the log.
It's a more descriptive name after most of the logic was moved into InvalidBlockFound. -BEGIN VERIFY SCRIPT- sed -i 's/InvalidChainFound/UpdateBestInvalid/g' $(git grep -l 'InvalidChainFound' -- src) -END VERIFY SCRIPT-
The block is not new, so call it invalid_block instead.
ff06c05 to
de9e3f2
Compare
l0rinc
left a comment
There was a problem hiding this comment.
The changes are very easy to review as such, but concurrent reconsideration can still clear the invalidation root's failure flag while the lock is released: left a suggestion to report that interference to the RPC caller - and a few smaller suggestions to make the propagation and batch-tip contracts clearer in the code and fuzz target.
| void Chainstate::PropagateBlockInvalidity(CBlockIndex* invalid_block) | ||
| { | ||
| AssertLockHeld(cs_main); | ||
| Assume(invalid_block->nStatus & BLOCK_FAILED_VALID); |
There was a problem hiding this comment.
44de389 validation: combine SetBlockFailureFlags with the best header update:
Ralph also flagged that a concurrent reconsiderblock can clear the failure flag before the final phase of InvalidateBlock().
The existing active-chain check can still pass, so we can reach the new Assume() with the flag cleared.
Suggested diff
diff --git a/src/validation.cpp b/src/validation.cpp
index e4162ff987..cf253b62bd 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3661,6 +3661,8 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
return false;
}
+ if (pindex_was_in_chain && !(to_mark_failed->nStatus & BLOCK_FAILED_VALID)) return state.Error("Concurrent reconsiderblock cleared the failure flag");
+
// Mark pindex as invalid if it never was in the main chain
if (!pindex_was_in_chain && !(pindex->nStatus & BLOCK_FAILED_VALID)) {
pindex->nStatus |= BLOCK_FAILED_VALID;
| state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "consensus-invalid"); | ||
| chainman.InvalidBlockFound(block, state); | ||
| // This results in duplicate calls to InvalidChainFound, but mirrors the behavior in validation | ||
| // Mirror ActivateBestChainStep by also considering the highest block of the failed batch |
There was a problem hiding this comment.
fce2a8d validation: Move most logic from InvalidChainFound into InvalidBlockFound:
The fuzz target could mirror the new batch-tip check, it models activation without calling ActivateBestChainStep(), so the production Assume() never runs here.
Suggested diff
diff --git a/src/test/fuzz/block_index_tree.cpp b/src/test/fuzz/block_index_tree.cpp
index 60dd130dc8..3ae143902c 100644
--- a/src/test/fuzz/block_index_tree.cpp
+++ b/src/test/fuzz/block_index_tree.cpp
@@ -133,2 +133,3 @@ FUZZ_TARGET(block_index_tree, .init = initialize_block_index_tree)
chainman.InvalidBlockFound(block, state);
+ assert(to_connect.front()->nStatus & BLOCK_FAILED_VALID);
// Mirror ActivateBestChainStep by also considering the highest block of the failed batch| pindex->nStatus |= BLOCK_FAILED_VALID; | ||
| m_blockman.m_dirty_blockindex.insert(pindex); | ||
| setBlockIndexCandidates.erase(pindex); | ||
| PropagateBlockInvalidity(pindex); |
There was a problem hiding this comment.
fce2a8d validation: Move most logic from InvalidChainFound into InvalidBlockFound:
This swaps the order of the two calls in both callers. Unless there's a particular reason, keeping the old order would simplify the diff slightly, or the commit message could mention that they're synonymous.
Suggested diff
diff --git a/src/validation.cpp b/src/validation.cpp
index 5728bc9c62..e553bb1a18 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -1989,8 +1989,8 @@ void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationSta
pindex->nStatus |= BLOCK_FAILED_VALID;
m_blockman.m_dirty_blockindex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
- PropagateBlockInvalidity(pindex);
InvalidChainFound(pindex);
+ PropagateBlockInvalidity(pindex);
LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
pindex->GetBlockHash().ToString(), pindex->nHeight,
@@ -3685,13 +3685,13 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
}
}
+ InvalidChainFound(to_mark_failed);
+
// Flag the remaining descendants as invalid and update the best header: The marking in
// the disconnect loop only covers blocks that were already present in
// highpow_outofchain_headers when it was built, and it doesn't run at all if pindex
// never was in the active chain.
PropagateBlockInvalidity(to_mark_failed);
-
- InvalidChainFound(to_mark_failed);
LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
to_mark_failed->GetBlockHash().ToString(), to_mark_failed->nHeight,
log(to_mark_failed->nChainWork.getdouble()) / log(2.0), FormatISO8601DateTime(to_mark_failed->GetBlockTime()));| } | ||
|
|
||
| void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block) | ||
| void Chainstate::PropagateBlockInvalidity(CBlockIndex* invalid_block) |
There was a problem hiding this comment.
44de389 validation: combine SetBlockFailureFlags with the best header update:
CoreCheck pointed out that invalid_block can be a pointer to const, making it clear that the caller marks the root and this helper only updates descendants and the best header.
Suggested diff
diff --git a/src/validation.cpp b/src/validation.cpp
index 991f365740..d4b693ed2e 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3798,3 +3798,3 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
-void Chainstate::PropagateBlockInvalidity(CBlockIndex* invalid_block)
+void Chainstate::PropagateBlockInvalidity(const CBlockIndex* invalid_block)
{
diff --git a/src/validation.h b/src/validation.h
index 03d168af4e..0272644022 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -876,3 +876,3 @@ protected:
* and recalculate the best header if it was in that subtree */
- void PropagateBlockInvalidity(CBlockIndex* invalid_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
+ void PropagateBlockInvalidity(const CBlockIndex* invalid_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
| # Invalidating the first header must also mark its descendant as invalid and move the | ||
| # best header back to the tip of the active chain. | ||
| node.invalidateblock(header1.hash_hex) | ||
| chaintips = {chaintip["hash"]: chaintip["status"] for chaintip in node.getchaintips()} |
There was a problem hiding this comment.
1a6c04c test: functional test for invalidateblock of blocks not in chain:
We only need the status of the second header here. Could we use next() to find it without collecting all the tips?
Suggested diff
diff --git a/test/functional/rpc_invalidateblock.py b/test/functional/rpc_invalidateblock.py
index f63a0dd31b..3abd21f995 100755
--- a/test/functional/rpc_invalidateblock.py
+++ b/test/functional/rpc_invalidateblock.py
@@ -149,8 +149,8 @@ class InvalidateTest(BitcoinTestFramework):
# Invalidating the first header must also mark its descendant as invalid and move the
# best header back to the tip of the active chain.
node.invalidateblock(header1.hash_hex)
- chaintips = {chaintip["hash"]: chaintip["status"] for chaintip in node.getchaintips()}
- assert_equal(chaintips[header2.hash_hex], "invalid")
+ header2_status = next(tip["status"] for tip in node.getchaintips() if tip["hash"] == header2.hash_hex)
+ assert_equal(header2_status, "invalid")
assert_equal(node.getblockchaininfo()["headers"], tip_height)
assert_equal(node.getbestblockhash(), tip_hash)
| { | ||
| struct TestChainstate : public Chainstate { | ||
| void CallInvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main) | ||
| void CallUpdateBestInvalid(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main) |
There was a problem hiding this comment.
c54a8cc scripted-diff: rename InvalidChainFound to UpdateBestInvalid:
The rename also needs to catch CallInvalidChainFound, we could we use a word boundary at the end only to make it clear that prefixes are deliberately allowed.
Suggested scripted commit message
-BEGIN VERIFY SCRIPT-
sed -i 's/InvalidChainFound\b/UpdateBestInvalid/g' $(git grep -l 'InvalidChainFound' -- src)
-END VERIFY SCRIPT-
InvalidChainFound()is called from 3 spots:InvalidBlockFound()ActivateBestChain(), with the highest connectable block of the chainas an arg (after having called
InvalidBlockFound()already for the block that failed inConnectTip())InvalidateBlock()(rpc-only)Most of the logic in
InvalidChainFound()is not required for 2) and 3):In
ActivateBestChain(), the previous call toInvalidChainFound()before viaInvalidBlockFounddid the flag updates, best header calculation and logging, so onlym_best_invalidcould need additional updating.In
InvalidateBlock()(which doesn't callInvalidBlockFound()), we do most of the accounting manually.Therefore move of all logic but the
m_best_invalidupdate intoInvalidBlockFound(), avoiding duplicate logging and unnecessary work (the loops over the block index inSetBlockFailureFlags()andRecalculateBestHeader()were done twice before).
The second commit renames
InvalidChainFoundtoUpdateBestInvalidto adjust to its remaining role.This addresses past discussions about repeated work in
InvalidateBlock()(#31405 (comment)) andActivateBestChain()(#31533 (comment))