diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index cd868225b..14fbf92b4 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/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index a823539d4..9eb4f7d8a 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -381,3 +381,46 @@ TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) { ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb)); EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again"; } + +// While the startup rescan is running or was cut short, init has not seeded the wallet tip yet, and the +// only stamp that can arrive is FlushStateToDisk's chain tip (its hourly write, or the one in Shutdown). +// Writing that over the scan's own locator would mark the unscanned range as scanned -- after +// -zapwallettxes, its transactions would be gone from the wallet. It must write nothing. +TEST_F(WalletShutdownSave, DoesNotStampTheChainTipOverAnIncompleteStartupRescan) { + CBlockLocator chainTip(std::vector{uint256S("0def")}); + + SaveWallet wallet; + wallet.NoteRescanStarted(0); + { + FakeWalletDB db; + EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "while the scan runs"; + EXPECT_TRUE(db.written.vHave.empty()); + } + wallet.NoteRescanInterrupted(500); + { + FakeWalletDB db; + EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "after the scan was cut short"; + EXPECT_TRUE(db.written.vHave.empty()); + } + + // Once init seeds the wallet tip (at the scan's checkpoint, when it was cut short), that is stamped. + uint256 hash = uint256S("0abc"); + CBlockIndex tip; + tip.phashBlock = &hash; + wallet.SetWalletTip(&tip); + { + FakeWalletDB db; + EXPECT_TRUE(wallet.SetBestChainWith(db, chainTip)); + ASSERT_FALSE(db.written.vHave.empty()); + EXPECT_EQ(hash, db.written.vHave.front()); + } + + // A startup scan that completed leaves nothing to protect: init's own stamp goes through. + SaveWallet completed; + int before = completed.NoteRescanStarted(0); + completed.NoteRescanCompleted(0, before); + FakeWalletDB db; + EXPECT_TRUE(completed.SetBestChainWith(db, chainTip)); + ASSERT_FALSE(db.written.vHave.empty()); + EXPECT_EQ(uint256S("0def"), db.written.vHave.front()); +} diff --git a/src/init.cpp b/src/init.cpp index 1c571bef9..0da56523a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -656,7 +656,7 @@ std::string HelpMessage(HelpMessageMode mode) 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)"), 10)); - strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8)); + strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction, %i to %i (default %i)"), MIN_SWEEP_MAX_INPUTS, MAX_SWEEP_MAX_INPUTS, DEFAULT_SWEEP_MAX_INPUTS)); // 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 strUsage += HelpMessageOpt("-zsweepexternal", _("Enable sweeping to an external wallet (default false)")); @@ -1306,6 +1306,44 @@ static void AdjustCoinCacheForMemoryPressure() nCoinCacheUsage = (size_t)(newTargetMB << 20); } +#ifdef ENABLE_WALLET +// Where a forced wallet rescan (-rescan, -zapwallettxes, a witness-cache reset) starts: genesis, or +// -rescanheight capped at the tip. +static CBlockIndex* ForcedRescanStart() +{ + int rescanHeight = GetArg("-rescanheight", 0); + if (rescanHeight > 0) + return rescanHeight > chainActive.Tip()->GetHeight() ? chainActive.Tip() : chainActive[rescanHeight]; + return chainActive.Genesis(); +} + +// A forced rescan starts below the locator on disk, which ScanForWalletTransactions only ever moves +// forward. Left there, a scan cut short -- a shutdown, abortrescan, or a kill -- would leave it at the +// old tip, and the next normal start would skip everything the scan had not reached. After +// -zapwallettxes that range's transactions are simply gone from the wallet until someone rescans +// again. So move the locator back to where the scan starts: an interrupted scan then checkpoints +// forward from there, and a killed one restarts from there. Never moves the locator forward. +static void RewindWalletLocatorForRescan(const std::string& strWalletFile, const CBlockIndex* pindexRescan) +{ + if (pindexRescan == NULL) + return; + CWalletDB walletdb(strWalletFile); + CBlockLocator locPersisted; + if (!walletdb.ReadBestBlock(locPersisted)) + return; + CBlockIndex* pindexPersisted = FindForkInGlobalIndex(chainActive, locPersisted); + if (pindexPersisted == NULL || pindexPersisted->GetHeight() <= pindexRescan->GetHeight()) + return; + if (walletdb.WriteBestBlock(chainActive.GetLocator(pindexRescan))) + LogPrintf("%s: moved the wallet's best-block locator back from height %d to %d, where the rescan " + "starts, so an interrupted rescan resumes instead of skipping the rest\n", + __func__, pindexPersisted->GetHeight(), pindexRescan->GetHeight()); + else + LogPrintf("%s: WARNING: could not move the wallet's best-block locator back to height %d; " + "if the rescan is interrupted, restart with -rescan\n", __func__, pindexRescan->GetHeight()); +} +#endif + bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) { // ********************************************************* Step 1: setup @@ -2411,6 +2449,12 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) delete pwalletMain; pwalletMain = NULL; + + // The zap is on disk now. Rewind the locator straight away rather than at the rescan below: + // if startup fails in between (a config error, say), the next start must still rescan the + // erased range rather than trust the old tip. + if (chainActive.Tip() != NULL) + RewindWalletLocatorForRescan(strWalletFile, ForcedRescanStart()); } uiInterface.InitMessage(_("Loading wallet...")); @@ -2630,6 +2674,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) LogPrintf("%s: set nextSweep=%d with sweepInterval=%d\n", __func__, pwalletMain->nextSweep, pwalletMain->sweepInterval ); fSweepTxFee = GetArg("-zsweepfee", DEFAULT_SWEEP_FEE); fSweepMapUsed = !mapMultiArgs["-zsweepaddress"].empty(); + int sweepMaxInputs = GetArg("-zsweepmaxinputs", DEFAULT_SWEEP_MAX_INPUTS); + if (sweepMaxInputs < MIN_SWEEP_MAX_INPUTS || sweepMaxInputs > MAX_SWEEP_MAX_INPUTS) { + LogPrintf("%s: Invalid -zsweepmaxinputs=%d (must be %d to %d), using the default of %d\n", __func__, + sweepMaxInputs, MIN_SWEEP_MAX_INPUTS, MAX_SWEEP_MAX_INPUTS, DEFAULT_SWEEP_MAX_INPUTS); + sweepMaxInputs = DEFAULT_SWEEP_MAX_INPUTS; + } + pwalletMain->sweepMaxInputs = sweepMaxInputs; //Validate Sapling Addresses vector& vSweep = mapMultiArgs["-zsweepaddress"]; @@ -2869,6 +2920,10 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pindexRescan = chainActive[rescanHeight]; } } + + // See RewindWalletLocatorForRescan. (After -zapwallettxes this already happened, right after + // the zap; doing it again is a no-op.) + RewindWalletLocatorForRescan(strWalletFile, pindexRescan); } else { CWalletDB walletdb(strWalletFile); CBlockLocator locator; diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index 75a5b20c2..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(); @@ -128,6 +198,15 @@ bool AsyncRPCOperation_sweep::main_impl() { return true; } + // A locked wallet yields no spending keys, so every address below would be skipped and the round + // would report success having swept nothing. RunSaplingSweep already declines to enqueue while + // locked; this catches a wallet locked between enqueue and execution, and makes the reason + // visible in z_getoperationstatus. + if (pwalletMain->IsLocked()) { + LogPrintf("%s: wallet is locked; nothing can be swept. Unlock it with walletpassphrase\n", getId()); + throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is locked; unlock it with walletpassphrase for zsweep to sign"); + } + std::vector saplingEntries; libzcash::SaplingPaymentAddress sweepAddress; std::map> mapAddresses; @@ -200,52 +279,52 @@ bool AsyncRPCOperation_sweep::main_impl() { std::vector fromNotes; CAmount amountToSend = 0; - int maxInputs = GetArg("-zsweepmaxinputs", 8); - if( maxInputs > 100 || maxInputs < 5) { - fprintf(stderr,"%s: Invalid zsweep maxinputs=%d is >100 and <5, setting to default of 8\n", __func__, maxInputs); - maxInputs = 8; - } + // -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) { @@ -253,34 +332,26 @@ bool AsyncRPCOperation_sweep::main_impl() { fee = 0; } - auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); - builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA); + // Build and expire against the tip as it is now, not as it was when the round began: a round + // over many addresses can outlive the block it started at, and a transaction built against + // a stale height can be expiring, or already expired, by the time it is committed. + int buildHeight; + { + LOCK(cs_main); + buildHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : tipHeight; + } + auto nextActivation = NextActivationHeight(buildHeight, consensusParams); + if (nextActivation && buildHeight + AUTO_OP_EXPIRY_DELTA >= nextActivation.get()) { + LogPrintf("%s: Sweep txs would now be created before a NU activation but may expire after. Stopping this round.\n", getId()); + break; + } + auto builder = TransactionBuilder(consensusParams, buildHeight, pwalletMain); + 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); @@ -307,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(); @@ -320,7 +392,15 @@ 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); + pwalletMain->amountSwept += amountToSend - fee; + } sweepTxIds.push_back(tx.GetHash().ToString()); numTxCreated++; } else { @@ -329,6 +409,17 @@ bool AsyncRPCOperation_sweep::main_impl() { status = false; break; } + } else if (pwalletMain->IsLocked()) { + // Locked part-way through the round (a walletpassphrase timeout): nothing further can be + // signed. Fail the round rather than report the unswept addresses as done. + LogPrintf("%s: wallet was locked during the sweep; stopping. Unlock it with walletpassphrase\n", getId()); + set_error_code(RPC_WALLET_UNLOCK_NEEDED); + set_error_message("Wallet was locked during the sweep; unlock it with walletpassphrase for zsweep to sign"); + status = false; + break; + } else { + // A viewing-key-only address: its notes are visible but cannot be spent from this wallet. + LogPrint("zrpcunsafe", "%s: no spending key for %s; not sweeping it\n", getId(), EncodePaymentAddress(addr)); } } diff --git a/src/wallet/asyncrpcoperation_sweep.h b/src/wallet/asyncrpcoperation_sweep.h index 254b32f3e..ebfbc101f 100644 --- a/src/wallet/asyncrpcoperation_sweep.h +++ b/src/wallet/asyncrpcoperation_sweep.h @@ -1,18 +1,55 @@ // 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 +#ifndef HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H +#define HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H + #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: @@ -44,3 +81,5 @@ private: void setSweepResult(int numTxCreated, const CAmount& amountSwept, const std::vector& sweepTxIds); }; + +#endif // HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 5b0457870..958bcb4ca 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -43,6 +43,7 @@ #include "wallet/asyncrpcoperation_sendmany.h" #include "wallet/asyncrpcoperation_shieldcoinbase.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h" +#include "wallet/asyncrpcoperation_sweep.h" #include "consensus/upgrades.h" #include "sodium.h" #include @@ -3541,7 +3542,21 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) if (fHelp || params.size() > 0) throw runtime_error( "z_sweepstatus\n" - "\nGive details about zsweep operations since the node was started." + "\nGive details about zsweep operations since the node was started.\n" + "\nResult:\n" + "{\n" + " \"zsweep\" : true|false, (boolean) whether -zsweep is enabled\n" + " \"running\" : true|false, (boolean) whether a sweep round is in flight\n" + " \"wallet_locked\" : true|false, (boolean) the wallet is encrypted and locked, so nothing can be swept\n" + " until it is unlocked with walletpassphrase\n" + " \"amount_swept\" : x.xxx, (numeric) DRGX sent to the sweep address since startup\n" + " \"next_zsweep\" : n, (numeric) height of the next round\n" + " \"zsweepinterval\" : n, (numeric) blocks between rounds\n" + " \"zsweepaddress\" : \"zaddr\", (string) where swept funds are sent\n" + " \"zsweepexclude\" : [\"zaddr\",...], (array) addresses that are never swept\n" + " \"zsweepmaxinputs\" : n, (numeric) shielded inputs per sweep transaction\n" + " \"zsweepfee\" : n, (numeric) fee per sweep transaction in puposhis\n" + " \"zsweepexternal\" : true|false (boolean) whether sweeping to an external wallet is allowed\n" "}\n" "\nExamples:\n" + HelpExampleCli("z_sweepstatus", "") @@ -3553,7 +3568,8 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) UniValue ret(UniValue::VOBJ); ret.push_back(Pair("zsweep", pwalletMain->fSweepEnabled)); ret.push_back(Pair("running", pwalletMain->fSweepRunning)); - ret.push_back(Pair("amount_swept", pwalletMain->amountSwept)); + ret.push_back(Pair("wallet_locked", pwalletMain->IsLocked())); + ret.push_back(Pair("amount_swept", ValueFromAmount(pwalletMain->amountSwept))); ret.push_back(Pair("next_zsweep", pwalletMain->nextSweep)); ret.push_back(Pair("zsweepinterval", pwalletMain->sweepInterval)); ret.push_back(Pair("zsweepaddress", pwalletMain->sweepAddress)); @@ -3563,7 +3579,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) } ret.push_back(Pair("zsweepexclude", excludes)); ret.push_back(Pair("zsweepmaxinputs", pwalletMain->sweepMaxInputs)); - ret.push_back(Pair("zsweepfee", pwalletMain->sweepFee)); + ret.push_back(Pair("zsweepfee", fSweepTxFee)); ret.push_back(Pair("zsweepexternal", pwalletMain->fSweepExternalEnabled)); return ret; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index c83396fda..100e5dc66 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -625,13 +625,14 @@ void CWallet::RunSaplingSweep(int blockHeight) { // consolidation waits on sweep, and autoshield shares the same gate, so a // wedged sweep silently disables coinbase shielding forever. // Only honour the baton while a sweep operation genuinely is in flight. + bool fSweepInFlight = false; if (fSweepRunning) { std::shared_ptr sweepQueue = getAsyncRPCQueue(); std::shared_ptr inFlightSweep = (sweepQueue != nullptr) ? sweepQueue->getOperationForId(saplingSweepOperationId) : nullptr; - bool inFlight = (inFlightSweep != nullptr) && - (inFlightSweep->isReady() || inFlightSweep->isExecuting()); - if (!inFlight) { + fSweepInFlight = (inFlightSweep != nullptr) && + (inFlightSweep->isReady() || inFlightSweep->isExecuting()); + if (!fSweepInFlight) { LogPrintf("%s: clearing stale fSweepRunning at blockHeight=%d (no sweep operation in flight)\n", __func__, blockHeight); fSweepRunning = false; @@ -642,12 +643,32 @@ void CWallet::RunSaplingSweep(int blockHeight) { return; } + // Self-guard: let an in-flight round finish. Re-dispatching on every block, as this used to, never + // stopped the running op -- AsyncRPCOperation::cancel() is not virtual, so through the queue's base + // pointer it only cancels an op that has not started -- it just queued a fresh round behind it, + // which then repeated note selection over the whole wallet for nothing. (On a single async worker + // a replacement could not get past a hung op anyway.) + if (fSweepInFlight) { + LogPrintf("%s: sweep operation %s (enqueued at height %d) is still running at blockHeight=%d; " + "not re-dispatching\n", __func__, saplingSweepOperationId, sweepDispatchHeight, blockHeight); + return; + } + if (nextSweep > blockHeight) { LogPrintf("%s: Not time to sweep yet at blockHeight=%d nextSweep=%d\n", __func__, blockHeight, nextSweep); return; } LogPrintf("%s: Sweep enabled at blockHeight=%d nextSweep=%d\n", __func__, blockHeight, nextSweep); + // Nothing can be signed while the wallet is locked: every address would be skipped and the round + // would report success with nothing swept. Say so, and look again an interval later. + if (IsLocked()) { + LogPrintf("%s: wallet locked; not sweeping at height=%d. Unlock it with walletpassphrase " + "for zsweep to resume\n", __func__, blockHeight); + nextSweep = sweepInterval + blockHeight; + return; + } + //Don't Run if consolidation will run soon. if (fSaplingConsolidationEnabled && nextConsolidation - 5 <= blockHeight) { LogPrintf("%s: not sweeping since next consolidation is within 5 blocks, nextConsolidation=%d , blockHeight=%d\n", __func__, nextConsolidation, blockHeight); @@ -680,6 +701,7 @@ void CWallet::RunSaplingSweep(int blockHeight) { pendingSaplingSweepTxs.clear(); std::shared_ptr operation(new AsyncRPCOperation_sweep(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET)); saplingSweepOperationId = operation->getId(); + sweepDispatchHeight = blockHeight; 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 6e14a5f39..2330b282b 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -112,6 +112,10 @@ 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 +// zsweep (-zsweepmaxinputs): Sapling spends per sweep transaction. Out-of-range values fall back to the default. +static const int DEFAULT_SWEEP_MAX_INPUTS = 8; +static const int MIN_SWEEP_MAX_INPUTS = 5; +static const int MAX_SWEEP_MAX_INPUTS = 100; // 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. @@ -930,7 +934,10 @@ public: // Id of the in-flight sweep op; read by the op to confirm it is still the // current one before mutating scheduler state. AsyncRPCOperationId saplingSweepOperationId; - int amountSwept = 0; + // Block height at which that op was enqueued (for the log while RunSaplingSweep waits on it). + int sweepDispatchHeight = 0; + // Total sent to the sweep address by committed sweep transactions since startup. Guarded by cs_wallet. + CAmount 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 @@ -945,8 +952,8 @@ public: 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; + // Set from -zsweepmaxinputs at startup and read by every sweep op. (The fee lives in fSweepTxFee.) + int sweepMaxInputs = DEFAULT_SWEEP_MAX_INPUTS; std::string sweepAddress = ""; std::vector sweepExcludeAddresses; std::string consolidationAddress = ""; @@ -1069,6 +1076,15 @@ protected: if (pindexWalletTip != nullptr) { locator = chainActive.GetLocator(pindexWalletTip); pindexStamped = pindexWalletTip; + } else if (nInterruptedRescanHeight >= 0) { + // No wallet tip yet, but a scan of this session is running or was cut short: this is + // the startup rescan, and the caller is FlushStateToDisk stamping the chain tip (its + // hourly write, or the one in Shutdown). Writing that would mark the unscanned range + // as scanned, and the next start would skip it for good -- after -zapwallettxes, the + // transactions in it would simply be gone. Keep the scan's own locator instead. + LogPrintf("SetBestChain(): not stamping the chain tip over an incomplete rescan; the next " + "start resumes it from height %d\n", nInterruptedRescanHeight); + return false; } else if (!loc.vHave.empty()) { BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front()); if (mi != mapBlockIndex.end())