From b61611d5c2cc9246fe082cacb4889f297c6b9863 Mon Sep 17 00:00:00 2001 From: DanS Date: Fri, 20 Nov 2026 15:49:38 -0600 Subject: [PATCH] wallet: one unspendable note no longer stops the whole zsweep round The sweep took the first maxInputs notes of an address and asked GetSaplingNoteWitnesses for their witnesses. If one had none -- a missing witness, or a desynced one that does not match the anchor the others agree on -- it logged "Missing Witnesses! Stopping.", built anyway with that note's value still counted, failed the build, and broke out of the address loop. The round failed, every address after that one went unswept, and the same thing happened again every interval. And because that anchor is a majority vote, a desynced group that outnumbers the good notes at an address (as one did on a real wallet) makes the "agreed" root one the chain never had. SelectSweepableNotes now picks each transaction's notes. It copies each note's latest cached witness under cs_wallet (GetSaplingNoteLatestWitness, which does no hashing), computes each root once with no lock held, groups the notes by root, and takes the largest group whose root is an anchor the chainstate knows -- the same lookup consensus applies to shielded spends. It reads the notes in windows of 2 * maxInputs and stops as soon as a known group can fill the transaction, so a healthy address costs about what the old first-maxInputs selection did (a Merkle root is ~1-2 ms, and an earlier all-notes pass held cs_main for ~30 s on a 13k-note wallet), while a run of bad notes at the front cannot hide good ones behind it. Notes left out are logged once per address with a count and the first outpoint, and looked at again next round. In the round itself: - an address with no spendable notes is skipped rather than failing the round; - a failed build moves on to the next address (nothing was recorded); a failed commit still stops the round, because CommitTransaction has already written the tx to the wallet; - a round counts as incomplete only once it has committed something, so an address whose notes are all unspendable no longer has the scheduler re-dispatch on every block -- it is retried an interval later. New gtest SweepNoteSelection, 9 cases, including a desynced majority, a desynced run ahead of good notes, a lone good note behind five desynced groups, two real anchors, and a healthy address being read one window at a time. Accepting every root as an anchor fails 4 of them, and reading every note fails the window test (200 notes took 244 ms against one window's worth). End to end on regtest, with gdb making the wallet's first witness lookup find nothing: the other 4 notes at that address and every other address were swept in the same round, the round succeeded, the next round swept the skipped note, and the wallet drained fully, with no per-note desync lines in the log. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/Makefile.gtest.include | 1 + src/gtest/test_sweep_note_selection.cpp | 158 +++++++++++++++++++++ src/wallet/asyncrpcoperation_sweep.cpp | 179 ++++++++++++++++-------- src/wallet/asyncrpcoperation_sweep.h | 34 +++++ 4 files changed, 311 insertions(+), 61 deletions(-) create mode 100644 src/gtest/test_sweep_note_selection.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index 7fb806c61..b3e356ace 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -16,6 +16,7 @@ hush_gtest_SOURCES = \ gtest/test_hdtransparent.cpp \ gtest/test_mnemonic_compat.cpp \ gtest/test_stratum_jobid.cpp \ + gtest/test_sweep_note_selection.cpp \ gtest/test_wallet_notedata.cpp \ gtest/test_net_closesocket.cpp \ gtest/test_fd_defense.cpp \ diff --git a/src/gtest/test_sweep_note_selection.cpp b/src/gtest/test_sweep_note_selection.cpp new file mode 100644 index 000000000..7886b4dc7 --- /dev/null +++ b/src/gtest/test_sweep_note_selection.cpp @@ -0,0 +1,158 @@ +// Copyright (c) 2016-2024 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 + +#include + +#include "primitives/transaction.h" +#include "uint256.h" +#include "wallet/asyncrpcoperation_sweep.h" +#include "zcash/IncrementalMerkleTree.hpp" + +namespace { + +// A witness in a one-leaf tree: each leaf gives a different root(). +SaplingWitness WitnessAt(const std::string& leaf) +{ + SaplingMerkleTree tree; + tree.append(uint256S(leaf)); + return tree.witness(); +} + +const SaplingWitness GOOD = WitnessAt("0a"); // at an anchor the chain knows +const SaplingWitness OTHER = WitnessAt("0c"); // at another known anchor +SaplingWitness Bad(int i) { return WitnessAt("b0" + std::to_string(i)); } // desynced: roots the chain never had + +SaplingOutPoint Op(int i) { return SaplingOutPoint(uint256S("f0"), i); } + +// Stands in for the wallet: each note's latest cached witness (none = no witness) and the chainstate's +// anchors. Counts how many notes the selection asked about. +struct FakeWallet { + std::map> latest; + std::set knownAnchors{GOOD.root(), OTHER.root()}; + int calls = 0; + size_t asked = 0; + + SweepNoteSelection Select(size_t n, size_t maxInputs) + { + std::vector ops; + for (size_t i = 0; i < n; i++) + ops.push_back(Op(i)); + return SelectSweepableNotes(ops, maxInputs, + [this](const std::vector& o) { + calls++; + asked += o.size(); + std::vector> out; + for (const SaplingOutPoint& op : o) + out.push_back(latest[op]); + return out; + }, + [this](const uint256& root) { return knownAnchors.count(root) > 0; }); + } +}; + +std::vector V(std::initializer_list l) { return std::vector(l); } +std::vector Range(size_t from, size_t to) { std::vector v; for (size_t i = from; i < to; i++) v.push_back(i); return v; } + +} + +TEST(SweepNoteSelection, TakesAtMostMaxInputsAndDoesNotSkipTheRest) { + FakeWallet w; + for (int i = 0; i < 7; i++) w.latest[Op(i)] = GOOD; + SweepNoteSelection sel = w.Select(7, 5); + EXPECT_EQ(Range(0, 5), sel.chosen); + EXPECT_EQ(5u, sel.witnesses.size()); + EXPECT_EQ(GOOD.root(), sel.anchor); + EXPECT_TRUE(sel.skipped.empty()) << "notes past the cap are left for the next round, not skipped"; +} + +// A healthy address costs about what the old first-maxInputs selection did: one window of 2*maxInputs. +TEST(SweepNoteSelection, AHealthyAddressReadsOneWindow) { + FakeWallet w; + for (int i = 0; i < 200; i++) w.latest[Op(i)] = GOOD; + SweepNoteSelection sel = w.Select(200, 5); + EXPECT_EQ(Range(0, 5), sel.chosen); + EXPECT_EQ(1, w.calls); + EXPECT_EQ(10u, w.asked); + EXPECT_TRUE(sel.skipped.empty()); +} + +TEST(SweepNoteSelection, SkipsNotesWithoutAWitness) { + FakeWallet w; + for (int i = 0; i < 5; i++) w.latest[Op(i)] = GOOD; + w.latest[Op(0)] = boost::none; + w.latest[Op(2)] = boost::none; + SweepNoteSelection sel = w.Select(5, 5); + EXPECT_EQ(V({1, 3, 4}), sel.chosen); + EXPECT_EQ(V({0, 2}), sel.skipped); +} + +// The case seen on a real wallet: desynced notes outnumber the good ones at their address. +TEST(SweepNoteSelection, PassesOverADesyncedMajority) { + FakeWallet w; + for (int i = 0; i < 3; i++) w.latest[Op(i)] = Bad(0); + for (int i = 3; i < 5; i++) w.latest[Op(i)] = GOOD; + SweepNoteSelection sel = w.Select(5, 5); + EXPECT_EQ(V({3, 4}), sel.chosen); + EXPECT_EQ(GOOD.root(), sel.anchor); + EXPECT_EQ(V({0, 1, 2}), sel.skipped); +} + +// A run of bad notes at the front must not hide good notes behind it. +TEST(SweepNoteSelection, ADesyncedRunAtTheFrontDoesNotHideTheRest) { + FakeWallet w; + for (int i = 0; i < 12; i++) w.latest[Op(i)] = Bad(0); + for (int i = 12; i < 14; i++) w.latest[Op(i)] = GOOD; + SweepNoteSelection sel = w.Select(14, 5); + EXPECT_EQ(V({12, 13}), sel.chosen); + EXPECT_EQ(Range(0, 12), sel.skipped); +} + +// However the desynced notes split, a good group is found: no limit on the number of bad roots. +TEST(SweepNoteSelection, ALoneGoodNoteBehindManyDesyncedGroups) { + FakeWallet w; + for (int g = 0; g < 5; g++) + for (int j = 0; j < 2; j++) + w.latest[Op(g * 2 + j)] = Bad(g); + w.latest[Op(10)] = GOOD; + SweepNoteSelection sel = w.Select(11, 5); + EXPECT_EQ(V({10}), sel.chosen); + EXPECT_EQ(Range(0, 10), sel.skipped); +} + +TEST(SweepNoteSelection, NothingWhenNoWitnessIsAtAKnownAnchor) { + FakeWallet w; + for (int i = 0; i < 4; i++) w.latest[Op(i)] = Bad(i % 2); + w.latest[Op(4)] = boost::none; + SweepNoteSelection sel = w.Select(5, 5); + EXPECT_TRUE(sel.chosen.empty()); + EXPECT_TRUE(sel.witnesses.empty()); + EXPECT_EQ(Range(0, 5), sel.skipped); +} + +// Two real anchors: one transaction can only use one, so the larger group is spent and the other waits +// for a later round. +TEST(SweepNoteSelection, OneAnchorPerTransaction) { + FakeWallet w; + for (int i = 0; i < 3; i++) w.latest[Op(i)] = GOOD; + for (int i = 3; i < 5; i++) w.latest[Op(i)] = OTHER; + SweepNoteSelection sel = w.Select(5, 5); + EXPECT_EQ(V({0, 1, 2}), sel.chosen); + EXPECT_EQ(GOOD.root(), sel.anchor); + EXPECT_EQ(V({3, 4}), sel.skipped); +} + +TEST(SweepNoteSelection, NoCandidates) { + FakeWallet w; + SweepNoteSelection sel = w.Select(0, 5); + EXPECT_TRUE(sel.chosen.empty()); + EXPECT_TRUE(sel.skipped.empty()); + EXPECT_EQ(0, w.calls); +} diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index fb4f9142a..12b9ddde5 100644 --- a/src/wallet/asyncrpcoperation_sweep.cpp +++ b/src/wallet/asyncrpcoperation_sweep.cpp @@ -15,6 +15,9 @@ #include "utilmoneystr.h" #include "wallet.h" +#include +#include + extern string randomSietchZaddr(); CAmount fSweepTxFee = DEFAULT_SWEEP_FEE; @@ -105,6 +108,73 @@ bool IsExcludedAddress(libzcash::SaplingPaymentAddress zaddr) { return false; } +SweepNoteSelection SelectSweepableNotes( + const std::vector& candidates, size_t maxInputs, + const std::function>(const std::vector&)>& getLatestWitnesses, + const std::function& isKnownAnchor) +{ + struct Group { + std::vector notes; + std::vector witnesses; + }; + std::map groups; // by witness root + std::map knownAnchor; // isKnownAnchor, asked once per root + const uint256* best = nullptr; + size_t bestSize = 0; + size_t examined = 0; + const size_t window = std::max(2 * maxInputs, 1); + + while (examined < candidates.size()) { + const size_t end = std::min(candidates.size(), examined + window); + std::vector ops(candidates.begin() + examined, candidates.begin() + end); + std::vector> latest = getLatestWitnesses(ops); + for (size_t k = 0; k < ops.size() && k < latest.size(); k++) { + if (!latest[k]) + continue; + Group& group = groups[latest[k]->root()]; + group.notes.push_back(examined + k); + group.witnesses.push_back(*latest[k]); + } + examined = end; + + // The largest group at a known anchor (ties: the lowest root, by map order). + best = nullptr; + bestSize = 0; + for (const auto& entry : groups) { + if (entry.second.notes.size() <= bestSize) + continue; + auto known = knownAnchor.find(entry.first); + if (known == knownAnchor.end()) + known = knownAnchor.emplace(entry.first, isKnownAnchor(entry.first)).first; + if (known->second) { + best = &entry.first; + bestSize = entry.second.notes.size(); + } + } + if (bestSize >= maxInputs) + break; + } + + SweepNoteSelection sel; + std::vector inBest(candidates.size(), false); + if (best != nullptr) { + const Group& group = groups[*best]; + sel.anchor = *best; + for (size_t i = 0; i < group.notes.size(); i++) { + inBest[group.notes[i]] = true; + if (sel.chosen.size() < maxInputs) { + sel.chosen.push_back(group.notes[i]); + sel.witnesses.push_back(group.witnesses[i]); + } + } + } + // Notes past the last window read were not looked at this round; they are not skipped. + for (size_t i = 0; i < examined; i++) + if (!inBest[i]) + sel.skipped.push_back(i); + return sel; +} + bool AsyncRPCOperation_sweep::main_impl() { bool status=true; auto opid=getId(); @@ -212,46 +282,49 @@ bool AsyncRPCOperation_sweep::main_impl() { // -zsweepmaxinputs, parsed and range-checked once at startup. const size_t maxInputs = pwalletMain->sweepMaxInputs; - //Count Notes availiable for this address - int targetCount = 0; - int noteCount = 0; + // Every note of this address the wallet can spend. + std::vector candidates; for (const SaplingNoteEntry& saplingEntry : saplingEntries) { - - libzcash::SaplingIncomingViewingKey ivk; - pwalletMain->GetSaplingIncomingViewingKey(boost::get(saplingEntry.address), ivk); - - if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) { - noteCount++; - } - } - - //Don't sweep if under the threshold - if (noteCount <= targetCount){ - continue; - } - - //if we make it here then we need to sweep and the routine is considered incomplete - sweepComplete = false; - - for (const SaplingNoteEntry& saplingEntry : saplingEntries) { - libzcash::SaplingIncomingViewingKey ivk; pwalletMain->GetSaplingIncomingViewingKey(boost::get(saplingEntry.address), ivk); - - //Select Notes from that same address we will be sending to. - if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) { - amountToSend += CAmount(saplingEntry.note.value()); - fromNotes.push_back(saplingEntry); - } - - if (fromNotes.size() >= maxInputs) - break; - + if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) + candidates.push_back(saplingEntry); } + if (candidates.empty()) + continue; - int minQuantity = 1; - if (fromNotes.size() < minQuantity) - continue; + // Up to maxInputs of them that share a witness anchor the chain knows. Notes without one (a + // missing or desynced witness) are left for a later round instead of failing this address, + // and with it the round and every address after it. + std::vector candidateOps; + for (const SaplingNoteEntry& candidate : candidates) + candidateOps.push_back(candidate.op); + SweepNoteSelection selection = SelectSweepableNotes(candidateOps, maxInputs, + [](const std::vector& ops) { + // Copies only; the roots are computed by the caller with no lock held. + std::vector> latest; + LOCK(pwalletMain->cs_wallet); + for (const SaplingOutPoint& op : ops) + latest.push_back(pwalletMain->GetSaplingNoteLatestWitness(op)); + return latest; + }, + [](const uint256& anchor) { + LOCK(cs_main); + SaplingMerkleTree tree; + return pcoinsTip->GetSaplingAnchorAt(anchor, tree); + }); + if (!selection.skipped.empty()) { + const SaplingOutPoint& first = candidates[selection.skipped.front()].op; + LogPrintf("%s: %u of the %u notes at one address cannot be spent with the others this round " + "(no witness, or one at an unknown or different anchor; first: %s:%u)\n", getId(), + selection.skipped.size(), candidates.size(), first.hash.ToString(), first.n); + } + if (selection.chosen.empty()) + continue; + for (size_t i : selection.chosen) { + fromNotes.push_back(candidates[i]); + amountToSend += CAmount(candidates[i].note.value()); + } CAmount fee = fSweepTxFee; if (amountToSend <= fSweepTxFee) { @@ -276,30 +349,9 @@ bool AsyncRPCOperation_sweep::main_impl() { builder.SetExpiryHeight(buildHeight + AUTO_OP_EXPIRY_DELTA); LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee)); - // 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); - 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", getId()); - break; - } - builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get()); - } + // Add Sapling spends, each with the witness it was selected with + for (size_t i = 0; i < fromNotes.size(); i++) + builder.AddSaplingSpend(extsk.expsk, fromNotes[i].note, selection.anchor, selection.witnesses[i].get()); builder.SetFee(fee); builder.AddSaplingOutput(extsk.expsk.ovk, sweepAddress, amountToSend - fee); @@ -326,9 +378,10 @@ bool AsyncRPCOperation_sweep::main_impl() { auto maybe_tx = builder.Build(); if (!maybe_tx) { - LogPrintf("%s: Failed to build transaction %s.\n",__func__, getId()); + // Nothing was recorded, so the other addresses can still be swept. The round still fails. + LogPrintf("%s: Failed to build transaction %s; trying the remaining addresses\n",__func__, getId()); status=false; - break; + continue; } CTransaction tx = maybe_tx.get(); @@ -339,6 +392,10 @@ bool AsyncRPCOperation_sweep::main_impl() { if (pwalletMain->CommitAutomatedTx(tx)) { LogPrintf("%s: Committed sweep transaction with txid=%s\n", getId(), tx.GetHash().ToString()); + // The address may hold more; the next block's round looks again. An address whose notes + // all lack a usable witness commits nothing, so it no longer has the scheduler re-dispatch + // on every block -- it is retried an interval later. + sweepComplete = false; amountSwept += amountToSend - fee; { LOCK(pwalletMain->cs_wallet); diff --git a/src/wallet/asyncrpcoperation_sweep.h b/src/wallet/asyncrpcoperation_sweep.h index 28f75711b..ebfbc101f 100644 --- a/src/wallet/asyncrpcoperation_sweep.h +++ b/src/wallet/asyncrpcoperation_sweep.h @@ -6,16 +6,50 @@ #include "amount.h" #include "asyncrpcoperation.h" +#include "primitives/transaction.h" +#include "uint256.h" #include "univalue.h" #include "zcash/Address.hpp" +#include "zcash/IncrementalMerkleTree.hpp" #include "zcash/zip32.h" +#include +#include + +#include + //Default fee used for sweep transactions static const CAmount DEFAULT_SWEEP_FEE = 10000; extern CAmount fSweepTxFee; extern bool fSweepMapUsed; extern boost::optional rpcSweepAddress; +// The notes of one address that a sweep transaction spends. +struct SweepNoteSelection { + std::vector chosen; // indexes into the candidates, at most maxInputs + std::vector> witnesses; // one per chosen note + uint256 anchor; // the root all of their witnesses share + std::vector skipped; // candidates looked at but not spendable alongside the + // chosen notes: no witness, or one at an unknown or + // different anchor +}; + +// Pick up to maxInputs of an address's notes that can be spent together: witnessed at one root that +// is an anchor the chain knows. getLatestWitnesses returns a copy of each note's latest cached witness +// (CWallet::GetSaplingNoteLatestWitness, which does no hashing), so each root is computed once, here, +// with no lock held. Notes are grouped by root and the largest group at a known anchor wins: a +// desynced group can outnumber the good notes at an address (it did on a real wallet), and its root is +// one the chain never had. The candidates are read in windows of 2 * maxInputs, stopping as soon as a +// known group can fill a transaction, so a healthy address costs about what the old first-maxInputs +// selection did, while a run of bad notes at the front cannot hide the good ones behind it. Notes left +// out are reported in skipped instead of failing the address -- or, as it used to, the whole round, +// which left every address after it unswept, every interval. Notes at another real anchor are swept +// by a later round, once the larger group is gone. +SweepNoteSelection SelectSweepableNotes( + const std::vector& candidates, size_t maxInputs, + const std::function>(const std::vector&)>& getLatestWitnesses, + const std::function& isKnownAnchor); + class AsyncRPCOperation_sweep : public AsyncRPCOperation { public: