Skip to content

RFC: consensus: Make CAmount a class - #35511

Draft
hodlinator wants to merge 12 commits into
bitcoin:masterfrom
hodlinator:2026/06/safer_camount.take2
Draft

hodlinator wants to merge 12 commits into
bitcoin:masterfrom
hodlinator:2026/06/safer_camount.take2

Conversation

@hodlinator

@hodlinator hodlinator commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

We should treat people's money with care across node and wallet.

Having our CAmount be a typedef for raw int64_t as on master has the following drawbacks:

  • Allows assigning to from bools, leading to the issues like the one previously fixed by 0026b33.
  • Allows direct comparison with integral types of differing size, leading to things like the issue previously fixed by 890a09b (reverting it on top of this PR leads to compile errors).
  • Allows forgetting to initialize amounts (CAmount fee;).
  • Allows direct operations with imprecise decimal types as in CAmount target = 49.5L * COIN in src/wallet/test/coinselector_tests.cpp.
  • Allows multiplying two 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 CAmount type itself or by using the sats unit 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

@DrahtBot

DrahtBot commented Jun 11, 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 sedited, ryanofsky

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:

  • #bitcoin-core/gui/952 (Adds non-mempool wallet balance to overview by polespinasa)
  • #36743 ([RFC] build: build with -Wmissing-declarations/prototypes by fanquake)
  • #36741 (policy: Document rounding behavior of feerate fee getters by maflcko)
  • #36696 (CTransaction: Add constructor taking inputs and outputs by purpleKarrot)
  • #36694 (test: construct mempool_tests inputs/outputs declaratively by alexanderwiederin)
  • #36686 (test: cover cumulative input value range in CheckTxInput tests. by KY-U)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #36601 (test: avoid reusing AssumeUTXO coin insertion method in test fixtures by l0rinc)
  • #36539 (gui: Use PSBT v0 by davidgumberg)
  • #36525 (mining: add getTotalFees(), protect m_block_template with mutex by Sjors)
  • #36451 (refactor: Use NotNull for CreateNewBlock and pimpls by maflcko)
  • #36386 (compressor: oversized script decoding can leave a spendable script by l0rinc)
  • #36384 (rpc: Use self.Arg<_>(name) helper over manual and duplicate parsing by maflcko)
  • #36367 (mempool: keep prioritisetransaction deltas within MAX_MONEY by Bruce039)
  • #36357 (mining: move BlockAssembler statics into BlockTemplateManager by w0xlt)
  • #36356 (mining: move getblocktemplate cache into BlockTemplateManager by w0xlt)
  • #36342 (wallet: reject recipient amounts above MAX_MONEY by Bruce039)
  • #36280 (validation: throw when a compressed script can't be decompressed by furszy)
  • #36255 (Refactor CoinGrinder tests by murchandamus)
  • #36188 (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy)
  • #36167 ([RFC] Enable -Wunused by fanquake)
  • #36097 (mining: replace interrupt methods with cancellation arguments by xyzconstant)
  • #36074 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36068 (fuzz: reuse one fuzzed wallet across inputs by brunoerg)
  • #36066 (validation: Separate check-only version of ConnectBlock by optout21)
  • #35997 (refactor: bench: make_hard_case to find a solution by yancyribbens)
  • #35751 (validation: use parallel input prevout fetching in TestBlockValidity by andrewtoth)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #35641 (kernel: Add script evaluation tracer by sedited)
  • #35557 (kernel, validation: Add btck_chainstate_manager_set_clock_time by ryanofsky)
  • #34824 (net: encapsulate TxRelay state and replace recursive mutexes by w0xlt)
  • #34698 (wallet: handle MiniMiner bump fee calculation failures by shuv-amp)
  • #34405 (wallet: skip APS when no partial spend exists by 8144225309)
  • #34360 (bench: add WalletBalanceManySpent for high-history wallet scenario by w0xlt)
  • #33741 (rpc: Optionally print feerates in sat/vb by polespinasa)
  • #32387 (ipc: add windows support by ryanofsky)
  • #31260 (scripted-diff: Type-safe settings retrieval by ryanofsky)
  • #30343 (wallet, logging: Replace WalletLogPrintf() with LogInfo() by ryanofsky)
  • #29700 (kernel, refactor: return error status on all fatal errors by ryanofsky)
  • #29491 ([EXPERIMENTAL] Schnorr batch verification for blocks by fjahr)
  • #29409 (ipc: Expose Chain interface to IPC clients 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.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(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

