From 3859a8ce22503947ebd74ba9e3958632c4834c09 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:25:59 -0500 Subject: [PATCH 01/11] 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 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_consolidation.cpp | 190 ++++++++++++++++++ ...asyncrpcoperation_saplingconsolidation.cpp | 62 ++++++ .../asyncrpcoperation_saplingconsolidation.h | 41 ++++ src/wallet/wallet.h | 15 ++ 5 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 src/gtest/test_wallet_consolidation.cpp 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 From a800a266e595463b6c411f35e1f31b4564c1c62f Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:37:33 -0500 Subject: [PATCH 02/11] wallet: consolidate with the threshold/batch policy, lock only its notes The consolidation op now plans its round with PlanSaplingConsolidation: only addresses holding more than -consolidationthreshold eligible notes (GetFilteredNotes at depth 11, as before), up to -consolidationmaxtxs transactions per address, each spending up to -consolidationbatchsize of the address's smallest notes back to it, with GetRand rather than rand() varying the input count. Each transaction is shaped as before: N spends, one real output to the same address, 7 Sietch dummy outputs, expiry at tip + AUTO_OP_EXPIRY_DELTA, and the fee unless the notes are worth no more than it (then none, as sweep does). Two fixes ride on the rewrite: - The op locked every eligible note in the wallet, and only after proving, so a send made during a round saw no funds at all, while one made during the proving could pick the very notes being spent. It now locks exactly the notes it plans to spend, at planning time under the wallet lock, and unlocks them on every exit (main()). - One note with a missing or desynced witness ("Missing Witnesses! Stopping.") failed the whole round, every round. It is now dropped, logged once with its txid:index, and the round re-planned without it. Per address, the witnesses come from one GetSaplingNoteWitnesses call, so all of an address's spends share its majority anchor. The scheduler snapshots the policy into the op when it enqueues it, and skips a round (one interval) while the wallet is locked, as autoshield does, instead of enqueueing one that can sign nothing. Options: -consolidationthreshold (25), -consolidationbatchsize (15, clamped to 2..50 and the tx size) and -consolidationmaxtxs (3, 1..100) are new. -consolidationinterval below 5 is now clamped to 5 with a warning instead of silently reset to 25; -consolidationtxfee is range checked like -autoshieldfee ([1000, 10000000], else the default). The policy is parsed even with -consolidation off, for z_consolidate. -consolidatesaplingaddress must now be a Sapling address the wallet holds the spending key of (startup error otherwise), except the zsweep address -zsweep substitutes, which may be external as before. It is resolved once at startup instead of on every round. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 104 +++-- ...asyncrpcoperation_saplingconsolidation.cpp | 380 ++++++++++-------- .../asyncrpcoperation_saplingconsolidation.h | 26 +- src/wallet/wallet.cpp | 16 +- src/wallet/wallet.h | 7 +- 5 files changed, 340 insertions(+), 193 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..d7c574bf6 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -479,10 +479,13 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-usemnemonic", strprintf(_("Create new wallets from a fresh BIP39 seed phrase so the 24 words can be exported (z_exportmnemonic) and used in SilentDragonXLite. Set to 0 for a raw random seed with no recovery phrase; existing wallets are never changed (default: %u)"), 1)); strUsage += HelpMessageOpt("-hdtransparentgaplimit=", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many HD transparent keys so a rescan can find coinbase paid to them (default: %u)"), 1000)); strUsage += HelpMessageOpt("-mnemonicsaplinggap=", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many shielded (Sapling) addresses so a rescan can find notes sent to them (default: %u)"), 100)); - strUsage += HelpMessageOpt("-consolidation", _("Enable auto Sapling note consolidation (default: false)")); - strUsage += HelpMessageOpt("-consolidationinterval", _("Block interval between consolidations (default: 25)")); - strUsage += HelpMessageOpt("-consolidatesaplingaddress=", _("Specify Sapling Address to Consolidate. (default: all)")); - strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee amount in Puposhis used send consolidation transactions. (default %i)"), DEFAULT_CONSOLIDATION_FEE)); + strUsage += HelpMessageOpt("-consolidation", _("Periodically merge the notes of every address holding more than -consolidationthreshold spendable notes back into that address (default: false; z_consolidate runs a round on demand)")); + strUsage += HelpMessageOpt("-consolidationinterval", strprintf(_("Block interval between consolidation rounds (default: %i, min %i)"), DEFAULT_CONSOLIDATION_INTERVAL, MIN_CONSOLIDATION_INTERVAL)); + strUsage += HelpMessageOpt("-consolidationthreshold", strprintf(_("Only consolidate addresses with more than this many spendable notes (default: %i)"), DEFAULT_CONSOLIDATION_THRESHOLD)); + strUsage += HelpMessageOpt("-consolidationbatchsize", strprintf(_("Most notes one consolidation transaction spends, smallest first (default: %i, %i to %i)"), DEFAULT_CONSOLIDATION_BATCHSIZE, MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE)); + strUsage += HelpMessageOpt("-consolidationmaxtxs", strprintf(_("Most consolidation transactions per address per round (default: %i, max %i)"), DEFAULT_CONSOLIDATION_MAXTXS, MAX_CONSOLIDATION_MAXTXS)); + strUsage += HelpMessageOpt("-consolidatesaplingaddress=", _("Only consolidate this Sapling address; may be repeated. The wallet must hold its spending key (default: all)")); + strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee in puposhis per consolidation transaction (default: %i, range %i to %i)"), DEFAULT_CONSOLIDATION_FEE, CONSOLIDATION_MIN_FEE, CONSOLIDATION_MAX_FEE)); strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks")); strUsage += HelpMessageOpt("-zsweepaddress=", _("Specify the shielded address where swept funds will be sent)")); @@ -2409,32 +2412,58 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) LogPrintf("%s: HD seed predates seed-provenance recording; recorded origin as unknown\n", __func__); } - //Set Sapling Consolidation + //Set Sapling Consolidation. The policy is read even with -consolidation off: z_consolidate + //runs rounds on demand with it. pwalletMain->fSaplingConsolidationEnabled = GetBoolArg("-consolidation", false); - if(pwalletMain->fSaplingConsolidationEnabled) { - fConsolidationTxFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE); - fConsolidationMapUsed = !mapMultiArgs["-consolidatesaplingaddress"].empty(); + { + CAmount consolidationFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE); + if (consolidationFee < CONSOLIDATION_MIN_FEE || consolidationFee > CONSOLIDATION_MAX_FEE) { + InitWarning(strprintf(_("-consolidationtxfee=%lld out of range [%lld,%lld], using default %lld"), + (long long)consolidationFee, (long long)CONSOLIDATION_MIN_FEE, (long long)CONSOLIDATION_MAX_FEE, (long long)DEFAULT_CONSOLIDATION_FEE)); + consolidationFee = DEFAULT_CONSOLIDATION_FEE; + } + fConsolidationTxFee = consolidationFee; - int consolidationInterval = GetArg("-consolidationinterval", 25); - if (consolidationInterval < 5) { - LogPrintf("%s: Invalid consolidation interval of %d < 5, setting to default of 25\n", __func__, consolidationInterval); - consolidationInterval = 25; + int consolidationInterval = GetArg("-consolidationinterval", DEFAULT_CONSOLIDATION_INTERVAL); + if (consolidationInterval < MIN_CONSOLIDATION_INTERVAL) { + InitWarning(strprintf(_("consolidation interval %d below the minimum, clamping to %d"), + consolidationInterval, MIN_CONSOLIDATION_INTERVAL)); + consolidationInterval = MIN_CONSOLIDATION_INTERVAL; + } + int consolidationThreshold = GetArg("-consolidationthreshold", DEFAULT_CONSOLIDATION_THRESHOLD); + if (consolidationThreshold < MIN_CONSOLIDATION_THRESHOLD) { + InitWarning(strprintf(_("-consolidationthreshold=%d below the minimum, clamping to %d"), + consolidationThreshold, MIN_CONSOLIDATION_THRESHOLD)); + consolidationThreshold = MIN_CONSOLIDATION_THRESHOLD; + } + int consolidationBatchSize = GetArg("-consolidationbatchsize", DEFAULT_CONSOLIDATION_BATCHSIZE); + if (ClampSaplingConsolidationBatchSize(consolidationBatchSize) != consolidationBatchSize) { + InitWarning(strprintf(_("-consolidationbatchsize=%d out of range [%d,%d], clamping to %d"), + consolidationBatchSize, MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE, + ClampSaplingConsolidationBatchSize(consolidationBatchSize))); + consolidationBatchSize = ClampSaplingConsolidationBatchSize(consolidationBatchSize); + } + int consolidationMaxTxs = GetArg("-consolidationmaxtxs", DEFAULT_CONSOLIDATION_MAXTXS); + if (consolidationMaxTxs < 1 || consolidationMaxTxs > MAX_CONSOLIDATION_MAXTXS) { + int clamped = std::max(1, std::min(consolidationMaxTxs, MAX_CONSOLIDATION_MAXTXS)); + InitWarning(strprintf(_("-consolidationmaxtxs=%d out of range [1,%d], clamping to %d"), + consolidationMaxTxs, MAX_CONSOLIDATION_MAXTXS, clamped)); + consolidationMaxTxs = clamped; } - pwalletMain->consolidationInterval = consolidationInterval; - pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height(); - LogPrintf("%s: set nextConsolidation=%d\n", __func__, pwalletMain->nextConsolidation ); - - //Validate Sapling Addresses - vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - for (int i = 0; i < vaddresses.size(); i++) { - LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); - auto zAddress = DecodePaymentAddress(vaddresses[i]); - if (!IsValidPaymentAddress(zAddress)) { - return InitError("Invalid consolidation address"); - } + pwalletMain->consolidationInterval = consolidationInterval; + pwalletMain->consolidationThreshold = consolidationThreshold; + pwalletMain->consolidationBatchSize = consolidationBatchSize; + pwalletMain->consolidationMaxTxs = consolidationMaxTxs; + if (pwalletMain->fSaplingConsolidationEnabled) { + pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height(); + LogPrintf("%s: consolidation enabled, nextConsolidation=%d interval=%d threshold=%d batchsize=%d maxtxs=%d fee=%d\n", + __func__, pwalletMain->nextConsolidation, consolidationInterval, consolidationThreshold, + consolidationBatchSize, consolidationMaxTxs, (int)fConsolidationTxFee); } } + // Set when -zsweep makes consolidation work on the sweep address (see below). + bool fConsolidateSweepAddress = false; //Set Sweep pwalletMain->fSweepEnabled = GetBoolArg("-zsweep", false); @@ -2495,7 +2524,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) //Validate 1 Consolidation address only that matches the sweep address vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; if (vaddresses.size() == 0) { - fConsolidationMapUsed = true; + fConsolidateSweepAddress = true; mapMultiArgs["-consolidatesaplingaddress"] = vSweep; } else { pwalletMain->consolidationAddress = vaddresses[0]; @@ -2508,6 +2537,31 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } + // The addresses consolidation works on: -consolidatesaplingaddress, or with -zsweep the sweep address. + // A user-given address must be one this wallet can spend, else every round would silently skip it. + { + const vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; + fConsolidationMapUsed = !vaddresses.empty(); + pwalletMain->consolidationAddresses.clear(); + for (size_t i = 0; i < vaddresses.size(); i++) { + LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); + auto zAddress = DecodePaymentAddress(vaddresses[i]); + if (!IsValidPaymentAddress(zAddress) || + boost::get(&zAddress) == nullptr) { + return InitError("Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address"); + } + if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) { + if (!fConsolidateSweepAddress) { + return InitError(strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i])); + } + LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__); + } + pwalletMain->consolidationAddresses.push_back(boost::get(zAddress)); + } + if (!vaddresses.empty()) + pwalletMain->consolidationAddress = vaddresses[0]; + } + // Sweep and consolidation pick notes with GetFilteredNotes at minDepth > 1. Older versions // located each note's block by re-reading its tx through the txindex, so on a -txindex=0 node // every fully shielded tx was skipped and these never moved those notes. Now they will. diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 14ea44631..835d49c28 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -90,7 +90,8 @@ std::vector PlanSaplingConsolidation( return plan; } -AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {} +AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request) + : targetHeight_(targetHeight), request_(request) {} AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {} @@ -153,6 +154,10 @@ void AsyncRPCOperation_saplingconsolidation::main() { } } +// Notes whose missing or desynced witness has already been logged, so a note that can't be spent is +// reported once rather than every round. Guarded by pwalletMain->cs_wallet. +static std::set setWitnessSkipLogged; + bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; auto opid=getId(); @@ -171,197 +176,256 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) { LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid); - setConsolidationResult(0, 0, std::vector()); + setConsolidationResult(ConsolidationTally()); return status; } - std::vector saplingEntries; - std::set addresses; + // One address's eligible notes and the key that spends them. + struct AddressNotes { + libzcash::SaplingPaymentAddress addr; + libzcash::SaplingExtendedSpendingKey extsk; + std::vector notes; + }; + // One transaction to build: notes of one address, with witnesses that share one anchor. + struct PlannedTx { + size_t group; + std::vector notes; + std::vector witnesses; + uint256 anchor; + }; + std::vector groups; + std::vector txs; + ConsolidationTally tally; { LOCK2(cs_main, pwalletMain->cs_wallet); // We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying - // an anchor at height N-10 for each SpendDescription - // Consider, should notes be sorted? - pwalletMain->GetFilteredNotes(saplingEntries, "", 11); + // an anchor at height N-10 for each SpendDescription. Spent (also by a mempool tx) and + // locked notes are left out, as are notes this wallet can't spend. + std::vector saplingEntries; + pwalletMain->GetFilteredNotes(saplingEntries, "", CONSOLIDATION_MIN_DEPTH); - if(saplingEntries.size() == 0) { - LogPrintf("%s: Nothing to consolidate, done.\n",opid); - return true; + std::set wanted(request_.addresses.begin(), request_.addresses.end()); + std::map groupOf; + std::set noKey; + for (const SaplingNoteEntry& entry : saplingEntries) { + if (!wanted.empty() && wanted.count(entry.address) == 0) + continue; + auto it = groupOf.find(entry.address); + if (it == groupOf.end()) { + if (noKey.count(entry.address)) + continue; + AddressNotes g; + g.addr = entry.address; + if (!pwalletMain->GetSaplingExtendedSpendingKey(entry.address, g.extsk)) { + noKey.insert(entry.address); + continue; + } + it = groupOf.insert(std::make_pair(entry.address, groups.size())).first; + groups.push_back(std::move(g)); + } + groups[it->second].notes.push_back(entry); } - // store sapling inputs so we can correctly lock and unlock them - for (auto entry : saplingEntries) { - z_sapling_inputs_.push_back(entry); - } - - if (fConsolidationMapUsed) { - const vector& v = mapMultiArgs["-consolidatesaplingaddress"]; - for(int i = 0; i < v.size(); i++) { - auto zAddress = DecodePaymentAddress(v[i]); - if (boost::get(&zAddress) != nullptr) { - libzcash::SaplingPaymentAddress saplingAddress = boost::get(zAddress); - addresses.insert(saplingAddress); - } else { - LogPrintf("%s: Invalid zaddr, exiting\n", opid); - return false; + // Plan the round, then fetch the planned notes' witnesses. A note without a usable witness is + // dropped and the round re-planned without it, so it costs the round nothing but a log line. + // Each pass drops at least one note, so this ends. + std::set excluded; + for (;;) { + std::vector> live(groups.size()); + std::vector> values(groups.size()); + for (size_t g = 0; g < groups.size(); g++) { + for (size_t i = 0; i < groups[g].notes.size(); i++) { + if (excluded.count(groups[g].notes[i].op)) + continue; + live[g].push_back(i); + values[g].push_back(CAmount(groups[g].notes[i].note.value())); } } - } else { - pwalletMain->GetSaplingPaymentAddresses(addresses); + std::vector plan = PlanSaplingConsolidation( + values, request_.policy, [](uint64_t n) { return GetRand(n); }); + + // Witnesses per address: every spend of one address's txs then shares that address's anchor. + std::map> opsOf; + for (const SaplingConsolidationBatch& b : plan) + for (size_t idx : b.notes) + opsOf[b.group].push_back(groups[b.group].notes[live[b.group][idx]].op); + std::map witnessOf; + std::map anchorOf; + bool missing = false; + for (const auto& p : opsOf) { + std::vector> witnesses; + uint256 anchor; + pwalletMain->GetSaplingNoteWitnesses(p.second, witnesses, anchor); + anchorOf[p.first] = anchor; + for (size_t i = 0; i < p.second.size(); i++) { + if (witnesses[i]) { + witnessOf.insert(std::make_pair(p.second[i], witnesses[i].get())); + continue; + } + missing = true; + excluded.insert(p.second[i]); + if (setWitnessSkipLogged.insert(p.second[i]).second) + LogPrintf("%s: skipping note %s:%u, it has no usable witness\n", + opid, p.second[i].hash.ToString(), p.second[i].n); + } + } + if (missing) + continue; + + for (const SaplingConsolidationBatch& b : plan) { + PlannedTx tx; + tx.group = b.group; + tx.anchor = anchorOf[b.group]; + for (size_t idx : b.notes) { + const SaplingNoteEntry& entry = groups[b.group].notes[live[b.group][idx]]; + tx.notes.push_back(entry); + tx.witnesses.push_back(witnessOf.at(entry.op)); + } + txs.push_back(std::move(tx)); + } + break; + } + tally.skippedNotes = excluded.size(); + + // Lock just the notes this round spends, before the locks are released for proving, so a send + // made meanwhile neither picks them nor goes without the rest of the wallet's notes. + for (const PlannedTx& tx : txs) { + for (const SaplingNoteEntry& entry : tx.notes) { + pwalletMain->LockNote(entry.op); + z_sapling_inputs_.push_back(entry); + } } } - int numTxCreated = 0; - std::vector consolidationTxIds; - CAmount amountConsolidated = 0; - CCoinsViewCache coinsView(pcoinsTip); + if (txs.empty()) { + LogPrintf("%s: Nothing to consolidate (no address over %d eligible notes), done.\n", opid, request_.policy.threshold); + setConsolidationResult(tally); + return true; + } + LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size()); - for (auto addr : addresses) { - libzcash::SaplingExtendedSpendingKey extsk; - if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { + for (const PlannedTx& planned : txs) { + if (isCancelled()) { + LogPrintf("%s: Canceled. Stopping.\n", opid); + tally.error = "cancelled"; + status=false; + break; + } + const AddressNotes& group = groups[planned.group]; - std::vector fromNotes; - CAmount amountToSend = 0; - // max of 8 zins means the tx cannot reduce the anonset, - // since there will be 8 zins and 8 zouts at worst case - // This also helps reduce ztx creation time - int maxQuantity = rand() % 8 + 1; - for (const SaplingNoteEntry& saplingEntry : saplingEntries) { + auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); + builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA); - libzcash::SaplingIncomingViewingKey ivk; - pwalletMain->GetSaplingIncomingViewingKey(boost::get(saplingEntry.address), ivk); + CAmount amountToSend = 0; + for (const SaplingNoteEntry& entry : planned.notes) + amountToSend += CAmount(entry.note.value()); + // Notes worth no more than the fee go fee-free rather than being burnt into it. + CAmount thisTxFee = amountToSend <= request_.fee ? 0 : request_.fee; + CAmount actualAmountToSend = amountToSend - thisTxFee; + LogPrintf("%s: %s Beginning to create transaction with %d Sapling inputs, output amount=%s\n", + __func__, opid, planned.notes.size(), FormatMoney(actualAmountToSend)); - //Select Notes from that same address we will be sending to. - if (ivk == extsk.expsk.full_viewing_key().in_viewing_key()) { - amountToSend += CAmount(saplingEntry.note.value()); - fromNotes.push_back(saplingEntry); - } - - //Only use a randomly determined number of notes - if (fromNotes.size() >= maxQuantity) - break; - - } - - // minimum required - // We use 3 so that addresses can spent one zutxo and still have another zutxo to use while that - // tx is confirming - int minQuantity = 3; - if (fromNotes.size() < minQuantity) - continue; - - auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); - builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA); - auto actualAmountToSend = amountToSend < fConsolidationTxFee ? 0 : amountToSend - fConsolidationTxFee; - LogPrintf("%s: %s Beginning to create transaction with Sapling output amount=%s\n", __func__, opid, FormatMoney(actualAmountToSend)); - - // Select Sapling notes - std::vector ops; - std::vector notes; - for (auto fromNote : fromNotes) { - ops.push_back(fromNote.op); - notes.push_back(fromNote.note); - } - - // Fetch Sapling anchor and witnesses - uint256 anchor; - std::vector> witnesses; - { - LOCK2(cs_main, pwalletMain->cs_wallet); - // LogPrint("zrpcunsafe", "%s: Fetching note witnesses\n", opid); - pwalletMain->GetSaplingNoteWitnesses(ops, witnesses, anchor); - } - - // Add Sapling spends - for (size_t i = 0; i < notes.size(); i++) { - if (!witnesses[i]) { - LogPrintf("%s: Missing Witnesses! Stopping.\n", opid); - status=false; - break; - } - builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get()); - LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i); - } - - CAmount thisTxFee = amountToSend < fConsolidationTxFee ? 0 : fConsolidationTxFee; - LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee); - builder.SetFee(thisTxFee); - - // Add the actual consolidation tx - builder.AddSaplingOutput(extsk.expsk.ovk, addr, actualAmountToSend); - LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, addr.GetHash().ToString().c_str(), actualAmountToSend); - - // Add sietch zouts: MIN_ZOUTS dummy zero-value shielded outputs to - // randomly-generated z-addresses, so the consolidation tx does not - // shrink the anonymity set. - for(size_t i = 0; i < MIN_ZOUTS; i++) { - string zdust = randomSietchZaddr(); - auto zaddr = DecodePaymentAddress(zdust); - if (IsValidPaymentAddress(zaddr)) { - CAmount amount=0; - auto sietchZoutput = boost::get(zaddr); - LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount); - - // actually add our sietch zoutput, the new way - builder.AddSaplingOutput(extsk.expsk.ovk, sietchZoutput, amount); - } else { - LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust); - status = false; - break; - } - } - LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS); - auto maybe_tx = builder.Build(); - if (!maybe_tx) { - LogPrintf("%s: Failed to build transaction.\n",opid); - status=false; + // Add Sapling spends + bool spendsOk = true; + for (size_t i = 0; i < planned.notes.size(); i++) { + if (!builder.AddSaplingSpend(group.extsk.expsk, planned.notes[i].note, planned.anchor, planned.witnesses[i])) { + spendsOk = false; break; } - CTransaction tx = maybe_tx.get(); + LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i); + } + if (!spendsOk) { + LogPrintf("%s: Consolidation inputs do not share one anchor! Stopping.\n", opid); + tally.error = "inputs do not share one anchor"; + status=false; + break; + } - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - status=false; - break; - } + LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee); + builder.SetFee(thisTxFee); - // Lock shielded input notes - lock_notes(); - LogPrint("zrpc", "%s: consolidation input notes locked\n", getId()); + // Add the actual consolidation tx + builder.AddSaplingOutput(group.extsk.expsk.ovk, group.addr, actualAmountToSend); + LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, group.addr.GetHash().ToString().c_str(), actualAmountToSend); - if(pwalletMain->CommitAutomatedTx(tx)) { - LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString()); - amountConsolidated += actualAmountToSend; - consolidationTxIds.push_back(tx.GetHash().ToString()); - numTxCreated++; + // Add sietch zouts: MIN_ZOUTS dummy zero-value shielded outputs to + // randomly-generated z-addresses, so the consolidation tx does not + // shrink the anonymity set. + bool zoutsOk = true; + for(size_t i = 0; i < MIN_ZOUTS; i++) { + string zdust = randomSietchZaddr(); + auto zaddr = DecodePaymentAddress(zdust); + if (IsValidPaymentAddress(zaddr)) { + CAmount amount=0; + auto sietchZoutput = boost::get(zaddr); + LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount); + + // actually add our sietch zoutput, the new way + builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount); } else { - LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); - - unlock_notes(); - LogPrint("zrpc", "%s: consolidatoin input notes unlocked\n", getId()); - - setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds); - status = false; + LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust); + zoutsOk = false; break; } + } + if (!zoutsOk) { + tally.error = "invalid sietch address"; + status = false; + break; + } + LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS); + auto maybe_tx = builder.Build(); + if (!maybe_tx) { + LogPrintf("%s: Failed to build transaction.\n",opid); + tally.error = "failed to build transaction"; + status=false; + break; + } + CTransaction tx = maybe_tx.get(); + if (isCancelled()) { + LogPrintf("%s: Canceled. Stopping.\n", opid); + tally.error = "cancelled"; + status=false; + break; + } + + if(pwalletMain->CommitAutomatedTx(tx)) { + LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString()); + tally.txids.push_back(tx.GetHash().ToString()); + tally.notesMerged += planned.notes.size(); + tally.amountMerged += amountToSend; + tally.amountConsolidated += actualAmountToSend; + tally.fees += thisTxFee; + } else { + LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); + tally.error = "transaction was not accepted (CommitTransaction failed)"; + status = false; + break; } } - LogPrintf("%s: Created %d transactions with total Sapling output amount=%s,status=%d\n",opid , numTxCreated, FormatMoney(amountConsolidated), (int)status); - setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds); + LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, status=%d\n", + opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, (int)status); + setConsolidationResult(tally); return status; } -void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds) { +void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { UniValue res(UniValue::VOBJ); - res.push_back(Pair("num_tx_created", numTxCreated)); - res.push_back(Pair("amount_consolidated", FormatMoney(amountConsolidated))); + res.push_back(Pair("num_tx_created", (int)tally.txids.size())); + res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); UniValue txIds(UniValue::VARR); - for (const std::string& txId : consolidationTxIds) { + for (const std::string& txId : tally.txids) { txIds.push_back(txId); } res.push_back(Pair("consolidation_txids", txIds)); + res.push_back(Pair("notes_merged", tally.notesMerged)); + res.push_back(Pair("amount_merged", FormatMoney(tally.amountMerged))); + res.push_back(Pair("fees", FormatMoney(tally.fees))); + res.push_back(Pair("skipped_notes", tally.skippedNotes)); + if (!tally.error.empty()) + res.push_back(Pair("error", tally.error)); set_result(res); } @@ -384,14 +448,6 @@ UniValue AsyncRPCOperation_saplingconsolidation::getStatus() const { return obj; } -// Lock input notes -void AsyncRPCOperation_saplingconsolidation::lock_notes() { - LOCK2(cs_main, pwalletMain->cs_wallet); - for (auto note : z_sapling_inputs_) { - pwalletMain->LockNote(note.op); - } -} - // Unlock input notes void AsyncRPCOperation_saplingconsolidation::unlock_notes() { LOCK2(cs_main, pwalletMain->cs_wallet); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 60effe51c..ac6a0e26f 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -54,10 +54,28 @@ std::vector PlanSaplingConsolidation( const SaplingConsolidationPolicy& policy, const std::function& rng); +// What a consolidation operation is asked to do, fixed when it is enqueued. +struct SaplingConsolidationRequest { + CAmount fee = DEFAULT_CONSOLIDATION_FEE; + SaplingConsolidationPolicy policy; + std::vector addresses; // empty: every address the wallet can spend +}; + +// What a round did. +struct ConsolidationTally { + std::vector txids; + int notesMerged = 0; + CAmount amountMerged = 0; // value of the notes spent + CAmount amountConsolidated = 0; // value of the notes created (amountMerged minus fees) + CAmount fees = 0; + int skippedNotes = 0; // left out for a missing or unusable witness + std::string error; +}; + class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation { public: - AsyncRPCOperation_saplingconsolidation(int targetHeight); + AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request); virtual ~AsyncRPCOperation_saplingconsolidation(); // We don't want to be copied or moved around @@ -72,16 +90,16 @@ public: virtual UniValue getStatus() const; - void lock_notes(); void unlock_notes(); private: int targetHeight_; + SaplingConsolidationRequest request_; bool main_impl(); - std::vector z_sapling_inputs_; + std::vector z_sapling_inputs_; // the notes this round locked - void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds); + void setConsolidationResult(const ConsolidationTally& tally); }; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f3f098589..48019e411 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -710,6 +710,14 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { return; } + // Nothing can be signed while the wallet is locked. Skip the round instead of enqueueing one that + // can spend nothing, and look again an interval later. + if (IsLocked()) { + LogPrintf("%s: wallet locked; not consolidating at height=%d\n", __func__, blockHeight); + nextConsolidation = consolidationInterval + blockHeight; + return; + } + LogPrintf("%s: consolidation enabled at blockHeight=%d fSweepRunning=%d\n", __func__, blockHeight, fSweepRunning ); if (fSweepRunning) { @@ -734,7 +742,13 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { q->popOperationForId(saplingConsolidationOperationId); } pendingSaplingConsolidationTxs.clear(); - std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET)); + SaplingConsolidationRequest request; + request.fee = fConsolidationTxFee; + request.policy.threshold = consolidationThreshold; + request.policy.batchSize = consolidationBatchSize; + request.policy.maxTxs = consolidationMaxTxs; + request.addresses = consolidationAddresses; + std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET, request)); saplingConsolidationOperationId = operation->getId(); if (!q->addOperation(operation)) { // Queue is closing (shutdown). Release the flag we just set, or it stays diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 41740ddeb..7a2e1b707 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -895,7 +895,12 @@ public: int amountSwept = 0; int amountConsolidated = 0; int sweepInterval = 10; - int consolidationInterval = 25; + int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL; + int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD; + int consolidationBatchSize = DEFAULT_CONSOLIDATION_BATCHSIZE; + int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS; + // -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend. + std::vector consolidationAddresses; int sweepFee = 10000; int sweepMaxInputs = 200; std::string sweepAddress = ""; From e5791fea714614b1bbae5a4633f560c99820d3b4 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:49:38 -0500 Subject: [PATCH 03/11] wallet/rpc: make z_consolidationstatus report what consolidation does z_consolidationstatus reported amount_consolidated from an int that nothing ever added to (so always 0, and it would have overflowed past 21 DRGX), no policy, nothing about the rounds, and no hint of why a round would not run. Each consolidation op now records its round in CWallet's consolidationStats when it finishes (the op-id-guarded block in main(), so on success, failure and exception alike): tip height, time, txids, notes merged, amount merged and created, fees, notes skipped for a bad witness, and the error that stopped it, if any. The cumulative totals come from the same records. z_consolidationstatus keeps its fields (amount_consolidated now accumulates, in puposhis like consolidationtxfee) and adds the policy settings, rounds, txs_created, notes_consolidated, last_round and a disabled_reason like z_autoshieldstatus has: off, wallet locked, syncing (the same test ChainTip applies), or deferred while zsweep or autoshield runs. With the new optional verbose argument it also counts every address's eligible notes and says which are over the threshold; that walks the wallet under cs_main + cs_wallet, so only on request. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_consolidation.cpp | 42 ++++++ src/rpc/client.cpp | 1 + ...asyncrpcoperation_saplingconsolidation.cpp | 15 +++ .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 122 +++++++++++++++++- src/wallet/wallet.cpp | 10 ++ src/wallet/wallet.h | 40 +++++- 7 files changed, 226 insertions(+), 5 deletions(-) diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp index 59c8eb8f7..fdd8eaa45 100644 --- a/src/gtest/test_wallet_consolidation.cpp +++ b/src/gtest/test_wallet_consolidation.cpp @@ -11,6 +11,7 @@ #include "primitives/transaction.h" #include "random.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h" +#include "wallet/wallet.h" namespace { @@ -188,3 +189,44 @@ TEST(SaplingConsolidationPlan, RandomCountsStayInRange) { } 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); +} diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 3daf6738e..14a8db459 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -151,6 +151,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "z_shieldcoinbase", 2}, { "z_shieldcoinbase", 3}, { "z_getoperationstatus", 0}, + { "z_consolidationstatus", 0}, { "z_getoperationresult", 0}, { "notaries", 2 }, { "minerids", 1 }, diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 835d49c28..135e29fbd 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -150,6 +150,20 @@ void AsyncRPCOperation_saplingconsolidation::main() { int tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_; pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + tipHeight; pwalletMain->fConsolidationRunning = false; + + SaplingConsolidationRound round; + round.height = tipHeight; + round.time = GetTime(); + round.txids = tally_.txids; + round.notesMerged = tally_.notesMerged; + round.amountMerged = tally_.amountMerged; + round.amountConsolidated = tally_.amountConsolidated; + round.fees = tally_.fees; + round.skippedNotes = tally_.skippedNotes; + round.error = tally_.error; + if (!success && round.error.empty()) + round.error = getErrorMessage(); + pwalletMain->consolidationStats.Record(round); } } } @@ -412,6 +426,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { + tally_ = tally; UniValue res(UniValue::VOBJ); res.push_back(Pair("num_tx_created", (int)tally.txids.size())); res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index ac6a0e26f..71eb6245d 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -98,6 +98,7 @@ private: bool main_impl(); std::vector z_sapling_inputs_; // the notes this round locked + ConsolidationTally tally_; // what the round did, for z_consolidationstatus void setConsolidationResult(const ConsolidationTally& tally); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 893c5ce56..e214be8ab 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3269,32 +3269,146 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&) return returnObj; } +// Whether the wallet's periodic operations hold off because the node is catching up: the same test +// CWallet::ChainTip applies before it runs them. Caller holds cs_main. +static bool AutoWalletOpsSyncing() +{ + return IsInitialBlockDownload() || chainActive.Tip() == NULL || + chainActive.Tip()->GetBlockTime() <= GetTime() - 144*ASSETCHAINS_BLOCKTIME; +} + +// Why no consolidation round can start right now, or "" if one can. Caller holds cs_main + cs_wallet. +static std::string ConsolidationDisabledReason() +{ + if (!pwalletMain->fSaplingConsolidationEnabled) + return "disabled (-consolidation=0); z_consolidate runs a round on demand"; + if (pwalletMain->IsLocked()) + return "wallet is locked; rounds are skipped until it is unlocked"; + if (AutoWalletOpsSyncing()) + return "node is syncing; rounds start once it has caught up"; + if (pwalletMain->fSweepRunning) + return "deferred while z_sweep is running; rounds resume when it finishes"; + if (pwalletMain->fAutoShieldRunning) + return "deferred while autoshield is running; rounds resume when it finishes"; + return ""; +} + UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; - if (fHelp || params.size() > 0) + if (fHelp || params.size() > 1) throw runtime_error( - "z_consolidationstatus\n" - "\nGive details about consolidation operations since the node was started." + "z_consolidationstatus ( verbose )\n" + "\nGive details about Sapling note consolidation: its settings, what it has done since the node was\n" + "started, and -- when no round can run -- why.\n" + "\nArguments:\n" + "1. verbose (boolean, optional, default=false) also count every address's eligible notes.\n" + " This walks the whole wallet.\n" + "\nResult:\n" + "{\n" + " \"consolidation\" : true|false, (boolean) whether periodic consolidation (-consolidation) is on\n" + " \"running\" : true|false, (boolean) whether a round is in flight\n" + " \"amount_consolidated\" : n, (numeric) value of the notes created since startup, in puposhis\n" + " \"next_consolidation\" : n, (numeric) height of the next periodic round\n" + " \"consolidationinterval\" : n, (numeric) blocks between periodic rounds\n" + " \"consolidationaddress\" : \"zaddr\", (string) the first -consolidatesaplingaddress; empty: all addresses\n" + " \"consolidationtxfee\" : n, (numeric) fee per transaction, in puposhis\n" + " \"consolidationthreshold\" : n, (numeric) addresses with more eligible notes than this are consolidated\n" + " \"consolidationbatchsize\" : n, (numeric) most notes one transaction spends\n" + " \"consolidationmaxtxs\" : n, (numeric) most transactions per address per round\n" + " \"consolidationaddresses\" : [...], (array) the addresses consolidated; empty: every address with a spending key\n" + " \"rounds\" : n, (numeric) rounds completed since startup\n" + " \"txs_created\" : n, (numeric) consolidation transactions since startup\n" + " \"notes_consolidated\" : n, (numeric) notes merged since startup\n" + " \"last_round\" : { (object, null before the first round)\n" + " \"height\" : n, \"time\" : n, (numeric) tip height and time when it finished\n" + " \"txids\" : [...], (array) the transactions it sent\n" + " \"notes_merged\" : n, (numeric)\n" + " \"amount_merged\" : n, (numeric) value of the notes spent, in puposhis\n" + " \"amount_consolidated\" : n, (numeric) value of the notes created, in puposhis\n" + " \"fees\" : n, (numeric) in puposhis\n" + " \"skipped_notes\" : n, (numeric) notes left out for a missing or unusable witness\n" + " \"error\" : \"...\" (string) why it stopped early; empty if it did not\n" + " },\n" + " \"disabled_reason\" : \"...\", (string) why no periodic round can start now; empty if one can\n" + " \"addresses\" : [ (array, verbose only) every address with eligible notes\n" + " { \"address\" : \"zaddr\", \"eligible_notes\" : n, \"over_threshold\" : true|false, \"included\" : true|false }\n" + " ],\n" + " \"addresses_over_threshold\" : n (numeric, verbose only) included addresses over the threshold\n" "}\n" "\nExamples:\n" + HelpExampleCli("z_consolidationstatus", "") + + HelpExampleCli("z_consolidationstatus", "true") + HelpExampleRpc("z_consolidationstatus", "") ); + bool fVerbose = params.size() > 0 && !params[0].isNull() && params[0].get_bool(); + LOCK2(cs_main, pwalletMain->cs_wallet); + const SaplingConsolidationStats& stats = pwalletMain->consolidationStats; UniValue ret(UniValue::VOBJ); ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled)); ret.push_back(Pair("running", pwalletMain->fConsolidationRunning)); - ret.push_back(Pair("amount_consolidated", pwalletMain->amountConsolidated)); + ret.push_back(Pair("amount_consolidated", (int64_t)stats.amountConsolidated)); ret.push_back(Pair("next_consolidation", pwalletMain->nextConsolidation)); ret.push_back(Pair("consolidationinterval", pwalletMain->consolidationInterval)); ret.push_back(Pair("consolidationaddress", pwalletMain->consolidationAddress)); ret.push_back(Pair("consolidationtxfee",(int)fConsolidationTxFee)); + ret.push_back(Pair("consolidationthreshold", pwalletMain->consolidationThreshold)); + ret.push_back(Pair("consolidationbatchsize", pwalletMain->consolidationBatchSize)); + ret.push_back(Pair("consolidationmaxtxs", pwalletMain->consolidationMaxTxs)); + UniValue addrs(UniValue::VARR); + for (const libzcash::SaplingPaymentAddress& addr : pwalletMain->consolidationAddresses) + addrs.push_back(EncodePaymentAddress(addr)); + ret.push_back(Pair("consolidationaddresses", addrs)); + ret.push_back(Pair("rounds", stats.rounds)); + ret.push_back(Pair("txs_created", stats.txsCreated)); + ret.push_back(Pair("notes_consolidated", stats.notesConsolidated)); + if (stats.hasLastRound) { + const SaplingConsolidationRound& r = stats.lastRound; + UniValue last(UniValue::VOBJ); + last.push_back(Pair("height", r.height)); + last.push_back(Pair("time", r.time)); + UniValue txids(UniValue::VARR); + for (const std::string& txid : r.txids) + txids.push_back(txid); + last.push_back(Pair("txids", txids)); + last.push_back(Pair("notes_merged", r.notesMerged)); + last.push_back(Pair("amount_merged", (int64_t)r.amountMerged)); + last.push_back(Pair("amount_consolidated", (int64_t)r.amountConsolidated)); + last.push_back(Pair("fees", (int64_t)r.fees)); + last.push_back(Pair("skipped_notes", r.skippedNotes)); + last.push_back(Pair("error", r.error)); + ret.push_back(Pair("last_round", last)); + } else { + ret.push_back(Pair("last_round", NullUniValue)); + } + ret.push_back(Pair("disabled_reason", ConsolidationDisabledReason())); + + if (fVerbose) { + std::set included(pwalletMain->consolidationAddresses.begin(), + pwalletMain->consolidationAddresses.end()); + int over = 0; + UniValue list(UniValue::VARR); + for (const auto& p : pwalletMain->CountConsolidationEligibleNotes()) { + const bool isIncluded = included.empty() || included.count(p.first) > 0; + const bool isOver = p.second > pwalletMain->consolidationThreshold; + if (isIncluded && isOver) + over++; + UniValue entry(UniValue::VOBJ); + entry.push_back(Pair("address", EncodePaymentAddress(p.first))); + entry.push_back(Pair("eligible_notes", p.second)); + entry.push_back(Pair("over_threshold", isOver)); + entry.push_back(Pair("included", isIncluded)); + list.push_back(entry); + } + ret.push_back(Pair("addresses", list)); + ret.push_back(Pair("addresses_over_threshold", over)); + } return ret; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 48019e411..1f2cac79d 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -759,6 +759,16 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { } } +std::map CWallet::CountConsolidationEligibleNotes() { + LOCK2(cs_main, cs_wallet); + std::vector entries; + GetFilteredNotes(entries, "", CONSOLIDATION_MIN_DEPTH); + std::map counts; + for (const SaplingNoteEntry& entry : entries) + counts[entry.address]++; + return counts; +} + // Periodically drain matured transparent coinbase into a wallet-owned Sapling // z-address. Default-ON but conditional: this is enqueue-only (all gathering // happens on the async worker thread inside the op, which is why we must not diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 7a2e1b707..5e2e7e995 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -400,6 +400,40 @@ struct SaplingNoteEntry int confirmations; }; +/** What one Sapling consolidation round did (z_consolidationstatus "last_round"). */ +struct SaplingConsolidationRound +{ + int height = 0; //!< chain tip when the round finished + int64_t time = 0; + std::vector txids; + int notesMerged = 0; + CAmount amountMerged = 0; //!< value of the notes spent + CAmount amountConsolidated = 0; //!< value of the notes created + CAmount fees = 0; + int skippedNotes = 0; //!< left out for a missing or unusable witness + std::string error; //!< why the round stopped early, if it did +}; + +/** Sapling consolidation totals since the node started. */ +struct SaplingConsolidationStats +{ + int rounds = 0; + int64_t txsCreated = 0; + int64_t notesConsolidated = 0; + CAmount amountConsolidated = 0; + bool hasLastRound = false; + SaplingConsolidationRound lastRound; + + void Record(const SaplingConsolidationRound& round) { + rounds++; + txsCreated += round.txids.size(); + notesConsolidated += round.notesMerged; + amountConsolidated += round.amountConsolidated; + lastRound = round; + hasLastRound = true; + } +}; + /** Height of the active-chain block holding a wallet tx that is nDepth deep (as GetDepthInMainChain * returns it, and SaplingNoteEntry::confirmations holds it), or 0 when the tx is unconfirmed or not * in the active chain. Caller holds cs_main. */ @@ -893,7 +927,8 @@ public: // current one before mutating scheduler state. AsyncRPCOperationId saplingSweepOperationId; int amountSwept = 0; - int amountConsolidated = 0; + // What consolidation rounds have done since startup. Guarded by cs_wallet. + SaplingConsolidationStats consolidationStats; int sweepInterval = 10; int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL; int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD; @@ -1338,6 +1373,9 @@ public: const CBlock *pblock, boost::optional> added); void RunSaplingConsolidation(int blockHeight); + /** Notes a consolidation round would count as eligible, per address. Walks the whole wallet + * under cs_main + cs_wallet, so it is only run on request. */ + std::map CountConsolidationEligibleNotes(); void RunAutoShieldCoinbase(int blockHeight); bool CommitAutomatedTx(const CTransaction& tx); /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ From 52b747f6d3dd61149286e750c3ff656ff1dd1572 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:09:20 -0500 Subject: [PATCH 04/11] wallet/rpc: add z_consolidate, one consolidation round on demand A CLI miner who keeps -consolidation off (the default) has no way to shed the notes autoshield piles up short of scripting z_mergetoaddress, which pauses the miner and rebuilds its RandomX dataset on every call. z_consolidate ( fee batchsize maxtxs ["zaddr",...] ) runs one round of the built-in consolidation now, with the -consolidation policy, also when -consolidation is off. Any argument may be null to keep its setting; out-of-range values and addresses that are not the wallet's own Sapling addresses are refused rather than clamped. It returns the operation id; z_getoperationstatus/-result give the round's result, and z_consolidationstatus records it as a last_round with manual=true. It refuses while the node is syncing (the test ChainTip applies to the periodic ops), while the wallet is locked, and while a consolidation, zsweep or autoshield round is in flight. It takes the scheduler's slot like RunSaplingConsolidation does (fConsolidationRunning plus the op id), so sweep and autoshield defer to it and its completion releases the slot. The scheduler no longer pops a z_consolidate op from the queue when it starts the next round, so the user's result stays until z_getoperationresult collects it. Co-Authored-By: Claude Opus 5.5 --- src/rpc/client.cpp | 4 + src/rpc/server.h | 1 + ...asyncrpcoperation_saplingconsolidation.cpp | 6 +- .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 105 ++++++++++++++++++ src/wallet/wallet.cpp | 7 +- src/wallet/wallet.h | 3 + 7 files changed, 124 insertions(+), 3 deletions(-) diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 14a8db459..90013a070 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -152,6 +152,10 @@ static const CRPCConvertParam vRPCConvertParams[] = { "z_shieldcoinbase", 3}, { "z_getoperationstatus", 0}, { "z_consolidationstatus", 0}, + { "z_consolidate", 0}, + { "z_consolidate", 1}, + { "z_consolidate", 2}, + { "z_consolidate", 3}, { "z_getoperationresult", 0}, { "notaries", 2 }, { "minerids", 1 }, diff --git a/src/rpc/server.h b/src/rpc/server.h index a2d5c17cc..1ceeaff99 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -368,6 +368,7 @@ extern UniValue z_sendmany(const UniValue& params, bool fHelp, const CPubKey& my extern UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp +extern UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_shieldcoinbase(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_getoperationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_getoperationresult(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 135e29fbd..1ef89f9ce 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -153,6 +153,7 @@ void AsyncRPCOperation_saplingconsolidation::main() { SaplingConsolidationRound round; round.height = tipHeight; + round.manual = request_.manual; round.time = GetTime(); round.txids = tally_.txids; round.notesMerged = tally_.notesMerged; @@ -175,7 +176,9 @@ static std::set setWitnessSkipLogged; bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; auto opid=getId(); - LogPrintf("%s: Beginning AsyncRPCOperation_saplingconsolidation\n", opid); + LogPrintf("%s: Beginning AsyncRPCOperation_saplingconsolidation%s (threshold=%d batchsize=%d maxtxs=%d fee=%d)\n", + opid, request_.manual ? " (z_consolidate)" : "", request_.policy.threshold, + request_.policy.batchSize, request_.policy.maxTxs, (int)request_.fee); auto consensusParams = Params().GetConsensus(); int tipHeight; { @@ -460,6 +463,7 @@ UniValue AsyncRPCOperation_saplingconsolidation::getStatus() const { UniValue obj = v.get_obj(); obj.push_back(Pair("method", "saplingconsolidation")); obj.push_back(Pair("target_height", targetHeight_)); + obj.push_back(Pair("manual", request_.manual)); return obj; } diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 71eb6245d..8a5fc72b2 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -56,6 +56,7 @@ std::vector PlanSaplingConsolidation( // What a consolidation operation is asked to do, fixed when it is enqueued. struct SaplingConsolidationRequest { + bool manual = false; // z_consolidate rather than the -consolidation scheduler CAmount fee = DEFAULT_CONSOLIDATION_FEE; SaplingConsolidationPolicy policy; std::vector addresses; // empty: every address the wallet can spend diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e214be8ab..1a254d597 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -42,6 +42,7 @@ #include "wallet/asyncrpcoperation_mergetoaddress.h" #include "wallet/asyncrpcoperation_sendmany.h" #include "wallet/asyncrpcoperation_shieldcoinbase.h" +#include "wallet/asyncrpcoperation_saplingconsolidation.h" #include "consensus/upgrades.h" #include "sodium.h" #include @@ -3325,6 +3326,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"notes_consolidated\" : n, (numeric) notes merged since startup\n" " \"last_round\" : { (object, null before the first round)\n" " \"height\" : n, \"time\" : n, (numeric) tip height and time when it finished\n" + " \"manual\" : true|false, (boolean) run by z_consolidate\n" " \"txids\" : [...], (array) the transactions it sent\n" " \"notes_merged\" : n, (numeric)\n" " \"amount_merged\" : n, (numeric) value of the notes spent, in puposhis\n" @@ -3373,6 +3375,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey UniValue last(UniValue::VOBJ); last.push_back(Pair("height", r.height)); last.push_back(Pair("time", r.time)); + last.push_back(Pair("manual", r.manual)); UniValue txids(UniValue::VARR); for (const std::string& txid : r.txids) txids.push_back(txid); @@ -3413,6 +3416,107 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey return ret; } +UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) +{ + if (!EnsureWalletIsAvailable(fHelp)) + return NullUniValue; + + if (fHelp || params.size() > 4) + throw runtime_error( + "z_consolidate ( fee batchsize maxtxs [\"zaddr\",...] )\n" + "\nRun one Sapling consolidation round now, with the -consolidation settings, also when\n" + "-consolidation is off. Every address holding more than -consolidationthreshold eligible notes\n" + "(unspent, unlocked, at least 11 confirmations) gets up to maxtxs transactions, each spending up to\n" + "batchsize of its smallest notes back to that same address, plus 7 zero-value dummy outputs.\n" + "Pass null for an argument to keep its setting.\n" + "\nArguments:\n" + "1. fee (numeric, optional, default=-consolidationtxfee) fee per transaction in " + CURRENCY_UNIT + "\n" + "2. batchsize (numeric, optional, default=-consolidationbatchsize) most notes per transaction, " + + strprintf("%d to %d", MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE) + "\n" + "3. maxtxs (numeric, optional, default=-consolidationmaxtxs) most transactions per address, " + + strprintf("1 to %d", MAX_CONSOLIDATION_MAXTXS) + "\n" + "4. addresses (array, optional, default=-consolidatesaplingaddress or all) Sapling addresses to consolidate\n" + "\nResult:\n" + "\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\n" + "\nExamples:\n" + + HelpExampleCli("z_consolidate", "") + + HelpExampleCli("z_consolidate", "null 50 20 '[\"zs1...\"]'") + + HelpExampleRpc("z_consolidate", "") + ); + + LOCK2(cs_main, pwalletMain->cs_wallet); + + EnsureWalletIsUnlocked(); + if (AutoWalletOpsSyncing()) + throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Node is syncing; try again once it has caught up"); + if (pwalletMain->fConsolidationRunning) + throw JSONRPCError(RPC_WALLET_ERROR, "A consolidation round is already running; see z_consolidationstatus"); + if (pwalletMain->fSweepRunning || pwalletMain->fAutoShieldRunning) + throw JSONRPCError(RPC_WALLET_ERROR, strprintf("A %s round is running; try again when it finishes", + pwalletMain->fSweepRunning ? "z_sweep" : "autoshield")); + + SaplingConsolidationRequest request; + request.manual = true; + request.fee = fConsolidationTxFee; + request.policy.threshold = pwalletMain->consolidationThreshold; + request.policy.batchSize = pwalletMain->consolidationBatchSize; + request.policy.maxTxs = pwalletMain->consolidationMaxTxs; + request.addresses = pwalletMain->consolidationAddresses; + + if (params.size() > 0 && !params[0].isNull()) { + request.fee = AmountFromValue(params[0]); + if (request.fee < CONSOLIDATION_MIN_FEE || request.fee > CONSOLIDATION_MAX_FEE) + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid fee: must be from %s to %s", + FormatMoney(CONSOLIDATION_MIN_FEE), FormatMoney(CONSOLIDATION_MAX_FEE))); + } + if (params.size() > 1 && !params[1].isNull()) { + request.policy.batchSize = params[1].get_int(); + if (request.policy.batchSize < MIN_CONSOLIDATION_BATCHSIZE || request.policy.batchSize > MAX_CONSOLIDATION_BATCHSIZE) + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid batchsize: must be from %d to %d", + MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE)); + } + if (params.size() > 2 && !params[2].isNull()) { + request.policy.maxTxs = params[2].get_int(); + if (request.policy.maxTxs < 1 || request.policy.maxTxs > MAX_CONSOLIDATION_MAXTXS) + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid maxtxs: must be from 1 to %d", MAX_CONSOLIDATION_MAXTXS)); + } + if (params.size() > 3 && !params[3].isNull()) { + UniValue addresses = params[3].get_array(); + if (addresses.size() == 0) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid addresses: the array is empty"); + request.addresses.clear(); + for (size_t i = 0; i < addresses.size(); i++) { + const std::string& str = addresses[i].get_str(); + auto zaddr = DecodePaymentAddress(str); + if (!IsValidPaymentAddress(zaddr) || boost::get(&zaddr) == nullptr) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address, must be a Sapling z-address: " + str); + if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zaddr)) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Wallet does not hold the spending key of " + str); + request.addresses.push_back(boost::get(zaddr)); + } + } + + // Take the scheduler's slot exactly as RunSaplingConsolidation does, so sweep and autoshield + // defer to this round and its completion releases the flag. + pwalletMain->fConsolidationRunning = true; + std::shared_ptr q = getAsyncRPCQueue(); + std::shared_ptr lastOperation = q->getOperationForId(pwalletMain->saplingConsolidationOperationId); + if (lastOperation != nullptr) { + lastOperation->cancel(); + if (!pwalletMain->saplingConsolidationOpManual) + q->popOperationForId(pwalletMain->saplingConsolidationOperationId); + } + std::shared_ptr operation( + new AsyncRPCOperation_saplingconsolidation(chainActive.Height() + AUTO_OP_TARGET_HEIGHT_OFFSET, request)); + pwalletMain->saplingConsolidationOperationId = operation->getId(); + pwalletMain->saplingConsolidationOpManual = true; + if (!q->addOperation(operation)) { + pwalletMain->fConsolidationRunning = false; + throw JSONRPCError(RPC_INTERNAL_ERROR, "The async queue is not accepting operations (shutting down?)"); + } + return operation->getId(); +} + UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) { @@ -6569,6 +6673,7 @@ static const CRPCCommand commands[] = { "wallet", "z_sweepstatus", &z_sweepstatus, true }, { "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true }, { "wallet", "z_consolidationstatus", &z_consolidationstatus, true }, + { "wallet", "z_consolidate", &z_consolidate, true }, { "wallet", "z_sendmany", &z_sendmany, false }, { "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false }, { "wallet", "z_getoperationstatus", &z_getoperationstatus, true }, diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 1f2cac79d..c3b52c7f3 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -738,8 +738,10 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { lastOperation->cancel(); // Drop it from the queue's map as well. Nothing else ever removes these: // popOperationForId is only reached from z_getoperationresult, so on a node - // running this every interval the map grew without bound. - q->popOperationForId(saplingConsolidationOperationId); + // running this every interval the map grew without bound. A z_consolidate + // round is the user's: its result stays until z_getoperationresult takes it. + if (!saplingConsolidationOpManual) + q->popOperationForId(saplingConsolidationOperationId); } pendingSaplingConsolidationTxs.clear(); SaplingConsolidationRequest request; @@ -750,6 +752,7 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { request.addresses = consolidationAddresses; std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET, request)); saplingConsolidationOperationId = operation->getId(); + saplingConsolidationOpManual = false; if (!q->addOperation(operation)) { // Queue is closing (shutdown). Release the flag we just set, or it stays // set with no operation in flight and blocks every later round. diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 5e2e7e995..183d49972 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -404,6 +404,7 @@ struct SaplingNoteEntry struct SaplingConsolidationRound { int height = 0; //!< chain tip when the round finished + bool manual = false; //!< run by z_consolidate int64_t time = 0; std::vector txids; int notesMerged = 0; @@ -889,6 +890,8 @@ public: // Id of the in-flight consolidation op; read by the op to confirm it is // still the current one before mutating scheduler state. AsyncRPCOperationId saplingConsolidationOperationId; + // That op was started by z_consolidate: its result stays in the queue for z_getoperationresult. + bool saplingConsolidationOpManual = false; bool fSaplingConsolidationEnabled = false; bool fConsolidationRunning = false; From ead339418884b9f63751982f496979a43d0a3b71 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:21:06 -0500 Subject: [PATCH 05/11] wallet: suggest consolidation when it is off and notes pile up Consolidation stays off by default, but a miner whose autoshield adds one note per round should hear that it would help before the wallet slows down. With -consolidation off, count the addresses holding more than -consolidationthreshold eligible notes right after the startup note cache warm-up (the plaintexts are in memory then, so the walk is cheap) and log once: N addresses have more than 25 spendable notes; consider -consolidation=1 or z_consolidate z_autoshieldstatus reports it as consolidation_suggested (refreshing the count at most once per consolidation interval, since autoshield is what keeps adding the notes), and z_consolidationstatus verbose as consolidation_suggested and consolidation_suggested_count from its own walk. A later count that first finds an address over the threshold logs the line then, still only once per run. Co-Authored-By: Claude Opus 5.5 --- src/init.cpp | 4 ++++ src/wallet/rpcwallet.cpp | 22 ++++++++++++++++++++-- src/wallet/wallet.cpp | 28 ++++++++++++++++++++++++++++ src/wallet/wallet.h | 10 ++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index d7c574bf6..1e80eb76a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2771,6 +2771,10 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if (GetBoolArg("-notecachewarmup", true) && !ShutdownRequested()) { uiInterface.InitMessage(_("Decrypting wallet notes...")); pwalletMain->WarmSaplingNoteCache(); + // With the notes decrypted, counting them per address is cheap: suggest consolidation to a + // wallet that has piled up notes (typically a miner's, one note per autoshield round). + if (!pwalletMain->fSaplingConsolidationEnabled && !ShutdownRequested()) + pwalletMain->RefreshConsolidationSuggestion(); } pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true)); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 1a254d597..72a56282e 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3339,7 +3339,10 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"addresses\" : [ (array, verbose only) every address with eligible notes\n" " { \"address\" : \"zaddr\", \"eligible_notes\" : n, \"over_threshold\" : true|false, \"included\" : true|false }\n" " ],\n" - " \"addresses_over_threshold\" : n (numeric, verbose only) included addresses over the threshold\n" + " \"addresses_over_threshold\" : n, (numeric, verbose only) included addresses over the threshold\n" + " \"consolidation_suggested\" : true|false, (boolean, verbose only) -consolidation is off and some\n" + " address is over the threshold: consider -consolidation=1 or z_consolidate\n" + " \"consolidation_suggested_count\" : n (numeric, verbose only) addresses over the threshold while it is off\n" "}\n" "\nExamples:\n" + HelpExampleCli("z_consolidationstatus", "") @@ -3411,6 +3414,9 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey } ret.push_back(Pair("addresses", list)); ret.push_back(Pair("addresses_over_threshold", over)); + pwalletMain->SetConsolidationSuggestion(over); + ret.push_back(Pair("consolidation_suggested", !pwalletMain->fSaplingConsolidationEnabled && over > 0)); + ret.push_back(Pair("consolidation_suggested_count", pwalletMain->consolidationSuggestCount)); } return ret; @@ -3576,7 +3582,9 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m " \"hdseedorigin\" : n, (numeric) 0 unrecorded, 1 created, 2 restored, 3 retrofit, 4 unknown\n" " \"hdseedorigin_desc\" : \"...\", (string) readable form of hdseedorigin\n" " \"seed_recoverable\" : true|false, (boolean) whether a seed phrase can be exported\n" - " \"disabled_reason\" : \"...\" (string) why auto-shielding is not running, if it is not\n" + " \"disabled_reason\" : \"...\", (string) why auto-shielding is not running, if it is not\n" + " \"consolidation_suggested\" : true|false (boolean) -consolidation is off and some address holds more\n" + " than -consolidationthreshold spendable notes (see z_consolidationstatus)\n" "}\n" "\nExamples:\n" + HelpExampleCli("z_autoshieldstatus", "") @@ -3628,6 +3636,16 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m } ret.push_back(Pair("disabled_reason", why)); + // Autoshield is what fills a miner's wallet with notes, one per round, so say here when consolidation + // would help. The count is refreshed at most once per consolidation interval: it walks the wallet. + if (!pwalletMain->fSaplingConsolidationEnabled && + (pwalletMain->consolidationSuggestHeight < 0 || + chainActive.Height() - pwalletMain->consolidationSuggestHeight >= pwalletMain->consolidationInterval)) { + pwalletMain->RefreshConsolidationSuggestion(); + } + ret.push_back(Pair("consolidation_suggested", + !pwalletMain->fSaplingConsolidationEnabled && pwalletMain->consolidationSuggestCount > 0)); + return ret; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index c3b52c7f3..d13fe8492 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -772,6 +772,34 @@ std::map CWallet::CountConsolidationEligib return counts; } +void CWallet::SetConsolidationSuggestion(int overThreshold) { + LOCK2(cs_main, cs_wallet); + if (fSaplingConsolidationEnabled) + overThreshold = 0; + consolidationSuggestCount = overThreshold; + consolidationSuggestHeight = chainActive.Height(); + if (overThreshold > 0 && !fConsolidationSuggestLogged) { + fConsolidationSuggestLogged = true; + LogPrintf("%d %s more than %d spendable notes; consider -consolidation=1 or z_consolidate\n", + overThreshold, overThreshold == 1 ? "address has" : "addresses have", consolidationThreshold); + } +} + +void CWallet::RefreshConsolidationSuggestion() { + LOCK2(cs_main, cs_wallet); + if (fSaplingConsolidationEnabled) { + SetConsolidationSuggestion(0); + return; + } + std::set included(consolidationAddresses.begin(), consolidationAddresses.end()); + int over = 0; + for (const auto& p : CountConsolidationEligibleNotes()) { + if ((included.empty() || included.count(p.first)) && p.second > consolidationThreshold) + over++; + } + SetConsolidationSuggestion(over); +} + // Periodically drain matured transparent coinbase into a wallet-owned Sapling // z-address. Default-ON but conditional: this is enqueue-only (all gathering // happens on the async worker thread inside the op, which is why we must not diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 183d49972..64c6d61eb 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -932,6 +932,11 @@ public: int amountSwept = 0; // What consolidation rounds have done since startup. Guarded by cs_wallet. SaplingConsolidationStats consolidationStats; + // With -consolidation off: how many addresses are over the threshold (-1 until counted), at which + // height that was counted, and whether the "consider -consolidation" hint has been logged. + int consolidationSuggestCount = -1; + int consolidationSuggestHeight = -1; + bool fConsolidationSuggestLogged = false; int sweepInterval = 10; int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL; int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD; @@ -1379,6 +1384,11 @@ public: /** Notes a consolidation round would count as eligible, per address. Walks the whole wallet * under cs_main + cs_wallet, so it is only run on request. */ std::map CountConsolidationEligibleNotes(); + /** With -consolidation off, counts the addresses over the threshold into consolidationSuggestCount + * and logs, once, that consolidation would help. Walks the wallet like the above. */ + void RefreshConsolidationSuggestion(); + /** Records a count of addresses over the threshold (from either walk) and logs the hint once. */ + void SetConsolidationSuggestion(int overThreshold); void RunAutoShieldCoinbase(int blockHeight); bool CommitAutomatedTx(const CTransaction& tx); /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ From 7983a3dc68e4c1134d400d1438a7d9574e79e81c Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:22:58 -0500 Subject: [PATCH 06/11] doc: describe consolidation as it now works; fix zsweep doc errors Rewrite the consolidation part of doc/zsweep-consolidation.md to match the code: off by default (also for GUI wallets, which the doc claimed were on), what an eligible note is, the threshold/batch/maxtxs policy and its defaults including -consolidationinterval, smallest-first and the randomised input count, the 8-output shape, locking only the round's notes, skipped bad-witness notes, the fee range (fee 0 is no longer accepted), the spending-key requirement, z_consolidationstatus (the doc named z_sweepstatus) and its verbose mode, z_consolidate, and the off-but-suggested hint. Also fix -zsweepinterval: it defaults to 10 (values below 5 fall back to 10), not the 5 the doc and -help claimed. Co-Authored-By: Claude Opus 5.5 --- doc/zsweep-consolidation.md | 65 +++++++++++++++++++++++++++++++++---- src/init.cpp | 2 +- 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index ded919365..b99c9cd47 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -13,7 +13,7 @@ This is to document zsweep and consolidation for advanced DragonX users. A user can use these options at the command line, but it is **recommended to configure these options within the DRAGONX.conf file**. -Consolidation takes many unspent shielded UTXOs (zutxos) into one zutxo, which makes spending them in the future faster and potentially cost less in fees. It also helps prevent certain kinds of metadata leakages and spam attacks. It is not recommended for very large wallets (wallet.dat files with thousands of transactions) for performance reasons. This is why it defaults to OFF for CLI full nodes but ON for GUI wallets that use an embedded dragonxd. +Consolidation merges many unspent shielded notes (zutxos) of one z-address into a few notes of that same address, which makes spending them later faster and cheaper, keeps the wallet smaller and shortens witness rebuilds and rescans. It never moves funds between addresses. Both zsweep and consolidation are **off by default** in dragonxd, for CLI nodes and for GUI wallets that run an embedded dragonxd alike (the ObsidianDragon GUI does its own, separate auto-consolidation through `z_mergetoaddress`). Zsweep is when you sweep numerous zutxos into one z-address that you configure. This z-address can be local to that system or it can be configured to sweep to a remote wallet on a different system with the zsweepexternal=1 option, which is explained below in the Zsweep section. @@ -32,7 +32,7 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. | Zsweep Option Name| Details of what it does | |-------------------|-------------------------| | zsweepexternal=1 | Will enable the option to zsweep to an "external" z-address which exists in a wallet on a different system. | - | zsweepinterval=5 | By default zsweep runs every 5 blocks, so set and modify this value to change that. | + | zsweepinterval=10 | By default zsweep runs every 10 blocks (values below 5 fall back to 10), so set and modify this value to change that. | | zsweepmaxinputs=8 | By default zsweep makes sure to not reduce the anonset in any tx by having a maximum number of inputs of 8. This should be fine for new wallets, but if you have an existing wallet with many zutxos it can be changed with this option. Keep in mind that large values will make sweeping faster at the expense of reducing the AnonSet. | | zsweepfee=0 | The default zsweep fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for zsweep transactions, set this option. | | zsweepexclude=zs1... | Exclude a certain address from being swept. Can be used multiple times to exclude multiple addressses | @@ -41,7 +41,31 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. ## Consolidation -1. We add the following to our conf file as per the Pre-Step. +Mining with auto-shielding on (the default for wallets created or restored by dragonxd) adds one shielded note to the +wallet per auto-shield round. Over weeks that is thousands of small notes, which slow down sends, balance calls and +witness rebuilds. Consolidation keeps that in check. + +### What a round does + +* An address is consolidated only when it holds **more than** `consolidationthreshold` (default 25) *eligible* + notes: unspent (also not spent by a transaction still in the mempool), not locked by another operation, spendable + by this wallet, and at least 11 confirmations deep. Addresses at or below the threshold are left alone. +* For each such address a round sends up to `consolidationmaxtxs` (default 3) transactions. Each spends up to + `consolidationbatchsize` (default 15) of the address's **smallest** notes and pays their value, minus the fee, back + to **the same address**. The big note an earlier round produced is therefore not merged again every round. +* The number of inputs per transaction is drawn at random between two thirds of the batch size and the batch size + (10 to 15 by default), so rounds don't all look alike. A transaction never takes an address's last remaining note, + so every address keeps at least one spendable note while the round confirms. +* Each transaction has exactly 8 shielded outputs: the real one plus 7 zero-value dummy ("Sietch") outputs to random + addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth + no more than the fee, and expires 15 blocks after it is made. +* Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of + the wallet. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. +* With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks. + +### Turning it on + +1. Add the following to the conf file as per the Pre-Step. ``` consolidation=1 ``` @@ -50,10 +74,34 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. | Consolidation Option Name| Details of what it does | |--------------------------|-------------------------| - | consolidationtxfee=0 | The default consolidation fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for consolidation transactions, set this option. | - | consolidatesaplingaddress=zs1... | Default of consolidation is set to all, but you can set this option if you have one specific z-address (zs1... is a placeholder for this documentation) that you want to only consolidate to. | + | consolidationinterval=25 | Blocks between rounds (default 25, minimum 5; smaller values are raised to 5). | + | consolidationthreshold=25 | Only addresses with more than this many eligible notes are consolidated (default 25, minimum 1). | + | consolidationbatchsize=15 | Most notes one consolidation transaction spends (default 15, clamped to 2..50). | + | consolidationmaxtxs=3 | Most consolidation transactions per address per round (default 3, clamped to 1..100). | + | consolidationtxfee=10000 | Fee in puposhis per consolidation transaction (default 10000 = 0.0001 DRAGONX; allowed range 1000..10000000, anything else falls back to the default). | + | consolidatesaplingaddress=zs1... | Only consolidate this address (may be given several times). The default is every address the wallet can spend. The wallet must hold the address's spending key, or dragonxd refuses to start. | -1. The following DragonX RPC will let you view your consolidation configuration options and run-time stats at the command line: `dragonx-cli z_sweepstatus` +1. `dragonx-cli z_consolidationstatus` shows the settings, whether a round is running, when the next one is due, + cumulative totals (`notes_consolidated`, `amount_consolidated` in puposhis), the last round (`last_round`: height, + time, txids, notes merged, amount merged, notes skipped, error) and, when rounds can't run, why + (`disabled_reason`). `dragonx-cli z_consolidationstatus true` also counts the eligible notes of every address and + lists which are over the threshold (this walks the whole wallet, so it is only done on request). + +### Consolidating on demand + +`dragonx-cli z_consolidate` runs one round now with the current settings, also when `consolidation` is off, so a CLI +miner can clean up whenever it suits them. It takes optional overrides, in order: fee (in DRAGONX), batch size, +maximum transactions per address, and a JSON array of addresses; pass `null` to keep a setting, e.g. +`dragonx-cli z_consolidate null 50 20 '["zs1..."]'`. It returns an operation id; `z_getoperationstatus` / +`z_getoperationresult` give the result. It refuses while the node is syncing, while the wallet is locked, and while a +consolidation, zsweep or auto-shield round is in flight. + +### Off, but suggested + +When consolidation is off and some address has more notes than the threshold, dragonxd logs once after loading the +wallet: `N addresses have more than 25 spendable notes; consider -consolidation=1 or z_consolidate`. +`z_autoshieldstatus` then reports `consolidation_suggested: true`, and `z_consolidationstatus true` reports +`consolidation_suggested` and `consolidation_suggested_count`. ## Zsweep & Consolidation Together @@ -66,6 +114,10 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. 1. Then follow along with the zsweep section above if you want to set specific options for the zsweep behavior. +1. With zsweep on, consolidation only works on the sweep address (a `consolidatesaplingaddress` other than the + sweep address is refused at startup). Sweep and consolidation never run at the same time, and a sweep is not + started when a consolidation round is due within 5 blocks. + ### Copyright The DragonX Developers, jahway603, and The Hush Developers @@ -73,4 +125,3 @@ The DragonX Developers, jahway603, and The Hush Developers ### License GPLv3 - diff --git a/src/init.cpp b/src/init.cpp index 1e80eb76a..60af3bce8 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -490,7 +490,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks")); strUsage += HelpMessageOpt("-zsweepaddress=", _("Specify the shielded address where swept funds will be sent)")); strUsage += HelpMessageOpt("-zsweepfee", strprintf(_("Fee amount in puposhis used send sweep transactions. (default %i)"), DEFAULT_SWEEP_FEE)); - strUsage += HelpMessageOpt("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 5)); + strUsage += HelpMessageOpt("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 10)); strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8)); // By default we only allow sweeping to the current wallet which must have the spending key of the sweep zaddr // This hopefully will make it harder for people to accidentally sweep funds to a wrong zaddr and lose funds From 63e7d6ef2d6550cc512b7c11166fc4ca3550ce6d Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:36:59 -0500 Subject: [PATCH 07/11] wallet: keep a throwing consolidation round's committed txs in its record The op tallied the round in a local and handed it over only through setConsolidationResult, which an exception thrown mid-round skips, so last_round and the cumulative totals lost transactions it had already committed. Tally into the member main() records from instead. Co-Authored-By: Claude Opus 5.5 --- src/wallet/asyncrpcoperation_saplingconsolidation.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 1ef89f9ce..82a81e7f0 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -212,7 +212,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { }; std::vector groups; std::vector txs; - ConsolidationTally tally; + // The member, not a local: if anything below throws, main() still records what was committed. + ConsolidationTally& tally = tally_; { LOCK2(cs_main, pwalletMain->cs_wallet); // We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying @@ -429,7 +430,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { - tally_ = tally; + if (&tally != &tally_) + tally_ = tally; UniValue res(UniValue::VOBJ); res.push_back(Pair("num_tx_created", (int)tally.txids.size())); res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); From 6d7ffeb2b909c32a6e8985d00239991aaff4d5ff Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:48:44 -0500 Subject: [PATCH 08/11] wallet: end a consolidation round early on shutdown or a queued op A stop issued during a consolidation round waited for the whole round to be built and committed: 634 s in review, ~8 min for the default 18 txs on a crowded wallet. StopRPC cancels every queued operation, but AsyncRPCOperation::cancel() is not virtual, so the op's own cancel(), which moves an EXECUTING op to CANCELLED, is never called and its isCancelled() checks between transactions never fire. A GUI that kills dragonxd 20 s into shutdown then kills it mid-round, which costs a chainstate replay and a witness rebuild on the next start. Check ShutdownRequested() next to isCancelled() before building each transaction and before committing it, so a stop waits for one tx at most. Making cancel() virtual would also do it, but would change what the sweep and autoshield schedulers' cancel of their previous op does. dragonxd also has a single async worker, so a z_sendmany made during a round waited for all of it. After each committed tx the round now ends when another operation is queued. Its unspent planned notes are unlocked as before and the next round takes them up. last_round and the op result report it as yielded. Co-Authored-By: Claude Opus 5.5 --- doc/zsweep-consolidation.md | 4 ++ ...asyncrpcoperation_saplingconsolidation.cpp | 45 +++++++++++++++---- .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 3 ++ src/wallet/wallet.h | 1 + 5 files changed, 46 insertions(+), 8 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index b99c9cd47..c93ea7349 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -62,6 +62,10 @@ witness rebuilds. Consolidation keeps that in check. * Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of the wallet. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. * With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks. +* dragonxd runs one async operation at a time. So that a `z_sendmany` (or any other async RPC) made during a round + does not wait for all of it, the round ends after its current transaction when another operation is queued + (`last_round.yielded`); the notes it did not get to are unlocked and taken up by the next round. A node that is + asked to stop also ends the round after the current transaction. ### Turning it on diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 82a81e7f0..148654336 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -8,7 +8,9 @@ #include "asyncrpcoperation_saplingconsolidation.h" #include "init.h" #include "key_io.h" +#include "asyncrpcqueue.h" #include "rpc/protocol.h" +#include "rpc/server.h" #include "random.h" #include "sync.h" #include "tinyformat.h" @@ -31,6 +33,20 @@ static const int MIN_ZOUTS = 7; extern string randomSietchZaddr(); +// Whether another operation waits in the async queue. dragonxd has a single async worker, so an +// operation queued during a round (a z_sendmany, say) runs only once the round is over. +static bool OtherAsyncOperationWaiting(const AsyncRPCOperationId& self) { + std::shared_ptr q = getAsyncRPCQueue(); + for (const AsyncRPCOperationId& id : q->getAllOperationIds()) { + if (id == self) + continue; + std::shared_ptr op = q->getOperationForId(id); + if (op && op->isReady()) + return true; + } + return false; +} + 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. @@ -161,6 +177,7 @@ void AsyncRPCOperation_saplingconsolidation::main() { round.amountConsolidated = tally_.amountConsolidated; round.fees = tally_.fees; round.skippedNotes = tally_.skippedNotes; + round.yielded = tally_.yielded; round.error = tally_.error; if (!success && round.error.empty()) round.error = getErrorMessage(); @@ -323,12 +340,22 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size()); for (const PlannedTx& planned : txs) { - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - tally.error = "cancelled"; + // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is + // not virtual), so look for the shutdown here, or a stop would wait for the whole round. + if (isCancelled() || ShutdownRequested()) { + LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); + tally.error = isCancelled() ? "cancelled" : "shutting down"; status=false; break; } + // Once a tx is made, give the worker to anything queued meanwhile: the notes not spent yet are + // unlocked and the next round takes them up. + if (!tally.txids.empty() && OtherAsyncOperationWaiting(opid)) { + LogPrintf("%s: an async operation is waiting; ending the round after %d transactions\n", + opid, tally.txids.size()); + tally.yielded = true; + break; + } const AddressNotes& group = groups[planned.group]; auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); @@ -401,9 +428,9 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } CTransaction tx = maybe_tx.get(); - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - tally.error = "cancelled"; + if (isCancelled() || ShutdownRequested()) { + LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); + tally.error = isCancelled() ? "cancelled" : "shutting down"; status=false; break; } @@ -423,8 +450,9 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } } - LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, status=%d\n", - opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, (int)status); + LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, yielded=%d, status=%d\n", + opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, + (int)tally.yielded, (int)status); setConsolidationResult(tally); return status; } @@ -444,6 +472,7 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol res.push_back(Pair("amount_merged", FormatMoney(tally.amountMerged))); res.push_back(Pair("fees", FormatMoney(tally.fees))); res.push_back(Pair("skipped_notes", tally.skippedNotes)); + res.push_back(Pair("yielded", tally.yielded)); if (!tally.error.empty()) res.push_back(Pair("error", tally.error)); set_result(res); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 8a5fc72b2..b7555d023 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -70,6 +70,7 @@ struct ConsolidationTally { CAmount amountConsolidated = 0; // value of the notes created (amountMerged minus fees) CAmount fees = 0; int skippedNotes = 0; // left out for a missing or unusable witness + bool yielded = false; // stopped after a tx to let a queued async operation run std::string error; }; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 72a56282e..e9b0b2d22 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3333,6 +3333,8 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"amount_consolidated\" : n, (numeric) value of the notes created, in puposhis\n" " \"fees\" : n, (numeric) in puposhis\n" " \"skipped_notes\" : n, (numeric) notes left out for a missing or unusable witness\n" + " \"yielded\" : true|false, (boolean) it stopped after a transaction to let a queued operation\n" + " (z_sendmany, ...) run; the next round goes on\n" " \"error\" : \"...\" (string) why it stopped early; empty if it did not\n" " },\n" " \"disabled_reason\" : \"...\", (string) why no periodic round can start now; empty if one can\n" @@ -3388,6 +3390,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey last.push_back(Pair("amount_consolidated", (int64_t)r.amountConsolidated)); last.push_back(Pair("fees", (int64_t)r.fees)); last.push_back(Pair("skipped_notes", r.skippedNotes)); + last.push_back(Pair("yielded", r.yielded)); last.push_back(Pair("error", r.error)); ret.push_back(Pair("last_round", last)); } else { diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 64c6d61eb..b83a718cd 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -412,6 +412,7 @@ struct SaplingConsolidationRound CAmount amountConsolidated = 0; //!< value of the notes created CAmount fees = 0; int skippedNotes = 0; //!< left out for a missing or unusable witness + bool yielded = false; //!< stopped early to let a queued async operation run std::string error; //!< why the round stopped early, if it did }; From 27a2f041897f150bf06f930ce51c5dba29d3dd05 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:54:55 -0500 Subject: [PATCH 09/11] 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 --- doc/zsweep-consolidation.md | 9 +- src/gtest/test_wallet_consolidation.cpp | 163 +++++++++++ ...asyncrpcoperation_saplingconsolidation.cpp | 258 ++++++++++++------ .../asyncrpcoperation_saplingconsolidation.h | 33 +++ src/wallet/wallet.cpp | 27 +- src/wallet/wallet.h | 2 + 6 files changed, 403 insertions(+), 89 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index c93ea7349..0efe4dbb2 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -60,7 +60,14 @@ witness rebuilds. Consolidation keeps that in check. addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth no more than the fee, and expires 15 blocks after it is made. * Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of - the wallet. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. + the wallet. +* All spends of one transaction must use one anchor (Sapling tree root). An address's spends use the tip's root, + where the wallet keeps its witnesses, or else the chain anchor most of its planned notes are at. A note without a + witness, or whose witness root the chain never had (a desynced witness), is skipped and the round goes on without + it; so is, until a later round, a note whose witness is at another real anchor. Each round logs how many it + skipped (`last_round.skipped_notes`). +* If one transaction fails to build or is not accepted, the rest of that address's transactions are skipped for + the round, but the other addresses still get theirs; `last_round.error` gives the first failure. * With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks. * dragonxd runs one async operation at a time. So that a `z_sendmany` (or any other async RPC) made during a round does not wait for all of it, the round ends after its current transaction when another operation is queued diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp index fdd8eaa45..d8761f551 100644 --- a/src/gtest/test_wallet_consolidation.cpp +++ b/src/gtest/test_wallet_consolidation.cpp @@ -8,6 +8,7 @@ #include #include +#include "arith_uint256.h" #include "primitives/transaction.h" #include "random.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h" @@ -230,3 +231,165 @@ TEST(SaplingConsolidationStats, RecordAccumulates) { 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>> roots; + std::set chainAnchors; + std::map, int> rootCalls; + std::map anchorCalls; + + SaplingConsolidationSpendPlan Plan(const std::vector>& 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> groups = { Values(60), Values(10), Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + for (const auto& g : groups) + w.roots.push_back(std::vector>(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> 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> groups = { Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + w.roots.assign(1, std::vector>(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> unusable(plan.unusable.begin(), plan.unusable.end()); + EXPECT_EQ(unusable, (std::set>{ {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> groups = { Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7), Root(6) }; + w.roots.assign(1, std::vector>(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> groups = { Values(26) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + w.roots.assign(1, std::vector>(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>(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); +} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 148654336..1f939a824 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -21,6 +21,7 @@ #include #include +#include CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE; bool fConsolidationMapUsed = false; @@ -106,6 +107,113 @@ std::vector PlanSaplingConsolidation( return plan; } +SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng, + const std::function(size_t, size_t)>& rootOf, + const std::function& isChainAnchor, + const uint256& preferredAnchor) +{ + SaplingConsolidationSpendPlan result; + std::map, boost::optional> roots; + std::map chainAnchor; + // A planned note's root if it is a chain anchor, else none. + auto usableRoot = [&](size_t g, size_t i) -> boost::optional { + const std::pair key(g, i); + auto ri = roots.find(key); + if (ri == roots.end()) + ri = roots.insert(std::make_pair(key, rootOf(g, i))).first; + if (!ri->second) + return boost::none; + auto ai = chainAnchor.find(*ri->second); + if (ai == chainAnchor.end()) + ai = chainAnchor.insert(std::make_pair(*ri->second, isChainAnchor(*ri->second))).first; + return ai->second ? ri->second : boost::none; + }; + + // Each pass leaves out at least one more note or is the last, so this ends. + std::vector> excluded(groups.size()); + for (;;) { + std::vector> live(groups.size()); + std::vector> values(groups.size()); + for (size_t g = 0; g < groups.size(); g++) { + for (size_t i = 0; i < groups[g].size(); i++) { + if (excluded[g].count(i)) + continue; + live[g].push_back(i); + values[g].push_back(groups[g][i]); + } + } + std::vector plan = PlanSaplingConsolidation(values, policy, rng); + for (SaplingConsolidationBatch& b : plan) + for (size_t& idx : b.notes) + idx = live[b.group][idx]; + + // An address planned for the first time gets its anchor from its planned notes; it then keeps it. + std::map> votes; + for (const SaplingConsolidationBatch& b : plan) { + if (result.anchors.count(b.group)) + continue; + for (size_t i : b.notes) { + boost::optional root = usableRoot(b.group, i); + if (root) + votes[b.group][*root]++; + } + } + for (const auto& v : votes) { + if (v.second.count(preferredAnchor)) { + result.anchors[v.first] = preferredAnchor; + continue; + } + int best = 0; + for (const auto& rv : v.second) { + if (rv.second > best) { + best = rv.second; + result.anchors[v.first] = rv.first; + } + } + } + + bool dropped = false; + for (const SaplingConsolidationBatch& b : plan) { + auto anchor = result.anchors.find(b.group); + for (size_t i : b.notes) { + boost::optional root = usableRoot(b.group, i); + if (root && anchor != result.anchors.end() && *root == anchor->second) + continue; + if (root) + result.deferred.push_back(std::make_pair(b.group, i)); + else + result.unusable.push_back(std::make_pair(b.group, i)); + excluded[b.group].insert(i); + dropped = true; + } + } + if (!dropped) { + result.batches = std::move(plan); + break; + } + } + + // An address whose notes were all left out ends up without batches; it needs no anchor. + std::set planned; + for (const SaplingConsolidationBatch& b : result.batches) + planned.insert(b.group); + for (auto it = result.anchors.begin(); it != result.anchors.end(); ) { + if (planned.count(it->first)) + ++it; + else + it = result.anchors.erase(it); + } + return result; +} + +CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee) { + // Notes worth no more than the fee go fee-free rather than being burnt into it. + return amount <= fee ? 0 : fee; +} + AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request) : targetHeight_(targetHeight), request_(request) {} @@ -186,10 +294,6 @@ void AsyncRPCOperation_saplingconsolidation::main() { } } -// Notes whose missing or desynced witness has already been logged, so a note that can't be spent is -// reported once rather than every round. Guarded by pwalletMain->cs_wallet. -static std::set setWitnessSkipLogged; - bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; auto opid=getId(); @@ -261,66 +365,57 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { groups[it->second].notes.push_back(entry); } - // Plan the round, then fetch the planned notes' witnesses. A note without a usable witness is - // dropped and the round re-planned without it, so it costs the round nothing but a log line. - // Each pass drops at least one note, so this ends. - std::set excluded; - for (;;) { - std::vector> live(groups.size()); - std::vector> values(groups.size()); - for (size_t g = 0; g < groups.size(); g++) { - for (size_t i = 0; i < groups[g].notes.size(); i++) { - if (excluded.count(groups[g].notes[i].op)) - continue; - live[g].push_back(i); - values[g].push_back(CAmount(groups[g].notes[i].note.value())); - } - } - std::vector plan = PlanSaplingConsolidation( - values, request_.policy, [](uint64_t n) { return GetRand(n); }); + // Plan the round over the notes that can be spent: a planned note whose witness is missing, or whose + // root the chain never had as an anchor (a desynced witness), is left out and the round re-planned + // without it. Checking the root against the chain, not just against the other notes, keeps a tx from + // being proved at an anchor no node accepts when the desynced notes are the majority of a batch. + const uint256 tipRoot = (chainActive.Tip() != NULL) ? chainActive.Tip()->hashFinalSaplingRoot : uint256(); + std::vector> values(groups.size()); + for (size_t g = 0; g < groups.size(); g++) + for (const SaplingNoteEntry& entry : groups[g].notes) + values[g].push_back(CAmount(entry.note.value())); + std::map, SaplingWitness> witnessOf; + SaplingConsolidationSpendPlan spendPlan = PlanSaplingConsolidationSpends( + values, request_.policy, [](uint64_t n) { return GetRand(n); }, + [&](size_t g, size_t i) -> boost::optional { + boost::optional w = pwalletMain->GetSaplingNoteLatestWitness(groups[g].notes[i].op); + if (!w) + return boost::none; + witnessOf.insert(std::make_pair(std::make_pair(g, i), *w)); + return w->root(); + }, + [](const uint256& root) { + SaplingMerkleTree tree; + return pcoinsTip->GetSaplingAnchorAt(root, tree); + }, + tipRoot); - // Witnesses per address: every spend of one address's txs then shares that address's anchor. - std::map> opsOf; - for (const SaplingConsolidationBatch& b : plan) - for (size_t idx : b.notes) - opsOf[b.group].push_back(groups[b.group].notes[live[b.group][idx]].op); - std::map witnessOf; - std::map anchorOf; - bool missing = false; - for (const auto& p : opsOf) { - std::vector> witnesses; - uint256 anchor; - pwalletMain->GetSaplingNoteWitnesses(p.second, witnesses, anchor); - anchorOf[p.first] = anchor; - for (size_t i = 0; i < p.second.size(); i++) { - if (witnesses[i]) { - witnessOf.insert(std::make_pair(p.second[i], witnesses[i].get())); - continue; - } - missing = true; - excluded.insert(p.second[i]); - if (setWitnessSkipLogged.insert(p.second[i]).second) - LogPrintf("%s: skipping note %s:%u, it has no usable witness\n", - opid, p.second[i].hash.ToString(), p.second[i].n); - } + for (const SaplingConsolidationBatch& b : spendPlan.batches) { + PlannedTx tx; + tx.group = b.group; + tx.anchor = spendPlan.anchors.at(b.group); + for (size_t i : b.notes) { + tx.notes.push_back(groups[b.group].notes[i]); + tx.witnesses.push_back(witnessOf.at(std::make_pair(b.group, i))); } - if (missing) - continue; - - for (const SaplingConsolidationBatch& b : plan) { - PlannedTx tx; - tx.group = b.group; - tx.anchor = anchorOf[b.group]; - for (size_t idx : b.notes) { - const SaplingNoteEntry& entry = groups[b.group].notes[live[b.group][idx]]; - tx.notes.push_back(entry); - tx.witnesses.push_back(witnessOf.at(entry.op)); - } - txs.push_back(std::move(tx)); - } - break; + txs.push_back(std::move(tx)); } - tally.skippedNotes = excluded.size(); + + // One line per round, not one per note: a note can be unusable for a while (a witness rebuild in + // progress) and fine later, so the next round reports it again rather than never. + tally.skippedNotes = spendPlan.unusable.size() + spendPlan.deferred.size(); + if (!spendPlan.unusable.empty()) { + std::string some; + for (size_t k = 0; k < spendPlan.unusable.size() && k < 5; k++) { + const SaplingOutPoint& op = groups[spendPlan.unusable[k].first].notes[spendPlan.unusable[k].second].op; + some += strprintf("%s%s:%u", k ? ", " : "", op.hash.ToString(), op.n); + } + LogPrintf("%s: skipping %d notes without a usable witness (none, or not at a chain anchor): %s%s\n", + opid, spendPlan.unusable.size(), some, spendPlan.unusable.size() > 5 ? ", ..." : ""); + } + if (!spendPlan.deferred.empty()) + LogPrintf("%s: deferring %d notes whose witness is at another anchor than the rest of their address\n", + opid, spendPlan.deferred.size()); // Lock just the notes this round spends, before the locks are released for proving, so a send // made meanwhile neither picks them nor goes without the rest of the wallet's notes. @@ -339,6 +434,18 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size()); + // A tx that fails ends its own address's part of the round, not the other addresses'. The round's error + // is the first such failure. + std::set failedGroups; + auto failAddress = [&](size_t g, const std::string& why) { + LogPrintf("%s: %s; skipping the rest of this round for address %s\n", + opid, why, groups[g].addr.GetHash().ToString()); + failedGroups.insert(g); + if (tally.error.empty()) + tally.error = why; + status = false; + }; + for (const PlannedTx& planned : txs) { // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is // not virtual), so look for the shutdown here, or a stop would wait for the whole round. @@ -356,6 +463,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { tally.yielded = true; break; } + if (failedGroups.count(planned.group)) + continue; const AddressNotes& group = groups[planned.group]; auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); @@ -364,8 +473,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { CAmount amountToSend = 0; for (const SaplingNoteEntry& entry : planned.notes) amountToSend += CAmount(entry.note.value()); - // Notes worth no more than the fee go fee-free rather than being burnt into it. - CAmount thisTxFee = amountToSend <= request_.fee ? 0 : request_.fee; + CAmount thisTxFee = SaplingConsolidationTxFee(amountToSend, request_.fee); CAmount actualAmountToSend = amountToSend - thisTxFee; LogPrintf("%s: %s Beginning to create transaction with %d Sapling inputs, output amount=%s\n", __func__, opid, planned.notes.size(), FormatMoney(actualAmountToSend)); @@ -380,10 +488,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i); } if (!spendsOk) { - LogPrintf("%s: Consolidation inputs do not share one anchor! Stopping.\n", opid); - tally.error = "inputs do not share one anchor"; - status=false; - break; + failAddress(planned.group, "inputs do not share one anchor"); + continue; } LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee); @@ -408,23 +514,20 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { // actually add our sietch zoutput, the new way builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount); } else { - LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust); + LogPrintf("%s: Invalid payment address %s!\n", opid, zdust); zoutsOk = false; break; } } if (!zoutsOk) { - tally.error = "invalid sietch address"; - status = false; - break; + failAddress(planned.group, "invalid sietch address"); + continue; } LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS); auto maybe_tx = builder.Build(); if (!maybe_tx) { - LogPrintf("%s: Failed to build transaction.\n",opid); - tally.error = "failed to build transaction"; - status=false; - break; + failAddress(planned.group, "failed to build transaction"); + continue; } CTransaction tx = maybe_tx.get(); @@ -444,9 +547,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { tally.fees += thisTxFee; } else { LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); - tally.error = "transaction was not accepted (CommitTransaction failed)"; - status = false; - break; + failAddress(planned.group, "transaction was not accepted (CommitTransaction failed)"); + continue; } } diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index b7555d023..e82825fff 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -14,8 +14,12 @@ #include "wallet.h" // for SaplingNoteEntry #include +#include +#include #include +#include + //Default fee used for consolidation transactions, in puposhis static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000; extern CAmount fConsolidationTxFee; @@ -54,6 +58,35 @@ std::vector PlanSaplingConsolidation( const SaplingConsolidationPolicy& policy, const std::function& rng); +// A round planned over the notes it can spend (see PlanSaplingConsolidationSpends). Note indices are the +// caller's: into the address's values as given. +struct SaplingConsolidationSpendPlan { + std::vector batches; + std::map anchors; // per address with batches: the anchor of all its spends + std::vector> unusable; // (address, note): no witness, or one at no chain anchor + std::vector> deferred; // (address, note): witness at another chain anchor +}; + +// Plans a round as PlanSaplingConsolidation does, but only over notes that can be spent together. rootOf(g, i) +// is the root of note i of address g's witness (none: there is none), isChainAnchor(root) whether the chain +// holds that root as a Sapling anchor, which is what consensus checks a spend's anchor against. An address's +// spends all use one anchor: preferredAnchor (the tip's root, where the wallet keeps its witnesses) when one +// of its planned notes is there, else the chain anchor most of them share. A planned note whose witness is +// missing or at no chain anchor is left out as unusable; one at another chain anchor is deferred to a later +// round. The round is then planned again without them, until no planned note is left out. Planned notes on a +// root the chain never had therefore can't outvote the address's good ones, however many they are. rootOf is +// called at most once per note and isChainAnchor at most once per root. +SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng, + const std::function(size_t, size_t)>& rootOf, + const std::function& isChainAnchor, + const uint256& preferredAnchor); + +// The fee of a consolidation tx spending amount: the fee, or none when the notes are worth no more than it. +CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee); + // What a consolidation operation is asked to do, fixed when it is enqueued. struct SaplingConsolidationRequest { bool manual = false; // z_consolidate rather than the -consolidation scheduler diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index d13fe8492..c737a584c 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2402,6 +2402,20 @@ bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const return false; } +boost::optional CWallet::GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const +{ + LOCK(cs_wallet); + // find(), not operator[]: a lookup must not default-construct mapWallet / mapSaplingNoteData entries. + auto wi = mapWallet.find(note.hash); + if (wi == mapWallet.end()) + return boost::none; + const mapSaplingNoteData_t& noteData = wi->second.mapSaplingNoteData; + auto ni = noteData.find(note); + if (ni == noteData.end() || ni->second.witnesses.empty()) + return boost::none; + return ni->second.witnesses.front(); +} + void CWallet::GetSaplingNoteWitnesses(std::vector notes, std::vector>& witnesses, uint256 &final_anchor) @@ -2416,16 +2430,9 @@ void CWallet::GetSaplingNoteWitnesses(std::vector notes, std::vector> cand(notes.size()); std::map rootVotes; for (size_t i = 0; i < notes.size(); i++) { - const SaplingOutPoint& note = notes[i]; - auto wi = mapWallet.find(note.hash); - if (wi == mapWallet.end()) - continue; - const mapSaplingNoteData_t& noteData = wi->second.mapSaplingNoteData; - auto ni = noteData.find(note); - if (ni == noteData.end() || ni->second.witnesses.empty()) - continue; - cand[i] = ni->second.witnesses.front(); - rootVotes[cand[i]->root()]++; + cand[i] = GetSaplingNoteLatestWitness(notes[i]); + if (cand[i]) + rootVotes[cand[i]->root()]++; } // Choose the anchor that the most witnesses agree on (robust even when the FIRST note is the diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index b83a718cd..0eb3d5b19 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1360,6 +1360,8 @@ public: std::vector notes, std::vector>& witnesses, uint256 &final_anchor); + //! The note's newest cached witness, whatever its root; none if the wallet has none for it. + boost::optional GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const; isminetype IsMine(const CTxIn& txin) const; CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const; From 25c79b7512d328f27182a91808e56fe3daf2305b Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:57:58 -0500 Subject: [PATCH 10/11] wallet: keep consolidation to the sweep address, warn on bad config off With -zsweep=1 and -consolidation=0, z_consolidate consolidated every address: the sweep-address substitution sat under fSaplingConsolidationEnabled, and an explicit address list skipped the sweep-address rule. Sweep and consolidation then fight over the same notes and pay fees for nothing. Apply the rule whatever -consolidation is, and have z_consolidate refuse any address but the sweep address while zsweep is on. The branch also started checking -consolidatesaplingaddress with -consolidation=0, so an old config with a stale, watch-only or mistyped address, which used to be ignored, stopped startup. Keep the InitError with -consolidation=1; with it off, warn and drop the address (with zsweep on, use the sweep address instead). Co-Authored-By: Claude Opus 5.5 --- doc/zsweep-consolidation.md | 9 +++--- src/init.cpp | 55 +++++++++++++++++++++---------------- src/wallet/rpcwallet.cpp | 6 +++- 3 files changed, 42 insertions(+), 28 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index 0efe4dbb2..caf5bc70c 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -90,7 +90,7 @@ witness rebuilds. Consolidation keeps that in check. | consolidationbatchsize=15 | Most notes one consolidation transaction spends (default 15, clamped to 2..50). | | consolidationmaxtxs=3 | Most consolidation transactions per address per round (default 3, clamped to 1..100). | | consolidationtxfee=10000 | Fee in puposhis per consolidation transaction (default 10000 = 0.0001 DRAGONX; allowed range 1000..10000000, anything else falls back to the default). | - | consolidatesaplingaddress=zs1... | Only consolidate this address (may be given several times). The default is every address the wallet can spend. The wallet must hold the address's spending key, or dragonxd refuses to start. | + | consolidatesaplingaddress=zs1... | Only consolidate this address (may be given several times). The default is every address the wallet can spend. With `consolidation=1` the wallet must hold the address's spending key, or dragonxd refuses to start; with it off, such an address is ignored with a warning (and `z_consolidate` works on all addresses unless given its own). | 1. `dragonx-cli z_consolidationstatus` shows the settings, whether a round is running, when the next one is due, cumulative totals (`notes_consolidated`, `amount_consolidated` in puposhis), the last round (`last_round`: height, @@ -125,9 +125,10 @@ wallet: `N addresses have more than 25 spendable notes; consider -consolidation= 1. Then follow along with the zsweep section above if you want to set specific options for the zsweep behavior. -1. With zsweep on, consolidation only works on the sweep address (a `consolidatesaplingaddress` other than the - sweep address is refused at startup). Sweep and consolidation never run at the same time, and a sweep is not - started when a consolidation round is due within 5 blocks. +1. With zsweep on, consolidation only works on the sweep address: a `consolidatesaplingaddress` other than the + sweep address is refused at startup (with `consolidation=0` it is replaced by the sweep address, with a warning), + and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and a + sweep is not started when a consolidation round is due within 5 blocks. ### Copyright diff --git a/src/init.cpp b/src/init.cpp index 60af3bce8..69a683dfa 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2520,46 +2520,55 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pwalletMain->sweepExcludeAddresses.push_back( vSweepExclude[i] ); } - if (pwalletMain->fSaplingConsolidationEnabled) { - //Validate 1 Consolidation address only that matches the sweep address - vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - if (vaddresses.size() == 0) { - fConsolidateSweepAddress = true; - mapMultiArgs["-consolidatesaplingaddress"] = vSweep; - } else { - pwalletMain->consolidationAddress = vaddresses[0]; - for (int i = 0; i < vaddresses.size(); i++) { - if (vSweep[0] != vaddresses[i]) { - return InitError("Consolidation can only be used on the sweep address when sweep is enabled."); - } - } - } + // With sweep on, consolidation works on the sweep address only, also for z_consolidate with + // -consolidation off: the two would otherwise fight over the same notes and pay fees for nothing. + vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; + bool fOtherAddress = false; + for (size_t i = 0; i < vaddresses.size(); i++) + fOtherAddress |= vSweep[0] != vaddresses[i]; + if (fOtherAddress) { + if (pwalletMain->fSaplingConsolidationEnabled) + return InitError("Consolidation can only be used on the sweep address when sweep is enabled."); + InitWarning(_("-consolidatesaplingaddress is not the sweep address; with -zsweep, consolidation only works on the sweep address")); + } + if (vaddresses.empty() || fOtherAddress) { + fConsolidateSweepAddress = true; + vaddresses = vSweep; } } // The addresses consolidation works on: -consolidatesaplingaddress, or with -zsweep the sweep address. // A user-given address must be one this wallet can spend, else every round would silently skip it. + // With -consolidation off, where older versions ignored the option, a bad one is only warned about + // and dropped; z_consolidate then works on all addresses unless given its own. { const vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - fConsolidationMapUsed = !vaddresses.empty(); pwalletMain->consolidationAddresses.clear(); + pwalletMain->consolidationAddress.clear(); for (size_t i = 0; i < vaddresses.size(); i++) { LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); + std::string strProblem; auto zAddress = DecodePaymentAddress(vaddresses[i]); if (!IsValidPaymentAddress(zAddress) || boost::get(&zAddress) == nullptr) { - return InitError("Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address"); + strProblem = "Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address"; + } else if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) { + if (!fConsolidateSweepAddress) + strProblem = strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i]); + else + LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__); } - if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) { - if (!fConsolidateSweepAddress) { - return InitError(strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i])); - } - LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__); + if (!strProblem.empty()) { + if (pwalletMain->fSaplingConsolidationEnabled) + return InitError(strProblem); + InitWarning(strProblem + "; ignoring it while -consolidation is off"); + continue; } pwalletMain->consolidationAddresses.push_back(boost::get(zAddress)); + if (pwalletMain->consolidationAddress.empty()) + pwalletMain->consolidationAddress = vaddresses[i]; } - if (!vaddresses.empty()) - pwalletMain->consolidationAddress = vaddresses[0]; + fConsolidationMapUsed = !pwalletMain->consolidationAddresses.empty(); } // Sweep and consolidation pick notes with GetFilteredNotes at minDepth > 1. Older versions diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e9b0b2d22..fc419b4d7 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3444,7 +3444,8 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) + strprintf("%d to %d", MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE) + "\n" "3. maxtxs (numeric, optional, default=-consolidationmaxtxs) most transactions per address, " + strprintf("1 to %d", MAX_CONSOLIDATION_MAXTXS) + "\n" - "4. addresses (array, optional, default=-consolidatesaplingaddress or all) Sapling addresses to consolidate\n" + "4. addresses (array, optional, default=-consolidatesaplingaddress or all) Sapling addresses to consolidate;\n" + " with -zsweep on, only the sweep address (also the default then)\n" "\nResult:\n" "\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\n" "\nExamples:\n" @@ -3501,6 +3502,9 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address, must be a Sapling z-address: " + str); if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zaddr)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Wallet does not hold the spending key of " + str); + // As at startup: with zsweep on, consolidating any other address only feeds the next sweep. + if (pwalletMain->fSweepEnabled && str != pwalletMain->sweepAddress) + throw JSONRPCError(RPC_INVALID_PARAMETER, "With -zsweep on, only the sweep address can be consolidated: " + str); request.addresses.push_back(boost::get(zaddr)); } } From 5d5b47d05a670fedc0c62b0a7a663bc7e1c28470 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:59:46 -0500 Subject: [PATCH 11/11] wallet/rpc: z_consolidate is not safe-mode; say which units it uses z_consolidate creates and broadcasts transactions, so like z_sendmany and z_shieldcoinbase it must not run in safe mode. Its fee argument is in DRGX, like z_sendmany's, while -consolidationtxfee and every amount in z_consolidationstatus are in puposhis; the help and the doc now say so. Co-Authored-By: Claude Opus 5.5 --- doc/zsweep-consolidation.md | 3 ++- src/wallet/rpcwallet.cpp | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index caf5bc70c..c809989c2 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -103,7 +103,8 @@ witness rebuilds. Consolidation keeps that in check. `dragonx-cli z_consolidate` runs one round now with the current settings, also when `consolidation` is off, so a CLI miner can clean up whenever it suits them. It takes optional overrides, in order: fee (in DRAGONX), batch size, maximum transactions per address, and a JSON array of addresses; pass `null` to keep a setting, e.g. -`dragonx-cli z_consolidate null 50 20 '["zs1..."]'`. It returns an operation id; `z_getoperationstatus` / +`dragonx-cli z_consolidate null 50 20 '["zs1..."]'`. Its fee is in DRAGONX like `z_sendmany`'s, while `consolidationtxfee` and the amounts in +`z_consolidationstatus` are in puposhis. It returns an operation id; `z_getoperationstatus` / `z_getoperationresult` give the result. It refuses while the node is syncing, while the wallet is locked, and while a consolidation, zsweep or auto-shield round is in flight. diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index fc419b4d7..5b0457870 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3448,6 +3448,8 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) " with -zsweep on, only the sweep address (also the default then)\n" "\nResult:\n" "\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\n" + "The fee here is in " + CURRENCY_UNIT + ", like z_sendmany's; -consolidationtxfee and the amounts in\n" + "z_consolidationstatus are in puposhis (1 " + CURRENCY_UNIT + " = 100000000).\n" "\nExamples:\n" + HelpExampleCli("z_consolidate", "") + HelpExampleCli("z_consolidate", "null 50 20 '[\"zs1...\"]'") @@ -6698,7 +6700,7 @@ static const CRPCCommand commands[] = { "wallet", "z_sweepstatus", &z_sweepstatus, true }, { "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true }, { "wallet", "z_consolidationstatus", &z_consolidationstatus, true }, - { "wallet", "z_consolidate", &z_consolidate, true }, + { "wallet", "z_consolidate", &z_consolidate, false }, { "wallet", "z_sendmany", &z_sendmany, false }, { "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false }, { "wallet", "z_getoperationstatus", &z_getoperationstatus, true },