From 145036fda83c1bbd7703bfdf3989014cec35c7cb Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 11:53:19 -0400 Subject: [PATCH 01/70] wallet: expose an on-demand seed accessor over core + UniFFI Wallet::create_wallet returned the 25-word seed exactly once and nothing could reach it afterwards, so a seed that was never backed up at creation was unrecoverable. Add Wallet::mnemonic() (one query_key mnemonic call on the open wallet file), Node::wallet_seed() mirroring wallet_create, and the additive UniFFI export Wire::wallet_seed() -> Kotlin Wire.walletSeed(). No existing signature changes. The refusals stay leak-free: an unconfigured wallet gets NOT_CONFIGURED_MSG without a dial, a watch-only wallet keeps the RPC's -29 view-only mapping, and no error string carries the RPC login. Tests (tests/wallet.rs) drive the per-connection Digest mock: the words come back verbatim, a JSON-RPC error surfaces without the login or endpoint, a rejected digest refusal does not leak the password, and an unconfigured wallet is refused without dialing. --- crates/onionwire-sdk/src/lib.rs | 11 +++++ src/node.rs | 12 ++++++ src/wallet.rs | 19 +++++++++ tests/wallet.rs | 74 +++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..3680aa7 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -594,6 +594,17 @@ impl Wire { .map_err(WireError::new) } + /// Re-read this wallet's 25-word seed so the UI can offer a "back up seed" + /// action after creation. Dials the wallet child's RPC (`query_key + /// mnemonic`), so it is cheap but not free, and it needs a wallet the child + /// has open. The result is a spend key: call this only from an explicit + /// user action, show it, and do not persist or log it. + /// + /// The Kotlin binding is `Wire.walletSeed()`. + pub async fn wallet_seed(&self) -> WResult { + self.node()?.wallet_seed().await.map_err(WireError::new) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { diff --git a/src/node.rs b/src/node.rs index fcc8015..a78ea8d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1179,6 +1179,18 @@ impl Node { .map_err(|e| e.to_string()) } + /// Re-read the seed of the wallet file the child has open. `create_wallet` + /// returns it once; after that this is the only path to it. The seed is a + /// spend key, so the caller must only show it on an explicit user action + /// and must not log or store it. + pub async fn wallet_seed(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.mnemonic().await.map_err(|e| e.to_string()) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { diff --git a/src/wallet.rs b/src/wallet.rs index 7195691..e4437da 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -788,6 +788,25 @@ impl Wallet { json_str(&v, "key") } + /// Re-read the seed of the wallet file the RPC has open (`query_key + /// mnemonic`). After `create_wallet` this is the **only** way to recover a + /// created wallet's seed, so the UI can offer a backup action instead of + /// showing it once. It needs an open, spend-capable wallet file; a + /// watch-only one answers the RPC's `-29` and surfaces as the view-only + /// refusal. + /// + /// The returned words are a spend key: never log them, never store them, + /// and never put them in an error string. + pub async fn mnemonic(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await?; + json_str(&v, "key") + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index da8e8f3..9c8649b 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -819,6 +819,80 @@ async fn mock_digest_auth_accepted() { assert!(got.starts_with('4'), "got {got}"); } +/// The seed is a spend key: `mnemonic` must be one `query_key mnemonic` call +/// and nothing else, so the caller sees exactly what the open wallet answers. +#[tokio::test] +async fn mnemonic_returns_the_words_the_rpc_answers() { + const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve \ +thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone \ +twentytwo twentythree twentyfour twentyfive"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { + "query_key" => rpc_result(&format!(r#"{{"key":"{WORDS}"}}"#)), + other => panic!("mnemonic must make one query_key call, saw {other}"), + }), + None, + None, + )); + let got = recording_wallet(port).mnemonic().await.expect("mnemonic"); + assert_eq!(got, WORDS); +} + +/// A wallet with no open file answers a JSON-RPC error. It must surface as the +/// wallet's error, and the RPC login from the URL must not ride along with it. +#[tokio::test] +async fn mnemonic_surfaces_an_rpc_error_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_error(-1, "wallet file is not open")), + None, + None, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); + assert!(!msg.contains("http://"), "endpoint leaked: {err}"); +} + +/// The refused-digest refusal names the login in prose ("the login does not +/// match"), which is exactly the copy that must not carry the credential. +#[tokio::test] +async fn mnemonic_refuses_a_rejected_digest_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns_with( + listener, + Arc::new(|_: &str| "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_string()), + None, + None, + true, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("digest rejected"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.mnemonic()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From 118191c5412aa489d5c2cf3f8c8b1bc764861af2 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 12:09:48 -0400 Subject: [PATCH 02/70] android: block the wallet screen on an unbacked seed, and make it re-showable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A created wallet's seed was two lines of small text at the bottom of the wallet page, dismissed by one tap, gone for good once the screen was left. A real user created a wallet, never saw the seed, and the app had no way to show it again. - `SeedBackupGate` (new, pure Kotlin): the confirm word `SEEN` and its case-insensitive match mirror the TUI's own `WalletSetup::CreateSeed` gate; create starts unbacked, import is backed up without the gate, and only a correct word can confirm. - The seed card is the whole body until the word is typed and Done is tapped: no Cancel, no copy button (the Android clipboard is readable by every other app), Done dead until `SEEN`. - "Back up seed" re-reads the seed through the new `Wire::wallet_seed()` (`WireViewModel.walletSeed()`), so a seed missed the first time is not lost. Its failure is shown next to the button, not at the bottom of a long scroll. - While unconfirmed: a warning strip stays at the top of the wallet screen and the receive address and Show QR are hidden — XMR received into a wallet whose 25 words were never written down is unrecoverable. - The flag lives in app-local prefs (`wallet_seed_backup`), not in the Keystore-wrapped store, and is reset by `createWallet` itself so no caller can forget it. The stored flag is nullable, and the null is load-bearing. `false` means this install created a wallet and nobody has confirmed the seed, so the strip is up whether or not the balance reads. `null` means nothing is stored — an install that predates the flag, or one that has never created a wallet here — and there the strip waits for `wallet_balance` to return a real amount, the core's own evidence that the child has a wallet open. Without that distinction a first-run user who had configured a chain source but not yet created a wallet (`wallet_balance` returns "err") would be warned about a seed they do not have. The app-bar Back still leaves the screen, deliberately — it is the TUI's `Esc`. It costs nothing now, because leaving no longer loses the seed. Verification: `./gradlew :app:testDebugUnitTest` green, 135 tests (`SeedBackupGateTest` 18 of them). --- .../siriusdevops/onionwire/WireViewModel.kt | 76 ++++++ .../onionwire/ui/SeedBackupGate.kt | 113 +++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 240 ++++++++++++++++-- .../onionwire/ui/SeedBackupGateTest.kt | 176 +++++++++++++ 4 files changed, 588 insertions(+), 17 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 6f26632..7be3c6a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -1,6 +1,8 @@ package com.siriusdevops.onionwire import android.app.Application +import android.content.Context +import android.content.SharedPreferences import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope @@ -11,6 +13,8 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore import com.siriusdevops.onionwire.keepalive.KeepAliveService import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost +import com.siriusdevops.onionwire.ui.SeedBackupGate +import com.siriusdevops.onionwire.ui.WalletKeyOrigin import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries @@ -588,11 +592,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + /** + * Create a wallet and read its seed once. The seed-backup flag is reset + * here, not by the screen: every successful create is a new seed nobody has + * read, and a caller that forgot to reset it would leave a spend key + * unrecoverable. See [SeedBackupGate.afterWallet]. + */ suspend fun createWallet(password: String): Result = runCatching { requireWire().createWallet(password) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) } + /** + * Import a wallet from a user-supplied seed. That seed is already on paper — + * the user just pasted it — so the wallet counts as backed up without the + * confirm step. + */ suspend fun importWallet(password: String, seed: String): Result = runCatching { requireWire().importWallet(password, seed) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) } + + /** + * Re-read the open wallet's 25-word seed, for the "Back up seed" recovery + * path. A spend key: only ever called from that explicit user action, shown + * on the blocking card, and dropped. Never logged and never persisted. + */ + suspend fun walletSeed(): Result = + runCatching { requireWire().walletSeed() } fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() @@ -600,6 +625,47 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." } + // --- Seed backup gate -------------------------------------------------- + // Whether the open wallet's seed has been confirmed written down. This is + // NOT a secret — it is a boolean in app-local prefs, deliberately kept out + // of the Keystore-wrapped store under `filesDir/secrets`, which holds the + // passphrase and nothing else. + // + // The flow is nullable, and the null is load-bearing: nothing stored means + // "this install has never created or imported a wallet through this build", + // which is not the same as "the user created one and has not confirmed it". + // See [SeedBackupGate.warningVisible] for why the screen needs both. + + private val seedBackupPrefs: SharedPreferences = + app.getSharedPreferences(SEED_BACKUP_PREFS, Context.MODE_PRIVATE) + + private val _walletSeedConfirmed = MutableStateFlow( + if (seedBackupPrefs.contains(SEED_BACKED_UP_KEY)) { + seedBackupPrefs.getBoolean(SEED_BACKED_UP_KEY, false) + } else { + null + }, + ) + + /** + * The stored seed-backup flag: `false` unconfirmed, `true` confirmed or + * imported, `null` nothing stored (an install that predates the flag). + */ + val walletSeedConfirmed: StateFlow = _walletSeedConfirmed.asStateFlow() + + /** + * One confirm step from the blocking seed card. The gate decides: a wrong + * word leaves the flag where it was, so this can never un-confirm a wallet. + */ + fun confirmWalletSeed(typed: String) { + setWalletSeedConfirmed(SeedBackupGate.afterConfirm(typed, _walletSeedConfirmed.value == true)) + } + + private fun setWalletSeedConfirmed(confirmed: Boolean) { + seedBackupPrefs.edit().putBoolean(SEED_BACKED_UP_KEY, confirmed).apply() + _walletSeedConfirmed.value = confirmed + } + // --- App-owned wallet child (issue #107) ------------------------------- // The app owns `monero-wallet-rpc` instead of asking the user to start one // and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced @@ -920,3 +986,13 @@ suspend fun walletChildRefreshLoop( /** Cadence of the wallet-child refresh loop, in milliseconds. */ private const val WALLET_CHILD_TICK_MS: Long = 2_000 + +/** + * App-local prefs file for the seed-backup flag. Not a secret, so it is a plain + * prefs file rather than anything under `filesDir/secrets`. + */ +private const val SEED_BACKUP_PREFS: String = "wallet_seed_backup" + +/** Key inside [SEED_BACKUP_PREFS]: has the open wallet's seed been written down? */ +private const val SEED_BACKED_UP_KEY: String = "backed_up" + diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt new file mode 100644 index 0000000..ee0c303 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt @@ -0,0 +1,113 @@ +package com.siriusdevops.onionwire.ui + +/** + * Where the open wallet's key material came from. + * + * The distinction is the whole gate. A seed the user *supplied* (import) is a + * seed the user already has on paper, so that wallet is backed up from the + * start. A seed the app *generated* (create) has been read by nobody until it + * is put on screen, so that wallet starts unbacked and stays unbacked until the + * user proves it is written down. + */ +enum class WalletKeyOrigin { + Created, + Imported, +} + +/** + * The seed-backup gate: every decision the wallet screen makes about an + * unconfirmed seed, as pure Kotlin — no Compose, no Android, no prefs — so the + * rules are covered by `SeedBackupGateTest` on the JVM without a device. + * + * The gate exists because a seed shown once and then lost is an unrecoverable + * wallet: XMR received into a wallet whose 25 words were never written down + * cannot be spent or recovered by anyone, including this app. So the answer is + * not advisory — while it says the seed is unbacked, the wallet screen keeps a + * warning up and hides the receive address and its QR. + * + * The confirm word and its case-insensitivity mirror the TUI's own seed screen + * (`src/tui.rs`, `WalletSetup::CreateSeed`, which compares with + * `eq_ignore_ascii_case("SEEN")`) instead of inventing a second convention for + * the same wallet. + */ +object SeedBackupGate { + + /** The word that releases the block. The TUI's word, not a new one. */ + const val CONFIRM_WORD: String = "SEEN" + + /** + * True when [typed] releases the block. + * + * Trimmed and case-insensitive, so a soft keyboard's auto-capitalised `Seen` + * and a trailing space from a paste both count. Everything else — including + * the empty string — stays blocked. + */ + fun accepts(typed: String): Boolean = + typed.trim().equals(CONFIRM_WORD, ignoreCase = true) + + /** + * The flag right after a wallet is created or imported. + * + * A create always resets it: the wallet file is new, and the seed it was + * built from has never been read by anyone. + */ + fun afterWallet(origin: WalletKeyOrigin): Boolean = when (origin) { + WalletKeyOrigin.Created -> false + WalletKeyOrigin.Imported -> true + } + + /** + * The flag after one confirm step. + * + * Only a correct [typed] can flip it to `true`; a wrong word can never + * un-confirm a wallet that is already backed up. + */ + fun afterConfirm(typed: String, backedUp: Boolean): Boolean = + backedUp || accepts(typed) + + /** Done is dead until the word is right. */ + fun confirmEnabled(typed: String): Boolean = accepts(typed) + + /** + * The persistent strip is up while this install has an unconfirmed seed. + * + * [confirmed] is the stored flag, and it is nullable on purpose: + * + * - `false` — this install created a wallet and nobody has confirmed the + * seed. The wallet exists whether or not its balance reads, so the strip + * is up regardless. + * - `true` — confirmed, or imported. Nothing to say. + * - `null` — nothing stored: an install that predates this flag, or one + * that has never created or imported a wallet here. "We never asked" is + * not "the user wrote it down", but it is also not evidence that a wallet + * exists — so the strip waits for [walletReadable], the core's own proof + * that the child has a wallet open. + * + * Without that last distinction the strip would fire on every install that + * has configured a chain source but not yet created a wallet, which is + * exactly the state a first-run user is in. + */ + fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) { + true -> false + false -> true + null -> walletReadable + } + + /** + * The receive address and its QR are shown only while there is no unbacked + * seed to worry about. Receiving into an unbacked wallet is the one mistake + * this gate exists to prevent, so the address is hidden rather than merely + * warned about. + */ + fun receiveAddressVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = + !warningVisible(confirmed, walletReadable) + + /** + * The strip's words. One source: the screen renders this verbatim, so the + * reason the address disappeared travels with the hiding. + */ + const val WARNING: String = + "seed not backed up. write down the 25 words before you receive anything — " + + "a wallet whose seed was never written down cannot be recovered. " + + "the receive address stays hidden until you do." +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 4fbeeac..ec98015 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -76,6 +76,7 @@ fun WalletScreen( val childError by vm.walletChildError.collectAsStateWithLifecycle() val starting by vm.walletChildStarting.collectAsStateWithLifecycle() val chain by vm.chainSource.collectAsStateWithLifecycle() + val seedConfirmed by vm.walletSeedConfirmed.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // Resolved once per composition: the native library directory is fixed for // the life of the process. @@ -92,7 +93,11 @@ fun WalletScreen( var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } - var backupSeed by remember { mutableStateOf(null) } + // The seed currently on the blocking card: set by a successful create, or by + // "Back up seed" re-reading it from the wallet child. Null means no card. + // Never persisted and never logged — it is a spend key. + var pendingSeed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } var daemonText by remember { mutableStateOf("") } var daemonError by remember { mutableStateOf(null) } @@ -103,6 +108,26 @@ fun WalletScreen( runCatching { transfers = vm.walletRecentTransfers(25) } } + /** + * "Back up seed": re-read the open wallet's seed from the wallet child and + * put it on the blocking card. This is the only path to a seed that was + * created before this screen existed, so the failure is shown rather than + * swallowed — it is the difference between "the child is not running" and + * "there is nothing to recover". + */ + fun openSeedBackup() { + scope.launch { + error = null + vm.walletSeed().fold( + onSuccess = { seed -> + pendingSeed = seed + seedConfirm = "" + }, + onFailure = { error = it.message ?: it.toString() }, + ) + } + } + LaunchedEffect(Unit) { reload() vm.refreshChainSource() @@ -151,6 +176,46 @@ fun WalletScreen( .screenContentInsets() .verticalScroll(rememberScrollState()), ) { + // The blocking seed step. While a seed is on screen this card is the + // whole body: no Cancel, and Done stays dead until the confirm word + // is typed, so the one-shot seed cannot be dismissed unread. The + // app-bar Back still leaves the screen — that is the TUI's `Esc` — + // and it costs nothing now, because leaving no longer loses the + // seed: the wallet stays unbacked (strip up, receive address hidden) + // until "Back up seed" puts this card back on screen. + val seed = pendingSeed + if (seed != null) { + SeedBackupCard( + seed = seed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + // The gate owns the transition: a wrong word (which the + // disabled Done button already blocks) cannot confirm. + vm.confirmWalletSeed(seedConfirm) + pendingSeed = null + seedConfirm = "" + }, + ) + error?.let { ErrorLine(it) } + return@Column + } + + // The persistent unbacked strip, above everything else on the page. + // `walletReadable` is the core's own evidence that the child has a + // wallet open: `wallet_balance` returns exactly "off" for a chain + // source that was never configured, "err" for a configured one whose + // read failed (no wallet file open yet, or the child is down), and a + // real amount otherwise. The gate uses it only for an install that + // has never created a wallet here, so a first-run user who has + // configured a daemon but not yet created anything is not nagged + // about a seed they do not have. + val walletReadable = balance != null && balance != "off" && balance != "err" + val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) + if (unbacked) { + UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) + } + Card( modifier = Modifier .fillMaxWidth() @@ -173,7 +238,12 @@ fun WalletScreen( style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace, ) - val addr = address + // Hidden until the seed is confirmed written down: XMR into a + // wallet whose 25 words were never recorded is unrecoverable, + // so the address and its QR are gated, not just warned about. + val addr = address?.takeIf { + SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable) + } if (addr != null) { Spacer(Modifier.height(8.dp)) Text( @@ -333,7 +403,9 @@ fun WalletScreen( onCancel = { setup = null }, onCreated = { seed -> setup = null - backupSeed = seed + // The card is the whole body from here until SEEN. + pendingSeed = seed + seedConfirm = "" scope.launch { reload() } }, onImported = { @@ -374,36 +446,170 @@ fun WalletScreen( modifier = Modifier.weight(1f), ) { Text("Import") } } + // The recovery path for a wallet whose seed was missed. The + // strip above carries its own copy of this button while the + // seed is unconfirmed, so exactly one is ever on screen — + // and this copy is only offered once the child can actually + // read a wallet, which is the only state in which the seed + // read can succeed. + if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) { + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = { openSeedBackup() }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } + } } } - backupSeed?.let { seed -> - Text( - "write this seed down once. anyone with it can spend.", - style = MaterialTheme.typography.labelSmall, - modifier = Modifier.padding(horizontal = 12.dp), - ) - Text( - seed, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), - ) - TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + // While the strip is up the error belongs next to the button that + // caused it: this page is one long scroll and the daemon card sits + // between the strip and the bottom, so a failed `wallet_seed` read + // would otherwise land off-screen. + if (!unbacked) { + error?.let { ErrorLine(it) } } + } + } +} +/** The one error line every wallet action shares. */ +@Composable +private fun ErrorLine(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} + +/** + * The persistent unbacked strip: up at the top of the wallet screen from the + * moment a create succeeds until the seed is confirmed written down, and again + * on any install whose wallet predates the flag. + * + * It is not a toast and not a dialog — leaving the screen does not dismiss it, + * because the state it reports is the wallet's, not the screen's. Its button is + * the recovery path for a seed that was created before the user knew to look. + */ +@Composable +private fun UnbackedSeedCard( + error: String?, + onBackUpSeed: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp) + .testTag("wallet-seed-warning"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + SeedBackupGate.WARNING, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = onBackUpSeed, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } error?.let { + Spacer(Modifier.height(6.dp)) Text( it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) } } } } +/** + * The blocking seed step: the 25 words, and a Done that is dead until the + * confirm word is typed. + * + * There is no Cancel and no copy button. No Cancel, because a seed this card is + * showing for the first time has never been written down anywhere else, so + * dismissing it unread is how a wallet becomes unrecoverable. No copy button, + * because the Android clipboard is readable by every other app on the device + * (and by the clipboard history on Android 13+), which would hand the spend key + * to whoever asks for it next. + * + * The seed is a Kotlin `String`, so it cannot be wiped in place the way the + * TUI's `Zeroizing` is; dropping the reference is the strongest thing + * available here. That is another reason it is never written to disk. + */ +@Composable +private fun SeedBackupCard( + seed: String, + typed: String, + onTyped: (String) -> Unit, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + .testTag("wallet-seed-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Back up this seed", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + Text( + "These 25 words are the only way to recover this wallet, and anyone who " + + "reads them can spend it. Write them down now — this is the only copy.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Text( + seed, + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-words"), + ) + Spacer(Modifier.height(12.dp)) + Text( + "Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-confirm-input"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button( + onClick = onDone, + enabled = SeedBackupGate.confirmEnabled(typed), + modifier = Modifier.testTag("wallet-seed-confirm-done"), + ) { Text("Done") } + } + } + } +} + @Composable private fun TransferCard(t: TransferRow) { Card( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt new file mode 100644 index 0000000..9318753 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt @@ -0,0 +1,176 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The seed-backup gate's rules, on the JVM. + * + * These are the decisions the wallet screen renders from: whether the created + * seed card is still blocking, whether the persistent warning is up, and + * whether the receive address is on screen at all. Pure logic, so no + * Robolectric and no Compose test dependency — same shape as + * `WalletChildStatusTextTest` and `OutboxDetailTest`. + */ +class SeedBackupGateTest { + + /** A wallet the child can actually read: `wallet_balance` returned a value. */ + private val readable = true + + /** `wallet_balance` said "off" (no chain source) or "err" (nothing open). */ + private val notReadable = false + + // --- the confirm word is the TUI's word --------------------------------- + + @Test + fun the_confirm_word_is_the_tui_word() { + // `src/tui.rs` `WalletSetup::CreateSeed` compares against "SEEN". A + // second convention here would be a different gate than the TUI's. + assertEquals("SEEN", SeedBackupGate.CONFIRM_WORD) + } + + @Test + fun a_correct_word_releases_the_block_whatever_its_case_or_padding() { + assertTrue(SeedBackupGate.accepts("SEEN")) + // The TUI compares with `eq_ignore_ascii_case`. + assertTrue(SeedBackupGate.accepts("seen")) + assertTrue(SeedBackupGate.accepts("SeEn")) + // A soft keyboard auto-capitalises and a paste can carry whitespace. + assertTrue(SeedBackupGate.accepts(" seen ")) + } + + @Test + fun a_blank_or_wrong_word_stays_blocked() { + assertFalse(SeedBackupGate.accepts("")) + assertFalse(SeedBackupGate.accepts(" ")) + assertFalse(SeedBackupGate.accepts("SEE")) + // A prefix is not the word: the TUI only fires on the whole match. + assertFalse(SeedBackupGate.accepts("SEENN")) + assertFalse(SeedBackupGate.accepts("seen.")) + // The other word in this flow is the spend-authority one. + assertFalse(SeedBackupGate.accepts("SPEND")) + } + + @Test + fun done_is_dead_until_the_word_is_right() { + assertFalse(SeedBackupGate.confirmEnabled("")) + assertFalse(SeedBackupGate.confirmEnabled("SEENN")) + assertTrue(SeedBackupGate.confirmEnabled("SEEN")) + assertTrue(SeedBackupGate.confirmEnabled("seen")) + } + + // --- the state transitions ---------------------------------------------- + + @Test + fun a_create_starts_unbacked() { + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + @Test + fun an_import_is_backed_up_without_the_gate() { + // The user pasted the seed to get here, so there is nothing to confirm. + assertTrue(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) + } + + @Test + fun a_successful_confirm_marks_the_wallet_backed_up() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.afterConfirm("SEEN", created)) + } + + @Test + fun a_wrong_word_leaves_an_unbacked_wallet_unbacked() { + assertFalse(SeedBackupGate.afterConfirm("", false)) + assertFalse(SeedBackupGate.afterConfirm("nope", false)) + } + + @Test + fun a_wrong_word_cannot_un_confirm_a_backed_up_wallet() { + // Done is disabled for a wrong word, but the flag must not be a way to + // walk a confirmed wallet back into the hidden-address state. + assertTrue(SeedBackupGate.afterConfirm("", true)) + assertTrue(SeedBackupGate.afterConfirm("SPEND", true)) + } + + @Test + fun a_new_create_resets_a_confirmed_wallet_to_unbacked() { + // Create -> confirm -> create again: the second wallet file has its own + // seed, and nobody has read it yet. + val first = + SeedBackupGate.afterConfirm("SEEN", SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + assertTrue(first) + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + // --- what the screen does with the flag --------------------------------- + + @Test + fun a_created_wallet_keeps_the_strip_up_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.warningVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertFalse(SeedBackupGate.warningVisible(confirmed, readable)) + } + + @Test + fun an_imported_wallet_never_shows_the_strip() { + val backedUp = SeedBackupGate.afterWallet(WalletKeyOrigin.Imported) + assertFalse(SeedBackupGate.warningVisible(backedUp, readable)) + assertFalse(SeedBackupGate.warningVisible(backedUp, notReadable)) + } + + @Test + fun a_created_wallet_keeps_the_strip_up_even_before_its_balance_reads() { + // A create is proof a wallet exists, so a child that has not answered + // yet must not be read as "no wallet to warn about". + assertTrue(SeedBackupGate.warningVisible(false, notReadable)) + } + + @Test + fun the_receive_address_is_hidden_while_the_seed_is_unconfirmed() { + assertFalse(SeedBackupGate.receiveAddressVisible(false, readable)) + assertTrue(SeedBackupGate.receiveAddressVisible(true, readable)) + } + + @Test + fun a_created_wallet_hides_its_receive_address_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertFalse(SeedBackupGate.receiveAddressVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertTrue(SeedBackupGate.receiveAddressVisible(confirmed, readable)) + } + + @Test + fun an_install_that_never_created_a_wallet_here_waits_for_a_readable_wallet() { + // `null` is "nothing stored": an install that predates the flag, or one + // that has only configured a chain source. `wallet_balance` returns + // "err" for a configured chain whose child has no wallet open, and a + // first-run user is in exactly that state — nagging them about a seed + // they do not have is the false positive this rule exists to prevent. + assertFalse(SeedBackupGate.warningVisible(null, notReadable)) + assertTrue(SeedBackupGate.receiveAddressVisible(null, notReadable)) + } + + @Test + fun an_unconfirmed_wallet_that_predates_the_flag_is_warned_about_once_it_reads() { + // The user this gate is for: they created a wallet on an older build, + // so nothing is stored, but the child can read the wallet. That is a + // real wallet whose seed nobody has confirmed. + assertTrue(SeedBackupGate.warningVisible(null, readable)) + assertFalse(SeedBackupGate.receiveAddressVisible(null, readable)) + } + + @Test + fun the_strip_says_why_the_address_is_gone() { + // The hiding is only fair if the strip names it; assert the strip is + // not empty and actually mentions the seed and the receive address. + val text = SeedBackupGate.WARNING + assertTrue(text.contains("seed")) + assertTrue(text.contains("receive address")) + assertTrue(text.contains("recovered")) + } +} From 99a4ab640e91841aedf4dcb88bc326e91252daa5 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 03/70] tui: wallet selection screen (F6 -> w) with create as the last row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screen::WalletSelect: a table of saved wallets — name, identity prefix, locator prefix, creation day — the selected row's full identity and locator under it, and a `+ create new wallet` row as the last item. j/k or arrows move, Enter takes the choice, Esc back. Empty, failed and in-flight reads each get their own copy; a wallet with a NULL label, no published locator or no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank. Presentation only. Rows are plain display data (WalletRow) built by the caller; the render path never reads the store, and the selection is by row index because two records may share an identity key. Loading a chosen record into the session is the wallet-store integration step, so the F6 `w` entry opens the screen on its unavailable state until that accessor lands, and the create row works today either way. Evidence: tests/tui_select.rs (16 tests) drives the real draw path through TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one focus marker, a cell-width line budget from 20 to 200 columns, the window disclosure with the create row always visible, hostile labels (ESC/BEL/C1/ bidi/newline/tab) and the crate-local UTC date formatter. --- docs/TUI.md | 23 +- src/tui.rs | 599 +++++++++++++++++++++++++++++++++++++++++++- tests/tui_select.rs | 475 +++++++++++++++++++++++++++++++++++ 3 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 tests/tui_select.rs diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index a72d071..7e7b9eb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + let footer = status_footer_phased( + f.area().width, + &self.me_fp, + &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + budget.max(1).min(total) + }; + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &state) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + let mut screen = String::new(); + for y in 0..h { + for x in 0..w { + screen.push_str(buf[(x, y)].symbol()); + } + screen.push('\n'); + } + screen +} + +#[test] +fn wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\n{screen}" + ); + } + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +} From 5f19a56be34dc22115ceed123a6396c1420e3ecd Mon Sep 17 00:00:00 2001 From: sirius Date: Tue, 22 Sep 2026 00:25:33 -0400 Subject: [PATCH 04/70] sdk: expose the wallet catalogue, the open wallet's keys, and the self profile The Android wallet/profile screens had nothing to call: the core could list wallets, switch the child onto one, read its keys and read/write the self profile, but none of it crossed UniFFI. Core: - Wallet::keys() -> WalletKeys { view_key, spend_key: Option }: two query_key calls against the file the RPC has open. A view-only wallet's -29 is spend_key: None, not an error. WalletKeys' Debug redacts both halves. - Node::wallet_keys() mirrors wallet_create/wallet_seed; refuses locally when no wallet is configured. - Node::active_wallet_filename() -> Option: the file the child is pointed at, None until wallet-child settings exist, so a client can mark the open row. SDK (UniFFI): - records WalletRow / WalletKeys / SelfProfile, and Wire::{wallets, open_wallet, active_wallet_filename, wallet_keys, self_profile, set_self_profile, push_self_profile}. - The rule the clients must express is in the docs: the seed and the private keys come from the OPEN wallet, so there is deliberately no accessor that reads another saved wallet's secrets without opening it. docs/WALLET.md (catalogue + 'secrets belong to the open wallet'), docs/THREAT_MODEL.md (the new on-demand-display exposure surface) and the SDK README are updated in the same commit. --- crates/onionwire-sdk/README.md | 18 ++ crates/onionwire-sdk/src/lib.rs | 385 +++++++++++++++++++++++++++++++- docs/THREAT_MODEL.md | 26 +++ docs/WALLET.md | 32 +++ src/node.rs | 124 ++++++++++ src/wallet.rs | 60 +++++ tests/wallet.rs | 142 ++++++++++++ 7 files changed, 784 insertions(+), 3 deletions(-) diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 1cd7124..9635337 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -104,6 +104,24 @@ val msgs: List = wire.messages(friend.pubkeyHex) // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends + +// 6. Saved wallets, and which one is open. +val wallets: List = wire.wallets() // a store read: never dials +val active: String? = wire.activeWalletFilename() // the open file, or null +val open = wallets.firstOrNull { it.walletFilename == active } +wire.openWallet("onionwire-2") // may restart a running wallet child; a name + // outside the catalogue is refused +val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys +// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer). +// That is not an error. The seed (`walletSeed()`) and these keys always belong +// to `activeWalletFilename()`: to show another wallet's backup, open it first. +// Both are spend secrets — show them from an explicit user action only, never +// log them, never persist them. + +// 7. Your own profile (nickname, bio, Monero address). +val me: SelfProfile = wire.selfProfile() +wire.setSelfProfile("ada", "on the wire", "4AdUnd...") // validated on write +wire.pushSelfProfile(friend.pubkeyHex) // signed `prf`, one-shot and fail-closed ``` All peer references are lowercase hex strings so nothing Rust-shaped leaks into diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index d17f7f3..11ca267 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -28,14 +28,14 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::Message; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::{ChainNetwork, ChainSource}; +use onionwire::wallet::{ChainNetwork, ChainSource, WalletKeys as CoreWalletKeys}; use onionwire::wallet_child::{ChildConfig, WalletChildState}; +use onionwire::{FriendProfile, Message, WalletRecord}; uniffi::setup_scaffolding!(); @@ -540,6 +540,128 @@ impl Wire { .collect()) } + // ---- Wallet catalogue, the open wallet, and its secrets ---- + + /// Every wallet this install remembers, oldest first. + /// + /// A store read: it never dials the wallet RPC or the chain, so it works + /// with the wallet child stopped or never configured. "No wallets" is an + /// empty list, never an error. `WireError.Stopped` after `shutdown`; + /// `WireError.Failed` only when the store itself cannot be read. + /// + /// The Kotlin binding is `Wire.wallets()`. + pub async fn wallets(&self) -> WResult> { + let rows = self.node()?.list_wallets().map_err(WireError::new)?; + Ok(rows.iter().map(wallet_row).collect()) + } + + /// Point the wallet child at a catalogue wallet's file: afterwards the + /// balance, transfers, seed and keys this surface reports are that + /// wallet's. + /// + /// **It may restart a running wallet child.** A live child is stopped and + /// started again onto the new file, which is what makes the change take + /// effect immediately — and why this call is slow (a `.onion` source waits + /// for its SOCKS listener, an in-process chain daemon for its RPC). An idle + /// child is only re-pointed: nothing is spawned, and the change applies at + /// the next [`Wire::start_wallet_child`]. + /// + /// A `filename` the catalogue does not hold is **refused**: the catalogue is + /// the only directory this app keeps wallets in, and a spend-capable child + /// is never pointed at a path a caller invented. Get the name from + /// [`Wire::wallets`]. `WireError.Stopped` after `shutdown`. + pub async fn open_wallet(&self, filename: String) -> WResult<()> { + self.node()?.open_wallet(&filename).map_err(WireError::new) + } + + /// The wallet file the child is currently pointed at, or `None` when no + /// wallet-child settings were ever stored (a fresh install has no open + /// wallet). + /// + /// A picker marks the open row with + /// `row.wallet_filename == active`; every other row means "open it first to + /// see its seed or keys", because the seed and the private keys always come + /// from the file the child has **open**. The value can name a file that is + /// not in the catalogue (an install whose wallet predates it) — that is "no + /// open wallet row", not an error. + /// + /// It never dials and never spawns. `WireError.Stopped` after `shutdown`. + pub async fn active_wallet_filename(&self) -> WResult> { + self.node()? + .active_wallet_filename() + .map_err(WireError::new) + } + + /// The private view key and spend key of the wallet file the child has + /// **open** (`query_key`). This is a dial to the wallet child's loopback + /// RPC, so call it from an explicit user action, not from a refresh loop. + /// + /// `spend_key` is `None` for a view-only wallet: the RPC answers `-29` + /// ("Cannot retrieve spend key") and that is the wallet's own answer, not a + /// failure, so it is not surfaced as one. `WireError.Failed` when no wallet + /// is configured or the child is not answering; `WireError.Stopped` after + /// `shutdown`. + /// + /// The values are spend secrets: show them, never log them, never persist + /// them. `WalletKeys`'s `Debug` redacts both. + pub async fn wallet_keys(&self) -> WResult { + let keys = self.node()?.wallet_keys().await.map_err(WireError::new)?; + Ok(keys_record(keys)) + } + + // ---- This identity's own profile ---- + + /// This identity's own profile (nickname, bio, Monero address) as stored. + /// + /// A store read: never dials. It is the local copy — what friends show for + /// you only changes once [`Wire::push_self_profile`] reaches them. + /// `WireError.Stopped` after `shutdown`. + pub async fn self_profile(&self) -> WResult { + let p = self.node()?.self_profile().map_err(WireError::new)?; + Ok(self_profile_record(&p)) + } + + /// Replace this identity's own profile. + /// + /// Validated before it is written, so a rejected edit leaves the stored + /// profile untouched: a nickname over 64 characters, a bio over 512, or a + /// non-empty address that fails the Monero checksum (the same check `/pay` + /// and `/tip` use) is refused with `WireError.Failed`. An empty address is + /// allowed. + /// + /// It does not tell anyone. Friends still see the previous profile until + /// [`Wire::push_self_profile`] is sent to them. `WireError.Stopped` after + /// `shutdown`. + pub async fn set_self_profile( + &self, + display_name: String, + bio: String, + xmr_addr: String, + ) -> WResult<()> { + self.node()? + .set_self_profile(&display_name, &bio, &xmr_addr) + .map_err(WireError::new) + } + + /// Send this identity's signed profile to one friend, so the nickname and + /// address they show for you are current. + /// + /// One-shot and fail closed: a peer whose onion is down means this fails + /// and **nothing is queued** — no retry, no outbox row (profiles are not + /// chat). Send it again when they are reachable. + /// + /// `pubkey_hex` is the friend's identity pubkey, the encoding + /// [`FriendInfo::pubkey_hex`] carries; an unparseable hex is + /// `WireError.Failed` before anything is dialled. `WireError.Stopped` after + /// `shutdown`. + pub async fn push_self_profile(&self, pubkey_hex: String) -> WResult<()> { + let pk = unhex(&pubkey_hex)?; + self.node()? + .push_self_profile(&pk) + .await + .map_err(WireError::new) + } + /// Send an invoice to a friend: sign an invoice for my receive address and send /// the frame one-shot. Peer onion down → this fails; invoices are not queued. /// @@ -1018,6 +1140,39 @@ fn outbox_row(entry: &OutboxEntry) -> OutboxRow { } } +/// `WalletRecord` → the picker row. `wallet_filename` is the file name only +/// (never a path): the core resolves it inside `$ONIONWIRE_HOME/wallet`. +fn wallet_row(w: &WalletRecord) -> WalletRow { + WalletRow { + id: w.id, + name: w.name.clone(), + wallet_filename: w.wallet_filename.clone(), + onion_locator: w.onion_locator.clone(), + identity_pubkey_hex: hex(&w.identity_pubkey), + created_at: w.created_at, + } +} + +/// The core's key record → the SDK's, with the secrets carried across verbatim +/// (this is a display path; nothing here logs or stores them). +fn keys_record(keys: CoreWalletKeys) -> WalletKeys { + WalletKeys { + view_key: keys.view_key, + spend_key: keys.spend_key, + } +} + +/// `FriendProfile` → the profile screen's record. `updated_at` is deliberately +/// not carried: the SDK surface has no use for it, and a client that wants +/// "did my push land" compares the fields it set. +fn self_profile_record(p: &FriendProfile) -> SelfProfile { + SelfProfile { + display_name: p.display_name.clone(), + bio: p.bio.clone(), + xmr_addr: p.xmr_addr.clone(), + } +} + /// A Monero transfer row for the wallet screen. /// /// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the @@ -1029,6 +1184,71 @@ pub struct TransferRow { pub address: String, } +/// One row of the saved-wallet catalogue, for the wallet picker. +/// +/// Mirrors the core's `WalletRecord`, with the identity pubkey as hex. `id` is +/// the `wallets.id` row id, `wallet_filename` is the file inside +/// `$ONIONWIRE_HOME/wallet` and is what [`Wire::open_wallet`] takes, and the +/// rows come back oldest-first so a list is stable between calls. +/// +/// `identity_pubkey_hex` is the identity this wallet belongs to and is **not** +/// unique; `onion_locator` is a locator that may be empty or stale. Never key a +/// selection, or the roster, on the locator. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletRow { + pub id: i64, + /// The user's label for this wallet. `None` when it was never named, and + /// never an empty string. + pub name: Option, + pub wallet_filename: String, + pub onion_locator: String, + /// The owning identity's ed25519 pubkey, hex — the same encoding + /// [`FriendInfo::pubkey_hex`] carries. + pub identity_pubkey_hex: String, + /// Unix seconds, assigned by the store when the row was created. + pub created_at: i64, +} + +/// The private keys of the **open** wallet file, for a backup screen. +/// +/// Both values are spend secrets: show them only from an explicit user action, +/// never log them, and never persist them. `Debug` is hand-written to redact +/// them so a stray `{:?}` cannot leak a key into a log. +#[derive(Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletKeys { + /// The open wallet file's private view key. + pub view_key: String, + /// The open wallet file's private spend key, or `None` for a view-only + /// wallet. `None` is the wallet's own answer — it has no spend key — and + /// not a failure. + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + +/// This identity's own profile, as the profile screen reads and edits it. +/// +/// It is what friends are shown for this identity once it has been pushed; +/// nothing here is secret (an empty `xmr_addr` is allowed, a non-empty one is +/// validated). +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SelfProfile { + pub display_name: String, + pub bio: String, + /// This identity's Monero address. May be empty. When non-empty the core + /// refuses to store it unless it passes the same address check `/pay` and + /// `/tip` use. + pub xmr_addr: String, +} + /// Where the app-owned wallet child gets its chain from. Mirrors the core's /// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] @@ -1341,8 +1561,8 @@ mod tests { //! handle, which is what a shut-down node must guarantee. A `Wire` with no //! node is exactly the state `shutdown()` leaves behind. use super::*; - use onionwire::Store; use onionwire::outbox::OutboxStatus; + use onionwire::{NewWallet, Store}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2105,4 +2325,163 @@ mod tests { let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } + + // ---- wallet catalogue, the open wallet, its keys, and the self profile ---- + + #[test] + fn wallets_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallets()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn open_wallet_on_a_stopped_handle_is_stopped_error() { + let err = + block_on(stopped_wire().open_wallet("onionwire".to_string())).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn active_wallet_filename_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().active_wallet_filename()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn wallet_keys_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_keys()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().self_profile()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn set_self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().set_self_profile( + "nick".to_string(), + String::new(), + String::new(), + )) + .expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_on_a_stopped_handle_is_stopped_error() { + // Valid 32-byte hex, so the hex parse cannot be the thing that failed: + // the handle is. + let err = + block_on(stopped_wire().push_self_profile("11".repeat(32))).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_rejects_a_pubkey_that_is_not_hex_before_any_work() { + let err = + block_on(stopped_wire().push_self_profile("nope".to_string())).expect_err("must fail"); + // The hex check runs first, so this is `Failed`, not `Stopped`. + assert!(matches!(err, WireError::Failed { .. }), "got {err:?}"); + } + + /// The picker row is the catalogue row, row for row: same id, same file + /// name, same label, and the pubkey as hex. A Kotlin picker keys on + /// `wallet_filename` for [`Wire::open_wallet`], so it has to be exact. + #[test] + fn wallet_rows_carry_the_catalogue_verbatim() { + let home = temp_home(); + let store = Store::open_at_with_passphrase(&home, "wallet-catalogue-pass").unwrap(); + let named = store + .create_wallet(&NewWallet { + name: Some("savings".to_string()), + identity_pubkey: [0xab; 32], + onion_locator: "peer.onion".to_string(), + wallet_filename: "onionwire-1".to_string(), + }) + .unwrap(); + let unnamed = store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [0xab; 32], + onion_locator: String::new(), + wallet_filename: "onionwire-2".to_string(), + }) + .unwrap(); + + let rows: Vec = store + .list_wallets() + .unwrap() + .iter() + .map(wallet_row) + .collect(); + + assert_eq!(rows.len(), 2, "both wallets are listed"); + assert_eq!(rows[0].id, named.id); + assert_eq!(rows[0].name.as_deref(), Some("savings")); + assert_eq!(rows[0].wallet_filename, "onionwire-1"); + assert_eq!(rows[0].onion_locator, "peer.onion"); + assert_eq!(rows[0].identity_pubkey_hex, "ab".repeat(32)); + assert_eq!(rows[0].created_at, named.created_at); + // A wallet created without a label is `None`, never an empty string. + assert_eq!(rows[1].id, unnamed.id); + assert_eq!(rows[1].name, None); + // The locator is a locator: it may be empty, and it is not an identity. + assert_eq!(rows[1].onion_locator, ""); + + std::fs::remove_dir_all(&home).ok(); + } + + #[test] + fn keys_mapping_carries_both_halves_and_the_view_only_answer() { + let both = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: Some("spend-material".to_string()), + }); + assert_eq!(both.view_key, "view-material"); + assert_eq!(both.spend_key.as_deref(), Some("spend-material")); + + let view_only = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: None, + }); + assert_eq!(view_only.view_key, "view-material"); + assert_eq!(view_only.spend_key, None); + } + + /// These two are spend secrets: the record the Kotlin side receives must not + /// print them through `Debug`, or a `{:?}` in a crash log leaks a key. + #[test] + fn wallet_keys_debug_never_prints_a_private_key() { + let keys = keys_record(CoreWalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }); + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + } + + #[test] + fn self_profile_mapping_carries_the_three_editable_fields() { + let core = FriendProfile { + display_name: "nick".to_string(), + bio: "bio".to_string(), + xmr_addr: String::new(), + updated_at: 1_700_000_000, + }; + let got = self_profile_record(&core); + assert_eq!(got.display_name, "nick"); + assert_eq!(got.bio, "bio"); + assert_eq!(got.xmr_addr, ""); + } } diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9781368..b3a7a44 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -249,6 +249,32 @@ the app does not pick a public remote node for them. Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs spend, and RPC credentials: [WALLET.md](WALLET.md). +## The recovery phrase and the private keys are displayable on demand + +Both clients can show the **open** wallet's recovery phrase (`query_key +mnemonic`) and its private view and spend keys (`query_key view_key` / +`spend_key`), from an explicit user action. That is new exposure the threat model +did not previously enumerate: the phone screen — and the Linux TUI window — is +now one of the places a spending secret can be read from. + +- The values come from the wallet file the child has **open**. There is no path + that reads another saved wallet's secret without opening it first, and none + that reads a wallet file directly: the RPC is the only source. +- They are never logged, never written to the store or any other file, and never + placed in an error string; the records that carry them (`WalletKeys`) redact + themselves under `Debug`. They exist in process memory only while a screen + shows them. +- They are shown only from an explicit user action, never on a refresh path. +- What this does **not** stop: a shoulder-surfer, a screen recorder, a + screenshot, or a malicious app with screen-capture permission. Whoever reads + the screen gets the keys; a view-only wallet leaks only the view key + (`spend_key` is `None`), but a spend-capable one leaks everything the file can + spend. +- The spend-authority warning above still applies and is now easier to reach: + the seed that makes a wallet spend-capable can be photographed off the device. + Treat any screen that shows a seed or a private key the way you treat the + wallet file itself. + ## Backup file is the identity `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. diff --git a/docs/WALLET.md b/docs/WALLET.md index 054c48c..8b0255a 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -203,6 +203,36 @@ launches the node *and* the wallet child. `wallet_status()` carries Monero ships **no Android binaries**. Any vendored blob's provenance doc must say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`. +### The wallet catalogue, and which wallet is open + +`wallets()` lists every wallet this install remembers (oldest first), each row +carrying the `wallet_filename` the child opens, its label, the owning identity +pubkey as hex, and the locator. `active_wallet_filename()` returns the file the +child is **currently pointed at** (or `None` on a fresh install), so a picker can +mark the open row. `open_wallet(filename)` switches to a catalogue row: a +running child is stopped and restarted onto the new file, an idle one is only +re-pointed (the change applies at the next `start_wallet_child`), and a file the +catalogue does not hold is refused — the catalogue is the only directory this app +keeps wallets in. + +## Secrets belong to the open wallet + +The seed (`wallet_seed()`, `query_key mnemonic`) and the private keys +(`wallet_keys()` → `query_key view_key` / `query_key spend_key`) are answered by +the wallet file the child has **open**, so they always belong to the row +`active_wallet_filename()` names. There is deliberately no accessor that reads +another saved wallet's seed or keys without opening it: show a backups screen, +then `open_wallet(...)` the row — the UI must say *which* wallet it is showing. +`WalletKeys.spend_key` is `None` for a view-only wallet (the RPC's `-29`), which +is an answer, not an error. + +Both values are spend secrets. They are displayable on demand in the TUI and in +the Android app, are never logged, never written to the store or to disk, and +never put into an error string (the core's `WalletKeys` `Debug` redacts them). +The exposure this creates is enumerated in +[THREAT_MODEL.md](THREAT_MODEL.md), "The recovery phrase and the private keys +are displayable on demand". + ## Create vs import `/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** @@ -263,6 +293,8 @@ Restore from a height at or before the first incoming transaction. | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | | OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | +| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works | +| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key | `ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with: diff --git a/src/node.rs b/src/node.rs index bbd0d24..923d3ca 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1232,6 +1232,43 @@ impl Node { w.mnemonic().await.map_err(|e| e.to_string()) } + /// The private view key and, when the wallet can spend, the private spend + /// key of the wallet file the child currently has **open** (`query_key`). + /// + /// Secrets therefore belong to the open wallet: viewing another saved + /// wallet's keys means opening it first. A view-only wallet answers `None` + /// for `spend_key` instead of an error (the RPC's `-29`). An unconfigured + /// wallet is refused locally, before any dial; a configured but unreachable + /// child surfaces the RPC error. + /// + /// The values are spend secrets: never log them and never persist them. + pub async fn wallet_keys(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.keys().await.map_err(|e| e.to_string()) + } + + /// The wallet file the child is currently pointed at, so a client can mark + /// the open row in the catalogue. `None` when no wallet-child settings have + /// ever been stored (a fresh install): a receive-only install has no open + /// wallet file, and the child never points at one until a wallet is created, + /// imported, or opened. + /// + /// The name is what the child would spawn with, not a message from the + /// running process, and it may not match a catalogue row (an install whose + /// wallet predates the catalogue). Match it against + /// [`Node::list_wallets`] rather than assuming it is there. + pub fn active_wallet_filename(&self) -> Result, String> { + let store = self.store.lock().map_err(|e| e.to_string())?; + let Some(raw) = store.load_wallet_child().map_err(|e| e.to_string())? else { + return Ok(None); + }; + let cfg = ChildConfig::from_record(&raw).map_err(|e| e.to_string())?; + Ok(cfg.map(|cfg| cfg.wallet_filename)) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret — and, like a create, it is remembered /// in the catalogue under its own file name. @@ -3374,4 +3411,91 @@ pub(crate) mod tests { "a refused switch must leave the child where it was" ); } + + /// The active wallet is a child-config fact, not a catalogue fact: a row in + /// the catalogue that the child was never pointed at is not open, and a + /// fresh install has no open wallet at all. + #[tokio::test] + async fn active_wallet_filename_is_none_until_the_child_has_been_pointed() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a fresh install has no open wallet file" + ); + + // A record written before the settings were persisted (creds, no + // source block) is not an open wallet either. + node.store + .lock() + .unwrap() + .save_wallet_child(r#"{"user":"owuser","pass":"ow-pass"}"#) + .unwrap(); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a creds-only record does not name a wallet file" + ); + + test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a catalogue row alone does not open the wallet" + ); + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.active_wallet_filename().expect("read").as_deref(), + Some("onionwire-1"), + "the open wallet is the file the child was pointed at" + ); + } + + /// No wallet, no dial: the refusal is the configured-guard copy, not a + /// connection error, and it happens before any socket is opened. + #[tokio::test] + async fn wallet_keys_without_a_wallet_refuses_without_dialing() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let err = node.wallet_keys().await.expect_err("no wallet configured"); + assert_eq!(err, wallet::NOT_CONFIGURED_MSG); + } + + /// The node-level path a Kotlin caller takes: two `query_key` calls against + /// the open wallet's RPC, with the view-only `-29` arriving as + /// `spend_key: None` rather than as an error. + #[tokio::test] + async fn wallet_keys_of_a_view_only_wallet_returns_no_spend_key() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("spend_key") { + r#"{"jsonrpc":"2.0","id":"0","error":{"code":-29,"message":"The wallet is watch-only. Cannot retrieve spend key."}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"aabbccdd"}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"), + ); + + let keys = node.wallet_keys().await.expect("keys"); + assert_eq!(keys.view_key, "aabbccdd"); + assert_eq!( + keys.spend_key, None, + "the RPC's -29 is the wallet's answer, not a failure" + ); + } } diff --git a/src/wallet.rs b/src/wallet.rs index e4437da..787ee90 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -349,6 +349,27 @@ impl std::fmt::Debug for Endpoint { } } +/// The private keys of the wallet file the RPC currently has open. +/// +/// `view_key` is the private view key; `spend_key` is the private spend key and +/// is `None` — not an error — for a view-only wallet, which has no spend key to +/// hand out. Both are secrets: never log them, never persist them, and never put +/// them in an error string. +pub struct WalletKeys { + pub view_key: String, + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, @@ -807,6 +828,45 @@ impl Wallet { json_str(&v, "key") } + /// The wallet file's private keys, as the RPC reports them: `query_key` + /// `view_key` and `query_key` `spend_key`. + /// + /// Both come from the wallet file the child currently has **open** — this is + /// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC + /// only ever answers for its open file. + /// + /// A view-only wallet has no spend key: its `query_key spend_key` answers + /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to + /// `spend_key: None` rather than an error, matching the `-29` view-only + /// detection the transfer probe already uses. Refuses locally, before any + /// dial, when the wallet is not configured. + /// + /// The two values are spend secrets: never log them, never store them, never + /// put them in an error string. [`WalletKeys`]'s `Debug` redacts both. + pub async fn keys(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "view_key"})) + .await?; + let view_key = json_str(&v, "key")?; + // Asked second and separately: on a view-only wallet this is the call + // that carries the `-29`, and `None` is the honest answer there. + let spend_key = match self + .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) + .await + { + Ok(v) => Some(json_str(&v, "key")?), + Err(e) if e.to_string() == VIEW_ONLY_MSG => None, + Err(e) => return Err(e), + }; + Ok(WalletKeys { + view_key, + spend_key, + }) + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index 9c8649b..0724779 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,5 +1,6 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use ed25519_dalek::SigningKey; @@ -893,6 +894,147 @@ fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); } +/// The two private keys come from the open wallet file, in two `query_key` +/// calls: `view_key` first (always available), `spend_key` second (absent on a +/// view-only wallet). A wallet that can spend answers both. +#[tokio::test] +async fn keys_returns_the_view_and_spend_keys_of_the_open_wallet() { + const VIEW: &str = "0f0e0d0c0b0a09080706050403020100"; + const SPEND: &str = "0102030405060708090a0b0c0d0e0f10"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_result(&format!(r#"{{"key":"{SPEND}"}}"#)), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port).keys().await.expect("keys"); + assert_eq!(keys.view_key, VIEW); + assert_eq!(keys.spend_key.as_deref(), Some(SPEND)); + assert_eq!(calls.load(Ordering::SeqCst), 2, "one call per key"); +} + +/// A view-only wallet has no spend key: the RPC answers `-29` +/// (`WALLET_RPC_ERROR_CODE_WATCH_ONLY`). That is the wallet's answer, so it must +/// come back as `spend_key: None` — not as an error, which would leave the +/// backup screen unable to show the view key. +#[tokio::test] +async fn keys_of_a_view_only_wallet_have_no_spend_key_and_no_error() { + const VIEW: &str = "aabbccddeeff00112233445566778899"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port) + .keys() + .await + .expect("a view-only wallet"); + assert_eq!(keys.view_key, VIEW); + assert_eq!( + keys.spend_key, None, + "view-only means no spend key to hand out" + ); +} + +/// Any *other* RPC failure is a real failure: a view-only `-29` is the only +/// error `keys` turns into `None`. +#[tokio::test] +async fn keys_surfaces_an_rpc_error_that_is_not_the_view_only_answer() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |_: &str| { + if seen.fetch_add(1, Ordering::SeqCst) == 0 { + rpc_result(r#"{"key":"aabbccdd"}"#) + } else { + rpc_error(-1, "wallet file is not open") + } + }), + None, + None, + )); + let err = recording_wallet(port) + .keys() + .await + .expect_err("a spend-key error that is not -29 must not read as view-only"); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn keys_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.keys()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + +/// The keys are spend secrets. `WalletKeys` is the value the whole path carries, +/// so its `Debug` must not print either key — a stray `{:?}` in a log is how a +/// key leaks. +#[test] +fn wallet_keys_debug_never_prints_a_private_key() { + let keys = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }; + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + + let only_view = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: None, + }; + let printed = format!("{only_view:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + printed.contains("None"), + "a view-only wallet must read as None: {printed}" + ); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From b6447f76d6c7a2ae49f629338bd09b539c8432a9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 00:28:39 -0400 Subject: [PATCH 05/70] android: collapse the roster identity block into a dropdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The identity card's full fingerprint wraps to several lines on a phone and pushes the friend list off the first screen. Collapse it: one line by default (label + `shortId(fingerprint)` + chevron), the full fingerprint and the full onion behind a tap, in the order they already had. The `sdk …` line and `keepAliveNote` stay outside the disclosure — the keep-alive denial is the only place that note appears, so hanging it off a collapsed block would hide it. `shortId` is a pure top-level function (`head … tail`, unchanged when the value is no longer than the abbreviation, empty stays empty) so the collapsed line is a slice of the value shown expanded, not a parallel encoding. The expand state is `rememberSaveable`: a rotation keeps what the user chose, and nothing about it belongs in the store. RosterIdTest covers the abbreviation on the JVM (7 cases: the 64-hex fingerprint, the head/tail boundary, custom head/tail, shorter-than-input, empty, single-char ellipsis). --- .../siriusdevops/onionwire/ui/RosterScreen.kt | 53 ++++++++++-- .../siriusdevops/onionwire/ui/RosterIdTest.kt | 84 +++++++++++++++++++ 2 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index ed641dc..b3903cd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Card @@ -27,6 +28,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -51,6 +53,10 @@ fun RosterScreen( onOpenWallet: () -> Unit, ) { var confirmWipe by remember { mutableStateOf(false) } + // Closed by default; `rememberSaveable` so a rotation keeps whatever the + // user chose instead of snapping back to (or away from) the summary. + // Nothing about this is worth persisting to the store. + var identityExpanded by rememberSaveable { mutableStateOf(false) } Scaffold( // The content root below consumes systemBars ∪ ime itself (see @@ -79,11 +85,33 @@ fun RosterScreen( ), ) { Column(Modifier.padding(12.dp)) { - Label("YOU (stable forever)") - Mono(fingerprint) - Spacer(Modifier.height(10.dp)) - Label("ONION (locator — rotates)") - Mono(onion) + // The disclosure header. Collapsed, this one line *is* the + // identity block: the label, the abbreviated fingerprint, + // and a chevron saying there is more behind it. + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { identityExpanded = !identityExpanded }, + verticalAlignment = Alignment.CenterVertically, + ) { + Label("YOU (stable forever)") + if (!identityExpanded) { + Spacer(Modifier.width(8.dp)) + Mono(shortId(fingerprint)) + } + Spacer(Modifier.weight(1f)) + Text( + if (identityExpanded) "▾" else "▸", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (identityExpanded) { + Mono(fingerprint) + Spacer(Modifier.height(10.dp)) + Label("ONION (locator — rotates)") + Mono(onion) + } Spacer(Modifier.height(10.dp)) Text( "sdk $sdkVersion · identity = ed25519 pubkey", @@ -194,6 +222,21 @@ private fun FriendRow(f: FriendInfo, onClick: () -> Unit) { } } +/** + * The compact stand-in for a long identity string: `head` characters, an + * ellipsis, then `tail` characters. Pure, so the roster's collapsed line and + * its unit test agree on what "short" means. + * + * A string no longer than the abbreviation is returned unchanged — the + * abbreviation must never grow a value, and a short value must never come back + * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/ + * `takeLast` cannot split a surrogate pair here. + */ +fun shortId(id: String, head: Int = 6, tail: Int = 4): String { + if (id.length < head + tail + 1) return id + return id.take(head) + "…" + id.takeLast(tail) +} + @Composable fun Label(text: String) { Text( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt new file mode 100644 index 0000000..d890fb3 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt @@ -0,0 +1,84 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * `shortId`, the roster's collapsed identity line, on the JVM. + * + * The collapsed card shows the fingerprint through this function, and the + * expanded one shows the raw value; the two must never disagree about what the + * fingerprint *is*, so the abbreviation has to be a pure slice of the input + * with nothing invented. Pure logic, no Robolectric — same shape as + * `SeedBackupGateTest` and `WalletChildStatusTextTest`. + */ +class RosterIdTest { + + /** An ed25519 pubkey as the core prints it: 64 lowercase hex characters. */ + private val fingerprint = + "9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49" + + // --- the long case ------------------------------------------------------- + + @Test + fun a_long_fingerprint_becomes_head_ellipsis_tail() { + assertEquals("9f2c41…6a49", shortId(fingerprint)) + } + + @Test + fun the_abbreviation_is_a_slice_of_the_input_not_a_re_encoding() { + // The head and the tail must be literally the input's own characters: + // a summary that cannot be checked against the full value is worse than + // no summary. + val short = shortId(fingerprint) + assertEquals(fingerprint.take(6), short.substringBefore("…")) + assertEquals(fingerprint.takeLast(4), short.substringAfter("…")) + // Nothing invented to pad the middle: 6 + "…" + 4. + assertEquals(11, short.length) + } + + @Test + fun head_and_tail_are_call_sites_choice() { + assertEquals("9f2c…6a49", shortId(fingerprint, head = 4, tail = 4)) + assertEquals("9f2c41ab77…3b6a49", shortId(fingerprint, head = 10, tail = 6)) + } + + // --- the short case ------------------------------------------------------ + + @Test + fun a_string_shorter_than_head_tail_plus_one_is_returned_unchanged() { + // head + tail + 1 == 11 here, so anything of 10 characters or fewer has + // no middle worth hiding. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abc", shortId("abc")) + assertEquals("a", shortId("a")) + } + + @Test + fun the_first_length_that_abbreviates_is_head_tail_plus_one() { + // The boundary, both sides: 10 unchanged, 11 abbreviated to the same + // length with the middle character collapsed. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abcdef…hijk", shortId("abcdefghijk")) + } + + // --- the empty case ------------------------------------------------------ + + @Test + fun an_empty_string_stays_empty() { + // `ready.fingerprint` is always populated in practice, but the function + // must not turn "nothing" into "…" on a card that is already on screen. + assertEquals("", shortId("")) + } + + // --- the shape the card relies on --------------------------------------- + + @Test + fun the_ellipsis_is_the_single_character_one() { + // U+2026, not three dots: the collapsed line is monospace and a + // three-dot tail is four cells where the design budgeted one. + assertTrue(shortId(fingerprint).contains("\u2026")) + assertEquals(1, shortId(fingerprint).count { it == '\u2026' }) + } +} From 812c259f460112d4bda06877f20a172311eacec7 Mon Sep 17 00:00:00 2001 From: apk-dev Date: Tue, 22 Sep 2026 01:23:47 -0400 Subject: [PATCH 06/70] android: saved-wallets screen (list, select, back up the open wallet) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app could hold several wallets and show none of them. Add the screen that lists the store's catalogue, marks the one the wallet child has open, switches to another on a tap, and — for the open one only — shows its recovery phrase and private keys. Everything secret here belongs to the file the child currently has open: `query_key` is answered by that file and no other, so the seed card and the keys card hang off `active_wallet_filename()`, not off a row. On a row that is not the open one both actions are dead and say why ("open this wallet to view its backup") instead of opening it under the user — switching wallets is a deliberate tap, because `open_wallet` stops and restarts a running child. The phrase keeps the existing treatment: the wallet screen's own `SeedBackupCard`, widened from `private` to `internal` rather than copied, so the gate constants are still the one `SeedBackupGate`. The keys card shows the view key always and the spend key when there is one; a view-only wallet says "view-only wallet — no spend key" in words, because `null` is the wallet's own answer and not a failure. Neither value is logged, persisted, tagged, or held in saved state, and both are dropped on dispose. The catalogue is re-read on entry and on Refresh, never cached from app start, so a wallet created on the wallet screen after this one was first opened shows up without restarting the app. An empty catalogue ("No saved wallets yet") and a read failure ("could not read the wallet catalogue" + the core's text) are rendered as the two different states they are. The gate is pure Kotlin in the new file and `WalletManagerTest` covers it on the JVM (17 cases): the row label's name/blank/whitespace fallback, which child states count as readable, and whether the secret actions are offered for a row. --- .../siriusdevops/onionwire/MainActivity.kt | 11 +- .../siriusdevops/onionwire/WireViewModel.kt | 46 ++ .../onionwire/ui/WalletManagerScreen.kt | 584 ++++++++++++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 14 +- .../onionwire/ui/WalletManagerTest.kt | 153 +++++ 5 files changed, 806 insertions(+), 2 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 1d14fa6..200c2b8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -29,6 +29,7 @@ import com.siriusdevops.onionwire.ui.RosterScreen import com.siriusdevops.onionwire.ui.RotateScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.UnlockScreen +import com.siriusdevops.onionwire.ui.WalletManagerScreen import com.siriusdevops.onionwire.ui.WalletScreen import com.siriusdevops.onionwire.ui.OnionWireTheme import kotlinx.coroutines.launch @@ -133,7 +134,15 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str } composable("wallet") { - WalletScreen(vm = vm, onBack = { nav.popBackStack() }) + WalletScreen( + vm = vm, + onBack = { nav.popBackStack() }, + onOpenWallets = { nav.navigate("wallets") }, + ) + } + + composable("wallets") { + WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) } composable( diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 7be3c6a..3c071c8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -41,6 +41,8 @@ import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.TransferRow import uniffi.onionwire_sdk.WalletChildStatus +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -619,6 +621,50 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun walletSeed(): Result = runCatching { requireWire().walletSeed() } + // --- Wallet catalogue, the open wallet, and its secrets ---------------- + // The saved-wallets screen's reads. The catalogue is a store read that + // never dials, so it goes to [Dispatchers.IO] like the other store reads in + // this file — a SQLCipher decrypt on the main thread is an ANR waiting for a + // slow device. + + /** + * Every wallet this install remembers, oldest first. + * + * A store read: it works with the wallet child stopped or never configured, + * and "no wallets" is an empty list rather than a failure — the caller must + * not render the two alike. + */ + suspend fun wallets(): Result> = + withContext(Dispatchers.IO) { runCatching { requireWire().wallets() } } + + /** + * The file name of the wallet the child currently has open, or null when it + * has none. The catalogue's in-use marker is this and nothing else. + */ + suspend fun activeWalletFilename(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().activeWalletFilename() } } + + /** + * Point the wallet child at a catalogue wallet's file. + * + * Slow on purpose: a live child is stopped and started again onto the new + * file. The core refuses a name the catalogue does not hold, and that + * refusal is surfaced verbatim to the caller. + */ + suspend fun openWallet(filename: String): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } + + /** + * The **open** wallet's private keys, for the saved-wallets screen. + * + * Both values are spend secrets: only ever called from an explicit tap, + * never logged, never persisted, and dropped when the screen goes. There is + * deliberately no accessor for another catalogue row's keys — the only way + * to read a saved wallet's keys is to open it first. + */ + suspend fun walletKeys(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().walletKeys() } } + fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() }.getOrElse { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt new file mode 100644 index 0000000..d041575 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -0,0 +1,584 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.launch +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +// --------------------------------------------------------------------------- +// The rules this screen renders from, as pure Kotlin so `WalletManagerTest` +// covers them on the JVM without a device. Same shape as `SeedBackupGate` and +// `WalletChildStatusText`: the composables below only lay these decisions out. +// --------------------------------------------------------------------------- + +/** + * A catalogue row's label: the user's name for the wallet, or the file name + * when there is none. + * + * `WalletRow.name` is documented as `None` when the wallet was never named and + * "never an empty string", but a blank string is treated as absent here too — + * a row labelled with spaces is a row the user cannot identify. + */ +internal fun walletRowLabel(name: String?, filename: String): String = + name?.takeIf { it.isNotBlank() } ?: filename + +/** + * A row's creation date, from the store's unix seconds. + * + * `created_at <= 0` is not a date: the store assigns it on insert, so anything + * else is a row that predates that — say so rather than render 1970. + */ +internal fun walletRowDate(createdAt: Long): String { + if (createdAt <= 0L) return "date unknown" + return Instant.ofEpochSecond(createdAt) + .atZone(ZoneId.systemDefault()) + .format(DateTimeFormatter.ISO_LOCAL_DATE) +} + +/** + * Whether the wallet child has a wallet open that the RPC answers for. + * + * The core's `state` is the only honest signal available here: `connecting` + * means its wallet RPC has not answered, `off`/`exited` mean there is no child + * at all, and `syncing`/`ready` mean it answered — the chain being behind is + * irrelevant to whether the open wallet's keys can be read. A `null` state is + * "nothing read yet", which is not readable. + */ +internal fun walletChildReadable(state: String?): Boolean = + state == "ready" || state == "syncing" + +/** + * Whether the open wallet's secrets may be offered for the row named + * [rowFilename]. + * + * Both halves are load-bearing: + * + * - **active**: the seed and the private keys come from `query_key` against + * the file the child currently has open, so they belong to exactly one + * wallet. A non-active row's buttons stay dead instead of quietly opening + * that wallet under the user — switching is a deliberate tap, not a side + * effect of asking for a backup. + * - **readable**: with no child running there is no file open, and + * `wallet_seed()` / `wallet_keys()` can only fail. Offering a button that + * always errors is worse than saying why it is off. + */ +internal fun walletSecretsEnabled( + activeFilename: String?, + rowFilename: String, + walletReadable: Boolean, +): Boolean = walletReadable && activeFilename != null && activeFilename == rowFilename + +/** + * Why the secret actions are off, in words — or `null` when they are on. + * + * The two reasons are different states of the world and are not collapsed: + * "this is not the open wallet" is fixed by tapping the row, "the child is not + * running" is fixed on the wallet screen. The first wording is the card's own. + */ +internal fun walletSecretsBlockedReason( + isActive: Boolean, + walletReadable: Boolean, +): String? = when { + !isActive -> "open this wallet to view its backup" + !walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup" + else -> null +} + +/** + * The saved-wallet catalogue: every wallet this install remembers, which one is + * open now, and — for that one — its recovery phrase and private keys. + * + * Three properties are deliberate and are the whole point of the screen: + * + * - The catalogue is re-read on entry and on Refresh, never cached from app + * start, so a wallet created on the wallet screen after this screen was + * first opened shows up without restarting the app. + * - A tap opens a row's file through `open_wallet(filename)` and reloads, so + * the in-use marker moves. The core refuses a name outside the catalogue, + * and its refusal is shown verbatim. + * - The secrets belong to the **open** wallet only. They are read on an + * explicit tap, are never shown for a row that is not the open one, and are + * never logged, persisted, put in a `testTag`/`contentDescription`, or held + * in saved state (`remember`, not `rememberSaveable`, and cleared on + * dispose). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun WalletManagerScreen( + vm: WireViewModel, + onBack: () -> Unit, +) { + val child by vm.walletChild.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + + /** `null` is "not read yet"; an empty list is a catalogue with no rows. */ + var rows by remember { mutableStateOf?>(null) } + /** The file name the core reports as open, or null when it reports none. */ + var active by remember { mutableStateOf(null) } + /** A catalogue/active-wallet read failure, distinct from an empty list. */ + var listError by remember { mutableStateOf(null) } + /** A failed open, verbatim from the core. */ + var actionError by remember { mutableStateOf(null) } + /** The file name currently being opened, so the row can say so. */ + var opening by remember { mutableStateOf(null) } + + // The seed on the blocking card, and the typed confirm word. Neither is + // persisted: a spend key lives in this composition and nowhere else. + var seed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } + // The open wallet's private keys, only ever set by an explicit tap on + // "Private keys". Null means no card. + var keys by remember { mutableStateOf(null) } + var keysError by remember { mutableStateOf(null) } + + suspend fun reload() { + vm.wallets().fold( + onSuccess = { + rows = it + listError = null + }, + onFailure = { + rows = null + listError = it.message ?: it.toString() + }, + ) + vm.activeWalletFilename().fold( + onSuccess = { active = it }, + onFailure = { + // Same store as the list: a failure here is a read failure, not + // "no wallet is open", and it must not be rendered as one. + active = null + if (listError == null) { + listError = it.message ?: it.toString() + } + }, + ) + } + + /** Open a row's file, then re-read so the in-use marker moves. */ + fun open(filename: String) { + if (opening != null) return + scope.launch { + actionError = null + opening = filename + vm.openWallet(filename).fold( + onSuccess = { reload() }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + opening = null + } + } + + /** + * "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 + * seed" — one gate, one card, no second ungated display. + */ + fun showPhrase() { + scope.launch { + actionError = null + vm.walletSeed().fold( + onSuccess = { + seed = it + seedConfirm = "" + }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + } + } + + /** + * "Private keys": read the open wallet's keys once, on this tap. Failure is + * shown where the card would be, so a wallet that cannot answer says so + * instead of looking like an empty one. + */ + fun showKeys() { + scope.launch { + actionError = null + keysError = null + vm.walletKeys().fold( + onSuccess = { keys = it }, + onFailure = { keysError = it.message ?: it.toString() }, + ) + } + } + + LaunchedEffect(Unit) { + // The cached child read never dials, so the screen paints; the live + // probe after it is what tells the truth about whether a wallet is + // open, which is what the secret actions hang on. + vm.paintWalletChildCached() + reload() + vm.refreshWalletChild() + } + + // Nothing here is `rememberSaveable`, so leaving the screen drops the + // composition's state — including the seed and the keys. Dropping the + // reference is the strongest wipe a Kotlin String allows (see + // `SeedBackupCard`); this makes it explicit rather than incidental. + DisposableEffect(Unit) { + onDispose { + seed = null + seedConfirm = "" + keys = null + keysError = null + } + } + + val walletReadable = walletChildReadable(child?.state) + + Scaffold( + // Root owns systemBars ∪ ime, exactly as the wallet screen does (see + // `screenContentInsets`). + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + TopAppBar( + title = { Text("Saved wallets") }, + navigationIcon = { + TextButton(onClick = onBack) { Text("Back") } + }, + actions = { + TextButton( + onClick = { + scope.launch { + vm.refreshWalletChild() + reload() + } + }, + ) { Text("Refresh") } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + ), + ) + }, + ) { pad -> + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()), + ) { + // The blocking seed card, when a phrase is on screen: the whole + // body, exactly as on the wallet screen. Done is dead until the + // confirm word is typed, and the app-bar Back still leaves. + val shownSeed = seed + if (shownSeed != null) { + SeedBackupCard( + seed = shownSeed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + vm.confirmWalletSeed(seedConfirm) + seed = null + seedConfirm = "" + }, + ) + actionError?.let { ErrorText(it) } + return@Column + } + + keys?.let { k -> + PrivateKeysCard( + keys = k, + warning = vm.spendAuthorityWarning(), + onDone = { keys = null }, + ) + } + keysError?.let { message -> + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("could not read the open wallet's private keys") + Spacer(Modifier.height(4.dp)) + Text(message, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { keysError = null }) { Text("Dismiss") } + } + } + } + + actionError?.let { ErrorText(it) } + + val listed = rows + when { + // A read failure is not an empty catalogue, and the two must + // not read alike: one is "the store did not answer", the other + // is "you have no wallets yet". + listError != null -> Column(Modifier.padding(12.dp)) { + Text( + "could not read the wallet catalogue", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(4.dp)) + Text( + listError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") } + } + + listed == null -> Text( + "loading…", + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(12.dp), + ) + + listed.isEmpty() -> Column(Modifier.padding(12.dp)) { + Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text( + "Wallets this install remembers show up here. Create or import one " + + "on the wallet screen and it appears on the next look.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Button(onClick = onBack) { Text("Create or import a wallet") } + } + + else -> { + Text( + "${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + listed.forEach { row -> + val isActive = active != null && active == row.walletFilename + WalletRowCard( + row = row, + isActive = isActive, + secretsEnabled = walletSecretsEnabled( + activeFilename = active, + rowFilename = row.walletFilename, + walletReadable = walletReadable, + ), + blockedReason = walletSecretsBlockedReason( + isActive = isActive, + walletReadable = walletReadable, + ), + opening = opening == row.walletFilename, + onOpen = { open(row.walletFilename) }, + onShowPhrase = { showPhrase() }, + onShowKeys = { showKeys() }, + ) + } + } + } + } + } +} + +/** + * One catalogue row: what it is called, which file it is, when it was created, + * and whether it is the open one. + * + * The open row is not tappable. Re-opening it would stop and restart a running + * wallet child onto the file it already has open — a slow no-op whose only + * effect is to make the screen look like it did something. + */ +@Composable +private fun WalletRowCard( + row: WalletRow, + isActive: Boolean, + secretsEnabled: Boolean, + blockedReason: String?, + opening: Boolean, + onOpen: () -> Unit, + onShowPhrase: () -> Unit, + onShowKeys: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + walletRowLabel(row.name, row.walletFilename), + style = MaterialTheme.typography.titleSmall, + ) + when { + isActive -> Text( + "in use", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + opening -> Text( + "opening…", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + else -> Text( + "tap to open", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Spacer(Modifier.height(4.dp)) + Text( + "file ${row.walletFilename}", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Text( + "created ${walletRowDate(row.createdAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) { + Text("Recovery phrase") + } + OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) { + Text("Private keys") + } + } + blockedReason?.let { + Spacer(Modifier.height(4.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * The open wallet's private keys, shown only after an explicit tap. + * + * The view key is always there; the spend key only when the wallet has one. + * A view-only wallet says so in words — it has no spend key, and rendering + * that as a failure would teach the user to read a normal wallet as a broken + * one. The values are spend secrets: no `testTag`, no `contentDescription`, + * no logging, no persistence, and the card is dropped when the screen goes. + */ +@Composable +private fun PrivateKeysCard( + keys: WalletKeys, + warning: String, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Text( + "view key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + keys.viewKey, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Spacer(Modifier.height(8.dp)) + val spend = keys.spendKey + if (spend != null) { + Text( + "spend key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + spend, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } else { + Text( + "view-only wallet — no spend key", + style = MaterialTheme.typography.bodyMedium, + ) + } + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button(onClick = onDone) { Text("Done") } + } + } + } +} + +/** A display-ready failure line. Never carries a secret; callers pass errors. */ +@Composable +private fun ErrorText(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index ec98015..f6ea31c 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -70,6 +70,7 @@ private enum class SetupKind { Create, Import } fun WalletScreen( vm: WireViewModel, onBack: () -> Unit, + onOpenWallets: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() @@ -161,6 +162,12 @@ fun WalletScreen( navigationIcon = { TextButton(onClick = onBack) { Text("Back") } }, + // The saved-wallet catalogue is its own screen: this one is the + // open wallet, and switching wallets restarts the child, so the + // picker does not belong in this page's scroll. + actions = { + TextButton(onClick = onOpenWallets) { Text("Wallets") } + }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, ), @@ -548,9 +555,14 @@ private fun UnbackedSeedCard( * The seed is a Kotlin `String`, so it cannot be wiped in place the way the * TUI's `Zeroizing` is; dropping the reference is the strongest thing * available here. That is another reason it is never written to disk. + * + * `internal` rather than `private`: the saved-wallets screen shows the same + * card for the open wallet's recovery phrase, and a second copy of this gate + * (or of its constants) is the thing that would eventually disagree with this + * one. */ @Composable -private fun SeedBackupCard( +internal fun SeedBackupCard( seed: String, typed: String, onTyped: (String) -> Unit, diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt new file mode 100644 index 0000000..99a35e4 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -0,0 +1,153 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The saved-wallets screen's rules, on the JVM. + * + * These are the decisions the screen renders from: what a catalogue row is + * called, whether the child has a wallet open at all, and whether the two + * secret actions may be offered for a given row. Pure logic, so no Robolectric + * and no Compose test dependency — same shape as `SeedBackupGateTest` and + * `WalletChildStatusTextTest`. + */ +class WalletManagerTest { + + private val openFile = "onionwire-main" + private val otherFile = "onionwire-second" + + /** The core's `wallet_status().state` for a child that answered. */ + private val readable = true + + /** No child, or one whose wallet RPC has not answered. */ + private val notReadable = false + + // --- what a row is called ----------------------------------------------- + + @Test + fun a_named_wallet_is_labelled_with_its_name() { + assertEquals("spending", walletRowLabel("spending", openFile)) + } + + @Test + fun an_unnamed_wallet_falls_back_to_its_file_name() { + assertEquals(openFile, walletRowLabel(null, openFile)) + } + + @Test + fun a_blank_name_counts_as_absent() { + // `WalletRow.name` is documented as never an empty string, but a + // whitespace label is a row the user cannot identify either way. + assertEquals(openFile, walletRowLabel("", openFile)) + assertEquals(openFile, walletRowLabel(" ", openFile)) + } + + @Test + fun a_name_is_not_trimmed_out_of_the_label() { + // Only the *blank* case falls back. A name with padding is still the + // user's name and is shown as stored. + assertEquals(" spending ", walletRowLabel(" spending ", openFile)) + } + + // --- is the child reading a wallet at all -------------------------------- + + @Test + fun only_an_answered_wallet_rpc_counts_as_readable() { + // `connecting` is "the RPC has not answered"; `off` and `exited` are + // "there is no child". None of them can answer a key query. + assertTrue(walletChildReadable("ready")) + assertTrue(walletChildReadable("syncing")) + assertFalse(walletChildReadable("connecting")) + assertFalse(walletChildReadable("off")) + assertFalse(walletChildReadable("exited")) + } + + @Test + fun nothing_read_yet_is_not_readable() { + assertFalse(walletChildReadable(null)) + } + + @Test + fun a_behind_chain_still_counts_as_readable() { + // Syncing means the RPC answered: the wallet's keys do not need the + // chain to be caught up. + assertTrue(walletChildReadable("syncing")) + } + + // --- whether the secret actions are offered ------------------------------ + + @Test + fun the_open_wallets_secrets_are_offered() { + assertTrue(walletSecretsEnabled(openFile, openFile, readable)) + } + + @Test + fun another_wallets_secrets_are_not_offered() { + // The seed and the keys come from the file the child has open. A row + // that is not the open one must not read as its own backup. + assertFalse(walletSecretsEnabled(openFile, otherFile, readable)) + } + + @Test + fun nothing_open_means_no_secrets_for_any_row() { + assertFalse(walletSecretsEnabled(null, openFile, readable)) + } + + @Test + fun the_open_wallet_offers_no_secrets_while_the_child_is_not_reading_it() { + // Active but no answer: `wallet_seed()` / `wallet_keys()` can only + // fail, so the buttons stay dead rather than always erroring. + assertFalse(walletSecretsEnabled(openFile, openFile, notReadable)) + assertFalse(walletSecretsEnabled(openFile, otherFile, notReadable)) + assertFalse(walletSecretsEnabled(null, openFile, notReadable)) + } + + // --- and why they are off, in words -------------------------------------- + + @Test + fun an_enabled_row_has_nothing_to_explain() { + assertNull(walletSecretsBlockedReason(isActive = true, walletReadable = readable)) + } + + @Test + fun a_row_that_is_not_open_says_to_open_it() { + val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable) + assertEquals("open this wallet to view its backup", why) + } + + @Test + fun an_open_wallet_with_no_child_says_the_child_is_not_running() { + val why = walletSecretsBlockedReason(isActive = true, walletReadable = notReadable) + assertTrue(why != null && why.contains("not running")) + // The two reasons are different fixes and must not read alike. + assertFalse(why == walletSecretsBlockedReason(isActive = false, walletReadable = readable)) + } + + // --- the created-at column ---------------------------------------------- + + @Test + fun a_stored_created_at_renders_as_a_date() { + // 2021-01-01T00:00:00Z. + val rendered = walletRowDate(1609459200L) + assertTrue("got '$rendered'", Regex("""\d{4}-\d{2}-\d{2}""").matches(rendered)) + } + + @Test + fun a_later_created_at_sorts_after_an_earlier_one() { + // The store hands the rows back oldest-first; the rendered date must + // not invert that order in the list. + assertTrue(walletRowDate(1700000000L) > walletRowDate(1609459200L)) + } + + @Test + fun a_row_with_no_assigned_created_at_says_so() { + // The store assigns `created_at` on insert, so 0 is a row that predates + // that — not 1970, and not "today". + assertEquals("date unknown", walletRowDate(0L)) + assertEquals("date unknown", walletRowDate(-1L)) + } +} From 775f2e88be31b9991d543016d26a6093e111f5b9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 02:12:32 -0400 Subject: [PATCH 07/70] =?UTF-8?q?android:=20profile=20screen=20=E2=80=94?= =?UTF-8?q?=20nickname=20+=20Monero=20receiving=20address?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone's half of the TUI's `/profile`. A `Profile` action on the roster's app bar opens `ui/ProfileScreen.kt`: nickname, bio, and the Monero address friends pay to, all three loaded from the store and written back through the core's own validation. - The address is checked with `uniffi.onionwire_sdk.checkAddress` *before* the write, so a typo is refused with the typed text still in the field instead of surfacing as a store error afterwards. An empty address is allowed and is labelled with its consequence: with no profile address and no running wallet child the core has nothing to hand a payer. - The bio is carried, not owned: a save that did not touch the field writes back the value read from the store immediately before the write, so a bio set in the TUI cannot be blanked from the phone. - On save the profile is pushed to **every** friend in the roster, one-shot and fail-closed per friend like the TUI's `save_profile`. A push failure is not a save failure: the status line always starts with `profile saved` and names the count, with each failure listed by petname (else shortened fingerprint). Every decision the screen makes is a pure function in the new file, covered by `ProfileDraftTest` (21 cases) on the JVM: the save-button rule (dead until the read lands, dead while the form is unchanged), the address branch, the bio rule, label selection and the status-line aggregation. Verified on AVD ow35 (x86_64 slice, emulator-5560): the roster app bar carries `Profile`; nickname/bio/address survive `am force-stop` + relaunch; an invalid address is refused before the write; a save with an empty roster reports `profile saved`; with one (self-)peer in the roster a save reports `profile saved · sent to 1 friend`, and with the emulator's network cut the same save reports `profile saved · sent to 0 of 1 friend · failed: