kernel, validation: Add btck_chainstate_manager_set_clock_time #35557

pull ryanofsky wants to merge 4 commits into bitcoin:master from ryanofsky:pr/kclock changing 11 files +209 −19
  1. ryanofsky commented at 2:52 AM on June 18, 2026: contributor

    Problem: Kernel applications can only override the time validation uses for the whole process, with btck_set_mock_time (#35496). Every chainstate manager in the process sees the same time, so a time set for one test, run, or thread leaks into the others unless the application remembers to reset it.

    Solution: Add btck_chainstate_manager_options_set_clock_time and btck_chainstate_manager_set_clock_time, which set the time for a single chainstate manager, before it is created (so it also applies to checks made while it loads the chainstate) and afterwards. Validation code gets the time from a new ChainstateManager::Now() method instead of calling NodeClock::now() directly. Details are in the commit messages.

    Keeping the time in the chainstate manager instead of in a global makes kernel applications more reliable, because state from one run or thread can't affect another.

    Other commits:

    • The first commit fixes a rare timing race in the chainstatemanager_ibd_exit_after_loading_blocks test, where test code and validation code read the clock separately and assumed they got the same time.
    • The last two commits switch that test and the utxo_total_supply fuzz target to the new per-chainman clock, as suggested in #35557 (comment).

    Two related commits that were previously part of this PR are in a follow-up branch based on it, https://github.com/ryanofsky/bitcoin/commits/pr/kclock2: a mempool refactor to represent clock times consistently, and a change that makes NodeClock::now() unavailable in libbitcoinkernel so kernel code can't use the system clock by accident.

  2. DrahtBot commented at 2:52 AM on June 18, 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. A summary of reviews will appear here.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36856 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36856.svg"></sub> (kernel: add manual pruning by pzafonte)
    • #36854 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36854.svg"></sub> (kernel: let callers create the block manager by pzafonte)
    • #36543 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36543.svg"></sub> (validation: check the most recent AssumeUTXO commitment during IBD by l0rinc)
    • #35906 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35906.svg"></sub> (First steps towards a stateless, side-effect free validation library by purpleKarrot)
    • #35570 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35570.svg"></sub> (refactor: Change some validation.cpp methods to return BlockValidationState by optout21)
    • #35187 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35187.svg"></sub> (kernel: Block validation without a complete UTXO set by sedited)
    • #33847 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/33847.svg"></sub> (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky)
    • #26022 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/26022.svg"></sub> (Add util::ResultPtr class by ryanofsky)
    • #25665 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/25665.svg"></sub> (refactor: Add util::Result failure types and ability to merge result values by ryanofsky)

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

  3. DrahtBot added the label CI failed on Jun 18, 2026
  4. DrahtBot commented at 4:07 AM on June 18, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/27733525041/job/82045427048</sub> <sub>LLM reason (✨ experimental): CI failed because the IWYU (include-what-you-use) check reported changes needed (generated “Failure generated from IWYU”).</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>

  5. in src/node/chainstate.cpp:251 in 9f67c9b269
     247 | @@ -248,7 +248,7 @@ ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const C
     248 |      for (auto& chainstate : chainman.m_chainstates) {
     249 |          if (!is_coinsview_empty(*chainstate)) {
     250 |              const CBlockIndex* tip = chainstate->m_chain.Tip();
     251 | -            if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
     252 | +            if (tip && tip->nTime > TicksSinceEpoch<std::chrono::seconds>(chainman.Now()) + MAX_FUTURE_BLOCK_TIME) {
    


    maflcko commented at 5:02 AM on June 18, 2026:

    9f67c9b269cbc0da459eafa1a5ba357e82f07212: You can use tip->Time(), to avoid the cast here.

    Generally, it is better to use the chrono types and let the compiler do the type checks. After compilation, there won't be a difference anyway.


    ryanofsky commented at 1:55 PM on June 18, 2026:

    re: #35557 (review)

    9f67c9b: You can use tip->Time(), to avoid the cast here.

    Thanks! That is so much better and I applied this many places

  6. in src/util/time.h:82 in 7d656ac341
      76 | @@ -66,6 +77,13 @@ struct MockableSteadyClock : public std::chrono::steady_clock {
      77 |      static void ClearMockTime();
      78 |  };
      79 |  
      80 | +/** Convert a time point into a duration of specified precision. */
      81 | +template <typename Duration, typename Timepoint>
      82 | +constexpr auto DurationSinceEpoch(Timepoint t)
    


    maflcko commented at 5:12 AM on June 18, 2026:

    Seems fine, but this may be promoting ugly code, such as count_seconds(DurationSinceEpoch<std::chrono::seconds>(...

    I think generally it is better to use the correct std chrono type and let the compiler do the type checks. Casting a time point to a duration (since epoch) seems like a violation that should be avoided, for the same reasons that GetTime is deprecated.

    At call sites you can just replace block->GetBlockTime() with block->Time() to avoid any casts, and this helper.


    ryanofsky commented at 1:56 PM on June 18, 2026:

    re: #35557 (review)

    Seems fine, but this may be promoting ugly code

    You're right, dropped this now

  7. in src/validation.h:1020 in 9f67c9b269
    1015 | +     * library users can control clock times used for validation.
    1016 | +     */
    1017 | +    NodeSeconds Now() const
    1018 | +    {
    1019 | +        const auto clock{m_clock_now_seconds.load(std::memory_order_relaxed)};
    1020 | +        return clock != std::chrono::seconds{0} ? NodeSeconds{clock} : std::chrono::time_point_cast<std::chrono::seconds>(NodeClock::now());
    


    maflcko commented at 5:17 AM on June 18, 2026:

    Do we really want the cast here? The answer is probably, "doesn't matter", because consensus time checks are seconds-based, and the double-precision rolling update mempool code doesn't care about sub-second precision. Though, I wanted to point it out, that this is intentional and not just something that was most likely to the LLM.

    An alternative could be to remove the cast here and only add the cast in call sites that need it (implicilty "upgrading" the call-sites to sub-second precision)


    ryanofsky commented at 2:03 PM on June 18, 2026:

    re: #35557 (review)

    Do we really want the cast here?

    I don't think so. It's definitely simpler not to have this and it is dropped now.

    Though, I wanted to point it out, that this is intentional and not just something that was most likely to the LLM.

    I guess it's fair to blame the LLM for this. Technically I added this cast, but the LLM originally wrote ::Now<NodeSeconds>() which was casting internally. Smarter to avoid it entirely.

  8. ryanofsky commented at 9:52 AM on June 18, 2026: contributor

    Thanks @maflcko! I was very dissatisfied with all the casts in the second commit and your tips should be helpful for getting rid of them. I will also implement your suggestion to not cast away precision in ChainstateManager::Now(). (The LLM actually didn't write the cast, but called ::Now<NodeSeconds>() instead and I manually added the cast to try to be more explicit.)

  9. ryanofsky force-pushed on Jun 18, 2026
  10. ryanofsky commented at 2:10 PM on June 18, 2026: contributor

    Updated 7d656ac341140dc80f73abcc45adc19f0430eaae -> 94622b041571f73e8e5e661b9bce4213b957a561 (pr/kclock.1 -> pr/kclock.2, compare)<!-- end --> adding a new commit to use time points to represent times in mempool code

    <!-- begin push-3 -->

    Updated 94622b041571f73e8e5e661b9bce4213b957a561 -> 27ea72916b71e40859d7d86348eb3d99c4211b34 (pr/kclock.2 -> pr/kclock.3, compare)<!-- end --> to fix CI: compile error (duration_cast on time_point in TRACEPOINT calls) and nondeterministic test (clock race in chainstatemanager_ibd_exit_after_loading_blocks); also prepends a standalone test fix commit using only pre-existing SetMockTime API https://github.com/bitcoin/bitcoin/actions/runs/27764264509/job/82146558123

    <!-- begin push-4 -->

    Updated 27ea72916b71e40859d7d86348eb3d99c4211b34 -> 8be500e6bec2e4e664f36dea22c6419237ba9ec2 (pr/kclock.3 -> pr/kclock.4, compare)<!-- end --> to fix fuzz UBSan signed integer overflow converting seconds to nanoseconds in ConsumeTxMemPoolEntry https://github.com/bitcoin/bitcoin/actions/runs/15491561394/job/82175291056

    <!-- begin push-5 -->

    Updated 8be500e6bec2e4e664f36dea22c6419237ba9ec2 -> 37fb1b596e2006ffb1af82945f81a27c2bc1777a (pr/kclock.4 -> pr/kclock.5, compare)<!-- end --> to fix UBSan signed-integer-overflow: throw in LoadMempool when nTime is out of MempoolTime range; also use ConsumeTime() in ConsumeTxMemPoolEntry https://github.com/bitcoin/bitcoin/actions/runs/27776901912/job/82191293065

  11. in src/test/fuzz/tx_pool.cpp:162 in 94622b0415 outdated
     158 | @@ -159,7 +159,7 @@ void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, Cha
     159 |      if (fuzzed_data_provider.ConsumeBool()) {
     160 |          // Try expiry
     161 |          LOCK2(::cs_main, tx_pool.cs);
     162 | -        tx_pool.Expire(GetMockTime() - std::chrono::seconds(fuzzed_data_provider.ConsumeIntegral<uint32_t>()));
     163 | +        tx_pool.Expire(NodeSeconds{GetMockTime() - std::chrono::seconds(fuzzed_data_provider.ConsumeIntegral<uint32_t>())});
    


    maflcko commented at 2:24 PM on June 18, 2026:

    probably not a problem in reality, but the call to GetMockTime here looks wrong for several reasons:

    • It directly access the test-only global of the mock time, which may be 0, and thus may lead to silent bugs if mocktime was not used here?
    • It side-steps the g_used_system_time runtime sanitizer.
    • It returns the wrong type (it should be a time point, not a duration)

    I guess it would be better to just call Now() or tx_pool.Now() to fix all issues and avoid the NodeSeconds{} cast.


    ryanofsky commented at 8:45 PM on June 18, 2026:

    re: #35557 (review)

    Makes sense, switched GetMockTime() -> Now()

  12. ryanofsky force-pushed on Jun 18, 2026
  13. ryanofsky force-pushed on Jun 18, 2026
  14. ryanofsky force-pushed on Jun 18, 2026
  15. DrahtBot removed the label CI failed on Jun 18, 2026
  16. ryanofsky marked this as ready for review on Jun 18, 2026
  17. ryanofsky commented at 9:01 PM on June 18, 2026: contributor

    Marked ready for review now that CI is passing. Possible questions for reviewers:

    • Should this PR be split up? I am thinking of dropping everything except the main commit 8a93ea0f2904ec780a690d987a25e5fa113552c9 and moving other commits to a followup PR. But happy to do anything.
    • Is btck_chainstate_manager_set_clock_time(chainman, now) a good kernel API? I think it is, giving applications control over time in a pretty granular way that doesn't get in the way of adding more control later.
    • Are the changes to validtion code ok? There's a new ChainstateManager::m_clock_now_seconds field which adds new state, but not much changes otherwise and the changes make code more consistent.
  18. sedited commented at 10:05 PM on June 21, 2026: contributor

    Should this PR be split up?

    My preference is larger pull requests usually, so I would keep this in one piece, but I would go a bit further. Can we use this new clock in one of the tests (maybe one of the utxo* fuzz tests, haven't looked too closely yet).

    Is btck_chainstate_manager_set_clock_time(chainman, now) a good kernel API?

    If we set it in the options instead, we can fake the time once per instance, if we set it like here, it can be moved any number of times. I think I prefer that, as it seems to overlap more closely with the current global mechanics. The only reservation I have with this is that there might be a case where the clock needs to be set during chainman construction. I don't think that is the case right now, but that might change in the future.

    Are the changes to validation code ok?

    I would feel more confident if something (a test, a utility, etc.) was actually exercising the various instances where the chainman-scoped fake time is used now.

  19. stickies-v commented at 2:44 PM on June 23, 2026: contributor
    • Is btck_chainstate_manager_set_clock_time(chainman, now) a good kernel API? I think it is, giving applications control over time in a pretty granular way that doesn't get in the way of adding more control later.

    This could get a bit annoying and potentially dangerous when users need to start managing clocks across multiple places. Perhaps a more ergonomic alternative could be to add a btck_Clock type which basically is just a callback that returns the current time? The callback can then be anything, e.g. a fixed value, the user's system time, a mocked clock, ...

    That way, a single clock can be passed multiple times, and updated in a single place. Of course, it comes with its costs of increased API surface and lifetime concerns that a simple seconds setter doesn't have.

  20. in src/test/validation_chainstatemanager_tests.cpp:179 in 37fb1b596e
     172 | @@ -172,6 +173,11 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
     173 |  
     174 |  BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTestingSetup)
     175 |  {
     176 | +    // Freeze the clock to avoid a race where Now<NodeSeconds>() in test setup
     177 | +    // and Now<NodeSeconds>() inside IsTipRecent() straddle a second boundary,
     178 | +    // causing a spurious failure in the tip_recent=true case.
     179 | +    SetMockTime(Now<NodeSeconds>());
    


    seduless commented at 3:47 AM on June 25, 2026:

    In commit "test: Fix nondeterministic clock race in chainstatemanager_ibd_exit_after_loading_blocks" (f0fea79bdaabbea40f1177702ff2c169d82f62be)

    Nice fix, thanks for cleaning this up.

    Instead of bare SetMockTime calls, this is a good candidate for the RAII FakeNodeClock.

    diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
    index b0176f641c..3c357844cd 100644
    --- a/src/test/validation_chainstatemanager_tests.cpp
    +++ b/src/test/validation_chainstatemanager_tests.cpp
    @@ -18,2 +18,3 @@
     #include <test/util/setup_common.h>
    +#include <test/util/time.h>
     #include <test/util/validation.h>
    @@ -22,3 +23,2 @@
     #include <util/result.h>
    -#include <util/time.h>
     #include <util/vector.h>
    @@ -178,3 +178,3 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTe
         // causing a spurious failure in the tip_recent=true case.
    -    SetMockTime(Now<NodeSeconds>());
    +    FakeNodeClock clock{};
    
    @@ -214,3 +214,2 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTe
         }
    -    SetMockTime(0);
     }
    

    ryanofsky commented at 12:11 AM on June 29, 2026:

    re: #35557 (review)

    Instead of bare SetMockTime calls, this is a good candidate for the RAII FakeNodeClock.

    Thanks! Applied your patch and switched to FakeNodeClock

  21. sedited added this to a project on Jun 25, 2026
  22. github-project-automation[bot] changed the project status on Jun 25, 2026
  23. sedited changed the project status on Jun 25, 2026
  24. ryanofsky referenced this in commit 1ae28a4013 on Jun 29, 2026
  25. ryanofsky force-pushed on Jun 29, 2026
  26. ryanofsky referenced this in commit 12a237f9d3 on Jun 29, 2026
  27. ryanofsky force-pushed on Jun 29, 2026
  28. DrahtBot added the label CI failed on Jun 29, 2026
  29. DrahtBot commented at 1:08 AM on June 29, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task Windows native, fuzz, VS: https://github.com/bitcoin/bitcoin/actions/runs/28340730799/job/83954616764</sub> <sub>LLM reason (✨ experimental): CI failed because the fuzz test corpus runner hit an error in the utxo_total_supply target (fuzz.exe exit code 1 processing a specific input).</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>

  30. ryanofsky commented at 1:30 AM on June 29, 2026: contributor

    re: sedited #35557 (comment)

    I would keep this in one piece

    Thanks, kept all commits for now and added new tests as suggested.

    re: stickies-v #35557 (comment)

    Perhaps a more ergonomic alternative could be to add a btck_Clock type which basically is just a callback that returns the current time?

    This is an interesting idea. Implemented in 3d513c5d03ceb8d33dc8e19c07149e3337c64ac6 to see what it would look like.

    The implementation barely even affects validation code so I think the main question is does it seem safer or easier to use for kernel applications?

    My instinct is that it doesn't because if you're creating multiple chainstate managers or other objects that accept times, and your application needs artificial times instead of the current clock time, I wouldn't assume that multiple objects would want to have the same time set. Or if they did, I wouldn't assume that setting the time once on a shared clock object would be much easier than setting the time directly on the relevant objects.

    But I also think this alternate API is clean, and would have no problem switching to this approach. It also seems like it wouldn't be hard to switch approaches later (with compatibly even).


    <!-- begin push-6 -->

    Updated 37fb1b596e2006ffb1af82945f81a27c2bc1777a -> 1ae28a401368448cc6466aada72afe2101ae7d61 (pr/kclock.5 -> pr/kclock.6, compare)<!-- end --> adding suggested tests

    <!-- begin push-7 -->

    Updated 1ae28a401368448cc6466aada72afe2101ae7d61 -> 12a237f9d3570f96663dd84550f9fcc25ee53584 (pr/kclock.6 -> pr/kclock.7, compare)<!-- end --> to fix utxo_total_supply fuzz g_used_system_time failure https://github.com/bitcoin/bitcoin/actions/runs/28340730799/job/83954616774

    <!-- begin push-8 -->

    Rebased 12a237f9d3570f96663dd84550f9fcc25ee53584 -> 058d434f3c5b25aef65dd71576576b35dfc9ce27 (pr/kclock.7 -> pr/kclock.8, compare)<!-- end --> due to conflicts with #35496 and #35792

    <!-- begin push-9 -->

    Rebased 058d434f3c5b25aef65dd71576576b35dfc9ce27 -> d364d7e35c3c7b5b9bfc44c4f4cb58fad09aa645 (pr/kclock.8 -> pr/kclock.9, compare)<!-- end --> due to conflicts with #34075

    <!-- begin push-10 -->

    Rebased d364d7e35c3c7b5b9bfc44c4f4cb58fad09aa645 -> 1d3a0270fcf3fcabd2249c4b06a071a32a7b364b (pr/kclock.9 -> pr/kclock.10, compare)<!-- end --> due to conflict with #36103

    <!-- begin push-11 -->

    Rebased 1d3a0270fcf3fcabd2249c4b06a071a32a7b364b -> 0e777d8b302d66360000ad55b6ac1232ac9b62ac (pr/kclock.10 -> pr/kclock.11, compare)<!-- end --> due to conflict with #34844

  31. DrahtBot removed the label CI failed on Jun 29, 2026
  32. willcl-ark added the label Kernel on Jul 9, 2026
  33. willcl-ark added the label Validation on Jul 9, 2026
  34. DrahtBot added the label Needs rebase on Jul 24, 2026
  35. ryanofsky referenced this in commit 058d434f3c on Aug 15, 2026
  36. ryanofsky force-pushed on Aug 15, 2026
  37. DrahtBot removed the label Needs rebase on Aug 15, 2026
  38. maflcko commented at 8:16 AM on August 17, 2026: member

    This is an alternative to #35496, and one of several alternatives discussed in that PR

    That one was merged, so is this here still relevant?

    Also, this conflicts with #35906 (review)

  39. DrahtBot added the label Needs rebase on Aug 21, 2026
  40. ryanofsky referenced this in commit d364d7e35c on Aug 24, 2026
  41. ryanofsky force-pushed on Aug 24, 2026
  42. DrahtBot removed the label Needs rebase on Aug 24, 2026
  43. DrahtBot added the label Needs rebase on Aug 31, 2026
  44. ryanofsky referenced this in commit 1d3a0270fc on Sep 8, 2026
  45. ryanofsky force-pushed on Sep 8, 2026
  46. DrahtBot removed the label Needs rebase on Sep 8, 2026
  47. nervana21 referenced this in commit b4f0f82942 on Oct 6, 2026
  48. DrahtBot added the label Needs rebase on Oct 7, 2026
  49. sedited commented at 12:04 PM on October 26, 2026: contributor

    That one was merged, so is this here still relevant?

    I'm not sure. Some of the test changes seem fine, but not sure if this is worth the squeeze. Maybe @stringintech can chime in?

  50. test: Fix nondeterministic clock race in chainstatemanager_ibd_exit_after_loading_blocks
    The test set up the tip time using Now<NodeSeconds>() and then called
    UpdateIBDStatus(), which calls IsTipRecent(), which also calls
    Now<NodeSeconds>(). If a second boundary was crossed between the two
    calls, the tip_recent=true case would fail spuriously.
    
    Fix by freezing the clock with FakeNodeClock before the test runs.
    
    Co-Authored-By: seduless <seduless@proton.me>
    This change was written with Claude Sonnet 4.6.
    79c304eacd
  51. kernel, validation: scope clock time to ChainstateManager
    Add ChainstateManager::Now() as the single injection point for the
    current time in all validation paths, replacing direct NodeClock::now()
    calls. A new m_clock_now_seconds field (std::atomic<NodeSeconds>)
    lets callers override the time for a chainstate manager instance.
    
    Affected paths:
    - ContextualCheckBlockHeader: future-time check
    - UpdateIBDStatus -> IsTipRecent: IBD latch (IsTipRecent gains a now
      parameter so callers control what time is used)
    - ProcessNewBlockHeaders / ReportHeadersPresync: IBD progress logging
    - GuessVerificationProgress: verification_progress in block tip callbacks
    - VerifyLoadedChainstate: future-tip sanity check on startup
    
    The kernel C API gains btck_chainstate_manager_set_clock_time(chainman,
    now_seconds), and the C++ wrapper gains a matching SetClockTime() method.
    The time can also be set before the chainstate manager is created, with
    btck_chainstate_manager_options_set_clock_time(), so it also applies to
    checks made while the chainstate is loaded (the VerifyLoadedChainstate
    future-tip check and the IBD latch), which run before
    btck_chainstate_manager_set_clock_time() can be called.
    Two concurrent test instances using different chainman objects see
    independent clocks; no cleanup of global state is required between tests.
    
    Note: this commit slightly changes behavior of the
    IsCurrentForFeeEstimation and GuessVerificationProgress functions
    because these function previously did time calculations with 1-second
    precision, and use with system clock level precision (typicaly
    nanoseconds). No other behavior outside of these two functions is
    changing.
    
    Co-Authored-By: stringintech <stringintech@gmail.com>
    Co-Authored-By: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz>
    This change was written with Claude Sonnet 4.6.
    98bb3d3114
  52. test: Use chainman-scoped clock in chainstatemanager_ibd_exit_after_loading_blocks
    Replace SetMockTime() with chainman.m_clock_now_seconds so the clock
    frozen for the race-prevention matches the same clock that
    UpdateIBDStatus/IsTipRecent() reads. This also avoids touching any
    global state and lets the test more directly exercise the new
    chainman-scoped clock path.
    
    This change was written with Claude Sonnet 4.6.
    a4c62cdd8c
  53. test: Use chainman-scoped clock in utxo_total_supply fuzz target
    Replace FakeNodeClock (global mock time) with chainman.m_clock_now_seconds
    so the fuzzed time is set directly on the chainstate manager instance
    rather than via a global. This exercises the IBD and tip-age checks
    through the new per-chainman clock path. Byte consumption order from
    fuzzed_data_provider is unchanged so existing corpus entries remain valid.
    
    Idea for using clock time in utxo fuzz test from sedited in:
    https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4763429282
    
    This change was written with Claude Sonnet 4.6.
    2f6b902f98
  54. ryanofsky referenced this in commit 0e777d8b30 on Oct 30, 2026
  55. ryanofsky force-pushed on Oct 30, 2026
  56. DrahtBot removed the label Needs rebase on Oct 30, 2026
  57. DrahtBot added the label CI failed on Oct 30, 2026
  58. maflcko removed the label CI failed on Oct 30, 2026
  59. in src/kernel/bitcoinkernel.h:1350 in 0e777d8b30 outdated
    1345 | + * @return                        0 on success, non-zero if now_seconds is
    1346 | + *                                negative or exceeds 4294967295.
    1347 | + */
    1348 | +BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_set_clock_time(
    1349 | +    btck_ChainstateManager* chainstate_manager,
    1350 | +    int64_t now_seconds) BITCOINKERNEL_ARG_NONNULL(1);
    


    ryanofsky commented at 11:25 PM on November 6, 2026:

    re: sedited #35557 (comment)

    In commit "kernel, validation: scope clock time to ChainstateManager" (98bb3d311435af967c75998d6eac04c1a8691758)

    Some of the test changes seem fine, but not sure if this is worth the squeeze.

    Thanks, that's fair, and the PR was trying to do too much. I made it smaller: it now has the test race fix, the btck_chainstate_manager_set_clock_time API (now with an options setter too, see the separate comment about construction time), and the two tests using the new clock (chainstatemanager_ibd_exit_after_loading_blocks and the utxo_total_supply fuzz target you suggested). The mempool time point refactor and the commit making NodeClock::now() a link error in kernel code are now in a follow-up branch based on this one: https://github.com/ryanofsky/bitcoin/commits/pr/kclock2. I know you suggested keeping this in one piece, so I can open the follow-up as a PR whenever that would help review.

    On maflcko's question in #35557 (comment): I think this is still relevant. #35496 sets the time for the whole process, and this sets it for one chainstate manager, so a time set for one test, run, or thread can't leak into another.

  60. in src/validation.cpp:4189 in 0e777d8b30 outdated
    4185 | @@ -4186,7 +4186,7 @@ static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidatio
    4186 |      }
    4187 |  
    4188 |      // Check timestamp
    4189 | -    if (block.Time() > NodeClock::now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
    4190 | +    if (block.Time() > chainman.Now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
    


    ryanofsky commented at 11:25 PM on November 6, 2026:

    re: maflcko #35557 (comment)

    In commit "kernel, validation: scope clock time to ChainstateManager" (98bb3d311435af967c75998d6eac04c1a8691758)

    The conflict with #35906 is only textual, and the two changes fit together: #35906 makes ContextualCheckBlockHeader take the time as a parameter, and with this PR its callers would pass chainman.Now() instead of NodeClock::now(). I'd suggest #35906 go first since it has ACKs, and I'll rebase on it.

  61. in src/validation.h:1031 in 0e777d8b30 outdated
    1026 | +     */
    1027 | +    NodeClock::time_point Now() const
    1028 | +    {
    1029 | +        const auto clock{m_clock_now_seconds.load(std::memory_order_relaxed)};
    1030 | +        return clock != std::chrono::seconds{0} ? NodeSeconds{clock} : NodeClock::_now_nondet();
    1031 | +    }
    


    ryanofsky commented at 11:25 PM on November 6, 2026:

    re: stickies-v #35557 (comment)

    In commit "kernel, validation: scope clock time to ChainstateManager" (98bb3d311435af967c75998d6eac04c1a8691758)

    One argument for your callback idea that I missed before: stringintech pointed out in #35496 (comment) that a long call like btck_chainstate_manager_process_block may need to read the time several times, for example when the IBD status is re-checked after each connected block. A fixed time set beforehand can't advance during the call, and a callback can. My prototype in 3d513c5d03ceb8d33dc8e19c07149e3337c64ac6 only made the time a shared settable value, so it didn't really test your suggestion. I still think a setter is simpler to start with, since a fixed time is what deterministic tests and replays want, but I'm happy to switch to a callback if you or others think it's worth the extra API surface.

  62. in src/node/chainstate.cpp:251 in 0e777d8b30 outdated
     247 | @@ -248,7 +248,7 @@ ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const C
     248 |      for (auto& chainstate : chainman.m_chainstates) {
     249 |          if (!is_coinsview_empty(*chainstate)) {
     250 |              const CBlockIndex* tip = chainstate->m_chain.Tip();
     251 | -            if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
     252 | +            if (tip && tip->Time() > chainman.Now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
    


    ryanofsky commented at 11:25 PM on November 6, 2026:

    re: sedited #35557 (comment)

    In commit "kernel, validation: scope clock time to ChainstateManager" (98bb3d311435af967c75998d6eac04c1a8691758)

    there might be a case where the clock needs to be set during chainman construction

    Looking again, there is one already: btck_chainstate_manager_create loads the chainstate, which runs this future-tip check and can latch the IBD status off, before the caller can call btck_chainstate_manager_set_clock_time. So I added btck_chainstate_manager_options_set_clock_time, which sets the time before the chainstate manager is created, and kept btck_chainstate_manager_set_clock_time for changing it afterwards, so the time can still be moved any number of times, as you preferred.

  63. ryanofsky force-pushed on Nov 7, 2026
  64. ryanofsky commented at 12:28 AM on November 7, 2026: contributor

    Thanks for the reviews, and sorry for the slow update. I made this PR smaller and added a way to set the time before the chainstate manager is created, which answers sedited's construction-time question. Replies to each comment are inline.

    <!-- begin push-12 -->

    Updated 0e777d8b302d66360000ad55b6ac1232ac9b62ac -> 2f6b902f980af4f9dcf885c6fc4a5eb6a2abb1ad (pr/kclock.11 -> pr/kclock.12, compare)<!-- end --> adding btck_chainstate_manager_options_set_clock_time(), using time point types for clock times, and moving the mempool refactor and the kernel now() check to https://github.com/ryanofsky/bitcoin/commits/pr/kclock2


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-21 11:51 UTC

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