wallet: plan consolidation rounds with a threshold/batch policy

Sapling consolidation picks notes in wallet order, a random 1..8 of them
per address with rand(), and merges every address with three or more
notes, every round. A miner whose wallet autoshield fills with one note
per round wants the opposite: leave tidy addresses alone, merge the
small notes of the crowded ones in bounded batches, and never re-merge
the big note an earlier round produced.

Add that policy as a pure function the op can use and the tests can
drive: PlanSaplingConsolidation() takes each address's eligible note
values and returns the round's batches. Only an address with MORE than
the threshold of notes (default 25) is consolidated; its notes are taken
smallest first, up to maxtxs transactions (default 3) of a per-tx input
count drawn from [max(2, ceil(2*batch/3)), batch] (default batch 15,
clamped to 2..50 and to what fits in MAX_TX_SIZE_AFTER_SAPLING next to
the 1 + 7 Sietch outputs). A transaction never takes an address's last
note, so the address stays spendable while the round confirms, and
batches never mix addresses. The randomness is the caller's (the op
will pass GetRand).

The option defaults live with the other auto-op defaults in wallet.h.
Nothing calls the planner yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 10:25:59 -05:00
co-authored by Claude Opus 5.5
parent fe988d6fbe
commit 3859a8ce22
5 changed files with 310 additions and 1 deletions
+2 -1
View File
@@ -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)
+190
View File
@@ -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 <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <set>
#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<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";
}
@@ -17,6 +17,9 @@
#include "utilmoneystr.h"
#include "wallet.h"
#include <algorithm>
#include <climits>
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<size_t>((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<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng)
{
std::vector<SaplingConsolidationBatch> 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<CAmount>& 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<size_t> 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<size_t>(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() {}
@@ -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 <functional>
#include <vector>
//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<size_t> 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<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng);
class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation
{
public:
@@ -45,3 +84,5 @@ private:
void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector<std::string>& consolidationTxIds);
};
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H
+15
View File
@@ -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