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

pull mzumsande wants to merge 3 commits into bitcoin:master from mzumsande:202601_invalidchain changing 6 files +64 −30
  1. mzumsande commented at 4:59 PM on January 11, 2026: contributor

    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)

  2. DrahtBot added the label Validation on Jan 11, 2026
  3. DrahtBot commented at 4:59 PM on January 11, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

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

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

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

  4. bensig commented at 9:48 PM on January 12, 2026: contributor

    ACK 73e0bab7adb0b16b2ac4d13c9d601a04b7184749

  5. in src/validation.cpp:2017 in c816490e82 outdated
    2029 | +        if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) {
    2030 | +            m_chainman.RecalculateBestHeader();
    2031 | +        }
    2032 | +
    2033 | +        LogInfo("%s: invalid block=%s  height=%d  log2_work=%f  date=%s\n", __func__,
    2034 | +        pindex->GetBlockHash().ToString(), pindex->nHeight,
    


    Crypt-iQ commented at 8:49 PM on January 20, 2026:

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


    mzumsande commented at 6:24 AM on February 1, 2026:

    done - applied clang-format to the commit.

  6. Crypt-iQ commented at 9:01 PM on January 20, 2026: contributor

    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)
  7. in src/validation.cpp:3737 in 73e0bab7ad outdated
    3733 | @@ -3733,7 +3734,10 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde
    3734 |              }
    3735 |          }
    3736 |  
    3737 | -        InvalidChainFound(to_mark_failed);
    3738 | +        UpdateBestInvalid(to_mark_failed);
    


    Crypt-iQ commented at 9:16 PM on January 20, 2026:

    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?


    mzumsande commented at 6:11 AM on February 1, 2026:

    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?


    Crypt-iQ commented at 8:31 PM on February 2, 2026:

    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 commented at 11:58 AM on February 12, 2026:

    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.


    mzumsande commented at 3:42 PM on August 19, 2026:

    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.


    Crypt-iQ commented at 7:21 PM on August 27, 2026:

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

  8. in src/validation.cpp:3305 in 73e0bab7ad outdated
    3301 | @@ -3301,7 +3302,7 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex*
    3302 |                  if (state.IsInvalid()) {
    3303 |                      // The block violates a consensus rule.
    3304 |                      if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    3305 | -                        InvalidChainFound(vpindexToConnect.front());
    3306 | +                        UpdateBestInvalid(vpindexToConnect.front());
    


    frankomosh commented at 11:34 AM on January 23, 2026:

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


    Crypt-iQ commented at 12:46 PM on January 23, 2026:

    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 commented at 6:54 AM on January 24, 2026:

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

  9. frankomosh commented at 11:42 AM on January 23, 2026: contributor

    Concept ACK on the overall refactoring approach.

  10. mzumsande force-pushed on Feb 1, 2026
  11. mzumsande commented at 6:25 AM on February 1, 2026: contributor

    73e0bab to f789d4f: applied clang-format

  12. DrahtBot added the label Needs rebase on Feb 18, 2026
  13. stratospher commented at 10:10 AM on March 24, 2026: contributor

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

  14. in src/validation.cpp:3738 in f789d4fa16
    3733 | @@ -3720,7 +3734,10 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde
    3734 |              }
    3735 |          }
    3736 |  
    3737 | -        InvalidChainFound(to_mark_failed);
    3738 | +        UpdateBestInvalid(to_mark_failed);
    3739 | +        LogInfo("Invalidated block: hash=%s height=%d\n",
    


    frankomosh commented at 7:06 AM on May 18, 2026:

    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.


    mzumsande commented at 3:39 PM on August 19, 2026:

    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.

  15. sedited commented at 7:33 PM on August 10, 2026: contributor

    Ping @mzumsande for a rebase and some unaddressed review.

  16. mzumsande commented at 4:06 PM on August 11, 2026: contributor

    Thanks for the reminder, I'll update soon!

  17. test: functional test for invalidateblock of blocks not in chain 3c16dc54e9
  18. validation: Move most logic from InvalidChainFound into InvalidBlockFound
    InvalidChainFound is called from 3 spots:
    1. from InvalidBlockFound
    2. from ActivateBestChain, with the highest connectable block of the chain
    as an arg (after having called InvalidBlockFound already for the block that
    actually failed)
    3. from InvalidateBlock
    
    Most of the logic in InvalidChainFound is not required for 2):
    In ActivateBestChain, we already called InvalidChainFound before via
    InvalidBlockFound, so only m_best_invalid needs updating. This would
    also result in duplicate log entries.
    
    Therefore move of all logic but the m_best_invalid update into
    InvalidBlockFound, avoiding duplicate logging and unnecessary work
    (the loops over the block index in SetBlockFailureFlags and RecalculateBestHeader
    were done twice before).
    Add it back to InvalidateBlock, which is only reachable via rpc.
    
    Also use a log message specific to invalidateblock there, instead of the
    one for invalid block discovery.
    b335786873
  19. validation: rename InvalidChainFound to UpdateBestInvalid
    It's a more descriptive name after most of the logic was moved
    into InvalidBlockFound.
    ff06c05043
  20. mzumsande force-pushed on Aug 19, 2026
  21. mzumsande commented at 3:56 PM on August 19, 2026: contributor

    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.

  22. DrahtBot removed the label Needs rebase on Aug 19, 2026
  23. Crypt-iQ commented at 7:43 PM on August 27, 2026: contributor

    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.

  24. DrahtBot requested review from stratospher on Aug 27, 2026
  25. DrahtBot requested review from frankomosh on Aug 27, 2026
  26. in src/validation.cpp:1974 in b335786873
    1969 | @@ -1970,39 +1970,40 @@ void Chainstate::CheckForkWarningConditions()
    1970 |      }
    1971 |  }
    1972 |  
    1973 | -// Called both upon regular invalid block discovery *and* InvalidateBlock
    1974 | +// Update m_best_invalid to track the invalid block with the most work
    1975 |  void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
    


    sedited commented at 12:20 PM on October 9, 2026:

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

  27. sedited approved
  28. sedited commented at 12:21 PM on October 9, 2026: contributor

    ACK ff06c05043bf2324085dd0a1969239a9fd19eda5

  29. sedited removed review request from frankomosh on Oct 9, 2026
  30. sedited requested review from stickies-v on Oct 9, 2026
  31. sedited referenced this in commit 92690e11fe on Nov 9, 2026
  32. sedited referenced this in commit 80de8c2647 on Nov 9, 2026
  33. sedited referenced this in commit 9adfc7a8b2 on Nov 9, 2026
  34. sedited referenced this in commit 14224b5e60 on Nov 10, 2026
  35. sedited referenced this in commit 165c3ef4ba on Nov 10, 2026
  36. sedited referenced this in commit 765d80aa85 on Nov 11, 2026
  37. sedited referenced this in commit 0173cd88d9 on Nov 11, 2026
  38. sedited referenced this in commit 3e5494bd63 on Nov 11, 2026
  39. sedited referenced this in commit e1da1d1a1f on Nov 11, 2026
  40. sedited referenced this in commit 4dfbb745de on Nov 12, 2026
  41. sedited referenced this in commit 0e95c753ee on Nov 12, 2026
  42. sedited requested review from l0rinc on Nov 12, 2026
  43. sedited referenced this in commit c03b1170ae on Nov 12, 2026
  44. sedited referenced this in commit cf4d0fa738 on Nov 12, 2026
  45. sedited referenced this in commit 6e063cf69d on Nov 13, 2026
  46. sedited referenced this in commit 89376e4665 on Nov 13, 2026
  47. in src/validation.cpp:1973 in b335786873 outdated
    1969 | @@ -1970,39 +1970,40 @@ void Chainstate::CheckForkWarningConditions()
    1970 |      }
    1971 |  }
    1972 |  
    1973 | -// Called both upon regular invalid block discovery *and* InvalidateBlock
    1974 | +// Update m_best_invalid to track the invalid block with the most work
    


    l0rinc commented at 7:17 PM on November 13, 2026:

    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?

  48. in src/validation.cpp:1992 in b335786873 outdated
    2004 |      AssertLockHeld(cs_main);
    2005 |      if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    2006 |          pindex->nStatus |= BLOCK_FAILED_VALID;
    2007 |          m_blockman.m_dirty_blockindex.insert(pindex);
    2008 |          setBlockIndexCandidates.erase(pindex);
    2009 | +        SetBlockFailureFlags(pindex);
    


    l0rinc commented at 7:17 PM on November 13, 2026:

    b335786 validation: Move most logic from InvalidChainFound into InvalidBlockFound:

    After splitting this locally (as suggested in #34254 (review)), 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 --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>

  49. in src/validation.cpp:1993 in b335786873 outdated
    2005 |      if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    2006 |          pindex->nStatus |= BLOCK_FAILED_VALID;
    2007 |          m_blockman.m_dirty_blockindex.insert(pindex);
    2008 |          setBlockIndexCandidates.erase(pindex);
    2009 | +        SetBlockFailureFlags(pindex);
    2010 | +        if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) {
    


    l0rinc commented at 7:18 PM on November 13, 2026:

    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.

    <details> <summary>Propagate invalidity and update the best header</summary>

    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>

  50. in src/validation.cpp:1974 in ff06c05043
    1969 | @@ -1970,39 +1970,40 @@ void Chainstate::CheckForkWarningConditions()
    1970 |      }
    1971 |  }
    1972 |  
    1973 | -// Called both upon regular invalid block discovery *and* InvalidateBlock
    1974 | -void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
    1975 | +// Update m_best_invalid to track the invalid block with the most work
    1976 | +void Chainstate::UpdateBestInvalid(CBlockIndex* pindexNew)
    


    l0rinc commented at 7:20 PM on November 13, 2026:

    ff06c05 validation: rename InvalidChainFound to UpdateBestInvalid:

    Could this be a scripted diff instead?

    <details> <summary>Scripted rename commit</summary>

    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>

  51. in test/functional/rpc_invalidateblock.py:144 in 3c16dc54e9 outdated
     139 | +        node = self.nodes[1]
     140 | +        tip_hash = node.getbestblockhash()
     141 | +        tip_height = node.getblockcount()
     142 | +        # Submit two headers building on the tip
     143 | +        block_time = node.getblock(tip_hash)["time"] + 1
     144 | +        header1 = create_block(int(tip_hash, 16), height=tip_height + 1, ntime=block_time)
    


    l0rinc commented at 7:22 PM on November 13, 2026:

    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.

    <details> <summary>Reuse the existing fork helper</summary>

    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>

  52. in src/test/fuzz/block_index_tree.cpp:134 in ff06c05043
     130 | @@ -131,8 +131,8 @@ FUZZ_TARGET(block_index_tree, .init = initialize_block_index_tree)
     131 |                                  BlockValidationState state;
     132 |                                  state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "consensus-invalid");
     133 |                                  chainman.InvalidBlockFound(block, state);
     134 | -                                // This results in duplicate calls to InvalidChainFound, but mirrors the behavior in validation
     135 | -                                chainman.InvalidChainFound(to_connect.front());
     136 | +                                // This results in duplicate calls to UpdateBestInvalid, but mirrors the behavior in validation
    


    l0rinc commented at 7:26 PM on November 13, 2026:

    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.

    <details> <summary>Refresh the invalid-chain names and comments</summary>

    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>

  53. in src/validation.cpp:3691 in b335786873 outdated
    3684 | @@ -3684,7 +3685,18 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const
    3685 |              }
    3686 |          }
    3687 |  
    3688 | +        // Flag the remaining descendants as invalid: The marking in the disconnect loop only
    3689 | +        // covers blocks that were already present in highpow_outofchain_headers when it was
    3690 | +        // built, and it doesn't run at all if pindex never was in the active chain.
    3691 | +        SetBlockFailureFlags(to_mark_failed);
    


    l0rinc commented at 7:28 PM on November 13, 2026:

    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.

    <details> <summary>Skip ancestor lookups at lower heights</summary>

    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>

  54. in src/validation.cpp:2000 in b335786873 outdated
    2012 | +        }
    2013 | +
    2014 | +        LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
    2015 | +                pindex->GetBlockHash().ToString(), pindex->nHeight,
    2016 | +                log(pindex->nChainWork.getdouble()) / log(2.0), FormatISO8601DateTime(pindex->GetBlockTime()));
    2017 | +        CBlockIndex* tip = m_chain.Tip();
    


    l0rinc commented at 7:28 PM on November 13, 2026:

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

    <details> <summary>Use Assert and log2 in the log code</summary>

    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>

  55. in src/validation.cpp:1994 in b335786873 outdated
    2006 |          pindex->nStatus |= BLOCK_FAILED_VALID;
    2007 |          m_blockman.m_dirty_blockindex.insert(pindex);
    2008 |          setBlockIndexCandidates.erase(pindex);
    2009 | +        SetBlockFailureFlags(pindex);
    2010 | +        if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex) {
    2011 | +            m_chainman.RecalculateBestHeader();
    


    l0rinc commented at 7:28 PM on November 13, 2026:

    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.

    <details> <summary>Simplify the best-header loop</summary>

    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>

  56. l0rinc changes_requested
  57. l0rinc commented at 7:35 PM on November 13, 2026: contributor

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

  58. DrahtBot requested review from frankomosh on Nov 13, 2026

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-16 00:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me