Skip to content

kernel, validation: Add btck_chainstate_manager_set_clock_time - #35557

Open
ryanofsky wants to merge 4 commits into
bitcoin:masterfrom
ryanofsky:pr/kclock
Open

ryanofsky wants to merge 4 commits into
bitcoin:masterfrom
ryanofsky:pr/kclock

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Jun 18, 2026 •

Copy link
Copy Markdown
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 kernel, validation: Add btck_chainstate_manager_set_clock_time #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.

@DrahtBot

DrahtBot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36856 (kernel: add manual pruning by pzafonte)
  • #36854 (kernel: let callers create the block manager by pzafonte)
  • #35906 (First steps towards a stateless, side-effect free validation library by purpleKarrot)
  • #35187 (kernel: Block validation without a complete UTXO set by sedited)
  • #33847 (kernel: Attach logging connections to contexts, per-connection log levels 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.

@DrahtBot

Copy link
Copy Markdown
Contributor

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

Hints

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.

Comment thread src/node/chainstate.cpp Resolved
Comment thread src/util/time.h Resolved
Comment thread src/validation.h Resolved
@ryanofsky

Copy link
Copy Markdown
Contributor Author

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

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Updated 94622b0 -> 27ea729 (pr/kclock.2 -> pr/kclock.3, compare) 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

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

Updated 8be500e -> 37fb1b5 (pr/kclock.4 -> pr/kclock.5, compare) 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

Comment thread src/node/chainstate.cpp Resolved
Comment thread src/util/time.h Resolved
Comment thread src/validation.h Resolved
Comment thread src/test/fuzz/tx_pool.cpp Resolved

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/test/fuzz/tx_pool.cpp Resolved
@sedited

sedited commented Jun 21, 2026

Copy link
Copy Markdown
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.

@stickies-v

Copy link
Copy Markdown
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.

// Freeze the clock to avoid a race where Now<NodeSeconds>() in test setup
// and Now<NodeSeconds>() inside IsTipRecent() straddle a second boundary,
// causing a spurious failure in the tip_recent=true case.
SetMockTime(Now<NodeSeconds>());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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);
 }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #35557 (comment)

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

Thanks! Applied your patch and switched to FakeNodeClock

ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Sep 8, 2026
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:
bitcoin#35557 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
nervana21 pushed a commit to nervana21/bitcoin that referenced this pull request Oct 6, 2026
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:
bitcoin#35557 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@sedited

sedited commented Oct 26, 2026

Copy link
Copy Markdown
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?

ryanofsky and others added 4 commits October 29, 2026 10:45
…fter_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 <[email protected]>
This change was written with Claude Sonnet 4.6.
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 <[email protected]>
Co-Authored-By: MarcoFalke <*~=`'#}+{/-|&$^[email protected]>
This change was written with Claude Sonnet 4.6.
…oading_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.
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:
bitcoin#35557 (comment)

This change was written with Claude Sonnet 4.6.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Oct 30, 2026
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:
bitcoin#35557 (comment)

This change was written with Claude Sonnet 4.6.
@maflcko maflcko removed the CI failed label Oct 30, 2026

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Updated 0e777d8 -> 2f6b902 (pr/kclock.11 -> pr/kclock.12, compare) 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

Comment on lines +1348 to +1350
BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_set_clock_time(
btck_ChainstateManager* chainstate_manager,
int64_t now_seconds) BITCOINKERNEL_ARG_NONNULL(1);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: sedited #35557 (comment)

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

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.

Comment thread src/validation.cpp

// Check timestamp
if (block.Time() > NodeClock::now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
if (block.Time() > chainman.Now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: maflcko #35557 (comment)

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

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.

Comment thread src/validation.h
Comment on lines +1027 to +1031
NodeClock::time_point Now() const
{
const auto clock{m_clock_now_seconds.load(std::memory_order_relaxed)};
return clock != std::chrono::seconds{0} ? NodeSeconds{clock} : NodeClock::_now_nondet();
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: stickies-v #35557 (comment)

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

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

Comment thread src/node/chainstate.cpp
if (!is_coinsview_empty(*chainstate)) {
const CBlockIndex* tip = chainstate->m_chain.Tip();
if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) {
if (tip && tip->Time() > chainman.Now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: sedited #35557 (comment)

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: API Development

Development

Successfully merging this pull request may close these issues.

7 participants