util: Add and use AssertUnreachable #36087

pull maflcko wants to merge 6 commits into bitcoin:master from maflcko:2608-unreachable changing 84 files +274 −264
  1. maflcko commented at 5:24 AM on August 26, 2026: member

    The current code uses assertions with falsy literal values in a few places. This is perfectly fine, but this comes with a bit of confusion sometimes:

    • assert(false) may cause confusion when it is unclear if NDEBUG can disable it. (The intention is to disallow NDEBUG compilation). Also, it can lead to warnings when used with clang-cl.exe (GCC seems to understand it)
    • Assert(false) hides the noreturn attribute behind a function call, which may cause GCC return-type warnings. (Clang seems to understand it)

    See https://godbolt.org/z/h7PT3jh3Y for the clang-cl/GCC warning reproducer.

    • When C++23 will be allowed, devs may prefer std::unreachable. However, this is unsafe and will invoke UB.
    • There is confusion why a CHECK_NONFATAL macro exists, but no fatal equivalent.

    Fix all those issues by:

    • Adding a new AssertUnreachable, which directly calls the noreturn internal_abort_helper helper.
    • Adding an assert_falsy linter to enforce code to use this macro.
  2. DrahtBot added the label Utils/log/libs on Aug 26, 2026
  3. DrahtBot commented at 5:24 AM on August 26, 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 l0rinc, hodlinator, jeanpablojp, ryanofsky
    Stale ACK hebasto

    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

    Reviewers, this pull request conflicts with the following ones:

    • #bitcoin-core/gui/945 <sub><img src="https://drahtbot.space/ack_count/bitcoin-core/gui/945.svg"></sub> (Fix sign message address book filtering by Bushstar)
    • #36897 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36897.svg"></sub> (wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes by achow101)
    • #36808 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36808.svg"></sub> (iwyu: Fix warnings in src/test/fuzz and treat them as errors by hebasto)
    • #36689 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36689.svg"></sub> (cli: Parse -signetchallenge like bitcoind by ekzyis)
    • #36598 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36598.svg"></sub> ([Demo] validation: remove AssumeUTXO by l0rinc)
    • #36549 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36549.svg"></sub> (WIP: improve MallocUsage and test in CI by sipa)
    • #36434 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36434.svg"></sub> (http: support unix sockets by pinheadmz)
    • #36122 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36122.svg"></sub> (BIP460: CISA for Taproot key path spends by fjahr)
    • #35911 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35911.svg"></sub> (Warn on and add missing [[noreturn]] by fanquake)
    • #35713 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35713.svg"></sub> (Remove boost as a unit test runner by rustaceanrob)
    • #35302 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35302.svg"></sub> (Silent Payments: Sending (take 2) by Eunovo)
    • #34909 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34909.svg"></sub> (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux)
    • #34193 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34193.svg"></sub> (wallet: make migration more robust against failures by furszy)
    • #34132 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34132.svg"></sub> (coins,dbwrapper: make point-read and txindex lookup failures fatal by l0rinc)
    • #32575 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/32575.svg"></sub> (consensus: Remove special treatment for single threaded script checking by fjahr)
    • #31252 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31252.svg"></sub> (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa)

    If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  4. maflcko force-pushed on Aug 26, 2026
  5. maflcko marked this as a draft on Aug 26, 2026
  6. DrahtBot added the label CI failed on Aug 26, 2026
  7. DrahtBot commented at 5:45 AM on August 26, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task lint: https://github.com/bitcoin/bitcoin/actions/runs/32933915544/job/98071384264</sub> <sub>LLM reason (✨ experimental): CI failed because the assert_falsy lint check detected an assert(0 && ...) (in src/tinyformat.h) that must be replaced with AssertUnreachable().</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  8. DrahtBot added the label Needs rebase on Aug 26, 2026
  9. maflcko force-pushed on Aug 26, 2026
  10. maflcko force-pushed on Aug 26, 2026
  11. DrahtBot removed the label Needs rebase on Aug 26, 2026
  12. DrahtBot added the label Needs rebase on Aug 29, 2026
  13. maflcko force-pushed on Aug 29, 2026
  14. maflcko force-pushed on Aug 29, 2026
  15. DrahtBot removed the label Needs rebase on Aug 29, 2026
  16. jeanpablojp commented at 5:37 PM on August 29, 2026: contributor

    Left 3 comments.

  17. in src/script/interpreter.cpp:414 in e8d53b989d outdated
     410 | @@ -411,7 +411,7 @@ static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::con
     411 |          // Key path spending in Taproot has no script, so this is unreachable.
     412 |          break;
     413 |      }
     414 | -    assert(false);
     415 | +    AssertUnreachable();
    


    jeanpablojp commented at 5:37 PM on August 29, 2026:

    AssertUnreachable here and in SignatureHashSchnorr calls assertion_fail from util/check.cpp. This file is in libbitcoin_consensus, which should only depend on crypto. Normal builds hide it, bitcoin_common pulls util in anyway, but the riscv job links the lib standalone and breaks. Exclude consensus from assert_falsy under the same "not linking the util lib" reason, or move assertion_fail?


    maflcko commented at 7:09 AM on September 1, 2026:

    Thx, will fix this some time before taking out of draft.


    maflcko commented at 7:33 PM on November 10, 2026:

    thx, excluded for now

  18. in test/lint/test_runner/src/lint_cpp.rs:189 in e8d53b989d
     184 | +    let found = git()
     185 | +        .args([
     186 | +            "grep",
     187 | +            "--line-number",
     188 | +            "--extended-regexp",
     189 | +            r"\<(a|A)ssert\((0|false)( &&|\))",
    


    jeanpablojp commented at 5:37 PM on August 29, 2026:

    The message says any falsy literal, but the regex hardcodes the spacing, so assert (false), assert(false ) and assert(0&&"x") all slip through. \<(a|A)ssert\s*\(\s*(0|false)\s*(&&|\)) catches them. And std_unreachable lets __builtin_unreachable() through. libstdc++ implements std::unreachable() as exactly that, and it builds under C++20 where std::unreachable() doesn't. Worth catching the builtin too?


    maflcko commented at 7:08 AM on September 1, 2026:

    \<(a|A)ssert\s*\(\s*(0|false)\s*(&&|\))

    Thx, used that.

    __builtin_unreachable

    I think the risk of someone using it should be low, because it is a compiler-specific built-in.

  19. in test/lint/test_runner/src/main.rs:78 in e8d53b989d outdated
      72 | @@ -73,6 +73,16 @@ fn get_linter_list() -> Vec<&'static Linter> {
      73 |              name: "rpc_assert",
      74 |              lint_fn: lint_rpc_assert
      75 |          },
      76 | +        &Linter {
      77 | +            description: "Check that assertions with falsy literal values are not used",
      78 | +            name: "assert_falsy",
    


    jeanpablojp commented at 5:37 PM on August 29, 2026:

    The scripted-diff that satisfies this linter is the next commit, so lint is red here, 135 lines. Swapping the two applies cleanly and gives the same tree. The linters already in master came in with their fix in one commit.


    maflcko commented at 7:09 AM on September 1, 2026:

    Thx, swapped commits

  20. DrahtBot added the label Needs rebase on Aug 31, 2026
  21. maflcko force-pushed on Sep 1, 2026
  22. DrahtBot removed the label Needs rebase on Sep 1, 2026
  23. DrahtBot added the label Needs rebase on Sep 5, 2026
  24. maflcko force-pushed on Nov 10, 2026
  25. DrahtBot removed the label CI failed on Nov 10, 2026
  26. DrahtBot removed the label Needs rebase on Nov 10, 2026
  27. maflcko force-pushed on Nov 10, 2026
  28. maflcko force-pushed on Nov 10, 2026
  29. DrahtBot added the label CI failed on Nov 10, 2026
  30. DrahtBot commented at 7:09 PM on November 10, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/42874130721/job/130032819364</sub> <sub>LLM reason (✨ experimental): CI failed because check-deps.sh detected an unexpected dependency: interpreter.cpp.o depends on check.cpp.o via internal_abort_helper.</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  31. maflcko force-pushed on Nov 10, 2026
  32. maflcko marked this as ready for review on Nov 10, 2026
  33. DrahtBot removed the label CI failed on Nov 10, 2026
  34. maflcko force-pushed on Nov 10, 2026
  35. in src/txgraph.cpp:708 in faf79448a2


    maflcko commented at 9:20 PM on November 10, 2026:

    self-nit: Could be NotNull?


    ryanofsky commented at 8:37 PM on November 20, 2026:

    In commit "util: Add AssertUnreachable" (fa81e4700a9495b7216580da151f36674b5affde)

    This list of check helpers doesn't mention AssertUnreachable() or NONFATAL_UNREACHABLE(). Since the PR description gives the missing fatal counterpart to NONFATAL_UNREACHABLE() as one of the motivations, it could be worth adding a bullet after this one, something like:

    * `AssertUnreachable()` should be used to mark code that can never be reached,
      for example after a `switch` that handles every enum value. Like `Assert`, it
      aborts if it is reached. `NONFATAL_UNREACHABLE()` is the counterpart for code
      where `CHECK_NONFATAL` would be used.
    

    maflcko commented at 2:02 PM on November 23, 2026:
  36. hebasto commented at 4:49 PM on November 11, 2026: member

    Concept ACK.

    Thank you for reviving this topic!

  37. in test/lint/test_runner/src/lint_cpp.rs:171 in fa0f314a5c
     166 | @@ -167,7 +167,8 @@ pub fn lint_rpc_assert() -> LintResult {
     167 |          .success();
     168 |      if found {
     169 |          Err(r#"
     170 | -CHECK_NONFATAL(condition) or NONFATAL_UNREACHABLE should be used instead of assert for RPC code.
     171 | +CHECK_NONFATAL(condition) or NONFATAL_UNREACHABLE should be used instead of Assert, Assume, or
     172 | +AssertUnreachable for RPC code.
    


    hebasto commented at 5:06 PM on November 11, 2026:

    fa47891c9b8db91b055ccbbee0282c295a52deb0

    The new message no longer mentions assert, but the regex still catches it.

  38. in src/txdb.cpp:16 in fa0f314a5c outdated
      12 | @@ -13,6 +13,7 @@
      13 |  #include <serialize.h>
      14 |  #include <uint256.h>
      15 |  #include <util/byte_units.h>
      16 | +#include <util/check.h>
    


    hebasto commented at 5:12 PM on November 11, 2026:

    faf79448a2293c8f6be0b17fe753e27a16e41d1c

    This makes #include <cassert> unnecessary.

  39. in src/test/util_tests.cpp:13 in fa0f314a5c
       9 | @@ -10,6 +10,7 @@
      10 |  #include <script/parsing.h>
      11 |  #include <span.h>
      12 |  #include <sync.h>
      13 | +#include <sys/types.h>
    


    hebasto commented at 5:31 PM on November 11, 2026:

    fa3ec8d81d141019e7a5352aec8f067970a027d7

    This header does not belong in this group.

  40. in src/wallet/wallet.cpp:1814 in fa0f314a5c
    1810 | @@ -1812,7 +1811,7 @@ void CWallet::InitWalletFlags(uint64_t flags)
    1811 |          throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1812 |      }
    1813 |  
    1814 | -    if (!LoadWalletFlags(flags)) assert(false);
    1815 | +    if (!LoadWalletFlags(flags)) AssertUnreachable();
    


    hebasto commented at 5:35 PM on November 11, 2026:

    nit: Why not use the more readable form (assuming we are okay with side effects in the asserted expression)?

        Assert(LoadWalletFlags(flags));
    
  41. in src/script/miniscript.h:1445 in fa0f314a5c
    1440 | @@ -1441,7 +1441,7 @@ class Node
    1441 |                  case Fragment::JUST_0: return {EMPTY, INVALID};
    1442 |                  case Fragment::JUST_1: return {INVALID, EMPTY};
    1443 |              }
    1444 | -            assert(false);
    1445 | +            AssertUnreachable();
    1446 |              return {INVALID, INVALID};
    


    hebasto commented at 5:41 PM on November 11, 2026:

    Dead code left over?

  42. hebasto commented at 5:42 PM on November 11, 2026: member

    Approach ACK fa0f314a5c21207dcab090178b55ede2337f3610..

    faf79448a2293c8f6be0b17fe753e27a16e41d1c, forgot this one? https://github.com/bitcoin/bitcoin/blob/fa0f314a5c21207dcab090178b55ede2337f3610/src/protocol.cpp#L95

  43. maflcko referenced this in commit fad6abf346 on Nov 12, 2026
  44. maflcko force-pushed on Nov 12, 2026
  45. maflcko referenced this in commit fa6f0937f0 on Nov 12, 2026
  46. maflcko force-pushed on Nov 12, 2026
  47. DrahtBot added the label CI failed on Nov 12, 2026
  48. DrahtBot commented at 8:10 AM on November 12, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task lint: https://github.com/bitcoin/bitcoin/actions/runs/43179667829/job/131052297731</sub> <sub>LLM reason (✨ experimental): CI failed on lint checks: assert_falsy flags assert(false) in src/test/fuzz/util/wallet.h, and the scripted_diff check also failed.</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  49. maflcko commented at 8:52 AM on November 12, 2026: member

    rebased for silent conflict and fixed all nits

  50. DrahtBot removed the label CI failed on Nov 12, 2026
  51. in test/lint/test_runner/src/lint_cpp.rs:193 in fa5c2d1440 outdated
     188 | +            "--extended-regexp",
     189 | +            r"\<(a|A)ssert\s*\(\s*(0|false)\s*(&&|\))",
     190 | +            "--",
     191 | +            "src/",
     192 | +            // Temporary exclusions, which are not linking the util lib:
     193 | +            ":(exclude)src/script/interpreter.cpp",
    


    hebasto commented at 9:49 AM on November 12, 2026:

    Why is src/script/interpreter.cpp the only bitcoin_consensus source excluded here? The other sources of that library do not link bitcoin_util either.


    maflcko commented at 9:54 AM on November 12, 2026:

    There are other linters (linkers) that enforce the exclusion as well: #36087 (comment). Happy to include the full list, but I think I'll leave as-is for now and this can be extended on a case-by-case basis, when needed. Hopefully this "fixes itself" some time in the future via the library cleanup efforts.

  52. hebasto commented at 9:49 AM on November 12, 2026: member

    ACK fa5c2d144060b0a855f35da7b9aae1d91f5258e5.

    nit:

    --- a/src/protocol.cpp
    +++ b/src/protocol.cpp
    @@ -6,6 +6,7 @@
     #include <protocol.h>
     
     #include <common/system.h>
    +#include <util/check.h>
     
     CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* msg_type, unsigned int nMessageSizeIn)
         : pchMessageStart{pchMessageStartIn}
    
  53. maflcko referenced this in commit fa1c77b7e1 on Nov 12, 2026
  54. maflcko force-pushed on Nov 12, 2026
  55. maflcko commented at 10:00 AM on November 12, 2026: member

    fixed include nit

  56. hebasto approved
  57. hebasto commented at 10:14 AM on November 12, 2026: member

    re-ACK fa343ffd11115063ee958f98954ff192b6e4a6e6.

  58. in test/lint/test_runner/src/lint_cpp.rs:170 in fa343ffd11
     166 | @@ -167,7 +167,8 @@ pub fn lint_rpc_assert() -> LintResult {
     167 |          .success();
     168 |      if found {
     169 |          Err(r#"
     170 | -CHECK_NONFATAL(condition) or NONFATAL_UNREACHABLE should be used instead of assert for RPC code.
     171 | +CHECK_NONFATAL(condition) or NONFATAL_UNREACHABLE should be used instead of fatal asserts or aborts
    


    hodlinator commented at 11:44 AM on November 16, 2026:

    nanonit: Think it's healthier for the shared semantics of the project to imply that all asserts are fatal rather than suggesting there are two classes.

    CHECK_NONFATAL(condition) or NONFATAL_UNREACHABLE should be used instead of asserts or aborts
    

    maflcko commented at 2:14 PM on November 16, 2026:

    ok, I may or may not reconsider this on the next push. I think the linter is fine either way for now.


    maflcko commented at 11:34 AM on November 17, 2026:

    thx, pushed something

  59. in src/util/check.h:134 in fa343ffd11 outdated
     129 | @@ -130,6 +130,9 @@ constexpr T&& inline_assertion_check(LIFETIMEBOUND T&& val, [[maybe_unused]] con
     130 |   */
     131 |  #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
     132 |  
     133 | +/// Mark unreachable code. Aborts if called.
     134 | +#define AssertUnreachable() internal_abort_helper(std::source_location::current(), "unreachable")
    


    hodlinator commented at 12:00 PM on November 16, 2026:

    remark: It's not obvious to me whether this shouldn't be named and/or cased FATAL_UNREACHABLE().

    Maybe the uppercasing of NONFATAL_UNREACHABLE() and CHECK_NONFATAL() could be inferred to mean that they have different effects in debug builds and release builds. That would explain why you didn't go that way with AssertUnreachable(). OTOH Assume() has different effects depending on the build too.


    maflcko commented at 2:14 PM on November 16, 2026:

    Assert already means fatal in this codebase and this is a bit like an AssertZero() (always fails), so I kept consistency with that. But naming is always hard and subjective, I guess.

  60. in test/lint/test_runner/src/lint_cpp.rs:195 in fa343ffd11
     190 | +            "--",
     191 | +            "src/",
     192 | +            // Temporary exclusions, which are not linking the util lib:
     193 | +            ":(exclude)src/script/interpreter.cpp",
     194 | +            ":(exclude)src/univalue/",
     195 | +            ":(exclude)src/tinyformat.h", // Uses exceptions, not the assert error handling
    


    hodlinator commented at 12:27 PM on November 16, 2026:

    nit: This is not entirely true, asserting 0 occurs in two places.

                ":(exclude)src/tinyformat.h", // Avoid flagging externally maintained code
    

    maflcko commented at 2:14 PM on November 16, 2026:

    Which ones? Did you see #define TINYFORMAT_ERROR(reasonString) throw tinyformat::format_error(reasonString)?


    hodlinator commented at 2:26 PM on November 16, 2026:

    That disables one of them, but there's also a TINYFORMAT_ASSERT(0) (which admittedly doesn't match the regex).


    maflcko commented at 3:11 PM on November 16, 2026:

    Ah, didn't see that. Though, at this point, it isn't really "externally maintained". At some point this will all be removed, so it doesn't matter, but if I touch this again, I can say: // Avoid flagging dead branches in temporary std::format port


    maflcko commented at 11:35 AM on November 17, 2026:

    pushed my last suggestion

  61. hodlinator approved
  62. hodlinator commented at 12:48 PM on November 16, 2026: contributor

    crACK fa343ffd11115063ee958f98954ff192b6e4a6e6

    Should reduce the issue with non-standard no-[[no_return]] assert()s on Windows Clang-CL as noted in #31507 (review).

    Makes me wonder if the scope of -Wno-error=return-type from ci-windows.py could be reduced to only code that doesn't depend on check.h, but don't see any obvious way to do it.

  63. in test/lint/test_runner/src/lint_cpp.rs:189 in fa343ffd11
     184 | +    let found = git()
     185 | +        .args([
     186 | +            "grep",
     187 | +            "--line-number",
     188 | +            "--extended-regexp",
     189 | +            r"\<(a|A)ssert\s*\(\s*(0|false)\s*(&&|\))",
    


    l0rinc commented at 3:31 PM on November 16, 2026:

    fa343ff test: Add assert_falsy linter, And use AssertUnreachable:

    To avoid assume / AssumeUnreachable / assertUnreachable, we could use --perl-regexp (with \b instead, which also avoids native macOS Git silently missing \< - seems lint_includes_build_config already uses it) and list the methods instead of (ume|ert) hacks

    <details> <summary>Spell out the assertion names</summary>

    diff --git a/test/lint/test_runner/src/lint_cpp.rs b/test/lint/test_runner/src/lint_cpp.rs
    index d1c51891a9..668e4bfbd6 100644
    --- a/test/lint/test_runner/src/lint_cpp.rs
    +++ b/test/lint/test_runner/src/lint_cpp.rs
    @@ -154,8 +154,8 @@ pub fn lint_rpc_assert() -> LintResult {
             .args([
                 "grep",
                 "--line-number",
    -            "--extended-regexp",
    -            r"\<(A|a)ss(ume|ert)(Unreachable)?\(",
    +            "--perl-regexp",
    +            r"\b(?:Assume|[aA]ssert|AssertUnreachable)\(",
                 "--",
                 "src/rpc/",
                 "src/wallet/rpc*",
    @@ -185,8 +185,8 @@ pub fn lint_assert_falsy() -> LintResult {
             .args([
                 "grep",
                 "--line-number",
    -            "--extended-regexp",
    -            r"\<(a|A)ssert\s*\(\s*(0|false)\s*(&&|\))",
    +            "--perl-regexp",
    +            r"\b[aA]ssert\s*\(\s*(0|false)\s*(&&|\))",
                 "--",
                 "src/",
                 // Temporary exclusions, which are not linking the util lib:
    

    </details>


    maflcko commented at 11:35 AM on November 17, 2026:

    Heh, didn't know that git doesn't bundle regex. Switched to perl regex

  64. in src/wallet/wallet.cpp:1815 in fa97e3ab1c outdated
    1811 | @@ -1812,7 +1812,7 @@ void CWallet::InitWalletFlags(uint64_t flags)
    1812 |          throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1813 |      }
    1814 |  
    1815 | -    if (!LoadWalletFlags(flags)) assert(false);
    1816 | +    Assert(LoadWalletFlags(flags));
    


    l0rinc commented at 3:31 PM on November 16, 2026:

    fa97e3a refactor: Use AssertUnreachable() and remove dead code:

    Same as in InitWalletFlags: it's weird to do if not ... assert(false)...

    <details> <summary>Assert the wallet results</summary>

    diff --git a/src/wallet/scriptpubkeyman.cpp b/src/wallet/scriptpubkeyman.cpp
    index d917f6b2bb..66deb1c9bc 100644
    --- a/src/wallet/scriptpubkeyman.cpp
    +++ b/src/wallet/scriptpubkeyman.cpp
    @@ -580,9 +580,7 @@ std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
         // keyids is now all non-HD keys. Each key will have its own combo descriptor
         for (const CKeyID& keyid : keyids) {
             CKey key;
    -        if (!GetKey(keyid, key)) {
    -            AssertUnreachable();
    -        }
    +        Assert(GetKey(keyid, key));
     
             // Get birthdate from key meta
             uint64_t creation_time = 0;
    @@ -635,9 +633,7 @@ std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
     
             // Get the master xprv
             CKey seed_key;
    -        if (!GetKey(chain.seed_id, seed_key)) {
    -            AssertUnreachable();
    -        }
    +        Assert(GetKey(chain.seed_id, seed_key));
             CExtKey master_key;
             master_key.SetSeed(seed_key);
     
    @@ -680,9 +676,7 @@ std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
         // Add the current master seed to the migration data
         if (!m_hd_chain.seed_id.IsNull()) {
             CKey seed_key;
    -        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
    -            AssertUnreachable();
    -        }
    +        Assert(GetKey(m_hd_chain.seed_id, seed_key));
             out.master_key.SetSeed(seed_key);
         }
     
    @@ -717,9 +711,7 @@ std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
             // Get the private keys for this descriptor
             std::vector<CScript> scripts;
             FlatSigningProvider keys;
    -        if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
    -            AssertUnreachable();
    -        }
    +        Assert(desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys));
             std::set<CKeyID> privkeyids;
             for (const auto& key_orig_pair : keys.origins) {
                 privkeyids.insert(key_orig_pair.first);
    diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
    index a0553ddf20..e3760e0ab6 100644
    --- a/src/wallet/test/wallet_tests.cpp
    +++ b/src/wallet/test/wallet_tests.cpp
    @@ -632,10 +632,8 @@ static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
         // Fill in dummy signatures for fee calculation.
         SignatureData sig_data;
     
    -    if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
    -        // We're hand-feeding it correct arguments; shouldn't happen
    -        AssertUnreachable();
    -    }
    +    // We're hand-feeding it correct arguments, so signing should succeed
    +    Assert(ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data));
     
         CTxIn tx_in;
         UpdateInput(tx_in, sig_data);
    

    </details>


    maflcko commented at 11:35 AM on November 17, 2026:

    thx, done

  65. in src/dbwrapper.h:296 in fa97e3ab1c outdated
     292 | @@ -293,7 +293,7 @@ class CDBWrapper
     293 |              case ReadFailure::Code::DeserializationError: return false;
     294 |              case ReadFailure::Code::DatabaseError: throw dbwrapper_error(err_msg);
     295 |          } // no default case, so the compiler can warn about missing cases
     296 | -        std::abort(); // unreachable
     297 | +        AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fa97e3a refactor: Use AssertUnreachable() and remove dead code:

    Maybe extend the existing scripted diff to cover these, too?

    <details> <summary>Use AssertUnreachable in both fallbacks</summary>

    diff --git a/src/validation.h b/src/validation.h
    index 68c1f7e0a4..09f29154c8 100644
    --- a/src/validation.h
    +++ b/src/validation.h
    @@ -1140,7 +1140,7 @@ public:
             for (auto& cs : m_chainstates) {
                 if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && !cs->TargetBlockHash()) return *cs;
             }
    -        abort();
    +        AssertUnreachable();
         }
     
         //! Return historical chainstate targeting a specific block, if any.
    @@ -1160,7 +1160,7 @@ public:
             for (auto* cs : {&CurrentChainstate(), HistoricalChainstate()}) {
                 if (cs && cs->m_assumeutxo == Assumeutxo::VALIDATED) return *cs;
             }
    -        abort();
    +        AssertUnreachable();
         }
     
         //! Remove a chainstate.
    

    </details>


    maflcko commented at 11:36 AM on November 17, 2026:

    Sure, done

  66. in src/memusage.h:62 in fafb9c61f7 outdated
      58 | @@ -59,7 +59,7 @@ static inline size_t MallocUsage(size_t alloc)
      59 |      } else if (sizeof(void*) == 4) {
      60 |          return ((alloc + 15) >> 3) << 3;
      61 |      } else {
      62 | -        assert(0);
      63 | +        AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    compat/assumptions.h already checks this (and even mentions MallocUsage).

    <details> <summary>Use the existing pointer-width check</summary>

    diff --git a/src/memusage.h b/src/memusage.h
    index d5777c37de..9a763ca32c 100644
    --- a/src/memusage.h
    +++ b/src/memusage.h
    @@ -8,7 +8,6 @@
     #include <indirectmap.h>
     #include <prevector.h>
     #include <support/allocators/pool.h>
    -#include <util/check.h>
     
     #include <cstdlib>
     #include <list>
    @@ -56,10 +55,8 @@ static inline size_t MallocUsage(size_t alloc)
             return 0;
         } else if (sizeof(void*) == 8) {
             return ((alloc + 31) >> 4) << 4;
    -    } else if (sizeof(void*) == 4) {
    +    } else { // 4-byte pointers, guaranteed by compat/assumptions.h
             return ((alloc + 15) >> 3) << 3;
    -    } else {
    -        AssertUnreachable();
         }
     }
     
    

    </details>


    maflcko commented at 11:34 AM on November 17, 2026:

    hmm, did something else in the first commit

  67. in src/test/fuzz/tx_pool.cpp:293 in fa97e3ab1c outdated
     289 | @@ -290,14 +290,12 @@ void CheckATMPInvariants(const MempoolAcceptResult& res, bool txid_in_mempool, b
     290 |      case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
     291 |      {
     292 |          // ATMP never sets this; only set in package settings
     293 | -        Assert(false);
     294 | -        break;
     295 | +        AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fa97e3a refactor: Use AssertUnreachable() and remove dead code:

    nit: we can just fall through

    <details> <summary>Share the two case labels</summary>

    diff --git a/src/test/fuzz/tx_pool.cpp b/src/test/fuzz/tx_pool.cpp
    index 892b362262..f740ca15bb 100644
    --- a/src/test/fuzz/tx_pool.cpp
    +++ b/src/test/fuzz/tx_pool.cpp
    @@ -288,13 +288,9 @@ void CheckATMPInvariants(const MempoolAcceptResult& res, bool txid_in_mempool, b
             break;
         }
         case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
    -    {
    -        // ATMP never sets this; only set in package settings
    -        AssertUnreachable();
    -    }
         case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS:
         {
    -        // ATMP never sets this; only set in package settings
    +        // Only set in package settings, never by ATMP
             AssertUnreachable();
         }
         }
    

    </details>


    maflcko commented at 11:33 AM on November 17, 2026:

    thx, done

  68. in src/test/httpserver_tests.cpp:1035 in fa97e3ab1c outdated
    1031 | @@ -1031,7 +1032,7 @@ BOOST_AUTO_TEST_CASE(http_socket_error_tests)
    1032 |      {
    1033 |      public:
    1034 |          explicit ErrorSock(std::shared_ptr<Pipes> pipes) : DynSock{std::move(pipes)} {}
    1035 | -        DynSock& operator=(Sock&&) override { assert(false); return *this; }
    1036 | +        DynSock& operator=(Sock&&) override { AssertUnreachable(); }
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fa97e3a refactor: Use AssertUnreachable() and remove dead code:

    As far as I can tell, ZeroSock already does this. Is the more specific error location a reason to keep these?

    <details> <summary>Inherit the existing assignment guard</summary>

    diff --git a/src/test/httpserver_tests.cpp b/src/test/httpserver_tests.cpp
    index b8933d08fa..ab4db9cc27 100644
    --- a/src/test/httpserver_tests.cpp
    +++ b/src/test/httpserver_tests.cpp
    @@ -782,10 +782,6 @@ BOOST_AUTO_TEST_CASE(http_should_disconnect_tests)
                 ssize_t Send(const void*, size_t len, int) const override {
                     return CeilDiv(len, 2U); // Only let through half per call
                 }
    -        private:
    -            SlowSocket& operator=(Sock&&) override {
    -                AssertUnreachable(); // Move of Sock into SlowSocket not allowed.
    -            }
             };
     
             // A request handed to a worker holds the idle timeout off until the reply is sent.
    @@ -1032,7 +1028,6 @@ BOOST_AUTO_TEST_CASE(http_socket_error_tests)
         {
         public:
             explicit ErrorSock(std::shared_ptr<Pipes> pipes) : DynSock{std::move(pipes)} {}
    -        DynSock& operator=(Sock&&) override { AssertUnreachable(); }
     
             ssize_t Send(const void* buf, size_t len, int flags) const override
             {
    diff --git a/src/test/util/net.cpp b/src/test/util/net.cpp
    index 681f9e851e..11333ad449 100644
    --- a/src/test/util/net.cpp
    +++ b/src/test/util/net.cpp
    @@ -255,11 +255,6 @@ ssize_t StaticContentsSock::Recv(void* buf, size_t len, int flags) const
         return consume_bytes;
     }
     
    -StaticContentsSock& StaticContentsSock::operator=(Sock&& other)
    -{
    -    AssertUnreachable(); // Move of Sock into StaticContentsSock not allowed.
    -}
    -
     ssize_t DynSock::Pipe::GetBytes(void* buf, size_t len, int flags)
     {
         LOCK(m_mutex);
    @@ -374,8 +369,3 @@ bool DynSock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_
     
         return true;
     }
    -
    -DynSock& DynSock::operator=(Sock&&)
    -{
    -    AssertUnreachable(); // Move of Sock into DynSock not allowed.
    -}
    diff --git a/src/test/util/net.h b/src/test/util/net.h
    index d226244077..ff80f4999f 100644
    --- a/src/test/util/net.h
    +++ b/src/test/util/net.h
    @@ -225,8 +225,6 @@ public:
         }
     
     private:
    -    StaticContentsSock& operator=(Sock&& other) override;
    -
         const std::string m_contents;
         mutable size_t m_consumed{0};
     };
    @@ -341,8 +339,6 @@ public:
         bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
     
     private:
    -    DynSock& operator=(Sock&&) override;
    -
         std::shared_ptr<Pipes> m_pipes;
         Queue* const m_accept_sockets;
     };
    

    </details>


    maflcko commented at 11:33 AM on November 17, 2026:

    I guess so, but I think this was written intentionally? I think I'll leave as-is for now.

  69. in src/kernel/bitcoinkernel.cpp:183 in fafb9c61f7 outdated
     179 | @@ -180,7 +180,7 @@ constexpr util::log::Level to_util(btck_LogLevel level)
     180 |          return util::log::Level::Error;
     181 |      }
     182 |      }
     183 | -    assert(false);
     184 | +    AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    nit: same comment as in to_btck for consistency?

    <details> <summary>Explain the omitted defaults</summary>

    diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
    index f68dc7b8b4..84ce94e240 100644
    --- a/src/bitcoin-cli.cpp
    +++ b/src/bitcoin-cli.cpp
    @@ -441,7 +441,7 @@ private:
                 return " regtest";
             case ChainType::MAIN:
                 return "";
    -        }
    +        } // no default case, so the compiler can warn about missing cases
             AssertUnreachable();
         }
         std::string PingTimeToString(double seconds) const
    diff --git a/src/chainparams.cpp b/src/chainparams.cpp
    index 7d255d623f..fed439c7ab 100644
    --- a/src/chainparams.cpp
    +++ b/src/chainparams.cpp
    @@ -158,7 +158,7 @@ std::unique_ptr<const CChainParams> CreateChainParams(const ArgsManager& args, c
             ReadRegTestArgs(args, opts);
             return CChainParams::RegTest(opts);
         }
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp
    index 61889bdd82..70ccc1287e 100644
    --- a/src/chainparamsbase.cpp
    +++ b/src/chainparamsbase.cpp
    @@ -71,7 +71,7 @@ std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const ArgsManager& args,
             return std::make_unique<CBaseChainParams>(GetSignetDataDir(args), 38332);
         case ChainType::REGTEST:
             return std::make_unique<CBaseChainParams>("regtest", 18443);
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
    index 732e7074fa..27f3272c1a 100644
    --- a/src/kernel/bitcoinkernel.cpp
    +++ b/src/kernel/bitcoinkernel.cpp
    @@ -179,7 +179,7 @@ constexpr util::log::Level to_util(btck_LogLevel level)
         case btck_LogLevel_ERROR: {
             return util::log::Level::Error;
         }
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    @@ -1066,7 +1066,7 @@ btck_ChainParameters* btck_chain_parameters_create(const btck_ChainType chain_ty
         case btck_ChainType_REGTEST: {
             return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
         }
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/kernel/mempool_removal_reason.cpp b/src/kernel/mempool_removal_reason.cpp
    index a078d081b2..9c32172893 100644
    --- a/src/kernel/mempool_removal_reason.cpp
    +++ b/src/kernel/mempool_removal_reason.cpp
    @@ -17,6 +17,6 @@ std::string RemovalReasonToString(const MemPoolRemovalReason& r) noexcept
             case MemPoolRemovalReason::BLOCK: return "block";
             case MemPoolRemovalReason::CONFLICT: return "conflict";
             case MemPoolRemovalReason::REPLACED: return "replaced";
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
    diff --git a/src/logging.cpp b/src/logging.cpp
    index edf799c800..de5ae7f67b 100644
    --- a/src/logging.cpp
    +++ b/src/logging.cpp
    @@ -254,7 +254,7 @@ std::string BCLog::Logger::LogLevelToStr(BCLog::Level level)
             return "warning";
         case BCLog::Level::Error:
             return "error";
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp
    index 014b4df4db..1e347ac9df 100644
    --- a/src/script/descriptor.cpp
    +++ b/src/script/descriptor.cpp
    @@ -2331,7 +2331,7 @@ struct KeyParser {
             switch (m_script_ctx) {
                 case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
                 case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    -        }
    +        } // no default case, so the compiler can warn about missing cases
             AssertUnreachable();
         }
     
    diff --git a/src/script/miniscript.cpp b/src/script/miniscript.cpp
    index 6dfa6832b4..7e34ac35d1 100644
    --- a/src/script/miniscript.cpp
    +++ b/src/script/miniscript.cpp
    @@ -257,7 +257,7 @@ Type ComputeType(Fragment fragment, Type x, Type y, Type z, const std::vector<Ty
                        "s"_mst.If(num_s >= n_subs - k + 1) |  // s= >=(n-k+1) s
                        acc_tl; // timelock info
                 }
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    @@ -291,7 +291,7 @@ size_t ComputeScriptLen(Fragment fragment, Type sub0typ, size_t subsize, uint32_
             case Fragment::ANDOR: return subsize + 3;
             case Fragment::WRAP_J: return subsize + 4;
             case Fragment::THRESH: return subsize + n_subs + BuildScript(k).size();
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/script/miniscript.h b/src/script/miniscript.h
    index 1ac4d71eec..1a24d39bfc 100644
    --- a/src/script/miniscript.h
    +++ b/src/script/miniscript.h
    @@ -261,7 +261,7 @@ constexpr bool IsTapscript(MiniscriptContext ms_ctx)
         switch (ms_ctx) {
             case MiniscriptContext::P2WSH: return false;
             case MiniscriptContext::TAPSCRIPT: return true;
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    @@ -867,7 +867,7 @@ public:
                         }
                         return BuildScript(std::move(script), node.k, verify ? OP_EQUALVERIFY : OP_EQUAL);
                     }
    -            }
    +            } // no default case, so the compiler can warn about missing cases
                 AssertUnreachable();
             };
             return TreeEval<CScript>(false, downfn, upfn);
    @@ -1071,7 +1071,7 @@ private:
                     assert(k < sats.size());
                     return {count, sats[k], sats[0]};
                 }
    -        }
    +        } // no default case, so the compiler can warn about missing cases
             AssertUnreachable();
         }
     
    @@ -1186,7 +1186,7 @@ private:
                         sats[0] + SatInfo::Push() + SatInfo::OP_EQUAL()
                     };
                 }
    -        }
    +        } // no default case, so the compiler can warn about missing cases
             AssertUnreachable();
         }
     
    @@ -1239,7 +1239,7 @@ private:
                     assert(k < sats.size());
                     return {sats[k], sats[0]};
                 }
    -        }
    +        } // no default case, so the compiler can warn about missing cases
             AssertUnreachable();
         }
     
    @@ -1440,7 +1440,7 @@ private:
                     }
                     case Fragment::JUST_0: return {EMPTY, INVALID};
                     case Fragment::JUST_1: return {INVALID, EMPTY};
    -            }
    +            } // no default case, so the compiler can warn about missing cases
                 AssertUnreachable();
             };
     
    diff --git a/src/test/fuzz/http_request.cpp b/src/test/fuzz/http_request.cpp
    index fcdcd1a4e5..88627d81cf 100644
    --- a/src/test/fuzz/http_request.cpp
    +++ b/src/test/fuzz/http_request.cpp
    @@ -82,7 +82,7 @@ int StateRank(HTTPRequest::State s)
         case HTTPRequest::State::NeedsBody: return 2;
         case HTTPRequest::State::Complete: return 3;
         case HTTPRequest::State::Error: return 4;
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/test/fuzz/miniscript.cpp b/src/test/fuzz/miniscript.cpp
    index 77c34415f0..22d86aabca 100644
    --- a/src/test/fuzz/miniscript.cpp
    +++ b/src/test/fuzz/miniscript.cpp
    @@ -834,7 +834,7 @@ std::optional<NodeInfo> ConsumeNodeSmart(MsCtx script_ctx, FuzzedDataProvider& p
                 while (subs.size() < children) subs.push_back(subs.back());
                 return {{std::move(subs), frag, k}};
             }
    -    }
    +    } // no default case, so the compiler can warn about missing cases
     
         AssertUnreachable();
     }
    diff --git a/src/util/chaintype.cpp b/src/util/chaintype.cpp
    index 7078a50c8f..5391c2e8ba 100644
    --- a/src/util/chaintype.cpp
    +++ b/src/util/chaintype.cpp
    @@ -22,7 +22,7 @@ std::string ChainTypeToString(ChainType chain)
             return "signet";
         case ChainType::REGTEST:
             return "regtest";
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    diff --git a/src/validation.cpp b/src/validation.cpp
    index 89deea5215..5ff03f9c3e 100644
    --- a/src/validation.cpp
    +++ b/src/validation.cpp
    @@ -2110,7 +2110,7 @@ bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
                     return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("mempool-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
                 case CheckInputScriptsFor::Block:
                     return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
    -            }
    +            } // no default case, so the compiler can warn about missing cases
                 AssertUnreachable();
             }
         }
    diff --git a/src/wallet/scriptpubkeyman.cpp b/src/wallet/scriptpubkeyman.cpp
    index 66deb1c9bc..9274c39204 100644
    --- a/src/wallet/scriptpubkeyman.cpp
    +++ b/src/wallet/scriptpubkeyman.cpp
    @@ -209,7 +209,7 @@ bool LegacyDataSPKM::IsMine(const CScript& script) const
         case IsMineResult::WATCH_ONLY:
         case IsMineResult::SPENDABLE:
             return true;
    -    }
    +    } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
     
    

    </details>


    maflcko commented at 11:33 AM on November 17, 2026:

    this is not possible to do in a scripted-diff. Also, I am sure your diff is wrong, because there is no compiler checks on stuff like btck_LogLevel_ERROR.


    l0rinc commented at 11:38 AM on November 17, 2026:

    btck_LogLevel_ERROR - ah, so the missing comments are sometimes deliberate. Isn't that another reason to add them when they would be true?


    maflcko commented at 11:47 AM on November 17, 2026:

    Yeah, they should be added, but this pull is already a bit large, and there is no consistency enforcement anyway, so I am not sure if reviewers will be happy about such a commit.

  70. in src/addrman.cpp:1048 in fafb9c61f7 outdated
    1044 | @@ -1045,7 +1045,7 @@ void AddrManImpl::Check() const
    1045 |      const int err{CheckAddrman()};
    1046 |      if (err) {
    1047 |          LogError("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
    1048 | -        assert(false);
    1049 | +        AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    This could just be a plain assert, the log seems superfluous:

    <details> <summary>Assert the addrman check directly</summary>

    diff --git a/src/addrman.cpp b/src/addrman.cpp
    index fe7bb0e65a..02d2b2f963 100644
    --- a/src/addrman.cpp
    +++ b/src/addrman.cpp
    @@ -1042,11 +1042,7 @@ void AddrManImpl::Check() const
         if (m_consistency_check_ratio == 0) return;
         if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
     
    -    const int err{CheckAddrman()};
    -    if (err) {
    -        LogError("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
    -        AssertUnreachable();
    -    }
    +    Assert(CheckAddrman() == 0);
     }
     
     int AddrManImpl::CheckAddrman() const
    

    </details>


    maflcko commented at 11:32 AM on November 17, 2026:

    I presume the log was intentional, so I'll leave as-is.

  71. in src/bitcoin-util.cpp:247 in fafb9c61f7 outdated
     243 | @@ -243,7 +244,7 @@ MAIN_FUNCTION
     244 |          } else if (cmd->command == "getchainparams") {
     245 |              ret = GetChainParams(cmd->args, strPrint);
     246 |          } else {
     247 | -            assert(false); // unknown command should be caught earlier
     248 | +            AssertUnreachable(); // unknown command should be caught earlier
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    Might as well tidy this up while we're here:

    <details> <summary>Assert the remaining command</summary>

    diff --git a/src/bitcoin-util.cpp b/src/bitcoin-util.cpp
    index e335d1e8e1..c1bc2fb0e6 100644
    --- a/src/bitcoin-util.cpp
    +++ b/src/bitcoin-util.cpp
    @@ -241,10 +241,9 @@ MAIN_FUNCTION
         try {
             if (cmd->command == "grind") {
                 ret = Grind(cmd->args, strPrint);
    -        } else if (cmd->command == "getchainparams") {
    -            ret = GetChainParams(cmd->args, strPrint);
             } else {
    -            AssertUnreachable(); // unknown command should be caught earlier
    +            Assert(cmd->command == "getchainparams");
    +            ret = GetChainParams(cmd->args, strPrint);
             }
         } catch (const std::exception& e) {
             strPrint = std::string("error: ") + e.what();
    

    </details>


    maflcko commented at 11:32 AM on November 17, 2026:

    not sure


    l0rinc commented at 11:40 AM on November 17, 2026:

    Isn't the error clearer saying that cmd is not getchainparams? Isn't the meaning the same as before? I don't insist, but seems simpler to me.


    maflcko commented at 11:44 AM on November 17, 2026:

    This makes it harder to add new commands in the future, because the diff would be more verbose

  72. in src/qt/bitcoin.cpp:170 in fafb9c61f7 outdated
     166 | @@ -166,7 +167,7 @@ static bool ErrorSettingsRead(const bilingual_str& error, const std::vector<std:
     167 |      case QMessageBox::Abort:
     168 |          return true;
     169 |      default:
     170 | -        assert(false);
     171 | +        AssertUnreachable();
    


    l0rinc commented at 3:32 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    If this is indeed unreachable, we could collapse it to a single return with comment:

    <details> <summary>Return the comparison</summary>

    diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
    index d8a299fd5d..5c365dbd67 100644
    --- a/src/qt/bitcoin.cpp
    +++ b/src/qt/bitcoin.cpp
    @@ -161,14 +161,7 @@ static bool ErrorSettingsRead(const bilingual_str& error, const std::vector<std:
         messagebox.setDetailedText(QString::fromStdString(MakeUnorderedList(details)));
         messagebox.setTextFormat(Qt::PlainText);
         messagebox.setDefaultButton(QMessageBox::Reset);
    -    switch (messagebox.exec()) {
    -    case QMessageBox::Reset:
    -        return false;
    -    case QMessageBox::Abort:
    -        return true;
    -    default:
    -        AssertUnreachable();
    -    }
    +    return messagebox.exec() == QMessageBox::Abort; // Reset or Abort
     }
     
     static void ErrorSettingsWrite(const bilingual_str& error, const std::vector<std::string>& details)
    

    </details>


    maflcko commented at 11:32 AM on November 17, 2026:

    All of this code will be deleted , so no need to rewrite it

  73. in src/netaddress.cpp:44 in fafb9c61f7 outdated
      40 | @@ -40,10 +41,10 @@ CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const
      41 |      case NET_INTERNAL:   // should have been handled before calling this function
      42 |      case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
      43 |      case NET_MAX:        // m_net is never and should not be set to NET_MAX
      44 | -        assert(false);
      45 | +        AssertUnreachable();
    


    l0rinc commented at 3:33 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    We still get warnings for missing cases this way (and is less repetitive if we just break):

    <details> <summary>Share the final assertion</summary>

    diff --git a/src/netaddress.cpp b/src/netaddress.cpp
    index c89569142c..64a0db7839 100644
    --- a/src/netaddress.cpp
    +++ b/src/netaddress.cpp
    @@ -41,7 +41,7 @@ CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const
         case NET_INTERNAL:   // should have been handled before calling this function
         case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
         case NET_MAX:        // m_net is never and should not be set to NET_MAX
    -        AssertUnreachable();
    +        break;
         } // no default case, so the compiler can warn about missing cases
     
         AssertUnreachable();
    @@ -495,7 +495,7 @@ bool CNetAddr::IsAddrV1Compatible() const
             return false;
         case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
         case NET_MAX:        // m_net is never and should not be set to NET_MAX
    -        AssertUnreachable();
    +        break;
         } // no default case, so the compiler can warn about missing cases
     
         AssertUnreachable();
    @@ -602,7 +602,7 @@ std::string CNetAddr::ToStringAddr() const
             return EncodeBase32(m_addr) + ".internal";
         case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
         case NET_MAX:        // m_net is never and should not be set to NET_MAX
    -        AssertUnreachable();
    +        break;
         } // no default case, so the compiler can warn about missing cases
     
         AssertUnreachable();
    diff --git a/src/netbase.cpp b/src/netbase.cpp
    index 587824b33a..510e1216c4 100644
    --- a/src/netbase.cpp
    +++ b/src/netbase.cpp
    @@ -122,7 +122,7 @@ std::string GetNetworkName(enum Network net)
         case NET_I2P: return "i2p";
         case NET_CJDNS: return "cjdns";
         case NET_INTERNAL: return "internal";
    -    case NET_MAX: AssertUnreachable();
    +    case NET_MAX: break;
         } // no default case, so the compiler can warn about missing cases
     
         AssertUnreachable();
    diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp
    index bdeb4d77e6..dbfe8ce61f 100644
    --- a/src/qt/guiutil.cpp
    +++ b/src/qt/guiutil.cpp
    @@ -694,7 +694,7 @@ QString NetworkToQString(Network net)
         //: Name of CJDNS network in peer info
         case NET_CJDNS: return QObject::tr("CJDNS", "network name");
         case NET_INTERNAL: return "Internal";  // should never actually happen
    -    case NET_MAX: AssertUnreachable();
    +    case NET_MAX: break;
         } // no default case, so the compiler can warn about missing cases
         AssertUnreachable();
     }
    

    </details>


    maflcko commented at 11:31 AM on November 17, 2026:

    this is part of the scripted-diff, so not sure


    l0rinc commented at 11:36 AM on November 17, 2026:

    We could add the break in a previous commit.


    maflcko commented at 11:48 AM on November 17, 2026:

    Right, but I think an explicit marker is clearer than a break, so I think I'll leave this as-is for now.

  74. in src/wallet/wallet.cpp:3833 in fafb9c61f7 outdated
    3829 | @@ -3831,7 +3830,7 @@ bool CWallet::MigrateToSQLite(bilingual_str& error)
    3830 |              batch->TxnAbort();
    3831 |              m_database->Close();
    3832 |              fs::remove(m_database->Filename());
    3833 | -            assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3834 | +            AssertUnreachable(); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    


    l0rinc commented at 3:33 PM on November 16, 2026:

    fafb9c6 scripted-diff: Replace falsy assertions with AssertUnreachable:

    Given the name suggests it's "unreachable", if we start handling it, it sounds like it's just "exceptional" ... Writes can fail, so would an exception make more sense once the caller can restore the backup - wouldn't this get tangled up with #34193?


    maflcko commented at 11:31 AM on November 17, 2026:

    Sure, happy to wait for the other pull first

  75. l0rinc changes_requested
  76. l0rinc commented at 3:43 PM on November 16, 2026: contributor

    Concept ACK! Glad we're converging on the assert-cleanup-projectâ„¢ - might as well simplify a few more of these while we're here, so we don't have to revisit the same lines later. I don't insist on any of them, but wanted to present the inconsistencies.

  77. DrahtBot added the label Needs rebase on Nov 16, 2026
  78. refactor: Replace unreachable run-time assert with compile time assert fa1c93477e
  79. util: Add AssertUnreachable fa81e4700a
  80. refactor: Use AssertUnreachable() and remove dead code
    * Use AssertUnreachable() instead of falsy asserts.
    * Use AssertUnreachable() instead of naked aborts, so that in the rare
      case it does happen, there is a diagnostic on stderr.
    * In the wallet code, use clearer Assert(...).
    * Remove dead code while touching.
    fa1574cdaa
  81. test: Remove unused includes in util_tests.cpp
    Requested by hebasto in https://github.com/bitcoin/bitcoin/pull/36087#discussion_r4541159776 and by iwyu:
    
    src/test/util_tests.cpp should remove these lines:
    - #include <sys/types.h>  // lines 46-46
    - #include <univalue.h>  // lines 18-18
    - #include <util/bitdeque.h>  // lines 19-19
    - #include <cstring>  // lines 35-35
    fa6b4604e8
  82. maflcko force-pushed on Nov 17, 2026
  83. scripted-diff: Replace falsy assertions with AssertUnreachable
    Replace assertions with falsy literal values by the explicit
    unreachable-code assertion macro.
    
    -BEGIN VERIFY SCRIPT-
    
     # Paths to edit.
     # Excluded are subtrees and modules that can not include util/check.
     paths=(
       'src'
       ':(exclude)src/script/interpreter.cpp'
       ':(exclude)src/tinyformat.h'
       ':(exclude)src/univalue/'
       ':(exclude)src/crc32c'
       ':(exclude)src/crypto/ctaes'
       ':(exclude)src/ipc/libmultiprocess'
       ':(exclude)src/leveldb'
       ':(exclude)src/minisketch'
       ':(exclude)src/secp256k1'
     )
    
     for f in $(git grep -l --extended-regexp '\<(a|A)ssert\((0|false)\)' -- "${paths[@]}"); do
    
       # Add the util/check.h includes
       if ! grep --quiet "util/check.h" "$f"; then
         line=$(grep --line-number --max-count=1 '^#include' "$f" | cut --delimiter=: --fields=1)
         sed --in-place "${line}i#include <util/check.h>" "$f"
       fi
    
       # Remove cassert includes
       sed --in-place '/^#include <cassert>$/d' "$f"
    
       # Sort includes
       git diff -U1 $f | ./contrib/devtools/clang-format-diff.py -p1 -i -v
    
       # Use AssertUnreachable
       sed --in-place --regexp-extended 's/\<(a|A)ssert\((0|false)\)/AssertUnreachable()/g' "$f"
    
     done
    
    -END VERIFY SCRIPT-
    fa20a5c705
  84. test: Add assert_falsy linter, And use AssertUnreachable fa9a4ddbaf
  85. maflcko force-pushed on Nov 17, 2026
  86. DrahtBot added the label CI failed on Nov 17, 2026
  87. DrahtBot commented at 11:32 AM on November 17, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task lint: https://github.com/bitcoin/bitcoin/actions/runs/44072951784/job/134003532996</sub> <sub>LLM reason (✨ experimental): CI failed the scripted_diff lint check because the scripted replacement incorrectly removes #include <util/check.h> from src/memusage.h.</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  88. in src/memusage.h:60 in fa9a4ddbaf
      58 | -    } else if (sizeof(void*) == 4) {
      59 | +    } else if constexpr (sizeof(void*) == 4) {
      60 |          return ((alloc + 15) >> 3) << 3;
      61 |      } else {
      62 | -        assert(0);
      63 | +        static_assert(sizeof(void*) == 4 || sizeof(void*) == 8);
    


    l0rinc commented at 11:35 AM on November 17, 2026:

    Not sure I understand what this means: if it's not 32 bits and not 64 bits, check that it's either 32 bits or 64 bits? We're already asserting that elsewhere, I don't think this is useful...


    maflcko commented at 11:41 AM on November 17, 2026:

    This will become static_assert(0) in C++23, which doesn't work in C++20 due to a language defect.

    static_assert(0) is the compile-time equivalent of assert(0) at runtime, so I think it is useful.

    Edit: Leaving this open, so I don't forget to follow-up with C++23 here.


    l0rinc commented at 11:43 AM on November 17, 2026:

    The proper fix here would be the removal of the incomplete 32 bit support anyway - please resolve the comment.


    ryanofsky commented at 8:27 PM on November 20, 2026:

    re: #36087 (review)

    This will become static_assert(0) in C++23, which doesn't work in C++20 due to a language defect.

    Two things to know for the follow-up:

    • MallocUsage needs to be made into a function template for static_assert(false) to work. In a non-template function, a static_assert is checked in every branch, including discarded if constexpr branches, so it fires on every platform.
    • Since the change is a defect report (CWG2518, which includes P2593R1), it depends on the compiler version, not the language version. It already works with -std=c++20 on GCC 13 and our minimum Clang, so this can change as soon as we drop support for GCC 12.

    maflcko commented at 2:03 PM on November 23, 2026:
    • MallocUsage needs to be made into a function template for static_assert(false) to work.

    Ok, I think I'll leave this as-is then. An alternative would be to append a short comment to this line:

            static_assert(sizeof(void*) == 4 || sizeof(void*) == 8); // Only 32-bit or 64-bit supported for now
    

    Edit: If you want me to add the trailing comment, leave a comment here or in https://github.com/bitcoin/bitcoin/pull/36042

  89. DrahtBot removed the label CI failed on Nov 17, 2026
  90. DrahtBot removed the label Needs rebase on Nov 17, 2026
  91. l0rinc approved
  92. l0rinc commented at 1:26 PM on November 17, 2026: contributor

    ACK fa9a4ddbaf16d7fc8f8c336600674b3c7facca16

    Nit: PR description needs update, AssertUnreachable doesn't call assertion_fail anymore.

  93. DrahtBot requested review from hodlinator on Nov 17, 2026
  94. DrahtBot requested review from hebasto on Nov 17, 2026
  95. hodlinator approved
  96. hodlinator commented at 4:06 PM on November 18, 2026: contributor

    re-ACK fa9a4ddbaf16d7fc8f8c336600674b3c7facca16

    Changes since previous review (https://github.com/bitcoin/bitcoin/pull/36087#pullrequestreview-5919415158):

    • Added commit to move unreachable assert from runtime to compile time
    • Switched to explicit regexp dialect with broader compatibility
    • Avoided implying some asserts being non-fatal in linter diagnostic, thanks!
    • Fall-through in switch
    • Use of AssertUnreachable() over abort() to make unreachability explicit
    • Cleaner use of Assert(blah) over if (!blah) { AssertUnreachable(); }
    • More accurate motivation for excluding tinyformat, thanks!
  97. jeanpablojp commented at 6:01 PM on November 18, 2026: contributor

    tACK fa9a4ddbaf16d7fc8f8c336600674b3c7facca16

  98. fanquake requested review from ryanofsky on Nov 18, 2026
  99. ryanofsky approved
  100. ryanofsky commented at 9:11 PM on November 20, 2026: contributor

    Code review ACK fa9a4ddbaf16d7fc8f8c336600674b3c7facca16. Nice cleanup making code more consistent, and I like the clever approach to updating includes in the scripted-diff

  101. ryanofsky assigned ryanofsky on Nov 20, 2026
  102. ryanofsky merged this on Nov 20, 2026
  103. ryanofsky closed this on Nov 20, 2026

  104. maflcko deleted the branch on Nov 23, 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-25 08:51 UTC

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