Skip to content

fix(consensus): handle transfer sum overflow with activation height & MN version gate - #3135

Closed
heddes24 wants to merge 8 commits into
DeFiCh:masterfrom
heddes24:feature/fix-0001-sum-all-transfers
Closed

heddes24 wants to merge 8 commits into
DeFiCh:masterfrom
heddes24:feature/fix-0001-sum-all-transfers

Conversation

@heddes24

@heddes24 heddes24 commented Nov 6, 2026 •

Copy link
Copy Markdown

Summary

SumAllTransfers() sums the amounts of all transfer destinations but ignores
the return value of AddBalances()
. When the sum of the transfer amounts
exceeds INT64_MAX, SafeAdd() reports Err("overflow") and Add() aborts
before mutating the balances — the sum silently stays at the first amount.

The source account is then debited with the truncated sum while every
destination is credited with its full amount. The difference is newly
created DFI.

This is a consensus-level bug. It affects the account transfer types
AccountToAccount ('B') and AnyAccountsToAccounts ('a').

To prevent an unannounced hardfork, keep historical blocks valid, and ensure a
clean network transition, this PR introduces:

  1. Consensus Activation Height (nBalanceOverflowHeight):
    • Below activation height: SumAllTransfersLegacy() retains the historical
      bit-exact behavior (swallowing the overflow, continuing accumulator additions).
    • From activation height on: The strict error check is enforced and
      transactions with overflowing sums are rejected.
  2. Masternode Version Gate (nMNVersionGateHeight):
    • From gate height on, all mined blocks must signal capability via
      VERSION_BIT_BALANCE_OVERFLOW (bit 24 in block.nVersion).
    • Blocks produced by outdated nodes (e.g. v4.2.5 without this bit) are
      strictly rejected with bad-version at the header level.
    • Prevents un-upgraded masternodes from minting invalid blocks or causing
      delayed block times on the updated network.

Root cause

src/dfi/balances.h:265

inline CBalances SumAllTransfers(const CAccounts &to) {
    CBalances sum;
    for (const auto &kv : to) {
        sum.AddBalances(kv.second.balances);   // <-- return value ignored
    }
    return sum;
}

SafeAdd() (src/amount.h:96) detects the overflow correctly:

const auto sum = a + b;
if ((sum - a) != b || static_cast<uint64_t>(std::numeric_limits<CAmount>::max()) < sum) {
    return Res::Err("overflow");
}

CBalances::Add() aborts before mutating the balances, so the sum stays at the
first amount — but nobody looks at the returned error.

The debit path uses that truncated sum, the crediting path uses the full
amounts:

src/dfi/consensus/accounts.cpp:80 (AccountToAccount)

if (auto res = SubBalanceDelShares(obj.from, SumAllTransfers(obj.to)); !res) {
    return res;                         // debits the TRUNCATED sum
}
return AddBalancesSetShares(obj.to);    // credits the FULL amounts

src/dfi/consensus/accounts.cpp:96 (AnyAccountsToAccounts) has the same
defect: sumFrom and sumTo are both truncated, so the
sumFrom != sumTo check passes.

The balance check itself (CTokenAmount::Sub, src/amount.h:163) is correct —
it is simply never presented with the real amount.

Impact

Maximum per transaction INT64_MAX ≈ 92.2 billion DFI
Attacker capital required 8.00000001 DFI
Affected types AccountToAccount ('B'), AnyAccountsToAccounts ('a')

Two conditions have to be met by the attacker:

  1. Destination order. CAccounts is a std::map<CScript, CBalances>, so the
    iteration follows the script bytes. The destination with the smaller script
    has to carry the smaller amount, otherwise the truncated sum is too large to
    pass the balance check.
  2. Raw transaction. ParseFixedPoint (src/util/strencodings.cpp:457)
    rejects amounts with more than 18 significant digits, so the value cannot be
    expressed through the RPC interface.

The fix, Activation Height & Version Gate

1. Error Propagation

Propagate the error in SumAllTransfers:

-inline CBalances SumAllTransfers(const CAccounts &to) {
+inline ResVal<CBalances> SumAllTransfers(const CAccounts &to) {
     CBalances sum;
     for (const auto &kv : to) {
-        sum.AddBalances(kv.second.balances);
+        if (auto res = sum.AddBalances(kv.second.balances); !res) {
+            return res;
+        }
     }
-    return sum;
+    return {sum, Res::Ok()};
 }

2. Historical Compatibility & Consensus Gate

To keep already-mined blocks valid, SumAllTransfersLegacy() retains the historical
behavior (loop continues without breaking even if overflow occurs), and
CCustomTxVisitor::SumTransfers() gates between the legacy and strict paths:

ResVal<CBalances> CCustomTxVisitor::SumTransfers(const CAccounts &to) const {
    if (txCtx.GetHeight() < txCtx.GetConsensus().nBalanceOverflowHeight) {
        return {SumAllTransfersLegacy(to), Res::Ok()};
    }
    return SumAllTransfers(to);
}

3. Masternode Version Gate

In ContextualCheckBlockHeader, blocks at or above nMNVersionGateHeight must carry
the overflow-fix signal bit (VERSION_BIT_BALANCE_OVERFLOW = 1 << 24 in nVersion):

if (nHeight >= consensusParams.nMNVersionGateHeight) {
    if ((block.nVersion & Consensus::Params::VERSION_BIT_BALANCE_OVERFLOW) == 0) {
        return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_HEADER,
                             false,
                             strprintf("bad-version(0x%08x)", block.nVersion),
                             strprintf("rejected outdated nVersion=0x%08x block at height %d (missing overflow fix signal)", block.nVersion, nHeight));
    }
}

4. Activation Heights per Network

Network nBalanceOverflowHeight nMNVersionGateHeight Rationale
Mainnet 6564035 6564035 First recorded block with an overflowing transfer sum. Confirmed by a full scan up to block 6582242 (found exactly 3 overflow txs).
Regtest 1 10000000 Strict rule active by default for transaction regression tests; version gate configurable via -mnversiongateheight.
Testnet INT_MAX INT_MAX Disabled until scheduled.
Changi INT_MAX INT_MAX Disabled until scheduled.
Devnet INT_MAX INT_MAX Disabled until scheduled.

Note for reviewers

ResVal<T> has an implicit conversion operator to T
(src/dfi/res.h:72), so the call sites are not enforced by the compiler —
the old one-liners still compile. The adaptation has to be done explicitly;
otherwise the error would be ignored again, and in release builds
(NDEBUG) dereferencing the empty std::optional is undefined behaviour.
This is worth addressing separately, but it is not required for this fix.

Verification

Three functional tests are included and registered in test_runner.py:

  1. test/functional/feature_account_overflow.py:

    • Builds raw attack transactions and asserts strict rejection with overflow.
    • Asserts no DFI is created on either destination account.
    • Tested against both unpatched (fails / exploit accepted) and patched (passes / exploit rejected).
  2. test/functional/feature_balance_overflow_height.py:

    • Verifies both sides of the activation height on regtest.
    • Below activation height: legacy behavior is accepted and balances match historical semantics.
    • From activation height on: transaction is strictly rejected with overflow.
  3. test/functional/feature_mn_version_gate.py:

    • Verifies the Masternode Version Gate transition.
    • Below gate height: blocks from legacy nodes (nVersion=0x20000000) are accepted.
    • From gate height on: blocks without bit 24 cannot be minted / are rejected with bad-version, while updated nodes mint successfully.

Additionally, existing functional test suites pass and defid builds cleanly.

Consensus & Coordination

  • Historical blocks mined prior to height 6564035 continue to validate cleanly under the legacy path.
  • This issue was reported privately to the DeFiChain security team (security@defichain.com, per SECURITY.md) before this pull request was opened.

AddBalances() reports Err("overflow") on overflow, but the return value was
ignored in SumAllTransfers(). The sum therefore silently stayed at the first
amount while the destination accounts were credited with the full amounts -
up to INT64_MAX (~92.2 billion DFI) of DFI created from nothing per
transaction.

SumAllTransfers() now returns ResVal<CBalances> and propagates the error.
The 12 call sites are adapted in the following commits.
Adapt the three consensus call sites of SumAllTransfers() to its new
ResVal<CBalances> return type and propagate the error explicitly.

The error has to be checked explicitly: ResVal has an implicit conversion
operator to T, so the previous one-liners would still compile and would
dereference an empty optional in release builds (see Issue 0006).

- AccountToAccount: the source account is now debited with the real sum
  instead of a truncated one. On overflow the transaction is rejected.
- AnyAccountsToAccounts: both sums are checked individually. The attacker
  controls both sides, so a single check would not be enough.
