Repository navigation
Description
Summary
SpvRuntime::stop() cannot terminate a running SpvRuntime::run(). The two methods deadlock against each other on the RwLock<Option<SpvClient>> guard. stop() must become synchronous and non-locking (or the lock layout must change) so it can signal termination without contending for the write lock that run() is blocking on.
Location
packages/rs-platform-wallet/src/spv/runtime.rs:132-159
pub async fn run(&self, config: ClientConfig) -> Result<(), PlatformWalletError> {
self.start(config).await?;
let client_guard = self.client.read().await; // ① read lock acquired
let client = client_guard.as_ref()
.ok_or(PlatformWalletError::SpvNotRunning)?;
let result = client.run().await.map_err(...); // ② held across the entire sync loop
drop(client_guard);
let mut client = self.client.write().await; // ③ only after run() returns
let _ = client.take();
result
}
pub async fn stop(&self) -> Result<(), PlatformWalletError> {
let mut client = self.client.write().await; // ④ needs write lock
if let Some(c) = client.take() {
c.stop().await...; // ⑤ never reached if step ② is alive
}
}Why it deadlocks
run()holds the read guard onself.clientfor the full lifetime ofclient.run().await(the SPV sync loop — runs for hours).- A concurrent call to
stop()queues a write-lock waiter onself.client. tokio::sync::RwLockis writer-priority: a queued writer also blocks new readers, so even other readers cannot ride along.- The only way to make
client.run()return — and let the read guard drop — is to flipDashSpvClient's internalArc<watch::Sender<bool>>viaclient.stop(). - The only place that calls
client.stop()is line ⑤, gated on acquiring the write lock that step 2 is blocked on.
Circular wait. Any concurrent stop() while sync is running hangs forever. Same applies to any other lifecycle operation that needs the write lock (e.g. a re-start()).
Where the regression came from
| Introducing PR | #3730 — fix(platform-wallet): spv client deadlocking when sending a tx |
| Commit | 9f3bfa3ca3 |
| Merged | 2026-05-22 |
The original shape (commit bee80e93bf by Ivan Shumkov, shipped via #3531 on 2026-04-24) was deadlock-free by construction: run() accepted an outer CancellationToken parameter; cancellation propagated inward into client.run(token), which returned cleanly, dropped the read guard at the end of an inner block, and then called self.stop().await outside the guard scope.
PR #3730 had to adapt to rust-dashcore #772 (Kevin Rombach, merged 2026-05-18) which removed the external CancellationToken parameter from DashSpvClient::run() and replaced it with an internal Arc<watch::Sender<bool>> flipped via client.stop(). The adaptation dropped the outer cancel_token from SpvRuntime::run() without replacing the termination mechanism — the only remaining way to make client.run() return is now client.stop(), which is reachable only after stop() acquires the write lock, which can never be acquired while run() holds the read guard.
So: a 3-day-old regression from fixing a different SPV deadlock.
What we need
SpvRuntime::stop() must be synchronous and non-locking — or, equivalently, must be able to signal client.run() to terminate without needing to acquire the RwLock write guard on self.client. Once client.run() returns and the read guard drops, the lifecycle teardown (take the client out of the Option, drop it) can happen anywhere — but the signaling step must not contend with the read guard.
The signaling needs to be reachable from synchronous contexts (e.g. a std::panic::set_hook callback — the original cancel_background() use case in PR #3549's e2e harness needs this same property).
Proposed fix shapes
| # | Approach | Sketch |
|---|---|---|
| A | Arc<DashSpvClient> instead of Option<DashSpvClient> under the lock. Both run() and stop() Arc::clone() from the lock and then operate without holding it. stop() becomes near-synchronous: clone the Arc, call client.stop() (which only flips an internal watch — already designed to be cheap/sync-ish), done. The platform-wallet write lock is then only used for swap operations, not held across awaits. |
Smallest patch, idiomatic for tokio-based SPV/blockchain clients. |
| B | Split the lock: one cell for the client handle, one parallel watch::Sender<RuntimeState> for lifecycle signaling. stop() flips the watch directly; run() selects on the watch alongside client.run(). |
More machinery; closest to the campaign-tree (#3549) cancel-token design. |
| C | take()-and-restore: run() removes the client from the Option at the start, owns it directly during the sync loop, puts it back when sync exits. stop() only needs to flip a separate watch. |
Conceptually clearest; loses concurrent state queries unless they also extract. |
Recommended: A, with the constraint that stop() must be callable synchronously (just client_arc.stop() if dash-spv exposes a sync flip, otherwise a fire-and-forget tokio::spawn).
Test plan
- Unit test in
runtime.rs: spawnrun()on a mockedSpvClient, then callstop()from another task — assertstop()returns within a timeout (currently hangs forever). - Unit test: panic-hook-style sync caller can fire termination without an async context (relevant for PR test(platform-wallet): e2e framework + full test suite — triage pins, Found-*/PA-* guards, fail-closed persist, Stage-2 merge #3549's e2e harness).
-
cargo test -p platform-wallet --libpasses after the fix.
Severity rationale (high)
This makes graceful shutdown impossible whenever sync is running. SwiftExampleApp + the FFI surface in packages/rs-platform-wallet-ffi/src/spv.rs:269-275 cannot reliably stop the SPV client between app sessions; the e2e harness in PR #3549 can't drive its panic-hook lifecycle teardown; the campaign tree pins an older rust-dashcore rev specifically because the post-#772 platform-wallet shape strands them.
Related
- rust-dashcore #772 — upstream API change that triggered the adaptation.
- dashpay/platform PR fix(platform-wallet): spv client deadlocking when sending a tx #3730 — the introducing commit.
- dashpay/platform PR test(platform-wallet): e2e framework + full test suite — triage pins, Found-*/PA-* guards, fail-closed persist, Stage-2 merge #3549 (e2e framework) — pins an older rust-dashcore rev because of this and other shape mismatches; its
SpvRuntimehas the deadlock-free outer-token design preserved. - dashpay/platform PR feat(platform-wallet): IdentityManager::identity_ids + FFI no-selectable-inputs error mapping #3651 — was carving cancellation out of test(platform-wallet): e2e framework + full test suite — triage pins, Found-*/PA-* guards, fail-closed persist, Stage-2 merge #3549 onto v3.1-dev; stripped because this issue's resolution belongs to the SPV runtime owner, not a backport author.
🤖 Co-authored by Claudius the Magnificent AI Agent
Activity