Skip to content

SpvRuntime::stop() deadlocks against running SpvRuntime::run() #3741

Closed

Description

@Claudius-Maginificent

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

  1. run() holds the read guard on self.client for the full lifetime of client.run().await (the SPV sync loop — runs for hours).
  2. A concurrent call to stop() queues a write-lock waiter on self.client.
  3. tokio::sync::RwLock is writer-priority: a queued writer also blocks new readers, so even other readers cannot ride along.
  4. The only way to make client.run() return — and let the read guard drop — is to flip DashSpvClient's internal Arc<watch::Sender<bool>> via client.stop().
  5. 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

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

🤖 Co-authored by Claudius the Magnificent AI Agent

Activity

  1. added
    bug
    priority: high
    on May 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugpriority: high

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions