diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index 7858124a6..465fdc954 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -17,6 +17,7 @@ hush_gtest_SOURCES = \ gtest/test_mnemonic_compat.cpp \ gtest/test_stratum_jobid.cpp \ gtest/test_sweep_note_selection.cpp \ + gtest/test_asyncrpc_cancel.cpp \ gtest/test_wallet_notedata.cpp \ gtest/test_net_closesocket.cpp \ gtest/test_fd_defense.cpp \ diff --git a/src/asyncrpcoperation.h b/src/asyncrpcoperation.h index f3a5dbf10..d78df9a85 100644 --- a/src/asyncrpcoperation.h +++ b/src/asyncrpcoperation.h @@ -60,8 +60,10 @@ public: // You must implement this method in your subclass. virtual void main(); - // Override this method if you can interrupt execution of main() in your subclass. - void cancel(); + // Override this method if you can interrupt execution of main() in your subclass. It must be virtual: + // callers hold a std::shared_ptr (the queue's map, the wallet schedulers). It used + // not to be, which left every subclass override dead and a running operation uncancellable. + virtual void cancel(); // Getters and setters diff --git a/src/gtest/test_asyncrpc_cancel.cpp b/src/gtest/test_asyncrpc_cancel.cpp new file mode 100644 index 000000000..2b36ffb0a --- /dev/null +++ b/src/gtest/test_asyncrpc_cancel.cpp @@ -0,0 +1,82 @@ +// 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 "asyncrpcoperation.h" +#include "wallet/asyncrpcoperation_autoshieldcoinbase.h" +#include "wallet/asyncrpcoperation_saplingconsolidation.h" +#include "wallet/asyncrpcoperation_sweep.h" + +namespace { + +// Lets a test put an operation into any state, without running it. +template +class Probe : public Op { +public: + template + explicit Probe(Args&&... args) : Op(std::forward(args)...) {} + void Set(OperationStatus status) { this->set_state(status); } +}; + +// An operation that does not override cancel(): the base behaviour. +class PlainOp : public AsyncRPCOperation { +public: + void main() override {} + void Set(OperationStatus status) { set_state(status); } +}; + +int S(OperationStatus status) { return static_cast(status); } + +// The queue's map and the wallet schedulers hold every operation as a shared_ptr, so +// that is how cancel() is called here. Before cancel() was virtual, each of these overrides was dead. +template +void CheckOverride(std::shared_ptr

probe) +{ + std::shared_ptr op = probe; + + probe->Set(OperationStatus::EXECUTING); + op->cancel(); + EXPECT_TRUE(op->isCancelled()) << "a running round can be stopped"; + + for (OperationStatus done : {OperationStatus::SUCCESS, OperationStatus::FAILED}) { + probe->Set(done); + op->cancel(); + EXPECT_EQ(S(done), S(op->getState())) << "a finished round is not relabelled as cancelled"; + } + + probe->Set(OperationStatus::READY); + op->cancel(); + EXPECT_TRUE(op->isCancelled()) << "a round that has not started is cancelled, as before"; +} + +} + +TEST(AsyncRPCCancel, TheSweepOverrideIsReachedThroughTheBasePointer) { + CheckOverride(std::make_shared>(100)); +} + +TEST(AsyncRPCCancel, TheConsolidationOverrideIsReachedThroughTheBasePointer) { + CheckOverride(std::make_shared>(100, SaplingConsolidationRequest())); +} + +TEST(AsyncRPCCancel, TheAutoshieldOverrideIsReachedThroughTheBasePointer) { + CheckOverride(std::make_shared>(100)); +} + +TEST(AsyncRPCCancel, AnOperationWithoutAnOverrideOnlyCancelsBeforeItStarts) { + auto plain = std::make_shared(); + std::shared_ptr op = plain; + + plain->Set(OperationStatus::EXECUTING); + op->cancel(); + EXPECT_TRUE(op->isExecuting()) << "z_sendmany and friends are not interrupted mid-run"; + + plain->Set(OperationStatus::READY); + op->cancel(); + EXPECT_TRUE(op->isCancelled()); +} diff --git a/src/wallet/asyncrpcoperation_autoshieldcoinbase.cpp b/src/wallet/asyncrpcoperation_autoshieldcoinbase.cpp index 4300dc176..8a21bde9f 100644 --- a/src/wallet/asyncrpcoperation_autoshieldcoinbase.cpp +++ b/src/wallet/asyncrpcoperation_autoshieldcoinbase.cpp @@ -82,7 +82,9 @@ void AsyncRPCOperation_autoshieldcoinbase::main() { } } - set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); + // A round cancelled part-way (the queue at shutdown) stays CANCELLED rather than being relabelled. + if (!isCancelled()) + set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); setResult(); LogPrintf("%s: autoshield operation finished (status=%s, txs=%d, shielded=%s)\n", @@ -475,11 +477,12 @@ void AsyncRPCOperation_autoshieldcoinbase::setResult() { } void AsyncRPCOperation_autoshieldcoinbase::cancel() { - // Cancelling is how the scheduler stops an in-flight round, so unlike the base - // class this must be able to move an EXECUTING operation to CANCELLED. What it - // must not do is overwrite a state that is already terminal: the scheduler - // cancels the previous operation when it enqueues the next one, and that one may - // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled. + // 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); diff --git a/src/wallet/asyncrpcoperation_autoshieldcoinbase.h b/src/wallet/asyncrpcoperation_autoshieldcoinbase.h index bb21f09ec..bc7ac2dd6 100644 --- a/src/wallet/asyncrpcoperation_autoshieldcoinbase.h +++ b/src/wallet/asyncrpcoperation_autoshieldcoinbase.h @@ -52,7 +52,7 @@ public: AsyncRPCOperation_autoshieldcoinbase& operator=(AsyncRPCOperation_autoshieldcoinbase&&) = delete; virtual void main(); - virtual void cancel(); + virtual void cancel() override; virtual UniValue getStatus() const; private: diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 1f939a824..b9800d244 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -245,14 +245,15 @@ void AsyncRPCOperation_saplingconsolidation::main() { stop_execution_clock(); - if (success) { - set_state(OperationStatus::SUCCESS); - } else { - set_state(OperationStatus::FAILED); - } + // 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); std::string s = strprintf("%s: Sapling Consolidation operation complete. (status=%s", getId(), getStateAsString()); - if (success) { + if (isCancelled()) { + s += ")\n"; + } else if (success) { s += strprintf(", success)\n"); } else { s += strprintf(", error=%s)\n", getErrorMessage()); @@ -447,8 +448,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { }; for (const PlannedTx& planned : txs) { - // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is - // not virtual), so look for the shutdown here, or a stop would wait for the whole round. + // ShutdownRequested() too: the shutdown flag is set well before the queue is closed and this op + // is cancelled, so checking it stops the round as soon as a stop is asked for. if (isCancelled() || ShutdownRequested()) { LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); tally.error = isCancelled() ? "cancelled" : "shutting down"; @@ -581,11 +582,12 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol } void AsyncRPCOperation_saplingconsolidation::cancel() { - // Cancelling is how the scheduler stops an in-flight round, so unlike the base - // class this must be able to move an EXECUTING operation to CANCELLED. What it - // must not do is overwrite a state that is already terminal: the scheduler - // cancels the previous operation when it enqueues the next one, and that one may - // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled. + // 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); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index e82825fff..e6023f148 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -121,7 +121,7 @@ public: virtual void main(); - virtual void cancel(); + virtual void cancel() override; virtual UniValue getStatus() const; diff --git a/src/wallet/asyncrpcoperation_sweep.cpp b/src/wallet/asyncrpcoperation_sweep.cpp index 12b9ddde5..3787dbfbc 100644 --- a/src/wallet/asyncrpcoperation_sweep.cpp +++ b/src/wallet/asyncrpcoperation_sweep.cpp @@ -54,11 +54,10 @@ void AsyncRPCOperation_sweep::main() { stop_execution_clock(); - if (success) { - set_state(OperationStatus::SUCCESS); - } else { - set_state(OperationStatus::FAILED); - } + // 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 @@ -78,7 +77,9 @@ void AsyncRPCOperation_sweep::main() { } std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString()); - if (success) { + if (isCancelled()) { + s += ")\n"; + } else if (success) { s += strprintf(", success)\n"); } else { s += strprintf(", error=%s)\n", getErrorMessage()); @@ -271,6 +272,11 @@ bool AsyncRPCOperation_sweep::main_impl() { 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; @@ -385,8 +391,8 @@ bool AsyncRPCOperation_sweep::main_impl() { } CTransaction tx = maybe_tx.get(); - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", getId()); + if (isCancelled() || ShutdownRequested()) { + LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down"); break; } @@ -447,11 +453,12 @@ void AsyncRPCOperation_sweep::setSweepResult(int numTxCreated, const CAmount& am } void AsyncRPCOperation_sweep::cancel() { - // Cancelling is how the scheduler stops an in-flight round, so unlike the base - // class this must be able to move an EXECUTING operation to CANCELLED. What it - // must not do is overwrite a state that is already terminal: the scheduler - // cancels the previous operation when it enqueues the next one, and that one may - // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled. + // 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); diff --git a/src/wallet/asyncrpcoperation_sweep.h b/src/wallet/asyncrpcoperation_sweep.h index ebfbc101f..389713712 100644 --- a/src/wallet/asyncrpcoperation_sweep.h +++ b/src/wallet/asyncrpcoperation_sweep.h @@ -64,7 +64,7 @@ public: virtual void main(); - virtual void cancel(); + virtual void cancel() override; virtual UniValue getStatus() const; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 100e5dc66..67049a74f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -643,11 +643,11 @@ 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.) + // Self-guard: let an in-flight round finish. Re-dispatching on every block, as this used to, cancels + // the running op (now that AsyncRPCOperation::cancel() is virtual, the sweep's override can stop an + // executing round), discarding the transaction it is building -- on a wallet where one build + // outlasts a block, nothing would ever be swept. Before cancel() was virtual it merely queued a + // redundant round behind the running one. 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);