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 3a6ac6c..cc16ef2 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -15,6 +15,7 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost import com.siriusdevops.onionwire.ui.SeedBackupGate import com.siriusdevops.onionwire.ui.WalletKeyOrigin +import com.siriusdevops.onionwire.ui.walletFailureText import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries @@ -682,6 +683,34 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun openWallet(filename: String): Result = withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } + /** + * Open a saved wallet with a passphrase the user just typed, and remember it + * (sealed) once the wallet daemon has accepted it. + * + * This is what ends a `needs_passphrase` status — a wallet created before + * the passphrase was sealed, or created on another install. The core refuses + * an empty passphrase, a name the catalogue does not hold, and an install + * with no configured wallet RPC, all before it dials anything; a passphrase + * the daemon refuses is **not** stored, so the wallet stays `needs_passphrase` + * and the prompt stays up rather than looking fixed. + * + * The passphrase goes to a UniFFI `String` parameter, so one immutable copy + * exists for the life of the call — the same limit `openWith` documents for + * the store passphrase. It is never logged, never persisted here (the core + * seals it), and the caller drops its own reference. The live probe on + * success is a one-shot read, not a second poller: the wallet screen still + * owns the only loop. + */ + suspend fun openWalletWithPassphrase(filename: String, passphrase: String): Result = + withContext(Dispatchers.IO) { + runCatching { requireWire().openWalletWithPassphrase(filename, passphrase) } + }.onSuccess { + // One live probe, so `needs_passphrase` flips and the prompt comes + // off the screen without waiting for the next tick of a loop that is + // only running while the wallet screen is up. + refreshWalletChild() + } + /** * The **open** wallet's private keys, for the saved-wallets screen. * @@ -858,7 +887,7 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { val result = withContext(Dispatchers.IO) { runCatching { read() } } result.fold( onSuccess = { _walletChild.value = it }, - onFailure = { _walletChildError.value = it.message ?: it.toString() }, + onFailure = { _walletChildError.value = walletFailureText(it.message ?: it.toString()) }, ) } @@ -1002,7 +1031,9 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } started.fold( onSuccess = { _walletChild.value = it }, - onFailure = { _walletChildError.value = it.message ?: it.toString() }, + onFailure = { + _walletChildError.value = walletFailureText(it.message ?: it.toString()) + }, ) } finally { startInFlight.set(false) @@ -1019,7 +1050,7 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } stopped.fold( onSuccess = { refreshWalletChild() }, - onFailure = { _walletChildError.value = it.message ?: it.toString() }, + onFailure = { _walletChildError.value = walletFailureText(it.message ?: it.toString()) }, ) return stopped } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt index d041575..fbbc9fa 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -1,5 +1,9 @@ package com.siriusdevops.onionwire.ui +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.view.WindowManager import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -18,6 +22,7 @@ import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -33,7 +38,10 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel @@ -123,6 +131,148 @@ internal fun walletSecretsBlockedReason( else -> null } +// --------------------------------------------------------------------------- +// A wallet that needs its passphrase, and never the daemon's own words +// --------------------------------------------------------------------------- + +/** + * The daemon's own phrase for "this RPC has no wallet file open" + * (`monero-wallet-rpc` answers `-13 No wallet file`). + * + * Matched case-insensitively anywhere in a failure string: the wallet client + * strips the JSON envelope and keeps only `error.message`, so the bare sentence + * is what actually reaches Kotlin — sometimes wrapped in the core's own + * `wallet file X is not open — …` prefix. + */ +private val NO_WALLET_FILE = Regex("no wallet file", RegexOption.IGNORE_CASE) + +/** + * A bare wallet-RPC error code. `-13` is + * `WALLET_RPC_ERROR_CODE_NO_WALLET_FILE`; the lookarounds keep it from firing + * on a longer number or on a negative offset like `-135`. + */ +private val RAW_RPC_CODE = Regex("""(? null + NO_WALLET_FILE.containsMatchIn(text) || RAW_RPC_CODE.containsMatchIn(text) -> + WALLET_NOT_OPEN_TEXT + RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT + else -> text + } +} + +/** + * Whether the manager screen must ask for a wallet-file passphrase. + * + * `needs_passphrase` is the core's own word for "a saved wallet is configured, + * and this install holds no passphrase that opens it" — a wallet created before + * the passphrase was sealed, or created on another install. It is not a start + * failure, and the child keeps running. + * + * `walletOpen` is the second half of the same statement and wins: a child that + * has a wallet file open has nothing to ask for, whatever the flag said a + * moment ago. Both come from one `WalletChildStatus`, so there is no second + * source of truth about which wallet is open. + */ +internal fun walletPassphrasePromptVisible(needsPassphrase: Boolean, walletOpen: Boolean): Boolean = + needsPassphrase && !walletOpen + +/** + * Whether the prompt's submit is actionable. + * + * A file name is required because the open is per-file (`open_wallet` on the + * file the child is pointed at); a blank passphrase is refused by the core + * anyway, so the button stays dead rather than round-tripping a guaranteed + * failure. An in-flight open is not re-submitted: it restarts the wallet child. + */ +internal fun walletPassphraseSubmitEnabled( + activeFilename: String?, + typed: String, + inFlight: Boolean, +): Boolean = !inFlight && activeFilename != null && typed.isNotEmpty() + +/** + * Why the prompt cannot be submitted yet, in words — or `null` when it can. + * + * The two reasons are different states of the world and are not collapsed: + * nothing typed is the user's own gap, no pointed-at file is the child's. + */ +internal fun walletPassphraseBlockedReason( + activeFilename: String?, + typed: String, +): String? = when { + activeFilename == null -> + "the wallet child is not pointed at a wallet file yet — open one from the list below" + typed.isEmpty() -> "type the passphrase for this wallet file" + else -> null +} + +/** + * Why the wallet child has nothing open, in this app's words — or `null` when + * it has a wallet open, or no child is running to hold one. + * + * A live `monero-wallet-rpc` is not a usable wallet: it starts with no wallet + * file open, and every read then answers `-13 No wallet file`. The status line + * reports the child's state, not that, so the screen says it here and names the + * one screen that fixes it. `needsPassphrase` is the case where the child is + * pointed at a file this install holds no passphrase for — the fix is a typed + * passphrase, not a different wallet, and the prompt lives on the manager + * screen. + */ +internal fun walletChildOpenHint( + childRunning: Boolean, + walletOpen: Boolean, + needsPassphrase: Boolean, +): String? = when { + !childRunning || walletOpen -> null + needsPassphrase -> + "No wallet is open in the wallet child: it needs the passphrase for the file it is " + + "pointed at. Open it on the Saved wallets screen, where the prompt is." + else -> + "No wallet is open in the wallet child yet. Open a saved wallet on the Saved wallets " + + "screen, or create or import one here." +} + /** * The saved-wallet catalogue: every wallet this install remembers, which one is * open now, and — for that one — its recovery phrase and private keys. @@ -161,6 +311,14 @@ fun WalletManagerScreen( /** The file name currently being opened, so the row can say so. */ var opening by remember { mutableStateOf(null) } + // The wallet-file passphrase, for a wallet this install holds none for. + // Masked on screen, never copied (there is no copy action, exactly as the + // seed card has none), never logged, never persisted, and wiped when the + // screen goes — see the `DisposableEffect` below. + var passphrase by remember { mutableStateOf("") } + var passphraseError by remember { mutableStateOf(null) } + var openingWithPassphrase by remember { mutableStateOf(false) } + // The seed on the blocking card, and the typed confirm word. Neither is // persisted: a spend key lives in this composition and nowhere else. var seed by remember { mutableStateOf(null) } @@ -178,7 +336,7 @@ fun WalletManagerScreen( }, onFailure = { rows = null - listError = it.message ?: it.toString() + listError = walletFailureText(it.message ?: it.toString()) }, ) vm.activeWalletFilename().fold( @@ -188,7 +346,7 @@ fun WalletManagerScreen( // "no wallet is open", and it must not be rendered as one. active = null if (listError == null) { - listError = it.message ?: it.toString() + listError = walletFailureText(it.message ?: it.toString()) } }, ) @@ -202,12 +360,44 @@ fun WalletManagerScreen( opening = filename vm.openWallet(filename).fold( onSuccess = { reload() }, - onFailure = { actionError = it.message ?: it.toString() }, + onFailure = { actionError = walletFailureText(it.message ?: it.toString()) }, ) opening = null } } + /** + * "Open this wallet": the one-time passphrase for a wallet this install + * holds none for. + * + * `openWalletWithPassphrase` is the parent card's binding. It is a per-file + * call, so it is handed the file the child is already pointed at — the same + * `active_wallet_filename()` the list marks in use, not a second idea of + * which wallet is open. The core seals the passphrase only once a live + * daemon has accepted it, so a wrong one leaves the prompt up rather than + * looking fixed. + */ + fun openWithPassphrase() { + val file = active ?: return + if (openingWithPassphrase || passphrase.isEmpty()) return + scope.launch { + passphraseError = null + openingWithPassphrase = true + vm.openWalletWithPassphrase(file, passphrase).fold( + onSuccess = { + // The secret has done its job. Drop it before anything else + // can see it, then re-read: the live probe in the ViewModel + // is what flips `needs_passphrase` and takes this card off + // the screen. + passphrase = "" + reload() + }, + onFailure = { passphraseError = walletFailureText(it.message ?: it.toString()) }, + ) + openingWithPassphrase = false + } + } + /** * "Recovery phrase": re-read the open wallet's 25 words and put them on the * existing blocking card. Same treatment as the wallet screen's "Back up @@ -221,7 +411,7 @@ fun WalletManagerScreen( seed = it seedConfirm = "" }, - onFailure = { actionError = it.message ?: it.toString() }, + onFailure = { actionError = walletFailureText(it.message ?: it.toString()) }, ) } } @@ -237,7 +427,7 @@ fun WalletManagerScreen( keysError = null vm.walletKeys().fold( onSuccess = { keys = it }, - onFailure = { keysError = it.message ?: it.toString() }, + onFailure = { keysError = walletFailureText(it.message ?: it.toString()) }, ) } } @@ -252,18 +442,33 @@ fun WalletManagerScreen( } // Nothing here is `rememberSaveable`, so leaving the screen drops the - // composition's state — including the seed and the keys. Dropping the - // reference is the strongest wipe a Kotlin String allows (see - // `SeedBackupCard`); this makes it explicit rather than incidental. + // composition's state — including the seed, the keys and the wallet-file + // passphrase. Dropping the reference is the strongest wipe a Kotlin String + // allows (see `SeedBackupCard`); this makes it explicit rather than + // incidental. DisposableEffect(Unit) { onDispose { seed = null seedConfirm = "" keys = null keysError = null + passphrase = "" + passphraseError = null } } + // Screenshots and the recents thumbnail. This screen renders a spend key and + // asks for the passphrase that opens a wallet file, so it takes the same + // `FLAG_SECURE` treatment the seed path wants — set while this composition is + // up, cleared when it goes, so no other screen inherits it. (No screen in + // this app set the flag before this change; see the PR body.) + val view = LocalView.current + DisposableEffect(view) { + val window = view.context.findActivity()?.window + window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } + } + val walletReadable = walletChildReadable(child?.state) Scaffold( @@ -346,6 +551,30 @@ fun WalletManagerScreen( actionError?.let { ErrorText(it) } + // The one-time passphrase for a wallet this install holds none for. + // A wallet created before the passphrase was sealed reports + // `needs_passphrase` and answers every read with `-13 No wallet + // file`, so without this the row tap looks like it did nothing. + if (walletPassphrasePromptVisible( + needsPassphrase = child?.needsPassphrase == true, + walletOpen = child?.walletOpen == true, + ) + ) { + WalletPassphraseCard( + filename = active, + typed = passphrase, + onTyped = { + passphrase = it + passphraseError = null + }, + inFlight = openingWithPassphrase, + childRunning = child?.running == true, + blockedReason = walletPassphraseBlockedReason(active, passphrase), + error = passphraseError, + onSubmit = { openWithPassphrase() }, + ) + } + val listed = rows when { // A read failure is not an empty catalogue, and the two must @@ -507,6 +736,107 @@ private fun WalletRowCard( } } +/** + * The one-time passphrase for a wallet file this install holds no passphrase + * for. + * + * Masked, and with no copy action at all — the same rule as [SeedBackupCard], + * for the same reason: the Android clipboard is readable by every other app and + * by the clipboard history on Android 13+, and this string opens a spend-capable + * wallet file. It is never logged, never persisted, and the caller drops it when + * the screen goes. + * + * Submit is dead while the wallet child is not running: the core verifies a + * passphrase against a live daemon and refuses to seal an unverified one, so a + * tap there could only fail. When the child *is* up — including `connecting`, + * whose RPC has not answered yet — the core restarts it onto the file with this + * passphrase, which is exactly the fix. + */ +@Composable +private fun WalletPassphraseCard( + filename: String?, + typed: String, + onTyped: (String) -> Unit, + inFlight: Boolean, + childRunning: Boolean, + blockedReason: String?, + error: String?, + onSubmit: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp) + .testTag("wallet-passphrase-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("This wallet needs its passphrase", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text( + "The wallet child is pointed at ${filename ?: "a wallet file"} but this install " + + "holds no passphrase that opens it — the wallet was created before the " + + "passphrase was stored, or on another device. Type it once: the wallet " + + "opens, and later starts reopen it on their own.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + // Masked on screen: this string opens a spend-capable wallet. + visualTransformation = PasswordVisualTransformation(), + label = { Text("wallet passphrase") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-passphrase-input"), + ) + Spacer(Modifier.height(4.dp)) + Text( + "Never copied to the clipboard, never logged, and dropped when you leave this screen.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (!childRunning) { + Spacer(Modifier.height(4.dp)) + Text( + "the wallet child is not running — start it on the wallet screen, then come back", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + error?.let { + Spacer(Modifier.height(6.dp)) + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + blockedReason?.let { + Spacer(Modifier.height(4.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button( + onClick = onSubmit, + enabled = childRunning && + walletPassphraseSubmitEnabled(filename, typed, inFlight), + modifier = Modifier.testTag("wallet-passphrase-submit"), + ) { Text(if (inFlight) "Opening…" else "Open this wallet") } + } + } + } +} + /** * The open wallet's private keys, shown only after an explicit tap. * @@ -582,3 +912,16 @@ private fun ErrorText(text: String) { modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) } + +/** + * The Activity behind a view's context, for the window flags. + * + * `view.context` is the Activity for a `setContent` root, but a wrapped context + * (a themed wrapper, a `ContextThemeWrapper` from a host) is a real case and + * silently skipping `FLAG_SECURE` because of it would be a silent leak. + */ +private tailrec fun Context.findActivity(): Activity? = when (this) { + is Activity -> this + is ContextWrapper -> baseContext.findActivity() + else -> null +} 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 f6ea31c..e03b744 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 @@ -104,7 +104,7 @@ fun WalletScreen( suspend fun reload() { runCatching { balance = vm.walletBalance() } - .onFailure { error = it.message ?: it.toString() } + .onFailure { error = walletFailureText(it.message ?: it.toString()) } runCatching { address = vm.walletReceiveAddress() } runCatching { transfers = vm.walletRecentTransfers(25) } } @@ -124,7 +124,7 @@ fun WalletScreen( pendingSeed = seed seedConfirm = "" }, - onFailure = { error = it.message ?: it.toString() }, + onFailure = { error = walletFailureText(it.message ?: it.toString()) }, ) } } @@ -307,6 +307,8 @@ fun WalletScreen( actionError = childError, daemonText = daemonText, daemonError = daemonError, + walletOpen = child?.walletOpen == true, + needsPassphrase = child?.needsPassphrase == true, onDaemonText = { daemonText = it daemonError = null @@ -319,7 +321,7 @@ fun WalletScreen( daemonError = null scope.launch { vm.saveRemoteDaemon(parsed.host, parsed.port, bins) - .onFailure { daemonError = it.message ?: it.toString() } + .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } } } }, @@ -327,14 +329,14 @@ fun WalletScreen( daemonError = null scope.launch { vm.setReceiveOnly(bins) - .onFailure { daemonError = it.message ?: it.toString() } + .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } } }, onInProcessNode = { mainnet, prune -> daemonError = null scope.launch { vm.setInProcessCuprate(bins, mainnet, prune) - .onFailure { daemonError = it.message ?: it.toString() } + .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } .onSuccess { // The mode buttons used to only persist the choice, // which read as a no-op besides the storage line. @@ -398,7 +400,7 @@ fun WalletScreen( composer = null reload() }, - onFailure = { error = it.message ?: it.toString() }, + onFailure = { error = walletFailureText(it.message ?: it.toString()) }, ) } }, @@ -419,7 +421,7 @@ fun WalletScreen( setup = null scope.launch { reload() } }, - onError = { error = it }, + onError = { error = walletFailureText(it) }, create = { pw -> vm.createWallet(pw) }, importWallet = { pw, seed -> vm.importWallet(pw, seed) }, scope = scope, @@ -849,6 +851,13 @@ private fun WalletChildCard( actionError: String?, daemonText: String, daemonError: String?, + /** + * The core's `wallet_open` / `needs_passphrase`, straight off the same + * `WalletChildStatus` the status line is drawn from — not a second idea of + * which wallet is open. + */ + walletOpen: Boolean, + needsPassphrase: Boolean, onDaemonText: (String) -> Unit, onSaveDaemon: () -> Unit, onReceiveOnly: () -> Unit, @@ -875,6 +884,14 @@ private fun WalletChildCard( null } val stopWhy = stopBlockedReason(input) + // A live child with no wallet file open answers every read with the daemon's + // own `-13 No wallet file`. Say that in this app's words, here, rather than + // letting the raw string arrive later on whichever card asked. + val openHint = walletChildOpenHint( + childRunning = input?.running == true, + walletOpen = walletOpen, + needsPassphrase = needsPassphrase, + ) Card( modifier = Modifier @@ -930,6 +947,21 @@ private fun WalletChildCard( ) } + // "No wallet file open" is a state of a live child, not a failure of + // the last call, so it is said here rather than left to surface as + // the daemon's `-13` on whichever card asked for a read. + openHint?.let { + Spacer(Modifier.height(6.dp)) + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-child-no-wallet"), + ) + } + // What the user can fix from here: which daemon the child dials. Spacer(Modifier.height(8.dp)) OutlinedTextField( @@ -1058,8 +1090,11 @@ private fun WalletChildCard( } // The last thing the core or the RPC call said. Sticky until the - // user acts, like the chat screen's load error. - val failure = input?.lastError ?: actionError ?: daemonError + // user acts, like the chat screen's load error. Filtered through + // `walletFailureText`: the daemon's own `-13 No wallet file` / JSON + // answer is not a sentence about this app and never reaches the + // screen. + val failure = walletFailureText(input?.lastError) ?: actionError ?: daemonError failure?.let { Spacer(Modifier.height(6.dp)) Text( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt index 99a35e4..a095523 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -150,4 +150,200 @@ class WalletManagerTest { assertEquals("date unknown", walletRowDate(0L)) assertEquals("date unknown", walletRowDate(-1L)) } + + // --- a wallet this install holds no passphrase for ----------------------- + // + // `needs_passphrase` is the core's own word for "a saved wallet is + // configured and nothing here opens it" — the pre-parent-change wallet. The + // prompt is the only way it becomes openable, so the decision to show it is + // asserted here rather than in a Compose test. + + @Test + fun a_wallet_with_no_stored_passphrase_asks_for_one() { + assertTrue(walletPassphrasePromptVisible(needsPassphrase = true, walletOpen = false)) + } + + @Test + fun an_open_wallet_is_never_asked_for_its_passphrase() { + assertFalse(walletPassphrasePromptVisible(needsPassphrase = false, walletOpen = true)) + } + + @Test + fun an_open_wallet_wins_over_a_stale_needs_passphrase_flag() { + // One `WalletChildStatus` carries both, and "there is a wallet open" is + // the stronger statement: asking for a passphrase the child has already + // used would look like the open failed. + assertFalse(walletPassphrasePromptVisible(needsPassphrase = true, walletOpen = true)) + } + + @Test + fun a_child_with_nothing_to_open_asks_for_nothing() { + // No child, or one never pointed at a file: there is no passphrase to + // ask for yet, and the list below is what the user acts on. + assertFalse(walletPassphrasePromptVisible(needsPassphrase = false, walletOpen = false)) + } + + @Test + fun the_prompt_can_be_submitted_once_a_file_and_a_passphrase_are_known() { + assertTrue( + walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "pw", inFlight = false), + ) + } + + @Test + fun a_blank_passphrase_leaves_submit_dead() { + assertFalse( + walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "", inFlight = false), + ) + } + + @Test + fun submit_is_dead_while_an_open_is_in_flight() { + // Re-submitting restarts the wallet child: one open at a time. + assertFalse( + walletPassphraseSubmitEnabled(activeFilename = openFile, typed = "pw", inFlight = true), + ) + } + + @Test + fun no_pointed_at_file_means_submit_is_dead_and_says_why() { + assertFalse( + walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false), + ) + val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw") + assertTrue("got '$why'", why != null && why.contains("not pointed at")) + // The two reasons are different fixes and must not read alike. + assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = "")) + } + + @Test + fun a_typed_passphrase_with_a_file_has_nothing_to_explain() { + assertNull(walletPassphraseBlockedReason(activeFilename = openFile, typed = "pw")) + } + + @Test + fun nothing_typed_is_the_other_reason() { + val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "") + assertTrue("got '$why'", why != null && why.contains("type the passphrase")) + } + + // --- the daemon's own words never reach the screen ----------------------- + + /** The three things a user must never be shown, in one place. */ + private fun assertNoRawRpc(text: String) { + assertFalse("raw RPC code on screen: $text", text.contains("-13")) + assertFalse("daemon phrase on screen: $text", text.contains("No wallet file")) + assertFalse("JSON on screen: $text", text.contains("{")) + assertFalse("JSON on screen: $text", text.contains("\"error\"")) + } + + @Test + fun the_daemons_no_wallet_file_never_reaches_the_screen() { + // What actually arrives: `parse_json_rpc` keeps `error.message` and + // drops the envelope, so the bare sentence is the common case. + val shown = walletFailureText("No wallet file") + assertEquals(WALLET_NOT_OPEN_TEXT, shown) + assertNoRawRpc(shown!!) + } + + @Test + fun a_bare_rpc_code_never_reaches_the_screen() { + val shown = walletFailureText("wallet rpc error -13") + assertEquals(WALLET_NOT_OPEN_TEXT, shown) + assertNoRawRpc(shown!!) + } + + @Test + fun a_raw_json_answer_never_reaches_the_screen() { + val raw = """{"error": {"code": -13, "message": "No wallet file"}}""" + val shown = walletFailureText(raw) + assertNoRawRpc(shown!!) + // The envelope is replaced, and because this one *is* the no-wallet-file + // answer the user gets the actionable text rather than the generic one. + assertEquals(WALLET_NOT_OPEN_TEXT, shown) + } + + @Test + fun a_json_answer_is_replaced_even_when_it_names_another_code() { + val shown = walletFailureText("""{"error":{"code":-1,"message":"busy"}}""") + assertEquals(WALLET_DAEMON_REFUSED_TEXT, shown) + assertNoRawRpc(shown!!) + } + + @Test + fun a_wrapped_daemon_phrase_is_still_replaced() { + // The core's open path prefixes the RPC's own message, and the prefix + // is no excuse to hand the daemon's words to the user. + val shown = walletFailureText( + "wallet file onionwire-1 is not open — the RPC refused its passphrase (No wallet file)", + ) + assertEquals(WALLET_NOT_OPEN_TEXT, shown) + assertNoRawRpc(shown!!) + } + + @Test + fun the_core_own_refusals_are_passed_through() { + // These are written for a person, carry no secret, and are the whole + // point of the message — replacing them would hide the reason. + val refusal = "no saved wallet in onionwire-9" + assertEquals(refusal, walletFailureText(refusal)) + val stopped = "node stopped: wallet_keys called on a shut-down node" + assertEquals(stopped, walletFailureText(stopped)) + } + + @Test + fun a_number_that_merely_starts_with_minus_thirteen_is_not_a_code() { + assertEquals("offset -135", walletFailureText("offset -135")) + assertEquals("height -1300", walletFailureText("height -1300")) + } + + @Test + fun nothing_to_show_is_null() { + assertNull(walletFailureText(null)) + assertNull(walletFailureText("")) + assertNull(walletFailureText(" ")) + } + + @Test + fun the_replacement_texts_carry_no_raw_rpc_of_their_own() { + assertNoRawRpc(WALLET_NOT_OPEN_TEXT) + assertNoRawRpc(WALLET_DAEMON_REFUSED_TEXT) + } + + // --- "there is no wallet open", on the wallet screen --------------------- + + @Test + fun a_live_child_with_no_wallet_says_what_to_do() { + val hint = walletChildOpenHint( + childRunning = true, + walletOpen = false, + needsPassphrase = false, + ) + assertTrue("got '$hint'", hint != null && hint.contains("No wallet is open")) + assertNoRawRpc(hint!!) + } + + @Test + fun a_child_that_needs_a_passphrase_says_where_the_prompt_is() { + val hint = walletChildOpenHint( + childRunning = true, + walletOpen = false, + needsPassphrase = true, + ) + assertTrue("got '$hint'", hint != null && hint.contains("Saved wallets")) + assertNoRawRpc(hint!!) + } + + @Test + fun an_open_wallet_has_no_hint() { + assertNull(walletChildOpenHint(childRunning = true, walletOpen = true, needsPassphrase = false)) + // An open wallet wins over a stale flag, same as the prompt. + assertNull(walletChildOpenHint(childRunning = true, walletOpen = true, needsPassphrase = true)) + } + + @Test + fun no_running_child_has_no_hint() { + // The status line already says off/exited and Start is right there. + assertNull(walletChildOpenHint(childRunning = false, walletOpen = false, needsPassphrase = true)) + } }