diff --git a/docs/TUI.md b/docs/TUI.md index 0595e0f..a5ea38d 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -26,13 +26,12 @@ ASCII chrome. | `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | -| `WalletSetupConfig` | `F7` | Wallet RPC endpoint and chain source, editable | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | | `Quit` | `Ctrl-Q` | Type `CLEAR` or `QUIT` | Help (`?`) is an overlay, not a screen. `/who` / `F5` is an overlay on Main. -Function keys that fire from Main, the settings menu, and +There is **no `F7`**. Function keys that fire from Main, the settings menu, and peer-payments are: | Key | `FunctionKey` | Action | @@ -42,13 +41,11 @@ peer-payments are: | `F4` | Rotate | Onion locator | | `F5` | Who | Selected friend's profile | | `F6` | Wallet | Wallet screen | -| `F7` | Setup | Wallet RPC endpoint and chain source | | `F8` | RotatePrekey | Prekey hard cut | | `F9` | OpenMenu | Wallets & settings | `F9` is live on Main, the settings menu, and peer-payments so a printed shortcut -never no-ops there, and `F7` joins it for the same reason: `/settings` points at -the setup screen. Other screens handle their own keys (Esc back, typed +never no-ops there. Other screens handle their own keys (Esc back, typed confirms). ## Main @@ -56,21 +53,16 @@ confirms). Focus starts on the composer. Footer hints (`main_footer_hints`): ``` -Tab F2 F3 F4 F5 F6 F7 F9 ? help Ctrl-Q +Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q ``` Pane-specific (`pane_footer_hints`): | Pane | Hint | |---|---| -| Roster | `j k F3 add F6 wallet F7 setup F9 ? help` | -| Chat | `j k g G ends F4 rotate F7 setup F9 ? help` | -| Composer | `Enter send / commands F7 setup F9 ? help` | - -The status line is drawn from the focused pane's hint, and the compactor drops -tokens from the front until the line fits, so a key that only appears in -`main_footer_hints` never reaches an 80-column terminal. `F7` is therefore named -in both, and the `F9` beside it is left bare so the whole hint still fits at 80. +| Roster | `j k select F3 add F6 wallet F9 settings ? help` | +| Chat | `j k scroll g G ends F4 rotate F9 settings ? help` | +| Composer | `Enter send / commands F9 settings ? help` | | Key | Action | |---|---| @@ -176,45 +168,6 @@ 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. -## Wallet setup (`F7`) - -Footer: `Esc back Enter save Ctrl-T test` (plus the status line's own `? help`). -The compactor drops tokens from the front, and at 80 columns the status line -leaves about 25 cells, so the tail is what the default terminal shows. `Tab` and -`?` are universal; `Ctrl-U` is named on the login row it clears. -Live from Main, the `F9` settings menu, and peer payments; the menu's `endpoint` -row names `F7` as the key that edits it. Body is `WalletSetupConfigState`, a -snapshot taken when the screen opens — the render path never reads the store. - -Two things live here: the wallet RPC endpoint, and the chain source. - -| Row | Kind | Notes | -|---|---|---| -| `url` | text | the wallet RPC endpoint | -| `login` | text | `user:pass`. Never rendered back: the row reads `hidden · set` or `(none)` | -| `view-only` | toggle | `no_spend`; `/tip` is refused before any dial | -| `chain` | picker | `space` cycles receive-only, local node, remote daemon, in-process | -| `daemon` | text | `host:port`, for the remote daemon | -| `monerod` | text | the binary this box spawns for a local node | -| `prune` | toggle | local and in-process sources | - -`Enter` saves and answers on the status row: `saved · not dialled — ctrl-t tests` -`the endpoint`, or the node's own refusal in its own words. The endpoint is -validated by `Node::wallet_save_config` — loopback host, login required — and a -rejected form is rejected **before** it is written: nothing in the sealed record -moves and a running wallet is not re-dialled. `Ctrl-T` dials the endpoint and -answers with the sanitized `PingResult` line (never the password). `Ctrl-U` -clears the focused field, which is how a hidden login gets replaced. - -The chain row is written only when it was changed. An untouched row leaves -whatever `F6`'s `1`/`2`/`3` picker stored, so opening `F7` to fix a port cannot -silently undo the in-process choice. Picking a remote daemon says so in the same -frame — `a daemon you do not run sees this wallet's chain traffic` — because that -is the pick that moves chain trust off this box. The address must parse as -`host:port` first. - -Esc is the single exit and wipes the login buffer (`Zeroizing`). - ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -227,14 +180,14 @@ Rows name the shortcut they sit beside (`F6 c`, `F6 i`, `F6 r`, `F6 s/x`, - `p` opens peer payment history for the selected friend (`Node::list_payments`). - Esc back to Main. -The menu **shows** endpoint state; it does not edit it. The `endpoint` row names -`F7`, which is the key that opens `WalletSetupConfig` and the key the “open F7” -copy in `src/wallet.rs` now points at — that error is no longer advice for a key -that does not exist. +The menu **shows** endpoint state; it does not edit a stored RPC URL. The error +copy for an unconfigured wallet still says “open F7” (`src/wallet.rs`); that +key does not exist. Set `ONIONWIRE_WALLET_RPC` or use `F6` create/import and +the child. -Chain source is stored via `Node::set_wallet_child_config`. `F6` keys -`1`/`2`/`3` set the in-process source; `F7` sets any of the four, plus the -external RPC URL and a remote daemon host. +Chain source (binaries, remote host) is stored via `Node::set_wallet_child_config`. +The desktop TUI's in-process picker is `F6` keys `1`/`2`/`3`. There is no +on-screen editor for an external RPC URL or a remote daemon host. ## Peer payments (`F9` then `p`) diff --git a/docs/WALLET.md b/docs/WALLET.md index a35586c..457e4d5 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -207,15 +207,10 @@ Boot precedence: **stored config → env → disabled**. Stored config that cann be used (non-loopback, `.onion`, missing login) is reported and falls back to env rather than dialling the bad endpoint. -`Store::save_wallet_config` / `Node::wallet_save_config` exist, and the `F7` -screen (`WalletSetupConfig`) writes them: the endpoint, its login, and the chain -source. Nothing else does — `F6` and `F9` show state, the env vars are the -headless path. The not-configured refusal says +`Store::save_wallet_config` / `Node::wallet_save_config` exist. **No TUI screen +writes them.** There is no `F7`. The not-configured refusal still says `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` -(`src/wallet.rs`), and that key is real. - -A save validated by `Node::wallet_save_config` (loopback host, login required) -re-points the wallet without a restart; a rejected form writes nothing. +(`src/wallet.rs`). Live surfaces: `F6`, `F9`, or the env vars. `/pay` and `/tip` run `wallet_readiness` before send: diff --git a/src/node.rs b/src/node.rs index 3fa6be0..6b128c9 100644 --- a/src/node.rs +++ b/src/node.rs @@ -669,49 +669,6 @@ impl Node { self.set_wallet_child_config(&cfg) } - /// Point the wallet child at a chain daemon the user runs elsewhere. - /// Same shape as [`Self::set_in_process_cuprate`]: read-modify-write on the - /// stored settings, an empty `wallet_rpc_bin` filled in, and validation - /// before anything is written. A `.onion` host needs no special case here — - /// the child pulls in the SOCKS proxy for it (`ChainSource::is_onion`). - pub fn set_remote_daemon(&self, host: &str, port: u16) -> Result<(), String> { - let mut cfg = self.wallet_child_config(); - if cfg.wallet_rpc_bin.as_os_str().is_empty() { - cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc"); - } - cfg.source = ChainSource::Remote { - host: host.trim().to_string(), - port, - }; - self.set_wallet_child_config(&cfg) - } - - /// Spawn a local `monerod`. Datadirs are split exactly as they are for the - /// in-process daemon so a pruned store cannot mix with a full one. - pub fn set_local_monerod(&self, monerod_bin: &Path, prune: bool) -> Result<(), String> { - let mut cfg = self.wallet_child_config(); - if cfg.wallet_rpc_bin.as_os_str().is_empty() { - cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc"); - } - cfg.source = ChainSource::Local { - monerod_bin: monerod_bin.to_path_buf(), - datadir: self - .home - .join("chain") - .join(if prune { "mainnet-pruned" } else { "mainnet-full" }), - prune, - }; - self.set_wallet_child_config(&cfg) - } - - /// Back to zero: no wallet child, no daemon, no spend. The way out of a - /// misconfigured chain source. - pub fn set_receive_only(&self) -> Result<(), String> { - let mut cfg = self.wallet_child_config(); - cfg.source = ChainSource::None; - self.set_wallet_child_config(&cfg) - } - /// Start the app-owned wallet child, point this node's wallet at it, and /// **open its wallet file**. /// @@ -3628,182 +3585,6 @@ pub(crate) mod tests { ); } - /// The F7 screen's three chain-source choices each round-trip through the - /// sealed record, and `receive-only` is the way back to zero. - #[tokio::test] - async fn the_setup_screen_persists_each_chain_source() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("child"); - let node = offline_node(&home, Arc::new(NoDial)); - assert_eq!( - node.wallet_child_config().source, - ChainSource::None, - "a fresh install is receive-only" - ); - - node.set_remote_daemon("127.0.0.1", 18089) - .expect("remote daemon"); - let remote = node.wallet_child_config(); - assert_eq!( - remote.source, - ChainSource::Remote { - host: "127.0.0.1".into(), - port: 18089, - } - ); - assert!(!remote.source.is_onion()); - assert_eq!( - remote.wallet_rpc_bin, - PathBuf::from("monero-wallet-rpc"), - "an empty binary is filled in, like the in-process source" - ); - - node.set_remote_daemon("peer.onion", 18089) - .expect("onion daemon"); - assert!( - node.wallet_child_config().source.is_onion(), - "a .onion host is the source's own SOCKS case, not a special one" - ); - - node.set_local_monerod(Path::new("/opt/monerod"), true) - .expect("local node"); - assert_eq!( - node.wallet_child_config().source, - ChainSource::Local { - monerod_bin: PathBuf::from("/opt/monerod"), - datadir: home.join("chain").join("mainnet-pruned"), - prune: true, - } - ); - - node.set_receive_only().expect("receive-only"); - assert_eq!(node.wallet_child_config().source, ChainSource::None); - - // The last write is what a restart sees. - node.set_local_monerod(Path::new("/opt/monerod"), false) - .expect("local node"); - drop(node); - let node = offline_node(&home, Arc::new(NoDial)); - assert_eq!( - node.wallet_child_config().source, - ChainSource::Local { - monerod_bin: PathBuf::from("/opt/monerod"), - datadir: home.join("chain").join("mainnet-full"), - prune: false, - }, - "the source outlives the process" - ); - } - - /// A chain source the user typed wrong is rejected before it is written, so - /// a bad form never points the child at nothing. - #[tokio::test] - async fn a_rejected_setup_chain_source_is_not_persisted() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - node.set_remote_daemon("127.0.0.1", 18089) - .expect("remote daemon"); - let saved = node.wallet_child_config(); - - let err = node - .set_remote_daemon(" ", 18089) - .expect_err("an empty host is refused"); - assert!(err.contains("daemon host required"), "{err}"); - let err = node - .set_remote_daemon("127.0.0.1", 0) - .expect_err("port 0 is refused"); - assert!(err.contains("daemon port required"), "{err}"); - let err = node - .set_local_monerod(Path::new(""), false) - .expect_err("an empty binary path is refused"); - assert!(err.contains("monerod path required"), "{err}"); - assert_eq!( - node.wallet_child_config(), - saved, - "a rejected source leaves the stored one alone" - ); - } - - /// The F7 screen's save round-trips through the sealed record, and a save - /// can never lock the wallet out of itself: the file passphrase the screen - /// does not carry is preserved. - #[tokio::test] - async fn a_screen_save_round_trips_and_keeps_the_wallet_passphrase() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - assert!( - node.wallet_config().is_none(), - "a fresh install has stored nothing" - ); - - node.wallet_save_config(&WalletConfig::new( - "http://127.0.0.1:18083/json_rpc", - "ow:hunter2", - false, - )) - .expect("save"); - let read = node.wallet_config().expect("the save is readable"); - assert_eq!(read.rpc_url, "http://127.0.0.1:18083/json_rpc"); - assert_eq!(read.rpc_login.as_str(), "ow:hunter2"); - assert!(!read.no_spend); - assert_eq!(read.wallet_passphrase.as_str(), ""); - assert!( - node.wallet_status().configured(), - "the live snapshot follows the save" - ); - - // The file passphrase is sealed by the open path, not by this screen. - node.seal_wallet_passphrase("wallet-file-pass") - .expect("seal"); - assert_eq!( - node.wallet_config().expect("stored").wallet_passphrase.as_str(), - "wallet-file-pass" - ); - - // A screen save (which never holds the file passphrase) keeps the stored - // one instead of blanking it — a save can never lock the wallet out of - // itself. A passphrase a caller hands `wallet_save_config` is ignored - // for the same reason: the file's passphrase is not the screen's. - let mut screen_save = - WalletConfig::new("http://127.0.0.1:18083/json_rpc", "ow:hunter2", true); - screen_save.wallet_passphrase = Zeroizing::new("not-the-files".to_string()); - node.wallet_save_config(&screen_save).expect("resave"); - let read = node.wallet_config().expect("the resave is readable"); - assert!(read.no_spend, "the view-only toggle reached the store"); - assert_eq!(read.wallet_passphrase.as_str(), "wallet-file-pass"); - } - - /// A rejected form leaves the stored config exactly as it was. The node is - /// the validator — the screen does not reimplement it. - #[tokio::test] - async fn a_rejected_wallet_config_is_not_persisted() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - node.wallet_save_config(&WalletConfig::new( - "http://127.0.0.1:18083/json_rpc", - "ow:hunter2", - false, - )) - .expect("save"); - let before = node.wallet_config().expect("stored"); - - for bad in [ - WalletConfig::new("", "ow:hunter2", false), - WalletConfig::new("http://192.0.2.10:18083/json_rpc", "ow:hunter2", false), - WalletConfig::new("http://127.0.0.1:18083/json_rpc", "", false), - ] { - let err = node - .wallet_save_config(&bad) - .expect_err("a bad form is refused"); - assert!(!err.is_empty()); - assert_eq!( - node.wallet_config().expect("stored"), - before, - "the stored config is intact" - ); - } - } - /// `shutdown` stops the processes the app owns: an exit must not orphan a /// spend-capable wallet RPC behind a loopback socket. #[tokio::test] diff --git a/src/tui.rs b/src/tui.rs index da8fcef..4d58215 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; use std::io::{self, IsTerminal, Write}; -use std::path::Path; use std::sync::{Arc, mpsc}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -21,8 +20,7 @@ use crate::sanitize; use crate::store::{ Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord, }; -use crate::wallet::{self, ChainNetwork, ChainSource, WalletConfig}; -use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; +use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -542,7 +540,6 @@ OnionWire keys\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ F6 wallet (receive QR, create/import)\n\ - F7 wallet setup: RPC endpoint, chain source\n\ F8 rotate prekey\n\ F9 wallets & settings menu\n\ /profile edit name, bio, Monero address\n\ @@ -1281,11 +1278,6 @@ enum Screen { qr_modal: Option, }, WalletSetup(WalletSetup), - /// F7: configure the wallet RPC endpoint and the chain source on screen. - /// A snapshot like the other editors — see `WalletSetupConfigState`. - WalletSetupConfig { - state: WalletSetupConfigState, - }, /// F9 / `/settings`: the WALLETS & SETTINGS discovery menu. Holds the /// snapshot, not a pre-rendered body, so a resize re-fits and nothing stale /// survives a repaint. @@ -1347,295 +1339,6 @@ enum WalletSetup { }, } -/// Which chain source the F7 picker is on — the four cases [`ChainSource`] -/// models, in the order `space` cycles them. `InProcessCuprate` is set on F6; -/// it is here so an F7 save does not silently overwrite it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum SetupSource { - ReceiveOnly, - Local, - Remote, - InProcess, -} - -impl SetupSource { - fn next(self) -> Self { - match self { - Self::ReceiveOnly => Self::Local, - Self::Local => Self::Remote, - Self::Remote => Self::InProcess, - Self::InProcess => Self::ReceiveOnly, - } - } - - /// The value the `chain` row prints. Every case spells itself out — colour - /// is never the only signal. - fn word(self) -> &'static str { - match self { - Self::ReceiveOnly => "receive-only · no chain, no spend", - Self::Local => "local node · this box spawns monerod", - Self::Remote => "remote daemon · one you run elsewhere", - Self::InProcess => "in-process node · set on F6", - } - } -} - -/// Row indices on the F7 screen. `Tab` cycles them in this order. -const SETUP_ROW_URL: usize = 0; -const SETUP_ROW_LOGIN: usize = 1; -const SETUP_ROW_NO_SPEND: usize = 2; -const SETUP_ROW_CHAIN: usize = 3; -const SETUP_ROW_DAEMON: usize = 4; -const SETUP_ROW_MONEROD: usize = 5; -const SETUP_ROW_PRUNE: usize = 6; -const SETUP_ROWS: usize = 7; - -/// The F7 screen's draft: plain data taken once when the screen opens -/// (`Node::wallet_config` plus `Node::wallet_child_config`), never a handle onto -/// `Node`, so a repaint can never re-read the store mid-frame. -/// -/// `rpc_login` is the one secret on this screen. It is a `Zeroizing`, -/// the login row renders a fixed mask rather than the value, and there is a -/// single exit path (Esc), which wipes it by hand. -#[derive(Clone)] -pub struct WalletSetupConfigState { - field: usize, - rpc_url: String, - rpc_login: Zeroizing, - no_spend: bool, - source: SetupSource, - /// `host:port` for the remote daemon. - daemon: String, - monerod_bin: String, - prune: bool, - /// The chain row was changed on this screen. An untouched row is not - /// written, so an in-process Cuprate source survives an F7 save. - chain_touched: bool, - cuprate_network: ChainNetwork, - /// The last save / test answer, display-ready, never a secret. - note: Option, -} - -/// `Debug` is written by hand and redacts the login. Nothing in the app prints -/// this state today; the point is that nothing can, by accident — a `dbg!` or a -/// panic message must not be a way to read the one secret the screen holds. -impl std::fmt::Debug for WalletSetupConfigState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WalletSetupConfigState") - .field("field", &self.field) - .field("rpc_url", &self.rpc_url) - .field( - "rpc_login", - &if self.rpc_login.is_empty() { - "(none)" - } else { - "(hidden)" - }, - ) - .field("no_spend", &self.no_spend) - .field("source", &self.source) - .field("daemon", &self.daemon) - .field("monerod_bin", &self.monerod_bin) - .field("prune", &self.prune) - .field("chain_touched", &self.chain_touched) - .field("cuprate_network", &self.cuprate_network) - .field("note", &self.note) - .finish() - } -} - -impl WalletSetupConfigState { - /// Prefill from the store: the stored wallet config, or the env-derived one - /// (`Node::wallet_config` is the migration path), and the stored chain - /// source. - pub fn from_node(node: &Node) -> Self { - let wallet = node.wallet_config(); - let child = node.wallet_child_config(); - let mut state = Self { - field: SETUP_ROW_URL, - rpc_url: wallet.as_ref().map(|c| c.rpc_url.clone()).unwrap_or_default(), - rpc_login: wallet - .as_ref() - .map(|c| c.rpc_login.clone()) - .unwrap_or_else(|| Zeroizing::new(String::new())), - no_spend: wallet.as_ref().map(|c| c.no_spend).unwrap_or(false), - source: SetupSource::ReceiveOnly, - daemon: format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"), - monerod_bin: "monerod".to_string(), - prune: false, - chain_touched: false, - cuprate_network: ChainNetwork::Mainnet, - note: None, - }; - match &child.source { - ChainSource::None => {} - ChainSource::Local { - monerod_bin, prune, .. - } => { - state.source = SetupSource::Local; - state.monerod_bin = monerod_bin.display().to_string(); - state.prune = *prune; - } - ChainSource::Remote { host, port } => { - state.source = SetupSource::Remote; - state.daemon = format!("{host}:{port}"); - } - ChainSource::InProcessCuprate { network, prune, .. } => { - state.source = SetupSource::InProcess; - state.prune = *prune; - state.cuprate_network = *network; - } - } - state - } - - /// The one secret in this state goes away with the screen, on purpose. - fn close(&mut self) { - self.rpc_login.zeroize(); - } - - fn next_field(&mut self) { - self.field = (self.field + 1) % SETUP_ROWS; - } - - fn prev_field(&mut self) { - self.field = (self.field + SETUP_ROWS - 1) % SETUP_ROWS; - } - - /// Characters reach a text row only; the toggle and picker rows answer - /// `space`. - fn push(&mut self, c: char) { - if c == '\n' { - return; - } - match self.field { - SETUP_ROW_URL => self.rpc_url.push(c), - SETUP_ROW_LOGIN => self.rpc_login.push(c), - SETUP_ROW_DAEMON => self.daemon.push(c), - SETUP_ROW_MONEROD => self.monerod_bin.push(c), - _ => {} - } - } - - fn backspace(&mut self) { - match self.field { - SETUP_ROW_URL => self.rpc_url.pop(), - SETUP_ROW_LOGIN => self.rpc_login.pop(), - SETUP_ROW_DAEMON => self.daemon.pop(), - SETUP_ROW_MONEROD => self.monerod_bin.pop(), - _ => None, - }; - } - - /// A typed secret is easier to clear than to backspace: the login row never - /// shows what is in it, so `Ctrl-U` has to exist. - fn clear_field(&mut self) { - match self.field { - SETUP_ROW_URL => self.rpc_url.clear(), - SETUP_ROW_LOGIN => self.rpc_login.zeroize(), - SETUP_ROW_DAEMON => self.daemon.clear(), - SETUP_ROW_MONEROD => self.monerod_bin.clear(), - _ => {} - } - } - - fn space(&mut self) { - match self.field { - SETUP_ROW_NO_SPEND => self.no_spend = !self.no_spend, - SETUP_ROW_CHAIN => { - self.source = self.source.next(); - self.chain_touched = true; - } - SETUP_ROW_PRUNE => { - self.prune = !self.prune; - self.chain_touched = true; - } - SETUP_ROW_URL => self.rpc_url.push(' '), - SETUP_ROW_LOGIN => self.rpc_login.push(' '), - SETUP_ROW_DAEMON => self.daemon.push(' '), - SETUP_ROW_MONEROD => self.monerod_bin.push(' '), - _ => {} - } - } - - /// Persist the draft through the node's own validators and answer with the - /// line the status row shows. Nothing is written by hand here: a rejected - /// form leaves the running wallet and the stored chain source untouched. - fn save(&mut self, node: &Node) -> String { - let cfg = WalletConfig::new(&self.rpc_url, self.rpc_login.as_str(), self.no_spend); - if let Err(e) = node.wallet_save_config(&cfg) { - return format!("not saved · {e}"); - } - let chain = match self.source { - SetupSource::ReceiveOnly => node.set_receive_only(), - SetupSource::Local => node.set_local_monerod(Path::new(&self.monerod_bin), self.prune), - SetupSource::Remote => match parse_daemon_addr(&self.daemon) { - Some((host, port)) => node.set_remote_daemon(&host, port), - None => return "not saved · daemon address must be host:port".to_string(), - }, - // Untouched: leave whatever F6 stored, including nothing. - SetupSource::InProcess if !self.chain_touched => Ok(()), - SetupSource::InProcess => node.set_in_process_cuprate(self.cuprate_network, self.prune), - }; - match chain { - Ok(()) => "saved · not dialled — ctrl-t tests the endpoint".to_string(), - Err(e) => format!("wallet config saved · chain source: {e}"), - } - } - - /// One shot at the endpoint the user typed. There is no password in the - /// answer: `PingResult::line()` is already sanitized. - fn test_connection(&self, node: &Node, rt: &tokio::runtime::Handle) -> String { - rt.block_on(node.wallet_test_connection(&self.rpc_url, self.rpc_login.as_str())) - .line() - } - - /// What the login row prints: never the value, only whether there is one. - fn login_display(&self) -> &'static str { - if self.rpc_login.is_empty() { - "(none) · type user:pass" - } else { - "hidden · set (ctrl-u clears)" - } - } - - fn no_spend_display(&self) -> &'static str { - if self.no_spend { - "yes · /tip refused before any dial" - } else { - "no · this wallet can spend" - } - } - - fn prune_display(&self) -> &'static str { - if self.prune { - "yes · pruned chain store" - } else { - "no · full chain store" - } - } - - fn status_display(&self) -> String { - self.note - .clone() - .unwrap_or_else(|| "nothing saved yet · enter saves, ctrl-t tests".to_string()) - } -} - -/// `host:port` for the remote-daemon row. The port has to be a number; a -/// missing port is not guessed (the child would dial the wrong daemon). -fn parse_daemon_addr(raw: &str) -> Option<(String, u16)> { - let (host, port) = raw.trim().rsplit_once(':')?; - if host.trim().is_empty() { - return None; - } - let port: u16 = port.trim().parse().ok()?; - if port == 0 { - return None; - } - Some((host.trim().to_string(), port)) -} - /// A function key the TUI answers before the per-screen `match`; the screen's /// own key handler never sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1647,7 +1350,6 @@ enum FunctionKey { Wallet, RotatePrekey, OpenMenu, - Setup, } /// The function key `screen` answers, or `None` when the key belongs to the @@ -1669,7 +1371,6 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { KeyCode::F(4) => Some(FunctionKey::Rotate), KeyCode::F(5) => Some(FunctionKey::Who), KeyCode::F(6) => Some(FunctionKey::Wallet), - KeyCode::F(7) => Some(FunctionKey::Setup), KeyCode::F(8) => Some(FunctionKey::RotatePrekey), KeyCode::F(9) => Some(FunctionKey::OpenMenu), _ => None, @@ -1803,9 +1504,6 @@ impl App { } FunctionKey::Who => self.who_open = true, FunctionKey::Wallet => self.open_wallet()?, - // The setup screen opens from Main, the settings menu and the - // peer history: those are the screens that name `F7`. - FunctionKey::Setup => self.open_setup_config(), FunctionKey::RotatePrekey => { self.screen = Screen::RotatePrekey { prompt: RotatePrompt::new(), @@ -2048,7 +1746,6 @@ impl App { _ => {} }, Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, - Screen::WalletSetupConfig { .. } => self.handle_wallet_setup_config(key), Screen::WalletsSettings { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('c') => copy_addr = true, @@ -2670,52 +2367,6 @@ impl App { }); } - /// F7: open the setup screen with the stored (or env-derived) values as the - /// draft. Nothing is read from the store while the screen is open. - fn open_setup_config(&mut self) { - self.screen = Screen::WalletSetupConfig { - state: WalletSetupConfigState::from_node(&self.node), - }; - } - - /// Keys on the F7 screen: `Tab` moves, `Enter` saves, `Ctrl-T` tests the - /// endpoint, `Ctrl-U` clears the focused field, `Esc` leaves and wipes the - /// login buffer. - fn handle_wallet_setup_config(&mut self, key: KeyEvent) { - if key.code == KeyCode::Esc { - if let Screen::WalletSetupConfig { state } = &mut self.screen { - state.close(); - } - self.screen = Screen::Main; - return; - } - let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); - if ctrl && key.code == KeyCode::Char('t') { - let Screen::WalletSetupConfig { state } = &mut self.screen else { - return; - }; - let note = state.test_connection(&self.node, &self.rt); - state.note = Some(note); - return; - } - let Screen::WalletSetupConfig { state } = &mut self.screen else { - return; - }; - match key.code { - KeyCode::Tab | KeyCode::Down => state.next_field(), - KeyCode::BackTab | KeyCode::Up => state.prev_field(), - KeyCode::Enter => { - let note = state.save(&self.node); - state.note = Some(note); - } - KeyCode::Backspace => state.backspace(), - KeyCode::Char('u') if ctrl => state.clear_field(), - KeyCode::Char(' ') => state.space(), - KeyCode::Char(c) if !ctrl => state.push(c), - _ => {} - } - } - /// The child status line, or the copy that names what is missing. fn wallet_child_note(&mut self) -> String { let line = self.rt.block_on(self.node.wallet_child_refresh()).line(); @@ -3238,17 +2889,6 @@ impl App { ) } Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), - Screen::WalletSetupConfig { 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_setup_config(f, state, &footer) - } Screen::WalletsSettings { state } => { // The one status line the screen carries: same `status_footer` // shape as Main, so TOR / identity / the copy confirmation read @@ -3863,7 +3503,7 @@ fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize /// a user finds the menu in the first place. Kept short so width 80 still shows /// TOR + identity + `? help`. pub fn main_footer_hints() -> &'static str { - "Tab F2 F3 F4 F5 F6 F7 F9 ? help Ctrl-Q" + "Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q" } /// Footer hints for one focused main pane. @@ -3873,15 +3513,10 @@ pub fn main_footer_hints() -> &'static str { /// (the discoverable menu) and `? help`, which `tests/tui_chrome.rs` asserts are /// reachable from the footer at 80, 120 and 200. pub fn pane_footer_hints(pane: Pane) -> &'static str { - // `F7` is named here as well as in `main_footer_hints`: the status line is - // drawn from the focused pane's hint, so a key only in the main list would - // never reach the 80-column terminal. The tokens have to fit whole — the - // compactor drops them from the front — so the words that matter to F7 stay - // and the neighbouring `F9` is left bare. match pane { - Pane::Roster => "j k F3 add F6 wallet F7 setup F9 ? help", - Pane::Chat => "j k g G ends F4 rotate F7 setup F9 ? help", - Pane::Composer => "Enter send / commands F7 setup F9 ? help", + Pane::Roster => "j k select F3 add F6 wallet F9 settings ? help", + Pane::Chat => "j k scroll g G ends F4 rotate F9 settings ? help", + Pane::Composer => "Enter send / commands F9 settings ? help", } } @@ -3923,7 +3558,6 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), - Screen::WalletSetupConfig { .. } => wallet_setup_config_footer_hint(), Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } @@ -3948,21 +3582,6 @@ pub fn wallets_settings_footer_hint() -> &'static str { const WALLETS_SETTINGS_FOOTER_HINT: &str = "Esc back c copy ? help"; -/// The hint line the F7 setup screen prints, single-sourced like the other -/// screens': its frame test builds the fixture from this, so a dumped frame can -/// never show a footer the app does not render. -pub fn wallet_setup_config_footer_hint() -> &'static str { - WALLET_SETUP_CONFIG_FOOTER_HINT -} - -/// The F7 screen's hint. Short on purpose: the status line already carries TOR, -/// the fingerprint and the locator, which leaves about 25 cells at 80 columns — -/// and the compactor drops tokens from the front, so `Esc back` goes first and -/// the two keys a save actually needs are the ones that survive. Tab and `?` -/// are universal and named elsewhere; `Ctrl-U` is named on the login row it -/// clears. -const WALLET_SETUP_CONFIG_FOOTER_HINT: &str = "Esc back Enter save Ctrl-T test"; - fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { let block = block.borders(Borders::ALL); if ascii_chrome() { @@ -4418,9 +4037,7 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { let receive_empty = s.receive_addr.is_empty(); let wallet = vec![ - // `F7` is the key that edits this row, so the row names it: the menu is - // the discovery layer, and the endpoint is the one thing only F7 writes. - MenuRow::new("endpoint", endpoint_value, "F7", endpoint_tone), + MenuRow::new("endpoint", endpoint_value, "", endpoint_tone), MenuRow::new("child", child_value, "F6 s/x", MenuTone::Normal), MenuRow::new("sync", sync_value, "F6 p", sync_tone), MenuRow::new( @@ -4669,127 +4286,6 @@ pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &st ); } -// --------------------------------------------------------------------------- -// F7 wallet setup: the RPC endpoint and the chain source, on screen. -// -// Three rules, all of them load-bearing: -// * the login row never renders the login — only whether one is set; -// * the endpoint is validated by `Node::wallet_save_config` (loopback-only, -// login required) and a rejected form writes nothing; -// * a remote daemon is a trust move, and the screen says so in one line at the -// moment the user makes it. -// --------------------------------------------------------------------------- - -/// One row: `> label value`, the value truncated in cells so no row can wrap. -fn setup_row_line( - width: usize, - state: &WalletSetupConfigState, - row: usize, - label: &str, - value: &str, -) -> Line<'static> { - let mark = if state.field == row { ">" } else { " " }; - let value = if value.trim().is_empty() { "(none)" } else { value }; - let text = fit_cells(&format!("{mark} {label:<9} {value}"), width); - let style = if state.field == row { - style_accent().add_modifier(Modifier::BOLD) - } else { - style_text() - }; - Line::from(Span::raw(text).style(style)) -} - -/// The F7 body, as lines. Widths are clamped with `fit_cells` (cells, not -/// chars), so every row fits the frame it is drawn in. -pub fn wallet_setup_config_lines(width: u16, s: &WalletSetupConfigState) -> Vec> { - let w = width as usize; - let mut out = vec![menu_section_line(w, "WALLET RPC")]; - out.push(setup_row_line(w, s, SETUP_ROW_URL, "url", &s.rpc_url)); - out.push(setup_row_line( - w, - s, - SETUP_ROW_LOGIN, - "login", - s.login_display(), - )); - out.push(setup_row_line( - w, - s, - SETUP_ROW_NO_SPEND, - "view-only", - s.no_spend_display(), - )); - out.push(Line::default()); - out.push(menu_section_line(w, "CHAIN SOURCE")); - out.push(setup_row_line( - w, - s, - SETUP_ROW_CHAIN, - "chain", - &format!("{} (space changes)", s.source.word()), - )); - if s.source == SetupSource::Remote { - out.push(Line::from( - Span::raw(fit_cells( - " a daemon you do not run sees this wallet's chain traffic", - w, - )) - .style(style_dim()), - )); - } - out.push(setup_row_line(w, s, SETUP_ROW_DAEMON, "daemon", &s.daemon)); - out.push(setup_row_line( - w, - s, - SETUP_ROW_MONEROD, - "monerod", - &s.monerod_bin, - )); - out.push(setup_row_line( - w, - s, - SETUP_ROW_PRUNE, - "prune", - s.prune_display(), - )); - out.push(Line::default()); - out.push(Line::from( - Span::raw(fit_cells(&format!("status {}", s.status_display()), w)).style(style_dim()), - )); - out -} - -/// The F7 body as plain text, for width and needle assertions. -pub fn wallet_setup_config_text(width: u16, s: &WalletSetupConfigState) -> String { - wallet_setup_config_lines(width, s) - .iter() - .map(|line| { - line.spans - .iter() - .map(|span| span.content.as_ref()) - .collect::() - }) - .collect::>() - .join("\n") -} - -/// F7: setup is a full screen like the other editors — body plus the one -/// status line every screen shares. -pub fn draw_wallet_setup_config(f: &mut Frame, state: &WalletSetupConfigState, footer: &str) { - let area = f.area(); - let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); - let inner = rows[0].width.saturating_sub(2); - f.render_widget( - Paragraph::new(wallet_setup_config_lines(inner, state)) - .block(themed_block("(o) wallet setup · F7")), - rows[0], - ); - f.render_widget( - Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), - rows[1], - ); -} - // --------------------------------------------------------------------------- // Peer payment history: the F9 menu's `payments` row. // @@ -6757,541 +6253,3 @@ mod wallet_offset_tests { ); } } - -/// F7 (`/settings` → wallet setup, or the key anywhere the footer names it) is -/// the screen that puts the wallet RPC endpoint and the chain source in the -/// user's hands. These tests drive it through the real key path and the real -/// node, and read the frames the app actually paints. -#[cfg(test)] -mod wallet_setup_config_tests { - use super::*; - use crate::node::test_node_with_wallets; - - fn app(home: &std::path::Path) -> (App, tokio::runtime::Runtime) { - let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); - let _guard = rt.enter(); - let node = test_node_with_wallets(home, &[]); - let app = App::new(node, rt.handle().clone()).expect("app"); - (app, rt) - } - - fn key(code: KeyCode) -> KeyEvent { - KeyEvent::new(code, KeyModifiers::NONE) - } - - fn type_str(app: &mut App, s: &str) { - for c in s.chars() { - app.handle_key(key(KeyCode::Char(c))).expect("typed key"); - } - } - - /// The frame the real `App::draw` path paints on a terminal of this size. - fn frame_on(app: &App, width: u16, height: u16) -> String { - let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)) - .expect("test terminal"); - term.draw(|f| app.draw(f)).expect("draw"); - let buf = term.backend().buffer().clone(); - let mut drawn = String::new(); - for y in 0..buf.area.height { - for x in 0..buf.area.width { - drawn.push_str(buf[(x, y)].symbol()); - } - drawn.push('\n'); - } - drawn - } - - fn state_of(app: &App) -> &WalletSetupConfigState { - let Screen::WalletSetupConfig { state } = &app.screen else { - panic!("not on the F7 setup screen"); - }; - state - } - - /// The endpoint a form types by hand: loopback, `host:port`, with a login, - /// because those are the two things `wallet_save_config` checks. - const URL: &str = "http://127.0.0.1:18083/json_rpc"; - const LOGIN: &str = "ow:hunter2"; - - fn fill_endpoint(app: &mut App) { - type_str(app, URL); - app.handle_key(key(KeyCode::Tab)).expect("tab"); - type_str(app, LOGIN); - } - - /// F7 opens it, it opens on the stored values, and Esc is the way back. - #[test] - fn f7_opens_the_setup_screen_and_esc_leaves_it() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - assert_eq!( - function_key_for(&app.screen, KeyCode::F(7)), - Some(FunctionKey::Setup) - ); - - app.handle_key(key(KeyCode::F(7))).expect("F7"); - assert!( - matches!(app.screen, Screen::WalletSetupConfig { .. }), - "F7 must land on the setup screen" - ); - - app.handle_key(key(KeyCode::Esc)).expect("esc"); - assert!(matches!(app.screen, Screen::Main), "esc leaves for main"); - } - - /// A fresh install prefills from the environment, and the screen says where - /// the picks are: F6's in-process source is shown, not hidden. - #[test] - fn the_screen_opens_on_what_is_already_stored() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, true)) - .expect("seed the store"); - - app.handle_key(key(KeyCode::F(7))).expect("F7"); - let state = state_of(&app); - assert_eq!(state.rpc_url, URL); - assert_eq!(state.rpc_login.as_str(), LOGIN); - assert!(state.no_spend, "view-only comes back as it was stored"); - assert_eq!(state.source, SetupSource::ReceiveOnly); - } - - /// The login row says a password is set, never what it is. This is the one - /// secret on the screen; it must not come back out. - #[test] - fn the_setup_screen_never_renders_the_login() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, true)) - .expect("seed the store"); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - - let body = wallet_setup_config_text(70, state_of(&app)); - assert!( - !body.contains(LOGIN) && !body.contains("hunter2"), - "the login row rendered the login:\n{body}" - ); - assert!( - body.contains("hidden"), - "the login row must say one is set:\n{body}" - ); - - for width in [40u16, 80, 120] { - let frame = frame_on(&app, width, 24); - assert!( - !frame.contains(LOGIN) && !frame.contains("hunter2"), - "the login leaked into the {width}-column frame:\n{frame}" - ); - assert!( - frame.contains("hidden"), - "the {width}-column frame lost the login row:\n{frame}" - ); - } - } - - /// Enter writes exactly what the form holds — and the running wallet is not - /// dialled at save time, so a typo cannot take the wallet down with it. - #[test] - fn enter_saves_the_form_through_the_node() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - fill_endpoint(&mut app); - - app.handle_key(key(KeyCode::Enter)).expect("enter"); - let cfg = app.node.wallet_config().expect("the save is readable"); - assert_eq!(cfg.rpc_url, URL); - assert_eq!(cfg.rpc_login.as_str(), LOGIN); - assert!(!cfg.no_spend); - assert!( - state_of(&app) - .note - .as_deref() - .expect("a status line") - .starts_with("saved"), - "the status row must say the save landed: {:?}", - state_of(&app).note - ); - } - - /// A rejected form is rejected before it is written: the store keeps what it - /// had, and the status row says why in the node's own words. - #[test] - fn a_rejected_form_writes_nothing() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, false)) - .expect("seed the store"); - - app.handle_key(key(KeyCode::F(7))).expect("F7"); - // Row 0 is focused; replace the endpoint with a clearnet one, which the - // node refuses (the wallet RPC is loopback-only). - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) - .expect("ctrl-u"); - type_str(&mut app, "http://198.51.100.7:18083/json_rpc"); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - - assert!( - state_of(&app) - .note - .as_deref() - .expect("a status line") - .starts_with("not saved"), - "a refused form must not report a save: {:?}", - state_of(&app).note - ); - assert_eq!( - app.node.wallet_config().expect("still stored").rpc_url, - URL, - "a refused form must leave the stored endpoint alone" - ); - } - - /// A remote daemon is a trust move, and the screen says who is trusted at - /// the moment the pick is made. The address itself is validated first: a - /// daemon the child cannot dial is not written. - #[test] - fn a_remote_daemon_is_named_trusted_and_needs_an_address() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, false)) - .expect("seed the store"); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - - for _ in 0..SETUP_ROW_CHAIN { - app.handle_key(key(KeyCode::Tab)).expect("tab"); - } - assert_eq!(state_of(&app).field, SETUP_ROW_CHAIN, "the chain row is focused"); - app.handle_key(key(KeyCode::Char(' '))).expect("space"); - app.handle_key(key(KeyCode::Char(' '))).expect("space"); - assert_eq!(state_of(&app).source, SetupSource::Remote); - - let body = wallet_setup_config_text(78, state_of(&app)); - assert!( - body.contains("a daemon you do not run"), - "the remote pick must say what it trusts:\n{body}" - ); - - // Row 4 is the daemon address; clear the loopback default and type junk. - app.handle_key(key(KeyCode::Tab)).expect("tab"); - assert_eq!(state_of(&app).field, SETUP_ROW_DAEMON); - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) - .expect("ctrl-u"); - type_str(&mut app, "daemon.invalid"); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - assert!( - state_of(&app) - .note - .as_deref() - .expect("a status line") - .contains("host:port"), - "a portless daemon must be refused with the reason: {:?}", - state_of(&app).note - ); - assert_eq!( - app.node.wallet_child_config().source, - ChainSource::None, - "nothing is written until the address parses" - ); - - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) - .expect("ctrl-u"); - type_str(&mut app, "127.0.0.1:18089"); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - match &app.node.wallet_child_config().source { - ChainSource::Remote { host, port } => { - assert_eq!(host, "127.0.0.1"); - assert_eq!(*port, 18089); - } - other => panic!("expected the remote daemon to be stored, got {other:?}"), - } - } - - /// F6 sets the in-process chain source; F7 must not silently undo it. An - /// untouched chain row is not part of the save. - #[test] - fn an_untouched_chain_row_leaves_the_in_process_source_alone() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .set_in_process_cuprate(ChainNetwork::Mainnet, false) - .expect("F6's choice"); - assert!(matches!( - app.node.wallet_child_config().source, - ChainSource::InProcessCuprate { .. } - )); - - app.handle_key(key(KeyCode::F(7))).expect("F7"); - assert_eq!( - state_of(&app).source, - SetupSource::InProcess, - "the picker opens on what F6 stored" - ); - assert!(!state_of(&app).chain_touched); - fill_endpoint(&mut app); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - - assert!( - matches!( - app.node.wallet_child_config().source, - ChainSource::InProcessCuprate { .. } - ), - "an untouched chain row must not overwrite F6's choice" - ); - assert_eq!( - app.node.wallet_config().expect("the endpoint saved").rpc_url, - URL - ); - } - - /// Esc is the single exit, and the login buffer goes with it: `close()` - /// wipes it by hand and the `Zeroizing` buffer wipes again on drop. - #[test] - fn esc_wipes_the_login_buffer() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - fill_endpoint(&mut app); - assert_eq!(state_of(&app).rpc_login.as_str(), LOGIN); - - app.handle_key(key(KeyCode::Esc)).expect("esc"); - assert!(matches!(app.screen, Screen::Main)); - - let mut state = WalletSetupConfigState::from_node(&app.node); - state.rpc_login = Zeroizing::new(LOGIN.to_string()); - state.close(); - assert!( - state.rpc_login.is_empty(), - "leaving the screen must wipe the login buffer" - ); - } - - /// Every row is clamped in cells, so no width wraps a row into the next one - /// or pushes the block border off the frame. - #[test] - fn every_row_fits_the_frame_at_any_width() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - let mut state = state_of(&app).clone(); - state.rpc_url = "http://127.0.0.1:18083/json_rpc-with-a-long-tail".to_string(); - state.source = SetupSource::Remote; - state.daemon = "a-very-long-daemon-name.onion:18089".to_string(); - - for width in [20usize, 24, 33, 40, 60, 78, 120] { - for line in wallet_setup_config_lines(width as u16, &state) { - let cells: usize = line.spans.iter().map(|s| cell_width(&s.content)).sum(); - assert!( - cells <= width, - "a {cells}-cell row does not fit {width} columns: {:?}", - line.spans.iter().map(|s| s.content.as_ref()).collect::() - ); - } - } - - // And on the real frame, at the standard size and at the tightest. - for (w, h) in [(80u16, 24u16), (40, 24)] { - let frame = frame_on(&app, w, h); - assert!(frame.contains("wallet setup"), "the title got lost at {w}x{h}:\n{frame}"); - assert!( - frame.lines().count() == h as usize, - "the frame lost rows at {w}x{h}" - ); - } - } - - /// F7 is named where the screen is reachable, and it survives the compact - /// footer at the standard 80 columns. - #[test] - fn the_footer_offers_f7_where_the_screen_is_reachable() { - assert!(main_footer_hints().contains("F7")); - assert!(pane_footer_hints(Pane::Roster).contains("F7")); - assert!(help_overlay_text().contains("F7")); - - let dir = tempfile::tempdir().unwrap(); - let (app, _rt) = app(&dir.path().join("home")); - let frame = frame_on(&app, 80, 24); - assert!( - frame.contains("F7"), - "the main footer must still name F7 at 80 columns:\n{frame}" - ); - for line in frame.lines() { - assert!( - cell_width(line) <= 80, - "a footer line overran 80 columns: {line:?}" - ); - } - } - - /// The F7 hint is a single source: the screen renders the string the footer - /// test asserts on, so a dumped frame cannot show a footer the app does not. - #[test] - fn the_setup_screen_prints_its_own_hint() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - - assert_eq!( - footer_hints(&app.screen), - wallet_setup_config_footer_hint() - ); - let frame = frame_on(&app, 120, 24); - for needle in ["Enter save", "Ctrl-T test", "Esc back"] { - assert!( - frame.contains(needle), - "{needle:?} must be on the 120-column frame:\n{frame}" - ); - } - - // 80 columns is the default terminal and the tight one: the status line - // spends half the width on TOR, the fingerprint and the locator, so only - // the tail of the hint survives. The two keys a save needs are the tail. - let frame = frame_on(&app, 80, 24); - for needle in ["Enter save", "Ctrl-T test"] { - assert!( - frame.contains(needle), - "{needle:?} was dropped from the 80-column footer:\n{frame}" - ); - } - - // And the screen's own hint is what the frame was built from. - assert_eq!( - footer_hints(&app.screen), - wallet_setup_config_footer_hint() - ); - } - - /// The never-no-op invariant: `F7` is named on Main, on the settings menu and - /// on peer payments, so it has to work on all three. - #[test] - fn f7_is_live_on_the_three_screens_that_name_it() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - - // Main. - app.handle_key(key(KeyCode::F(7))).expect("F7"); - assert!(matches!(app.screen, Screen::WalletSetupConfig { .. })); - app.handle_key(key(KeyCode::Esc)).expect("esc"); - - // The settings menu, where `/settings` lands. - app.handle_key(key(KeyCode::F(9))).expect("F9"); - assert!(matches!(app.screen, Screen::WalletsSettings { .. })); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - assert!( - matches!(app.screen, Screen::WalletSetupConfig { .. }), - "F7 must not no-op on the settings menu" - ); - app.handle_key(key(KeyCode::Esc)).expect("esc"); - - // Peer payments (F9 then `p`), built directly: the roster is empty here. - app.screen = Screen::PeerPayments { - state: PeerPaymentsState::from_payments("alice".to_string(), &[]), - }; - app.handle_key(key(KeyCode::F(7))).expect("F7"); - assert!( - matches!(app.screen, Screen::WalletSetupConfig { .. }), - "F7 must not no-op on peer payments" - ); - } - - /// The login never leaves in a message: not in the frame, not in the app's - /// status line, not in a `PingResult::line()`, and not through `Debug`. - #[test] - fn the_login_never_leaves_in_a_message() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, false)) - .expect("seed the store"); - app.handle_key(key(KeyCode::F(7))).expect("F7"); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - - let state = state_of(&app); - assert_eq!(state.rpc_login.as_str(), LOGIN, "the draft really holds it"); - assert!( - !format!("{state:?}").contains(LOGIN), - "Debug printed the login: {state:?}" - ); - assert!( - !state.status_display().contains(LOGIN), - "the status row carried the login" - ); - assert!( - !app.status_note.clone().unwrap_or_default().contains(LOGIN), - "the app's status note carried the login" - ); - - let answer = state.test_connection(&app.node, &app.rt); - assert!( - !answer.contains(LOGIN) && !answer.contains("hunter2"), - "the test-connection answer carried the login: {answer}" - ); - assert!( - !answer.is_empty(), - "a test that answers nothing is a broken test" - ); - } - - /// The env vars stay optional. With no store and no env, the app still boots, - /// receive-only, and the screen is the way in: what it saves is what the next - /// boot reads. - #[test] - fn a_fresh_install_needs_no_env_vars_to_reach_a_saved_config() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("home"); - let (mut fresh, _rt) = app(&home); - assert!(matches!(fresh.screen, Screen::Main), "the app still boots"); - assert_eq!( - fresh.node.wallet_child_config().source, - ChainSource::None, - "receive-only is the default, and it needs no wallet at all" - ); - - fresh.handle_key(key(KeyCode::F(7))).expect("F7"); - fill_endpoint(&mut fresh); - fresh.handle_key(key(KeyCode::Enter)).expect("enter"); - let saved = fresh.node.wallet_config().expect("saved on screen"); - assert_eq!(saved.rpc_url, URL); - assert!(fresh.node.wallet_status().configured()); - - // A second boot over the same home reads the screen's save: the store is - // the path that boots, not the environment. - let (next, _rt2) = app(&home); - assert_eq!( - next.node.wallet_config().expect("the save boots").rpc_url, - URL - ); - } - - /// A rejected form leaves the stored config exactly as it was — all three - /// fields, not just the one the test typed. - #[test] - fn a_rejected_form_leaves_the_whole_stored_config_alone() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home")); - app.node - .wallet_save_config(&WalletConfig::new(URL, LOGIN, true)) - .expect("seed the store"); - let before = app.node.wallet_config().expect("stored"); - - app.handle_key(key(KeyCode::F(7))).expect("F7"); - // Empty the endpoint: `wallet_save_config` refuses it. - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) - .expect("ctrl-u"); - // And flip a toggle on the way past, so "nothing moved" means the whole - // form, not a form that was already equal. - for _ in 0..SETUP_ROW_NO_SPEND { - app.handle_key(key(KeyCode::Tab)).expect("tab"); - } - app.handle_key(key(KeyCode::Char(' '))).expect("space"); - app.handle_key(key(KeyCode::Enter)).expect("enter"); - - let after = app.node.wallet_config().expect("still stored"); - assert_eq!(after, before, "a rejected form wrote something"); - assert!(after.no_spend, "the stored view-only flag is untouched"); - } -}