Skip to content
2 changes: 2 additions & 0 deletions lib/ain-cpp-imports/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ pub mod ffi {
fn getEVMSystemTxsFromBlock(block_hash: [u8; 32]) -> Vec<SystemTxData>;
fn getDF23Height() -> u64;
fn getDF24Height() -> u64;
fn getBalanceOverflowHeight() -> u64;
fn getMNVersionGateHeight() -> u64;
fn migrateTokensFromEVM(
mnview_ptr: usize,
old_amount: TokenAmount,
Expand Down
17 changes: 17 additions & 0 deletions lib/ain-cpp-imports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,12 @@ mod ffi {
pub fn getDF24Height() -> u64 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getBalanceOverflowHeight() -> u64 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getMNVersionGateHeight() -> u64 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn migrateTokensFromEVM(
_mnview_ptr: usize,
_old_amount: TokenAmount,
Expand Down Expand Up @@ -476,6 +482,17 @@ pub fn get_df24_height() -> u64 {
ffi::getDF24Height()
}

/// Gets the height from which on an overflowing sum of transfer amounts is
/// rejected. Below that height the historical behaviour is kept.
pub fn get_balance_overflow_height() -> u64 {
ffi::getBalanceOverflowHeight()
}

/// Gets the height from which on blocks must signal the overflow fix in nVersion.
pub fn get_mn_version_gate_height() -> u64 {
ffi::getMNVersionGateHeight()
}

/// Send tokens to DVM to split
pub fn split_tokens_from_evm(
mnview_ptr: usize,
Expand Down
33 changes: 33 additions & 0 deletions src/chainparams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ class CMainParams : public CChainParams {
consensus.DF22MetachainHeight = 3462000; // Nov 15th, 2023.
consensus.DF23Height = 4006000; // May 23th, 2024.
consensus.DF24Height = 4463000; // Oct 29th, 2024.
// Height from which on an overflowing transfer sum is rejected.
// Below this height the historical behaviour is kept, so that already
// mined blocks stay valid.
//
// 6564035 is the first block that contains an overflowing transfer
// sum. A full scan of the range up to block 6582242 found exactly
// three overflowing transactions (6564035, 6565374, 6566081).
//
// This is a consensus constant: it must be identical on every node.
consensus.nBalanceOverflowHeight = 6564035;
consensus.nMNVersionGateHeight = 6564035;

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
// consensus.pos.nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
Expand Down Expand Up @@ -436,6 +447,10 @@ class CTestNetParams : public CChainParams {
consensus.DF22MetachainHeight = 1150040;
consensus.DF23Height = 1507200;
consensus.DF24Height = 1810800;
// TODO(testnet): set to a height above the current testnet tip
// before the v4.2.6 release.
consensus.nBalanceOverflowHeight = std::numeric_limits<int>::max();
consensus.nMNVersionGateHeight = std::numeric_limits<int>::max();

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
// consensus.pos.nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
Expand Down Expand Up @@ -660,6 +675,10 @@ class CChangiParams : public CChainParams {
consensus.DF22MetachainHeight = 1586750;
consensus.DF23Height = 1985600;
consensus.DF24Height = 2241000;
// TODO(changi): set to a height above the current changi tip
// before the v4.2.6 release.
consensus.nBalanceOverflowHeight = std::numeric_limits<int>::max();
consensus.nMNVersionGateHeight = std::numeric_limits<int>::max();

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.pos.nTargetTimespan = 5 * 60; // 5 min == 10 blocks
Expand Down Expand Up @@ -878,6 +897,8 @@ class CDevNetParams : public CChainParams {
consensus.DF22MetachainHeight = 1586750;
consensus.DF23Height = std::numeric_limits<int>::max();
consensus.DF24Height = std::numeric_limits<int>::max();
consensus.nBalanceOverflowHeight = std::numeric_limits<int>::max();
consensus.nMNVersionGateHeight = std::numeric_limits<int>::max();

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.pos.nTargetTimespan = 5 * 60; // 5 min == 10 blocks
Expand Down Expand Up @@ -1100,6 +1121,12 @@ class CRegTestParams : public CChainParams {
consensus.DF22MetachainHeight = 10000000;
consensus.DF23Height = 10000000;
consensus.DF24Height = 10000000;
// On regtest the strict rule is active from the start, so that the
// existing tests (e.g. feature_account_overflow.py) keep seeing the
// fixed behaviour. Use -balanceoverflowheight to test the legacy
// path (activation height above the transaction height).
consensus.nBalanceOverflowHeight = 1;
consensus.nMNVersionGateHeight = 10000000;

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.pos.nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
Expand Down Expand Up @@ -1371,6 +1398,12 @@ void SetupCommonArgActivationParams(Consensus::Params &consensus) {
UpdateHeightValidation("Metachain", "-metachainheight", consensus.DF22MetachainHeight);
UpdateHeightValidation("DF23 Upgrade Height", "-df23height", consensus.DF23Height);
UpdateHeightValidation("DF24 Upgrade Height", "-df24height", consensus.DF24Height);
// Overflow of a transfer sum is rejected from this height on. The value
// is a consensus constant - it must be identical on every node, so the
// override is only evaluated on regtest and mocknet (both call
// SetupCommonArgActivationParams).
UpdateHeightValidation("Balance Overflow Height", "-balanceoverflowheight", consensus.nBalanceOverflowHeight);
UpdateHeightValidation("Masternode Version Gate Height", "-mnversiongateheight", consensus.nMNVersionGateHeight);

if (gArgs.GetBoolArg("-simulatemainnet", false)) {
consensus.pos.nTargetTimespan = 5 * 60; // 5 min == 10 blocks
Expand Down
16 changes: 16 additions & 0 deletions src/consensus/params.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,22 @@ struct Params {
int DF22MetachainHeight;
int DF23Height;
int DF24Height;
/**
* Height from which on an overflowing sum of transfer amounts is
* rejected. Below this height the previous behaviour is kept, so that
* already mined blocks stay valid.
*
* The strict rule applies from this height on (height >= nBalanceOverflowHeight).
* This is a consensus constant: it must be identical on every node.
*/
int nBalanceOverflowHeight;
/**
* Masternode Version Gate: Height from which on blocks must signal the
* overflow-fix capability in block.nVersion (VERSION_BIT_BALANCE_OVERFLOW).
* Blocks without this signal are rejected with bad-version.
*/
int nMNVersionGateHeight;
static constexpr int32_t VERSION_BIT_BALANCE_OVERFLOW = (1 << 24);

/** Foundation share after AMK, normalized to COIN = 100% */
CAmount foundationShareDFIP1;
Expand Down
30 changes: 29 additions & 1 deletion src/dfi/balances.h
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,35 @@ struct CStatsTokenBalances {
}
};

inline CBalances SumAllTransfers(const CAccounts &to) {
// Sums up the amounts of all destination accounts.
//
// NOTE: the return value of AddBalances must be checked! On overflow
// SafeAdd reports "overflow" and Add aborts before mutating the balances,
// so the sum would silently stay at the first amount. Without this check
// the source account is debited with too little while the destination
// accounts are credited with the full amounts.
inline ResVal<CBalances> SumAllTransfers(const CAccounts &to) {
CBalances sum;
for (const auto &kv : to) {
if (auto res = sum.AddBalances(kv.second.balances); !res) {
return res;
}
}
return {sum, Res::Ok()};
}

// Sums up the amounts of all destination accounts the way it was done
// before the overflow fix: the return value of AddBalances is ignored.
//
// This reproduces the historical behaviour bit-exactly and is needed for
// blocks below nBalanceOverflowHeight: those blocks were mined with this
// behaviour and must stay valid.
//
// The loop deliberately continues after an overflow. CBalances::Add aborts
// before mutating the balances, so an account with several tokens keeps
// the tokens before the overflowing one. Breaking out of the loop here
// would change the resulting sum and invalidate already mined blocks.
inline CBalances SumAllTransfersLegacy(const CAccounts &to) {
CBalances sum;
for (const auto &kv : to) {
sum.AddBalances(kv.second.balances);
Expand Down
27 changes: 20 additions & 7 deletions src/dfi/consensus/accounts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ Res CAccountsConsensus::operator()(const CUtxosToAccountMessage &obj) const {
return burnt;
}

const auto mustBeBurnt = SumAllTransfers(obj.to);
if (*burnt.val != mustBeBurnt) {
const auto mustBeBurnt = SumTransfers(obj.to);
if (!mustBeBurnt) {
return mustBeBurnt;
}
if (*burnt.val != *mustBeBurnt.val) {
return Res::Err(
"transfer tokens mismatch burnt tokens: (%s) != (%s)", mustBeBurnt.ToString(), burnt.val->ToString());
"transfer tokens mismatch burnt tokens: (%s) != (%s)", mustBeBurnt.val->ToString(), burnt.val->ToString());
}

// transfer
Expand Down Expand Up @@ -77,7 +80,11 @@ Res CAccountsConsensus::operator()(const CAccountToAccountMessage &obj) const {
}

// transfer
if (auto res = SubBalanceDelShares(obj.from, SumAllTransfers(obj.to)); !res) {
auto mustTransfer = SumTransfers(obj.to);
if (!mustTransfer) {
return mustTransfer;
}
if (auto res = SubBalanceDelShares(obj.from, *mustTransfer.val); !res) {
return res;
}

Expand All @@ -93,10 +100,16 @@ Res CAccountsConsensus::operator()(const CAnyAccountsToAccountsMessage &obj) con
}

// compare
const auto sumFrom = SumAllTransfers(obj.from);
const auto sumTo = SumAllTransfers(obj.to);
const auto sumFrom = SumTransfers(obj.from);
if (!sumFrom) {
return sumFrom;
}
const auto sumTo = SumTransfers(obj.to);
if (!sumTo) {
return sumTo;
}

if (sumFrom != sumTo) {
if (*sumFrom.val != *sumTo.val) {
return Res::Err("sum of inputs (from) != sum of outputs (to)");
}

Expand Down
6 changes: 5 additions & 1 deletion src/dfi/consensus/poolpairs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,11 @@ Res CPoolPairsConsensus::operator()(const CPoolSwapMessageV2 &obj) const {
}

Res CPoolPairsConsensus::operator()(const CLiquidityMessage &obj) const {
CBalances sumTx = SumAllTransfers(obj.from);
auto sumTxRes = SumTransfers(obj.from);
if (!sumTxRes) {
return sumTxRes;
}
CBalances sumTx = *sumTxRes.val;
if (sumTx.balances.size() != 2) {
return Res::Err("the pool pair requires two tokens");
}
Expand Down
12 changes: 12 additions & 0 deletions src/dfi/consensus/txvisitor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,18 @@ Res CCustomTxVisitor::CheckCustomTx() const {
return Res::Ok();
}

ResVal<CBalances> CCustomTxVisitor::SumTransfers(const CAccounts &to) const {
const auto &consensus = txCtx.GetConsensus();
const auto height = txCtx.GetHeight();
// Below the activation height the historical behaviour is kept so that
// already mined blocks stay valid. From that height on an overflowing
// sum is a consensus error.
if (height < static_cast<uint32_t>(consensus.nBalanceOverflowHeight)) {
return {SumAllTransfersLegacy(to), Res::Ok()};
}
return SumAllTransfers(to);
}

Res CCustomTxVisitor::TransferTokenBalance(DCT_ID id, CAmount amount, const CScript &from, const CScript &to) const {
assert(!from.empty() || !to.empty());

Expand Down
7 changes: 7 additions & 0 deletions src/dfi/consensus/txvisitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ class CCustomTxVisitor {
Res HasFoundationAuth() const;

Res CheckCustomTx() const;
/// Sums up the amounts of all destination accounts, honouring the
/// balance overflow activation height.
///
/// Below consensus.nBalanceOverflowHeight the historical behaviour is
/// used (the overflow error is ignored), from that height on an
/// overflowing sum is a consensus error.
ResVal<CBalances> SumTransfers(const CAccounts &to) const;
Res TransferTokenBalance(DCT_ID id, CAmount amount, const CScript &from, const CScript &to) const;
ResVal<CBalances> MintedTokens(uint32_t mintingOutputsStart) const;
Res SetShares(const CScript &owner, const TAmounts &balances) const;
Expand Down
6 changes: 5 additions & 1 deletion src/dfi/mn_rpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,11 @@ CAccounts SelectAccountsByTargetBalances(const CAccounts &accounts,
}
}

const auto selectedBalancesSum = SumAllTransfers(selectedAccountsBalances);
auto selectedBalancesSumRes = SumAllTransfers(selectedAccountsBalances);
if (!selectedBalancesSumRes) {
return {};
}
const auto selectedBalancesSum = *selectedBalancesSumRes.val;
if (selectedBalancesSum != targetBalances) {
// we have not enough tokens balance to transfer
return {};
Expand Down
24 changes: 20 additions & 4 deletions src/dfi/rpc_accounts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,11 @@ UniValue utxostoaccount(const JSONRPCRequest &request) {
scriptBurn << OP_RETURN;

// burn
const auto toBurn = SumAllTransfers(msg.to);
auto toBurnRes = SumAllTransfers(msg.to);
if (!toBurnRes) {
throw JSONRPCError(RPC_INVALID_PARAMETER, toBurnRes.msg);
}
const auto toBurn = *toBurnRes.val;
if (toBurn.balances.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "zero amounts");
}
Expand Down Expand Up @@ -986,7 +990,11 @@ UniValue accounttoaccount(const JSONRPCRequest &request) {
auto ownershipCheck = gArgs.GetBoolArg("-dvmownerskipcheck", DEFAULT_DVM_OWNERSHIP_CHECK);
msg.to = DecodeRecipientsDefaultInternal(pwallet, request.params[1].get_obj(), ownershipCheck);

if (SumAllTransfers(msg.to).balances.empty()) {
auto sumToRes = SumAllTransfers(msg.to);
if (!sumToRes) {
throw JSONRPCError(RPC_INVALID_PARAMETER, sumToRes.msg);
}
if (sumToRes.val->balances.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "zero amounts");
}

Expand Down Expand Up @@ -1099,7 +1107,11 @@ UniValue accounttoutxos(const JSONRPCRequest &request) {
msg.from = DecodeScript(request.params[0].get_str());
RejectErc55Address(msg.from);
const auto to = DecodeRecipients(pwallet->chain(), request.params[1]);
msg.balances = SumAllTransfers(to);
auto sumToRes = SumAllTransfers(to);
if (!sumToRes) {
throw JSONRPCError(RPC_INVALID_PARAMETER, sumToRes.msg);
}
msg.balances = *sumToRes.val;
if (msg.balances.balances.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "zero amounts");
}
Expand Down Expand Up @@ -2126,7 +2138,11 @@ UniValue sendtokenstoaddress(const JSONRPCRequest &request) {
auto ownershipCheck = gArgs.GetBoolArg("-dvmownerskipcheck", DEFAULT_DVM_OWNERSHIP_CHECK);
msg.to = DecodeRecipientsDefaultInternal(pwallet, request.params[1].get_obj(), ownershipCheck);

const CBalances sumTransfersTo = SumAllTransfers(msg.to);
auto sumTransfersToRes = SumAllTransfers(msg.to);
if (!sumTransfersToRes) {
throw JSONRPCError(RPC_INVALID_PARAMETER, sumTransfersToRes.msg);
}
const CBalances sumTransfersTo = *sumTransfersToRes.val;
if (sumTransfersTo.balances.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "zero amounts in \"to\" param");
}
Expand Down
7 changes: 6 additions & 1 deletion src/dfi/rpc_customtx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,12 @@ class CCustomTxRpcVisitor {
}

void operator()(const CLiquidityMessage &obj) const {
CBalances sumTx = SumAllTransfers(obj.from);
auto sumTxRes = SumAllTransfers(obj.from);
if (!sumTxRes) {
rpcInfo.pushKV("error", sumTxRes.msg);
return;
}
const CBalances sumTx = *sumTxRes.val;
if (sumTx.balances.size() == 2) {
auto amountA = *sumTx.balances.begin();
auto amountB = *(std::next(sumTx.balances.begin(), 1));
Expand Down
14 changes: 14 additions & 0 deletions src/ffi/ffiexports.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,20 @@ uint64_t getDF24Height() {
return Params().GetConsensus().DF24Height;
}

uint64_t getBalanceOverflowHeight() {
// nBalanceOverflowHeight is an int and may be INT_MAX (disabled).
// A negative value must not be wrapped around to a huge uint64_t,
// so it is clamped to 0 (meaning: the strict rule is active from the
// genesis block - the same semantics as a height of 0).
const auto height = Params().GetConsensus().nBalanceOverflowHeight;
return height < 0 ? 0 : static_cast<uint64_t>(height);
}

uint64_t getMNVersionGateHeight() {
const auto height = Params().GetConsensus().nMNVersionGateHeight;
return height < 0 ? 0 : static_cast<uint64_t>(height);
}

bool migrateTokensFromEVM(std::size_t mnview_ptr, TokenAmount old_amount, TokenAmount &new_amount) {
return ExecuteTokenMigrationEVM(mnview_ptr, old_amount, new_amount);
}
Expand Down
2 changes: 2 additions & 0 deletions src/ffi/ffiexports.h
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ bool isEthDebugTraceRPCEnabled();
rust::vec<SystemTxData> getEVMSystemTxsFromBlock(std::array<uint8_t, 32> evmBlockHash);
uint64_t getDF23Height();
uint64_t getDF24Height();
uint64_t getBalanceOverflowHeight();
uint64_t getMNVersionGateHeight();
bool migrateTokensFromEVM(std::size_t mnview_ptr, TokenAmount old_amount, TokenAmount &new_amount);
bool isSkippedTx(std::array<uint8_t, 32> txHash);

Expand Down
2 changes: 2 additions & 0 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,8 @@ void SetupServerArgs()
gArgs.AddArg("-metachainheight", "Metachain fork activation height (regtest only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
gArgs.AddArg("-df23height", "DF23 fork activation height (regtest only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
gArgs.AddArg("-df24height", "DF24 fork activation height (regtest only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
gArgs.AddArg("-balanceoverflowheight", "Height from which on an overflowing sum of transfer amounts is rejected (regtest only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
gArgs.AddArg("-mnversiongateheight", "Height from which on blocks must signal the overflow fix in nVersion (regtest only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
gArgs.AddArg("-jellyfish_regtest", "Configure the regtest network for jellyfish testing", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-regtest-skip-loan-collateral-validation", "Skip loan collateral check for jellyfish testing", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-regtest-minttoken-simulate-mainnet", "Simulate mainnet for minttokens on regtest - default behavior on regtest is to allow anyone to mint mintable tokens for ease of testing", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
Expand Down
3 changes: 3 additions & 0 deletions src/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,9 @@ ResVal<std::unique_ptr<CBlockTemplate>> BlockAssembler::CreateNewBlock(const CSc

auto consensus = chainparams.GetConsensus();
pblock->nVersion = ComputeBlockVersion(pindexPrev, consensus);
if (nHeight >= consensus.nMNVersionGateHeight) {
pblock->nVersion |= Consensus::Params::VERSION_BIT_BALANCE_OVERFLOW;
}
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand()) {
Expand Down
Loading