diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 3680aa7..d17f7f3 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -587,11 +587,16 @@ 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) } /// Re-read this wallet's 25-word seed so the UI can offer a "back up seed" @@ -606,12 +611,14 @@ impl Wire { } /// 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/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 a78ea8d..bbd0d24 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,16 +1192,32 @@ 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 }) } /// Re-read the seed of the wallet file the child has open. `create_wallet` @@ -1192,14 +1233,108 @@ impl Node { } /// 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()) + } + + /// 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. + 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()) } @@ -1898,7 +2033,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; @@ -1910,11 +2080,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>( @@ -1971,7 +2141,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()) } @@ -2976,4 +3146,232 @@ 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}"); + } + + /// 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 7e7b9eb..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 @@ -2337,9 +2382,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(), }); } @@ -2412,7 +2457,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(); } @@ -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")); + } +}