Compare commits

..
7 changed files with 34 additions and 103 deletions

View file

@ -40,7 +40,6 @@ 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. */
@ -619,14 +618,6 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
private val _walletChildError = MutableStateFlow<String?>(null)
val walletChildError: StateFlow<String?> = _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<Boolean> = _walletChildStarting.asStateFlow()
/** The stored chain source + binary settings, for prefilling the editor. */
private val _chainSource = MutableStateFlow<ChainConfig?>(null)
val chainSource: StateFlow<ChainConfig?> = _chainSource.asStateFlow()
@ -804,28 +795,25 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home)
/**
* 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.
* 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.
*/
fun startWalletChild() {
if (!startInFlight.compareAndSet(false, true)) return
_walletChildStarting.value = true
suspend fun startWalletChild(): Result<WalletChildStatus> {
_walletChildError.value = null
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
}
val started = withContext(Dispatchers.IO) {
runCatching { requireWire().startWalletChild() }
}
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. */

View file

@ -303,9 +303,6 @@ 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.
*
@ -391,10 +388,8 @@ 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."

View file

@ -74,7 +74,6 @@ 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
@ -260,8 +259,7 @@ fun WalletScreen(
.onFailure { daemonError = it.message ?: it.toString() }
}
},
starting = starting,
onStart = { vm.startWalletChild() },
onStart = { scope.launch { vm.startWalletChild() } },
onStop = { scope.launch { vm.stopWalletChild() } },
)
@ -618,7 +616,6 @@ private fun WalletChildCard(
onSaveDaemon: () -> Unit,
onReceiveOnly: () -> Unit,
onInProcessNode: () -> Unit,
starting: Boolean = false,
onStart: () -> Unit,
onStop: () -> Unit,
) {
@ -629,7 +626,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, starting)
val startWhy = startBlockedReason(bins, input, onionDaemon)
?: if (inProcess) chainStorageBlockedReason(nodeFreeBytes) else null
val stopWhy = stopBlockedReason(input)

View file

@ -183,14 +183,6 @@ 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(

View file

@ -609,10 +609,7 @@ 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. 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).
/// listener. Call it off the main thread, like `send_tip`.
///
/// Idempotent: a live child is reported, not respawned. Fails with
/// `WireError.Failed` when no chain source is configured
@ -624,11 +621,7 @@ impl Wire {
/// and call [`Wire::wallet_status`] (or start again) for the later states.
pub async fn start_wallet_child(&self) -> WResult<WalletChildStatus> {
let node = self.node()?;
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)?;
node.start_wallet_child().map_err(WireError::new)?;
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_refresh().await, &source))
}
@ -1344,7 +1337,11 @@ 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")
);
}
@ -1495,7 +1492,8 @@ 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:?}");
}

View file

@ -617,12 +617,10 @@ impl Node {
cfg.build(self.home.join("wallet"))
.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 client = {
let store = self.store.lock().map_err(|e| e.to_string())?;
child.start(&store).map_err(|e| e.to_string())?
};
let Some(client) = client else {
return Err("chain source is receive-only — nothing to start".into());
};

View file

@ -435,36 +435,13 @@ 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<Option<WalletClient>> {
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<Store>) -> Result<Option<WalletClient>> {
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<String>)>,
) -> Result<Option<WalletClient>> {
if !self.is_enabled() {
return Ok(None);
}
if self.running() {
return Err(ChildError("wallet child already running".into()));
}
match self.start_children(creds) {
match self.start_children(store) {
Ok(client) => Ok(client),
Err(e) => {
// A failure after the SOCKS child came up must not leave the
@ -475,10 +452,7 @@ impl WalletChild {
}
}
fn start_children(
&self,
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
) -> Result<Option<WalletClient>> {
fn start_children(&self, store: &Store) -> Result<Option<WalletClient>> {
// 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
@ -511,10 +485,7 @@ impl WalletChild {
_ => None,
};
// 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 (user, pass) = self.creds(store)?;
let port = Self::pick_port()?;
let login = format!("{user}:{}", pass.as_str());
let daemon = Self::daemon_address(&self.source);
@ -1164,14 +1135,6 @@ 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 <port>`
/// binds localhost only, so 127.0.0.1 is exactly what the gate probes.
fn held_loopback_port() -> (std::net::TcpListener, u16) {