diff --git a/README.md b/README.md index 5545d90..873d78e 100644 --- a/README.md +++ b/README.md @@ -200,15 +200,19 @@ payload can contain `?`). | `F3` | Paste a friend's invite | | `F4` | Rotate **onion** (locator only) | | `F5` | Selected friend's profile (`/who`) | -| `F6` | Wallet (receive QR, create/import, child, chain source) | +| `F6` | Wallet (receive QR, balance, transfers, create/import) | +| `F7` | Node & wallet setup (wallet RPC endpoint, chain source, start/stop, live node state) | | `F8` | Rotate **prekey** (hard cut: every friend re-pastes the invite) | | `F9` | Wallets & settings menu (`/settings`) | | Enter | Send chat to the selected friend, or run a `/command` | | `Esc` | Close overlay / back to Main / clear composer | | `Ctrl-Q` | Quit: type `CLEAR`+Enter to wipe history, `QUIT`+Enter to leave it, Esc to stay | -There is **no `F7`**. The not-configured wallet error still says “open F7”; the -live screens are `F6` (wallet) and `F9` (settings). Full map: [docs/TUI.md](docs/TUI.md). +`F7` is where the Monero side is set up: the wallet RPC endpoint and login, the +chain source (receive-only, a local `monerod`, a remote daemon, or the in-process +Cuprate node), the chain datadir, and `Ctrl-S`/`Ctrl-X` to start and stop it. It +is also what the “open F7” wallet error points at. Full map: +[docs/TUI.md](docs/TUI.md). Composer `/commands` (`src/tui.rs` `parse_cmd`): `/wipe`, `/wipe-all`, `/profile`, `/who`, `/pay [memo]`, `/tip [memo]`, `/backup /path`, `/restore /path`, @@ -425,7 +429,7 @@ Do not run `cargo publish`; `publish = false`. | Blank / broken TUI | Real terminal emulator, not `nohup` / systemd without a TTY. | | Two chats, same laptop | Separate `ONIONWIRE_HOME` per process. | | Friend cannot find you after F4 | Expected if they were offline. They F3-paste the new invite. | -| Wallet error says “open F7” | There is no F7. Use `F6` / `F9`, or set `ONIONWIRE_WALLET_RPC`. | +| Wallet error says “open F7” | `F7` is the node & wallet setup screen: set the RPC endpoint there, or set `ONIONWIRE_WALLET_RPC`. | ## Not in v1 diff --git a/docs/TUI.md b/docs/TUI.md index a5ea38d..c460312 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -22,16 +22,17 @@ ASCII chrome. | `Wipe` | `/wipe` or `/wipe-all` | Type `WIPE` or `WIPEALL` | | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | -| `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `Wallet` | `F6` | Receive QR, balance, transfers | | `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` | Node & wallet setup: RPC endpoint, chain source, start/stop, live node state | | `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. -There is **no `F7`**. Function keys that fire from Main, the settings menu, and +Function keys that fire from Main, the settings menu, and peer-payments are: | Key | `FunctionKey` | Action | @@ -41,11 +42,13 @@ peer-payments are: | `F4` | Rotate | Onion locator | | `F5` | Who | Selected friend's profile | | `F6` | Wallet | Wallet screen | +| `F7` | Setup | Node & wallet setup: RPC endpoint, chain source, start/stop | | `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. Other screens handle their own keys (Esc back, typed +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 confirms). ## Main @@ -53,16 +56,21 @@ confirms). Focus starts on the composer. Footer hints (`main_footer_hints`): ``` -Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q +Tab F2 F3 F4 F5 F6 F7 F9 ? help Ctrl-Q ``` Pane-specific (`pane_footer_hints`): | Pane | Hint | |---|---| -| 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` | +| 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. | Key | Action | |---|---| @@ -107,10 +115,14 @@ Pane-specific (`pane_footer_hints`): ## Wallet (`F6`) +The wallet, not the node: receive, balance, transfers, and create/import. Chain +and node configuration is `F7` (`Configures the wallet RPC endpoint and the +chain source`), named in the footer so the key is findable from here. + Footer: ``` -c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets F7 node Esc back ? help ``` | Key | Effect | @@ -119,14 +131,14 @@ c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc | `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | -| `s` | Start app-owned wallet child | -| `x` | Stop child (idempotent) | -| `p` | Probe child (RPC answering? chain at tip?) | -| `1` | In-process Cuprate **mainnet pruned** (unvalidated) | -| `2` | In-process Cuprate **mainnet full** (unvalidated) | -| `3` | In-process Cuprate **testnet** | +| `F7` | Node & wallet setup (`WalletSetupConfig`) | | Esc | Back to Main | +The child's state and the chain source are shown here (and on `F9`), but they are +**set** on `F7`: the start/stop/probe keys and the `1`/`2`/`3` in-process picker +that used to live on this screen are gone, so there is one place that configures +the chain. + The chain line for an in-process source always carries `testnet only — mainnet is unvalidated` (`cuprate::TESTNET_ONLY`). Starting Cuprate needs `--features cuprate-daemon`; without it, start fails with that @@ -168,11 +180,66 @@ 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. +## 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; the node's own keys (`ctrl-s`, `ctrl-x`, `ctrl-r`) and +`Ctrl-U` are named in the body, on the row they act on. +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. + +This is the only screen that sets up the chain: the wallet RPC endpoint, and the +node that serves it. + +| 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 | +| `datadir` | text | where the chain is stored. Prefilled with the path already in use; an empty one is refused rather than silently defaulted | +| `prune` | toggle | local and in-process sources | +| `network` | picker | in-process source: `space` cycles mainnet (`unvalidated`) and testnet | + +Under them, a `NODE` section: the live `Node::wallet_child_status` line (state, +chain source, `sync h/t` once a daemon reports numbers, the last error) and the +last save/test answer. The live row is the node's answer, never the draft above +it, and it is re-read by `Ctrl-R`. + +`Enter` saves and answers on the status row: `saved · not dialled yet — ctrl-s +starts it, 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. + +`Ctrl-S` saves and then starts the wallet child — the daemon and, for a local +source, `monerod` — so the setup screen is also the key that brings the node up. +A start that lands on a wallet file with no stored passphrase moves the app to +the unlock prompt. `Ctrl-X` stops the child. Both go through the same +`Node::start_wallet_child` / `stop_wallet_child` the app's own lifecycle uses. + +The chain row is written only when it was changed. An untouched row leaves the +stored source alone, so opening `F7` to fix a port cannot silently undo an +in-process Cuprate choice or move a chain datadir. 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. -Rows name the shortcut they sit beside (`F6 c`, `F6 i`, `F6 r`, `F6 s/x`, -`F6 p`, `/profile`, `/backup`, `/wipe`, …). +Rows name the shortcut they sit beside (`F6 c`, `F6 i`, `F6 r`, `/profile`, +`/backup`, `/wipe`, …). - **No credentials** on this screen. Login, seed, and passphrase are never passed into the menu snapshot. @@ -180,14 +247,15 @@ 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 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. +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. -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. +Chain source is stored via `Node::set_wallet_child_config`. `F7` is the one +screen that sets any of the four sources — receive-only, a local `monerod`, a +remote daemon, or the in-process Cuprate node — along with the external RPC URL +and the chain datadir. ## Peer payments (`F9` then `p`) diff --git a/docs/WALLET.md b/docs/WALLET.md index 457e4d5..1053374 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -89,14 +89,17 @@ The child is stopped rather than left answering `-13`, and the status reports (`open_wallet_with_passphrase`, or the TUI/Android prompt) and it is remembered. Nothing spawns the child at boot. `Node::start_wallet_child` is the only start -path. The desktop TUI drives it from `F6`: +path. The desktop TUI drives it from `F7` (`Ctrl-S` / `Ctrl-X`), which is also +the screen that picks the chain source: | Key | Effect | |---|---| -| `s` | Start the child, then probe it once. A child whose wallet file needs a passphrase opens the passphrase prompt instead of leaving every read at `-13`. | -| `x` | Stop it (idempotent). | -| `p` | Probe: is wallet RPC answering, is the chain at the tip? | -| `1` / `2` / `3` | Store in-process Cuprate as mainnet-pruned / mainnet-full / testnet. | +| `Ctrl-S` | Save the form, then start the child and probe it once. A child whose wallet file needs a passphrase opens the passphrase prompt instead of leaving every read at `-13`. | +| `Ctrl-X` | Stop it (idempotent). | +| `Ctrl-R` | Re-read the live node line (`off` / `connecting` / `syncing` / `ready` / `exited`). | +| `Enter` | Save the endpoint and chain source without dialling or starting anything. | +| `chain` row + `space` | Receive-only / local `monerod` / remote daemon / in-process Cuprate. | +| `network` row + `space` | In-process network: mainnet (unvalidated) or testnet. | State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a chain-source label, plus `wallet locked` while a catalogue wallet is configured @@ -149,9 +152,10 @@ cargo build --release --features cuprate-daemon `this build has no in-process chain daemon — rebuild with --features cuprate-daemon`. - **Pre-production.** Cuprate's own user book says do not use `cuprated` for serious purposes. RPC parity is incomplete (`docs/cuprate-launch-spike.md`). -- **Mainnet is unvalidated.** The TUI can store mainnet-pruned (`F6` `1`) or - mainnet-full (`F6` `2`) or testnet (`F6` `3`). Every in-process surface still - prints `testnet only — mainnet is unvalidated` (`cuprate::TESTNET_ONLY`). +- **Mainnet is unvalidated.** The TUI stores the in-process network on `F7`'s + `network` row (mainnet or testnet) and the store's shape on its `prune` row. + Every in-process surface still prints `testnet only — mainnet is unvalidated` + (`cuprate::TESTNET_ONLY`). Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not something this build claims to do. - **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client @@ -207,10 +211,16 @@ 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. **No TUI screen -writes them.** There is no `F7`. The not-configured refusal still says +`Store::save_wallet_config` / `Node::wallet_save_config` exist, and the `F7` +screen (`WalletSetupConfig`) writes them: the endpoint, its login, the chain +source, and (for a local node) its datadir and network. It is also the only +screen that starts and stops the child (`Ctrl-S` / `Ctrl-X`). `F6` and `F9` +show state, the env vars are the headless path. The not-configured refusal says `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` -(`src/wallet.rs`). Live surfaces: `F6`, `F9`, or the env vars. +(`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. `/pay` and `/tip` run `wallet_readiness` before send: diff --git a/src/node.rs b/src/node.rs index 6b128c9..ed4d666 100644 --- a/src/node.rs +++ b/src/node.rs @@ -669,6 +669,75 @@ 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 datadir = self.local_chain_datadir(prune); + self.set_local_monerod_at(monerod_bin, &datadir, prune) + } + + /// The chain datadir a local node uses when the user did not name one. + /// Split by prune mode exactly as it always was, so an existing install + /// keeps the store it already has. + pub fn local_chain_datadir(&self, prune: bool) -> PathBuf { + self.home + .join("chain") + .join(if prune { "mainnet-pruned" } else { "mainnet-full" }) + } + + /// [`Self::set_local_monerod`], with the chain datadir spelled out — the + /// shape the F7 screen saves when the user typed one. + /// + /// An empty datadir is refused rather than silently replaced with the + /// default: a store that moved without the user saying so looks exactly + /// like a chain that vanished, and a silent rewrite would resync the whole + /// chain into a directory they did not choose. + pub fn set_local_monerod_at( + &self, + monerod_bin: &Path, + datadir: &Path, + prune: bool, + ) -> Result<(), String> { + if datadir.as_os_str().is_empty() { + return Err("chain datadir required for a local node".into()); + } + 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: datadir.to_path_buf(), + 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**. /// @@ -3585,6 +3654,182 @@ 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 4edce3e..da3543d 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,5 +1,6 @@ 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}; @@ -20,7 +21,8 @@ use crate::sanitize; use crate::store::{ Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord, }; -use crate::wallet::{self, ChainNetwork, ChainSource}; +use crate::wallet::{self, ChainNetwork, ChainSource, WalletConfig}; +use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -549,6 +551,7 @@ 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\ @@ -1287,6 +1290,11 @@ 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. @@ -1348,6 +1356,361 @@ 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 · cuprate in this app", + } + } +} + +/// 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_DATADIR: usize = 6; +const SETUP_ROW_PRUNE: usize = 7; +const SETUP_ROW_NETWORK: usize = 8; +const SETUP_ROWS: usize = 9; + +/// 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, + /// Chain datadir for a local node (spawned `monerod` or in-process Cuprate). + /// Prefilled with the path the node already uses, so a save that leaves it + /// alone keeps the chain where it is. + datadir: 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, + /// The live node/child line, refreshed on open and by `Ctrl-R`. This is the + /// answer to "did the node I just configured come up?" — taken from + /// `Node::wallet_child_status`, never inferred from the draft above. + status: 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("datadir", &self.datadir) + .field("prune", &self.prune) + .field("chain_touched", &self.chain_touched) + .field("cuprate_network", &self.cuprate_network) + .field("note", &self.note) + .field("status", &self.status) + .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(), + // The default a save would use if the user never types one; a stored + // local/in-process source overwrites it below with its real path. + datadir: node.local_chain_datadir(false).display().to_string(), + prune: false, + chain_touched: false, + cuprate_network: ChainNetwork::Mainnet, + note: None, + status: None, + }; + match &child.source { + ChainSource::None => {} + ChainSource::Local { + monerod_bin, + datadir, + prune, + } => { + state.source = SetupSource::Local; + state.monerod_bin = monerod_bin.display().to_string(); + state.datadir = datadir.display().to_string(); + state.prune = *prune; + } + ChainSource::Remote { host, port } => { + state.source = SetupSource::Remote; + state.daemon = format!("{host}:{port}"); + } + ChainSource::InProcessCuprate { + datadir, + network, + prune, + } => { + state.source = SetupSource::InProcess; + state.datadir = datadir.display().to_string(); + state.prune = *prune; + state.cuprate_network = *network; + } + } + state + } + + /// Read the live node/child line into the screen. Called on open and by + /// `Ctrl-R`, so what the status row shows is what the node answered, never + /// what the draft above it claims. + pub fn refresh_status(&mut self, node: &Node) { + let line = node.wallet_child_status().line(); + self.status = Some(if line.is_empty() { + "node not configured · pick a chain source and ctrl-s".to_string() + } else { + format!("node {line}") + }); + } + + /// 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), + SETUP_ROW_DATADIR => self.datadir.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(), + SETUP_ROW_DATADIR => self.datadir.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(), + SETUP_ROW_DATADIR => self.datadir.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; + } + // The in-process node's network, which F6's `1`/`2`/`3` used to own: + // moving the chain picker here must not lose the choice. + SETUP_ROW_NETWORK => { + self.cuprate_network = match self.cuprate_network { + ChainNetwork::Mainnet => ChainNetwork::Testnet, + ChainNetwork::Testnet => ChainNetwork::Mainnet, + }; + 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(' '), + SETUP_ROW_DATADIR => self.datadir.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_at( + Path::new(&self.monerod_bin), + Path::new(&self.datadir), + 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 held it before, including the in-process + // choice F6 used to own, rather than silently rewriting its datadir. + 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 yet — ctrl-s starts it, 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" + } + } + + /// The in-process node's network row. Mainnet says it is unvalidated in the + /// same words `cuprate::TESTNET_ONLY` uses, because that is the fact a user + /// picking it needs. + fn network_display(&self) -> &'static str { + match self.cuprate_network { + ChainNetwork::Mainnet => "mainnet · unvalidated", + ChainNetwork::Testnet => "testnet", + } + } + + 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)] @@ -1359,6 +1722,7 @@ enum FunctionKey { Wallet, RotatePrekey, OpenMenu, + Setup, } /// The function key `screen` answers, or `None` when the key belongs to the @@ -1380,6 +1744,7 @@ 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, @@ -1513,6 +1878,9 @@ 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(), @@ -1736,12 +2104,8 @@ impl App { // `w` is the wallet list: the F6 screen is about the wallet you // are on, and this is how you get off it. KeyCode::Char('w') => self.open_wallet_select(), - KeyCode::Char('s') => self.wallet_child_start(), - KeyCode::Char('x') => self.wallet_child_stop(), - KeyCode::Char('p') => self.wallet_child_probe(), - KeyCode::Char('1') => self.set_cuprate_chain(ChainNetwork::Mainnet, true), - KeyCode::Char('2') => self.set_cuprate_chain(ChainNetwork::Mainnet, false), - KeyCode::Char('3') => self.set_cuprate_chain(ChainNetwork::Testnet, false), + // The node's own keys (start/stop/probe, chain source) are F7's. + // F6 is the wallet: receive, balance, transfers, create/import. KeyCode::Char('c') => { self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { typed: String::new(), @@ -1755,6 +2119,7 @@ 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, @@ -2360,20 +2725,82 @@ impl App { }); } - /// Key `p`: one probe of the running child — is its RPC answering, and is - /// the chain at the tip? The only thing that can report `ready`. - fn wallet_child_probe(&mut self) { - self.status_note = Some(self.wallet_child_note()); + /// 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) { + let mut state = WalletSetupConfigState::from_node(&self.node); + state.refresh_status(&self.node); + self.screen = Screen::WalletSetupConfig { state }; } - fn set_cuprate_chain(&mut self, network: ChainNetwork, prune: bool) { - self.status_note = Some(match self.node.set_in_process_cuprate(network, prune) { - Ok(()) => format!( - "chain source: {}", - self.node.wallet_child_config().source.label() - ), - Err(e) => format!("chain source: {e}"), - }); + /// Keys on the F7 screen: `Tab` moves, `Enter` saves, `Ctrl-T` tests the + /// wallet RPC endpoint, `Ctrl-S` saves and starts the node/wallet child, + /// `Ctrl-X` stops it, `Ctrl-R` re-reads the live node line, `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; + } + // Start/stop go through `App`'s own child helpers so this screen and the + // wallet screen that used to own them cannot drift: same start, same + // passphrase prompt, same status line. + if ctrl && key.code == KeyCode::Char('s') { + let Screen::WalletSetupConfig { state } = &mut self.screen else { + return; + }; + let note = state.save(&self.node); + state.note = Some(note); + self.wallet_child_start(); + self.refresh_setup_status(); + return; + } + if ctrl && key.code == KeyCode::Char('x') { + self.wallet_child_stop(); + self.refresh_setup_status(); + return; + } + if ctrl && key.code == KeyCode::Char('r') { + self.refresh_setup_status(); + 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), + _ => {} + } + } + + /// Re-read the live node line into the F7 screen, if it is still the screen + /// on show. A start that needed a passphrase has already moved the app to + /// the unlock prompt, and this must not drag it back. + fn refresh_setup_status(&mut self) { + if let Screen::WalletSetupConfig { state } = &mut self.screen { + state.refresh_status(&self.node); + } } /// The child status line, or the copy that names what is missing. @@ -2898,6 +3325,17 @@ 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 @@ -3512,7 +3950,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 F9 ? help Ctrl-Q" + "Tab F2 F3 F4 F5 F6 F7 F9 ? help Ctrl-Q" } /// Footer hints for one focused main pane. @@ -3522,10 +3960,15 @@ 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 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", + 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", } } @@ -3548,7 +3991,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets F7 node Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::UnlockPass { .. }) => { @@ -3567,6 +4010,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSetupConfig { .. } => wallet_setup_config_footer_hint(), Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } @@ -3591,6 +4035,21 @@ 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() { @@ -4043,9 +4502,11 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { let receive_empty = s.receive_addr.is_empty(); let wallet = vec![ - 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), + // `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("child", child_value, "F7 ctrl-s/x", MenuTone::Normal), + MenuRow::new("sync", sync_value, "F7 ctrl-r", sync_tone), MenuRow::new( "receive", if receive_empty { @@ -4292,6 +4753,163 @@ 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_DATADIR, + "datadir", + &s.datadir, + )); + out.push(setup_row_line( + w, + s, + SETUP_ROW_PRUNE, + "prune", + s.prune_display(), + )); + out.push(setup_row_line( + w, + s, + SETUP_ROW_NETWORK, + "network", + &format!("{} (space changes)", s.network_display()), + )); + out.push(Line::default()); + out.push(menu_section_line(w, "NODE")); + // What the node answered, not what the draft claims: the row is filled from + // `Node::wallet_child_status` and says so when nothing is configured yet. + out.push(Line::from( + Span::raw(fit_cells( + s.status + .as_deref() + .unwrap_or("node unknown — ctrl-r re-reads the live state"), + w, + )) + .style(style_dim()), + )); + // The node's own keys are named here, on the section they act on, for the + // same reason the login row names `ctrl-u`: at 80 columns the footer has + // room for one group and the status line already spends half the width. + out.push(Line::from( + Span::raw(fit_cells( + "keys ctrl-s save + start ctrl-x stop ctrl-r re-read", + w, + )) + .style(style_dim()), + )); + out.push(Line::from( + Span::raw(fit_cells(&format!("last {}", 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. // @@ -5406,7 +6024,7 @@ balance lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "s start child x stop child p probe c create i import r qr Esc back"; + let help = "c create i import r qr w wallets F7 node Esc back"; lines.push("".into()); f.render_widget( Paragraph::new(lines.join("\n")) @@ -5725,12 +6343,6 @@ mod wallet_store_tests { frame_on(app, 80, 24) } - /// Whitespace-collapsed copy of some drawn text, so a sentence the renderer - /// wrapped across lines still reads as the one string that produced it. - fn flattened(text: &str) -> String { - text.split_whitespace().collect::>().join(" ") - } - /// Nothing remembered means nothing to warn about: a first run opens on the /// main view, not on the create flow's spend-authority warning. Asserting /// the screen alone would pass with the warning merely drawn behind Main, so @@ -5906,10 +6518,6 @@ mod wallet_store_tests { assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh")); } - fn key(code: KeyCode) -> KeyEvent { - KeyEvent::new(code, KeyModifiers::NONE) - } - /// What the real render path puts on an 80x24 terminal — `App::draw`, not a /// stand-in widget. fn frame_text(app: &App) -> String { @@ -6371,3 +6979,782 @@ 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"); + } + + /// `Tab` from wherever the form is focused until `row` has it. The tests + /// below drive the real key path, not the state directly. + fn focus_row(app: &mut App, row: usize) { + let mut guard = 0; + while state_of(app).field != row { + app.handle_key(key(KeyCode::Tab)).expect("tab"); + guard += 1; + assert!(guard <= SETUP_ROWS, "row {row} is unreachable by Tab"); + } + } + + /// Pick the `chain` row's source by cycling it with `space`. + fn pick_source(app: &mut App, want: SetupSource) { + focus_row(app, SETUP_ROW_CHAIN); + for _ in 0..4 { + if state_of(app).source == want { + return; + } + app.handle_key(key(KeyCode::Char(' '))).expect("space"); + } + panic!("the picker never reached {want:?}"); + } + + /// The point of the datadir row: a local node goes where the user says, not + /// where the default was. This is the node-setup path the app lacked — + /// `set_local_monerod` was reachable only from Kotlin. + #[test] + fn a_local_node_saves_the_datadir_the_user_typed() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let (mut app, _rt) = app(&home); + app.handle_key(key(KeyCode::F(7))).expect("F7"); + fill_endpoint(&mut app); + pick_source(&mut app, SetupSource::Local); + + focus_row(&mut app, SETUP_ROW_MONEROD); + for _ in 0.."monerod".len() { + app.handle_key(key(KeyCode::Backspace)).expect("backspace"); + } + type_str(&mut app, "/opt/monero/monerod"); + + let typed = home.join("chain-tank"); + focus_row(&mut app, SETUP_ROW_DATADIR); + app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) + .expect("ctrl-u"); + type_str(&mut app, typed.to_str().expect("utf8 path")); + + app.handle_key(key(KeyCode::Enter)).expect("enter"); + + assert!( + state_of(&app) + .note + .as_deref() + .expect("a status line") + .starts_with("saved"), + "the save must land: {:?}", + state_of(&app).note + ); + match &app.node.wallet_child_config().source { + ChainSource::Local { + monerod_bin, + datadir, + prune, + } => { + assert_eq!(monerod_bin.to_str(), Some("/opt/monero/monerod")); + assert_eq!( + datadir, &typed, + "the node must store its chain where the user said" + ); + assert!(!prune); + } + other => panic!("expected a local node, got {other:?}"), + } + } + + /// An empty datadir is refused rather than silently replaced with the + /// default: a store that moved without being asked looks like a vanished + /// chain, and the resync lands somewhere the user did not choose. + #[test] + fn an_empty_datadir_is_refused_and_the_source_is_not_written() { + 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); + pick_source(&mut app, SetupSource::Local); + focus_row(&mut app, SETUP_ROW_DATADIR); + app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) + .expect("ctrl-u"); + + app.handle_key(key(KeyCode::Enter)).expect("enter"); + + let note = state_of(&app).note.as_deref().expect("a status line"); + assert!( + note.contains("datadir required"), + "the refusal must name the missing field: {note}" + ); + assert_eq!( + app.node.wallet_child_config().source, + ChainSource::None, + "a refused chain source must not be stored" + ); + } + + /// The row answers with what the node says, not with what the draft above it + /// claims: on a fresh install that is "nothing configured yet". + #[test] + fn the_node_row_shows_the_live_state_on_open() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + + app.handle_key(key(KeyCode::F(7))).expect("F7"); + + let status = state_of(&app) + .status + .as_deref() + .expect("the screen reads the node on open"); + assert!( + status.starts_with("node"), + "the live row must be the node's answer: {status}" + ); + let body = wallet_setup_config_text(78, state_of(&app)); + assert!( + body.contains("not configured"), + "an unconfigured install must say so, not print a blank row:\n{body}" + ); + // The node's keys are discoverable from the body: at 80 columns the + // footer has no room for them. + for needle in ["ctrl-s save + start", "ctrl-x stop", "ctrl-r re-read"] { + assert!( + body.contains(needle), + "{needle:?} must be named on the screen that uses it:\n{body}" + ); + } + } + + /// `Ctrl-S` is the key that actually brings the node up: it saves the form + /// and then asks the node to start. With no chain source the start refuses + /// in the node's own words and the screen stays put. + #[test] + fn ctrl_s_saves_then_reports_the_nodes_own_refusal() { + 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(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)) + .expect("ctrl-s"); + + assert!( + state_of(&app) + .note + .as_deref() + .expect("a status line") + .starts_with("saved"), + "ctrl-s must save first: {:?}", + state_of(&app).note + ); + assert_eq!( + app.node + .wallet_config() + .expect("the endpoint saved") + .rpc_url, + URL + ); + let note = app.status_note.as_deref().expect("the start reported"); + assert!( + note.contains("receive-only"), + "a receive-only install must be told why nothing started: {note}" + ); + assert!( + matches!(app.screen, Screen::WalletSetupConfig { .. }), + "a start that needs no passphrase must leave the user on F7" + ); + } + + /// F6's `1`/`2`/`3` keys were also the only way to pick the in-process node's + /// network. That choice moved here with the picker instead of being lost. + #[test] + fn the_in_process_network_is_still_selectable() { + 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); + pick_source(&mut app, SetupSource::InProcess); + assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Mainnet); + + focus_row(&mut app, SETUP_ROW_NETWORK); + let body = wallet_setup_config_text(78, state_of(&app)); + assert!( + body.contains("unvalidated"), + "mainnet must say it is unvalidated before it is picked:\n{body}" + ); + app.handle_key(key(KeyCode::Char(' '))).expect("space"); + assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Testnet); + + app.handle_key(key(KeyCode::Enter)).expect("enter"); + + match &app.node.wallet_child_config().source { + ChainSource::InProcessCuprate { network, .. } => assert_eq!( + *network, + ChainNetwork::Testnet, + "the network pick must reach the stored source" + ), + other => panic!("expected an in-process source, got {other:?}"), + } + } + + /// F6 is the wallet again: the chain picker and the child's start/stop keys + /// moved to F7, so pressing them there changes nothing and the store is not + /// touched behind the user's back. + #[test] + fn f6_no_longer_owns_the_chain_picker_or_the_child_keys() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + app.handle_key(key(KeyCode::F(6))).expect("F6"); + assert!(matches!(app.screen, Screen::Wallet { .. })); + + for c in ['s', 'x', 'p', '1', '2', '3'] { + app.handle_key(key(KeyCode::Char(c))).expect("key"); + assert!( + matches!(app.screen, Screen::Wallet { .. }), + "`{c}` must not leave the wallet screen" + ); + } + assert_eq!( + app.node.wallet_child_config().source, + ChainSource::None, + "keys F6 no longer owns must not write a chain source" + ); + // And the footer no longer advertises them. + let footer = footer_hints(&app.screen); + assert!( + footer.contains("F7 node"), + "F6 must point at F7 for the node: {footer}" + ); + assert!( + !footer.contains("1 pruned") && !footer.contains("s/x child"), + "F6 must not still advertise the keys it lost: {footer}" + ); + } +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 8e9a4c2..a49b2fe 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1030,11 +1030,13 @@ fn wallets_settings_menu_lists_both_groups_and_every_key() { ); } // Every actionable row names the key or command that fires it, including the - // F6 wallet screen's own keys, so the menu teaches the shortcuts it sits - // beside instead of hiding them. + // keys that now live on F7, so the menu teaches the shortcuts it sits beside + // instead of hiding them. A row must never name a key that no longer works: + // `F6 s/x` and `F6 p` moved to `F7 ctrl-s/x` and `F7 ctrl-r` with the node + // screen, and naming the dead keys here is how they would keep looking live. for key in [ - "F6 s/x", - "F6 p", + "F7 ctrl-s/x", + "F7 ctrl-r", "c copy F6 r", "F6 c", "F6 i",