From 0acf89a0b432c035ba8db40b71d264c650dbe581 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 12:03:01 -0400 Subject: [PATCH] android: Start wallet no longer looks like a no-op while Cuprate launches Tapping Start held the SQLCipher mutex for the whole in-process Node::launch and blocked the UniFFI tokio worker, so wallet_status stayed off with no error. Drop the store lock until creds are needed, spawn_blocking the sync start, and show that Start is in flight. The APK still runs Cuprate testnet only; this does not add mainnet or prune. --- .../siriusdevops/onionwire/WireViewModel.kt | 44 ++++++++++++------- .../onionwire/ui/WalletChildStatusText.kt | 5 +++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 7 ++- .../onionwire/ui/WalletChildStatusTextTest.kt | 8 ++++ crates/onionwire-sdk/src/lib.rs | 20 +++++---- src/node.rs | 10 +++-- src/wallet_child.rs | 43 ++++++++++++++++-- 7 files changed, 103 insertions(+), 34 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 04097ed..bbabf37 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -40,6 +40,7 @@ import uniffi.onionwire_sdk.WalletChildStatus import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File +import java.util.concurrent.atomic.AtomicBoolean sealed interface Phase { /** No identity unlocked. Nothing Tor-related is running. */ @@ -618,6 +619,14 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private val _walletChildError = MutableStateFlow(null) val walletChildError: StateFlow = _walletChildError.asStateFlow() + /** + * Start is in flight. Core status stays `off` until Cuprate/`monerod` answers, + * so the screen must not wait on that snapshot to show that the tap landed. + */ + private val startInFlight = AtomicBoolean(false) + private val _walletChildStarting = MutableStateFlow(false) + val walletChildStarting: StateFlow = _walletChildStarting.asStateFlow() + /** The stored chain source + binary settings, for prefilling the editor. */ private val _chainSource = MutableStateFlow(null) val chainSource: StateFlow = _chainSource.asStateFlow() @@ -795,25 +804,28 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home) /** - * Spawns the child (and its daemon/SOCKS siblings) and returns what the core - * reached. - * - * The returned state is `connecting` at best on the first call — the wallet - * RPC does not answer the instant the process exists — and that is reported - * as-is. The spawn is synchronous inside the node and a `.onion` source - * waits up to 20s for its SOCKS listener, so this never runs on the main - * thread. + * Kick off start on [viewModelScope] so leaving the composition does not + * cancel Cuprate launch. Returns immediately; watch [walletChildStarting] + * and [walletChildError]. Core status stays `off` until the node answers. */ - suspend fun startWalletChild(): Result { + fun startWalletChild() { + if (!startInFlight.compareAndSet(false, true)) return + _walletChildStarting.value = true _walletChildError.value = null - val started = withContext(Dispatchers.IO) { - runCatching { requireWire().startWalletChild() } + viewModelScope.launch { + try { + val started = withContext(Dispatchers.IO) { + runCatching { requireWire().startWalletChild() } + } + started.fold( + onSuccess = { _walletChild.value = it }, + onFailure = { _walletChildError.value = it.message ?: it.toString() }, + ) + } finally { + startInFlight.set(false) + _walletChildStarting.value = false + } } - started.fold( - onSuccess = { _walletChild.value = it }, - onFailure = { _walletChildError.value = it.message ?: it.toString() }, - ) - return started } /** Stops the child and its siblings. Idempotent in the core. */ diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 247d91b..81befaf 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -303,6 +303,9 @@ const val ONION_NEEDS_ARTI_NOTICE: String = /** Shown while the first `wallet_status()` read is still in flight. */ const val READING_CHILD_NOTICE: String = "Reading the wallet child status…" +const val STARTING_CHILD_NOTICE: String = + "Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button." + /** * The caveat the on-device node is offered with, **before** Start. * @@ -388,8 +391,10 @@ fun startBlockedReason( bins: WalletChildBinaryPaths, input: WalletChildInput?, onionDaemon: Boolean = false, + starting: Boolean = false, ): String? = when { bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE + starting -> STARTING_CHILD_NOTICE input == null -> READING_CHILD_NOTICE input.running -> "The wallet child is already running." !input.configured -> "No chain source yet: a wallet child needs a daemon to dial." diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 3f54179..f8fcebe 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -74,6 +74,7 @@ fun WalletScreen( val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() val childError by vm.walletChildError.collectAsStateWithLifecycle() + val starting by vm.walletChildStarting.collectAsStateWithLifecycle() val chain by vm.chainSource.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // Resolved once per composition: the native library directory is fixed for @@ -259,7 +260,8 @@ fun WalletScreen( .onFailure { daemonError = it.message ?: it.toString() } } }, - onStart = { scope.launch { vm.startWalletChild() } }, + starting = starting, + onStart = { vm.startWalletChild() }, onStop = { scope.launch { vm.stopWalletChild() } }, ) @@ -616,6 +618,7 @@ private fun WalletChildCard( onSaveDaemon: () -> Unit, onReceiveOnly: () -> Unit, onInProcessNode: () -> Unit, + starting: Boolean = false, onStart: () -> Unit, onStop: () -> Unit, ) { @@ -626,7 +629,7 @@ private fun WalletChildCard( // read comes back: the warning and the storage line must not wait for the // poller, or the user would press Start having seen neither. val inProcess = input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE - val startWhy = startBlockedReason(bins, input, onionDaemon) + val startWhy = startBlockedReason(bins, input, onionDaemon, starting) ?: if (inProcess) chainStorageBlockedReason(nodeFreeBytes) else null val stopWhy = stopBlockedReason(input) diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index 0ad32b9..ddd412f 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -183,6 +183,14 @@ class WalletChildStatusTextTest { assertNull(startBlockedReason(bundled, input("off"))) } + @Test + fun start_is_blocked_while_start_is_in_flight() { + assertEquals( + STARTING_CHILD_NOTICE, + startBlockedReason(bundled, input("off"), starting = true), + ) + } + @Test fun start_is_allowed_again_after_the_child_exited() { assertNull( diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 24bc2fb..ef014e3 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -609,7 +609,10 @@ impl Wire { /// /// The spawn itself is synchronous inside the node: argv is built, the /// process is spawned, and a `.onion` source waits up to 20s for the SOCKS - /// listener. Call it off the main thread, like `send_tip`. + /// listener. An in-process Cuprate launch is the same shape and can take + /// much longer. That work runs on `spawn_blocking` so it does not stall the + /// UniFFI tokio worker (Android: a blocked worker is a Start tap that never + /// returns). /// /// Idempotent: a live child is reported, not respawned. Fails with /// `WireError.Failed` when no chain source is configured @@ -621,7 +624,11 @@ impl Wire { /// and call [`Wire::wallet_status`] (or start again) for the later states. pub async fn start_wallet_child(&self) -> WResult { let node = self.node()?; - node.start_wallet_child().map_err(WireError::new)?; + let blocking = node.clone(); + tokio::task::spawn_blocking(move || blocking.start_wallet_child()) + .await + .map_err(|e| WireError::new(format!("start wallet child join: {e}")))? + .map_err(WireError::new)?; let source = node.wallet_child_config().source; Ok(child_status(node.wallet_child_refresh().await, &source)) } @@ -1337,11 +1344,7 @@ mod tests { Some("sending") ); assert_eq!( - delivery_of( - "out", - Some(OutboxStatus::Failed("no route".into())) - ) - .as_deref(), + delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), Some("failed: no route") ); } @@ -1492,8 +1495,7 @@ mod tests { #[test] fn wallet_recent_transfers_on_stopped_handle_is_stopped_error() { - let err = - block_on(stopped_wire().wallet_recent_transfers(8)).expect_err("must fail"); + let err = block_on(stopped_wire().wallet_recent_transfers(8)).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } diff --git a/src/node.rs b/src/node.rs index 5e2f18f..3ce2edd 100644 --- a/src/node.rs +++ b/src/node.rs @@ -617,10 +617,12 @@ impl Node { cfg.build(self.home.join("wallet")) .map_err(|e| e.to_string())?, ); - let client = { - let store = self.store.lock().map_err(|e| e.to_string())?; - child.start(&store).map_err(|e| e.to_string())? - }; + // Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status` + // also locks the store, and a blocked poller is how Android Start looks + // like it did nothing. + let client = child + .start_unlocking_store(&self.store) + .map_err(|e| e.to_string())?; let Some(client) = client else { return Err("chain source is receive-only — nothing to start".into()); }; diff --git a/src/wallet_child.rs b/src/wallet_child.rs index d8cce49..37fc404 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -435,13 +435,36 @@ impl WalletChild { /// what gates every spawn: the SOCKS child, like the wallet child, is only /// reachable through an unlocked store. pub fn start(&self, store: &Store) -> Result> { + self.start_with_creds(|| self.creds(store)) + } + + /// Same as [`WalletChild::start`], but the store mutex is taken only for + /// the generated RPC creds — not across chain-daemon launch. + /// + /// Cuprate's `Node::launch` (and a slow `monerod`) can run for a long time. + /// Holding SQLCipher for that whole window freezes every `wallet_status` + /// poll, which on Android makes **Start** look like a no-op: the button + /// fires, status stays `off`, no error. + pub fn start_unlocking_store(&self, store: &Mutex) -> Result> { + self.start_with_creds(|| { + let guard = store + .lock() + .map_err(|e| ChildError(format!("store lock: {e}")))?; + self.creds(&guard) + }) + } + + fn start_with_creds( + &self, + creds: impl FnOnce() -> Result<(String, Zeroizing)>, + ) -> Result> { if !self.is_enabled() { return Ok(None); } if self.running() { return Err(ChildError("wallet child already running".into())); } - match self.start_children(store) { + match self.start_children(creds) { Ok(client) => Ok(client), Err(e) => { // A failure after the SOCKS child came up must not leave the @@ -452,7 +475,10 @@ impl WalletChild { } } - fn start_children(&self, store: &Store) -> Result> { + fn start_children( + &self, + creds: impl FnOnce() -> Result<(String, Zeroizing)>, + ) -> Result> { // Local chain source: own the daemon first, so the wallet child has // something to dial. Either a spawned `monerod` or the in-process // Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so @@ -485,7 +511,10 @@ impl WalletChild { _ => None, }; - let (user, pass) = self.creds(store)?; + // Creds are the only store read. Callers that pass + // `start_unlocking_store` take the mutex here, after the chain daemon + // is already up, so a long Cuprate launch does not freeze SQLCipher. + let (user, pass) = creds()?; let port = Self::pick_port()?; let login = format!("{user}:{}", pass.as_str()); let daemon = Self::daemon_address(&self.source); @@ -1135,6 +1164,14 @@ mod tests { ); } + #[test] + fn start_unlocking_store_is_the_same_as_start_for_receive_only() { + let dir = tmp_dir("none-unlock"); + let store = std::sync::Mutex::new(open_store(&dir)); + let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap(); + assert!(child.start_unlocking_store(&store).unwrap().is_none()); + } + /// A live listener for the readiness gate to dial. `arti proxy -p ` /// binds localhost only, so 127.0.0.1 is exactly what the gate probes. fn held_loopback_port() -> (std::net::TcpListener, u16) { -- 2.52.0