Files
dragonx/src/gtest/test_wallet_consolidation.cpp
T
DanSandClaude Opus 5.5 27a2f04189 wallet: spend consolidation notes only at a chain anchor
The round took its anchor from GetSaplingNoteWitnesses, a majority vote
over the planned notes alone that never looks at the chain. A real
wallet has had 108 notes desynced onto one root the chain never had, at
the same address as 104 healthy ones. Smallest-first planning can pick
a batch that is mostly desynced notes. The vote then made the healthy
notes the "unusable" ones, and the tx was proved at a non-anchor: Build
succeeds, since witnesses and anchor agree, but CommitTransaction adds
it to the wallet before the mempool refuses it. Its notes then look
spent, and since the plan is nearly deterministic this recurs every
round. One failed tx also ended the round for every other address.

PlanSaplingConsolidationSpends now plans over the notes that can be
spent together. A planned note is used only if its newest witness root
is a Sapling anchor the chain holds (GetSaplingAnchorAt on pcoinsTip,
the check consensus makes) and is its address's anchor: the tip's root
if any planned note is there, else the chain anchor most share. Other
planned notes are left out and the round is re-planned until none are.
The planner is pure apart from its callbacks and is tested, including
a desynced majority. GetSaplingNoteLatestWitness is pass 1 of
GetSaplingNoteWitnesses, split out; that function is unchanged.

A tx that fails to build or commit now only skips the rest of its own
address's txs; the first failure is the round's error.

Skipped notes are logged once per round with a count and the first
five outpoints, instead of once per process: a note that is unusable
only during a witness rebuild was otherwise never reported again.

The fee rule moves into SaplingConsolidationTxFee, with a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:54:55 -05:00

396 lines
16 KiB
C++

// Copyright (c) 2016-2026 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <set>
#include "arith_uint256.h"
#include "primitives/transaction.h"
#include "random.h"
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
#include "wallet/wallet.h"
namespace {
// Always the low end, always the high end, or a fixed sequence.
uint64_t RngLow(uint64_t) { return 0; }
uint64_t RngHigh(uint64_t n) { return n == 0 ? 0 : n - 1; }
std::vector<CAmount> Values(size_t n, CAmount start = 1000, CAmount step = 1000) {
std::vector<CAmount> v;
for (size_t i = 0; i < n; i++)
v.push_back(start + step * (CAmount)i);
return v;
}
size_t PlannedNotes(const std::vector<SaplingConsolidationBatch>& plan, size_t group) {
size_t n = 0;
for (const SaplingConsolidationBatch& b : plan)
if (b.group == group)
n += b.notes.size();
return n;
}
} // namespace
TEST(SaplingConsolidationPlan, ThresholdIsStrict) {
SaplingConsolidationPolicy policy; // threshold 25, batch 15, 3 txs
std::vector<std::vector<CAmount>> groups = { Values(25), Values(26) };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
EXPECT_EQ(PlannedNotes(plan, 0), 0u) << "an address AT the threshold is left alone";
EXPECT_GT(PlannedNotes(plan, 1), 0u) << "an address one note over it is consolidated";
}
TEST(SaplingConsolidationPlan, DefaultsMergeUpToThreeBatches) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(200) };
auto high = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(high.size(), 3u);
for (const auto& b : high)
EXPECT_EQ(b.notes.size(), 15u);
// ceil(2*15/3) = 10 at the low end.
auto low = PlanSaplingConsolidation(groups, policy, RngLow);
ASSERT_EQ(low.size(), 3u);
for (const auto& b : low)
EXPECT_EQ(b.notes.size(), 10u);
}
TEST(SaplingConsolidationPlan, SmallestNotesFirstAndDisjoint) {
SaplingConsolidationPolicy policy;
// Shuffled values; the planner must take them in ascending order.
std::vector<CAmount> v = Values(100);
std::vector<CAmount> shuffled = v;
std::reverse(shuffled.begin(), shuffled.end());
std::rotate(shuffled.begin(), shuffled.begin() + 37, shuffled.end());
std::vector<std::vector<CAmount>> groups = { shuffled };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
std::set<size_t> seen;
std::vector<CAmount> taken;
for (const auto& b : plan) {
for (size_t idx : b.notes) {
ASSERT_LT(idx, shuffled.size());
EXPECT_TRUE(seen.insert(idx).second) << "a note is planned twice";
taken.push_back(shuffled[idx]);
}
}
// The 45 notes taken are exactly the 45 smallest, in ascending order across batches.
ASSERT_EQ(taken.size(), 45u);
for (size_t i = 0; i < taken.size(); i++)
EXPECT_EQ(taken[i], v[i]);
}
TEST(SaplingConsolidationPlan, NeverCrossesAddresses) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(40, 5), Values(3), Values(80, 7), Values(26, 1) };
auto plan = PlanSaplingConsolidation(groups, policy, [](uint64_t n) { return GetRand(n); });
std::map<size_t, int> txs;
std::map<size_t, std::set<size_t>> used;
for (const auto& b : plan) {
ASSERT_LT(b.group, groups.size());
txs[b.group]++;
for (size_t idx : b.notes) {
ASSERT_LT(idx, groups[b.group].size());
EXPECT_TRUE(used[b.group].insert(idx).second);
}
}
EXPECT_EQ(txs.count(1), 0u) << "3 notes is under the threshold";
for (const auto& t : txs)
EXPECT_LE(t.second, policy.maxTxs);
// Each consolidated address keeps at least one note outside the round.
for (const auto& u : used)
EXPECT_LT(u.second.size(), groups[u.first].size());
}
TEST(SaplingConsolidationPlan, LeavesOneNoteAndStopsBelowTwoInputs) {
SaplingConsolidationPolicy policy;
policy.threshold = 2;
// 30 notes, batch 15: 15, then at most 14 (one must stay out), then nothing.
auto plan = PlanSaplingConsolidation({ Values(30) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 2u);
EXPECT_EQ(plan[0].notes.size(), 15u);
EXPECT_EQ(plan[1].notes.size(), 14u);
// 3 notes over a threshold of 2: one tx of 2, the third note stays.
plan = PlanSaplingConsolidation({ Values(3) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 1u);
EXPECT_EQ(plan[0].notes.size(), 2u);
// 2 notes over a threshold of 1: merging both would leave none outside the round.
policy.threshold = 1;
plan = PlanSaplingConsolidation({ Values(2) }, policy, RngHigh);
EXPECT_TRUE(plan.empty());
}
TEST(SaplingConsolidationPlan, MaxTxsAndBatchSize) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 0;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(500) }, policy, RngHigh).empty());
policy.maxTxs = 7;
policy.batchSize = 2;
auto plan = PlanSaplingConsolidation({ Values(500) }, policy, RngLow);
ASSERT_EQ(plan.size(), 7u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
// Out-of-range batch sizes are clamped, not trusted.
policy.batchSize = 1;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
policy.batchSize = 1000;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), (size_t)MAX_CONSOLIDATION_BATCHSIZE);
}
TEST(SaplingConsolidationPlan, RespectsTxSizeCap) {
// The real cap fits the largest allowed batch with room to spare.
EXPECT_GE(SaplingConsolidationMaxInputs(MAX_TX_SIZE_AFTER_SAPLING), MAX_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15), 15);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(0), MIN_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(51), MAX_CONSOLIDATION_BATCHSIZE);
// A tx size that only fits 5 spends next to the 8 outputs caps every batch at 5.
const size_t outputs = 8 * OUTPUTDESCRIPTION_SIZE;
const size_t small = 1000 + outputs + 5 * SPENDDESCRIPTION_SIZE + SPENDDESCRIPTION_SIZE / 2;
EXPECT_EQ(SaplingConsolidationMaxInputs(small), 5);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15, small), 5);
SaplingConsolidationPolicy policy;
policy.maxTxSize = small;
auto plan = PlanSaplingConsolidation({ Values(100) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 5u);
// Too small for even two spends: nothing is planned.
policy.maxTxSize = 1000 + outputs + SPENDDESCRIPTION_SIZE;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(100) }, policy, RngHigh).empty());
}
TEST(SaplingConsolidationPlan, RandomCountsStayInRange) {
SaplingConsolidationPolicy policy;
std::set<size_t> sizes;
for (int run = 0; run < 200; run++) {
auto plan = PlanSaplingConsolidation({ Values(300) }, policy, [](uint64_t n) { return GetRand(n); });
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan) {
EXPECT_GE(b.notes.size(), 10u);
EXPECT_LE(b.notes.size(), 15u);
sizes.insert(b.notes.size());
}
}
EXPECT_GT(sizes.size(), 1u) << "the per-tx input count should vary";
}
TEST(SaplingConsolidationStats, RecordAccumulates) {
SaplingConsolidationStats stats;
EXPECT_FALSE(stats.hasLastRound);
EXPECT_EQ(stats.amountConsolidated, 0);
SaplingConsolidationRound first;
first.height = 100;
first.txids = { "aa", "bb", "cc" };
first.notesMerged = 40;
first.amountMerged = 4000000;
first.fees = 30000;
first.amountConsolidated = 4000000 - 30000;
stats.Record(first);
// A round that found nothing to do still counts as a round and becomes the last one.
SaplingConsolidationRound idle;
idle.height = 125;
stats.Record(idle);
SaplingConsolidationRound failed;
failed.height = 150;
failed.txids = { "dd" };
failed.notesMerged = 12;
failed.amountMerged = 1200000;
failed.fees = 10000;
failed.amountConsolidated = 1190000;
failed.skippedNotes = 2;
failed.error = "transaction was not accepted (CommitTransaction failed)";
stats.Record(failed);
EXPECT_EQ(stats.rounds, 3);
EXPECT_EQ(stats.txsCreated, 4);
EXPECT_EQ(stats.notesConsolidated, 52);
EXPECT_EQ(stats.amountConsolidated, 3970000 + 1190000);
ASSERT_TRUE(stats.hasLastRound);
EXPECT_EQ(stats.lastRound.height, 150);
EXPECT_EQ(stats.lastRound.txids.size(), 1u);
EXPECT_EQ(stats.lastRound.skippedNotes, 2);
EXPECT_EQ(stats.lastRound.error, failed.error);
}
namespace {
uint256 Root(int n) { return ArithToUint256(arith_uint256(n)); }
// Witness roots per note, for PlanSaplingConsolidationSpends; also counts its lookups.
struct Witnesses {
std::vector<std::vector<boost::optional<uint256>>> roots;
std::set<uint256> chainAnchors;
std::map<std::pair<size_t, size_t>, int> rootCalls;
std::map<uint256, int> anchorCalls;
SaplingConsolidationSpendPlan Plan(const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy, const uint256& tip) {
return PlanSaplingConsolidationSpends(groups, policy, RngHigh,
[this](size_t g, size_t i) { rootCalls[std::make_pair(g, i)]++; return roots[g][i]; },
[this](const uint256& r) { anchorCalls[r]++; return chainAnchors.count(r) > 0; },
tip);
}
};
void ExpectAllAt(const SaplingConsolidationSpendPlan& plan, const Witnesses& w) {
for (const auto& b : plan.batches) {
ASSERT_TRUE(plan.anchors.count(b.group));
for (size_t i : b.notes) {
ASSERT_TRUE(w.roots[b.group][i]);
EXPECT_EQ(*w.roots[b.group][i], plan.anchors.at(b.group)) << "note " << i << " of address " << b.group;
}
}
}
} // namespace
TEST(SaplingConsolidationSpends, HealthyWalletPlansAsBefore) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(60), Values(10), Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
for (const auto& g : groups)
w.roots.push_back(std::vector<boost::optional<uint256>>(g.size(), Root(7)));
auto spends = w.Plan(groups, policy, Root(7));
auto plain = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(spends.batches.size(), plain.size());
for (size_t k = 0; k < plain.size(); k++) {
EXPECT_EQ(spends.batches[k].group, plain[k].group);
EXPECT_EQ(spends.batches[k].notes, plain[k].notes);
}
EXPECT_TRUE(spends.unusable.empty());
EXPECT_TRUE(spends.deferred.empty());
EXPECT_EQ(spends.anchors.size(), 2u) << "the address under the threshold gets no anchor";
EXPECT_EQ(spends.anchors.at(0), Root(7));
// Only planned notes are looked at, each once, and the one root once.
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
EXPECT_EQ(w.rootCalls.size(), PlannedNotes(plain, 0) + PlannedNotes(plain, 2));
EXPECT_EQ(w.anchorCalls.size(), 1u);
EXPECT_EQ(w.anchorCalls[Root(7)], 1);
}
// The case seen on a real wallet: many notes of one address share a root the chain never had, and smallest-first
// planning picks mostly (here: only) those. They must not decide the anchor and take the healthy notes down.
TEST(SaplingConsolidationSpends, DesyncedMajorityDoesNotWin) {
SaplingConsolidationPolicy policy; // 25 / 15 / 3
std::vector<std::vector<CAmount>> groups = { Values(100) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.resize(1);
for (size_t i = 0; i < 100; i++)
w.roots[0].push_back(i < 50 ? Root(666) : Root(7)); // the 50 smallest are desynced
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 3u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
for (const auto& b : plan.batches)
for (size_t i : b.notes)
EXPECT_GE(i, 50u);
EXPECT_EQ(plan.unusable.size(), 50u);
EXPECT_TRUE(plan.deferred.empty());
EXPECT_EQ(w.anchorCalls[Root(666)], 1) << "a root is checked against the chain once";
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
// The same when the tip's root is not among them: the chain anchor wins, not the majority.
Witnesses old = w;
old.chainAnchors = { Root(5) };
for (size_t i = 50; i < 100; i++)
old.roots[0][i] = Root(5);
old.rootCalls.clear();
old.anchorCalls.clear();
auto plan2 = old.Plan(groups, policy, Root(7));
ASSERT_EQ(plan2.batches.size(), 3u);
EXPECT_EQ(plan2.anchors.at(0), Root(5));
ExpectAllAt(plan2, old);
}
TEST(SaplingConsolidationSpends, MissingWitnessesAreSkipped) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][0] = boost::none;
w.roots[0][3] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.batches[0].notes.size(), 15u) << "the dropped notes are replaced by the next smallest";
ExpectAllAt(plan, w);
std::set<std::pair<size_t, size_t>> unusable(plan.unusable.begin(), plan.unusable.end());
EXPECT_EQ(unusable, (std::set<std::pair<size_t, size_t>>{ {0, 0}, {0, 3} }));
}
// Witnesses at a different, real anchor (a rebuild still under way) are deferred, not called unusable.
TEST(SaplingConsolidationSpends, OtherChainAnchorIsDeferred) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7), Root(6) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][1] = Root(6);
w.roots[0][2] = Root(6);
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
EXPECT_TRUE(plan.unusable.empty());
EXPECT_EQ(plan.deferred.size(), 2u);
}
// Leaving notes out can bring an address down to the threshold; then it is not consolidated, and needs no anchor.
TEST(SaplingConsolidationSpends, ThresholdCountsUsableNotes) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(26) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(7)));
w.roots[0][0] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
EXPECT_TRUE(plan.batches.empty());
EXPECT_TRUE(plan.anchors.empty());
EXPECT_EQ(plan.unusable.size(), 1u);
// Nothing at a chain anchor at all: nothing planned, every looked-at note reported.
Witnesses bad;
bad.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(666)));
auto none = bad.Plan(groups, policy, Root(7));
EXPECT_TRUE(none.batches.empty());
EXPECT_EQ(none.unusable.size(), 25u) << "the first plan took 25 of the 26, then 1 was too few to plan";
}
TEST(SaplingConsolidationFee, NotesWorthTheFeeGoFeeFree) {
EXPECT_EQ(SaplingConsolidationTxFee(10000, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(9999, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(10001, 10000), 10000);
EXPECT_EQ(SaplingConsolidationTxFee(5000000, 10000), 10000);
}