validation: Prevent duplicate logging and looping in invalid block handling #34254

Open
mzumsande wants to merge 6 commits from 202601_invalidchain into master AGit
mzumsande commented 2026-01-11 16:59:21 +00:00 (Migrated from github.com)

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 failed in ConnectTip())
  3. from InvalidateBlock() (rpc-only)

Most of the logic in InvalidChainFound() is not required for 2) and 3):
In ActivateBestChain(), the previous call to InvalidChainFound() before via InvalidBlockFound did the flag updates, best header calculation and logging, so only m_best_invalid could need additional updating.
In InvalidateBlock() (which doesn't call InvalidBlockFound()), we do most of the accounting manually.

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

The second commit renames InvalidChainFound to UpdateBestInvalid to adjust to its remaining role.

This addresses past discussions about repeated work in InvalidateBlock() (https://github.com/bitcoin/bitcoin/pull/31405#discussion_r2135717500) and ActivateBestChain() (https://github.com/bitcoin/bitcoin/pull/31533#discussion_r2607189790)

`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 failed in `ConnectTip()`) 3. from `InvalidateBlock()` (rpc-only) Most of the logic in `InvalidChainFound()` is not required for 2) and 3): In `ActivateBestChain()`, the previous call to `InvalidChainFound()` before via `InvalidBlockFound` did the flag updates, best header calculation and logging, so only `m_best_invalid` could need additional updating. In `InvalidateBlock()` (which doesn't call `InvalidBlockFound()`), we do most of the accounting manually. 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). The second commit renames `InvalidChainFound` to `UpdateBestInvalid` to adjust to its remaining role. This addresses past discussions about repeated work in `InvalidateBlock()` (https://github.com/bitcoin/bitcoin/pull/31405#discussion_r2135717500) and `ActivateBestChain()` (https://github.com/bitcoin/bitcoin/pull/31533#discussion_r2607189790)
DrahtBot commented 2026-01-11 16:59:27 +00:00 (Migrated from github.com)

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

External sites

Reviews

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

Type Reviewers
Concept ACK frankomosh, stratospher, l0rinc
Stale ACK bensig, Crypt-iQ, sedited

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/34254 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/34254.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/34254#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [frankomosh](https://github.com/bitcoin/bitcoin/pull/34254#pullrequestreview-3697084304), [stratospher](https://github.com/bitcoin/bitcoin/pull/34254#pullrequestreview-3997887968), [l0rinc](https://github.com/bitcoin/bitcoin/pull/34254#pullrequestreview-5896694942) | | Stale ACK | [bensig](https://github.com/bitcoin/bitcoin/pull/34254#issuecomment-3740651522), [Crypt-iQ](https://github.com/bitcoin/bitcoin/pull/34254#issuecomment-5444370723), [sedited](https://github.com/bitcoin/bitcoin/pull/34254#pullrequestreview-5469927989) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3-->
bensig commented 2026-01-12 21:48:39 +00:00 (Migrated from github.com)

ACK 73e0bab7adb0b16b2ac4d13c9d601a04b7184749

ACK 73e0bab7adb0b16b2ac4d13c9d601a04b7184749
Crypt-iQ (Migrated from github.com) reviewed 2026-01-20 21:01:10 +00:00
Crypt-iQ (Migrated from github.com) left a comment

This looks good, going to think about it more. I think the noticeable changes here are that:

  • InvalidateBlock won't have warnings anymore since CheckForkWarningConditions is no longer called (this seems fine, the warnings mention falling out of consensus which is irrelevant here imo)
  • ActivateBestChainStep does not duplicate logging / work (also fine)
This looks good, going to think about it more. I think the noticeable changes here are that: - ~~`InvalidateBlock` won't have warnings anymore since `CheckForkWarningConditions` is no longer called (this seems fine, the warnings mention falling out of consensus which is irrelevant here imo)~~ - `ActivateBestChainStep` does not duplicate logging / work (also fine)
Crypt-iQ (Migrated from github.com) commented 2026-01-20 20:49:32 +00:00

nit: both LogInfo calls could be formatted so the lines here have spaces?

nit: both `LogInfo` calls could be formatted so the lines here have spaces?
Crypt-iQ (Migrated from github.com) reviewed 2026-01-20 21:16:26 +00:00
Crypt-iQ (Migrated from github.com) commented 2026-01-20 21:16:26 +00:00

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?

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?
frankomosh (Migrated from github.com) reviewed 2026-01-23 11:42:36 +00:00
frankomosh (Migrated from github.com) left a comment

Concept ACK on the overall refactoring approach.

Concept ACK on the overall refactoring approach.
frankomosh (Migrated from github.com) commented 2026-01-23 11:34:31 +00:00

I think this update is already handled by InvalidBlockFound(), called from within ConnectTip(), so this second call is maybe unnecessary?

I think this update is already handled by `InvalidBlockFound()`, called from within `ConnectTip()`, so this second call is maybe unnecessary?
Crypt-iQ (Migrated from github.com) reviewed 2026-01-23 12:46:34 +00:00
Crypt-iQ (Migrated from github.com) commented 2026-01-23 12:46:34 +00:00

It's slightly different, this second call might update m_best_invalid to the last descendant in the chain. vpindexToConnect is iterated in reverse order, and this call is only a no-op if the last descendant is the one that failed in ConnectTip.

It's slightly different, this second call might update `m_best_invalid` to the last descendant in the chain. `vpindexToConnect` is iterated in reverse order, and this call is only a no-op if the last descendant is the one that failed in `ConnectTip`.
frankomosh (Migrated from github.com) reviewed 2026-01-24 06:54:10 +00:00
frankomosh (Migrated from github.com) commented 2026-01-24 06:54:10 +00:00

Ah, I see and understand it now. Thanks for clarifying

Ah, I see and understand it now. Thanks for clarifying
mzumsande (Migrated from github.com) reviewed 2026-02-01 06:11:09 +00:00
mzumsande (Migrated from github.com) commented 2026-02-01 06:11:09 +00:00

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?

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?
mzumsande (Migrated from github.com) reviewed 2026-02-01 06:24:33 +00:00
mzumsande (Migrated from github.com) commented 2026-02-01 06:24:33 +00:00

done - applied clang-format to the commit.

done - applied clang-format to the commit.
mzumsande commented 2026-02-01 06:25:01 +00:00 (Migrated from github.com)

73e0bab to f789d4f: applied clang-format

[73e0bab](https://github.com/bitcoin/bitcoin/commit/73e0bab7adb0b16b2ac4d13c9d601a04b7184749) to [f789d4f](https://github.com/bitcoin/bitcoin/commit/f789d4fa160ee53145555c6d068b7dd3a23e88be): applied clang-format
Crypt-iQ (Migrated from github.com) reviewed 2026-02-02 20:31:31 +00:00
Crypt-iQ (Migrated from github.com) commented 2026-02-02 20:31:31 +00:00

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.

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

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 github.com/bitcoin/bitcoin@ed764ea2b4, 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.

> 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 https://github.com/bitcoin/bitcoin/commit/ed764ea2b4edb3cf1925a4bff5f39567a8be54ac, `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.
DrahtBot commented 2026-02-18 17:06:15 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
stratospher (Migrated from github.com) reviewed 2026-03-24 10:10:06 +00:00
stratospher (Migrated from github.com) left a 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?

  1. 1st iteration through block index to set BLOCK_FAILED_VALID
  2. 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 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, 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.

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? 1. 1st iteration through block index to set `BLOCK_FAILED_VALID` 2. 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 since`RecalculateBestHeader` originally 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`, sometimes `m_best_invalid`, and sometimes removing from `setBlockIndexCandidates`) being performed from different places across the code, I have a [summary sheet here](https://gist.github.com/stratospher/6e4a1ef0a7ceec3319533e36fdf09e5e) - hopefully it 's not too hard to follow and makes things easier to reason about.
frankomosh (Migrated from github.com) reviewed 2026-05-18 07:06:36 +00:00
frankomosh (Migrated from github.com) commented 2026-05-18 07:06:36 +00:00

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.

Ran both `master` and this branch on regtest with `-debug=validation` to confirm what changed in the `invalidateblock` logging. `master`: ```text 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`: ```text 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.
sedited commented 2026-08-10 19:33:58 +00:00 (Migrated from github.com)

Ping @mzumsande for a rebase and some unaddressed review.

Ping @mzumsande for a rebase and some unaddressed review.
mzumsande commented 2026-08-11 16:06:07 +00:00 (Migrated from github.com)

Thanks for the reminder, I'll update soon!

Thanks for the reminder, I'll update soon!
mzumsande (Migrated from github.com) reviewed 2026-08-19 15:39:16 +00:00
mzumsande (Migrated from github.com) commented 2026-08-19 15:39:16 +00:00

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.

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.
mzumsande (Migrated from github.com) reviewed 2026-08-19 15:42:22 +00:00
mzumsande (Migrated from github.com) commented 2026-08-19 15:42:22 +00:00

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.

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.
mzumsande commented 2026-08-19 15:56:27 +00:00 (Migrated from github.com)

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.

wondering if it’s also possible to avoid looping over the block index twice and instead combine this into a single pass?

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.

[f789d4f](https://github.com/bitcoin/bitcoin/commit/f789d4fa160ee53145555c6d068b7dd3a23e88be) to [ff06c05](https://github.com/bitcoin/bitcoin/commit/ff06c05043bf2324085dd0a1969239a9fd19eda5): 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. > wondering if it’s also possible to avoid looping over the block index twice and instead combine this into a single pass? 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.
Crypt-iQ (Migrated from github.com) reviewed 2026-08-27 19:21:55 +00:00
Crypt-iQ (Migrated from github.com) commented 2026-08-27 19:21:55 +00:00

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

> 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...
Crypt-iQ commented 2026-08-27 19:43:45 +00:00 (Migrated from github.com)

crACK ff06c05043

I still am confused by how InvalidateBlock behaves in multi-threaded scenarios. I also think m_best_invalid could be updated properly in a follow-up PR. This PR by itself is a good improvement to ActivateBestChain.

crACK ff06c05043bf2324085dd0a1969239a9fd19eda5 I still am confused by how `InvalidateBlock` behaves in multi-threaded scenarios. I also think `m_best_invalid` could be updated properly in a follow-up PR. This PR by itself is a good improvement to `ActivateBestChain`.
First-time contributor

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.

🟠 Minor · Concurrent reconsiderblock can trip the new Assume

Source inspection shows concurrent authenticated invalidateblock and reconsiderblock calls can now abort Debug or fuzz builds; the race predates this PR, and release builds do not enforce the new Assume.

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

🔵 Suggestion · Duplicate invalid-block logging has no regression assertion

The new tests would still pass if UpdateBestInvalid emitted the duplicate invalid-block messages again.

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

Review coverage was incomplete.


Reviewed: de9e3f2c69e7 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:58e9d98f3110c6e759f3148d974305b843fed33c --> <!-- ralph-head:de9e3f2c69e7704592f691217c305eb2ac44af0f --> <!-- ralph-case:61e8707440db7ec06b71a512eeb2d3bbb05b39ada690cea7fa91c65071a0cd92 --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · Concurrent `reconsiderblock` can trip the new `Assume`** Source inspection shows concurrent authenticated `invalidateblock` and `reconsiderblock` calls can now abort Debug or fuzz builds; the race predates this PR, and release builds do not enforce the new `Assume`. Location: [`src/validation.cpp:3726`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/de9e3f2c69e7704592f691217c305eb2ac44af0f/src/validation.cpp#L3726>) (head). **🔵 Suggestion · Duplicate invalid-block logging has no regression assertion** The new tests would still pass if `UpdateBestInvalid` emitted the duplicate invalid-block messages again. Location: [`src/validation.cpp:3255`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/de9e3f2c69e7704592f691217c305eb2ac44af0f/src/validation.cpp#L3255>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`de9e3f2c69e7`](<https://git.fish.foo/bitcoin/bitcoin/commit/de9e3f2c69e7704592f691217c305eb2ac44af0f>) · [Review report](<https://review.fish.foo/report/34254-de9e3f2c69e7704592f691217c305eb2ac44af0f-3269-2.html>) · [Previous reports](<https://review.fish.foo/traces/34254/>) [permalink](<https://review.fish.foo/report/34254-de9e3f2c69e7704592f691217c305eb2ac44af0f-3269-2.html>)
sedited (Migrated from github.com) approved these changes 2026-10-09 12:21:30 +00:00
sedited (Migrated from github.com) left a comment
ACK ff06c05043bf2324085dd0a1969239a9fd19eda5
sedited (Migrated from github.com) commented 2026-10-09 12:20:54 +00:00

Nit: Calling the block index entry new is a bit confusing in my eyes. Maybe call this invalid_block or something along the lines?

Nit: Calling the block index entry `new` is a bit confusing in my eyes. Maybe call this `invalid_block` or something along the lines?
l0rinc (Migrated from github.com) requested changes 2026-11-13 19:35:48 +00:00
l0rinc (Migrated from github.com) left a 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...)

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...)
l0rinc (Migrated from github.com) commented 2026-11-13 19:26:59 +00:00

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;
     }
 
> [ff06c05](https://github.com/bitcoin/bitcoin/pull/34254/changes/ff06c05043bf2324085dd0a1969239a9fd19eda5) _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. <details> <summary>Refresh the invalid-chain names and comments</summary> ```diff 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; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:17:36 +00:00

b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:

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?

> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _validation: Move most logic from InvalidChainFound into InvalidBlockFound_: 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?
l0rinc (Migrated from github.com) commented 2026-11-13 19:20:58 +00:00

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-
> [ff06c05](https://github.com/bitcoin/bitcoin/pull/34254/changes/ff06c05043bf2324085dd0a1969239a9fd19eda5) _validation: rename InvalidChainFound to UpdateBestInvalid_: Could this be a scripted diff instead? <details> <summary>Scripted rename commit</summary> ```bash 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- ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:17:47 +00:00

b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:

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
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();
> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _validation: Move most logic from InvalidChainFound into InvalidBlockFound_: 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. <details> <summary>Assert the failed batch tip is already marked invalid</summary> ```diff 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(); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:18:49 +00:00

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);
> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _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. <details> <summary>Propagate invalidity and update the best header</summary> ```diff 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); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:28:48 +00:00

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;
         }
     }
 }
> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _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. <details> <summary>Simplify the best-header loop</summary> ```diff 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; } } } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:28:32 +00:00

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();
     }
> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _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)`. <details> <summary>Use Assert and log2 in the log code</summary> ```diff 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(); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:28:15 +00:00

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);
         }
> [b335786](https://github.com/bitcoin/bitcoin/pull/34254/changes/b335786873cfffd75a98163cf36cfaadd9419b53) _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. <details> <summary>Skip ancestor lookups at lower heights</summary> ```diff 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); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-13 19:22:47 +00:00

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
> [3c16dc5](https://github.com/bitcoin/bitcoin/pull/34254/changes/3c16dc54e9697df8fdebbcbbe75f6b171ef76c76) _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. <details> <summary>Reuse the existing fork helper</summary> ```diff 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 ``` </details>
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:30:30 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:30:30 +00:00

added a commit do to this. Did it by hand instead of a scripted diff because pindexNew is very common.

added a commit do to this. Did it by hand instead of a scripted diff because `pindexNew` is very common.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:31:15 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:31:15 +00:00

done in 5e71b29a36

done in 5e71b29a369c61a3a05d755820434852cb1e58ef
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:33:02 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:33:02 +00:00

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.

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.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:34:56 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:34:56 +00:00

done in 44de389855
also added an Assume that the block is invalid.

done in 44de3898557ede67f5217def5f201222c2c15d81 also added an `Assume` that the block is invalid.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:35:45 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:35:45 +00:00

done, but I used sed for the scripted diff, which seems the more common choice.

done, but I used `sed` for the scripted diff, which seems the more common choice.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:36:00 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:36:00 +00:00

done.

done.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:36:45 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:36:45 +00:00

changed the comments as suggested (in the main commit)

changed the comments as suggested (in the main commit)
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:37:28 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:37:28 +00:00

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.

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.
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:38:35 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:38:35 +00:00

didn't do this here, since this is just being copied, and the std::log2 suggestion should then also be applied elsewhere (UpdateTip)

didn't do this here, since this is just being copied, and the `std::log2` suggestion should then also be applied elsewhere (`UpdateTip`)
mzumsande (Migrated from github.com) reviewed 2026-11-27 16:38:55 +00:00
mzumsande (Migrated from github.com) commented 2026-11-27 16:38:55 +00:00

also didn’t do this here to not extend the scope of this PR further.

also didn’t do this here to not extend the scope of this PR further.
mzumsande commented 2026-11-27 16:40:30 +00:00 (Migrated from github.com)

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.

[ff06c05](https://github.com/bitcoin/bitcoin/commit/ff06c05043bf2324085dd0a1969239a9fd19eda5) to [de9e3f2](https://github.com/bitcoin/bitcoin/commit/de9e3f2c69e7704592f691217c305eb2ac44af0f): 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.
l0rinc (Migrated from github.com) requested changes 2026-12-03 13:07:16 +00:00
l0rinc (Migrated from github.com) left a 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.

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.
l0rinc (Migrated from github.com) commented 2026-12-03 12:55:05 +00:00

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
> [fce2a8d](https://github.com/bitcoin/bitcoin/pull/34254/changes/fce2a8d5334162cba0a7f1badcca45a7e2699576) _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. <details><summary>Suggested diff</summary> ```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 ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 13:03:55 +00:00

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
scripted-diff: rename InvalidChainFound to UpdateBestInvalid

It's a more descriptive name after most of the logic was moved
into InvalidBlockFound.

-BEGIN VERIFY SCRIPT-
sed -i 's/InvalidChainFound\b/UpdateBestInvalid/g' $(git grep -l 'InvalidChainFound' -- src)
-END VERIFY SCRIPT-
> [c54a8cc](https://github.com/bitcoin/bitcoin/pull/34254/changes/c54a8ccef6d45ec07fb2ee8ad58a43672e4284ee) _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. <details><summary>Suggested scripted commit message</summary> ```text scripted-diff: rename InvalidChainFound to UpdateBestInvalid It's a more descriptive name after most of the logic was moved into InvalidBlockFound. -BEGIN VERIFY SCRIPT- sed -i 's/InvalidChainFound\b/UpdateBestInvalid/g' $(git grep -l 'InvalidChainFound' -- src) -END VERIFY SCRIPT- ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 12:57:27 +00:00

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()));
> [fce2a8d](https://github.com/bitcoin/bitcoin/pull/34254/changes/fce2a8d5334162cba0a7f1badcca45a7e2699576) _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. <details><summary>Suggested diff</summary> ```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())); ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 12:57:17 +00:00

The batch-tip update still feeds the fork warning at the end of ActivateBestChainStep(). feature_notifications.py covers that case. Could we document that next to the batch-tip check?

Suggested diff
diff --git a/src/validation.cpp b/src/validation.cpp
index 9947505b8f..c5a5bc961e 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3326,2 +3326,3 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex&
                         // failed block and all of its descendants as invalid.
+                        // The final fork-warning check also considers the work at the batch tip.
                         Assume(vpindexToConnect.front()->nStatus & BLOCK_FAILED_VALID);
The batch-tip update still feeds the fork warning at the end of `ActivateBestChainStep()`. `feature_notifications.py` covers that case. Could we document that next to the batch-tip check? <details><summary>Suggested diff</summary> ```diff diff --git a/src/validation.cpp b/src/validation.cpp index 9947505b8f..c5a5bc961e 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -3326,2 +3326,3 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& // failed block and all of its descendants as invalid. + // The final fork-warning check also considers the work at the batch tip. Assume(vpindexToConnect.front()->nStatus & BLOCK_FAILED_VALID); ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 12:57:36 +00:00

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);
 
> [44de389](https://github.com/bitcoin/bitcoin/pull/34254/changes/44de3898557ede67f5217def5f201222c2c15d81) _validation: combine SetBlockFailureFlags with the best header update_: [CoreCheck](https://corecheck.dev/bitcoin/bitcoin/pulls/34254) 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. <details><summary>Suggested diff</summary> ```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); ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 12:52:14 +00:00

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;
> [44de389](https://github.com/bitcoin/bitcoin/pull/34254/changes/44de3898557ede67f5217def5f201222c2c15d81) _validation: combine SetBlockFailureFlags with the best header update_: [Ralph](https://review.fish.foo/report/34254-de9e3f2c69e7704592f691217c305eb2ac44af0f-3269-2.html) 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. <details><summary>Suggested diff</summary> ```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; ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 12:57:43 +00:00

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)
 
> [1a6c04c](https://github.com/bitcoin/bitcoin/pull/34254/changes/1a6c04c9228aba9fbdd91111d2dc5391996006b9) _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? <details><summary>Suggested diff</summary> ```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) ``` </details>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!34254
No description provided.