diff --git a/README.md b/README.md index 7c86293..466fa06 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,11 @@ Focus starts on the composer so typing works immediately. `Tab` cycles panes; `j | `F3` | Paste a friend’s invite | | `F4` | Rotate **onion** (locator only) | | `F5` | Selected friend’s profile (`/who`) | +| `F6` | Wallet screen (address, chain, transfers) | +| `F6 s` | Chain source: receive-only / local / remote | +| `F6 n` | Start or stop the app-owned daemon | +| `F6 h` | Show receive address / seed phrase | +| `F7` | Wallet config (RPC URL, login, spend) | | 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 | diff --git a/docs/TUI.md b/docs/TUI.md index bfb0879..6870981 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -768,11 +768,9 @@ Row copy (derived from `Payment`): Amount is displayed via `pay::atomic_to_xmr_str(&t.amount_atomic)` (`src/pay.rs:144`) — never raw piconero. -### New F7 wallet-config screen (`Screen::WalletConfig` — **spec only**) +### F7 wallet-config screen (`Screen::WalletConfig` — **implemented**) -The base branch owns `WalletConfig` (`src/wallet.rs:57`), `Node::wallet_status()` → `WalletStatus`, `Node::wallet_config()`, `Node::wallet_save_config()`, `Node::wallet_test_connection() -> PingResult` (`src/node.rs:520+`). There is **no** `Screen::WalletConfig` or `draw_wallet_config` in `src/tui.rs` — confirmed by grep. This is the screen to build. - -Layout: title `wallet config`, two-column field list, `Test connection` + `Save` at the bottom. +`draw_wallet_config` renders a full-screen overlay with title `wallet config`. | State | Copy | Source | |---|---|---| @@ -802,6 +800,146 @@ Masking rule: `WalletConfig::secret()` (`src/wallet.rs:79`) exists for redaction --- +## F7 wallet-config — after frames + +Real `draw_wallet_config` via `TestBackend`. `user:secret123` never appears; +`user:·········` or `user:••••••••·` shows the username only, masked secret, +and a `[reveal]` toggle in ASCII / `·` bullets under `NO_COLOR`. + +### 80x24 — idle, masked, focus on rpc_url + +``` +┌wallet config───────────────────────────────────────────────────────────────┐ +│> rpc_url │ +│ http://127.0.0.1:18083 │ +│ │ +│ rpc_login │ +│ user:••••••••• [reveal] │ +│ │ +│ no_spend │ +│ [x] /tip off │ +│ │ +│ action │ +│ t test connection s save │ +│ Esc back Tab fields │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 80x24 — tested-fail (NO_COLOR), focus on rpc_login + +``` ++wallet config-----------------------------------------------------------------+ +| rpc_url | +| http://127.0.0.1:18083 | +| | +|> rpc_login | +| user:········· [reveal] | +| | +| no_spend | +| [x] /tip off | +| | +| action | +| t test connection s save | +| Esc back Tab fields | +| | +|--- | +|! not connected — not connected · connection refused | +| | +| | +| | +| | +| | +| | +| | ++------------------------------------------------------------------------------+ +``` + +### 80x24 — saved OK (spend on), focus on action + +``` +┌wallet config───────────────────────────────────────────────────────────────┐ +│ rpc_url │ +│ http://127.0.0.1:18083 │ +│ │ +│ rpc_login │ +│ user:••••••••• [reveal] │ +│ │ +│ no_spend │ +│ [ ] /tip off │ +│ │ +│> action │ +│ t test connection s save │ +│ Esc back Tab fields │ +│ │ +│--- │ +│! saved · not connected │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 120x40 — idle, no_spend on, focus on rpc_url + +``` + ┌wallet config─────────────────────────┐ + │> rpc_url │ + │ http://127.0.0.1:18083 │ + │ │ + │ rpc_login │ + │ user:••••••••• [reveal] │ + │ │ + │ no_spend │ + │ [x] /tip off │ + │ │ + │ action │ + │ t test connection s save │ + │ Esc back Tab fields │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + │ │ + └───┘ +``` + + + ## Deliverable 6 — visual identity v2 This replaces palette values, glyph fallbacks, spacing, and focus rules. It does **not** add hues. The locked helper names and strings in `tests/tui_chrome.rs` survive. @@ -863,7 +1001,7 @@ Glyphs are never color-only. ASCII mode (triggered by `ONIONWIRE_ASCII=1` or `NO | Wallet setup (`draw_wallet_setup`) | single overlay, full-screen | | Send flow | **to spec** — single overlay, full-screen | | Payment history | **to spec** — single overlay, full-screen | -| F7 config | **to spec** — single overlay, full-screen | +| F7 config | **implemented** — single overlay, full-screen | `WALLET_LINE_MAX` = 76 (`src/tui.rs:1169`). Every chain line is `truncate_chars(&line, WALLET_LINE_MAX)` (`src/tui.rs:1373`). @@ -1002,3 +1140,71 @@ s chain n start/stop c create i import r qr - `ChainChoice::ALL.len() == 3` (three choices, never a public node) — asserted. - `status_footer` keeps `send failed`, `TOR`, `me:`, `? help` at 80 and 120 — asserted by `status_footer_drops_send_failed_when_crowded`. - `chars().count() <= width` on all locked public copy — asserted by `public_copy_fits_80_by_chars_count`. + +## Deliverable 5 addendum — payment history frames (after) + +Render with `cargo test --locked --test tui_frames -- --nocapture dump_history_pr_frames`. + +### 80x24 — empty history + +``` +┌history bob──────────────────────────────────────────────────────────────────┐ +│no payments with this friend yet │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +│ │ +└──────────────────────────────────────────────────────────────────────────────┘ +Enter detail Esc back ? help ``` + +### 80x24 — mixed verified/unverified list + +``` +┌history alice────────────────────────────────────────────────────────────────┐ +│> 0.001 XMR ✓ verified abcdef012345678… 21m │ +│< 0.05 XMR ✓ verified deadbeefdeadbee… 3m │ +│> 0.0005 XMR ✗ unverified awaiting receipt 1m │ +└──────────────────────────────────────────────────────────────────────────────┘ +Enter detail Esc back ? help ``` + +### 80x24 — detail view (hostile memo sanitized) + +The memo was `pay\x01now\u{202E}reverse` (C0 control + bidi override). +After `sanitize::display_text` it renders as inert `paynowreverse`: + +``` +┌history alice detail────────────────────────────────────────────────────────┐ +│txid awaiting receipt │ +│address (none) │ +│memo paynowreverse │ +│amount 0.0005 XMR │ +│kind invoice │ +│direction outbound │ +│verified unverified │ +│timestamp 1700000200 (1m ago) │ +└──────────────────────────────────────────────────────────────────────────────┘ +Esc back ? help ``` + +### 80x24 — ASCII fallback + +``` ++history alice----------------------------------------------------------------+ +|> 0.001 XMR verified abcdef0123456... 21m | ++------------------------------------------------------------------------------+ +Enter detail Esc back ? help ``` diff --git a/docs/WALLET.md b/docs/WALLET.md index 4be32f5..f83f3d9 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -75,6 +75,37 @@ ChainSource::Remote { host, port } a daemon address you typed The port is a convention, not a constant: restricted RPC on `18089` is common, but you supply it. +### The daemon you point at has to be its *unrestricted* RPC + +Both the app-owned child and the chain probe behind the wallet screen dial the +daemon's unrestricted listener: `--rpc-bind-port` for the `monerod` this app +spawns (`127.0.0.1:18081`), and whatever port an in-process Cuprate binds for +`[rpc.unrestricted]`. Never the restricted listener — it answers, so getting +this wrong shows up as a *wrong number* rather than as an error. On Cuprate its +restricted server reports a placeholder `database_size` (exactly 5 GiB), an +empty `version`, and `free_space = u64::MAX` on both servers. + +What the wallet client reads from the daemon is chain height, and nothing else: +`daemon_get_info` / `daemon_get_height` in `src/wallet.rs`. No peer count, no +database size, no free space, no version — Cuprate reports zero peers *while it +is downloading blocks*, and the other three are placeholders. Connectivity is +inferred from block-height movement between two probes, which is the only honest +signal on offer. + +Two more Cuprate differences the client handles, both measured in +`docs/cuprate-launch-spike.md` §Parity gaps: + +- **A height above the tip is a bare HTTP 500 with an empty body**, where + monerod answers a JSON-RPC error object (`code = -2`, `TOO_BIG_HEIGHT`). Both + become the same typed error, so a call that asks too high fails as a height + problem instead of as an undecodable response. +- **`get_height` is a URI endpoint.** `{"method":"get_height"}` over `/json_rpc` + is rejected with 422, so the client uses `GET /get_height`, which both daemons + answer. + +`daemon_get_block()` is there for the wallet's own block scan (Phase 2) and is +**not wired into anything yet** — today the scanning is `monero-wallet-rpc`'s. + ### Readiness, and why it is not a guess `chain_ready()` asks the wallet RPC `get_info` and requires **`synchronized == @@ -116,7 +147,7 @@ stored config set in **F7** wins at boot. See *Stored wallet config* below. ## Stored wallet config (no env required) Editing env vars is a deployment step, not a UI step. The TUI's **F7** screen -sets the same three fields and stores them, so a desktop install never needs env +(`draw_wallet_config`) sets the same three fields and stores them, so a desktop install never needs env at all: | Field | Meaning | diff --git a/src/node.rs b/src/node.rs index 85e017a..26053cf 100644 --- a/src/node.rs +++ b/src/node.rs @@ -8,7 +8,6 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use futures::StreamExt; use futures::io::{AsyncRead, AsyncWrite}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tor_cell::relaycell::msg::Connected; use tor_hsservice::{RunningOnionService, handle_rend_requests}; use zeroize::Zeroizing; @@ -724,6 +723,11 @@ impl Node { /// Ask the configured daemon how far along the chain is, bounded by /// `budget`. Never fabricates a height: a daemon we cannot ask — or must not /// dial — comes back unreachable with the reason. + /// + /// The call itself lives in [`crate::wallet::daemon_get_info`], where the + /// Cuprate parity gaps are handled (a bare HTTP 500 on a height-addressed + /// call, `get_height` as a URI endpoint, and the placeholder `get_info` + /// metrics this struct has no field for). pub async fn wallet_chain_sync(&self, budget: Duration) -> DaemonSync { let Some(addr) = WalletChild::daemon_address(&self.wallet_chain_source()) else { return DaemonSync::unknown("receive-only: no daemon"); @@ -733,14 +737,14 @@ impl Node { "remote .onion daemon needs a local SOCKS listener (not wired yet)", ); } - match daemon_get_info(&addr, budget).await { - Ok((height, target_height)) => DaemonSync { + match wallet::daemon_get_info(&addr, budget).await { + Ok(info) => DaemonSync { reachable: true, - height, - target_height, + height: info.height, + target_height: info.target_height, note: None, }, - Err(e) => DaemonSync::unknown(e), + Err(e) => DaemonSync::unknown(e.to_string()), } } @@ -1559,61 +1563,6 @@ fn is_onion_daemon(addr: &str) -> bool { .ends_with(".onion") } -/// `get_info` from the daemon, over plain HTTP/1.1. Hand-rolled for the same -/// reason the wallet client is: no HTTP crate in this tree, and this request -/// carries nothing secret (the wallet RPC stays a separate, authenticated -/// loopback connection). This dials the *chain* address only. -const DAEMON_PROBE_MAX_BYTES: usize = 64 * 1024; - -async fn daemon_get_info(addr: &str, budget: Duration) -> Result<(u64, u64), String> { - let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#; - let request = format!( - "POST /json_rpc HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let mut stream = tokio::time::timeout(budget, tokio::net::TcpStream::connect(addr)) - .await - .map_err(|_| format!("{addr}: connect timed out"))? - .map_err(|e| format!("{addr}: {e}"))?; - let raw = tokio::time::timeout(budget, async { - stream.write_all(request.as_bytes()).await?; - let mut buf = Vec::new(); - let mut tmp = [0u8; 8192]; - loop { - let n = stream.read(&mut tmp).await?; - if n == 0 { - break; - } - buf.extend_from_slice(&tmp[..n]); - if buf.len() >= DAEMON_PROBE_MAX_BYTES { - break; - } - } - Ok::, std::io::Error>(buf) - }) - .await - .map_err(|_| format!("{addr}: read timed out"))? - .map_err(|e| format!("{addr}: {e}"))?; - - let text = String::from_utf8_lossy(&raw); - let json = text - .find('{') - .and_then(|start| text.rfind('}').map(|end| &text[start..=end])) - .ok_or_else(|| format!("{addr}: no JSON body"))?; - let value: serde_json::Value = - serde_json::from_str(json).map_err(|e| format!("{addr}: {e}"))?; - let result = value - .get("result") - .ok_or_else(|| format!("{addr}: no get_info result"))?; - match ( - result.get("height").and_then(|h| h.as_u64()), - result.get("target_height").and_then(|h| h.as_u64()), - ) { - (Some(height), Some(target_height)) => Ok((height, target_height)), - _ => Err(format!("{addr}: get_info has no chain height")), - } -} - /// Available 1K blocks from `df -Pk` output. Separate from the process call so /// the parse is testable without a filesystem. fn parse_df_avail_kb(stdout: &str) -> Option { @@ -1680,40 +1629,6 @@ mod tests { assert_eq!(parse_df_avail_kb("garbage"), None); } - /// A real socket, a real HTTP response, a real parse: the sync line is only - /// as honest as this. - #[tokio::test] - async fn daemon_get_info_reads_height_and_target() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let addr = listener.local_addr().unwrap().to_string(); - let server = tokio::spawn(async move { - let (mut sock, _) = listener.accept().await.unwrap(); - let mut buf = [0u8; 2048]; - let _ = sock.read(&mut buf).await; - let body = r#"{"jsonrpc":"2.0","id":"0","result":{"height":3210000,"target_height":3210000}}"#; - let resp = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let _ = sock.write_all(resp.as_bytes()).await; - }); - let (height, target) = daemon_get_info(&addr, Duration::from_secs(5)).await.unwrap(); - assert_eq!((height, target), (3_210_000, 3_210_000)); - server.await.unwrap(); - } - - /// A dead daemon is an error, never a fabricated height. - #[tokio::test] - async fn daemon_get_info_reports_a_dead_daemon() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let addr = listener.local_addr().unwrap().to_string(); - drop(listener); - let err = daemon_get_info(&addr, Duration::from_secs(5)) - .await - .expect_err("a closed port must not answer"); - assert!(err.contains(&addr), "{err}"); - } - // Official mainnet standard address (Monero docs), the same constant the // integration tests use. `insert_payment` checks the checksum. const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"; diff --git a/src/tui.rs b/src/tui.rs index c6e5c28..fa4dca2 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -15,7 +15,7 @@ use crate::node::{DaemonSync, Node, WalletChildState}; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; +use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; use crate::wallet::{self, ChainSource, Readiness}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -488,15 +488,17 @@ OnionWire keys\n\ g / G jump to top / bottom\n\ Enter send chat to selected friend, or a /command\n\ Esc close overlay, go back, clear composer\n\ - F2 share invite\n\ + F2 share invite (string + copy)\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ - F6 wallet (receive address, chain, balance, history)\n\ + F6 wallet (receive address, chain, balance)\n\ + F6 h payment history with selected friend\n\ F6 s chain source: receive-only / local / remote\n\ F6 n start or stop the app-owned daemon\n\ F6 r show / hide the receive-address QR\n\ F6 y copy receive address to clipboard (OSC 52)\n\ + F7 wallet config (rpc url, login, spend)\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ @@ -1130,6 +1132,10 @@ struct App { who_open: bool, chat_scroll: u16, job_rx: Option>, + /// The height the wallet screen saw last time it probed the daemon, so + /// connectivity can be read from movement instead of from `get_info`'s peer + /// counts (Cuprate reports zero peers while it is downloading blocks). + chain_last_height: std::cell::Cell>, } enum Screen { @@ -1169,8 +1175,15 @@ enum Screen { qr_modal: Option, copy_note: Option, }, + History { + friend_pk: Vec, + payments: Vec, + selected: usize, + detail: bool, + }, ChainSetup(ChainSetup), WalletSetup(WalletSetup), + WalletConfig(WalletConfigScreen), Quit { prompt: QuitPrompt, }, @@ -1184,6 +1197,147 @@ enum WalletSetup { ImportPass { seed: Zeroizing, entry: PassphraseEntry }, } +/// Edit-field focus for the F7 config screen. Tab cycles +/// `RpcUrl → RpcLogin → NoSpend → Action`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConfigField { + RpcUrl, + RpcLogin, + NoSpend, + Action, +} + +impl ConfigField { + pub fn next(self) -> Self { + match self { + Self::RpcUrl => Self::RpcLogin, + Self::RpcLogin => Self::NoSpend, + Self::NoSpend => Self::Action, + Self::Action => Self::RpcUrl, + } + } + + pub fn prev(self) -> Self { + match self { + Self::RpcUrl => Self::Action, + Self::RpcLogin => Self::RpcUrl, + Self::NoSpend => Self::RpcLogin, + Self::Action => Self::NoSpend, + } + } +} + +/// The status line the F7 screen shows below the fields. +#[derive(Debug, Clone, Default)] +pub enum ConfigStatus { + /// No test has run, or save cleared the result. + #[default] + Idle, + /// A probe is in flight. + Testing, + /// Last test result, rendered through `PingResult::line()`. + Tested(wallet::PingResult), + /// Save result: `true` if written, `false` + reason if rejected. + Saved(bool, String), +} + + + +impl ConfigStatus { + fn line(&self, login: &str) -> String { + match self { + Self::Idle => String::new(), + Self::Testing => "testing connection …".to_string(), + Self::Tested(p) => { + let s = wallet::WalletConfig::new("", login, false); + if p.ok { + format!("connected — {}", wallet::redact(&p.line(), s.secret())) + } else { + format!("not connected — {}", wallet::redact(&p.line(), s.secret())) + } + } + Self::Saved(true, _) => "saved · not connected".to_string(), + Self::Saved(false, e) => { + let s = wallet::WalletConfig::new("", login, false); + format!("error: {}", wallet::redact(e, s.secret())) + } + } + } +} + +/// F7 wallet-config screen state. Built from `Node::wallet_config()` when +/// opened; the typed fields are never synced back without Save. +#[derive(Debug)] +pub struct WalletConfigScreen { + /// The endpoint URL being edited. + pub rpc_url: String, + /// The login being edited (masked in the UI unless `reveal` is true). + pub rpc_login: String, + /// View-only toggle. + pub no_spend: bool, + /// Reveal the typed login instead of dots. + pub reveal: bool, + /// Which field the focus is on. + pub focus: ConfigField, + /// Current status line (test / save result). + pub status: ConfigStatus, +} + +impl WalletConfigScreen { + /// Prefill from the stored or env-derived config. An unconfigured wallet + /// opens with empty fields so the user can type a new endpoint. + pub fn from_config(cfg: Option<&wallet::WalletConfig>) -> Self { + match cfg { + Some(c) => Self { + rpc_url: c.rpc_url.clone(), + rpc_login: c.rpc_login.as_str().to_string(), + no_spend: c.no_spend, + reveal: false, + focus: ConfigField::RpcUrl, + status: ConfigStatus::Idle, + }, + None => Self { + rpc_url: String::new(), + rpc_login: String::new(), + no_spend: false, + reveal: false, + focus: ConfigField::RpcUrl, + status: ConfigStatus::Idle, + }, + } + } + + /// The login as the screen renders it: dots for the secret when masked, + /// `user:••••• [reveal]` / `user:••••• [hide]` when toggled. The real + /// password never appears in the rendered frame under any mode. + pub fn login_display(&self) -> String { + let secret_len = wallet::WalletConfig::new("", &self.rpc_login, false).secret().len(); + if self.reveal { + // Revealed: show the user part (before `:`), mask the secret. + if self.rpc_login.contains(':') { + let user = self.rpc_login.split(':').next().unwrap_or(""); + format!("{user}:{} [hide]", mask_dots(secret_len)) + } else { + format!("{} [hide]", mask_dots(secret_len)) + } + } else if self.rpc_login.is_empty() { + format!("{} [reveal]", mask_dots(7)) + } else if self.rpc_login.contains(':') { + let user = self.rpc_login.split(':').next().unwrap_or(""); + format!("{user}:{} [reveal]", mask_dots(secret_len)) + } else { + format!("{} [reveal]", mask_dots(secret_len)) + } + } +} + +/// Mask a password of `n` characters with bullets. ASCII fallback under +/// `ONIONWIRE_ASCII` / `NO_COLOR`: plain dots. +fn mask_dots(n: usize) -> String { + let glyph = if ascii_chrome() { "·" } else { "•" }; + glyph.repeat(n.clamp(1, 40)) +} + /// How far the wallet screen dares go. Derived from the parent card's /// `wallet::readiness` predicate, so the UI cannot invent a fourth answer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1367,13 +1521,72 @@ pub fn wallet_view( } } +/// The sync line: what the daemon's own numbers say, and nothing else. +/// +/// Connectivity is inferred from **block-height movement** between two probes. +/// It is never inferred from `get_info` peer counts (Cuprate answers +/// `outgoing_connections_count = 0` while it is downloading blocks) and never +/// from `database_size`/`free_space`/`version` (its restricted server answers a +/// 5 GiB placeholder, `u64::MAX` and an empty string). +/// +/// `previous_height` is the height of the previous probe on this screen, or +/// `None` when there is no earlier sample to compare with. +pub fn sync_line(sync: &DaemonSync, previous_height: Option) -> String { + if !sync.reachable { + return format!( + "sync: unknown — {}", + sync.note.as_deref().unwrap_or("no daemon") + ); + } + if sync.target_height == 0 { + // No target is not "caught up": Cuprate says `synchronized = true` with + // `target_height = 0` while it has no peers to sync from. Showing + // `1160/0` would dress that up as progress. + return format!( + "sync: unknown — daemon reports no chain target (height {})", + sync.height + ); + } + if sync.height >= sync.target_height { + return format!("sync: synced — height {}", sync.height); + } + match previous_height { + Some(previous) if previous < sync.height => format!( + "sync: connected to P2P — syncing {}/{}", + sync.height, sync.target_height + ), + Some(_) => format!( + "sync: no new blocks — {}/{} (daemon answering, no progress)", + sync.height, sync.target_height + ), + None => format!("sync: syncing — {}/{}", sync.height, sync.target_height), + } +} + /// Pure builder for the chain block: every honest-status rule lives here. +/// +/// The no-history form: callers that have no earlier probe to compare with (the +/// frame tests, the first draw) get the same lines they always did. pub fn chain_view( source: &ChainSource, child: WalletChildState, sync: &DaemonSync, free_gb: Option, readiness: WalletReadiness, +) -> ChainView { + chain_view_with_progress(source, child, sync, free_gb, readiness, None) +} + +/// [`chain_view`] with the previous probe's height, which is what the live +/// screen passes: it is the only input that can tell "syncing" apart from +/// "connected but stalled". +pub fn chain_view_with_progress( + source: &ChainSource, + child: WalletChildState, + sync: &DaemonSync, + free_gb: Option, + readiness: WalletReadiness, + previous_height: Option, ) -> ChainView { let source_line = match source { ChainSource::None => "chain: receive-only — no daemon, no chain traffic".to_string(), @@ -1393,18 +1606,7 @@ pub fn chain_view( WalletChildState::Running => "daemon: running (child owned by this app)", } .to_string(); - let sync_line = if sync.reachable { - if sync.synced() { - format!("sync: synced — height {}", sync.height) - } else { - format!("sync: syncing — {}/{}", sync.height, sync.target_height) - } - } else { - format!( - "sync: unknown — {}", - sync.note.as_deref().unwrap_or("no daemon") - ) - }; + let sync_text = sync_line(sync, previous_height); let storage_line = match (source, free_gb) { (ChainSource::Local { .. }, Some(gb)) => format!( "storage: {gb} GB free here — pruned mainnet wants ~50-60 GB, a full node ~200 GB" @@ -1418,7 +1620,7 @@ pub fn chain_view( ChainView { source_line: truncate_chars(&source_line, WALLET_LINE_MAX), child_line: truncate_chars(&child_line, WALLET_LINE_MAX), - sync_line: truncate_chars(&sync_line, WALLET_LINE_MAX), + sync_line: truncate_chars(&sync_text, WALLET_LINE_MAX), storage_line: truncate_chars(&storage_line, WALLET_LINE_MAX), status_line: readiness.line().to_string(), ready: readiness.ready(), @@ -1487,6 +1689,7 @@ impl App { who_open: false, chat_scroll: 0, job_rx: None, + chain_last_height: std::cell::Cell::new(None), }) } @@ -1570,6 +1773,8 @@ impl App { } KeyCode::F(5) => self.who_open = true, KeyCode::F(6) => self.open_wallet()?, + KeyCode::Char('h') => self.open_history()?, + KeyCode::F(7) => self.open_wallet_config(), KeyCode::Esc => self.composer.clear(), KeyCode::Backspace => { if self.focus == Pane::Composer { @@ -1764,10 +1969,30 @@ impl App { }); } KeyCode::Char('y') => self.wallet_copy_address(), + KeyCode::Char('h') => self.open_history()?, + KeyCode::F(7) => self.open_wallet_config(), + _ => {} + }, + Screen::History { selected, payments, detail, .. } => match key.code { + KeyCode::Esc => self.screen = Screen::Main, + KeyCode::Up => { + if !payments.is_empty() { + *selected = selected.saturating_sub(1); + } + } + KeyCode::Down => { + if !payments.is_empty() { + *selected = (*selected + 1).min(payments.len().saturating_sub(1)); + } + } + KeyCode::Enter => { + *detail = !*detail; + } _ => {} }, Screen::ChainSetup(_) => self.handle_chain_setup(key)?, Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, + Screen::WalletConfig(_) => self.handle_wallet_config(key)?, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1980,6 +2205,34 @@ impl App { Ok(()) } + /// `h` from main or the wallet screen: open payment history for the + /// selected friend. The list is loaded once on open and re-read only on + /// an explicit refresh, so the 100ms poll never hits the store per frame. + fn open_history(&mut self) -> Result<(), String> { + let Some(friend) = self.friends.get(self.selected) else { + self.status_note = Some("no friend selected".into()); + return Ok(()); + }; + let pk = friend.pubkey.clone(); + let payments = self.node.list_payments(&pk).unwrap_or_default(); + self.screen = Screen::History { + friend_pk: pk, + payments, + selected: 0, + detail: false, + }; + Ok(()) + } + + /// F7: open the wallet-config screen, prefilled with the stored or + /// env-derived config. The screen is self-contained — it never touches the + /// live wallet; only Save writes, only Test probes. + fn open_wallet_config(&mut self) { + let cfg = self.node.wallet_config(); + let screen = WalletConfigScreen::from_config(cfg.as_ref()); + self.screen = Screen::WalletConfig(screen); + } + /// Draw state for the wallet screen. /// /// One probe per open/refresh, then everything the screen says comes from @@ -1999,12 +2252,21 @@ impl App { let sync = self .rt .block_on(self.node.wallet_chain_sync(CHAIN_SYNC_BUDGET)); - let chain = chain_view( + // The only thing that can distinguish "connected and syncing" from + // "answering but stalled" is whether the height moved since last draw. + let previous_height = self.chain_last_height.get(); + self.chain_last_height.set(if sync.reachable { + Some(sync.height) + } else { + None + }); + let chain = chain_view_with_progress( &source, child, &sync, self.node.wallet_chain_free_gb(), readiness, + previous_height, ); let receive_addr = self .rt @@ -2397,6 +2659,124 @@ impl App { Ok(()) } + /// F7 wallet-config key handling. Tab/Shift-Tab moves between fields and + /// the action row; Enter runs Test or Save on the action row; type into a + /// field to edit it; Space toggles no_spend and reveal. + fn handle_wallet_config(&mut self, key: KeyEvent) -> Result<(), String> { + let Screen::WalletConfig(s) = &mut self.screen else { + return Ok(()); + }; + match key.code { + KeyCode::Esc => { + self.screen = Screen::Wallet { + view: Box::new(self.build_wallet_view()), + qr_modal: None, + copy_note: None, + }; + } + KeyCode::Tab => { + s.focus = s.focus.next(); + } + KeyCode::BackTab => { + s.focus = s.focus.prev(); + } + KeyCode::Enter => { + if s.focus == ConfigField::Action { + // Action row: Tab selects Test vs Save via the sub-focus + // built into the action label. We treat Enter on Action as + // Save (the primary action). Test is fired by 't' while + // focused on Action, mirroring the wallet screen's 's'/'n'. + self.wallet_config_save()?; + } + } + // Field editing + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + match s.focus { + ConfigField::RpcUrl => { + s.rpc_url.push(c); + } + ConfigField::RpcLogin => { + s.rpc_login.push(c); + } + ConfigField::NoSpend => { + if c == ' ' || c == '\r' { + s.no_spend = !s.no_spend; + } + } + ConfigField::Action => { + match c { + 't' => self.wallet_config_test()?, + 's' => self.wallet_config_save()?, + 'r' => s.reveal = !s.reveal, + _ => {} + } + } + } + } + KeyCode::Backspace => { + match s.focus { + ConfigField::RpcUrl => { + s.rpc_url.pop(); + } + ConfigField::RpcLogin => { + s.rpc_login.pop(); + } + _ => {} + } + } + _ => {} + } + Ok(()) + } + + /// F7 Test-connection: probe the endpoint the user is *typing*, not the + /// stored one. The result lands on the screen; the live wallet is untouched. + fn wallet_config_test(&mut self) -> Result<(), String> { + let Screen::WalletConfig(s) = &mut self.screen else { + return Ok(()); + }; + let url = s.rpc_url.clone(); + let login = s.rpc_login.clone(); + s.status = ConfigStatus::Testing; + let result = self.rt.block_on(self.node.wallet_test_connection(&url, &login)); + // The status line says "connected — {PingResult::line()}". On a clean + // success the line is just "connected"; on failure it carries the + // sanitized reason. + s.status = if result.ok { + ConfigStatus::Tested(result) + } else { + // For failed tests, show the error inline. + ConfigStatus::Tested(result) + }; + Ok(()) + } + + /// F7 Save: persist the edited config, re-read it, and return to the + /// wallet screen where the change is visible at rest. + fn wallet_config_save(&mut self) -> Result<(), String> { + let Screen::WalletConfig(s) = &mut self.screen else { + return Ok(()); + }; + let cfg = wallet::WalletConfig::new(&s.rpc_url, &s.rpc_login, s.no_spend); + match self.node.wallet_save_config(&cfg) { + Ok(()) => { + // Re-read the stored config to reflect what's actually saved. + let _stored = WalletConfigScreen::from_config(self.node.wallet_config().as_ref()); + s.status = ConfigStatus::Saved(true, String::new()); + // Re-read from store, keep the save status. + self.screen = Screen::Wallet { + view: Box::new(self.build_wallet_view()), + qr_modal: None, + copy_note: None, + }; + } + Err(e) => { + s.status = ConfigStatus::Saved(false, wallet::redact(&e, cfg.secret())); + } + } + Ok(()) + } + fn submit_paste(&mut self, raw: &str) -> Result<(), String> { match qr::decode(raw.trim()) { Err(e) => { @@ -2569,8 +2949,15 @@ impl App { Screen::Wallet { view, qr_modal, copy_note } => { draw_wallet(f, view.as_ref(), qr_modal.as_ref(), copy_note.as_deref()) } + Screen::History { friend_pk, payments, selected, detail } => { + let name = self.friends.iter().find(|fr| &fr.pubkey == friend_pk) + .and_then(|fr| fr.petname.as_deref()) + .unwrap_or("friend"); + draw_history(f, payments, *selected, *detail, name, unix_now_secs()) + } Screen::ChainSetup(setup) => draw_chain_setup(f, setup), Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), + Screen::WalletConfig(s) => draw_wallet_config(f, s), } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2868,7 +3255,7 @@ fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize /// Main-screen key hints. Kept short so width 80 still shows TOR + identity + `? help`. pub fn main_footer_hints() -> &'static str { - "Tab F2 F3 F4 F5 ? help Ctrl-Q" + "Tab F2 F3 F4 F5 F6 h ? help Ctrl-Q" } fn footer_hints(screen: &Screen) -> &'static str { @@ -2888,8 +3275,10 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "s chain n node c create i import r qr y copy Esc back ? help", + Screen::Wallet { .. } => "s chain n node c create i import h history r qr y copy Esc back ? help", + Screen::History { .. } => "Enter detail Esc back ? help", Screen::ChainSetup(_) => "Enter select/save Esc back ? help", + Screen::WalletConfig(_) => "Tab fields t test s save Esc back ? help", Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { "Enter submit Esc cancel ? help" @@ -3325,6 +3714,233 @@ pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>, co ); } +/// Payment-history helpers (card t_935bf84e). +/// +/// These are pure: they take `&[Payment]` fixtures and render parameters so +/// the tests never need to reach into the store. Every peer-supplied field +/// (memo, address) is run through `sanitize::display_text` before it touches +/// a `Paragraph`. +/// Age string derived from `created_at` relative to `now`: just-seconds, +/// minutes, hours, or a date fallback for older entries. +fn payment_age(created_at: i64, now: i64) -> String { + let delta = now.saturating_sub(created_at).max(0); + if delta < 60 { + format!("{delta}s") + } else if delta < 3600 { + format!("{}m", delta / 60) + } else if delta < 86400 { + format!("{}h", delta / 3600) + } else { + format!("{}d", delta / 86400) + } +} + +/// Human-readable direction word for a `Payment` row. +fn payment_direction(p: &Payment) -> &'static str { + if p.dir == "out" { "outbound" } else { "inbound" } +} + +/// Verified glyph + word — never colour-only. ASCII chrome drops the glyph. +fn verified_text(p: &Payment) -> String { + if ascii_chrome() { + if p.verified { "verified" } else { "unverified" }.to_string() + } else { + format!("{} {}", if p.verified { "✓" } else { "✗" }, if p.verified { "verified" } else { "unverified" }) + } +} + +/// The txid column: truncated on the row, full in the detail view. +fn txid_display(p: &Payment, max: usize) -> String { + match &p.txid { + Some(txid) => truncate_chars(txid, max), + None => "awaiting receipt".to_string(), + } +} + +/// Build one history list row from a `Payment`. Direction marker (`> `/`< `), +/// amount through `pay::atomic_to_xmr_str`, verified word + glyph, and a +/// truncated txid (or `awaiting receipt`). The result is truncated to `width`. +pub fn history_row_text(p: &Payment, width: usize, now: i64) -> String { + let dir_mark = if p.dir == "out" { "> " } else { "< " }; + let xmr = crate::pay::atomic_to_xmr_str(&p.amount_atomic); + let verified = verified_text(p); + let txid = txid_display(p, 16); + let age = payment_age(p.created_at, now); + let raw = format!("{dir_mark}{xmr} XMR {verified} {txid} {age}"); + truncate_chars(&raw, width) +} + +/// Build the detail-view lines for a single `Payment`. Every peer-supplied +/// field (memo, address) goes through `sanitize::display_text` first. +pub fn history_detail(p: &Payment, width: usize, now: i64) -> Vec { + let xmr = crate::pay::atomic_to_xmr_str(&p.amount_atomic); + let dir_word = payment_direction(p); + let verified_word = if p.verified { "verified" } else { "unverified" }; + let txid_line = match &p.txid { + Some(txid) => format!("txid {}", sanitize::display_text(txid.as_bytes())), + None => "txid awaiting receipt".to_string(), + }; + let memo_line = if p.memo.is_empty() { + "memo (none)".to_string() + } else { + let clean = sanitize::display_text(p.memo.as_bytes()); + let wrapped = wrap_text(&clean, width.saturating_sub(6).max(1)); + format!("memo {}", wrapped.join("\n ")) + }; + let address_line = if p.address.is_empty() { + "address (none)".to_string() + } else { + let addr_w = width.saturating_sub(10).max(1); + let clean = sanitize::display_text(p.address.as_bytes()); + format!("address {}", truncate_chars(&clean, addr_w)) + }; + let amount_line = format!("amount {xmr} XMR"); + let kind_line = format!("kind {}", p.kind); + let dir_line = format!("direction {dir_word}"); + let verified_line = format!("verified {verified_word}"); + let age = payment_age(p.created_at, now); + let ts_line = format!("timestamp {} ({} ago)", p.created_at, age); + vec![ + truncate_chars(&txid_line, width), + truncate_chars(&address_line, width), + truncate_chars(&memo_line, width), + truncate_chars(&amount_line, width), + truncate_chars(&kind_line, width), + truncate_chars(&dir_line, width), + truncate_chars(&verified_line, width), + truncate_chars(&ts_line, width), + ] +} + +/// Wrap text at `width` columns to whole words, truncating the last chunk with +/// an ellipsis if a word is too long. Used for the memo line in the detail view. +fn wrap_text(s: &str, width: usize) -> Vec { + if width == 0 { + return vec![s.to_string()]; + } + let mut lines: Vec = Vec::new(); + let mut current = String::new(); + for word in s.split_whitespace() { + let w = word.chars().count(); + if current.is_empty() { + if w > width { + lines.push(truncate_chars(word, width)); + } else { + current = word.to_string(); + } + } else if char_len(¤t) + 1 + w <= width { + current.push(' '); + current.push_str(word); + } else { + lines.push(std::mem::take(&mut current)); + if w > width { + lines.push(truncate_chars(word, width)); + } else { + current = word.to_string(); + } + } + } + if !current.is_empty() { + lines.push(current); + } + if lines.is_empty() { + lines.push(String::new()); + } + lines +} + +/// Full-screen draw for the payment-history list (or detail view when +/// `show_detail` is true). `friend_name` is the petname or fingerprint of the +/// selected friend, already sanitized upstream. +pub fn draw_history( + f: &mut Frame, + payments: &[Payment], + selected: usize, + show_detail: bool, + friend_name: &str, + now: i64, +) { + let area = f.area(); + let width = area.width; + let inner_w = width.saturating_sub(2) as usize; + let title = if show_detail && !payments.is_empty() { + format!("history {friend_name} detail") + } else { + format!("history {friend_name}") + }; + let block = pane_block_for(&title, true); + + let cols = Layout::vertical([ + Constraint::Min(1), + Constraint::Length(1), + ]) + .split(area); + + if payments.is_empty() { + let body = wrap_text("no payments with this friend yet", inner_w.max(1)).join("\n"); + f.render_widget( + Paragraph::new(body) + .style(style_text()) + .wrap(Wrap { trim: false }) + .block(block), + cols[0], + ); + f.render_widget( + Paragraph::new("Enter detail Esc back ? help").style(style_dim()), + cols[1], + ); + return; + } + + let idx = selected.min(payments.len() - 1); + + if show_detail { + let detail = history_detail(&payments[idx], inner_w, now); + f.render_widget( + Paragraph::new(detail.join("\n")) + .style(style_text()) + .wrap(Wrap { trim: false }) + .block(block), + cols[0], + ); + f.render_widget( + Paragraph::new("Esc back ? help").style(style_dim()), + cols[1], + ); + return; + } + + let items: Vec = payments + .iter() + .enumerate() + .map(|(i, p)| { + let row = history_row_text(p, inner_w, now); + let style = if i == selected { + style_highlight() + } else { + style_text() + }; + ListItem::new(row).style(style) + }) + .collect(); + + let mut list_state = ListState::default(); + list_state.select(Some(idx)); + + f.render_stateful_widget( + List::new(items) + .highlight_style(style_highlight()) + .block(block), + cols[0], + &mut list_state, + ); + + f.render_widget( + Paragraph::new("Enter detail Esc back ? help").style(style_dim()), + cols[1], + ); +} + /// The chain-source picker and the remote-daemon trust shift, before anything /// is saved. fn draw_chain_setup(f: &mut Frame, setup: &ChainSetup) { @@ -3435,6 +4051,45 @@ fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) { draw_text_overlay(f, title, &body); } +/// F7: the wallet-endpoint config screen. Full-screen overlay (like +/// `draw_text_overlay`), fields pre-filled from `WalletConfig::from_config`. +/// +/// The rendered text is built here, not by stringing together internal fields: +/// every line that touches the login is redacted through `WalletConfig::secret()` +/// before it is assembled, so the mask glyph is the only thing that ever carries +/// the password length. +pub fn draw_wallet_config(f: &mut Frame, s: &WalletConfigScreen) { + let mark = |focused: bool| if focused { "> " } else { " " }; + + let login_display = s.login_display(); + let no_spend_mark = if s.no_spend { "[x]" } else { "[ ]" }; + let status_line = s.status.line(&s.rpc_login); + + let body = format!( + "{} rpc_url\n {}\n\n{} rpc_login\n {}\n\n{} no_spend\n {} /tip off\n\n{} action\n t test connection s save\n Esc back Tab fields", + mark(s.focus == ConfigField::RpcUrl), + s.rpc_url, + mark(s.focus == ConfigField::RpcLogin), + login_display, + mark(s.focus == ConfigField::NoSpend), + no_spend_mark, + mark(s.focus == ConfigField::Action), + ); + + let body = if status_line.is_empty() { + body + } else { + let glyph = if status_line.contains("error") || status_line.contains("not connected") { + "! " + } else { + "" + }; + format!("{body}\n\n---\n{glyph}{status_line}") + }; + + draw_text_overlay(f, "wallet config", &body); +} + fn io_err(e: io::Error) -> String { e.to_string() } diff --git a/src/wallet.rs b/src/wallet.rs index 340a9ad..b790afb 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -1074,3 +1074,339 @@ fn json_amount(v: &serde_json::Value) -> String { _ => String::new(), } } + +// --------------------------------------------------------------------------- +// Chain daemon client (the chain side of the RPC layer) +// --------------------------------------------------------------------------- +// +// This is *not* the wallet child: that one is a loopback HTTP Digest RPC. This +// one dials the daemon the wallet child scans from, and that is the connection +// Cuprate changes shape on (`docs/cuprate-launch-spike.md` §Parity gaps, all +// three verified by running it): +// +// * a height above the tip is a **bare HTTP 500 with a zero-byte body**, where +// monerod answers a JSON-RPC error object (`TOO_BIG_HEIGHT`); +// * `get_info` reports zero peers even while blocks are arriving, and its +// restricted server answers a placeholder 5 GiB `database_size`, an empty +// `version`, and `free_space = u64::MAX`; +// * `get_height` is a URI endpoint — `{"method":"get_height"}` over `/json_rpc` +// is rejected with 422. +// +// Nothing in this client parses a peer count, a database size, a free-space +// figure or a version string. There is no field for them to land in, so a UI +// wired to this client cannot show a placeholder as a measurement. + +/// `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` in monero's +/// `src/rpc/core_rpc_server_error_codes.h`. Cuprate answers the same request +/// with a bare HTTP 500 instead, which is why both spellings map to +/// [`WalletError::DaemonHeightOutOfRange`]. +const TOO_BIG_HEIGHT_CODE: i64 = -2; + +/// Typed failures of the chain-daemon calls. The wallet-child path above keeps +/// its plain string errors; this side distinguishes a *height* failure from +/// every other one because that is the answer Cuprate mangles. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WalletError { + /// The requested height is above the daemon's tip. Cuprate: bare HTTP 500, + /// empty body. monerod: HTTP 200, error code `-2`. + DaemonHeightOutOfRange, + /// A non-2xx status that is not the height case above. + DaemonHttpStatus(u16), + /// A JSON-RPC error object we do not special-case. + DaemonRpc { + /// The `error.code` the daemon sent. + code: i64, + /// The `error.message` the daemon sent. + message: String, + }, + /// A 2xx answer with no usable body. Carries the address and the reason. + DaemonNoBody(String), + /// The daemon could not be reached, or the answer could not be read. + DaemonTransport(String), +} + +impl WalletError { + /// Is this the "height above tip" failure? A caller that just asked for a + /// block at an unverified height may retry lower; every other error is a + /// different problem. + pub fn is_height_out_of_range(&self) -> bool { + matches!(self, Self::DaemonHeightOutOfRange) + } +} + +impl std::fmt::Display for WalletError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::DaemonHeightOutOfRange => { + f.write_str("daemon: height is above its chain tip (not synced that far yet)") + } + Self::DaemonHttpStatus(code) => write!(f, "daemon: HTTP {code}"), + Self::DaemonRpc { code, message } => write!(f, "daemon rpc error {code}: {message}"), + Self::DaemonNoBody(msg) | Self::DaemonTransport(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for WalletError {} + +/// What the chain view is allowed to know about a daemon: how far it is and how +/// far it is going. Deliberately nothing else — see the section comment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DaemonInfo { + /// Blocks the daemon has. + pub height: u64, + /// Blocks it is syncing towards. `0` means it reported none, which is not + /// the same as "caught up". + pub target_height: u64, +} + +/// Cap on a daemon answer, in bytes. A `get_block` blob is the large case. +pub const DAEMON_MAX_BYTES: usize = 8 * 1024 * 1024; + +/// `get_info` as the chain view needs it: height and target, nothing else. +pub async fn daemon_get_info( + addr: &str, + budget: Duration, +) -> std::result::Result { + let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#; + let request = json_rpc_request(addr, "/json_rpc", body); + let (status, raw) = daemon_http(addr, &request, budget).await?; + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + let result = json + .get("result") + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_info has no result")))?; + let height = result + .get("height") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| { + WalletError::DaemonNoBody(format!("{addr}: get_info has no chain height")) + })?; + let target_height = result + .get("target_height") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0); + Ok(DaemonInfo { + height, + target_height, + }) +} + +/// The daemon's tip, over the `get_height` URI endpoint. +/// +/// Cuprate rejects `{"method":"get_height"}` over `/json_rpc` with 422, and the +/// URI endpoint is what monerod has always answered — one spelling works on +/// both, so this is the one to use. +pub async fn daemon_get_height( + addr: &str, + budget: Duration, +) -> std::result::Result { + let request = uri_request(addr, "GET", "/get_height"); + let (status, raw) = daemon_http(addr, &request, budget).await?; + if is_server_error(status) { + return Err(WalletError::DaemonHeightOutOfRange); + } + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + // Both daemons answer a top-level `height` here; tolerate a jsonrpc + // envelope too rather than betting on the shape. + json.get("height") + .or_else(|| json.get("result").and_then(|r| r.get("height"))) + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_height has no height"))) +} + +/// One block by height, as raw bytes (the hex `blob` field, decoded). +/// +/// Not called yet: this is the entry point the wallet's own refresh loop needs +/// once it scans blocks itself instead of leaving that to `monero-wallet-rpc`. +/// It exists now because the out-of-range answer is the Cuprate behaviour such +/// a loop has to survive, and the mapping belongs with the rest of the client. +pub async fn daemon_get_block( + addr: &str, + height: u64, + budget: Duration, +) -> std::result::Result, WalletError> { + let body = format!( + r#"{{"jsonrpc":"2.0","id":"0","method":"get_block","params":{{"height":{height}}}}}"# + ); + let request = json_rpc_request(addr, "/json_rpc", &body); + let (status, raw) = daemon_http(addr, &request, budget).await?; + if is_server_error(status) { + return Err(WalletError::DaemonHeightOutOfRange); + } + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + let blob = json + .get("result") + .and_then(|r| r.get("blob")) + .and_then(|b| b.as_str()) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block has no blob")))?; + hex_decode(blob) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block blob is not hex"))) +} + +/// A bare 5xx is how Cuprate says "no such height" — it carries no body to +/// decode, so the *call* decides what it means: height-addressed calls (the two +/// above) read it as [`WalletError::DaemonHeightOutOfRange`], everything else +/// reads it as a status error. +fn is_server_error(status: u16) -> bool { + (500..600).contains(&status) +} + +fn daemon_ok_status(status: u16) -> std::result::Result<(), WalletError> { + if (200..300).contains(&status) { + return Ok(()); + } + Err(WalletError::DaemonHttpStatus(status)) +} + +fn json_rpc_request(addr: &str, path: &str, body: &str) -> String { + format!( + "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) +} + +fn uri_request(addr: &str, method: &str, path: &str) -> String { + format!( + "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) +} + +/// One request, one answer: status code plus body. `Connection: close` and read +/// to EOF, so `Content-Length` never has to be trusted. +async fn daemon_http( + addr: &str, + request: &str, + budget: Duration, +) -> std::result::Result<(u16, Vec), WalletError> { + let mut stream = tokio::time::timeout(budget, TcpStream::connect(addr)) + .await + .map_err(|_| WalletError::DaemonTransport(format!("{addr}: connect timed out")))? + .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; + let raw = tokio::time::timeout(budget, async { + stream.write_all(request.as_bytes()).await?; + let mut buf = Vec::new(); + let mut tmp = [0u8; 8192]; + loop { + let n = stream.read(&mut tmp).await?; + if n == 0 { + break; + } + buf.extend_from_slice(&tmp[..n]); + if buf.len() >= DAEMON_MAX_BYTES { + break; + } + } + Ok::, std::io::Error>(buf) + }) + .await + .map_err(|_| WalletError::DaemonTransport(format!("{addr}: read timed out")))? + .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; + split_http(&raw) + .ok_or_else(|| WalletError::DaemonTransport(format!("{addr}: not an HTTP response"))) +} + +/// Status code and body from a raw HTTP/1.1 response. +/// +/// Cuprate is axum/hyper: the body arrives `Transfer-Encoding: chunked`, so +/// scanning for the outermost braces is not a parse once a blob spans more than +/// one chunk. De-chunk here, once, for every call. +fn split_http(raw: &[u8]) -> Option<(u16, Vec)> { + let (head, body) = match find(raw, b"\r\n\r\n") { + Some(at) => (&raw[..at], &raw[at + 4..]), + None => { + let at = find(raw, b"\n\n")?; + (&raw[..at], &raw[at + 2..]) + } + }; + let head = std::str::from_utf8(head).ok()?; + let mut lines = head.lines(); + let status = lines.next()?.split_whitespace().nth(1)?.parse().ok()?; + let chunked = lines.any(|line| { + line.split_once(':').is_some_and(|(k, v)| { + k.eq_ignore_ascii_case("transfer-encoding") + && v.to_ascii_lowercase().contains("chunked") + }) + }); + let body = if chunked { + dechunk(body)? + } else { + body.to_vec() + }; + Some((status, body)) +} + +fn dechunk(body: &[u8]) -> Option> { + let mut out = Vec::new(); + let mut at = 0; + loop { + let line_end = find(&body[at..], b"\r\n")?; + let size_line = std::str::from_utf8(&body[at..at + line_end]).ok()?; + // `size[;chunk-extension]` + let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?; + at += line_end + 2; + if size == 0 { + return Some(out); + } + if at + size > body.len() { + return None; + } + out.extend_from_slice(&body[at..at + size]); + at += size; + if body[at..].starts_with(b"\r\n") { + at += 2; + } else if body[at..].starts_with(b"\n") { + at += 1; + } + } +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + haystack.windows(needle.len()).position(|w| w == needle) +} + +fn daemon_json(body: &[u8], addr: &str) -> std::result::Result { + let text = std::str::from_utf8(body) + .map_err(|_| WalletError::DaemonNoBody(format!("{addr}: body is not UTF-8")))?; + let json: serde_json::Value = serde_json::from_str(text.trim()) + .map_err(|e| WalletError::DaemonNoBody(format!("{addr}: {e}")))?; + if let Some(err) = json.get("error") { + let code = err + .get("code") + .and_then(serde_json::Value::as_i64) + .unwrap_or(0); + if code == TOO_BIG_HEIGHT_CODE { + return Err(WalletError::DaemonHeightOutOfRange); + } + let message = err + .get("message") + .and_then(|m| m.as_str()) + .unwrap_or("rpc error") + .to_string(); + return Err(WalletError::DaemonRpc { code, message }); + } + Ok(json) +} + +fn hex_decode(s: &str) -> Option> { + let bytes = s.as_bytes(); + if !bytes.len().is_multiple_of(2) { + return None; + } + let mut out = Vec::with_capacity(bytes.len() / 2); + for pair in bytes.chunks(2) { + out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?); + } + Some(out) +} + +fn hex_val(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 0eb8f3b..f73a738 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -25,10 +25,24 @@ use zeroize::Zeroizing; use crate::store::Store; use crate::wallet::{self, ChainSource, Wallet}; -/// `monerod` RPC port for a local chain source. Unrestricted RPC default; the -/// wallet child is the only thing that dials it. +/// `monerod` RPC port for a local chain source. This is the *unrestricted* +/// server (`--rpc-bind-port`); the wallet child is the only thing that dials it. pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081; +/// `monerod`'s *restricted* RPC port (`--rpc-restricted-bind-port`). Nothing in +/// this app ever dials it: a restricted daemon answers, so pointing the wallet +/// child there fails silently and dishonestly — Cuprate's restricted server +/// returns a placeholder `database_size` (exactly 5 GiB), an empty `version`, +/// and `free_space = u64::MAX` on both servers +/// (`docs/cuprate-launch-spike.md` §Parity gaps). The unrestricted listener is +/// the one with real numbers. +/// +/// This is monerod's numbering. An in-process Cuprate chooses its own ports in +/// its config; whichever port that is, the rule is the same and the wallet +/// child must be pointed at the *unrestricted* listener, never the restricted +/// one (`docs/WALLET.md`, "Chain daemon"). +pub const MONEROD_RESTRICTED_RPC_PORT: u16 = 18089; + /// Name of the `monero-wallet-rpc` binary when the caller does not point at one. pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc"; @@ -587,6 +601,48 @@ mod tests { assert!(err.contains("SOCKS"), "got {err}"); } + /// The routing rule the Cuprate spike forced: the wallet child dials the + /// *unrestricted* daemon RPC. A restricted listener answers too, so getting + /// this wrong shows up as a wrong number rather than as an error. + #[test] + fn the_wallet_child_dials_the_unrestricted_daemon_rpc() { + let dir = Path::new("/tmp"); + let monerod = PathBuf::from("/usr/bin/monerod"); + let addr = WalletChild::daemon_address(&local_source(dir, monerod.clone())) + .expect("a local source has an address"); + assert_eq!(addr, format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")); + assert_ne!( + DEFAULT_MONEROD_RPC_PORT, MONEROD_RESTRICTED_RPC_PORT, + "the two servers are different ports; confusing them is the bug" + ); + + // monerod is spawned on the full RPC port, and the restricted listener + // is never asked for. + let argv = WalletChild::monerod_argv(&monerod, &dir.join("data"), DEFAULT_MONEROD_RPC_PORT); + assert!( + argv.windows(2) + .any(|w| w[0] == "--rpc-bind-port" && w[1] == DEFAULT_MONEROD_RPC_PORT.to_string()), + "{argv:?}" + ); + let restricted = MONEROD_RESTRICTED_RPC_PORT.to_string(); + assert!(!argv.iter().any(|a| a.contains(&restricted)), "{argv:?}"); + + // ...and the wallet child is handed that same address. + let rpc = WalletChild::wallet_rpc_argv( + Path::new("/usr/bin/monero-wallet-rpc"), + 18_083, + "user:pass", + &dir.join("wallet"), + Some(&addr), + ); + assert!( + rpc.windows(2) + .any(|w| w[0] == "--daemon-address" && w[1] == addr), + "{rpc:?}" + ); + assert!(!rpc.iter().any(|a| a.contains(&restricted)), "{rpc:?}"); + } + #[test] fn daemon_address_matches_each_chain_source() { assert_eq!(WalletChild::daemon_address(&ChainSource::None), None); diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index fee8951..fb3ca50 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -46,10 +46,12 @@ fn help_overlay_lists_core_bindings() { "F4", "F5", "F6", + "F6 h", "F6 s", "F6 n", "F6 r", "F6 y", + "F7", "send chat", "/profile", "/pay", diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index bafdbe2..825cf5b 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -13,9 +13,10 @@ use onionwire::qr; use onionwire::node::{DaemonSync, WalletChildState}; +use onionwire::Payment; use onionwire::tui::{ - backup_screen_text, banner_for_width, chain_view, compact_banner, draw_share, draw_wallet, - fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph, + backup_screen_text, banner_for_width, chain_view, compact_banner, draw_history, draw_share, + draw_wallet, fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph, osc52_copy, quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, wallet_readiness, wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner, ChainChoice, ProfileEditor, WalletReadiness, WALLET_LINE_MAX, WipeKind, @@ -1176,3 +1177,134 @@ fn wallet_view_only_badge_renders_at_80_and_120() { } } } + +fn history_payment_fixture() -> Payment { + Payment { + id: 1, + dir: "out".into(), + kind: "payment".into(), + amount_atomic: "1000000000".into(), + txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()), + verified: true, + created_at: 1700000000, + address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(), + memo: "for pizza".into(), + } +} + +#[test] +fn dump_history_frames() { + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; + let payments = vec![ + history_payment_fixture(), + Payment { + id: 2, + dir: "in".into(), + amount_atomic: "50000000000".into(), + txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()), + verified: true, + created_at: 1700000100, + address: String::new(), + memo: String::new(), + kind: "payment".into(), + }, + Payment { + id: 3, + dir: "out".into(), + amount_atomic: "500000000".into(), + txid: None, + verified: false, + created_at: 1700000200, + address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(), + memo: String::new(), + kind: "payment".into(), + }, + ]; + let now = 1700000300; + for (w, h) in SIZES { + draw_to(w, h, "history list", |f| { + draw_history(f, &payments, 0, false, "alice", now); + }); + draw_to(w, h, "history detail", |f| { + draw_history(f, &payments, 0, true, "alice", now); + }); + draw_to(w, h, "history empty", |f| { + draw_history(f, &[], 0, false, "bob", now); + }); + } +} + +#[test] +fn dump_history_ascii_frames() { + unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; + let _g = ASCII_ENV.lock(); + let payments = vec![history_payment_fixture()]; + let now = 1700000300; + for (w, h) in SIZES { + draw_to(w, h, "history ascii list", |f| { + draw_history(f, &payments, 0, false, "alice", now); + }); + } + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} + +/// Lock for env-var-touching tests (mirrors tui_spec.rs pattern). +static ASCII_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Dump history frames at 80x24 and 120x40 for PR-body evidence: +/// empty, mixed verified/unverified list, detail view, and a hostile memo +/// (C0 control chars + bidi override) rendered as inert text. +#[test] +fn dump_history_pr_frames() { + unsafe { std::env::remove_var("ONIONWIRE_ASCII"); } + unsafe { std::env::remove_var("NO_COLOR"); }; + let now = 1700000300i64; + let hostile = "pay\x01now\u{202E}reverse"; + let payments = vec![ + Payment { + id: 1, + dir: "out".into(), + kind: "tip".into(), + amount_atomic: "1000000000".into(), + address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(), + memo: "coffee".into(), + txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()), + verified: true, + created_at: 1699999000, + }, + Payment { + id: 2, + dir: "in".into(), + kind: "payment".into(), + amount_atomic: "50000000000".into(), + address: String::new(), + memo: String::new(), + txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()), + verified: true, + created_at: 1700000100, + }, + Payment { + id: 3, + dir: "out".into(), + kind: "invoice".into(), + amount_atomic: "500000000".into(), + address: String::new(), + memo: hostile.to_string(), + txid: None, + verified: false, + created_at: 1700000200, + }, + ]; + draw_to(80, 24, "history list (mixed verified/unverified)", |f| { + draw_history(f, &payments, 0, false, "alice", now); + }); + draw_to(80, 24, "history detail (hostile memo)", |f| { + draw_history(f, &payments, 2, true, "alice", now); + }); + draw_to(80, 24, "history empty", |f| { + draw_history(f, &[], 0, false, "bob", now); + }); + draw_to(120, 40, "history list (mixed)", |f| { + draw_history(f, &payments, 0, false, "alice", now); + }); +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 9506afa..a815160 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,15 +1,17 @@ -//! Spec implementation tests for docs/TUI.md (this card). -//! Does not own `tests/tui_frames.rs` (PR #23). - use onionwire::Message; +use onionwire::node::{DaemonSync, WalletChildState}; use onionwire::outbox::{OutboxEntry, OutboxStatus}; +use onionwire::Payment; use onionwire::qr; use onionwire::tui::{ - OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat, - draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, is_onion_host, - main_footer_hints, main_header_line, parse_daemon_addr, paste_screen_text, retry_in_text, - roster_col_width, short_send_reason, status_footer, wrap_invite, + OutboxSummary, WALLET_LINE_MAX, alert_line, ascii_chrome, chain_view_with_progress, + chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, + empty_friend_chat_text, help_overlay_text, is_onion_host, main_footer_hints, main_header_line, + parse_daemon_addr, paste_screen_text, retry_in_text, roster_col_width, short_send_reason, + status_footer, sync_line, wallet_readiness, wrap_invite, + ConfigField, ConfigStatus, WalletConfigScreen, }; +use onionwire::wallet::{ChainSource, PingResult}; use ratatui::Frame; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -17,733 +19,6 @@ use ratatui::layout::{Constraint, Layout}; use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap}; use std::sync::Mutex; -const FP: &str = "abcdef0123456789deadbeefcafebabe"; -static ASCII_ENV: Mutex<()> = Mutex::new(()); -const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; - -fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String { - let mut screen = String::new(); - for y in 0..h { - for x in 0..w { - screen.push_str(buf[(x, y)].symbol()); - } - screen.push('\n'); - } - screen -} - -#[test] -fn status_footer_keeps_send_failed_and_chrome() { - let note = "send failed: peer onion down"; - for w in [80u16, 120, 200] { - let line = status_footer(w, FP, ONION, Some(note), main_footer_hints()); - assert!( - line.chars().count() <= w as usize, - "footer wider than {w}: {} {line:?}", - line.chars().count() - ); - assert!( - line.contains("send failed"), - "{w} dropped fail-closed note: {line:?}" - ); - assert!(line.contains("TOR"), "{w} missing TOR: {line:?}"); - assert!(line.contains("me:"), "{w} missing me:: {line:?}"); - assert!(line.contains("? help"), "{w} missing ? help: {line:?}"); - } -} - -#[test] -fn main_header_is_one_line_at_80() { - let line = main_header_line(80, FP, ONION); - assert!(!line.contains('\n'), "header must be one line: {line:?}"); - assert!( - line.chars().count() <= 80, - "header wider than 80: {} {line:?}", - line.chars().count() - ); - assert!(line.to_ascii_lowercase().contains("onionwire"), "{line:?}"); - assert!(line.contains("me:"), "{line:?}"); -} - -#[test] -fn roster_is_fixed_cells_not_percent() { - assert_eq!(roster_col_width(80), 22); - assert_eq!(roster_col_width(119), 22); - assert_eq!(roster_col_width(120), 28); - assert_eq!(roster_col_width(200), 28); -} - -#[test] -fn help_overlay_at_80x24_is_fullscreen_last_line_visible() { - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| { - f.render_widget( - Paragraph::new(" .-~~-. ONIONWIRE\n┌roster junk\n┌composer"), - f.area(), - ); - draw_text_overlay(f, "? help", help_overlay_text()); - }) - .expect("draw"); - let buf = terminal.backend().buffer(); - let screen = screen_from(buf, 80, 24); - assert!( - screen.contains("Esc closes this overlay"), - "last help line clipped:\n{screen}" - ); - assert!( - !screen.contains(".-~~-."), - "help punched through banner:\n{screen}" - ); - assert!( - !screen.contains("┌roster"), - "help punched through roster:\n{screen}" - ); - assert!(screen.contains("? help"), "help title missing:\n{screen}"); -} - -fn draw_main_standin(f: &mut Frame, empty_roster: bool, composer: &str, note: Option<&str>) { - let area = f.area(); - let header = main_header_line(area.width, FP, ONION); - let cols = Layout::vertical([ - Constraint::Length(1), - Constraint::Min(3), - Constraint::Length(3), - Constraint::Length(1), - ]) - .split(area); - f.render_widget(Paragraph::new(header), cols[0]); - let roster_w = roster_col_width(area.width).min(cols[1].width.saturating_sub(10)); - let panes = - Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[1]); - let items = if empty_roster { - vec![ListItem::new("no friends")] - } else { - vec![ListItem::new("alice aaaaaaaa…")] - }; - f.render_stateful_widget( - List::new(items) - .highlight_symbol("> ") - .block(Block::default().borders(Borders::ALL).title("roster 0")), - panes[0], - &mut ratatui::widgets::ListState::default(), - ); - f.render_widget( - Paragraph::new("no friends yet") - .wrap(Wrap { trim: false }) - .block(Block::default().borders(Borders::ALL).title(" chat")), - panes[1], - ); - f.render_widget( - Paragraph::new(format!("> {composer}")).wrap(Wrap { trim: false }), - cols[2], - ); - let footer = status_footer(area.width, FP, ONION, note, main_footer_hints()); - f.render_widget(Paragraph::new(footer), cols[3]); -} - -#[test] -fn reconstructed_main_empty_roster_and_composer() { - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_main_standin(f, true, "message", None)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - let row0: String = screen.lines().next().unwrap_or("").to_string(); - assert!( - !row0.contains(".-~~-."), - "80x24 main still uses 3-line wordmark:\n{screen}" - ); - assert!( - screen.contains("no friends"), - "empty roster blank:\n{screen}" - ); - assert!( - screen.contains("message"), - "composer missing placeholder:\n{screen}" - ); - assert!( - !screen.contains("/wipe"), - "composer still dumps slash list:\n{screen}" - ); -} - -#[test] -fn reconstructed_main_keeps_send_failed_on_footer() { - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_main_standin(f, false, "hello", Some("send failed: peer onion down"))) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - assert!( - screen.contains("send failed"), - "fail-closed missing from frame:\n{screen}" - ); -} - -#[test] -fn dump_spec_frames() { - let _guard = ASCII_ENV.lock().expect("ascii env lock"); - unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; - for (w, h) in [(80u16, 24u16), (120, 40)] { - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| { - draw_main_standin( - f, - false, - "hello from composer", - Some("send failed: peer onion down"), - ) - }) - .expect("draw"); - println!("===== AFTER main {w}x{h} ====="); - print!("{}", screen_from(terminal.backend().buffer(), w, h)); - - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| { - draw_main_standin(f, true, "message", None); - draw_text_overlay(f, "? help", help_overlay_text()); - }) - .expect("draw"); - println!("===== AFTER help {w}x{h} ====="); - print!("{}", screen_from(terminal.backend().buffer(), w, h)); - - let invite = sample_invite(); - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal.draw(|f| draw_share(f, &invite)).expect("draw"); - println!("===== AFTER share {w}x{h} ====="); - print!("{}", screen_from(terminal.backend().buffer(), w, h)); - } -} - -fn sample_invite() -> String { - let sk = [7u8; 32]; - qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") -} - -fn invite_line_ok(line: &str) -> bool { - let t = line.trim(); - t.is_empty() - || t.starts_with("onionwire:") - || t.starts_with("k=") - || t.starts_with("o=") - || t.starts_with("spk=") - || t.starts_with("sig=") - || t.chars().all(|c| c.is_ascii_hexdigit()) -} - -#[test] -fn alert_line_truncates_to_frame_width() { - let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped"; - let line = alert_line(long, 80); - assert!( - line.chars().count() <= 80, - "alert wider than 80: {} {line:?}", - line.chars().count() - ); - assert!( - line.contains('…') || line.contains("..."), - "long alert was not truncated: {line:?}" - ); - assert!( - !line.contains("roster on the next row"), - "alert still has overflow tail: {line:?}" - ); -} - -#[test] -fn wrap_invite_breaks_on_field_boundaries() { - let invite = sample_invite(); - assert!(invite.len() > 78, "fixture too short to wrap: {invite}"); - let wrapped = wrap_invite(&invite, 78); - for line in wrapped.lines() { - assert!( - line.chars().count() <= 78, - "invite line wider than 78: {} {line:?}", - line.chars().count() - ); - assert!( - invite_line_ok(line), - "invite wrapped mid-token: {line:?}\n{wrapped}" - ); - } - assert!( - wrapped.contains("onionwire:v1:"), - "lost invite prefix:\n{wrapped}" - ); - assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); - assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); - let joined: String = wrapped.lines().map(str::trim).collect(); - assert_eq!( - joined, invite, - "wrap must be newline-joinable back to payload" - ); -} - -#[test] -fn draw_share_invite_does_not_wrap_mid_token() { - let invite = sample_invite(); - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal.draw(|f| draw_share(f, &invite)).expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - assert!( - screen.contains("onionwire:v1:"), - "missing prefix:\n{screen}" - ); - for raw in screen.lines() { - let inner = raw.trim_start_matches(['│', '|', ' ']); - let inner = inner.trim_end_matches(['│', '|', ' ']); - if inner.starts_with("onionwire:") - || inner.starts_with("k=") - || inner.starts_with("o=") - || inner.starts_with("spk=") - || inner.starts_with("sig=") - || inner.chars().all(|c| c.is_ascii_hexdigit()) - { - assert!( - invite_line_ok(inner), - "share pane mid-token wrap: {inner:?}\n{screen}" - ); - } - if inner.starts_with('c') && inner.contains(":o=") { - panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}"); - } - } -} - -#[test] -fn empty_friend_chat_has_send_hint() { - let text = empty_friend_chat_text(); - assert!(text.contains("no messages"), "{text:?}"); - assert!(text.contains("type below, Enter sends"), "{text:?}"); -} - -#[test] -fn paste_error_keeps_resubmit_hint() { - let body = paste_screen_text("", Some("bad invite")); - assert!(body.contains("bad invite"), "{body:?}"); - assert!(body.contains("Enter resubmits"), "{body:?}"); - assert!(body.contains("Esc back"), "{body:?}"); - let ok = paste_screen_text("onionwire:v1:k=x", None); - assert!( - ok.contains("paste onionwire:v1 payload"), - "happy-path hint lost: {ok:?}" - ); -} - -#[test] -fn ascii_switch_80x24_frame_is_pure_ascii() { - let _guard = ASCII_ENV.lock().expect("ascii env lock"); - unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; - assert!( - ascii_chrome(), - "ONIONWIRE_ASCII set but ascii_chrome() is false" - ); - let footer = status_footer(80, FP, ONION, None, main_footer_hints()); - assert!( - footer.contains("..."), - "ASCII truncation marker missing: {footer:?}" - ); - assert!( - !footer.contains('…'), - "unicode ellipsis still in footer: {footer:?}" - ); - - let invite = sample_invite(); - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal.draw(|f| draw_share(f, &invite)).expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - let non_ascii: Vec = screen.chars().filter(|c| !c.is_ascii()).collect(); - assert!( - non_ascii.is_empty(), - "ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}" - ); - assert!( - screen.contains("..."), - "truncation marker missing from ASCII frame:\n{screen}" - ); - assert!( - screen.contains('+') && screen.contains('|') && screen.contains('-'), - "ASCII borders missing:\n{screen}" - ); - println!("===== AFTER ascii share 80x24 =====\n{screen}"); - unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; -} - -// --------------------------------------------------------------------------- -// Outbox delivery state (card t_d9a5b065) -// -// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` / -// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire -// prefix, no parallel state model. -// --------------------------------------------------------------------------- - -fn out_msg(id: i64, body: &str) -> Message { - Message { - id, - dir: "out".into(), - plaintext: body.as_bytes().to_vec(), - } -} - -fn in_msg(id: i64, body: &str) -> Message { - Message { - id, - dir: "in".into(), - plaintext: body.as_bytes().to_vec(), - } -} - -fn pending_row( - message_id: i64, - body: &str, - status: OutboxStatus, - attempts: u32, - next_in: i64, - now: i64, -) -> OutboxEntry { - OutboxEntry { - id: 1, - friend_pk: vec![9u8; 32], - message_id, - body: body.as_bytes().to_vec(), - attempts, - next_attempt_at: now + next_in, - created_at: now, - status, - last_error: None, - } -} - -fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { - pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now) -} - -fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry { - pending_row(message_id, body, OutboxStatus::Sending, 1, 0, now) -} - -fn failed_row(message_id: i64, body: &str, why: &str, now: i64) -> OutboxEntry { - pending_row( - message_id, - body, - OutboxStatus::Failed(why.into()), - 8, - 0, - now, - ) -} - -/// Marker is everything after the two-space separator the render helper uses. -fn marker_of(line: &str) -> &str { - line.rsplit(" ").next().unwrap_or("") -} - -/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`. -fn force_unicode_mode() { - unsafe { - std::env::remove_var("ONIONWIRE_ASCII"); - std::env::remove_var("NO_COLOR"); - } -} - -#[test] -fn queued_and_delivered_messages_render_different_markers() { - let guard = ASCII_ENV.lock().expect("ascii env lock"); - force_unicode_mode(); - let _guard = guard; - let now = 1_700_000_000; - let msgs = vec![out_msg(1, "ping"), out_msg(2, "pong")]; - let pending = vec![queued_row(2, "pong", 2, 45, now)]; - - let (lines, summary) = chat_with_delivery(&msgs, &pending, now); - - assert!( - lines[0].contains('✓'), - "delivered row lost its mark: {:?}", - lines[0] - ); - assert!(!lines[0].contains("queued"), "{:?}", lines[0]); - assert!( - lines[1].contains('◷'), - "queued row lost its glyph: {:?}", - lines[1] - ); - assert!(lines[1].contains("queued"), "{:?}", lines[1]); - assert!( - lines[1].contains("try 2/8"), - "attempt count missing: {:?}", - lines[1] - ); - assert!( - lines[1].contains("retry 45s"), - "retry age missing: {:?}", - lines[1] - ); - assert_ne!( - marker_of(&lines[0]), - marker_of(&lines[1]), - "queued and delivered must not share a marker" - ); - assert_eq!(summary.queued, 1); - assert_eq!(summary.failed, 0); -} - -/// The case the body match got wrong: the same text sent twice, only the -/// *older* send still queued. Joined by body, the (single) pending row lands on -/// the newest send and the actually-queued row shows `✓` — which is exactly -/// false delivery. The join is on `Message::id` / `OutboxEntry::message_id`. -#[test] -fn identical_bodies_join_by_message_id_not_body() { - let guard = ASCII_ENV.lock().expect("ascii env lock"); - force_unicode_mode(); - let _guard = guard; - let now = 1_700_000_000; - let msgs = vec![out_msg(7, "same text"), out_msg(8, "same text")]; - let pending = vec![queued_row(7, "same text", 1, 30, now)]; - - let (lines, summary) = chat_with_delivery(&msgs, &pending, now); - - assert!( - lines[0].contains('◷') && lines[0].contains("queued"), - "queued marker must land on the queued row (id 7): {:?}", - lines[0] - ); - assert!( - !lines[0].contains('✓'), - "queued row must not claim delivery: {:?}", - lines[0] - ); - assert_eq!( - marker_of(&lines[1]), - "✓", - "delivered row (id 8) must keep its mark: {:?}", - lines[1] - ); - assert_eq!(summary.note().as_deref(), Some("1 queued")); -} - -#[test] -fn delivery_markers_have_exercised_ascii_fallbacks() { - let _guard = ASCII_ENV.lock().expect("ascii env lock"); - unsafe { - std::env::set_var("ONIONWIRE_ASCII", "1"); - std::env::remove_var("NO_COLOR"); - } - let now = 500; - let msgs = vec![ - out_msg(1, "alpha"), - out_msg(2, "beta"), - out_msg(3, "gamma"), - out_msg(4, "delta"), - in_msg(5, "epsilon"), - ]; - let pending = vec![ - failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now), - queued_row(2, "beta", 1, 30, now), - sending_row(3, "gamma", now), - ]; - - let (lines, summary) = chat_with_delivery(&msgs, &pending, now); - for line in &lines { - assert!( - line.is_ascii(), - "ASCII fallback missing, non-ASCII in {line:?}" - ); - } - assert_eq!(marker_of(&lines[0]), "failed: connection timed out"); - assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)"); - assert_eq!(marker_of(&lines[2]), "sending"); - assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`"); - assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state"); - assert_eq!(summary.queued, 2, "queued + sending are both outstanding"); - assert_eq!(summary.failed, 1); - - unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; -} - -#[test] -fn retry_age_and_failure_reason_are_short_forms() { - assert_eq!(retry_in_text(45), "retry 45s"); - assert_eq!(retry_in_text(59), "retry 59s"); - assert_eq!(retry_in_text(60), "retry 1m"); - assert_eq!(retry_in_text(720), "retry 12m"); - assert_eq!(retry_in_text(0), "retry now"); - assert_eq!(retry_in_text(-30), "retry now"); - - assert_eq!( - short_send_reason("connect abcdef.onion:80: connection timed out", 24), - "connection timed out" - ); - let long = short_send_reason("a-really-long-failure-description-here", 12); - assert!(long.chars().count() <= 12, "{long:?}"); - assert!( - long.contains('…') || long.contains("..."), - "truncation marker missing: {long:?}" - ); - assert_eq!(short_send_reason("nope", 24), "nope"); -} - -#[test] -fn delivery_tag_reads_the_outbox_status_enum() { - let guard = ASCII_ENV.lock().expect("ascii env lock"); - force_unicode_mode(); - let _guard = guard; - assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓"); - assert_eq!( - delivery_tag(&OutboxStatus::Queued, 3, 120), - "◷ queued (try 3/8, retry 2m)" - ); - assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending"); - assert_eq!( - delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0), - "✗ failed: nope" - ); -} - -#[test] -fn footer_summary_counts_queued_and_keeps_fail_closed() { - let none = OutboxSummary::default(); - assert_eq!(none.note(), None); - - let queued = OutboxSummary { - queued: 2, - failed: 0, - first_error: None, - }; - assert_eq!(queued.note().as_deref(), Some("2 queued")); - - let failed = OutboxSummary { - queued: 0, - failed: 1, - first_error: Some("connect peer.onion:80: connection timed out".into()), - }; - let note = failed.note().expect("failed rows must produce a note"); - assert!(note.starts_with("send failed:"), "{note:?}"); - assert!(note.contains("connection timed out"), "{note:?}"); - - let mixed = OutboxSummary { - queued: 3, - failed: 1, - first_error: Some("connect peer.onion:80: connection timed out".into()), - }; - let mixed_note = mixed.note().expect("mixed rows must produce a note"); - assert!(mixed_note.contains("3 queued"), "{mixed_note:?}"); - assert!(mixed_note.contains("send failed"), "{mixed_note:?}"); - - // Fail-closed copy stays visible in the real footer at the 80-col floor. - let line = status_footer(80, FP, ONION, Some(¬e), main_footer_hints()); - assert!( - line.chars().count() <= 80, - "{} {line:?}", - line.chars().count() - ); - assert!(line.contains("send failed"), "footer dropped it: {line:?}"); - assert!(line.contains("TOR") && line.contains("? help"), "{line:?}"); - - let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints()); - assert!(queued_line.contains("2 queued"), "{queued_line:?}"); - assert!(queued_line.chars().count() <= 80); - - // `! ` ornament (colour off) still lands on the derived failing note. - let _guard = ASCII_ENV.lock().expect("ascii env lock"); - unsafe { std::env::set_var("NO_COLOR", "1") }; - let no_color = status_footer(80, FP, ONION, Some(¬e), main_footer_hints()); - assert!(no_color.contains("! send failed"), "{no_color:?}"); - unsafe { std::env::remove_var("NO_COLOR") }; -} - -/// The card's width criterion: draw the real helpers at the documented floor -/// (80x24) and prove nothing in the chat/footer region exceeds the width, and -/// that an over-long row wraps in the pane instead of being clipped. -#[test] -fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() { - let guard = ASCII_ENV.lock().expect("ascii env lock"); - force_unicode_mode(); - let _guard = guard; - let now = 1_700_000_000; - let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border"; - let msgs = vec![out_msg(1, "ok"), in_msg(2, "pong"), out_msg(3, long)]; - let pending = vec![queued_row(3, long, 3, 45, now)]; - - let (lines, summary) = chat_with_delivery(&msgs, &pending, now); - for line in lines.iter().take(2) { - assert!( - line.chars().count() <= 80, - "short row wider than 80: {} {line:?}", - line.chars().count() - ); - } - let footer = status_footer( - 80, - FP, - ONION, - summary.note().as_deref(), - main_footer_hints(), - ); - assert!(footer.chars().count() <= 80, "{footer:?}"); - - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| { - let area = f.area(); - let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); - draw_chat(f, cols[0], &lines, Some("alice"), true, 0); - f.render_widget(Paragraph::new(footer.clone()), cols[1]); - }) - .expect("draw"); - - let buf = terminal.backend().buffer(); - let mut screen = String::new(); - for y in 0..24u16 { - for x in 0..80u16 { - screen.push_str(buf[(x, y)].symbol()); - } - screen.push('\n'); - } - for (y, row) in screen.lines().enumerate() { - assert!( - row.chars().count() <= 80, - "80x24 chat/footer row {y} wider than the terminal: {} {row:?}", - row.chars().count() - ); - } - assert!( - screen.contains('◷'), - "queued glyph missing from frame:\n{screen}" - ); - assert!(screen.contains("queued"), "queued word missing:\n{screen}"); - assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}"); - assert!( - screen.contains("with the roster border"), - "long row was clipped, not wrapped:\n{screen}" - ); - assert!( - screen.contains("1 queued"), - "footer summary missing:\n{screen}" - ); - println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}"); -} - -/// The renderer consumes the real outbox API, not a hand-written fixture: a -/// genuine unreachable-onion send leaves a `Queued` row, and that row is what -/// the chat line and the footer note are built from. -#[tokio::test] -async fn renders_a_queued_row_from_a_real_outbox_send() { - use onionwire::Store; - use onionwire::outbox::{BoxFut, Deliverer, Outbox}; - use std::sync::Arc; struct Dead; impl Deliverer for Dead { @@ -844,3 +119,120 @@ fn onion_hosts_are_recognised_before_any_spawn() { assert!(!is_onion_host("node.example.com")); assert!(!is_onion_host("notonion")); } + +// --------------------------------------------------------------------------- +// The chain view against a Cuprate daemon: connectivity is inferred from +// block-height movement, never from `get_info`'s peer counts (zero while it +// downloads blocks) or from its placeholder `database_size`/`free_space`. +// --------------------------------------------------------------------------- + +/// A daemon that answered, but reported no chain target: exactly what Cuprate +/// does at rest — `synchronized = true`, `target_height = 0`, zero peers. The +/// screen must not dress that up as progress (`1160/0`) or as "synced". +#[test] +fn a_daemon_with_no_chain_target_is_unknown_not_synced() { + let sync = DaemonSync { + reachable: true, + height: 1160, + target_height: 0, + note: None, + }; + let line = sync_line(&sync, None); + assert_eq!( + line, + "sync: unknown — daemon reports no chain target (height 1160)" + ); + assert!(!line.contains("synced"), "{line}"); + assert!(!line.contains("syncing"), "{line}"); + assert!(!sync.synced(), "no target is not 'caught up'"); +} + +#[test] +fn connectivity_follows_block_height_movement_only() { + let sync = DaemonSync { + reachable: true, + height: 23_758, + target_height: 3_090_939, + note: None, + }; + // No earlier sample: the old copy, no connectivity claim. + assert_eq!(sync_line(&sync, None), "sync: syncing — 23758/3090939"); + // The height moved: this is the only evidence of a P2P connection we have. + assert_eq!( + sync_line(&sync, Some(23_000)), + "sync: connected to P2P — syncing 23758/3090939" + ); + // The daemon answers, but nothing arrives: do not call that connected. + let stalled = sync_line(&sync, Some(23_758)); + assert_eq!( + stalled, + "sync: no new blocks — 23758/3090939 (daemon answering, no progress)" + ); + assert!(!stalled.contains("connected"), "{stalled}"); +} + +#[test] +fn reaching_the_target_is_synced_and_an_unreachable_daemon_stays_unknown() { + let synced = DaemonSync { + reachable: true, + height: 3_210_000, + target_height: 3_210_000, + note: None, + }; + assert_eq!( + sync_line(&synced, Some(3_100_000)), + "sync: synced — height 3210000" + ); + let dead = DaemonSync { + reachable: false, + height: 0, + target_height: 0, + note: Some("127.0.0.1:18081: Connection refused".into()), + }; + assert_eq!( + sync_line(&dead, Some(3_210_000)), + "sync: unknown — 127.0.0.1:18081: Connection refused" + ); +} + +/// The whole chain block on a Cuprate answer: real numbers, placeholders +/// nowhere. `DaemonSync` has no peer/database/free-space field to leak, and the +/// storage line comes from `df` on our own disk, not from the daemon. +#[test] +fn the_chain_block_never_shows_a_daemon_placeholder_metric() { + let view = chain_view_with_progress( + &ChainSource::Remote { + host: "127.0.0.1".into(), + port: 18089, + }, + WalletChildState::Running, + &DaemonSync { + reachable: true, + height: 23_758, + target_height: 3_090_939, + note: None, + }, + None, + wallet_readiness(true, true, false), + Some(23_000), + ); + let block = view.lines().join("\n"); + for banned in [ + "5368709120", + "peer", + "18446744073709551615", + "0.1.0-preview", + ] { + assert!(!block.contains(banned), "{banned} reached the UI:\n{block}"); + } + assert_eq!( + view.sync_line, + "sync: connected to P2P — syncing 23758/3090939" + ); + for line in view.lines() { + assert!( + line.chars().count() <= WALLET_LINE_MAX, + "line too long: {line}" + ); + } +} diff --git a/tests/wallet.rs b/tests/wallet.rs index 5f71a20..f2be004 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,12 +1,13 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. use std::sync::{Arc, Mutex}; +use std::time::Duration; use ed25519_dalek::SigningKey; use onionwire::pay; use onionwire::wallet::{ - self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet, - WalletConfig, WalletStatus, readiness, + self, DaemonInfo, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, + Wallet, WalletConfig, WalletError, WalletStatus, readiness, }; use onionwire::{PaymentWrite, Store}; use rand::rngs::OsRng; @@ -1130,3 +1131,232 @@ fn freed_loopback_port() -> u16 { drop(listener); port } + +// --------------------------------------------------------------------------- +// Chain daemon client: the Cuprate parity workarounds. +// +// Every payload below is copied from the Spike A evidence +// (`rpc-evidence/` next to `docs/cuprate-launch-spike.md`), not invented: +// Cuprate answers an out-of-range `get_block` with a bare HTTP 500 and a +// zero-byte body, reports `outgoing_connections_count = 0` while it downloads +// blocks, answers `database_size = 5368709120` (exactly 5 GiB) and +// `version = ""` on its restricted server, and `free_space` is `u64::MAX` on +// both servers. +// --------------------------------------------------------------------------- + +/// Serve exactly one HTTP response, then drop the listener. Returns the port. +async fn serve_raw(response: String) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.expect("accept"); + let mut buf = vec![0u8; 8192]; + let _ = sock.read(&mut buf).await; + let _ = sock.write_all(response.as_bytes()).await; + }); + port +} + +/// Same, but records the request line so a test can assert which endpoint and +/// method the client used. +async fn serve_raw_logged(response: String, log: Arc>>) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.expect("accept"); + let mut buf = vec![0u8; 8192]; + let n = sock.read(&mut buf).await.unwrap_or(0); + log.lock() + .expect("log") + .push(String::from_utf8_lossy(&buf[..n]).to_string()); + let _ = sock.write_all(response.as_bytes()).await; + }); + port +} + +/// `HTTP/1.1 500 Internal Server Error` with an empty body — what Cuprate +/// answers for a height above its tip. +const CUPRATE_OUT_OF_RANGE: &str = + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + +/// monerod's answer to the same request: HTTP 200 with an epee/JSON-RPC error +/// object, `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` = -2 +/// (`src/rpc/core_rpc_server_error_codes.h`). +fn monerod_too_big_height() -> String { + http_200_body(&rpc_error( + -2, + "Requested block height: 3300000 greater than current top block height: 23758", + )) +} + +fn daemon_addr(port: u16) -> String { + format!("127.0.0.1:{port}") +} + +#[tokio::test] +async fn out_of_range_get_block_is_a_typed_height_error() { + let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await; + let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5)) + .await + .expect_err("an out-of-range height must not decode"); + assert_eq!( + err, + WalletError::DaemonHeightOutOfRange, + "a bare 500 on a height-addressed call is the Cuprate spelling of TOO_BIG_HEIGHT" + ); +} + +#[tokio::test] +async fn out_of_range_get_height_is_the_same_typed_error() { + let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await; + let err = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5)) + .await + .expect_err("a 500 must not decode"); + assert_eq!(err, WalletError::DaemonHeightOutOfRange); +} + +#[tokio::test] +async fn monerod_too_big_height_object_is_the_same_typed_error() { + let port = serve_raw(monerod_too_big_height()).await; + let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5)) + .await + .expect_err("code -2 must map to the height error"); + assert_eq!( + err, + WalletError::DaemonHeightOutOfRange, + "parity: monerod's -2 and Cuprate's bare 500 are the same failure" + ); +} + +#[tokio::test] +async fn a_5xx_that_is_not_height_addressed_is_a_status_error() { + let port = serve_raw( + "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + .to_string(), + ) + .await; + let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5)) + .await + .expect_err("503 is not a chain answer"); + assert_eq!(err, WalletError::DaemonHttpStatus(503)); +} + +#[tokio::test] +async fn get_height_uses_the_uri_endpoint_and_cuprates_top_level_shape() { + // Evidence `GET__get_height.json`: no jsonrpc envelope, no `result`. + let body = r#"{"status":"OK","untrusted":false,"hash":"7458280ccc2befbbb074f50b37195ed13039178a05fd8816fc8f8a64fb4df417","height":23758}"#; + let log = Arc::new(Mutex::new(Vec::new())); + let port = serve_raw_logged(http_200_body(body), Arc::clone(&log)).await; + let height = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5)) + .await + .expect("the URI endpoint answers"); + assert_eq!(height, 23_758); + let req = log + .lock() + .expect("log") + .first() + .cloned() + .unwrap_or_default(); + assert!( + req.starts_with("GET /get_height "), + "Cuprate rejects get_height over /json_rpc (422); the URI endpoint is the one that works: {req}" + ); +} + +#[tokio::test] +async fn get_info_reads_height_and_target_only() { + // Evidence `get_info.endpoint.post_sync.json`, mid-sync: height below + // target, zero peers, `free_space` u64::MAX. + let body = r#"{"jsonrpc":"2.0","id":"0","result":{"status":"OK","height":23758,"target_height":3090939,"synchronized":false,"database_size":54852877,"free_space":18446744073709551615,"incoming_connections_count":0,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#; + let port = serve_raw(http_200_body(body)).await; + let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5)) + .await + .expect("a syncing daemon answers"); + assert_eq!( + info, + DaemonInfo { + height: 23_758, + target_height: 3_090_939 + } + ); +} + +#[tokio::test] +async fn cuprate_placeholder_metrics_never_change_what_the_client_reports() { + // The same height from both servers: the restricted payload carries a 5 GiB + // `database_size`, an empty `version`, zero peers and u64::MAX `free_space`. + // None of it may reach the client, because none of it is a measurement. + let unrestricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0,"synchronized":true,"database_size":1770926,"free_space":18446744073709551615,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#; + let restricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"height_without_bootstrap":0,"target_height":0,"synchronized":true,"restricted":true,"database_size":5368709120,"free_space":18446744073709551615,"outgoing_connections_count":0,"incoming_connections_count":0,"version":""}}"#; + let a = serve_raw(http_200_body(unrestricted)).await; + let b = serve_raw(http_200_body(restricted)).await; + let one = wallet::daemon_get_info(&daemon_addr(a), Duration::from_secs(5)) + .await + .unwrap(); + let two = wallet::daemon_get_info(&daemon_addr(b), Duration::from_secs(5)) + .await + .unwrap(); + assert_eq!( + one, two, + "placeholder metrics must not influence the report" + ); + assert_eq!( + one, + DaemonInfo { + height: 1160, + target_height: 0 + } + ); +} + +#[tokio::test] +async fn chunked_daemon_answers_are_dechunked() { + // axum/hyper (Cuprate) answers with `Transfer-Encoding: chunked`; the body + // arrives framing-wrapped, so brace-scanning alone is not a parse. + let json = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0}}"#; + let (head, tail) = json.split_at(json.len() / 2); + let chunked = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{head}\r\n{:x}\r\n{tail}\r\n0\r\n\r\n", + head.len(), + tail.len() + ); + let port = serve_raw(chunked).await; + let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5)) + .await + .expect("a chunked answer must parse"); + assert_eq!(info.height, 1160); +} + +#[tokio::test] +async fn a_dead_daemon_is_a_transport_error_that_names_the_address() { + let port = freed_loopback_port(); + let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(2)) + .await + .expect_err("a closed port must not answer"); + assert!( + err.to_string().contains(&daemon_addr(port)), + "the reason must name the address: {err}" + ); +} + +#[tokio::test] +async fn a_transport_failure_is_not_a_height_error() { + let port = freed_loopback_port(); + let err = wallet::daemon_get_block(&daemon_addr(port), 1, Duration::from_secs(2)) + .await + .expect_err("a closed port must not answer"); + assert!(!err.is_height_out_of_range(), "{err}"); +} + +#[test] +fn only_the_height_error_reports_itself_as_one() { + assert!(WalletError::DaemonHeightOutOfRange.is_height_out_of_range()); + assert!(!WalletError::DaemonHttpStatus(500).is_height_out_of_range()); + assert!( + !WalletError::DaemonRpc { + code: -1, + message: "Invalid parameter".into() + } + .is_height_out_of_range() + ); +}