From a800a266e595463b6c411f35e1f31b4564c1c62f Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:37:33 -0500 Subject: [PATCH] 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 = "";