From 89867248485a3f25a5a560ba456afc394c5014ac Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 11:43:07 -0400 Subject: [PATCH] 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")); + } +}