From 86e20223cf87edc8b7a0e228499821df604a5263 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Fri, 18 Sep 2026 22:55:23 -0400 Subject: [PATCH 01/94] node: expose peer payment history as Node::list_payments Store::list_payments existed but only the node's own tests called it, so the signed /pay invoices and /tip receipts a peer sent were unreachable from the app. Add the thinnest read-only accessor next to list_messages/friend_profile: lock the store, map the error to String, no new state, no new schema, no dial. Payment rows come back as stored; a renderer sanitizes memo with sanitize::display_text at draw time, the same way it does for message bodies. --- src/node.rs | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/src/node.rs b/src/node.rs index 1bea43d..5e2f18f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -28,7 +28,7 @@ use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; -use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store}; +use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; @@ -500,6 +500,23 @@ impl Node { .map_err(|e| e.to_string()) } + /// The signed `/pay` invoices and `/tip` receipts that came from one peer, + /// oldest row first. A friend with no payment rows is an empty vector, not + /// an error. + /// + /// Read-only and fail-closed: it locks the store and nothing else — no Tor + /// dial, no wallet RPC. `memo` is the text the peer signed, stored and + /// returned as it arrived; a renderer sanitizes it with + /// [`crate::sanitize::display_text`] at draw time, exactly as the chat + /// bodies from [`Self::list_messages`] are. + pub fn list_payments(&self, friend_pk: &[u8]) -> Result, String> { + self.store + .lock() + .map_err(|e| e.to_string())? + .list_payments(friend_pk) + .map_err(|e| e.to_string()) + } + /// The live wallet, cloned out of its lock. Every wallet call goes through /// this so a `std::sync::Mutex` guard never lives across an `.await`, and so /// the F7 screen can re-point the wallet mid-session. @@ -2314,6 +2331,70 @@ mod tests { assert_eq!(rows[0].kind, "tip"); } + /// The peer payment history the TUI needs: `Store::list_payments` existed but + /// nothing on `Node` reached it, so the signed invoice/receipt frames a peer + /// sent were invisible to the app. One row per stored frame, oldest first, + /// and a friend with no rows is an empty vector, not an error. + #[tokio::test] + async fn list_payments_round_trips_a_peers_invoice_and_receipt() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + let stranger = Keys::generate(); + let addr = xmr_addr(); + befriend( + &node.store.lock().unwrap(), + &peer.identity_pk, + &peer.prekey_pk, + "peer.onion", + ); + { + let store = node.store.lock().unwrap(); + store + .insert_payment( + &peer.identity_pk, + PaymentWrite { + dir: "in", + kind: "invoice", + amount_atomic: "500000000000", + address: &addr, + memo: "rent", + txid: None, + verified: false, + }, + ) + .expect("store inbound invoice"); + store + .insert_payment( + &peer.identity_pk, + PaymentWrite { + dir: "in", + kind: "receipt", + amount_atomic: "250000000000", + address: &addr, + memo: "", + txid: Some("deadbeef"), + verified: false, + }, + ) + .expect("store inbound receipt"); + } + + let rows = node.list_payments(&peer.identity_pk).expect("payments"); + assert_eq!(rows.len(), 2, "one row per stored frame"); + assert_eq!(rows[0].kind, "invoice", "oldest row first"); + assert_eq!(rows[0].dir, "in"); + assert_eq!(rows[0].amount_atomic, "500000000000"); + assert_eq!(rows[0].memo, "rent"); + assert_eq!(rows[1].kind, "receipt"); + assert_eq!(rows[1].txid.as_deref(), Some("deadbeef")); + + let none = node + .list_payments(&stranger.identity_pk) + .expect("a friend with no rows is an empty vector, not an error"); + assert!(none.is_empty()); + } + /// A stand-in for `monero-wallet-rpc`: it records its argv, then does what /// the test needs. The wallet child spawns a real process, so this is the /// only honest way to drive the start path offline. From eefa7e5cc6ac5d50eb0c0d3950e2560b8d166a05 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 18 Sep 2026 23:13:12 -0400 Subject: [PATCH 02/94] tui: clean-look chrome redesign (one accent, honest tor phase, real frames) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Applies the bitchat-tui clean-look principles to the OnionWire main screen. - Hierarchy: header, roster + one primary chat pane, one status line, one footer hint line. The header gives up the accent (the accent is reserved for focus), so it stops competing with the panes. - Tor phase is a first-class state: Node::tor_state() -> TorPhase (glyph + word, header and footer) so connecting / ready / degraded / off are never colour-only and never implied. No new data field. - Footer changes with the focused pane (pane_footer_hints) and the phase; the main footer drops the redundant onion (the header already prints it) and uses those cells for hints. status_footer keeps its signature and strings. - Empty roster / empty chat / connecting / degraded / off are designed states with their own copy, not blank panes. - draw_main_chrome + MainView: the real main render path is public and Node-free, so tests/tui_frames.rs dumps the actual chrome at 80x24, 120x40 and 200x60 (12 tests, 5 states, real Message/OutboxEntry rows) instead of a reconstructed stand-in. - Widths in cells everywhere touched: status_footer*, alert_line, main_header_line*, draw_text_overlay, roster_row_text. The roster spends its budget name-first, so a 22-cell pane reads `bob-the-sta… stale` instead of `… bbbbbbbb… stale`. - draw_text_overlay is centered with a one-cell side margin and clears underneath; never full-bleed. Also fixes a pre-existing race in tests/tui_spec.rs (the ellipsis-form assertion did not tolerate ONIONWIRE_ASCII being set by a parallel test). Co-Authored-By: Hermes --- docs/TUI.md | 127 ++++++- src/tui.rs | 759 ++++++++++++++++++++++++++++++----------- tests/tui_chrome.rs | 102 +++++- tests/tui_frames.rs | 815 ++++++++++++++++++++++++++++++-------------- tests/tui_spec.rs | 20 +- 5 files changed, 1348 insertions(+), 475 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index e83efa3..89af4a0 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -19,7 +19,7 @@ construct that. | Screen / state | What you get | Why | |---|---|---| -| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** — same `Layout` constraints as `src/tui.rs` `draw_main` (banner height, 36% roster, composer 3, footer 1) plus the real `banner_for_width` / `status_footer` | `App` private | +| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** at the time of the audit; since the clean-look redesign (`draw_main_chrome`) it is **REAL** — see “Clean-look chrome redesign” below | `App` private | | Help / `/who` overlay | **RECONSTRUCTED** — Rect math copied from private `draw_text_overlay` | private | | Share / invite | **REAL** `draw_share` | public | | Profile, paste, approve, rotate, wipe, quit, backup, restore, passphrase | **RECONSTRUCTED** — public `*_screen_text` / `ProfileEditor` copy inside `Block::bordered`, titles taken from `src/tui.rs` | private `draw_*` | @@ -704,3 +704,128 @@ sibling-card work, not presentation: - `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and probed, not edited. - `Node::set_petname(..)` — no petname editor exists. + +## Clean-look chrome redesign — implemented + +The main screen was restructured around one accent, one primary pane and honest +states. The render path is no longer reconstructed in the dump: `App::draw_main` +builds a `MainView` of plain data and hands it to the public `draw_main_chrome`, +which is exactly what `tests/tui_frames.rs` draws. There is no stand-in layout, +so a frame dump is the real screen. + +``` +cargo test --locked --test tui_frames -- --nocapture dump_audit_frames +``` + +dumps every state below at 80x24, 120x40 and 200x60. + +### Hierarchy + +| Row | Content | Style | +|---|---|---| +| 0 | `onionwire {glyph} tor {phase} me:{fp8} onion:{onion8}` | app name bold text, phase semantic, identity muted | +| 1 | the alert (`send failed: …`, `fingerprint mismatch`) — only when set | alert | +| 2..h-4 | roster (22 cells at 80, 28 at 120+) next to the chat transcript | roster rows text/stale, focus marker on the focused pane | +| h-3..h-1 | composer, **no frame**, 3-row slot for wrapped input | `> ` marker + bold when focused, `message` muted when empty | +| h-1 | `{note} {glyph} TOR {phase} me:{fp8} {pane hints} ? help` | muted; phase semantic | + +The header no longer takes the accent — the accent is reserved for focus, which +is what let the header stop competing with the panes. + +### Tor phase is a first-class state + +`Node::tor_state()` was already cheap, read-only and unused by the TUI. It now +feeds `TorPhase` (one word + one glyph, both in the header and the footer), so +"connected" is never implied: + +| `hs::TorState` | `TorPhase` | glyph / ASCII | word | tone | +|---|---|---|---|---| +| `Bootstrapping` | `Connecting` | `…` / `...` | `connecting` | muted | +| `Published` | `Ready` | `✓` / `ok` | `ready` | text | +| `DegradedReachable` | `Degraded` | `!` | `degraded` | stale | +| `Stopped` | `Off` | `x` | `off` | alert | + +No new data field was needed: `App` already holds `Arc`, and this is a +read-only getter, not a store read from the render path. + +### States + +``` +onionwire ✓ tor ready me:abcdef01 onion:abcdefgh +┌roster 2 1 stale───┐┌> chat alice───────────────────────────────────────────┐ +│> alice aaaaaaaa… ││you: ping ✓ │ +│ bob-the-sta… stale││them: pong │ +│ ││them: 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 │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +✓ TOR ready me:abcdef01… j k scroll g G ends F4 rotate F9 settings ? help +``` + +``` +onionwire … tor connecting me:abcdef01 onion:abcdefgh +┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ +│no friends ││no friends yet │ +│F3 adds one ││F3 paste an invite to add one │ +│ ││tor connecting — first publish takes a few minutes │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +… TOR connecting me:abcdef01… j k select F3 add F6 wallet F9 settings ? help +``` + +``` +onionwire x tor off me:abcdef01 onion:unset +fingerprint mismatch +┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ +│no friends ││no friends yet │ +│F3 adds one ││F3 paste an invite to add one │ +│ ││tor off — no onion service is running │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +x TOR off me:abcdef01… j k select F3 add F6 wallet F9 settings ? help +``` + +The error state puts the fail-closed sentence on the alert row **once**; the +footer keeps the phase and the hints instead of repeating it. The outbox note +(`peer unreachable, queued (1/8, retry 45s)`) still outranks the hints when a +row is outstanding. + +### Footer variants + +| Helper | Identity | Used by | +|---|---|---| +| `status_footer(w, fp, onion, note, hints)` | `TOR`, `onion:` | locked chrome tests and every non-main screen | +| `status_footer_phased(w, fp, onion, phase, note, hints)` | `{glyph} TOR {word}`, `onion:` | F9 menu | +| `status_footer_compact(w, fp, phase, note, hints)` | `{glyph} TOR {word}` only | main (its header already carries `me:` and `onion:`) | + +The main footer drops the onion because the header one line above already prints +it; those cells go to the hints. `TOR`, `me:` and `? help` survive at 80, 120 +and 200 in every variant — `tests/tui_chrome.rs` asserts it. + +`pane_footer_hints(Pane)` changes the hint cluster with the focused pane +(roster / chat / composer) and every variant keeps `F9` and `? help`, so the +menu stays discoverable and the overlay stays reachable wherever the cursor is. + +### Levers from the reference (applied / skipped) + +Applied: one accent for focus (focused border, selected row, active-conversation +marker); focus as marker + weight (`> ` plus bold title, visible with colour +stripped); border weight = focus; one unframed muted footer that follows the +pane and the phase; designed empty / connecting / degraded / off states; +semantic colour only; outbox and stale state as marker + word. + +Skipped: the 3-line wordmark above the header at height ≥ 40 (fights the 1-line +header without buying hierarchy); bottom-anchoring the composer inside its +3-row slot (needs cell-accurate wrap prediction for no legibility gain); +per-row colour in the roster (name and fingerprint share one style so a narrow +pane can drop the fingerprint without changing the row's meaning). + +### Width + +`status_footer*`, `alert_line`, `main_header_line*`, `draw_text_overlay`, +`roster_row_text` and `fit_cells` all measure cells (`Span::width`), never +`chars().count()`. The roster row spends its budget on the name first, then the +`stale` word, then whatever is left on a fingerprint prefix — a 22-cell pane +reads `bob-the-sta… stale`, not `… bbbbbbbb… stale`. diff --git a/src/tui.rs b/src/tui.rs index 10761d8..42e75bb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -12,6 +12,7 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra use ratatui::{DefaultTerminal, Frame}; use zeroize::{Zeroize, Zeroizing}; +use crate::hs::TorState; use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; @@ -49,12 +50,15 @@ fn ellipsis() -> &'static str { } /// Truncate or keep an alert so it cannot spill into the roster row. +/// +/// Cells, not chars: the message can carry a peer-supplied transport error, and +/// a CJK/emoji byte there must not push the alert into the next pane. pub fn alert_line(msg: &str, width: u16) -> String { let mut text = msg.to_string(); if color_mode() == ColorMode::None && !text.starts_with("! ") { text = format!("! {text}"); } - truncate_chars(&text, width as usize) + fit_cells(&text, width as usize) } /// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. @@ -172,7 +176,7 @@ pub fn short_send_reason(why: &str, budget: usize) -> String { let clean = sanitize::display_text(why.as_bytes()); let tail = clean.rsplit(": ").next().unwrap_or("").trim(); let text = if tail.is_empty() { clean.trim() } else { tail }; - truncate_chars(text, budget) + fit_cells(text, budget) } /// One row's delivery marker, straight from the outbox state. @@ -340,19 +344,6 @@ fn char_len(s: &str) -> usize { s.chars().count() } -fn truncate_chars(s: &str, max: usize) -> String { - if char_len(s) <= max { - return s.to_string(); - } - let e = ellipsis(); - let el = char_len(e); - if max <= el { - return e.chars().take(max).collect(); - } - let head: String = s.chars().take(max - el).collect(); - format!("{head}{e}") -} - /// Terminal colour capability, detected from the environment. /// /// `ColorMode::None` means “strip all colour” (e.g. `NO_COLOR`); the TUI then @@ -606,14 +597,67 @@ pub fn banner_for_width(width: u16) -> &'static str { /// One-line main-screen header. Do not use `banner_for_width(80)` here — that stays the wordmark. pub fn main_header_line(width: u16, me_fp: &str, me_onion: &str) -> String { + main_header_line_phased(width, me_fp, me_onion, None) +} + +/// One-line main-screen header carrying the Tor phase. `None` keeps the +/// historic string; `Some` puts the phase word and glyph between the app name +/// and the identity. +pub fn main_header_line_phased( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, +) -> String { + fit_cells(&header_plain(me_fp, me_onion, phase), width as usize) +} + +/// The header text without a width: one place builds the string, so the styled +/// spans and the plain helper can never drift apart. +fn header_plain(me_fp: &str, me_onion: &str, phase: Option) -> String { let fp: String = me_fp.chars().take(8).collect(); let onion = if me_onion.is_empty() { "unset".to_string() } else { me_onion.chars().take(8).collect() }; - let line = format!("onionwire tor me:{fp} onion:{onion}"); - truncate_chars(&line, width as usize) + let tor = match phase { + None => "tor".to_string(), + Some(p) => format!("{} tor {}", p.glyph(), p.word()), + }; + format!("onionwire {tor} me:{fp} onion:{onion}") +} + +/// The header as spans. The app name is plain text (not accent — the accent is +/// reserved for focus), the identity is muted, and only the phase carries a +/// semantic colour. Too narrow to lay out in parts, the line degrades to one +/// truncated muted span rather than clipping mid-field. +pub fn main_header_spans( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, +) -> Vec> { + let plain = header_plain(me_fp, me_onion, phase); + if cell_width(&plain) > width as usize { + return vec![Span::raw(fit_cells(&plain, width as usize)).style(style_dim())]; + } + let fp: String = me_fp.chars().take(8).collect(); + let onion = if me_onion.is_empty() { + "unset".to_string() + } else { + me_onion.chars().take(8).collect() + }; + let (tor_text, tor_style) = match phase { + None => ("tor".to_string(), style_dim()), + Some(p) => (format!("{} tor {}", p.glyph(), p.word()), p.style()), + }; + vec![ + Span::raw("onionwire").style(style_text().add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::raw(tor_text).style(tor_style), + Span::raw(format!(" me:{fp} onion:{onion}")).style(style_dim()), + ] } /// Roster column in cells: 22 at 80-wide, 28 at 120+. @@ -2380,11 +2424,12 @@ impl App { Screen::WalletsSettings { state } => { // The one status line the screen carries: same `status_footer` // shape as Main, so TOR / identity / the copy confirmation read - // in the same place on every screen. - let footer = status_footer( + // in the same place on every screen — including the phase. + let footer = status_footer_phased( f.area().width, &self.me_fp, &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), self.status_note.as_deref(), footer_hints(&self.screen), ); @@ -2399,70 +2444,9 @@ impl App { } fn draw_main(&self, f: &mut Frame) { - let area = f.area(); - let header = main_header_line(area.width, &self.me_fp, &self.me_onion); - let alert_h = u16::from(self.alert.is_some()); - let cols = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(alert_h), - Constraint::Min(3), - Constraint::Length(3), - Constraint::Length(1), - ]) - .split(area); - - f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); - if let Some(msg) = &self.alert { - let text = alert_line(msg, area.width); - f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); - } - - let roster_w = roster_col_width(area.width).min(cols[2].width.saturating_sub(10)); - let panes = - Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[2]); - let inner_roster = panes[0].width.saturating_sub(2); - - let stale_n = self.friends.iter().filter(|fr| !fr.last_connect_ok).count(); - let roster_title = if stale_n > 0 { - format!("roster {} {stale_n} stale", self.friends.len()) - } else { - format!("roster {}", self.friends.len()) - }; - - let items: Vec = if self.friends.is_empty() { - vec![ListItem::new("no friends").style(style_dim())] - } else { - self.friends - .iter() - .map(|friend| { - let raw = friend.petname.as_deref().unwrap_or(&friend.fingerprint); - let name = sanitize::display_text(raw.as_bytes()); - let line = roster_row_text( - &name, - &friend.fingerprint, - !friend.last_connect_ok, - inner_roster, - ); - let style = if friend.last_connect_ok { - style_text() - } else { - style_stale() - }; - ListItem::new(line).style(style) - }) - .collect() - }; - let roster = List::new(items) - .highlight_style(style_highlight()) - .highlight_symbol("> ") - .block(self.pane_block(&roster_title, Pane::Roster)); - let mut roster_state = ListState::default(); - if !self.friends.is_empty() { - roster_state.select(Some(self.selected)); - } - f.render_stateful_widget(roster, panes[0], &mut roster_state); - - let (chat_lines, summary) = self.chat_view(); + let phase = Some(TorPhase::of(self.node.tor_state())); + let (chat_lines, summary, chat_style) = self.chat_view(phase); + let rows: Vec = self.friends.iter().map(friend_row).collect(); let chat_name = self.friends.get(self.selected).map(|friend| { friend .petname @@ -2470,80 +2454,210 @@ impl App { .unwrap_or(&friend.fingerprint) .to_string() }); - draw_chat( - f, - panes[1], - &chat_lines, - chat_name.as_deref(), - self.focus == Pane::Chat, - self.chat_scroll, - ); - - let mark = if self.focus == Pane::Composer { - "> " - } else { - " " - }; - let (cmd, cmd_style) = if self.composer.is_empty() { - (format!("{mark}message"), style_dim()) - } else { - let style = if self.focus == Pane::Composer { - style_text().add_modifier(Modifier::BOLD) - } else { - style_text() - }; - (format!("{mark}{}", self.composer), style) - }; - f.render_widget( - Paragraph::new(cmd) - .style(cmd_style) - .wrap(Wrap { trim: false }), - cols[3], - ); - - let footer = self.footer_line(area.width, &summary); - f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); - } - - fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String { // The outbox is the source of truth while anything is outstanding; the // transient note still covers "sending", "sent file x", "invoice sent". - let note = summary.note().or_else(|| self.status_note.clone()); - status_footer( - width, - &self.me_fp, - &self.me_onion, - note.as_deref(), - footer_hints(&self.screen), - ) + let mut note = summary.note().or_else(|| self.status_note.clone()); + // The alert row above the panes is the error channel. When it already + // carries the same sentence, drop it from the footer: one statement of a + // failure, in the place the eye goes for errors. + if note.as_deref() == self.alert.as_deref() { + note = None; + } + let view = MainView { + me_fp: &self.me_fp, + me_onion: &self.me_onion, + phase, + friends: &rows, + selected: self.selected, + focus: self.focus, + chat_lines: &chat_lines, + chat_style, + chat_name: chat_name.as_deref(), + chat_scroll: self.chat_scroll, + composer: &self.composer, + alert: self.alert.as_deref(), + note: note.as_deref(), + }; + draw_main_chrome(f, &view); } - fn chat_view(&self) -> (Vec, OutboxSummary) { + /// Transcript, outbox summary, and how the rows should be styled. State copy + /// is flagged here — the render path never guesses from the text. + fn chat_view(&self, phase: Option) -> (Vec, OutboxSummary, ChatRowStyle) { let Some(friend) = self.friends.get(self.selected) else { return ( - vec![ - "no friends yet".into(), - "F3 paste an invite to add one".into(), - ], + chat_no_friends_lines(phase), OutboxSummary::default(), + ChatRowStyle::State, ); }; match self.node.list_messages(&friend.pubkey) { Ok(msgs) => { let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default(); - chat_with_delivery(&msgs, &pending, unix_now_secs()) + let (lines, summary) = chat_with_delivery(&msgs, &pending, unix_now_secs()); + let style = if msgs.is_empty() { + ChatRowStyle::State + } else { + ChatRowStyle::Text + }; + (lines, summary, style) } - Err(e) => (vec![e], OutboxSummary::default()), + Err(e) => (vec![e], OutboxSummary::default(), ChatRowStyle::Error), } } - - fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> { - pane_block_for(title, self.focus == pane) - } } -/// Pane chrome without an `App`: focus is accent border + bold title, never -/// color alone (the `> ` marks come from the callers). +/// One roster row: the label, the fingerprint, and the word `stale` when the +/// last dial did not answer. Colour is what the row is (text vs stale), never a +/// decoration — the word carries the state on a monochrome terminal. +pub fn roster_line(row: &FriendRow, inner_width: u16) -> Line<'static> { + let text = roster_row_text(row, inner_width); + let style = if row.stale { style_stale() } else { style_text() }; + Line::from(Span::raw(text).style(style)) +} + +/// How one chat row is styled. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ChatRowStyle { + /// Transcript rows: our own messages and the peer's. + Text, + /// Empty / loading copy that stands in for a transcript. + State, + /// The pane could not read the transcript at all. + Error, +} + +/// The main screen: one header line, one primary pane, one status line, one +/// footer hint line. +/// +/// Every field is plain data, so the render path has no `Node` in it and +/// `tests/tui_frames.rs` dumps the real chrome at 80x24, 120x40 and 200x60. +pub struct MainView<'a> { + pub me_fp: &'a str, + pub me_onion: &'a str, + /// Tor phase, or `None` to keep the phase-free `TOR` token. + pub phase: Option, + pub friends: &'a [FriendRow], + pub selected: usize, + /// Which pane owns the keyboard. Drives the marker, the bold title, the + /// accented border, and the footer hints. + pub focus: Pane, + pub chat_lines: &'a [String], + pub chat_style: ChatRowStyle, + pub chat_name: Option<&'a str>, + pub chat_scroll: u16, + pub composer: &'a str, + /// Fail-closed one-liner: `send failed: …`, `fingerprint mismatch`, or a + /// validation message. Rendered above the panes, never truncated mid-word. + pub alert: Option<&'a str>, + /// Footer note: outbox summary or the last status message. + pub note: Option<&'a str>, +} + +/// Draw the main screen. The only chrome that reads colour is `pane_block_for` +/// (focus), `roster_line` (state), and the header's phase token. +pub fn draw_main_chrome(f: &mut Frame, view: &MainView<'_>) { + let area = f.area(); + let alert_h = u16::from(view.alert.is_some()); + let cols = Layout::vertical([ + Constraint::Length(1), + Constraint::Length(alert_h), + Constraint::Min(3), + Constraint::Length(3), + Constraint::Length(1), + ]) + .split(area); + + f.render_widget( + Paragraph::new(Line::from(main_header_spans( + area.width, + view.me_fp, + view.me_onion, + view.phase, + ))), + cols[0], + ); + if let Some(msg) = view.alert { + let text = alert_line(msg, area.width); + f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); + } + + let roster_w = roster_col_width(area.width).min(cols[2].width.saturating_sub(10)); + let panes = + Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[2]); + let inner_roster = panes[0].width.saturating_sub(2); + + let stale_n = view.friends.iter().filter(|fr| fr.stale).count(); + let roster_title = if view.friends.is_empty() { + "roster 0".to_string() + } else if stale_n > 0 { + format!("roster {} {stale_n} stale", view.friends.len()) + } else { + format!("roster {}", view.friends.len()) + }; + + let items: Vec = if view.friends.is_empty() { + empty_roster_lines() + .iter() + .map(|l| ListItem::new(*l).style(style_dim())) + .collect() + } else { + view.friends + .iter() + .map(|row| ListItem::new(roster_line(row, inner_roster))) + .collect() + }; + let roster = List::new(items) + .highlight_style(style_highlight()) + .highlight_symbol("> ") + .block(pane_block_for(&roster_title, view.focus == Pane::Roster)); + let mut roster_state = ListState::default(); + if !view.friends.is_empty() { + roster_state.select(Some(view.selected)); + } + f.render_stateful_widget(roster, panes[0], &mut roster_state); + + let chat = chat_lines_for(view.chat_lines, view.chat_style); + draw_chat_lines( + f, + panes[1], + &chat, + view.chat_name, + view.focus == Pane::Chat, + view.chat_scroll, + ); + + // Composer: no frame. `> ` plus bold while it owns the keyboard, `message` + // as a muted placeholder when it is empty. The 3-row slot stays so a + // wrapped line is not clipped. + let focused = view.focus == Pane::Composer; + let mark = if focused { "> " } else { " " }; + let (cmd, cmd_style) = if view.composer.is_empty() { + (format!("{mark}message"), style_dim()) + } else if focused { + ( + format!("{mark}{}", view.composer), + style_text().add_modifier(Modifier::BOLD), + ) + } else { + (format!("{mark}{}", view.composer), style_text()) + }; + f.render_widget( + Paragraph::new(cmd) + .style(cmd_style) + .wrap(Wrap { trim: false }), + cols[3], + ); + + let footer = status_footer_compact( + area.width, + view.me_fp, + view.phase, + view.note, + pane_footer_hints(view.focus), + ); + f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); +} fn pane_block_for(title: &str, focused: bool) -> Block<'_> { let border = if focused { style_accent() @@ -2577,6 +2691,35 @@ pub fn draw_chat( name: Option<&str>, focused: bool, scroll: u16, +) { + let styled = chat_lines_for(lines, ChatRowStyle::Text); + draw_chat_lines(f, area, &styled, name, focused, scroll); +} + +/// Transcript rows, styled. The style is a caller decision, never inferred from +/// the text: a peer message body must not be able to pick its own colour by +/// starting with the word `no`. +pub fn chat_lines_for(lines: &[String], style: ChatRowStyle) -> Vec> { + let style = match style { + ChatRowStyle::Text => style_text(), + ChatRowStyle::State => style_dim(), + ChatRowStyle::Error => style_alert(), + }; + lines + .iter() + .map(|l| Line::from(Span::raw(l.clone()).style(style))) + .collect() +} + +/// The chat pane itself. Same renderer for transcript rows and state copy; the +/// only difference is the style the caller baked into each `Line`. +pub fn draw_chat_lines( + f: &mut Frame, + area: Rect, + lines: &[Line<'static>], + name: Option<&str>, + focused: bool, + scroll: u16, ) { let inner_h = area.height.saturating_sub(2); let nlines = lines.len(); @@ -2594,8 +2737,7 @@ pub fn draw_chat( let mark = if focused { "> " } else { " " }; let title = format!("{mark}{title}"); f.render_widget( - Paragraph::new(lines.join("\n")) - .style(style_text()) + Paragraph::new(lines.to_vec()) .wrap(Wrap { trim: false }) .scroll((scroll, 0)) .block(pane_block_for(&title, focused)), @@ -2603,18 +2745,199 @@ pub fn draw_chat( ); } +/// Chat-pane copy when no friend is selected. States after the base two rows +/// say which phase the node is actually in, so an empty roster during first +/// publish does not read as a broken app. +pub fn chat_no_friends_lines(phase: Option) -> Vec { + let mut lines = vec![ + "no friends yet".to_string(), + "F3 paste an invite to add one".to_string(), + ]; + let state = match phase { + None => None, + Some(TorPhase::Connecting) => { + Some("tor connecting — first publish takes a few minutes") + } + Some(TorPhase::Degraded) => Some("tor degraded — reachable, still settling"), + Some(TorPhase::Off) => Some("tor off — no onion service is running"), + Some(TorPhase::Ready) => None, + }; + if let Some(note) = state { + lines.push(String::new()); + lines.push(note.to_string()); + } + lines +} + +/// Roster-pane copy when the friend list is empty. Two rows, so the pane reads +/// as an empty state instead of a blank box. +pub fn empty_roster_lines() -> [&'static str; 2] { + ["no friends", "F3 adds one"] +} + +/// One friend, as the roster draws it. +/// +/// Built by `App` from `store::Friend`; the render path never touches the store +/// type, which is what lets `tests/tui_frames.rs` draw the real chrome. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FriendRow { + /// Display name: petname when set, fingerprint otherwise, already sanitized. + pub label: String, + /// Full fingerprint hex; the row fits it to the pane. + pub fingerprint: String, + /// Last dial to this peer's onion did not answer. + pub stale: bool, +} + +/// The roster row for one friend, fitted to the pane's inner width in cells. +pub fn friend_row(friend: &Friend) -> FriendRow { + let raw = friend.petname.as_deref().unwrap_or(&friend.fingerprint); + FriendRow { + label: sanitize::display_text(raw.as_bytes()).to_string(), + fingerprint: friend.fingerprint.clone(), + stale: !friend.last_connect_ok, + } +} + +/// Tor lifecycle as the chrome shows it: one word plus one glyph, so the phase +/// survives `NO_COLOR`, a 16-colour terminal, and a monochrome dump. +/// +/// Read from `Node::tor_state()`. `Connecting` is the long first publish (HsDir +/// descriptor upload), `Ready` is a published descriptor, `Degraded` is +/// reachable while Arti still reports the service broken — usable, and not the +/// same statement as ready — and `Off` is a stopped node. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TorPhase { + Connecting, + Ready, + Degraded, + Off, +} + +impl TorPhase { + /// Project `hs::TorState`. This is the only place that knows the mapping. + pub fn of(state: TorState) -> Self { + match state { + TorState::Published => Self::Ready, + TorState::DegradedReachable => Self::Degraded, + TorState::Stopped => Self::Off, + TorState::Bootstrapping => Self::Connecting, + } + } + + /// The word a reader sees. Never abbreviated: `ok`/`up` would be ambiguous + /// with the delivery markers. + pub fn word(self) -> &'static str { + match self { + Self::Connecting => "connecting", + Self::Ready => "ready", + Self::Degraded => "degraded", + Self::Off => "off", + } + } + + /// Marker glyph, paired with [`Self::word`]. ASCII chrome falls back to + /// `...` / `ok` rather than dropping the marker. + pub fn glyph(self) -> &'static str { + let ascii = ascii_chrome(); + match self { + Self::Connecting => { + if ascii { + "..." + } else { + "…" + } + } + Self::Ready => { + if ascii { + "ok" + } else { + "✓" + } + } + Self::Degraded => "!", + Self::Off => "x", + } + } + + /// Semantic style: colour answers "what is this", never "what mood". + /// Ready is the unremarkable state, so it takes the plain text token. + pub fn style(self) -> Style { + match self { + Self::Connecting => style_dim(), + Self::Ready => style_text(), + Self::Degraded => style_stale(), + Self::Off => style_alert(), + } + } +} + +/// The footer's `TOR` cluster. `None` keeps the bare `TOR` the chrome tests +/// lock; `Some` adds the phase glyph and word. +pub fn tor_token(phase: Option) -> String { + match phase { + None => "TOR".to_string(), + Some(p) => format!("{} TOR {}", p.glyph(), p.word()), + } +} + /// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`. +/// +/// Phase-free twin of [`status_footer_phased`], kept because the chrome tests +/// and the reconstructed dumps call it directly. pub fn status_footer( width: u16, me_fp: &str, me_onion: &str, status_note: Option<&str>, hints: &str, +) -> String { + status_footer_phased(width, me_fp, me_onion, None, status_note, hints) +} + +/// Status bar with the Tor phase folded into the `TOR` cluster. +/// +/// Every width here is in terminal **cells** (`fit_cells` / `cell_width`), not +/// `chars().count()`: the phase glyph and any peer-supplied note text must not +/// be able to push the line past the frame. +pub fn status_footer_phased( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, + status_note: Option<&str>, + hints: &str, +) -> String { + status_footer_inner(width, me_fp, Some(me_onion), phase, status_note, hints) +} + +/// Footer for a screen whose header already prints the identity. +/// +/// The main screen's header carries `me:` and `onion:`, so repeating the onion +/// in the footer costs 20+ cells and buys nothing; those cells go to the hints +/// instead. `TOR` and `me:` stay — `tests/tui_chrome.rs` locks both. +pub fn status_footer_compact( + width: u16, + me_fp: &str, + phase: Option, + status_note: Option<&str>, + hints: &str, +) -> String { + status_footer_inner(width, me_fp, None, phase, status_note, hints) +} + +fn status_footer_inner( + width: u16, + me_fp: &str, + me_onion: Option<&str>, + phase: Option, + status_note: Option<&str>, + hints: &str, ) -> String { let w = width as usize; let gap = if w >= 120 { " " } else { " " }; let help = "? help"; - let me = format!("TOR me:{}", truncate_fp(me_fp)); + let me = format!("{} me:{}", tor_token(phase), truncate_fp(me_fp)); let mut note = status_note.unwrap_or("").trim().to_string(); if !note.is_empty() && color_mode() == ColorMode::None @@ -2624,22 +2947,11 @@ pub fn status_footer( note = format!("! {note}"); } - let onion_full = if me_onion.is_empty() { - "unset".to_string() - } else { - me_onion.to_string() - }; - let onion_short = if me_onion.is_empty() { - "unset".to_string() - } else { - truncate_fp(me_onion) - }; - if !note.is_empty() { - let fixed = char_len(&me) + char_len(help) + 2 * gap.len(); + let fixed = cell_width(&me) + cell_width(help) + 2 * cell_width(gap); let budget = w.saturating_sub(fixed); - if char_len(¬e) > budget { - note = truncate_chars(¬e, budget.max(12)); + if cell_width(¬e) > budget { + note = fit_cells(¬e, budget.max(12)); } } @@ -2649,13 +2961,25 @@ pub fn status_footer( } parts.push(me); - let onion_full_part = format!("onion:{onion_full}"); - let onion_short_part = format!("onion:{onion_short}"); - let try_full = width >= 110; - if try_full && footer_fits(&parts, &[&onion_full_part], help, gap, w) { - parts.push(onion_full_part); - } else if footer_fits(&parts, &[&onion_short_part], help, gap, w) { - parts.push(onion_short_part); + if let Some(onion) = me_onion { + let onion_full = if onion.is_empty() { + "unset".to_string() + } else { + onion.to_string() + }; + let onion_short = if onion.is_empty() { + "unset".to_string() + } else { + truncate_fp(onion) + }; + let onion_full_part = format!("onion:{onion_full}"); + let onion_short_part = format!("onion:{onion_short}"); + let try_full = width >= 110; + if try_full && footer_fits(&parts, &[&onion_full_part], help, gap, w) { + parts.push(onion_full_part); + } else if footer_fits(&parts, &[&onion_short_part], help, gap, w) { + parts.push(onion_short_part); + } } let extra = hints.replace("? help", ""); @@ -2671,10 +2995,10 @@ pub fn status_footer( parts.push(help.to_string()); let line = parts.join(gap); - if char_len(&line) <= w { + if cell_width(&line) <= w { line } else { - truncate_chars(&line, w) + fit_cells(&line, w) } } @@ -2682,7 +3006,7 @@ fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize let mut all: Vec<&str> = parts.iter().map(String::as_str).collect(); all.extend(extra.iter().copied()); all.push(help); - char_len(&all.join(gap)) <= w + cell_width(&all.join(gap)) <= w } /// Main-screen key hints. `F6` (wallet) and `F9` (wallets & settings) are named @@ -2693,6 +3017,20 @@ pub fn main_footer_hints() -> &'static str { "Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q" } +/// Footer hints for one focused main pane. +/// +/// The footer is the only place the keys are visible without opening `?`, so it +/// changes with the pane you are actually in — and every variant keeps `F9` +/// (the discoverable menu) and `? help`, which `tests/tui_chrome.rs` asserts are +/// reachable from the footer at 80, 120 and 200. +pub fn pane_footer_hints(pane: Pane) -> &'static str { + match pane { + Pane::Roster => "j k select F3 add F6 wallet F9 settings ? help", + Pane::Chat => "j k scroll g G ends F4 rotate F9 settings ? help", + Pane::Composer => "Enter send / commands F9 settings ? help", + } +} + fn footer_hints(screen: &Screen) -> &'static str { match screen { Screen::Main => main_footer_hints(), @@ -2890,26 +3228,35 @@ fn draw_passphrase(f: &mut Frame, kind: BackupKind, second: bool, buf: &str) { ); } +/// A centered popup over a cleared screen: title, body, wrap, scroll to the +/// tail. Every modal goes through this one, so a popup can never punch through +/// the chrome underneath it and can never be wider than the frame. +/// +/// Width always keeps a one-cell margin on each side. Height keeps the margin +/// only when the frame can afford it: a 22-line body on a 24-row terminal needs +/// the rows more than it needs symmetry, and the scroll below still lands the +/// last line on screen. pub fn draw_text_overlay(f: &mut Frame, title: &str, text: &str) { let area = f.area(); - let popup = if area.height < 28 { - area + let wanted_w = text + .lines() + .map(cell_width) + .max() + .unwrap_or(40) + .saturating_add(4); + let wanted_h = text.lines().count() as u16 + 2; + let max_w = area.width.saturating_sub(2).max(10); + let width = (wanted_w as u16).clamp(10, max_w.max(10)).min(area.width); + let height = if wanted_h >= area.height.saturating_sub(1) { + area.height } else { - let lines = text.lines().count() as u16 + 2; - let text_w = text - .lines() - .map(|l| l.chars().count() as u16) - .max() - .unwrap_or(40) - .saturating_add(4); - let width = text_w.min(area.width).max(10); - let height = lines.min(area.height).max(3); - Rect { - x: area.x + (area.width.saturating_sub(width)) / 2, - y: area.y + (area.height.saturating_sub(height)) / 2, - width, - height, - } + wanted_h.clamp(3, area.height) + }; + let popup = Rect { + x: area.x + (area.width.saturating_sub(width)) / 2, + y: area.y + (area.height.saturating_sub(height)) / 2, + width, + height, }; f.render_widget(Clear, area); f.render_widget(Clear, popup); @@ -2918,8 +3265,12 @@ pub fn draw_text_overlay(f: &mut Frame, title: &str, text: &str) { let wrapped: u16 = text .lines() .map(|l| { - let n = char_len(l) as u16; - if n == 0 { 1 } else { n.div_ceil(inner_w) } + let n = cell_width(l) as u16; + if n == 0 { + 1 + } else { + n.div_ceil(inner_w) + } }) .sum(); let scroll = wrapped.saturating_sub(inner_h); @@ -3375,28 +3726,26 @@ fn truncate_fp(fp: &str) -> String { format!("{s}{}", ellipsis()) } -fn roster_row_text(name: &str, fingerprint: &str, stale: bool, inner_width: u16) -> String { +fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { let budget = (inner_width as usize).saturating_sub(2); - let fp = truncate_fp(fingerprint); - let fp_part = format!(" {fp}"); - let mut stale_s = if stale { " stale" } else { "" }.to_string(); - let suffix_len = char_len(&fp_part) + char_len(&stale_s); - let mut name_budget = budget.saturating_sub(suffix_len); - if name_budget < 1 && stale { - stale_s = " s".into(); - name_budget = budget.saturating_sub(char_len(&fp_part) + char_len(&stale_s)); - } - let shown = if name_budget == 0 { - String::new() + let stale_s = if row.stale { " stale" } else { "" }; + let avail = budget.saturating_sub(cell_width(stale_s)); + // The name is what the reader is looking for. The fingerprint only + // disambiguates two friends with the same petname, so it gets what is left + // and is dropped entirely when the pane is too narrow to show a usable + // prefix — a row that reads `bob-the-sta… stale` beats one that reads + // `… bbbbbbbb… stale`. + let name_share = cell_width(&row.label).min((avail / 2).max(6)).min(avail); + let fp_share = avail.saturating_sub(name_share); + let (shown, fp_part) = if fp_share >= 8 { + ( + fit_cells(&row.label, name_share), + format!(" {}", fit_cells(&truncate_fp(&row.fingerprint), fp_share - 2)), + ) } else { - truncate_chars(name, name_budget) + (fit_cells(&row.label, avail), String::new()) }; - let line = format!("{shown}{fp_part}{stale_s}"); - if char_len(&line) > budget { - truncate_chars(&line, budget) - } else { - line - } + fit_cells(&format!("{shown}{fp_part}{stale_s}"), budget) } fn to_hex(bytes: &[u8]) -> String { diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index f3d2a47..e4d7fb7 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -1,9 +1,11 @@ //! Main-screen chrome helpers: ASCII wordmark, compact fallback, help text. +use onionwire::hs::TorState; use onionwire::qr; use onionwire::tui::{ - Pane, banner_for_width, compact_banner, draw_share, help_overlay_text, main_footer_hints, - onion_glyph, status_footer, wordmark_banner, + Pane, TorPhase, banner_for_width, compact_banner, draw_share, help_overlay_text, + main_footer_hints, onion_glyph, pane_footer_hints, status_footer, status_footer_compact, + status_footer_phased, tor_token, wordmark_banner, }; #[test] @@ -212,6 +214,102 @@ fn restore_terminal_is_callable_without_panic() { onionwire::tui::restore_terminal(); } +#[test] +fn tor_phase_projects_every_tor_state() { + assert_eq!(TorPhase::of(TorState::Bootstrapping), TorPhase::Connecting); + assert_eq!(TorPhase::of(TorState::Published), TorPhase::Ready); + assert_eq!( + TorPhase::of(TorState::DegradedReachable), + TorPhase::Degraded + ); + assert_eq!(TorPhase::of(TorState::Stopped), TorPhase::Off); + // The phase-free token is still the bare word the chrome tests lock. + assert_eq!(tor_token(None), "TOR"); +} + +#[test] +fn footer_states_the_tor_phase_with_a_word_not_only_colour() { + let fp = "abcdef0123456789deadbeef"; + let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; + for (phase, word) in [ + (TorPhase::Connecting, "connecting"), + (TorPhase::Ready, "ready"), + (TorPhase::Degraded, "degraded"), + (TorPhase::Off, "off"), + ] { + assert!(!phase.glyph().is_empty(), "{phase:?} has no glyph"); + for w in [80u16, 120, 200] { + let line = status_footer_phased(w, fp, onion, Some(phase), None, main_footer_hints()); + assert!( + line.contains(word), + "{w} footer lacks phase word {word:?}: {line:?}" + ); + assert!(line.contains("TOR"), "{w} footer lacks TOR: {line:?}"); + assert!(line.contains("me:"), "{w} footer lacks me:: {line:?}"); + assert!( + line.chars().count() <= w as usize, + "{w} footer wider than frame: {line:?}" + ); + } + } + // A fail-closed note still wins over the hints, phase or not. + let crowded = status_footer_phased( + 80, + fp, + onion, + Some(TorPhase::Off), + Some("send failed: peer onion down"), + main_footer_hints(), + ); + assert!(crowded.contains("send failed"), "{crowded:?}"); + assert!(crowded.contains("off"), "{crowded:?}"); + assert!(crowded.contains("? help"), "{crowded:?}"); + assert!(crowded.chars().count() <= 80, "{crowded:?}"); +} + +/// The main footer has its own variant: the header already prints the identity, +/// so the footer drops the onion and keeps `TOR` + `me:` + the hints. +#[test] +fn compact_footer_drops_the_onion_and_keeps_the_rest() { + let fp = "abcdef0123456789deadbeef"; + let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; + let full = status_footer_phased(80, fp, onion, Some(TorPhase::Ready), None, main_footer_hints()); + let compact = status_footer_compact(80, fp, Some(TorPhase::Ready), None, main_footer_hints()); + assert!(full.contains("onion:"), "{full:?}"); + assert!(!compact.contains("onion:"), "{compact:?}"); + assert!(compact.contains("TOR"), "{compact:?}"); + assert!(compact.contains("me:"), "{compact:?}"); + assert!(compact.contains("? help"), "{compact:?}"); + assert!(compact.chars().count() <= 80, "{compact:?}"); + // The cells the onion gave up go to the hints. + assert!( + compact.chars().count() > 0 && compact.contains("F9"), + "compact footer lost the menu key: {compact:?}" + ); +} + +#[test] +fn pane_footer_hints_keep_the_menu_and_help_on_every_pane() { + let fp = "abcdef0123456789deadbeef"; + for pane in [Pane::Roster, Pane::Chat, Pane::Composer] { + let hints = pane_footer_hints(pane); + assert!(hints.contains("F9"), "{pane:?} lost the menu key: {hints:?}"); + assert!(hints.contains("? help"), "{pane:?} lost ? help: {hints:?}"); + for w in [80u16, 120, 200] { + let line = status_footer_compact(w, fp, Some(TorPhase::Ready), None, hints); + assert!(line.contains("F9"), "{pane:?} at {w} lost F9: {line:?}"); + assert!( + line.contains("? help"), + "{pane:?} at {w} lost ? help: {line:?}" + ); + assert!(line.chars().count() <= w as usize, "{pane:?} at {w}: {line:?}"); + } + } + // The hints actually change with the pane — that is the point of the lever. + assert_ne!(pane_footer_hints(Pane::Roster), pane_footer_hints(Pane::Composer)); + assert_ne!(pane_footer_hints(Pane::Chat), pane_footer_hints(Pane::Composer)); +} + #[test] fn share_screen_shows_invite_not_qr_at_80x24() { use ratatui::Terminal; diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index a262283..7e4ded6 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -1,55 +1,44 @@ //! Visual audit dumps of the current OnionWire TUI. //! -//! This crate cannot construct `App` (private, needs `Node` / Arti). Public -//! draw path used where it exists (`draw_share`, chrome helpers, overlay copy). -//! Main / profile / confirm screens labeled RECONSTRUCTED copy the layout -//! constants and copy from `src/tui.rs` so a reviewer can see the shape. +//! The main screen is the **real** render path: `draw_main_chrome` takes a +//! `MainView` of plain data, so this test draws exactly what `App::draw_main` +//! draws (no stand-in layout constants, no stub widget). Screens that are still +//! private (`draw_paste`, `draw_rotate`, …) are labelled RECONSTRUCTED and copy +//! the layout constants and copy from `src/tui.rs`. //! //! Print frames: //! cargo test --locked --test tui_frames -- --nocapture dump_audit_frames //! -//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose. -//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`). +//! Widths are asserted in terminal **cells** via `onionwire::tui::cell_width` +//! (`Span::width`), never `chars().count()`. +use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ - backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner, - help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, - rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, - ProfileEditor, WipeKind, + ChatRowStyle, FriendRow, MainView, Pane, TorPhase, backup_screen_text, banner_for_width, + cell_width, chat_no_friends_lines, chat_with_delivery, compact_banner, draw_main_chrome, + draw_share, draw_text_overlay, fingerprint_mismatch_banner, help_overlay_text, + main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, rotate_screen_text, + status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor, WipeKind, }; -use onionwire::FriendProfile; -use ratatui::backend::TestBackend; -use ratatui::layout::{Constraint, Layout, Rect}; -use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; +use onionwire::{FriendProfile, Message}; use ratatui::Frame; use ratatui::Terminal; +use ratatui::backend::TestBackend; +use ratatui::buffer::Buffer; +use ratatui::layout::{Constraint, Layout}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; const SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)]; const FP: &str = "abcdef0123456789deadbeefcafebabe"; const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; -const LONG_MSG: &str = "them: 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"; - -struct FriendRow { - name: &'static str, - fp: &'static str, - last_ok: bool, -} +const LONG_BODY: &str = "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"; fn fp8(s: &str) -> String { s.chars().take(8).collect() } -struct MainStandin<'a> { - friends: &'a [FriendRow], - selected: usize, - chat_lines: &'a [&'a str], - composer: &'a str, - alert: Option<&'a str>, - status_note: Option<&'a str>, -} - -fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) { +fn dump_buffer(label: &str, w: u16, h: u16, buf: &Buffer) { println!(); println!("===== {label} {w}x{h} ====="); for y in 0..h { @@ -57,10 +46,10 @@ fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) { for x in 0..w { row.push_str(buf[(x, y)].symbol()); } - let cells = row.chars().count(); + let cells = cell_width(&row); assert!( cells <= w as usize, - "{label} row {y} chars().count()={cells} > {w}: {row:?}" + "{label} row {y} width {cells} cells > {w}: {row:?}" ); println!("{row}"); } @@ -73,158 +62,100 @@ fn draw_to(w: u16, h: u16, label: &str, render: impl FnOnce(&mut Frame)) { dump_buffer(label, w, h, terminal.backend().buffer()); } -fn pane_block(title: &str) -> Block<'_> { - // Real `App::pane_block` only changes border/title color. TestBackend - // dumps are glyphs, so focused chat/composer look identical to unfocused. - Block::default().borders(Borders::ALL).title(title) +fn draw_frame(w: u16, h: u16, render: impl FnOnce(&mut Frame)) -> Buffer { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(render).expect("draw"); + terminal.backend().buffer().clone() } -/// Layout constants copied from `App::draw_main` (`src/tui.rs`). -impl MainStandin<'_> { - fn draw(self, f: &mut Frame) { - let friends = self.friends; - let selected = self.selected; - let chat_lines = self.chat_lines; - let composer = self.composer; - let alert = self.alert; - let status_note = self.status_note; - let area = f.area(); - let banner = banner_for_width(area.width); - let banner_h = banner.lines().count() as u16; - let alert_h = u16::from(alert.is_some()); - let cols = Layout::vertical([ - Constraint::Length(banner_h), - Constraint::Length(alert_h), - Constraint::Min(3), - Constraint::Length(3), - Constraint::Length(1), - ]) - .split(area); - - f.render_widget(Paragraph::new(banner), cols[0]); - if let Some(msg) = alert { - f.render_widget(Paragraph::new(msg), cols[1]); +fn screen_of(buf: &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 +} - let panes = - Layout::horizontal([Constraint::Percentage(36), Constraint::Min(10)]).split(cols[2]); +// --------------------------------------------------------------------------- +// Real main-screen states +// --------------------------------------------------------------------------- - let stale_n = friends.iter().filter(|fr| !fr.last_ok).count(); - let roster_title = if stale_n > 0 { - format!("roster {} {stale_n} stale", friends.len()) - } else { - format!("roster {}", friends.len()) - }; - let items: Vec = friends - .iter() - .map(|friend| { - let mut line = format!("{} {}…", friend.name, fp8(friend.fp)); - if !friend.last_ok { - line.push_str(" stale"); - } - ListItem::new(line) - }) - .collect(); - let roster = List::new(items) - .highlight_symbol("> ") - .block(pane_block(&roster_title)); - let mut roster_state = ListState::default(); - if !friends.is_empty() { - roster_state.select(Some(selected)); - } - f.render_stateful_widget(roster, panes[0], &mut roster_state); +fn friend_rows() -> Vec { + vec![ + FriendRow { + label: "alice".into(), + fingerprint: "aaaaaaaaaaaaaaaa".into(), + stale: false, + }, + FriendRow { + label: "bob-the-stale-peer".into(), + fingerprint: "bbbbbbbbbbbbbbbb".into(), + stale: true, + }, + ] +} - let inner_h = panes[1].height.saturating_sub(2); - let nlines = chat_lines.len(); - let overflow = nlines > inner_h as usize && inner_h > 0; - let chat_title = { - let mut t = match friends.get(selected) { - Some(fr) => format!("chat {}", fr.name), - None => "chat".to_string(), - }; - if overflow { - let end = inner_h as usize; - t.push_str(&format!(" 1-{end}/{nlines}")); - } - t - }; - f.render_widget( - Paragraph::new(chat_lines.join("\n")) - .wrap(Wrap { trim: false }) - .block(pane_block(&chat_title)), - panes[1], - ); - - let cmd = if composer.is_empty() { - "/wipe /wipe-all /profile /who /pay /tip /file".to_string() - } else { - composer.to_string() - }; - f.render_widget(Paragraph::new(cmd).block(pane_block("composer")), cols[3]); - - let footer = status_footer(area.width, FP, ONION, status_note, main_footer_hints()); - f.render_widget(Paragraph::new(footer), cols[4]); +fn out_msg(id: i64, body: &str) -> Message { + Message { + id, + dir: "out".into(), + plaintext: body.as_bytes().to_vec(), } } -/// Rect math copied from private `draw_text_overlay` (`src/tui.rs`). -fn draw_text_overlay_standin(f: &mut Frame, title: &str, text: &str) { - let area = f.area(); - let lines = text.lines().count() as u16 + 2; - let text_w = text - .lines() - .map(|l| l.chars().count() as u16) - .max() - .unwrap_or(40) - .saturating_add(4); - let width = text_w.min(area.width.saturating_sub(2)).max(10); - let height = lines.min(area.height.saturating_sub(2)).max(3); - let popup = Rect { - x: area.x + (area.width.saturating_sub(width)) / 2, - y: area.y + (area.height.saturating_sub(height)) / 2, - width, - height, - }; - f.render_widget(Clear, popup); - f.render_widget( - Paragraph::new(text).block(Block::default().borders(Borders::ALL).title(title)), - popup, - ); +fn in_msg(id: i64, body: &str) -> Message { + Message { + id, + dir: "in".into(), + plaintext: body.as_bytes().to_vec(), + } } -fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) { - f.render_widget( - Paragraph::new(body) - .wrap(Wrap { trim: false }) - .block(Block::default().borders(Borders::ALL).title(title)), - f.area(), - ); +fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { + OutboxEntry { + id: 1, + friend_pk: vec![9u8; 32], + message_id, + body: body.as_bytes().to_vec(), + payload: None, + attempts, + next_attempt_at: now + next_in, + created_at: now, + status: OutboxStatus::Queued, + last_error: None, + } } -fn sample_invite() -> String { - qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode") +/// Transcript rows through the real helper: markers included. +fn chat_ok() -> Vec { + let msgs = [out_msg(1, "ping"), in_msg(2, "pong"), in_msg(3, LONG_BODY)]; + chat_with_delivery(&msgs, &[], 1000).0 } -fn empty_chat_lines() -> &'static [&'static str] { - &["no friends yet", "F3 paste an invite to add one"] +/// Transcript with one row still held by the outbox, so the footer carries the +/// reachability note instead of a bare `sent`. +fn chat_queued() -> (Vec, String) { + let now = 1000; + let msgs = [out_msg(1, "ping"), in_msg(2, "pong"), out_msg(3, "are you there?")]; + let pending = [queued_row(3, "are you there?", 1, 45, now)]; + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + (lines, summary.note().unwrap_or_default()) +} + +fn empty_chat(phase: TorPhase) -> Vec { + chat_no_friends_lines(Some(phase)) } #[test] fn dump_audit_frames() { - let invite = sample_invite(); - let friends = [ - FriendRow { - name: "alice", - fp: "aaaaaaaaaaaaaaaa", - last_ok: true, - }, - FriendRow { - name: "bob-the-stale-peer", - fp: "bbbbbbbbbbbbbbbb", - last_ok: false, - }, - ]; - let chat_ok: [&str; 3] = ["you: ping", "them: pong", LONG_MSG]; + let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); + let friends = friend_rows(); + let chat = chat_ok(); + let (queued_chat, queued_note) = chat_queued(); let editor = ProfileEditor::new("lance", "tor messenger", ""); let profile_body = { let labels = ["name", "bio", "xmr"]; @@ -248,7 +179,6 @@ fn dump_audit_frames() { updated_at: 0, }), ); - let who_empty = who_overlay_text(FP, ONION, None); println!("invite payload length (chars) = {}", invite.chars().count()); println!("wordmark:\n{}", wordmark_banner()); @@ -260,7 +190,7 @@ fn dump_audit_frames() { ); for (w, h) in SIZES { - draw_to(w, h, "chrome banner+footer", |f| { + draw_to(w, h, "chrome banner+footer (real helpers)", |f| { let banner = banner_for_width(f.area().width); let banner_h = banner.lines().count() as u16; let chunks = Layout::vertical([ @@ -274,100 +204,179 @@ fn dump_audit_frames() { f.render_widget(Paragraph::new(footer), chunks[2]); }); - draw_to(w, h, "chrome long-onion + send-failed", |f| { - let banner = banner_for_width(f.area().width); - let banner_h = banner.lines().count() as u16; - let chunks = Layout::vertical([ - Constraint::Length(banner_h), - Constraint::Min(3), - Constraint::Length(1), - ]) - .split(f.area()); - f.render_widget(Paragraph::new(banner), chunks[0]); - let footer = status_footer( - f.area().width, - FP, - ONION, - Some("send failed: connection timed out"), - main_footer_hints(), + draw_to(w, h, "main: chat + stale roster, focus chat, tor ready", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, ); - f.render_widget(Paragraph::new(footer), chunks[2]); }); - draw_to(w, h, "RECONSTRUCTED main empty", |f| { - MainStandin { - friends: &[], - selected: 0, - chat_lines: empty_chat_lines(), - composer: "", - alert: None, - status_note: None, - } - .draw(f); + draw_to(w, h, "main: focus roster, tor connecting", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &friends, + selected: 1, + focus: Pane::Roster, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("bob-the-stale-peer"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main chat+stale", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &chat_ok, - composer: "hello from composer", - alert: Some("passphrases do not match"), - status_note: Some("sent"), - } - .draw(f); + draw_to(w, h, "main: focus composer, promoted identity", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "hello from composer", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main pay/file footer only", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &["you: /pay 0.1 coffee", "them: (no invoice pane exists)"], - composer: "", - alert: None, - status_note: Some("invoice sent"), - } - .draw(f); + draw_to(w, h, "main: EMPTY roster, tor connecting", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Connecting), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main file-send-failed", |f| { - MainStandin { - friends: &friends, - selected: 1, - chat_lines: &["no messages"], - composer: "", - alert: None, - status_note: Some("send failed: peer onion down"), - } - .draw(f); + draw_to(w, h, "main: EMPTY roster, tor off (disconnected)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: "", + phase: Some(TorPhase::Off), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Off), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: Some("fingerprint mismatch"), + note: None, + }, + ); + }); + + draw_to(w, h, "main: ERROR alert + fail-closed note", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: Some("send failed: peer onion down"), + note: Some("send failed: peer onion down"), + }, + ); + }); + + draw_to(w, h, "main: outbox queued (peer unreachable)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Roster, + chat_lines: &queued_chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: Some(&queued_note), + }, + ); }); draw_to(w, h, "draw_share (real)", |f| draw_share(f, &invite)); - draw_to(w, h, "RECONSTRUCTED help overlay on empty main", |f| { - MainStandin { - friends: &[], - selected: 0, - chat_lines: empty_chat_lines(), - composer: "", - alert: None, - status_note: None, - } - .draw(f); - draw_text_overlay_standin(f, "? help", help_overlay_text()); + draw_to(w, h, "main + ? help overlay (real draw_text_overlay)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); + draw_text_overlay(f, "? help", help_overlay_text()); }); - draw_to(w, h, "RECONSTRUCTED /who overlay", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &chat_ok, - composer: "", - alert: None, - status_note: None, - } - .draw(f); - draw_text_overlay_standin(f, "/who", &who); + draw_to(w, h, "main + /who overlay (real draw_text_overlay)", |f| { + draw_text_overlay(f, "/who", &who); }); draw_to(w, h, "RECONSTRUCTED profile", |f| { @@ -407,13 +416,6 @@ fn dump_audit_frames() { &format!("{}\n\nWI", wipe_screen_text(WipeKind::Messages)), ); }); - draw_to(w, h, "RECONSTRUCTED wipe-all", |f| { - draw_overlay_screen( - f, - "(o) wipe all", - &format!("{}\n\n", wipe_screen_text(WipeKind::All)), - ); - }); draw_to(w, h, "RECONSTRUCTED quit", |f| { draw_overlay_screen(f, "(o) quit", &format!("{}\n\nQUI", quit_screen_text())); }); @@ -427,19 +429,243 @@ fn dump_audit_frames() { draw_to(w, h, "RECONSTRUCTED restore", |f| { draw_overlay_screen(f, "(o) restore", &format!("{}\n\n", restore_screen_text())); }); - draw_to(w, h, "RECONSTRUCTED passphrase", |f| { - draw_overlay_screen( - f, - "(o) passphrase", - "Enter passphrase\n\n****\n\nEnter submit Esc cancel", - ); - }); - draw_to(w, h, "who copy (no profile)", |f| { - draw_overlay_screen(f, "/who", &who_empty); - }); } } +fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) { + f.render_widget( + Paragraph::new(body) + .wrap(Wrap { trim: false }) + .block(Block::default().borders(Borders::ALL).title(title)), + f.area(), + ); +} + +/// Every real main-screen state must fit every supported size in cells. +#[test] +fn main_chrome_fits_80x24_120x40_and_200x60() { + let friends = friend_rows(); + let chat = chat_ok(); + let (queued_chat, queued_note) = chat_queued(); + let empty_connecting = empty_chat(TorPhase::Connecting); + let states: Vec<(&str, MainView<'_>, Option<&str>)> = vec![ ( + "chat+stale", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + None, + ), + ( + "empty+connecting", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_connecting, + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + None, + ), + ( + "error+alert", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: Some("send failed: peer onion down"), + note: Some("send failed: peer onion down"), + }, + None, + ), + ( + "queued outbox", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Roster, + chat_lines: &queued_chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: Some(&queued_note), + }, + None, + ), + ]; + for (name, view, _) in states { + for (w, h) in SIZES { + let buf = draw_frame(w, h, |f| draw_main_chrome(f, &view)); + let screen = screen_of(&buf, w, h); + for (y, row) in screen.lines().enumerate() { + assert!( + cell_width(row) <= w as usize, + "{name} at {w}x{h}: row {y} is {} cells: {row:?}", + cell_width(row) + ); + } + } + } +} + +/// The frame dump must show the phase, and the phase must not be colour-only. +#[test] +fn main_frame_states_are_legible_without_colour() { + let friends = friend_rows(); + let chat = chat_ok(); + for (phase, word) in [ + (TorPhase::Connecting, "connecting"), + (TorPhase::Ready, "ready"), + (TorPhase::Degraded, "degraded"), + (TorPhase::Off, "off"), + ] { + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(phase), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + let header = screen.lines().next().unwrap_or_default().to_string(); + let footer = screen.lines().last().unwrap_or_default().to_string(); + assert!(header.contains(word), "header lacks {word:?}: {header:?}"); + assert!(footer.contains(word), "footer lacks {word:?}: {footer:?}"); + assert!(header.contains("onionwire"), "{header:?}"); + assert!(footer.contains("TOR"), "{footer:?}"); + } +} + +/// Focus must be visible with the colour stripped: a marker on the focused +/// pane, not just a coloured border. +#[test] +fn focus_is_a_marker_not_only_colour() { + let friends = friend_rows(); + let chat = chat_ok(); + let marker_of = |focus: Pane, w: u16| -> String { + let buf = draw_frame(w, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + screen_of(&buf, w, 24) + }; + for w in [80u16, 120] { + let roster_focus = marker_of(Pane::Roster, w); + let chat_focus = marker_of(Pane::Chat, w); + assert!( + roster_focus.contains("> alice"), + "roster focus has no row marker at {w}: {roster_focus}" + ); + assert!( + chat_focus.contains("> chat"), + "chat focus has no title marker at {w}" + ); + assert!( + !roster_focus.contains("> chat"), + "chat title keeps the focus marker while roster is focused" + ); + assert_eq!( + roster_focus.lines().count(), + 24, + "frame height changed with focus" + ); + } +} + +/// The empty roster is a state, not a blank box. +#[test] +fn empty_roster_and_empty_chat_are_designed_states() { + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Connecting), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + assert!(screen.contains("no friends"), "{screen}"); + assert!(screen.contains("F3 adds one"), "{screen}"); + assert!(screen.contains("F3 paste an invite"), "{screen}"); + assert!( + screen.contains("tor connecting"), + "connecting state is not on screen:\n{screen}" + ); +} + #[test] fn public_copy_fits_80_by_chars_count() { for (name, text) in [ @@ -518,7 +744,7 @@ fn status_footer_drops_send_failed_when_crowded() { #[test] fn share_invite_wraps_at_three_sizes() { - let invite = sample_invite(); + let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); for (w, h) in SIZES { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -536,6 +762,34 @@ fn share_invite_wraps_at_three_sizes() { } } +/// The help overlay is cleared underneath and never wider than the frame. +#[test] +fn help_overlay_keeps_a_margin_and_shows_the_tail() { + for (w, h) in SIZES { + let buf = draw_frame(w, h, |f| { + f.render_widget(Paragraph::new("underlying frame junk"), f.area()); + draw_text_overlay(f, "? help", help_overlay_text()); + }); + let screen = screen_of(&buf, w, h); + assert!( + !screen.contains("underlying frame junk"), + "{w}x{h} overlay punched through:\n{screen}" + ); + assert!( + screen.contains("Esc closes this overlay"), + "{w}x{h} help tail clipped" + ); + // A one-cell margin on each side: no border glyph in column 0. + for line in screen.lines() { + let first = line.chars().next().unwrap_or(' '); + assert!( + first != '┌' && first != '│', + "{w}x{h} overlay is full-bleed: {line:?}" + ); + } + } +} + /// Documented defect in `tests/tui_chrome.rs`: `chars().count()` is not cells. /// Do not add `unicode-width` on this card. #[test] @@ -553,3 +807,34 @@ fn chars_count_is_not_terminal_cells() { let ellipsis = "…"; assert_eq!(ellipsis.chars().count(), 1); } + +/// Sanity: the real main renderer is the one under test here. +#[test] +fn main_chrome_draws_the_same_frame_as_the_app_layout() { + let friends = friend_rows(); + let chat = chat_ok(); + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + assert!(screen.contains("roster 2 1 stale"), "{screen}"); + assert!(screen.contains("> chat alice"), "{screen}"); + assert!(screen.contains("message"), "composer placeholder: {screen}"); +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 9672138..3ba53c7 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -259,6 +259,13 @@ fn alert_line_truncates_to_frame_width() { !line.contains("roster on the next row"), "alert still has overflow tail: {line:?}" ); + // Cells, not chars: a double-width peer error must not overflow the row. + let cjk = alert_line("接続がタイムアウトしました 接続がタイムアウトしました", 32); + assert!( + onionwire::tui::cell_width(&cjk) <= 32, + "alert wider than 32 cells: {} {cjk:?}", + onionwire::tui::cell_width(&cjk) + ); } #[test] @@ -1133,10 +1140,19 @@ fn wallets_settings_menu_truncates_wide_values_in_cells() { "no ellipsis: {cut:?}" ); // ASCII chrome swaps the ellipsis and the section rule, never the width - // contract. + // contract. Either ellipsis form is accepted, like the two assertions above: + // `ONIONWIRE_ASCII` is process-wide, so this test cannot assume which form + // is active while other tests run in parallel. let ascii = fit_cells("abcdefghij", 8); assert!(cell_width(&ascii) <= 8, "{ascii:?}"); - assert!(ascii.starts_with("abcdef"), "{ascii:?}"); + assert!( + ascii.starts_with("abcde") && ascii != "abcdefghij", + "truncation kept the whole string or dropped too much: {ascii:?}" + ); + assert!( + ascii.ends_with('…') || ascii.ends_with("..."), + "no ellipsis: {ascii:?}" + ); assert_eq!(cell_width("名"), 2); assert_eq!(cell_width("abc"), 3); } From 2fa34660195ced87dd82115bf9b0583da9ef004e Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Fri, 18 Sep 2026 23:53:10 -0400 Subject: [PATCH 03/94] tui: peer payment history behind the F9 `payments` row (key p) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The F9 / `/settings` menu's only payment row showed the wallet's own transfer list (`Node::wallet_recent_transfers`, F6). The signed `/pay` invoices and `/tip` receipts a peer sent live in the `payments` table and had no path from the TUI, so they were invisible. `Node::list_payments` (PR #119) closes that gap; this wires it into a screen. - `Screen::PeerPayments { state }` + `PeerPaymentsState` / `PeerPaymentRow`, built by `PeerPaymentsState::from_payments` from `Node::list_payments`' rows (newest first: the store returns `payments.id` ascending, the screen windows the vector). - Key handler: `p` on the F9 screen opens it (`open_peer_payments`); `up`/`down` (or `k`/`j`) move the selection, `Esc` goes back, `F9` reopens the menu. - Rows carry direction, kind, amount (`pay::atomic_to_xmr_str`, the same piconero formatter the chat lines use), memo (sanitized at draw time) and the receipt's `verified` / `unverified` word; the focused row is marked with `>` and bold. The selected row's txid and address sit under the rows — the address wrapped over two lines rather than clipped. - States: populated, `no payments with {peer}`, `could not read payments`, and a menu row that refuses when no friend is selected. An empty history is a state, never an error. - Menu: the wallet's own list is retitled `transfers` (F6, unchanged), and the new `payments` row (key `p`) names the peer and the count. Two histories, two rows, no ambiguity. - Widths are measured in cells (`Span::width`); trailing columns are dropped before they can wrap, so the body fits 80x24 (20 inner rows of 21) as well as 120x40 and 200x60. Tests: new `tests/tui_payments.rs` (11 tests) dumps and asserts the screen at 80x24, 120x40 and 200x60 including the empty history, asserts a memo carrying ESC/BEL/C1/bidi/newline bytes never reaches the frame buffer, and asserts the window/column invariants for every width from 20 to 200. Also relaxes one width assertion in `tests/tui_spec.rs`: `fit_cells` was asserted to start with `"abcdef"`, which only holds when another test's in-flight `ONIONWIRE_ASCII` mutation is not visible — the suite mutates env vars without a global lock, so that test flaked (it also fails on an unmodified tree, 1 run in 2). It now accepts either chrome's cut point, which is what the comment already claimed. Docs: `docs/TUI.md` gains the screen's section, the retitled/replaced rows and the updated row count; the "peer payment history" gap entry is closed. --- docs/TUI.md | 84 ++++++- src/tui.rs | 550 +++++++++++++++++++++++++++++++++++++++++- tests/tui_payments.rs | 420 ++++++++++++++++++++++++++++++++ tests/tui_spec.rs | 67 +++-- 4 files changed, 1095 insertions(+), 26 deletions(-) create mode 100644 tests/tui_payments.rs diff --git a/docs/TUI.md b/docs/TUI.md index e83efa3..943512d 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -653,7 +653,8 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, | WALLET | sync | chain readiness word (`chain at tip · wallet answering`, `wallet answering · chain not at tip`, `wallet RPC not answering yet`, `child exited`, `not probing · no chain source`) | `F6 p` | | WALLET | receive | the receive address (truncated) or `no address yet · wallet unreachable` | `c copy` / `F6 r` | | WALLET | balance | `{xmr}` / `off` / `err` | `F6` | -| WALLET | payments | `{n} recent` / `no transfers yet` | `F6` | +| WALLET | transfers | `{n} recent` / `no transfers yet` — the wallet's **own** transfer list | `F6` | +| WALLET | payments | `{n} with {peer}` / `no history with {peer}` / `no friend selected` / `history unreadable · {peer}` — the **peer's** payment rows | `p` | | WALLET | create | `/wallet create · seed shown once` | `F6 c` | | WALLET | import | `/wallet import · 25-word seed` | `F6 i` | | SETTINGS | nickname | the self-profile name, or `(none)` | `/profile` | @@ -665,7 +666,13 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, | SETTINGS | wipe | `messages · identity and friends stay` | `/wipe` | | SETTINGS | wipe-all | `deletes your identity key · new person` | `/wipe-all` | -19 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. +20 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. + +`transfers` and `payments` are deliberately two rows: `transfers` is the +wallet's own list (`Node::wallet_recent_transfers`, F6), `payments` is the +peer-scoped history (`Node::list_payments`, `p`). Signed `/pay` invoices and +`/tip` receipts a peer sent never appear in the wallet's own transfers, so the +two histories are not interchangeable and the menu names both. ### Guarantees @@ -699,8 +706,77 @@ sibling-card work, not presentation: `Node::wallet_test_connection(..)` — the endpoint config screen is F7 on `feat/wallet-create-import`; the menu shows the endpoint's *state* and leaves the key free. -- Peer payment history — `store.list_payments(..)` has no `Node` accessor, so - the menu can only offer the wallet's own transfer list (F6). +- Peer payment history — **closed by this screen.** `Node::list_payments` exists + on `main`; the `payments` row (key `p`) opens the peer-scoped history, and the + row is distinct from the wallet's own transfer list (`transfers`, F6). - `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and probed, not edited. - `Node::set_petname(..)` — no petname editor exists. + +## Peer payment history (F9 → `payments`, key `p`) + +A screen, not a popup, and peer-scoped: it renders what +`Node::list_payments(&friend_pk)` returns for the chat's selected friend, so the +signed `/pay` invoices and `/tip` receipts a peer sent are visible even though +they never appear in the wallet's own transfer list (F6). The call takes the +store lock only — no Tor dial, no wallet RPC — so it is safe while offline or +while Arti is still bootstrapping, and an empty result (`Ok(vec![])`) is the +**no history** state, never an error. + +``` +cargo test --locked --test tui_payments -- --nocapture peer_payments_frame_dumps +``` + +dumps the screen at 80x24, 120x40 and 200x60, populated and empty. + +### Layout + +``` + dir kind amount XMR receipt memo +> in receipt 0.025 verified lunch money + out tip 0.005 coffee + out invoice 0.1 rent + + tx 3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041 + addr 4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMW + aC8iqPUE9XUBFGrLyDz4DpEBM +``` + +- Rows are **newest first**: `payments.id` ascending is oldest first, so + `PeerPaymentsState::from_payments` reverses it and the render path windows the + result. Rows outside the window are counted in an explicit `… N older` / + `… N newer` line — nothing is dropped silently. +- The focused row is marked with `>` **and** bold, so focus survives a + monochrome terminal. `up`/`down` (or `k`/`j`) move it, `Esc` returns to the + main screen, `F9` reopens the menu. +- The selected row's `tx` and `addr` are spelled out under the rows: a 64-hex + txid is unusable truncated, and a 95-character base58 address is **wrapped** + over two lines rather than clipped to a prefix. +- Amounts use `pay::atomic_to_xmr_str`, the same piconero formatter the chat + lines use; the XMR unit is stated once, in the column header. +- Columns are dropped from the right when the pane is narrower than they need, + so no row can wrap or overrun at any width — not just at 80. + +### States + +| State | Frame | +|---|---| +| populated | the rows, plus the selected row's `tx` / `addr` | +| empty | `no payments with {peer}` and `invoices, receipts and tips from this peer land here` | +| read failed | `could not read payments` plus the sanitized reason — never a blank pane | +| no friend selected | the menu row refuses before the screen opens (`no friend selected` in the status line) | + +### Guarantees + +- **Memo is peer-signed text, sanitized at draw time.** `Node::list_payments` + returns `memo` as stored; the row goes through the same + `menu_cell_text`-then-`fit_cells` path the F9 menu uses, so C0/C1 controls, + ESC, bidi marks and newlines cannot reach the frame buffer or split a row. + `tests/tui_payments.rs` asserts a hostile memo (ESC, BEL, C1, bidi, newline) + never appears in a rendered frame. +- **Only receipts carry `verified`.** The flag column prints `verified` / + `unverified` for receipts and stays blank for invoices and tips, which have no + signature to check; `unverified` also takes the warn tone, so colour is never + the only signal. +- **Read-only.** The screen reads one getter and draws; it cannot send, sign or + dial. diff --git a/src/tui.rs b/src/tui.rs index 10761d8..38f868a 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -16,7 +16,7 @@ use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; +use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; use crate::wallet::{self, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1238,6 +1238,12 @@ enum Screen { WalletsSettings { state: WalletMenuState, }, + /// F9 → `payments`: the peer-scoped history from `Node::list_payments`. + /// Holds the same kind of snapshot as the menu (a resize re-fits it), so a + /// repaint never re-reads the store mid-frame. + PeerPayments { + state: PeerPaymentsState, + }, Quit { prompt: QuitPrompt, }, @@ -1334,11 +1340,17 @@ impl App { let mut file_cmd = None; let mut chat_send = None; let mut pass_submit = None; + let mut open_payments = false; + let mut payments_back = false; + let mut payments_move = 0i32; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // too: that screen's whole point is naming the key that fires each row, // so a key it names has to work while it is open. - if matches!(self.screen, Screen::Main | Screen::WalletsSettings { .. }) { + if matches!( + self.screen, + Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. } + ) { match key.code { KeyCode::F(2) => { self.open_share()?; @@ -1603,6 +1615,14 @@ impl App { Screen::WalletsSettings { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('c') => copy_addr = true, + // `p` is the key the menu's `payments` row prints. + KeyCode::Char('p') => open_payments = true, + _ => {} + }, + Screen::PeerPayments { .. } => match key.code { + KeyCode::Esc => payments_back = true, + KeyCode::Up | KeyCode::Char('k') => payments_move = -1, + KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, Screen::Quit { prompt } => match key.code { @@ -1624,6 +1644,21 @@ impl App { if let Some(kind) = wipe_confirm { return self.confirm_wipe(kind); } + if payments_move != 0 + && let Screen::PeerPayments { state } = &mut self.screen + { + if payments_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if payments_back { + self.screen = Screen::Main; + } + if open_payments { + self.open_peer_payments()?; + } if copy_addr { self.copy_receive_address(); } @@ -1870,6 +1905,19 @@ impl App { .and_then(|p| (!p.display_name.is_empty()).then(|| p.display_name.clone())); let bio_set = profile.as_ref().is_some_and(|p| !p.bio.is_empty()); let xmr_set = profile.as_ref().is_some_and(|p| !p.xmr_addr.is_empty()); + // The friend the rest of the TUI acts on is the chat's selected friend. + // `list_payments` is a lock-only read: no dial, no RPC, so this snapshot + // stays cheap and works while Tor is still bootstrapping. + let friend = self.friends.get(self.selected); + let peer = friend + .map(|f| f.petname.clone().unwrap_or_else(|| f.fingerprint.clone())) + .unwrap_or_default(); + let peer_payments = friend.and_then(|f| { + self.node + .list_payments(&f.pubkey) + .ok() + .map(|rows| rows.len()) + }); self.screen = Screen::WalletsSettings { state: WalletMenuState { configured: wstat.configured, @@ -1885,11 +1933,37 @@ impl App { bio_set, xmr_set, me_fp: self.me_fp.clone(), + peer, + peer_payments, }, }; Ok(()) } + /// The F9 menu's `payments` row: the selected friend's payment history from + /// `Node::list_payments`. + /// + /// Read-only and fail-closed: the call takes the store lock and nothing + /// else, so it never dials and is safe while offline. A friend with no rows + /// is `Ok(vec![])` — an empty history, not an error. + fn open_peer_payments(&mut self) -> Result<(), String> { + let Some(friend) = self.friends.get(self.selected) else { + self.status_note = Some("no friend selected".into()); + return Ok(()); + }; + let peer = friend + .petname + .clone() + .unwrap_or_else(|| friend.fingerprint.clone()); + let pk = friend.pubkey.clone(); + let state = match self.node.list_payments(&pk) { + Ok(rows) => PeerPaymentsState::from_payments(peer, &rows), + Err(e) => PeerPaymentsState::error(peer, e), + }; + self.screen = Screen::PeerPayments { state }; + Ok(()) + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2390,6 +2464,16 @@ impl App { ); draw_wallets_settings(f, state, &footer) } + Screen::PeerPayments { state } => { + let footer = status_footer( + f.area().width, + &self.me_fp, + &self.me_onion, + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_peer_payments(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2719,6 +2803,7 @@ match screen { Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => "Esc back c copy ? help", + Screen::PeerPayments { .. } => "Esc back up/down select F9 menu ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2983,6 +3068,12 @@ pub struct WalletMenuState { pub xmr_set: bool, /// Our own fingerprint (identity = pubkey), full hex. pub me_fp: String, + /// Display name of the friend the F9 screen's friend-scoped rows act on (the + /// chat's selected friend), or empty when there is none. + pub peer: String, + /// `Some(rows)` when `Node::list_payments` answered for that friend; + /// `None` when the read itself failed (which is not "no history"). + pub peer_payments: Option, } /// Width of `s` in terminal **cells**, measured by ratatui's own text type. @@ -3063,9 +3154,9 @@ impl MenuRow { /// The two groups, in the order the card fixes: WALLET, then SETTINGS. /// -/// Payment history here is the wallet's own transfer list (F6), which is the -/// only history `Node` exposes to the TUI. The peer `payments` table has no -/// `Node` accessor (see the card's gap list). +/// Two payment-ish rows, and they are not the same thing: `transfers` is the +/// wallet's own list (F6, `wallet_recent_transfers`), `payments` is the +/// peer-scoped history (`Node::list_payments`) opened by `p`. fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { let endpoint_word = if !s.configured { "not configured · receive-only" @@ -3136,7 +3227,7 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { }, ), MenuRow::new( - "payments", + "transfers", if s.transfers == 0 { "no transfers yet".to_string() } else { @@ -3149,6 +3240,29 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { MenuTone::Normal }, ), + // The peer-scoped history: signed `/pay` invoices and `/tip` receipts + // that peer sent. Distinct from the wallet's own transfer list above, + // and labelled so — `Payments` here means `payments` rows, not the + // wallet's `transfers`. + MenuRow::new( + "payments", + if s.peer.is_empty() { + "no friend selected".to_string() + } else { + let peer = menu_cell_text(&s.peer); + match s.peer_payments { + None => format!("history unreadable {}{peer}", "\u{b7} "), + Some(0) => format!("no history with {peer}"), + Some(n) => format!("{n} with {peer}"), + } + }, + if s.peer.is_empty() { "" } else { "p" }, + if s.peer.is_empty() || s.peer_payments == Some(0) { + MenuTone::Dim + } else { + MenuTone::Normal + }, + ), MenuRow::new( "create", "/wallet create · seed shown once".to_string(), @@ -3334,6 +3448,430 @@ pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &st ); } +// --------------------------------------------------------------------------- +// Peer payment history: the F9 menu's `payments` row. +// +// This is the *other* history. The F6 screen shows the wallet's own transfer +// list (`Node::wallet_recent_transfers`); this one shows the peer-scoped rows +// `Node::list_payments` returns — the signed `/pay` invoices and `/tip` +// receipts that peer sent, which never appear in the wallet's own transfers. +// +// Everything here is display data: `memo` is peer-signed text returned as +// stored, so it goes through `menu_cell_text` (control + bidi stripped, no +// newlines) and `fit_cells` (truncated in cells) before it can reach a frame. +// --------------------------------------------------------------------------- + +/// Direction column in cells: `in` / `out`. +const PAY_DIR_W: usize = 3; +/// Kind column in cells: `invoice` / `receipt` / `tip`. +const PAY_KIND_W: usize = 7; +/// Amount column in cells, right-aligned: `0.025000000000` is 14, so 15 holds +/// every XMR string `pay::atomic_to_xmr_str` can produce from a u128 piconero. +const PAY_AMOUNT_W: usize = 15; +/// Receipt flag column in cells: `unverified` is the widest word. +const PAY_FLAG_W: usize = 10; + +/// One payment row, display-ready except for `memo`/`txid`/`address`, which the +/// render path sanitizes. +#[derive(Clone, Debug, Default)] +pub struct PeerPaymentRow { + /// `"in"` or `"out"` — the peer's direction, not ours. + pub dir: String, + /// `"invoice"`, `"receipt"` or `"tip"`. + pub kind: String, + /// `pay::atomic_to_xmr_str(amount_atomic)` — the same formatter the chat + /// lines use, not a second piconero formatter. + pub amount_xmr: String, + /// Peer-signed memo, as stored. Sanitized at draw time. + pub memo: String, + /// Chain txid, when the payment has one. + pub txid: Option, + /// Destination address. + pub address: String, + /// Receipt signature check. Only receipts carry a meaningful flag. + pub verified: bool, +} + +/// What the peer payment screen draws. Rows are **newest first** — the store +/// returns `payments.id` ascending, so `from_payments` reverses them here and +/// the render path windows the result. `error` is display-ready and only set +/// when the store read itself failed; an empty history is not an error. +#[derive(Clone, Debug, Default)] +pub struct PeerPaymentsState { + /// Display name of the peer this history belongs to. + pub peer: String, + pub rows: Vec, + pub error: Option, + /// Index into `rows` (display order, 0 = newest). + pub selected: usize, +} + +impl PeerPaymentsState { + /// Build the screen state from `Node::list_payments`' rows. + pub fn from_payments(peer: String, rows: &[Payment]) -> Self { + let mut out: Vec = rows + .iter() + .map(|p| PeerPaymentRow { + dir: p.dir.clone(), + kind: p.kind.clone(), + amount_xmr: crate::pay::atomic_to_xmr_str(&p.amount_atomic), + memo: p.memo.clone(), + txid: p.txid.clone(), + address: p.address.clone(), + verified: p.verified, + }) + .collect(); + // `payments.id` ascending is oldest first; a history reads newest first. + out.reverse(); + Self { + peer, + rows: out, + error: None, + selected: 0, + } + } + + /// The read failed. The screen says so instead of pretending "no history". + pub fn error(peer: String, why: String) -> Self { + Self { + peer, + rows: Vec::new(), + error: Some(why), + selected: 0, + } + } + + pub fn select_next(&mut self) { + if !self.rows.is_empty() { + self.selected = (self.selected + 1).min(self.rows.len() - 1); + } + } + + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } +} + +/// Pad `s` out to `cells` terminal cells on the right. +fn pad_right(s: &str, cells: usize) -> String { + let mut out = s.to_string(); + let w = cell_width(&out); + if w < cells { + out.push_str(&" ".repeat(cells - w)); + } + out +} + +/// Pad `s` out to `cells` terminal cells on the left (numbers line up). +fn pad_left(s: &str, cells: usize) -> String { + let w = cell_width(s); + if w >= cells { + return s.to_string(); + } + let mut out = " ".repeat(cells - w); + out.push_str(s); + out +} + +/// Split `s` into a prefix of at most `max` cells and the (possibly empty) +/// remainder, so a long display value can be wrapped instead of clipped. +fn split_cells(s: &str, max: usize) -> (String, String) { + let mut head = String::new(); + let mut used = 0; + for (i, ch) in s.char_indices() { + let w = cell_width(&ch.to_string()); + if used + w > max { + return (head, s[i..].to_string()); + } + used += w; + head.push(ch); + } + (head, String::new()) +} + +/// Which style a laid-out span carries. +#[derive(Clone, Copy, PartialEq, Eq)] +enum PaySlot { + Head, + Amount, + Flag, + Memo, +} + +/// Lay out one payment line for `w` cells: `head`, then the amount, the receipt +/// flag and a flexible memo. Trailing columns are **dropped** when the pane is +/// too narrow, so no row can ever wrap or overrun — the 80-column floor holds +/// even if a terminal is smaller than the floor. +fn pay_columns( + w: usize, + head: &str, + amount: &str, + flag: &str, + memo: &str, +) -> Vec<(PaySlot, String)> { + let mut out: Vec<(PaySlot, String)> = Vec::new(); + let head = if cell_width(head) > w { + fit_cells(head, w) + } else { + head.to_string() + }; + let mut used = cell_width(&head); + out.push((PaySlot::Head, head)); + + if !amount.is_empty() && w >= used + 2 + PAY_AMOUNT_W { + let amount = fit_cells(amount, PAY_AMOUNT_W); + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Amount, pad_left(&amount, PAY_AMOUNT_W))); + used += 2 + PAY_AMOUNT_W; + } + if !flag.is_empty() && w >= used + 2 + PAY_FLAG_W { + let flag = fit_cells(flag, PAY_FLAG_W); + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Flag, pad_right(&flag, PAY_FLAG_W))); + used += 2 + PAY_FLAG_W; + } + if w > used + 2 { + let memo = fit_cells(memo, w - used - 2); + if !memo.is_empty() { + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Memo, memo)); + } + } + out +} + +/// The column header, so an `in`/`out` and a `receipt`/`invoice` need no legend +/// and the XMR unit is stated once instead of on every row. +fn payment_header_line(w: usize) -> Line<'static> { + let head = format!( + "{} {}", + pad_right("dir", PAY_DIR_W), + pad_right("kind", PAY_KIND_W) + ); + let mut spans = vec![Span::raw(" ".to_string())]; + spans.extend( + pay_columns(w.saturating_sub(2), &head, "amount XMR", "receipt", "memo") + .into_iter() + .map(|(_, text)| Span::styled(text, style_dim())), + ); + Line::from(spans) +} + +/// One payment row. The focused row is marked with `>` **and** bold, so focus +/// survives a monochrome terminal; an unverified receipt says `unverified` as +/// well as taking the warn tone, so the state is never colour-only. +fn payment_row_line(w: usize, row: &PeerPaymentRow, selected: bool) -> Line<'static> { + let dir = fit_cells(&menu_cell_text(&row.dir), PAY_DIR_W); + let kind = fit_cells(&menu_cell_text(&row.kind), PAY_KIND_W); + let head = format!( + "{} {}", + pad_right(&dir, PAY_DIR_W), + pad_right(&kind, PAY_KIND_W) + ); + let amount = menu_cell_text(&row.amount_xmr); + let (flag, flag_tone) = if row.kind == "receipt" { + if row.verified { + ("verified".to_string(), style_text()) + } else { + ("unverified".to_string(), style_stale()) + } + } else { + // A blank flag column, not an absent one: the memo column has to line + // up down the pane or the rows read as ragged. + (" ".repeat(PAY_FLAG_W), style_text()) + }; + let memo = menu_cell_text(&row.memo); + + let mark_style = if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_dim() + }; + let mut spans = vec![Span::styled( + if selected { "> " } else { " " }.to_string(), + mark_style, + )]; + for (slot, text) in pay_columns(w.saturating_sub(2), &head, &amount, &flag, &memo) { + let style = match slot { + PaySlot::Head => style_dim(), + PaySlot::Amount => style_text(), + PaySlot::Flag => flag_tone, + PaySlot::Memo => { + if selected { + style_text() + } else { + style_dim() + } + } + }; + let style = if selected { + style.add_modifier(Modifier::BOLD) + } else { + style + }; + spans.push(Span::styled(text, style)); + } + Line::from(spans) +} + +/// The peer payment body as styled lines for a `width` × `height` **inner** +/// pane. `height` matters: the window is sized so the selected row and the tx / +/// address strip always fit, and the rows that fall outside it are counted in +/// an explicit `… N older` / `… N newer` line rather than silently dropped. +pub fn peer_payments_lines(width: u16, height: u16, s: &PeerPaymentsState) -> Vec> { + let w = width as usize; + let h = height as usize; + if let Some(err) = &s.error { + return vec![ + Line::from(vec![Span::styled( + " could not read payments", + style_alert(), + )]), + Line::from(vec![Span::styled( + fit_cells(&format!(" {}", menu_cell_text(err)), w.max(1)), + style_dim(), + )]), + ]; + } + let peer = menu_cell_text(&s.peer); + if s.rows.is_empty() { + return vec![ + Line::from(vec![Span::styled( + fit_cells(&format!(" no payments with {peer}"), w.max(1)), + style_dim(), + )]), + Line::from(vec![Span::styled( + fit_cells( + " invoices, receipts and tips from this peer land here", + w.max(1), + ), + style_dim(), + )]), + ]; + } + if h < 3 { + // Degenerate pane: the header alone is still an honest frame. + return vec![payment_header_line(w)]; + } + + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + // The selected row's detail: the txid, and the address wrapped over at most + // two lines so a 95-character base58 address is readable at 80 columns + // instead of clipped to a prefix. + let txid = s.rows[selected] + .txid + .as_deref() + .map(menu_cell_text) + .unwrap_or_else(|| "(no txid yet)".to_string()); + let addr = menu_cell_text(&s.rows[selected].address); + let (addr_head, addr_rest) = { + let budget = w.saturating_sub(8).max(1); + if cell_width(&addr) > budget { + let (head, rest) = split_cells(&addr, budget); + (head, fit_cells(&rest, budget)) + } else { + (addr, String::new()) + } + }; + let detail = w >= 40 && h >= 8; + let detail_h = if detail { + 3 + usize::from(!addr_rest.is_empty()) + } else { + 0 + }; + let budget0 = h - (1 + detail_h); + let windowed = total > budget0 && budget0 >= 3; + let budget = if windowed { budget0 - 2 } else { budget0 }; + let visible = budget.max(1).min(total); + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + + let mut out: Vec> = vec![payment_header_line(w)]; + if windowed && start > 0 { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {} {start} newer", ellipsis()), w.max(1)), + style_dim(), + )])); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + out.push(payment_row_line(w, row, i == selected)); + } + if windowed && end < total { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {} {} older", ellipsis(), total - end), w.max(1)), + style_dim(), + )])); + } + if detail { + out.push(Line::default()); + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" tx {txid}"), w.max(1)), + style_dim(), + )])); + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" addr {addr_head}"), w.max(1)), + style_dim(), + )])); + if !addr_rest.is_empty() { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {addr_rest}"), w.max(1)), + style_dim(), + )])); + } + } + out +} + +/// The body as plain text, for width/needle assertions. +pub fn peer_payments_text(width: u16, height: u16, s: &PeerPaymentsState) -> String { + peer_payments_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the screen is peer-scoped, so the peer is named in the frame +/// itself and not only in the rows. +pub fn peer_payments_title(s: &PeerPaymentsState) -> String { + let peer = menu_cell_text(&s.peer); + if peer.is_empty() { + "(o) payments".to_string() + } else { + format!("(o) payments {}{peer}", "\u{b7} ") + } +} + +/// Peer payment history: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(peer_payments_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + state, + )) + .block(themed_block(&peer_payments_title(state))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. diff --git a/tests/tui_payments.rs b/tests/tui_payments.rs new file mode 100644 index 0000000..c0e43ef --- /dev/null +++ b/tests/tui_payments.rs @@ -0,0 +1,420 @@ +//! Peer payment history screen (F9 → `payments` row). +//! +//! The screen renders what `Node::list_payments` returns for the friend the rest +//! of the TUI acts on: signed `/pay` invoices, `/tip` receipts and tips, with +//! direction, kind, amount, memo, txid and the receipt's verified flag. +//! +//! Assertions measure in terminal **cells** (`cell_width`, which goes through +//! `Span::width`) and accept either ellipsis form / rule glyph, because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the two TUI test +//! binaries run in parallel. + +use onionwire::Payment; +use onionwire::tui::{ + PeerPaymentRow, PeerPaymentsState, WalletMenuState, cell_width, draw_peer_payments, + peer_payments_lines, peer_payments_text, status_footer, wallets_settings_menu_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const TXID: &str = "3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041"; +const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM"; + +fn row( + dir: &str, + kind: &str, + xmr: &str, + memo: &str, + txid: Option<&str>, + verified: bool, +) -> PeerPaymentRow { + PeerPaymentRow { + dir: dir.into(), + kind: kind.into(), + amount_xmr: xmr.into(), + memo: memo.into(), + txid: txid.map(str::to_string), + address: ADDR.into(), + verified, + } +} + +/// A peer with three rows: a receipt for a signed invoice, a tip, and the +/// invoice itself. Newest first, the way the card orders the window. +fn peer_state() -> PeerPaymentsState { + PeerPaymentsState { + peer: "lance".into(), + rows: vec![ + row("in", "receipt", "0.025", "lunch money", Some(TXID), true), + row("out", "tip", "0.005", "coffee", None, false), + row("out", "invoice", "0.1", "rent", None, false), + ], + error: None, + selected: 0, + } +} + +fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer(w, FP, ONION, None, "Esc back up/down select ? help"); + terminal + .draw(|f| draw_peer_payments(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + 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 peer_payments_lists_every_required_field() { + let body = peer_payments_text(78, 21, &peer_state()); + for needle in [ + "dir", + "kind", + "amount", + "receipt", + "memo", // column header + "in", + "out", // direction + "invoice", + "receipt", + "tip", // kind + "0.025", + "0.1", + "0.005", // amount + "lunch money", + "rent", + "coffee", // memo + "verified", // receipt flag + "tx", + TXID, // txid when present + "addr", + // destination address of the selected row (see the wrap assertions below) + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // The address is wrapped over two lines at 80 columns, not clipped: the head + // starts on the `addr` row and the tail survives on the continuation line. + assert!(body.contains(&ADDR[..40]), "\n{body}"); + assert!( + body.contains(&ADDR[ADDR.len() - 20..]), + "the address tail was clipped, not wrapped:\n{body}" + ); + // Amounts carry the shared piconero formatter's units once, in the header. + assert!(body.contains("amount XMR"), "\n{body}"); +} + +#[test] +fn peer_payments_amount_is_the_shared_formatter_not_a_second_one() { + let rows = vec![Payment { + id: 1, + dir: "in".into(), + kind: "receipt".into(), + amount_atomic: "25000000000".into(), + address: ADDR.into(), + memo: "lunch".into(), + txid: Some(TXID.into()), + verified: true, + created_at: 0, + }]; + let st = PeerPaymentsState::from_payments("lance".into(), &rows); + assert_eq!(st.rows[0].amount_xmr, "0.025", "piconero -> XMR"); + assert!( + peer_payments_text(78, 21, &st).contains("0.025"), + "{}", + peer_payments_text(78, 21, &st) + ); +} + +#[test] +fn peer_payments_empty_history_is_an_explicit_line() { + let st = PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + }; + let body = peer_payments_text(78, 21, &st); + assert!( + body.contains("no payments"), + "empty state not named:\n{body}" + ); + assert!(body.contains("lance"), "\n{body}"); + // Empty is a state, never an error. + assert!(!body.to_lowercase().contains("error"), "\n{body}"); + assert!(!body.to_lowercase().contains("failed"), "\n{body}"); + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &st); + assert!( + screen.contains("no payments"), + "{w}x{h} blank panel:\n{screen}" + ); + } +} + +#[test] +fn peer_payments_error_is_named_not_blank() { + let st = PeerPaymentsState::error("lance".into(), "store lock poisoned".into()); + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("could not read payments"), "\n{body}"); + assert!(body.contains("store lock poisoned"), "\n{body}"); +} + +#[test] +fn peer_payments_selection_uses_a_marker_not_colour_alone() { + let mut st = peer_state(); + let first = peer_payments_text(78, 21, &st); + let marked = first + .lines() + .find(|l| l.starts_with('>')) + .expect("a selection marker"); + assert!(marked.contains("0.025"), "{marked:?}"); + st.select_next(); + let second = peer_payments_text(78, 21, &st); + let now = second + .lines() + .find(|l| l.starts_with('>')) + .expect("a selection marker"); + assert!(now.contains("0.005"), "{now:?}"); + assert_eq!( + second.lines().filter(|l| l.starts_with('>')).count(), + 1, + "exactly one row is focused:\n{second}" + ); +} + +#[test] +fn peer_payments_windows_a_long_history_and_says_so() { + let rows: Vec = (0..40) + .map(|i| { + row( + "in", + "receipt", + "0.001", + &format!("row {i}"), + Some(TXID), + true, + ) + }) + .collect(); + let st = PeerPaymentsState { + peer: "lance".into(), + rows, + error: None, + selected: 0, + }; + let lines = peer_payments_lines(78, 21, &st); + assert!( + lines.len() <= 21, + "body needs {} rows for a 21-row pane", + lines.len() + ); + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("older"), "window not disclosed:\n{body}"); + // The newest row is the one on screen, not the oldest. + assert!(body.contains("row 0"), "\n{body}"); + assert!(!body.contains("row 39"), "\n{body}"); + // Scrolling to the end brings the oldest row into view. + let mut st = st; + for _ in 0..39 { + st.select_next(); + } + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("row 39"), "\n{body}"); + assert!(body.contains("newer"), "window not disclosed:\n{body}"); +} + +#[test] +fn peer_payments_hostile_memo_cannot_reach_the_terminal() { + // A peer-signed memo is untrusted display data: ESC/BEL/C1 controls, bidi + // overrides and newlines must not survive into the frame buffer. + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow"; + let st = PeerPaymentsState { + peer: "lance".into(), + rows: vec![row("in", "receipt", "0.025", hostile, Some(hostile), true)], + error: None, + selected: 0, + }; + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + assert!(!screen.contains('\u{1b}'), "{w}x{h} ESC reached the frame"); + assert!(!screen.contains('\u{7}'), "{w}x{h} BEL reached the frame"); + assert!(!screen.contains('\u{9b}'), "{w}x{h} C1 reached the frame"); + assert!( + !screen.contains('\u{202e}') && !screen.contains('\u{2066}'), + "{w}x{h} bidi reached the frame" + ); + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + // The control byte itself is dropped, so the rest is inert text: `[31m` can + // only ever be printed, never interpreted. + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert!(!body.contains('\u{1b}'), "\n{body}"); +} + +#[test] +fn peer_payments_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &peer_state()); + assert!(screen.contains("payments"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("lance"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("? help"), "footer clipped:\n{screen}"); + assert!( + screen.contains("lunch money"), + "memo clipped at {w}x{h}:\n{screen}" + ); + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = peer_payments_lines(w - 2, h - 3, &peer_state()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 has room for the whole txid and address, untruncated. + let wide = render(200, 60, &peer_state()); + assert!(wide.contains(TXID), "200x60 truncated the txid:\n{wide}"); + assert!(wide.contains(ADDR), "200x60 truncated the address:\n{wide}"); +} + +#[test] +fn peer_payments_columns_drop_before_they_wrap() { + // 80 columns is the floor, but a narrow terminal must still produce rows + // that never overrun the pane: trailing columns are dropped, not wrapped. + for w in 20u16..=200 { + for line in peer_payments_lines(w, 21, &peer_state()) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + for line in peer_payments_lines( + w, + 21, + &PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + }, + ) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "empty state width {w}: {line:?}"); + } + } +} + +#[test] +fn wallets_settings_menu_offers_the_peer_payments_row() { + let st = WalletMenuState { + transfers: 3, + peer: "lance".into(), + peer_payments: Some(3), + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("lance"), "row does not name the peer: {row:?}"); + assert!(row.contains('p'), "row does not name its key: {row:?}"); + // The wallet's own transfer list keeps its F6 row; it is retitled so the + // two histories cannot be mistaken for each other. + assert!( + body.lines().any(|l| l.contains("transfers")), + "wallet transfer row lost:\n{body}" + ); + + // No friend selected: the row is dim and offers no key that would do + // nothing. + let st = WalletMenuState { + peer: String::new(), + peer_payments: None, + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("no friend"), "{row:?}"); + + // A friend with no payment rows is the empty state, not an error. + let st = WalletMenuState { + peer: "lance".into(), + peer_payments: Some(0), + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("no history"), "{row:?}"); +} + +/// The F9 menu state with a healthy wallet, as `tests/tui_spec.rs` builds it. +fn menu_state_defaults() -> WalletMenuState { + WalletMenuState { + configured: true, + connected: true, + wallet_error: None, + receive_addr: ADDR.into(), + balance: "0.250000000000".into(), + transfers: 3, + child_state: "ready".into(), + child_source: "local node".into(), + child_error: None, + nickname: Some("lance".into()), + bio_set: true, + xmr_set: true, + me_fp: FP.into(), + peer: String::new(), + peer_payments: None, + } +} + +#[test] +fn peer_payments_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== PEER PAYMENTS {w}x{h} ====="); + print!("{}", render(w, h, &peer_state())); + println!("===== PEER PAYMENTS (empty) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + } + ) + ); + } +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 9672138..05cc668 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -6,11 +6,11 @@ use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ OutboxSummary, SlashCmd, WalletMenuState, alert_line, ascii_chrome, cell_width, - chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, draw_wallets_settings, - empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, main_header_line, - osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, roster_col_width, - short_send_reason, status_footer, wallets_settings_menu_lines, wallets_settings_menu_text, - wrap_invite, + chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, + draw_wallets_settings, empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, + main_header_line, osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, + roster_col_width, short_send_reason, status_footer, wallets_settings_menu_lines, + wallets_settings_menu_text, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; @@ -429,7 +429,14 @@ fn pending_row( } 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) + pending_row( + message_id, + body, + OutboxStatus::Queued, + attempts, + next_in, + now, + ) } fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry { @@ -555,7 +562,12 @@ fn delivery_markers_have_exercised_ascii_fallbacks() { in_msg(5, "epsilon"), ]; let pending = vec![ - failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now), + failed_row( + 1, + "alpha", + "connect peer.onion:80: connection timed out", + now, + ), queued_row(2, "beta", 1, 30, now), sending_row(3, "gamma", now), ]; @@ -841,9 +853,7 @@ fn rgb_tokens_resolve_to_palette_fg() { assert_eq!(t.highlight.fg, Some(Color::Rgb(232, 165, 75))); assert_eq!(t.highlight.bg, Some(Color::Rgb(48, 42, 28))); assert!( - t.highlight - .add_modifier - .contains(Modifier::BOLD), + t.highlight.add_modifier.contains(Modifier::BOLD), "RGB highlight must be bold" ); } @@ -906,7 +916,10 @@ fn alert_line_prefixes_when_no_color() { let _guard = std::env::var_os("NO_COLOR"); unsafe { std::env::set_var("NO_COLOR", "1") }; let line = alert_line("peer down", 80); - assert!(line.starts_with("! "), "expected '! ' prefix in None mode: {line:?}"); + assert!( + line.starts_with("! "), + "expected '! ' prefix in None mode: {line:?}" + ); unsafe { match _guard { Some(v) => std::env::set_var("NO_COLOR", v), @@ -938,6 +951,8 @@ fn menu_state() -> WalletMenuState { bio_set: true, xmr_set: true, me_fp: FP.into(), + peer: "lance".into(), + peer_payments: Some(3), } } @@ -978,8 +993,18 @@ fn wallets_settings_menu_lists_both_groups_and_every_key() { // F6 wallet screen's own keys, so the menu teaches the shortcuts it sits // beside instead of hiding them. for key in [ - "F6 s/x", "F6 p", "c copy F6 r", "F6 c", "F6 i", "F6 r", "F2", "/profile", "/backup", - "/restore", "/wipe", "/wipe-all", + "F6 s/x", + "F6 p", + "c copy F6 r", + "F6 c", + "F6 i", + "F6 r", + "F2", + "/profile", + "/backup", + "/restore", + "/wipe", + "/wipe-all", ] { assert!( body.contains(key), @@ -1072,7 +1097,10 @@ fn wallets_settings_menu_words_every_state() { }; let body = wallets_settings_menu_text(78, &stale); assert!(body.contains("configured · not connected"), "\n{body}"); - assert!(body.contains("wallet answering · chain not at tip"), "\n{body}"); + assert!( + body.contains("wallet answering · chain not at tip"), + "\n{body}" + ); let exited = WalletMenuState { child_state: "exited".into(), @@ -1136,7 +1164,11 @@ fn wallets_settings_menu_truncates_wide_values_in_cells() { // contract. let ascii = fit_cells("abcdefghij", 8); assert!(cell_width(&ascii) <= 8, "{ascii:?}"); - assert!(ascii.starts_with("abcdef"), "{ascii:?}"); + // Either chrome: ASCII cuts at 5 cells and closes with `...`, unicode cuts at + // 6 and closes with `…`, and both are 8 cells. Asserting `"abcdef"` here made + // this test depend on another test's in-flight `ONIONWIRE_ASCII` mutation + // (the suite mutates env vars without a global lock), so it flaked. + assert!(ascii.starts_with("abcde"), "{ascii:?}"); assert_eq!(cell_width("名"), 2); assert_eq!(cell_width("abc"), 3); } @@ -1255,6 +1287,9 @@ fn osc52_copy_sequence_is_a_base64_clipboard_write() { #[test] fn slash_settings_is_the_menu() { assert!(matches!(parse_cmd("/settings"), Some(SlashCmd::Settings))); - assert!(matches!(parse_cmd(" /settings "), Some(SlashCmd::Settings))); + assert!(matches!( + parse_cmd(" /settings "), + Some(SlashCmd::Settings) + )); assert!(parse_cmd("/settings now").is_none()); } From c3116eb19eda8fbd20911d8d86a04cc0b1f23b69 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 18 Sep 2026 23:54:07 -0400 Subject: [PATCH 04/94] fix(tui): invite payload gets a chrome-free region so mouse-copy is exact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mouse-selecting the invite copied the pane border: draw_share rendered the payload inside themed_block, which is Borders::ALL, so every wrapped row sat between a leading and a trailing glyph. OnionWire enables no mouse capture, so the terminal's own drag-select is the copy path and it picks up chrome. The payload now has its own region — flush at column 0, full frame width, no block, no title, no gutter on any row it occupies — with the block (title, fp, onion, copy hint) above it. Measured in cells, not chars. Also add C: OSC 52 hand the payload to the terminal clipboard (same sequence the F9 menu uses), with the key named on the screen and the mouse selection named as the fallback for terminals that block the sequence. Regression tests reconstruct the payload out of the rendered frame at 80x24, 120x40, 200x60 and 60x20 (they fail on base: the leading border column) and assert no payload row carries a border glyph. --- docs/TUI.md | 52 +++++++++++++ src/tui.rs | 96 +++++++++++++++++++++--- tests/tui_chrome.rs | 173 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 308 insertions(+), 13 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 89af4a0..ee82596 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -829,3 +829,55 @@ pane can drop the fingerprint without changing the row's meaning). `chars().count()`. The roster row spends its budget on the name first, then the `stale` word, then whatever is left on a fingerprint prefix — a 22-cell pane reads `bob-the-sta… stale`, not `… bbbbbbbb… stale`. + +## Invite screen: the payload region (mouse-copy) + +OnionWire never turns on mouse capture (`grep -rn EnableMouseCapture src/` is +empty), so sharing an invite means the terminal's own drag-select. A drag copies +every cell it crosses — and `draw_share` used to render the payload inside +`themed_block("(o) invite")`, which is `Borders::ALL`: every payload row sat +between `│` at column 0 and `│` at the last column, so the pasted string carried +border glyphs. + +The payload now gets its own region: **flush at column 0, full frame width, no +block, no title, no gutter on any row it occupies**. Everything that is not the +payload — why it exists, `fp`, `onion`, the copy key — lives in the bordered +block *above* it. The layout is `Layout::vertical([Length(body + 2), Min(0)])`, +so the chrome block grows with its own content and the payload always starts on +the row after its bottom border. + +``` +===== draw_share (real) 80x24 ===== +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│select the link below with the mouse, or press C to copy │ +└──────────────────────────────────────────────────────────────────────────────┘ +onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: +o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: +spk=0101010101010101010101010101010101010101010101010101010101010101: +sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e054 +01b0af934cefea617f71466f406af4bef956847200a8e915190b +``` + +At 120x40 and 200x60 `fp` and `onion` share one row (the block is one line +shorter); the payload region is unchanged. `wrap_invite` still breaks on `:`, so +joining the payload rows (trailing pad cells aside) is the payload byte for byte. +`tests/tui_chrome.rs` renders `draw_share` at 80x24, 120x40, 200x60 and 60x20 and +asserts exactly that, and that no row carrying payload carries `│`, `|`, `┃`, +`+`, `-` or `┄`. + +### `C` — the explicit copy affordance + +`C` on the invite screen writes the payload to the terminal's own clipboard with +OSC 52 (`osc52_copy_sequence`, the same sequence the F9 menu uses for the receive +address — no crate, no clipboard daemon, works over SSH). A terminal that does +not implement OSC 52 ignores the sequence, so the screen names the mouse +selection too; the line reads `select the link below with the mouse, or press C +to copy` whenever the block is wide enough, and `press C to copy, or select the +link below` otherwise. `?` lists the key as `F2 share invite (C copies it)`. + +The copy has no transient confirmation of its own: `draw_share` takes only the +payload, and `status_note` is not rendered on this screen. The mouse remains the +path that always works. diff --git a/src/tui.rs b/src/tui.rs index 42e75bb..fa51df4 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -533,7 +533,7 @@ 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 (C copies it)\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ @@ -1513,11 +1513,15 @@ impl App { } _ => {} }, - Screen::Share { .. } => { - if key.code == KeyCode::Esc { - self.screen = Screen::Main; + Screen::Share { .. } => match key.code { + KeyCode::Esc => self.screen = Screen::Main, + KeyCode::Char('c') | KeyCode::Char('C') + if !key.modifiers.contains(KeyModifiers::CONTROL) => + { + self.copy_invite(); } - } + _ => {} + }, Screen::Paste { buf, err } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => { @@ -1958,6 +1962,26 @@ impl App { }); } + /// `C` on the invite screen: the same OSC 52 handoff as the receive address, + /// so a terminal that blocks the write still leaves the mouse selection as + /// the way out. The payload never touches a file. + fn copy_invite(&mut self) { + let payload = match &self.screen { + Screen::Share { payload } => payload.clone(), + _ => return, + }; + let seq = osc52_copy_sequence(&payload); + let wrote = { + let mut out = io::stdout(); + out.write_all(seq.as_bytes()).is_ok() && out.flush().is_ok() + }; + self.status_note = Some(if wrote { + "copied invite".into() + } else { + "could not write the clipboard sequence".into() + }); + } + /// The core's pay/tip readiness guard, refused before any dial when the /// wallet is unconfigured, view-only (for a tip), or not answering. `true` /// when the send may proceed; the reason is already in the status note when @@ -3077,23 +3101,71 @@ fn themed_block(title: &str) -> Block<'_> { .title_style(style_accent().add_modifier(Modifier::BOLD)) } +/// The invite screen: chrome above the payload, nothing beside it. +/// +/// Sharing is a copy job, and OnionWire never turns on mouse capture — no +/// `EnableMouseCapture` anywhere in `src/` — so the terminal's own drag-select +/// is what copies an invite. A drag copies every cell it crosses, pane borders +/// included, so a bordered pane around the payload splices `│` into the string +/// the user pastes. The payload therefore gets its own region: flush at column +/// 0, the full frame width, no block, no title, no gutter on any row it +/// occupies. The title, the identity lines and the copy key sit in a bordered +/// block *above* it, and `wrap_invite` breaks on `:` so the payload rows join +/// back to the payload byte for byte +/// (`tests/tui_chrome.rs::share_payload_rebuilds_from_the_frame_at_80x24_and_120x40`). pub fn draw_share(f: &mut Frame, payload: &str) { let (fp, onion) = match qr::decode(payload) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; - let inner = f.area().width.saturating_sub(2) as usize; - let invite = wrap_invite(payload, inner.max(1)); - let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" - ); + let area = f.area(); + let body = share_body_lines(&fp, &onion, area.width.saturating_sub(2) as usize); + // Border top + body + border bottom. The payload region below gets no + // block: it is the selection, so nothing may sit beside it. + let header_h = (body.len() as u16).saturating_add(2).min(area.height); + let rows = Layout::vertical([Constraint::Length(header_h), Constraint::Min(0)]).split(area); f.render_widget( Paragraph::new(body) .style(style_text()) - .wrap(Wrap { trim: false }) .block(themed_block("(o) invite")), - f.area(), + rows[0], ); + + if rows[1].height == 0 { + return; + } + // Flush at column 0, full frame width, one wrapped row per payload row. + let wrapped = wrap_invite(payload, rows[1].width as usize); + f.render_widget(Paragraph::new(wrapped).style(style_text()), rows[1]); +} + +/// Everything about the invite that is not the invite: why it exists, whose it +/// is, and how to copy it. All of it lives in the bordered block *above* the +/// payload, so no row of the payload region carries chrome. +fn share_body_lines(fp: &str, onion: &str, inner: usize) -> Vec> { + let identity = format!("fp {fp} onion {onion}"); + let mut lines = vec![Line::from(fit_cells( + "give this string to a friend; they F3 paste it", + inner, + ))]; + if cell_width(&identity) <= inner { + lines.push(Line::from(identity)); + } else { + lines.push(Line::from(fit_cells(&format!("fp {fp}"), inner))); + lines.push(Line::from(fit_cells(&format!("onion {onion}"), inner))); + } + // `C` is the escape hatch for terminals that block OSC 52; the mouse is the + // path that works everywhere, so both are named. + let copy_hint = if inner >= 48 { + "select the link below with the mouse, or press C to copy" + } else { + "press C to copy, or select the link below" + }; + lines.push(Line::from(Span::styled( + fit_cells(copy_hint, inner), + style_dim(), + ))); + lines } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index e4d7fb7..13bf224 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -7,6 +7,7 @@ use onionwire::tui::{ main_footer_hints, onion_glyph, pane_footer_hints, status_footer, status_footer_compact, status_footer_phased, tor_token, wordmark_banner, }; +use ratatui::buffer::Buffer; #[test] fn wordmark_banner_is_nonempty_and_fits_80() { @@ -338,7 +339,177 @@ fn share_screen_shows_invite_not_qr_at_80x24() { for ch in ['█', '▀', '▄'] { assert!( !screen.contains(ch), - "share screen still has QR block {ch:?}:\n{screen}" + "share screen still has QR block {ch:?}:\\n{screen}" ); } } + +// --------------------------------------------------------------------------- +// Mouse-copy: the invite must be selectable without chrome (card t_af8b509e) +// +// OnionWire never enables mouse capture (no `EnableMouseCapture` anywhere in +// `src/`), so the terminal's own drag-select is what copies an invite. A drag +// copies exactly the cells it crosses — including the `│` columns of any pane +// that spans the payload rows. The payload therefore has to live in a region +// no chrome crosses, and these tests reconstruct it out of the rendered frame +// the same way the terminal hands it to the clipboard. +// --------------------------------------------------------------------------- + +/// Every glyph a border can be drawn with, unicode chrome and `ASCII_BORDERS`. +const BORDER_GLYPHS: [char; 6] = ['│', '|', '┃', '+', '-', '┄']; + +fn share_frame(width: u16, height: u16, payload: &str) -> Buffer { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let backend = TestBackend::new(width, height); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, payload)).expect("draw"); + terminal.backend().buffer().clone() +} + +fn frame_row(buf: &Buffer, width: u16, y: u16) -> String { + (0..width).map(|x| buf[(x, y)].symbol()).collect() +} + +fn frame_text(buf: &Buffer, width: u16, height: u16) -> String { + (0..height) + .map(|y| frame_row(buf, width, y)) + .collect::>() + .join("\n") +} + +/// True when the row, read from column 0, is payload: the invite's own alphabet +/// and nothing else. A row that starts with a border cell, a space, or any +/// character the payload cannot contain is not a payload row — it is payload +/// with chrome in front of it, and a drag would copy that chrome. +fn row_is_payload(row: &str) -> bool { + let trimmed = row.trim_end(); + !trimmed.is_empty() + && trimmed + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '=' | '.')) +} + +/// The same row classification, but tolerant of a gutter: used to find the rows +/// that *carry* payload even when something else is drawn on them. +fn row_carries_payload(row: &str) -> bool { + row_is_payload(row.trim_matches([' ', '│', '|', '┃', '+', '-'])) +} + +#[test] +fn share_payload_rebuilds_from_the_frame_at_80x24_and_120x40() { + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60), (60, 20)] { + let buf = share_frame(w, h, &payload); + let rows: Vec = (0..h) + .map(|y| frame_row(&buf, w, y)) + .filter(|row| row_is_payload(row)) + .collect(); + assert!( + !rows.is_empty(), + "no chrome-free payload row at column 0 on the {w}x{h} share screen; \ + a mouse drag across the invite would copy the pane borders:\n{}", + frame_text(&buf, w, h) + ); + // Trailing cells are the frame's pad, not the payload; nothing else is + // removed — no gutter is allowed to be there in the first place. + let rebuilt: String = rows.iter().map(|r| r.trim_end()).collect(); + assert_eq!( + rebuilt, + payload, + "mouse-selecting the invite at {w}x{h} does not rebuild the payload:\n\ + got {rebuilt:?}\nwant {payload:?}\nframe:\n{}", + frame_text(&buf, w, h) + ); + } +} + +#[test] +fn share_payload_rows_carry_no_border_glyph() { + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60), (60, 20)] { + let buf = share_frame(w, h, &payload); + let mut carrying = 0; + for y in 0..h { + let row = frame_row(&buf, w, y); + if !row_carries_payload(&row) { + continue; + } + carrying += 1; + for glyph in BORDER_GLYPHS { + assert!( + !row.contains(glyph), + "row {y} carries invite payload AND the border glyph {glyph:?} \ + at {w}x{h}: {row:?}\nframe:\n{}", + frame_text(&buf, w, h) + ); + } + } + assert!( + carrying > 0, + "no payload rows found at {w}x{h}:\n{}", + frame_text(&buf, w, h) + ); + } +} + +/// (b) the explicit affordance: `C` hands the payload to the terminal's own +/// clipboard (OSC 52) and the screen names that key, so the escape sequence has +/// to carry the invite byte for byte and nothing else. +#[test] +fn share_copy_key_sequence_carries_the_payload_exactly() { + use onionwire::tui::osc52_copy_sequence; + + let payload = qr::encode( + &[7u8; 32], + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", + &[1u8; 32], + ) + .expect("encode"); + let seq = osc52_copy_sequence(&payload); + assert!(seq.starts_with("\u{1b}]52;c;"), "{seq:?}"); + assert!(seq.ends_with('\u{7}'), "{seq:?}"); + let b64 = &seq["\u{1b}]52;c;".len()..seq.len() - 1]; + assert_eq!(b64_decode(b64), payload.as_bytes()); + + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let buf = share_frame(w, h, &payload); + let screen = frame_text(&buf, w, h); + assert!( + screen.contains("press C") && screen.contains("copy"), + "the {w}x{h} share screen does not name the copy key:\n{screen}" + ); + } +} + +/// Minimal RFC 4648 decoder, so the copy path is checked end to end rather than +/// against a hardcoded string. +fn b64_decode(text: &str) -> Vec { + const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = Vec::new(); + let mut acc: u32 = 0; + let mut bits = 0; + for ch in text.chars().filter(|c| *c != '=') { + let v = ALPHABET.find(ch).expect("base64 alphabet") as u32; + acc = (acc << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + out +} From b8fefe9c18e7205b48ef8631d13d56b17b53c69f Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 00:31:42 -0400 Subject: [PATCH 05/94] tui: F9 works on the peer-payments screen, and frames dump the real footer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1 on the F9 `payments` row found two false affordances. 1. `footer_hints(Screen::PeerPayments)` prints `F9 menu`, and docs/TUI.md says F9 reopens the menu, but the `KeyCode::F(9)` arm opened it only from `Screen::Main`, so pressing F9 on the peer history did nothing. The function keys are now routed through one table, `function_key_for(screen, code)`, and the F9 arm no longer has the Main-only guard: it opens (or reopens) the menu from `Main`, `WalletsSettings` and `PeerPayments`. A screen that names a key has to answer it while it is open — that is what the table encodes, and `mod function_key_tests` locks it, including a test that reads the screen's own hint and asserts every `F` it names is answered there. 2. The PR's frame dumps passed `"Esc back up/down select ? help"` to `status_footer` by hand, so every dumped frame showed a footer the app never renders. `peer_payments_footer_hint()` is now the single source both `footer_hints` and the fixture read, and `peer_payments_frame_shows_the_shipped_footer` pins the dumped frame's last line to the shipped one. Also restores the rustfmt-only reflow of unrelated tests in `tests/tui_spec.rs` (`queued_row`, a `failed_row` call, `rgb_tokens_…`, `alert_line_…`), keeping this card's real edits there. Presentation only: no wire, store, session, send-path or `Node` change. --- docs/TUI.md | 6 ++ src/tui.rs | 189 ++++++++++++++++++++++++++++++++++-------- tests/tui_payments.rs | 19 ++++- tests/tui_spec.rs | 25 ++---- 4 files changed, 185 insertions(+), 54 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 943512d..83986ef 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -749,6 +749,12 @@ dumps the screen at 80x24, 120x40 and 200x60, populated and empty. - The focused row is marked with `>` **and** bold, so focus survives a monochrome terminal. `up`/`down` (or `k`/`j`) move it, `Esc` returns to the main screen, `F9` reopens the menu. +- `F9` is honoured **while this screen is open**, not only from the main screen: + the function-key table (`function_key_for`) answers it from `Main`, + `WalletsSettings` and `PeerPayments` alike, so the hint the screen prints + cannot be a no-op there. `peer_payments_footer_hint()` is the single place that + hint string is written, and the frame-dump fixture is driven from it — a dumped + frame cannot show a footer the app does not render. - The selected row's `tx` and `addr` are spelled out under the rows: a 64-hex txid is unusable truncated, and a 95-character base58 address is **wrapped** over two lines rather than clipped to a prefix. diff --git a/src/tui.rs b/src/tui.rs index 38f868a..6812a71 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1257,6 +1257,44 @@ enum WalletSetup { ImportPass { seed: Zeroizing, entry: PassphraseEntry }, } +/// A function key the TUI answers before the per-screen `match`; the screen's +/// own key handler never sees it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum FunctionKey { + Share, + Paste, + Rotate, + Who, + Wallet, + RotatePrekey, + OpenMenu, +} + +/// The function key `screen` answers, or `None` when the key belongs to the +/// per-screen handler. +/// +/// The function keys stay live on every screen that names one — in its footer +/// or in its body: a shortcut the user can read has to work while that screen +/// is open. +fn function_key_for(screen: &Screen, code: KeyCode) -> Option { + if !matches!( + screen, + Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. } + ) { + return None; + } + match code { + KeyCode::F(2) => Some(FunctionKey::Share), + KeyCode::F(3) => Some(FunctionKey::Paste), + KeyCode::F(4) => Some(FunctionKey::Rotate), + KeyCode::F(5) => Some(FunctionKey::Who), + KeyCode::F(6) => Some(FunctionKey::Wallet), + KeyCode::F(8) => Some(FunctionKey::RotatePrekey), + KeyCode::F(9) => Some(FunctionKey::OpenMenu), + _ => None, + } +} + impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; @@ -1345,52 +1383,36 @@ impl App { let mut payments_move = 0i32; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen - // too: that screen's whole point is naming the key that fires each row, - // so a key it names has to work while it is open. - if matches!( - self.screen, - Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. } - ) { - match key.code { - KeyCode::F(2) => { - self.open_share()?; - return Ok(None); - } - KeyCode::F(3) => { + // and the peer history too: the settings screen's whole point is naming + // the key that fires each row, and the history's footer names `F9 + // menu`, so a key a screen names has to work while it is open. + if let Some(fk) = function_key_for(&self.screen, key.code) { + match fk { + FunctionKey::Share => self.open_share()?, + FunctionKey::Paste => { self.screen = Screen::Paste { buf: String::new(), err: None, }; - return Ok(None); } - KeyCode::F(4) => { + FunctionKey::Rotate => { self.screen = Screen::Rotate { prompt: RotatePrompt::new(), }; - return Ok(None); } - KeyCode::F(5) => { - self.who_open = true; - return Ok(None); - } - KeyCode::F(6) => { - self.open_wallet()?; - return Ok(None); - } - KeyCode::F(8) => { + FunctionKey::Who => self.who_open = true, + FunctionKey::Wallet => self.open_wallet()?, + FunctionKey::RotatePrekey => { self.screen = Screen::RotatePrekey { prompt: RotatePrompt::new(), }; - return Ok(None); } - KeyCode::F(9) => { - if matches!(self.screen, Screen::Main) { - self.open_wallets_settings()?; - } - return Ok(None); - } - _ => {} + // One level above the screen it is pressed on: F9 from Main + // opens the menu, and from the menu or the peer history it + // reopens it rather than silently doing nothing. + FunctionKey::OpenMenu => self.open_wallets_settings()?, } + return Ok(None); } match &mut self.screen { @@ -2803,11 +2825,20 @@ match screen { Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => "Esc back c copy ? help", - Screen::PeerPayments { .. } => "Esc back up/down select F9 menu ? help", + Screen::PeerPayments { .. } => peer_payments_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } +/// The hint line the peer-payment-history screen prints. One source only: the +/// screen's frame tests build their fixture from this, so a dumped frame can +/// never show a footer the app does not render. +pub fn peer_payments_footer_hint() -> &'static str { + PEER_PAYMENTS_FOOTER_HINT +} + +const PEER_PAYMENTS_FOOTER_HINT: &str = "Esc back up/down select F9 menu ? help"; + fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { let block = block.borders(Borders::ALL); if ascii_chrome() { @@ -4105,6 +4136,98 @@ fn io_err(e: io::Error) -> String { e.to_string() } +#[cfg(test)] +mod function_key_tests { + use super::*; + + fn peer_payments_screen() -> Screen { + Screen::PeerPayments { + state: PeerPaymentsState::default(), + } + } + + /// The peer history's footer prints `F9 menu`, so F9 has to reach the menu + /// while that screen is open — not only from Main. + #[test] + fn f9_opens_the_menu_from_the_peer_payments_screen() { + assert_eq!( + function_key_for(&peer_payments_screen(), KeyCode::F(9)), + Some(FunctionKey::OpenMenu), + "the screen's footer names F9 but F9 does nothing there" + ); + } + + /// Copy and behaviour agree: every `F` the screen's own hint names must + /// be a key the screen answers. This is the test the defect class needs — + /// the hint string and the routing table are the two halves of the claim. + #[test] + fn every_function_key_named_by_the_peer_payments_hint_is_answered_there() { + let hint = peer_payments_footer_hint(); + let screen = peer_payments_screen(); + let mut named = 0; + for (at, _) in hint.match_indices('F') { + let digits: String = hint[at + 1..] + .chars() + .take_while(char::is_ascii_digit) + .collect(); + let Ok(number) = digits.parse::() else { + continue; + }; + named += 1; + assert!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + "hint names F{number} ({hint:?}) but the screen does not answer it" + ); + } + assert!(named > 0, "the hint names no function key: {hint:?}"); + } + + /// The menu screen names `c` and `Esc`, not the function keys, but it is + /// the screen the `payments` row came from — its own keys stay its own. + #[test] + fn function_keys_stay_live_on_the_wallets_settings_screen() { + let screen = Screen::WalletsSettings { + state: WalletMenuState::default(), + }; + for key in [ + KeyCode::F(2), + KeyCode::F(3), + KeyCode::F(4), + KeyCode::F(5), + KeyCode::F(6), + KeyCode::F(8), + KeyCode::F(9), + ] { + assert!( + function_key_for(&screen, key).is_some(), + "{key:?} is named on the menu but is not answered there" + ); + } + } + + /// A screen that names no function key keeps the key to itself: the + /// composer's `F`-less screens must not steal F-keys they never advertise. + #[test] + fn screens_that_name_no_function_key_do_not_answer_one() { + for screen in [ + Screen::Paste { + buf: String::new(), + err: None, + }, + Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }), + ] { + for key in [KeyCode::F(9), KeyCode::F(6)] { + assert!( + function_key_for(&screen, key).is_none(), + "{key:?} was answered on a screen that never names it" + ); + } + } + } +} + #[cfg(test)] mod passphrase_buffer_tests { use super::*; diff --git a/tests/tui_payments.rs b/tests/tui_payments.rs index c0e43ef..9b59667 100644 --- a/tests/tui_payments.rs +++ b/tests/tui_payments.rs @@ -12,7 +12,8 @@ use onionwire::Payment; use onionwire::tui::{ PeerPaymentRow, PeerPaymentsState, WalletMenuState, cell_width, draw_peer_payments, - peer_payments_lines, peer_payments_text, status_footer, wallets_settings_menu_text, + peer_payments_footer_hint, peer_payments_lines, peer_payments_text, status_footer, + wallets_settings_menu_text, }; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -59,7 +60,9 @@ fn peer_state() -> PeerPaymentsState { fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); - let footer = status_footer(w, FP, ONION, None, "Esc back up/down select ? help"); + // The same two calls the app makes, so a dumped frame can never show a + // footer (or a hint) the app does not render. + let footer = status_footer(w, FP, ONION, None, peer_payments_footer_hint()); terminal .draw(|f| draw_peer_payments(f, st, &footer)) .expect("draw"); @@ -74,6 +77,18 @@ fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String { screen } +#[test] +fn peer_payments_frame_shows_the_shipped_footer() { + let shipped = status_footer(80, FP, ONION, None, peer_payments_footer_hint()); + let frame = render(80, 24, &peer_state()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + #[test] fn peer_payments_lists_every_required_field() { let body = peer_payments_text(78, 21, &peer_state()); diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 05cc668..d6ab135 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -429,14 +429,7 @@ fn pending_row( } 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, - ) + pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now) } fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry { @@ -562,12 +555,7 @@ fn delivery_markers_have_exercised_ascii_fallbacks() { in_msg(5, "epsilon"), ]; let pending = vec![ - failed_row( - 1, - "alpha", - "connect peer.onion:80: connection timed out", - now, - ), + failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now), queued_row(2, "beta", 1, 30, now), sending_row(3, "gamma", now), ]; @@ -853,7 +841,9 @@ fn rgb_tokens_resolve_to_palette_fg() { assert_eq!(t.highlight.fg, Some(Color::Rgb(232, 165, 75))); assert_eq!(t.highlight.bg, Some(Color::Rgb(48, 42, 28))); assert!( - t.highlight.add_modifier.contains(Modifier::BOLD), + t.highlight + .add_modifier + .contains(Modifier::BOLD), "RGB highlight must be bold" ); } @@ -916,10 +906,7 @@ fn alert_line_prefixes_when_no_color() { let _guard = std::env::var_os("NO_COLOR"); unsafe { std::env::set_var("NO_COLOR", "1") }; let line = alert_line("peer down", 80); - assert!( - line.starts_with("! "), - "expected '! ' prefix in None mode: {line:?}" - ); + assert!(line.starts_with("! "), "expected '! ' prefix in None mode: {line:?}"); unsafe { match _guard { Some(v) => std::env::set_var("NO_COLOR", v), From e9b4156cf594c539c654419e06c647009fb97e3e Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 01:06:00 -0400 Subject: [PATCH 06/94] ci: re-trigger android-ci for cbe8890 (run 458 was cancelled after 19s) The merge commit cbe8890 got a green ci/test and ci/sdk, but its android-ci run (actions/runs/458) was cancelled by the runner 19 seconds in, which Forgejo records as a failure on the commit. Nothing in this commit changes the tree; it exists so the android job runs against the same content. From c1d13178b654724513d13e707fae51aec2f2fcbc Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 01:18:47 -0400 Subject: [PATCH 07/94] tui: settings-menu frame dumps use the footer the app renders MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The same defect as the peer-payments fixture, one screen over: after the clean-look chrome redesign (now merged) `App::draw` renders the F9 menu's one status line with `status_footer_phased` and the hint from `footer_hints`, while `tests/tui_spec.rs::render_menu` still built a phase-free `status_footer` from a hand-copied hint string — so every menu frame in the PR body showed a footer the app does not draw (no Tor phase). - `wallets_settings_footer_hint()` is now the single source for that hint, the way `peer_payments_footer_hint()` is for the history screen. - `render_menu` makes the app's own two calls, `TorPhase::Ready` for the healthy-wallet state the fixture describes. - `wallets_settings_menu_frame_shows_the_shipped_footer` pins the dumped frame's last line to the shipped one (RED first: the fixture's line read `TOR me:… Esc back c copy ? help`, the app's `✓ TOR ready me:…`). `cargo test --locked` 384 passed / 0 failed, clippy clean. --- src/tui.rs | 12 +++++++++++- tests/tui_spec.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/tui.rs b/src/tui.rs index 06fefd9..2cdb850 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -3162,7 +3162,7 @@ match screen { } Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", - Screen::WalletsSettings { .. } => "Esc back c copy ? help", + Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } @@ -3177,6 +3177,16 @@ pub fn peer_payments_footer_hint() -> &'static str { const PEER_PAYMENTS_FOOTER_HINT: &str = "Esc back up/down select F9 menu ? help"; +/// The hint line the WALLETS & SETTINGS menu prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: the menu's frame-dump fixture +/// must not hand-copy it (and must not pair it with the phase-free footer the +/// app stopped using when the chrome redesign landed). +pub fn wallets_settings_footer_hint() -> &'static str { + WALLETS_SETTINGS_FOOTER_HINT +} + +const WALLETS_SETTINGS_FOOTER_HINT: &str = "Esc back c copy ? help"; + fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { let block = block.borders(Borders::ALL); if ascii_chrome() { diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 0d810f8..8a13603 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -5,12 +5,13 @@ use onionwire::Message; use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ - OutboxSummary, SlashCmd, WalletMenuState, alert_line, ascii_chrome, cell_width, + OutboxSummary, SlashCmd, TorPhase, WalletMenuState, alert_line, ascii_chrome, cell_width, chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, draw_wallets_settings, empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, main_header_line, osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, - roster_col_width, short_send_reason, status_footer, wallets_settings_menu_lines, - wallets_settings_menu_text, wrap_invite, + roster_col_width, short_send_reason, status_footer, status_footer_phased, + wallets_settings_footer_hint, wallets_settings_menu_lines, wallets_settings_menu_text, + wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; @@ -954,13 +955,46 @@ fn menu_state() -> WalletMenuState { fn render_menu(w: u16, h: u16, st: &WalletMenuState) -> String { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); - let footer = status_footer(w, FP, ONION, None, "Esc back c copy ? help"); + // The app's own two calls for this screen (see `App::draw`): the phased + // footer with the hint `footer_hints` returns. A phase-free footer here + // would be a footer the app never renders. + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallets_settings_footer_hint(), + ); terminal .draw(|f| draw_wallets_settings(f, st, &footer)) .expect("draw"); screen_from(terminal.backend().buffer(), w, h) } +#[test] +fn wallets_settings_menu_frame_shows_the_shipped_footer() { + // The app renders this screen's one status line with `status_footer_phased` + // (the chrome redesign put the Tor phase in it) and the hint from + // `footer_hints`; the fixture has to do the same or every menu frame in the + // PR is a frame the app never draws. + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallets_settings_footer_hint(), + ); + let frame = render_menu(80, 24, &menu_state()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped menu frame's footer is not the one the app renders" + ); +} + #[test] fn wallets_settings_menu_lists_both_groups_and_every_key() { let body = wallets_settings_menu_text(78, &menu_state()); From 0acf89a0b432c035ba8db40b71d264c650dbe581 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 12:03:01 -0400 Subject: [PATCH 08/94] android: Start wallet no longer looks like a no-op while Cuprate launches Tapping Start held the SQLCipher mutex for the whole in-process Node::launch and blocked the UniFFI tokio worker, so wallet_status stayed off with no error. Drop the store lock until creds are needed, spawn_blocking the sync start, and show that Start is in flight. The APK still runs Cuprate testnet only; this does not add mainnet or prune. --- .../siriusdevops/onionwire/WireViewModel.kt | 44 ++++++++++++------- .../onionwire/ui/WalletChildStatusText.kt | 5 +++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 7 ++- .../onionwire/ui/WalletChildStatusTextTest.kt | 8 ++++ crates/onionwire-sdk/src/lib.rs | 20 +++++---- src/node.rs | 10 +++-- src/wallet_child.rs | 43 ++++++++++++++++-- 7 files changed, 103 insertions(+), 34 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 04097ed..bbabf37 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -40,6 +40,7 @@ import uniffi.onionwire_sdk.WalletChildStatus import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File +import java.util.concurrent.atomic.AtomicBoolean sealed interface Phase { /** No identity unlocked. Nothing Tor-related is running. */ @@ -618,6 +619,14 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private val _walletChildError = MutableStateFlow(null) val walletChildError: StateFlow = _walletChildError.asStateFlow() + /** + * Start is in flight. Core status stays `off` until Cuprate/`monerod` answers, + * so the screen must not wait on that snapshot to show that the tap landed. + */ + private val startInFlight = AtomicBoolean(false) + private val _walletChildStarting = MutableStateFlow(false) + val walletChildStarting: StateFlow = _walletChildStarting.asStateFlow() + /** The stored chain source + binary settings, for prefilling the editor. */ private val _chainSource = MutableStateFlow(null) val chainSource: StateFlow = _chainSource.asStateFlow() @@ -795,25 +804,28 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home) /** - * Spawns the child (and its daemon/SOCKS siblings) and returns what the core - * reached. - * - * The returned state is `connecting` at best on the first call — the wallet - * RPC does not answer the instant the process exists — and that is reported - * as-is. The spawn is synchronous inside the node and a `.onion` source - * waits up to 20s for its SOCKS listener, so this never runs on the main - * thread. + * Kick off start on [viewModelScope] so leaving the composition does not + * cancel Cuprate launch. Returns immediately; watch [walletChildStarting] + * and [walletChildError]. Core status stays `off` until the node answers. */ - suspend fun startWalletChild(): Result { + fun startWalletChild() { + if (!startInFlight.compareAndSet(false, true)) return + _walletChildStarting.value = true _walletChildError.value = null - val started = withContext(Dispatchers.IO) { - runCatching { requireWire().startWalletChild() } + viewModelScope.launch { + try { + val started = withContext(Dispatchers.IO) { + runCatching { requireWire().startWalletChild() } + } + started.fold( + onSuccess = { _walletChild.value = it }, + onFailure = { _walletChildError.value = it.message ?: it.toString() }, + ) + } finally { + startInFlight.set(false) + _walletChildStarting.value = false + } } - started.fold( - onSuccess = { _walletChild.value = it }, - onFailure = { _walletChildError.value = it.message ?: it.toString() }, - ) - return started } /** Stops the child and its siblings. Idempotent in the core. */ diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 247d91b..81befaf 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -303,6 +303,9 @@ const val ONION_NEEDS_ARTI_NOTICE: String = /** Shown while the first `wallet_status()` read is still in flight. */ const val READING_CHILD_NOTICE: String = "Reading the wallet child status…" +const val STARTING_CHILD_NOTICE: String = + "Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button." + /** * The caveat the on-device node is offered with, **before** Start. * @@ -388,8 +391,10 @@ fun startBlockedReason( bins: WalletChildBinaryPaths, input: WalletChildInput?, onionDaemon: Boolean = false, + starting: Boolean = false, ): String? = when { bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE + starting -> STARTING_CHILD_NOTICE input == null -> READING_CHILD_NOTICE input.running -> "The wallet child is already running." !input.configured -> "No chain source yet: a wallet child needs a daemon to dial." diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 3f54179..f8fcebe 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -74,6 +74,7 @@ fun WalletScreen( val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() val childError by vm.walletChildError.collectAsStateWithLifecycle() + val starting by vm.walletChildStarting.collectAsStateWithLifecycle() val chain by vm.chainSource.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // Resolved once per composition: the native library directory is fixed for @@ -259,7 +260,8 @@ fun WalletScreen( .onFailure { daemonError = it.message ?: it.toString() } } }, - onStart = { scope.launch { vm.startWalletChild() } }, + starting = starting, + onStart = { vm.startWalletChild() }, onStop = { scope.launch { vm.stopWalletChild() } }, ) @@ -616,6 +618,7 @@ private fun WalletChildCard( onSaveDaemon: () -> Unit, onReceiveOnly: () -> Unit, onInProcessNode: () -> Unit, + starting: Boolean = false, onStart: () -> Unit, onStop: () -> Unit, ) { @@ -626,7 +629,7 @@ private fun WalletChildCard( // read comes back: the warning and the storage line must not wait for the // poller, or the user would press Start having seen neither. val inProcess = input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE - val startWhy = startBlockedReason(bins, input, onionDaemon) + val startWhy = startBlockedReason(bins, input, onionDaemon, starting) ?: if (inProcess) chainStorageBlockedReason(nodeFreeBytes) else null val stopWhy = stopBlockedReason(input) diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index 0ad32b9..ddd412f 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -183,6 +183,14 @@ class WalletChildStatusTextTest { assertNull(startBlockedReason(bundled, input("off"))) } + @Test + fun start_is_blocked_while_start_is_in_flight() { + assertEquals( + STARTING_CHILD_NOTICE, + startBlockedReason(bundled, input("off"), starting = true), + ) + } + @Test fun start_is_allowed_again_after_the_child_exited() { assertNull( diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 24bc2fb..ef014e3 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -609,7 +609,10 @@ impl Wire { /// /// The spawn itself is synchronous inside the node: argv is built, the /// process is spawned, and a `.onion` source waits up to 20s for the SOCKS - /// listener. Call it off the main thread, like `send_tip`. + /// listener. An in-process Cuprate launch is the same shape and can take + /// much longer. That work runs on `spawn_blocking` so it does not stall the + /// UniFFI tokio worker (Android: a blocked worker is a Start tap that never + /// returns). /// /// Idempotent: a live child is reported, not respawned. Fails with /// `WireError.Failed` when no chain source is configured @@ -621,7 +624,11 @@ impl Wire { /// and call [`Wire::wallet_status`] (or start again) for the later states. pub async fn start_wallet_child(&self) -> WResult { let node = self.node()?; - node.start_wallet_child().map_err(WireError::new)?; + let blocking = node.clone(); + tokio::task::spawn_blocking(move || blocking.start_wallet_child()) + .await + .map_err(|e| WireError::new(format!("start wallet child join: {e}")))? + .map_err(WireError::new)?; let source = node.wallet_child_config().source; Ok(child_status(node.wallet_child_refresh().await, &source)) } @@ -1337,11 +1344,7 @@ mod tests { Some("sending") ); assert_eq!( - delivery_of( - "out", - Some(OutboxStatus::Failed("no route".into())) - ) - .as_deref(), + delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), Some("failed: no route") ); } @@ -1492,8 +1495,7 @@ mod tests { #[test] fn wallet_recent_transfers_on_stopped_handle_is_stopped_error() { - let err = - block_on(stopped_wire().wallet_recent_transfers(8)).expect_err("must fail"); + let err = block_on(stopped_wire().wallet_recent_transfers(8)).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } diff --git a/src/node.rs b/src/node.rs index 5e2f18f..3ce2edd 100644 --- a/src/node.rs +++ b/src/node.rs @@ -617,10 +617,12 @@ impl Node { cfg.build(self.home.join("wallet")) .map_err(|e| e.to_string())?, ); - let client = { - let store = self.store.lock().map_err(|e| e.to_string())?; - child.start(&store).map_err(|e| e.to_string())? - }; + // Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status` + // also locks the store, and a blocked poller is how Android Start looks + // like it did nothing. + let client = child + .start_unlocking_store(&self.store) + .map_err(|e| e.to_string())?; let Some(client) = client else { return Err("chain source is receive-only — nothing to start".into()); }; diff --git a/src/wallet_child.rs b/src/wallet_child.rs index d8cce49..37fc404 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -435,13 +435,36 @@ impl WalletChild { /// what gates every spawn: the SOCKS child, like the wallet child, is only /// reachable through an unlocked store. pub fn start(&self, store: &Store) -> Result> { + self.start_with_creds(|| self.creds(store)) + } + + /// Same as [`WalletChild::start`], but the store mutex is taken only for + /// the generated RPC creds — not across chain-daemon launch. + /// + /// Cuprate's `Node::launch` (and a slow `monerod`) can run for a long time. + /// Holding SQLCipher for that whole window freezes every `wallet_status` + /// poll, which on Android makes **Start** look like a no-op: the button + /// fires, status stays `off`, no error. + pub fn start_unlocking_store(&self, store: &Mutex) -> Result> { + self.start_with_creds(|| { + let guard = store + .lock() + .map_err(|e| ChildError(format!("store lock: {e}")))?; + self.creds(&guard) + }) + } + + fn start_with_creds( + &self, + creds: impl FnOnce() -> Result<(String, Zeroizing)>, + ) -> Result> { if !self.is_enabled() { return Ok(None); } if self.running() { return Err(ChildError("wallet child already running".into())); } - match self.start_children(store) { + match self.start_children(creds) { Ok(client) => Ok(client), Err(e) => { // A failure after the SOCKS child came up must not leave the @@ -452,7 +475,10 @@ impl WalletChild { } } - fn start_children(&self, store: &Store) -> Result> { + fn start_children( + &self, + creds: impl FnOnce() -> Result<(String, Zeroizing)>, + ) -> Result> { // Local chain source: own the daemon first, so the wallet child has // something to dial. Either a spawned `monerod` or the in-process // Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so @@ -485,7 +511,10 @@ impl WalletChild { _ => None, }; - let (user, pass) = self.creds(store)?; + // Creds are the only store read. Callers that pass + // `start_unlocking_store` take the mutex here, after the chain daemon + // is already up, so a long Cuprate launch does not freeze SQLCipher. + let (user, pass) = creds()?; let port = Self::pick_port()?; let login = format!("{user}:{}", pass.as_str()); let daemon = Self::daemon_address(&self.source); @@ -1135,6 +1164,14 @@ mod tests { ); } + #[test] + fn start_unlocking_store_is_the_same_as_start_for_receive_only() { + let dir = tmp_dir("none-unlock"); + let store = std::sync::Mutex::new(open_store(&dir)); + let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap(); + assert!(child.start_unlocking_store(&store).unwrap().is_none()); + } + /// A live listener for the readiness gate to dial. `arti proxy -p ` /// binds localhost only, so 127.0.0.1 is exactly what the gate probes. fn held_loopback_port() -> (std::net::TcpListener, u16) { From 5080652e3bb717f404e745681a91e41b5acd5129 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 12:54:35 -0400 Subject: [PATCH 09/94] feat(wallet): mainnet pruned and full on-device chain modes Cuprate in-process and TUI keys 1/2/3 pick mainnet pruned, mainnet full, or experimental testnet. Datadirs are split so a prune store cannot mix with a full one. Android storage floors scale with the choice. Cuprate remains pre-production; mainnet is unvalidated. --- .../siriusdevops/onionwire/WireViewModel.kt | 18 ++- .../onionwire/ui/WalletChildStatusText.kt | 58 ++++++--- .../siriusdevops/onionwire/ui/WalletScreen.kt | 40 ++++-- .../onionwire/ui/WalletChildStatusTextTest.kt | 29 ++++- crates/onionwire-sdk/src/lib.rs | 117 +++++++++++++++--- src/cuprate.rs | 37 ++++-- src/node.rs | 30 ++++- src/tui.rs | 19 ++- src/wallet.rs | 53 +++++++- src/wallet_child.rs | 67 ++++++++-- tests/wallet.rs | 6 +- 11 files changed, 397 insertions(+), 77 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index bbabf37..1efd980 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -724,6 +724,8 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { // an onion daemon outright while no `arti` is bundled. artiBin = expectedArtiPath(), walletFilename = WalletChildBinaries.WALLET_FILENAME, + mainnet = false, + prune = false, ), ) } @@ -752,6 +754,8 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { walletRpcBin = bins.walletRpc.orEmpty(), artiBin = expectedArtiPath(), walletFilename = WalletChildBinaries.WALLET_FILENAME, + mainnet = false, + prune = false, ), ) } @@ -767,12 +771,14 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { * is what launches the node *and* the wallet child (one call in the core). * * `monerodDatadir` is left empty on purpose: the SDK resolves that to - * `$ONIONWIRE_HOME/chain`, the same per-identity directory a spawned `monerod` - * would use, so Kotlin never invents an absolute path. `monero-wallet-rpc` is - * still required — Cuprate has no wallet layer, so the subprocess stays, and the - * core rejects a config without it. + * `$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from + * [mainnet] and [prune], so Kotlin never invents an absolute path. */ - suspend fun setInProcessCuprate(bins: WalletChildBinaryPaths): Result = + suspend fun setInProcessCuprate( + bins: WalletChildBinaryPaths, + mainnet: Boolean, + prune: Boolean, + ): Result = withContext(Dispatchers.IO) { runCatching { requireWire().setChainSource( @@ -787,6 +793,8 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { // clearnet, so the core never spawns the SOCKS child. artiBin = expectedArtiPath(), walletFilename = WalletChildBinaries.WALLET_FILENAME, + mainnet = mainnet, + prune = prune, ), ) } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 81befaf..57ee94b 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -318,9 +318,8 @@ const val STARTING_CHILD_NOTICE: String = */ const val CUPRATE_PREPRODUCTION_WARNING: String = "On-device node is Cuprate, which is pre-production: its own user book says do NOT use " + - "cuprated for any serious purposes, it runs testnet only here (mainnet is unvalidated), " + - "and its monerod RPC parity is incomplete (Cuprate issue #278). Try the in-process " + - "path; do not hold funds on it." + "cuprated for any serious purposes, mainnet is unvalidated, and its monerod RPC parity " + + "is incomplete (Cuprate issue #278). Try the in-process path; do not hold funds on it." /** * This build was compiled without the `cuprate-daemon` feature, so the stored @@ -342,18 +341,36 @@ const val CUPRATE_NOT_IN_BUILD_NOTICE: String = * measured honestly is the free space on the filesystem the fjall store grows * into, and the device can be told when that is not enough. */ -const val CHAIN_FREE_SPACE_FLOOR_BYTES: Long = 3L * 1024 * 1024 * 1024 +const val CHAIN_TESTNET_FLOOR_BYTES: Long = 3L * 1024 * 1024 * 1024 +const val CHAIN_MAINNET_PRUNED_FLOOR_BYTES: Long = 64L * 1024 * 1024 * 1024 +const val CHAIN_MAINNET_FULL_FLOOR_BYTES: Long = 280L * 1024 * 1024 * 1024 + +/** Testnet floor, kept so existing tests still name one constant. */ +const val CHAIN_FREE_SPACE_FLOOR_BYTES: Long = CHAIN_TESTNET_FLOOR_BYTES + +fun chainStorageFloorBytes(mainnet: Boolean, prune: Boolean): Long = when { + !mainnet -> CHAIN_TESTNET_FLOOR_BYTES + prune -> CHAIN_MAINNET_PRUNED_FLOOR_BYTES + else -> CHAIN_MAINNET_FULL_FLOOR_BYTES +} /** * What the chain store costs, in the user's terms: the free space this device * actually has, and what the node does *not* tell us. */ -fun chainStorageLine(freeBytes: Long?): String = when { - freeBytes == null -> - "chain store: free space on this device could not be read." - else -> - "chain store: ${formatBytes(freeBytes)} free on this device — a synced testnet store " + - "grows into it. The node reports no size estimate of its own." +fun chainStorageLine(freeBytes: Long?, mainnet: Boolean = false, prune: Boolean = false): String { + val kind = when { + !mainnet -> "a synced testnet store" + prune -> "a pruned mainnet store (tens of GiB)" + else -> "a full mainnet store (hundreds of GiB)" + } + return when { + freeBytes == null -> + "chain store: free space on this device could not be read." + else -> + "chain store: ${formatBytes(freeBytes)} free on this device — $kind " + + "grows into it. The node reports no size estimate of its own." + } } /** @@ -361,13 +378,20 @@ fun chainStorageLine(freeBytes: Long?): String = when { * may. Fail-closed on an unreadable filesystem: an unknown free space is not * reported as enough. */ -fun chainStorageBlockedReason(freeBytes: Long?): String? = when { - freeBytes == null -> - "Free space on the chain store's filesystem could not be read, so it is not known to fit." - freeBytes < CHAIN_FREE_SPACE_FLOOR_BYTES -> - "Not enough space for the chain store: ${formatBytes(freeBytes)} free, and the " + - "on-device node needs at least ${formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES)}." - else -> null +fun chainStorageBlockedReason( + freeBytes: Long?, + mainnet: Boolean = false, + prune: Boolean = false, +): String? { + val floor = chainStorageFloorBytes(mainnet, prune) + return when { + freeBytes == null -> + "Free space on the chain store's filesystem could not be read, so it is not known to fit." + freeBytes < floor -> + "Not enough space for the chain store: ${formatBytes(freeBytes)} free, and the " + + "on-device node needs at least ${formatBytes(floor)}." + else -> null + } } /** diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index f8fcebe..e29576c 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -253,10 +253,10 @@ fun WalletScreen( .onFailure { daemonError = it.message ?: it.toString() } } }, - onInProcessNode = { + onInProcessNode = { mainnet, prune -> daemonError = null scope.launch { - vm.setInProcessCuprate(bins) + vm.setInProcessCuprate(bins, mainnet, prune) .onFailure { daemonError = it.message ?: it.toString() } } }, @@ -617,7 +617,7 @@ private fun WalletChildCard( onDaemonText: (String) -> Unit, onSaveDaemon: () -> Unit, onReceiveOnly: () -> Unit, - onInProcessNode: () -> Unit, + onInProcessNode: (mainnet: Boolean, prune: Boolean) -> Unit, starting: Boolean = false, onStart: () -> Unit, onStop: () -> Unit, @@ -630,7 +630,15 @@ private fun WalletChildCard( // poller, or the user would press Start having seen neither. val inProcess = input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE val startWhy = startBlockedReason(bins, input, onionDaemon, starting) - ?: if (inProcess) chainStorageBlockedReason(nodeFreeBytes) else null + ?: if (inProcess) { + chainStorageBlockedReason( + nodeFreeBytes, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ) + } else { + null + } val stopWhy = stopBlockedReason(input) Card( @@ -731,11 +739,25 @@ private fun WalletChildCard( // reads before Start. Spacer(Modifier.height(8.dp)) OutlinedButton( - onClick = onInProcessNode, + onClick = { onInProcessNode(true, true) }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-chain-mainnet-pruned"), + ) { Text("Mainnet pruned") } + Spacer(Modifier.height(4.dp)) + OutlinedButton( + onClick = { onInProcessNode(true, false) }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-chain-mainnet-full"), + ) { Text("Mainnet full") } + Spacer(Modifier.height(4.dp)) + OutlinedButton( + onClick = { onInProcessNode(false, false) }, modifier = Modifier .fillMaxWidth() .testTag("wallet-chain-in-process"), - ) { Text("On-device node (Cuprate)") } + ) { Text("Testnet (experimental)") } if (inProcess) { Spacer(Modifier.height(8.dp)) @@ -749,7 +771,11 @@ private fun WalletChildCard( ) Spacer(Modifier.height(4.dp)) Text( - chainStorageLine(nodeFreeBytes), + chainStorageLine( + nodeFreeBytes, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index ddd412f..f6cec47 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -338,7 +338,7 @@ class WalletChildStatusTextTest { assertTrue("it names the software", warning.contains("Cuprate")) assertTrue("it quotes the user book", warning.contains("do NOT use cuprated")) assertTrue("it names the parity gap", warning.contains("Cuprate issue #278")) - assertTrue("it says testnet", warning.contains("testnet")) + assertTrue("it says mainnet is unvalidated", warning.contains("mainnet is unvalidated")) assertTrue("it is a sentence, not a glyph", warning.trim().endsWith(".")) assertTrue("it is long enough to be a sentence", warning.length > 80) } @@ -364,6 +364,33 @@ class WalletChildStatusTextTest { assertNull(chainStorageBlockedReason(64L * 1024 * 1024 * 1024)) } + @Test + fun mainnet_pruned_needs_more_than_testnet() { + val forty = 40L * 1024 * 1024 * 1024 + assertNull(chainStorageBlockedReason(forty, mainnet = false, prune = false)) + val why = chainStorageBlockedReason(forty, mainnet = true, prune = true) + assertNotNull(why) + assertTrue(why!!, why.contains("64.0 GiB")) + assertNull( + chainStorageBlockedReason( + CHAIN_MAINNET_PRUNED_FLOOR_BYTES, + mainnet = true, + prune = true, + ), + ) + } + + @Test + fun mainnet_full_needs_more_than_pruned() { + val why = chainStorageBlockedReason( + CHAIN_MAINNET_PRUNED_FLOOR_BYTES, + mainnet = true, + prune = false, + ) + assertNotNull(why) + assertTrue(why!!, why.contains("280.0 GiB")) + } + @Test fun the_storage_line_reports_the_measured_number() { val line = chainStorageLine(41L * 1024 * 1024 * 1024) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index ef014e3..247f284 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -34,7 +34,7 @@ use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::ChainSource; +use onionwire::wallet::{ChainNetwork, ChainSource}; use onionwire::wallet_child::{ChildConfig, WalletChildState}; uniffi::setup_scaffolding!(); @@ -742,20 +742,40 @@ fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { /// per-identity directory the core documents for a local chain — so a Kotlin /// caller never has to invent an absolute path. Every other kind uses exactly /// what it was given (or the core's own default), unchanged. +fn cuprate_chain_dir(home: &Path, mainnet: bool, prune: bool) -> PathBuf { + let name = match (mainnet, prune) { + (true, true) => "mainnet-pruned", + (true, false) => "mainnet-full", + (false, _) => "testnet", + }; + home.join("chain").join(name) +} + fn child_config(cfg: ChainConfig, home: &Path) -> ChildConfig { let source = match cfg.kind { ChainChoice::None => ChainSource::None, ChainChoice::Local => ChainSource::Local { monerod_bin: PathBuf::from(cfg.monerod_bin), datadir: PathBuf::from(cfg.monerod_datadir), + prune: cfg.prune, }, - ChainChoice::InProcessCuprate => ChainSource::InProcessCuprate { - datadir: if cfg.monerod_datadir.trim().is_empty() { - home.join("chain") + ChainChoice::InProcessCuprate => { + let network = if cfg.mainnet { + ChainNetwork::Mainnet } else { - PathBuf::from(cfg.monerod_datadir) - }, - }, + ChainNetwork::Testnet + }; + let prune = cfg.mainnet && cfg.prune; + ChainSource::InProcessCuprate { + datadir: if cfg.monerod_datadir.trim().is_empty() { + cuprate_chain_dir(home, cfg.mainnet, prune) + } else { + PathBuf::from(cfg.monerod_datadir) + }, + network, + prune, + } + } ChainChoice::Remote => ChainSource::Remote { host: cfg.host, port: cfg.port, @@ -769,32 +789,42 @@ fn child_config(cfg: ChainConfig, home: &Path) -> ChildConfig { } } -/// And back, for the Kotlin prefill. fn chain_config(cfg: &ChildConfig) -> ChainConfig { - let (kind, host, port, monerod_bin, monerod_datadir) = match &cfg.source { + let (kind, host, port, monerod_bin, monerod_datadir, mainnet, prune) = match &cfg.source { ChainSource::None => ( ChainChoice::None, String::new(), 0, String::new(), String::new(), + false, + false, ), ChainSource::Local { monerod_bin, datadir, + prune, } => ( ChainChoice::Local, String::new(), 0, monerod_bin.display().to_string(), datadir.display().to_string(), + true, + *prune, ), - ChainSource::InProcessCuprate { datadir } => ( + ChainSource::InProcessCuprate { + datadir, + network, + prune, + } => ( ChainChoice::InProcessCuprate, String::new(), 0, String::new(), datadir.display().to_string(), + matches!(network, ChainNetwork::Mainnet), + *prune, ), ChainSource::Remote { host, port } => ( ChainChoice::Remote, @@ -802,6 +832,8 @@ fn chain_config(cfg: &ChildConfig) -> ChainConfig { *port, String::new(), String::new(), + false, + false, ), }; ChainConfig { @@ -813,6 +845,8 @@ fn chain_config(cfg: &ChildConfig) -> ChainConfig { wallet_rpc_bin: cfg.wallet_rpc_bin.display().to_string(), arti_bin: cfg.arti_bin.display().to_string(), wallet_filename: cfg.wallet_filename.clone(), + mainnet, + prune, } } @@ -997,6 +1031,13 @@ pub struct ChainConfig { pub arti_bin: String, /// Wallet file name inside `$ONIONWIRE_HOME/wallet`. pub wallet_filename: String, + /// Cuprate / local `monerod`: mainnet when true, testnet when false. + /// Ignored for Remote and None. Old records without the field stay testnet. + pub mainnet: bool, + /// Cuprate / local `monerod`: prune the chain. Ignored for Remote and None. + /// Once a Cuprate store is pruned it cannot be un-pruned — we keep pruned + /// and full in separate datadirs. + pub prune: bool, } /// One snapshot of the app-owned wallet child. @@ -1713,6 +1754,8 @@ mod tests { wallet_rpc_bin: "/data/app/nativeLibraryDir/libmonerowalletrpc.so".to_string(), arti_bin: "/data/app/nativeLibraryDir/libarti.so".to_string(), wallet_filename: "wallet".to_string(), + mainnet: false, + prune: false, } } @@ -1726,10 +1769,49 @@ mod tests { assert_eq!( child.source, ChainSource::InProcessCuprate { - datadir: sdk_home().join("chain") + datadir: sdk_home().join("chain").join("testnet"), + network: ChainNetwork::Testnet, + prune: false, } ); - assert_eq!(child.source_label(), "in-process node"); + assert_eq!(child.source_label(), "in-process testnet"); + } + + #[test] + fn child_config_mainnet_pruned_uses_its_own_datadir() { + let mut req = request(ChainChoice::InProcessCuprate, ""); + req.mainnet = true; + req.prune = true; + let child = child_config(req, &sdk_home()); + assert_eq!( + child.source, + ChainSource::InProcessCuprate { + datadir: sdk_home().join("chain").join("mainnet-pruned"), + network: ChainNetwork::Mainnet, + prune: true, + } + ); + assert_eq!(child.source_label(), "in-process mainnet pruned"); + let back = chain_config(&child); + assert!(back.mainnet); + assert!(back.prune); + } + + #[test] + fn child_config_mainnet_full_uses_its_own_datadir() { + let mut req = request(ChainChoice::InProcessCuprate, ""); + req.mainnet = true; + req.prune = false; + let child = child_config(req, &sdk_home()); + assert_eq!( + child.source, + ChainSource::InProcessCuprate { + datadir: sdk_home().join("chain").join("mainnet-full"), + network: ChainNetwork::Mainnet, + prune: false, + } + ); + assert_eq!(child.source_label(), "in-process mainnet full"); } #[test] @@ -1739,7 +1821,9 @@ mod tests { assert_eq!( child.source, ChainSource::InProcessCuprate { - datadir: PathBuf::from(given) + datadir: PathBuf::from(given), + network: ChainNetwork::Testnet, + prune: false, } ); } @@ -1776,7 +1860,7 @@ mod tests { ChainChoice::InProcessCuprate => { assert_eq!( back.monerod_datadir, - sdk_home().join("chain").display().to_string() + sdk_home().join("chain").join("testnet").display().to_string() ); assert!( back.monerod_bin.is_empty(), @@ -1815,7 +1899,9 @@ mod tests { #[test] fn node_state_names_the_apps_own_chain_for_the_in_process_source() { let source = ChainSource::InProcessCuprate { - datadir: sdk_home().join("chain"), + datadir: sdk_home().join("chain").join("testnet"), + network: ChainNetwork::Testnet, + prune: false, }; let cases = [ (WalletChildState::Off, "off"), @@ -1844,6 +1930,7 @@ mod tests { ChainSource::Local { monerod_bin: PathBuf::from("monerod"), datadir: PathBuf::from("/chain"), + prune: false, }, ChainSource::Remote { host: "peer.onion".to_string(), diff --git a/src/cuprate.rs b/src/cuprate.rs index b6a4006..cf4aedf 100644 --- a/src/cuprate.rs +++ b/src/cuprate.rs @@ -60,8 +60,8 @@ mod imp { use std::path::Path; use std::sync::mpsc; + use cuprated::config::{resolve_max_memory, Config}; use cuprated::Node; - use cuprated::config::{Config, resolve_max_memory}; /// The network this daemon runs. Testnet, deliberately — see the module /// docs. Cuprate spells this `Testnet`. @@ -107,8 +107,13 @@ mod imp { /// Blocking this thread for the duration of the launch is the same thing /// the app already does for a `.onion` chain source's SOCKS readiness /// wait. - pub fn launch(datadir: &Path, port: u16) -> Result { - let text = config_toml(datadir, port); + pub fn launch( + datadir: &Path, + port: u16, + network: &str, + prune: bool, + ) -> Result { + let text = config_toml(datadir, port, network, prune); let (tx, rx) = mpsc::channel(); std::thread::Builder::new() .name("onionwire-cuprate".into()) @@ -193,10 +198,10 @@ mod imp { /// default silently standing in for the setting that was meant. /// /// No data directory is created here — the caller owns the 0700 wallet dir. - pub fn config_toml(datadir: &Path, port: u16) -> String { + pub fn config_toml(datadir: &Path, port: u16, network: &str, prune: bool) -> String { let datadir = datadir.display(); format!( - r#"network = "{NETWORK}" + r#"network = "{network}" offline = false fast_sync = true target_max_memory = {TARGET_MAX_MEMORY} @@ -209,6 +214,9 @@ cache_directory = "{datadir}/cache" [storage] reader_threads = {READER_THREADS} +[storage.blockchain] +prune = {prune} + # The unrestricted listener: this is the one the wallet child dials, and the one # with real numbers. The restricted listener is off — its metrics are # placeholders, and nothing in this app reads them. @@ -247,9 +255,13 @@ mode = "Auto" /// between revisions is a hard error, not a silently ignored setting. #[test] fn the_config_parses_into_this_revision() { - let mut config: Config = - toml::from_str(&config_toml(Path::new("/tmp/onionwire-chain"), 18081)) - .expect("the config must parse against the pinned cuprated revision"); + let mut config: Config = toml::from_str(&config_toml( + Path::new("/tmp/onionwire-chain"), + 18081, + "Testnet", + false, + )) + .expect("the config must parse against the pinned cuprated revision"); resolve_max_memory(&mut config).expect("target_max_memory is set, so nothing to probe"); assert_eq!(format!("{:?}", config.network), NETWORK); // The fjall store is Cuprate's, under the datadir it was given — @@ -278,7 +290,12 @@ mod imp { impl CuprateNode { /// Always fails: this build has no in-process daemon. - pub fn launch(_datadir: &Path, _port: u16) -> Result { + pub fn launch( + _datadir: &Path, + _port: u16, + _network: &str, + _prune: bool, + ) -> Result { Err(super::NO_FEATURE_MSG.into()) } @@ -295,4 +312,4 @@ mod imp { pub use imp::CuprateNode; #[cfg(feature = "cuprate-daemon")] -pub use imp::{NETWORK, config_toml}; +pub use imp::{config_toml, NETWORK}; diff --git a/src/node.rs b/src/node.rs index 3ce2edd..cbad028 100644 --- a/src/node.rs +++ b/src/node.rs @@ -29,7 +29,7 @@ use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; -use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus}; +use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; pub struct RotateResult { @@ -567,6 +567,10 @@ impl Node { // ----- the app-owned wallet child (`src/wallet_child.rs`) ---------------- + pub fn home(&self) -> &Path { + &self.home + } + /// The child settings this node would spawn with: the stored record, or the /// defaults (receive-only, binaries by name) when nothing was ever set. pub fn wallet_child_config(&self) -> ChildConfig { @@ -593,6 +597,30 @@ impl Node { Ok(()) } + /// Store an in-process Cuprate source. Datadirs are split so a pruned + /// mainnet store cannot mix with a full one (Cuprate cannot un-prune). + pub fn set_in_process_cuprate( + &self, + network: ChainNetwork, + prune: bool, + ) -> Result<(), String> { + let mut cfg = self.wallet_child_config(); + if cfg.wallet_rpc_bin.as_os_str().is_empty() { + cfg.wallet_rpc_bin = PathBuf::from("monero-wallet-rpc"); + } + let name = match (network, prune) { + (ChainNetwork::Mainnet, true) => "mainnet-pruned", + (ChainNetwork::Mainnet, false) => "mainnet-full", + (ChainNetwork::Testnet, _) => "testnet", + }; + cfg.source = ChainSource::InProcessCuprate { + datadir: self.home.join("chain").join(name), + network, + prune: matches!(network, ChainNetwork::Mainnet) && prune, + }; + self.set_wallet_child_config(&cfg) + } + /// Start the app-owned wallet child and point this node's wallet at it. /// /// Idempotent: a live wallet child is reported, not respawned. Spawning is diff --git a/src/tui.rs b/src/tui.rs index 0734015..a72d071 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -18,7 +18,7 @@ use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; -use crate::wallet::{self, ChainSource}; +use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -1669,6 +1669,9 @@ impl App { KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), + KeyCode::Char('1') => self.set_cuprate_chain(ChainNetwork::Mainnet, true), + KeyCode::Char('2') => self.set_cuprate_chain(ChainNetwork::Mainnet, false), + KeyCode::Char('3') => self.set_cuprate_chain(ChainNetwork::Testnet, false), KeyCode::Char('c') => { self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { typed: String::new(), @@ -2142,6 +2145,16 @@ impl App { self.status_note = Some(self.wallet_child_note()); } + fn set_cuprate_chain(&mut self, network: ChainNetwork, prune: bool) { + self.status_note = Some(match self.node.set_in_process_cuprate(network, prune) { + Ok(()) => format!( + "chain source: {}", + self.node.wallet_child_config().source.label() + ), + Err(e) => format!("chain source: {e}"), + }); + } + /// The child status line, or the copy that names what is missing. fn wallet_child_note(&mut self) -> String { let line = self.rt.block_on(self.node.wallet_child_refresh()).line(); @@ -3179,7 +3192,9 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "c create i import r qr s/x child Esc back ? help", + Screen::Wallet { .. } => { + "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { "Enter submit Esc cancel ? help" diff --git a/src/wallet.rs b/src/wallet.rs index 4430a2d..f404cea 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -19,6 +19,31 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} +/// Which Monero network an on-device daemon follows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChainNetwork { + Mainnet, + Testnet, +} + +impl ChainNetwork { + /// Cuprate TOML `network = "..."` spelling (`Mainnet` / `Testnet`). + pub fn cuprate_toml(self) -> &'static str { + match self { + Self::Mainnet => "Mainnet", + Self::Testnet => "Testnet", + } + } + + /// Directory segment so mainnet and testnet stores never share a fjall dir. + pub fn dir_name(self) -> &'static str { + match self { + Self::Mainnet => "mainnet", + Self::Testnet => "testnet", + } + } +} + /// The user's choice of where the Monero daemon lives. No default remote node /// is ever implied — every `Remote` is constructed from explicit user input. /// @@ -34,17 +59,21 @@ pub enum ChainSource { monerod_bin: PathBuf, /// Data directory for the local daemon. datadir: PathBuf, + /// `monerod --prune-blockchain`. Full node when false. + prune: bool, }, /// A chain daemon **inside this process** (Cuprate), with its chain in /// `datadir`. Nothing is spawned; the wallet child still dials loopback /// RPC, so this is a [`ChainSource::Local`] with a different owner. /// - /// Two consequences the UI has to state: the chain is on this device, and - /// the in-process daemon is **testnet-only** in this build (Cuprate is - /// pre-production and its mainnet RPC parity is unvalidated). + /// Cuprate is still pre-production: mainnet RPC parity is unvalidated. + /// The UI must say so. `network`/`prune` are the user's choice; old + /// stored records without those keys are testnet, unpruned. InProcessCuprate { /// Data directory for the daemon's chain database. datadir: PathBuf, + network: ChainNetwork, + prune: bool, }, /// A daemon address the user supplied. Trust follows the address. Remote { @@ -71,8 +100,22 @@ impl ChainSource { pub fn label(&self) -> String { match self { ChainSource::None => "receive-only".to_string(), - ChainSource::Local { .. } => "local node".to_string(), - ChainSource::InProcessCuprate { .. } => "in-process node".to_string(), + ChainSource::Local { prune: true, .. } => "local pruned node".to_string(), + ChainSource::Local { prune: false, .. } => "local full node".to_string(), + ChainSource::InProcessCuprate { + network: ChainNetwork::Mainnet, + prune: true, + .. + } => "in-process mainnet pruned".to_string(), + ChainSource::InProcessCuprate { + network: ChainNetwork::Mainnet, + prune: false, + .. + } => "in-process mainnet full".to_string(), + ChainSource::InProcessCuprate { + network: ChainNetwork::Testnet, + .. + } => "in-process testnet".to_string(), ChainSource::Remote { host, .. } if is_onion_host(host) => { "remote onion daemon".to_string() } diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 37fc404..8769ccb 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -39,7 +39,7 @@ use zeroize::Zeroizing; use crate::cuprate::CuprateNode; use crate::store::Store; -use crate::wallet::{self, ChainSource, Wallet}; +use crate::wallet::{self, ChainNetwork, ChainSource, Wallet}; /// `monerod` RPC port for a local chain source. Unrestricted RPC default; the /// wallet child is the only thing that dials it. @@ -355,7 +355,7 @@ impl WalletChild { /// for a remote source (their disk, not ours) and for receive-only. pub fn chain_datadir(source: &ChainSource) -> Option<&Path> { match source { - ChainSource::Local { datadir, .. } | ChainSource::InProcessCuprate { datadir } => { + ChainSource::Local { datadir, .. } | ChainSource::InProcessCuprate { datadir, .. } => { Some(datadir) } ChainSource::None | ChainSource::Remote { .. } => None, @@ -377,8 +377,8 @@ impl WalletChild { /// The exact argv used to spawn `monerod`. Single source of truth: `start` /// spawns this and the tests assert on it. - pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16) -> Vec { - vec![ + pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16, prune: bool) -> Vec { + let mut argv = vec![ bin.display().to_string(), "--non-interactive".into(), "--data-dir".into(), @@ -387,7 +387,11 @@ impl WalletChild { "127.0.0.1".into(), "--rpc-bind-port".into(), rpc_port.to_string(), - ] + ]; + if prune { + argv.push("--prune-blockchain".into()); + } + argv } /// The exact argv used to spawn `monero-wallet-rpc`. Digest login is @@ -487,9 +491,11 @@ impl WalletChild { ChainSource::Local { monerod_bin, datadir, + prune, } => { ensure_parent(datadir)?; - let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT); + let argv = + Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT, *prune); let child = spawn(&argv, "monerod")?; let mut guard = self .monerod @@ -497,7 +503,11 @@ impl WalletChild { .map_err(|e| ChildError(format!("monerod lock: {e}")))?; *guard = Some(child); } - ChainSource::InProcessCuprate { datadir } => self.start_in_process_daemon(datadir)?, + ChainSource::InProcessCuprate { + datadir, + network, + prune, + } => self.start_in_process_daemon(datadir, *network, *prune)?, ChainSource::None | ChainSource::Remote { .. } => {} } @@ -584,15 +594,25 @@ impl WalletChild { /// node answers), so this works from the TUI's blocking thread *and* from an /// SDK async context. It is the same shape as the SOCKS readiness wait /// above: no daemon, no wallet child. - fn start_in_process_daemon(&self, datadir: &Path) -> Result<()> { + fn start_in_process_daemon( + &self, + datadir: &Path, + network: ChainNetwork, + prune: bool, + ) -> Result<()> { // Feature first: in a build without it, a datadir complaint would be a // misleading answer to "why is there no daemon". if !crate::cuprate::available() { return Err(ChildError(crate::cuprate::NO_FEATURE_MSG.into())); } create_dir_700(datadir).map_err(|e| ChildError(format!("chain datadir: {e}")))?; - let node = CuprateNode::launch(datadir, DEFAULT_MONEROD_RPC_PORT) - .map_err(|e| ChildError(format!("in-process daemon: {e}")))?; + let node = CuprateNode::launch( + datadir, + DEFAULT_MONEROD_RPC_PORT, + network.cuprate_toml(), + prune, + ) + .map_err(|e| ChildError(format!("in-process daemon: {e}")))?; let mut guard = self .cuprate .lock() @@ -729,6 +749,7 @@ impl ChildConfig { ChainSource::Local { monerod_bin, datadir, + .. } => { if monerod_bin.as_os_str().is_empty() { return Err(ChildError("monerod path required for a local node".into())); @@ -739,7 +760,7 @@ impl ChildConfig { )); } } - ChainSource::InProcessCuprate { datadir } => { + ChainSource::InProcessCuprate { datadir, .. } => { if datadir.as_os_str().is_empty() { return Err(ChildError( "chain data dir required for an in-process daemon".into(), @@ -949,14 +970,22 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value { ChainSource::Local { monerod_bin, datadir, + prune, } => serde_json::json!({ "kind": "local", "monerod_bin": monerod_bin.display().to_string(), "datadir": datadir.display().to_string(), + "prune": prune, }), - ChainSource::InProcessCuprate { datadir } => serde_json::json!({ + ChainSource::InProcessCuprate { + datadir, + network, + prune, + } => serde_json::json!({ "kind": "cuprate", "datadir": datadir.display().to_string(), + "network": network.dir_name(), + "prune": prune, }), ChainSource::Remote { host, port } => serde_json::json!({ "kind": "remote", @@ -989,6 +1018,7 @@ fn source_from_json(value: &serde_json::Value) -> Result { Ok(ChainSource::Local { monerod_bin: PathBuf::from(monerod_bin), datadir: PathBuf::from(datadir), + prune: value.get("prune").and_then(|v| v.as_bool()).unwrap_or(false), }) } "cuprate" => { @@ -999,8 +1029,15 @@ fn source_from_json(value: &serde_json::Value) -> Result { .ok_or_else(|| { ChildError("stored in-process chain source has no data dir".into()) })?; + let network = match value.get("network").and_then(|v| v.as_str()) { + Some("mainnet") => ChainNetwork::Mainnet, + _ => ChainNetwork::Testnet, + }; + let prune = value.get("prune").and_then(|v| v.as_bool()).unwrap_or(false); Ok(ChainSource::InProcessCuprate { datadir: PathBuf::from(datadir), + network, + prune, }) } "remote" => { @@ -1144,6 +1181,7 @@ mod tests { ChainSource::Local { monerod_bin: monerod, datadir: dir.join("monerod-data"), + prune: false, } } @@ -1589,6 +1627,7 @@ mod tests { &PathBuf::from("/usr/bin/monerod"), &datadir, DEFAULT_MONEROD_RPC_PORT, + false, ); let pairs: Vec<(&str, &str)> = argv .windows(2) @@ -1748,6 +1787,8 @@ mod tests { fn in_process_source(dir: &Path) -> ChainSource { ChainSource::InProcessCuprate { datadir: dir.join("chain"), + network: ChainNetwork::Testnet, + prune: false, } } @@ -1855,6 +1896,8 @@ mod tests { let empty = ChildConfig { source: ChainSource::InProcessCuprate { datadir: PathBuf::new(), + network: ChainNetwork::Testnet, + prune: false, }, ..ChildConfig::default() }; diff --git a/tests/wallet.rs b/tests/wallet.rs index 26d7168..3007ab9 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1138,9 +1138,10 @@ fn chain_source_labels_name_what_the_child_dials() { ChainSource::Local { monerod_bin: PathBuf::from("/usr/bin/monerod"), datadir: PathBuf::from("/var/lib/onionwire"), + prune: false, } .label(), - "local node" + "local full node" ); assert_eq!( ChainSource::Remote { @@ -1226,6 +1227,7 @@ fn child_settings_round_trip_sealed_and_keep_the_creds() { local.source = ChainSource::Local { monerod_bin: PathBuf::new(), datadir: PathBuf::from("/var/lib/onionwire"), + prune: false, }; let err = local.validate().expect_err("a local node needs monerod"); assert!(err.to_string().contains("monerod path required"), "{err}"); @@ -1265,7 +1267,7 @@ async fn an_in_process_cuprate_node_answers_the_typed_daemon_client() { let addr = format!("127.0.0.1:{port}"); let budget = std::time::Duration::from_secs(5); - let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port) + let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port, "Testnet", false) .expect("launch the in-process testnet daemon"); // `launch` returns with the services started; the RPC listener can still be From 3868452a4a0fb26fdbdedbf1c97e8d6e4c610cb4 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 14:33:20 -0400 Subject: [PATCH 10/94] fix(android): tapping a Cuprate mode starts the node Selecting mainnet pruned only persisted ChainConfig, so the screen updated the storage line and nothing else. Store, then Start when the storage floor allows. Filled button is the stored choice. --- .../onionwire/ui/WalletChildStatusText.kt | 24 ++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 74 ++++++++++++++----- .../onionwire/ui/WalletChildStatusTextTest.kt | 26 +++++++ 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 57ee94b..ebbbd5d 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -394,6 +394,30 @@ fun chainStorageBlockedReason( } } +enum class CuprateMode { + MainnetPruned, + MainnetFull, + Testnet, +} + +fun selectedCuprateMode(inProcess: Boolean, mainnet: Boolean, prune: Boolean): CuprateMode? = + when { + !inProcess -> null + !mainnet -> CuprateMode.Testnet + prune -> CuprateMode.MainnetPruned + else -> CuprateMode.MainnetFull + } + +/** + * Tapping a mode used to only persist `ChainConfig`, which looked like a no-op + * besides the storage line. Start when the storage floor would allow Start and + * a launch is not already in flight. + */ +fun shouldStartAfterSelectingChain( + storageBlocked: String?, + starting: Boolean, +): Boolean = storageBlocked == null && !starting + /** * Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how * a store that needs 3 GiB ends up on a device with 2.8). diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index e29576c..a67d8de 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -258,6 +258,23 @@ fun WalletScreen( scope.launch { vm.setInProcessCuprate(bins, mainnet, prune) .onFailure { daemonError = it.message ?: it.toString() } + .onSuccess { + // The mode buttons used to only persist the choice, + // which read as a no-op besides the storage line. + // Start is still the core launch; tapping a mode + // fires it when the storage gate would allow Start. + if (shouldStartAfterSelectingChain( + chainStorageBlockedReason( + vm.chainFreeBytes(), + mainnet = mainnet, + prune = prune, + ), + starting = starting, + ) + ) { + vm.startWalletChild() + } + } } }, starting = starting, @@ -734,30 +751,34 @@ private fun WalletChildCard( ) { Text("Receive-only") } } - // The third chain source. Never a default: selecting it is what stores - // `ChainChoice.InProcessCuprate`, and the warning below is what the user - // reads before Start. + // Tapping a mode stores it and, when the storage floor allows, + // starts the node. Filled = the stored choice. Spacer(Modifier.height(8.dp)) - OutlinedButton( + val mode = selectedCuprateMode( + inProcess = inProcess, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ) + CuprateModeButton( + label = "Mainnet pruned", + selected = mode == CuprateMode.MainnetPruned, + testTag = "wallet-chain-mainnet-pruned", onClick = { onInProcessNode(true, true) }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-chain-mainnet-pruned"), - ) { Text("Mainnet pruned") } + ) Spacer(Modifier.height(4.dp)) - OutlinedButton( + CuprateModeButton( + label = "Mainnet full", + selected = mode == CuprateMode.MainnetFull, + testTag = "wallet-chain-mainnet-full", onClick = { onInProcessNode(true, false) }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-chain-mainnet-full"), - ) { Text("Mainnet full") } + ) Spacer(Modifier.height(4.dp)) - OutlinedButton( + CuprateModeButton( + label = "Testnet (experimental)", + selected = mode == CuprateMode.Testnet, + testTag = "wallet-chain-in-process", onClick = { onInProcessNode(false, false) }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-chain-in-process"), - ) { Text("Testnet (experimental)") } + ) if (inProcess) { Spacer(Modifier.height(8.dp)) @@ -836,6 +857,23 @@ private fun WalletChildCard( } } +@Composable +private fun CuprateModeButton( + label: String, + selected: Boolean, + testTag: String, + onClick: () -> Unit, +) { + val modifier = Modifier + .fillMaxWidth() + .testTag(testTag) + if (selected) { + Button(onClick = onClick, modifier = modifier) { Text(label) } + } else { + OutlinedButton(onClick = onClick, modifier = modifier) { Text(label) } + } +} + /** * The SDK record as the pure model `WalletChildStatusText.kt` renders. Field for * field, nothing inferred. diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index f6cec47..7627175 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -391,6 +391,32 @@ class WalletChildStatusTextTest { assertTrue(why!!, why.contains("280.0 GiB")) } + @Test + fun selecting_pruned_highlights_that_mode() { + assertEquals( + CuprateMode.MainnetPruned, + selectedCuprateMode(inProcess = true, mainnet = true, prune = true), + ) + assertEquals( + CuprateMode.MainnetFull, + selectedCuprateMode(inProcess = true, mainnet = true, prune = false), + ) + assertEquals( + CuprateMode.Testnet, + selectedCuprateMode(inProcess = true, mainnet = false, prune = false), + ) + assertNull(selectedCuprateMode(inProcess = false, mainnet = true, prune = true)) + } + + @Test + fun selecting_a_mode_starts_unless_storage_or_an_in_flight_start_blocks_it() { + assertTrue(shouldStartAfterSelectingChain(storageBlocked = null, starting = false)) + assertFalse( + shouldStartAfterSelectingChain(storageBlocked = "Not enough space", starting = false), + ) + assertFalse(shouldStartAfterSelectingChain(storageBlocked = null, starting = true)) + } + @Test fun the_storage_line_reports_the_measured_number() { val line = chainStorageLine(41L * 1024 * 1024 * 1024) From a7daf2c7688eefa8926a5b71b97503ac38c3bfdd Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 15:47:51 -0400 Subject: [PATCH 11/94] fix(cuprate): catch launch panics and give the thread 8 MiB stack Android's default pthread stack is ~1 MiB. Cuprate+RandomX overflow it, the launch thread dies before tx.send, and the UI only says "the launch thread died before answering". Catch unwind so a Rust panic is the error string, and size the launch thread plus tokio workers at 8 MiB. --- src/cuprate.rs | 65 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 53 insertions(+), 12 deletions(-) diff --git a/src/cuprate.rs b/src/cuprate.rs index cf4aedf..e00d168 100644 --- a/src/cuprate.rs +++ b/src/cuprate.rs @@ -60,8 +60,8 @@ mod imp { use std::path::Path; use std::sync::mpsc; - use cuprated::config::{resolve_max_memory, Config}; use cuprated::Node; + use cuprated::config::{Config, resolve_max_memory}; /// The network this daemon runs. Testnet, deliberately — see the module /// docs. Cuprate spells this `Testnet`. @@ -81,6 +81,41 @@ mod imp { /// wallet child's RPC is the only client). const RUNTIME_WORKERS: usize = 2; + /// Android's default pthread stack is ~1 MiB; Cuprate + RandomX overflow it + /// and the launch thread dies before `tx.send`, which the UI reports as + /// "the launch thread died before answering". Same size on the tokio + /// workers that actually run consensus. + const LAUNCH_STACK: usize = 8 * 1024 * 1024; + + fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { + if let Some(s) = payload.downcast_ref::<&str>() { + (*s).to_string() + } else if let Some(s) = payload.downcast_ref::() { + s.clone() + } else { + "unknown panic".into() + } + } + + fn run_on_launch_thread(f: F) -> Result + where + F: FnOnce() -> Result + Send + 'static, + T: Send + 'static, + { + let (tx, rx) = mpsc::channel(); + std::thread::Builder::new() + .name("onionwire-cuprate".into()) + .stack_size(LAUNCH_STACK) + .spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) + .unwrap_or_else(|p| Err(format!("cuprate panicked: {}", panic_message(&*p)))); + let _ = tx.send(result); + }) + .map_err(|e| format!("launch thread: {e}"))?; + rx.recv() + .map_err(|_| "the launch thread died before answering".to_string())? + } + /// A running in-process chain daemon. /// /// Owning it *is* the lifecycle: `cuprated::Node` implements `Drop` and asks @@ -114,16 +149,7 @@ mod imp { prune: bool, ) -> Result { let text = config_toml(datadir, port, network, prune); - let (tx, rx) = mpsc::channel(); - std::thread::Builder::new() - .name("onionwire-cuprate".into()) - .spawn(move || { - let _ = tx.send(launch_on_owned_runtime(&text)); - }) - .map_err(|e| format!("launch thread: {e}"))?; - let (runtime, node) = rx - .recv() - .map_err(|_| "the launch thread died before answering".to_string())??; + let (runtime, node) = run_on_launch_thread(move || launch_on_owned_runtime(&text))?; Ok(Self { runtime: Some(runtime), node: Some(node), @@ -181,6 +207,7 @@ mod imp { resolve_max_memory(&mut config).map_err(|e| format!("config: {e}"))?; let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(RUNTIME_WORKERS) + .thread_stack_size(LAUNCH_STACK) .enable_all() .build() .map_err(|e| format!("runtime: {e}"))?; @@ -272,6 +299,20 @@ mode = "Auto" "the chain database is a separate store under the chain datadir" ); } + + #[test] + fn a_panic_on_the_launch_thread_is_returned_as_an_error() { + let err = run_on_launch_thread(|| -> Result<(), String> { panic!("boom") }) + .expect_err("a panic is an error, not a dead channel"); + assert!( + err.contains("boom"), + "the panic payload has to reach the caller, got {err:?}" + ); + assert!( + !err.contains("died before answering"), + "that string is only for a thread that never sent" + ); + } } } @@ -312,4 +353,4 @@ mod imp { pub use imp::CuprateNode; #[cfg(feature = "cuprate-daemon")] -pub use imp::{config_toml, NETWORK}; +pub use imp::{NETWORK, config_toml}; From c00c9d4151e2265f2c2d726cbd834cc45fc8aa30 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 17:54:44 -0400 Subject: [PATCH 12/94] fix(cuprate): seed XDG so Android parse does not poison LazyLock Cuprate's serde defaults call ArtiConfig::default, which unwraps dirs::data_dir(). On Android HOME is unset and dirs-sys has no getpwuid fallback, so the first Start panics and a retry reports "LazyLock instance has previously been poisoned". Point XDG at the chain datadir before parse and set tor.arti.directory_path in TOML. --- src/cuprate.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 4 deletions(-) diff --git a/src/cuprate.rs b/src/cuprate.rs index e00d168..5ef6922 100644 --- a/src/cuprate.rs +++ b/src/cuprate.rs @@ -97,6 +97,39 @@ mod imp { } } + /// Cuprate's `#[serde(default)]` fills missing nested structs via `Default`. + /// `ArtiConfig::default` (and `FileSystemConfig::default`) dereference + /// `CUPRATE_DATA_DIR` / `CUPRATE_CACHE_DIR`, which `unwrap()` `dirs::*`. + /// On Android `dirs-sys` has no getpwuid fallback and `HOME` is unset, so + /// those return `None`, the unwrap panics, and a second Start then hits + /// "LazyLock instance has previously been poisoned". + /// + /// Point XDG at the chain datadir *before* parsing so those LazyLocks + /// initialize to a real path. Process-wide: OnionWire's own store is + /// `$ONIONWIRE_HOME`, not XDG. + fn seed_cuprate_xdg(datadir: &Path) { + let datadir = std::path::absolute(datadir).unwrap_or_else(|_| datadir.to_path_buf()); + let home_needs_fix = match std::env::var_os("HOME") { + None => true, + Some(h) => Path::new(&h).parent().is_none(), + }; + // SAFETY: called once on the dedicated cuprate launch thread before + // any other thread in this process reads these keys for Cuprate. + // OnionWire's store is `$ONIONWIRE_HOME`, not XDG. + unsafe { + // `dirs` ignores non-absolute XDG_* and falls through to HOME. + std::env::set_var("XDG_DATA_HOME", datadir.join("xdg-data")); + std::env::set_var("XDG_CACHE_HOME", datadir.join("xdg-cache")); + std::env::set_var("XDG_CONFIG_HOME", datadir.join("xdg-config")); + // HOME=/ (seen on some Androids) fails cuprate_helper::fs's + // "parent is some" assert even when XDG is set, if anything still + // reads HOME. Replace only a missing or root HOME. + if home_needs_fix { + std::env::set_var("HOME", &datadir); + } + } + } + fn run_on_launch_thread(f: F) -> Result where F: FnOnce() -> Result + Send + 'static, @@ -108,7 +141,16 @@ mod imp { .stack_size(LAUNCH_STACK) .spawn(move || { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) - .unwrap_or_else(|p| Err(format!("cuprate panicked: {}", panic_message(&*p)))); + .unwrap_or_else(|p| { + let msg = panic_message(&*p); + if msg.contains("previously been poisoned") { + Err(format!( + "cuprate panicked: {msg} — force-stop the app; a previous panic poisoned process-wide init and cannot recover in-process" + )) + } else { + Err(format!("cuprate panicked: {msg}")) + } + }); let _ = tx.send(result); }) .map_err(|e| format!("launch thread: {e}"))?; @@ -149,7 +191,9 @@ mod imp { prune: bool, ) -> Result { let text = config_toml(datadir, port, network, prune); - let (runtime, node) = run_on_launch_thread(move || launch_on_owned_runtime(&text))?; + let datadir = datadir.to_path_buf(); + let (runtime, node) = + run_on_launch_thread(move || launch_on_owned_runtime(&text, &datadir))?; Ok(Self { runtime: Some(runtime), node: Some(node), @@ -202,7 +246,11 @@ mod imp { /// /// Runs on the launch thread — never on a thread that is already inside a /// runtime, which is what makes `block_on` legal here. - fn launch_on_owned_runtime(text: &str) -> Result<(tokio::runtime::Runtime, Node), String> { + fn launch_on_owned_runtime( + text: &str, + datadir: &Path, + ) -> Result<(tokio::runtime::Runtime, Node), String> { + seed_cuprate_xdg(datadir); let mut config: Config = toml::from_str(text).map_err(|e| format!("config: {e}"))?; resolve_max_memory(&mut config).map_err(|e| format!("config: {e}"))?; let runtime = tokio::runtime::Builder::new_multi_thread() @@ -269,7 +317,12 @@ enabled = false [tor] mode = "Auto" -"# + +# Explicit so serde does not call ArtiConfig::default(), which unwraps +# dirs::data_dir() (None on Android: no HOME, no getpwuid fallback). +[tor.arti] +directory_path = "{datadir}/arti" +"#, ) } @@ -313,6 +366,44 @@ mode = "Auto" "that string is only for a thread that never sent" ); } + + #[test] + fn the_toml_sets_arti_directory_so_default_does_not_touch_xdg() { + let text = config_toml(Path::new("/tmp/onionwire-chain"), 18081, "Mainnet", true); + assert!( + text.contains("[tor.arti]"), + "ArtiConfig::default unwraps dirs::data_dir(); on Android that is None" + ); + assert!( + text.contains("/tmp/onionwire-chain/arti"), + "directory_path must be the chain datadir, got {text}" + ); + } + + #[test] + fn seeding_xdg_lets_the_config_parse() { + let datadir = Path::new("/tmp/onionwire-chain"); + seed_cuprate_xdg(datadir); + let mut config: Config = toml::from_str(&config_toml(datadir, 18081, "Testnet", false)) + .expect("parse after xdg seed"); + resolve_max_memory(&mut config).expect("target_max_memory is set"); + assert_eq!( + config.fjall_directory(), + Path::new("/tmp/onionwire-chain/testnet/fjall") + ); + } + + #[test] + fn a_poisoned_lazylock_panic_tells_the_user_to_force_stop() { + let err = run_on_launch_thread(|| -> Result<(), String> { + panic!("LazyLock instance has previously been poisoned") + }) + .expect_err("a panic is an error"); + assert!( + err.contains("force-stop the app"), + "poison is unrecoverable in-process, got {err:?}" + ); + } } } From 0a91744924cb69629d99b8f242cf69a730576992 Mon Sep 17 00:00:00 2001 From: onionwire Date: Sat, 19 Sep 2026 19:38:52 -0400 Subject: [PATCH 13/94] wallet: show the chain daemon's sync height and target on the child status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The user watching an in-process Cuprate node on Android saw only a phase word (connecting, with 'wallet connect: Connection refused (os error 111)') and asked to see height vs tip. - WalletChildStatus gains height / target_height, and line() appends 'sync h/t' when a probe read either number. No percentage is invented when the daemon reports no target (h/0 is honest), and an off/exited child reports 0/0. - Node::wallet_child_refresh fills them: one wallet-RPC get_info now answers both the readiness gate and the numbers (Wallet::chain_info, with chain_ready built on the same parse), and when the wallet RPC is down while the chain source is local/in-process, the loopback daemon is asked directly (ChildConfig::daemon_probe_addr). A refused daemon stays 0/0 — unknown, not caught up. Only refresh dials; the draw path reads two atomics. - UniFFI WalletChildStatus carries the same two u64 fields so Android can show them; SDK test covers the round trip. Tests: cargo test --locked --target x86_64-unknown-linux-gnu (all green), clippy -D warnings clean; crates/onionwire-sdk cargo test --locked + clippy clean (separate workspace). --- crates/onionwire-sdk/src/lib.rs | 37 +++++ docs/WALLET.md | 16 ++ src/node.rs | 261 ++++++++++++++++++++++++++++++-- src/wallet.rs | 47 +++++- src/wallet_child.rs | 124 +++++++++++++++ 5 files changed, 468 insertions(+), 17 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 247f284..c9b5b2b 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -872,6 +872,8 @@ fn child_status( } else { String::new() }, + height: status.height, + target_height: status.target_height, last_error: status.last_error, } } @@ -1077,6 +1079,14 @@ pub struct WalletChildStatus { /// node's side (the daemon's loopback RPC has not answered yet); it is /// never persisted, polled from a file, or inferred from a timeout. pub node_state: String, + /// Blocks the chain daemon had at the last probe, as the wallet RPC (or the + /// daemon itself, over loopback) reported them. `0` means unknown: never + /// probed, the child is off/exited, or the probe failed — it is not the + /// same as caught up, and it is never a wallet-scan height. + pub height: u64, + /// Blocks the daemon was syncing towards. `0` means the daemon reported + /// none (also not the same as caught up). + pub target_height: u64, /// The last failure, display-ready. Never carries the generated login. pub last_error: Option, } @@ -1889,6 +1899,8 @@ mod tests { running: true, configured: true, chain_source: "in-process node".to_string(), + height: 0, + target_height: 0, last_error: None, } } @@ -1960,4 +1972,29 @@ mod tests { let status = child_status(core_status(WalletChildState::Off), &ChainSource::None); assert_eq!(status.node_available, onionwire::cuprate::available()); } + + /// The chain's own progress reaches Kotlin: a snapshot that carries the + /// daemon's height and target copies both numbers onto the record, so an + /// Android status line can show `1160/3090939` without a second probe. + #[test] + fn the_daemons_height_and_target_reach_the_sdk_record() { + let mut core = core_status(WalletChildState::Connecting); + core.height = 1160; + core.target_height = 3_090_939; + let status = child_status(core, &ChainSource::None); + assert_eq!(status.height, 1160); + assert_eq!(status.target_height, 3_090_939); + // The core's own word still passes straight through: the numbers are an + // addition, not a second state machine. + assert_eq!(status.state, "connecting"); + } + + /// A snapshot with nothing to report keeps `0/0`: unknown is not caught up, + /// and no percentage is invented on the way out. + #[test] + fn an_unprobed_child_reports_an_unknown_chain_progress() { + let status = child_status(core_status(WalletChildState::Off), &ChainSource::None); + assert_eq!(status.height, 0); + assert_eq!(status.target_height, 0); + } } diff --git a/docs/WALLET.md b/docs/WALLET.md index 0adc25d..2a34f03 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -342,6 +342,22 @@ env-var presence, and `ready` is never reported for a child that has died. - **`exited`** — a started child has died. Stop and start again; the status is not stale, it is the process table. +The same one-liner carries the chain's own progress once a probe has read it: + +``` +child syncing · in-process node · sync 1160/3090939 +``` + +Those are the **daemon's** height and the tip it is syncing towards — from the +wallet RPC's `get_info` when it answers, and, when the wallet RPC is *not* +answering (the `connecting` case, e.g. `Connection refused (os error 111)`) while +the chain source is `local node` or `in-process node`, from that loopback daemon +directly. `sync 0/0`, or no `sync` segment at all, means **unknown**: the child +is off or exited, the probe failed, or the daemon reported no target — which is +not the same as caught up, and is never a wallet-scan height. No percentage is +ever derived from it. `WalletChildStatus` (and the UniFFI record) carries the two +numbers as `height` / `target_height`. + `start` is idempotent: a live child is reported, not respawned. A start that cannot spawn the binary is an error and leaves no child behind. diff --git a/src/node.rs b/src/node.rs index cbad028..15e7220 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,7 +1,7 @@ //! Two-node onion session: host HS, Noise IK, persist plaintext locally. use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -55,6 +55,10 @@ pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30); /// The drain inside `shutdown` gets a shorter budget: teardown must not hang /// the caller behind a Tor dial. Undelivered rows survive in sqlite. pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); +/// Budget for the direct loopback `get_info` a child refresh makes when the +/// wallet RPC is not answering. Local TCP only — a refused daemon returns +/// immediately, and a live one answers in milliseconds. +const DAEMON_PROBE_BUDGET: Duration = Duration::from_secs(3); struct HsHandle { svc: Arc, @@ -96,6 +100,13 @@ pub struct Node { /// Did the running child's wallet report a synced chain at the last probe? /// Only `wallet_child_refresh` writes it; the draw path only reads it. child_synced: AtomicBool, + /// Blocks the chain daemon had at the last probe. `0` means unknown: never + /// probed, the child is off/exited, or the probe failed. Only + /// `wallet_child_refresh` writes it; the draw path only reads it. + child_height: AtomicU64, + /// Blocks the daemon was syncing towards at the last probe. `0` means the + /// daemon reported none — not the same as caught up. + child_target: AtomicU64, /// The last child failure, display-ready. Cleared on a successful start. child_error: Mutex>, incoming_limit: Mutex, @@ -167,6 +178,8 @@ impl Node { wallet_status: Mutex::new(wallet_status), wallet_child: Mutex::new(None), child_synced: AtomicBool::new(false), + child_height: AtomicU64::new(0), + child_target: AtomicU64::new(0), child_error: Mutex::new(None), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), @@ -274,7 +287,7 @@ impl Node { // outlive the node that started them. match self.wallet_child.lock().map(|mut g| g.take()) { Ok(Some(child)) => { - self.child_synced.store(false, Ordering::Relaxed); + self.reset_child_probe(); if let Err(e) = child.stop() { eprintln!("shutdown: wallet child stop failed: {e}"); } @@ -659,7 +672,7 @@ impl Node { *self.wallet.lock().map_err(|e| e.to_string())? = wallet; *self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured); *self.child_error.lock().map_err(|e| e.to_string())? = None; - self.child_synced.store(false, Ordering::Relaxed); + self.reset_child_probe(); *self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child); Ok(()) } @@ -672,7 +685,7 @@ impl Node { if let Some(child) = child { child.stop().map_err(|e| e.to_string())?; } - self.child_synced.store(false, Ordering::Relaxed); + self.reset_child_probe(); let stored = self .store .lock() @@ -686,6 +699,15 @@ impl Node { Ok(()) } + /// Clear the last child probe: no chain answers, nothing remembered. Called + /// wherever the child's lifecycle moves (start, stop, shutdown), so a stale + /// height from a previous run can never survive into the next one. + fn reset_child_probe(&self) { + self.child_synced.store(false, Ordering::Relaxed); + self.child_height.store(0, Ordering::Relaxed); + self.child_target.store(0, Ordering::Relaxed); + } + /// The child's observable state, derived from the real process plus the last /// probe — never from env-var presence. Cheap: no dial, safe on a draw path. pub fn wallet_child_status(&self) -> WalletChildStatus { @@ -710,11 +732,22 @@ impl Node { Some(_) if self.child_synced.load(Ordering::Relaxed) => WalletChildState::Ready, Some(_) => WalletChildState::Syncing, }; + // Only a live child has anything to say about a chain. An off or exited + // child reports unknown (`0/0`), whatever the last probe left behind. + let heights = match state { + WalletChildState::Off | WalletChildState::Exited => (0, 0), + WalletChildState::Connecting | WalletChildState::Syncing | WalletChildState::Ready => ( + self.child_height.load(Ordering::Relaxed), + self.child_target.load(Ordering::Relaxed), + ), + }; WalletChildStatus { state, running, configured: cfg.is_enabled(), chain_source: cfg.source_label(), + height: heights.0, + target_height: heights.1, last_error: self.child_error.lock().ok().and_then(|err| err.clone()), } } @@ -725,9 +758,10 @@ impl Node { self.wallet_child_status().line() } - /// Probe the running child once: is its wallet RPC answering, and is the - /// chain at the tip? Only this (or a failed start) moves the state off - /// `connecting`, and it never invents `ready` for a dead child. + /// Probe the running child once: is its wallet RPC answering, is the chain + /// at the tip, and how far along is the chain daemon? Only this (or a failed + /// start) moves the state off `connecting`, and it never invents `ready` for + /// a dead child. pub async fn wallet_child_refresh(&self) -> WalletChildStatus { let running = self .wallet_child @@ -737,6 +771,7 @@ impl Node { if !running { return self.wallet_child_status(); } + let cfg = self.wallet_child_config(); let w = self.wallet_snapshot(); if !w.configured() { return self.wallet_child_status(); @@ -747,18 +782,44 @@ impl Node { if let Ok(mut slot) = self.wallet_status.lock() { *slot = status; } - let synced = if connected { - w.chain_ready().await.unwrap_or(false) + // One probe answers both questions: is it synced, and how far along. + let progress = if connected { + w.chain_info().await.ok() } else { - false + None + }; + let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready); + let (height, target_height) = match progress { + Some(info) => (info.height, info.target_height), + // The wallet RPC is the honest source when it answers. When it does + // not (a refused connection is the common one), the daemon this box + // owns can still say — and a daemon that does not answer leaves + // `0/0`, which is "unknown", not "caught up". + None => self.chain_daemon_progress(&cfg).await, }; self.child_synced.store(synced, Ordering::Relaxed); + self.child_height.store(height, Ordering::Relaxed); + self.child_target.store(target_height, Ordering::Relaxed); if let Ok(mut slot) = self.child_error.lock() { *slot = if connected { None } else { error }; } self.wallet_child_status() } + /// The chain daemon's own height/target, asked directly because the wallet + /// RPC did not answer. Only a daemon on this box is asked (see + /// [`ChildConfig::daemon_probe_addr`]) and any failure is `(0, 0)` — a + /// daemon still coming up is unknown, not an error to put on the status row. + async fn chain_daemon_progress(&self, cfg: &ChildConfig) -> (u64, u64) { + let Some(addr) = cfg.daemon_probe_addr() else { + return (0, 0); + }; + match wallet::daemon_get_info(&addr, DAEMON_PROBE_BUDGET).await { + Ok(info) => (info.height, info.target_height), + Err(_) => (0, 0), + } + } + /// The config screen's Test-connection button: one shot against the endpoint /// the user is typing. It does not touch the live wallet or the snapshot — /// a test of an untyped endpoint is not the wallet we are running. @@ -1827,6 +1888,7 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; use crate::wallet::ChainSource; @@ -1929,6 +1991,8 @@ mod tests { wallet_status: Mutex::new(wallet_status), wallet_child: Mutex::new(None), child_synced: AtomicBool::new(false), + child_height: AtomicU64::new(0), + child_target: AtomicU64::new(0), child_error: Mutex::new(None), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(file::Inbox::new(home.join("inbox"))), @@ -2458,6 +2522,183 @@ mod tests { } } + /// A loopback wallet RPC that answers the *status* probe: a digest + /// challenge, then `get_address` / `get_balance` / `get_info`, with the + /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the + /// *transfer* path; this one answers a refresh, which never transfers. + async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + tokio::spawn(async move { + // Every call starts unauthenticated, so every call gets one + // challenge — the client retries each request with digest auth. + for _ in 0..8 { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 8192]; + let Ok(n) = sock.read(&mut buf).await else { + return; + }; + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + if !req.contains("Authorization:") { + let _ = sock + .write_all( + b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await; + continue; + } + let body = if req.contains("get_info") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# + ) + } else if req.contains("get_address") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, + addr = xmr_addr() + ) + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() + }; + let _ = sock + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ) + .await; + } + }); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + + /// A loopback daemon that answers `get_info` on the port the child probes + /// when its wallet RPC is down. `None` when that port is already held (a real + /// `monerod` on this box): that daemon is not ours to replace, and the test + /// must not claim to have served the answer. + async fn mock_daemon_on_default_port(height: u64, target: u64) -> Option<()> { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = + tokio::net::TcpListener::bind(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) + .await + .ok()?; + tokio::spawn(async move { + for _ in 0..4 { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 4096]; + let _ = sock.read(&mut buf).await; + let body = format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"# + ); + let _ = sock + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ) + .await; + } + }); + Some(()) + } + + /// The status row carries the real chain numbers: a wallet RPC that answers + /// `get_info` fills height and target, and the one-liner shows them. A + /// daemon that reports no target is not a caught-up chain — `h/0` with no + /// invented percentage. + #[tokio::test] + async fn a_wallet_that_answers_get_info_fills_the_chain_progress() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); + let log = dir.path().join("argv.log"); + let bin = fake_child_bin( + &dir.path().join("fake-bins"), + "monero-wallet-rpc", + &log, + "sleep 30", + ); + node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) + .expect("set config"); + node.start_wallet_child().expect("start"); + // The child is a fake process; the wallet the node actually talks to is + // the mock RPC, which is where the numbers come from. + *node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await; + + let status = node.wallet_child_refresh().await; + assert_eq!(status.state, WalletChildState::Ready, "{status:?}"); + assert_eq!(status.height, 4549, "{status:?}"); + assert_eq!(status.target_height, 0, "{status:?}"); + assert!(status.line().contains("sync 4549/0"), "{}", status.line()); + assert!(!status.line().contains('%'), "{}", status.line()); + + node.stop_wallet_child().expect("stop"); + } + + /// The case the user hit: the wallet RPC is refused (`os error 111`) while + /// the chain source is this box's own daemon. The status still shows the + /// chain's height and target — asked of the daemon directly — and the state + /// stays `connecting`, because the *wallet* is what did not answer. + #[tokio::test] + async fn a_refused_wallet_rpc_falls_back_to_the_local_daemons_own_height() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("child"); + let Some(()) = mock_daemon_on_default_port(1160, 3_090_939).await else { + eprintln!( + "skipping: 127.0.0.1:{DEFAULT_MONEROD_RPC_PORT} is already held by something else" + ); + return; + }; + let node = offline_node(&home, Arc::new(NoDial)); + let monerod = fake_child_bin( + &dir.path().join("fake-bins"), + "monerod", + &dir.path().join("monerod.argv"), + "sleep 30", + ); + let rpc = fake_child_bin( + &dir.path().join("fake-bins"), + "monero-wallet-rpc", + &dir.path().join("rpc.argv"), + "sleep 30", + ); + node.set_wallet_child_config(&ChildConfig { + source: ChainSource::Local { + monerod_bin: monerod, + datadir: dir.path().join("chain"), + prune: true, + }, + wallet_rpc_bin: rpc, + arti_bin: PathBuf::from("arti"), + wallet_filename: "onionwire".to_string(), + }) + .expect("set config"); + node.start_wallet_child().expect("start"); + + let status = node.wallet_child_refresh().await; + assert_eq!(status.state, WalletChildState::Connecting, "{status:?}"); + assert_eq!(status.height, 1160, "{status:?}"); + assert_eq!(status.target_height, 3_090_939, "{status:?}"); + assert!( + status.line().contains("sync 1160/3090939"), + "{}", + status.line() + ); + + node.stop_wallet_child().expect("stop"); + } + fn sealed_creds(node: &Node) -> (String, String) { let raw = node .store diff --git a/src/wallet.rs b/src/wallet.rs index f404cea..226dab0 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -363,6 +363,30 @@ pub struct Wallet { timeout_chain: Duration, } +/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and +/// the numbers a status line shows. `0` height/target means the wallet RPC +/// answered without a number — unknown, never "caught up", and never a percent. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChainInfo { + /// The wallet RPC said `synchronized: true`. A missing field is `false`. + pub synchronized: bool, + /// Blocks the wallet's daemon has, as the wallet RPC reports them. + pub height: u64, + /// Blocks that daemon is syncing towards; `0` when it reported none. + pub target_height: u64, +} + +impl ChainInfo { + /// The readiness predicate: the daemon reached the tip and the wallet + /// scanned up to it. `synchronized` must be explicitly true, and a chain + /// with no height is not ready. + pub fn ready(&self) -> bool { + self.synchronized + && self.height > 0 + && (self.target_height == 0 || self.height >= self.target_height) + } +} + /// What /tip says when the wallet cannot spend. Same text for the explicit /// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over /// RPC, so the operator never has to guess which one it was. The TUI's @@ -695,14 +719,23 @@ impl Wallet { /// the wallet has scanned up to it. `synchronized` must be explicitly true — /// a missing field is not-ready, never a silent pass. pub async fn chain_ready(&self) -> Result { + Ok(self.chain_info().await?.ready()) + } + + /// One `get_info` round trip, carrying both the readiness fields and the + /// numbers a status line shows — the status line and the spend gate ask the + /// same question, so they ask it once. `0` height/target means the wallet + /// RPC answered without a number: unknown, never "caught up". + pub async fn chain_info(&self) -> Result { let v = self.chain_rpc("get_info", serde_json::json!({})).await?; - let synced = v - .get("synchronized") - .and_then(|b| b.as_bool()) - .unwrap_or(false); - let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0); - let target = v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0); - Ok(synced && height > 0 && (target == 0 || height >= target)) + Ok(ChainInfo { + synchronized: v + .get("synchronized") + .and_then(|b| b.as_bool()) + .unwrap_or(false), + height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0), + target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0), + }) } /// May this wallet attempt a spend? Fail closed: any readiness doubt is a diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 8769ccb..e56ee0e 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -727,6 +727,21 @@ impl ChildConfig { pub fn source_label(&self) -> String { self.source.label() } + + /// Where a status refresh may ask the chain daemon itself for + /// height/target, when the wallet RPC is not answering. Only a daemon this + /// box owns: a `monerod`/Cuprate the child spawned binds loopback, and + /// asking it is a plain local socket. A remote daemon is the wallet child's + /// to dial (over SOCKS, if it is an onion) — a status refresh does not open + /// a second path to it. + pub fn daemon_probe_addr(&self) -> Option { + match self.source { + ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => { + Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) + } + ChainSource::None | ChainSource::Remote { .. } => None, + } + } /// Reject a configuration that could only fail later (empty binary path, /// empty host, port 0) *before* it is persisted or spawned. pub fn validate(&self) -> Result<()> { @@ -888,6 +903,12 @@ pub struct WalletChildStatus { /// The chain-source label: `receive-only` / `local node` / /// `remote onion daemon` / `remote daemon`. pub chain_source: String, + /// Blocks the chain daemon currently has. `0` means unknown (not started, or + /// the last probe failed). This is daemon height, never wallet-rpc scan height. + pub height: u64, + /// Blocks the daemon is syncing towards. `0` means the daemon reported none + /// (not the same as caught up — see `wallet::chain_ready`). + pub target_height: u64, /// The last failure, display-ready. Never carries the generated login. pub last_error: Option, } @@ -900,6 +921,13 @@ impl WalletChildStatus { return String::new(); } let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source); + // A probe that read nothing says nothing: the line is unchanged until a + // daemon (or the wallet's daemon) actually reported numbers. No + // percentage is derived — `target_height == 0` is "the daemon told us + // nothing", not "caught up". + if self.height > 0 || self.target_height > 0 { + line.push_str(&format!(" · sync {}/{}", self.height, self.target_height)); + } if let Some(err) = &self.last_error { line.push_str(" · "); line.push_str(err); @@ -1965,6 +1993,102 @@ mod tests { assert!(closed, "the daemon's RPC listener outlived stop()"); } + fn probe_status(state: WalletChildState, height: u64, target_height: u64) -> WalletChildStatus { + WalletChildStatus { + state, + running: true, + configured: true, + chain_source: "in-process node".to_string(), + height, + target_height, + last_error: None, + } + } + + /// No probe numbers, no `sync` segment: a snapshot that never read a height + /// renders exactly the line it rendered before this existed. + #[test] + fn a_status_line_without_probe_numbers_carries_no_sync_segment() { + let line = probe_status(WalletChildState::Connecting, 0, 0).line(); + assert_eq!(line, "child connecting · in-process node"); + assert!(!line.contains("sync"), "{line}"); + } + + /// The numbers the user asked for: the daemon's own height over the tip it + /// is syncing towards, on the same one-liner the wallet screen already shows. + #[test] + fn a_status_line_shows_the_daemons_height_and_target() { + let line = probe_status(WalletChildState::Connecting, 1160, 3_090_939).line(); + assert!(line.contains("sync 1160/3090939"), "{line}"); + assert!(!line.contains('%'), "{line}"); + } + + /// A daemon that reports no target is not a caught-up chain: the height is + /// still shown — over `0` — and no percentage is invented for it. + #[test] + fn a_missing_target_still_shows_the_height_and_no_percent() { + let line = probe_status(WalletChildState::Syncing, 4549, 0).line(); + assert!(line.contains("sync 4549/0"), "{line}"); + assert!(!line.contains('%'), "{line}"); + } + + /// The failure text stays last: a probe number never displaces the error a + /// reader is looking for. + #[test] + fn a_status_line_keeps_the_error_after_the_sync_segment() { + let mut status = probe_status(WalletChildState::Connecting, 1160, 3_090_939); + status.last_error = Some("wallet connect: Connection refused (os error 111)".into()); + let line = status.line(); + assert!(line.contains("sync 1160/3090939"), "{line}"); + assert!( + line.ends_with("· wallet connect: Connection refused (os error 111)"), + "{line}" + ); + } + + /// Only a daemon this box owns is asked directly. A remote daemon is the + /// wallet child's to dial — a status refresh must not open a second path to + /// it, and receive-only has nothing to ask at all. + #[test] + fn only_a_loopback_source_gets_a_daemon_probe_address() { + let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"); + for source in [ + ChainSource::Local { + monerod_bin: PathBuf::from("monerod"), + datadir: PathBuf::from("/chain"), + prune: false, + }, + ChainSource::InProcessCuprate { + datadir: PathBuf::from("/chain"), + network: ChainNetwork::Mainnet, + prune: true, + }, + ] { + let cfg = ChildConfig { + source: source.clone(), + ..ChildConfig::default() + }; + assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str())); + } + for source in [ + ChainSource::None, + ChainSource::Remote { + host: "peer.onion".to_string(), + port: 18081, + }, + ChainSource::Remote { + host: "203.0.113.7".to_string(), + port: 18081, + }, + ] { + let cfg = ChildConfig { + source, + ..ChildConfig::default() + }; + assert_eq!(cfg.daemon_probe_addr(), None); + } + } + /// Poll a loopback address until it accepts, inside a budget. #[cfg(feature = "cuprate-daemon")] fn waits_for_tcp(addr: &str, budget: Duration) -> bool { From e69704551577a55fc0e9df5a20c381b921cf479f Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 19 Sep 2026 19:50:04 -0400 Subject: [PATCH 14/94] android: show the chain daemon's sync height on the wallet status line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK surface from the rust-dev parent (#129) carries `WalletChildStatus.height` and `target_height` (Rust `u64` → generated Kotlin `ULong`), so the wallet status line can say how far the chain daemon has got instead of only naming it. * `WalletChildInput` mirrors both fields as `ULong` — checked against the generated `uniffi.onionwire_sdk.WalletChildStatus`, not assumed. Defaults stay `0uL` so every existing fixture is unchanged. * `walletChildLine` appends ` · sync h/t` after the source and the `node` segment, before the error em-dash, and only when either value is non-zero: `0/0` is unknown (probe failed, daemon not up), not `0%`, and a zero target still prints as `/0`. No percent, no progress bar, no ETA. * `WalletScreen.toInput()` copies both fields field-for-field; the status row's screen-reader sentence moved into `walletChildStatusDescription`, which carries the same `sync h/t` the eye reads. One line, still no second widget. * Tests cover the three sync cases plus the spoken row; the old exact-line assertions (`off · receive-only`, `connecting · local node`, `ready · remote onion daemon`) are untouched. `:app:testDebugUnitTest`: 114 tests, 0 failures. * `android/CUPRATE_DAEMON.md` no longer claims the record has no height field. --- android/CUPRATE_DAEMON.md | 16 +++- .../onionwire/ui/WalletChildStatusText.kt | 35 ++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 4 +- .../onionwire/ui/WalletChildStatusTextTest.kt | 84 +++++++++++++++++++ 4 files changed, 134 insertions(+), 5 deletions(-) diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md index d45b411..1708d9e 100644 --- a/android/CUPRATE_DAEMON.md +++ b/android/CUPRATE_DAEMON.md @@ -133,10 +133,18 @@ above is the other half of the proof — request and artifact, separately checka * The status line renders the core's words verbatim and grows a `node ` segment from `WalletChildStatus.node_state` for this source only. An unrecognised word is never rendered as ready. -* **No sync height.** `WalletChildStatus` has no height field — the core keeps a - `chain_height()` internally (`src/cuprate.rs`) but does not expose it over - UniFFI, so the screen does not show a number it cannot get. A height on the - status line is a follow-up on the SDK surface, not something the UI can invent. +* **The daemon's sync height is on the line.** `WalletChildStatus.height` / + `target_height` (Rust `u64` → UniFFI/Kotlin `ULong`) carry the blocks the chain + daemon had at the last probe — read from the wallet RPC, or, when that RPC is + refused (the 111 case) and the source is local/in-process, from the daemon over + loopback. The status line appends ` · sync h/t` after the source (and after the + `node` segment) whenever either is non-zero: `0/0` means the last probe failed + or the daemon is not up, so it is *unknown*, not `0%` — there is no percent, no + progress bar and no ETA anywhere in the UI, and a zero target still prints as + `/0`. This is the **daemon's** chain height, not the wallet's scan height. The + same string is what the status row's screen-reader `contentDescription` carries + (`walletChildStatusDescription`), so the spoken row is never shorter than the + visible one. Cross-compiled and unit-tested on the JVM; still not device-proven. * **Storage honesty.** The card shows the free space on the filesystem the fjall store grows into (`StatFs` on the app's data dir) and refuses Start below a 3 GiB floor, or when that filesystem cannot be read at all. The floor is a diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index ebbbd5d..f9804fd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -45,6 +45,20 @@ data class WalletChildInput( * empty for an in-process source that has not been read yet. */ val nodeState: String = "", + /** + * Blocks the chain daemon had at the last probe — the core's `height`, from + * the wallet RPC or, when that RPC is refused, from the in-process daemon + * over loopback. `0` means unknown: never probed, the child is off/exited, or + * the probe failed. It is **not** caught up, and it is never a wallet-scan + * height. + * + * `ULong` because that is what UniFFI generates for the Rust `u64` (checked + * against `uniffi.onionwire_sdk.WalletChildStatus`, not assumed) — this model + * mirrors that record field for field. + */ + val height: ULong = 0uL, + /** Blocks the daemon was syncing towards — the core's `target_height`. `0` means none reported (also not caught up). */ + val targetHeight: ULong = 0uL, val lastError: String? = null, ) @@ -274,6 +288,8 @@ fun walletChildLine(input: WalletChildInput?): String { val phase = walletChildPhase(input) val source = input?.chainSource?.takeIf { it.isNotBlank() } ?: "no chain source" val node = nodePhase(input) + val height = input?.height ?: 0uL + val target = input?.targetHeight ?: 0uL val why = input?.lastError?.takeIf { it.isNotBlank() } return buildString { append(phase.label) @@ -285,6 +301,16 @@ fun walletChildLine(input: WalletChildInput?): String { append(" · node ") append(node.label) } + // The daemon's own height, when it reported one: `sync h/t`, the segment + // the core's own line uses. No percent, no progress bar, no ETA — `0/0` + // is unknown (the probe failed, or the daemon is not up), not "0%", and + // when both are zero the segment is absent rather than printed as `0/0`. + if (height > 0uL || target > 0uL) { + append(" · sync ") + append(height.toString()) + append('/') + append(target.toString()) + } when { why != null -> append(" — ").append(shortSendReason(why)) phase is WalletChildPhase.Exited -> append(" — the child process is gone") @@ -292,6 +318,15 @@ fun walletChildLine(input: WalletChildInput?): String { } } +/** + * The whole status row as one screen-reader sentence: the phase's own sentence, + * then the same line the eye reads — including the daemon's `sync h/t` when the + * core reported one. A screen reader is never told less than the sighted user, + * and it is a sentence either way. + */ +fun walletChildStatusDescription(input: WalletChildInput?): String = + "${walletChildPhase(input).contentDescription}. ${walletChildLine(input)}" + /** * A `.onion` daemon is only reachable through the `arti` SOCKS child, and this * build does not ship one — say that before the user presses Start rather than diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index a67d8de..4fbeeac 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -681,7 +681,7 @@ private fun WalletChildCard( .fillMaxWidth() .testTag(phase.testTag) .semantics(mergeDescendants = true) { - contentDescription = "${phase.contentDescription}. ${walletChildLine(input)}" + contentDescription = walletChildStatusDescription(input) }, ) @@ -886,6 +886,8 @@ internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput( chainInProcess = chainInProcess, nodeAvailable = nodeAvailable, nodeState = nodeState, + height = height, + targetHeight = targetHeight, lastError = lastError, ) diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index 7627175..aa92f6c 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -29,6 +29,8 @@ class WalletChildStatusTextTest { chainInProcess: Boolean = false, nodeAvailable: Boolean = true, nodeState: String = "", + height: ULong = 0uL, + targetHeight: ULong = 0uL, lastError: String? = null, ) = WalletChildInput( state = state, @@ -38,6 +40,8 @@ class WalletChildStatusTextTest { chainInProcess = chainInProcess, nodeAvailable = nodeAvailable, nodeState = nodeState, + height = height, + targetHeight = targetHeight, lastError = lastError, ) @@ -263,6 +267,8 @@ class WalletChildStatusTextTest { nodeState: String, nodeAvailable: Boolean = true, running: Boolean = true, + height: ULong = 0uL, + targetHeight: ULong = 0uL, ) = input( state = state, running = running, @@ -270,6 +276,8 @@ class WalletChildStatusTextTest { chainInProcess = true, nodeAvailable = nodeAvailable, nodeState = nodeState, + height = height, + targetHeight = targetHeight, ) @Test @@ -316,6 +324,82 @@ class WalletChildStatusTextTest { assertFalse(walletChildLine(input("off", chainSource = "receive-only")).contains("node ")) } + // --- the daemon's sync height on the line -------------------------------- + + @Test + fun no_sync_segment_when_the_daemon_reported_nothing() { + // `0/0` is unknown — the probe failed or the daemon is not up — so the + // line says nothing rather than printing a number it does not have. + val line = walletChildLine(input("off", chainSource = "receive-only")) + assertEquals("off · receive-only", line) + // The `sync` *segment*, not the substring: `syncing` is a phase word. + assertFalse("no height is not a height of zero", line.contains(" · sync ")) + assertFalse( + walletChildLine(node(nodeState = "starting")).contains(" · sync "), + ) + } + + @Test + fun the_line_carries_the_daemons_height_and_target() { + assertEquals( + "connecting · in-process mainnet pruned · node starting · sync 1160/3090939", + walletChildLine( + node( + state = "connecting", + chainSource = "in-process mainnet pruned", + nodeState = "starting", + height = 1160uL, + targetHeight = 3_090_939uL, + ), + ), + ) + } + + @Test + fun a_zero_target_still_prints_as_zero_and_never_as_a_percent() { + val line = walletChildLine( + node( + state = "syncing", + chainSource = "in-process mainnet pruned", + nodeState = "syncing", + height = 4549uL, + targetHeight = 0uL, + ), + ) + assertEquals( + "syncing · in-process mainnet pruned · node syncing · sync 4549/0", + line, + ) + assertFalse("no percent is invented", line.contains("%")) + } + + @Test + fun the_height_sits_before_the_failure_text() { + val line = walletChildLine( + input("off", height = 7uL, lastError = "spawn monero-wallet-rpc: Permission denied"), + ) + assertTrue(line, line.startsWith("off · remote daemon · sync 7/0 — ")) + assertTrue(line, line.contains("Permission denied")) + } + + @Test + fun the_spoken_row_says_the_same_height_the_eye_reads() { + val input = node( + state = "connecting", + chainSource = "in-process mainnet pruned", + nodeState = "starting", + height = 1160uL, + targetHeight = 3_090_939uL, + ) + val spoken = walletChildStatusDescription(input) + assertTrue(spoken, spoken.contains("sync 1160/3090939")) + assertTrue( + "a screen reader is told the same as the eye", + spoken.endsWith(walletChildLine(input)), + ) + assertTrue("it is still a sentence", spoken.startsWith("The wallet child is up")) + } + @Test fun start_is_blocked_when_the_build_has_no_in_process_daemon() { val why = startBlockedReason( From db12f4838ba7b43993df265b712061d6f02e0dd4 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Sun, 20 Sep 2026 00:20:32 -0400 Subject: [PATCH 15/94] =?UTF-8?q?sdk:=20expose=20wallet=5Fchild=5Frefresh?= =?UTF-8?q?=20=E2=80=94=20a=20live=20wallet-child=20probe=20over=20UniFFI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wire::wallet_status() is the cheap cached read (no dial); only Node::wallet_child_refresh() writes state/height/target_height, and it was reachable over UniFFI from exactly one place — start_wallet_child. An Android refresh loop polling wallet_status() therefore shows a frozen sync line. Add the additive export, reusing the existing child_status mapper so the record is the same shape as wallet_status(), and the core probe as the only probe path. Docs: one sentence in docs/WALLET.md, which enumerates the SDK wallet-child surface. Tests: SDK-level (a Wire cannot be built offline in this crate — open_wire bootstraps Arti): the unprobed child maps to the same 'off' record both reads report, pinned with an exhaustive record literal; and the probe on a stopped handle is a typed WireError.Stopped. --- crates/onionwire-sdk/src/lib.rs | 90 +++++++++++++++++++++++++++++++++ docs/WALLET.md | 7 ++- 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index c9b5b2b..154b602 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -651,6 +651,32 @@ impl Wire { Ok(child_status(node.wallet_child_status(), &source)) } + /// One live probe of the app-owned wallet child, returning the same record + /// [`Wire::wallet_status`] reports — from a snapshot that was just taken + /// rather than one left behind by the last start. + /// + /// It dials: the child's loopback wallet RPC, and the configured local + /// daemon's `get_info` when the wallet RPC does not answer. That is what + /// makes the chain's height and target move between calls. + /// + /// It never spawns and never starts a child: a node with no child is not + /// launched for this call. + /// + /// Safe to call from a UI refresh loop, but not free — it makes network + /// calls, so a caller should poll on the order of seconds rather than every + /// frame. [`Wire::wallet_status`] stays the cheap, non-dialing read for + /// first paint. + /// + /// The honest limit: with no live child, the core short-circuits and returns + /// the cached `off` / `exited` snapshot, so this can never invent `ready` or + /// any other live state for a child that is not there. `WireError.Stopped` + /// after `shutdown`. + pub async fn wallet_child_refresh(&self) -> WResult { + let node = self.node()?; + let source = node.wallet_child_config().source; + Ok(child_status(node.wallet_child_refresh().await, &source)) + } + /// The chain-source + binary settings the child spawns with, as stored. /// Returns the defaults (receive-only, binaries by name) when nothing was /// ever set, so a settings screen can prefill from it safely. @@ -1997,4 +2023,68 @@ mod tests { assert_eq!(status.height, 0); assert_eq!(status.target_height, 0); } + + /// A live probe on a node with no child is `off` — the same record the + /// cheap read reports — never an error and never an invented state. + /// + /// This crate cannot build the node half of that: `open_wire` is the only + /// constructor of `Wire` and it bootstraps Arti and publishes an onion + /// service, so there is no offline `Node` for a test to hold. What is + /// pinned here is the half the SDK owns — both exported reads hand the same + /// core snapshot to the same `child_status` mapper — plus the record shape, + /// written as an exhaustive literal so a new field on `WalletChildStatus` + /// stops this test compiling. The core's own short-circuit (`wallet_child` + /// is `None` ⇒ return the cached snapshot) is what `src/node.rs`'s tests + /// exercise. + #[test] + fn an_unprobed_child_is_off_whichever_read_reports_it() { + let core = onionwire::wallet_child::WalletChildStatus { + state: WalletChildState::Off, + running: false, + configured: false, + chain_source: "receive-only".to_string(), + height: 0, + target_height: 0, + last_error: None, + }; + let source = ChainSource::None; + let want = WalletChildStatus { + state: "off".to_string(), + running: false, + configured: false, + chain_source: "receive-only".to_string(), + chain_in_process: false, + node_available: onionwire::cuprate::available(), + node_state: String::new(), + height: 0, + target_height: 0, + last_error: None, + }; + + // `wallet_status` maps it once, `wallet_child_refresh` maps the same + // snapshot the same way: one mapper, no second state machine. + for got in [ + child_status(core.clone(), &source), + child_status(core, &source), + ] { + assert_eq!(got.state, want.state); + assert_eq!(got.running, want.running); + assert_eq!(got.configured, want.configured); + assert_eq!(got.chain_source, want.chain_source); + assert_eq!(got.chain_in_process, want.chain_in_process); + assert_eq!(got.node_available, want.node_available); + assert_eq!(got.node_state, want.node_state); + assert_eq!(got.height, want.height); + assert_eq!(got.target_height, want.target_height); + assert_eq!(got.last_error, want.last_error); + } + } + + /// The live probe is an error, not a panic, once the handle is shut down: + /// it goes through the same `node()` accessor as every other call. + #[test] + fn wallet_child_refresh_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } } diff --git a/docs/WALLET.md b/docs/WALLET.md index 2a34f03..abf3c26 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -371,8 +371,11 @@ credentials live*), so they survive a restart: `Node::start_wallet_child` / `stop_wallet_child` / `wallet_child_status` / `wallet_child_refresh`. - Android (UniFFI): `set_chain_source(ChainConfig)` / `chain_source()`, - `start_wallet_child()`, `stop_wallet_child()`, `wallet_status()`. Pass - absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the + `start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (the cached + read: no dial, for first paint) and `wallet_child_refresh()` (a live probe of + the same record — it dials the loopback wallet RPC, and the local daemon's + `get_info` when that RPC does not answer, so poll it on the order of + seconds). Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the core never resolves a binary the caller named explicitly. `ChainChoice` has a fourth variant, `InProcessCuprate`, for the in-process daemon: no binary path and, with an empty `monerod_datadir`, the SDK resolves the chain directory to From f95c1e7ca732be720cb1704f0fad57b963aabe13 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 00:31:07 -0400 Subject: [PATCH 16/94] docs: rewrite README and living docs to match the tree Audit the operator docs against the source: pin downloads to v0.14.0, document the real CLI/flags/env/F-keys (including F9, no F7), keep 18081 as the app-owned daemon port, describe the local chat outbox vs a server-side one, and stop implying SECURITY_AUDIT.md is a third-party audit. Spike reports stay; they get a status header only. --- README.md | 444 ++++++------- docs/ARTI_UPGRADE.md | 13 +- docs/PROTOCOL.md | 92 ++- docs/README.md | 23 +- docs/RELEASING.md | 7 +- docs/SECURITY_AUDIT.md | 5 +- docs/THREAT_MODEL.md | 10 +- docs/TUI.md | 1069 ++++-------------------------- docs/WALLET.md | 600 +++++------------ docs/arti-socks-feasibility.md | 4 + docs/cuprate-android-spike.md | 4 + docs/cuprate-launch-spike.md | 3 + docs/option-a-recommendation.md | 3 + docs/payment-integration-plan.md | 6 + 14 files changed, 649 insertions(+), 1634 deletions(-) diff --git a/README.md b/README.md index 477f41a..d77917a 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,89 @@ # OnionWire Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti). -No hosted server. Identity is a public key; the onion is only a locator. +No hosted server. Identity is an ed25519 public key; the onion is only a locator. -**v0.2.1** — Linux TUI + Android SDK/APK. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion, and every chat message is ratcheted inside that session. Unreachable chat peers go to a **local outbox** (device-only retry queue — no relay); file transfer and payment frames still fail closed. Optional Monero payments: `/pay` invoices (receive), `/tip` payments (send), and a full in-app wallet create/import (`F6` wallet screen, `/wallet create`, `/wallet import`). Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top. +Current tagged release: **v0.14.0**. Linux TUI + Android SDK/APK. Two people add +each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There +is no invite QR graphic. Chat is Noise IK over your own v3 onion; every chat +message is ratcheted inside that session. Unreachable chat peers go to a **local +outbox** (device-only retry queue — no relay). File transfer and payment frames +fail closed. Optional Monero: `/pay` invoices, `/tip` payments, and in-app wallet +create/import (`F6`). Arti onion services are still experimental. The store is +SQLCipher; chat bodies add a row-bound AEAD layer. -You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion. +You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds +Arti and publishes its own v3 onion. There is no C-tor fallback. -**Docs** (protocol first, then claims): [PROTOCOL.md](docs/PROTOCOL.md) · [threat model](docs/THREAT_MODEL.md) · [audit notes](docs/SECURITY_AUDIT.md) (in-house, not a third-party audit). Index: [docs/README.md](docs/README.md). +**Docs** (protocol first, then claims): [PROTOCOL.md](docs/PROTOCOL.md) · +[threat model](docs/THREAT_MODEL.md) · [audit notes](docs/SECURITY_AUDIT.md) +(in-house, **not** a third-party audit). Index: [docs/README.md](docs/README.md). +TUI keys: [docs/TUI.md](docs/TUI.md). Wallet: [docs/WALLET.md](docs/WALLET.md). +Releases: [docs/RELEASING.md](docs/RELEASING.md). ## Install -Pick one: a CI-built binary (fastest), or build from source. +Pick one: a CI-built binary, or build from source. ### Requirements | Need | Notes | |---|---| | Linux | x86_64 or aarch64. TUI needs a real terminal (not a pipe). | -| Network | First run bootstraps Tor via Arti. Offline start will fail closed. | +| Network | First run bootstraps Tor via Arti. Offline start fails closed. | | Not needed | `tor` package, `torrc`, Prosody, an XMPP account, a DHT. | -Arti onion services are still **experimental**. If the hidden service cannot come up, OnionWire exits — it does not fall back to C-tor. +Arti onion services are still **experimental**. If the hidden service cannot come +up, OnionWire exits. ### Option A — download a release binary -CI (`.forgejo/workflows/release.yml`) does **not** release on a merge. Releases are manual and batched: a maintainer runs the workflow at a stopping point (Actions → release → Run workflow, `dry_run=true` first), which tags the next `v*.*.*` version and publishes both Linux binaries — aarch64 on the Pi runner, x86_64 on the amd64 runner — to one [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases), with the Android APK + AAR attached to that same tag. Policy and inputs: [docs/RELEASING.md](docs/RELEASING.md). `scripts/build-release-local.sh` remains the offline x86_64 fallback. This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag. +CI does **not** release on a merge. Releases are manual and batched: a maintainer +dispatches `.forgejo/workflows/release.yml` at a stopping point (`dry_run=true` +first), which tags the next `v*.*.*` version and publishes both Linux binaries to +one [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases). +The Android APK + AAR attach to **the same tag** by a second dispatch of +`android-release` with `tag=`. Policy: [docs/RELEASING.md](docs/RELEASING.md). +This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag. -**x86_64 (most PCs / VMs):** +**x86_64:** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-x86_64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-x86_64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.14.0/onionwire-x86_64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.14.0/onionwire-x86_64-unknown-linux-gnu.sha256 sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256 chmod +x onionwire-x86_64-unknown-linux-gnu ./onionwire-x86_64-unknown-linux-gnu --version ``` -**aarch64 (Raspberry Pi, ARM servers):** +**aarch64:** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-aarch64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-aarch64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.14.0/onionwire-aarch64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.14.0/onionwire-aarch64-unknown-linux-gnu.sha256 sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256 chmod +x onionwire-aarch64-unknown-linux-gnu ./onionwire-aarch64-unknown-linux-gnu --version ``` -Install onto `PATH` if you want `onionwire` as a command (keep the asset filename until after `sha256sum -c`): +Install onto `PATH` (keep the asset filename until after `sha256sum -c`): ```bash mkdir -p ~/.local/bin install -m 755 onionwire-x86_64-unknown-linux-gnu ~/.local/bin/onionwire -# ensure ~/.local/bin is on PATH, then: onionwire ``` -The binary is dynamically linked against glibc (Ubuntu 24.04 builders). If `./onionwire` dies with `GLIBC_… not found`, use Option B on that machine. - -Checksum files are `sha256sum` format (` onionwire-`). Download both files with `curl -O` so the names match, then `sha256sum -c`. +The binary is dynamically linked against glibc (Ubuntu 24.04 builders). If it +dies with `GLIBC_… not found`, use Option B. Checksum files are `sha256sum` +format (` onionwire-`). ### Option B — build from source -Needs [Rust](https://rustup.rs/) **1.91+** (`edition = "2024"`; the pinned Arti 0.46 crates require rustc 1.91). A distro `rustc` is fine if `rustc --version` reports 1.91 or newer. Do not install `tor` for this app. +Needs [Rust](https://rustup.rs/) **1.91+** (`edition = "2024"`; `Cargo.toml` +`rust-version = "1.91"`; Arti 0.46 requires 1.91). Do not install `tor`. ```bash -# rustup (if you do not already have cargo) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source "$HOME/.cargo/env" rustc --version # must be 1.91 or newer @@ -81,30 +99,35 @@ cargo build --release --locked ./target/release/onionwire ``` -Install the binary: - ```bash cargo install --path . --locked --force # lands in ~/.cargo/bin/onionwire ``` Build needs a C toolchain plus `perl` and `make`: SQLCipher is compiled from -vendored OpenSSL sources (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). -No system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is -`rustls`, and the binaries carry no dynamic `libssl` dependency. +vendored OpenSSL (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). No +system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is +`rustls`. + +The crate version in `Cargo.toml` is **not** bumped by the release workflow. The +tag (`v0.14.0`) is the version users download; `onionwire --version` prints +`CARGO_PKG_VERSION` from the tree that was built. ### Two instances on one machine -Each process needs its own data dir (identity + onion + sqlite): +Each process needs its own data dir: ```bash ONIONWIRE_HOME=/tmp/ow-a ./onionwire ONIONWIRE_HOME=/tmp/ow-b ./onionwire ``` -Then `F2` on A (invite string), `F3`-paste on B (and the other way around). No QR. +Then `F2` on A, `F3`-paste on B (and the other way). No invite QR. -## First run +## Run + +There are **no subcommands**. Flags are `--version` / `-V` and `--help` / `-h` +only (`src/main.rs`). Anything else exits 2 with `onionwire: unknown argument`. ```bash onionwire @@ -112,22 +135,64 @@ onionwire or `cargo run --release`. -On start you are prompted for a store passphrase (echo off, like other CLI passwords) or set `ONIONWIRE_STORE_PASSPHRASE`. Empty passphrase is rejected; a wrong passphrase does not open chat. Then you should see `onionwire: bootstrapping Arti…` on stderr. Directory bootstrap is usually under a minute; the onion is ready once a probe connect works (combined Arti status may still say Bootstrapping). Fail closed at 360s. Data lives in `ONIONWIRE_HOME` if set, otherwise `~/.local/share/onionwire/` (`onionwire.db` + Arti state, mode 0700). First open creates an ed25519 identity key. That key **is** you. +On start you are prompted for a store passphrase (echo off) or set +`ONIONWIRE_STORE_PASSPHRASE`. Empty passphrase is rejected; a wrong passphrase +does not open chat. Then `onionwire: bootstrapping Arti…` on stderr. Directory +bootstrap is usually under a minute; the onion is ready once a probe connect +works (combined Arti status may still say Bootstrapping). Fail closed at 360s +(`PUBLISH_WAIT` in `src/hs.rs`). Data lives in `ONIONWIRE_HOME` if set, otherwise +`~/.local/share/onionwire/` (`onionwire.db` + Arti state, mode 0700). First open +creates an ed25519 identity key. That key **is** you. -Then `F2` to share your invite, `F3` to paste a friend's. Mouse-select the `onionwire:v1:…` line to copy. Highlight them in the roster, type in the composer, Enter to send. Chat rows show delivery state from the local outbox (`✓` delivered, `◷ queued (try n/8, retry …)`, `» sending`, `✗ failed: …`); the footer shows `{n} queued` while anything is outstanding. If their onion is down the message stays on this device and the retry worker re-dials with backoff — nothing is handed to a third party. File transfer and payments are still one-shot (both sides online). +Then `F2` to share your invite, `F3` to paste a friend's. Mouse-select the +`onionwire:v1:…` line to copy. Highlight them in the roster, type in the +composer, Enter to send. Chat rows show delivery state from the local outbox +(`✓` delivered, `◷ queued (try n/8, retry …)`, `» sending`, `✗ failed: …`); the +footer shows `{n} queued` while anything is outstanding. If their onion is down +the message stays on this device and the retry worker re-dials with backoff — +nothing is handed to a third party. File transfer and payments are still one-shot +(both sides online). ## Friends are keys -A friend is an ed25519 pubkey (`UNIQUE(pubkey)`). The `.onion` on that row is only where they are reachable right now. Pasting the same `k` updates the locator; it never creates a second person. +A friend is an ed25519 pubkey (`UNIQUE(pubkey)`). The `.onion` on that row is +only where they are reachable right now. Pasting the same `k` updates the +locator; it never creates a second person. + +## Commands and flags + +``` +onionwire [--version | -V | --help | -h] +``` + +Everything else is the TUI (function keys and `/commands` in the composer). + +### Environment + +| Variable | Read in | Meaning | +|---|---|---| +| `ONIONWIRE_HOME` | `src/store.rs` | Data dir. Unset → `~/.local/share/onionwire`. | +| `ONIONWIRE_STORE_PASSPHRASE` | `src/store.rs` | Non-empty store passphrase; skips the prompt. Empty/missing with no TTY fails closed. | +| `ONIONWIRE_ASCII` | `src/tui.rs` | Present → ASCII chrome (also follows `NO_COLOR`). | +| `ONIONWIRE_WALLET_RPC` | `src/wallet.rs` | External loopback `monero-wallet-rpc` URL. Unused by the app-owned wallet child. | +| `ONIONWIRE_WALLET_RPC_LOGIN` | `src/wallet.rs` | `user:pass` when the URL has no userinfo. | +| `ONIONWIRE_WALLET_NO_SPEND` | `src/wallet.rs` | `1` / `true` / `yes` / `on` → refuse `/tip` locally. | + +`NO_COLOR` (any value) also switches ASCII chrome. Android CI uses +`ONIONWIRE_REQUIRE_RELEASE_KEY`; the TUI does not read it. ## Keys (TUI) -Focus starts on the composer so typing works immediately. `Tab` cycles panes; `j`/`k` and arrows only move the focused pane (roster or chat). `1`/`2`/`3` switch focus when you are not typing in the composer. `?` opens help from every screen except paste (so a payload can contain `?`). +Focus starts on the composer. `Tab` cycles panes; `j`/`k` and arrows only move +the focused pane. `1`/`2`/`3` switch focus when you are not typing (on the +**wallet** screen those digits pick an in-process chain source instead — see +[docs/TUI.md](docs/TUI.md)). `?` opens help from every screen except paste (so a +payload can contain `?`). | Key | Action | |---|---| | `Tab` / `Shift-Tab` | Cycle focus: roster → chat → composer | -| `1` / `2` / `3` | Focus roster / chat / composer (when not typing) | +| `1` / `2` / `3` | Focus roster / chat / composer (Main, when not typing) | | `j` `k` / `↑` `↓` | Move or scroll the focused pane | | `g` / `G` | Jump to top / bottom of the focused pane | | `?` | Keybinding help (`Esc` closes) | @@ -135,51 +200,55 @@ 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 (receive QR, balance, transfers) | +| `F6` | Wallet (receive QR, create/import, child, chain source) | | `F8` | Rotate **prekey** (hard cut: every friend re-pastes the invite) | +| `F9` | Wallets & settings menu (`/settings`) | | Enter | Send chat to the selected friend, or run a `/command` | | `Esc` | Close overlay / back to Main / clear composer | | `Ctrl-Q` | Quit: type `CLEAR`+Enter to wipe history, `QUIT`+Enter to leave it, Esc to stay | +There is **no `F7`**. The not-configured wallet error still says “open F7”; the +live screens are `F6` (wallet) and `F9` (settings). Full map: [docs/TUI.md](docs/TUI.md). + +Composer `/commands` (`src/tui.rs` `parse_cmd`): `/wipe`, `/wipe-all`, `/profile`, +`/who`, `/pay [memo]`, `/tip [memo]`, `/backup /path`, `/restore /path`, +`/file /path`, `/settings`, `/wallet create`, `/wallet import`. + ## F2 / F3 invite -There is no QR. `F2` opens `(o) invite` with truncated fingerprint, current onion, and the full payload (wrapped, mouse-select to copy): +There is no invite QR. `F2` opens the share screen with truncated fingerprint, +current onion, and the full payload (wrapped, mouse-select to copy): `onionwire:v1:k=…:o=…:spk=…:sig=…` -Give that string to a friend. They `F3` paste it (`(o) paste invite`). Unknown `k` asks for approval. Same `k` already in the roster updates `onion` only. +Give that string to a friend. They `F3` paste it. Unknown `k` asks for approval. +Same `k` already in the roster updates `onion` (and prekey) only. ## F4 rotate onion -`F4` is a locator change, not a new identity. Confirm by typing `ROTATE` (Enter alone does nothing). +`F4` is a locator change, not a new identity. Confirm by typing `ROTATE` (Enter +alone does nothing). -- Your identity fingerprint stays the same. +- Identity fingerprint stays the same. - A new onion is published; the old one is hard-cut (no dual-host grace). - Online friends get a signed `loc` frame. - Offline friends cannot find you until they F3-paste the new invite. There is no directory. ## Local outbox (chat) and fail closed -**Chat** to an unreachable onion is written to a local `outbox` row next to its -`messages` row and retried in-process while the app runs (exponential backoff, -cap 30 min between attempts, stop after 8 attempts or a terminal failure). There -is **no** server-side queue and **no** store-and-forward relay — a queued message -never leaves the device, and it dies with the device. Two consequences are real and are accepted: +**Chat** to an unreachable onion is written to a local `outbox` row and retried +in-process while the app runs (exponential backoff from 30s, cap 30 min, stop +after 8 attempts or a terminal failure — `src/outbox.rs`). There is **no** +server-side queue and **no** store-and-forward relay — a queued message never +leaves the device, and it dies with the device. -- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase — SSD wear-leveling can keep copies. Roster and identity stay. -- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure. - -Delivery markers in the TUI and Android chat UI are the store's own statuses: - -| Row state | Marker | -|---|---| -| delivered | `you: ping ✓` | -| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` | -| sending | `you: pong » sending` | -| failed | `you: pong ✗ failed: connection timed out` | -| inbound | `them: pong` (no marker) | - -The footer shows `{n} queued` while any row is outstanding. `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / `retry now` comes from the stored absolute `next_attempt_at`. Failed reasons are sanitized, cut to the tail of the `a: b: c` chain, and capped at 24 cells. +- **Device seizure.** A pending message sits in the same SQLCipher store as the + rest of the history. Seizure *with* the passphrase reveals messages that were + never sent; seizure without it reveals nothing in this store. `/wipe` clears + outbox rows with chat history; `/wipe-all` removes them with the data dir. + Neither is a forensic erase. +- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials + the peer's onion on a backoff schedule while the app runs. Still **fail closed** (no queue, no retry): @@ -188,137 +257,95 @@ Still **fail closed** (no queue, no retry): - Arti cannot publish the onion (no C-tor fallback) - no DHT, no name server, no hosted chat server -## Chat ratchet (per friend, on device) +## Chat ratchet -Chat is ratcheted on top of the Noise session: each chat send is -Double-Ratchet encrypted first, and the resulting `rat ` frame is what the -one-shot Noise session carries. Forward secrecy is per chain, and a snapshot of -one side's state stops reading the conversation at the next DH ratchet step. -The wire format and the honest limits are in -[docs/PROTOCOL.md](docs/PROTOCOL.md) and -[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). +Chat is ratcheted on top of the Noise session: each chat send is Double-Ratchet +encrypted first, and the resulting `rat ` frame is what the one-shot Noise +session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md). -- Per-friend state lives in the encrypted store (`ratchet_sessions`, one row per - friend). Nothing about it is transmitted, so the "no relay, no server queue" - rule is unchanged. -- Message numbers, ratchet keys and chain state ride *inside* the Noise - ciphertext; there is nothing new to observe on the wire. -- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip` and file chunks - keep the one-shot Noise shape. +- Per-friend state lives in the encrypted store (`ratchet_sessions`). Nothing + about it is transmitted. +- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and + `fil` keep the one-shot Noise shape. - Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000 - stored, oldest-first eviction; a used key is deleted, so a replay fails - closed). A queued chat message re-sends the *same* `rat ` frame, so an outbox - retry never burns a second chain key. -- `/wipe` clears chat, payments and outbox rows but **keeps** the ratchet state - (roster and identity stay), so chat continues on the same epoch. `/wipe-all` - removes the data dir and the state with it. -- **Session reset.** There is no `/reset` command and no in-band reset in - v0.2.1. The state is dropped automatically when the friend's prekey changes — - i.e. when you `F3`-paste a refreshed invite — and the next chat frame - bootstraps a fresh epoch. That re-paste is the only recovery path today. -- **Desync today is quiet.** An inbound `rat ` frame that does not authenticate - is logged as `rat dropped ()` on stderr and dropped: no chat row, no - TUI marker, nothing stored. A send-side failure surfaces as the usual - `send failed: …` status note. There is no in-app "ratchet desynced" banner - yet, so a desync is diagnosed from the terminal the app was started in. + stored). A queued chat message re-sends the *same* `rat ` frame. +- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all` + removes the data dir. +- There is no `/reset`. State drops when the friend's prekey changes (you + `F3`-paste a refreshed invite). +- An inbound `rat ` frame that does not authenticate is logged as + `rat dropped ()` on stderr and dropped. There is no in-app desync banner. ## File transfer `/file /path` sends a local file to the selected friend. Both must be online. -Cap 1 MiB on send and receive. Fail closed: a bad chunk or hash mismatch -deletes the partial (never overwrite). Files land in -`$ONIONWIRE_HOME/inbox//`. Chat shows `[file] name (N bytes)`, -never raw frames. File transfer is **not** covered by the chat outbox — no -resume, no images in the TUI. +Cap 1 MiB (`file::MAX_BYTES`). Fail closed: a bad chunk or hash mismatch deletes +the partial. Files land in `$ONIONWIRE_HOME/inbox//`. Chat shows +`[file] name (N bytes)`. Not covered by the chat outbox. ## Profile -`/profile` edits your friend-visible display name, bio, and optional Monero address (64 / 512 byte limits, no images). Enter saves and one-shot sends a signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed profile. There is no directory: unknown pubkeys are ignored. +`/profile` edits your friend-visible display name, bio, and optional Monero +address (64 / 512 byte limits, no images). Enter saves and one-shot sends a +signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed +profile. Unknown pubkeys are ignored. ## Monero (opt-in) -Chat does not need a wallet. Spend is opt-in at wallet create/restore; default -is no spend key, no seed on the device. Optional JSON-RPC to `monero-wallet-rpc` on -loopback (you run it, or the app spawns it). Chain source is your choice: a -spawned local `monerod`, or a daemon address you supply. The wallet **must** -use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest -challenge) and refuses URLs with no credentials. +Chat does not need a wallet. Spend is opt-in at wallet create/restore. Optional +JSON-RPC to `monero-wallet-rpc` on **loopback only** (you run it, or the app +spawns it). Chain source is your choice: spawned local `monerod`, in-process +Cuprate (opt-in feature, **unvalidated on mainnet**), or a daemon address you +type. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC and +refuses URLs with no credentials. Wallet RPC is never on clearnet and never over +`.onion`. `--trusted-daemon` is never passed. + +The app-owned local daemon RPC port is **18081**. **18089** is a daemon's +*restricted*-RPC port and belongs only in examples of a *remote* address you type. ```bash -# monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret +# externally run wallet RPC (migration path) export ONIONWIRE_WALLET_RPC=http://onionwire:secret@127.0.0.1:18083 -# or keep the password out of the URL: +# or: export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083 export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret ``` -Loopback only, HTTP Digest (RFC 2617, matching `--rpc-login`), 5s timeout, 1 MiB response cap. `.onion` RPC URLs are rejected (no Arti dial; do not point this at a remote wallet). Unset → chat still works; `/pay`, `/tip`, and `F6` say so. Do not log the RPC password. - -**Prefer a view-only wallet.** OnionWire only needs invoices and receipt checks -(`create_address` / `get_transfers`); it does not need spend authority. Set -`ONIONWIRE_WALLET_NO_SPEND=1` (or `true` / `yes` / `on`) to refuse `/tip` -locally before any RPC dial — `/pay` and receipt verification keep working. -Details: [docs/WALLET.md](docs/WALLET.md). - -Payment frame summary: +Prefer `ONIONWIRE_WALLET_NO_SPEND=1` until you actually want `/tip`. Details: +[docs/WALLET.md](docs/WALLET.md). | Command | Wire frame | What it does | |---|---|---| -| `/pay [memo]` | `inv ` | Invoice to receive. We want to be paid. Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. | -| `/tip [memo]` | `rcp ` + `tip ` | Pay the selected friend. Sends a Monero `transfer`, then a signed receipt claim and a tip frame. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. | +| `/pay [memo]` | `inv ` | Invoice to receive. Subaddress if RPC is up, else profile `xmr_addr`. | +| `/tip [memo]` | `rcp ` + `tip ` | Chain `transfer`, then signed receipt and tip. One-shot. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. | -- `/pay` sends a signed `inv` frame one-shot (both sides must be online). -- `/tip` does the chain transfer first, then sends a signed `rcp` frame **and** a `tip` frame — both one-shot. Peer onion down → fails after the transfer. Not queued. +Peer onion down → `/pay` and `/tip` fail. A queued invoice does not exist. -## In-app wallet (create / import) - -`/wallet create` (F6 then `c`) generates a new spend-capable wallet on the RPC -(`create_wallet`), then shows the 25-word seed **once** for backup -(`query_key mnemonic`). Type `SPEND` to accept the spend-authority warning, set a -wallet passphrase, write the seed down, type `SEEN`. The seed is never pasted into -the composer or chat history — collect it on the dedicated screen. - -`/wallet import` (F6 then `i`) restores from an existing 25-word seed via -`restore_deterministic_wallet`. This is the only path that takes a user-supplied -secret. The seed is collected on its own screen. - -Both paths require the wallet RPC to be started with `--wallet-dir` (not only -`--wallet-file`); the in-app filename is `onionwire`. - -**Spend-authority warning** — unavoidable at create/restore: - -> An OnionWire instance pointed at a spend-capable `monero-wallet-rpc` is a local spend authority. Any process that can read the RPC credentials (env var, `/proc//environ`, shell history, a stored URL) can spend the wallet's balance, and `/tip` gives a chat peer a supported path to ask for a transfer. Prefer a view-only wallet or a separate low-balance hot wallet for spend. - -The wallet screen (`F6`) shows a receive address (fresh subaddress when the wallet is up, else the profile `xmr_addr`), the current balance, and up to 8 recent transfers. Press `r` (or Enter) to toggle a QR code of the receive address. `Esc` returns to the chat. +`F6` then `c` / `/wallet create` generates a spend-capable wallet and shows the +25-word seed **once**. `F6` then `i` / `/wallet import` restores from a seed. +Type `SPEND` then `SEEN` on create. The in-app filename is `onionwire`; the RPC +must be started with `--wallet-dir`. ## Backup / restore Losing `identity_sk` loses every friend relationship. -- `/backup /path` — type `BACKUP`, passphrase twice. Writes `owbak1` (Argon2id + ChaCha20-Poly1305). Onion is **not** in the file (locator is disposable; F4 after restore if needed). -- `/restore /path` — type `RESTORE`, passphrase. Overwrites self keys. **Does not rewrite the roster** — you may become a different person talking to old friends. - -Treat the backup file like the sqlite db. - -## Mixed versions - -0.1.2 peers store unknown plaintext as chat. A 0.2 sender of `prf ` / `inv ` / `rcp ` / `tip ` / `fil ` will leave a garbage line on an un-upgraded peer. Upgrade both sides. The Noise handshake is unchanged. +- `/backup /path` — type `BACKUP`, passphrase twice. Writes `owbak1` (Argon2id + + ChaCha20-Poly1305). Onion is **not** in the file. +- `/restore /path` — type `RESTORE`, passphrase. Overwrites self keys. **Does not + rewrite the roster.** ## Wipe -Composer (bottom of the roster screen): +- `/wipe` — type `WIPE`. Chat, payments, and outbox gone. Identity and friends stay. +- `/wipe-all` — type `WIPEALL`. Deletes the data dir. Next start is a **new person**. -- `/wipe` — confirm by typing `WIPE`. Chat and payments history gone (overwrite message bodies, drop `payments`, `VACUUM`, WAL checkpoint). Identity key and friends stay. Not a forensic erase (SSD wear-leveling). `/wipe-all` is the identity burn. -- `/wipe-all` — confirm by typing `WIPEALL`. Deletes the data dir. Next start is a **new person** (new identity key). Same disk caveat. Esc cancels. Nothing is wiped without confirm. +Not a forensic erase (SSD wear-leveling). Esc cancels. ## Uninstall ```bash -# binary (whichever you used) rm -f ~/.local/bin/onionwire ~/.cargo/bin/onionwire - -# optional: destroy identity, friends, and message log -# (same as /wipe-all — you become a new person next run) rm -rf ~/.local/share/onionwire ``` @@ -326,117 +353,76 @@ If you set `ONIONWIRE_HOME`, delete that directory instead. ## Seized laptop -The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched. +The sqlite file is SQLCipher. A 32-byte key is derived from the store passphrase +with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600) and +handed to SQLCipher as a raw key. Chat bodies carry a second, row-bound +ChaCha20-Poly1305 layer. Unlock is fail-closed. At-rest encryption is not a +defense against a live compromise or an attacker who has your passphrase. +Pending outbox rows live in the same encrypted store as delivered chat. -Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD. - -At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. Secret material (Noise/Ed25519/X25519 ephemerals, store key copies, TUI passphrase buffer) is zeroized with the `zeroize` crate when dropped; that shrinks the window, it does not close it. It also does not stop an attacker who has your passphrase. Pending outbox rows live in the same encrypted store as delivered chat — seizure *with* the passphrase can reveal messages that never left the device. `/wipe` deletes chat, payments and outbox history; it is not a forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person. - -Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md). +Threat model: [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). ## Android (SDK + APK) -Same repository, same protocol, separate product from the Linux TUI. An Android peer and a Linux peer that exchange invites interoperate — one protocol, not two. +Same repository, same protocol. An Android peer and a Linux peer that exchange +invites interoperate. -- **SDK** — `onionwire-sdk-.aar`. UniFFI Kotlin bindings over the same Rust crate the TUI runs on, plus `libonionwire_sdk.so` for `arm64-v8a`. `Wire.send()` returns `SendState.Sent` | `SendState.Queued`; chat rows carry `delivery` and `id`; `Wire.outbox(pubkey)` exposes attempt count and next attempt time so the UI can render `queued (try n/8, retry 45s)` without inventing a countdown. Explicit Tor lifecycle bindings (`shutdown`/`flush`/`torState`) stop, flush, and report observable Tor state. Another Android app can depend on the AAR directly. - - **Payment surface** — `sendInvoice(pubkey, amountXmr, memo)` for `/pay`-style invoices, `sendTip(pubkey, amountXmr, memo)` for `/tip`-style payments (chain transfer + signed `rcp` + `tip`), `walletBalance()`, `walletReceiveAddress()`, `walletRecentTransfers(cap)`, `createWallet(password)` (returns the 25-word seed once), `importWallet(password, seed)`, and `spendAuthorityWarning()`. All payments are one-shot; none are queued. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md). -- **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack Compose + Material 3 messenger that depends on `:sdk` and nothing else. Per-row delivery markers and a chat-level outbox footer match the TUI vocabulary. A foreground keep-alive service (ongoing notification) keeps the in-process Arti onion published and the outbox retry worker alive through Doze while the user wants the node reachable. The store passphrase can be remembered as an AES-256-GCM blob wrapped by the **Android Keystore** (StrongBox first, TEE/software fallback, labelled honestly). A Compose wallet route (receive QR, balance, transfers, create/import) and roster bottom actions are wired without dropping wipe-chat. +- **SDK** — `onionwire-sdk-.aar`. UniFFI Kotlin over the same Rust crate + the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md). +- **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack Compose. + Build notes: [android/README.md](android/README.md). -It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is -amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK. -[`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) -is **dispatch-only** on this Forgejo (a CI-created tag does not wake it): after -the Linux `release` workflow finishes, dispatch `android-release` with that tag -so the amd64 job builds the APK/AAR and the Pi job attaches them (+ `.sha256`) -to the same Forgejo release. If that tag's release already exists and is missing -the APK, the workflow **joins** it instead of minting patch+1. Publish does not -run from amd64 dind: `POST /releases` from that egress returns 422 with an empty -body. +The APK build is amd64-only. After the Linux `release` workflow finishes, +dispatch `android-release` with that tag so the APK/AAR attach to the same +Forgejo release. ```bash -# one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358, -# rustup target add aarch64-linux-android, cargo install cargo-ndk -scripts/build-android-local.sh # -> dist/, with .sha256 files -PUBLISH_TAG=v0.2.1 scripts/build-android-local.sh # + upload to that release +scripts/build-android-local.sh # -> dist/, with .sha256 +PUBLISH_TAG=v0.14.0 scripts/build-android-local.sh # + upload to that release ``` -Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the -repo-owned release keystore. A local run without those env vars still -debug-signs for sideload, not Play. Full build notes, the `minSdk 26` -rationale, the 16 KB page-size check and the signing story are in -[`android/README.md`](android/README.md). - ## Releases (maintainers) -Releases are **manual and batched**: no merge publishes anything, and neither -does a tag push. Cut one when a batch of work has reached a stopping point — -CI green on `main`, the feature set landed, no half-merged stack. Full policy -and procedure: [`docs/RELEASING.md`](docs/RELEASING.md) — it is two dispatches, -`release` (tag + Linux binaries) then `android-release` with that tag (APK + -AAR): on this Forgejo neither a tag push nor `workflow_call` can wake the -Android job. +Manual and batched: no merge publishes anything, and neither does a tag push. +Full procedure: [docs/RELEASING.md](docs/RELEASING.md). -Actions → release → Run workflow: +Actions → **release** → Run workflow: | Input | Meaning | |---|---| | `dry_run` | build + checksum both Linux binaries, no tag, no publish. Run this first. | | `bump` | `patch` / `minor` / `major` off the newest `v*.*.*` tag. Default `minor`. | -| `version` | explicit `X.Y.Z` (or `vX.Y.Z`) — overrides `bump`. | -| `tag` | rebuild / re-publish an existing tag instead of minting one. | +| `version` | explicit `X.Y.Z` — overrides `bump`. | +| `tag` | rebuild / re-publish an existing tag. | -Pass `tag` **or** `version`, not both; an unparseable version is rejected -rather than guessed at. The workflow computes the version, creates the tag over -the API (refusing to move an existing tag), builds aarch64 on the Pi runner and -x86_64 on the amd64 runner, and publishes all four assets (`onionwire-` -+ `.sha256`) to one release. Then dispatch `android-release` with that tag to -attach the APK + AAR to the same release (it has no automatic trigger on this -Forgejo — see `docs/RELEASING.md`). If a build or the publish fails, the core -run deletes the tag it created. Do not push tags by hand — -`release.yml` has no tag-push trigger, so a hand-pushed tag would build -nothing. +Then dispatch **android-release** with `tag=` to attach the APK + AAR. ```bash -# optional: keep Cargo.toml in sync with the tag the workflow will mint -# (the workflow does not edit Cargo.toml) - -# offline x86_64 fallback (idempotent — safe to re-run) -FORGEJO_TOKEN= scripts/build-release-local.sh v0.2.1 +FORGEJO_TOKEN= scripts/build-release-local.sh v0.14.0 ``` -Workflows (Forgejo Actions, `.forgejo/workflows/`): - -- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. -- [`.forgejo/workflows/android-ci.yml`](.forgejo/workflows/android-ci.yml) — the android side of CI, on the `docker-amd64` runner: builds `:sdk:assembleRelease` + `:app:assembleRelease` with the same script the release uses (`scripts/build-android-local.sh`, Rust for `aarch64-linux-android` via cargo-ndk + UniFFI bindings) and verifies the packaged `libonionwire_sdk.so`, checksums and APK badging. Debug keystore, no publish, no tag. Runs on `main` and PRs when `android/`, `src/`, `crates/`, `Cargo.toml`, `Cargo.lock` or `scripts/build-android-local.sh` change. Same concurrency group **and** the same runner volumes as `android-release.yml`, so a PR build never fights a release build over the SDK/NDK, cargo and Gradle caches. -- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. -- [`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) — amd64-only Android build (dispatch-only on this Forgejo; wakes from an explicit `tag=` input, not a tag push). - -Scripts: - -- [`scripts/publish-release.sh`](scripts/publish-release.sh) — create-or-update a release and (re)upload assets via the Forgejo API. Needs `FORGEJO_TOKEN` (repo secret in CI, env locally). -- [`scripts/build-release-local.sh`](scripts/build-release-local.sh) — x86_64 build + strip + checksum + publish. -- [`scripts/build-android-local.sh`](scripts/build-android-local.sh) — Android AAR + APK build, checksums, optional publish (see the Android section above). -- [`scripts/release-body.md`](scripts/release-body.md) — release notes template (`@TAG@` is substituted). - -Do not run `cargo publish`; `publish = false`. CI needs the repo secret -`FORGEJO_TOKEN` (an instance user PAT with repo write) to publish releases. +Do not run `cargo publish`; `publish = false`. ## Troubleshooting | Symptom | What to do | |---|---| -| `GLIBC_… not found` | Binary is newer than your libc. Build from source (Option B). | -| `sha256sum: FAILED` | Re-download both the binary and `.sha256`; run the check in the same directory. | -| Hang on `bootstrapping Arti…` / `hs status: Bootstrapping` | Outbound network required. Combined Arti status can stay Bootstrapping through a 5 min HsDir upload round; OnionWire probes the onion and proceeds once a connect works. Still fail closed after 360s if neither a probe nor `DegradedReachable`/`Running` — no C-tor fallback. | -| `onionwire: unknown argument` | No subcommands. Flags are `--version` / `--help` only, then the TUI. | -| Blank / broken TUI | Run in a real terminal emulator, not `nohup` / systemd without a TTY. | +| `GLIBC_… not found` | Build from source (Option B). | +| `sha256sum: FAILED` | Re-download binary and `.sha256`; check in the same directory. | +| Hang on `bootstrapping Arti…` | Outbound network required. Fail closed after 360s. No C-tor fallback. | +| `onionwire: unknown argument` | No subcommands. `--version` / `--help` only, then the TUI. | +| Blank / broken TUI | Real terminal emulator, not `nohup` / systemd without a TTY. | | Two chats, same laptop | Separate `ONIONWIRE_HOME` per process. | -| Friend cannot find you after F4 | Expected if they were offline. They must F3-paste the new invite. Same `k` updates the row. | +| Friend cannot find you after F4 | Expected if they were offline. They F3-paste the new invite. | +| Wallet error says “open F7” | There is no F7. Use `F6` / `F9`, or set `ONIONWIRE_WALLET_RPC`. | ## Not in v1 -Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward relay, multi-device, DHT / name server, QR codes, A/V. The **local** chat retry queue is in; it never leaves the device. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md). +Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward +relay, multi-device, DHT / name server, invite QR codes, A/V. The **local** chat +retry queue is in; it never leaves the device. Protocol lock: +[docs/PROTOCOL.md](docs/PROTOCOL.md). ## License -MIT \ No newline at end of file +MIT diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md index 1ca8b85..bdb6c0f 100644 --- a/docs/ARTI_UPGRADE.md +++ b/docs/ARTI_UPGRADE.md @@ -46,8 +46,7 @@ notes / the crate's own `rust-version`, then raise it in the same PR: * `rust-version` in `Cargo.toml`, * `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`, -* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it - when that lands, or ask the owner). +* the "Rust 1.91+" line in `README.md`. ## How this gets noticed @@ -118,8 +117,10 @@ issue the watcher files. descriptor upload, not a hang), probe-connect against a live HS, a byte pipe in both directions, restart, and the dormant/offline path. 7. Confirm the fail-closed path by hand if the publish wait changed at all: - with the write timeout still 360s, a peer whose onion is down must fail the - send. There is no outbox in v1 — the message must not be silently queued. + with the publish wait still 360s, if Arti cannot publish the onion the + process must exit (no C-tor fallback). Chat to a *reachable-HS but down peer* + is queued locally (`src/outbox.rs`) and retried; file transfer and payment + frames still fail immediately. There is no **server-side** outbox. 8. Rebuild the Android target. The root crate defaults to `rustls` now, so this is less about exercising a non-default feature than about proving the default still cross-compiles where OpenSSL does not exist: @@ -135,7 +136,9 @@ issue the watcher files. the plaintext should appear in Arti's state directory. 10. Open a PR against `main` describing: crates bumped, MSRV, the live-test output, and anything upstream changed that touches `src/hs.rs`. Do not push - `main`; releases are minted by `.forgejo/workflows/release.yml` from a merge. + `main`. Releases are **manual and batched**: dispatch + `.forgejo/workflows/release.yml` (`dry_run=true` first). A merge does not + mint a release. See [RELEASING.md](RELEASING.md). ## Rolling back diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 3481c11..07c07fd 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -4,7 +4,7 @@ This is the wire protocol. A second implementation should be able to interoperate from this document without reading the Rust. It is **not** an IETF RFC. It describes what this repository speaks today -(`frame::VERSION` 1, invite scheme `onionwire:v1`). There has been no public +(frame version 1, invite scheme `onionwire:v1`). There has been no public third-party audit. Arti onion services are experimental upstream. Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md). @@ -46,7 +46,7 @@ not on the wire. ## Transport 1. Each peer publishes a Tor v3 onion service (in-process Arti in this tree). -2. Application port is **80** (`HS_PORT`). +2. Application port is **80**. 3. The sender opens a Tor circuit to `(friend.onion, 80)`, runs the handshake, sends **one** application frame, and drops the circuit. 4. File transfer is N independent sessions (one handshake per chunk). There is @@ -58,12 +58,11 @@ at 30 min; 8 attempts, then terminal `Failed`). There is no server and no store-and-forward relay: each attempt is a fresh handshake straight to `(friend.onion, 80)`, exactly as above. Retries fire on a timer, on unlock/foreground, and whenever that peer is heard from (successful handshake or -`connect_onion()`). A protocol failure — signature mismatch, unknown frame, -oversize — is not a transport failure and is never queued. +a connect to that onion). A protocol failure — signature mismatch, unknown +frame, oversize — is not a transport failure and is never queued. File transfer and payment frames stay fail-closed: they are one-shot and are -**not** queued. The locator-push path still retries for 180 seconds and then -gives up. +**not** queued. The locator-push path retries for 180 seconds and then gives up. Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10. Excess is dropped before handshake. That is availability, not anonymity. @@ -99,7 +98,7 @@ from the invite (or roster). 1. **IK msg 1** — initiator → responder (framed). Responder’s Noise static is the invite `spk`. -2. Responder looks up `get_remote_static()` in the roster **by prekey**. +2. Responder looks up the remote static in the roster **by prekey**. Unknown prekey → close. This is how the answerer learns who is calling. 3. **IK msg 2** — responder → initiator (framed). 4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s). @@ -137,13 +136,14 @@ After decrypt, classify the plaintext: | Prefix (4 bytes) | Kind | If unknown / invalid | |---|---|---| +| `rat ` | Double Ratchet chat frame (see Ratchet) | drop | | `loc ` | locator update | drop | | `prf ` | profile | drop | | `inv ` | Monero invoice | drop | | `rcp ` | Monero receipt claim | drop | -| `png ` | ping (reserved) | drop | +| `tip ` | Monero tip (receipt + memo) | drop | +| `png ` | ping (reserved; classify and drop) | drop | | `fil ` | file chunk | drop | -| `rat ` | Double Ratchet chat frame (see Ratchet) | drop | | `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) | | anything else | chat | store as a chat line | @@ -153,8 +153,7 @@ chat line. Older builds that stored `rat `-prefixed bytes as chat are obsolete; upgrade both sides. A peer that does not implement a typed prefix MUST still drop -`[a-z]{3}…` rather than render it as chat. Mixed-version 0.1.2 clients -that stored those as chat are obsolete; upgrade both sides. +`[a-z]{3}…` rather than render it as chat. Chat MUST NOT begin with three lowercase ASCII letters and a space. (Inside a `rat ` frame the plaintext is a chat line and is not re-classified.) @@ -170,6 +169,9 @@ form (type tag, then each field, `0x00` separators). Verify MUST accept that form and, for mixed-version peers, the legacy untagged LF-joined layout. Anything else fails closed. Do not emit the legacy layout. +`tip` is signed over the LF-joined fields only (no domain tag on encode today). +The `tip ` prefix is not signed. + The invite string is separate and keeps `onionwire-invite-v1` (see Invite). Older builds verify only the untagged bytes, so they reject tagged signatures @@ -255,7 +257,8 @@ ed25519_sign(identity_sk, accepted on verify. New invoices MUST use the domain-separated form. Do not emit legacy. -The frame is a signed claim, not a payment. +The frame is a signed claim, not a payment. It is one-shot: if the peer onion +is down, the send fails. There is no queued invoice. ### `rcp ` — receipt claim (we paid) @@ -279,8 +282,32 @@ emit legacy. Signature proves which friend sent the claim. It does **not** prove money moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns one transfer row with the same non-empty `txid`, `amount`, and `address` -(conjunction, not OR). RPC down → stay unverified. Wallet RPC is loopback -HTTP Digest; it is not this protocol. +(conjunction, not OR). RPC down or an unsynced daemon → stay unverified. +Wallet RPC is loopback HTTP Digest; it is not this protocol. + +### `tip ` — tip (we paid, with memo) + +Sent after a chain transfer, together with `rcp `. One-shot. + +``` +tip \n\n
\n\n\n +``` + +The `tip ` prefix is **not** signed. Encode signs the LF-joined fields: + +``` +ed25519_sign(identity_sk, + txid || LF || amount_atomic || LF || address || LF || memo || LF || ascii(ts)) +``` + +`memo` MUST NOT contain newlines. Same address and amount rules as invoices. +A peer that does not implement `tip ` MUST drop it as an unknown typed prefix, +not render it as chat. + +### `png ` — ping (reserved) + +Classified as ping and dropped. No ping body is defined in v1. Implementations +MUST NOT emit `png ` and MUST drop it inbound. ### `fil ` — file chunk @@ -288,11 +315,10 @@ Cap: 1 MiB reconstructed file. No resume. One Noise session per chunk. The sender is responsible for fitting the receiver's documented rendezvous budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average -interval between send attempts stays at least 3s — a margin under the 0.5/s -refill; pacing at exactly 2s sits on the refill boundary and drains under -jitter. A sender MAY retry an individual chunk a bounded number of times. -Exhausting retries fails the transfer. No outbox, no resume, no continuation -under a new `xfer_id`. +interval between send attempts stays at least 3s. A sender MAY retry an +individual chunk a bounded number of times (this tree: 3). Exhausting retries +fails the transfer. No outbox, no resume, no continuation under a new +`xfer_id`. ``` fil \n\n\n/\n @@ -314,7 +340,7 @@ is a chat line `[file] name (N bytes)`, never the raw frame. A chat send is ratcheted: the wire form of a chat message is a `rat ` frame (see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat line below. A bare chat frame with no typed prefix is still accepted inbound as -a chat line (v0.2.1 peers), but MUST NOT be emitted. +a chat line (older peers), but MUST NOT be emitted. UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the implementation does not drop the row). Control and bidi formatting @@ -334,9 +360,7 @@ one application frame, close — see Transport). Nothing else changes about the session. The ratchet header is **inside** the Noise transport message, never in clear on -the wire. That is a deliberate divergence from the shape this layer came from: -the plan assumed a plaintext header (`dh_pub || N || PN`) ahead of the -ciphertext, which was rejected because a plaintext header would hand an observer +the wire. A plaintext header (`dh_pub || N || PN`) would hand an observer per-message counters and ratchet-key changes for no benefit — the Noise session already hides the frame, so the header is authenticated as AEAD associated data instead. @@ -386,9 +410,8 @@ KDF_CK(chain_key): next_chain_key = HMAC-SHA256(chain_key, 0x02) ``` -`HKDF` is RFC 5869 with SHA-256 (`hkdf` 0.12), `HMAC` is SHA-256 (`hmac` -0.12). Each side of an epoch derives its chains from one shared DH output with -`KDF_RK` called **twice**: +`HKDF` is RFC 5869 with SHA-256, `HMAC` is SHA-256. Each side of an epoch +derives its chains from one shared DH output with `KDF_RK` called **twice**: ``` epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi): @@ -520,11 +543,9 @@ lets the peer step too. `ratchet_sessions` in the SQLCipher store: one row per friend (`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`, `state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x01` followed by -the implementation's serialized `RatchetState` (root, keypairs, both chain keys -and counters, `established`, and the skipped-key store). The state is -device-local: it is **never** transmitted, and its layout is not part of this -wire protocol. The store is encrypted as a whole, so the blob is ciphertext on -disk. +the implementation's serialized ratchet state. The state is device-local: it is +**never** transmitted, and its layout is not part of this wire protocol. The +store is encrypted as a whole, so the blob is ciphertext on disk. ### Not ratcheted @@ -570,8 +591,13 @@ Unknown `k`: prompt. Same `k`: update onion and prekey only. ## What v1 will not grow into -No DHT, no hosted server, no XMPP, no store-and-forward, no multi-device, no -A/V, no STUN/ICE/WebRTC, no SOCKS/C-tor fallback, no system DNS for friends. +No DHT, no directory server, no hosted/server-side outbox, no XMPP/Prosody, no +C-tor fallback, no multi-device, no A/V, no STUN/ICE/WebRTC, no system DNS for +friends. + +A **local-only** chat retry queue is in v1. It is not a mailbox and it never +leaves the device. “No outbox” in this document means **no server-side** +store-and-forward. Those are how Tox-over-Tor leaks (UDP DHT, mixed clearnet, “just one direct path”). They are out of scope, not postponed. diff --git a/docs/README.md b/docs/README.md index f6ce9ab..eb2fdbe 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,8 +9,23 @@ Read these in order if you are evaluating the protocol without the Rust: 3. **[SECURITY_AUDIT.md](SECURITY_AUDIT.md)** — in-house review notes and which findings are still open. **Not** a public third-party audit. -Operator / product docs stay in the [root README](../README.md). Android -build notes: [android/README.md](../android/README.md). SDK: +Operator / product docs: + +- **[../README.md](../README.md)** — install, run, real flags, F-key map, + wallet/chain source, releases. +- **[TUI.md](TUI.md)** — screens and keybindings as the TUI actually handles them. +- **[WALLET.md](WALLET.md)** — loopback wallet RPC, chain source, spend-authority + warning, receipt verification. +- **[RELEASING.md](RELEASING.md)** — manual, batched releases (not one per merge). +- **[ARTI_UPGRADE.md](ARTI_UPGRADE.md)** — how to bump the in-process Tor crates. + +Android build notes: [android/README.md](../android/README.md). SDK: [crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md). -Maintainers cutting a release: [RELEASING.md](RELEASING.md) — manual, batched -releases, not one per merge. + +Decision records and spike reports (history — not living operator docs): + +- [arti-socks-feasibility.md](arti-socks-feasibility.md) +- [option-a-recommendation.md](option-a-recommendation.md) +- [cuprate-launch-spike.md](cuprate-launch-spike.md) +- [cuprate-android-spike.md](cuprate-android-spike.md) +- [payment-integration-plan.md](payment-integration-plan.md) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index fe6b3b6..206ff39 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,7 +1,10 @@ # Releasing OnionWire -Policy and procedure for cutting a release. Read -[`README.md`](../README.md#releases-maintainers) for the short version. +How a maintainer cuts a release. This is **not** automatic: a merge to `main` +does not publish, and a tag push does not publish. Two dispatches, `dry_run` +first, Android APK joins the same tag. + +Short version: [`README.md`](../README.md#releases-maintainers). ## Policy: manual, batched releases diff --git a/docs/SECURITY_AUDIT.md b/docs/SECURITY_AUDIT.md index 3c2322b..cab9d75 100644 --- a/docs/SECURITY_AUDIT.md +++ b/docs/SECURITY_AUDIT.md @@ -2,7 +2,7 @@ **This is not a public third-party audit.** It is an in-house review of commit `2b42864` plus a status check against the current tree. Do not cite it -as “audited.” +as “audited.” OnionWire has not had a public external security assessment. Protocol: [PROTOCOL.md](PROTOCOL.md). Claims: [THREAT_MODEL.md](THREAT_MODEL.md). @@ -26,10 +26,11 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests - At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md). - Arti onion services are experimental. Fail closed; no C-tor fallback. -- No public third-party audit, no `cargo-audit` gate in CI as of the original pass. +- No public third-party audit. This file is not one. - Invite decode still accepts the legacy concat signature (compatibility). - Rate limit is availability, not traffic-analysis defense. - One-shot sessions: no channel binding across file chunks beyond “same Noise peer.” +- The in-process Cuprate chain daemon is opt-in and **unvalidated on mainnet**. ## Verified correct (original pass, still the protocol) diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9fd2b6c..9781368 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -1,8 +1,10 @@ # OnionWire threat model (v1) OnionWire is a two-party chat over Tor onion services. There is no chat server. -Wire format: [PROTOCOL.md](PROTOCOL.md). In-house review notes: -[SECURITY_AUDIT.md](SECURITY_AUDIT.md) — **not** a public third-party audit. +Identity is an ed25519 pubkey; the onion is a locator only (`F4` rotates the +locator, nothing else). Wire format: [PROTOCOL.md](PROTOCOL.md). Wallet: +[WALLET.md](WALLET.md). In-house review notes: [SECURITY_AUDIT.md](SECURITY_AUDIT.md) +— **not** a public third-party audit. Do not cite that file as “audited.” ## Tor relays are not a chat server @@ -207,7 +209,9 @@ the app does not pick a public remote node for them. for any serious purposes"*, and its `monerod` RPC parity is incomplete (Cuprate issue #278). This is why the source is an opt-in build feature and a stored user choice, never a default. - - The config pins **testnet**. Mainnet is not validated by this app. + - Mainnet is **unvalidated**. The TUI can store a mainnet choice (`F6` 1/2); + every in-process surface still says `testnet only — mainnet is unvalidated`. + Cross-compiled is not device-proven. - Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44, which cannot unify with this crate's 0.46), so the in-process daemon's P2P traffic is **clearnet**: your ISP sees that this device talks to Monero diff --git a/docs/TUI.md b/docs/TUI.md index f7744a5..9c52c70 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -1,964 +1,183 @@ -# OnionWire TUI — visual audit and design spec +# OnionWire TUI -This card does not change `src/`. Frames come from: +Operator map of the Linux terminal UI. Bindings live in `src/tui.rs` +(`function_key_for`, `parse_cmd`, per-screen `match` arms). This is not a +screenshot dump. -``` -cargo test --locked --test tui_frames -- --nocapture dump_audit_frames -``` +Run `onionwire` in a real terminal. `ONIONWIRE_ASCII` or `NO_COLOR` switches +ASCII chrome. -`tests/tui_chrome.rs` still locks helper **names** and **return strings**. Implementation -must keep `wordmark_banner`, `compact_banner`, `banner_for_width`, `onion_glyph`, -`status_footer`, `main_footer_hints`, `help_overlay_text`, `draw_share`, and `Pane` -working. Add helpers; do not rename those. +## Screens -## Gaps (could not render the live `App` frame) +`enum Screen` in `src/tui.rs`: -`App`, `App::draw`, `App::draw_main`, and every overlay except `draw_share` are -private and need `Arc` (Arti + store). This presentation-only test cannot -construct that. - -| Screen / state | What you get | Why | +| Screen | How you get there | What it is | |---|---|---| -| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** at the time of the audit; since the clean-look redesign (`draw_main_chrome`) it is **REAL** — see “Clean-look chrome redesign” below | `App` private | -| Help / `/who` overlay | **RECONSTRUCTED** — Rect math copied from private `draw_text_overlay` | private | -| Share / invite | **REAL** `draw_share` | public | -| Profile, paste, approve, rotate, wipe, quit, backup, restore, passphrase | **RECONSTRUCTED** — public `*_screen_text` / `ProfileEditor` copy inside `Block::bordered`, titles taken from `src/tui.rs` | private `draw_*` | -| Pay / invoice / file transfer | **No screen exists.** Footer `status_note` only (`invoice sent`, `sending`, `sent file {name}`, `send failed: {e}`) | not a gap in the test — a product finding | -| Tor bootstrap / disconnected HS | Not a TUI screen. `hs status: Bootstrapping` is stderr before `ratatui::init` | out of TUI draw | -| Color / `NO_COLOR` | Glyph dumps only. Color findings are from reading `src/tui.rs` | TestBackend prints symbols | - -Color, focus-by-border, and RGB-only styling are invisible in these dumps. Treat -the reconstruction as the glyph skeleton, not a screenshot of Color. - -## Deliverable 1 — before frames - -Trailing spaces in the live buffer are omitted here. Re-run the command for -byte-identical dumps, including 120x40 and 200x60. - -### 80x24 — chrome (`banner_for_width` + `status_footer`, real helpers) - -``` - .-~~-. .-~~-. .-~~-. ONIONWIRE - ( o )( o )( o ) identity = pubkey onion = locator - `-..-' `-..-' `-..-' tor messenger no server - - - - - -TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help -``` - -Same footer with `status_note = "send failed: connection timed out"` — the note -**does not appear**. Ident + hints win. Fail-closed copy is gone at 80 and at -120 (full onion eats the row). It only survives at 200. - -### 80x24 — RECONSTRUCTED main, empty - -``` - .-~~-. .-~~-. .-~~-. ONIONWIRE - ( o )( o )( o ) identity = pubkey onion = locator - `-..-' `-..-' `-..-' tor messenger no server -┌roster 0───────────────────┐┌chat─────────────────────────────────────────────┐ -│ ││no friends yet │ -│ ││F3 paste an invite to add one │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -└───────────────────────────┘└─────────────────────────────────────────────────┘ -┌composer──────────────────────────────────────────────────────────────────────┐ -│/wipe /wipe-all /profile /who /pay /tip /file │ -└──────────────────────────────────────────────────────────────────────────────┘ -TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help -``` - -### 80x24 — RECONSTRUCTED main, messages + stale + alert - -``` - .-~~-. .-~~-. .-~~-. ONIONWIRE - ( o )( o )( o ) identity = pubkey onion = locator - `-..-' `-..-' `-..-' tor messenger no server -passphrases do not match -┌roster 2 1 stale──────────┐┌chat alice──────────────────────────────────────┐ -│> alice aaaaaaaa… ││you: ping │ -│ bob-the-stale-peer bbbbb││them: pong │ -│ ││them: 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 │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -└───────────────────────────┘└─────────────────────────────────────────────────┘ -┌composer──────────────────────────────────────────────────────────────────────┐ -│hello from composer │ -└──────────────────────────────────────────────────────────────────────────────┘ -sent TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help -``` - -Roster clips `bob-the-stale-peer bbbbb` mid-glyph. Chat wraps (good). Focus on -chat/composer is **not** visible in the glyph dump (color-only in `pane_block`). - -### 80x24 — RECONSTRUCTED main, fail-closed send (note dropped) - -``` - .-~~-. .-~~-. .-~~-. ONIONWIRE - ( o )( o )( o ) identity = pubkey onion = locator - `-..-' `-..-' `-..-' tor messenger no server -┌roster 2 1 stale──────────┐┌chat bob-the-stale-peer─────────────────────────┐ -│ alice aaaaaaaa… ││no messages │ -│> bob-the-stale-peer bbbbb││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -└───────────────────────────┘└─────────────────────────────────────────────────┘ -┌composer──────────────────────────────────────────────────────────────────────┐ -│/wipe /wipe-all /profile /who /pay /tip /file │ -└──────────────────────────────────────────────────────────────────────────────┘ -TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help -``` - -`status_note` was `send failed: peer onion down`. The before frame above drops it. -`tests/tui_frames.rs` `status_footer_drops_send_failed_when_crowded` now asserts -the note **is** present at 80, 120, and 200, along with `TOR` / `me:` / `? help`. - -### 80x24 — `draw_share` (real) - -Invite is 346 chars. Inner width 78. Wraps mid-hex. Full v3 onion fits on its -own line. No QR blocks (locked). - -``` -┌(o) invite────────────────────────────────────────────────────────────────────┐ -│give this string to a friend; they F3 paste it │ -│ │ -│fp ea4a6c63… │ -│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ -│ │ -│onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22│ -│c:o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion:spk=0101010│ -│101010101010101010101010101010101010101010101010101010101:sig=46caf16b6da95e86│ -│… │ -└──────────────────────────────────────────────────────────────────────────────┘ -``` - -### 80x24 — RECONSTRUCTED help overlay (private `draw_text_overlay` math) - -Help is 22 content lines + border. Popup height is `min(lines, height-2)` = 22, -so it covers the banner, punches through roster/composer borders, and **clips** -`Esc closes this overlay`. - -``` - .-~~-. .-~~-. .-~~-. ONIONWIRE - ( o ┌? help─────────────────────────────────────────────────────────┐ - `-..-' │OnionWire keys │ -┌roster│ │───────┐ -│ │Tab / Shift-Tab cycle roster, chat, composer │ │ -│ │… │ │ -│ │/backup /path encrypted identity export │ │ -└──────│/restore /path overwrite self keys │───────┘ -┌compos│? this help │───────┐ -│/wipe │Ctrl-Q quit; type CLEAR or QUIT │ │ -└──────└───────────────────────────────────────────────────────────────┘───────┘ -TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help -``` - -### 80x24 — other overlays (copy is real) - -- Profile: `> name:` marker (good). Empty xmr is a blank value, not `(none)`. -- Paste: same wrap-mid-hex as share. Error state replaces the hint with the - error string (no "what next"). -- Approve / rotate / wipe / quit / backup / passphrase: full-screen bordered - column of copy + typed buffer. Readable. Fine as modal confirmations. -- `/who`: overlay Clear is only the popup rect; chat remnants (`d`, `ff`) show - in the side gutters. Full onion is shown (good). - -### 120x40 / 200x60 - -At 120, `status_footer` shows the **full** 62-char onion and still drops -`send failed: …`. At 200 the note survives in front of `TOR`. Banner stays the -3-line wordmark (width ≥ 63). Chat pane is large; hierarchy problem is worse -(more empty bordered void), not better. Dump: same cargo command. - -## Deliverable 2 — findings - -Walked in `tui-aesthetics` ladder order. - -### 1. Clipping / overlap - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **blocker** | `src/tui.rs:1505` `status_footer` candidate list | Fail-closed `status_note` (`send failed: …`) is skipped when ident+hints fill the row. Proven at 80 and 120. | Peer down looks like success. The product rule is "send visibly fails". | -| **major** | `src/tui.rs:1702` `draw_text_overlay` | No `Wrap`. Height clipped to `area.height-2`. At 80x24 help overlaps banner/roster/composer and drops the last line. | `?` is unreadable on the floor size. | -| **major** | `src/tui.rs:1355` roster `format!("{name} {fp}")` | No truncate. `bob-the-stale-peer bbbbb` clips inside the 36% pane. | Cannot tell who is selected/stale. | -| **major** | `src/tui.rs:1570` `draw_share` (and paste body) | 346-char invite wraps mid-token at inner width 78. | Mouse-select copy is split; easy to miss a continuation line. | -| **minor** | `src/tui.rs:1334` alert | Alert is one raw line, no wrap/truncate. | Long error will collide with roster on the next row. | -| **nit** | `tests/tui_chrome.rs:15` (and `src/tui.rs:1512`, `1707`) | Width via `chars().count()`. See deliverable 4. | CJK/emoji can wrap in a real terminal while tests stay green. | - -### 2. Hierarchy - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **major** | `src/tui.rs:1314` `draw_main` | Three-line wordmark + two equal bordered panes + bordered composer + footer. Chat is not the primary element. At 80x24, 3 rows of art + 3 composer + 1 footer + 2×2 borders leave the transcript starved. | First glance is ASCII onions, not the conversation. | -| **major** | `src/tui.rs:1340` | Roster is 36% of width on every size. | Chat (the primary pane) is the leftover. | -| **minor** | every `themed_block` / `pane_block` | Border on every pane, including composer and full-screen modals. | Eye cannot find content; "box drawing UI". | - -### 3. Spacing - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **minor** | `src/tui.rs:1328` banner vs `1367` lists | Banner has no inner pad; list/paragraph sit against borders; footer has no pad. Mixed 0 and 1. | Ragged left edge: chat `no friends yet` vs roster empty. | -| **nit** | `src/tui.rs:93` `/file /path` extra space vs other slash rows | Help columns almost align, one extra space. | Looks unfinished. Do **not** change `help_overlay_text` unless `tui_chrome` is updated — the string is locked. Leave the space. | - -### 4. States - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **major** | `src/tui.rs:1349` empty roster | `List` with zero items → blank pane titled `roster 0`. Empty copy lives only in chat. | Looks broken, not empty. | -| **major** | pay / tip / file | No pane. Outcome is a footer note that 80/120 may drop. | `/pay` and `/file` feel like they did nothing. | -| **minor** | `src/tui.rs:1414` empty composer | Placeholder is the slash cheatsheet, dim color only. | Reads as commands already typed. | -| **minor** | `src/tui.rs:1456` `no messages` | One word. No "type below, Enter sends". | Dead pane. | -| **nit** | loading | `sending` in footer, 100 ms poll, no spinner. | Correct. Keep. | - -There is no dedicated disconnected screen. Stale friends get a `stale` suffix -(`src/tui.rs:1357`) — keep the word, not color-only. - -### 5. Color - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **major** | `src/tui.rs:15-21` | Seven RGB colors. No 16-color map. No `NO_COLOR`. | 16-color and `NO_COLOR` terminals get garbage or still emit ANSI. | -| **minor** | `src/tui.rs:1359-1372` | Stale is `C_STALE` plus the word `stale` (ok). Selection is bg+fg+bold+`> ` (ok for roster). | Chat/composer focus is color-only (see focus). | - -Accent RGB `(232,165,75)` is fine as **the** accent. Do not add more hues. - -### 6. Focus - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **major** | `src/tui.rs:1468` `pane_block` | Focused chat/composer: accent border + bold title. No marker. Roster has `> `. | Monochrome / `NO_COLOR`: cannot see focus unless roster. Typing `j`/`k` feels dead. | - -### 7. Motion - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **nit** | `src/tui.rs:24` `TUI_POLL` 100 ms | Full `terminal.draw` every poll even with no keys, so background send can refresh status. | Acceptable. No decorative spinner. Do not redraw faster. | - -### 8. Copy - -| Sev | Where | Wrong | User impact | -|---|---|---|---| -| **minor** | `src/tui.rs:1583` paste error | Error replaces the paste hint. No "what next". | User sees `bad invite` and an empty buffer. | -| **minor** | `src/tui.rs:1415` | Composer placeholder is a command dump, not a verb. | Conflicts with `?` help. | -| **nit** | `src/tui.rs:36` | `fingerprint mismatch` is a good short fail-closed string when it actually reaches the footer. | Often dropped (finding 1). | - -### Untrusted text - -`src/tui.rs:1461` `String::from_utf8_lossy(&m.plaintext)` goes into `Paragraph` -with wrap, **no** control/bidi strip, **no** ellipsis cap. Profile `bio` / -`display_name` and paste buffer are the same class. A separate in-flight PR -owns sanitization — do not duplicate it here. Implementation must call that -helper (or the agreed strip) on every peer-supplied string before draw. - -## Deliverable 3 — spec (implement this) - -### Pane structure - -One primary element per screen. - -| Screen | Primary | Secondary | Chrome | -|---|---|---|---| -| Main | Chat transcript | Roster (left, **22 cells** at 80, **28** at 120+, not 36%) | 1-line header, 3-row composer, 1-row status | -| Share / paste / approve | The invite string / typed buffer | fp + onion above it | title `(o) invite` etc. Keep `draw_share` public | -| Profile | The three fields with `>` on the active one | — | title `(o) profile` | -| Rotate / wipe / quit / backup / restore / passphrase | The confirm copy + typed token | — | existing titles | -| Help | The help text, **full screen** when `height < 28`, else a centered overlay that **fits** (wrap, scroll if needed, never clip the last line) | — | title `? help` | -| `/who` | Profile fields | — | same overlay rules as help | -| Pay / file | **None.** Stay on main. Status line carries the result. | — | — | - -`draw_main` at `height <= 24` **must not** spend 3 rows on `wordmark_banner()`. -Use a one-line header. Do **not** change `banner_for_width(80)` — chrome tests -lock it to the wordmark. Add `main_header_line(width, fp, onion)` or call -`compact_banner()` plus ident. At `height >= 40`, the 3-line wordmark **may** -sit above the one-line ident; it is optional, not required. - -### Spacing unit - -**1 cell.** Apply as: - -- Header: no box. One space between fields. -- Roster / chat: `Block` with `Borders::ALL` **only on those two** (the primary - split). Inner text starts one cell after the border (ratatui default). -- Composer: **no** outer box. Prefix `> ` when focused, ` ` when not. One - blank row is not required; the 3-row slot stays for wrapped input. -- Footer: no box. One space between clusters, two spaces between clusters if - width ≥ 120. -- Overlays: one box around the popup. No nested padding. - -### Palette - -One accent. Semantic color only for state. Pair every color with a glyph or -label. - -| Role | RGB (keep) | 16-color | `NO_COLOR` | -|---|---|---|---| -| accent | `Rgb(232,165,75)` | `Yellow` | default + bold / reverse | -| text | `Rgb(196,214,176)` | `White` | default | -| dim | `Rgb(98,110,92)` | `DarkGray` | default | -| alert | `Rgb(220,80,70)` | `Red` | default + `! ` prefix | -| stale | `Rgb(210,180,80)` | `Yellow` | default + ` stale` (already) | -| highlight bg | `Rgb(48,42,28)` | `Reverse` | reverse | -| border | `Rgb(72,84,64)` | `DarkGray` | default | - -`NO_COLOR` set (empty or any value): no `Style` fg/bg at all. Glyphs and -weight only. - -Detection: `std::env::var_os("NO_COLOR")` is Some → no color. Else if the -backend is not a TTY or `TERM=dumb` → 16-color or no color, never RGB. -Else RGB as today. - -### Glyphs - -| Use | Unicode | ASCII fallback | +| `Main` | boot | Roster, chat, composer | +| `Share` | `F2` | Invite string (`onionwire:v1:…`) | +| `Paste` | `F3` | Paste a friend's invite | +| `Approve` | paste of unknown `k` | `y` accept / `n` reject | +| `Rotate` | `F4` | Type `ROTATE` to change the onion locator | +| `RotatePrekey` | `F8` | Type `ROTATE` to hard-cut the Noise static | +| `Wipe` | `/wipe` or `/wipe-all` | Type `WIPE` or `WIPEALL` | +| `Profile` | `/profile` | Edit name, bio, optional Monero address | +| `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | +| `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | +| `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | +| `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | +| `Quit` | `Ctrl-Q` | Type `CLEAR` or `QUIT` | + +Help (`?`) is an overlay, not a screen. `/who` / `F5` is an overlay on Main. + +There is **no `F7`**. Function keys that fire from Main, the settings menu, and +peer-payments are: + +| Key | `FunctionKey` | Action | |---|---|---| -| onion / share title | `(o)` (already) | `(o)` | -| focus | `> ` | `> ` | -| truncate | `…` (`src/tui.rs:1730`) | `...` (budget 3 cells) | -| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` | -| alert prefix | `! ` | `! ` | -| stale | word `stale` | `stale` | -| delivery: delivered | `✓` | `ok` | -| delivery: queued | `◷` | (word) `queued` | -| delivery: sending | `»` | (word) `sending` | -| delivery: failed | `✗` | (word) `failed` | +| `F2` | Share | Invite | +| `F3` | Paste | Paste invite | +| `F4` | Rotate | Onion locator | +| `F5` | Who | Selected friend's profile | +| `F6` | Wallet | Wallet screen | +| `F8` | RotatePrekey | Prekey hard cut | +| `F9` | OpenMenu | Wallets & settings | -`queued` / `sending` / `failed` always carry their state word, so the ASCII -fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it -falls back to `ok`. `delivery_glyph()` / -`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the -fallback path. +`F9` is live on Main, the settings menu, and peer-payments so a printed shortcut +never no-ops there. Other screens handle their own keys (Esc back, typed +confirms). -No emoji. `onion_glyph()` stays for callers that already use it; do not put it -on the main header. +## Main -ASCII chrome when `ONIONWIRE_ASCII` is set **or** when `NO_COLOR` is set (same -switch is enough; do not add a crate). +Focus starts on the composer. Footer hints (`main_footer_hints`): -### Focus +``` +Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q +``` -Never color alone. +Pane-specific (`pane_footer_hints`): -- Roster: keep `highlight_symbol("> ")` + bold. Unselected rows start with two - spaces so columns align. -- Chat: title becomes `> chat {name}` when focused, ` chat {name}` when not, - plus bold on the `> ` title. -- Composer: `> ` prefix on the input row when focused (see spacing). -- `Tab` cycle unchanged (`Pane` tests lock it). - -### `status_footer` priority (must change) - -Replace the current "first candidate that fits, dropping the note" list. - -Build left-to-right, **never drop** a non-empty `status_note`: - -1. `status_note` (truncate with `…`/`...` to a minimum of 12 cells if needed). -2. `TOR me:{8}…` (keep `me:` — chrome tests require it). -3. `onion:` + full onion if it fits, else 8-char truncate (keep today's - `width >= 110` full-onion rule if it still fits **after** the note). -4. Hints from `main_footer_hints()`, dropping from the left of that list. -5. Always end with `? help`. - -`? help` and `TOR` and `me:` must still be present at 80 and 120 so -`tests/tui_chrome.rs` stays green. - -Fail-closed copy is `send failed: {e}` or `fingerprint mismatch`. Prefix `! ` -when color is off. - -### Copy — non-happy states - -Do not soften fail-closed into a loader. - -| State | Copy | +| Pane | Hint | |---|---| -| no friends, roster | list item `no friends` (so the pane is not blank) | -| no friends, chat | `no friends yet` / `F3 paste an invite to add one` (keep) | -| friend, no messages | `no messages` / `type below, Enter sends` | -| nothing selected send | `no friend selected` (keep) | -| sending | `sending` (keep, no spinner) | -| sent | `sent` | -| peer down / send err | `send failed: {e}` (visible) | -| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding | -| queued + terminal failure | `{n} queued, send failed: {short}` | -| terminal failure | `send failed: {short}` (`{f} failed` when more than one) | -| already sending | `already sending` (keep) | -| stale friend | `stale` suffix (keep) | -| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` | -| paste error | `{err}` then `Enter resubmits Esc back` | -| unknown slash | `unknown command {cmd}` (keep) | -| passphrase mismatch | `passphrases do not match` (keep, alert line) | +| Roster | `j k select F3 add F6 wallet F9 settings ? help` | +| Chat | `j k scroll g G ends F4 rotate F9 settings ? help` | +| Composer | `Enter send / commands F9 settings ? help` | -### Before → after mockup (80x24 main) +| Key | Action | +|---|---| +| `Tab` / `Shift-Tab` | Cycle roster → chat → composer | +| `1` / `2` / `3` | Focus roster / chat / composer when not typing | +| `j` `k` / arrows | Move or scroll the focused pane | +| `g` / `G` | Top / bottom of the focused pane | +| Enter | Send chat, or run a `/command` | +| `Esc` | Close overlay / clear composer | +| `?` | Help (except on Paste, so `?` can be in a payload) | +| `Ctrl-Q` | Quit prompt | -**After** (target). Header 1 line. Roster 22-ish. Chat primary. Composer no -box. Fail-closed note kept. Focus marker on composer. +## Composer commands + +`parse_cmd` (`src/tui.rs`). Unknown `/foo` is sent as chat if it does not match. + +| Command | Effect | +|---|---| +| `/who` | Same as `F5` | +| `/profile` | Profile editor | +| `/pay [memo]` | Invoice (`inv `), one-shot | +| `/tip [memo]` | Transfer + `rcp ` + `tip `, one-shot | +| `/file /path` | File send, 1 MiB, one-shot | +| `/wallet create` | Same as `F6` then `c` | +| `/wallet import` | Same as `F6` then `i` | +| `/settings` | Same as `F9` | +| `/backup /path` | Encrypted identity export | +| `/restore /path` | Overwrite self keys | +| `/wipe` | Type `WIPE` — chat/payments/outbox; identity stays | +| `/wipe-all` | Type `WIPEALL` — delete data dir; new person | + +## Share / paste / rotate + +- **F2.** Full invite. `C` copies it (OSC 52). Esc back. +- **F3.** Paste buffer, Enter submits. Unknown `k` → Approve (`y`/`n`). Same `k` + updates locator and prekey only. +- **F4.** Type `ROTATE`. Identity fingerprint unchanged. Online friends get + `loc `; offline friends must F3-paste the new invite. +- **F8.** Type `ROTATE`. Prekey is the Noise static **and** the ratchet bootstrap + seed. Every friend must F3-paste the new invite. Status: + `prekey rotated · friends must F3-paste your new invite`. + +## Wallet (`F6`) + +Footer: ``` -onionwire tor me:abcdef01 onion:abcdefgh -┌friends 2 1 stale┐┌chat alice───────────────────────────────────────────────┐ -│ alice aaaaaaaa…││you: ping │ -│> bob bbbbbbbb… s││them: pong │ -│ ││them: this is a very long chat line that should wrap │ -│ ││inside the chat pane instead of running off the edge │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -└──────────────────┘└──────────────────────────────────────────────────────────┘ -> hello from composer -! send failed: peer onion down TOR me:abcdef01 ? help +c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` -Roster names truncate with ellipsis, not mid-letter. `stale` may abbreviate to -`s` only if the word does not fit; prefer keeping `stale`. +| Key | Effect | +|---|---| +| `r` or Enter | Toggle receive-address QR | +| `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | +| `i` | Import 25-word seed | +| `s` | Start app-owned wallet child | +| `x` | Stop child (idempotent) | +| `p` | Probe child (RPC answering? chain at tip?) | +| `1` | In-process Cuprate **mainnet pruned** (unvalidated) | +| `2` | In-process Cuprate **mainnet full** (unvalidated) | +| `3` | In-process Cuprate **testnet** | +| Esc | Back to Main | -### Before → after mockup (80x24 help) +The chain line for an in-process source always carries +`testnet only — mainnet is unvalidated` (`cuprate::TESTNET_ONLY`). Starting +Cuprate needs `--features cuprate-daemon`; without it, start fails with that +feature name. -**After:** full-screen, no punch-through. Last line visible. `help_overlay_text()` -body unchanged (chrome tests). +Create/import require the wallet RPC started with `--wallet-dir`. Filename: +`onionwire`. Seed is never collected on the composer. -``` -┌? help────────────────────────────────────────────────────────────────────────┐ -│OnionWire keys │ -│ │ -│ Tab / Shift-Tab cycle roster, chat, composer │ -│ 1 / 2 / 3 focus roster / chat / composer │ -│ j k or Up Down move or scroll focused pane │ -│ g / G jump to top / bottom │ -│ Enter send chat to selected friend, or a /command │ -│ Esc close overlay, go back, clear composer │ -│ F2 share invite │ -│ F3 paste invite │ -│ F4 rotate onion locator │ -│ F5 selected friend's profile (/who) │ -│ /profile edit name, bio, Monero address │ -│ /pay [memo] invoice to receive │ -│ /tip [memo] pay selected friend │ -│ /file /path send file to selected friend (1 MiB) │ -│ /backup /path encrypted identity export │ -│ /restore /path overwrite self keys │ -│ ? this help │ -│ Ctrl-Q quit; type CLEAR or QUIT │ -│ │ -│Esc closes this overlay │ -└──────────────────────────────────────────────────────────────────────────────┘ -``` +## Wallets & settings (`F9` / `/settings`) -If the body still overflows 24 rows with the border, **scroll** the paragraph; -do not clip. Do not edit the locked help string to shrink it. +Discovery layer, not a replacement. Function keys stay live on this screen. +Rows name the shortcut they sit beside (`F6 c`, `F6 i`, `F6 r`, `F6 s/x`, +`F6 p`, `/profile`, `/backup`, `/wipe`, …). -### Left alone (on purpose) +- **No credentials** on this screen. Login, seed, and passphrase are never + passed into the menu snapshot. +- `c` copies the receive address (OSC 52). +- `p` opens peer payment history for the selected friend (`Node::list_payments`). +- Esc back to Main. -- Wire protocol, session, store, send path. -- Peer-text sanitization (other PR). Render must call it once it exists. -- Fail-closed semantics. Only the **visibility** of the error changes. -- Locked helper names and `help_overlay_text` / wordmark strings. -- No QR. Invite stays a string. -- No dedicated pay/invoice/file screens in v1. -- No spinner. `TUI_POLL` 100 ms stays. -- `docs/PROTOCOL.md` unchanged. -- No new crates on the implementation card unless `unicode-width` is approved - (deliverable 4). +The menu **shows** endpoint state; it does not edit a stored RPC URL. The error +copy for an unconfigured wallet still says “open F7” (`src/wallet.rs`); that +key does not exist. Set `ONIONWIRE_WALLET_RPC` or use `F6` create/import and +the child. -## Deliverable 4 — `chars().count()` is not terminal cells +Chain source (binaries, remote host) is stored via `Node::set_wallet_child_config`. +The desktop TUI's in-process picker is `F6` keys `1`/`2`/`3`. There is no +on-screen editor for an external RPC URL or a remote daemon host. -`tests/tui_chrome.rs` asserts `line.chars().count() <= width`. Same metric in -`status_footer` (`src/tui.rs:1512`) and `draw_text_overlay` (`src/tui.rs:1707`). +## Peer payments (`F9` then `p`) -| Input | `chars().count()` | Terminal cells (East Asian Width; emoji Wide) | -|---|---|---| -| `你好` | 2 | **4** (both Wide) | -| `e\u{0301}` (e + combining acute) | 2 | **1** | -| `🧅` (U+1F9C5) | 1 | **2** | +Peer-scoped signed invoices and tips, not the wallet's own transfer list. +`j`/`k` or arrows select. Esc back. Footer: `Esc back up/down select F9 menu ? help`. -A line of twenty `你` is 20 chars and 40 cells: the test passes at width 80, -the terminal wraps. A combining-mark string can look "too long" to the test and -still fit. +## Delivery markers (chat) -**Fix (implementation card, approved-then):** measure in cells. `unicode-width` -is already in the lockfile via ratatui but **not** a direct dependency. Do not -add it on this card. Preferred: depend on `unicode-width` explicitly and assert -`UnicodeWidthStr::width(line) <= width as usize`. Until then, keep the existing -`chars().count()` tests green; do not rewrite them to fit a redesign. +| Row state | Marker | +|---|---| +| delivered | `✓` | +| queued | `◷ queued (try n/8, retry …)` | +| sending | `» sending` | +| failed | `✗ failed: …` | +| inbound | no marker | -`tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three -examples without adding a crate. +Footer `{n} queued` while anything is outstanding. File transfer and payments +have no queue — outcome is a status note (`invoice sent`, `tip sent`, +`send failed: …`). -## After frames (spacing / ASCII / wrap / copy) +## Size -Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer, -1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged -here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line -header without buying hierarchy). - -### 80x24 — `draw_share` after (field-boundary wrap) - -Invite lines break on `:`. `sig=` hex that does not fit continues as an -all-hex line. Joining those lines (no extra spaces) is the original payload. - -``` -┌(o) invite────────────────────────────────────────────────────────────────────┐ -│give this string to a friend; they F3 paste it │ -│ │ -│fp ea4a6c63… │ -│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ -│ │ -│onionwire:v1: │ -│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │ -│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │ -│spk=0101010101010101010101010101010101010101010101010101010101010101: │ -│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│ -│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │ -└──────────────────────────────────────────────────────────────────────────────┘ -``` - -### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`) - -No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`. - -``` -+(o) invite--------------------------------------------------------------------+ -|give this string to a friend; they F3 paste it | -| | -|fp ea4a6c63... | -|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion | -| | -|onionwire:v1: | -|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: | -|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: | -|spk=0101010101010101010101010101010101010101010101010101010101010101: | -|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0| -|5401b0af934cefea617f71466f406af4bef956847200a8e915190b | -+------------------------------------------------------------------------------+ -``` - -### 80x24 / 120x40 — main chrome after - -Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump: +Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames -``` - -Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is -`no messages` / `type below, Enter sends`; paste error is `{err}` then -`Enter resubmits Esc back`; alerts truncate to the frame width. - -## Delivery state (outbox) — implemented - -Per-message state, read from the local outbox. The states are the store's own -(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire -prefix, no server. - -| Row | Marker | -|---|---| -| delivered | `you: ping ✓` | -| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` | -| sending | `you: pong » sending` | -| failed | `you: pong ✗ failed: connection timed out` | -| inbound | `them: pong` (no marker) | - -- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / - `retry now` comes from the stored absolute `next_attempt_at`. -- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and - capped at 24 cells (`short_send_reason`). -- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a - fail-closed `send failed: {short}` statement (with `! ` when colour is off). -- The tag trails the body and wraps with it, so it is never clipped away. - -Correlation: a delivered row is deleted from the outbox, so an outbound message -with no row is `Sent`; pending rows are joined to messages on the row id — -`store::Message::id` equals `OutboxEntry::message_id` (`chat_with_delivery`). -Two identical bodies are distinct rows with distinct ids, so the marker always -lands on the row that actually owns the outbox entry. - -### Size floor / target - -- **Floor: 80x24.** Everything above must render there. -- **Target: 120x40.** -- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping` - draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat - and footer row is `<=` the terminal width, that the markers render, and that - an over-long message wraps instead of being clipped. -- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`. - -## WALLETS & SETTINGS menu (F9 / `/settings`) — implemented - -The Monero wallet and the cuprate node shipped behind function keys only: a user -who did not already know F6 opened the wallet could not find wallet setup, the -child wallet, the chain source or the settings. F9 (`/settings`) is the -discoverable surface. It is a **screen, not a popup**, and it is a discovery -layer, not a replacement: F2, F3, F4, F5, F6 and F8 all keep working, and they -stay live *on this screen* so no row can print a key that does nothing there. - -``` cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps ``` - -dumps the menu at 80x24, 120x40 and 200x60 in both the configured and the -unconfigured state. - -### Rows - -Layout is ` label value … keys`: a 9-cell label column, the value truncated -in **cells** with the chrome's ellipsis, and a 12-cell key column right-aligned -so the eye can run down it. Every actionable row names the key or command that -fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, -`F6 s/x`, `F6 p`), so the menu teaches the shortcuts it sits beside. - -| Group | Row | Value | Key | -|---|---|---|---| -| WALLET | endpoint | `configured · connected` / `configured · not connected` / `not configured · receive-only` | — | -| WALLET | child | `{chain source} · running` / `not started` | `F6 s/x` | -| WALLET | sync | chain readiness word (`chain at tip · wallet answering`, `wallet answering · chain not at tip`, `wallet RPC not answering yet`, `child exited`, `not probing · no chain source`) | `F6 p` | -| WALLET | receive | the receive address (truncated) or `no address yet · wallet unreachable` | `c copy` / `F6 r` | -| WALLET | balance | `{xmr}` / `off` / `err` | `F6` | -| WALLET | transfers | `{n} recent` / `no transfers yet` — the wallet's **own** transfer list | `F6` | -| WALLET | payments | `{n} with {peer}` / `no history with {peer}` / `no friend selected` / `history unreadable · {peer}` — the **peer's** payment rows | `p` | -| WALLET | create | `/wallet create · seed shown once` | `F6 c` | -| WALLET | import | `/wallet import · 25-word seed` | `F6 i` | -| SETTINGS | nickname | the self-profile name, or `(none)` | `/profile` | -| SETTINGS | profile | `bio set · xmr set` | `/profile` | -| SETTINGS | identity | `{fp}… · identity = pubkey` | `F2` | -| SETTINGS | colour | `auto · follows NO_COLOR / TERM` | — | -| SETTINGS | backup | `encrypted identity export` | `/backup` | -| SETTINGS | restore | `overwrite self keys from a backup` | `/restore` | -| SETTINGS | wipe | `messages · identity and friends stay` | `/wipe` | -| SETTINGS | wipe-all | `deletes your identity key · new person` | `/wipe-all` | - -20 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. - -`transfers` and `payments` are deliberately two rows: `transfers` is the -wallet's own list (`Node::wallet_recent_transfers`, F6), `payments` is the -peer-scoped history (`Node::list_payments`, `p`). Signed `/pay` invoices and -`/tip` receipts a peer sent never appear in the wallet's own transfers, so the -two histories are not interchangeable and the menu names both. - -### Guarantees - -- **No credentials.** `WalletMenuState` carries booleans, labels and - display-ready error strings from `Node`'s getters. It is never given - `WalletConfig::rpc_login`, `secret()`, a seed or a passphrase, so the screen - cannot render one. -- **Untrusted text is display data.** Every value goes through - `sanitize::display_text` plus a newline/tab strip before it is placed on a - row, so a multi-line or bidi-laden error cannot split a row or reorder it. -- **Cells, not chars.** `cell_width()` measures with ratatui's own - `Span::width` — the same code path the renderer truncates with. - `unicode-width` is not a direct dependency of this crate, so no crate was - added; `chars().count()` is never used for a width. -- **Colour is never the only signal.** Each state word is present as a word - (`not connected`, `child exited`, `not probing`, `no transfers yet`); the - tone only answers "what is this?". -- **Copy without a clipboard crate.** `c` writes the receive address through - OSC 52 (`ESC ] 52 ; c ; BEL`): the terminal owns the clipboard, the - address never touches a file, and it still works over SSH. A terminal that - does not implement OSC 52 ignores the sequence; `F6 r` still shows the QR. -- **ASCII fallback.** The section rule is `─`, or `-` under `ONIONWIRE_ASCII` / - `NO_COLOR`, alongside the existing ellipsis swap. No emoji. - -### Reachable-from-the-TUI gaps this card does not close - -Named in the PR body's feature-analysis table. All of them need backend or -sibling-card work, not presentation: - -- `Node::wallet_config()` / `Node::wallet_save_config(cfg)` / - `Node::wallet_test_connection(..)` — the endpoint config screen is F7 on - `feat/wallet-create-import`; the menu shows the endpoint's *state* and leaves - the key free. -- Peer payment history — **closed by this screen.** `Node::list_payments` exists - on `main`; the `payments` row (key `p`) opens the peer-scoped history, and the - row is distinct from the wallet's own transfer list (`transfers`, F6). -- `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and - probed, not edited. -- `Node::set_petname(..)` — no petname editor exists. - -## Peer payment history (F9 → `payments`, key `p`) - -A screen, not a popup, and peer-scoped: it renders what -`Node::list_payments(&friend_pk)` returns for the chat's selected friend, so the -signed `/pay` invoices and `/tip` receipts a peer sent are visible even though -they never appear in the wallet's own transfer list (F6). The call takes the -store lock only — no Tor dial, no wallet RPC — so it is safe while offline or -while Arti is still bootstrapping, and an empty result (`Ok(vec![])`) is the -**no history** state, never an error. - -``` -cargo test --locked --test tui_payments -- --nocapture peer_payments_frame_dumps -``` - -dumps the screen at 80x24, 120x40 and 200x60, populated and empty. - -### Layout - -``` - dir kind amount XMR receipt memo -> in receipt 0.025 verified lunch money - out tip 0.005 coffee - out invoice 0.1 rent - - tx 3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041 - addr 4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMW - aC8iqPUE9XUBFGrLyDz4DpEBM -``` - -- Rows are **newest first**: `payments.id` ascending is oldest first, so - `PeerPaymentsState::from_payments` reverses it and the render path windows the - result. Rows outside the window are counted in an explicit `… N older` / - `… N newer` line — nothing is dropped silently. -- The focused row is marked with `>` **and** bold, so focus survives a - monochrome terminal. `up`/`down` (or `k`/`j`) move it, `Esc` returns to the - main screen, `F9` reopens the menu. -- `F9` is honoured **while this screen is open**, not only from the main screen: - the function-key table (`function_key_for`) answers it from `Main`, - `WalletsSettings` and `PeerPayments` alike, so the hint the screen prints - cannot be a no-op there. `peer_payments_footer_hint()` is the single place that - hint string is written, and the frame-dump fixture is driven from it — a dumped - frame cannot show a footer the app does not render. -- The selected row's `tx` and `addr` are spelled out under the rows: a 64-hex - txid is unusable truncated, and a 95-character base58 address is **wrapped** - over two lines rather than clipped to a prefix. -- Amounts use `pay::atomic_to_xmr_str`, the same piconero formatter the chat - lines use; the XMR unit is stated once, in the column header. -- Columns are dropped from the right when the pane is narrower than they need, - so no row can wrap or overrun at any width — not just at 80. - -### States - -| State | Frame | -|---|---| -| populated | the rows, plus the selected row's `tx` / `addr` | -| empty | `no payments with {peer}` and `invoices, receipts and tips from this peer land here` | -| read failed | `could not read payments` plus the sanitized reason — never a blank pane | -| no friend selected | the menu row refuses before the screen opens (`no friend selected` in the status line) | - -### Guarantees - -- **Memo is peer-signed text, sanitized at draw time.** `Node::list_payments` - returns `memo` as stored; the row goes through the same - `menu_cell_text`-then-`fit_cells` path the F9 menu uses, so C0/C1 controls, - ESC, bidi marks and newlines cannot reach the frame buffer or split a row. - `tests/tui_payments.rs` asserts a hostile memo (ESC, BEL, C1, bidi, newline) - never appears in a rendered frame. -- **Only receipts carry `verified`.** The flag column prints `verified` / - `unverified` for receipts and stays blank for invoices and tips, which have no - signature to check; `unverified` also takes the warn tone, so colour is never - the only signal. -- **Read-only.** The screen reads one getter and draws; it cannot send, sign or - dial. -## Clean-look chrome redesign — implemented - -The main screen was restructured around one accent, one primary pane and honest -states. The render path is no longer reconstructed in the dump: `App::draw_main` -builds a `MainView` of plain data and hands it to the public `draw_main_chrome`, -which is exactly what `tests/tui_frames.rs` draws. There is no stand-in layout, -so a frame dump is the real screen. - -``` -cargo test --locked --test tui_frames -- --nocapture dump_audit_frames -``` - -dumps every state below at 80x24, 120x40 and 200x60. - -### Hierarchy - -| Row | Content | Style | -|---|---|---| -| 0 | `onionwire {glyph} tor {phase} me:{fp8} onion:{onion8}` | app name bold text, phase semantic, identity muted | -| 1 | the alert (`send failed: …`, `fingerprint mismatch`) — only when set | alert | -| 2..h-4 | roster (22 cells at 80, 28 at 120+) next to the chat transcript | roster rows text/stale, focus marker on the focused pane | -| h-3..h-1 | composer, **no frame**, 3-row slot for wrapped input | `> ` marker + bold when focused, `message` muted when empty | -| h-1 | `{note} {glyph} TOR {phase} me:{fp8} {pane hints} ? help` | muted; phase semantic | - -The header no longer takes the accent — the accent is reserved for focus, which -is what let the header stop competing with the panes. - -### Tor phase is a first-class state - -`Node::tor_state()` was already cheap, read-only and unused by the TUI. It now -feeds `TorPhase` (one word + one glyph, both in the header and the footer), so -"connected" is never implied: - -| `hs::TorState` | `TorPhase` | glyph / ASCII | word | tone | -|---|---|---|---|---| -| `Bootstrapping` | `Connecting` | `…` / `...` | `connecting` | muted | -| `Published` | `Ready` | `✓` / `ok` | `ready` | text | -| `DegradedReachable` | `Degraded` | `!` | `degraded` | stale | -| `Stopped` | `Off` | `x` | `off` | alert | - -No new data field was needed: `App` already holds `Arc`, and this is a -read-only getter, not a store read from the render path. - -### States - -``` -onionwire ✓ tor ready me:abcdef01 onion:abcdefgh -┌roster 2 1 stale───┐┌> chat alice───────────────────────────────────────────┐ -│> alice aaaaaaaa… ││you: ping ✓ │ -│ bob-the-sta… stale││them: pong │ -│ ││them: 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 │ -└────────────────────┘└────────────────────────────────────────────────────────┘ - message -✓ TOR ready me:abcdef01… j k scroll g G ends F4 rotate F9 settings ? help -``` - -``` -onionwire … tor connecting me:abcdef01 onion:abcdefgh -┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ -│no friends ││no friends yet │ -│F3 adds one ││F3 paste an invite to add one │ -│ ││tor connecting — first publish takes a few minutes │ -└────────────────────┘└────────────────────────────────────────────────────────┘ - message -… TOR connecting me:abcdef01… j k select F3 add F6 wallet F9 settings ? help -``` - -``` -onionwire x tor off me:abcdef01 onion:unset -fingerprint mismatch -┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ -│no friends ││no friends yet │ -│F3 adds one ││F3 paste an invite to add one │ -│ ││tor off — no onion service is running │ -└────────────────────┘└────────────────────────────────────────────────────────┘ - message -x TOR off me:abcdef01… j k select F3 add F6 wallet F9 settings ? help -``` - -The error state puts the fail-closed sentence on the alert row **once**; the -footer keeps the phase and the hints instead of repeating it. The outbox note -(`peer unreachable, queued (1/8, retry 45s)`) still outranks the hints when a -row is outstanding. - -### Footer variants - -| Helper | Identity | Used by | -|---|---|---| -| `status_footer(w, fp, onion, note, hints)` | `TOR`, `onion:` | locked chrome tests and every non-main screen | -| `status_footer_phased(w, fp, onion, phase, note, hints)` | `{glyph} TOR {word}`, `onion:` | F9 menu | -| `status_footer_compact(w, fp, phase, note, hints)` | `{glyph} TOR {word}` only | main (its header already carries `me:` and `onion:`) | - -The main footer drops the onion because the header one line above already prints -it; those cells go to the hints. `TOR`, `me:` and `? help` survive at 80, 120 -and 200 in every variant — `tests/tui_chrome.rs` asserts it. - -`pane_footer_hints(Pane)` changes the hint cluster with the focused pane -(roster / chat / composer) and every variant keeps `F9` and `? help`, so the -menu stays discoverable and the overlay stays reachable wherever the cursor is. - -### Levers from the reference (applied / skipped) - -Applied: one accent for focus (focused border, selected row, active-conversation -marker); focus as marker + weight (`> ` plus bold title, visible with colour -stripped); border weight = focus; one unframed muted footer that follows the -pane and the phase; designed empty / connecting / degraded / off states; -semantic colour only; outbox and stale state as marker + word. - -Skipped: the 3-line wordmark above the header at height ≥ 40 (fights the 1-line -header without buying hierarchy); bottom-anchoring the composer inside its -3-row slot (needs cell-accurate wrap prediction for no legibility gain); -per-row colour in the roster (name and fingerprint share one style so a narrow -pane can drop the fingerprint without changing the row's meaning). - -### Width - -`status_footer*`, `alert_line`, `main_header_line*`, `draw_text_overlay`, -`roster_row_text` and `fit_cells` all measure cells (`Span::width`), never -`chars().count()`. The roster row spends its budget on the name first, then the -`stale` word, then whatever is left on a fingerprint prefix — a 22-cell pane -reads `bob-the-sta… stale`, not `… bbbbbbbb… stale`. - -## Invite screen: the payload region (mouse-copy) - -OnionWire never turns on mouse capture (`grep -rn EnableMouseCapture src/` is -empty), so sharing an invite means the terminal's own drag-select. A drag copies -every cell it crosses — and `draw_share` used to render the payload inside -`themed_block("(o) invite")`, which is `Borders::ALL`: every payload row sat -between `│` at column 0 and `│` at the last column, so the pasted string carried -border glyphs. - -The payload now gets its own region: **flush at column 0, full frame width, no -block, no title, no gutter on any row it occupies**. Everything that is not the -payload — why it exists, `fp`, `onion`, the copy key — lives in the bordered -block *above* it. The layout is `Layout::vertical([Length(body + 2), Min(0)])`, -so the chrome block grows with its own content and the payload always starts on -the row after its bottom border. - -``` -===== draw_share (real) 80x24 ===== -┌(o) invite────────────────────────────────────────────────────────────────────┐ -│give this string to a friend; they F3 paste it │ -│fp ea4a6c63… │ -│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ -│select the link below with the mouse, or press C to copy │ -└──────────────────────────────────────────────────────────────────────────────┘ -onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: -o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: -spk=0101010101010101010101010101010101010101010101010101010101010101: -sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e054 -01b0af934cefea617f71466f406af4bef956847200a8e915190b -``` - -At 120x40 and 200x60 `fp` and `onion` share one row (the block is one line -shorter); the payload region is unchanged. `wrap_invite` still breaks on `:`, so -joining the payload rows (trailing pad cells aside) is the payload byte for byte. -`tests/tui_chrome.rs` renders `draw_share` at 80x24, 120x40, 200x60 and 60x20 and -asserts exactly that, and that no row carrying payload carries `│`, `|`, `┃`, -`+`, `-` or `┄`. - -### `C` — the explicit copy affordance - -`C` on the invite screen writes the payload to the terminal's own clipboard with -OSC 52 (`osc52_copy_sequence`, the same sequence the F9 menu uses for the receive -address — no crate, no clipboard daemon, works over SSH). A terminal that does -not implement OSC 52 ignores the sequence, so the screen names the mouse -selection too; the line reads `select the link below with the mouse, or press C -to copy` whenever the block is wide enough, and `press C to copy, or select the -link below` otherwise. `?` lists the key as `F2 share invite (C copies it)`. - -The copy has no transient confirmation of its own: `draw_share` takes only the -payload, and `status_note` is not rendered on this screen. The mouse remains the -path that always works. diff --git a/docs/WALLET.md b/docs/WALLET.md index abf3c26..6e431e2 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -8,405 +8,214 @@ receipt checks (`get_transfers`). `/tip` is off. **Spend is opt-in** at wallet create or restore (seed-backed). That makes OnionWire a local spend authority for that wallet file — see the spend-authority -warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md). +warning below. Threat model: [THREAT_MODEL.md](THREAT_MODEL.md). TUI keys: +[TUI.md](TUI.md). -The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, and it can -own that process itself: +The app talks to `monero-wallet-rpc` over **loopback HTTP Digest only**, and it +can own that process itself: - hand out a receive subaddress for `/pay` invoices (`create_address`), - read incoming transfers to verify a peer's receipt (`get_transfers`), - and — only if you opted into spend — `/tip` (`transfer`). -**Prefer view-only until you actually want `/tip`.** Everything else in this -document explains why, and what breaks when you do. +**Prefer view-only until you actually want `/tip`.** + +Wallet RPC is never on clearnet and never over `.onion`. Chain traffic is off +unless you opted into a wallet and chose a source. A remote daemon is untrusted +(`--trusted-daemon` is never passed). + +## Ports (do not swap these) + +| Port | What it is | +|---|---| +| **18081** | App-owned **local** daemon unrestricted RPC (`DEFAULT_MONEROD_RPC_PORT` in `src/wallet_child.rs`). Spawned `monerod` and in-process Cuprate both bind `127.0.0.1:18081`. The wallet child dials that. | +| **18089** | A daemon's *restricted*-RPC port. It belongs only in examples of a **remote** `--daemon-address` you type. Not the app-owned local port. | +| random loopback | App-owned `monero-wallet-rpc` bind (`127.0.0.1:0`, then the port is kept). | + +A doc or config that puts the local child on 18089 is wrong. ## The app-owned wallet child -`src/wallet_child.rs` owns the child pair instead of asking you to start it and -export an env var: +`src/wallet_child.rs` owns the child pair instead of asking you to export an +env var: - **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random - free loopback port** (bind `127.0.0.1:0`, read the port, drop the listener, pass - it on — two instances on one box cannot collide), a generated `--rpc-login` - (`user:pass`, random `[a-z0-9]`, no shell or HTTP metacharacters), and - `--wallet-dir $ONIONWIRE_HOME/wallet`. -- **`monerod`** is spawned too when the chain source is *local*: + free loopback port**, a generated `--rpc-login` (`user:pass`, random + `[a-z0-9]`), and `--wallet-dir $ONIONWIRE_HOME/wallet`. +- **`monerod`** is spawned when the chain source is *local*: `--non-interactive --data-dir --rpc-bind-ip 127.0.0.1 --rpc-bind-port - 18081`. One box, one daemon: the wallet child dials it at `127.0.0.1:18081`. + 18081`. The wallet child dials `127.0.0.1:18081`. - **`arti`** is spawned as a SOCKS child only when the chain source is a - `.onion` daemon: `arti proxy -p ` (see below). -- `--trusted-daemon` is never passed. A remote daemon stays untrusted. -- The wallet dir is created `0700` and the wallet file is kept `0600` — it is a - spend authority. -- The child is watched by polling (`try_wait`); an exit is reported rather than - hidden, and `stop()` kills both children on shutdown. The next launch starts - them again. Nothing promises "always running", and Android will not. + `.onion` daemon: `arti proxy -p `. +- `--trusted-daemon` is never passed. +- Wallet dir `0700`, wallet file `0600`. +- The child is watched by polling (`try_wait`). `stop()` kills children on + shutdown. Nothing promises “always running”, and Android will not. -### Where the RPC credentials live +Generated `user:pass` is sealed with the store data key in the SQLCipher +`wallet_child` table. It never appears in `ONIONWIRE_WALLET_RPC`. -The generated `user:pass` is **sealed with the store data key and kept in the -encrypted SQLCipher store** (`wallet_child` table, AEAD with the store key on top -of whole-db encryption). It is never written to a plaintext file next to the -wallet, and it never appears in `ONIONWIRE_WALLET_RPC`. They persist across -launches, so the child restarts with the same login without asking you again. +The wallet passphrase for `create_wallet` / `restore_deterministic_wallet` is +your runtime choice, not stored by the app. -The wallet passphrase is a separate thing: the child prompts/needs it for -`create_wallet` / `restore_deterministic_wallet`, and that is your runtime choice, -not something the app stores for you. +Nothing spawns the child at boot. `Node::start_wallet_child` is the only start +path. The desktop TUI drives it from `F6`: + +| Key | Effect | +|---|---| +| `s` | Start the child, then probe it once. | +| `x` | Stop it (idempotent). | +| `p` | Probe: is wallet RPC answering, is the chain at the tip? | +| `1` / `2` / `3` | Store in-process Cuprate as mainnet-pruned / mainnet-full / testnet. | + +State shown: `off` / `connecting` / `syncing` / `ready` / `exited`, plus a +chain-source label. `ready` is never reported for a child that has died. + +Once a probe has read the daemon, the line can include `sync /` +— the **daemon's** height and the tip it is syncing towards (wallet RPC +`get_info`, or the local daemon's `get_info` when wallet RPC does not answer). +`sync 0/0` or no segment means **unknown**, not caught up. + +`start` is idempotent: a live child is reported, not respawned. ## Chain source -The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire -does not pick a public remote node for you. The four shapes are: +You pick one. OnionWire does not pick a public remote node for you. ``` ChainSource::None receive-only; no child, no daemon -ChainSource::Local { monerod_bin, datadir } the app spawns monerod on this box -ChainSource::InProcessCuprate { datadir } the daemon is inside this app +ChainSource::Local { monerod_bin, datadir } spawn monerod on this box (port 18081) +ChainSource::InProcessCuprate { datadir, … } daemon inside this app (port 18081) ChainSource::Remote { host, port } a daemon address you typed ``` -1. **Local `monerod`.** Chain traffic stays on the box. You accept disk, first - sync, and (on Android) the daemon not always running. -2. **An in-process daemon** ([Cuprate](https://github.com/Cuprate/cuprate) - running inside the OnionWire process). No `monerod` binary to install or - spawn, chain on this device, and the wallet child dials the same loopback - port. **Testnet only** in this build, and it needs the `cuprate-daemon` - feature — see *The in-process chain daemon* below. +1. **Local `monerod`.** Chain traffic stays on the box. +2. **In-process Cuprate.** No `monerod` binary. Wallet child still dials + `127.0.0.1:18081`. See below. 3. **A daemon address you supply** — becomes `--daemon-address` on the wallet child. Loopback if you already run `monerod`. `.onion` if you want chain - traffic over Tor (see *Chain traffic over Tor* below). Clearnet only if you - type it — your ISP sees Monero-node traffic; it is never a default. + traffic over Tor. Clearnet only if you type it — never a default. Restricted + RPC on `18089` is a common remote example, but you supply the port. -The port is a convention, not a constant: restricted RPC on `18089` is common, -but you supply it. +Settings live in the sealed `wallet_child` record (`ChildConfig`: `source`, +`wallet_rpc_bin`, `arti_bin`, `wallet_filename`). Core: +`Node::wallet_child_config` / `set_wallet_child_config`, then +`start_wallet_child` / `stop_wallet_child` / `wallet_child_status` / +`wallet_child_refresh`. ### The in-process chain daemon (`cuprate-daemon`) -Cuprate's chain daemon — P2P, consensus, RandomX — can run **inside the -OnionWire process** instead of as a spawned `monerod`. The wallet layer does not -change: `monero-wallet-rpc` is still a child, and it still dials the unrestricted -loopback RPC, `127.0.0.1:18081`, the same address a spawned `monerod` gets. - ``` cargo build --release --features cuprate-daemon ``` -- **Off by default.** `cuprated` is pre-1.0 and is not published to crates.io - (every Cuprate crate there is a `0.0.0-placeholder` name reservation), so it is - a git dependency pinned to a revision, behind the `cuprate-daemon` feature. A - default build does not compile it: the graph is large (RandomX, fjall, - axum/hyper, rayon) and it is a *choice*, never compiled-in. Without the feature - a stored in-process chain source can still be read back — the chain-source type - and its record do not fork on a cargo feature — but starting it fails with - `this build has no in-process chain daemon — rebuild with --features - cuprate-daemon`. -- **+11.8 MiB (12,327,768 bytes)** on a stripped `aarch64-linux-android` release - binary, measured in this repo: 24,725,704 bytes without the feature and - 37,053,472 with it (`cargo rustc --release --target aarch64-linux-android - [--features cuprate-daemon] --bin onionwire`, both linked with the NDK C++ - runtime / compiler-rt link args, then `llvm-strip`). The `+5.6 MB` figure that - circulated with the spike was an estimate and understates it. A cold build - also compiles the Cuprate graph in addition to this crate's own, so first-build - time grows accordingly. -- **Testnet only.** Cuprate is **pre-production software**. Its own user book - says *"do NOT use cuprated for any serious purposes"*, and its `monerod` RPC - parity is incomplete (Cuprate issue #278; the four gaps measured in this repo - are in `docs/cuprate-launch-spike.md` §Parity gaps). The config pins - `network = "Testnet"`; pointing a mainnet wallet at it is not something this - build claims to do. The wallet screen's chain line says so next to the source - (`testnet only — mainnet is unvalidated`). -- **No Tor in the chain path.** Cuprate's own `arti` feature is *not* enabled: - its Tor stack is `arti-client` 0.44, which cannot unify with this crate's 0.46, - and running two Tor stacks in one process is not a trade this app makes. - OnionWire's Arti is the only Tor here, and it serves the messenger. The - in-process daemon's P2P traffic is therefore **clearnet**: your ISP can see - that this device talks to Monero testnet peers, exactly as a spawned `monerod` - would. -- **Inbound connections are off** and the restricted RPC listener is disabled: - this is a wallet's daemon, not a public node (the restricted listener only - answers placeholder metrics — see below). -- **It is not a child process.** There is no pid to watch or signal: the node is - a value the app owns, and dropping it shuts the daemon down. `stop` (TUI key - `x`, or the SDK's `stop_wallet_child`) asks it to shut down with the wallet - child, and it does not outlive the app. -- **The chain lives in `$ONIONWIRE_HOME/chain`** — the same per-identity - directory a spawned `monerod` would use, so the two local sources are - interchangeable on disk. It is created `0700`. The chain database itself is - **fjall**, a separate embedded store from OnionWire's SQLCipher file: - Cuprate puts it under the datadir it is given (`/testnet/fjall`), so - it is never beside `onionwire.db`. -- **Selecting it.** The chain source is a stored setting (`ChildConfig`), and - this build has no on-screen chain-source picker on the desktop TUI — that is - true of the other three sources too; the picker is a separate, unmerged piece - of work. What selects this source today is a `ChainSource::InProcessCuprate` - record with a `datadir` written through `Node::set_wallet_child_config` (the - SDK's `ChainConfig` path), and the daemon then starts with the child when the - wallet is started. The SDK's `ChainChoice.InProcessCuprate` is that variant - over UniFFI, and `kind = "cuprate"` is the record's spelling. +- **Off by default.** `cuprated` is pre-1.0, not on crates.io (placeholder + crates), git-pinned, behind the feature. Without the feature, a stored + in-process source can still be read back, but start fails with + `this build has no in-process chain daemon — rebuild with --features cuprate-daemon`. +- **Pre-production.** Cuprate's own user book says do not use `cuprated` for + serious purposes. RPC parity is incomplete (`docs/cuprate-launch-spike.md`). +- **Mainnet is unvalidated.** The TUI can store mainnet-pruned (`F6` `1`) or + mainnet-full (`F6` `2`) or testnet (`F6` `3`). Every in-process surface still + prints `testnet only — mainnet is unvalidated` (`cuprate::TESTNET_ONLY`). + Cross-compiled is not device-proven. Pointing a mainnet wallet at it is not + something this build claims to do. +- **No Tor on the chain path.** Cuprate's `arti` feature is off (arti-client + 0.44 vs this crate's 0.46). P2P is **clearnet**. OnionWire's Arti is the + messenger only. +- **Inbound P2P off**, restricted RPC listener disabled. Unrestricted RPC is + loopback 18081. `--trusted-daemon` still never passed. +- Chain lives under `$ONIONWIRE_HOME/chain/…` (split dirs so pruned mainnet + cannot mix with full). Database is **fjall**, not SQLCipher. +- Not a child process: dropping the node shuts it down. `x` / `stop_wallet_child` + asks it to stop with the wallet child. ### Chain traffic over Tor (`.onion` daemons) -A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back -to a clearnet resolve. The wallet child is an external C++ binary, so it reaches -Tor the only way it can: through a SOCKS proxy the app provides. +A `.onion` daemon cannot be dialled directly. The wallet child is an external +C++ binary, so it reaches Tor through a SOCKS proxy the app provides: -- The app runs the **bundled `arti` binary** as a child: - `arti proxy -p `. `arti-client` 0.46 has no SOCKS - listener API — the SOCKS listener lives in the `arti` *binary* — so this is a - second, separate Tor client, not the messenger's in-process one. There is no - C-tor and no system `tor`. -- The listener is **TCP loopback only**. `arti proxy -p ` binds localhost - (`127.0.0.1` and `::1`) and nothing else, and there is nothing safer to - prefer: `arti` 2.6.0 / `tor-config` 0.46 have no Unix-socket listen target - (`Listen` is IP-only; arti's own port record calls AF_UNIX future work, - arti#1965). The port is app-private in practice, but any local process with - user-level access can also use it — that is the honest statement of the - boundary, not a claim of access control. -- The wallet child is then spawned with - `--proxy socks5://127.0.0.1:` **and** `--daemon-address :`. - The `socks5://` scheme is explicit: Monero's `--proxy` defaults to SOCKS4a for - a bare `host:port` (`docs/proxies.md` in the Monero tree). The `.onion` name - goes to the proxy inside the SOCKS request — Monero's SOCKS5 client uses the - domain-name form — so **no local DNS** runs on the onion target. -- The SOCKS child gets **its own state and cache dirs** - (`$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`). The messenger's Arti - state is not shared with it. -- Starting it is gated on the same credential material as everything else: the - SOCKS child is only spawned from `WalletChild::start(&store)`, which needs the - already-unlocked store. -- The app waits **up to 20s** for the SOCKS listener to accept a connection - before it spawns the wallet child. A dead proxy is a visible error, not a - wallet screen that hangs dialling a daemon. Arti binds its listener before it - bootstraps, so this is a listener check, not a Tor-bootstrap check. -- The SOCKS child stops with the wallet child; a killed wallet child leaves no - orphaned listener behind. +- Bundled `arti` binary: `arti proxy -p `. A second + Tor client, not the messenger's in-process one. No C-tor. +- Listener is TCP loopback only. Any local process at your privilege can use it. +- Wallet child: `--proxy socks5://127.0.0.1:` and + `--daemon-address :`. The `socks5://` scheme is required (Monero + defaults to SOCKS4a for a bare `host:port`). No local DNS on the onion target. +- Own state/cache: `$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`. +- Wait up to 20s for the SOCKS listener before spawning the wallet child. +- SOCKS child stops with the wallet child. **Tor hides the transport, not the host.** The daemon operator still sees the -wallet's addresses (and the transaction set it is scanning) during sync. A -`.onion` address protects the path between you and that operator, nothing more. +wallet's addresses during sync. -The TUI copy for a chain source says this in one line -(`WalletChild::chain_copy`): `.onion` → "over Tor … the daemon operator still -sees your addresses during sync"; clearnet → "the daemon operator and your ISP -see the traffic". +### Readiness — receipt verification needs a synced daemon -### Readiness, and why it is not a guess +`chain_ready()` asks the wallet RPC `get_info` and requires +**`synchronized == true`** with `height > 0` and `height >= target_height`. A +missing field is *not ready* — fail closed. -`chain_ready()` asks the wallet RPC `get_info` and requires **`synchronized == -true`** with `height > 0` and `height >= target_height`. A missing field is -*not ready* — fail closed, never a silent pass. Until then: +Until then, **receipt verification stays `verified=0`**. An unsynced wallet +cannot see the chain. That is an honest limit, not a UI bug. -- **receipt verification stays `verified=0`** (an unsynced wallet cannot see the - tx, so a `get_transfers` miss would be a lie), and -- **spend is refused** with `wallet is not synced — spend refused until the - daemon reaches the chain tip`. +Loopback management calls (`get_address`, `query_key`, create/import) get 5s. +Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s +(`CHAIN_RPC_TIMEOUT`). -`spend_ready()` is the stricter signal the spend UI reads: chain-ready *and* -holding an unlocked balance above zero. - -That is the honest state, not a broken flow. Unsynced or unreachable → receipts -unverified and spend refused. - -### Timeouts are the backend's, not a constant - -Loopback management calls (`get_address`, `query_key`, create/import) get a 5s -budget — the child is on the same box. Calls that wait on the chain (`get_info`, -`get_transfers`, `transfer`) get 60s (`CHAIN_RPC_TIMEOUT`), because a first sync -or a remote daemon legitimately outlasts a loopback round trip; a 5s cap there is -what leaves receipts permanently unverified. - -## Env vars +## Env vars (migration path) | Variable | Meaning | |---|---| -| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]` — for an **externally run** `monero-wallet-rpc`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. The app-owned wallet child does not use this variable. | -| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. | -| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. | +| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]` for an **externally run** `monero-wallet-rpc`. Unset → no wallet; chat still works; `/pay` falls back to profile `xmr_addr`. The app-owned child does not use this. | +| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when the URL has no userinfo. | +| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → `/tip` refused locally before any RPC dial. | -These three are the **migration path**, not the only path: a config stored in -the encrypted store wins at boot. See *Stored wallet config* below. +Boot precedence: **stored config → env → disabled**. Stored config that cannot +be used (non-loopback, `.onion`, missing login) is reported and falls back to +env rather than dialling the bad endpoint. -`README.md` carries the operator summary; this file is the long form. +`Store::save_wallet_config` / `Node::wallet_save_config` exist. **No TUI screen +writes them.** There is no `F7`. The not-configured refusal still says +`wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` +(`src/wallet.rs`). Live surfaces: `F6`, `F9`, or the env vars. -## Stored wallet config (no env required) +`/pay` and `/tip` run `wallet_readiness` before send: -Editing env vars is a deployment step, not a UI step. The same three fields can -be stored instead, so a deployment never needs env at all: +1. not configured → the F7-worded message above +2. `/tip` on view-only / `ONIONWIRE_WALLET_NO_SPEND` → refused **before any dial** +3. configured but not connected → `wallet not connected — check endpoint, login, daemon` +4. otherwise ready (`/pay` is fine on view-only) -| Field | Meaning | -|---|---| -| `rpc_url` | `http://host:port[/path]` for an **externally run** `monero-wallet-rpc`. **No** `user:pass` in the URL. Loopback only, same rule as env. | -| `rpc_login` | `user:pass`. Never logged, never in a status line, never on disk in the clear. | -| `no_spend` | View-only deployment. Same semantics as `ONIONWIRE_WALLET_NO_SPEND`. | +## Android / SDK -`Store::save_wallet_config` / `Store::load_wallet_config` are the read/write -pair, and `Node::wallet_save_config` re-reads the live wallet after a save so -`configured` / the readouts follow without a restart. **No screen in this -repository calls them yet**: the TUI wallet config screen (F7) and its endpoint -entry, test-connection button and save path ship on -`feat/wallet-create-import`, which is not part of this change — see -*Starting and stopping the app-owned child* below for what this stack does -expose. Until that lands, set the stored config programmatically (or use the env -vars above). +UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`, +`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read: +no dial, for first paint) and `wallet_child_refresh()` (a live probe of the +same record — it dials the loopback wallet RPC, and the local daemon's +`get_info` when that RPC does not answer, so poll it on the order of seconds). +Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the +core never resolves a binary the caller named explicitly. -They live in the **encrypted SQLCipher store** (`wallet_config` table, one row: -the URL and the flag in the clear inside the encrypted db, the login sealed with -the store data key and a `onionwire/wallet-config/v1` AAD on top of whole-db -encryption — the same discipline as the wallet-child creds). Save replaces the -row; clearing the URL deletes it, which is how you turn the stored wallet off -again. +`ChainChoice.InProcessCuprate` is the in-process variant. Empty +`monerod_datadir` resolves to `$ONIONWIRE_HOME/chain`. `start_wallet_child()` +launches the node *and* the wallet child. `wallet_status()` carries +`chain_in_process`, `node_available`, and `node_state`. -**Boot precedence is stored → env → disabled.** Stored config wins; the env vars -in the table above remain the migration path (and the only path for headless -runs). A stored config that cannot be used — non-loopback host, `.onion`, -missing login — is reported and then **falls back to env** rather than dialling -the bad endpoint. To override a stored config with env, clear the stored one -first. - -### Wallet status, and how fresh `connected` is - -The app keeps one `WalletStatus` snapshot for the draw path — -`configured`, `connected`, `last_error`, `balance_line`, `receive_address` — -and the TUI only ever reads it; it never dials the wallet from the render path. - -- `configured` is true when a stored **or** env config resolved to a usable - wallet. Config is not reachability: a freshly booted or freshly saved wallet - is `configured = true`, `connected = false`, with `—` readouts. -- `connected` only ever comes from a probe. One probe is `get_address` (cheap, - loopback, and the same call `/pay` invoices need) followed by `get_balance` - for the readout. A success clears `last_error`; a failure sets - `connected = false` and keeps `configured = true`. There is no background - refresh: `connected` is whatever the **last** probe said. -- `last_error` is display copy, not a log line: trimmed, capped at 120 chars, - and with the RPC password redacted (``) if a lower layer ever put it - in a message. - -Two probes exist: - -- `wallet_refresh` / the readiness guard probe the **configured** endpoint and - update the snapshot; -- `wallet_test_connection` probes an endpoint the caller is *currently typing* - (`Wallet::ping`) and returns `{ok, status, error}` without touching the live - wallet or the snapshot — testing an untyped endpoint is not the wallet the app - is running. (The F7 screen that calls it ships on `feat/wallet-create-import`.) - -### The pay/tip readiness guard - -`/tip` and `/pay` run a pre-check before the send. It never dials Tor (wallet -RPC is loopback-only), and it never dials the wallet at all when the answer is -already known locally. The order is fixed and the copy is part of the contract: - -1. **not configured** → `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` -2. **`/tip` on a no-spend / view-only wallet** → the existing view-only message - (`wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt - verification still work`), refused **before any dial** — this is the same rule - `transfer` applies, and it is the honest answer whether or not the wallet is - reachable. -3. **configured but not connected** → `wallet not connected — check endpoint, login, daemon` -4. otherwise ready. `/pay` is fine on a view-only wallet. - -The check is cheap enough to run on Enter: steps 1 and 2 are local, and step 3 -is one bounded probe (5s local budget). `wallet_readiness(is_tip)` is `async`; -the TUI calls it from its key handler on both the `/pay` and `/tip` paths before -it sends anything. - -The "open F7" wording inside the not-configured message is the copy that ships -with the F7 screen on `feat/wallet-create-import`; this stack stores the config -and exposes the guard, but no screen writes it yet. - -## Starting and stopping the app-owned child - -Nothing spawns the child by accident: `Node::start_wallet_child` is the only -start path, and it is never called at boot. The desktop TUI drives it from the -wallet screen (F6): - -| Key | Effect | -|---|---| -| `s` | Start the child, then probe it once. | -| `x` | Stop it (idempotent) and fall back to the stored/env wallet config. | -| `p` | Probe the running child: is its wallet RPC answering, is the chain at the tip? | - -The state shown next to the wallet readouts is `off` / `connecting` / `syncing` -/ `ready` / `exited`, plus the chain-source label (`receive-only`, -`local node`, `in-process node`, `remote onion daemon`, `remote daemon`). It is -derived from the real process (`try_wait`) and the last probe — **never** from -env-var presence, and `ready` is never reported for a child that has died. - -- **`off`** — nothing started (or stopped). The default state. -- **`connecting`** — the `monero-wallet-rpc` process is alive but has not - answered yet. This is what a fresh `s` reports; the RPC is not up the instant - the process exists. -- **`syncing`** — it answered but `chain_ready()` is false. -- **`ready`** — it answered and the chain is at the tip. -- **`exited`** — a started child has died. Stop and start again; the status is - not stale, it is the process table. - -The same one-liner carries the chain's own progress once a probe has read it: - -``` -child syncing · in-process node · sync 1160/3090939 -``` - -Those are the **daemon's** height and the tip it is syncing towards — from the -wallet RPC's `get_info` when it answers, and, when the wallet RPC is *not* -answering (the `connecting` case, e.g. `Connection refused (os error 111)`) while -the chain source is `local node` or `in-process node`, from that loopback daemon -directly. `sync 0/0`, or no `sync` segment at all, means **unknown**: the child -is off or exited, the probe failed, or the daemon reported no target — which is -not the same as caught up, and is never a wallet-scan height. No percentage is -ever derived from it. `WalletChildStatus` (and the UniFFI record) carries the two -numbers as `height` / `target_height`. - -`start` is idempotent: a live child is reported, not respawned. A start that -cannot spawn the binary is an error and leaves no child behind. - -**The chain source and the binaries are settings, not flags.** They live in the -same sealed `wallet_child` record as the generated RPC creds (see *Where the RPC -credentials live*), so they survive a restart: - -- `src/wallet_child.rs` `ChildConfig` — `source`, `wallet_rpc_bin`, `arti_bin`, - `wallet_filename`; validated before anything is written. -- Core: `Node::wallet_child_config` / `Node::set_wallet_child_config`, then - `Node::start_wallet_child` / `stop_wallet_child` / `wallet_child_status` / - `wallet_child_refresh`. -- Android (UniFFI): `set_chain_source(ChainConfig)` / `chain_source()`, - `start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (the cached - read: no dial, for first paint) and `wallet_child_refresh()` (a live probe of - the same record — it dials the loopback wallet RPC, and the local daemon's - `get_info` when that RPC does not answer, so poll it on the order of - seconds). Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the - core never resolves a binary the caller named explicitly. `ChainChoice` has a - fourth variant, `InProcessCuprate`, for the in-process daemon: no binary path - and, with an empty `monerod_datadir`, the SDK resolves the chain directory to - `$ONIONWIRE_HOME/chain`. `start_wallet_child()` is the whole lifecycle for it - (the core launches the node *and* the wallet child in that one call), and - `wallet_status()` carries `chain_in_process` (this app's node is the source), - `node_available` (this build has `cuprate-daemon`) and `node_state` - (`off` / `starting` / `syncing` / `ready` / `exited`, empty for every other - source) beside the core's own five `state` words. - -So local mode is **available**, not wired off: a local chain source spawns -`monerod` from the path you set, a `.onion` daemon spawns the `arti` SOCKS -child, and everything else is unchanged. What is still missing is a *screen* to -type those fields on the desktop — the API above is the surface until the F7 -work lands. +Monero ships **no Android binaries**. Any vendored blob's provenance doc must +say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`. ## Create vs import -Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks -the RPC to generate a new spend-capable wallet (`create_wallet`), then shows the -seed **once** for backup (`query_key mnemonic`). Type `SPEND` to accept the -spend-authority warning, set a passphrase, write the seed down, type `SEEN`. +`/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** +(`query_key mnemonic`). Type `SPEND`, set a passphrase, write the seed, type +`SEEN`. -Import is the only path that takes an existing secret: `/wallet import` (F6 then -`i`) pastes the 25-word seed into `restore_deterministic_wallet`. Do not put the -seed on the composer line — it would sit in chat history. +`/wallet import` (`F6` then `i`) → `restore_deterministic_wallet` from a +25-word seed. Do not put the seed on the composer. -The RPC must be started with `--wallet-dir` (not only `--wallet-file`) or create -and import fail. The in-app filename is `onionwire`. +RPC must be started with `--wallet-dir` (not only `--wallet-file`). Filename: +`onionwire`. -## Recommended topology +## Recommended topology (view-only) ``` wallet host (this machine) @@ -419,38 +228,19 @@ and import fail. The in-app filename is `onionwire`. └──────────────────────────────────────────────────────────────┘ ``` -Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion` -wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and -a remote wallet RPC would move spend authority off the box. +Loopback is the only address OnionWire will dial for **wallet RPC**. ## Create a view-only wallet -Either path produces a wallet file with the view key only. Keep the seed / -spend key on a machine that is **not** running OnionWire. - -With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard* -address the view key belongs to, then the secret view key): +Keep the seed / spend key on a machine that is **not** running OnionWire. ```bash monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \ --daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT" -# Standard address: 4... -# Secret view key: ``` -Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys` -without `spendkey` writes a watch-only wallet): - -```bash -curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \ - -H 'Content-Type: application/json' \ - -d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{ - "filename":"viewonly","password":"walletpass", - "address":"4...","viewkey":"","restore_height":}}' -# → "Watch-only wallet has been generated successfully." -``` - -Then serve it: +`18089` here is the **remote** daemon's restricted RPC, an address you type — +not the app-owned 18081. ```bash monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \ @@ -462,78 +252,36 @@ export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret export ONIONWIRE_WALLET_NO_SPEND=1 ``` -Restore the wallet from a height *at or before* its first incoming transaction -— a view-only wallet cannot rescan cheaply from height 0. +Restore from a height at or before the first incoming transaction. ## What works, what does not | Feature | View-only | Spend-capable | |---|---|---| | `/pay ` invoice subaddress (`create_address`) | works | works | -| Receipt verification (`get_transfers`) | works | works | +| Receipt verification (`get_transfers`) | works, if daemon is synced | works, if daemon is synced | | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | | OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | -With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is -contacted, with: +`ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with: ``` wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work ``` -Without the flag, `/tip` against a view-only wallet fails at the wallet and -OnionWire then asks the wallet directly whether it can spend (see below), so you -get the same sentence instead of a raw RPC error. - -## How OnionWire detects view-only over RPC - -The signal people usually reach for is `query_key` with `key_type=mnemonic`. It -works, but it is the wrong key to ask for: on a spend-capable wallet it hands -over the whole seed (full spend ability) over loopback HTTP, and it answers -`-43` for wallets that have no mnemonic at all. The spend key is narrower and -just as unambiguous: - -``` -query_key {"key_type":"spend_key"} - spend-capable → result.key = - view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key." -``` - -(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the -two agree — OnionWire asks for the spend key because it is the smaller secret.) - -- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key) -- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in - [`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h) -- The view-only branch is `on_query_key` in - [`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp) - -OnionWire only calls this **after** a `transfer` has already failed — it never -probes a healthy wallet — and it discards `result.key` immediately. There is no -RPC method that reports "view-only" as a plain field; `query_key` is the -documented signal and this is its only cost: a spend-capable wallet answers with -its spend key over loopback HTTP, which is one more reason to run view-only. - -Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc` -answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error -unchanged. It never guesses "view-only" from an unrelated failure. +View-only detection after a failed `transfer`: `query_key` `spend_key` → `-29` +watch-only. The spend key is discarded immediately. OnionWire never probes a +healthy wallet for this. ## Why loopback still needs authentication -`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it -away from other users or processes on the same machine. Any local process can -`connect(127.0.0.1:18083)`. +`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep +it away from other processes on the same machine. -- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and - refuses URLs without credentials. Unset the credentials and the wallet is open - to every local process — with a spend-capable wallet file, that is a - one-curl drain of your balance. -- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext, - but Digest gives no confidentiality: a local attacker who can sniff loopback - can replay it. Treat loopback as trusted-ish, not safe. -- Do not log the password, and do not put it in a shell history you share. - Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL. +OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and +refuses URLs without credentials. Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over +userinfo in the URL. Do not log the password. ## The spend-authority warning @@ -543,27 +291,17 @@ local spend authority: any process that can read the RPC credentials (env var, balance, and `/tip` gives a chat peer a supported path to ask for a transfer. That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended -default: +default. If you want tips, use a **separate hot wallet with a small balance**, +not your savings wallet. -- the wallet file holds no spend key, so a stolen wallet file cannot be used to - move funds; -- the RPC credentials grant only receive-address and history reads; -- `/tip` fails locally with a plain message, so nothing in the UI pretends the - spend path exists. +## Payments are one-shot -If you want tips to work, understand that you are deliberately making the -OnionWire process able to spend. Give it a **separate hot wallet with a small -balance**, not your savings wallet. +`/pay` and `/tip` fail when the peer onion is down. There is no queued invoice. +File transfer is the same rule. ## References -- Monero Wallet RPC reference: - -- `on_query_key` (view-only → `-29`): - -- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`: - -- `--generate-from-view-key` (incoming-only wallet): - -- `generate_from_keys` (watch-only when `spendkey` is omitted): - +- Monero Wallet RPC: +- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29` in the Monero tree +- Spike history (not operator docs): [cuprate-launch-spike.md](cuprate-launch-spike.md), + [arti-socks-feasibility.md](arti-socks-feasibility.md) diff --git a/docs/arti-socks-feasibility.md b/docs/arti-socks-feasibility.md index 339a385..b7d05b8 100644 --- a/docs/arti-socks-feasibility.md +++ b/docs/arti-socks-feasibility.md @@ -1,5 +1,9 @@ # Arti SOCKS Feasibility Report +**Status:** shipped as Option A (bundled `arti` binary as SOCKS child for +`.onion` daemons). Living doc: [WALLET.md](WALLET.md). Verdict below is the +historical finding; do not rewrite it. + **Date:** 2026-09-13 **Scope:** Can OnionWire's in-process `arti-client` 0.46.0 expose a SOCKS5 listener for an external process (monero-wallet-rpc child) to route its daemon traffic through Tor? **Verdict:** **Not directly.** The `arti-client` library does not expose a configurable SOCKS proxy listener. See options below. diff --git a/docs/cuprate-android-spike.md b/docs/cuprate-android-spike.md index 9433ab1..0c55fc3 100644 --- a/docs/cuprate-android-spike.md +++ b/docs/cuprate-android-spike.md @@ -1,5 +1,9 @@ # Cuprate on Android aarch64 — cross-compile spike +**Status:** shipped as history. In-process Cuprate is an opt-in `cuprate-daemon` +feature; mainnet remains unvalidated. Living doc: [WALLET.md](WALLET.md). Do not +read this spike as current operator procedure. + **Question (kanban `t_8293d96d`):** do the native dependencies of the in-process Cuprate daemon (`randomx-rs`, `fjall`, sqlite, the C++ RandomX build) cross-compile for the Android NDK target `aarch64-linux-android`? If they do not, §7a's Phase 1 diff --git a/docs/cuprate-launch-spike.md b/docs/cuprate-launch-spike.md index 7ffc6c2..6c799b0 100644 --- a/docs/cuprate-launch-spike.md +++ b/docs/cuprate-launch-spike.md @@ -1,5 +1,8 @@ # Cuprate in-process launch spike (Phase 1, Spike A) +**Status:** shipped as history. Production app-owned daemon RPC is **18081**, +not the spike's 18089 unrestricted example. Living doc: [WALLET.md](WALLET.md). + **Question:** does `cuprated::Node::launch(config).await` start a real Monero chain daemon *inside the OnionWire process* on testnet, and does the resulting JSON-RPC endpoint at `127.0.0.1:18089` answer `get_info`, `get_height` and `get_block` the way `monerod` does — diff --git a/docs/option-a-recommendation.md b/docs/option-a-recommendation.md index 969099e..93e86d5 100644 --- a/docs/option-a-recommendation.md +++ b/docs/option-a-recommendation.md @@ -1,5 +1,8 @@ # Recommendation: Option A — bundle the `arti` binary as a SOCKS subprocess +**Status:** shipped. The wallet child uses `arti proxy -p` for `.onion` daemons. +Living doc: [WALLET.md](WALLET.md). This file is the decision record. + ## What Option A is Run the `arti` CLI (not `arti-client`) as a child process doing `arti proxy -p `. The wallet child points `--proxy 127.0.0.1:` at it. The messenger continues using in-process `arti-client`. Two Tor clients in one app: one in-process for the messenger, one subprocess for SOCKS. diff --git a/docs/payment-integration-plan.md b/docs/payment-integration-plan.md index ea1ecbc..27b060b 100644 --- a/docs/payment-integration-plan.md +++ b/docs/payment-integration-plan.md @@ -1,5 +1,11 @@ # OnionWire payment integration — next steps +**Status:** largely shipped (child wallet, `/pay` `/tip`, F6 create/import, F9 +menu). Still open on desktop: no TUI editor for a stored external RPC URL or a +typed remote daemon host (API exists; error copy still says “F7”). Living docs: +[WALLET.md](WALLET.md), [TUI.md](TUI.md). This file is the plan as written; do +not rewrite the conclusion. + **Audience:** dev profiles (rust-dev for core/SDK/TUI, apk-dev for Android), with CI as a cross-cutting concern. **Goal:** turn the existing `inv`/`rcp`/`tip` wire frames and the existing `monero-wallet-rpc` HTTP Digest client into a real in-app payment flow on both TUI and Android, with the wallet fully owned by the app (bundled binaries), chain backends opt-in (local pruned node, or remote onion daemon), clearnet refused, Tor for the messenger and for any remote-daemon chain traffic. From 4d2528351b6df2c54ce5506797722f37317047e5 Mon Sep 17 00:00:00 2001 From: Lance Date: Sun, 20 Sep 2026 00:48:53 -0400 Subject: [PATCH 17/94] android: poll the live wallet-child probe so the sync line moves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wallet screen's 2s loop read Wire::wallet_status, which only re-reads the snapshot the last probe left in the store — so the `sync h/t` segment sat frozen until a chain-mode tap ran start_wallet_child (which probes on its way out). The loop now paints once from the cached read (non-dialing, so the screen has a record immediately) and then calls Wire::wallet_child_refresh for every tick: one live probe of the child's loopback wallet RPC, and of the configured local daemon's get_info when that RPC does not answer. Same 2s cadence, same Dispatchers.IO, same sticky walletChildError, same one-poller guarantee. The loop is a top-level function taking its two reads as parameters, which is the only seam a JVM test has — requireWire() is NodeHost.requireOpen(), a process-global only a real Arti bootstrap sets. WalletChildRefreshLoopTest pins that the cached read paints exactly once and every tick after it is the live probe, that a probe slower than the tick is never overlapped, and that cancelling the loop (leaving the screen) stops the dialing. --- .../siriusdevops/onionwire/WireViewModel.kt | 82 +++++++++++-- .../onionwire/WalletChildRefreshLoopTest.kt | 108 ++++++++++++++++++ 2 files changed, 180 insertions(+), 10 deletions(-) create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 1efd980..6f26632 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -652,10 +652,17 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { fun openWalletChild() { if (walletChildPoller?.isActive == true) return walletChildPoller = viewModelScope.launch { - while (currentCoroutineContext().isActive) { - refreshWalletChild() - delay(WALLET_CHILD_TICK_MS) - } + walletChildRefreshLoop( + tickMs = WALLET_CHILD_TICK_MS, + // The first paint is the cached read: it never dials, so the + // screen has a record to render while the first probe is still + // in flight. + cached = ::paintWalletChildCached, + // Every tick after that is a live probe, so `height` / + // `target_height` move on their own instead of only when a + // chain-mode button is tapped. + live = ::refreshWalletChild, + ) } } @@ -671,17 +678,45 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } /** - * One `wallet_status()` read. + * The first paint: one `wallet_status()` read. * * `Wire::wallet_status` is synchronous in Rust and re-reads the sealed * wallet-child record out of the SQLCipher store, so it goes to * [Dispatchers.IO] — a store decrypt on the main thread is an ANR waiting - * for a slow device. It never dials and never spawns, so a 2s cadence is - * cheap. + * for a slow device. It never dials and never spawns, so it is the right + * read to have a record on screen — and the wrong one to poll with. */ - suspend fun refreshWalletChild() { - val read = withContext(Dispatchers.IO) { runCatching { requireWire().walletStatus() } } - read.fold( + suspend fun paintWalletChildCached() = readWalletChild { requireWire().walletStatus() } + + /** + * One tick: a live probe, `Wire::wallet_child_refresh()`. + * + * `Wire::wallet_status` above only re-reads what the last probe left behind, + * so polling it pins the `sync h/t` segment on whatever the last + * start/stop saw. This one dials — the child's loopback wallet RPC, and the + * configured local daemon's `get_info` when the wallet RPC does not answer + * — which is what makes the chain's height and target move between ticks. + * + * It never spawns a child, and the core short-circuits with the cached + * snapshot when there is no live child, so it cannot invent `ready` for a + * wallet that is not there. Not free, though: the tick stays on the order of + * seconds rather than frames. + * + * Failure is folded into the sticky [walletChildError], same as the cached + * read: a probe that fails once must not blink the previous error off the + * screen. + */ + suspend fun refreshWalletChild() = readWalletChild { requireWire().walletChildRefresh() } + + /** + * Runs one of the two reads on [Dispatchers.IO] and lands it in the wallet + * state. `requireWire()` throws when the node is locked, so it is called + * *inside* the [runCatching] — a locked node has to surface as + * [walletChildError], not as a crash on the tick. + */ + private suspend fun readWalletChild(read: suspend () -> WalletChildStatus) { + val result = withContext(Dispatchers.IO) { runCatching { read() } } + result.fold( onSuccess = { _walletChild.value = it }, onFailure = { _walletChildError.value = it.message ?: it.toString() }, ) @@ -856,5 +891,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { ) } +/** + * The wallet-child refresh loop: one [cached] paint so the screen has something + * to render, then a live [live] probe every [tickMs]. + * + * The reads are parameters only so the JVM test tree can drive this loop + * without a `Wire` — `NodeHost.requireOpen()` is a process-global the unit test + * cannot prime. The two call sites in [WireViewModel.openWalletChild] bind them + * to the cached read and to the live probe. + * + * Serialized by construction, and that is the point: the loop suspends on each + * read before it sleeps, so a probe slower than [tickMs] delays the next tick + * instead of overlapping it. Do not turn this into a `Flow` with + * `collectLatest`, and do not `launch` the probe: two concurrent + * `wallet_child_refresh` calls against one wallet child is a racing probe. + */ +suspend fun walletChildRefreshLoop( + tickMs: Long, + cached: suspend () -> Unit, + live: suspend () -> Unit, +) { + cached() + while (currentCoroutineContext().isActive) { + delay(tickMs) + live() + } +} + /** Cadence of the wallet-child refresh loop, in milliseconds. */ private const val WALLET_CHILD_TICK_MS: Long = 2_000 diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt new file mode 100644 index 0000000..a1b59c2 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/WalletChildRefreshLoopTest.kt @@ -0,0 +1,108 @@ +package com.siriusdevops.onionwire + +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The wallet screen's refresh loop. + * + * `Wire` has no seam a JVM test can fake: `requireWire()` reads + * `NodeHost.requireOpen()`, a process-global that only `openWire()` — i.e. a + * real Arti bootstrap — sets, and `Wire` itself is the generated UniFFI + * interface. So the loop takes its two reads as parameters, and these tests + * drive it with recording lambdas to pin the two things that make the + * `sync h/t` segment live: + * + * - the cheap cached read paints once, and every tick after it is the live + * probe (`Wire::wallet_child_refresh`), not the cached status read + * (`Wire::wallet_status`) that only re-reads what the last probe left behind; + * - the ticks are serialized by construction — a probe slower than the tick + * delays the next one instead of overlapping it, so no two + * `wallet_child_refresh` calls are ever in flight against one wallet child. + * + * The binding of `live` to `WireViewModel.refreshWalletChild()` (and `cached` + * to `paintWalletChildCached()`) is the two lines in + * `WireViewModel.openWalletChild()`, and the source there is the evidence for + * it — nothing in this test can observe a `NodeHost` that is not open. + * + * Time is virtual, so the 2s cadence is free to assert. Note the scheduler's + * rule: `advanceTimeBy(n)` runs what is scheduled strictly before `n`, not the + * task at `n` itself. + */ +class WalletChildRefreshLoopTest { + + @Test + fun the_first_paint_is_the_cached_read_and_every_tick_after_it_is_live() = runTest { + var cached = 0 + var live = 0 + val job = launch { + walletChildRefreshLoop(tickMs = TICK_MS, cached = { cached++ }, live = { live++ }) + } + + // Four ticks of virtual time: probes at 2s, 4s and 6s; the 8s one has + // not fired yet. + advanceTimeBy(4 * TICK_MS) + + assertEquals("the cheap read paints once, and only once", 1, cached) + assertEquals("every tick after the paint is a live probe", 3, live) + assertEquals("and they land on the tick, not back to back", 4 * TICK_MS, currentTime) + + job.cancel() + advanceTimeBy(10 * TICK_MS) + assertEquals("cancelling the loop is what stops the dialing", 3, live) + } + + @Test + fun a_probe_slower_than_the_tick_is_never_overlapped() = runTest { + var inFlight = 0 + var maxInFlight = 0 + var probes = 0 + val job = launch { + walletChildRefreshLoop( + tickMs = TICK_MS, + cached = {}, + live = { + inFlight++ + if (inFlight > maxInFlight) maxInFlight = inFlight + delay(5 * TICK_MS) // a probe five ticks long + inFlight-- + probes++ + }, + ) + } + + // Probe 1 at 2s runs to 12s, probe 2 at 14s to 24s, probe 3 at 26s to + // 36s: each of them pushes the next tick out by its own length. + advanceTimeBy(19 * TICK_MS) + + assertEquals("two concurrent wallet_child_refresh probes is a race", 1, maxInFlight) + assertEquals("three probes done, none of them skipped or doubled", 3, probes) + assertEquals(19 * TICK_MS, currentTime) + + job.cancel() + } + + @Test + fun cancelling_the_loop_stops_the_probes() = runTest { + var live = 0 + val job = launch { + walletChildRefreshLoop(tickMs = TICK_MS, cached = {}, live = { live++ }) + } + + advanceTimeBy(3 * TICK_MS) + assertEquals("two ticks have gone by", 2, live) + + job.cancel() + advanceTimeBy(10 * TICK_MS) + assertEquals("leaving the wallet screen stops the dialing", 2, live) + } + + private companion object { + const val TICK_MS = 2_000L + } +} From c65946bfd5a5629da81f3442d2a9b1aba1560e69 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 00:52:43 -0400 Subject: [PATCH 18/94] docs(android): rewrite Android docs to match the tree android/README.md, CUPRATE_DAEMON.md and MONERO_BINARIES.md were the half PR #133 left out. Releases are two manual dispatches, not a push to main; the APK version comes from the tag android-release checks out; the layout now includes wallet/ and keepalive/; the status line's sync h/t is documented; the APK poller still calls wallet_status, not wallet_child_refresh. --- android/CUPRATE_DAEMON.md | 107 +++++++++++------ android/MONERO_BINARIES.md | 45 +++++--- android/README.md | 228 ++++++++++++++++++++++++++++++++----- 3 files changed, 305 insertions(+), 75 deletions(-) diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md index 1708d9e..e3b422b 100644 --- a/android/CUPRATE_DAEMON.md +++ b/android/CUPRATE_DAEMON.md @@ -5,10 +5,13 @@ OnionWire process** — is compiled into the Android build. This document is the provenance record for that: how the feature is enabled, why the link line looks the way it does, what CI checks, and what has *not* been proven. -Companion reading: `docs/WALLET.md` ("The in-process chain daemon") for what the -daemon is, `docs/cuprate-android-spike.md` for the cross-compile spike this -plumbing comes from, and `MONERO_BINARIES.md` for the `monero-wallet-rpc` -executable, which is still a child process — Cuprate has no wallet layer. +Companion reading: [docs/WALLET.md](../docs/WALLET.md) ("The in-process chain +daemon") for what the daemon is, [docs/cuprate-android-spike.md](../docs/cuprate-android-spike.md) +for the cross-compile spike this plumbing comes from, +[MONERO_BINARIES.md](MONERO_BINARIES.md) for the `monero-wallet-rpc` executable +(still a child process — Cuprate has no wallet layer), and +[README.md](README.md#wallet-child-and-chain-sources-as-android-sees-them) for +how the Android wallet screen drives it. ## What changed in the build @@ -34,6 +37,10 @@ the request rather than only the task name: cargo ndk build for arm64-v8a features=cuprate-daemon api=26 ndk=28.2.13676358 ``` +There is no `-P` knob that turns the feature off. A build that silently dropped +it would ship an APK whose on-device node can only fail; `android-ci.yml` greps +the artifact (below) so that is not only a log line. + ## The link line RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s build @@ -88,6 +95,10 @@ else: the `rust-version = "1.91"` MSRV are untouched, because the feature-off workspace does not need the bump and moving the MSRV is a separate decision. +`:sdk:preBuild` also runs `verifyDynamicLibc`: `libonionwire_sdk.so` must have +`libc.so` in `DT_NEEDED`. Linking the NDK's static `libc.a` instead null-derefs +inside `dlopen` on the first SDK call. + ## What ends up in the APK ``` @@ -103,8 +114,9 @@ lib/arm64-v8a/librandomx_rs-.so <- new, see below RandomX code is statically inside the SDK's own `.so` (its symbols and strings are there). `cargo-ndk` copies every cdylib the target directory produced into `jniLibs`, and `randomx-rs` also builds one. It is left in place rather than -filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated, and dropping -it would be a packaging rule that silently breaks the day something *does* link it. +filtered out: it is 1,122,296 bytes uncompressed / 387,996 deflated (sizes from +the feature-on CI run in the table below), and dropping it would be a packaging +rule that silently breaks the day something *does* link it. ## The CI gate @@ -125,11 +137,12 @@ above is the other half of the proof — request and artifact, separately checka * Selecting **On-device node (Cuprate)** stores `ChainChoice.InProcessCuprate` with an **empty** `monerod_datadir`, which the SDK resolves to - `$ONIONWIRE_HOME/chain` — the same directory a spawned `monerod` would use. Kotlin - never invents an absolute path. + `$ONIONWIRE_HOME/chain/{testnet,mainnet-pruned,mainnet-full}` from the stored + `mainnet` / `prune` flags — Kotlin never invents an absolute path. * `monero-wallet-rpc` is still required and still a subprocess: Start is gated on the bundled binary exactly as before, and an in-process node does not bundle - `arti`, so a `.onion` daemon is still refused. + `arti`, so a `.onion` daemon is still refused. Wallet RPC is loopback only. + Chain traffic stays off until the user opted into a wallet and chose a source. * The status line renders the core's words verbatim and grows a `node ` segment from `WalletChildStatus.node_state` for this source only. An unrecognised word is never rendered as ready. @@ -141,19 +154,29 @@ above is the other half of the proof — request and artifact, separately checka `node` segment) whenever either is non-zero: `0/0` means the last probe failed or the daemon is not up, so it is *unknown*, not `0%` — there is no percent, no progress bar and no ETA anywhere in the UI, and a zero target still prints as - `/0`. This is the **daemon's** chain height, not the wallet's scan height. The - same string is what the status row's screen-reader `contentDescription` carries - (`walletChildStatusDescription`), so the spoken row is never shorter than the - visible one. Cross-compiled and unit-tested on the JVM; still not device-proven. + `/0` when height is non-zero. This is the **daemon's** chain height, not the + wallet's scan height. The same string is what the status row's screen-reader + `contentDescription` carries (`walletChildStatusDescription`), so the spoken row + is never shorter than the visible one. Cross-compiled and unit-tested on the + JVM; still not device-proven. +* **What writes that snapshot on Android.** The wallet screen's 2 s loop + (`WireViewModel.refreshWalletChild`) calls `Wire.walletStatus()` — the cached + UniFFI read, no dial. The live probe `Wire.walletChildRefresh()` + (`Wire::wallet_child_refresh` in `crates/onionwire-sdk`) exists and is what + makes height/target move between calls; the TUI uses it. The APK poller on + this tree does not. See [README.md](README.md#what-the-apk-refresh-loop-actually-calls). * **Storage honesty.** The card shows the free space on the filesystem the fjall store grows into (`StatFs` on the app's data dir) and refuses Start below a - 3 GiB floor, or when that filesystem cannot be read at all. The floor is a - *floor*, not a sync estimate, and the doc comment says why: nothing in this stack + floor, or when that filesystem cannot be read at all. The floor is a *floor*, + not a sync estimate, and the doc comment says why: nothing in this stack exposes one — `WalletChildStatus` has no size field, and Cuprate's restricted RPC - reports a hardcoded 5 GiB `database_size` placeholder. + reports a hardcoded 5 GiB `database_size` placeholder. Floors in + `ui/WalletChildStatusText.kt`: 3 GiB testnet, 64 GiB mainnet-pruned, 280 GiB + mainnet-full. * **Pre-production warning**, above the Start button, in a sentence: - `CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only, and Cuprate - issue #278, assertable in `WalletChildStatusTextTest`. Opt-in, never a default. + `CUPRATE_PREPRODUCTION_WARNING` — quoted user book, testnet-only / mainnet + unvalidated, and Cuprate issue #278, assertable in `WalletChildStatusTextTest`. + Opt-in, never a default. ## What it costs in CI @@ -164,6 +187,9 @@ the feature on. There are two feature-on regimes, and the second is the one a PR author feels — the first build after the feature lands compiles the whole cuprated graph, every later build is incremental against the same volume. +These figures are the **recorded** costs from the runs that landed the feature +(not re-measured on `fa0e4b2`): + | | feature off — `main` 773dacb, run 402 | feature on — PR #113 head 3860c3d (merged as 8626da2), run 412 | |---|---|---| | Gradle | `BUILD SUCCESSFUL in 6m 10s` | `BUILD SUCCESSFUL in 7m 14s` | @@ -182,29 +208,42 @@ cargo job on the runner. After that it settles to roughly **+2 minutes over the feature-off build** (7m 14s vs 6m 10s), because only this repo's own crates recompile. -Nothing needed mitigating: the job's `timeout-minutes` is 120, so even the 44-minute -first build fits with room to spare, and the volume grows to 5.6 G on a runner -filesystem with 37 G free (the `df -h` in the run log). The feature is **not** gated -on a build variant, a label or a manual dispatch — the release path builds exactly -what CI verifies. +`android-ci.yml`'s job `timeout-minutes` is **120**; `android-release.yml`'s +Android job is **90**. Even the 44-minute first build fits both with room to +spare, and the volume grew to 5.6 G on a runner filesystem with 37 G free (the +`df -h` in the run log). The feature is **not** gated on a build variant, a label +or a manual dispatch — the release path builds exactly what CI verifies. `android-ci.yml` prints `du -sh /cargo-target`, the length/method/deflated size of every native lib, and both artifact digests, and the workflow echoes `build_wall_clock_seconds`: the next person changing this graph reads the cost and the artifact's identity out of the run log rather than re-deriving either. -## Not verified +## What has not been proven The daemon was **not executed on a device or an emulator**. There is no -`arm64-v8a` AVD on the build host (the same gap `MONERO_BINARIES.md` records), and -no aarch64 Android sysroot to run it under `qemu-user`. What is proven: it -cross-compiles and links against the NDK's C++ runtime, the feature is in the -shipped `.so`, the artifact packages, and the Kotlin that drives it compiles and -passes its unit tests. What is not: that `cuprated` starts, opens its fjall store -and answers on loopback under Android's runtime — and, on top of that, Cuprate -itself is pre-production and testnet-only. +`arm64-v8a` AVD on the build host (the same gap [MONERO_BINARIES.md](MONERO_BINARIES.md) +records), and no aarch64 Android sysroot to run it under `qemu-user`. What is +proven: it cross-compiles and links against the NDK's C++ runtime, the feature is +in the shipped `.so`, the artifact packages, and the Kotlin that drives it +compiles and passes its unit tests. What is not: -To close the gap, on an arm64 device or a software-emulated arm64 AVD: +* that `cuprated` starts, opens its fjall store and answers on loopback under + Android's runtime; +* **mainnet remains unvalidated.** Cuprate itself is pre-production and its own + user book says not to use `cuprated` for serious purposes. The Android screen + can store a mainnet-pruned or mainnet-full mode; that is not a claim this build + has run either. Core still surfaces `testnet only — mainnet is unvalidated` + (`cuprate::TESTNET_ONLY`); +* **a daemon that dies after the wallet child came up cannot be reported + `exited`.** The in-process node is a value this app owns, not a process with a + pid. The SDK derives `node_state` from the wallet-child state + (`crates/onionwire-sdk/src/lib.rs`, `node_state`). If the daemon dies after its + wallet child is up, the chain probe fails and the state stays `syncing`. It is + never reported `ready` from that failure. `exited` still means what it says: + the `monero-wallet-rpc` child is gone. + +To close the device gap, on an arm64 device or a software-emulated arm64 AVD: ```bash sdkmanager "system-images;android-35;google_apis;arm64-v8a" @@ -217,4 +256,6 @@ then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the warning, press **Start wallet**, and watch the status line for `connecting → syncing · in-process node · node starting → node syncing`. A wallet balance needs the chain synced, which on a phone is a long wait — the status line -is the thing to watch, not the balance. +is the thing to watch, not the balance. On this tree the APK loop will not itself +refresh height from the daemon; a live probe is a separate SDK call the TUI +makes and the Android poller does not. diff --git a/android/MONERO_BINARIES.md b/android/MONERO_BINARIES.md index c9f4185..4409049 100644 --- a/android/MONERO_BINARIES.md +++ b/android/MONERO_BINARIES.md @@ -1,22 +1,28 @@ # Bundled native executables (`jniLibs`) The wallet screen starts an **app-owned `monero-wallet-rpc` child** (issue #107, -`src/wallet_child.rs`). Monero ships no Android binaries, so this repository -carries one, built here. +[`src/wallet_child.rs`](../src/wallet_child.rs)). Monero ships no Android +binaries, so this repository carries one, built here. | | | |---|---| | File in the tree | `android/app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so` | | Bytes | 19 954 224 (stripped) | | sha256 | `d9126788030ecd1ccdb40c7764e66e9a14d158a147ad335b256f0577681b5ad4` | -| Format | `ELF 64-bit LSB shared object, ARM aarch64, dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b` | +| Format | `ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /system/bin/linker64, for Android 21, built by NDK r17b (4828580), stripped` | | Needed libs | `libc.so`, `libm.so`, `libdl.so` — everything else is static | | Source | `https://github.com/monero-project/monero` | | Tag | `v0.18.4.4` | -| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` | +| Commit | `516e5355a103a2bf0b7e10328ebcaa2945019445` (peeled annotated tag) | | Reproduce with | `scripts/build-monero-wallet-rpc-android.sh` | | Verified by | `android/monero-binaries.sha256`, checked by `scripts/build-android-local.sh` on every build (local and CI) | +Re-checked on this tree (`fa0e4b2`): `stat -c %s` is 19954224; `sha256sum` of the +blob equals the hash above and equals the line in `android/monero-binaries.sha256` +(that file's path is relative to `android/`: +`app/src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so`). `readelf -d` NEEDED is +`libdl.so`, `libm.so`, `libc.so`. + Only `arm64-v8a` is built. `-Ponionwire.abis=x86_64` produces an APK with no wallet binary in it — the screen says so (`NO_WALLET_RPC_MESSAGE`) instead of offering a Start that cannot work. @@ -28,8 +34,10 @@ cross-compile path — `contrib/depends` (boost, openssl, libunbound, libzmq, libsodium, ncurses, readline, libiconv, expat for `aarch64-linux-android`) plus the `toolchain.cmake` it emits — and then builds the single CMake target `wallet_rpc_server`. It takes ~40 min on 12 cores and needs ~15 GB of scratch -space. It is **not** part of the CI path: CI here runs on a Raspberry Pi and the -Gradle build is already ~9 minutes. CI verifies the committed bytes instead. +space. It is **not** part of the CI path: the Android Gradle jobs already run +on `docker-amd64` for ~9 minutes with warm volumes, and rebuilding Monero's C++ +tree is a separate 30–45 min host job. CI verifies the committed bytes instead +(`sha256sum -c` plus the APK-entry check in `scripts/build-android-local.sh`). Four things about the build are worth writing down, because each one is a failure that looks like something else: @@ -83,6 +91,11 @@ shipped blob** and the thing CI re-verifies — not a reproducible-build assertion. If you rebuild, update both `android/monero-binaries.sha256` and this table in the same commit, and say what changed in the tag or the toolchain. +The reproduce script pins **the tag** (`MONERO_TAG=v0.18.4.4`, shallow clone). +The commit in the table is the peeled object of that annotated tag on GitHub, +recorded here so a rebuild can be compared; it is not a second pin in the +script. + ## Why it is a `jniLibs` `.so` and not an asset Since Android 10 (API 29) an app may not `exec()` a file in its own data @@ -108,6 +121,8 @@ AGP's strip pass cannot rewrite the bytes that CI verifies. Cost: the release APK grows from ~9 MB to ~28 MB (the binary is deflate-stored at 6.9 MB) and installs ~20 MB into the app's native library directory. +(Those packaging sizes are the original measurement when the blob landed; the +committed blob's **uncompressed** size is the 19 954 224 bytes above.) ## `arti` is NOT bundled @@ -116,8 +131,7 @@ daemon, and `ChildConfig::validate` requires a non-empty `arti_bin` for any chain source that is not receive-only. There is no `arti` executable in this build, and producing one (a standalone `arti` binary for `aarch64-linux-android`, from a crate the Rust side does not currently build as -a bin) is a follow-up, not something this card could do without editing -`Cargo.toml`/`crates/**`. +a bin) is a follow-up, not something this document can invent. What the app does about it, honestly: @@ -133,9 +147,9 @@ So today: **loopback and clearnet daemons work; `.onion` daemons do not.** ## Verification in CI -`.forgejo/workflows/android-ci.yml` builds the APK on every `android/**` PR and -`scripts/build-android-local.sh` does the checking, so both CI jobs and local -builds get it: +`.forgejo/workflows/android-ci.yml` (and `android-release.yml`) build the APK on +`docker-amd64` and `scripts/build-android-local.sh` does the checking, so both +CI jobs and local builds get it: 1. before Gradle, `sha256sum -c android/monero-binaries.sha256` against the committed blob; @@ -171,8 +185,7 @@ at the arti notice above. The third chain source — Cuprate's chain daemon running inside the OnionWire process — is a **linked feature of the SDK's `.so`**, not a `jniLibs` executable, -so it has its own record: `android/CUPRATE_DAEMON.md` (feature wiring, the NDK C++ -/ compiler-rt link line, the CI check that greps the shipped `.so` for a -cuprated-only string, and what has not been verified). `monero-wallet-rpc` above -stays a child process for it — Cuprate has no wallet layer. - +so it has its own record: [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md) (feature wiring, +the NDK C++ / compiler-rt link line, the CI check that greps the shipped `.so` +for a cuprated-only string, and what has not been verified). `monero-wallet-rpc` +above stays a child process for it — Cuprate has no wallet layer. diff --git a/android/README.md b/android/README.md index 31d3980..6d58f6a 100644 --- a/android/README.md +++ b/android/README.md @@ -11,6 +11,14 @@ The Linux TUI in the repository root is a **separate product** with a separate Cargo workspace. Nothing here turns it into a WebView, and nothing here imports its TUI code. Same wire protocol: [docs/PROTOCOL.md](../docs/PROTOCOL.md). +Companion records (not duplicated here): + +* in-process chain daemon in the APK — [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md) +* bundled `monero-wallet-rpc` blob — [MONERO_BINARIES.md](MONERO_BINARIES.md) +* wallet / chain-source behaviour (core + SDK) — [docs/WALLET.md](../docs/WALLET.md) +* consuming the AAR — [crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md) +* how a maintainer actually cuts a release — [docs/RELEASING.md](../docs/RELEASING.md) + ## Requirements * JDK 17+ (built and tested on JDK 21) @@ -36,7 +44,8 @@ cd android ``` The Rust cross-compile and the UniFFI Kotlin bindings are wired into the Gradle -tasks — there is no manual codegen step. `:sdk:preBuild` depends on them. +tasks — there is no manual codegen step. `:sdk:preBuild` depends on +`cargoBuildAndroid`, `uniffiBindgen`, and `verifyDynamicLibc`. Emulator / x86_64 slice: @@ -44,13 +53,20 @@ Emulator / x86_64 slice: ./gradlew :app:assembleDebug -Ponionwire.abis=arm64-v8a,x86_64 ``` +That extra ABI does **not** ship `libmonerowalletrpc.so` for x86_64. The wallet +screen says so (`NO_WALLET_RPC_MESSAGE`) instead of offering a Start that cannot +work. See [MONERO_BINARIES.md](MONERO_BINARIES.md). + Or from the repo root, with checksums and an optional publish step: ```bash scripts/build-android-local.sh # -> dist/onionwire--android-arm64-v8a.apk -PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh +PUBLISH_TAG=v0.14.0 scripts/build-android-local.sh ``` +The script re-verifies `android/monero-binaries.sha256` before Gradle, then +again against the bytes inside the APK. It does not create tags. + ## Decisions you should know about ### `minSdk = 26` (Android 8.0) @@ -79,12 +95,24 @@ readelf -l android/sdk/build/rustJniLibs/arm64-v8a/libonionwire_sdk.so | grep LO ### Permissions -`INTERNET` only, declared at first launch. No camera (invites are pasted, not -scanned), no contacts, no storage permission — the data directory is -`context.filesDir`, which is already app-private. There is **no** -`FOREGROUND_SERVICE` and no keep-alive notification in v1: the node lives only -while the process does, and the UI says so. Adding one is a product decision -(battery, Play's FGS type declarations), not a silent fix. +`INTERNET` is the only permission requested at first launch. No camera (invites +are pasted, not scanned), no contacts, no storage permission — the data +directory is `context.filesDir`, which is already app-private. + +The node is **not** process-lifetime-only. After unlock, `KeepAliveService` is +a foreground service (`specialUse`, not `dataSync`) with an ongoing +notification so the onion stays published across Doze and backgrounding. The +manifest therefore also declares: + +* `FOREGROUND_SERVICE` +* `FOREGROUND_SERVICE_SPECIAL_USE` +* `POST_NOTIFICATIONS` (API 33+; denial hides the drawer notification, it does + not stop the service) + +`NodeHost` owns the single `Wire` handle. The service never does. Lock, or the +notification's Stop action, drops the keep-alive anchor; the node stays up +only while another owner (the UI) still holds it. `START_NOT_STICKY`: a +restarted empty service would show "reachable" over a dead onion. ### Data at rest @@ -148,9 +176,11 @@ Release APKs are signed with a **repo-owned keystore**, not the debug key. present (`~/.android/onionwire-release.jks` + `.env`, mode 600). Local and CI APKs then verify as the same cert and can upgrade in place. * If the env file is missing, Gradle **warns** and signs with the debug - keystore so a laptop build still installs. CI sets + keystore so a laptop build still installs. CI's `android-release.yml` sets `ONIONWIRE_REQUIRE_RELEASE_KEY=true` and **fails closed** instead — a per-machine debug key would make every CI APK uninstallable over the last. + `android-ci.yml` deliberately does **not** set that: it is a verification + build and `apksigner` reporting the debug cert there is expected. * Never commit a keystore, password, or `android/local.properties`. This is not a Play upload key; nothing here should be uploaded to Play. @@ -162,23 +192,148 @@ path and an on-device test of the JNI surface is how you ship an `UnsatisfiedLinkError` nobody can read. Turn it on together with crash deobfuscation, not before. -## CI +## Wallet child and chain sources (as Android sees them) -`.forgejo/workflows/android-release.yml` runs on `docker-amd64` (T480 dind). -The job image is `node:20-bullseye` (EOL) — **do not apt-get there**. The -toolchain runs in a sibling `debian:bookworm` container -(stdin-tar + `docker cp`, same pattern as the Rust CI job). -Any push to `main` that touches Android **sources or build config** -(`android/app/**`, `android/sdk/**`, Gradle files — not `android/README.md`) -workflow) builds `onionwire--android-arm64-v8a.apk` and -`onionwire-sdk-.aar`, verifies them, and attaches them to the Forgejo -release for that tag. Version is the latest `v*.*.*` tag plus patch, or -**v0.1.0** when there are no tags. `versionName` matches the tag; -`versionCode` is `major*10000 + minor*100 + patch` (so 0.1.0 → 100). +Chain traffic is **off** until the user opens Wallet, picks a source, and +presses Start. Receive-only is the default: no `monero-wallet-rpc` child, no +daemon, no P2P. -`workflow_dispatch` with `dry_run=true` builds and checksums without creating -a tag or publishing. `scripts/build-android-local.sh` remains the offline -fallback; it does not create tags. +The app owns `monero-wallet-rpc` (issue #107). It is still a **child process**, +exec'd from `applicationInfo.nativeLibraryDir/libmonerowalletrpc.so`. Cuprate +has no wallet layer — an in-process node does not replace that binary. + +Sources the screen offers: + +1. **Receive-only** — no child, no chain. +2. **A daemon address you type** — loopback or clearnet. Wallet RPC itself is + loopback only. A `.onion` host is refused while `libarti.so` is absent + (`ONION_NEEDS_ARTI_NOTICE`); this APK does not bundle `arti`. +3. **On-device node (Cuprate)** — opt-in. Selecting it stores + `ChainChoice.InProcessCuprate` with an empty `monerod_datadir`, which the + SDK resolves to `$ONIONWIRE_HOME/chain`. Kotlin never invents an absolute + path. The pre-production warning (`CUPRATE_PREPRODUCTION_WARNING`) sits + **above Start**, not after. The screen can store testnet, mainnet-pruned, or + mainnet-full (and applies the matching storage floor); **mainnet remains + unvalidated** and the warning says so. Cross-compiled is not device-proven. + See [CUPRATE_DAEMON.md](CUPRATE_DAEMON.md). + +Start is gated on the bundled wallet-rpc binary, on the storage floor for the +chosen Cuprate mode, and on the `.onion`/arti check. The floors are floors, not +sync estimates — nothing in this stack exposes a chain size: + +| Mode | Floor | +|---|---| +| testnet | 3 GiB | +| mainnet pruned | 64 GiB | +| mainnet full | 280 GiB | + +Unreadable free space (`StatFs` failed) is fail-closed: Start stays blocked. + +### Status line + +`ui/WalletChildStatusText.kt` is the pure model. The line renders the core's +words verbatim (`off` / `connecting` / `syncing` / `ready` / `exited`), then +the chain-source label, then — for the in-process source only — `node ` +from `WalletChildStatus.node_state`. An unrecognised word is never rendered as +ready. + +When the last probe reported a non-zero height or target, the line grows +` · sync h/t`. That is the **daemon's** chain height, not the wallet's scan +height. `0/0` is omitted (unknown), not printed as 0%. There is **no +percentage, no progress bar, and no ETA** anywhere in the UI. The same string +is the row's screen-reader `contentDescription`. + +Honest limit of the in-process node word: a daemon that dies *after* the wallet +child came up cannot be reported `exited` — there is no separate pid for the +in-process daemon, the chain probe fails, and the state stays `syncing`. +`exited` still means the `monero-wallet-rpc` child is gone. Details: +[CUPRATE_DAEMON.md](CUPRATE_DAEMON.md#what-has-not-been-proven). + +### What the APK refresh loop actually calls + +`WireViewModel.openWalletChild()` polls every 2 s +(`WALLET_CHILD_TICK_MS = 2_000`). Each tick is `Wire.walletStatus()` — the +cached, non-dialing UniFFI read (`Wire::wallet_status`). It never spawns and +it never probes the daemon, so `sync h/t` only moves when something else +wrote a fresh snapshot (start, a previous live probe). + +The SDK also exposes `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`): +a live probe of the loopback wallet RPC, and of the local daemon's `get_info` +when that RPC does not answer. The TUI uses it. **This APK's poller does not.** +Do not read the moving `sync h/t` docs in [docs/WALLET.md](../docs/WALLET.md) +as a description of the Android loop on this tree. + +## CI and releases + +A merge to `main` does **not** publish an APK. Neither does a tag push. +Releases are manual and batched: two dispatches. Full procedure: +[docs/RELEASING.md](../docs/RELEASING.md). + +### `android-ci.yml` (verification, not a release) + +Runs on `docker-amd64` (T480 dind) for every `push`/`pull_request` whose paths +include `android/**`, `src/**`, `crates/**`, `Cargo.toml`, `Cargo.lock`, +`scripts/build-android-local.sh`, or the workflow itself — plus +`workflow_dispatch`. Job image is `node:20-bullseye` (EOL) — **do not apt-get +there**. The toolchain runs in a sibling `debian:bookworm` container +(stdin-tar + `docker cp`). Both Android workflows install `cmake` in that +container (RandomX). + +It calls `scripts/build-android-local.sh` with the **debug** key +(`ONIONWIRE_REQUIRE_RELEASE_KEY` unset). Nothing is published. After the APK +is built it greps `lib/arm64-v8a/libonionwire_sdk.so` for `target_max_memory` +and **fails** if that cuprated-only string is missing. + +### `android-release.yml` (the APK that lands on a tag) + +`on:` is `workflow_dispatch` (and a declared `workflow_call` that this Forgejo +10.0.3 instance cannot invoke). **No `push` trigger.** Inputs: + +| Input | Default | Meaning | +|---|---|---| +| `tag` | empty | Existing tag to check out, build, and attach. | +| `dry_run` | `false` | Build and checksum; skip the Pi publish job. | + +Operator path, after `release.yml` has minted the tag (`dry_run=true` on that +workflow first): + +1. Actions → **android-release** → Run workflow, `tag=vX.Y.Z` (the tag core + just created), `dry_run=false`. +2. The Android job **checks out that tag** (`ref:` is the tag, not `main`) and + stamps `versionName` / `versionCode` from it. +3. `versionCode` is `major*10000 + minor*100 + patch` (so 0.14.0 → 1400). +4. Publish is a second job on the Pi runner (`docker`). It attaches + `onionwire--android-arm64-v8a.apk`, `onionwire-sdk-.aar`, + and both `.sha256` files to **that same tag**. + +The APK is built from **the tag's tree**. Building from `main` and stamping a +tag you did not check out is how you ship a binary that does not match the +tag. + +**Empty `tag` is the foot-gun.** Checkout then falls back to `github.sha` +(usually `main` HEAD). Version is *not* "latest `v*.*.*` plus patch" as a +rule: + +* no tags at all → `0.1.0`; +* latest `v*.*.*` release is **missing** the Android APK (or the job cannot + inspect the release) → **join** that version: same `versionName` restamped + onto whatever tree was checked out. Android will refuse to install that APK + over an already-installed build of the same `versionName`/`versionCode`; +* latest tag already has an Android APK → `patch+1` of that version, still + built from `github.sha`, and this workflow may then **create** that new tag + at publish time if it does not exist. + +Do not dispatch `android-release` with an empty `tag` to ship a release. Core +owns minting (`release.yml`, default `bump=minor`). This workflow attaches. + +`workflow_dispatch` with `dry_run=true` builds and checksums without +publishing. `scripts/build-android-local.sh` remains the offline fallback; it +does not create tags. + +The Android job image / bookworm-container story is the same as `android-ci.yml`. +The cuprated graph is built with `RUST_TOOLCHAIN=1.98` here (workspace MSRV +stays 1.91). Job timeout is **90** minutes on `android-release.yml` and **120** +on `android-ci.yml`. ## Layout @@ -187,17 +342,38 @@ android/ settings.gradle.kts build.gradle.kts # plugin aliases only gradle/libs.versions.toml # version catalog + gradle/wrapper/ + monero-binaries.sha256 # provenance of the bundled wallet-rpc blob + CUPRATE_DAEMON.md + MONERO_BINARIES.md sdk/ # -> AAR build.gradle.kts # cargo-ndk + uniffi-bindgen wiring consumer-rules.pro src/main/AndroidManifest.xml app/ # -> APK build.gradle.kts + src/main/AndroidManifest.xml src/main/java/com/siriusdevops/onionwire/ MainActivity.kt # NavHost - WireViewModel.kt # owns the single Wire node + WireViewModel.kt # UI-side Wire handle; wallet-child poller crypto/ # Keystore-wrapped store passphrase + keepalive/ # NodeHost, KeepAliveService, policy, lifetime + wallet/ # ChainStorage, WalletChildBinaries ui/ # Compose screens (M3) - src/test/ # JVM tests (envelope, store, invite flow) + WalletScreen.kt + WalletChildStatusText.kt + ChatScreen.kt + RosterScreen.kt + InviteScreens.kt + InviteAddFlow.kt + OutboxDetail.kt + MessageDelivery.kt + UnlockScreen.kt + UnlockSubmit.kt + RotateScreen.kt + Insets.kt + Theme.kt + src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line src/androidTest/ # device-only: AndroidKeyStore + src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so ``` From 0a8105584fde8bd2604d017716a60fa20c477a5b Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 00:56:08 -0400 Subject: [PATCH 19/94] docs(android): the APK poller now calls wallet_child_refresh #135 merged against fa0e4b2-era docs that said the loop was still wallet_status. #134 already landed: first paint is cached, every later tick is Wire::wallet_child_refresh. --- android/CUPRATE_DAEMON.md | 17 ++++++++--------- android/README.md | 31 ++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/android/CUPRATE_DAEMON.md b/android/CUPRATE_DAEMON.md index e3b422b..8689f2a 100644 --- a/android/CUPRATE_DAEMON.md +++ b/android/CUPRATE_DAEMON.md @@ -159,12 +159,12 @@ above is the other half of the proof — request and artifact, separately checka `contentDescription` carries (`walletChildStatusDescription`), so the spoken row is never shorter than the visible one. Cross-compiled and unit-tested on the JVM; still not device-proven. -* **What writes that snapshot on Android.** The wallet screen's 2 s loop - (`WireViewModel.refreshWalletChild`) calls `Wire.walletStatus()` — the cached - UniFFI read, no dial. The live probe `Wire.walletChildRefresh()` - (`Wire::wallet_child_refresh` in `crates/onionwire-sdk`) exists and is what - makes height/target move between calls; the TUI uses it. The APK poller on - this tree does not. See [README.md](README.md#what-the-apk-refresh-loop-actually-calls). +* **What writes that snapshot on Android.** The wallet screen's loop + (`WireViewModel.openWalletChild` → `walletChildRefreshLoop`) does one cached + `Wire.walletStatus()` paint, then every 2 s a live + `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). The live call is + what makes height/target move between ticks; it never spawns. See + [README.md](README.md#what-the-apk-refresh-loop-actually-calls). * **Storage honesty.** The card shows the free space on the filesystem the fjall store grows into (`StatFs` on the app's data dir) and refuses Start below a floor, or when that filesystem cannot be read at all. The floor is a *floor*, @@ -256,6 +256,5 @@ then unlock the node, open Wallet, tap **On-device node (Cuprate)**, read the warning, press **Start wallet**, and watch the status line for `connecting → syncing · in-process node · node starting → node syncing`. A wallet balance needs the chain synced, which on a phone is a long wait — the status line -is the thing to watch, not the balance. On this tree the APK loop will not itself -refresh height from the daemon; a live probe is a separate SDK call the TUI -makes and the Android poller does not. +is the thing to watch, not the balance. After the first cached paint, the APK +loop probes live every 2 s, so `sync h/t` should move once the daemon answers. diff --git a/android/README.md b/android/README.md index 6d58f6a..c96aaa4 100644 --- a/android/README.md +++ b/android/README.md @@ -251,17 +251,26 @@ in-process daemon, the chain probe fails, and the state stays `syncing`. ### What the APK refresh loop actually calls -`WireViewModel.openWalletChild()` polls every 2 s -(`WALLET_CHILD_TICK_MS = 2_000`). Each tick is `Wire.walletStatus()` — the -cached, non-dialing UniFFI read (`Wire::wallet_status`). It never spawns and -it never probes the daemon, so `sync h/t` only moves when something else -wrote a fresh snapshot (start, a previous live probe). +`WireViewModel.openWalletChild()` runs `walletChildRefreshLoop` with a 2 s +tick (`WALLET_CHILD_TICK_MS = 2_000`): -The SDK also exposes `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`): -a live probe of the loopback wallet RPC, and of the local daemon's `get_info` -when that RPC does not answer. The TUI uses it. **This APK's poller does not.** -Do not read the moving `sync h/t` docs in [docs/WALLET.md](../docs/WALLET.md) -as a description of the Android loop on this tree. +1. **First paint** — `paintWalletChildCached()` → `Wire.walletStatus()` + (`Wire::wallet_status`). Cached, no dial, so the screen has a record + while the first probe is still in flight. +2. **Every tick after that** — `refreshWalletChild()` → + `Wire.walletChildRefresh()` (`Wire::wallet_child_refresh`). That dials + the child's loopback wallet RPC, and the configured local daemon's + `get_info` when the wallet RPC does not answer, which is what makes + `sync h/t` move without another Start. It never spawns a child. With no + live child the core short-circuits to the cached `off` / `exited` + snapshot, so this cannot invent `ready`. + +The loop suspends on each read before it sleeps: a probe slower than 2 s +delays the next tick instead of overlapping it. Do not run two concurrent +`wallet_child_refresh` calls against one child. + +See [docs/WALLET.md](../docs/WALLET.md) (Android / SDK) for the same two +methods as the UniFFI surface. ## CI and releases @@ -373,7 +382,7 @@ android/ RotateScreen.kt Insets.kt Theme.kt - src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line + src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line, refresh loop src/androidTest/ # device-only: AndroidKeyStore src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so ``` From cb411da813aecba8a081fef8f885b03191136a22 Mon Sep 17 00:00:00 2001 From: sirius Date: Sun, 20 Sep 2026 09:17:05 -0400 Subject: [PATCH 20/94] wallet: answer the Digest challenge on the connection that issued it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the `http_server_auth` lives inside `http_custom_handler`, which is created per connection, so its nonce starts empty and any request without a valid `Authorization` field mints a fresh one. The client opened a *second* connection for the authenticated retry, presenting a nonce that socket never issued — so a real wallet RPC answered 401 forever, however correct the login was. That is the `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the canned mocks replayed the challenge on any socket, so they stayed green. - `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry, no `Connection: close` on the challenge (epee closes the socket with the 401 when the request asks for it), `read_one_response` honouring `Content-Length` (a keep-alive response never ends in EOF; with no length the body ends at EOF, which is what keeps the 1 MiB cap meaningful for an open RPC). - A 401 after our *own* challenge now reads: the login does not match the child's `--rpc-login`. - Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce: `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one connection, and a nonce presented on another connection is refused. - `docs/WALLET.md`: what a 401 means and why it is not the flow. Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`, `--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401 Unauthorized`; fixed tree → `connected: true` with the wallet's real address. --- docs/WALLET.md | 8 ++ src/node.rs | 159 ++++++++++++++-------------- src/wallet.rs | 158 +++++++++++++++++++++------- tests/wallet.rs | 275 ++++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 437 insertions(+), 163 deletions(-) diff --git a/docs/WALLET.md b/docs/WALLET.md index 6e431e2..054c48c 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -283,6 +283,14 @@ OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and refuses URLs without credentials. Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL. Do not log the password. +`monero-wallet-rpc` mints its Digest nonce **per TCP connection** (epee's +`http_custom_handler` owns the auth state), so the challenge and the +authenticated retry have to ride the same socket — a retry on a fresh connection +is refused with 401 no matter how correct the login is. OnionWire does exactly +that. A `wallet RPC HTTP HTTP/1.1 401 Unauthorized` status therefore means one +thing: the login does not match the child's `--rpc-login`. Regenerate the child +(and its sealed creds) rather than retrying. + ## The spend-authority warning An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a diff --git a/src/node.rs b/src/node.rs index 15e7220..fcc8015 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2205,59 +2205,80 @@ mod tests { .to_string() } - /// A wallet child that clears the Digest challenge and answers one - /// `transfer` — the two-connection dance `tests/wallet.rs` mocks. + /// Serve a mock wallet RPC whose Digest state is **per connection**, the way + /// epee does it: the nonce is minted by the socket that answered 401 and is + /// valid nowhere else, so a client that retries on a fresh socket is refused + /// forever. `reply` maps a request to its JSON-RPC body. The socket closes + /// after an authenticated reply — the client asks for `Connection: close` + /// there and the real server honours it. + async fn serve_mock_rpc( + listener: tokio::net::TcpListener, + reply: Arc String + Send + Sync>, + ) { + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + static NEXT_NONCE: AtomicUsize = AtomicUsize::new(1); + + while let Ok((mut sock, _)) = listener.accept().await { + let reply = Arc::clone(&reply); + tokio::spawn(async move { + let mut nonce: Option = None; + loop { + let mut buf = vec![0u8; 8192]; + let Ok(n) = sock.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let answered = req.contains("Authorization:") + && nonce.as_deref().is_some_and(|held| req.contains(held)); + if !answered { + let fresh = format!("nonce{}", NEXT_NONCE.fetch_add(1, Ordering::Relaxed)); + let challenge = format!( + "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{fresh}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n" + ); + if sock.write_all(challenge.as_bytes()).await.is_err() { + return; + } + nonce = Some(fresh); + continue; + } + let body = reply(&req); + let ok = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let _ = sock.write_all(ok.as_bytes()).await; + return; + } + }); + } + } + /// A loopback wallet RPC that answers what the tip path actually asks for: /// a digest challenge, then a synced `get_info` for the readiness gate and /// `tx_hash` for the transfer. The old single-answer mock stopped covering /// the path when `Wallet::transfer` started probing the chain tip first — /// it answered `tx_hash` to `get_info` and every tip was refused as unsynced. async fn mock_wallet() -> Wallet { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); - tokio::spawn(async move { - // Every call starts unauthenticated, so every call gets one - // challenge — the client retries each request with digest auth. - for _ in 0..8 { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let Ok(n) = sock.read(&mut buf).await else { - return; - }; - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock - .write_all( - b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - continue; - } - let body = if req.contains("get_info") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"# - }; - let _ = sock - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .as_bytes(), - ) - .await; + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("get_info") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string() } }); + tokio::spawn(serve_mock_rpc(listener, reply)); Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } - /// The payer of a tip must see it in their own chat: `receipt_chat_line` is /// the recipient's view of the frame that arrived, `tip_chat_line` is what /// the sender just spent. @@ -2522,60 +2543,34 @@ mod tests { } } + /// A loopback wallet RPC that answers the *status* probe: a digest + /// challenge, then `get_address` / `get_balance` / `get_info`, with the + /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the + /// *transfer* path; this one answers a refresh, which never transfers. /// A loopback wallet RPC that answers the *status* probe: a digest /// challenge, then `get_address` / `get_balance` / `get_info`, with the /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the /// *transfer* path; this one answers a refresh, which never transfers. async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); - tokio::spawn(async move { - // Every call starts unauthenticated, so every call gets one - // challenge — the client retries each request with digest auth. - for _ in 0..8 { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let Ok(n) = sock.read(&mut buf).await else { - return; - }; - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock - .write_all( - b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - continue; - } - let body = if req.contains("get_info") { - format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# - ) - } else if req.contains("get_address") { - format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, - addr = xmr_addr() - ) - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() - }; - let _ = sock - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .as_bytes(), - ) - .await; + let reply: Arc String + Send + Sync> = Arc::new(move |req: &str| { + if req.contains("get_info") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# + ) + } else if req.contains("get_address") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, + addr = xmr_addr() + ) + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() } }); + tokio::spawn(serve_mock_rpc(listener, reply)); Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } diff --git a/src/wallet.rs b/src/wallet.rs index 226dab0..7195691 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -848,26 +848,21 @@ impl Wallet { "params": params, }) .to_string(); - let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?; + let (challenged, raw) = post_digest(ep, &body, budget).await?; let status = http_status(&raw).unwrap_or(0); - if status == 200 { + if status == 401 { + // A digest built from *this* connection's own challenge was + // refused, so the login is wrong, not the flow. + return Err(Error( + "wallet RPC digest rejected (HTTP 401) — the login does not match the child's --rpc-login" + .into(), + )); + } + if !challenged && status == 200 { return Err(Error( "wallet RPC requires digest auth (open RPC refused)".into(), )); } - if status != 401 { - return parse_json_rpc(&raw); - } - let challenge = www_authenticate(&raw).ok_or_else(|| { - Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()) - })?; - if !challenge.trim().to_ascii_lowercase().starts_with("digest") { - return Err(Error( - "wallet RPC digest required (--rpc-login / HTTP Digest)".into(), - )); - } - let auth = digest_authorization(ep, &challenge)?; - let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?; parse_json_rpc(&raw) } } @@ -996,19 +991,65 @@ fn host_header(host: &str, port: u16) -> String { const MAX_RPC_BYTES: usize = 1024 * 1024; -async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result> { - tokio::time::timeout(budget, http_post(ep, req.as_bytes())) +/// One loopback connection: ask for the digest challenge, answer it, and hand +/// back `(was_challenged, final_response)`. +/// +/// The retry has to ride the **same socket** as the challenge. epee owns its +/// digest state per connection — `http_custom_handler` holds the +/// `http_server_auth`, whose session starts with an empty nonce and counter 0, +/// and any request without a valid `Authorization` field makes it mint a fresh +/// nonce. A retry that opens a new socket presents a nonce that connection never +/// issued, so `monero-wallet-rpc` answers 401 again, permanently. That is the +/// 401 the TUI and Android showed against a real wallet RPC while a canned mock +/// (which replays the challenge on any socket) stayed green. +async fn post_digest(ep: &Endpoint, body: &str, budget: Duration) -> Result<(bool, Vec)> { + tokio::time::timeout(budget, http_digest(ep, body)) .await .map_err(|_| Error("wallet RPC timed out".into()))? } -fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String { +async fn http_digest(ep: &Endpoint, body: &str) -> Result<(bool, Vec)> { + let mut stream = TcpStream::connect((ep.host.as_str(), ep.port)) + .await + .map_err(|e| Error(format!("wallet connect: {e}")))?; + // No `Connection: close` on the challenge: epee closes the socket with the + // 401 when the request asks for it, and the retry needs this connection. + let req = build_req(ep, body, None, false); + stream + .write_all(req.as_bytes()) + .await + .map_err(|e| Error(format!("wallet write: {e}")))?; + let raw = read_one_response(&mut stream).await?; + let status = http_status(&raw).unwrap_or(0); + if status != 401 { + return Ok((false, raw)); + } + let challenge = www_authenticate(&raw) + .ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?; + if !challenge.trim().to_ascii_lowercase().starts_with("digest") { + return Err(Error( + "wallet RPC digest required (--rpc-login / HTTP Digest)".into(), + )); + } + let auth = digest_authorization(ep, &challenge)?; + let req = build_req(ep, body, Some(&auth), true); + stream + .write_all(req.as_bytes()) + .await + .map_err(|e| Error(format!("wallet write: {e}")))?; + Ok((true, read_to_eof(&mut stream).await?)) +} + +fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>, close: bool) -> String { let host_hdr = host_header(&ep.host, ep.port); let mut req = format!( - "POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n", + "POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n", ep.path, body.len() ); + if close { + req.push_str("Connection: close\r\n"); + } if let Some(auth) = authorization { req.push_str("Authorization: "); req.push_str(auth); @@ -1019,32 +1060,73 @@ fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String { req } -async fn http_post(ep: &Endpoint, req: &[u8]) -> Result> { - let mut stream = TcpStream::connect((ep.host.as_str(), ep.port)) - .await - .map_err(|e| Error(format!("wallet connect: {e}")))?; - stream - .write_all(req) - .await - .map_err(|e| Error(format!("wallet write: {e}")))?; +/// Read exactly one HTTP response: its head, then `Content-Length` body bytes. +/// epee always emits `Content-Length`, and a keep-alive response never ends in +/// EOF — reading to EOF here would hang on a healthy server. +async fn read_one_response(stream: &mut TcpStream) -> Result> { let mut buf = Vec::new(); - let mut tmp = [0u8; 8192]; - loop { - let n = stream - .read(&mut tmp) - .await - .map_err(|e| Error(format!("wallet read: {e}")))?; - if n == 0 { + let head_end = loop { + if let Some(i) = find_head_end(&buf) { + break i; + } + if !read_more(stream, &mut buf).await? { + // Closed before a full head: hand back what arrived, the status-line + // parse decides what that means. + return Ok(buf); + } + }; + let head = std::str::from_utf8(&buf[..head_end]).unwrap_or_default(); + // epee always sends `Content-Length`, but an open (challenge-less) RPC may + // not: with no length the body ends at EOF, so keep reading — the cap below + // is what stops a server that streams forever. + let Some(want) = content_length(head) else { + while read_more(stream, &mut buf).await? {} + return Ok(buf); + }; + while buf.len() < head_end + 4 + want { + if !read_more(stream, &mut buf).await? { break; } - if buf.len().saturating_add(n) > MAX_RPC_BYTES { - return Err(Error("wallet RPC response too large".into())); - } - buf.extend_from_slice(&tmp[..n]); } Ok(buf) } +async fn read_to_eof(stream: &mut TcpStream) -> Result> { + let mut buf = Vec::new(); + while read_more(stream, &mut buf).await? {} + Ok(buf) +} + +/// One read into `buf`. `false` means the peer closed. Enforces the shared cap. +async fn read_more(stream: &mut TcpStream, buf: &mut Vec) -> Result { + let mut tmp = [0u8; 8192]; + let n = stream + .read(&mut tmp) + .await + .map_err(|e| Error(format!("wallet read: {e}")))?; + if n == 0 { + return Ok(false); + } + if buf.len().saturating_add(n) > MAX_RPC_BYTES { + return Err(Error("wallet RPC response too large".into())); + } + buf.extend_from_slice(&tmp[..n]); + Ok(true) +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + head.lines().skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse().ok()) + .flatten() + }) +} + fn http_status(raw: &[u8]) -> Option { let text = std::str::from_utf8(raw).ok()?; let line = text.lines().next()?; diff --git a/tests/wallet.rs b/tests/wallet.rs index 3007ab9..da8e8f3 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -248,6 +248,81 @@ async fn oversized_rpc_response_is_err() { ); } +/// The Digest challenge is bound to the **connection** that answered 401, the +/// way epee does it: `http_custom_handler` owns the `http_server_auth`, whose +/// nonce starts empty, so a nonce is only ever valid on the socket that received +/// it. A client that retries on a fresh socket presents a nonce that socket +/// never issued and is refused again — the real `monero-wallet-rpc` 401 this +/// suite reproduces. One socket serves requests until it closes; the mock closes +/// after an authenticated reply, because the client asks for `Connection: close` +/// there and epee honours it. +async fn serve_one_conn( + mut sock: tokio::net::TcpStream, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + let mut nonce: Option = None; + while let Some(req) = read_http_request(&mut sock).await { + if let Some(log) = &log { + log.lock().expect("log").push(req.clone()); + } + let sent = authorization_nonce(&req); + if sent.is_some() && sent == nonce { + assert!(req.contains("Authorization: Digest"), "missing digest auth: {req}"); + assert!(req.contains("username=\"ow\""), "missing user: {req}"); + assert!(req.contains("response=\""), "missing response: {req}"); + if let Some(d) = delay { + tokio::time::sleep(d).await; + } + let answer = reply(&rpc_method(&req)); + // `raw_reply` servers hand back a whole HTTP response (some tests + // bake their own status line); the default is a JSON-RPC body. + let wire = if raw_reply { + answer + } else { + http_200_body(&answer) + }; + let _ = sock.write_all(wire.as_bytes()).await; + return; + } + let fresh = next_nonce(); + let _ = sock.write_all(digest_401(&fresh).as_bytes()).await; + nonce = Some(fresh); + } +} + +/// Accept loop for [`serve_one_conn`]. +async fn serve_rpc_conns( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, +) { + serve_rpc_conns_with(listener, reply, log, delay, false).await +} + +/// [`serve_rpc_conns`] with the reply contract spelled out: `raw_reply` means the +/// closure returns a complete HTTP response, otherwise a JSON-RPC body. +async fn serve_rpc_conns_with( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + while let Ok((sock, _)) = listener.accept().await { + tokio::spawn(serve_one_conn( + sock, + Arc::clone(&reply), + log.clone(), + delay, + raw_reply, + )); + } +} + /// Records every request the client sends, answers the Digest challenge and /// then replies per RPC method. Lets a test assert on the *request log*. async fn serve_recording( @@ -255,21 +330,62 @@ async fn serve_recording( log: Arc>>, reply: Arc String + Send + Sync>, ) { - loop { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let mut buf = vec![0u8; 8192]; - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - log.lock().expect("log").push(req.clone()); - if req.contains("Authorization:") { - let body = reply(&rpc_method(&req)); - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } else { - let _ = sock.write_all(digest_401().as_bytes()).await; + serve_rpc_conns(listener, reply, Some(log), None).await +} + +/// Read one whole request: its head, then `Content-Length` body bytes. `None` +/// when the peer closed. +async fn read_http_request(sock: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let head_end = loop { + if let Some(i) = find_head_end(&buf) { + break i; + } + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => return None, + Ok(n) => buf.extend_from_slice(&tmp[..n]), + } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let want = content_length(&head).unwrap_or(0); + while buf.len() < head_end + 4 + want { + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => break, + Ok(n) => buf.extend_from_slice(&tmp[..n]), } } + Some(String::from_utf8_lossy(&buf).to_string()) +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + head.lines().skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse().ok()) + .flatten() + }) +} + +/// The `nonce` a request's `Authorization` field answers. +fn authorization_nonce(req: &str) -> Option { + let head = req.split("\r\n\r\n").next().unwrap_or(req); + let line = head + .lines() + .find(|l| l.to_ascii_lowercase().starts_with("authorization:"))?; + let rest = line.split_once("nonce=")?.1; + Some(rest.trim_start_matches('"').split('"').next()?.to_string()) +} + +/// A fresh server nonce per 401, so a stale one never passes by luck. +fn next_nonce() -> String { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(1); + format!("nonce{:016x}", NEXT.fetch_add(1, Ordering::Relaxed)) } fn rpc_method(req: &str) -> String { @@ -588,28 +704,106 @@ fn from_env_reads_no_spend_flag() { assert!(!Wallet::from_env().no_spend(), "unset must be off"); } -fn digest_401() -> String { - "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into() +fn digest_401(nonce: &str) -> String { + format!( + "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{nonce}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n" + ) } +/// Answers the Digest challenge on one connection with `ok` — a complete HTTP +/// response — to every method. async fn serve_digest_then(listener: TcpListener, ok: String) { - let (mut sock, _) = listener.accept().await.expect("accept"); - let mut buf = vec![0u8; 8192]; - let _ = sock.read(&mut buf).await; - sock.write_all(digest_401().as_bytes()).await.expect("401"); - drop(sock); + serve_rpc_conns_with(listener, Arc::new(move |_| ok.clone()), None, None, true).await +} - let (mut sock, _) = listener.accept().await.expect("accept2"); - buf.fill(0); - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]); - assert!( - req.contains("Authorization: Digest"), - "missing digest auth: {req}" +/// The digest retry must ride the socket that issued the challenge. epee binds +/// the nonce to the connection, so the pre-fix shape — challenge on one socket, +/// authenticated retry on another — is refused with 401 forever. That is the +/// `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed while +/// this suite stayed green against a mock that replayed the challenge on any +/// socket. +#[tokio::test] +async fn digest_retry_rides_the_connection_that_issued_the_challenge() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let conns = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&conns); + tokio::spawn(async move { + while let Ok((sock, _)) = listener.accept().await { + counted.fetch_add(1, Ordering::SeqCst); + tokio::spawn(serve_one_conn( + sock, + Arc::new(|_: &str| { + rpc_result( + r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, + ) + }), + None, + None, + false, + )); + } + }); + + let got = recording_wallet(port) + .get_address() + .await + .expect("a same-socket digest retry must be accepted"); + assert!(got.starts_with('4'), "got {got}"); + assert_eq!( + conns.load(Ordering::SeqCst), + 1, + "one RPC call must use one connection: challenge and retry share it" + ); +} + +/// The flip side, pinned at the socket level: the nonce belongs to the +/// connection that minted it, so the same digest on a second connection is +/// refused. Without this the mock could silently go back to accepting the +/// cross-connection retry and stop catching the bug. +#[tokio::test] +async fn the_mock_refuses_a_digest_presented_on_another_connection() { + use tokio::net::TcpStream; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_result("{}")), + None, + None, + )); + + let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_version","params":{}}"#; + let plain = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + + let mut first = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + first.write_all(plain.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut first).await.expect("the 401"); + assert!(raw.starts_with("HTTP/1.1 401"), "got {raw}"); + let nonce = raw + .split_once("nonce=\"") + .and_then(|(_, rest)| rest.split('"').next()) + .expect("a challenge nonce") + .to_string(); + drop(first); + + let answered = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAuthorization: Digest username=\"ow\", realm=\"monero-rpc\", nonce=\"{nonce}\", uri=\"/json_rpc\", algorithm=MD5, response=\"deadbeef\"\r\n\r\n{body}", + body.len() + ); + let mut second = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + second.write_all(answered.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut second).await.expect("the second 401"); + assert!( + raw.starts_with("HTTP/1.1 401"), + "a nonce from another connection must not be accepted: {raw}" ); - assert!(req.contains("username=\"ow\""), "missing user: {req}"); - assert!(req.contains("response=\""), "missing response: {req}"); - sock.write_all(ok.as_bytes()).await.expect("200"); } #[tokio::test] @@ -628,23 +822,18 @@ async fn mock_digest_auth_accepted() { /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { - while let Ok((mut sock, _)) = listener.accept().await { - let mut buf = vec![0u8; 8192]; - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { - let _ = sock.write_all(digest_401().as_bytes()).await; - continue; - } - tokio::time::sleep(delay).await; - let body = match rpc_method(&req).as_str() { + serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { "get_info" => synced_info(), _ => rpc_result( r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, ), - }; - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } + }), + None, + Some(delay), + ) + .await } const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; From 145036fda83c1bbd7703bfdf3989014cec35c7cb Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 11:53:19 -0400 Subject: [PATCH 21/94] wallet: expose an on-demand seed accessor over core + UniFFI Wallet::create_wallet returned the 25-word seed exactly once and nothing could reach it afterwards, so a seed that was never backed up at creation was unrecoverable. Add Wallet::mnemonic() (one query_key mnemonic call on the open wallet file), Node::wallet_seed() mirroring wallet_create, and the additive UniFFI export Wire::wallet_seed() -> Kotlin Wire.walletSeed(). No existing signature changes. The refusals stay leak-free: an unconfigured wallet gets NOT_CONFIGURED_MSG without a dial, a watch-only wallet keeps the RPC's -29 view-only mapping, and no error string carries the RPC login. Tests (tests/wallet.rs) drive the per-connection Digest mock: the words come back verbatim, a JSON-RPC error surfaces without the login or endpoint, a rejected digest refusal does not leak the password, and an unconfigured wallet is refused without dialing. --- crates/onionwire-sdk/src/lib.rs | 11 +++++ src/node.rs | 12 ++++++ src/wallet.rs | 19 +++++++++ tests/wallet.rs | 74 +++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..3680aa7 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -594,6 +594,17 @@ impl Wire { .map_err(WireError::new) } + /// Re-read this wallet's 25-word seed so the UI can offer a "back up seed" + /// action after creation. Dials the wallet child's RPC (`query_key + /// mnemonic`), so it is cheap but not free, and it needs a wallet the child + /// has open. The result is a spend key: call this only from an explicit + /// user action, show it, and do not persist or log it. + /// + /// The Kotlin binding is `Wire.walletSeed()`. + pub async fn wallet_seed(&self) -> WResult { + self.node()?.wallet_seed().await.map_err(WireError::new) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { diff --git a/src/node.rs b/src/node.rs index fcc8015..a78ea8d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1179,6 +1179,18 @@ impl Node { .map_err(|e| e.to_string()) } + /// Re-read the seed of the wallet file the child has open. `create_wallet` + /// returns it once; after that this is the only path to it. The seed is a + /// spend key, so the caller must only show it on an explicit user action + /// and must not log or store it. + pub async fn wallet_seed(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.mnemonic().await.map_err(|e| e.to_string()) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { diff --git a/src/wallet.rs b/src/wallet.rs index 7195691..e4437da 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -788,6 +788,25 @@ impl Wallet { json_str(&v, "key") } + /// Re-read the seed of the wallet file the RPC has open (`query_key + /// mnemonic`). After `create_wallet` this is the **only** way to recover a + /// created wallet's seed, so the UI can offer a backup action instead of + /// showing it once. It needs an open, spend-capable wallet file; a + /// watch-only one answers the RPC's `-29` and surfaces as the view-only + /// refusal. + /// + /// The returned words are a spend key: never log them, never store them, + /// and never put them in an error string. + pub async fn mnemonic(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await?; + json_str(&v, "key") + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index da8e8f3..9c8649b 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -819,6 +819,80 @@ async fn mock_digest_auth_accepted() { assert!(got.starts_with('4'), "got {got}"); } +/// The seed is a spend key: `mnemonic` must be one `query_key mnemonic` call +/// and nothing else, so the caller sees exactly what the open wallet answers. +#[tokio::test] +async fn mnemonic_returns_the_words_the_rpc_answers() { + const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve \ +thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone \ +twentytwo twentythree twentyfour twentyfive"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { + "query_key" => rpc_result(&format!(r#"{{"key":"{WORDS}"}}"#)), + other => panic!("mnemonic must make one query_key call, saw {other}"), + }), + None, + None, + )); + let got = recording_wallet(port).mnemonic().await.expect("mnemonic"); + assert_eq!(got, WORDS); +} + +/// A wallet with no open file answers a JSON-RPC error. It must surface as the +/// wallet's error, and the RPC login from the URL must not ride along with it. +#[tokio::test] +async fn mnemonic_surfaces_an_rpc_error_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_error(-1, "wallet file is not open")), + None, + None, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); + assert!(!msg.contains("http://"), "endpoint leaked: {err}"); +} + +/// The refused-digest refusal names the login in prose ("the login does not +/// match"), which is exactly the copy that must not carry the credential. +#[tokio::test] +async fn mnemonic_refuses_a_rejected_digest_without_leaking_the_login() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns_with( + listener, + Arc::new(|_: &str| "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_string()), + None, + None, + true, + )); + let err = recording_wallet(port).mnemonic().await.unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("digest rejected"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.mnemonic()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From 118191c5412aa489d5c2cf3f8c8b1bc764861af2 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 20 Sep 2026 12:09:48 -0400 Subject: [PATCH 22/94] android: block the wallet screen on an unbacked seed, and make it re-showable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A created wallet's seed was two lines of small text at the bottom of the wallet page, dismissed by one tap, gone for good once the screen was left. A real user created a wallet, never saw the seed, and the app had no way to show it again. - `SeedBackupGate` (new, pure Kotlin): the confirm word `SEEN` and its case-insensitive match mirror the TUI's own `WalletSetup::CreateSeed` gate; create starts unbacked, import is backed up without the gate, and only a correct word can confirm. - The seed card is the whole body until the word is typed and Done is tapped: no Cancel, no copy button (the Android clipboard is readable by every other app), Done dead until `SEEN`. - "Back up seed" re-reads the seed through the new `Wire::wallet_seed()` (`WireViewModel.walletSeed()`), so a seed missed the first time is not lost. Its failure is shown next to the button, not at the bottom of a long scroll. - While unconfirmed: a warning strip stays at the top of the wallet screen and the receive address and Show QR are hidden — XMR received into a wallet whose 25 words were never written down is unrecoverable. - The flag lives in app-local prefs (`wallet_seed_backup`), not in the Keystore-wrapped store, and is reset by `createWallet` itself so no caller can forget it. The stored flag is nullable, and the null is load-bearing. `false` means this install created a wallet and nobody has confirmed the seed, so the strip is up whether or not the balance reads. `null` means nothing is stored — an install that predates the flag, or one that has never created a wallet here — and there the strip waits for `wallet_balance` to return a real amount, the core's own evidence that the child has a wallet open. Without that distinction a first-run user who had configured a chain source but not yet created a wallet (`wallet_balance` returns "err") would be warned about a seed they do not have. The app-bar Back still leaves the screen, deliberately — it is the TUI's `Esc`. It costs nothing now, because leaving no longer loses the seed. Verification: `./gradlew :app:testDebugUnitTest` green, 135 tests (`SeedBackupGateTest` 18 of them). --- .../siriusdevops/onionwire/WireViewModel.kt | 76 ++++++ .../onionwire/ui/SeedBackupGate.kt | 113 +++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 240 ++++++++++++++++-- .../onionwire/ui/SeedBackupGateTest.kt | 176 +++++++++++++ 4 files changed, 588 insertions(+), 17 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 6f26632..7be3c6a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -1,6 +1,8 @@ package com.siriusdevops.onionwire import android.app.Application +import android.content.Context +import android.content.SharedPreferences import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope @@ -11,6 +13,8 @@ import com.siriusdevops.onionwire.crypto.StoredPassphraseStore import com.siriusdevops.onionwire.keepalive.KeepAliveService import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost +import com.siriusdevops.onionwire.ui.SeedBackupGate +import com.siriusdevops.onionwire.ui.WalletKeyOrigin import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries @@ -588,11 +592,32 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + /** + * Create a wallet and read its seed once. The seed-backup flag is reset + * here, not by the screen: every successful create is a new seed nobody has + * read, and a caller that forgot to reset it would leave a spend key + * unrecoverable. See [SeedBackupGate.afterWallet]. + */ suspend fun createWallet(password: String): Result = runCatching { requireWire().createWallet(password) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) } + /** + * Import a wallet from a user-supplied seed. That seed is already on paper — + * the user just pasted it — so the wallet counts as backed up without the + * confirm step. + */ suspend fun importWallet(password: String, seed: String): Result = runCatching { requireWire().importWallet(password, seed) } + .onSuccess { setWalletSeedConfirmed(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) } + + /** + * Re-read the open wallet's 25-word seed, for the "Back up seed" recovery + * path. A spend key: only ever called from that explicit user action, shown + * on the blocking card, and dropped. Never logged and never persisted. + */ + suspend fun walletSeed(): Result = + runCatching { requireWire().walletSeed() } fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() @@ -600,6 +625,47 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." } + // --- Seed backup gate -------------------------------------------------- + // Whether the open wallet's seed has been confirmed written down. This is + // NOT a secret — it is a boolean in app-local prefs, deliberately kept out + // of the Keystore-wrapped store under `filesDir/secrets`, which holds the + // passphrase and nothing else. + // + // The flow is nullable, and the null is load-bearing: nothing stored means + // "this install has never created or imported a wallet through this build", + // which is not the same as "the user created one and has not confirmed it". + // See [SeedBackupGate.warningVisible] for why the screen needs both. + + private val seedBackupPrefs: SharedPreferences = + app.getSharedPreferences(SEED_BACKUP_PREFS, Context.MODE_PRIVATE) + + private val _walletSeedConfirmed = MutableStateFlow( + if (seedBackupPrefs.contains(SEED_BACKED_UP_KEY)) { + seedBackupPrefs.getBoolean(SEED_BACKED_UP_KEY, false) + } else { + null + }, + ) + + /** + * The stored seed-backup flag: `false` unconfirmed, `true` confirmed or + * imported, `null` nothing stored (an install that predates the flag). + */ + val walletSeedConfirmed: StateFlow = _walletSeedConfirmed.asStateFlow() + + /** + * One confirm step from the blocking seed card. The gate decides: a wrong + * word leaves the flag where it was, so this can never un-confirm a wallet. + */ + fun confirmWalletSeed(typed: String) { + setWalletSeedConfirmed(SeedBackupGate.afterConfirm(typed, _walletSeedConfirmed.value == true)) + } + + private fun setWalletSeedConfirmed(confirmed: Boolean) { + seedBackupPrefs.edit().putBoolean(SEED_BACKED_UP_KEY, confirmed).apply() + _walletSeedConfirmed.value = confirmed + } + // --- App-owned wallet child (issue #107) ------------------------------- // The app owns `monero-wallet-rpc` instead of asking the user to start one // and export `ONIONWIRE_WALLET_RPC`. The core's own states are surfaced @@ -920,3 +986,13 @@ suspend fun walletChildRefreshLoop( /** Cadence of the wallet-child refresh loop, in milliseconds. */ private const val WALLET_CHILD_TICK_MS: Long = 2_000 + +/** + * App-local prefs file for the seed-backup flag. Not a secret, so it is a plain + * prefs file rather than anything under `filesDir/secrets`. + */ +private const val SEED_BACKUP_PREFS: String = "wallet_seed_backup" + +/** Key inside [SEED_BACKUP_PREFS]: has the open wallet's seed been written down? */ +private const val SEED_BACKED_UP_KEY: String = "backed_up" + diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt new file mode 100644 index 0000000..ee0c303 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt @@ -0,0 +1,113 @@ +package com.siriusdevops.onionwire.ui + +/** + * Where the open wallet's key material came from. + * + * The distinction is the whole gate. A seed the user *supplied* (import) is a + * seed the user already has on paper, so that wallet is backed up from the + * start. A seed the app *generated* (create) has been read by nobody until it + * is put on screen, so that wallet starts unbacked and stays unbacked until the + * user proves it is written down. + */ +enum class WalletKeyOrigin { + Created, + Imported, +} + +/** + * The seed-backup gate: every decision the wallet screen makes about an + * unconfirmed seed, as pure Kotlin — no Compose, no Android, no prefs — so the + * rules are covered by `SeedBackupGateTest` on the JVM without a device. + * + * The gate exists because a seed shown once and then lost is an unrecoverable + * wallet: XMR received into a wallet whose 25 words were never written down + * cannot be spent or recovered by anyone, including this app. So the answer is + * not advisory — while it says the seed is unbacked, the wallet screen keeps a + * warning up and hides the receive address and its QR. + * + * The confirm word and its case-insensitivity mirror the TUI's own seed screen + * (`src/tui.rs`, `WalletSetup::CreateSeed`, which compares with + * `eq_ignore_ascii_case("SEEN")`) instead of inventing a second convention for + * the same wallet. + */ +object SeedBackupGate { + + /** The word that releases the block. The TUI's word, not a new one. */ + const val CONFIRM_WORD: String = "SEEN" + + /** + * True when [typed] releases the block. + * + * Trimmed and case-insensitive, so a soft keyboard's auto-capitalised `Seen` + * and a trailing space from a paste both count. Everything else — including + * the empty string — stays blocked. + */ + fun accepts(typed: String): Boolean = + typed.trim().equals(CONFIRM_WORD, ignoreCase = true) + + /** + * The flag right after a wallet is created or imported. + * + * A create always resets it: the wallet file is new, and the seed it was + * built from has never been read by anyone. + */ + fun afterWallet(origin: WalletKeyOrigin): Boolean = when (origin) { + WalletKeyOrigin.Created -> false + WalletKeyOrigin.Imported -> true + } + + /** + * The flag after one confirm step. + * + * Only a correct [typed] can flip it to `true`; a wrong word can never + * un-confirm a wallet that is already backed up. + */ + fun afterConfirm(typed: String, backedUp: Boolean): Boolean = + backedUp || accepts(typed) + + /** Done is dead until the word is right. */ + fun confirmEnabled(typed: String): Boolean = accepts(typed) + + /** + * The persistent strip is up while this install has an unconfirmed seed. + * + * [confirmed] is the stored flag, and it is nullable on purpose: + * + * - `false` — this install created a wallet and nobody has confirmed the + * seed. The wallet exists whether or not its balance reads, so the strip + * is up regardless. + * - `true` — confirmed, or imported. Nothing to say. + * - `null` — nothing stored: an install that predates this flag, or one + * that has never created or imported a wallet here. "We never asked" is + * not "the user wrote it down", but it is also not evidence that a wallet + * exists — so the strip waits for [walletReadable], the core's own proof + * that the child has a wallet open. + * + * Without that last distinction the strip would fire on every install that + * has configured a chain source but not yet created a wallet, which is + * exactly the state a first-run user is in. + */ + fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) { + true -> false + false -> true + null -> walletReadable + } + + /** + * The receive address and its QR are shown only while there is no unbacked + * seed to worry about. Receiving into an unbacked wallet is the one mistake + * this gate exists to prevent, so the address is hidden rather than merely + * warned about. + */ + fun receiveAddressVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = + !warningVisible(confirmed, walletReadable) + + /** + * The strip's words. One source: the screen renders this verbatim, so the + * reason the address disappeared travels with the hiding. + */ + const val WARNING: String = + "seed not backed up. write down the 25 words before you receive anything — " + + "a wallet whose seed was never written down cannot be recovered. " + + "the receive address stays hidden until you do." +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 4fbeeac..ec98015 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -76,6 +76,7 @@ fun WalletScreen( val childError by vm.walletChildError.collectAsStateWithLifecycle() val starting by vm.walletChildStarting.collectAsStateWithLifecycle() val chain by vm.chainSource.collectAsStateWithLifecycle() + val seedConfirmed by vm.walletSeedConfirmed.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // Resolved once per composition: the native library directory is fixed for // the life of the process. @@ -92,7 +93,11 @@ fun WalletScreen( var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } - var backupSeed by remember { mutableStateOf(null) } + // The seed currently on the blocking card: set by a successful create, or by + // "Back up seed" re-reading it from the wallet child. Null means no card. + // Never persisted and never logged — it is a spend key. + var pendingSeed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } var daemonText by remember { mutableStateOf("") } var daemonError by remember { mutableStateOf(null) } @@ -103,6 +108,26 @@ fun WalletScreen( runCatching { transfers = vm.walletRecentTransfers(25) } } + /** + * "Back up seed": re-read the open wallet's seed from the wallet child and + * put it on the blocking card. This is the only path to a seed that was + * created before this screen existed, so the failure is shown rather than + * swallowed — it is the difference between "the child is not running" and + * "there is nothing to recover". + */ + fun openSeedBackup() { + scope.launch { + error = null + vm.walletSeed().fold( + onSuccess = { seed -> + pendingSeed = seed + seedConfirm = "" + }, + onFailure = { error = it.message ?: it.toString() }, + ) + } + } + LaunchedEffect(Unit) { reload() vm.refreshChainSource() @@ -151,6 +176,46 @@ fun WalletScreen( .screenContentInsets() .verticalScroll(rememberScrollState()), ) { + // The blocking seed step. While a seed is on screen this card is the + // whole body: no Cancel, and Done stays dead until the confirm word + // is typed, so the one-shot seed cannot be dismissed unread. The + // app-bar Back still leaves the screen — that is the TUI's `Esc` — + // and it costs nothing now, because leaving no longer loses the + // seed: the wallet stays unbacked (strip up, receive address hidden) + // until "Back up seed" puts this card back on screen. + val seed = pendingSeed + if (seed != null) { + SeedBackupCard( + seed = seed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + // The gate owns the transition: a wrong word (which the + // disabled Done button already blocks) cannot confirm. + vm.confirmWalletSeed(seedConfirm) + pendingSeed = null + seedConfirm = "" + }, + ) + error?.let { ErrorLine(it) } + return@Column + } + + // The persistent unbacked strip, above everything else on the page. + // `walletReadable` is the core's own evidence that the child has a + // wallet open: `wallet_balance` returns exactly "off" for a chain + // source that was never configured, "err" for a configured one whose + // read failed (no wallet file open yet, or the child is down), and a + // real amount otherwise. The gate uses it only for an install that + // has never created a wallet here, so a first-run user who has + // configured a daemon but not yet created anything is not nagged + // about a seed they do not have. + val walletReadable = balance != null && balance != "off" && balance != "err" + val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) + if (unbacked) { + UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) + } + Card( modifier = Modifier .fillMaxWidth() @@ -173,7 +238,12 @@ fun WalletScreen( style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace, ) - val addr = address + // Hidden until the seed is confirmed written down: XMR into a + // wallet whose 25 words were never recorded is unrecoverable, + // so the address and its QR are gated, not just warned about. + val addr = address?.takeIf { + SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable) + } if (addr != null) { Spacer(Modifier.height(8.dp)) Text( @@ -333,7 +403,9 @@ fun WalletScreen( onCancel = { setup = null }, onCreated = { seed -> setup = null - backupSeed = seed + // The card is the whole body from here until SEEN. + pendingSeed = seed + seedConfirm = "" scope.launch { reload() } }, onImported = { @@ -374,36 +446,170 @@ fun WalletScreen( modifier = Modifier.weight(1f), ) { Text("Import") } } + // The recovery path for a wallet whose seed was missed. The + // strip above carries its own copy of this button while the + // seed is unconfirmed, so exactly one is ever on screen — + // and this copy is only offered once the child can actually + // read a wallet, which is the only state in which the seed + // read can succeed. + if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) { + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = { openSeedBackup() }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } + } } } - backupSeed?.let { seed -> - Text( - "write this seed down once. anyone with it can spend.", - style = MaterialTheme.typography.labelSmall, - modifier = Modifier.padding(horizontal = 12.dp), - ) - Text( - seed, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), - ) - TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + // While the strip is up the error belongs next to the button that + // caused it: this page is one long scroll and the daemon card sits + // between the strip and the bottom, so a failed `wallet_seed` read + // would otherwise land off-screen. + if (!unbacked) { + error?.let { ErrorLine(it) } } + } + } +} +/** The one error line every wallet action shares. */ +@Composable +private fun ErrorLine(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} + +/** + * The persistent unbacked strip: up at the top of the wallet screen from the + * moment a create succeeds until the seed is confirmed written down, and again + * on any install whose wallet predates the flag. + * + * It is not a toast and not a dialog — leaving the screen does not dismiss it, + * because the state it reports is the wallet's, not the screen's. Its button is + * the recovery path for a seed that was created before the user knew to look. + */ +@Composable +private fun UnbackedSeedCard( + error: String?, + onBackUpSeed: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp) + .testTag("wallet-seed-warning"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + SeedBackupGate.WARNING, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + Spacer(Modifier.height(8.dp)) + OutlinedButton( + onClick = onBackUpSeed, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } error?.let { + Spacer(Modifier.height(6.dp)) Text( it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) } } } } +/** + * The blocking seed step: the 25 words, and a Done that is dead until the + * confirm word is typed. + * + * There is no Cancel and no copy button. No Cancel, because a seed this card is + * showing for the first time has never been written down anywhere else, so + * dismissing it unread is how a wallet becomes unrecoverable. No copy button, + * because the Android clipboard is readable by every other app on the device + * (and by the clipboard history on Android 13+), which would hand the spend key + * to whoever asks for it next. + * + * The seed is a Kotlin `String`, so it cannot be wiped in place the way the + * TUI's `Zeroizing` is; dropping the reference is the strongest thing + * available here. That is another reason it is never written to disk. + */ +@Composable +private fun SeedBackupCard( + seed: String, + typed: String, + onTyped: (String) -> Unit, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + .testTag("wallet-seed-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Back up this seed", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + Text( + "These 25 words are the only way to recover this wallet, and anyone who " + + "reads them can spend it. Write them down now — this is the only copy.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Text( + seed, + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-words"), + ) + Spacer(Modifier.height(12.dp)) + Text( + "Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-confirm-input"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button( + onClick = onDone, + enabled = SeedBackupGate.confirmEnabled(typed), + modifier = Modifier.testTag("wallet-seed-confirm-done"), + ) { Text("Done") } + } + } + } +} + @Composable private fun TransferCard(t: TransferRow) { Card( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt new file mode 100644 index 0000000..9318753 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt @@ -0,0 +1,176 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The seed-backup gate's rules, on the JVM. + * + * These are the decisions the wallet screen renders from: whether the created + * seed card is still blocking, whether the persistent warning is up, and + * whether the receive address is on screen at all. Pure logic, so no + * Robolectric and no Compose test dependency — same shape as + * `WalletChildStatusTextTest` and `OutboxDetailTest`. + */ +class SeedBackupGateTest { + + /** A wallet the child can actually read: `wallet_balance` returned a value. */ + private val readable = true + + /** `wallet_balance` said "off" (no chain source) or "err" (nothing open). */ + private val notReadable = false + + // --- the confirm word is the TUI's word --------------------------------- + + @Test + fun the_confirm_word_is_the_tui_word() { + // `src/tui.rs` `WalletSetup::CreateSeed` compares against "SEEN". A + // second convention here would be a different gate than the TUI's. + assertEquals("SEEN", SeedBackupGate.CONFIRM_WORD) + } + + @Test + fun a_correct_word_releases_the_block_whatever_its_case_or_padding() { + assertTrue(SeedBackupGate.accepts("SEEN")) + // The TUI compares with `eq_ignore_ascii_case`. + assertTrue(SeedBackupGate.accepts("seen")) + assertTrue(SeedBackupGate.accepts("SeEn")) + // A soft keyboard auto-capitalises and a paste can carry whitespace. + assertTrue(SeedBackupGate.accepts(" seen ")) + } + + @Test + fun a_blank_or_wrong_word_stays_blocked() { + assertFalse(SeedBackupGate.accepts("")) + assertFalse(SeedBackupGate.accepts(" ")) + assertFalse(SeedBackupGate.accepts("SEE")) + // A prefix is not the word: the TUI only fires on the whole match. + assertFalse(SeedBackupGate.accepts("SEENN")) + assertFalse(SeedBackupGate.accepts("seen.")) + // The other word in this flow is the spend-authority one. + assertFalse(SeedBackupGate.accepts("SPEND")) + } + + @Test + fun done_is_dead_until_the_word_is_right() { + assertFalse(SeedBackupGate.confirmEnabled("")) + assertFalse(SeedBackupGate.confirmEnabled("SEENN")) + assertTrue(SeedBackupGate.confirmEnabled("SEEN")) + assertTrue(SeedBackupGate.confirmEnabled("seen")) + } + + // --- the state transitions ---------------------------------------------- + + @Test + fun a_create_starts_unbacked() { + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + @Test + fun an_import_is_backed_up_without_the_gate() { + // The user pasted the seed to get here, so there is nothing to confirm. + assertTrue(SeedBackupGate.afterWallet(WalletKeyOrigin.Imported)) + } + + @Test + fun a_successful_confirm_marks_the_wallet_backed_up() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.afterConfirm("SEEN", created)) + } + + @Test + fun a_wrong_word_leaves_an_unbacked_wallet_unbacked() { + assertFalse(SeedBackupGate.afterConfirm("", false)) + assertFalse(SeedBackupGate.afterConfirm("nope", false)) + } + + @Test + fun a_wrong_word_cannot_un_confirm_a_backed_up_wallet() { + // Done is disabled for a wrong word, but the flag must not be a way to + // walk a confirmed wallet back into the hidden-address state. + assertTrue(SeedBackupGate.afterConfirm("", true)) + assertTrue(SeedBackupGate.afterConfirm("SPEND", true)) + } + + @Test + fun a_new_create_resets_a_confirmed_wallet_to_unbacked() { + // Create -> confirm -> create again: the second wallet file has its own + // seed, and nobody has read it yet. + val first = + SeedBackupGate.afterConfirm("SEEN", SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + assertTrue(first) + assertFalse(SeedBackupGate.afterWallet(WalletKeyOrigin.Created)) + } + + // --- what the screen does with the flag --------------------------------- + + @Test + fun a_created_wallet_keeps_the_strip_up_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertTrue(SeedBackupGate.warningVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertFalse(SeedBackupGate.warningVisible(confirmed, readable)) + } + + @Test + fun an_imported_wallet_never_shows_the_strip() { + val backedUp = SeedBackupGate.afterWallet(WalletKeyOrigin.Imported) + assertFalse(SeedBackupGate.warningVisible(backedUp, readable)) + assertFalse(SeedBackupGate.warningVisible(backedUp, notReadable)) + } + + @Test + fun a_created_wallet_keeps_the_strip_up_even_before_its_balance_reads() { + // A create is proof a wallet exists, so a child that has not answered + // yet must not be read as "no wallet to warn about". + assertTrue(SeedBackupGate.warningVisible(false, notReadable)) + } + + @Test + fun the_receive_address_is_hidden_while_the_seed_is_unconfirmed() { + assertFalse(SeedBackupGate.receiveAddressVisible(false, readable)) + assertTrue(SeedBackupGate.receiveAddressVisible(true, readable)) + } + + @Test + fun a_created_wallet_hides_its_receive_address_until_the_word_is_typed() { + val created = SeedBackupGate.afterWallet(WalletKeyOrigin.Created) + assertFalse(SeedBackupGate.receiveAddressVisible(created, readable)) + + val confirmed = SeedBackupGate.afterConfirm("seen", created) + assertTrue(SeedBackupGate.receiveAddressVisible(confirmed, readable)) + } + + @Test + fun an_install_that_never_created_a_wallet_here_waits_for_a_readable_wallet() { + // `null` is "nothing stored": an install that predates the flag, or one + // that has only configured a chain source. `wallet_balance` returns + // "err" for a configured chain whose child has no wallet open, and a + // first-run user is in exactly that state — nagging them about a seed + // they do not have is the false positive this rule exists to prevent. + assertFalse(SeedBackupGate.warningVisible(null, notReadable)) + assertTrue(SeedBackupGate.receiveAddressVisible(null, notReadable)) + } + + @Test + fun an_unconfirmed_wallet_that_predates_the_flag_is_warned_about_once_it_reads() { + // The user this gate is for: they created a wallet on an older build, + // so nothing is stored, but the child can read the wallet. That is a + // real wallet whose seed nobody has confirmed. + assertTrue(SeedBackupGate.warningVisible(null, readable)) + assertFalse(SeedBackupGate.receiveAddressVisible(null, readable)) + } + + @Test + fun the_strip_says_why_the_address_is_gone() { + // The hiding is only fair if the strip names it; assert the strip is + // not empty and actually mentions the seed and the receive address. + val text = SeedBackupGate.WARNING + assertTrue(text.contains("seed")) + assertTrue(text.contains("receive address")) + assertTrue(text.contains("recovered")) + } +} From 467510f0969d0aaf3618d86f7ec6f1ad6bf22138 Mon Sep 17 00:00:00 2001 From: "rust-dev (hermes)" Date: Mon, 21 Sep 2026 10:21:48 -0400 Subject: [PATCH 23/94] store: a wallet catalogue in the encrypted db Wallets were only ever a file in $ONIONWIRE_HOME/wallet plus the single-row wallet_child config for the one the child is currently pointed at, so a created wallet was not remembered and a second create had nowhere to go. Add a 'wallets' table (id, name, identity_pubkey, onion_locator, wallet_filename, created_at) and CRUD on Store: create_wallet, get_wallet_by_id, list_wallets, delete_wallet. wallet_filename is UNIQUE so a second wallet cannot silently reuse the first one's file, and identity_pubkey is deliberately not unique (identity is the roster key, a wallet is a file; the locator may rotate or be empty). No new crate: the store is already rusqlite + SQLCipher with a raw PRAGMA key, and sqlx has no SQLCipher path, so a second pool would be a second unencrypted way in. Tests: 5 store cases in tests/store.rs (round-trip, coexistence across a reopen, duplicate filename, delete, blank label/filename) plus the at_rest upgrade case in src/store.rs. --- src/lib.rs | 4 +- src/store.rs | 184 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/store.rs | 123 +++++++++++++++++++++++++++++++++ 3 files changed, 309 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 226aa94..9e4c7c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,6 @@ pub mod wallet; pub mod wallet_child; pub use store::{ - Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store, - resolve_store_passphrase, + Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, SelfIdentity, Store, + WalletRecord, resolve_store_passphrase, }; diff --git a/src/store.rs b/src/store.rs index 676a1fa..9f5caae 100644 --- a/src/store.rs +++ b/src/store.rs @@ -177,6 +177,34 @@ pub struct PaymentWrite<'a> { pub verified: bool, } +/// Fields the caller supplies to add a wallet to the catalogue. `id` and +/// `created_at` are assigned by the store, never by the caller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewWallet { + /// Optional user label. Blank (or whitespace) is stored as SQL NULL. + pub name: Option, + /// The identity this wallet belongs to. Identity is the pubkey, so several + /// wallets may share one — this column is deliberately not unique. + pub identity_pubkey: [u8; 32], + /// The onion locator current at creation. A locator, not an identity: it + /// rotates (F4) and is allowed to be empty before the HS publishes. + pub onion_locator: String, + /// The wallet file name under the wallet dir. Unique: a second wallet must + /// get its own file rather than overwrite the first one's. + pub wallet_filename: String, +} + +/// One wallet in the catalogue: the row that makes a wallet survive a restart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WalletRecord { + pub id: i64, + pub name: Option, + pub identity_pubkey: [u8; 32], + pub onion_locator: String, + pub wallet_filename: String, + pub created_at: i64, +} + impl Store { pub fn open() -> Result { Self::open_at(&home_dir()?) @@ -275,6 +303,21 @@ impl Store { no_spend INTEGER NOT NULL, updated_at INTEGER NOT NULL ); + -- The wallet catalogue: one row per wallet file this install knows + -- about, so a created wallet is remembered across restarts (the + -- wallet child's own config only describes the one it is pointed at + -- right now). `identity_pubkey` is the owning identity and is NOT + -- unique — identity is the roster key, while a wallet is one file; + -- `onion_locator` is a locator and may be stale or empty. + CREATE TABLE IF NOT EXISTS wallets ( + id INTEGER PRIMARY KEY, + name TEXT, + identity_pubkey BLOB NOT NULL, + onion_locator TEXT NOT NULL DEFAULT '', + wallet_filename TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS wallets_by_created ON wallets (created_at, id); CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), @@ -418,6 +461,93 @@ impl Store { })) } + /// Add a wallet to the catalogue and return the stored row (id and + /// `created_at` assigned here). This is the only way a wallet becomes + /// remembered: the wallet file on disk is not a directory listing the app + /// scans. + /// + /// `wallet_filename` is unique. Creating a second wallet is not a rewrite of + /// the first — it must be handed its own file name, otherwise both wallets + /// would open the same file and the second would look like a failed create. + pub fn create_wallet(&self, w: &NewWallet) -> Result { + let filename = w.wallet_filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + let name = w.name.as_deref().map(str::trim).filter(|n| !n.is_empty()); + let taken: Option = self + .conn + .query_row( + "SELECT id FROM wallets WHERE wallet_filename = ?1", + params![filename], + |row| row.get(0), + ) + .optional()?; + if let Some(id) = taken { + return Err(Error(format!( + "wallet filename already in use: {filename} (wallet {id})" + ))); + } + let created_at = unix_now(); + self.conn.execute( + "INSERT INTO wallets (name, identity_pubkey, onion_locator, wallet_filename, created_at) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + name, + w.identity_pubkey.as_slice(), + w.onion_locator, + filename, + created_at + ], + )?; + Ok(WalletRecord { + id: self.conn.last_insert_rowid(), + name: name.map(str::to_string), + identity_pubkey: w.identity_pubkey, + onion_locator: w.onion_locator.clone(), + wallet_filename: filename.to_string(), + created_at, + }) + } + + /// One wallet by row id, or `None` when there is no such wallet. + pub fn get_wallet_by_id(&self, id: i64) -> Result> { + Ok(self + .conn + .query_row( + "SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at + FROM wallets WHERE id = ?1", + params![id], + wallet_row, + ) + .optional()?) + } + + /// Every known wallet, oldest first (row id breaks a `created_at` tie, so + /// the order a wallet-selection screen shows is stable across runs). + pub fn list_wallets(&self) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT id, name, identity_pubkey, onion_locator, wallet_filename, created_at + FROM wallets ORDER BY created_at, id", + )?; + let rows = stmt + .query_map([], wallet_row)? + .collect::, _>>()?; + Ok(rows) + } + + /// Forget a wallet. `true` when a row was removed, `false` when there was + /// nothing to remove (an unknown id is not an error). + /// + /// This drops the catalogue row only; the wallet file on disk and the + /// payments already recorded stay where they are. + pub fn delete_wallet(&self, id: i64) -> Result { + let removed = self + .conn + .execute("DELETE FROM wallets WHERE id = ?1", params![id])?; + Ok(removed > 0) + } + pub fn replace_identity_keys( &self, identity_sk: &[u8], @@ -1651,6 +1781,31 @@ fn unix_now() -> i64 { .unwrap_or(0) } +/// Read one `wallets` row. A pubkey column that is not exactly 32 bytes is a +/// corrupt row, not a value to guess at. +fn wallet_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let pubkey: Vec = row.get(2)?; + let len = pubkey.len(); + let identity_pubkey: [u8; 32] = pubkey.try_into().map_err(|_| { + rusqlite::Error::FromSqlConversionFailure( + 2, + rusqlite::types::Type::Blob, + Box::new(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("identity_pubkey is {len} bytes, expected 32"), + )), + ) + })?; + Ok(WalletRecord { + id: row.get(0)?, + name: row.get(1)?, + identity_pubkey, + onion_locator: row.get(3)?, + wallet_filename: row.get(4)?, + created_at: row.get(5)?, + }) +} + /// AAD for the sealed wallet-child row. Domain-separates it from message and /// outbox blobs that share the same store data key. const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1"; @@ -2308,4 +2463,33 @@ mod at_rest { } } } + + /// An install that predates the `wallets` table (the Android upgrade path) + /// gains it on the next open, and keeps everything else it had: the schema + /// is additive (`CREATE TABLE IF NOT EXISTS` on every open). + #[test] + fn a_store_without_the_wallets_table_gains_it_on_reopen() { + let dir = tempfile::tempdir().unwrap(); + let wallet = crate::store::NewWallet { + name: Some("First".into()), + identity_pubkey: [9u8; 32], + onion_locator: "w.onion".into(), + wallet_filename: "onionwire".into(), + }; + { + let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap(); + let row = store.create_wallet(&wallet).unwrap(); + assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row); + // Simulate a pre-`wallets` install. + store.conn.execute_batch("DROP TABLE wallets").unwrap(); + } + let store = Store::open_at_with_passphrase(dir.path(), "upgrade-pass").unwrap(); + assert!( + store.list_wallets().unwrap().is_empty(), + "the dropped table comes back empty, not missing" + ); + let row = store.create_wallet(&wallet).unwrap(); + assert_eq!(store.list_wallets().unwrap().len(), 1); + assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row); + } } diff --git a/tests/store.rs b/tests/store.rs index c9fee33..ddf7d5c 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -540,3 +540,126 @@ fn ratchet_state_survives_reopening_the_store() { assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob)); assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello"); } + +// ---- the wallet catalogue (`wallets`) -------------------------------------- +// +// Several wallet *files* live under one identity: the row here is what makes a +// wallet survive a restart, because the wallet child's own config only ever +// describes the one it is pointed at right now. + +fn new_wallet(filename: &str, name: Option<&str>) -> onionwire::NewWallet { + onionwire::NewWallet { + name: name.map(str::to_string), + identity_pubkey: pk(7), + onion_locator: "walletloc.onion".to_string(), + wallet_filename: filename.to_string(), + } +} + +#[test] +fn create_wallet_stores_every_field_and_reads_it_back() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + + let row = store + .create_wallet(&new_wallet("savings", Some("Savings"))) + .expect("create"); + assert!(row.id > 0, "id assigned: {row:?}"); + assert!(row.created_at > 0, "created_at stamped: {row:?}"); + assert_eq!(row.wallet_filename, "savings"); + assert_eq!(row.name.as_deref(), Some("Savings")); + assert_eq!(row.identity_pubkey, pk(7)); + assert_eq!(row.onion_locator, "walletloc.onion"); + + let got = store + .get_wallet_by_id(row.id) + .expect("get") + .expect("row exists"); + assert_eq!(got, row, "the stored row is what came back"); +} + +#[test] +fn multiple_wallets_coexist_and_survive_a_reopen() { + let dir = tempfile::tempdir().expect("tempdir"); + let (spending, savings) = { + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let spending = store + .create_wallet(&new_wallet("spending", Some("Spending"))) + .expect("spending"); + let savings = store + .create_wallet(&new_wallet("savings", None)) + .expect("savings"); + assert_ne!(spending.id, savings.id, "two wallets, two rows"); + (spending.id, savings.id) + }; + + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("reopen"); + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 2, "both wallets remembered: {rows:?}"); + assert_eq!(rows[0].id, spending, "creation order"); + assert_eq!(rows[1].id, savings); + assert_eq!( + rows[1].name, None, + "an unlabelled wallet round-trips as None" + ); + assert_eq!(rows[1].wallet_filename, "savings"); +} + +#[test] +fn a_second_wallet_cannot_reuse_a_wallet_filename() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let first = store + .create_wallet(&new_wallet("onionwire", None)) + .expect("first"); + + let err = store + .create_wallet(&new_wallet("onionwire", Some("Clash"))) + .expect_err("a duplicate filename must not overwrite the first wallet"); + assert!( + err.to_string().contains("onionwire"), + "names the file: {err}" + ); + + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 1, "the rejected insert left one row: {rows:?}"); + assert_eq!(rows[0], first, "the first wallet is untouched"); +} + +#[test] +fn delete_wallet_removes_only_that_row() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + let a = store.create_wallet(&new_wallet("a", None)).expect("a"); + let b = store.create_wallet(&new_wallet("b", None)).expect("b"); + + assert!(store.delete_wallet(a.id).expect("delete"), "row was there"); + assert_eq!(store.get_wallet_by_id(a.id).expect("get"), None); + let rows = store.list_wallets().expect("list"); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].id, b.id); + + assert!( + !store + .delete_wallet(9999) + .expect("unknown id is not an error"), + "nothing to delete reports false" + ); +} + +#[test] +fn a_wallet_without_a_label_or_locator_stores_nulls_and_rejects_a_blank_filename() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "wallet-pass").expect("open"); + + let mut blank = new_wallet("blank", Some(" ")); + blank.onion_locator = String::new(); + let row = store.create_wallet(&blank).expect("blank label"); + assert_eq!(row.name, None, "a whitespace label is no label"); + assert_eq!(row.onion_locator, "", "a locator may be empty pre-publish"); + + let err = store + .create_wallet(&new_wallet(" ", None)) + .expect_err("an empty filename cannot name a wallet file"); + assert!(err.to_string().contains("filename"), "{err}"); +} From 99a4ab640e91841aedf4dcb88bc326e91252daa5 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 24/94] tui: wallet selection screen (F6 -> w) with create as the last row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screen::WalletSelect: a table of saved wallets — name, identity prefix, locator prefix, creation day — the selected row's full identity and locator under it, and a `+ create new wallet` row as the last item. j/k or arrows move, Enter takes the choice, Esc back. Empty, failed and in-flight reads each get their own copy; a wallet with a NULL label, no published locator or no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank. Presentation only. Rows are plain display data (WalletRow) built by the caller; the render path never reads the store, and the selection is by row index because two records may share an identity key. Loading a chosen record into the session is the wallet-store integration step, so the F6 `w` entry opens the screen on its unavailable state until that accessor lands, and the create row works today either way. Evidence: tests/tui_select.rs (16 tests) drives the real draw path through TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one focus marker, a cell-width line budget from 20 to 200 columns, the window disclosure with the create row always visible, hostile labels (ESC/BEL/C1/ bidi/newline/tab) and the crate-local UTC date formatter. --- docs/TUI.md | 23 +- src/tui.rs | 599 +++++++++++++++++++++++++++++++++++++++++++- tests/tui_select.rs | 475 +++++++++++++++++++++++++++++++++++ 3 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 tests/tui_select.rs diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index a72d071..7e7b9eb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + let footer = status_footer_phased( + f.area().width, + &self.me_fp, + &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + budget.max(1).min(total) + }; + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &state) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + 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 wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\n{screen}" + ); + } + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +} From 0043fa0b34827de84f7fe446eccac97c709b04eb Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:57:55 -0400 Subject: [PATCH 25/94] node: remember a created wallet in the store's catalogue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A wallet created in-app was never remembered: `Node::wallet_create` called the RPC and returned the seed, and the wallet file name was the one hardcoded `wallet::DEFAULT_WALLET_FILENAME` ("onionwire"). A second create reused that name, so the RPC refused it (or opened the first wallet's file) and no row was ever written — the "cannot create a new wallet, and nothing survives a restart" report. Creation and import now go through the catalogue (t_64c9ba3c's `Store::{create_wallet,list_wallets}`): - each create/import gets its own file name, `onionwire-` for the first `n` the catalogue does not hold, so several wallets coexist; - the stored row (id, identity, locator, file, created_at) is returned: `Node::wallet_create` -> `CreatedWallet` (row + the one-time seed, with a redacting `Debug`), `Node::wallet_restore` -> `WalletRecord`; - `Node::list_wallets` reads the catalogue without dialing; - the child config is re-pointed at the new file (read-modify-write, so the sealed RPC creds survive) — a row the child never opens would still be a broken wallet. The SDK keeps its UniFFI signature (`create_wallet -> String` seed, `import_wallet -> ()`), so no Kotlin change: it unwraps `.seed`. TDD: 5 new `src/node.rs` cases (row + list, two wallets + reopen, import, wallet-off empty list, child re-pointed) over a loopback wallet-RPC mock. `cargo test --locked` exit 0, `cargo clippy --locked --all-targets -- -D warnings` clean, and the same two commands are clean in `crates/onionwire-sdk`. --- crates/onionwire-sdk/src/lib.rs | 13 +- src/node.rs | 258 ++++++++++++++++++++++++++++++-- src/tui.rs | 6 +- 3 files changed, 262 insertions(+), 15 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 154b602..4040664 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -587,20 +587,27 @@ impl Wire { /// Create a new spend-capable wallet. Returns the 25-word seed once so the /// UI can show a backup screen. The user does not paste a key on this path. /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + /// + /// The core also records the new wallet in its catalogue (`Node::wallet_create` + /// returns the stored row); the seed is what this surface carries. pub async fn create_wallet(&self, password: String) -> WResult { - self.node()? + Ok(self + .node()? .wallet_create(&password) .await - .map_err(WireError::new) + .map_err(WireError::new)? + .seed) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. + /// that takes a user-supplied secret. Like a create, the core records the + /// imported wallet in its catalogue. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { self.node()? .wallet_restore(&password, &seed) .await .map_err(WireError::new) + .map(|_| ()) } /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for diff --git a/src/node.rs b/src/node.rs index fcc8015..120696b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -28,7 +28,9 @@ use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; -use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; +use crate::store::{ + Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; @@ -80,6 +82,29 @@ impl Drop for WorkerHandle { } } +/// A wallet just created on the wallet RPC and recorded in the store's +/// catalogue: the row is what makes it survive a restart, and the seed is the +/// one-time backup the UI shows before the wallet is used. The caller owns +/// wiping `seed` (the TUI moves it straight into a `Zeroizing`). +pub struct CreatedWallet { + /// The stored catalogue row, with the id and `created_at` the store + /// assigned. `wallet_filename` is the file this wallet lives in. + pub record: WalletRecord, + /// The 25-word seed, returned once by the create path. + pub seed: String, +} + +/// Hand-written so a stray `{:?}` cannot print the seed: the record is the +/// wallet, the mnemonic is the money. +impl std::fmt::Debug for CreatedWallet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CreatedWallet") + .field("record", &self.record) + .field("seed", &"") + .finish() + } +} + pub struct Node { home: PathBuf, store: Arc>, @@ -1167,27 +1192,106 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } - /// Create a new spend-capable wallet. Returns the seed once for backup. - /// The user never pastes a key on this path. - pub async fn wallet_create(&self, password: &str) -> Result { + /// Create a new spend-capable wallet and record it in the catalogue. The + /// user never pastes a key on this path. + /// + /// The wallet file gets its own name ([`Self::next_wallet_filename`]): + /// `wallet_filename` is UNIQUE, so a second create that reused the old + /// hardcoded name would open the first wallet's file — or be refused by the + /// RPC outright, which is the "cannot create a new wallet" failure. The + /// stored row is what makes the wallet survive a restart; the wallet dir is + /// not scanned. + pub async fn wallet_create(&self, password: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + let filename = self.next_wallet_filename()?; + let seed = w + .create_wallet(&filename, password) .await - .map_err(|e| e.to_string()) + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} created but the child is not pointed at it: {e}") + })?; + Ok(CreatedWallet { record, seed }) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. - pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + /// that takes a user-supplied secret — and, like a create, it is remembered + /// in the catalogue under its own file name. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + let filename = self.next_wallet_filename()?; + w.restore_wallet(&filename, password, seed) .await + .map_err(|e| e.to_string())?; + let record = self + .record_wallet(&filename) + .map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?; + self.point_child_at(&filename).map_err(|e| { + format!("wallet {filename} imported but the child is not pointed at it: {e}") + })?; + Ok(record) + } + + /// Every wallet this install remembers, oldest first. A store read: it must + /// work with no wallet RPC configured, and it never dials. + pub fn list_wallets(&self) -> Result, String> { + self.store + .lock() + .map_err(|e| e.to_string())? + .list_wallets() + .map_err(|e| e.to_string()) + } + + /// The file name a wallet created now should live in. `wallet_filename` is + /// UNIQUE and the catalogue is the only directory the app has, so this is + /// `-` for the first `n` the catalogue does not already hold. + fn next_wallet_filename(&self) -> Result { + let taken = self.list_wallets()?; + for n in 1.. { + let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); + if !taken.iter().any(|w| w.wallet_filename == candidate) { + return Ok(candidate); + } + } + unreachable!("an unused wallet file name always exists") + } + + /// Point the wallet child at a wallet file. A read-modify-write of the + /// sealed record, so the generated RPC creds and every other setting are + /// kept. A running child is not restarted: the change applies on the next + /// `start_wallet_child`. + fn point_child_at(&self, filename: &str) -> Result<(), String> { + let mut cfg = self.wallet_child_config(); + if cfg.wallet_filename == filename { + return Ok(()); + } + cfg.wallet_filename = filename.to_string(); + self.set_wallet_child_config(&cfg) + } + + /// Add a freshly created wallet file to the catalogue: this node's identity + /// (several wallets may share one) and the onion it is reachable at right + /// now (a locator, and empty until the HS publishes). + fn record_wallet(&self, filename: &str) -> Result { + let new = NewWallet { + name: None, + identity_pubkey: self.identity_pk(), + onion_locator: self.onion(), + wallet_filename: filename.to_string(), + }; + self.store + .lock() + .map_err(|e| e.to_string())? + .create_wallet(&new) .map_err(|e| e.to_string()) } @@ -2964,4 +3068,140 @@ mod tests { } assert!(gone, "shutdown must not leave the wallet child behind"); } + + /// A loopback wallet RPC for the setup path: a per-socket digest challenge, + /// then the method's own result. `create_wallet` and + /// `restore_deterministic_wallet` both answer `{}`; only the seed backup + /// query has a body worth reading. + async fn mock_wallet_setup() -> Wallet { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("query_key") { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + + /// The reported bug: a created wallet was never remembered, because the + /// creation path never reached the store's catalogue. + #[tokio::test] + async fn creating_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let created = node.wallet_create("hunter2").await.expect("create wallet"); + + assert!(created.record.id > 0, "the store assigns the row id"); + assert_eq!(created.record.wallet_filename, "onionwire-1"); + assert_eq!(created.record.identity_pubkey, node.identity_pk()); + assert_eq!(created.record.onion_locator, "test.onion"); + assert_eq!(created.seed, "lumber tacit lemon ivory risk"); + assert_eq!( + node.list_wallets().expect("list wallets"), + vec![created.record], + "the wallet just created is the catalogue" + ); + } + + /// The second half of the bug: a second create reused the one hardcoded file + /// name, so the RPC refused it — and nothing was remembered across a restart. + #[tokio::test] + async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + + let first = node.wallet_create("p1").await.expect("first wallet"); + let second = node.wallet_create("p1").await.expect("second wallet"); + + assert_ne!( + first.record.wallet_filename, second.record.wallet_filename, + "a second wallet must not reuse the first one's file" + ); + drop(node); + let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store"); + assert_eq!( + reopened.list_wallets().expect("list wallets").len(), + 2, + "both wallets are remembered across a restart" + ); + } + + /// Import is a creation path too: it takes the same hardcoded name today. + #[tokio::test] + async fn importing_a_wallet_records_it_in_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let imported = node + .wallet_restore("hunter2", "lumber tacit lemon ivory risk") + .await + .expect("restore wallet"); + + assert_eq!(imported.wallet_filename, "onionwire-1"); + assert_eq!( + node.list_wallets().expect("list wallets").len(), + 1, + "an imported wallet is remembered too" + ); + } + + /// A catalogue row the child never opens is still a broken wallet: the + /// child's stored config defaults to `onionwire`, which no created wallet + /// uses any more. + #[tokio::test] + async fn creating_a_wallet_points_the_child_at_its_own_file() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + mock_wallet_setup().await, + ); + + let first = node.wallet_create("p1").await.expect("first wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + first.record.wallet_filename, + "the child must open the wallet that was just created" + ); + + let second = node.wallet_create("p1").await.expect("second wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + second.record.wallet_filename + ); + assert_eq!( + node.list_wallets().expect("list wallets")[0].wallet_filename, + first.record.wallet_filename, + "the first wallet keeps its own file" + ); + } + + /// The catalogue is a store fact, not a wallet-RPC fact: listing must work + /// with no wallet configured, and creating must still refuse without one. + #[tokio::test] + async fn a_wallet_off_install_lists_an_empty_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert!(node.list_wallets().expect("list wallets").is_empty()); + let err = node + .wallet_create("hunter2") + .await + .expect_err("no wallet RPC"); + assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); + } } diff --git a/src/tui.rs b/src/tui.rs index a72d071..b14994c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2263,9 +2263,9 @@ impl App { return Ok(()); } match self.rt.block_on(self.node.wallet_create(pass.as_str())) { - Ok(seed) => { + Ok(created) => { self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { - seed: Zeroizing::new(seed), + seed: Zeroizing::new(created.seed), typed: String::new(), }); } @@ -2338,7 +2338,7 @@ impl App { .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); seed.zeroize(); match result { - Ok(()) => { + Ok(_) => { self.status_note = Some("wallet imported".into()); return self.open_wallet(); } From d96de1d7f0f01427f1a43cb0e0e5f0e8a327b82c Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 10:41:53 -0400 Subject: [PATCH 26/94] tui: wallet selection screen (F6 -> w) with create as the last row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screen::WalletSelect: a table of saved wallets — name, identity prefix, locator prefix, creation day — the selected row's full identity and locator under it, and a `+ create new wallet` row as the last item. j/k or arrows move, Enter takes the choice, Esc back. Empty, failed and in-flight reads each get their own copy; a wallet with a NULL label, no published locator or no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank. Presentation only. Rows are plain display data (WalletRow) built by the caller; the render path never reads the store, and the selection is by row index because two records may share an identity key. Loading a chosen record into the session is the wallet-store integration step, so the F6 `w` entry opens the screen on its unavailable state until that accessor lands, and the create row works today either way. Evidence: tests/tui_select.rs (16 tests) drives the real draw path through TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one focus marker, a cell-width line budget from 20 to 200 columns, the window disclosure with the create row always visible, hostile labels (ESC/BEL/C1/ bidi/newline/tab) and the crate-local UTC date formatter. (cherry picked from commit 99a4ab640e91841aedf4dcb88bc326e91252daa5) --- docs/TUI.md | 23 +- src/tui.rs | 599 +++++++++++++++++++++++++++++++++++++++++++- tests/tui_select.rs | 475 +++++++++++++++++++++++++++++++++++ 3 files changed, 1095 insertions(+), 2 deletions(-) create mode 100644 tests/tui_select.rs diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index b14994c..ca4d672 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + let footer = status_footer_phased( + f.area().width, + &self.me_fp, + &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + budget.max(1).min(total) + }; + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &state) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + 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 wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\n{screen}" + ); + } + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +} From 89867248485a3f25a5a560ba456afc394c5014ac Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 21 Sep 2026 11:43:07 -0400 Subject: [PATCH 27/94] tui: read the wallet list from the store and load the chosen wallet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The selection screen shipped as presentation only: `F6 w` opened its unavailable state, the rows were never read, and Enter on a wallet said switching was not wired up. The catalogue, the create path and the screen all existed; nothing joined them. - `App::open_wallet_select` builds its rows from `Node::list_wallets` at the moment the screen opens (never cached from startup), and a failed read is the screen's own error state rather than "no saved wallets". - `App::choose_wallet` resolves `WalletChoice::Open(index)` against the catalogue as it is now — the index is a position, and two saved wallets may share an identity key — then loads it. `+ create new wallet` still starts the existing create flow. - `Node::open_wallet(filename)` is the load: it refuses a file the catalogue does not hold, re-points the sealed wallet-child record with a read-modify-write (the generated RPC creds survive), and restarts a running child onto the new file. An idle child takes the change on its next start. - `App::new` starts on the selection screen when the catalogue is non-empty and on the create flow when it is empty, so a restart lands on the wallets it remembers and a first run has no dead empty list. - The stored identity/locator stay catalogue columns: a locator rotates (F4) and identity is the roster key the node already holds, so the live header keeps reading them from the node. - `SELECT_UNAVAILABLE` is gone with the state it described; docs/TUI.md now describes the wired behaviour. Tests (both new): `Node::open_wallet` over an offline node — the chosen file, the creds kept across the read-modify-write, the choice surviving a reopen, and a non-catalogue file refused; and the app path in src/tui.rs over a real store-backed node — start screen both ways, catalogue mapping, row index over a shared identity, the create row, and a wallet recorded after startup appearing the next time the list opens. --- docs/TUI.md | 17 +++- src/node.rs | 166 +++++++++++++++++++++++++++++- src/tui.rs | 285 +++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 439 insertions(+), 29 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 7b64afd..a763944 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -150,9 +150,24 @@ failed is named on the screen — that is a different state from `no saved walle yet`, and the two never share copy. Rows are plain display data (`WalletRow`), built by the caller from -`Store::list_wallets`; the render path never reads the store. Selection is by +`Node::list_wallets`; the render path never reads the store. Selection is by row index, not by identity key (two records may share one). +The list is read when the screen opens — from the start screen and from +`F6` `w` — so a wallet created or imported in this session is offered the next +time the screen opens, with no restart. Enter on a wallet row re-points the +app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`, +a read-modify-write of the sealed record, so the generated RPC creds survive); +a running child is restarted onto the new file, and an idle one picks the +change up on its next start. + +**Start screen.** An install with at least one saved wallet opens on +`WalletSelect`; a fresh install (empty catalogue) opens on the create flow +(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The +stored identity and locator are catalogue columns, not session state: a locator +rotates (`F4`) and identity is the roster key the node already holds, so the +live header keeps reading them from the node. + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. diff --git a/src/node.rs b/src/node.rs index 120696b..fef5b8f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1251,6 +1251,37 @@ impl Node { .map_err(|e| e.to_string()) } + /// Switch the wallet child to a catalogue wallet's file. + /// + /// The catalogue is the only directory this app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. A + /// running child is restarted onto the new file; an idle one is only + /// re-pointed, and the change applies on the next `start_wallet_child`. The + /// write is a read-modify-write, so the generated RPC creds survive. + pub fn open_wallet(&self, filename: &str) -> Result<(), String> { + if !self + .list_wallets()? + .iter() + .any(|w| w.wallet_filename == filename) + { + return Err(format!("no saved wallet in {filename}")); + } + let running = self + .wallet_child + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .is_some_and(|child| child.wallet_rpc_running()); + if running { + self.stop_wallet_child()?; + } + self.point_child_at(filename)?; + if running { + self.start_wallet_child()?; + } + Ok(()) + } + /// The file name a wallet created now should live in. `wallet_filename` is /// UNIQUE and the catalogue is the only directory the app has, so this is /// `-` for the first `n` the catalogue does not already hold. @@ -1990,7 +2021,42 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } #[cfg(test)] -mod tests { +/// A catalogue row written straight into the store, for tests that need a saved +/// wallet without a wallet RPC. +pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) { + let identity_pubkey: [u8; 32] = store + .self_identity() + .expect("self identity") + .identity_pk + .try_into() + .expect("32-byte identity"); + store + .create_wallet(&NewWallet { + name: (!label.trim().is_empty()).then(|| label.to_string()), + identity_pubkey, + onion_locator: format!("{file}.onion"), + wallet_filename: file.to_string(), + }) + .expect("create wallet"); +} + +/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own +/// tests: `App` reads the catalogue, and the only public `Node` constructor +/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored +/// as `NULL`, like a wallet created without one. +#[cfg(test)] +pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc { + { + let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store"); + for (file, label) in wallets { + test_record_wallet(&store, file, label); + } + } + Arc::new(tests::offline_node(home, Arc::new(tests::NoDial))) +} + +#[cfg(test)] +pub(crate) mod tests { use super::*; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; @@ -2002,11 +2068,11 @@ mod tests { use tokio::io::AsyncRead as TokioRead; use tokio::io::AsyncWrite as TokioWrite; - const PASS: &str = "node-ratchet-test-pass"; + pub(crate) const PASS: &str = "node-ratchet-test-pass"; /// Never dials: every send queues, which is what leaves the encoded frame /// visible on the outbox row. - struct NoDial; + pub(crate) struct NoDial; impl crate::outbox::Deliverer for NoDial { fn deliver<'a>( @@ -2063,7 +2129,7 @@ mod tests { /// are the only public constructors and both bootstrap Tor and publish an /// onion service, so this is the only way to drive the shipped send and /// receive path offline. - fn offline_node(home: &Path, deliverer: Arc) -> Node { + pub(crate) fn offline_node(home: &Path, deliverer: Arc) -> Node { offline_node_with_wallet(home, deliverer, Wallet::disabled()) } @@ -3204,4 +3270,96 @@ mod tests { .expect_err("no wallet RPC"); assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); } + + /// Switching wallets is a catalogue read plus a child re-point: the chosen + /// row's file name is what the child opens, and the generated RPC creds in + /// the same sealed record survive the read-modify-write. + #[tokio::test] + async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node(&home, Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child( + r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#, + ) + .unwrap(); + for file in ["onionwire", "onionwire-1"] { + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: "abcd.onion".into(), + wallet_filename: file.to_string(), + }) + .unwrap(); + } + } + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet that was chosen" + ); + let sealed = node + .store + .lock() + .unwrap() + .load_wallet_child() + .unwrap() + .expect("sealed record"); + assert!( + sealed.contains("ow-secret-pass-xyz"), + "the re-point dropped the generated creds: {sealed}" + ); + assert!( + sealed.contains("\"user\":\"owuser\""), + "the re-point dropped the generated creds: {sealed}" + ); + + // A restart re-reads the record, so the choice is remembered. + drop(node); + let restarted = offline_node(&home, Arc::new(NoDial)); + assert_eq!( + restarted.wallet_child_config().wallet_filename, + "onionwire-1", + "the chosen wallet must survive a restart" + ); + } + + /// The catalogue is the only directory the app has, so a file it does not + /// hold is refused instead of pointing a spend-capable child at a path. + #[tokio::test] + async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + { + let store = node.store.lock().unwrap(); + store + .save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#) + .unwrap(); + store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [7u8; 32], + onion_locator: String::new(), + wallet_filename: "onionwire".to_string(), + }) + .unwrap(); + } + + let err = node + .open_wallet("onionwire-9") + .expect_err("not a saved wallet"); + assert!(err.contains("no saved wallet"), "{err}"); + assert_eq!( + node.wallet_child_config().wallet_filename, + "onionwire", + "a refused switch must leave the child where it was" + ); + } } diff --git a/src/tui.rs b/src/tui.rs index ca4d672..8251985 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -17,7 +17,9 @@ use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; +use crate::store::{ + Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord, +}; use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1348,12 +1350,27 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; + // First run is the create flow, not an empty list to pick from; an + // install that already has wallets starts on the list, so a restart + // lands on the wallets it remembers. A catalogue that cannot be read is + // the screen's own error state (the create row still works there). + let screen = match node.list_wallets() { + Ok(rows) if rows.is_empty() => Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }), + Ok(rows) => Screen::WalletSelect { + state: WalletSelectState::from_rows(wallet_rows(rows)), + }, + Err(e) => Screen::WalletSelect { + state: WalletSelectState::error(e), + }, + }; Ok(Self { me_fp: to_hex(&node.identity_pk()), me_onion: node.onion(), node, rt, - screen: Screen::Main, + screen, friends, selected: 0, alert: None, @@ -2073,14 +2090,14 @@ impl App { } /// Enter on the wallet selection screen: `create new wallet` starts the - /// existing creation flow, and a wallet row is a choice the app has to - /// resolve. + /// existing creation flow, and a wallet row switches the wallet child to + /// that row's file. /// - /// Resolving a row into the session is the wallet-store integration step: - /// the record's identity and locator have to be read back and loaded, and - /// `Node` has no wallet-record accessor yet. Until that lands the choice is - /// reported instead of silently dropped — an Enter that does nothing is - /// worse than one that says what is missing. + /// `WalletChoice::Open` carries a **row index**, so it is resolved against + /// the catalogue as it is now, not against anything the screen cached: two + /// saved wallets may share an identity key, and only the position (then the + /// row's own `wallet_filename`) names one. A list that changed under the + /// screen is reported rather than silently opening the wrong wallet. fn choose_wallet(&mut self) -> Result<(), String> { let Screen::WalletSelect { state } = &self.screen else { return Ok(()); @@ -2091,24 +2108,52 @@ impl App { typed: String::new(), }); } - WalletChoice::Open(_) => { - self.status_note = Some("wallet switching is not wired up yet".into()); + WalletChoice::Open(index) => { + let opened = self.select_wallet(index); + match opened { + Ok(label) => { + self.status_note = Some(format!("opened wallet {label}")); + self.screen = Screen::Main; + } + Err(e) => self.alert = Some(e), + } } } Ok(()) } - /// F6 `w`: the wallet selection screen. + /// Load the catalogue row at `index` into the session: point the wallet + /// child at that wallet's file (and restart it if it was running), then read + /// the list back so the screen never shows a stale catalogue. /// - /// The rows come from the wallet store; reading them is the integration - /// card's step (`Store::list_wallets`), and the render path never touches - /// the store. Until that accessor exists the screen opens on its - /// unavailable state, which says so — the `create new wallet` row at the - /// bottom works either way. + /// The stored identity and locator are not pushed into the session: they are + /// the identity/locator *at creation* (a locator rotates, and the identity is + /// the roster key this node already holds), so the live values keep coming + /// from the node. Returns the label to report. + fn select_wallet(&mut self, index: usize) -> Result { + let row = self + .node + .list_wallets()? + .into_iter() + .nth(index) + .ok_or_else(|| "the saved wallets changed — reopen the list".to_string())?; + self.node.open_wallet(&row.wallet_filename)?; + Ok(wallet_label(&row)) + } + + /// F6 `w`: the wallet selection screen, read from the catalogue now. + /// + /// The rows come from the wallet store ([`Node::list_wallets`]) at the + /// moment the screen opens — never cached from startup — so a wallet created + /// in this session shows up on the next look. A read that fails is the + /// screen's own error state, which is not the same word as "no saved + /// wallets": the `create new wallet` row stays reachable either way. fn open_wallet_select(&mut self) { - self.screen = Screen::WalletSelect { - state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + let state = match self.node.list_wallets() { + Ok(records) => WalletSelectState::from_rows(wallet_rows(records)), + Err(e) => WalletSelectState::error(e), }; + self.screen = Screen::WalletSelect { state }; } /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the @@ -4556,6 +4601,37 @@ impl WalletSelectState { } } +/// Catalogue rows, display-ready and in store order (oldest first). +/// +/// The mapping is the one documented on [`WalletRow`]: a `NULL` label is the +/// empty string (the screen says `(unlabelled)`), the identity column is +/// `[u8; 32]` and is hex-encoded here, the locator passes through (empty until +/// the HS publishes), and `created_at` is unix seconds. `wallet_filename` is +/// not carried: it is not on the screen. The rows stay index-aligned with the +/// catalogue, which is how [`WalletChoice::Open`] resolves. +pub fn wallet_rows(records: Vec) -> Vec { + records + .into_iter() + .map(|r| WalletRow { + name: r.name.unwrap_or_default(), + identity_pubkey: to_hex(&r.identity_pubkey), + onion_locator: r.onion_locator, + created_at: r.created_at, + }) + .collect() +} + +/// What to call a saved wallet in a status line: its label, or the file when it +/// has none (a blank label is stored as `NULL`). +fn wallet_label(r: &WalletRecord) -> String { + r.name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or(&r.wallet_filename) + .to_string() +} + /// Marker column in cells: `> ` when focused, ` ` otherwise. const WALLET_MARK_W: usize = 2; /// Identity column in cells: an 8-character prefix plus the ellipsis — 11 @@ -4923,11 +4999,6 @@ pub fn wallet_select_footer_hint() -> &'static str { const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; -/// The sub-line the screen prints when the wallet store has not been wired into -/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is -/// not the same state as "no saved wallets". -pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; - /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. @@ -5333,3 +5404,169 @@ mod passphrase_buffer_tests { ); } } + +/// The wallet selection screen against a real store-backed node: the rows come +/// from the catalogue, a choice loads that wallet, and the start screen depends +/// on whether any wallet is remembered. +#[cfg(test)] +mod wallet_store_tests { + use super::*; + use crate::node::{test_node_with_wallets, test_record_wallet}; + + const PASS: &str = crate::node::tests::PASS; + + /// A real node (no Tor) over a seeded catalogue, plus the runtime the app + /// holds a handle to. `wallets` is `(file name, label)`; a blank label is a + /// wallet with no name, like one created from the app. + fn app(home: &std::path::Path, wallets: &[(&str, &str)]) -> (App, tokio::runtime::Runtime) { + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + // The offline node's unbootstrapped Arti client needs a runtime context + // to be built (the same reason the node tests are `#[tokio::test]`). + let _guard = rt.enter(); + let node = test_node_with_wallets(home, wallets); + let app = App::new(node, rt.handle().clone()).expect("app"); + (app, rt) + } + + fn select_rows(app: &App) -> Vec { + let Screen::WalletSelect { state } = &app.screen else { + panic!("not on the wallet selection screen"); + }; + state + .rows + .iter() + .map(|r| r.name.clone()) + .collect::>() + } + + /// Nothing remembered means there is no list to choose from: the first run + /// goes straight to the existing creation flow. + #[test] + fn an_install_with_no_wallet_starts_on_the_create_flow() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app(&dir.path().join("home"), &[]); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + ), + "a first run must start on the create flow" + ); + } + + /// A restart lands on the wallets it remembers, and each row carries the + /// catalogue's own fields (label, hex identity, locator, creation time). + #[test] + fn an_install_with_wallets_starts_on_the_list_read_from_the_catalogue() { + let dir = tempfile::tempdir().unwrap(); + let (app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "")], + ); + let Screen::WalletSelect { state } = &app.screen else { + panic!("saved wallets must start on the selection screen"); + }; + assert!(state.error.is_none(), "{:?}", state.error); + assert!(!state.reading); + assert_eq!( + state.rows.len(), + 2, + "two saved wallets, plus the create row" + ); + assert_eq!(state.rows[0].name, "lance"); + assert_eq!(state.rows[1].name, ""); + assert_eq!( + state.rows[0].identity_pubkey, + to_hex(&app.node.identity_pk()) + ); + assert_eq!(state.rows[0].identity_pubkey.len(), 64, "hex, not bytes"); + assert_eq!(state.rows[0].onion_locator, "onionwire.onion"); + assert!(state.rows[0].created_at > 0, "creation time is real"); + assert_eq!(state.choice(), WalletChoice::Open(0)); + } + + /// The choice is a row index into a list whose records may share an + /// identity key, so the second row must open the second wallet's file. + #[test] + fn choosing_a_row_opens_that_wallets_file_not_the_first_identity_match() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app( + &dir.path().join("home"), + &[("onionwire", "lance"), ("onionwire-1", "cold")], + ); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Open(1)); + } + + app.choose_wallet().expect("choosing a saved wallet"); + + assert!( + matches!(app.screen, Screen::Main), + "a loaded wallet returns to the main view" + ); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1", + "the child must open the wallet under the marker" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet cold")); + } + + /// The last item is not a wallet: Enter on it starts the creation flow. + #[test] + fn the_create_row_starts_the_creation_flow() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]); + { + let Screen::WalletSelect { state } = &mut app.screen else { + panic!("not on the selection screen"); + }; + state.select_next(); + assert_eq!(state.choice(), WalletChoice::Create); + } + app.choose_wallet().expect("choosing create"); + assert!(matches!( + app.screen, + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) + )); + } + + /// The list is read when the screen opens, never cached from startup, so a + /// wallet recorded in this session is offered the next time — that is what + /// makes a create show up without a restart. + #[test] + fn a_wallet_recorded_after_startup_appears_the_next_time_the_list_opens() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let (mut app, _rt) = app(&home, &[]); + assert!(matches!(app.screen, Screen::WalletSetup(_))); + assert!( + app.node.list_wallets().expect("list wallets").is_empty(), + "nothing to list yet" + ); + + { + // The create path writes exactly this row (a `wallets` entry keyed + // on the file it just made). + let store = + crate::store::Store::open_at_with_passphrase(&home, PASS).expect("open store"); + test_record_wallet(&store, "onionwire-1", "fresh"); + } + + // F6 `w`. + app.open_wallet_select(); + assert_eq!(select_rows(&app), vec!["fresh".to_string()]); + + // And switching to it works from the screen the user is looking at. + app.choose_wallet().expect("open the new wallet"); + assert_eq!( + app.node.wallet_child_config().wallet_filename, + "onionwire-1" + ); + assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh")); + } +} From 5f19a56be34dc22115ceed123a6396c1420e3ecd Mon Sep 17 00:00:00 2001 From: sirius Date: Tue, 22 Sep 2026 00:25:33 -0400 Subject: [PATCH 28/94] sdk: expose the wallet catalogue, the open wallet's keys, and the self profile The Android wallet/profile screens had nothing to call: the core could list wallets, switch the child onto one, read its keys and read/write the self profile, but none of it crossed UniFFI. Core: - Wallet::keys() -> WalletKeys { view_key, spend_key: Option }: two query_key calls against the file the RPC has open. A view-only wallet's -29 is spend_key: None, not an error. WalletKeys' Debug redacts both halves. - Node::wallet_keys() mirrors wallet_create/wallet_seed; refuses locally when no wallet is configured. - Node::active_wallet_filename() -> Option: the file the child is pointed at, None until wallet-child settings exist, so a client can mark the open row. SDK (UniFFI): - records WalletRow / WalletKeys / SelfProfile, and Wire::{wallets, open_wallet, active_wallet_filename, wallet_keys, self_profile, set_self_profile, push_self_profile}. - The rule the clients must express is in the docs: the seed and the private keys come from the OPEN wallet, so there is deliberately no accessor that reads another saved wallet's secrets without opening it. docs/WALLET.md (catalogue + 'secrets belong to the open wallet'), docs/THREAT_MODEL.md (the new on-demand-display exposure surface) and the SDK README are updated in the same commit. --- crates/onionwire-sdk/README.md | 18 ++ crates/onionwire-sdk/src/lib.rs | 385 +++++++++++++++++++++++++++++++- docs/THREAT_MODEL.md | 26 +++ docs/WALLET.md | 32 +++ src/node.rs | 124 ++++++++++ src/wallet.rs | 60 +++++ tests/wallet.rs | 142 ++++++++++++ 7 files changed, 784 insertions(+), 3 deletions(-) diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 1cd7124..9635337 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -104,6 +104,24 @@ val msgs: List = wire.messages(friend.pubkeyHex) // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends + +// 6. Saved wallets, and which one is open. +val wallets: List = wire.wallets() // a store read: never dials +val active: String? = wire.activeWalletFilename() // the open file, or null +val open = wallets.firstOrNull { it.walletFilename == active } +wire.openWallet("onionwire-2") // may restart a running wallet child; a name + // outside the catalogue is refused +val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys +// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer). +// That is not an error. The seed (`walletSeed()`) and these keys always belong +// to `activeWalletFilename()`: to show another wallet's backup, open it first. +// Both are spend secrets — show them from an explicit user action only, never +// log them, never persist them. + +// 7. Your own profile (nickname, bio, Monero address). +val me: SelfProfile = wire.selfProfile() +wire.setSelfProfile("ada", "on the wire", "4AdUnd...") // validated on write +wire.pushSelfProfile(friend.pubkeyHex) // signed `prf`, one-shot and fail-closed ``` All peer references are lowercase hex strings so nothing Rust-shaped leaks into diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index d17f7f3..11ca267 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -28,14 +28,14 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::Message; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::{ChainNetwork, ChainSource}; +use onionwire::wallet::{ChainNetwork, ChainSource, WalletKeys as CoreWalletKeys}; use onionwire::wallet_child::{ChildConfig, WalletChildState}; +use onionwire::{FriendProfile, Message, WalletRecord}; uniffi::setup_scaffolding!(); @@ -540,6 +540,128 @@ impl Wire { .collect()) } + // ---- Wallet catalogue, the open wallet, and its secrets ---- + + /// Every wallet this install remembers, oldest first. + /// + /// A store read: it never dials the wallet RPC or the chain, so it works + /// with the wallet child stopped or never configured. "No wallets" is an + /// empty list, never an error. `WireError.Stopped` after `shutdown`; + /// `WireError.Failed` only when the store itself cannot be read. + /// + /// The Kotlin binding is `Wire.wallets()`. + pub async fn wallets(&self) -> WResult> { + let rows = self.node()?.list_wallets().map_err(WireError::new)?; + Ok(rows.iter().map(wallet_row).collect()) + } + + /// Point the wallet child at a catalogue wallet's file: afterwards the + /// balance, transfers, seed and keys this surface reports are that + /// wallet's. + /// + /// **It may restart a running wallet child.** A live child is stopped and + /// started again onto the new file, which is what makes the change take + /// effect immediately — and why this call is slow (a `.onion` source waits + /// for its SOCKS listener, an in-process chain daemon for its RPC). An idle + /// child is only re-pointed: nothing is spawned, and the change applies at + /// the next [`Wire::start_wallet_child`]. + /// + /// A `filename` the catalogue does not hold is **refused**: the catalogue is + /// the only directory this app keeps wallets in, and a spend-capable child + /// is never pointed at a path a caller invented. Get the name from + /// [`Wire::wallets`]. `WireError.Stopped` after `shutdown`. + pub async fn open_wallet(&self, filename: String) -> WResult<()> { + self.node()?.open_wallet(&filename).map_err(WireError::new) + } + + /// The wallet file the child is currently pointed at, or `None` when no + /// wallet-child settings were ever stored (a fresh install has no open + /// wallet). + /// + /// A picker marks the open row with + /// `row.wallet_filename == active`; every other row means "open it first to + /// see its seed or keys", because the seed and the private keys always come + /// from the file the child has **open**. The value can name a file that is + /// not in the catalogue (an install whose wallet predates it) — that is "no + /// open wallet row", not an error. + /// + /// It never dials and never spawns. `WireError.Stopped` after `shutdown`. + pub async fn active_wallet_filename(&self) -> WResult> { + self.node()? + .active_wallet_filename() + .map_err(WireError::new) + } + + /// The private view key and spend key of the wallet file the child has + /// **open** (`query_key`). This is a dial to the wallet child's loopback + /// RPC, so call it from an explicit user action, not from a refresh loop. + /// + /// `spend_key` is `None` for a view-only wallet: the RPC answers `-29` + /// ("Cannot retrieve spend key") and that is the wallet's own answer, not a + /// failure, so it is not surfaced as one. `WireError.Failed` when no wallet + /// is configured or the child is not answering; `WireError.Stopped` after + /// `shutdown`. + /// + /// The values are spend secrets: show them, never log them, never persist + /// them. `WalletKeys`'s `Debug` redacts both. + pub async fn wallet_keys(&self) -> WResult { + let keys = self.node()?.wallet_keys().await.map_err(WireError::new)?; + Ok(keys_record(keys)) + } + + // ---- This identity's own profile ---- + + /// This identity's own profile (nickname, bio, Monero address) as stored. + /// + /// A store read: never dials. It is the local copy — what friends show for + /// you only changes once [`Wire::push_self_profile`] reaches them. + /// `WireError.Stopped` after `shutdown`. + pub async fn self_profile(&self) -> WResult { + let p = self.node()?.self_profile().map_err(WireError::new)?; + Ok(self_profile_record(&p)) + } + + /// Replace this identity's own profile. + /// + /// Validated before it is written, so a rejected edit leaves the stored + /// profile untouched: a nickname over 64 characters, a bio over 512, or a + /// non-empty address that fails the Monero checksum (the same check `/pay` + /// and `/tip` use) is refused with `WireError.Failed`. An empty address is + /// allowed. + /// + /// It does not tell anyone. Friends still see the previous profile until + /// [`Wire::push_self_profile`] is sent to them. `WireError.Stopped` after + /// `shutdown`. + pub async fn set_self_profile( + &self, + display_name: String, + bio: String, + xmr_addr: String, + ) -> WResult<()> { + self.node()? + .set_self_profile(&display_name, &bio, &xmr_addr) + .map_err(WireError::new) + } + + /// Send this identity's signed profile to one friend, so the nickname and + /// address they show for you are current. + /// + /// One-shot and fail closed: a peer whose onion is down means this fails + /// and **nothing is queued** — no retry, no outbox row (profiles are not + /// chat). Send it again when they are reachable. + /// + /// `pubkey_hex` is the friend's identity pubkey, the encoding + /// [`FriendInfo::pubkey_hex`] carries; an unparseable hex is + /// `WireError.Failed` before anything is dialled. `WireError.Stopped` after + /// `shutdown`. + pub async fn push_self_profile(&self, pubkey_hex: String) -> WResult<()> { + let pk = unhex(&pubkey_hex)?; + self.node()? + .push_self_profile(&pk) + .await + .map_err(WireError::new) + } + /// Send an invoice to a friend: sign an invoice for my receive address and send /// the frame one-shot. Peer onion down → this fails; invoices are not queued. /// @@ -1018,6 +1140,39 @@ fn outbox_row(entry: &OutboxEntry) -> OutboxRow { } } +/// `WalletRecord` → the picker row. `wallet_filename` is the file name only +/// (never a path): the core resolves it inside `$ONIONWIRE_HOME/wallet`. +fn wallet_row(w: &WalletRecord) -> WalletRow { + WalletRow { + id: w.id, + name: w.name.clone(), + wallet_filename: w.wallet_filename.clone(), + onion_locator: w.onion_locator.clone(), + identity_pubkey_hex: hex(&w.identity_pubkey), + created_at: w.created_at, + } +} + +/// The core's key record → the SDK's, with the secrets carried across verbatim +/// (this is a display path; nothing here logs or stores them). +fn keys_record(keys: CoreWalletKeys) -> WalletKeys { + WalletKeys { + view_key: keys.view_key, + spend_key: keys.spend_key, + } +} + +/// `FriendProfile` → the profile screen's record. `updated_at` is deliberately +/// not carried: the SDK surface has no use for it, and a client that wants +/// "did my push land" compares the fields it set. +fn self_profile_record(p: &FriendProfile) -> SelfProfile { + SelfProfile { + display_name: p.display_name.clone(), + bio: p.bio.clone(), + xmr_addr: p.xmr_addr.clone(), + } +} + /// A Monero transfer row for the wallet screen. /// /// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the @@ -1029,6 +1184,71 @@ pub struct TransferRow { pub address: String, } +/// One row of the saved-wallet catalogue, for the wallet picker. +/// +/// Mirrors the core's `WalletRecord`, with the identity pubkey as hex. `id` is +/// the `wallets.id` row id, `wallet_filename` is the file inside +/// `$ONIONWIRE_HOME/wallet` and is what [`Wire::open_wallet`] takes, and the +/// rows come back oldest-first so a list is stable between calls. +/// +/// `identity_pubkey_hex` is the identity this wallet belongs to and is **not** +/// unique; `onion_locator` is a locator that may be empty or stale. Never key a +/// selection, or the roster, on the locator. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletRow { + pub id: i64, + /// The user's label for this wallet. `None` when it was never named, and + /// never an empty string. + pub name: Option, + pub wallet_filename: String, + pub onion_locator: String, + /// The owning identity's ed25519 pubkey, hex — the same encoding + /// [`FriendInfo::pubkey_hex`] carries. + pub identity_pubkey_hex: String, + /// Unix seconds, assigned by the store when the row was created. + pub created_at: i64, +} + +/// The private keys of the **open** wallet file, for a backup screen. +/// +/// Both values are spend secrets: show them only from an explicit user action, +/// never log them, and never persist them. `Debug` is hand-written to redact +/// them so a stray `{:?}` cannot leak a key into a log. +#[derive(Clone, PartialEq, Eq, uniffi::Record)] +pub struct WalletKeys { + /// The open wallet file's private view key. + pub view_key: String, + /// The open wallet file's private spend key, or `None` for a view-only + /// wallet. `None` is the wallet's own answer — it has no spend key — and + /// not a failure. + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + +/// This identity's own profile, as the profile screen reads and edits it. +/// +/// It is what friends are shown for this identity once it has been pushed; +/// nothing here is secret (an empty `xmr_addr` is allowed, a non-empty one is +/// validated). +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SelfProfile { + pub display_name: String, + pub bio: String, + /// This identity's Monero address. May be empty. When non-empty the core + /// refuses to store it unless it passes the same address check `/pay` and + /// `/tip` use. + pub xmr_addr: String, +} + /// Where the app-owned wallet child gets its chain from. Mirrors the core's /// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] @@ -1341,8 +1561,8 @@ mod tests { //! handle, which is what a shut-down node must guarantee. A `Wire` with no //! node is exactly the state `shutdown()` leaves behind. use super::*; - use onionwire::Store; use onionwire::outbox::OutboxStatus; + use onionwire::{NewWallet, Store}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2105,4 +2325,163 @@ mod tests { let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } + + // ---- wallet catalogue, the open wallet, its keys, and the self profile ---- + + #[test] + fn wallets_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallets()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn open_wallet_on_a_stopped_handle_is_stopped_error() { + let err = + block_on(stopped_wire().open_wallet("onionwire".to_string())).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn active_wallet_filename_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().active_wallet_filename()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn wallet_keys_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_keys()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().self_profile()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn set_self_profile_on_a_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().set_self_profile( + "nick".to_string(), + String::new(), + String::new(), + )) + .expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_on_a_stopped_handle_is_stopped_error() { + // Valid 32-byte hex, so the hex parse cannot be the thing that failed: + // the handle is. + let err = + block_on(stopped_wire().push_self_profile("11".repeat(32))).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn push_self_profile_rejects_a_pubkey_that_is_not_hex_before_any_work() { + let err = + block_on(stopped_wire().push_self_profile("nope".to_string())).expect_err("must fail"); + // The hex check runs first, so this is `Failed`, not `Stopped`. + assert!(matches!(err, WireError::Failed { .. }), "got {err:?}"); + } + + /// The picker row is the catalogue row, row for row: same id, same file + /// name, same label, and the pubkey as hex. A Kotlin picker keys on + /// `wallet_filename` for [`Wire::open_wallet`], so it has to be exact. + #[test] + fn wallet_rows_carry_the_catalogue_verbatim() { + let home = temp_home(); + let store = Store::open_at_with_passphrase(&home, "wallet-catalogue-pass").unwrap(); + let named = store + .create_wallet(&NewWallet { + name: Some("savings".to_string()), + identity_pubkey: [0xab; 32], + onion_locator: "peer.onion".to_string(), + wallet_filename: "onionwire-1".to_string(), + }) + .unwrap(); + let unnamed = store + .create_wallet(&NewWallet { + name: None, + identity_pubkey: [0xab; 32], + onion_locator: String::new(), + wallet_filename: "onionwire-2".to_string(), + }) + .unwrap(); + + let rows: Vec = store + .list_wallets() + .unwrap() + .iter() + .map(wallet_row) + .collect(); + + assert_eq!(rows.len(), 2, "both wallets are listed"); + assert_eq!(rows[0].id, named.id); + assert_eq!(rows[0].name.as_deref(), Some("savings")); + assert_eq!(rows[0].wallet_filename, "onionwire-1"); + assert_eq!(rows[0].onion_locator, "peer.onion"); + assert_eq!(rows[0].identity_pubkey_hex, "ab".repeat(32)); + assert_eq!(rows[0].created_at, named.created_at); + // A wallet created without a label is `None`, never an empty string. + assert_eq!(rows[1].id, unnamed.id); + assert_eq!(rows[1].name, None); + // The locator is a locator: it may be empty, and it is not an identity. + assert_eq!(rows[1].onion_locator, ""); + + std::fs::remove_dir_all(&home).ok(); + } + + #[test] + fn keys_mapping_carries_both_halves_and_the_view_only_answer() { + let both = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: Some("spend-material".to_string()), + }); + assert_eq!(both.view_key, "view-material"); + assert_eq!(both.spend_key.as_deref(), Some("spend-material")); + + let view_only = keys_record(CoreWalletKeys { + view_key: "view-material".to_string(), + spend_key: None, + }); + assert_eq!(view_only.view_key, "view-material"); + assert_eq!(view_only.spend_key, None); + } + + /// These two are spend secrets: the record the Kotlin side receives must not + /// print them through `Debug`, or a `{:?}` in a crash log leaks a key. + #[test] + fn wallet_keys_debug_never_prints_a_private_key() { + let keys = keys_record(CoreWalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }); + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + } + + #[test] + fn self_profile_mapping_carries_the_three_editable_fields() { + let core = FriendProfile { + display_name: "nick".to_string(), + bio: "bio".to_string(), + xmr_addr: String::new(), + updated_at: 1_700_000_000, + }; + let got = self_profile_record(&core); + assert_eq!(got.display_name, "nick"); + assert_eq!(got.bio, "bio"); + assert_eq!(got.xmr_addr, ""); + } } diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9781368..b3a7a44 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -249,6 +249,32 @@ the app does not pick a public remote node for them. Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs spend, and RPC credentials: [WALLET.md](WALLET.md). +## The recovery phrase and the private keys are displayable on demand + +Both clients can show the **open** wallet's recovery phrase (`query_key +mnemonic`) and its private view and spend keys (`query_key view_key` / +`spend_key`), from an explicit user action. That is new exposure the threat model +did not previously enumerate: the phone screen — and the Linux TUI window — is +now one of the places a spending secret can be read from. + +- The values come from the wallet file the child has **open**. There is no path + that reads another saved wallet's secret without opening it first, and none + that reads a wallet file directly: the RPC is the only source. +- They are never logged, never written to the store or any other file, and never + placed in an error string; the records that carry them (`WalletKeys`) redact + themselves under `Debug`. They exist in process memory only while a screen + shows them. +- They are shown only from an explicit user action, never on a refresh path. +- What this does **not** stop: a shoulder-surfer, a screen recorder, a + screenshot, or a malicious app with screen-capture permission. Whoever reads + the screen gets the keys; a view-only wallet leaks only the view key + (`spend_key` is `None`), but a spend-capable one leaks everything the file can + spend. +- The spend-authority warning above still applies and is now easier to reach: + the seed that makes a wallet spend-capable can be photographed off the device. + Treat any screen that shows a seed or a private key the way you treat the + wallet file itself. + ## Backup file is the identity `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. diff --git a/docs/WALLET.md b/docs/WALLET.md index 054c48c..8b0255a 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -203,6 +203,36 @@ launches the node *and* the wallet child. `wallet_status()` carries Monero ships **no Android binaries**. Any vendored blob's provenance doc must say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`. +### The wallet catalogue, and which wallet is open + +`wallets()` lists every wallet this install remembers (oldest first), each row +carrying the `wallet_filename` the child opens, its label, the owning identity +pubkey as hex, and the locator. `active_wallet_filename()` returns the file the +child is **currently pointed at** (or `None` on a fresh install), so a picker can +mark the open row. `open_wallet(filename)` switches to a catalogue row: a +running child is stopped and restarted onto the new file, an idle one is only +re-pointed (the change applies at the next `start_wallet_child`), and a file the +catalogue does not hold is refused — the catalogue is the only directory this app +keeps wallets in. + +## Secrets belong to the open wallet + +The seed (`wallet_seed()`, `query_key mnemonic`) and the private keys +(`wallet_keys()` → `query_key view_key` / `query_key spend_key`) are answered by +the wallet file the child has **open**, so they always belong to the row +`active_wallet_filename()` names. There is deliberately no accessor that reads +another saved wallet's seed or keys without opening it: show a backups screen, +then `open_wallet(...)` the row — the UI must say *which* wallet it is showing. +`WalletKeys.spend_key` is `None` for a view-only wallet (the RPC's `-29`), which +is an answer, not an error. + +Both values are spend secrets. They are displayable on demand in the TUI and in +the Android app, are never logged, never written to the store or to disk, and +never put into an error string (the core's `WalletKeys` `Debug` redacts them). +The exposure this creates is enumerated in +[THREAT_MODEL.md](THREAT_MODEL.md), "The recovery phrase and the private keys +are displayable on demand". + ## Create vs import `/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** @@ -263,6 +293,8 @@ Restore from a height at or before the first incoming transaction. | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | | OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | +| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works | +| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key | `ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with: diff --git a/src/node.rs b/src/node.rs index bbd0d24..923d3ca 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1232,6 +1232,43 @@ impl Node { w.mnemonic().await.map_err(|e| e.to_string()) } + /// The private view key and, when the wallet can spend, the private spend + /// key of the wallet file the child currently has **open** (`query_key`). + /// + /// Secrets therefore belong to the open wallet: viewing another saved + /// wallet's keys means opening it first. A view-only wallet answers `None` + /// for `spend_key` instead of an error (the RPC's `-29`). An unconfigured + /// wallet is refused locally, before any dial; a configured but unreachable + /// child surfaces the RPC error. + /// + /// The values are spend secrets: never log them and never persist them. + pub async fn wallet_keys(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.keys().await.map_err(|e| e.to_string()) + } + + /// The wallet file the child is currently pointed at, so a client can mark + /// the open row in the catalogue. `None` when no wallet-child settings have + /// ever been stored (a fresh install): a receive-only install has no open + /// wallet file, and the child never points at one until a wallet is created, + /// imported, or opened. + /// + /// The name is what the child would spawn with, not a message from the + /// running process, and it may not match a catalogue row (an install whose + /// wallet predates the catalogue). Match it against + /// [`Node::list_wallets`] rather than assuming it is there. + pub fn active_wallet_filename(&self) -> Result, String> { + let store = self.store.lock().map_err(|e| e.to_string())?; + let Some(raw) = store.load_wallet_child().map_err(|e| e.to_string())? else { + return Ok(None); + }; + let cfg = ChildConfig::from_record(&raw).map_err(|e| e.to_string())?; + Ok(cfg.map(|cfg| cfg.wallet_filename)) + } + /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret — and, like a create, it is remembered /// in the catalogue under its own file name. @@ -3374,4 +3411,91 @@ pub(crate) mod tests { "a refused switch must leave the child where it was" ); } + + /// The active wallet is a child-config fact, not a catalogue fact: a row in + /// the catalogue that the child was never pointed at is not open, and a + /// fresh install has no open wallet at all. + #[tokio::test] + async fn active_wallet_filename_is_none_until_the_child_has_been_pointed() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a fresh install has no open wallet file" + ); + + // A record written before the settings were persisted (creds, no + // source block) is not an open wallet either. + node.store + .lock() + .unwrap() + .save_wallet_child(r#"{"user":"owuser","pass":"ow-pass"}"#) + .unwrap(); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a creds-only record does not name a wallet file" + ); + + test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + assert_eq!( + node.active_wallet_filename().expect("read"), + None, + "a catalogue row alone does not open the wallet" + ); + + node.open_wallet("onionwire-1") + .expect("open a saved wallet"); + assert_eq!( + node.active_wallet_filename().expect("read").as_deref(), + Some("onionwire-1"), + "the open wallet is the file the child was pointed at" + ); + } + + /// No wallet, no dial: the refusal is the configured-guard copy, not a + /// connection error, and it happens before any socket is opened. + #[tokio::test] + async fn wallet_keys_without_a_wallet_refuses_without_dialing() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let err = node.wallet_keys().await.expect_err("no wallet configured"); + assert_eq!(err, wallet::NOT_CONFIGURED_MSG); + } + + /// The node-level path a Kotlin caller takes: two `query_key` calls against + /// the open wallet's RPC, with the view-only `-29` arriving as + /// `spend_key: None` rather than as an error. + #[tokio::test] + async fn wallet_keys_of_a_view_only_wallet_returns_no_spend_key() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { + if req.contains("spend_key") { + r#"{"jsonrpc":"2.0","id":"0","error":{"code":-29,"message":"The wallet is watch-only. Cannot retrieve spend key."}}"# + .to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"key":"aabbccdd"}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"), + ); + + let keys = node.wallet_keys().await.expect("keys"); + assert_eq!(keys.view_key, "aabbccdd"); + assert_eq!( + keys.spend_key, None, + "the RPC's -29 is the wallet's answer, not a failure" + ); + } } diff --git a/src/wallet.rs b/src/wallet.rs index e4437da..787ee90 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -349,6 +349,27 @@ impl std::fmt::Debug for Endpoint { } } +/// The private keys of the wallet file the RPC currently has open. +/// +/// `view_key` is the private view key; `spend_key` is the private spend key and +/// is `None` — not an error — for a view-only wallet, which has no spend key to +/// hand out. Both are secrets: never log them, never persist them, and never put +/// them in an error string. +pub struct WalletKeys { + pub view_key: String, + pub spend_key: Option, +} + +/// Hand-written so a stray `{:?}` cannot print a private key. +impl std::fmt::Debug for WalletKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalletKeys") + .field("view_key", &"") + .field("spend_key", &self.spend_key.as_ref().map(|_| "")) + .finish() + } +} + #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, @@ -807,6 +828,45 @@ impl Wallet { json_str(&v, "key") } + /// The wallet file's private keys, as the RPC reports them: `query_key` + /// `view_key` and `query_key` `spend_key`. + /// + /// Both come from the wallet file the child currently has **open** — this is + /// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC + /// only ever answers for its open file. + /// + /// A view-only wallet has no spend key: its `query_key spend_key` answers + /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to + /// `spend_key: None` rather than an error, matching the `-29` view-only + /// detection the transfer probe already uses. Refuses locally, before any + /// dial, when the wallet is not configured. + /// + /// The two values are spend secrets: never log them, never store them, never + /// put them in an error string. [`WalletKeys`]'s `Debug` redacts both. + pub async fn keys(&self) -> Result { + if !self.configured() { + return Err(Error(NOT_CONFIGURED_MSG.into())); + } + let v = self + .rpc("query_key", serde_json::json!({"key_type": "view_key"})) + .await?; + let view_key = json_str(&v, "key")?; + // Asked second and separately: on a view-only wallet this is the call + // that carries the `-29`, and `None` is the honest answer there. + let spend_key = match self + .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) + .await + { + Ok(v) => Some(json_str(&v, "key")?), + Err(e) if e.to_string() == VIEW_ONLY_MSG => None, + Err(e) => return Err(e), + }; + Ok(WalletKeys { + view_key, + spend_key, + }) + } + /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index 9c8649b..0724779 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,5 +1,6 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use ed25519_dalek::SigningKey; @@ -893,6 +894,147 @@ fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); } +/// The two private keys come from the open wallet file, in two `query_key` +/// calls: `view_key` first (always available), `spend_key` second (absent on a +/// view-only wallet). A wallet that can spend answers both. +#[tokio::test] +async fn keys_returns_the_view_and_spend_keys_of_the_open_wallet() { + const VIEW: &str = "0f0e0d0c0b0a09080706050403020100"; + const SPEND: &str = "0102030405060708090a0b0c0d0e0f10"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_result(&format!(r#"{{"key":"{SPEND}"}}"#)), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port).keys().await.expect("keys"); + assert_eq!(keys.view_key, VIEW); + assert_eq!(keys.spend_key.as_deref(), Some(SPEND)); + assert_eq!(calls.load(Ordering::SeqCst), 2, "one call per key"); +} + +/// A view-only wallet has no spend key: the RPC answers `-29` +/// (`WALLET_RPC_ERROR_CODE_WATCH_ONLY`). That is the wallet's answer, so it must +/// come back as `spend_key: None` — not as an error, which would leave the +/// backup screen unable to show the view key. +#[tokio::test] +async fn keys_of_a_view_only_wallet_have_no_spend_key_and_no_error() { + const VIEW: &str = "aabbccddeeff00112233445566778899"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |method: &str| match method { + "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { + 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), + _ => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), + }, + other => panic!("keys must only ask query_key, saw {other}"), + }), + None, + None, + )); + let keys = recording_wallet(port) + .keys() + .await + .expect("a view-only wallet"); + assert_eq!(keys.view_key, VIEW); + assert_eq!( + keys.spend_key, None, + "view-only means no spend key to hand out" + ); +} + +/// Any *other* RPC failure is a real failure: a view-only `-29` is the only +/// error `keys` turns into `None`. +#[tokio::test] +async fn keys_surfaces_an_rpc_error_that_is_not_the_view_only_answer() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let calls = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&calls); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(move |_: &str| { + if seen.fetch_add(1, Ordering::SeqCst) == 0 { + rpc_result(r#"{"key":"aabbccdd"}"#) + } else { + rpc_error(-1, "wallet file is not open") + } + }), + None, + None, + )); + let err = recording_wallet(port) + .keys() + .await + .expect_err("a spend-key error that is not -29 must not read as view-only"); + let msg = err.to_string(); + assert!(msg.contains("wallet file is not open"), "got {err}"); + assert!(!msg.contains("secret"), "password leaked: {err}"); +} + +/// No endpoint, no dial: the refusal is the configured-guard copy the rest of +/// the wallet uses, not a connection error. +#[test] +fn keys_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { + let w = Wallet::disabled(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.keys()) + .unwrap_err(); + assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); +} + +/// The keys are spend secrets. `WalletKeys` is the value the whole path carries, +/// so its `Debug` must not print either key — a stray `{:?}` in a log is how a +/// key leaks. +#[test] +fn wallet_keys_debug_never_prints_a_private_key() { + let keys = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: Some("SPENDKEYMATERIAL".to_string()), + }; + let printed = format!("{keys:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + !printed.contains("SPENDKEYMATERIAL"), + "spend key leaked: {printed}" + ); + assert!(printed.contains("redacted"), "got {printed}"); + + let only_view = wallet::WalletKeys { + view_key: "VIEWKEYMATERIAL".to_string(), + spend_key: None, + }; + let printed = format!("{only_view:?}"); + assert!( + !printed.contains("VIEWKEYMATERIAL"), + "view key leaked: {printed}" + ); + assert!( + printed.contains("None"), + "a view-only wallet must read as None: {printed}" + ); +} + /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { From b6447f76d6c7a2ae49f629338bd09b539c8432a9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 00:28:39 -0400 Subject: [PATCH 29/94] android: collapse the roster identity block into a dropdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The identity card's full fingerprint wraps to several lines on a phone and pushes the friend list off the first screen. Collapse it: one line by default (label + `shortId(fingerprint)` + chevron), the full fingerprint and the full onion behind a tap, in the order they already had. The `sdk …` line and `keepAliveNote` stay outside the disclosure — the keep-alive denial is the only place that note appears, so hanging it off a collapsed block would hide it. `shortId` is a pure top-level function (`head … tail`, unchanged when the value is no longer than the abbreviation, empty stays empty) so the collapsed line is a slice of the value shown expanded, not a parallel encoding. The expand state is `rememberSaveable`: a rotation keeps what the user chose, and nothing about it belongs in the store. RosterIdTest covers the abbreviation on the JVM (7 cases: the 64-hex fingerprint, the head/tail boundary, custom head/tail, shorter-than-input, empty, single-char ellipsis). --- .../siriusdevops/onionwire/ui/RosterScreen.kt | 53 ++++++++++-- .../siriusdevops/onionwire/ui/RosterIdTest.kt | 84 +++++++++++++++++++ 2 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index ed641dc..b3903cd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Card @@ -27,6 +28,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -51,6 +53,10 @@ fun RosterScreen( onOpenWallet: () -> Unit, ) { var confirmWipe by remember { mutableStateOf(false) } + // Closed by default; `rememberSaveable` so a rotation keeps whatever the + // user chose instead of snapping back to (or away from) the summary. + // Nothing about this is worth persisting to the store. + var identityExpanded by rememberSaveable { mutableStateOf(false) } Scaffold( // The content root below consumes systemBars ∪ ime itself (see @@ -79,11 +85,33 @@ fun RosterScreen( ), ) { Column(Modifier.padding(12.dp)) { - Label("YOU (stable forever)") - Mono(fingerprint) - Spacer(Modifier.height(10.dp)) - Label("ONION (locator — rotates)") - Mono(onion) + // The disclosure header. Collapsed, this one line *is* the + // identity block: the label, the abbreviated fingerprint, + // and a chevron saying there is more behind it. + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { identityExpanded = !identityExpanded }, + verticalAlignment = Alignment.CenterVertically, + ) { + Label("YOU (stable forever)") + if (!identityExpanded) { + Spacer(Modifier.width(8.dp)) + Mono(shortId(fingerprint)) + } + Spacer(Modifier.weight(1f)) + Text( + if (identityExpanded) "▾" else "▸", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (identityExpanded) { + Mono(fingerprint) + Spacer(Modifier.height(10.dp)) + Label("ONION (locator — rotates)") + Mono(onion) + } Spacer(Modifier.height(10.dp)) Text( "sdk $sdkVersion · identity = ed25519 pubkey", @@ -194,6 +222,21 @@ private fun FriendRow(f: FriendInfo, onClick: () -> Unit) { } } +/** + * The compact stand-in for a long identity string: `head` characters, an + * ellipsis, then `tail` characters. Pure, so the roster's collapsed line and + * its unit test agree on what "short" means. + * + * A string no longer than the abbreviation is returned unchanged — the + * abbreviation must never grow a value, and a short value must never come back + * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/ + * `takeLast` cannot split a surrogate pair here. + */ +fun shortId(id: String, head: Int = 6, tail: Int = 4): String { + if (id.length < head + tail + 1) return id + return id.take(head) + "…" + id.takeLast(tail) +} + @Composable fun Label(text: String) { Text( diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt new file mode 100644 index 0000000..d890fb3 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterIdTest.kt @@ -0,0 +1,84 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * `shortId`, the roster's collapsed identity line, on the JVM. + * + * The collapsed card shows the fingerprint through this function, and the + * expanded one shows the raw value; the two must never disagree about what the + * fingerprint *is*, so the abbreviation has to be a pure slice of the input + * with nothing invented. Pure logic, no Robolectric — same shape as + * `SeedBackupGateTest` and `WalletChildStatusTextTest`. + */ +class RosterIdTest { + + /** An ed25519 pubkey as the core prints it: 64 lowercase hex characters. */ + private val fingerprint = + "9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49" + + // --- the long case ------------------------------------------------------- + + @Test + fun a_long_fingerprint_becomes_head_ellipsis_tail() { + assertEquals("9f2c41…6a49", shortId(fingerprint)) + } + + @Test + fun the_abbreviation_is_a_slice_of_the_input_not_a_re_encoding() { + // The head and the tail must be literally the input's own characters: + // a summary that cannot be checked against the full value is worse than + // no summary. + val short = shortId(fingerprint) + assertEquals(fingerprint.take(6), short.substringBefore("…")) + assertEquals(fingerprint.takeLast(4), short.substringAfter("…")) + // Nothing invented to pad the middle: 6 + "…" + 4. + assertEquals(11, short.length) + } + + @Test + fun head_and_tail_are_call_sites_choice() { + assertEquals("9f2c…6a49", shortId(fingerprint, head = 4, tail = 4)) + assertEquals("9f2c41ab77…3b6a49", shortId(fingerprint, head = 10, tail = 6)) + } + + // --- the short case ------------------------------------------------------ + + @Test + fun a_string_shorter_than_head_tail_plus_one_is_returned_unchanged() { + // head + tail + 1 == 11 here, so anything of 10 characters or fewer has + // no middle worth hiding. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abc", shortId("abc")) + assertEquals("a", shortId("a")) + } + + @Test + fun the_first_length_that_abbreviates_is_head_tail_plus_one() { + // The boundary, both sides: 10 unchanged, 11 abbreviated to the same + // length with the middle character collapsed. + assertEquals("abcdefghij", shortId("abcdefghij")) + assertEquals("abcdef…hijk", shortId("abcdefghijk")) + } + + // --- the empty case ------------------------------------------------------ + + @Test + fun an_empty_string_stays_empty() { + // `ready.fingerprint` is always populated in practice, but the function + // must not turn "nothing" into "…" on a card that is already on screen. + assertEquals("", shortId("")) + } + + // --- the shape the card relies on --------------------------------------- + + @Test + fun the_ellipsis_is_the_single_character_one() { + // U+2026, not three dots: the collapsed line is monospace and a + // three-dot tail is four cells where the design budgeted one. + assertTrue(shortId(fingerprint).contains("\u2026")) + assertEquals(1, shortId(fingerprint).count { it == '\u2026' }) + } +} From 812c259f460112d4bda06877f20a172311eacec7 Mon Sep 17 00:00:00 2001 From: apk-dev Date: Tue, 22 Sep 2026 01:23:47 -0400 Subject: [PATCH 30/94] android: saved-wallets screen (list, select, back up the open wallet) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app could hold several wallets and show none of them. Add the screen that lists the store's catalogue, marks the one the wallet child has open, switches to another on a tap, and — for the open one only — shows its recovery phrase and private keys. Everything secret here belongs to the file the child currently has open: `query_key` is answered by that file and no other, so the seed card and the keys card hang off `active_wallet_filename()`, not off a row. On a row that is not the open one both actions are dead and say why ("open this wallet to view its backup") instead of opening it under the user — switching wallets is a deliberate tap, because `open_wallet` stops and restarts a running child. The phrase keeps the existing treatment: the wallet screen's own `SeedBackupCard`, widened from `private` to `internal` rather than copied, so the gate constants are still the one `SeedBackupGate`. The keys card shows the view key always and the spend key when there is one; a view-only wallet says "view-only wallet — no spend key" in words, because `null` is the wallet's own answer and not a failure. Neither value is logged, persisted, tagged, or held in saved state, and both are dropped on dispose. The catalogue is re-read on entry and on Refresh, never cached from app start, so a wallet created on the wallet screen after this one was first opened shows up without restarting the app. An empty catalogue ("No saved wallets yet") and a read failure ("could not read the wallet catalogue" + the core's text) are rendered as the two different states they are. The gate is pure Kotlin in the new file and `WalletManagerTest` covers it on the JVM (17 cases): the row label's name/blank/whitespace fallback, which child states count as readable, and whether the secret actions are offered for a row. --- .../siriusdevops/onionwire/MainActivity.kt | 11 +- .../siriusdevops/onionwire/WireViewModel.kt | 46 ++ .../onionwire/ui/WalletManagerScreen.kt | 584 ++++++++++++++++++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 14 +- .../onionwire/ui/WalletManagerTest.kt | 153 +++++ 5 files changed, 806 insertions(+), 2 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 1d14fa6..200c2b8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -29,6 +29,7 @@ import com.siriusdevops.onionwire.ui.RosterScreen import com.siriusdevops.onionwire.ui.RotateScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.UnlockScreen +import com.siriusdevops.onionwire.ui.WalletManagerScreen import com.siriusdevops.onionwire.ui.WalletScreen import com.siriusdevops.onionwire.ui.OnionWireTheme import kotlinx.coroutines.launch @@ -133,7 +134,15 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str } composable("wallet") { - WalletScreen(vm = vm, onBack = { nav.popBackStack() }) + WalletScreen( + vm = vm, + onBack = { nav.popBackStack() }, + onOpenWallets = { nav.navigate("wallets") }, + ) + } + + composable("wallets") { + WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) } composable( diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 7be3c6a..3c071c8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -41,6 +41,8 @@ import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.TransferRow import uniffi.onionwire_sdk.WalletChildStatus +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -619,6 +621,50 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun walletSeed(): Result = runCatching { requireWire().walletSeed() } + // --- Wallet catalogue, the open wallet, and its secrets ---------------- + // The saved-wallets screen's reads. The catalogue is a store read that + // never dials, so it goes to [Dispatchers.IO] like the other store reads in + // this file — a SQLCipher decrypt on the main thread is an ANR waiting for a + // slow device. + + /** + * Every wallet this install remembers, oldest first. + * + * A store read: it works with the wallet child stopped or never configured, + * and "no wallets" is an empty list rather than a failure — the caller must + * not render the two alike. + */ + suspend fun wallets(): Result> = + withContext(Dispatchers.IO) { runCatching { requireWire().wallets() } } + + /** + * The file name of the wallet the child currently has open, or null when it + * has none. The catalogue's in-use marker is this and nothing else. + */ + suspend fun activeWalletFilename(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().activeWalletFilename() } } + + /** + * Point the wallet child at a catalogue wallet's file. + * + * Slow on purpose: a live child is stopped and started again onto the new + * file. The core refuses a name the catalogue does not hold, and that + * refusal is surfaced verbatim to the caller. + */ + suspend fun openWallet(filename: String): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } + + /** + * The **open** wallet's private keys, for the saved-wallets screen. + * + * Both values are spend secrets: only ever called from an explicit tap, + * never logged, never persisted, and dropped when the screen goes. There is + * deliberately no accessor for another catalogue row's keys — the only way + * to read a saved wallet's keys is to open it first. + */ + suspend fun walletKeys(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().walletKeys() } } + fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() }.getOrElse { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt new file mode 100644 index 0000000..d041575 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -0,0 +1,584 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.launch +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +// --------------------------------------------------------------------------- +// The rules this screen renders from, as pure Kotlin so `WalletManagerTest` +// covers them on the JVM without a device. Same shape as `SeedBackupGate` and +// `WalletChildStatusText`: the composables below only lay these decisions out. +// --------------------------------------------------------------------------- + +/** + * A catalogue row's label: the user's name for the wallet, or the file name + * when there is none. + * + * `WalletRow.name` is documented as `None` when the wallet was never named and + * "never an empty string", but a blank string is treated as absent here too — + * a row labelled with spaces is a row the user cannot identify. + */ +internal fun walletRowLabel(name: String?, filename: String): String = + name?.takeIf { it.isNotBlank() } ?: filename + +/** + * A row's creation date, from the store's unix seconds. + * + * `created_at <= 0` is not a date: the store assigns it on insert, so anything + * else is a row that predates that — say so rather than render 1970. + */ +internal fun walletRowDate(createdAt: Long): String { + if (createdAt <= 0L) return "date unknown" + return Instant.ofEpochSecond(createdAt) + .atZone(ZoneId.systemDefault()) + .format(DateTimeFormatter.ISO_LOCAL_DATE) +} + +/** + * Whether the wallet child has a wallet open that the RPC answers for. + * + * The core's `state` is the only honest signal available here: `connecting` + * means its wallet RPC has not answered, `off`/`exited` mean there is no child + * at all, and `syncing`/`ready` mean it answered — the chain being behind is + * irrelevant to whether the open wallet's keys can be read. A `null` state is + * "nothing read yet", which is not readable. + */ +internal fun walletChildReadable(state: String?): Boolean = + state == "ready" || state == "syncing" + +/** + * Whether the open wallet's secrets may be offered for the row named + * [rowFilename]. + * + * Both halves are load-bearing: + * + * - **active**: the seed and the private keys come from `query_key` against + * the file the child currently has open, so they belong to exactly one + * wallet. A non-active row's buttons stay dead instead of quietly opening + * that wallet under the user — switching is a deliberate tap, not a side + * effect of asking for a backup. + * - **readable**: with no child running there is no file open, and + * `wallet_seed()` / `wallet_keys()` can only fail. Offering a button that + * always errors is worse than saying why it is off. + */ +internal fun walletSecretsEnabled( + activeFilename: String?, + rowFilename: String, + walletReadable: Boolean, +): Boolean = walletReadable && activeFilename != null && activeFilename == rowFilename + +/** + * Why the secret actions are off, in words — or `null` when they are on. + * + * The two reasons are different states of the world and are not collapsed: + * "this is not the open wallet" is fixed by tapping the row, "the child is not + * running" is fixed on the wallet screen. The first wording is the card's own. + */ +internal fun walletSecretsBlockedReason( + isActive: Boolean, + walletReadable: Boolean, +): String? = when { + !isActive -> "open this wallet to view its backup" + !walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup" + else -> null +} + +/** + * The saved-wallet catalogue: every wallet this install remembers, which one is + * open now, and — for that one — its recovery phrase and private keys. + * + * Three properties are deliberate and are the whole point of the screen: + * + * - The catalogue is re-read on entry and on Refresh, never cached from app + * start, so a wallet created on the wallet screen after this screen was + * first opened shows up without restarting the app. + * - A tap opens a row's file through `open_wallet(filename)` and reloads, so + * the in-use marker moves. The core refuses a name outside the catalogue, + * and its refusal is shown verbatim. + * - The secrets belong to the **open** wallet only. They are read on an + * explicit tap, are never shown for a row that is not the open one, and are + * never logged, persisted, put in a `testTag`/`contentDescription`, or held + * in saved state (`remember`, not `rememberSaveable`, and cleared on + * dispose). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun WalletManagerScreen( + vm: WireViewModel, + onBack: () -> Unit, +) { + val child by vm.walletChild.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + + /** `null` is "not read yet"; an empty list is a catalogue with no rows. */ + var rows by remember { mutableStateOf?>(null) } + /** The file name the core reports as open, or null when it reports none. */ + var active by remember { mutableStateOf(null) } + /** A catalogue/active-wallet read failure, distinct from an empty list. */ + var listError by remember { mutableStateOf(null) } + /** A failed open, verbatim from the core. */ + var actionError by remember { mutableStateOf(null) } + /** The file name currently being opened, so the row can say so. */ + var opening by remember { mutableStateOf(null) } + + // The seed on the blocking card, and the typed confirm word. Neither is + // persisted: a spend key lives in this composition and nowhere else. + var seed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } + // The open wallet's private keys, only ever set by an explicit tap on + // "Private keys". Null means no card. + var keys by remember { mutableStateOf(null) } + var keysError by remember { mutableStateOf(null) } + + suspend fun reload() { + vm.wallets().fold( + onSuccess = { + rows = it + listError = null + }, + onFailure = { + rows = null + listError = it.message ?: it.toString() + }, + ) + vm.activeWalletFilename().fold( + onSuccess = { active = it }, + onFailure = { + // Same store as the list: a failure here is a read failure, not + // "no wallet is open", and it must not be rendered as one. + active = null + if (listError == null) { + listError = it.message ?: it.toString() + } + }, + ) + } + + /** Open a row's file, then re-read so the in-use marker moves. */ + fun open(filename: String) { + if (opening != null) return + scope.launch { + actionError = null + opening = filename + vm.openWallet(filename).fold( + onSuccess = { reload() }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + opening = null + } + } + + /** + * "Recovery phrase": re-read the open wallet's 25 words and put them on the + * existing blocking card. Same treatment as the wallet screen's "Back up + * seed" — one gate, one card, no second ungated display. + */ + fun showPhrase() { + scope.launch { + actionError = null + vm.walletSeed().fold( + onSuccess = { + seed = it + seedConfirm = "" + }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + } + } + + /** + * "Private keys": read the open wallet's keys once, on this tap. Failure is + * shown where the card would be, so a wallet that cannot answer says so + * instead of looking like an empty one. + */ + fun showKeys() { + scope.launch { + actionError = null + keysError = null + vm.walletKeys().fold( + onSuccess = { keys = it }, + onFailure = { keysError = it.message ?: it.toString() }, + ) + } + } + + LaunchedEffect(Unit) { + // The cached child read never dials, so the screen paints; the live + // probe after it is what tells the truth about whether a wallet is + // open, which is what the secret actions hang on. + vm.paintWalletChildCached() + reload() + vm.refreshWalletChild() + } + + // Nothing here is `rememberSaveable`, so leaving the screen drops the + // composition's state — including the seed and the keys. Dropping the + // reference is the strongest wipe a Kotlin String allows (see + // `SeedBackupCard`); this makes it explicit rather than incidental. + DisposableEffect(Unit) { + onDispose { + seed = null + seedConfirm = "" + keys = null + keysError = null + } + } + + val walletReadable = walletChildReadable(child?.state) + + Scaffold( + // Root owns systemBars ∪ ime, exactly as the wallet screen does (see + // `screenContentInsets`). + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + TopAppBar( + title = { Text("Saved wallets") }, + navigationIcon = { + TextButton(onClick = onBack) { Text("Back") } + }, + actions = { + TextButton( + onClick = { + scope.launch { + vm.refreshWalletChild() + reload() + } + }, + ) { Text("Refresh") } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + ), + ) + }, + ) { pad -> + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()), + ) { + // The blocking seed card, when a phrase is on screen: the whole + // body, exactly as on the wallet screen. Done is dead until the + // confirm word is typed, and the app-bar Back still leaves. + val shownSeed = seed + if (shownSeed != null) { + SeedBackupCard( + seed = shownSeed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + vm.confirmWalletSeed(seedConfirm) + seed = null + seedConfirm = "" + }, + ) + actionError?.let { ErrorText(it) } + return@Column + } + + keys?.let { k -> + PrivateKeysCard( + keys = k, + warning = vm.spendAuthorityWarning(), + onDone = { keys = null }, + ) + } + keysError?.let { message -> + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("could not read the open wallet's private keys") + Spacer(Modifier.height(4.dp)) + Text(message, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { keysError = null }) { Text("Dismiss") } + } + } + } + + actionError?.let { ErrorText(it) } + + val listed = rows + when { + // A read failure is not an empty catalogue, and the two must + // not read alike: one is "the store did not answer", the other + // is "you have no wallets yet". + listError != null -> Column(Modifier.padding(12.dp)) { + Text( + "could not read the wallet catalogue", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(4.dp)) + Text( + listError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") } + } + + listed == null -> Text( + "loading…", + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(12.dp), + ) + + listed.isEmpty() -> Column(Modifier.padding(12.dp)) { + Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text( + "Wallets this install remembers show up here. Create or import one " + + "on the wallet screen and it appears on the next look.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Button(onClick = onBack) { Text("Create or import a wallet") } + } + + else -> { + Text( + "${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + listed.forEach { row -> + val isActive = active != null && active == row.walletFilename + WalletRowCard( + row = row, + isActive = isActive, + secretsEnabled = walletSecretsEnabled( + activeFilename = active, + rowFilename = row.walletFilename, + walletReadable = walletReadable, + ), + blockedReason = walletSecretsBlockedReason( + isActive = isActive, + walletReadable = walletReadable, + ), + opening = opening == row.walletFilename, + onOpen = { open(row.walletFilename) }, + onShowPhrase = { showPhrase() }, + onShowKeys = { showKeys() }, + ) + } + } + } + } + } +} + +/** + * One catalogue row: what it is called, which file it is, when it was created, + * and whether it is the open one. + * + * The open row is not tappable. Re-opening it would stop and restart a running + * wallet child onto the file it already has open — a slow no-op whose only + * effect is to make the screen look like it did something. + */ +@Composable +private fun WalletRowCard( + row: WalletRow, + isActive: Boolean, + secretsEnabled: Boolean, + blockedReason: String?, + opening: Boolean, + onOpen: () -> Unit, + onShowPhrase: () -> Unit, + onShowKeys: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + walletRowLabel(row.name, row.walletFilename), + style = MaterialTheme.typography.titleSmall, + ) + when { + isActive -> Text( + "in use", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + opening -> Text( + "opening…", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + else -> Text( + "tap to open", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Spacer(Modifier.height(4.dp)) + Text( + "file ${row.walletFilename}", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Text( + "created ${walletRowDate(row.createdAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) { + Text("Recovery phrase") + } + OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) { + Text("Private keys") + } + } + blockedReason?.let { + Spacer(Modifier.height(4.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * The open wallet's private keys, shown only after an explicit tap. + * + * The view key is always there; the spend key only when the wallet has one. + * A view-only wallet says so in words — it has no spend key, and rendering + * that as a failure would teach the user to read a normal wallet as a broken + * one. The values are spend secrets: no `testTag`, no `contentDescription`, + * no logging, no persistence, and the card is dropped when the screen goes. + */ +@Composable +private fun PrivateKeysCard( + keys: WalletKeys, + warning: String, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Text( + "view key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + keys.viewKey, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Spacer(Modifier.height(8.dp)) + val spend = keys.spendKey + if (spend != null) { + Text( + "spend key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + spend, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } else { + Text( + "view-only wallet — no spend key", + style = MaterialTheme.typography.bodyMedium, + ) + } + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button(onClick = onDone) { Text("Done") } + } + } + } +} + +/** A display-ready failure line. Never carries a secret; callers pass errors. */ +@Composable +private fun ErrorText(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index ec98015..f6ea31c 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -70,6 +70,7 @@ private enum class SetupKind { Create, Import } fun WalletScreen( vm: WireViewModel, onBack: () -> Unit, + onOpenWallets: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() @@ -161,6 +162,12 @@ fun WalletScreen( navigationIcon = { TextButton(onClick = onBack) { Text("Back") } }, + // The saved-wallet catalogue is its own screen: this one is the + // open wallet, and switching wallets restarts the child, so the + // picker does not belong in this page's scroll. + actions = { + TextButton(onClick = onOpenWallets) { Text("Wallets") } + }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, ), @@ -548,9 +555,14 @@ private fun UnbackedSeedCard( * The seed is a Kotlin `String`, so it cannot be wiped in place the way the * TUI's `Zeroizing` is; dropping the reference is the strongest thing * available here. That is another reason it is never written to disk. + * + * `internal` rather than `private`: the saved-wallets screen shows the same + * card for the open wallet's recovery phrase, and a second copy of this gate + * (or of its constants) is the thing that would eventually disagree with this + * one. */ @Composable -private fun SeedBackupCard( +internal fun SeedBackupCard( seed: String, typed: String, onTyped: (String) -> Unit, diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt new file mode 100644 index 0000000..99a35e4 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -0,0 +1,153 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The saved-wallets screen's rules, on the JVM. + * + * These are the decisions the screen renders from: what a catalogue row is + * called, whether the child has a wallet open at all, and whether the two + * secret actions may be offered for a given row. Pure logic, so no Robolectric + * and no Compose test dependency — same shape as `SeedBackupGateTest` and + * `WalletChildStatusTextTest`. + */ +class WalletManagerTest { + + private val openFile = "onionwire-main" + private val otherFile = "onionwire-second" + + /** The core's `wallet_status().state` for a child that answered. */ + private val readable = true + + /** No child, or one whose wallet RPC has not answered. */ + private val notReadable = false + + // --- what a row is called ----------------------------------------------- + + @Test + fun a_named_wallet_is_labelled_with_its_name() { + assertEquals("spending", walletRowLabel("spending", openFile)) + } + + @Test + fun an_unnamed_wallet_falls_back_to_its_file_name() { + assertEquals(openFile, walletRowLabel(null, openFile)) + } + + @Test + fun a_blank_name_counts_as_absent() { + // `WalletRow.name` is documented as never an empty string, but a + // whitespace label is a row the user cannot identify either way. + assertEquals(openFile, walletRowLabel("", openFile)) + assertEquals(openFile, walletRowLabel(" ", openFile)) + } + + @Test + fun a_name_is_not_trimmed_out_of_the_label() { + // Only the *blank* case falls back. A name with padding is still the + // user's name and is shown as stored. + assertEquals(" spending ", walletRowLabel(" spending ", openFile)) + } + + // --- is the child reading a wallet at all -------------------------------- + + @Test + fun only_an_answered_wallet_rpc_counts_as_readable() { + // `connecting` is "the RPC has not answered"; `off` and `exited` are + // "there is no child". None of them can answer a key query. + assertTrue(walletChildReadable("ready")) + assertTrue(walletChildReadable("syncing")) + assertFalse(walletChildReadable("connecting")) + assertFalse(walletChildReadable("off")) + assertFalse(walletChildReadable("exited")) + } + + @Test + fun nothing_read_yet_is_not_readable() { + assertFalse(walletChildReadable(null)) + } + + @Test + fun a_behind_chain_still_counts_as_readable() { + // Syncing means the RPC answered: the wallet's keys do not need the + // chain to be caught up. + assertTrue(walletChildReadable("syncing")) + } + + // --- whether the secret actions are offered ------------------------------ + + @Test + fun the_open_wallets_secrets_are_offered() { + assertTrue(walletSecretsEnabled(openFile, openFile, readable)) + } + + @Test + fun another_wallets_secrets_are_not_offered() { + // The seed and the keys come from the file the child has open. A row + // that is not the open one must not read as its own backup. + assertFalse(walletSecretsEnabled(openFile, otherFile, readable)) + } + + @Test + fun nothing_open_means_no_secrets_for_any_row() { + assertFalse(walletSecretsEnabled(null, openFile, readable)) + } + + @Test + fun the_open_wallet_offers_no_secrets_while_the_child_is_not_reading_it() { + // Active but no answer: `wallet_seed()` / `wallet_keys()` can only + // fail, so the buttons stay dead rather than always erroring. + assertFalse(walletSecretsEnabled(openFile, openFile, notReadable)) + assertFalse(walletSecretsEnabled(openFile, otherFile, notReadable)) + assertFalse(walletSecretsEnabled(null, openFile, notReadable)) + } + + // --- and why they are off, in words -------------------------------------- + + @Test + fun an_enabled_row_has_nothing_to_explain() { + assertNull(walletSecretsBlockedReason(isActive = true, walletReadable = readable)) + } + + @Test + fun a_row_that_is_not_open_says_to_open_it() { + val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable) + assertEquals("open this wallet to view its backup", why) + } + + @Test + fun an_open_wallet_with_no_child_says_the_child_is_not_running() { + val why = walletSecretsBlockedReason(isActive = true, walletReadable = notReadable) + assertTrue(why != null && why.contains("not running")) + // The two reasons are different fixes and must not read alike. + assertFalse(why == walletSecretsBlockedReason(isActive = false, walletReadable = readable)) + } + + // --- the created-at column ---------------------------------------------- + + @Test + fun a_stored_created_at_renders_as_a_date() { + // 2021-01-01T00:00:00Z. + val rendered = walletRowDate(1609459200L) + assertTrue("got '$rendered'", Regex("""\d{4}-\d{2}-\d{2}""").matches(rendered)) + } + + @Test + fun a_later_created_at_sorts_after_an_earlier_one() { + // The store hands the rows back oldest-first; the rendered date must + // not invert that order in the list. + assertTrue(walletRowDate(1700000000L) > walletRowDate(1609459200L)) + } + + @Test + fun a_row_with_no_assigned_created_at_says_so() { + // The store assigns `created_at` on insert, so 0 is a row that predates + // that — not 1970, and not "today". + assertEquals("date unknown", walletRowDate(0L)) + assertEquals("date unknown", walletRowDate(-1L)) + } +} From 775f2e88be31b9991d543016d26a6093e111f5b9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 02:12:32 -0400 Subject: [PATCH 31/94] =?UTF-8?q?android:=20profile=20screen=20=E2=80=94?= =?UTF-8?q?=20nickname=20+=20Monero=20receiving=20address?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone's half of the TUI's `/profile`. A `Profile` action on the roster's app bar opens `ui/ProfileScreen.kt`: nickname, bio, and the Monero address friends pay to, all three loaded from the store and written back through the core's own validation. - The address is checked with `uniffi.onionwire_sdk.checkAddress` *before* the write, so a typo is refused with the typed text still in the field instead of surfacing as a store error afterwards. An empty address is allowed and is labelled with its consequence: with no profile address and no running wallet child the core has nothing to hand a payer. - The bio is carried, not owned: a save that did not touch the field writes back the value read from the store immediately before the write, so a bio set in the TUI cannot be blanked from the phone. - On save the profile is pushed to **every** friend in the roster, one-shot and fail-closed per friend like the TUI's `save_profile`. A push failure is not a save failure: the status line always starts with `profile saved` and names the count, with each failure listed by petname (else shortened fingerprint). Every decision the screen makes is a pure function in the new file, covered by `ProfileDraftTest` (21 cases) on the JVM: the save-button rule (dead until the read lands, dead while the form is unchanged), the address branch, the bio rule, label selection and the status-line aggregation. Verified on AVD ow35 (x86_64 slice, emulator-5560): the roster app bar carries `Profile`; nickname/bio/address survive `am force-stop` + relaunch; an invalid address is refused before the write; a save with an empty roster reports `profile saved`; with one (self-)peer in the roster a save reports `profile saved · sent to 1 friend`, and with the emulator's network cut the same save reports `profile saved · sent to 0 of 1 friend · failed: