diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index eb985f328..28874a6ed 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -20,7 +20,8 @@ hush_gtest_SOURCES = \ gtest/test_fd_defense.cpp \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ - gtest/test_wallet_history.cpp + gtest/test_wallet_history.cpp \ + gtest/test_wallet_consolidation.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp new file mode 100644 index 000000000..59c8eb8f7 --- /dev/null +++ b/src/gtest/test_wallet_consolidation.cpp @@ -0,0 +1,190 @@ +// 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 + +#include +#include +#include + +#include "primitives/transaction.h" +#include "random.h" +#include "wallet/asyncrpcoperation_saplingconsolidation.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 Values(size_t n, CAmount start = 1000, CAmount step = 1000) { + std::vector v; + for (size_t i = 0; i < n; i++) + v.push_back(start + step * (CAmount)i); + return v; +} + +size_t PlannedNotes(const std::vector& 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> 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> 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 v = Values(100); + std::vector shuffled = v; + std::reverse(shuffled.begin(), shuffled.end()); + std::rotate(shuffled.begin(), shuffled.begin() + 37, shuffled.end()); + std::vector> groups = { shuffled }; + + auto plan = PlanSaplingConsolidation(groups, policy, RngHigh); + ASSERT_EQ(plan.size(), 3u); + std::set seen; + std::vector 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> 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 txs; + std::map> 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 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"; +} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 6096d3d19..14ea44631 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -17,6 +17,9 @@ #include "utilmoneystr.h" #include "wallet.h" +#include +#include + CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE; bool fConsolidationMapUsed = false; @@ -28,6 +31,65 @@ static const int MIN_ZOUTS = 7; extern string randomSietchZaddr(); +int SaplingConsolidationMaxInputs(size_t maxTxSize) { + // Everything but the descriptions (header, value balance, binding signature, counts) is a few + // hundred bytes; 1000 leaves room to spare. + const size_t overhead = 1000; + const size_t outputs = (1 + MIN_ZOUTS) * OUTPUTDESCRIPTION_SIZE; + if (maxTxSize <= overhead + outputs) + return 0; + return (int)std::min((maxTxSize - overhead - outputs) / SPENDDESCRIPTION_SIZE, INT_MAX); +} + +int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize) { + int batch = std::max(MIN_CONSOLIDATION_BATCHSIZE, std::min(requested, MAX_CONSOLIDATION_BATCHSIZE)); + return std::min(batch, SaplingConsolidationMaxInputs(maxTxSize)); +} + +std::vector PlanSaplingConsolidation( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng) +{ + std::vector plan; + const int batch = ClampSaplingConsolidationBatchSize(policy.batchSize, policy.maxTxSize); + if (batch < 2) + return plan; + // ceil(2*batch/3), at least 2: the low end of the per-tx input count. + const int low = std::max(2, (2 * batch + 2) / 3); + + for (size_t g = 0; g < groups.size(); g++) { + const std::vector& values = groups[g]; + if (policy.threshold < 0 || values.size() <= (size_t)policy.threshold) + continue; + + // Smallest first; ties keep wallet order so the plan is deterministic for a given rng. + std::vector order(values.size()); + for (size_t i = 0; i < order.size(); i++) + order[i] = i; + std::stable_sort(order.begin(), order.end(), + [&values](size_t a, size_t b) { return values[a] < values[b]; }); + + size_t next = 0; + for (int t = 0; t < policy.maxTxs; t++) { + const size_t left = order.size() - next; + size_t take = low + (size_t)rng((uint64_t)(batch - low + 1)); + take = std::min(take, batch); + // Leave at least one note out of the round so the address stays spendable meanwhile. + if (left == 0 || take > left - 1) + take = (left == 0) ? 0 : left - 1; + if (take < 2) + break; + SaplingConsolidationBatch b; + b.group = g; + b.notes.assign(order.begin() + next, order.begin() + next + take); + next += take; + plan.push_back(std::move(b)); + } + } + return plan; +} + AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {} AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 675a56ad7..60effe51c 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -3,6 +3,9 @@ // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html +#ifndef HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H +#define HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H + #include "amount.h" #include "asyncrpcoperation.h" #include "univalue.h" @@ -10,11 +13,47 @@ #include "zcash/zip32.h" #include "wallet.h" // for SaplingNoteEntry +#include +#include + //Default fee used for consolidation transactions, in puposhis static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000; extern CAmount fConsolidationTxFee; extern bool fConsolidationMapUsed; +// What one consolidation round may do (see PlanSaplingConsolidation). +struct SaplingConsolidationPolicy { + int threshold = DEFAULT_CONSOLIDATION_THRESHOLD; // only addresses with MORE eligible notes than this + int batchSize = DEFAULT_CONSOLIDATION_BATCHSIZE; // most notes one transaction spends + int maxTxs = DEFAULT_CONSOLIDATION_MAXTXS; // most transactions per address per round + size_t maxTxSize = MAX_TX_SIZE_AFTER_SAPLING; // the batch is also capped to what fits in this +}; + +// One planned consolidation transaction: notes of a single address merged back into it. +struct SaplingConsolidationBatch { + size_t group; // index of the address in the groups handed to the planner + std::vector notes; // indices into that address's note values +}; + +// Most spends a consolidation tx can carry next to its 1 + MIN_ZOUTS outputs within maxTxSize. +int SaplingConsolidationMaxInputs(size_t maxTxSize); + +// The batch size actually used: clamped to [MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE] +// and to SaplingConsolidationMaxInputs(maxTxSize). +int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize = MAX_TX_SIZE_AFTER_SAPLING); + +// Plans one round. groups[i] holds the values of address i's eligible notes. Only an address with more +// than policy.threshold notes is consolidated. Its notes are taken smallest first (so the note an earlier +// round produced is not merged again and again), up to policy.maxTxs transactions, each spending a count +// drawn uniformly from [max(2, ceil(2*batch/3)), batch] so rounds don't all look alike. A transaction never +// takes the address's last remaining note (one stays spendable while the round confirms), and the address +// is done once fewer than two notes could be taken. Batches never mix addresses. rng(n) returns a uniform +// value in [0, n); pure apart from it. +std::vector PlanSaplingConsolidation( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng); + class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation { public: @@ -45,3 +84,5 @@ private: void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds); }; + +#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 96bd4b631..41740ddeb 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -112,6 +112,21 @@ static const int MIN_AUTOSHIELD_INTERVAL = 5; static const int DEFAULT_AUTOSHIELD_MIN_UTXOS = 1; static const CAmount AUTOSHIELD_MIN_FEE = 1000; // comfortably above minRelayTxFee for a small tx static const CAmount AUTOSHIELD_MAX_FEE = 10000000; // 0.1 DRGX; no sane autoshield fee exceeds this +// Sapling consolidation (-consolidation / z_consolidate). An address is only consolidated once it holds +// MORE than the threshold of spendable notes; a round then sends up to maxtxs transactions per address, +// each spending up to batchsize of its smallest notes back to that same address. +static const int DEFAULT_CONSOLIDATION_INTERVAL = 25; +static const int MIN_CONSOLIDATION_INTERVAL = 5; +static const int DEFAULT_CONSOLIDATION_THRESHOLD = 25; +static const int MIN_CONSOLIDATION_THRESHOLD = 1; +static const int DEFAULT_CONSOLIDATION_BATCHSIZE = 15; +static const int MIN_CONSOLIDATION_BATCHSIZE = 2; +static const int MAX_CONSOLIDATION_BATCHSIZE = 50; +static const int DEFAULT_CONSOLIDATION_MAXTXS = 3; +static const int MAX_CONSOLIDATION_MAXTXS = 100; +static const CAmount CONSOLIDATION_MIN_FEE = AUTOSHIELD_MIN_FEE; +static const CAmount CONSOLIDATION_MAX_FEE = AUTOSHIELD_MAX_FEE; +static const int CONSOLIDATION_MIN_DEPTH = 11; // leaves room for an anchor at height N-10 static const int AUTO_OP_TARGET_HEIGHT_OFFSET = 5; // blocks of lookahead when scheduling an async op static const int AUTO_OP_EXPIRY_DELTA = 15; // NU-straddle expiry window, shared by all three ops