android: ask for the wallet passphrase, and stop printing RPC errors #150

4 changed files with 721 additions and 21 deletions

View file

@ -15,6 +15,7 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost import com.siriusdevops.onionwire.keepalive.NodeHost
import com.siriusdevops.onionwire.ui.SeedBackupGate import com.siriusdevops.onionwire.ui.SeedBackupGate
import com.siriusdevops.onionwire.ui.WalletKeyOrigin import com.siriusdevops.onionwire.ui.WalletKeyOrigin
import com.siriusdevops.onionwire.ui.walletFailureText
import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.ChainStorage
import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE
import com.siriusdevops.onionwire.wallet.WalletChildBinaries import com.siriusdevops.onionwire.wallet.WalletChildBinaries
@ -682,6 +683,34 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun openWallet(filename: String): Result<Unit> = suspend fun openWallet(filename: String): Result<Unit> =
withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } 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<Unit> =
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. * 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() } } val result = withContext(Dispatchers.IO) { runCatching { read() } }
result.fold( result.fold(
onSuccess = { _walletChild.value = it }, 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( started.fold(
onSuccess = { _walletChild.value = it }, onSuccess = { _walletChild.value = it },
onFailure = { _walletChildError.value = it.message ?: it.toString() }, onFailure = {
_walletChildError.value = walletFailureText(it.message ?: it.toString())
},
) )
} finally { } finally {
startInFlight.set(false) startInFlight.set(false)
@ -1019,7 +1050,7 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
} }
stopped.fold( stopped.fold(
onSuccess = { refreshWalletChild() }, onSuccess = { refreshWalletChild() },
onFailure = { _walletChildError.value = it.message ?: it.toString() }, onFailure = { _walletChildError.value = walletFailureText(it.message ?: it.toString()) },
) )
return stopped return stopped
} }

View file

