mining: handle negative and NaN wait timeouts #36940

pull enochaz wants to merge 3 commits into bitcoin:master from enochaz:11-26-mining-timeout-nan changing 5 files +59 −4
  1. enochaz commented at 4:54 PM on November 21, 2026: contributor

    An ipc client can pass any timeout to waitTipChanged, but the code assumes it is never negative:

    Assume(timeout >= 0ms); // No internal callers should use a negative timeout
    

    On debug builds, a negative or NaN timeout fails this check and aborts the node. I reproduced this with a timeout of -1.0.

    On release builds the check is skipped. Negative values are clamped to zero, but NaN is not, because every comparison with NaN is false. It ends up as the deadline passed to wait_until.

    waitNext has no Assume, but it also doesn't check its timeout. A NaN timeout waits one extra fee tick (about one second) before returning.

    waitTipChanged and waitNext now throw an error for negative or NaN timeouts. The internal Assume in WaitTipChanged still checks internal callers. The interface documents the errors, and the functional test covers rejection of negative and NaN timeouts and acceptance of positive infinity in both methods.

    I'm not aware of any client that sends these values (sv2-tp, for example, requires an interval of at least one second), so this is hardening against bad input from ipc clients.

    This is similar to #36520, which handles invalid arguments to the Chain interface for the same reason.

    Links

    <!-- *** Please remove the following help text before submitting: *** Pull requests may be closed immediately if they: - do not have a rationale and clear improvement - do not adhere to doc/AI_POLICY.md GUI-related pull requests should be opened against https://github.com/bitcoin-core/gui first. See CONTRIBUTING.md -->

    <!-- Please provide clear motivation for your patch and explain how it improves Bitcoin Core user experience or Bitcoin Core developer experience significantly: * Any test improvements or new tests that improve coverage are always welcome. * All other changes should have accompanying unit tests (see `src/test/`) or functional tests (see `test/`). Contributors should note which tests cover modified code. If no tests exist for a region of modified code, new tests should accompany the change. * Bug fixes are most welcome when they come with steps to reproduce or an explanation of the potential issue as well as reasoning for the way the bug was fixed. * Features are welcome, but might be rejected due to design or scope issues. If a feature is based on a lot of dependencies, contributors should first consider building the system outside of Bitcoin Core, if possible. * Refactoring changes are only accepted if they are required for a feature or bug fix or otherwise improve developer experience significantly. For example, most "code style" refactoring changes require a thorough explanation why they are useful, what downsides they have and why they *significantly* improve developer experience or avoid serious programming bugs. Note that code style is often a subjective matter. Unless they are explicitly mentioned to be preferred in the [developer notes](/doc/developer-notes.md), stylistic code changes are usually rejected. -->

    <!-- Bitcoin Core has a thorough review process and even the most trivial change needs to pass a lot of eyes and requires non-zero or even substantial time effort to review. There is a huge lack of active reviewers on the project, so patches often sit for a long time. -->

  2. DrahtBot added the label Mining on Nov 21, 2026
  3. DrahtBot commented at 4:54 PM on November 21, 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
    Stale ACK nervana21, ryanofsky

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

    LLM Linter (✨ experimental)

    Possible places where comparison-specific test macros should replace generic comparisons:

    • test/functional/interface_ipc_mining.py: assert template8 is None → Prefer assert_equal(template8, None).
    • test/functional/test_framework/ipc_util.py: assert wait_done >= do_called → Prefer assert_greater_than_or_equal(wait_done, do_called).

    <sup>2026-11-30 15:01:37</sup>

  4. enochaz force-pushed on Nov 21, 2026
  5. enochaz renamed this:
    mining: handle negative and NaN waitTipChanged timeouts
    mining: handle negative and NaN wait timeouts
    on Nov 21, 2026
  6. DrahtBot added the label Needs rebase on Nov 21, 2026
  7. enochaz force-pushed on Nov 21, 2026
  8. nervana21 commented at 7:59 PM on November 21, 2026: contributor

    Concept ACK

  9. DrahtBot removed the label Needs rebase on Nov 21, 2026
  10. in test/functional/interface_ipc_mining.py:342 in e1bee89d32
     335 | @@ -330,6 +336,15 @@ async def create_block():
     336 |                  waitoptions.timeout = self.no_event_timeout_ms
     337 |                  template7 = await mining_wait_next_template(template6, stack, ctx, waitoptions)
     338 |                  assert template7 is None
     339 | +
     340 | +                self.log.debug("Negative or NaN timeout times out without a new template")
     341 | +                waitoptions.feeThreshold = MAX_MONEY
     342 | +                for timeout in (-1.0, float("nan")):
    


    Sjors commented at 2:13 PM on November 23, 2026:

    Might as well also cover "-inf" (rejected) and "inf" (accepted).


    enochaz commented at 3:40 PM on November 23, 2026:

    Done. -inf is now tested alongside -1.0 and NaN as rejected.

  11. Sjors commented at 2:40 PM on November 23, 2026: member

    Thanks.

    Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0.

  12. enochaz force-pushed on Nov 23, 2026
  13. enochaz commented at 3:42 PM on November 23, 2026: contributor

    Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0.

    Thanks, done. waitTipChanged and waitNext now throw an error for negative or NaN timeouts instead of clamping them.

  14. in src/node/interfaces.cpp:972 in 758ae2c916
     967 | @@ -965,6 +968,8 @@ class MinerImpl : public Mining
     968 |  
     969 |      std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
     970 |      {
     971 | +        // Timeout can come from an IPC client, reject negative and NaN values.
     972 | +        if (!(timeout >= 0ms)) throw std::runtime_error("Invalid timeout: must not be negative or NaN");
    


    ryanofsky commented at 4:45 PM on November 23, 2026:

    In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945)

    The commit message and PR description still describe the previous push: the commit says negative and NaN timeouts are treated as zero, and the PR description says the Assume is removed. Now that these calls throw and the Assume stays, both should be updated. The commit subject could also mention waitNext, for example "mining: reject negative and NaN wait timeouts from IPC clients", and NaN is spelled "Nan" in two places.


    enochaz commented at 8:56 AM on November 25, 2026:

    Made the changes here, updated both. They now say that waitTipChanged and waitNext reject negative and NaN timeouts. The internal Assume stays

  15. in src/node/interfaces.cpp:928 in 758ae2c916
     923 | @@ -923,6 +924,8 @@ class BlockTemplateImpl : public BlockTemplate
     924 |  
     925 |      std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options) override
     926 |      {
     927 | +        // Timeout can come from an IPC client, reject negative and NaN values.
     928 | +        if (!(options.timeout >= 0ms)) throw std::runtime_error("Invalid timeout: must not be negative or NaN");
    


    ryanofsky commented at 4:45 PM on November 23, 2026:

    In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945)

    nit: could say why the comparison is negated, here and in waitTipChanged, so it doesn't get simplified to timeout < 0ms, which would accept NaN:

    // Timeout can come from an IPC client, so reject negative and NaN values.
    // The negated comparison is also true for NaN.
    

    enochaz commented at 8:53 AM on November 25, 2026:

    Thanks, added a comment at both checks explaining that the negated comparison also catches NaN.

  16. DrahtBot added the label CI failed on Nov 23, 2026
  17. DrahtBot commented at 4:48 PM on November 23, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/45207773992/job/137808054907</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU added a missing <compare> include to src/node/interfaces.cpp, leaving an uncommitted diff that the check rejects.</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>

  18. in src/node/interfaces.cpp:84 in 758ae2c916 outdated
      80 | @@ -81,6 +81,7 @@
      81 |  #include <map>
      82 |  #include <memory>
      83 |  #include <optional>
      84 | +#include <stdexcept>
    


    ryanofsky commented at 5:31 PM on November 23, 2026:

    In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945)

    The iwyu CI job is failing because the new timeout >= 0ms comparisons need <compare>. Adding #include <compare> after #include <atomic> a few lines above should fix it. That one line is the whole diff the job prints.


    enochaz commented at 8:51 AM on November 25, 2026:

    Thanks, added <compare> after <atomic>

  19. ryanofsky approved
  20. ryanofsky commented at 5:41 PM on November 23, 2026: contributor

    Code review ACK 758ae2c916eb8d2127ab1949b9630cf4348b8945. This stops an IPC client from crashing debug builds of the node by passing a negative or NaN timeout to waitTipChanged, and from turning a NaN timeout into a wait_until deadline in release builds. Rejecting these values in node/interfaces.cpp, as Sjors suggested, is the same way #36520 handles invalid Chain arguments, and it lets the internal Assume stay.

    This issue was also reported privately in two security audits: [1] found the negative and NaN timeout problem and reproduced the abort, and [2] suggested rejecting non-finite values when libmultiprocess reads any duration from the wire, which could stop this kind of bug from coming back with new duration parameters.

  21. enochaz force-pushed on Nov 25, 2026
  22. enochaz commented at 9:10 AM on November 25, 2026: contributor

    Thanks for the reviews, resolved the iwyu issues and updated the commit and pr descriptions to match the recent changes

  23. DrahtBot removed the label CI failed on Nov 25, 2026
  24. nervana21 commented at 5:33 PM on November 25, 2026: contributor

    tACK 2bfe24e3ad8be86c76a6530ea056964c50cc1ca9

  25. DrahtBot requested review from ryanofsky on Nov 25, 2026
  26. in test/functional/interface_ipc_mining.py:358 in 2bfe24e3ad
     353 | +                    inf_waitoptions = self.capnp_modules['mining'].BlockWaitOptions()
     354 | +                    inf_waitoptions.timeout = float("inf")
     355 | +                    inf_waitoptions.feeThreshold = MAX_MONEY
     356 | +                    template8 = await mining_wait_next_template(template6, stack, ctx, inf_waitoptions)
     357 | +                    assert template8 is None
     358 | +                await wait_and_do(wait_for_block_inf(), template6.interruptWait())
    


    ryanofsky commented at 7:03 PM on November 25, 2026:

    In commit "mining: reject negative and NaN wait timeouts from IPC clients" (2bfe24e3ad8be86c76a6530ea056964c50cc1ca9)

    These "Infinite timeout is accepted" tests, here and in the waitTipChanged test above, check that an infinite timeout isn't rejected, but not that the call actually waits. They would also pass if an infinite timeout made waitNext or waitTipChanged return immediately, for example because it was clamped to zero. template6.interruptWait() is evaluated as an argument to wait_and_do, and pycapnp sends the request right then, so the interrupt reaches the node before the wait starts and the wait returns immediately. I measured both waits returning in under 4ms instead of after wait_and_do's 0.1s sleep. The Ralph review pointed out the waitNext case.

    Passing the method without calling it (template6.interruptWait rather than template6.interruptWait()) lets wait_and_do call it after the sleep. To catch the problem, wait_and_do could take an optional check_order argument that asserts the wait finished after do_fn was called, used here for the two new tests. I checked that this passes with the current code and fails with wait finished 0.097s before do_fn was called if waitNext treats an infinite timeout as zero:

    diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py
    --- a/test/functional/interface_ipc_mining.py
    +++ b/test/functional/interface_ipc_mining.py
    @@ -168,7 +168,7 @@ class IPCMiningTest(BitcoinTestFramework):
                 async def wait_for_tip_inf():
                     result = (await mining.waitTipChanged(ctx, newblockref.hash, float("inf"))).result
                     assert_equal(len(result.hash), 0)
    -            await wait_and_do(wait_for_tip_inf(), mining.interrupt())
    +            await wait_and_do(wait_for_tip_inf(), mining.interrupt, check_order=True)
    
                 self.log.debug("interrupt() should abort waitTipChanged()")
                 async def wait_for_tip():
    @@ -355,7 +355,7 @@ class IPCMiningTest(BitcoinTestFramework):
                         inf_waitoptions.feeThreshold = MAX_MONEY
                         template8 = await mining_wait_next_template(template6, stack, ctx, inf_waitoptions)
                         assert template8 is None
    -                await wait_and_do(wait_for_block_inf(), template6.interruptWait())
    +                await wait_and_do(wait_for_block_inf(), template6.interruptWait, check_order=True)
                     waitoptions.timeout = self.default_ipc_timeout_ms
    
                     self.log.debug("interruptWait should abort the current wait")
    diff --git a/test/functional/test_framework/ipc_util.py b/test/functional/test_framework/ipc_util.py
    --- a/test/functional/test_framework/ipc_util.py
    +++ b/test/functional/test_framework/ipc_util.py
    @@ -10,6 +10,7 @@ from dataclasses import dataclass
     from io import BytesIO
     from pathlib import Path
     import shutil
    +import time
     from typing import Optional
    
     from test_framework.messages import CBlock
    @@ -45,20 +46,31 @@ async def destroying(obj, ctx):
             await obj.destroy(ctx)
    
    
    -async def wait_and_do(wait_fn, do_fn, sleep_time=0.1):
    +async def wait_and_do(wait_fn, do_fn, sleep_time=0.1, check_order=False):
         """Call wait_fn, then sleep, then call do_fn in a parallel task. Wait for
    -    both tasks to complete."""
    +    both tasks to complete.
    +
    +    With check_order, assert that wait_fn finishes after do_fn is called, to
    +    catch waits that return early instead of being ended by do_fn. Pass do_fn
    +    as a callable for this: pycapnp sends an IPC request when the method is
    +    called, so cap.method() passed directly reaches the server before the
    +    wait starts."""
         wait_started = asyncio.Event()
         result = None
    +    wait_done = None
    +    do_called = None
    
         async def wait():
    -        nonlocal result
    +        nonlocal result, wait_done
             wait_started.set()
             result = await wait_fn
    +        wait_done = time.monotonic()
    
         async def do():
    +        nonlocal do_called
             await wait_started.wait()
             await asyncio.sleep(sleep_time)
    +        do_called = time.monotonic()
             # Let do_fn be either a callable or an awaitable object
             if inspect.isawaitable(do_fn):
                 await do_fn
    @@ -66,6 +78,8 @@ async def wait_and_do(wait_fn, do_fn, sleep_time=0.1):
                 do_fn()
    
         await asyncio.gather(wait(), do())
    +    if check_order:
    +        assert wait_done >= do_called, f"wait finished {do_called - wait_done:.3f}s before do_fn was called"
         return result
    
    
    

    The interrupt tests already on master have the same problem: the interrupt() test for waitTipChanged, the createNewBlock cooldown test and the interruptWait() test all pass the IPC call itself, so the interrupt is sent before the wait starts. The cooldown test also has no cooldown to interrupt: the previous step submits the announced block, so the tip has caught up. With the interrupt sent at the right time, createNewBlock returns a template and the test fails; announcing a header for a new block first fixes it.

    A follow-up could fix these three tests, make check_order the default so every wait_and_do caller gets the check, and require do_fn to be a callable (awaiting what it returns) so an IPC call can't be passed directly again. I tried that version with all five call sites passing the method uncalled and the cooldown test fixed, and the test passes. That could be done here as well, or separately.


    enochaz commented at 6:56 PM on November 26, 2026:

    Good point, I checked this locally by timing the wait in the infinite timeout tests. With the interrupt passed as a call the wait returned in about 1ms, and after passing it uncalled it took about 105ms, so it now actually waits for the interrupt.

    Added your check_order change in a separate commit and used it for both tests, also added you as the co author. Thanks

    The existing interrupt tests have the same issue, so they could use check_order too. Making it the default and only accepting a callable would also stop this from coming back. I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling.


    ryanofsky commented at 2:39 PM on November 30, 2026:

    re: #36940 (review)

    I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling.

    Makes sense, thanks for applying this and for checking the timing. Doing the existing tests separately keeps this PR focused, and the cooldown test needs its setup fixed as well, which is unrelated to timeouts.

    The Ralph review points out two more things that would fit the follow-up: wait_and_do calls do_fn without awaiting what it returns, so an error from the interrupt call is dropped, and with an infinite timeout a broken interrupt would make the test hang instead of fail, which an asyncio.wait_for deadline around those waits would prevent.

  27. ryanofsky approved
  28. ryanofsky commented at 8:13 PM on November 25, 2026: contributor

    Code review ACK 2bfe24e3ad8be86c76a6530ea056964c50cc1ca9. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a wait_until deadline in release builds.

    Thanks for the quick updates, this addresses all my earlier comments. One test suggestion inline: the new infinite-timeout checks don't test what they're meant to, because of how the interrupt is sent.

  29. test: add check_order option to wait_and_do
    Add an optional check_order argument that asserts the wait finishes
    after the interrupt is sent.
    
    Passing an IPC call directly sends the request before the wait starts,
    so the wait can return early and the test still passes.
    
    Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
    44dbc7c835
  30. mining: reject negative and NaN wait timeouts from IPC clients
    Mining IPC clients can pass negative or NaN timeouts. Reject these
    values in waitTipChanged and waitNext before calling the block template
    manager. The internal Assume in WaitTipChanged continues to check
    internal callers.
    
    Document the error in both interfaces and test rejection of invalid
    timeouts and acceptance of positive infinity over IPC. Check that
    waits with an infinite timeout last until they are interrupted.
    525d69e3f9
  31. enochaz force-pushed on Nov 26, 2026
  32. enochaz commented at 7:03 PM on November 26, 2026: contributor

    Thanks for the review @ryanofsky, split the test change into a separate commit that adds check_order to wait_and_do, and used it for both infinite timeout tests so they now check the wait actually lasts until the interrupt. Will open a follow-up for the existing interrupt tests

  33. in src/node/interfaces.cpp:973 in 525d69e3f9 outdated
     968 | @@ -965,6 +969,8 @@ class MinerImpl : public Mining
     969 |  
     970 |      std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
     971 |      {
     972 | +        // Timeout can come from an IPC client. The negated comparison also catches NaN.
     973 | +        if (!(timeout >= 0ms)) throw std::runtime_error("Invalid timeout: must not be negative or NaN");
    


    ryanofsky commented at 2:40 PM on November 30, 2026:

    In commit "mining: reject negative and NaN wait timeouts from IPC clients" (525d69e3f9c258e61c4dde540ec0722470eab2df)

    Since IPC clients can see this change, it could use a release note, like the one in the 32.1 notes for #33966 ("The IPC mining interface now rejects out-of-range block template options instead of silently clamping them"). The Ralph review suggested this too. Maybe a doc/release-notes-36940.md like:

    Mining
    ------
    
    - The IPC mining interface now rejects negative and NaN timeouts passed to
      `waitTipChanged` and `waitNext`. Previously, release builds treated a
      negative timeout as zero and could misbehave on NaN, and debug builds
      aborted. (#36940)
    

    enochaz commented at 3:03 PM on November 30, 2026:

    Thanks, added it here with some slight changes. It documents the behaviour this pr changes, so it made more sense here than in the follow up.

  34. ryanofsky approved
  35. ryanofsky commented at 2:42 PM on November 30, 2026: contributor

    Code review ACK 525d69e3f9c258e61c4dde540ec0722470eab2df. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a wait_until deadline in release builds.

    Thanks for adding the check_order commit! Left some possible followup suggestions but no changes need to be made here.

  36. doc: add release note for rejected IPC wait timeouts
    Negative and NaN wait timeouts from IPC clients are now rejected.
    Add a release note so client authors know about the change.
    d293ef600d
  37. enochaz commented at 3:06 PM on November 30, 2026: contributor

    Thanks for the review @ryanofsky, added a release note in a separate commit. The test suggestions will go in the follow up.


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-12-01 02:51 UTC

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