@sedited

sedited commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/27339510417/job/80774458061
LLM reason (✨ experimental): CI failed because the fuzz target wouldn’t compile: clang++ reported -Wc++11-narrowing errors in coinselection.cpp when initializing CAmount from group_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.

Comment thread src/ipc/capnp/common-types.h Resolved
Comment thread src/node/mempool_persist.cpp Resolved
@hodlinator
hodlinator force-pushed the 2026/06/safer_camount.take2 branch from c14d67a to 6b8a616 Compare June 11, 2026 18:11
This was referenced Jun 12, 2026
hodlinator and others added 3 commits November 24, 2026 13:51
This is enables later commit which changes CAmount to no longer be an integer, so it cannot be used directly through ConsumeIntegralInRange<CAmount>().
This allows for later banning of multiplying amount with floating point types.

Uses a "unit type" to multiply with along the lines of the mp_units library http://wg21.link/p3045, instead of a _BTC user-defined literal.
@hodlinator
hodlinator force-pushed the 2026/06/safer_camount.take2 branch from c8ebdc5 to 5d4dbb0 Compare November 24, 2026 13:03
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/45399558461/job/138464256043
LLM reason (✨ experimental): The build fails because miner_tests.cpp:269 subtracts CAmount feeToUse from a long 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.

@hodlinator
hodlinator force-pushed the 2026/06/safer_camount.take2 branch from 5d4dbb0 to a0e1107 Compare November 24, 2026 14:35
No longer allows implicit conversions from non-integer types such as floats or bools.

Would prevent issues such as the one fixed by 0026b33.
…ization becomes required

-BEGIN VERIFY SCRIPT-
sed -i -E "s/(^\s+CAmount )(\w+);/\1\2{0};/g" $( git grep -lE "^\s+CAmount \w+;" -- src/ ':!src/primitives/transaction.h' )
-END VERIFY SCRIPT-
…mpoolInfo

Preparation for CAmount not having default ctor.
-BEGIN VERIFY SCRIPT-
sed -i -E "s/(\s+CAmount )(\w+) = (-?[0-9]+);/\1\2{\3};/g" $( git grep -lE "CAmount \w+ = -?[0-9]+;" src/ )
sed -i -E "s/CFeeRate([\(\{])((-?[0-9\'])+)([\)\}])/CFeeRate\1CAmount{\2}\4/g" $( git grep -lE "CFeeRate[\(\{]-?[0-9\']+[\)\}]" src/ )
sed -i -E "s/\.nValue = ([a-zA-Z_]+ - )?([0-9]+[0-9L]*([ \-]*[0-9]+(LL)?)*)([^\*0-9])/.nValue = \1CAmount{\2}\5/g" src/test/miner_tests.cpp src/test/transaction_tests.cpp src/test/script_p2sh_tests.cpp
sed -i -E "s/([\(\{])(-?(0x)?[0-9a-f]+), (-?\w+)([\)\}])/\1CAmount{\2}, \4\5/g" src/test/feefrac_tests.cpp src/test/rbf_tests.cpp
sed -i -E "s/(\bCTxOut\{)(([0-9]{1,9})LL|([0-9L\ \-]+))(, .*)/\1CAmount{\3\4}\5/g" $( git grep -lE "CTxOut\{[0-9]+" src/ )
-END VERIFY SCRIPT-
-BEGIN VERIFY SCRIPT-
sed -i -E "s/CAmount[\{\(](-?[0-9\']+)[\}\)]/\1*sats/g" $( git grep -lE "CAmount[\{\(]-?[0-9\']+[\}\)]" src/ )
-END VERIFY SCRIPT-
@hodlinator
hodlinator force-pushed the 2026/06/safer_camount.take2 branch from a0e1107 to b889efb Compare November 24, 2026 19:34
@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

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.

10 participants