From 2e7876981712e3fd005fa0a2d74f0d213dc7a578 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 18 Nov 2026 11:08:57 -0600 Subject: [PATCH 1/5] wallet: let an in-flight zsweep round finish, and build each tx at the current tip RunSaplingSweep re-dispatched a sweep on every block while a round was still running. That 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, and the sweep's own cancel() override is never reached -- it just queued a fresh round behind it, which then repeated note selection over the whole wallet and was itself superseded a block later. Leave an in-flight op alone, as RunSaplingConsolidation already does, and log that it is still running and since which height. A round can outlive the block it started at (a busy deposit wallet takes seconds per sweep transaction), but since v1.3.0 every transaction in a round was built and expired against the tip read once when the round began, so late transactions in a long round could be expiring, or already expired, by the time they were committed. Read the tip for each transaction, and re-check the NU-straddle guard there. Regtest, same fixture as dev (3 deposit addresses x 7 notes, -zsweepmaxinputs=5, a block every ~3 s while each build takes ~7 s): the same 7 sweep transactions and amount as dev, with "still running; not re-dispatching" where dev queued a redundant round on every block. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/wallet/asyncrpcoperation_sweep.cpp | 17 +++++++++++++++-- src/wallet/wallet.cpp | 19 ++++++++++++++++--- src/wallet/wallet.h | 2 ++ 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index 75a5b20c2..981141099 100644 --- a/src/wallet/asyncrpcoperation_sweep.cpp +++ b/src/wallet/asyncrpcoperation_sweep.cpp @@ -253,8 +253,21 @@ 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 diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index c83396fda..941fb08dc 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,6 +643,17 @@ 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; @@ -680,6 +692,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..9b16ba6f3 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -930,6 +930,8 @@ 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; + // Block height at which that op was enqueued (for the log while RunSaplingSweep waits on it). + int sweepDispatchHeight = 0; int amountSwept = 0; // What consolidation rounds have done since startup. Guarded by cs_wallet. SaplingConsolidationStats consolidationStats; From 70dd6c6f8b9874d4deb5ac07ed4748561d0a233b Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 18 Nov 2026 11:08:57 -0600 Subject: [PATCH 2/5] wallet: stop zsweep reporting success on a locked wallet On an encrypted wallet that is locked, the sweep op could get no spending key, skipped every address without a word, and finished "Created 0 transactions ... status=1": a successful round that swept nothing, every interval, with no hint anywhere. Every restart locks an encrypted wallet, so an exchange that restarted its node to upgrade saw its deposit -> withdraw sweep simply stop. - RunSaplingSweep skips the round while the wallet is locked, logs why, and looks again an interval later, as consolidation and autoshield already do. - The op fails with RPC_WALLET_UNLOCK_NEEDED if the wallet is locked when it starts, and fails the round with that error if the wallet is locked part-way through (a walletpassphrase timeout). - An address the wallet has only a viewing key for is now logged (zrpcunsafe) rather than skipped silently. Regtest, dev vs this branch on the same encrypted fixture: dev logs "Created 0 transactions ... status=success" while locked; this logs "wallet locked; not sweeping ... Unlock it with walletpassphrase", and locking mid-round ends it "status=failed, error=Wallet was locked during the sweep ...". After unlocking, both sweep everything. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/wallet/asyncrpcoperation_sweep.cpp | 20 ++++++++++++++++++++ src/wallet/wallet.cpp | 9 +++++++++ 2 files changed, 29 insertions(+) diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index 981141099..c40b091aa 100644 --- a/src/wallet/asyncrpcoperation_sweep.cpp +++ b/src/wallet/asyncrpcoperation_sweep.cpp @@ -128,6 +128,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; @@ -342,6 +351,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/wallet.cpp b/src/wallet/wallet.cpp index 941fb08dc..100e5dc66 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -660,6 +660,15 @@ void CWallet::RunSaplingSweep(int blockHeight) { } 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); From eec0d86dbf4351374c71855a2ec51664ae94248e Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 18 Nov 2026 11:08:57 -0600 Subject: [PATCH 3/5] wallet: make z_sweepstatus report what the sweep actually does Three z_sweepstatus fields read members nothing kept up to date: - zsweepmaxinputs showed a member never set from -zsweepmaxinputs, so it always said 200 while the op used GetArg("-zsweepmaxinputs", 8). Parse and range-check the option once at startup into that member (5 to 100, default 8; same fallback as before) and have the op read it. - zsweepfee showed a member never set from -zsweepfee. Report fSweepTxFee, which the op uses, and drop the dead member. - amount_swept showed a counter nothing incremented (an int of puposhis, which would also have overflowed past ~21 DRGX). Count committed sweep transactions in a CAmount and report DRGX. Add wallet_locked, so it is visible at a glance why nothing is being swept, and give the RPC a real help text (it had a stray "}" and no Result section). Add the include guard that asyncrpcoperation_sweep.h lacked, now that rpcwallet.cpp includes it too. Release-notes item: amount_swept is now a decimal DRGX amount (it was an integer that was always 0). Co-Authored-By: Claude Opus 5.5 (1M context) --- src/init.cpp | 9 ++++++++- src/wallet/asyncrpcoperation_sweep.cpp | 11 ++++++----- src/wallet/asyncrpcoperation_sweep.h | 5 +++++ src/wallet/rpcwallet.cpp | 22 +++++++++++++++++++--- src/wallet/wallet.h | 11 ++++++++--- 5 files changed, 46 insertions(+), 12 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 1c571bef9..564519db5 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)")); @@ -2630,6 +2630,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"]; diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index c40b091aa..fb4f9142a 100644 --- a/src/wallet/asyncrpcoperation_sweep.cpp +++ b/src/wallet/asyncrpcoperation_sweep.cpp @@ -209,11 +209,8 @@ 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; @@ -343,6 +340,10 @@ bool AsyncRPCOperation_sweep::main_impl() { if (pwalletMain->CommitAutomatedTx(tx)) { LogPrintf("%s: Committed sweep transaction with txid=%s\n", getId(), tx.GetHash().ToString()); amountSwept += amountToSend - fee; + { + LOCK(pwalletMain->cs_wallet); + pwalletMain->amountSwept += amountToSend - fee; + } sweepTxIds.push_back(tx.GetHash().ToString()); numTxCreated++; } else { diff --git a/src/wallet/asyncrpcoperation_sweep.h b/src/wallet/asyncrpcoperation_sweep.h index 254b32f3e..28f75711b 100644 --- a/src/wallet/asyncrpcoperation_sweep.h +++ b/src/wallet/asyncrpcoperation_sweep.h @@ -1,6 +1,9 @@ // 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 "univalue.h" @@ -44,3 +47,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.h b/src/wallet/wallet.h index 9b16ba6f3..22fd7188a 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. @@ -932,7 +936,8 @@ public: AsyncRPCOperationId saplingSweepOperationId; // Block height at which that op was enqueued (for the log while RunSaplingSweep waits on it). int sweepDispatchHeight = 0; - int amountSwept = 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 @@ -947,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 = ""; From ca07b8299f8844b90931faa2c11024bbb3cec7c7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 18 Nov 2026 11:08:57 -0600 Subject: [PATCH 4/5] wallet: keep an interrupted -zapwallettxes / -rescan from hiding the unscanned range -zapwallettxes erases every wallet transaction but leaves the best-block locator at the old tip. The forced rescan that follows starts at genesis, and ScanForWalletTransactions only ever moves the locator forward, so when that rescan was cut short -- killed, or a clean shutdown -- the next normal start read the old locator, skipped the rescan, and the wallet came up without the erased transactions: zero balance and no notes until someone ran -rescan. Plain -rescan had the same gap. - Before a forced rescan that starts below the locator on disk, move the locator back to where the scan starts (RewindWalletLocatorForRescan). An interrupted scan then checkpoints forward from there, and a killed one restarts from there. With -zapwallettxes this is done right after the zap, so a startup that fails in between (a config error, say) cannot reopen the gap. - SetBestChainWith no longer stamps the chain tip while the startup rescan is running or was cut short and init has not seeded the wallet tip yet. That stamp comes from FlushStateToDisk (its hourly write, or the one in Shutdown) and would overwrite the scan's own locator the same way. Regtest, dev vs this branch on the same fixture (141 blocks, 26 notes, 146 txs, 430.0496418 DRGX), stopping the node under gdb as the zap rescan begins and then starting it normally: dev comes up empty (0 balance, 0 notes, 0 txs) after both SIGKILL and SIGTERM; this branch resumes the rescan from block 0 and restores exactly the baseline. New gtest WalletShutdownSave.DoesNotStampTheChainTipOverAnIncompleteStartupRescan. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/gtest/test_wallet_shutdownsave.cpp | 43 +++++++++++++++++++++++ src/init.cpp | 48 ++++++++++++++++++++++++++ src/wallet/wallet.h | 9 +++++ 3 files changed, 100 insertions(+) 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 564519db5..0da56523a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -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...")); @@ -2876,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/wallet.h b/src/wallet/wallet.h index 22fd7188a..2330b282b 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1076,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()) From b61611d5c2cc9246fe082cacb4889f297c6b9863 Mon Sep 17 00:00:00 2001 From: DanS Date: Fri, 20 Nov 2026 15:49:38 -0600 Subject: [PATCH 5/5] 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: