mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
WIP: RFC: consensus: Make CAmount a class #35511
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35511
Loading…
Reference in a new issue
No description provided.
Delete branch "2026/06/safer_camount.take2"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
We should treat people's money with care across node and wallet.
Having our
CAmountbe atypedeffor rawint64_tas on master has the following drawbacks:bools, leading to the issues like the one previously fixed by0026b330c4.890a09b1e4(reverting it on top of this PR leads to compile errors).CAmount fee;).CAmount target = 49.5L * COINin src/wallet/test/coinselector_tests.cpp.CAmounts with each other, which does not make sense.Beyond fixing the above, this PR also makes amounts stick out more in code - either by the
CAmounttype itself or by using thesatsunit specifier.This work is also a stepping stone for possible future work introducing an even safer amount type which only allows values in the range
[0, MAX_MONEY].Already merged PRs spawned out of this work: #35456, #35372
Prior attempts in similar directions: #5430, #4067
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.
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:
mempool_testsinputs/outputs declaratively by alexanderwiederin)-Wunusedby fanquake)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.
LLM Linter (✨ experimental)
Possible places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):src/test/rbf_tests.cpp:PaysForRBF(high_fee, high_fee - 1*sats, 1, CFeeRate(0*sats), unused_txid)src/test/rbf_tests.cpp:PaysForRBF(high_fee, high_fee + 1*sats, 11, incremental_relay_feerate, unused_txid)src/test/rbf_tests.cpp:PaysForRBF(high_fee, high_fee + 1*sats, 10, incremental_relay_feerate, unused_txid)src/test/rbf_tests.cpp:PaysForRBF(high_fee, high_fee + 2*sats, 11, higher_relay_feerate, unused_txid)src/test/rbf_tests.cpp:PaysForRBF(high_fee, high_fee + 4*sats, 20, higher_relay_feerate, unused_txid)src/test/rbf_tests.cpp:StageAddition(tx1_conflict, tx1_fee + 1*sats, 0, 1, 0, false, 4, LockPoints())src/test/rbf_tests.cpp:StageAddition(tx3, tx2_fee, 0, 1, 0, false, 4, LockPoints())src/test/rbf_tests.cpp:CreateValidMempoolTransaction(tx_parent, 0, 101, child_key, child_spk, coinbase_value - low_fee_amt - 300*sats, false)2026-11-24 19:35:39
Concept ACK
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/27339510417/job/80774458061LLM reason (✨ experimental): CI failed because the fuzz target wouldn’t compile: clang++ reported
-Wc++11-narrowingerrors incoinselection.cppwhen initializingCAmountfromgroup_pos.size().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.
Current code gets a local copy, overrides the local copy and local copy gets destroyed at the end of the function. Nothing is written back to the Cap'n Proto message.
Regression test:
NIT: Change suggestion isn't helpful but now that we have new Serialization/deserialization, deserializes straight into a
CAmount amountdelta. Dropping the need for the int64_t nFeeDelta temporary and the separateCAmount amountdelta{nFeeDelta}wrap.Thanks for catching this! I'm surprised it was not covered by tests earlier. I guess transaction serialization has the
CAmounts outputs serialized as part of a byte-stream before reaching our Cap'n Proto integration layer. Added your test in a separate commit (44e5ba33d8ded7c1d72ce29321bcf839aacfb7e4) in the latest push (6b8a616b60541c77120525f74ebb11e422373a44), omitting the comment (let me know if you disagree, I think it was good context for your comment here in the PR but a bit verbose in the context of the test).Agreed - switched in latest push (6b8a616b60541c77120525f74ebb11e422373a44) to serializing and checking
CAmount fee_delta{0};. I thinknFeeDeltawas a more descriptive name, but altered it to match current naming style.yeah test was for proving the bug not the intention to add it so i'm glad you altered it somewhat !
Concept ACK. New CAmount implementation seems simple and clean and adds safety benefits.
I haven't looked through the commits yet, but the PR seems very big. Could it make sense to split up somehow, maybe by introducing a new amount class and beginning to use that in places where it's most important, and gradually replacing CAmount, instead of replacing it everywhere? Or maybe there are other ways to split it up? Or maybe it is trivial to review and splitting it up would not be helpful? Curious what you think. This is just larger than I might have expected.
I think the main reason why this looks large is commit c8fa9d5fbef02ccb2150448cb84ed6e9bba383ef and the two following ones. It should be trivial to split the them up and then reduce the size of this pull by two thirds. After this, it seems small enough and easy enough to do in one go.
Either mark with LIFETIMEBOUND, or just return a copy, which is usually not slower anyway?
q: Shouldn't this check against MAX_MONEY?
In addition to making b7af8d94d6708e50ebede9a513d006ac0031606c a followup or earlier PR (to introduce the _sats literal), it could be a scripted diff? The script is already in the commit description, but then CI can check it too.
Nice. I'd be ok with reviewing this all together, but IMO it would be good to introduce the
_satssuffix as a standalone readability improvement so this PR is smaller and just focused on safety issues, which seem more subtle.Thanks for the encouraging feedback & ideas to facilitate review!
Migrating to a new class gradually is worth at least keeping in the back-pocket (https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4712614640).
Agree with https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4715661184 that peeling off the beginning half of this PR up until before
CAmountstarts becoming an actual class could make sense (everything before "ipc: Add coverage for passing CAmount"?).Regarding https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4727632236, making a scripted diff commit out of the largest one ("refactor: Apply _sats literals (trivial)"):
In that commit I'm preemptively manually inserting
_satsin places which will otherwise no longer compile due to later commits. Outside of some kind of heavily C++ AST-aware Clang-integrated tooling, I don't see a way of doing that in a scripted fashion. Maybe there is some creative way of running the sed-script I have in reverse... I just cannot come up with it now, but I'm open to suggestions.Ah, it is an inverse scripted diff. In theory (after https://github.com/bitcoin/bitcoin/pull/35547) you could do an empty scripted diff in the next commit with:
Not sure if that is too spicy.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/27693235629/job/81909522457LLM reason (✨ experimental): CI failed because IWYU reported include issues (“Failure generated from IWYU”), causing the test script to exit with 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.
A strong like for the concept of
CAmountas a class rather than a simple typedef.These properties make a lot of sense:
However, to be constructible only from
_satsliterals, and to be comparable only against otherCAmountseems a bit of an overkill to me, and it hinders introduction (large change). An amount is a special kind of number, but it is a number, and I don't see the benefit of abstracting away that fact that it is a number.I would be happier to see a more gradual introduction:
amount.Int() < 1000instead ofamount < 1000_satAlso, I'm a bit uneasy with the allowed negative values. Maybe such a change would be a good time to separate absolute amounts and amount differences, with the former being strictly non-negative (e.g.
CAmountanddCAmountDelta; an analogue would be time points and time differences). I suspect for most of the usages, non-negative absolute amount would fit.Thanks for your feedback @optout21!
One of my first experiments in this area was having distinct
Amount(signed) andUAmount(unsigned) types (older branch: https://github.com/hodlinator/bitcoin/tree/2026/03/safer_camount).After presenting this experiment at https://btctranscripts.com/bitcoin-core-dev-tech/2026-05/camount I got feedback about the pitfalls of unsigned integers (mixing signed with unsigned in the same expression makes the result unsigned, which might result in unintentional conversion from negative values to positive).
This made me change my approach to only keep signed amounts, but to experiment with having an amount type which only allows [0,21M BTC] in addition to a type which allows any
int64_tvalue. A first attempt in this direction is made here: https://github.com/hodlinator/bitcoin/tree/2026/06/safer_camount.take2.unchecked. But will probably go with a more careful approach as described in the final commit message.If we were going to introduce the requirement to use
.Int()everywhere we might as well instead introduce the literal directly?I briefly experimented with having an
operator int64_t()method and allowing comparisons against integers. What I ran into a lot was that the compiler couldn't resolve the resulting ambiguities. Maybe there's a way to resolve those ambiguities, but my impression from earlier feedback is that the current approach without that intermediate step may be acceptable.It might be worth having a look into the crystal ball. If P3045 gets accepted into the C++ standard in one form or another, then our preferred way of defining amount might become something like this:
I don't want to suggest using a polyfill for
std::quantity, but I strongly recommend having a look into the proposal linked above and see whether some of its design decisions could influence the design of a customAmountclass.For example, there is a design decision against user defined literals that contains:
Which is absolutely true and convinces me to vote against a
_satUDL.I also strongly believe that whether an amount is inside a particular value range should be a predicate rather than an invarant.
re: https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4765530904
This seems to already be the case if you look at ed38d9ffa1da4cfafb17fc7977edc579e5147207. The
CAmountclass doesn't enforce any range requirements. It could be useful to have other types that enforce runtime invariants likenot_nullor boost'ssafe_signed_rangetype do, but this would be a separate concern. There is also aMoneyRangepredicate already.The std::quantity proposal is interesting and seems to write units with multiplication syntax (
quantity dist1 = 80 * km;) instead of literal suffixes. This does seem more general and could be a good idea to apply here.True. Such a utility may be handy in some areas of the codebase, but we should keep in mind (and probably document somewhere) that there are areas where such a utility must not be used. A function like
validate(Block) -> boolhas three different outcomes:truewhen the block was found validfalsewhen the block was found invalidIt is especially crucial that we are always able to distinguish between 2 and 3. That means:
throwin case of consensus violations.catchin validation code.But outside of consensus, yes, such a utility may be useful.
Thanks for your comments @purpleKarrot & @ryanofsky! (https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4765530904, https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4772817451, https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4776362626).
User-defined literals
The future quantities & units library makes sense for use-cases mixing different quantities (radius vs distance), units (metre vs foot) and kinds (energy vs length). In our domain we are typically interested in sats, sat/vbyte and similar cost/weight unit ratios. At least one test had me define a
_BTCliteral (fe04bd335bc407c2754f332c697c1f7475f1dd17).Writing
0_satsrather thanCAmount{0}was nice for readability and is okay for code that is not exposed by the kernel IMO. However, my next plan is to experiment with a version of this PR which does not introduce any UDLs and instead tries to survive on explicitCAmount-ctors and possibly increased usage of.Int().Constraining valid ranges -
[0,21M] BTCMy experimentation so far confirms that it would be safer to introduce constraints on amount types outside of the consensus code.
re: https://github.com/bitcoin/bitcoin/pull/35511#issuecomment-4809818861
I think you should consider using the
* satsmultiplication syntax likestd::quantity. It seems pretty nice, and better than literal suffixes because it can work with all integer expressions, not just integer literals. It should also be more readable and self-documenting than passing numbers without units to the CAmount constructor.As mentioned by others, I am also not comfortable with taking such a large change in one step. I would prefer introducing a new amount type first, with a few focused examples, and then converting call sites gradually. I also think
_sats,* sats, and explicitCAmount{}construction should be debated independently.I share the concern around value-range semantics. If the goal is that an amount object is always valid once constructed, then the boundary needs to be explicit: parsing should probably produce an unchecked/raw amount first, and validation should then finalize it into a bounded monetary amount, for example through a factory returning
std::optional<MoneyAmount>orutil::Result<MoneyAmount>. If negative values are needed, they may deserve a separateMoneyDeltatype instead of being folded into the same bounded money type.One area I would like clarified is amount compression and serialization. After this change,
AmountCompressionstill appears to deserialize compressed amounts intoCAmountwithout enforcingMoneyRange. Is that intentional and byte-for-byte compatible with the current behavior? Several fuzz targets insrc/test/fuzz/deserialize.cppcan already construct invalid monetary values, and coins/undo data previously seemed to treat a successful parse as sufficient, as far as I can tell.... guess this will finally put an end to the sats-vs-bits debate ...
Do we need to keep the Hungarian notation
Cprefix?What are the expected use cases for dividing one
CAmountby another? What is the expected outcome of 10_sats / 3_sats? Since this returns a scalar ratio rather than another amount, would it be clearer to avoid exposing this as a generic operator and keep the few ratio-style uses explicit?Could we rather encapsulate the serialization inside the new type?
alternatively we could add a
booloperator to it (we have many other cases when we're checking forvalue > 0)seems contrived to do math with the new types, wouldn't it make a lot more sense to extract the value, do the math and reparse at the end?
note that
0.5 * COINmay not be the same asCOIN / 2Won't this introduce unnecessary headaches around floating-point money, even if this is only test code? This was already doing something similar before, but adding a
_BTCliteral seems to make that pattern more attractive rather than less. See 5aadd4b and fa2ac58.why do we have
CAmount{1}here instead of1_satsWouldn't it make more sense to make this optional instead of using a magic value?
Thanks for checking this out @l0rinc!
Yes, explicit construction could be split off as a later PR.
Yup, introducing an additional bounded type should come after this work. Something like
MoneyDelta/AmountDeltasounds good.As far as I can see there is no change to the on the wire format. This comment makes me uneasy but the number of out of bounds values serialized should be the same as on master.
github.com/bitcoin/bitcoin@341360964a/src/compressor.h (L30-L39)Agree it would be nice to rename to
Amountas a before/after marker that the codebase is more typesafe, just want to keep the file count down a bit for now.When would it be harmful to allow calculating the scalar ratio? Exploring this helped me find a
CeilDiv.Diff from disabling `amount / amount` and `amount % amount` while still being able to divide & mod by scalars.
Agreed, thanks for pushing back on this.
(Edit: Fixed in later push).
What I'm going for is to make amounts stand out more in code and have less implicit conversions with raw types.
The idea is for
CAmountto not implicitly convert back & forth with raw integers. Not sure I follow, are you objecting to there being two calls toCOIN.Int()?0.5 * COINon master isdouble * int64_twhich somehow ends up being sent into aint64_tparameter. MakingCOINa typed amount and disallowing implicitdoubleoperations is a step in the right direction I think.(We also know that 100'000'000 is divisible by 2 without any remainder).
The literal is only declared in this one .CPP file and has a comment that it should only be used for tests due to imprecision.
github.com/bitcoin/bitcoin@cc90782e0c/src/wallet/test/coinselector_tests.cpp (L34-L39)(The standard non-long
doubletype has more than enough bits1 to represent satoshi-amounts, which is part of why we have 21M BTC as I got confirmed when I presented this).https://cppreference.com/cpp/language/types#Standard_floating-point_types ↩︎
Good point, it's inconsistent with the similar case around L177.
Agreed, that would be cleaner. However we do have:
github.com/bitcoin/bitcoin@341360964a/src/wallet/spend.cpp (L1485)So I'd prefer if that change happened in another PR.
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/31179697887/job/92869756766LLM reason (✨ experimental): CI failed because the lint check
rpc_assertflagged a fatalassertused in RPC code (src/rpc/rawtransaction.cpp) instead of a non-fatal check.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.
🐙 This pull request conflicts with the target branch and needs rebase.
Latest push removes the
_satsUDL. Instead the commits get by onCAmount{<literal>}until the end, when asatsunit is defined and applied as<literal>*sats. (It can also be applied to non-literal expressions). The push also uses scripted diffs to a larger extent than before.🐙 This pull request conflicts with the target branch and needs rebase.
1 additional verified finding in the Review report.
Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.
🔵 Suggestion ·
CAmountrestrictions lack compile-time regression testsThe amount tests exercise supported expressions, so they would not detect removal of the constructor restrictions that provide the PR's main guarantees.
Location:
src/consensus/amount.h:38(head).🔵 Suggestion · The Qt property bridge bypasses
CAmountrestrictions for C++ callersNo current caller misusing these conversions was found, but
QAmountand the publicsetValue(qint64)overload expose integer, boolean and floating-point conversions outside the Qt property bridge.Location:
src/qt/bitcoinamountfield.h:35(head).🔵 Suggestion · The new
BTChelper changes two coin-selection targets by one satoshiThe two
1.9 * BTCtargets evaluate to 189999999 sats with 80-bitlong double, versus 190000000 with binary64long double; no assertion failure was established.Location:
src/wallet/test/coinselector_tests.cpp:39(head).🔵 Suggestion ·
CAmount{...}no longer rejects narrowing integer inputsUnlike the base typedef's brace initialization,
CAmount{u64}can now wrap values aboveINT64_MAX; no current caller supplying such a value was found.Location:
src/consensus/amount.h:39(head).🔵 Suggestion ·
CAmountIPC building bypasses existing integer-range checksAll current amount fields are
Int64, but the new IPC build hook bypassesBuildPrimitive's compile-time checks that the wire type covers the fullint64_trange.Location:
src/ipc/capnp/common-types.h:150(head).🔵 Suggestion · Orphanage resource ratios acquire monetary types
Eviction ordering is unchanged, but
GetDosScore()now represents latency counts and memory usage asCAmount, making non-monetary resource ratios look like satoshi values.Location:
src/node/txorphanage.cpp:166(head).Review coverage was incomplete.
Reviewed:
b889efb6232c· Review report · Previous reportspermalink
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/38296359020/job/114968285143LLM reason (✨ experimental): CI failed during compilation:
bip352_tests.cpppasses{}forCTxOutamounts, butCAmount’s default constructor is deleted.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.
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
🚧 At least one of the CI tasks failed.
Task
FreeBSD Cross: https://github.com/bitcoin/bitcoin/actions/runs/41603274148/job/125806849923LLM reason (✨ experimental): CI fails during compilation because
amount_tests.cppcallsCFeeRatewith two integer arguments that don’t match its constructor’sCAmountparameter.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.
🐙 This pull request conflicts with the target branch and needs rebase.
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/45399558461/job/138464256043LLM reason (✨ experimental): The build fails because
miner_tests.cpp:269subtractsCAmount feeToUsefrom along long, causing an invalid-operand type error.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.
🐙 This pull request conflicts with the target branch and needs rebase.