mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:50:37 +00:00
validation: Prevent duplicate logging and looping in invalid block handling #34254
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34254
Loading…
Reference in a new issue
No description provided.
Delete branch "202601_invalidchain"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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()(https://github.com/bitcoin/bitcoin/pull/31405#discussion_r2135717500) andActivateBestChain()(https://github.com/bitcoin/bitcoin/pull/31533#discussion_r2607189790)The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
No conflicts as of last run.
ACK 73e0bab7adb0b16b2ac4d13c9d601a04b7184749
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)nit: both
LogInfocalls could be formatted so the lines here have spaces?I think this can fail to set
m_best_invalidproperly sinceto_mark_failedwalks backwards (ifpindexis in the main chain) and thenUpdateBestInvalidis called after looping?Concept ACK on the overall refactoring approach.
I think this update is already handled by
InvalidBlockFound(), called from withinConnectTip(), so this second call is maybe unnecessary?It's slightly different, this second call might update
m_best_invalidto the last descendant in the chain.vpindexToConnectis iterated in reverse order, and this call is only a no-op if the last descendant is the one that failed inConnectTip.Ah, I see and understand it now. Thanks for clarifying
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_invalidis 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?done - applied clang-format to the commit.
73e0bab to f789d4f: applied clang-format
Brain-dump of what I think happens (haven't written a test) with InvalidateBlock calling InvalidChainFound in master:
InvalidChainFound will:
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:
BLOCK_FAILED_CHILD in the loop.
loop already updated it. If the best header is out-of-chain, it was not invalidated.
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):
marked as m_best_invalid instead of to_mark_failed, depending on what block the user calls InvalidateBlock on.
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?
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?
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.
Good catch! I think it should be possible to add these back to the
!pindex_was_in_chainconditional, 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 torpc_invalidateblock, because sincegithub.com/bitcoin/bitcoin@ed764ea2b4,CheckBlockIndexhas 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.
🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK. nice cleanup!
wondering if it’s also possible to avoid looping over the block index twice and instead combine this into a single pass?
BLOCK_FAILED_VALIDm_best_headeri guess doing it this way would make
m_best_headertemporarily inconsistent (for this chain: 1 ←2 ←3 ← 4 ← 5, intermediate states during the loop could have 3 still marked as invalid and 5 as them_best_header) but after the loop finishes it should be consistent.thinking of something like:
also since
RecalculateBestHeaderoriginally existed for reconsiderblock RPC before https://github.com/bitcoin/bitcoin/pull/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, sometimesm_best_invalid, and sometimes removing fromsetBlockIndexCandidates) 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.Ran both
masterand this branch on regtest with-debug=validationto confirm what changed in theinvalidateblocklogging.master:This branch:log2_work,date, and thecurrent bestline are gone. Also, the prefix changes fromInvalidChainFound:toInvalidated 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.
Ping @mzumsande for a rebase and some unaddressed review.
Thanks for the reminder, I'll update soon!
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.
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_chainsince during the earlier chain disconnecting we releasecs_main, and if any blocks would have been added by another thread, these could have been missed otherwise.f789d4f to ff06c05:
rebased and addressed comments - including adding a test for the case I missed in the earlier version. Sorry it took so long, I'll be much faster from now on.
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.
Good point. I mistakenly thought locking
m_chainstate_mutexprevented 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...crACK
ff06c05043I still am confused by how
InvalidateBlockbehaves in multi-threaded scenarios. I also thinkm_best_invalidcould be updated properly in a follow-up PR. This PR by itself is a good improvement toActivateBestChain.Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor · Concurrent
reconsiderblockcan trip the newAssumeSource inspection shows concurrent authenticated
invalidateblockandreconsiderblockcalls can now abort Debug or fuzz builds; the race predates this PR, and release builds do not enforce the newAssume.Location:
src/validation.cpp:3726(head).🔵 Suggestion · Duplicate invalid-block logging has no regression assertion
The new tests would still pass if
UpdateBestInvalidemitted the duplicate invalid-block messages again.Location:
src/validation.cpp:3255(head).Review coverage was incomplete.
Reviewed:
de9e3f2c69e7· Review report · Previous reportspermalink
ACK
ff06c05043Nit: Calling the block index entry
newis a bit confusing in my eyes. Maybe call thisinvalid_blockor something along the lines?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...)
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_failedcomment 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
This mixes low-risk logging changes with higher-risk work removal.
Could we split them into separate commits so we can review the duplicate removal on its own?
Could this be a scripted diff instead?
Scripted rename commit
After splitting this locally (as suggested in https://github.com/bitcoin/bitcoin/pull/34254#discussion_r4567574582), 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
InvalidBlockFound()andInvalidateBlock()both callSetBlockFailureFlags()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 inInvalidBlockFound(), so the two callers follow the same order.Propagate invalidity and update the best header
As an optional cleanup in
RecalculateBestHeader(), we can usestd::views::valuesto access eachCBlockIndexdirectly instead ofentry.second.We can also use
(~val.nStatus & BLOCK_FAILED_VALID)for the single-flag check.Simplify the best-header loop
The tip lookup and assertion can be one line using
Assert(m_chain.Tip())and brace initialization.We can also use
std::log2(...)instead oflog(...) / log(2.0).Use Assert and log2 in the log code
Small optional optimization: descendants must have a greater height, so we can use
block_index.nHeight > invalid_block->nHeightinstead of the pointer comparison inSetBlockFailureFlags().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
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
added a commit do to this. Did it by hand instead of a scripted diff because
pindexNewis very common.done in
5e71b29a36did it, but used Assume instead to lower (future) risk. This should be recoverable, since
FindMostWorkChaincan deal with indexes that were not marked invalid.done in
44de389855also added an
Assumethat the block is invalid.done, but I used
sedfor the scripted diff, which seems the more common choice.done.
changed the comments as suggested (in the main commit)
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.
didn't do this here, since this is just being copied, and the
std::log2suggestion should then also be applied elsewhere (UpdateTip)also didn’t do this here to not extend the scope of this PR further.
ff06c05 to de9e3f2:
Updated after Review - took the suggestion by @sedited and most of the comments by @lorinc.
That's a few more commits now, but the added ones are not very complicated.
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.
The fuzz target could mirror the new batch-tip check? It models activation without calling
ActivateBestChainStep(), so the productionAssume()never runs here.Suggested diff
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
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
The batch-tip update still feeds the fork warning at the end of
ActivateBestChainStep().feature_notifications.pycovers that case. Could we document that next to the batch-tip check?Suggested diff
CoreCheck pointed out that
invalid_blockcan be a pointer toconst, making it clear that the caller marks the root and this helper only updates descendants and the best header.Suggested diff
Ralph also flagged that a concurrent
reconsiderblockcan clear the failure flag before the final phase ofInvalidateBlock().The existing active-chain check can still pass, so we can reach the new
Assume()with the flag cleared.Suggested diff
We only need the status of the second header here. Could we use
next()to find it without collecting all the tips?Suggested diff