diff --git a/csnode/CMakeLists.txt b/csnode/CMakeLists.txt index f1c3a1b00..a2819cc27 100644 --- a/csnode/CMakeLists.txt +++ b/csnode/CMakeLists.txt @@ -93,6 +93,7 @@ add_library(csnode include/csnode/serializers_helper.hpp include/csnode/apihandler_serializer.hpp include/csnode/roundstat_serializer.hpp + include/csnode/statecorrection.hpp src/blockchain.cpp src/blockchain_serializer.cpp src/node.cpp @@ -100,6 +101,7 @@ add_library(csnode src/conveyer.cpp src/transactionspacket.cpp src/walletscache.cpp + src/statecorrection.cpp src/walletscache_serializer.cpp src/walletsids.cpp src/walletsids_serializer.cpp diff --git a/csnode/include/csnode/blockchain.hpp b/csnode/include/csnode/blockchain.hpp index 2db844221..b872e38e5 100644 --- a/csnode/include/csnode/blockchain.hpp +++ b/csnode/include/csnode/blockchain.hpp @@ -392,7 +392,7 @@ public slots: void getTransactionsUntill(Transactions& transactions, csdb::Address address, csdb::TransactionID id, uint16_t flagg); void getAccountRegTime(uint64_t& aTime, csdb::Address address); void setBlocksToBeRemoved(cs::Sequence number); - double getStakingCoefficient(cs::StakingCoefficient coeff); + static double getStakingCoefficient(cs::StakingCoefficient coeff); std::string printWalletCaches(); diff --git a/csnode/include/csnode/statecorrection.hpp b/csnode/include/csnode/statecorrection.hpp new file mode 100644 index 000000000..02d87783f --- /dev/null +++ b/csnode/include/csnode/statecorrection.hpp @@ -0,0 +1,96 @@ +#ifndef STATECORRECTION_HPP +#define STATECORRECTION_HPP + +#include +#include +#include +#include + +#include +#include +#include + +namespace cs { + +// The chain uuid of the Credits mainnet (BlockChain::uuid(), from the hash of block 1). The test +// network and private networks have other genesis blocks, so other uuids. +constexpr uint64_t kMainnetUuid = 11024959585341937636ULL; + +// A known, verified difference between the wallet state this node's lineage carries and the one +// the network majority computes. A correction is applied only at a block that proves it: the +// proven wallet is a trusted confidant of the block, the block's stored reward split (signed by +// the majority) does not match what this node's stakes give, and it matches exactly once the delta +// is applied. The counterpart adjustments are applied in the same step; they cannot be proven by +// the reward split (the counterparts are not confidants), they come from the transaction that +// caused the difference. A node whose state is already right never applies the correction, and an +// applied correction cannot be applied twice (the proven wallet's split then matches). +struct KnownStateCorrection { + struct Adjustment { + cs::PublicKey wallet; + csdb::Amount delta; // added to balance_ + }; + + uint64_t networkUuid; // the chain the difference exists on (BlockChain::uuid()) + cs::Sequence fromSequence; // the block that caused it: no block below can prove it + cs::PublicKey wallet; // the proven wallet + csdb::Amount delta; // added to its balance_ + std::vector counterparts; + const char* note; +}; + +const std::vector& knownStateCorrections(); + +// The stake value SolverCore::setBlockReward gives a trusted confidant (solver/src/solvercore.cpp), +// reproduced with the same csdb::Amount operations, from the wallet's balance and the delegations +// it received (delegateSources_). +csdb::Amount confidantStake(const csdb::Amount& balance, + const std::map>* delegateSources); + +// The reward split SolverCore::setBlockReward writes for the given stakes (one per confidant, +// ignored for untrusted ones), the real trusted mask (255 = untrusted) and the mined value. +// stakingOn mirrors Consensus::stakingOn: when it is off every share is 0 but the last trusted +// confidant's, which takes the whole mined value. Below Consensus::StartingDPOS the solver mines 0, +// so the stored split sums to 0 and the caller passes minedValue 0. +std::vector blockRewardSplit(const std::vector& stakes, + const cs::Bytes& realTrusted, + const csdb::Amount& minedValue, + bool stakingOn = true); + +// What a block says about the known corrections, given this node's wallet state. +struct StateCorrectionBlock { + uint64_t networkUuid = 0; + cs::Sequence sequence = 0; + bool stakingOn = true; + const cs::ConfidantsKeys* confidants = nullptr; + const cs::Bytes* realTrusted = nullptr; // bitsToMask of the block (255 = untrusted) + const std::vector* storedReward = nullptr; // the block's reward split +}; + +struct StateCorrectionWallet { + csdb::Amount balance; + const std::map>* delegateSources = nullptr; +}; + +using StateCorrectionLookup = std::function; + +enum class StateCorrectionVerdict { + None, // the block proves nothing (no entry applies, or the state already matches) + Apply, // apply the entry: the proven wallet and all its counterparts + Unexplained, // the split differs and the entry's delta does not explain it + CounterpartTooLow // proven, but a counterpart's balance would become negative: apply nothing +}; + +struct StateCorrectionDecision { + StateCorrectionVerdict verdict = StateCorrectionVerdict::None; + size_t entry = 0; // index in the table, for every verdict but None +}; + +// The decision WalletsCache::Updater::applyKnownStateCorrections takes before a block's own +// changes, with the wallet state read through lookup. At most one entry per block. +StateCorrectionDecision decideKnownStateCorrection(const std::vector& table, + const StateCorrectionBlock& block, + const StateCorrectionLookup& lookup); + +} // namespace cs + +#endif // STATECORRECTION_HPP diff --git a/csnode/include/csnode/walletscache.hpp b/csnode/include/csnode/walletscache.hpp index 381ba1e78..e77338f74 100644 --- a/csnode/include/csnode/walletscache.hpp +++ b/csnode/include/csnode/walletscache.hpp @@ -91,6 +91,10 @@ class WalletsCache { std::unique_ptr staking_; + // per entry of the known state corrections (csnode/statecorrection.hpp): the blocks that proved + // nothing for it although the reward split differed, counted for the rate-limited warning + std::vector stateCorrectionMisses_; + friend class WalletsCache_Serializer; }; @@ -129,6 +133,10 @@ class WalletsCache::Updater { WalletData getWalletData(const PublicKey&); WalletData getWalletData(const csdb::Address&); + // applies the known state corrections a block proves (csnode/statecorrection.hpp), before the + // block's own changes + void applyKnownStateCorrections(const csdb::Pool& pool, const cs::ConfidantsKeys& confidants, const BlockChain& blockchain); + double load(const csdb::Transaction& tr, const BlockChain& blockchain, const uint64_t timeStamp, bool inverse); double loadTrxForSource(const csdb::Transaction& tr, diff --git a/csnode/src/statecorrection.cpp b/csnode/src/statecorrection.cpp new file mode 100644 index 000000000..73c0fc5ae --- /dev/null +++ b/csnode/src/statecorrection.cpp @@ -0,0 +1,200 @@ +#include + +#include + +#include +#include + +namespace cs { + +namespace { +constexpr uint8_t kUntrustedMarker = 255; + +// 7hWM6wvsojdPy3A2pQjqWKtfJM4hQRCWe3YC2hB2WzbE +constexpr cs::PublicKey kWallet7hWM = { + 0x63, 0x86, 0x89, 0x45, 0xde, 0x6a, 0x10, 0x02, 0xea, 0x7c, 0xbc, 0xa5, 0x0b, 0xbe, 0x46, 0x13, + 0xbc, 0xa6, 0xa6, 0x56, 0x38, 0xcc, 0x56, 0xcd, 0x8c, 0xba, 0x98, 0xed, 0xdb, 0x08, 0xa6, 0x1d +}; + +} // namespace + +const std::vector& knownStateCorrections() { + // Mainnet, 2026-06-05: the payout 176760929.2 of the dice contract (block 176,760,929) pays + // MooNRor8... the win of its call 176760925.1. The lineage of the published pruned snapshots + // replayed that contract state with a stale ref_execute (the previous successful execution, a + // call by 7hWM6wvs...), and charged the payout's contract-state fee (0.008740234375 CS) to + // 7hWM6wvs... (see docs/differences.md, "Known state corrections"). Every block of November + // 2026 where 7hWM6wvs... is a confidant reproduces the stored reward split bit for bit with +1 + // fee on it and with no other value (checked over 40,000 blocks around 187,722,000). + // No counterpart: MooNRor8... paid the emitted fee with its call on every lineage, and the + // nodes of the majority report the same MooNRor8... balance as this lineage (public API of 8 + // majority and 3 minority nodes, block 187,731,527, 2026-11-10), while 7hWM6wvs... differs by + // exactly one fee. Adjusting MooNRor8... would create a difference, not remove one. + static const csdb::Amount kFee(0, 8740234375000000ULL); // 0.008740234375 CS + static const std::vector corrections = { + { kMainnetUuid, 176'760'929, kWallet7hWM, kFee, {}, + "mainnet 7hWM6wvs: fee of dice payout 176760929.2 charged to it while syncing" } + }; + return corrections; +} + +csdb::Amount confidantStake(const csdb::Amount& balance, + const std::map>* delegateSources) { + // Mirrors SolverCore::setBlockReward (solver/src/solvercore.cpp): keep the same operations and + // the same operand types, the csdb::Amount conversions decide the result. + csdb::Amount nodeConfidantAndStake; + csdb::Amount nodeConfidantAndFreezenStake; + csdb::Amount totalNodeStake = 0; + totalNodeStake += balance; + nodeConfidantAndStake += balance; + if (delegateSources != nullptr && delegateSources->size() > 0) { + for (auto& keyAndStake : *delegateSources) { + for (auto& tm : keyAndStake.second) { + if (tm.coeff == StakingCoefficient::NoStaking) { + nodeConfidantAndStake += tm.amount; + } + else { + nodeConfidantAndFreezenStake += tm.amount * BlockChain::getStakingCoefficient(tm.coeff); + } + } + } + } + totalNodeStake = nodeConfidantAndStake + nodeConfidantAndFreezenStake; + + csdb::Amount totaNodeCutStake = totalNodeStake; + if (totaNodeCutStake > Consensus::MaxStakeValue) { + totaNodeCutStake = Consensus::MaxStakeValue; + } + + return (nodeConfidantAndStake * BlockChain::getStakingCoefficient(StakingCoefficient::NoStaking) + nodeConfidantAndFreezenStake) * + (totalNodeStake > csdb::Amount{ 1 } ? totaNodeCutStake / totalNodeStake : csdb::Amount{ 1 }); +} + +std::vector blockRewardSplit(const std::vector& stakes, + const cs::Bytes& realTrusted, + const csdb::Amount& minedValue, + bool stakingOn) { + std::vector result; + const size_t n = std::min(stakes.size(), realTrusted.size()); + csdb::Amount totalStake = 0; + int32_t realTrustedNumber = 0; + for (size_t i = 0; i < n; ++i) { + if (realTrusted[i] == kUntrustedMarker) { + continue; + } + ++realTrustedNumber; + totalStake += stakes[i]; + } + if (totalStake < csdb::Amount{ 1 }) { + totalStake = csdb::Amount{ 1 }; + } + csdb::Amount oneMiningPart = stakingOn ? minedValue / totalStake : csdb::Amount{ 0 }; + csdb::Amount payedReward = 0; + int32_t numPayedTrusted = 0; + for (size_t i = 0; i < n; ++i) { + csdb::Amount rewardToPay = 0; + if (realTrusted[i] != kUntrustedMarker) { + if (numPayedTrusted == realTrustedNumber - 1) { + rewardToPay = minedValue - payedReward; + } + else { + rewardToPay = oneMiningPart * stakes[i]; + } + ++numPayedTrusted; + } + if (rewardToPay > minedValue || rewardToPay < csdb::Amount{ 0 }) { + rewardToPay = csdb::Amount{ 0 }; + } + result.push_back(rewardToPay); + payedReward += rewardToPay; + } + return result; +} + +StateCorrectionDecision decideKnownStateCorrection(const std::vector& table, + const StateCorrectionBlock& block, + const StateCorrectionLookup& lookup) { + StateCorrectionDecision none; + if (table.empty() || block.confidants == nullptr || block.realTrusted == nullptr || block.storedReward == nullptr) { + return none; + } + // with staking off the split does not depend on the stakes, so it proves nothing + if (!block.stakingOn) { + return none; + } + const auto& confidants = *block.confidants; + const auto& realTrusted = *block.realTrusted; + const auto& rewards = *block.storedReward; + + bool prepared = false; + std::vector stakes; + StateCorrectionDecision failed; // the first entry that is not applied, if no other one is + csdb::Amount mined = 0; + for (size_t e = 0; e < table.size(); ++e) { + const auto& c = table[e]; + if (block.networkUuid != c.networkUuid || block.sequence < c.fromSequence) { + continue; + } + auto it = std::find(confidants.begin(), confidants.end(), c.wallet); + if (it == confidants.end()) { + continue; + } + const size_t idx = static_cast(it - confidants.begin()); + if (!prepared) { + prepared = true; + if (confidants.empty() || realTrusted.size() != confidants.size() || rewards.size() != confidants.size()) { + return none; + } + for (const auto& r : rewards) { + mined += r; + } + if (mined <= csdb::Amount{ 0 }) { + return none; // below StartingDPOS, or nothing mined: the split proves nothing + } + for (size_t i = 0; i < confidants.size(); ++i) { + if (realTrusted[i] == kUntrustedMarker) { + stakes.emplace_back(0); + continue; + } + auto w = lookup(confidants[i]); + stakes.push_back(confidantStake(w.balance, w.delegateSources)); + } + // the stored split is the one the writer computed from the majority's stakes + if (blockRewardSplit(stakes, realTrusted, mined, block.stakingOn) == rewards) { + return none; // this node's stakes give the stored split: nothing to correct + } + } + if (realTrusted[idx] == kUntrustedMarker) { + continue; + } + auto w = lookup(c.wallet); + std::vector corrected = stakes; + corrected[idx] = confidantStake(w.balance + c.delta, w.delegateSources); + if (blockRewardSplit(corrected, realTrusted, mined, block.stakingOn) != rewards) { + if (failed.verdict == StateCorrectionVerdict::None) { + failed = { StateCorrectionVerdict::Unexplained, e }; + } + continue; + } + bool counterpartsCover = true; + for (const auto& adj : c.counterparts) { + // += as the caller applies it (Amount::operator+ does not carry a fraction of exactly 1) + csdb::Amount after = lookup(adj.wallet).balance; + after += adj.delta; + if (after < csdb::Amount{ 0 }) { + counterpartsCover = false; + break; + } + } + if (!counterpartsCover) { + if (failed.verdict == StateCorrectionVerdict::None) { + failed = { StateCorrectionVerdict::CounterpartTooLow, e }; + } + continue; + } + return { StateCorrectionVerdict::Apply, e }; + } + return failed; +} + +} // namespace cs diff --git a/csnode/src/walletscache.cpp b/csnode/src/walletscache.cpp index 6678fc27e..fd2861e69 100644 --- a/csnode/src/walletscache.cpp +++ b/csnode/src/walletscache.cpp @@ -1,10 +1,14 @@ #include #include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -160,6 +164,10 @@ void WalletsCache::Updater::loadNextBlock(const csdb::Pool& pool, //csdebug() << kLogPrefix << "No balance change info will be logged"; } + if (!inverse) { + applyKnownStateCorrections(pool, confidants, blockchain); + } + auto& transactions = pool.transactions(); csdb::Amount totalAmountOfCountedFee = 0; //if (!transactions.empty()) { @@ -448,6 +456,86 @@ void WalletsCache::Updater::fundConfidantsWalletsWithExecFee(const csdb::Transac ); } +void WalletsCache::Updater::applyKnownStateCorrections(const csdb::Pool& pool, const cs::ConfidantsKeys& confidants, + const BlockChain& blockchain) { + const auto& corrections = knownStateCorrections(); + if (corrections.empty() || confidants.empty()) { + return; + } + // cheap filters first: the network and the first block any entry can be proven at + const uint64_t uuid = blockchain.uuid(); + bool candidate = false; + for (const auto& c : corrections) { + if (c.networkUuid == uuid && pool.sequence() >= c.fromSequence && + std::find(confidants.begin(), confidants.end(), c.wallet) != confidants.end()) { + candidate = true; + break; + } + } + if (!candidate) { + return; + } + + const cs::Bytes realTrusted = cs::Utils::bitsToMask(pool.numberTrusted(), pool.realTrusted()); + const std::vector rewards = getRewardDistribution(pool); + std::map read; // keeps delegateSources_ alive while deciding + StateCorrectionBlock block; + block.networkUuid = uuid; + block.sequence = pool.sequence(); + block.stakingOn = Consensus::stakingOn; // as SolverCore::setBlockReward + block.confidants = &confidants; + block.realTrusted = &realTrusted; + block.storedReward = &rewards; + const auto decision = decideKnownStateCorrection(corrections, block, [&](const cs::PublicKey& key) { + auto it = read.find(key); + if (it == read.end()) { + it = read.emplace(key, getWalletData(key)).first; + } + return StateCorrectionWallet{ it->second.balance_, it->second.delegateSources_.get() }; + }); + if (decision.verdict == StateCorrectionVerdict::None) { + return; + } + + const auto& c = corrections[decision.entry]; + if (decision.verdict != StateCorrectionVerdict::Apply) { + auto& misses = data_.stateCorrectionMisses_; + if (misses.size() < corrections.size()) { + misses.resize(corrections.size(), 0); + } + if (misses[decision.entry]++ % 1000 == 0) { + if (decision.verdict == StateCorrectionVerdict::Unexplained) { + cswarning() << kLogPrefix << "block " << pool.sequence() << ": the stored reward split differs from this node's stakes, " + << "and the known correction (" << c.note << ") does not explain it (" << misses[decision.entry] << " such blocks so far)"; + } + else { + cswarning() << kLogPrefix << "block " << pool.sequence() << " proves the known state correction (" << c.note + << "), but a counterpart balance is below its adjustment: nothing applied (" << misses[decision.entry] + << " such blocks so far)"; + } + } + return; + } + + // the proven wallet and its counterparts, in one step + auto wd = getWalletData(c.wallet); + wd.balance_ += c.delta; + data_.multiWallets_->onWalletCacheUpdated(wd); + logOperation("Known state correction applied: +", c.wallet, c.delta); + std::ostringstream counterpartsLog; + for (const auto& adj : c.counterparts) { + auto cd = getWalletData(adj.wallet); + cd.balance_ += adj.delta; + data_.multiWallets_->onWalletCacheUpdated(cd); + logOperation("Known state correction applied (counterpart): ", adj.wallet, adj.delta); + counterpartsLog << ", balance of " << EncodeBase58(adj.wallet.data(), adj.wallet.data() + adj.wallet.size()) << " += " + << adj.delta.to_string() << " -> " << cd.balance_.to_string(); + } + cslog() << kLogPrefix << "block " << pool.sequence() << " proves the known state correction (" << c.note << "): balance of " + << EncodeBase58(c.wallet.data(), c.wallet.data() + c.wallet.size()) << " += " << c.delta.to_string() + << " -> " << wd.balance_.to_string() << counterpartsLog.str() << "; this node's reward split now equals the stored one"; +} + std::vector WalletsCache::Updater::getRewardDistribution(const csdb::Pool& pool) { std::vector rewDistribution; auto mask = cs::Utils::bitsToMask(pool.numberTrusted(), pool.realTrusted()); diff --git a/docs/differences.md b/docs/differences.md index af69958e4..1ed238c1a 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -291,6 +291,34 @@ consensus rules. balances such a node computes for those callers, and makes them those of the nodes that took part in the rounds. +- **Known state corrections.** The lineage of the published pruned snapshots synced the dice-contract + blocks of 2026-06-05 with the official replay rule above. The payout 176760929.2 (block + 176,760,929) pays `MooNRor8…` the win of its call 176760925.1, whose fee already includes the + emitted transaction's fee. The replay of that contract state failed, the stale `ref_execute` + still pointed to the previous successful call, by `7hWM6wvs…`, and the payout's contract-state + fee (0.008740234375 CS) was charged to `7hWM6wvs…` as well: that lineage holds one fee less for + `7hWM6wvs…` than the majority that executed the contract. `MooNRor8…` was the expected + counterpart, but the nodes of the majority report the same `MooNRor8…` balance as that lineage + (public API of 8 majority and 3 minority nodes at block 187,731,527, 2026-11-10, with `7hWM6wvs…` + one fee apart on the same calls), so there is none to correct. `7hWM6wvs…` is a confidant in half + of the rounds, and every reward split a community node signs for it differs from the majority's + by that fee, which puts the node in the stage-3 minority. `csnode/statecorrection` keeps a table + of such known differences: the proven wallet, its delta, and optional counterpart adjustments + applied in the same step (counterparts are not proven by the reward split; they come from the + transaction that caused the difference). An entry applies only on its network (the chain uuid + of mainnet, also known to nodes started from a snapshot; never on the test network or private + networks) and from the block that caused it (176,760,929). A correction is applied once, at the + first block that proves it: the proven wallet is a trusted confidant of the block, staking is + on, the block's stored reward split (signed by the majority) differs from the one this node's + stakes give, and it is reproduced exactly with the delta applied. If a counterpart's balance is + below its adjustment, nothing is applied and a warning is logged: no balance is made negative. A + node whose state is already right never applies it, an applied correction is never applied + twice, and a block that neither value explains is only logged (rate-limited per entry). The node + logs the block that proved the correction and the new balances of every wallet it changed. + Rounds where the trusted majority is the uncorrected group may still put a corrected node in the + minority: the correction makes the node agree with the network majority, not with every round's + trusted majority. + Official nodes on the side that keeps its block behave as before; mixed networks do not fork (CI: equal state digests with official binaries on half of the nodes, and the same share of signed rounds for both). diff --git a/tests/csnode/statecorrection_fixtures.inc b/tests/csnode/statecorrection_fixtures.inc new file mode 100644 index 000000000..c934b52f7 --- /dev/null +++ b/tests/csnode/statecorrection_fixtures.inc @@ -0,0 +1,24 @@ +// mainnet block 187722656, confidants and their wallet state before the block as the community node holds it +const Fixture kWith7hWM = { 187722656, 7, 127ULL, { + { "G278kRzy4DVTiCJMw2utqz26Mc2ZhUTxFaEMCE9gGBRB", {0xdf, 0x27, 0xd1, 0xea, 0xbf, 0x28, 0xd8, 0x53, 0x4e, 0x71, 0x8a, 0x7d, 0x76, 0x26, 0x55, 0x09, 0x7a, 0x9f, 0x4c, 0x30, 0xf6, 0xb9, 0x0f, 0x7c, 0x56, 0xc3, 0x00, 0xd2, 0x50, 0xfd, 0x0a, 0x6a}, csdb::Amount(36375, 748705850970894239ULL), {{csdb::Amount(60000, 0ULL), 4}, {csdb::Amount(440000, 0ULL), 4}} }, + { "7xdmGZjnRjjPswdhra58uLVpzCtPQEybLwz2GgW5yCeS", {0x67, 0x66, 0xa2, 0x67, 0x9f, 0x7f, 0x62, 0xc0, 0x94, 0xae, 0x6b, 0x54, 0x32, 0xac, 0x1b, 0x5a, 0x19, 0xb4, 0x97, 0xd7, 0x75, 0x01, 0x60, 0xcb, 0xd6, 0x33, 0xc4, 0x7c, 0xcc, 0x1d, 0x25, 0x67}, csdb::Amount(34599, 306516779878152441ULL), {{csdb::Amount(500001, 0ULL), 0}} }, + { "DQFhRFsSVQpsAh4NQHmmzyD19pGS8DNan9dfaKhJ9wtd", {0xb8, 0x41, 0x38, 0x32, 0xba, 0x1e, 0xd8, 0x0c, 0x67, 0xc9, 0x7f, 0xd8, 0xb8, 0xb0, 0x07, 0xc7, 0xc4, 0x89, 0x32, 0xdf, 0x72, 0xe5, 0xdc, 0xaa, 0x2f, 0xeb, 0x24, 0x87, 0x2f, 0x66, 0x12, 0x9a}, csdb::Amount(36210, 559918127363392054ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "48RZfGU1qdkEjv8dHEmxwJfsvW1AHLFzxfemF3M1UKxY", {0x2e, 0x79, 0xe6, 0x68, 0x37, 0x44, 0x5a, 0x17, 0xe8, 0x31, 0xd1, 0x68, 0x60, 0x3a, 0x57, 0x55, 0xc0, 0x85, 0xb9, 0xfe, 0x3d, 0x5a, 0xb0, 0x53, 0xc4, 0x65, 0x7b, 0x1f, 0xb4, 0x29, 0x79, 0x55}, csdb::Amount(36041, 946207300694455059ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "7hWM6wvsojdPy3A2pQjqWKtfJM4hQRCWe3YC2hB2WzbE", {0x63, 0x86, 0x89, 0x45, 0xde, 0x6a, 0x10, 0x02, 0xea, 0x7c, 0xbc, 0xa5, 0x0b, 0xbe, 0x46, 0x13, 0xbc, 0xa6, 0xa6, 0x56, 0x38, 0xcc, 0x56, 0xcd, 0x8c, 0xba, 0x98, 0xed, 0xdb, 0x08, 0xa6, 0x1d}, csdb::Amount(52742, 216824342122695719ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "CuX7e7wasnkqZs31ccAaBwuLdCkra4fvtPr4G6T6dtbF", {0xb0, 0xe4, 0xcf, 0x0e, 0x8e, 0xb4, 0x45, 0x89, 0x39, 0xca, 0x66, 0xb8, 0xd9, 0x54, 0x9d, 0xb1, 0x10, 0xc8, 0x3c, 0x87, 0xd2, 0xf5, 0xe6, 0xcc, 0x36, 0x02, 0x06, 0x9e, 0x32, 0xba, 0x00, 0xde}, csdb::Amount(35714, 45038713062742496ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "JCwdiknRX4SwtcvHy8zdCV2jPm53wtoFxvpJZgrfJuKh", {0xff, 0xa5, 0xd7, 0x2a, 0x8e, 0x54, 0xe5, 0x3d, 0x4c, 0xa1, 0x88, 0x70, 0x1c, 0x2f, 0xf0, 0x83, 0xf9, 0xd0, 0x09, 0x42, 0x9a, 0x27, 0x42, 0xcf, 0xdf, 0x98, 0x4d, 0xd8, 0xbf, 0x14, 0x66, 0xf4}, csdb::Amount(132409, 409301065627331196ULL), {{csdb::Amount(400000, 0ULL), 4}, {csdb::Amount(100000, 0ULL), 4}} }, +}, { + csdb::Amount(0, 168171793538608304ULL), csdb::Amount(0, 17910372488185828ULL), csdb::Amount(0, 168218024882074212ULL), csdb::Amount(0, 168265425857313186ULL), csdb::Amount(0, 163722755751970500ULL), csdb::Amount(0, 168357486604241046ULL), csdb::Amount(0, 145354140877606924ULL) +} }; +// mainnet block 187722654, confidants and their wallet state before the block as the community node holds it +const Fixture kWithout7hWM = { 187722654, 7, 127ULL, { + { "BFS5ZVLUGt61wnmkH2kvD3zhTfLGkfLipcR17KqmR4ss", {0x98, 0x47, 0x5b, 0x69, 0x9c, 0xb2, 0x5e, 0x68, 0x16, 0x76, 0x0f, 0xe8, 0xb9, 0x55, 0x1e, 0x5e, 0x2d, 0xc4, 0x27, 0xed, 0x59, 0x0a, 0xe8, 0x15, 0xc3, 0xb1, 0x8a, 0x9a, 0xc6, 0x37, 0xc6, 0xf2}, csdb::Amount(35751, 339458275431069155ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "5u5Qh71RvSXMhuUmNQmPwMVbQ49WSs7V6JsxmauoJFpK", {0x48, 0xc5, 0xef, 0x38, 0x5c, 0x92, 0x8c, 0x20, 0x6e, 0x58, 0xd4, 0xfa, 0xe8, 0xe3, 0x5c, 0x57, 0xd4, 0xce, 0x00, 0x5c, 0x7c, 0xef, 0x67, 0xf1, 0x39, 0xf0, 0x4b, 0xa2, 0x7e, 0x77, 0x2f, 0xf8}, csdb::Amount(35112, 569298786372169492ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "6TDSsNGTCkHhbwtLwgZumfr8pDa6nJZku5DqBeFdLo8c", {0x51, 0x01, 0x9b, 0xc0, 0xea, 0x2a, 0x03, 0x28, 0xb0, 0x99, 0x29, 0xf9, 0x06, 0xed, 0x5b, 0x92, 0x11, 0x7d, 0xf3, 0x54, 0xeb, 0xdd, 0xb0, 0x1a, 0x20, 0x95, 0xbc, 0xfc, 0x0e, 0x12, 0x6c, 0x69}, csdb::Amount(35872, 302216649501918707ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "38Ve8pMYychCCJ3fbGf2Fxg9iCTGmjEQHpxxX9oKXbje", {0x1f, 0xa2, 0xd2, 0xba, 0x4e, 0xf1, 0x6c, 0x3e, 0x17, 0xad, 0x9e, 0xe9, 0xa3, 0x3d, 0xbc, 0x7c, 0xd6, 0xcb, 0x3d, 0x12, 0xf8, 0x1c, 0xae, 0x27, 0x63, 0x2a, 0x66, 0xd6, 0xee, 0xd7, 0x8d, 0x01}, csdb::Amount(35386, 376602000286248142ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "7xdmGZjnRjjPswdhra58uLVpzCtPQEybLwz2GgW5yCeS", {0x67, 0x66, 0xa2, 0x67, 0x9f, 0x7f, 0x62, 0xc0, 0x94, 0xae, 0x6b, 0x54, 0x32, 0xac, 0x1b, 0x5a, 0x19, 0xb4, 0x97, 0xd7, 0x75, 0x01, 0x60, 0xcb, 0xd6, 0x33, 0xc4, 0x7c, 0xcc, 0x1d, 0x25, 0x67}, csdb::Amount(34599, 271945923472135596ULL), {{csdb::Amount(500001, 0ULL), 0}} }, + { "CuX7e7wasnkqZs31ccAaBwuLdCkra4fvtPr4G6T6dtbF", {0xb0, 0xe4, 0xcf, 0x0e, 0x8e, 0xb4, 0x45, 0x89, 0x39, 0xca, 0x66, 0xb8, 0xd9, 0x54, 0x9d, 0xb1, 0x10, 0xc8, 0x3c, 0x87, 0xd2, 0xf5, 0xe6, 0xcc, 0x36, 0x02, 0x06, 0x9e, 0x32, 0xba, 0x00, 0xde}, csdb::Amount(35713, 720073053922062120ULL), {{csdb::Amount(500000, 0ULL), 4}} }, + { "DtPavgsgtrcSjSKJw5rHS3BQS3VMf1Uhv97UTkP8x7jG", {0xbf, 0x76, 0x66, 0xb7, 0x57, 0xd0, 0x45, 0x55, 0xc4, 0xe0, 0x36, 0x13, 0xeb, 0x89, 0xe8, 0xaa, 0x3d, 0x78, 0x54, 0xc1, 0x0b, 0x87, 0x10, 0x30, 0x9e, 0x2d, 0xf1, 0xd0, 0x5a, 0x6c, 0xca, 0xf3}, csdb::Amount(948, 482295191417891334ULL), {{csdb::Amount(500000, 0ULL), 4}} }, +}, { + csdb::Amount(0, 162074364837593696ULL), csdb::Amount(0, 162247018324784695ULL), csdb::Amount(0, 162041660691310142ULL), csdb::Amount(0, 162173104971891290ULL), csdb::Amount(0, 17243017248704028ULL), csdb::Amount(0, 162084347925809991ULL), csdb::Amount(0, 172136485999906158ULL) +} }; diff --git a/tests/csnode/statecorrection_tests.cpp b/tests/csnode/statecorrection_tests.cpp new file mode 100644 index 000000000..01e2e023b --- /dev/null +++ b/tests/csnode/statecorrection_tests.cpp @@ -0,0 +1,328 @@ +// Known state corrections: the reward split of SolverCore::setBlockReward reproduced from the +// wallet state, checked against blocks the mainnet stored (November 2026). +#include + +#include +#include +#include +#include + +#include +#include + +namespace { + +struct Donor { + csdb::Amount sum; + int coeff; +}; + +struct Confidant { + const char* base58; + cs::PublicKey key; + csdb::Amount balanceBefore; + std::vector donors; +}; + +struct Fixture { + uint64_t sequence; + uint8_t numberTrusted; + uint64_t realTrusted; + std::vector confidants; + std::vector storedReward; +}; + +#include "statecorrection_fixtures.inc" + +const char* const k7hWM = "7hWM6wvsojdPy3A2pQjqWKtfJM4hQRCWe3YC2hB2WzbE"; +const csdb::Amount kOneContractStateFee(0, 8740234375000000ULL); // 0.008740234375 CS + +cs::Bytes maskOf(const Fixture& f) { + cs::Bytes mask; + for (uint8_t i = 0; i < f.numberTrusted; ++i) { + mask.push_back(((f.realTrusted >> i) & 1U) ? 0 : 255); + } + return mask; +} + +std::map> sourcesOf(const Confidant& c) { + std::map> res; + cs::PublicKey donor{}; + for (const auto& d : c.donors) { + ++donor[0]; + cs::TimeMoney tm(0, 0, d.sum); + tm.coeff = static_cast(d.coeff); + res[donor].push_back(tm); + } + return res; +} + +std::vector splitOf(const Fixture& f, const std::string& adjustKey, const csdb::Amount& delta) { + std::vector stakes; + csdb::Amount mined = 0; + for (const auto& r : f.storedReward) { + mined += r; + } + for (const auto& c : f.confidants) { + auto sources = sourcesOf(c); + csdb::Amount balance = c.balanceBefore; + if (adjustKey == c.base58) { + balance += delta; + } + stakes.push_back(cs::confidantStake(balance, &sources)); + } + return cs::blockRewardSplit(stakes, maskOf(f), mined); +} + +const char* const kMooNRor8 = "MooNRor8TcLT3xpAw3UvA2Q6xT8huRoQojn6ZSveDpP"; +const csdb::Amount kMooNRor8Balance(900.8214765625476); // as this lineage holds it (2026-11-10) +constexpr uint64_t kTestnetUuid = 5283967947175248524ULL; + +cs::PublicKey keyOf(const char* base58) { + std::vector bytes; + DecodeBase58(base58, bytes); + cs::PublicKey key{}; + if (bytes.size() == key.size()) { + std::copy(bytes.begin(), bytes.end(), key.begin()); + } + return key; +} + +// The wallet state WalletsCache::Updater::applyKnownStateCorrections reads, injected: the +// confidants of a fixture plus the counterpart. +struct State { + std::map balance; + std::map>> sources; + + explicit State(const Fixture& f) { + for (const auto& c : f.confidants) { + balance[c.key] = c.balanceBefore; + sources[c.key] = sourcesOf(c); + } + balance[keyOf(kMooNRor8)] = kMooNRor8Balance; + } + + cs::StateCorrectionLookup lookup() const { + return [this](const cs::PublicKey& key) { + cs::StateCorrectionWallet w; + if (auto it = balance.find(key); it != balance.end()) { + w.balance = it->second; + } + if (auto it = sources.find(key); it != sources.end()) { + w.delegateSources = &it->second; + } + return w; + }; + } + + // what applyKnownStateCorrections does on an Apply verdict + void apply(const cs::KnownStateCorrection& c) { + balance[c.wallet] += c.delta; + for (const auto& adj : c.counterparts) { + balance[adj.wallet] += adj.delta; + } + } +}; + +struct Block { + cs::ConfidantsKeys confidants; + cs::Bytes realTrusted; + std::vector stored; + cs::StateCorrectionBlock view; + + Block(const Fixture& f, cs::Sequence sequence, uint64_t uuid = cs::kMainnetUuid, bool stakingOn = true) + : realTrusted(maskOf(f)), stored(f.storedReward) { + for (const auto& c : f.confidants) { + confidants.push_back(c.key); + } + view.networkUuid = uuid; + view.sequence = sequence; + view.stakingOn = stakingOn; + view.confidants = &confidants; + view.realTrusted = &realTrusted; + view.storedReward = &stored; + } + Block(const Block&) = delete; +}; + +// the mainnet entry with a counterpart (MooNRor8... -1 fee), to exercise paired adjustments +const std::vector& pairedTable() { + static const std::vector table = [] { + auto t = cs::knownStateCorrections(); + t[0].counterparts.push_back({ keyOf(kMooNRor8), csdb::Amount(0) - kOneContractStateFee }); + return t; + }(); + return table; +} + +cs::StateCorrectionDecision decide(const Block& b, const State& s) { + return cs::decideKnownStateCorrection(pairedTable(), b.view, s.lookup()); +} + +} // namespace + +TEST(StateCorrection, AmountOfTheFee) { + EXPECT_TRUE(kOneContractStateFee == csdb::Amount(0.008740234375)); +} + +TEST(StateCorrection, BlockWithoutTheWalletIsReproducedExactly) { + EXPECT_TRUE(splitOf(kWithout7hWM, "", csdb::Amount(0)) == kWithout7hWM.storedReward); +} + +TEST(StateCorrection, BlockWithTheWalletNeedsExactlyOneFee) { + const auto& f = kWith7hWM; + const auto asHeld = splitOf(f, "", csdb::Amount(0)); + EXPECT_TRUE(asHeld != f.storedReward); + // only the wallet's share and the remainder of the last paid confidant differ + size_t differing = 0; + for (size_t i = 0; i < asHeld.size(); ++i) { + if (asHeld[i] != f.storedReward[i]) { + ++differing; + } + } + EXPECT_EQ(differing, 2U); + + EXPECT_TRUE(splitOf(f, k7hWM, kOneContractStateFee) == f.storedReward); + EXPECT_TRUE(splitOf(f, k7hWM, kOneContractStateFee * 2) != f.storedReward); + EXPECT_TRUE(splitOf(f, k7hWM, csdb::Amount(0, 1000000000000000ULL)) != f.storedReward); // 0.001 CS +} + +TEST(StateCorrection, CorrectionTable) { + const auto& table = cs::knownStateCorrections(); + ASSERT_EQ(table.size(), 1U); + EXPECT_TRUE(table[0].delta == kOneContractStateFee); + EXPECT_EQ(table[0].networkUuid, cs::kMainnetUuid); + EXPECT_EQ(table[0].fromSequence, 176'760'929ULL); + // MooNRor8... holds the same balance on the majority's nodes: no counterpart + EXPECT_TRUE(table[0].counterparts.empty()); + bool found = false; + for (const auto& c : kWith7hWM.confidants) { + if (std::string(c.base58) == k7hWM) { + found = (c.key == table[0].wallet); + } + } + EXPECT_TRUE(found); +} + +// The decision WalletsCache::Updater::applyKnownStateCorrections takes, with the wallet state injected +// and the mainnet entry given a counterpart (pairedTable) +// (a WalletsCache needs a BlockChain and its databases; the adapter only reads the wallets, calls +// decideKnownStateCorrection and applies the entry on Apply, as State::apply does here). +using cs::StateCorrectionVerdict; + +TEST(StateCorrectionTrigger, FiresOnceAndAppliesBothAdjustments) { + State s(kWith7hWM); + const auto k7 = keyOf(k7hWM); + const auto kMoon = keyOf(kMooNRor8); + const csdb::Amount before7 = s.balance[k7]; + Block b(kWith7hWM, kWith7hWM.sequence); + + const auto d = decide(b, s); + ASSERT_EQ(d.verdict, StateCorrectionVerdict::Apply); + ASSERT_EQ(d.entry, 0U); + s.apply(pairedTable()[d.entry]); + EXPECT_TRUE(s.balance[k7] == before7 + kOneContractStateFee); + EXPECT_TRUE(s.balance[kMoon] + kOneContractStateFee == kMooNRor8Balance); + // the reward split this node now computes is the stored one + EXPECT_TRUE(splitOf(kWith7hWM, k7hWM, kOneContractStateFee) == kWith7hWM.storedReward); +} + +TEST(StateCorrectionTrigger, DoesNotFireAgainOnTheNextProvingBlock) { + State s(kWith7hWM); + Block b(kWith7hWM, kWith7hWM.sequence); + ASSERT_EQ(decide(b, s).verdict, StateCorrectionVerdict::Apply); + s.apply(pairedTable()[0]); + const csdb::Amount moon = s.balance[keyOf(kMooNRor8)]; + + Block next(kWith7hWM, kWith7hWM.sequence + 2); + EXPECT_EQ(decide(next, s).verdict, StateCorrectionVerdict::None); + EXPECT_EQ(decide(b, s).verdict, StateCorrectionVerdict::None); + EXPECT_TRUE(s.balance[keyOf(kMooNRor8)] == moon); +} + +TEST(StateCorrectionTrigger, DoesNotFireOnACorrectState) { + // a node of the majority: 7hWM6wvs... already holds the fee, MooNRor8... does not + State s(kWith7hWM); + s.balance[keyOf(k7hWM)] += kOneContractStateFee; + s.balance[keyOf(kMooNRor8)] -= kOneContractStateFee; + Block b(kWith7hWM, kWith7hWM.sequence); + EXPECT_EQ(decide(b, s).verdict, StateCorrectionVerdict::None); +} + +TEST(StateCorrectionTrigger, BlockWithoutTheWalletProvesNothing) { + State s(kWithout7hWM); + Block b(kWithout7hWM, kWithout7hWM.sequence); + EXPECT_EQ(decide(b, s).verdict, StateCorrectionVerdict::None); +} + +TEST(StateCorrectionTrigger, DoesNotFireBelowFromSequence) { + State s(kWith7hWM); + Block below(kWith7hWM, 176'760'928); + EXPECT_EQ(decide(below, s).verdict, StateCorrectionVerdict::None); + Block at(kWith7hWM, 176'760'929); + EXPECT_EQ(decide(at, s).verdict, StateCorrectionVerdict::Apply); +} + +TEST(StateCorrectionTrigger, MainnetOnly) { + State s(kWith7hWM); + Block testnet(kWith7hWM, kWith7hWM.sequence, kTestnetUuid); + EXPECT_EQ(decide(testnet, s).verdict, StateCorrectionVerdict::None); + Block privateNet(kWith7hWM, kWith7hWM.sequence, 1234567ULL); + EXPECT_EQ(decide(privateNet, s).verdict, StateCorrectionVerdict::None); + Block unknown(kWith7hWM, kWith7hWM.sequence, 0); + EXPECT_EQ(decide(unknown, s).verdict, StateCorrectionVerdict::None); +} + +TEST(StateCorrectionTrigger, StakingOffProvesNothing) { + State s(kWith7hWM); + Block b(kWith7hWM, kWith7hWM.sequence, cs::kMainnetUuid, false); + EXPECT_EQ(decide(b, s).verdict, StateCorrectionVerdict::None); +} + +TEST(StateCorrectionTrigger, CounterpartBalanceGuard) { + State s(kWith7hWM); + s.balance[keyOf(kMooNRor8)] = csdb::Amount(0, 8740234374999999ULL); // one unit below the fee + Block b(kWith7hWM, kWith7hWM.sequence); + const auto d = decide(b, s); + EXPECT_EQ(d.verdict, StateCorrectionVerdict::CounterpartTooLow); + EXPECT_EQ(d.entry, 0U); + + s.balance[keyOf(kMooNRor8)] = csdb::Amount(0); + EXPECT_EQ(decide(b, s).verdict, StateCorrectionVerdict::CounterpartTooLow); + + // exactly the fee: the counterpart ends at 0, never below + s.balance[keyOf(kMooNRor8)] = kOneContractStateFee; + ASSERT_EQ(decide(b, s).verdict, StateCorrectionVerdict::Apply); + s.apply(pairedTable()[0]); + EXPECT_TRUE(s.balance[keyOf(kMooNRor8)] == csdb::Amount(0)); +} + +TEST(StateCorrectionTrigger, UnexplainedDifferenceIsOnlyReported) { + State s(kWith7hWM); + s.balance[keyOf(k7hWM)] -= kOneContractStateFee; // two fees short: the entry does not explain it + Block b(kWith7hWM, kWith7hWM.sequence); + const auto d = decide(b, s); + EXPECT_EQ(d.verdict, StateCorrectionVerdict::Unexplained); + EXPECT_EQ(d.entry, 0U); +} + +TEST(StateCorrection, StakingOffSplitGivesAllToTheLastTrusted) { + const auto& f = kWith7hWM; + std::vector stakes(f.confidants.size(), csdb::Amount(1000)); + const auto split = cs::blockRewardSplit(stakes, maskOf(f), csdb::Amount(1), false); + ASSERT_EQ(split.size(), f.confidants.size()); + for (size_t i = 0; i + 1 < split.size(); ++i) { + EXPECT_TRUE(split[i] == csdb::Amount(0)); + } + EXPECT_TRUE(split.back() == csdb::Amount(1)); +} + +TEST(StateCorrectionTrigger, MainnetTableAppliesOnlyTheProvenWallet) { + State s(kWith7hWM); + Block b(kWith7hWM, kWith7hWM.sequence); + const auto d = cs::decideKnownStateCorrection(cs::knownStateCorrections(), b.view, s.lookup()); + ASSERT_EQ(d.verdict, StateCorrectionVerdict::Apply); + s.apply(cs::knownStateCorrections()[d.entry]); + EXPECT_TRUE(s.balance[keyOf(kMooNRor8)] == kMooNRor8Balance); + EXPECT_EQ(cs::decideKnownStateCorrection(cs::knownStateCorrections(), b.view, s.lookup()).verdict, StateCorrectionVerdict::None); +}