wallet: land the file-name picker fix and the wallet manager on main (from t_67879b98) #153

Merged
sirius merged 8 commits from onionwire/t_67879b98-wallet-actually-open-the-wallet-file-and into main 2026-09-23 02:33:40 +00:00
7 changed files with 1122 additions and 54 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))
}
} }

View file

@ -34,6 +34,7 @@ use crate::store::{
use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ use crate::wallet_child::{
ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus, ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus,
wallet_name_taken,
}; };
pub struct RotateResult { pub struct RotateResult {
@ -697,10 +698,7 @@ impl Node {
if already_running { if already_running {
return Ok(()); return Ok(());
} }
let child = Arc::new( let child = Arc::new(cfg.build(self.wallet_dir()).map_err(|e| e.to_string())?);
cfg.build(self.home.join("wallet"))
.map_err(|e| e.to_string())?,
);
// Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status` // Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status`
// also locks the store, and a blocked poller is how Android Start looks // also locks the store, and a blocked poller is how Android Start looks
// like it did nothing. // like it did nothing.
@ -1571,20 +1569,42 @@ impl Node {
self.open_wallet_file(filename, passphrase) self.open_wallet_file(filename, passphrase)
} }
/// The file name a wallet created now should live in. `wallet_filename` is /// The file name a wallet created now should live in.
/// UNIQUE and the catalogue is the only directory the app has, so this is ///
/// `<default>-<n>` for the first `n` the catalogue does not already hold. /// `wallet_filename` is UNIQUE and the catalogue is not the whole story:
/// `Store::delete_wallet` drops the row and keeps the file, and a create
/// whose `record_wallet` failed leaves a file with no row, so a *file* the
/// catalogue does not know about is still a name the daemon refuses with
/// `-21 Cannot create wallet. Already exists.` — for ever, because the
/// catalogue never changed. So the first `<default>-<n>` that is free in
/// both places wins, and a wallet dir that cannot be listed is an error
/// rather than a guess ([`wallet_name_taken`]).
///
/// Nothing is deleted here: a file the catalogue does not hold may be the
/// only copy of a funded wallet.
fn next_wallet_filename(&self) -> Result<String, String> { fn next_wallet_filename(&self) -> Result<String, String> {
let taken = self.list_wallets()?; let taken = self.list_wallets()?;
let dir = self.wallet_dir();
for n in 1.. { for n in 1.. {
let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n);
if !taken.iter().any(|w| w.wallet_filename == candidate) { if taken.iter().any(|w| w.wallet_filename == candidate) {
return Ok(candidate); continue;
} }
if wallet_name_taken(&dir, &candidate).map_err(|e| e.to_string())? {
continue;
}
return Ok(candidate);
} }
unreachable!("an unused wallet file name always exists") unreachable!("an unused wallet file name always exists")
} }
/// Where this install's wallet files live: `$ONIONWIRE_HOME/wallet`, the
/// `--wallet-dir` the app-owned child is spawned with. The one path, so
/// the picker and the child can never disagree about the directory.
fn wallet_dir(&self) -> PathBuf {
self.home.join("wallet")
}
/// Point the wallet child at a wallet file. A read-modify-write of the /// Point the wallet child at a wallet file. A read-modify-write of the
/// sealed record, so the generated RPC creds and every other setting are /// sealed record, so the generated RPC creds and every other setting are
/// kept. A running child is not restarted: the change applies on the next /// kept. A running child is not restarted: the change applies on the next
@ -2508,6 +2528,9 @@ pub(crate) mod tests {
wallet: Wallet, wallet: Wallet,
) -> Node { ) -> Node {
std::fs::create_dir_all(home).expect("create home"); std::fs::create_dir_all(home).expect("create home");
// The app-owned child creates the wallet dir 0700 before a wallet can
// be configured, and the picker now insists on listing it.
std::fs::create_dir_all(home.join("wallet")).expect("create wallet dir");
let store = Store::open_at_with_passphrase(home, PASS).expect("open store"); let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys"); let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys");
let client = arti_client::TorClient::builder() let client = arti_client::TorClient::builder()
@ -3051,14 +3074,38 @@ pub(crate) mod tests {
/// A stand-in for `monero-wallet-rpc`: it records its argv, then does what /// A stand-in for `monero-wallet-rpc`: it records its argv, then does what
/// the test needs. The wallet child spawns a real process, so this is the /// the test needs. The wallet child spawns a real process, so this is the
/// only honest way to drive the start path offline. /// only honest way to drive the start path offline.
///
/// The argv is `mv`d into place in one step rather than truncated and
/// appended: a poller must never read half of it. It did — the port was
/// parsed while it was still being written, so `42765` read as `427`, and
/// the mock was bound on a port nothing dialled.
///
/// Every child also writes its own copy at `<log>.<pid>`, which no other
/// child can touch, and the shared copy lands first, so a pid-named file
/// implies the shared one is already complete. The shared path is what the
/// single-child tests read; a test that spans two children reads the
/// pid-named one, because a previous child's write into the shared path is
/// unsequenced against the test (see [`wait_for_child_rpc_port`]).
fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf {
fake_child_bin_after(dir, name, log, "", body)
}
/// [`fake_child_bin`] with `prelude` run *before* the argv is written: the
/// stand-in for a runner that schedules this child's exec late.
fn fake_child_bin_after(
dir: &Path,
name: &str,
log: &Path,
prelude: &str,
body: &str,
) -> PathBuf {
std::fs::create_dir_all(dir).expect("fake bin dir"); std::fs::create_dir_all(dir).expect("fake bin dir");
let path = dir.join(name); let path = dir.join(name);
let script = format!( let script = format!(
"#!/bin/sh\n: > '{}'\nprintf '%s\\n' \"$0\" >> '{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done\n{body}\n", "#!/bin/sh\n{prelude}\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\ncp -f \"$tmp\" '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\nmv -f \"$tmp\" '{log}'.$$\n{body}\n",
log.display(), prelude = prelude,
log.display(), log = log.display(),
log.display() body = body
); );
std::fs::write(&path, script).expect("write fake bin"); std::fs::write(&path, script).expect("write fake bin");
let mut perms = std::fs::metadata(&path).expect("stat").permissions(); let mut perms = std::fs::metadata(&path).expect("stat").permissions();
@ -3630,6 +3677,84 @@ pub(crate) mod tests {
); );
} }
/// A catalogue name is still skipped: the disk check is an addition, not a
/// replacement, and a remembered wallet must keep its own file.
#[tokio::test]
async fn a_catalogue_name_is_still_skipped_by_the_picker() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
{
let store = node.store.lock().expect("store");
test_record_wallet(&store, "onionwire-1", "");
}
let created = node.wallet_create("p1").await.expect("create wallet");
assert_eq!(created.record.wallet_filename, "onionwire-2");
}
/// The reported bug: a wallet file whose catalogue row is gone — an
/// explicit `Store::delete_wallet`, or a create whose `record_wallet`
/// failed — is still on disk, so a catalogue-only picker proposes the same
/// name for ever and the daemon answers `-21 Cannot create wallet. Already
/// exists.` with no way out from the UI.
#[tokio::test]
async fn wallet_files_on_disk_are_skipped_when_picking_a_name() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
// No catalogue rows at all: only the disk knows about these two, and
// monero writes two files per wallet, so either one means "taken".
std::fs::write(home.join("wallet").join("onionwire-1.keys"), b"keys").unwrap();
std::fs::write(home.join("wallet").join("onionwire-2"), b"wallet").unwrap();
let created = node.wallet_create("p1").await.expect("create wallet");
assert_eq!(
created.record.wallet_filename, "onionwire-3",
"the stray `.keys` file and the stray wallet file are both taken"
);
}
/// A stray file under some *other* name must not bump the picker: the
/// check is about this candidate, not about the directory being busy.
#[tokio::test]
async fn an_unrelated_file_on_disk_does_not_cost_the_first_name() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
std::fs::write(home.join("wallet").join("someone-elses"), b"x").unwrap();
let created = node.wallet_create("p1").await.expect("create wallet");
assert_eq!(created.record.wallet_filename, "onionwire-1");
}
/// Fail closed: a wallet directory that cannot be listed is an error, not
/// "every name is free". Guessing here is how the collision comes back.
#[tokio::test]
async fn the_wallet_name_picker_fails_closed_when_the_dir_cannot_be_read() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("bob");
let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await);
std::fs::remove_dir_all(home.join("wallet")).unwrap();
let err = node
.wallet_create("p1")
.await
.expect_err("an unreadable wallet dir must refuse, not guess");
assert!(
err.contains("wallet dir"),
"the error must name the directory it could not list: {err}"
);
assert!(
node.list_wallets().expect("list wallets").is_empty(),
"a refused create records nothing"
);
}
/// The catalogue is a store fact, not a wallet-RPC fact: listing must work /// The catalogue is a store fact, not a wallet-RPC fact: listing must work
/// with no wallet configured, and creating must still refuse without one. /// with no wallet configured, and creating must still refuse without one.
#[tokio::test] #[tokio::test]
@ -3851,24 +3976,71 @@ pub(crate) mod tests {
}) })
} }
/// The port the fake child was spawned with. The fake bin writes its argv one /// The pid of the running wallet child. Panics when there is none: every
/// argument per line, so `--rpc-bind-port` is followed by the number; the /// caller has just started one.
/// write happens right after `spawn` returns, hence the wait. fn child_pid(node: &Node) -> u32 {
async fn wait_for_child_rpc_port(argv_log: &Path) -> u16 { node.wallet_child
.lock()
.ok()
.and_then(|guard| guard.clone())
.and_then(|child| child.wallet_rpc_pid())
.expect("a running wallet child")
}
/// Wait for the pid of a child that is not `previous` — the restart's.
async fn wait_for_new_child_pid(node: &Node, previous: u32) -> u32 {
for _ in 0..600 { for _ in 0..600 {
if let Ok(raw) = std::fs::read_to_string(argv_log) { let pid = node
let lines: Vec<&str> = raw.lines().collect(); .wallet_child
if let Some(i) = lines.iter().position(|line| *line == "--rpc-bind-port") .lock()
&& let Some(port) = lines.get(i + 1).and_then(|p| p.trim().parse::<u16>().ok()) .ok()
{ .and_then(|guard| guard.clone())
return port; .and_then(|child| child.wallet_rpc_pid());
} if let Some(pid) = pid
&& pid != previous
{
return pid;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the restart never reported a new wallet-child pid");
}
/// `--rpc-bind-port <port>` out of a fake child's argv log.
fn rpc_port_in(raw: &str) -> Option<u16> {
let lines: Vec<&str> = raw.lines().collect();
let i = lines.iter().position(|line| *line == "--rpc-bind-port")?;
lines
.get(i + 1)
.and_then(|port| port.trim().parse::<u16>().ok())
}
/// The port the child with this pid was spawned with, read out of the argv
/// log that child alone writes — `<log>.<pid>`, `mv`d into place in one step.
///
/// The shared path must not be used for this. Every child writes it and a
/// previous child's write is unsequenced against the test, so on a loaded
/// runner it lands after a poller has cleared the file: the poller then binds
/// its mock on the port of a child that has already been killed, and the
/// restarted child's `open_wallet` is refused for the whole
/// `WALLET_OPEN_WAIT` (CI run 905, job 1373 — the same message in run 901,
/// green 3/3 on a 16-core host). A pid in the file name is a handshake the
/// child cannot lose.
async fn wait_for_child_rpc_port(argv_log: &Path, pid: u32) -> u16 {
let mut name = argv_log.as_os_str().to_owned();
name.push(format!(".{pid}"));
let path = PathBuf::from(name);
for _ in 0..600 {
if let Ok(raw) = std::fs::read_to_string(&path)
&& let Some(port) = rpc_port_in(&raw)
{
return port;
} }
tokio::time::sleep(Duration::from_millis(10)).await; tokio::time::sleep(Duration::from_millis(10)).await;
} }
panic!( panic!(
"the fake child never wrote an --rpc-bind-port to {}", "the fake child {pid} never wrote an --rpc-bind-port to {}",
argv_log.display() path.display()
); );
} }
@ -3918,15 +4090,19 @@ pub(crate) mod tests {
assert!(status.last_error.is_none(), "{status:?}"); assert!(status.last_error.is_none(), "{status:?}");
// Restart it with the passphrase the user supplied. The child picks a // Restart it with the passphrase the user supplied. The child picks a
// fresh port, so the mock is bound to what the new argv names while the // fresh port, so the mock is bound to the port *this* spawn named while
// open waits for the RPC to answer. // the open waits for its RPC to answer — read from the argv log the new
// pid owns, never from the shared path the previous child wrote: a loaded
// runner lands that write after a clear (CI run 905, job 1373).
let first_pid = child_pid(&node);
std::fs::write(&argv_log, b"").expect("clear the argv log"); std::fs::write(&argv_log, b"").expect("clear the argv log");
let requests = Arc::new(Mutex::new(Vec::new())); let requests = Arc::new(Mutex::new(Vec::new()));
let starter = Arc::clone(&node); let starter = Arc::clone(&node);
let started = tokio::task::spawn_blocking(move || { let started = tokio::task::spawn_blocking(move || {
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass") starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
}); });
let port = wait_for_child_rpc_port(&argv_log).await; let pid = wait_for_new_child_pid(&node, first_pid).await;
let port = wait_for_child_rpc_port(&argv_log, pid).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await .await
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}")); .unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
@ -3976,6 +4152,89 @@ pub(crate) mod tests {
node.stop_wallet_child().expect("stop"); node.stop_wallet_child().expect("stop");
} }
/// The port the restarted child's mock listens on must come from *that*
/// child, not from the shared argv path a previous child has already written.
/// The old harness cleared that path and read it anyway, and the clear is not
/// a synchronisation: on a loaded runner the killed child's write lands after
/// it, so the mock was bound on a port nothing dialled and the restarted
/// child's `open_wallet` was refused for the whole `WALLET_OPEN_WAIT` (CI run
/// 905, job 1373; the same message in run 901, green 3/3 on a 16-core host).
/// Here the killed child's argv is left in place — the worst case of that
/// race — and the restart still reaches the mock on its own port.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_restart_is_not_given_the_stopped_childs_port() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("child");
let argv_log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&argv_log,
"sleep 30",
);
let node = Arc::new(offline_node(&home, Arc::new(NoDial)));
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1"))
.expect("set config");
test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings");
node.start_wallet_child().expect("first start");
let first_pid = child_pid(&node);
// The killed child's argv is in the shared path (its own log lands first,
// so this waits for both) — the content the old harness would read.
let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await;
// The restart's exec is late here, the way a loaded runner delays it, so
// the shared path still holds the killed child's argv while the restarted
// child is already being dialled.
let restart = fake_child_bin_after(
&dir.path().join("fake-bins-restart"),
"monero-wallet-rpc",
&argv_log,
"sleep 2",
"sleep 30",
);
node.set_wallet_child_config(&loopback_child_config(restart, "onionwire-1"))
.expect("re-point the child at the late-write stand-in");
let requests = Arc::new(Mutex::new(Vec::new()));
let starter = Arc::clone(&node);
let started = tokio::task::spawn_blocking(move || {
starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass")
});
let pid = wait_for_new_child_pid(&node, first_pid).await;
// The premise of the test: the shared path still holds the killed
// child's argv, so a harness that reads it binds the mock on the wrong
// port. Reading the restarted child's own log instead is what the fix
// is — with the shared read, this test fails on the port above after the
// whole `WALLET_OPEN_WAIT`.
assert_eq!(
rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()),
Some(stale_port),
"the restarted child must not have written the shared path yet"
);
let port = wait_for_child_rpc_port(&argv_log, pid).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}"));
tokio::spawn(serve_mock_rpc(
listener,
recording_wallet_reply(Arc::clone(&requests)),
));
started
.await
.expect("join the start")
.expect("open the wallet with a passphrase");
assert!(
requests
.lock()
.unwrap()
.iter()
.any(|request| request.contains("open_wallet")),
"the restart never reached the mock on the port it dialled"
);
node.stop_wallet_child().expect("stop");
}
/// No stored passphrase: the child starts with no wallet open and the status /// No stored passphrase: the child starts with no wallet open and the status
/// says `needs passphrase`. It must not fail the start — a wallet created /// says `needs passphrase`. It must not fail the start — a wallet created
/// before the passphrase was stored still has a working node — and it must /// before the passphrase was stored still has a working node — and it must
@ -4006,6 +4265,7 @@ pub(crate) mod tests {
assert!(status.running, "{status:?}"); assert!(status.running, "{status:?}");
assert!(!status.wallet_open, "{status:?}"); assert!(!status.wallet_open, "{status:?}");
assert!(status.needs_passphrase, "{status:?}"); assert!(status.needs_passphrase, "{status:?}");
let first_pid = child_pid(&node);
node.stop_wallet_child().expect("stop"); node.stop_wallet_child().expect("stop");
// A second start, this time with an RPC listening on the port it was // A second start, this time with an RPC listening on the port it was
@ -4015,7 +4275,8 @@ pub(crate) mod tests {
let requests = Arc::new(Mutex::new(Vec::new())); let requests = Arc::new(Mutex::new(Vec::new()));
let starter = Arc::clone(&node); let starter = Arc::clone(&node);
let started = tokio::task::spawn_blocking(move || starter.start_wallet_child()); let started = tokio::task::spawn_blocking(move || starter.start_wallet_child());
let port = wait_for_child_rpc_port(&argv_log).await; let pid = wait_for_new_child_pid(&node, first_pid).await;
let port = wait_for_child_rpc_port(&argv_log, pid).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await .await
.unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}")); .unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}"));

View file

@ -207,6 +207,20 @@ impl WalletChild {
self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false) self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
} }
/// The pid of the running `monero-wallet-rpc` child, when there is one.
///
/// Test-only: the lib test harness names *this* spawn's argv log with it.
/// The shared log path is written by every child and a previous child's
/// write is unsequenced against anything a test does, so a restarted
/// child's port cannot be learned from it (see `node::tests`).
#[cfg(test)]
pub(crate) fn wallet_rpc_pid(&self) -> Option<u32> {
self.wallet_rpc
.lock()
.ok()
.and_then(|guard| guard.as_ref().map(std::process::Child::id))
}
/// Is a tracked child still alive? Polls the process table; an exited child /// Is a tracked child still alive? Polls the process table; an exited child
/// is reaped here so a later `stop` is a no-op. /// is reaped here so a later `stop` is a no-op.
/// ///
@ -1161,6 +1175,33 @@ fn create_dir_700(path: &Path) -> std::io::Result<()> {
fs::set_permissions(path, perms) fs::set_permissions(path, perms)
} }
/// Is `name` already a wallet file in `wallet_dir`?
///
/// monero writes two files per wallet — `<name>` and `<name>.keys` — and either
/// one makes `monero-wallet-rpc` refuse a create with `-21 Cannot create wallet.
/// Already exists.`, so both count as taken. The catalogue alone is not enough:
/// `Store::delete_wallet` drops the row and keeps the file, and a create whose
/// row was never written leaves a file too, so a picker that only consults the
/// catalogue proposes a colliding name for ever.
///
/// Fail closed: a directory that cannot be listed is an error, never "every
/// name is free". Guessing is how the collision comes back.
///
/// Reads only: nothing here deletes anything — a file the catalogue does not
/// know about may be the only copy of a funded wallet.
pub fn wallet_name_taken(wallet_dir: &Path, name: &str) -> Result<bool> {
let keys = format!("{name}.keys");
let unreadable =
|e: std::io::Error| ChildError(format!("wallet dir {}: {e}", wallet_dir.display()));
for entry in fs::read_dir(wallet_dir).map_err(unreadable)? {
let found = entry.map_err(unreadable)?.file_name();
if found == std::ffi::OsStr::new(name) || found == std::ffi::OsStr::new(keys.as_str()) {
return Ok(true);
}
}
Ok(false)
}
fn ensure_parent(path: &Path) -> Result<()> { fn ensure_parent(path: &Path) -> Result<()> {
if let Some(parent) = path.parent() if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty() && !parent.as_os_str().is_empty()
@ -1206,17 +1247,24 @@ mod tests {
} }
/// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks. /// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks.
///
/// The argv lands in `<log>` with one `mv`, not a truncate-then-append: a
/// reader must never see half an argv. It did — the poll below could catch
/// `--rpc-bind-port` while the port was still being written and parse
/// `427` out of `42765`, a valid-but-wrong port, and the test then bound a
/// mock nobody dialled.
fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf { fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf {
let path = dir.join(name); let path = dir.join(name);
let mut f = fs::File::create(&path).unwrap(); let mut f = fs::File::create(&path).unwrap();
writeln!(f, "#!/bin/sh").unwrap(); writeln!(f, "#!/bin/sh").unwrap();
writeln!(f, ": > '{}'", log.display()).unwrap(); writeln!(f, "tmp='{}'.$$", log.display()).unwrap();
writeln!(f, ": > \"$tmp\"").unwrap();
writeln!( writeln!(
f, f,
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", "for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done"
log.display()
) )
.unwrap(); .unwrap();
writeln!(f, "mv -f \"$tmp\" '{}'", log.display()).unwrap();
writeln!(f, "sleep 30").unwrap(); writeln!(f, "sleep 30").unwrap();
drop(f); drop(f);
let mut perms = fs::metadata(&path).unwrap().permissions(); let mut perms = fs::metadata(&path).unwrap().permissions();

View file

@ -9,6 +9,7 @@ use onionwire::wallet::{
self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet, self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet,
WalletConfig, WalletStatus, readiness, WalletConfig, WalletStatus, readiness,
}; };
use onionwire::wallet_child;
use onionwire::{PaymentWrite, Store}; use onionwire::{PaymentWrite, Store};
use rand::rngs::OsRng; use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
@ -1833,3 +1834,61 @@ async fn open_wallet_surfaces_the_rpcs_own_refusal() {
"the passphrase must never be echoed back in an error: {err}" "the passphrase must never be echoed back in an error: {err}"
); );
} }
// ---------------------------------------------------------------------------
// `next_wallet_filename`'s disk half: monero writes two files per wallet and
// the daemon refuses a create that would collide with either, so the picker
// has to look at the directory, not only at the catalogue.
// ---------------------------------------------------------------------------
/// `<name>` and `<name>.keys` both mean taken; nothing else does.
#[test]
fn wallet_name_taken_sees_the_file_and_its_keys_sibling() {
let dir = tempfile::tempdir().expect("tempdir");
let wallet_dir = dir.path();
std::fs::write(wallet_dir.join("onionwire-1.keys"), b"keys").unwrap();
std::fs::write(wallet_dir.join("onionwire-2"), b"wallet").unwrap();
assert!(
wallet_child::wallet_name_taken(wallet_dir, "onionwire-1").unwrap(),
"the `.keys` sibling is enough to make the name taken"
);
assert!(
wallet_child::wallet_name_taken(wallet_dir, "onionwire-2").unwrap(),
"the wallet file itself is enough"
);
assert!(!wallet_child::wallet_name_taken(wallet_dir, "onionwire-3").unwrap());
assert!(
!wallet_child::wallet_name_taken(wallet_dir, "onionwire").unwrap(),
"a prefix is not a collision"
);
assert!(
!wallet_child::wallet_name_taken(wallet_dir, "onionwire-20").unwrap(),
"neither is a longer name that starts with a taken one"
);
// The files may be the only copy of a funded wallet: naming the collision
// must not remove it.
assert!(wallet_dir.join("onionwire-1.keys").is_file());
assert!(wallet_dir.join("onionwire-2").is_file());
}
/// Fail closed: a directory that cannot be listed is an error, not "every name
/// is free". Guessing here is how the collision comes back.
#[test]
fn wallet_name_taken_fails_closed_when_the_dir_cannot_be_read() {
let dir = tempfile::tempdir().expect("tempdir");
let missing = dir.path().join("no-such-wallet-dir");
let err = wallet_child::wallet_name_taken(&missing, "onionwire-1")
.expect_err("a missing wallet dir must refuse, not answer 'free'")
.to_string();
assert!(
err.contains("wallet dir"),
"the error must name what could not be listed: {err}"
);
// A path that is a file, not a directory, is unreadable too.
let file = dir.path().join("not-a-dir");
std::fs::write(&file, b"x").unwrap();
assert!(wallet_child::wallet_name_taken(&file, "onionwire-1").is_err());
}