Skip to content

refactor: keep duration calculations typed - #35820

Closed
l0rinc wants to merge 13 commits into
bitcoin:masterfrom
l0rinc:l0rinc/compile-time-chrono-hardening
Closed

l0rinc wants to merge 13 commits into
bitcoin:masterfrom
l0rinc:l0rinc/compile-time-chrono-hardening

Conversation

@l0rinc

@l0rinc l0rinc commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem: Several fixed-duration calculations use raw integer time counts, leaving their units implicit and allowing unrelated integer values to be mixed.

Fix: Use std::chrono types through calculations where the surrounding APIs already support them, including GUI formatting, peer bans, scheduler forwarding, block timestamps, and target-spacing arithmetic.
Where carrying chrono through an integer interface would broaden the change or make the result harder to read, this PR leaves the expression unchanged or keeps the conversion simply duration / 1s.
The remaining integer interfaces receive the same values, and characterization tests pin the PoW timing and inclusive assumevalid threshold.

@DrahtBot

DrahtBot commented Jul 27, 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.

Type Reviewers
Concept ACK janb84

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36398 (wallet: only rebroadcast transactions originating from the wallet by mzumsande)
  • #35906 (First steps towards a stateless, side-effect free validation library by purpleKarrot)
  • #35716 (wallet: Replace mapWallet and wtxOrdered with a boost::multi_index by achow101)
  • #35570 (refactor: Change some validation.cpp methods to return BlockValidationState by optout21)
  • #35557 (kernel, validation: Add btck_chainstate_manager_set_clock_time by ryanofsky)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
  • #26022 (Add util::ResultPtr class by ryanofsky)
  • #25665 (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.

@janb84 janb84 left a comment

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.

Concept ACK 7bb44a4

I like the clarity / readability this changes gives. It will even provide less proficient in C++ users to read consensus code.

Maybe split commit in kernel/consensus touching and the rest. In that way it's easy to ACK / review the consensus relevant changes.

Some NIT suggestions to use std::chrono::<<duration>> can be done on more places but I have limited the NITS to hear the current thinking first :)

Comment thread src/qt/guiutil.cpp Outdated
Comment on lines +785 to +788
constexpr int HOUR_IN_SECONDS{TicksSeconds(1h)};
constexpr int DAY_IN_SECONDS{TicksSeconds(24h)};
constexpr int WEEK_IN_SECONDS{TicksSeconds(7 * 24h)};
constexpr int YEAR_IN_SECONDS{TicksSeconds(std::chrono::years{1})};

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.

Just to unify this section I would opt for using std::chrono for every line. (not Blocking bike-shedding NIT)

Suggested change
constexpr int HOUR_IN_SECONDS{TicksSeconds(1h)};
constexpr int DAY_IN_SECONDS{TicksSeconds(24h)};
constexpr int WEEK_IN_SECONDS{TicksSeconds(7 * 24h)};
constexpr int YEAR_IN_SECONDS{TicksSeconds(std::chrono::years{1})};
constexpr int HOUR_IN_SECONDS{TicksSeconds(std::chrono::hours{1})};
constexpr int DAY_IN_SECONDS{TicksSeconds(std::chrono::days{1})};
constexpr int WEEK_IN_SECONDS{TicksSeconds(std::chrono::weeks{1})};
constexpr int YEAR_IN_SECONDS{TicksSeconds(std::chrono::years{1})};

Comment thread src/net_processing.cpp Outdated
/// protection against fingerprinting. Set to one month, denominated in seconds.
static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
/// protection against fingerprinting. Set to one month.
static constexpr int STALE_RELAY_AGE_LIMIT{TicksSeconds(30 * 24h)};

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.

NIT: why not go one step further for even more clarity ?

Suggested change
static constexpr int STALE_RELAY_AGE_LIMIT{TicksSeconds(30 * 24h)};
static constexpr int STALE_RELAY_AGE_LIMIT{TicksSeconds(std::chrono::days{30})};

Note: not to use std::chrono::month{1};

Comment thread src/net_processing.cpp Outdated
/// limiting block relay. Set to one week, denominated in seconds.
static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
/// limiting block relay. Set to one week.
static constexpr int HISTORICAL_BLOCK_AGE{TicksSeconds(7 * 24h)};

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.

Suggested change
static constexpr int HISTORICAL_BLOCK_AGE{TicksSeconds(7 * 24h)};
static constexpr int HISTORICAL_BLOCK_AGE{TicksSeconds(std::chrono::weeks{1})};

@stickies-v

Copy link
Copy Markdown
Contributor

~0, some minor clarity improvements here and there but for the most part I don't see the point as this doesn't add any actual type safety or clarity. I don't find 14 * 24 * 60 * 60; // two weeks harder to read than TicksSeconds(2 * 7 * 24h);

@l0rinc

l0rinc commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review and feedback.

I agree that 14 * 24 * 60 * 60; // two weeks is readable in isolation - the main benefit is moving units from comments into expressions and (where possible), into types.

E.g. MIN_BLOCKS_TO_KEEP - 3600 / nPowTargetSpacing needed a (1 hour) comment (proving that others didn't consider them trivial), while MIN_BLOCKS_TO_KEEP - 1h / PowTargetSpacing() is self-describing and keeps both operands typed.

Likewise, 8 * 60 * 60; // in seconds becomes TicksSeconds(8h), making the conversion and units explicit.

The branch is now split by risk, with exact-value coverage for the consensus-sensitive changes.

@l0rinc
l0rinc force-pushed the l0rinc/compile-time-chrono-hardening branch from 96f6453 to 46fe617 Compare July 28, 2026 01:38
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/30320524467/job/90155255838
LLM reason (✨ experimental): CI failed because IWYU detected missing/incorrect includes and forced an error (“Failure generated from IWYU” / exit status 1).

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.

@l0rinc
l0rinc force-pushed the l0rinc/compile-time-chrono-hardening branch from 46fe617 to 7104b41 Compare July 28, 2026 01:45

@maflcko maflcko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tend to agree with stickies. The changes as-is also violate the util/time.h docs.

Comment thread src/qt/bitcoingui.cpp Outdated
* Ref: https://github.com/bitcoin/bitcoin/pull/1026
*/
static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
static constexpr int64_t MAX_BLOCK_TIME_GAP{TicksSeconds(90min)};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This seems like a step in the wrong direction. The docstring of TicksSeconds also says that it should be avoided in code.

the correct approach would be to write constexpr auto ...{90min}; and then use proper chrono types below: std::chrono::seconds secs{blockDate.secsTo(currentDate)};

@maflcko

maflcko commented Jul 28, 2026

Copy link
Copy Markdown
Member

Follow-up to #35792.

Also, the pull description seems wrong. I fail to see how any of the changes here are related to ODR?

@l0rinc
l0rinc force-pushed the l0rinc/compile-time-chrono-hardening branch from 7104b41 to 7baa431 Compare July 29, 2026 06:01
@l0rinc l0rinc changed the title refactor: use chrono literals for durations refactor: keep duration calculations typed Jul 29, 2026
@l0rinc

l0rinc commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

I fail to see how any of the changes here are related to ODR?

They're not, I noticed these raw duration expressions while reviewing #35792's changes, which is why I originally described this as a follow-up.
Since that wording can read as grouping the two changes, I removed it from the PR description.

The docstring of TicksSeconds also says that it should be avoided in code.

Thanks for the suggestion, I reworked the branch so durations remain typed where the surrounding APIs already support chrono, and I like it a lot better this way.
Where carrying chrono farther would broaden the change or make call sites harder to read, I left the expression unchanged or converted only where an existing interface still takes integer seconds.

Comment thread src/qt/modaloverlay.cpp Outdated
m_animation.setTargetObject(this);
m_animation.setPropertyName("pos");
m_animation.setDuration(300 /* ms */);
m_animation.setDuration(count_milliseconds(300ms));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not sure what exactly this is trying to enforce or harden. A plain 300 /* ms */ seems more readable and direct than a count_milliseconds(300ms) or the alternative used in other parts of this pull: 300ms / 1ms.

I think the chrono types should only be used when the type adds some compile-time checks. And I don't think replacing a 300-raw-int literal with a 300-chrono-literal, and a cast to int is adding any checks.

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.

Sure, I’ve reverted the ones that were arguably noisier than the original code. Thanks for the pushback!

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.

think the chrono types should only be used when the type adds some compile-time checks.

I'd argue it's also valuable when we can remove comments that had to explain the values (e.g. 14 * 24 * 60 * 60; // two weeks) or when we can use the literals in range checks, e.g. if (delta_seconds <= 0 || delta_seconds > 3600) {.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/36026083226/job/107722840641
LLM reason (✨ experimental): CI failed because the IWYU check detected required include changes (edited /src/rpc/node.cpp and other file), causing it to exit non-zero.

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.

l0rinc and others added 13 commits September 24, 2026 11:05
Parse the requested delta as seconds, compare it against typed limits, and pass it directly to the scheduler interfaces.
Make `formatNiceTimeOffset` accept seconds so its comparisons and divisions retain units.
Callers now construct durations from raw values provided by Qt or consensus code.

Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^[email protected]>
Pass typed durations from the peer menu to `banSelectedNode`, converting only at the integer `Node::ban` interface.
Keep the one-year action exactly 365 days.

Co-authored-by: janb84 <[email protected]>
Name the assumed blocks per day directly in the prune backup estimate.
Store the rolling fee halflife as `std::chrono::seconds` and convert it to a scalar only for the decay calculation.
The existing decay test independently pins the duration to 43,200 seconds.
Use `Consensus::Params::PowTargetSpacing()` so the pruning and RPC calculations divide durations directly.
This keeps their units visible and avoids converting either operand to raw seconds.
State fixed durations in their natural units while preserving integer interfaces and exact values.
Store relay age limits as durations and use typed block timestamps for the time arithmetic.
Convert only where `GetBlockProofEquivalentTime` still returns integer seconds.

Co-authored-by: janb84 <[email protected]>
Pin literal target timespan and spacing values for every built-in chain.
These assertions provide a redundant units check before the following representation-only refactor.
Express each built-in chain’s target timespan and spacing in its natural duration unit.
The preceding characterization pins the exact integer values consumed by consensus code.

Co-authored-by: janb84 <[email protected]>
Store the two-hour allowance as a duration and use it directly in time-point comparisons.
Convert it only where existing interfaces still operate on integer seconds.

The `chain_tests/basic_tests` assertion pins the duration to 7,200 seconds.
Make the assumevalid test hit exactly two weeks of equivalent work and pin that scripts remain checked at the inclusive threshold.
Split longer header sequences at `MAX_HEADERS_RESULTS`.
Express the inclusive two-week comparison directly in integer seconds.
The preceding functional characterization pins the exact threshold.
@sedited

sedited commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

This has not received review for some time now and the response to the changes has been somewhat lukewarm. I'm also not entirely convinced that std::chrono::weeks{2} / 1s is more readable/better than 14 * 24 * 60 * 60; // two weeks. The division by 1s is still something that a casual reader would have to read up on imo. Maybe this should be reconsidered?

@maflcko

maflcko commented Nov 6, 2026

Copy link
Copy Markdown
Member

Yeah, I like the concept of moving toward chrono types, but if the casts are just "normalized" or "hidden" via /1s, it seems more confusing than helpful. I think it is fine to have some casts, but they should be verbose and use Ticks or TicksSinceEpoch, so that they either act as explicit documentation, or can be removed in the future.

So I think stuff like this is fine to use:

    int blockcount = std::chrono::days{30} / chainman.GetParams().GetConsensus().PowTargetSpacing();

However, this is not:

        consensus.nPowTargetSpacing = 10min / 1s;

I'd be happy to review a pull with the first type of changes, but the second one can be left for now as-is.

@l0rinc

l0rinc commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Up for grabs

@l0rinc l0rinc closed this Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants