Skip to content

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

Merged
heddes24 merged 8 commits into
ms-01:masterfrom
heddes24:feature/fix-0001-sum-all-transfers
Nov 9, 2026
Merged

heddes24 merged 8 commits into
ms-01:masterfrom
heddes24:feature/fix-0001-sum-all-transfers

Conversation

@heddes24

@heddes24 heddes24 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Fix critical integer overflow vulnerability in CBalances::AddBalances() where summing transfer amounts could exceed int64::max(), allowing unauthorized DFI minting.
  • Add network activation height nBalanceOverflowHeight (Mainnet: block 6564035) to preserve historical blockchain consensus below the activation block.
  • Add Masternode Version Gate (nMNVersionGateHeight, Bit 24 in nVersion / 0x21000000) starting at the same activation height:
    • Upgraded masternodes assemble blocks signaling Bit 24.
    • Blocks minted by un-upgraded masternodes (e.g. v4.2.5 without Bit 24) are rejected with bad-version in ContextualCheckBlockHeader.
    • Prevents outdated nodes from generating blocks that stall consensus or destabilize the network.
  • Migrated from fix(consensus): handle transfer sum overflow with activation height & MN version gate DeFiCh/ain#3135 for active upstream review and integration.

Tests & Verification

  • Unit & functional test suite passes 100%:
    • feature_account_overflow.py (verifies transfer sum overflow detection)
    • feature_balance_overflow_height.py (verifies activation height dual-side behavior)
    • feature_mn_version_gate.py (verifies Bit 24 version gate enforcement and legacy rejection)
  • Verified on a 20-node heterogeneous cluster simulation (10 patched / 10 legacy) over 300 blocks:
    • 100% consensus maintained up to gate height.
    • Seamless version gate activation at block 200.
    • Exploit injection at block 250 strictly rejected by patched nodes while old nodes diverged (+92.23B DFI inflation on unpatched chain vs 0.00 DFI on patched chain).
    • Zero disruption to block propagation on the patched consensus chain.

Flags

  • -balanceoverflowheight=<height>: Regtest/debug flag to configure overflow activation height.
  • -mnversiongateheight=<height>: Regtest/debug flag to configure version gate activation height.

Implications

  • Storage:
    • Database reindex not required
    • None
  • Consensus:
    • Network upgrade required (hard fork activation at height 6564035)
    • Includes backward compatible changes
    • None

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).
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 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator 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 & Chain Protection (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.
  4. Phase 4: Exploit Attempt at Block 250

    • The DFI inflation attack transaction was submitted to both chains:
      • Patched Chain (Nodes 0–9): Transaction strictly rejected with AccountToAccountTx: overflow (-26). 0.00 DFI phantom inflation.
      • Legacy Chain (Nodes 10–19): Transaction accepted and mined into Block 250. +92,233,720,360.55 DFI phantom inflation.

Cluster Monitoring Snapshot:

==============================================================================
 DEFI CLUSTER MONITOR: CONSENSUS & FORK TRANSITION (N=20 Nodes) 
==============================================================================

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

REAL-TIME GRAPHS & PERFORMANCE METRICS:
  • Block-Größe (Bytes) : New [0–9]  ▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ (Peak:  365 B)
                          Old [10–19]                 █▅▆ (Peak:  737 B) [SPIKE!]
  • Block-Zeit (Intervall): New [0–9]  █ ██ ██ ██ ██ ██ ██ (Ø 0.7s)
                          Old [10–19] ██ ██ ██ ██ ██ ██  (Ø 0.6s)
  • DFI Supply Integrity : New [🛡️ SAFE - 0 DFI Inflation]
                          Old [⚠️ EXPLOITED: +92,233,720,361 DFI]
  • Rejected 'bad-version': 200 Events (Header rejections on Patched Nodes)

NODE DETAILS:
NODE    STATUS  HEIGHT TIP        B24   | NODE    STATUS  HEIGHT TIP        B24  
--------------------------------------+---------------------------------------
Node 0  ONLINE  300    9552485c.. ✔ YES | Node 10 ONLINE  301    5940a936.. ✖ NO 
Node 1  ONLINE  300    9552485c.. ✔ YES | Node 11 ONLINE  301    5940a936.. ✖ NO 
Node 2  ONLINE  300    9552485c.. ✔ YES | Node 12 ONLINE  301    5940a936.. ✖ NO 
Node 3  ONLINE  300    9552485c.. ✔ YES | Node 13 ONLINE  301    5940a936.. ✖ NO 
Node 4  ONLINE  300    9552485c.. ✔ YES | Node 14 ONLINE  301    5940a936.. ✖ NO 
Node 5  ONLINE  300    9552485c.. ✔ YES | Node 15 ONLINE  301    5940a936.. ✖ NO 
Node 6  ONLINE  300    9552485c.. ✔ YES | Node 16 ONLINE  301    5940a936.. ✖ NO 
Node 7  ONLINE  300    9552485c.. ✔ YES | Node 17 ONLINE  301    5940a936.. ✖ NO 
Node 8  ONLINE  300    9552485c.. ✔ YES | Node 18 ONLINE  301    5940a936.. ✖ NO 
Node 9  ONLINE  300    9552485c.. ✔ YES | Node 19 ONLINE  301    5940a936.. ✖ 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 marked this pull request as draft November 9, 2026 20:22
@heddes24
heddes24 marked this pull request as ready for review November 9, 2026 20:22
@heddes24
heddes24 marked this pull request as draft November 9, 2026 20:22
@heddes24
heddes24 marked this pull request as ready for review November 9, 2026 20:22
@heddes24
heddes24 merged commit b9f983e into ms-01:master 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