- UtxosToAccount: unchanged behaviour, more precise error message.
Finish the adaptation of SumAllTransfers() to its ResVal<CBalances> return
type. All call sites now handle the error explicitly - the error must not
be ignored, otherwise the sum would silently be truncated again.

Error handling follows the role of each call site:
- consensus (AddPoolLiquidity): reject the transaction
- account selection for masternode transfers: no selection
- RPC endpoints: reject the request with the error message
- decodecustomtx output: report the error instead of failing silently
SumAllTransfers() ignored the return value of AddBalances(): when the sum
exceeded INT64_MAX, SafeAdd() reported "overflow" and Add() aborted before
the balances were mutated - the sum silently stayed at the first amount.
The source account was debited with the truncated sum while every
destination was credited with the full amount. The difference was newly
created DFI.

The test builds the transaction raw because ParseFixedPoint() rejects
amounts with more than 18 significant digits, and the destinations have to
be ordered by their script bytes because CAccounts is a
std::map<CScript, CBalances>.

The test asserts that
- the transaction is rejected with "overflow"
- no DFI is created on either destination account
- the control case (sum exactly INT64_MAX, no overflow) is still rejected
  because the source account cannot cover it

Verified in both directions: fails with "No exception raised" on the
unpatched code (the transaction is accepted there) and passes with the fix.
The fix from 0001 (overflow in the transfer sum) changes the consensus
rule globally: the strict SumAllTransfers() rule applies implicitly from
block 1. Every history in which a transfer sum overflows would therefore
be invalidated - the extent of the reset would be undetermined.

With an activation height:
- below the height the historical behaviour (bit-exact like v4.2.5),
- from that height on the strict rule.

Main change:
- new consensus parameter nBalanceOverflowHeight (mainnet 6564035)
- SumAllTransfersLegacy() reproduces the old behaviour bit-exactly.
  Decisive: the loop continues after an overflow, because CBalances::Add
  aborts before the mutation. A break would change the historical sum
  and invalidate already mined blocks.
- CCustomTxVisitor::SumTransfers() selects between both behaviours based
  on txCtx.GetHeight()/GetConsensus().

The mainnet value is measured: a scan of the range up to block 6582242
found exactly three overflowing transactions (6564035, 6565374, 6566081).

Test: feature_balance_overflow_height.py covers both sides of the
activation height (strict rejection / legacy acceptance with the
historical balances).
@heddes24 heddes24 changed the title fix: SumAllTransfers must not swallow the overflow error fix(consensus): handle transfer sum overflow with activation height Nov 9, 2026
From consensus.nMNVersionGateHeight on (mainnet 6564035), all mined blocks
must signal the overflow-fix capability in block.nVersion
(VERSION_BIT_BALANCE_OVERFLOW, bit 24). Blocks minted by outdated nodes
(e.g. v4.2.5 without this bit) are rejected with 'bad-version' in
ContextualCheckBlockHeader.

This ensures outdated masternodes cannot mint invalid blocks or slow down
block production on the updated network.

Test: feature_mn_version_gate.py verifies legacy acceptance below the gate
height and rejection of outdated blocks at/above the gate height.
@heddes24 heddes24 changed the title fix(consensus): handle transfer sum overflow with activation height fix(consensus): handle transfer sum overflow with activation height & MN version gate Nov 9, 2026
@heddes24

heddes24 commented Nov 9, 2026

Copy link
Copy Markdown
Author

🔬 20-Node Heterogeneous Cluster Test Results: Masternode Version Gate Verification

To rigorously verify the consensus safety of the Masternode Version Gate under real P2P network conditions, we conducted an automated end-to-end test on a 20-node cluster in full mesh topology.

Test Configuration:

  • Topology: 20 nodes in a full P2P mesh (regtest), independent data directories and masternode operator keys.
  • Split (10 / 10):
    • Nodes 0–9 (Patched): Running this PR with Bit 24 signaled in nVersion and -mnversiongateheight=200.
    • Nodes 10–19 (Legacy): Running DeFiChain v4.2.5 (unpatched, standard block version without Bit 24 capability).

Test Phases & Observed Behavior:

  1. Phase 1: Pre-Gate Consensus (Blocks 1–199)

    • All 20 nodes produced and accepted blocks under the legacy version format (0x20000000, Bit 24 inactive).
    • Result: 100% consensus across all 20 nodes. Zero block or header rejections.
  2. Phase 2: Version Gate Activation (Block 200)

    • Node 0 (patched) assembled and minted block 200 with Bit 24 set (0x31000000).
    • The block was accepted by both patched nodes (0–9) and legacy nodes (10–19) due to standard BIP9 forward-tolerance in legacy clients.
    • Result: 100% consensus maintained at height 200 with Bit 24 active across the entire cluster.
  3. Phase 3: Outdated Masternode Block Rejection (Block 201)

    • Node 10 (legacy v4.2.5) attempted to mint Block 201 without Bit 24 (0x20000000).
    • Patched nodes (0–9) evaluated the incoming block header in ContextualCheckBlockHeader():
      ContextualCheckBlockHeader: bad-version(0x20000000), block does not signal balance overflow fix capability (requires bit 24)
      
    • Result: All 10 patched nodes immediately rejected the outdated block. Exactly 200 rejection events were recorded across P2P links.
    • Patched nodes continued on the valid chain (de3914e2ce73...) minted with Bit 24, cleanly isolating the outdated nodes without chain stalls or consensus disruption.

Cluster Monitoring Snapshot at Block 201:

==============================================================================
 DEFI CLUSTER MONITOR: CONSENSUS & FORK TRANSITION (N=20 Nodes) 
 Timestamp: 2026-11-09 17:52:14 | Online: 20 / 20 | Offline: 0
==============================================================================

CHAIN FRACTIONS (Tip Consensus):
  ⚡ FORK DETECTED: Network is partitioned into 2 fractions:
    • Height   201 | Tip: de3914e2ce73... (10 Nodes) [Patched: Bit 24 ACTIVE]
      Members: Nodes 0–9 (10 nodes)
    • Height   201 | Tip: aefab977d812... (10 Nodes) [Legacy / Outdated]
      Members: Nodes 10–19 (10 nodes)

CONSENSUS & FILTER METRICS:
  • Tip with Bit 24 (Version Gate) : 10 / 20 Nodes
  • Tip without Bit 24 (Legacy Tip)  : 10 / 20 Nodes
  • Rejected 'bad-version' logs    : 200 Events (Header rejections)

NODE DETAILS:
NODE    STATUS  HEIGHT TIP        B24   | NODE    STATUS  HEIGHT TIP        B24  
--------------------------------------+---------------------------------------
Node 0  ONLINE  201    de3914e2.. ✔ YES | Node 10 ONLINE  201    aefab977.. ✖ NO 
Node 1  ONLINE  201    de3914e2.. ✔ YES | Node 11 ONLINE  201    aefab977.. ✖ NO 
Node 2  ONLINE  201    de3914e2.. ✔ YES | Node 12 ONLINE  201    aefab977.. ✖ NO 
Node 3  ONLINE  201    de3914e2.. ✔ YES | Node 13 ONLINE  201    aefab977.. ✖ NO 
Node 4  ONLINE  201    de3914e2.. ✔ YES | Node 14 ONLINE  201    aefab977.. ✖ NO 
Node 5  ONLINE  201    de3914e2.. ✔ YES | Node 15 ONLINE  201    aefab977.. ✖ NO 
Node 6  ONLINE  201    de3914e2.. ✔ YES | Node 16 ONLINE  201    aefab977.. ✖ NO 
Node 7  ONLINE  201    de3914e2.. ✔ YES | Node 17 ONLINE  201    aefab977.. ✖ NO 
Node 8  ONLINE  201    de3914e2.. ✔ YES | Node 18 ONLINE  201    aefab977.. ✖ NO 
Node 9  ONLINE  201    de3914e2.. ✔ YES | Node 19 ONLINE  201    aefab977.. ✖ NO 
==============================================================================

Conclusion:

The Masternode Version Gate functions reliably under cluster conditions:

  • Clean forward compatibility below and at the activation height.
  • Instant, deterministic rejection of blocks minted by outdated masternodes above the activation height.
  • Zero impact on upgraded node availability or block propagation.

@heddes24

heddes24 commented Nov 9, 2026

Copy link
Copy Markdown
Author

Due to the upstream repository appearing inactive, this consensus fix (including activation height & Masternode Version Gate) has also been submitted for active review and integration on the community fork: ms-01#1

@heddes24 heddes24 closed this by deleting the head repository Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant