WIP: RFC: consensus: Make CAmount a class

bitcoin/bitcoin: PR #35511

9 suggestions

Optional improvements

Link

[suggestion] · CAmount's rejected operations have no regression checks

amount_tests.cpp checks valid runtime operations but never asserts that default construction, implicit conversion, boolean or floating-point construction, amount multiplication, and mixed-integer comparisons remain ill-formed.

Location: src/consensus/amount.h:38 (head).

Details and suggested fix

The deleted default constructor, explicit non_bool_integral constructor, and restricted operators provide the new protections. The existing positive-value assertions do not distinguish that API from a more permissive version. Add negative static_asserts using std::is_default_constructible_v<CAmount>, std::is_constructible_v<CAmount, bool>, std::is_constructible_v<CAmount, double>, and std::is_convertible_v<int64_t, CAmount>, alongside a positive integer-construction check. Dependent requires helpers can also check that multiplication of two amounts, multiplication by double, and comparison with an integer are unavailable, while integer multiplication and division remain available and return CAmount. This directly tests the compile-time contract rather than only exercising expressions that should compile.


Link

[suggestion] · The BTC helper changes fractional CoinGrinder targets across platforms

25.33 * BTC and 1.9 * BTC truncate one satoshi below the former fixtures when long double is wider than double; no failing assertion was demonstrated.

Location: src/wallet/test/coinselector_tests.cpp:39 (head).

Details and suggested fix

BTCUnit::operator* receives a long double, multiplies by COIN.Int(), and truncates to the amount's integer type. Removing the L suffixes rounds these literals to double before widening them, preserving their small negative errors. With x87 extended precision or binary128 arithmetic, the resulting targets are 2,532,999,999 and 189,999,999 satoshis rather than the former 2,533,000,000 and 190,000,000. With binary64 long double, multiplication rounds to the exact integers before truncation. These are therefore platform-dependent fixture changes in tests that retain exact selection and attempt-count expectations. Restore the L suffixes on the migrated targets to preserve their previous values.


Link

[suggestion] · USDT amount operands no longer use the documented integer type

ENABLE_TRACING now forwards CAmount objects for documented int64 operands; no incorrect trace value or tracing-enabled build failure has been demonstrated.

Location: src/wallet/spend.cpp:1480 (head).

Details and suggested fix

TRACEPOINT forwards its arguments unchanged to STAP_PROBEV from the external sys/sdt.h. This now includes the fees in coin_selection:normal_create_tx_internal and coin_selection:aps_create_tx_internal, the amounts in coin_selection:selected_coins, and the fee arguments in mempool:added, mempool:removed, and mempool:replaced. Extract these operands with .Int(), using expressions such as res ? res->fee.Int() : int64_t{0} for the conditional fees. That preserves the documented scalar input type without relying on unverified class-operand handling in sys/sdt.h, and matches the .Int() boundary already used by the coin-cache tracepoints.


Link

[suggestion] · non_bool_integral leaves 64-bit signedness choices implicit

CAmount permits unsigned-64-bit arithmetic and silently narrowing construction; the unsigned arithmetic is pre-existing, and no current caller producing the negative-amount trigger was found.

Location: src/consensus/amount.h:95 (head).

Details and suggested fix

The scalar overloads evaluate m_sats / other and m_sats % other directly. With uint64_t, the usual arithmetic conversions make these unsigned operations, so CAmount{-15} / uint64_t{3} returns 6,148,914,691,236,517,200 rather than -5. Existing callers such as getblockstats and CreateTransactionInternal divide nonnegative totals, but still leave that signedness choice implicit. The constructor's m_sats(sats) also allows a nonconstant uint64_t through CAmount{u64} without the narrowing diagnostic provided by brace-initializing the old typedef; EvaluateFee now uses this form. Constrain the scalar operators and constructor to signed integers or unsigned types narrower than 64 bits. Existing unsigned call sites can then use explicit int64_t conversions where their bounds justify them.


Link

[suggestion] · QAmount exposes Qt property conversions to ordinary C++ callers

Although current callers are correct and the base API returned int64_t, returning QAmount keeps the amount-entry API implicitly convertible to integers and booleans and permits floating-point arithmetic.

Location: src/qt/bitcoinamountfield.h:35 (head).

Details and suggested fix

value() returns a public CAmount subclass with an implicit operator qint64(). Consequently, expressions such as bool b = field->value(), field->value() * field->value(), and field->value() * 1.5 remain valid through built-in operators. The public setValue(qint64) similarly accepts true and 1.5. This accessor feeds the zero-amount check, dust check, and recipient amount in SendCoinsEntry. Keep the public getter and setter on CAmount, and point the property's READ and WRITE at separately named qint64 bridge accessors using Int() and CAmount{v}. Those bridges can be private because the generated metacall is a member. The property name, type, notification signal, and USER mapping can remain unchanged.


Link

[suggestion] · CAmount IPC serialization bypasses field-width checks

CAmount's new IPC builder skips BuildPrimitive's range assertions, allowing a narrower integer schema field to truncate amounts silently; current amount fields use Int64.

Location: src/ipc/capnp/common-types.h:150 (head).

Details and suggested fix

The generic CustomBuildField calls BuildPrimitive, whose assertions require the schema field's range to contain the full C++ integer range. The new CAmount overload instead calls output.set(value.Int()) directly. An accidental Int32 or UInt32 declaration would therefore narrow on write, while the reader's const CAmount::inner_type& source{input.get()} would accept the already-truncated value by widening it. Route the extracted integer through the existing check: output.set(BuildPrimitive(invoke_context, value.Int(), TypeList<decltype(output.get())>()));. This restores schema validation without changing the value written to current Int64 fields.


Link

[suggestion] · mempool.dat's mixed amount encodings lack a direct compatibility test

mempool.dat now depends on matching CAmount and raw int64_t encodings in both directions; today's bytes agree, but direct negative-value and boundary compatibility tests are missing.

Location: src/node/mempool_persist.cpp:124 (head).

Details and suggested fix

LoadMempool reads the trailing delta map as inner_type, while DumpMempool writes it through CAmount serialization. Per-transaction deltas cross the opposite boundary: raw integers are written and amounts are read. The raw map is needed because map deserialization default-constructs its mapped values. READWRITE(amount.m_sats) currently preserves the encoding, but a divergence could misread fee deltas or fail loading without a type error. The genesis assertion and positive-delta persistence cases do not directly check the negative and extreme encodings. Add a table test for 0, 1, MAX_MONEY, -1, INT64_MIN, and INT64_MAX that compares the eight-byte encodings and deserializes each as the other type, explicitly initializing the CAmount destination.


Link

[suggestion] · FeeFrac now gives orphanage resource scores a monetary type

TxOrphanage must wrap memory usage and latency scores in CAmount and express its unit threshold as 1*sats, weakening the monetary distinction without changing eviction arithmetic.

Location: src/node/txorphanage.cpp:166 (head).

Details and suggested fix

GetDosScore computes ratios of latency scores and memory usage to their respective allowances. Changing FeeFrac::fee and its constructor to CAmount forces these non-monetary numerators through CAmount{m_total_latency_score} and CAmount{m_total_usage}, and LimitOrphans now uses FeeFrac{1*sats, 1} for a dimensionless threshold. This makes monetary construction necessary for values that are not amounts. Factor the fraction implementation over its numerator type, using an integer numerator for resource scores and CAmount for monetary fee ratios. Retaining the existing cross-multiplication and denominator tie-breaking preserves the current ordering while allowing the types and sats notation to identify money accurately.


Link

[suggestion] · Amount-map initialization now performs two lookups on insertion

A single try_emplace preserves behavior while removing the lock-annotated lambda in PrioritiseTransaction, the branch in GetAddressBalances, and their extra insertion lookup.

Location: src/txmempool.cpp:682 (head).

Details and suggested fix

PrioritiseTransaction now finds the delta entry and separately emplaces zero on a miss while holding cs; GetAddressBalances uses the same find/insert pattern. try_emplace directly initializes the mapped value, so it works with both the explicit constructor and deleted default constructor. Use CAmount& delta{mapDeltas.try_emplace(hash, 0).first->second}; under the existing lock, and balances.try_emplace(addr, 0*sats).first->second += n; for balances. These retain the saturating delta update, removal of zero deltas, and insertion of zero-valued address entries. The wallet already uses this pattern for truc_txid_by_value.


Coverage details

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

The typedef was a deliberate low-risk abstraction, not an assertion that integer aliases provide strong type safety. Earlier discussion favored naming monetary values while preserving exactly the behavior of int64_t, including division and rounding, because a new arithmetic implementation would consume scarce consensus-testing and review capacity.

The base defines CAmount as int64_t; the head replaces it with constructors, operators, and serialization. Historically, preserving arithmetic behavior and making that preservation verifiable were central reasons for stopping at the alias. #4234 introduced the typedef, and the later #5430 discussion explicitly described the separate-class approach as having benefits that had not then outweighed its risks.

Source 1 · Source 2 · Source 3

The competing rationale for a distinct money type was semantic explicitness: restrict the permitted arithmetic and require explicit conversions so that hidden assumptions about the underlying integer representation cannot silently accumulate. The original proposal also sought easier code sharing with chains using different monetary arithmetic; later discussion identified analyzability and type safety as benefits for Bitcoin itself.

The head’s explicit constructor, exclusion of bool and floating-point inputs, explicit Int() boundary, and restricted amount/scalar operations address this longstanding distinction between merely naming an integer and enforcing a monetary API. The historical cross-chain motivation explains the proposal’s breadth without establishing that such compatibility is a requirement for Bitcoin.

Source 1 · Source 2 · Source 3 · Source 4

Earlier proposals distinguished a core monetary representation from human-facing conversion. Pieter Wuille argued that the type should encapsulate arithmetic and serialization without pulling formatting, rounding utilities, or other application dependencies into protocol data structures; the proposal’s author subsequently moved FormatMoney and ParseMoney back out.

This explains why changing the representation need not make decimal display or parsing intrinsic properties of CAmount. At the pinned head, CAmount serializes its int64_t member, while the RPC layer separately parses fixed-point text, explicitly constructs an amount, and applies MoneyRange.

Source 1 · Source 2 · Source 3

Human-facing decimal compatibility required more than accepting a binary floating-point value. Issue #6297 documented that rejecting scientific notation broke JSON clients and tests. The resulting change introduced fixed-point parsing into a 64-bit integer, with tests accepting exact satoshi values and rejecting sub-satoshi precision and overflow.

The affected RPC boundary retains this separation: JSON number or string syntax is interpreted by ParseFixedPoint before construction and monetary range validation. Historical support for decimal and scientific notation therefore does not imply a requirement for implicit floating-point arithmetic inside CAmount.

Source 1 · Source 2 · Source 3

The conversion hazards cited in the assignment have concrete historical examples. #34888 fixed a comparison result being stored as an amount; an existing wallet test exercised the path but passed because other values dominated the condition. #34939 changed a fuzz-test waste accumulator from int to CAmount because monetary values could exceed int’s range.

These incidents explain the safety motivation for distinguishing amounts from booleans and differently sized integers. They also show why successful execution of an existing test path is not necessarily evidence that the monetary intermediate had the intended meaning. This is historical motivation, not a conclusion about the present class’s coverage.

Source 1 · Source 2 · Source 3

Ralph's inferences

The pinned design separates a representable amount from a valid transaction amount. An amount container can hold invalid values, while consensus checks reject negative outputs, individually excessive outputs, and excessive accumulated output totals. The code explicitly connects these checks to the historical overflow incident CVE-2010-5139.

The head retains these checks and the same MAX_MONEY boundary rather than enforcing [0, MAX_MONEY] in the constructor. Thus stronger compile-time typing and adversarial transaction-value validation remain distinct responsibilities. The amount-header warning also makes clear that MAX_MONEY is a consensus sanity boundary, not simply a statement of circulating supply.

Signed amounts support internal states beyond spendable output values: CTxOut uses -1 as its null sentinel. This is a concrete reason that the existing general-purpose amount representation has a broader domain than valid on-chain output amounts, although the original historical choice of that sentinel was not traced.

Both base and head preserve the negative sentinel. The head deletes CAmount’s default constructor but explicitly initializes default CTxOut objects to -1, illustrating that requiring initialization is separate from requiring a nonnegative monetary value.

Unresolved disagreements

The historical record contains competing judgments about when stronger monetary typing justifies changes to consensus-adjacent code. Advocates emphasized preventing hidden assumptions and improving auditability; skeptics emphasized unchanged integer semantics, review cost, and benefits demonstrable for Bitcoin rather than downstream projects. The typedef was the concrete historical compromise, but that outcome did not resolve the general cost-benefit threshold for a later class proposal.

This is the central historical tradeoff behind the affected behavior. It explains both the persistence of the raw-integer alias and the recurring interest in replacing it, without treating past objections or endorsements as a verdict on this PR.

Source 1 · Source 2 · Source 3 · Source 4