// 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 "assert.h" #include "boost/variant/static_visitor.hpp" #include "asyncrpcoperation_sweep.h" #include "init.h" #include "key_io.h" #include "rpc/protocol.h" #include "random.h" #include "sync.h" #include "tinyformat.h" #include "transaction_builder.h" #include "util.h" #include "utilmoneystr.h" #include "wallet.h" #include #include extern string randomSietchZaddr(); CAmount fSweepTxFee = DEFAULT_SWEEP_FEE; bool fSweepMapUsed = false; boost::optional rpcSweepAddress; AsyncRPCOperation_sweep::AsyncRPCOperation_sweep(int targetHeight, bool fromRpc) : targetHeight_(targetHeight), fromRPC_(fromRpc){} AsyncRPCOperation_sweep::~AsyncRPCOperation_sweep() {} void AsyncRPCOperation_sweep::main() { if (isCancelled()) { // Only the current op owns the scheduler flag; a stale/cancelled op must // not clear it out from under a freshly-enqueued successor. if (pwalletMain) { LOCK(pwalletMain->cs_wallet); if (getId() == pwalletMain->saplingSweepOperationId) { pwalletMain->fSweepRunning = false; } } return; } set_state(OperationStatus::EXECUTING); start_execution_clock(); bool success = false; try { success = main_impl(); } catch (...) { set_error_from_current_exception(); } stop_execution_clock(); // A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays // CANCELLED rather than being relabelled by how much of it got done. if (!isCancelled()) set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); // Scheduler bookkeeping, done here so it runs on success AND failure AND // exception (main_impl's terminal code is skipped when it throws). Only the // current op mutates scheduler state. Preserves the "keep draining every // block until swept" model: on a successful-but-incomplete round we leave // fSweepRunning set and nextSweep unadvanced so the next block continues. // On completion OR on failure/exception we release fSweepRunning and back // off one interval — critically, a persistently failing sweep no longer // leaves fSweepRunning stuck true and wedges consolidation + autoshield. if (pwalletMain) { LOCK2(cs_main, pwalletMain->cs_wallet); if (getId() == pwalletMain->saplingSweepOperationId && (!success || sweepComplete_)) { int tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_; pwalletMain->nextSweep = pwalletMain->sweepInterval + tipHeight; pwalletMain->fSweepRunning = false; } } std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString()); if (isCancelled()) { s += ")\n"; } else if (success) { s += strprintf(", success)\n"); } else { s += strprintf(", error=%s)\n", getErrorMessage()); } LogPrintf("%s", s); } // Is this zaddr excluded from zsweep ? bool IsExcludedAddress(libzcash::SaplingPaymentAddress zaddr) { for( auto & sweepExcludeAddress : pwalletMain->sweepExcludeAddresses ) { auto zAddressExclude = DecodePaymentAddress(sweepExcludeAddress); if (boost::get(&zAddressExclude) != nullptr) { auto excludeAddress = boost::get(zAddressExclude); if (excludeAddress == zaddr) { return true; } } else { // This is an invalid sapling zaddr LogPrintf("%s: Invalid zsweepexclude zaddr %s, ignoring\n", __func__, sweepExcludeAddress); continue; } } 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(); LogPrintf("%s: Beginning asyncrpcoperation_sweep.\n", getId()); auto consensusParams = Params().GetConsensus(); int tipHeight; { LOCK(cs_main); tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_; } // Key the NU-straddle guard and the tx builder/expiry off tipHeight (the // height we actually build and expire against), not the stale enqueue-time // targetHeight_, so a queue delay cannot slip a straddling expiry past this // guard. Mirrors the autoshield op (commit 65130c312). auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) { LogPrintf("%s: Sweep txs would be created before a NU activation but may expire after. Skipping this round.\n", getId()); setSweepResult(0, 0, std::vector()); sweepComplete_ = true; // nothing to do this round; back nextSweep off one interval instead of re-dispatching every block 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; { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->GetFilteredNotes(saplingEntries, "", 11); if (!fromRPC_) { if (fSweepMapUsed) { const vector& v = mapMultiArgs["-zsweepaddress"]; for(int i = 0; i < v.size(); i++) { auto zAddress = DecodePaymentAddress(v[i]); if (boost::get(&zAddress) != nullptr) { sweepAddress = boost::get(zAddress); } else { LogPrintf("%s: Invalid zsweepaddress configured, exiting\n", opid); return false; } } } else { LogPrintf("%s: No zsweepaddress configured, exiting\n", opid); return false; } } else { if (boost::get(&rpcSweepAddress) != nullptr) { sweepAddress = boost::get(rpcSweepAddress); } else { LogPrintf("%s: Invalid zsweepaddress, exiting\n", opid); return false; } } // Map all notes (zutxos) by address for (auto & entry : saplingEntries) { // do not need to sweep Excluded Addresses if(IsExcludedAddress(entry.address)) { continue; } // do not need to sweep the sweepAddress as that is the destination if (sweepAddress == entry.address) { continue; } else { std::map>::iterator it; it = mapAddresses.find(entry.address); if (it != mapAddresses.end()) { it->second.push_back(entry); } else { std::vector entries; entries.push_back(entry); mapAddresses[entry.address] = entries; } } } } int numTxCreated = 0; std::vector sweepTxIds; CAmount amountSwept = 0; CCoinsViewCache coinsView(pcoinsTip); bool sweepComplete = true; for (std::map>::iterator it = mapAddresses.begin(); it != mapAddresses.end(); it++) { // Stop before starting another address: building takes seconds, and a stop would only discard it. if (isCancelled() || ShutdownRequested()) { LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down"); break; } auto addr = (*it).first; auto saplingEntries = (*it).second; libzcash::SaplingExtendedSpendingKey extsk; if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { std::vector fromNotes; CAmount amountToSend = 0; // -zsweepmaxinputs, parsed and range-checked once at startup. const size_t maxInputs = pwalletMain->sweepMaxInputs; // 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) candidates.push_back(saplingEntry); } if (candidates.empty()) 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) { LogPrintf("%s: Amount to send %s is <= fee, using fee=0", getId(), FormatMoney(amountToSend)); fee = 0; } // 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 + AutoOpExpiryDelta() >= 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 + AutoOpExpiryDelta()); LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee)); // 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); // Add sietch zouts int ZOUTS = 7; for(size_t i = 0; i < ZOUTS; i++) { // In Privacy Zdust We Trust -- Duke string zdust = randomSietchZaddr(); auto zaddr = DecodePaymentAddress(zdust); if (IsValidPaymentAddress(zaddr)) { CAmount amount=0; auto sietchZoutput = boost::get(zaddr); LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d\n", __func__, i); // %d %s amount=%li\n", __func__, i, zaddr, amount); builder.AddSaplingOutput(extsk.expsk.ovk, sietchZoutput, amount); } else { LogPrintf("%s: Invalid payment address %s! Stopping.\n", __func__, zdust); status = false; break; } } LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", __func__, ZOUTS); auto maybe_tx = builder.Build(); if (!maybe_tx) { // 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; continue; } CTransaction tx = maybe_tx.get(); if (isCancelled() || ShutdownRequested()) { LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down"); break; } 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 { LogPrintf("%s: Sweep transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); setSweepResult(numTxCreated, amountSwept, sweepTxIds); 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)); } } // Record whether the wallet is fully swept; the scheduler bookkeeping // (advancing nextSweep / clearing fSweepRunning) is done in main() so it // also runs on the failure/exception/cancel paths and cannot wedge the // shared fSweepRunning flag (which now also gates consolidation + autoshield). sweepComplete_ = sweepComplete; LogPrintf("%s: Created %d transactions with total output amount=%s, status=%d\n", getId(), numTxCreated, FormatMoney(amountSwept), (int)status); setSweepResult(numTxCreated, amountSwept, sweepTxIds); return status; } void AsyncRPCOperation_sweep::setSweepResult(int numTxCreated, const CAmount& amountSwept, const std::vector& sweepTxIds) { UniValue res(UniValue::VOBJ); res.push_back(Pair("num_tx_created", numTxCreated)); res.push_back(Pair("amount_swept", FormatMoney(amountSwept))); UniValue txIds(UniValue::VARR); for (const std::string& txId : sweepTxIds) { txIds.push_back(txId); } res.push_back(Pair("sweep_txids", txIds)); set_result(res); } void AsyncRPCOperation_sweep::cancel() { // Lets the queue stop an executing round when it closes at shutdown, so unlike the // base class this must be able to move an EXECUTING operation to CANCELLED. The // scheduler never cancels a running round (it returns early while one is in flight); // it cancels the previous operation only when enqueueing the next, by which time // that one is terminal -- and a terminal state must not be overwritten, or a // SUCCEEDED result would be relabelled as cancelled. if (isSuccess() || isFailed() || isCancelled()) return; set_state(OperationStatus::CANCELLED); } UniValue AsyncRPCOperation_sweep::getStatus() const { UniValue v = AsyncRPCOperation::getStatus(); UniValue obj = v.get_obj(); obj.push_back(Pair("method", "sweep")); obj.push_back(Pair("target_height", targetHeight_)); return obj; }