@ -1,5 +1,9 @@
package com.siriusdevops.onionwire.ui 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.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@ -18,6 +22,7 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
@ -33,7 +38,10 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier 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.font.FontFamily
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel import com.siriusdevops.onionwire.WireViewModel
@ -123,6 +131,148 @@ internal fun walletSecretsBlockedReason(
else -> null 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("""(?<![\d-])-13(?!\d)""")
/**
* A JSON envelope — the raw RPC answer itself rather than a sentence about it.
* Either an object/array, or a quoted key of the JSON-RPC error shape.
*/
private val RAW_JSON = Regex("""[{}]|\[\s*\{|"(error|code|message|result|jsonrpc)"\s*:""")
/** Shown instead of the daemon's `-13` / `No wallet file` / JSON answer. */
const val WALLET_NOT_OPEN_TEXT: String =
"No wallet is open in the wallet child yet. Open one from the list below — a wallet that " +
"needs a passphrase asks for it here — and the balance, address and backups work again."
/** Shown instead of a raw JSON refusal that names no condition the user can act on. */
const val WALLET_DAEMON_REFUSED_TEXT: String =
"The wallet daemon refused that request and gave no readable reason. Check the wallet child " +
"on the wallet screen, then try again."
/**
* A failure string safe to put on screen, or `null` when there is nothing to
* show.
*
* The wallet daemon answers in JSON, and the wallet client hands the parsed
* `error.message` straight up the stack: `-13 No wallet file` reaches Kotlin as
* the bare sentence, and a failure that never got that far can still arrive as
* the envelope itself. Neither is a sentence about this app, so both are
* replaced — the user gets told whether a wallet is open and what to do about
* it, which is the only thing that changes what they tap next.
*
* Anything else is passed through verbatim: the core's own refusals ("no saved
* wallet in onionwire-9", "node stopped: …", "wallet file X is not open — the
* RPC refused its passphrase (…)") are already written for a person and carry
* no secret. This is a *display* filter, not an error channel — nothing here
* decides whether an action succeeded.
*
* Fail-closed by construction: an over-eager match only downgrades a readable
* message to a plainer one. It can never leak the raw string it did not
* recognise as raw.
*/
internal fun walletFailureText(raw: String?): String? {
val text = raw?.trim().orEmpty()
return when {
text.isEmpty() -> 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 * The saved-wallet catalogue: every wallet this install remembers, which one is
* open now, and — for that one — its recovery phrase and private keys. * 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. */ /** The file name currently being opened, so the row can say so. */
var opening by remember { mutableStateOf<String?>(null) } var opening by remember { mutableStateOf<String?>(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<String?>(null) }
var openingWithPassphrase by remember { mutableStateOf(false) }
// The seed on the blocking card, and the typed confirm word. Neither is // The seed on the blocking card, and the typed confirm word. Neither is
// persisted: a spend key lives in this composition and nowhere else. // persisted: a spend key lives in this composition and nowhere else.
var seed by remember { mutableStateOf<String?>(null) } var seed by remember { mutableStateOf<String?>(null) }
@ -178,7 +336,7 @@ fun WalletManagerScreen(
}, },
onFailure = { onFailure = {
rows = null rows = null
listError = it.message ?: it.toString() listError = walletFailureText(it.message ?: it.toString())
}, },
) )
vm.activeWalletFilename().fold( vm.activeWalletFilename().fold(
@ -188,7 +346,7 @@ fun WalletManagerScreen(
// "no wallet is open", and it must not be rendered as one. // "no wallet is open", and it must not be rendered as one.
active = null active = null
if (listError == null) { if (listError == null) {
listError = it.message ?: it.toString() listError = walletFailureText(it.message ?: it.toString())
} }
}, },
) )
@ -202,12 +360,44 @@ fun WalletManagerScreen(
opening = filename opening = filename
vm.openWallet(filename).fold( vm.openWallet(filename).fold(
onSuccess = { reload() }, onSuccess = { reload() },
onFailure = { actionError = it.message ?: it.toString() }, onFailure = { actionError = walletFailureText(it.message ?: it.toString()) },
) )
opening = null 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 * "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 * existing blocking card. Same treatment as the wallet screen's "Back up
@ -221,7 +411,7 @@ fun WalletManagerScreen(
seed = it seed = it
seedConfirm = "" seedConfirm = ""
}, },
onFailure = { actionError = it.message ?: it.toString() }, onFailure = { actionError = walletFailureText(it.message ?: it.toString()) },
) )
} }
} }
@ -237,7 +427,7 @@ fun WalletManagerScreen(
keysError = null keysError = null
vm.walletKeys().fold( vm.walletKeys().fold(
onSuccess = { keys = it }, 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 // Nothing here is `rememberSaveable`, so leaving the screen drops the
// composition's state — including the seed and the keys. Dropping the // composition's state — including the seed, the keys and the wallet-file
// reference is the strongest wipe a Kotlin String allows (see // passphrase. Dropping the reference is the strongest wipe a Kotlin String
// `SeedBackupCard`); this makes it explicit rather than incidental. // allows (see `SeedBackupCard`); this makes it explicit rather than
// incidental.
DisposableEffect(Unit) { DisposableEffect(Unit) {
onDispose { onDispose {
seed = null seed = null
seedConfirm = "" seedConfirm = ""
keys = null keys = null
keysError = 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) val walletReadable = walletChildReadable(child?.state)
Scaffold( Scaffold(
@ -346,6 +551,30 @@ fun WalletManagerScreen(
actionError?.let { ErrorText(it) } 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 val listed = rows
when { when {
// A read failure is not an empty catalogue, and the two must // 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. * 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), 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
}

View file

@ -104,7 +104,7 @@ fun WalletScreen(
suspend fun reload() { suspend fun reload() {
runCatching { balance = vm.walletBalance() } runCatching { balance = vm.walletBalance() }
.onFailure { error = it.message ?: it.toString() } .onFailure { error = walletFailureText(it.message ?: it.toString()) }
runCatching { address = vm.walletReceiveAddress() } runCatching { address = vm.walletReceiveAddress() }
runCatching { transfers = vm.walletRecentTransfers(25) } runCatching { transfers = vm.walletRecentTransfers(25) }
} }
@ -124,7 +124,7 @@ fun WalletScreen(
pendingSeed = seed pendingSeed = seed
seedConfirm = "" seedConfirm = ""
}, },
onFailure = { error = it.message ?: it.toString() }, onFailure = { error = walletFailureText(it.message ?: it.toString()) },
) )
} }
} }
@ -307,6 +307,8 @@ fun WalletScreen(
actionError = childError, actionError = childError,
daemonText = daemonText, daemonText = daemonText,
daemonError = daemonError, daemonError = daemonError,
walletOpen = child?.walletOpen == true,
needsPassphrase = child?.needsPassphrase == true,
onDaemonText = { onDaemonText = {
daemonText = it daemonText = it
daemonError = null daemonError = null
@ -319,7 +321,7 @@ fun WalletScreen(
daemonError = null daemonError = null
scope.launch { scope.launch {
vm.saveRemoteDaemon(parsed.host, parsed.port, bins) 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 daemonError = null
scope.launch { scope.launch {
vm.setReceiveOnly(bins) vm.setReceiveOnly(bins)
.onFailure { daemonError = it.message ?: it.toString() } .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) }
} }
}, },
onInProcessNode = { mainnet, prune -> onInProcessNode = { mainnet, prune ->
daemonError = null daemonError = null
scope.launch { scope.launch {
vm.setInProcessCuprate(bins, mainnet, prune) vm.setInProcessCuprate(bins, mainnet, prune)
.onFailure { daemonError = it.message ?: it.toString() } .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) }
.onSuccess { .onSuccess {
// The mode buttons used to only persist the choice, // The mode buttons used to only persist the choice,
// which read as a no-op besides the storage line. // which read as a no-op besides the storage line.
@ -398,7 +400,7 @@ fun WalletScreen(
composer = null composer = null
reload() reload()
}, },
onFailure = { error = it.message ?: it.toString() }, onFailure = { error = walletFailureText(it.message ?: it.toString()) },
) )
} }
}, },
@ -419,7 +421,7 @@ fun WalletScreen(
setup = null setup = null
scope.launch { reload() } scope.launch { reload() }
}, },
onError = { error = it }, onError = { error = walletFailureText(it) },
create = { pw -> vm.createWallet(pw) }, create = { pw -> vm.createWallet(pw) },
importWallet = { pw, seed -> vm.importWallet(pw, seed) }, importWallet = { pw, seed -> vm.importWallet(pw, seed) },
scope = scope, scope = scope,
@ -849,6 +851,13 @@ private fun WalletChildCard(
actionError: String?, actionError: String?,
daemonText: String, daemonText: String,
daemonError: 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, onDaemonText: (String) -> Unit,
onSaveDaemon: () -> Unit, onSaveDaemon: () -> Unit,
onReceiveOnly: () -> Unit, onReceiveOnly: () -> Unit,
@ -875,6 +884,14 @@ private fun WalletChildCard(
null null
} }
val stopWhy = stopBlockedReason(input) 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( Card(
modifier = Modifier 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. // What the user can fix from here: which daemon the child dials.
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(8.dp))
OutlinedTextField( OutlinedTextField(
@ -1058,8 +1090,11 @@ private fun WalletChildCard(
} }
// The last thing the core or the RPC call said. Sticky until the // The last thing the core or the RPC call said. Sticky until the
// user acts, like the chat screen's load error. // user acts, like the chat screen's load error. Filtered through
val failure = input?.lastError ?: actionError ?: daemonError // `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 { failure?.let {
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
Text( Text(
@ -1095,6 +1130,17 @@ private fun CuprateModeButton(
/** /**
* The SDK record as the pure model `WalletChildStatusText.kt` renders. Field for * The SDK record as the pure model `WalletChildStatusText.kt` renders. Field for
* field, nothing inferred. * field, nothing inferred.
*
* `lastError` is the one field that is not verbatim. It is the core's
* `wallet_status().last_error`, which is the *daemon's* own words on the path
* this screen exists for: a live child with no wallet open answers `-13 No
* wallet file`, and `parse_json_rpc` strips the envelope and keeps that bare
* sentence. The status line renders this field — `walletChildLine`, and through
* it `walletChildStatusDescription` for the screen reader — so the filter
* belongs here, at the seam where the SDK record becomes the Kotlin model,
* rather than at one of the render sites. `walletFailureText` is idempotent on
* its own replacement texts, so the second pass on the sticky error card is
* stable.
*/ */
internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput( internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput(
state = state, state = state,
@ -1106,7 +1152,7 @@ internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput(
nodeState = nodeState, nodeState = nodeState,
height = height, height = height,
targetHeight = targetHeight, targetHeight = targetHeight,
lastError = lastError, lastError = walletFailureText(lastError),
) )
/** Generate a QR bitmap for the given URI string. Returns null on encode failure. */ /** Generate a QR bitmap for the given URI string. Returns null on encode failure. */

View file

@ -5,6 +5,7 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
import uniffi.onionwire_sdk.WalletChildStatus
/** /**
* The saved-wallets screen's rules, on the JVM. * The saved-wallets screen's rules, on the JVM.
@ -150,4 +151,283 @@ class WalletManagerTest {
assertEquals("date unknown", walletRowDate(0L)) assertEquals("date unknown", walletRowDate(0L))
assertEquals("date unknown", walletRowDate(-1L)) 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))
}
// --- the status line itself, from the record the screen renders -----------
/**
* The child's record as the SDK hands it over, for the state this card
* exists for: a live `connecting` child pointed at a wallet file this
* install holds no passphrase for. Its probe answers `-13 No wallet file`
* and `parse_json_rpc` keeps only `error.message`, so the bare sentence is
* what the core reports as `last_error`.
*/
private fun sdkStatus(
state: String = "connecting",
running: Boolean = true,
walletOpen: Boolean = false,
needsPassphrase: Boolean = true,
lastError: String? = "No wallet file",
) = WalletChildStatus(
state = state,
running = running,
walletOpen = walletOpen,
needsPassphrase = needsPassphrase,
configured = true,
chainSource = "remote daemon",
chainInProcess = false,
nodeAvailable = false,
nodeState = "",
height = 0uL,
targetHeight = 0uL,
lastError = lastError,
)
@Test
fun the_status_line_never_renders_the_daemons_own_words() {
// The render path, not the filter in isolation: the SDK record the
// poller lands is what the status line is drawn from, and the same
// field feeds the screen-reader sentence.
assertNoRawRpc(walletChildLine(sdkStatus().toInput()))
assertNoRawRpc(walletChildStatusDescription(sdkStatus().toInput()))
}
@Test
fun a_raw_rpc_envelope_on_the_status_line_is_replaced_too() {
// A failure that never reached the parser arrives as the envelope.
val raw = """{"error": {"code": -13, "message": "No wallet file"}}"""
assertNoRawRpc(walletChildLine(sdkStatus(lastError = raw).toInput()))
}
@Test
fun the_status_line_still_says_the_state_and_the_source() {
// Filtering the trailing text must not cost the line its own words.
val line = walletChildLine(sdkStatus().toInput())
assertTrue("got '$line'", line.startsWith("connecting · remote daemon"))
}
@Test
fun an_open_wallet_has_nothing_left_to_filter() {
val line = walletChildLine(
sdkStatus(state = "ready", walletOpen = true, needsPassphrase = false, lastError = null)
.toInput(),
)
assertEquals("ready · remote daemon", line)
}
@Test
fun the_cores_own_reason_for_a_dead_child_still_reaches_the_line() {
// The other side of the same seam: a reason written for a person is
// passed through, so the filter is not a mute button.
val line = walletChildLine(
sdkStatus(state = "exited", running = false, needsPassphrase = false,
lastError = "spawn monero-wallet-rpc: No such file").toInput(),
)
assertTrue("got '$line'", line.contains("No such file"))
assertNoRawRpc(line)
}
@Test
fun filtering_the_sdk_record_twice_changes_nothing() {
// The sticky error card runs the same filter over the same field, so
// the replacement must survive a second pass unchanged.
val once = sdkStatus().toInput().lastError
assertEquals(WALLET_NOT_OPEN_TEXT, once)
assertEquals(once, walletFailureText(once))
}
} }