From 0043fa0b34827de84f7fe446eccac97c709b04eb Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:57:55 -0400 Subject: [PATCH 01/70] node: remember a created wallet in the store's catalogue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A wallet created in-app was never remembered: `Node::wallet_create` called the RPC and returned the seed, and the wallet file name was the one hardcoded `wallet::DEFAULT_WALLET_FILENAME` ("onionwire"). A second create reused that name, so the RPC refused it (or opened the first wallet's file) and no row was ever written — the "cannot create a new wallet, and nothing survives a restart" report. Creation and import now go through the catalogue (t_64c9ba3c's `Store::{create_wallet,list_wallets}`): - each create/import gets its own file name, `onionwire-` for the first `n` the catalogue does not hold, so several wallets coexist; - the stored row (id, identity, locator, file, created_at) is returned: `Node::wallet_create` -> `CreatedWallet` (row + the one-time seed, with a redacting `Debug`), `Node::wallet_restore` -> `WalletRecord`; - `Node::list_wallets` reads the catalogue without dialing; - the child config is re-pointed at the new file (read-modify-write, so the sealed RPC creds survive) — a row the child never opens would still be a broken wallet. The SDK keeps its UniFFI signature (`create_wallet -> String` seed, `import_wallet -> ()`), so no Kotlin change: it unwraps `.seed`. TDD: 5 new `src/node.rs` cases (row + list, two wallets + reopen, import, wallet-off empty list, child re-pointed) over a loopback wallet-RPC mock. `cargo test --locked` exit 0, `cargo clippy --locked --all-targets -- -D warnings` clean, and the same two commands are clean in `crates/onionwire-sdk`. --- crates/onionwire-sdk/src/lib.rs | 13 +- src/node.rs | 258 ++++++++++++++++++++++++++++++-- src/tui.rs | 6 +- 3 files changed, 262 insertions(+), 15 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..4040664 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -587,20 +587,27 @@ impl Wire { /// Create a new spend-capable wallet. Returns the 25-word seed once so the /// UI can show a backup screen. The user does not paste a key on this path. /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + /// + /// The core also records the new wallet in its catalogue (`Node::wallet_create` + /// returns the stored row); the seed is what this surface carries. pub async fn create_wallet(&self, password: String) -> WResult { - self.node()? + Ok(self + .node()? .wallet_create(&password) .await - .map_err(WireError::new) + .map_err(WireError::new)? + .seed) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. + /// that takes a user-supplied secret. Like a create, the core records the + /// imported wallet in its catalogue. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { self.node()? .wallet_restore(&password, &seed) .await .map_err(WireError::new) + .map(|_| ()) } /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for diff --git a/src/node.rs b/src/node.rs index fcc8015..120696b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -28,7 +28,9 @@ use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; -use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; +use crate::store::{ + Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; @@ -80,6 +82,29 @@ impl Drop for WorkerHandle { } } +/// A wallet just created on the wallet RPC and recorded in the store's +/// catalogue: the row is what makes it survive a restart, and the seed is the +/// one-time backup the UI shows before the wallet is used. The caller owns +/// wiping `seed` (the TUI moves it straight into a `Zeroizing`). +pub struct CreatedWallet { + /// The stored catalogue row, with the id and `created_at` the store + /// assigned. `wallet_filename` is the file this wallet lives in. + pub record: WalletRecord, + /// The 25-word seed, returned once by the create path. + pub seed: String, +} + +/// Hand-written so a stray `{:?}` cannot print the seed: the record is the +/// wallet, the mnemonic is the money. +impl std::fmt::Debug for CreatedWallet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CreatedWallet") + .field("record", &self.record) + .field("seed", &"") + .finish() + } +} + pub struct Node { home: PathBuf, store: Arc>, @@ -1167,27 +1192,106 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } - /// Create a new spend-capable wallet. Returns the seed once for backup. - /// The user never pastes a key on this path. - pub async fn wallet_create(&self, password: &str) -> Result { + /// Create a new spend-capable wallet and record it in the catalogue. The + /// user never pastes a key on this path. + /// + /// The wallet file gets its own name ([`Self::next_wallet_filename`]): + /// `wallet_filename` is UNIQUE, so a second create that reused the old + /// hardcoded name would open the first wallet's file — or be refused by the + /// RPC outright, which is the "cannot create a new wallet" failure. The + /// stored row is what makes the wallet survive a restart; the wallet dir is + /// not scanned. + pub async fn wallet_create(&self, password: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + let filename = self.next_wallet_filename()?; + let seed = w + .create_wallet(&filename, password) .await - .map_err(|e| e.to_string()) + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} created but the child is not pointed at it: {e}") + })?; + Ok(CreatedWallet { record, seed }) } /// 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> { + /// that takes a user-supplied secret — and, like a create, it is remembered + /// in the catalogue under its own file name. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + let filename = self.next_wallet_filename()?; + w.restore_wallet(&filename, password, seed) .await + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} imported but the child is not pointed at it: {e}") + })?; + Ok(record) + } + + /// Every wallet this install remembers, oldest first. A store read: it must + /// work with no wallet RPC configured, and it never dials. + pub fn list_wallets(&self) -> Result, String> { + self.store + .lock() + .map_err(|e| e.to_string())? + .list_wallets() + .map_err(|e| e.to_string()) + } + + /// The file name a wallet created now should live in. `wallet_filename` is + /// UNIQUE and the catalogue is the only directory the app has, so this is + /// `-` for the first `n` the catalogue does not already hold. + fn next_wallet_filename(&self) -> Result { + let taken = self.list_wallets()?; + for n in 1.. { + let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); + if !taken.iter().any(|w| w.wallet_filename == candidate) { + return Ok(candidate); + } + } + unreachable!("an unused wallet file name always exists") + } + + /// Point the wallet child at a wallet file. A read-modify-write of the + /// sealed record, so the generated RPC creds and every other setting are + /// kept. A running child is not restarted: the change applies on the next + /// `start_wallet_child`. + fn point_child_at(&self, filename: &str) -> Result<(), String> { + let mut cfg = self.wallet_child_config(); + if cfg.wallet_filename == filename { + return Ok(()); + } + cfg.wallet_filename = filename.to_string(); + self.set_wallet_child_config(&cfg) + } + + /// Add a freshly created wallet file to the catalogue: this node's identity + /// (several wallets may share one) and the onion it is reachable at right + /// now (a locator, and empty until the HS publishes). + fn record_wallet(&self, filename: &str) -> Result { + let new = NewWallet { + name: None, + identity_pubkey: self.identity_pk(), + onion_locator: self.onion(), + wallet_filename: filename.to_string(), + }; + self.store + .lock() + .map_err(|e| e.to_string())? + .create_wallet(&new) .map_err(|e| e.to_string()) } @@ -2964,4 +3068,140 @@ mod tests { } assert!(gone, "shutdown must not leave the wallet child behind"); } + + /// A loopback wallet RPC for the setup path: a per-socket digest challenge, + /// then the method's own result. `create_wallet` and + /// `restore_deterministic_wallet` both answer `{}`; only the seed backup + /// query has a body worth reading. + async fn mock_wallet_setup() -> Wallet { + 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("query_key") { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + + /// The reported bug: a created wallet was never remembered, because the + /// creation path never reached the store's catalogue. + #[tokio::test] + async fn creating_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let created = node.wallet_create("hunter2").await.expect("create wallet"); + + assert!(created.record.id > 0, "the store assigns the row id"); + assert_eq!(created.record.wallet_filename, "onionwire-1"); + assert_eq!(created.record.identity_pubkey, node.identity_pk()); + assert_eq!(created.record.onion_locator, "test.onion"); + assert_eq!(created.seed, "lumber tacit lemon ivory risk"); + assert_eq!( + node.list_wallets().expect("list wallets"), + vec![created.record], + "the wallet just created is the catalogue" + ); + } + + /// The second half of the bug: a second create reused the one hardcoded file + /// name, so the RPC refused it — and nothing was remembered across a restart. + #[tokio::test] + async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let first = node.wallet_create("p1").await.expect("first wallet"); + let second = node.wallet_create("p1").await.expect("second wallet"); + + assert_ne!( + first.record.wallet_filename, second.record.wallet_filename, + "a second wallet must not reuse the first one's file" + ); + drop(node); + let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store"); + assert_eq!( + reopened.list_wallets().expect("list wallets").len(), + 2, + "both wallets are remembered across a restart" + ); + } + + /// Import is a creation path too: it takes the same hardcoded name today. + #[tokio::test] + async fn importing_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let imported = node + .wallet_restore("hunter2", "lumber tacit lemon ivory risk") + .await + .expect("restore wallet"); + + assert_eq!(imported.wallet_filename, "onionwire-1"); + assert_eq!( + node.list_wallets().expect("list wallets").len(), + 1, + "an imported wallet is remembered too" + ); + } + + /// A catalogue row the child never opens is still a broken wallet: the + /// child's stored config defaults to `onionwire`, which no created wallet + /// uses any more. + #[tokio::test] + async fn creating_a_wallet_points_the_child_at_its_own_file() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let first = node.wallet_create("p1").await.expect("first wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + first.record.wallet_filename, + "the child must open the wallet that was just created" + ); + + let second = node.wallet_create("p1").await.expect("second wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + second.record.wallet_filename + ); + assert_eq!( + node.list_wallets().expect("list wallets")[0].wallet_filename, + first.record.wallet_filename, + "the first wallet keeps its own file" + ); + } + + /// The catalogue is a store fact, not a wallet-RPC fact: listing must work + /// with no wallet configured, and creating must still refuse without one. + #[tokio::test] + async fn a_wallet_off_install_lists_an_empty_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert!(node.list_wallets().expect("list wallets").is_empty()); + let err = node + .wallet_create("hunter2") + .await + .expect_err("no wallet RPC"); + assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); + } } diff --git a/src/tui.rs b/src/tui.rs index a72d071..b14994c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2263,9 +2263,9 @@ impl App { return Ok(()); } match self.rt.block_on(self.node.wallet_create(pass.as_str())) { - Ok(seed) => { + Ok(created) => { self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { - seed: Zeroizing::new(seed), + seed: Zeroizing::new(created.seed), typed: String::new(), }); } @@ -2338,7 +2338,7 @@ impl App { .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); seed.zeroize(); match result { - Ok(()) => { + Ok(_) => { self.status_note = Some("wallet imported".into()); return self.open_wallet(); } From d96de1d7f0f01427f1a43cb0e0e5f0e8a327b82c Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 02/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. (cherry picked from commit 99a4ab640e91841aedf4dcb88bc326e91252daa5) --- 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 b14994c..ca4d672 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 89867248485a3f25a5a560ba456afc394c5014ac Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 11:43:07 -0400 Subject: [PATCH 03/70] tui: read the wallet list from the store and load the chosen wallet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The selection screen shipped as presentation only: `F6 w` opened its unavailable state, the rows were never read, and Enter on a wallet said switching was not wired up. The catalogue, the create path and the screen all existed; nothing joined them. - `App::open_wallet_select` builds its rows from `Node::list_wallets` at the moment the screen opens (never cached from startup), and a failed read is the screen's own error state rather than "no saved wallets". - `App::choose_wallet` resolves `WalletChoice::Open(index)` against the catalogue as it is now — the index is a position, and two saved wallets may share an identity key — then loads it. `+ create new wallet` still starts the existing create flow. - `Node::open_wallet(filename)` is the load: it refuses a file the catalogue does not hold, re-points the sealed wallet-child record with a read-modify-write (the generated RPC creds survive), and restarts a running child onto the new file. An idle child takes the change on its next start. - `App::new` starts on the selection screen when the catalogue is non-empty and on the create flow when it is empty, so a restart lands on the wallets it remembers and a first run has no dead empty list. - The stored identity/locator stay catalogue columns: a locator rotates (F4) and identity is the roster key the node already holds, so the live header keeps reading them from the node. - `SELECT_UNAVAILABLE` is gone with the state it described; docs/TUI.md now describes the wired behaviour. Tests (both new): `Node::open_wallet` over an offline node — the chosen file, the creds kept across the read-modify-write, the choice surviving a reopen, and a non-catalogue file refused; and the app path in src/tui.rs over a real store-backed node — start screen both ways, catalogue mapping, row index over a shared identity, the create row, and a wallet recorded after startup appearing the next time the list opens. --- docs/TUI.md | 17 +++- src/node.rs | 166 +++++++++++++++++++++++++++++- src/tui.rs | 285 +++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 439 insertions(+), 29 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 7b64afd..a763944 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -150,9 +150,24 @@ failed is named on the screen — that is a different state from `no saved walle 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 +`Node::list_wallets`; the render path never reads the store. Selection is by row index, not by identity key (two records may share one). +The list is read when the screen opens — from the start screen and from +`F6` `w` — so a wallet created or imported in this session is offered the next +time the screen opens, with no restart. Enter on a wallet row re-points the +app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`, +a read-modify-write of the sealed record, so the generated RPC creds survive); +a running child is restarted onto the new file, and an idle one picks the +change up on its next start. + +**Start screen.** An install with at least one saved wallet opens on +`WalletSelect`; a fresh install (empty catalogue) opens on the create flow +(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The +stored identity and locator are catalogue columns, not session state: a locator +rotates (`F4`) and identity is the roster key the node already holds, so the +live header keeps reading them from the node. + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. diff --git a/src/node.rs b/src/node.rs index 120696b..fef5b8f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1251,6 +1251,37 @@ impl Node { .map_err(|e| e.to_string()) } + /// Switch the wallet child to a catalogue wallet's file. + /// + /// The catalogue is the only directory this app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. A + /// running child is restarted onto the new file; an idle one is only + /// re-pointed, and the change applies on the next `start_wallet_child`. The + /// write is a read-modify-write, so the generated RPC creds survive. + pub fn open_wallet(&self, filename: &str) -> Result<(), String> { + if !self + .list_wallets()? + .iter() + .any(|w| w.wallet_filename == filename) + { + return Err(format!("no saved wallet in {filename}")); + } + let running = self + .wallet_child + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .is_some_and(|child| child.wallet_rpc_running()); + if running { + self.stop_wallet_child()?; + } + self.point_child_at(filename)?; + if running { + self.start_wallet_child()?; + } + Ok(()) + } + /// The file name a wallet created now should live in. `wallet_filename` is /// UNIQUE and the catalogue is the only directory the app has, so this is /// `-` for the first `n` the catalogue does not already hold. @@ -1990,7 +2021,42 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } #[cfg(test)] -mod tests { +/// A catalogue row written straight into the store, for tests that need a saved +/// wallet without a wallet RPC. +pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) { + let identity_pubkey: [u8; 32] = store + .self_identity() + .expect("self identity") + .identity_pk + .try_into() + .expect("32-byte identity"); + store + .create_wallet(&NewWallet { + name: (!label.trim().is_empty()).then(|| label.to_string()), + identity_pubkey, + onion_locator: format!("{file}.onion"), + wallet_filename: file.to_string(), + }) + .expect("create wallet"); +} + +/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own +/// tests: `App` reads the catalogue, and the only public `Node` constructor +/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored +/// as `NULL`, like a wallet created without one. +#[cfg(test)] +pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc { + { + let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store"); + for (file, label) in wallets { + test_record_wallet(&store, file, label); + } + } + Arc::new(tests::offline_node(home, Arc::new(tests::NoDial))) +} + +#[cfg(test)] +pub(crate) mod tests { use super::*; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; @@ -2002,11 +2068,11 @@ mod tests { use tokio::io::AsyncRead as TokioRead; use tokio::io::AsyncWrite as TokioWrite; - const PASS: &str = "node-ratchet-test-pass"; + pub(crate) const PASS: &str = "node-ratchet-test-pass"; /// Never dials: every send queues, which is what leaves the encoded frame /// visible on the outbox row. - struct NoDial; + pub(crate) struct NoDial; impl crate::outbox::Deliverer for NoDial { fn deliver<'a>( @@ -2063,7 +2129,7 @@ mod tests { /// are the only public constructors and both bootstrap Tor and publish an /// onion service, so this is the only way to drive the shipped send and /// receive path offline. - fn offline_node(home: &Path, deliverer: Arc) -> Node { + pub(crate) fn offline_node(home: &Path, deliverer: Arc) -> Node { offline_node_with_wallet(home, deliverer, Wallet::disabled()) } @@ -3204,4 +3270,96 @@ mod tests { .expect_err("no wallet RPC"); assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); } + + /// Switching wallets is a catalogue read plus a child re-point: the chosen + /// row's file name is what the child opens, and the generated RPC creds in + /// the same sealed record survive the read-modify-write. + #[tokio::test] + async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node(&home, Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child( + r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#, + ) + .unwrap(); + for file in ["onionwire", "onionwire-1"] { + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: "abcd.onion".into(), + wallet_filename: file.to_string(), + }) + .unwrap(); + } + } + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet that was chosen" + ); + let sealed = node + .store + .lock() + .unwrap() + .load_wallet_child() + .unwrap() + .expect("sealed record"); + assert!( + sealed.contains("ow-secret-pass-xyz"), + "the re-point dropped the generated creds: {sealed}" + ); + assert!( + sealed.contains("\"user\":\"owuser\""), + "the re-point dropped the generated creds: {sealed}" + ); + + // A restart re-reads the record, so the choice is remembered. + drop(node); + let restarted = offline_node(&home, Arc::new(NoDial)); + assert_eq!( + restarted.wallet_child_config().wallet_filename, + "onionwire-1", + "the chosen wallet must survive a restart" + ); + } + + /// The catalogue is the only directory the app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. + #[tokio::test] + async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#) + .unwrap(); + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: String::new(), + wallet_filename: "onionwire".to_string(), + }) + .unwrap(); + } + + let err = node + .open_wallet("onionwire-9") + .expect_err("not a saved wallet"); + assert!(err.contains("no saved wallet"), "{err}"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire", + "a refused switch must leave the child where it was" + ); + } } diff --git a/src/tui.rs b/src/tui.rs index ca4d672..8251985 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -17,7 +17,9 @@ use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; +use crate::store::{ + Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1348,12 +1350,27 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; + // First run is the create flow, not an empty list to pick from; an + // install that already has wallets starts on the list, so a restart + // lands on the wallets it remembers. A catalogue that cannot be read is + // the screen's own error state (the create row still works there). + let screen = match node.list_wallets() { + Ok(rows) if rows.is_empty() => Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }), + Ok(rows) => Screen::WalletSelect { + state: WalletSelectState::from_rows(wallet_rows(rows)), + }, + Err(e) => Screen::WalletSelect { + state: WalletSelectState::error(e), + }, + }; Ok(Self { me_fp: to_hex(&node.identity_pk()), me_onion: node.onion(), node, rt, - screen: Screen::Main, + screen, friends, selected: 0, alert: None, @@ -2073,14 +2090,14 @@ impl App { } /// 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. + /// existing creation flow, and a wallet row switches the wallet child to + /// that row's file. /// - /// 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. + /// `WalletChoice::Open` carries a **row index**, so it is resolved against + /// the catalogue as it is now, not against anything the screen cached: two + /// saved wallets may share an identity key, and only the position (then the + /// row's own `wallet_filename`) names one. A list that changed under the + /// screen is reported rather than silently opening the wrong wallet. fn choose_wallet(&mut self) -> Result<(), String> { let Screen::WalletSelect { state } = &self.screen else { return Ok(()); @@ -2091,24 +2108,52 @@ impl App { typed: String::new(), }); } - WalletChoice::Open(_) => { - self.status_note = Some("wallet switching is not wired up yet".into()); + WalletChoice::Open(index) => { + let opened = self.select_wallet(index); + match opened { + Ok(label) => { + self.status_note = Some(format!("opened wallet {label}")); + self.screen = Screen::Main; + } + Err(e) => self.alert = Some(e), + } } } Ok(()) } - /// F6 `w`: the wallet selection screen. + /// Load the catalogue row at `index` into the session: point the wallet + /// child at that wallet's file (and restart it if it was running), then read + /// the list back so the screen never shows a stale catalogue. /// - /// 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. + /// The stored identity and locator are not pushed into the session: they are + /// the identity/locator *at creation* (a locator rotates, and the identity is + /// the roster key this node already holds), so the live values keep coming + /// from the node. Returns the label to report. + fn select_wallet(&mut self, index: usize) -> Result { + let row = self + .node + .list_wallets()? + .into_iter() + .nth(index) + .ok_or_else(|| "the saved wallets changed — reopen the list".to_string())?; + self.node.open_wallet(&row.wallet_filename)?; + Ok(wallet_label(&row)) + } + + /// F6 `w`: the wallet selection screen, read from the catalogue now. + /// + /// The rows come from the wallet store ([`Node::list_wallets`]) at the + /// moment the screen opens — never cached from startup — so a wallet created + /// in this session shows up on the next look. A read that fails is the + /// screen's own error state, which is not the same word as "no saved + /// wallets": the `create new wallet` row stays reachable either way. fn open_wallet_select(&mut self) { - self.screen = Screen::WalletSelect { - state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + let state = match self.node.list_wallets() { + Ok(records) => WalletSelectState::from_rows(wallet_rows(records)), + Err(e) => WalletSelectState::error(e), }; + self.screen = Screen::WalletSelect { state }; } /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the @@ -4556,6 +4601,37 @@ impl WalletSelectState { } } +/// Catalogue rows, display-ready and in store order (oldest first). +/// +/// The mapping is the one documented on [`WalletRow`]: a `NULL` label is the +/// empty string (the screen says `(unlabelled)`), the identity column is +/// `[u8; 32]` and is hex-encoded here, the locator passes through (empty until +/// the HS publishes), and `created_at` is unix seconds. `wallet_filename` is +/// not carried: it is not on the screen. The rows stay index-aligned with the +/// catalogue, which is how [`WalletChoice::Open`] resolves. +pub fn wallet_rows(records: Vec) -> Vec { + records + .into_iter() + .map(|r| WalletRow { + name: r.name.unwrap_or_default(), + identity_pubkey: to_hex(&r.identity_pubkey), + onion_locator: r.onion_locator, + created_at: r.created_at, + }) + .collect() +} + +/// What to call a saved wallet in a status line: its label, or the file when it +/// has none (a blank label is stored as `NULL`). +fn wallet_label(r: &WalletRecord) -> String { + r.name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or(&r.wallet_filename) + .to_string() +} + /// 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 @@ -4923,11 +4999,6 @@ pub fn wallet_select_footer_hint() -> &'static str { 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. @@ -5333,3 +5404,169 @@ mod passphrase_buffer_tests { ); } } + +/// The wallet selection screen against a real store-backed node: the rows come +/// from the catalogue, a choice loads that wallet, and the start screen depends +/// on whether any wallet is remembered. +#[cfg(test)] +mod wallet_store_tests { + use super::*; + use crate::node::{test_node_with_wallets, test_record_wallet}; + + const PASS: &str = crate::node::tests::PASS; + + /// A real node (no Tor) over a seeded catalogue, plus the runtime the app + /// holds a handle to. `wallets` is `(file name, label)`; a blank label is a + /// wallet with no name, like one created from the app. + fn app(home: &std::path::Path, wallets: &[(&str, &str)]) -> (App, tokio::runtime::Runtime) { + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + // The offline node's unbootstrapped Arti client needs a runtime context + // to be built (the same reason the node tests are `#[tokio::test]`). + let _guard = rt.enter(); + let node = test_node_with_wallets(home, wallets); + let app = App::new(node, rt.handle().clone()).expect("app"); + (app, rt) + } + + fn select_rows(app: &App) -> Vec { + let Screen::WalletSelect { state } = &app.screen else { + panic!("not on the wallet selection screen"); + }; + state + .rows + .iter() + .map(|r| r.name.clone()) + .collect::>() + } + + /// Nothing remembered means there is no list to choose from: the first run + /// goes straight to the existing creation flow. + #[test] + fn an_install_with_no_wallet_starts_on_the_create_flow() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app(&dir.path().join("home"), &[]); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + ), + "a first run must start on the create flow" + ); + } + + /// A restart lands on the wallets it remembers, and each row carries the + /// catalogue's own fields (label, hex identity, locator, creation time). + #[test] + fn an_install_with_wallets_starts_on_the_list_read_from_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "")], + ); + let Screen::WalletSelect { state } = &app.screen else { + panic!("saved wallets must start on the selection screen"); + }; + assert!(state.error.is_none(), "{:?}", state.error); + assert!(!state.reading); + assert_eq!( + state.rows.len(), + 2, + "two saved wallets, plus the create row" + ); + assert_eq!(state.rows[0].name, "lance"); + assert_eq!(state.rows[1].name, ""); + assert_eq!( + state.rows[0].identity_pubkey, + to_hex(&app.node.identity_pk()) + ); + assert_eq!(state.rows[0].identity_pubkey.len(), 64, "hex, not bytes"); + assert_eq!(state.rows[0].onion_locator, "onionwire.onion"); + assert!(state.rows[0].created_at > 0, "creation time is real"); + assert_eq!(state.choice(), WalletChoice::Open(0)); + } + + /// The choice is a row index into a list whose records may share an + /// identity key, so the second row must open the second wallet's file. + #[test] + fn choosing_a_row_opens_that_wallets_file_not_the_first_identity_match() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "cold")], + ); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Open(1)); + } + + app.choose_wallet().expect("choosing a saved wallet"); + + assert!( + matches!(app.screen, Screen::Main), + "a loaded wallet returns to the main view" + ); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet under the marker" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet cold")); + } + + /// The last item is not a wallet: Enter on it starts the creation flow. + #[test] + fn the_create_row_starts_the_creation_flow() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Create); + } + app.choose_wallet().expect("choosing create"); + assert!(matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + )); + } + + /// The list is read when the screen opens, never cached from startup, so a + /// wallet recorded in this session is offered the next time — that is what + /// makes a create show up without a restart. + #[test] + fn a_wallet_recorded_after_startup_appears_the_next_time_the_list_opens() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let (mut app, _rt) = app(&home, &[]); + assert!(matches!(app.screen, Screen::WalletSetup(_))); + assert!( + app.node.list_wallets().expect("list wallets").is_empty(), + "nothing to list yet" + ); + + { + // The create path writes exactly this row (a `wallets` entry keyed + // on the file it just made). + let store = + crate::store::Store::open_at_with_passphrase(&home, PASS).expect("open store"); + test_record_wallet(&store, "onionwire-1", "fresh"); + } + + // F6 `w`. + app.open_wallet_select(); + assert_eq!(select_rows(&app), vec!["fresh".to_string()]); + + // And switching to it works from the screen the user is looking at. + app.choose_wallet().expect("open the new wallet"); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh")); + } +} 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: