onionwire/src/tui.rs
rust-dev 3aafaefae8
Some checks failed
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled
wallet: derive readiness from the wallet's get_height, not a nonexistent get_info
monero-wallet-rpc does not implement get_info (-32601 Method not found); it
exists on the daemon only. Every wallet therefore sat in syncing forever:
no balance, spends refused, receipts never verified.

Readiness is now the pair:
- the wallet RPC's own get_height (its scanned height), and
- the chain tip from the existing daemon client (GET /get_height).

ready = height > 0 && (tip == 0 || height + 2 >= tip). The 2-block slack is
deliberate: the tip moves every ~2 min and the two reads are not a snapshot.
A daemon that does not answer, a missing height and -13 No wallet file are
all not-ready, never an error banner.

ChildConfig::daemon_probe_addr resolves a tip source for clearnet remotes
(the wallet child already dials them); a .onion daemon is not dialled without
the SOCKS child and stays fail-closed. docs/WALLET.md now documents the real
rule. Tests cover -32601 get_info, equal tip, slack boundary, dead daemon and
the no-wallet-file answer.
2026-10-31 01:35:15 -04:00

7749 lines
280 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::collections::HashMap;
use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
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};
use crate::sanitize;
use crate::store::{
Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment, WalletRecord,
};
use crate::wallet::{self, ChainNetwork, ChainSource, WalletConfig};
use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT;
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
const C_DIM: Color = Color::Rgb(98, 110, 92);
const C_ALERT: Color = Color::Rgb(220, 80, 70);
const C_STALE: Color = Color::Rgb(210, 180, 80);
const C_HL_BG: Color = Color::Rgb(48, 42, 28);
const C_BORDER: Color = Color::Rgb(72, 84, 64);
/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate.
pub fn ascii_chrome() -> bool {
std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some()
}
const ASCII_BORDERS: border::Set = border::Set {
top_left: "+",
top_right: "+",
bottom_left: "+",
bottom_right: "+",
vertical_left: "|",
vertical_right: "|",
horizontal_top: "-",
horizontal_bottom: "-",
};
fn ellipsis() -> &'static str {
if ascii_chrome() { "..." } else { "…" }
}
/// 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 {
alert_line_for_mode(color_mode(), msg, width)
}
/// [`alert_line`] with the colour mode supplied by the caller.
///
/// Tests pin the `! ` ornament of the no-colour path through this entry point
/// rather than flipping `NO_COLOR`, which is process-global and mutated
/// concurrently by other tests in the same binary.
pub fn alert_line_for_mode(mode: ColorMode, msg: &str, width: u16) -> String {
let mut text = msg.to_string();
if mode == ColorMode::None && !text.starts_with("! ") {
text = format!("! {text}");
}
fit_cells(&text, width as usize)
}
/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation.
/// Joining the lines (no extra spaces) reconstructs `payload`.
pub fn wrap_invite(payload: &str, width: usize) -> String {
if width == 0 {
return String::new();
}
let mut lines: Vec<String> = Vec::new();
let mut cur = String::new();
let parts: Vec<&str> = payload.split(':').collect();
for (i, part) in parts.iter().enumerate() {
let piece = if i + 1 < parts.len() {
format!("{part}:")
} else {
(*part).to_string()
};
for chunk in char_chunks(&piece, width) {
if cur.is_empty() {
cur = chunk;
} else if char_len(&cur) + char_len(&chunk) <= width {
cur.push_str(&chunk);
} else {
lines.push(std::mem::take(&mut cur));
cur = chunk;
}
}
}
if !cur.is_empty() {
lines.push(cur);
}
lines.join("\n")
}
fn char_chunks(s: &str, width: usize) -> Vec<String> {
if width == 0 {
return Vec::new();
}
if char_len(s) <= width {
return vec![s.to_string()];
}
let chars: Vec<char> = s.chars().collect();
chars.chunks(width).map(|c| c.iter().collect()).collect()
}
/// Friend selected, no messages yet.
pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
/// capped at `budget` cells so one peer's error cannot blow out the row.
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 };
fit_cells(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
/// Highest attempt count across outstanding rows (0 when nothing is
/// outstanding). With `DEFAULT_MAX_ATTEMPTS` this is the `n` in `(n/8)`.
pub attempts: u32,
/// Seconds until the earliest scheduled retry, relative to the render
/// `now`. `None` while nothing is outstanding.
pub next_in_secs: Option<i64>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
///
/// An outstanding row is a reachability statement, not just a count: the
/// peer's onion did not answer *this* dial, so the note names that and the
/// retry it is waiting on (`peer unreachable, queued (n/8, retry 45s)`).
/// There is no mutual-online indicator to fall back on.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
let queued = || {
format!(
"peer unreachable, queued ({}/{DEFAULT_MAX_ATTEMPTS}, {})",
self.attempts,
retry_in_text(self.next_in_secs.unwrap_or(0))
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(_, 0) => Some(queued()),
(_, _) => Some(format!("{}, send failed: {}", queued(), reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are joined to messages on `Message::id` /
/// `OutboxEntry::message_id` — never on the body. Two identical bodies are
/// distinct rows with distinct ids, so the marker always lands on the row that
/// actually owns the outbox entry.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => {
summary.queued += 1;
// The note is the reachability statement for the selected
// friend: highest attempt count, soonest scheduled retry.
summary.attempts = summary.attempts.max(entry.attempts);
let secs = entry.next_attempt_at - now;
summary.next_in_secs = Some(match summary.next_in_secs {
Some(prev) => prev.min(secs),
None => secs,
});
}
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
// One row per message in practice (a retry updates its row, not inserts a
// second), and `pending` is ordered by row id, so a hypothetical duplicate
// resolves to the newest — the same rule the store's own
// `outbox_status_of_message` uses.
let by_id: HashMap<i64, &OutboxEntry> =
pending.iter().map(|entry| (entry.message_id, entry)).collect();
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate() {
if msg.dir != "out" {
continue;
}
if let Some(entry) = by_id.get(&msg.id) {
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
Some(e) => format!("{e}\nEnter resubmits Esc back"),
None => "paste onionwire:v1 payload, Enter to submit".to_string(),
};
format!("{hint}\n\n{buf}")
}
fn char_len(s: &str) -> usize {
s.chars().count()
}
/// Terminal colour capability, detected from the environment.
///
/// `ColorMode::None` means “strip all colour” (e.g. `NO_COLOR`); the TUI then
/// falls back to ASCII chrome and a `! ` prefix on alerts so signal survives.
/// `Ansi16` is the 16-colour fallback for dumb / non-TTY output. `Rgb` is the
/// full-fidelity path.
///
/// The palette (`C_*`) is always defined. `tokens_for(mode)` projects it into a
/// concrete `TokenStyles` so that tests can assert on the resolved `Style`
/// without depending on the process environment.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ColorMode {
Rgb,
Ansi16,
None,
}
/// Detect the terminal's colour capability from the environment.
///
/// - `NO_COLOR` is set → `ColorMode::None`.
/// - `TERM=dumb` or stdout is not a TTY → `ColorMode::Ansi16`.
/// - Otherwise → `ColorMode::Rgb`.
pub fn color_mode() -> ColorMode {
if std::env::var_os("NO_COLOR").is_some() {
ColorMode::None
} else if std::env::var("TERM").ok().as_deref() == Some("dumb") || !io::stdout().is_terminal() {
ColorMode::Ansi16
} else {
ColorMode::Rgb
}
}
/// All UI styles resolved for a single `ColorMode`. Tests construct this
/// directly instead of calling `color_mode()`, because the latter reads the
/// process environment (which is non-deterministic in `cargo test`).
pub struct TokenStyles {
/// Primary text (names, message bodies).
pub text: Style,
/// Muted / secondary text (timestamps, hints).
pub dim: Style,
/// Accent: headers, focus ring, selected friend.
pub accent: Style,
/// Alert: failure / validation errors.
pub alert: Style,
/// Stale data (unconfirmed, timed out).
pub stale: Style,
/// Border / chrome lines.
pub border: Style,
/// Highlight block (selected list row).
pub highlight: Style,
}
/// Project the RGB palette constants into a concrete [`TokenStyles`] for the
/// given `ColorMode`. This is the single source of truth the `style_*` helpers
/// delegate to, and the only surface tests assert against.
pub fn tokens_for(mode: ColorMode) -> TokenStyles {
let rgb = |fg: Color, ansi: Color| match mode {
ColorMode::None => Style::default(),
ColorMode::Ansi16 => Style::default().fg(ansi),
ColorMode::Rgb => Style::default().fg(fg),
};
let accent = match mode {
ColorMode::None => Style::default().add_modifier(Modifier::BOLD),
ColorMode::Ansi16 => Style::default().fg(Color::Yellow),
ColorMode::Rgb => Style::default().fg(C_ACCENT),
};
let highlight = match mode {
ColorMode::None => Style::default().add_modifier(Modifier::BOLD | Modifier::REVERSED),
ColorMode::Ansi16 => Style::default()
.add_modifier(Modifier::REVERSED | Modifier::BOLD),
ColorMode::Rgb => Style::default()
.bg(C_HL_BG)
.fg(C_ACCENT)
.add_modifier(Modifier::BOLD),
};
TokenStyles {
text: rgb(C_TEXT, Color::White),
dim: rgb(C_DIM, Color::DarkGray),
accent,
alert: rgb(C_ALERT, Color::Red),
stale: rgb(C_STALE, Color::Yellow),
border: rgb(C_BORDER, Color::DarkGray),
highlight,
}
}
fn style_accent() -> Style {
tokens_for(color_mode()).accent
}
fn style_text() -> Style {
tokens_for(color_mode()).text
}
fn style_dim() -> Style {
tokens_for(color_mode()).dim
}
fn style_alert() -> Style {
tokens_for(color_mode()).alert
}
fn style_stale() -> Style {
tokens_for(color_mode()).stale
}
fn style_border() -> Style {
tokens_for(color_mode()).border
}
fn style_highlight() -> Style {
tokens_for(color_mode()).highlight
}
/// How long the TUI waits for a key before redrawing (so background send can update status).
pub const TUI_POLL: Duration = Duration::from_millis(100);
/// How often a screen that shows chain height re-asks the daemon. The NODE row
/// is a snapshot of the last probe; without this it stays on the height from
/// child start while the chain keeps moving.
const CHAIN_STATUS_INTERVAL: Duration = Duration::from_secs(1);
/// Non-blocking read of a background send/job status. Never waits on Tor.
pub fn take_job_result(rx: &mpsc::Receiver<String>) -> Option<String> {
match rx.try_recv() {
Ok(s) => Some(s),
Err(mpsc::TryRecvError::Empty) => None,
Err(mpsc::TryRecvError::Disconnected) => Some("send failed".into()),
}
}
pub fn fingerprint_mismatch_banner() -> &'static str {
"fingerprint mismatch"
}
pub fn rotate_screen_text() -> &'static str {
"Rotate onion address?\n\
Your identity key stays the same.\n\
Online friends get a signed location update.\n\
Offline friends CANNOT find you until they F3-paste your new invite.\n\
Type ROTATE to confirm Esc to cancel"
}
/// F8. Hard cut like the locator rotate: the prekey is our Noise static and the
/// ratchet bootstrap is derived from the prekey DH, so nothing short of a fresh
/// invite re-syncs a friend.
pub fn prekey_screen_text() -> &'static str {
"Rotate prekey?\n\
Your identity and onion stay the same.\n\
Every friend must F3-paste your new invite to pick up the new prekey,\n\
or you cannot reach them and they cannot reach you.\n\
Type ROTATE to confirm Esc to cancel"
}
pub fn quit_screen_text() -> &'static str {
"Quit OnionWire?\n\
Message history can be cleared; identity and friends stay.\n\
This is not /wipe-all.\n\
Type CLEAR then Enter to clear history and quit.\n\
Type QUIT then Enter to quit without clearing.\n\
Esc to cancel"
}
/// Full Main-screen wordmark. Every line is <= 80 ASCII characters.
pub fn wordmark_banner() -> &'static str {
"\
.-~~-. .-~~-. .-~~-. ONIONWIRE\n\
( o )( o )( o ) identity = pubkey onion = locator\n\
`-..-' `-..-' `-..-' tor messenger no server"
}
/// One-line fallback when the terminal is narrower than the wordmark.
pub fn compact_banner() -> &'static str {
"ONIONWIRE (o) tor"
}
pub fn onion_glyph() -> &'static str {
"\
.-.\n\
( o )\n\
'-'"
}
pub fn help_overlay_text() -> &'static str {
"\
OnionWire keys\n\
\n\
Tab / Shift-Tab cycle roster, chat, composer\n\
1 / 2 / 3 focus roster / chat / composer\n\
j k or Up Down move or scroll focused pane\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 (C copies it)\n\
F3 paste invite\n\
F4 rotate onion locator\n\
F5 selected friend's profile (/who)\n\
F6 wallet (receive QR, create/import)\n\
F7 wallet setup: RPC endpoint, chain source\n\
F8 rotate prekey\n\
p peer payments (roster or chat)\n\
/profile edit name, bio, Monero address\n\
/pay <xmr> [memo] invoice to receive\n\
/tip <xmr> [memo] pay selected friend\n\
/wallet create new spend wallet (seed shown once)\n\
/wallet import restore from existing seed\n\
/file /path send file to selected friend (1 MiB)\n\
/backup /path encrypted identity export\n\
/restore /path overwrite self keys\n\
/wipe wipe messages; identity and friends stay\n\
/wipe-all wipe identity too — you become a new person\n\
? this help\n\
Ctrl-Q quit; type CLEAR or QUIT\n\
\n\
Esc closes this overlay"
}
pub fn who_overlay_text(fingerprint: &str, onion: &str, profile: Option<&FriendProfile>) -> String {
match profile {
None => format!(
"friend profile\n\nfp {fingerprint}\nonion {onion}\n\nno profile yet\n\nEsc closes"
),
Some(p) => {
let name = if p.display_name.is_empty() {
"(none)"
} else {
p.display_name.as_str()
};
let bio = if p.bio.is_empty() {
"(none)"
} else {
p.bio.as_str()
};
let xmr = if p.xmr_addr.is_empty() {
"(none)"
} else {
p.xmr_addr.as_str()
};
format!(
"friend profile\n\nname {name}\nbio {bio}\nxmr {xmr}\nfp {fingerprint}\nonion {onion}\n\nEsc closes"
)
}
}
}
pub fn banner_for_width(width: u16) -> &'static str {
let full = wordmark_banner();
let max_line = full.lines().map(|l| l.chars().count()).max().unwrap_or(0);
if (width as usize) >= max_line {
full
} else {
compact_banner()
}
}
/// 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<TorPhase>,
) -> 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<TorPhase>) -> 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 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<TorPhase>,
) -> Vec<Span<'static>> {
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+.
pub fn roster_col_width(term_width: u16) -> u16 {
if term_width >= 120 { 28 } else { 22 }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
Roster,
Chat,
Composer,
}
impl Pane {
pub fn next(self) -> Self {
match self {
Self::Roster => Self::Chat,
Self::Chat => Self::Composer,
Self::Composer => Self::Roster,
}
}
pub fn prev(self) -> Self {
match self {
Self::Roster => Self::Composer,
Self::Chat => Self::Roster,
Self::Composer => Self::Chat,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WipeKind {
Messages,
All,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlashCmd {
Wipe(WipeKind),
Profile,
Who,
Pay { atomic: String, memo: String },
Tip { atomic: String, memo: String },
Backup { path: String },
Restore { path: String },
File { path: String },
WalletCreate,
WalletImport,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ComposerAction {
Cmd(SlashCmd),
Send(String),
UnknownSlash(String),
}
/// Enter in the composer: slash command, chat send, or unknown `/cmd`.
pub fn composer_enter(raw: &str) -> Option<ComposerAction> {
let s = raw.trim();
if s.is_empty() {
return None;
}
if let Some(cmd) = parse_cmd(raw) {
return Some(ComposerAction::Cmd(cmd));
}
if s.starts_with('/') {
return Some(ComposerAction::UnknownSlash(s.to_string()));
}
Some(ComposerAction::Send(s.to_string()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileDraft {
pub display_name: String,
pub bio: String,
pub xmr_addr: String,
}
#[derive(Debug, Clone)]
pub struct ProfileEditor {
name: String,
bio: String,
xmr: String,
field: usize,
}
impl ProfileEditor {
pub fn new(display_name: &str, bio: &str, xmr_addr: &str) -> Self {
Self {
name: display_name.to_string(),
bio: bio.to_string(),
xmr: xmr_addr.to_string(),
field: 0,
}
}
pub fn on_enter(&self) -> ProfileDraft {
ProfileDraft {
display_name: self.name.clone(),
bio: self.bio.clone(),
xmr_addr: self.xmr.clone(),
}
}
pub fn on_tab(&mut self) {
self.field = (self.field + 1) % 3;
}
pub fn on_backtab(&mut self) {
self.field = (self.field + 2) % 3;
}
pub fn on_char(&mut self, c: char) {
if c == '\n' {
return;
}
self.field_mut().push(c);
}
pub fn on_backspace(&mut self) {
self.field_mut().pop();
}
pub fn field(&self) -> usize {
self.field
}
pub fn display_name(&self) -> &str {
&self.name
}
pub fn bio(&self) -> &str {
&self.bio
}
pub fn xmr_addr(&self) -> &str {
&self.xmr
}
fn field_mut(&mut self) -> &mut String {
match self.field {
0 => &mut self.name,
1 => &mut self.bio,
_ => &mut self.xmr,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WipeDecision {
Pending,
Confirm,
Cancel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppExit {
Quit,
WipeAll,
}
pub fn parse_cmd(raw: &str) -> Option<SlashCmd> {
let s = raw.trim();
match s {
"/wipe" => return Some(SlashCmd::Wipe(WipeKind::Messages)),
"/wipe-all" => return Some(SlashCmd::Wipe(WipeKind::All)),
"/profile" => return Some(SlashCmd::Profile),
"/who" => return Some(SlashCmd::Who),
_ => {}
}
if let Some(rest) = s.strip_prefix("/pay")
&& (rest.is_empty() || rest.starts_with(char::is_whitespace))
{
return parse_amount_cmd(rest).map(|(atomic, memo)| SlashCmd::Pay { atomic, memo });
}
if let Some(rest) = s.strip_prefix("/tip")
&& (rest.is_empty() || rest.starts_with(char::is_whitespace))
{
return parse_amount_cmd(rest).map(|(atomic, memo)| SlashCmd::Tip { atomic, memo });
}
if let Some(rest) = s.strip_prefix("/backup")
&& (rest.is_empty() || rest.starts_with(char::is_whitespace))
{
return parse_path_cmd(rest).map(|path| SlashCmd::Backup { path });
}
if let Some(rest) = s.strip_prefix("/restore")
&& (rest.is_empty() || rest.starts_with(char::is_whitespace))
{
return parse_path_cmd(rest).map(|path| SlashCmd::Restore { path });
}
if let Some(rest) = s.strip_prefix("/file")
&& (rest.is_empty() || rest.starts_with(char::is_whitespace))
{
return parse_path_cmd(rest).map(|path| SlashCmd::File { path });
}
match s {
"/wallet create" => return Some(SlashCmd::WalletCreate),
"/wallet import" => return Some(SlashCmd::WalletImport),
_ => {}
}
None
}
fn parse_path_cmd(rest: &str) -> Option<String> {
let path = rest.trim();
if path.is_empty() {
None
} else {
Some(path.to_string())
}
}
fn parse_amount_cmd(rest: &str) -> Option<(String, String)> {
let rest = rest.trim();
if rest.is_empty() {
return None;
}
let mut parts = rest.splitn(2, char::is_whitespace);
let amount = parts.next()?.trim();
let memo = parts.next().unwrap_or("").trim().to_string();
let atomic = crate::pay::xmr_to_atomic(amount).ok()?;
Some((atomic, memo))
}
pub fn parse_slash(raw: &str) -> Option<WipeKind> {
match parse_cmd(raw) {
Some(SlashCmd::Wipe(k)) => Some(k),
_ => None,
}
}
pub fn wipe_screen_text(kind: WipeKind) -> &'static str {
match kind {
WipeKind::Messages => {
"Wipe chat and payments history?\n\
Identity key and friends stay.\n\
Not a forensic erase.\n\
Type WIPE to confirm Esc to cancel"
}
WipeKind::All => {
"Wipe ALL local data?\n\
This deletes your identity key. You become a new person.\n\
Type WIPEALL to confirm Esc to cancel"
}
}
}
#[derive(Debug)]
pub struct WipePrompt {
expected: &'static str,
buf: String,
}
impl WipePrompt {
pub fn messages() -> Self {
Self {
expected: "WIPE",
buf: String::new(),
}
}
pub fn all() -> Self {
Self {
expected: "WIPEALL",
buf: String::new(),
}
}
pub fn on_esc(&self) -> WipeDecision {
WipeDecision::Cancel
}
pub fn on_char(&mut self, c: char) -> WipeDecision {
if c == '\n' {
return WipeDecision::Pending;
}
if c == '\u{8}' {
self.buf.pop();
return WipeDecision::Pending;
}
if !c.is_ascii_alphabetic() {
return WipeDecision::Pending;
}
self.buf.push(c);
if self.buf == self.expected {
WipeDecision::Confirm
} else {
WipeDecision::Pending
}
}
pub fn typed(&self) -> &str {
&self.buf
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotateDecision {
Pending,
Confirm,
Cancel,
}
#[derive(Debug, Default)]
pub struct RotatePrompt {
buf: String,
}
impl RotatePrompt {
pub fn new() -> Self {
Self::default()
}
pub fn on_esc(&self) -> RotateDecision {
RotateDecision::Cancel
}
pub fn on_char(&mut self, c: char) -> RotateDecision {
if c == '\n' {
return RotateDecision::Pending;
}
if c == '\u{8}' {
self.buf.pop();
return RotateDecision::Pending;
}
if !c.is_ascii_alphabetic() {
return RotateDecision::Pending;
}
self.buf.push(c);
if self.buf == "ROTATE" {
RotateDecision::Confirm
} else {
RotateDecision::Pending
}
}
pub fn typed(&self) -> &str {
&self.buf
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuitDecision {
Pending,
ClearAndQuit,
Quit,
Cancel,
}
#[derive(Debug, Default)]
pub struct QuitPrompt {
buf: String,
}
impl QuitPrompt {
pub fn new() -> Self {
Self::default()
}
pub fn on_esc(&self) -> QuitDecision {
QuitDecision::Cancel
}
pub fn on_char(&mut self, c: char) -> QuitDecision {
if c == '\n' {
return match self.buf.as_str() {
"CLEAR" => QuitDecision::ClearAndQuit,
"QUIT" => QuitDecision::Quit,
_ => QuitDecision::Pending,
};
}
if c == '\u{8}' {
self.buf.pop();
return QuitDecision::Pending;
}
if !c.is_ascii_alphabetic() {
return QuitDecision::Pending;
}
self.buf.push(c);
QuitDecision::Pending
}
pub fn typed(&self) -> &str {
&self.buf
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackupKind {
Backup,
Restore,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackupDecision {
Pending,
Confirm,
Cancel,
}
#[derive(Debug)]
pub struct BackupPrompt {
expected: &'static str,
buf: String,
}
impl BackupPrompt {
pub fn backup() -> Self {
Self {
expected: "BACKUP",
buf: String::new(),
}
}
pub fn restore() -> Self {
Self {
expected: "RESTORE",
buf: String::new(),
}
}
pub fn on_esc(&self) -> BackupDecision {
BackupDecision::Cancel
}
pub fn on_char(&mut self, c: char) -> BackupDecision {
if c == '\n' {
return BackupDecision::Pending;
}
if c == '\u{8}' {
self.buf.pop();
return BackupDecision::Pending;
}
if !c.is_ascii_alphabetic() {
return BackupDecision::Pending;
}
self.buf.push(c);
if self.buf == self.expected {
BackupDecision::Confirm
} else {
BackupDecision::Pending
}
}
pub fn typed(&self) -> &str {
&self.buf
}
}
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
/// plus the first entry, kept across the second prompt of the backup flow.
///
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
/// value to be dropped, and the wrapper covers the paths that cannot call it
/// (Ctrl-Q, a panic).
pub struct PassphraseEntry {
first: Option<Zeroizing<String>>,
buf: Zeroizing<String>,
}
impl Default for PassphraseEntry {
fn default() -> Self {
Self {
first: None,
buf: Zeroizing::new(String::new()),
}
}
}
impl PassphraseEntry {
pub fn new() -> Self {
Self::default()
}
/// Second prompt of the backup flow: the first passphrase was already typed.
pub fn with_first(first: &str) -> Self {
Self {
first: Some(Zeroizing::new(first.to_string())),
..Self::default()
}
}
pub fn push(&mut self, c: char) {
self.buf.push(c);
}
pub fn backspace(&mut self) {
self.buf.pop();
}
/// What the screen echoes back — the passphrase itself is not drawn.
pub fn buf(&self) -> &str {
self.buf.as_str()
}
pub fn first(&self) -> Option<&str> {
self.first.as_deref().map(String::as_str)
}
/// Take the typed passphrase for submission, leaving this entry empty.
pub fn take_buf(&mut self) -> Zeroizing<String> {
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
}
/// Take the first-passphrase copy for the confirm comparison.
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
self.first.take()
}
/// Wipe both buffers: the screen is done with them.
pub fn close(&mut self) {
self.buf.zeroize();
if let Some(first) = self.first.as_mut() {
first.zeroize();
}
self.first = None;
}
}
pub fn backup_screen_text() -> &'static str {
"Write encrypted identity backup?\n\
This file is your identity secret. Treat it like the database.\n\
Onion (locator) is not included.\n\
Type BACKUP to confirm Esc to cancel"
}
pub fn restore_screen_text() -> &'static str {
"Restore identity from backup?\n\
This overwrites your self keys. It does not rewrite the roster.\n\
You may become a different person with old friends.\n\
Type RESTORE to confirm Esc to cancel"
}
pub fn restore_terminal() {
ratatui::restore();
}
pub fn run(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<AppExit, String> {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
restore_terminal();
prev(info);
}));
let mut app = App::new(node, rt)?;
let mut terminal = ratatui::init();
let result = app.run(&mut terminal);
restore_terminal();
result
}
struct App {
node: Arc<Node>,
rt: tokio::runtime::Handle,
screen: Screen,
friends: Vec<Friend>,
selected: usize,
me_fp: String,
me_onion: String,
alert: Option<String>,
status_note: Option<String>,
composer: String,
focus: Pane,
help_open: bool,
who_open: bool,
chat_scroll: u16,
job_rx: Option<mpsc::Receiver<String>>,
/// In-flight chain-status probe. The draw path only reprints the last
/// answer; this is what asks again.
chain_probe_rx: Option<mpsc::Receiver<()>>,
/// When the last probe was started. `None` means one is due now.
chain_probe_at: Option<Instant>,
/// Tests set this to zero so a second height is asked immediately.
chain_status_every: Duration,
}
enum Screen {
Main,
Share {
payload: String,
},
Paste {
buf: String,
err: Option<String>,
},
Approve {
payload: QrPayload,
},
Rotate {
prompt: RotatePrompt,
},
RotatePrekey {
prompt: RotatePrompt,
},
Wipe {
kind: WipeKind,
prompt: WipePrompt,
},
Profile {
editor: ProfileEditor,
},
ConfirmKeys {
kind: BackupKind,
path: String,
prompt: BackupPrompt,
},
Passphrase {
kind: BackupKind,
path: String,
entry: PassphraseEntry,
},
Wallet {
receive_addr: String,
balance: String,
transfers: Vec<wallet::TransferRow>,
qr_modal: Option<QrModal>,
},
WalletSetup(WalletSetup),
/// F7: configure the wallet RPC endpoint and the chain source on screen.
/// A snapshot like the other editors — see `WalletSetupConfigState`.
WalletSetupConfig {
state: WalletSetupConfigState,
},
/// `p` on Main (roster or chat): the peer-scoped history from
/// `Node::list_payments`. Holds a snapshot, so a resize re-fits it and a
/// repaint never re-reads the store mid-frame. An empty peer is the
/// no-friend state — the screen says so, it does not pretend "no history".
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,
},
}
enum WalletSetup {
CreateWarn { typed: String },
CreatePass { entry: PassphraseEntry },
CreateSeed { seed: Zeroizing<String>, typed: String },
ImportSeed { buf: Zeroizing<String> },
/// The optional seed offset passphrase, asked between the seed and the
/// wallet-file passphrase. It is a second spend secret mixed into the seed
/// at restore time, so it needs its own two-prompt entry (not the file
/// passphrase's) and is never drawn.
ImportOffset {
seed: Zeroizing<String>,
entry: PassphraseEntry,
},
/// Import, carrying the offset (empty means none) through both file
/// passphrase prompts, including the mismatch path, which zeroizes both
/// secrets.
ImportPass {
seed: Zeroizing<String>,
offset: Zeroizing<String>,
entry: PassphraseEntry,
},
/// A restore that used an offset: the app keeps neither the offset nor a
/// copy of the pasted words, so this one notice is all the user gets. The
/// wallet file already exists; `Esc` does not leave this screen and only
/// `SEEN` opens the wallet.
ImportOffsetSeen {
typed: String,
},
/// The wallet file the child is pointed at is not open because this install
/// has no passphrase for it. Same prompt idiom as the create path: one
/// hidden entry, `Enter` submits, `Esc` cancels, and the buffer is zeroized
/// on every exit.
UnlockPass {
filename: String,
entry: PassphraseEntry,
},
}
/// Which chain source the F7 picker is on — the four cases [`ChainSource`]
/// models, in the order `space` cycles them. `InProcessCuprate` is set on F6;
/// it is here so an F7 save does not silently overwrite it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SetupSource {
ReceiveOnly,
Local,
Remote,
InProcess,
}
impl SetupSource {
fn next(self) -> Self {
match self {
Self::ReceiveOnly => Self::Local,
Self::Local => Self::Remote,
Self::Remote => Self::InProcess,
Self::InProcess => Self::ReceiveOnly,
}
}
/// Does the app spawn the wallet child for this source itself?
///
/// Both local cases are app-owned: `ChainSource::Local` (this box's
/// `monerod`) and `ChainSource::InProcessCuprate` (in this app) bring up a
/// `monero-wallet-rpc` of the app's own, with generated creds on a port it
/// picked, so the `url`/`login` rows describe no endpoint the app dials.
fn is_app_owned(self) -> bool {
matches!(self, Self::Local | Self::InProcess)
}
/// The chain source's own label. Every case spells itself out — colour is
/// never the only signal. `WalletSetupConfigState::chain_display` adds what
/// this build can actually do with it.
fn word(self) -> &'static str {
match self {
Self::ReceiveOnly => "receive-only · no chain, no spend",
Self::Local => "local node · this box spawns monerod",
Self::Remote => "remote daemon · one you run elsewhere",
Self::InProcess => "in-process node · cuprate in this app",
}
}
}
/// Row indices on the F7 screen. `Tab` cycles them in this order.
const SETUP_ROW_URL: usize = 0;
const SETUP_ROW_LOGIN: usize = 1;
const SETUP_ROW_NO_SPEND: usize = 2;
const SETUP_ROW_CHAIN: usize = 3;
const SETUP_ROW_DAEMON: usize = 4;
const SETUP_ROW_MONEROD: usize = 5;
const SETUP_ROW_DATADIR: usize = 6;
const SETUP_ROW_PRUNE: usize = 7;
const SETUP_ROW_NETWORK: usize = 8;
const SETUP_ROWS: usize = 9;
/// The F7 screen's draft: plain data taken once when the screen opens
/// (`Node::wallet_config` plus `Node::wallet_child_config`), never a handle onto
/// `Node`, so a repaint can never re-read the store mid-frame.
///
/// `rpc_login` is the one secret on this screen. It is a `Zeroizing<String>`,
/// the login row renders a fixed mask rather than the value, and there is a
/// single exit path (Esc), which wipes it by hand.
#[derive(Clone)]
pub struct WalletSetupConfigState {
field: usize,
rpc_url: String,
rpc_login: Zeroizing<String>,
no_spend: bool,
source: SetupSource,
/// `host:port` for the remote daemon.
daemon: String,
monerod_bin: String,
/// Chain datadir for a local node (spawned `monerod` or in-process Cuprate).
/// Prefilled with the path the node already uses, so a save that leaves it
/// alone keeps the chain where it is.
datadir: String,
prune: bool,
/// The chain row was changed on this screen. An untouched row is not
/// written, so an in-process Cuprate source survives an F7 save.
chain_touched: bool,
cuprate_network: ChainNetwork,
/// The last save / test answer, display-ready, never a secret.
note: Option<String>,
/// The live node/child line. Filled on open, by `Ctrl-R`, and by the
/// chain-status poll while this screen is showing. Taken from
/// `Node::wallet_child_status`, never inferred from the draft above.
status: Option<String>,
}
/// `Debug` is written by hand and redacts the login. Nothing in the app prints
/// this state today; the point is that nothing can, by accident — a `dbg!` or a
/// panic message must not be a way to read the one secret the screen holds.
impl std::fmt::Debug for WalletSetupConfigState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletSetupConfigState")
.field("field", &self.field)
.field("rpc_url", &self.rpc_url)
.field(
"rpc_login",
&if self.rpc_login.is_empty() {
"(none)"
} else {
"(hidden)"
},
)
.field("no_spend", &self.no_spend)
.field("source", &self.source)
.field("daemon", &self.daemon)
.field("monerod_bin", &self.monerod_bin)
.field("datadir", &self.datadir)
.field("prune", &self.prune)
.field("chain_touched", &self.chain_touched)
.field("cuprate_network", &self.cuprate_network)
.field("note", &self.note)
.field("status", &self.status)
.finish()
}
}
impl WalletSetupConfigState {
/// Prefill from the store: the stored wallet config, or the env-derived one
/// (`Node::wallet_config` is the migration path), and the stored chain
/// source.
pub fn from_node(node: &Node) -> Self {
let wallet = node.wallet_config();
let child = node.wallet_child_config();
let mut state = Self {
field: SETUP_ROW_URL,
rpc_url: wallet.as_ref().map(|c| c.rpc_url.clone()).unwrap_or_default(),
rpc_login: wallet
.as_ref()
.map(|c| c.rpc_login.clone())
.unwrap_or_else(|| Zeroizing::new(String::new())),
no_spend: wallet.as_ref().map(|c| c.no_spend).unwrap_or(false),
source: SetupSource::ReceiveOnly,
daemon: format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"),
monerod_bin: "monerod".to_string(),
// The default a save would use if the user never types one; a stored
// local/in-process source overwrites it below with its real path.
datadir: node.local_chain_datadir(false).display().to_string(),
prune: false,
chain_touched: false,
cuprate_network: ChainNetwork::Mainnet,
note: None,
status: None,
};
match &child.source {
ChainSource::None => {}
ChainSource::Local {
monerod_bin,
datadir,
prune,
} => {
state.source = SetupSource::Local;
state.monerod_bin = monerod_bin.display().to_string();
state.datadir = datadir.display().to_string();
state.prune = *prune;
}
ChainSource::Remote { host, port } => {
state.source = SetupSource::Remote;
state.daemon = format!("{host}:{port}");
}
ChainSource::InProcessCuprate {
datadir,
network,
prune,
} => {
state.source = SetupSource::InProcess;
state.datadir = datadir.display().to_string();
state.prune = *prune;
state.cuprate_network = *network;
}
}
state
}
/// Read the live node/child line into the screen. The poll and `Ctrl-R`
/// call this after a probe, so the row is what the node answered, never
/// what the draft above it claims.
pub fn refresh_status(&mut self, node: &Node) {
let line = node.wallet_child_status().line();
self.status = Some(if line.is_empty() {
"node not configured · pick a chain source and ctrl-s".to_string()
} else {
format!("node {line}")
});
}
/// The one secret in this state goes away with the screen, on purpose.
fn close(&mut self) {
self.rpc_login.zeroize();
}
fn next_field(&mut self) {
self.field = (self.field + 1) % SETUP_ROWS;
}
fn prev_field(&mut self) {
self.field = (self.field + SETUP_ROWS - 1) % SETUP_ROWS;
}
/// Characters reach a text row only; the toggle and picker rows answer
/// `space`.
fn push(&mut self, c: char) {
if c == '\n' {
return;
}
match self.field {
SETUP_ROW_URL => self.rpc_url.push(c),
SETUP_ROW_LOGIN => self.rpc_login.push(c),
SETUP_ROW_DAEMON => self.daemon.push(c),
SETUP_ROW_MONEROD => self.monerod_bin.push(c),
SETUP_ROW_DATADIR => self.datadir.push(c),
_ => {}
}
}
fn backspace(&mut self) {
match self.field {
SETUP_ROW_URL => self.rpc_url.pop(),
SETUP_ROW_LOGIN => self.rpc_login.pop(),
SETUP_ROW_DAEMON => self.daemon.pop(),
SETUP_ROW_MONEROD => self.monerod_bin.pop(),
SETUP_ROW_DATADIR => self.datadir.pop(),
_ => None,
};
}
/// A typed secret is easier to clear than to backspace: the login row never
/// shows what is in it, so `Ctrl-U` has to exist.
fn clear_field(&mut self) {
match self.field {
SETUP_ROW_URL => self.rpc_url.clear(),
SETUP_ROW_LOGIN => self.rpc_login.zeroize(),
SETUP_ROW_DAEMON => self.daemon.clear(),
SETUP_ROW_MONEROD => self.monerod_bin.clear(),
SETUP_ROW_DATADIR => self.datadir.clear(),
_ => {}
}
}
fn space(&mut self) {
match self.field {
SETUP_ROW_NO_SPEND => self.no_spend = !self.no_spend,
SETUP_ROW_CHAIN => {
self.source = self.source.next();
self.chain_touched = true;
}
SETUP_ROW_PRUNE => {
self.prune = !self.prune;
self.chain_touched = true;
}
// The in-process node's network, which F6's `1`/`2`/`3` used to own:
// moving the chain picker here must not lose the choice.
SETUP_ROW_NETWORK => {
self.cuprate_network = match self.cuprate_network {
ChainNetwork::Mainnet => ChainNetwork::Testnet,
ChainNetwork::Testnet => ChainNetwork::Mainnet,
};
self.chain_touched = true;
}
SETUP_ROW_URL => self.rpc_url.push(' '),
SETUP_ROW_LOGIN => self.rpc_login.push(' '),
SETUP_ROW_DAEMON => self.daemon.push(' '),
SETUP_ROW_MONEROD => self.monerod_bin.push(' '),
SETUP_ROW_DATADIR => self.datadir.push(' '),
_ => {}
}
}
/// Persist the draft through the node's own validators and answer with the
/// line the status row shows. Nothing is written by hand here: a rejected
/// form leaves the running wallet and the stored chain source untouched.
///
/// Both halves are attempted even when one is refused — a wallet-RPC refusal
/// must not silently drop a chain source the user just picked — and the
/// answer names each half, so one line shape covers every outcome.
fn save(&mut self, node: &Node) -> String {
let wallet = self.save_wallet_config(node);
let chain = self.save_chain_source(node);
if wallet.is_ok() && chain.is_ok() {
return "saved · not dialled yet — ctrl-s starts it, ctrl-t tests the endpoint"
.to_string();
}
format!(
"not saved · {} · {}",
saved_half("wallet config", &wallet),
saved_half("chain source", &chain)
)
}
/// The wallet RPC half of a save.
///
/// An app-owned chain source (see [`SetupSource::is_app_owned`]) brings up
/// its own `monero-wallet-rpc`: the child generates its own creds and port,
/// and `Node::start_wallet_child_with` replaces the stored client after the
/// spawn, so an empty `url` describes an endpoint the app never dials and
/// must not veto the write. `Wallet::from_config` keeps refusing an empty
/// endpoint — that is the externally run RPC path, where it is the truth.
fn save_wallet_config(&self, node: &Node) -> Result<(), String> {
if self.rpc_url.trim().is_empty() && self.source.is_app_owned() {
return Ok(());
}
let cfg = WalletConfig::new(&self.rpc_url, self.rpc_login.as_str(), self.no_spend);
node.wallet_save_config(&cfg)
}
/// The chain-source half of a save. `Ok(())` with nothing written is the
/// untouched in-process row: it keeps whatever F6 stored.
fn save_chain_source(&self, node: &Node) -> Result<(), String> {
match self.source {
SetupSource::ReceiveOnly => node.set_receive_only(),
SetupSource::Local => node.set_local_monerod_at(
Path::new(&self.monerod_bin),
Path::new(&self.datadir),
self.prune,
),
SetupSource::Remote => match parse_daemon_addr(&self.daemon) {
Some((host, port)) => node.set_remote_daemon(&host, port),
None => Err("daemon address must be host:port".to_string()),
},
SetupSource::InProcess if !self.chain_touched => Ok(()),
// Untouched: leave whatever held it before, including the in-process
// choice F6 used to own, rather than silently rewriting its datadir.
SetupSource::InProcess => node.set_in_process_cuprate(self.cuprate_network, self.prune),
}
}
/// One shot at the endpoint the user typed. There is no password in the
/// answer: `PingResult::line()` is already sanitized.
fn test_connection(&self, node: &Node, rt: &tokio::runtime::Handle) -> String {
rt.block_on(node.wallet_test_connection(&self.rpc_url, self.rpc_login.as_str()))
.line()
}
/// What the login row prints: never the value, only whether there is one.
fn login_display(&self) -> &'static str {
if self.rpc_login.is_empty() {
"(none) · type user:pass"
} else {
"hidden · set (ctrl-u clears)"
}
}
fn no_spend_display(&self) -> &'static str {
if self.no_spend {
"yes · /tip refused before any dial"
} else {
"no · this wallet can spend"
}
}
fn prune_display(&self) -> &'static str {
if self.prune {
"yes · pruned chain store"
} else {
"no · full chain store"
}
}
/// The in-process node's network row. Mainnet says it is unvalidated in the
/// same words `cuprate::TESTNET_ONLY` uses, because that is the fact a user
/// picking it needs.
fn network_display(&self) -> &'static str {
match self.cuprate_network {
ChainNetwork::Mainnet => "mainnet · unvalidated",
ChainNetwork::Testnet => "testnet",
}
}
/// The value the `chain` row prints, including the one thing this build may
/// not be able to do: without `cuprate-daemon` the in-process choice cannot
/// start anything at all, so the row says so where the choice is made rather
/// than leaving the refusal for the start (`crate::cuprate::NO_FEATURE_MSG`).
/// The choice itself is never removed — builds with the feature exist.
fn chain_display(&self) -> String {
if self.source == SetupSource::InProcess && !crate::cuprate::available() {
format!(
"{} — {}",
self.source.word(),
crate::cuprate::NO_FEATURE_MSG
)
} else {
self.source.word().to_string()
}
}
fn status_display(&self) -> String {
self.note
.clone()
.unwrap_or_else(|| "nothing saved yet · enter saves, ctrl-t tests".to_string())
}
}
/// `host:port` for the remote-daemon row. The port has to be a number; a
/// missing port is not guessed (the child would dial the wrong daemon).
fn parse_daemon_addr(raw: &str) -> Option<(String, u16)> {
let (host, port) = raw.trim().rsplit_once(':')?;
if host.trim().is_empty() {
return None;
}
let port: u16 = port.trim().parse().ok()?;
if port == 0 {
return None;
}
Some((host.trim().to_string(), port))
}
/// One half of the F7 `last` line. A success says so; a failure carries the
/// validator's own words, so both halves read the same way whichever failed.
fn saved_half(what: &str, result: &Result<(), String>) -> String {
match result {
Ok(()) => format!("{what} saved"),
Err(e) => format!("{what}: {e}"),
}
}
/// 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,
Setup,
}
/// 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.
/// `p` on Main opens peer payments when the composer is not taking the key.
/// Typing `p` in the composer still inserts the letter — the composer is the
/// default focus, and a chat has to be able to contain the letter p.
pub fn main_opens_peer_payments(focus: Pane, code: KeyCode) -> bool {
focus != Pane::Composer && matches!(code, KeyCode::Char('p'))
}
fn function_key_for(screen: &Screen, code: KeyCode) -> Option<FunctionKey> {
// A printed shortcut has to work on the screen that prints it, and a screen
// that does not name a function key must not answer one. Main names F2–F8.
// The wallet screen names F7 in its own hint. F9 is not a key.
match (screen, code) {
(Screen::Main, KeyCode::F(2)) => Some(FunctionKey::Share),
(Screen::Main, KeyCode::F(3)) => Some(FunctionKey::Paste),
(Screen::Main, KeyCode::F(4)) => Some(FunctionKey::Rotate),
(Screen::Main, KeyCode::F(5)) => Some(FunctionKey::Who),
(Screen::Main, KeyCode::F(6)) => Some(FunctionKey::Wallet),
(Screen::Main, KeyCode::F(7)) => Some(FunctionKey::Setup),
(Screen::Main, KeyCode::F(8)) => Some(FunctionKey::RotatePrekey),
(Screen::Wallet { .. }, KeyCode::F(7)) => Some(FunctionKey::Setup),
_ => None,
}
}
impl App {
fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> {
let friends = node.list_friends()?;
// A fresh install has no wallet to pick and nothing to warn about yet,
// so it starts on the main view. The spend-authority warning is not
// weakened by this: every path where a user commits to creating or
// restoring a wallet (`/wallet create`, F6 `c`, the list's create row)
// still routes into `WalletSetup::CreateWarn`. 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::Main,
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,
friends,
selected: 0,
alert: None,
status_note: None,
composer: String::new(),
focus: Pane::Composer,
help_open: false,
who_open: false,
chat_scroll: 0,
job_rx: None,
chain_probe_rx: None,
chain_probe_at: None,
chain_status_every: CHAIN_STATUS_INTERVAL,
})
}
fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<AppExit, String> {
loop {
self.drain_job();
self.pump_chain_status();
terminal.draw(|f| self.draw(f)).map_err(|e| e.to_string())?;
if !event::poll(TUI_POLL).map_err(io_err)? {
continue;
}
let Event::Key(key) = event::read().map_err(io_err)? else {
continue;
};
if key.kind != KeyEventKind::Press {
continue;
}
if key.code == KeyCode::Char('q') && key.modifiers.contains(KeyModifiers::CONTROL) {
if !matches!(self.screen, Screen::Quit { .. }) {
self.screen = Screen::Quit {
prompt: QuitPrompt::new(),
};
}
continue;
}
if let Some(exit) = self.handle_key(key)? {
return Ok(exit);
}
}
}
fn handle_key(&mut self, key: KeyEvent) -> Result<Option<AppExit>, String> {
if self.help_open {
match key.code {
KeyCode::Esc | KeyCode::Char('?') => self.help_open = false,
_ => {}
}
return Ok(None);
}
if self.who_open {
match key.code {
KeyCode::Esc | KeyCode::F(5) => self.who_open = false,
KeyCode::Char('?') => {
self.who_open = false;
self.help_open = true;
}
_ => {}
}
return Ok(None);
}
if key.code == KeyCode::Char('?') && !matches!(self.screen, Screen::Paste { .. }) {
self.help_open = true;
return Ok(None);
}
let mut wipe_confirm = None;
let mut quit_clear = None;
let mut profile_save = None;
let mut open_profile = false;
let mut pay_cmd = None;
let mut tip_cmd = None;
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;
let mut select_back = false;
let mut select_move = 0i32;
let mut select_enter = false;
// A function key a screen names has to work while that screen is open.
// Screens that name none keep the key to themselves.
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,
};
}
FunctionKey::Rotate => {
self.screen = Screen::Rotate {
prompt: RotatePrompt::new(),
};
}
FunctionKey::Who => self.who_open = true,
FunctionKey::Wallet => self.open_wallet()?,
// Main and the wallet screen both name F7. It is the node.
FunctionKey::Setup => self.open_setup_config(),
FunctionKey::RotatePrekey => {
self.screen = Screen::RotatePrekey {
prompt: RotatePrompt::new(),
};
}
}
return Ok(None);
}
match &mut self.screen {
Screen::Main => match key.code {
KeyCode::Tab => self.focus = self.focus.next(),
KeyCode::BackTab => self.focus = self.focus.prev(),
KeyCode::Up => self.nav_up(),
KeyCode::Down => self.nav_down(),
KeyCode::Esc => self.composer.clear(),
KeyCode::Backspace => {
if self.focus == Pane::Composer {
self.composer.pop();
}
}
KeyCode::Enter => match composer_enter(&self.composer) {
Some(ComposerAction::Cmd(SlashCmd::Wipe(kind))) => {
self.composer.clear();
let prompt = match kind {
WipeKind::Messages => WipePrompt::messages(),
WipeKind::All => WipePrompt::all(),
};
self.screen = Screen::Wipe { kind, prompt };
}
Some(ComposerAction::Cmd(SlashCmd::Profile)) => {
self.composer.clear();
open_profile = true;
}
Some(ComposerAction::Cmd(SlashCmd::Who)) => {
self.composer.clear();
self.who_open = true;
}
Some(ComposerAction::Cmd(SlashCmd::Pay { atomic, memo })) => {
self.composer.clear();
pay_cmd = Some((atomic, memo));
}
Some(ComposerAction::Cmd(SlashCmd::Tip { atomic, memo })) => {
self.composer.clear();
tip_cmd = Some((atomic, memo));
}
Some(ComposerAction::Cmd(SlashCmd::Backup { path })) => {
self.composer.clear();
self.screen = Screen::ConfirmKeys {
kind: BackupKind::Backup,
path,
prompt: BackupPrompt::backup(),
};
}
Some(ComposerAction::Cmd(SlashCmd::Restore { path })) => {
self.composer.clear();
self.screen = Screen::ConfirmKeys {
kind: BackupKind::Restore,
path,
prompt: BackupPrompt::restore(),
};
}
Some(ComposerAction::Cmd(SlashCmd::File { path })) => {
self.composer.clear();
file_cmd = Some(path);
}
Some(ComposerAction::Cmd(SlashCmd::WalletCreate)) => {
self.composer.clear();
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
});
}
Some(ComposerAction::Cmd(SlashCmd::WalletImport)) => {
self.composer.clear();
self.screen = Screen::WalletSetup(WalletSetup::ImportSeed {
buf: Zeroizing::new(String::new()),
});
}
Some(ComposerAction::Send(text)) => {
self.composer.clear();
chat_send = Some(text);
}
Some(ComposerAction::UnknownSlash(cmd)) => {
self.composer.clear();
self.status_note = Some(format!("unknown command {cmd}"));
}
None => {}
},
// `p` opens peer payments from the roster or the chat. The
// composer still types the letter — see `main_opens_peer_payments`.
KeyCode::Char('p')
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& main_opens_peer_payments(self.focus, key.code) =>
{
open_payments = true;
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
self.handle_main_char(c);
}
_ => {}
},
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 => {
let raw = buf.clone();
self.submit_paste(&raw)?;
}
KeyCode::Backspace => {
buf.pop();
*err = None;
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
*err = None;
}
_ => {}
},
Screen::Approve { payload } => match key.code {
KeyCode::Char('y') | KeyCode::Enter => {
let p = payload.clone();
self.accept_friend(&p)?;
}
KeyCode::Char('n') | KeyCode::Esc => self.screen = Screen::Main,
_ => {}
},
Screen::Rotate { prompt } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
if prompt.on_char(c) == RotateDecision::Confirm {
self.confirm_rotate()?;
}
}
KeyCode::Backspace => {
prompt.on_char('\u{8}');
}
_ => {}
},
Screen::RotatePrekey { prompt } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
if prompt.on_char(c) == RotateDecision::Confirm {
self.confirm_rotate_prekey()?;
}
}
KeyCode::Backspace => {
prompt.on_char('\u{8}');
}
_ => {}
},
Screen::Wipe { kind, prompt } => {
let kind = *kind;
match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
if prompt.on_char(c) == WipeDecision::Confirm {
wipe_confirm = Some(kind);
}
}
KeyCode::Backspace => {
prompt.on_char('\u{8}');
}
_ => {}
}
}
Screen::Profile { editor } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Tab => editor.on_tab(),
KeyCode::BackTab => editor.on_backtab(),
KeyCode::Backspace => editor.on_backspace(),
KeyCode::Enter => profile_save = Some(editor.on_enter()),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
editor.on_char(c);
}
_ => {}
},
Screen::ConfirmKeys { kind, path, prompt } => {
let kind = *kind;
match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
if prompt.on_char(c) == BackupDecision::Confirm {
self.screen = Screen::Passphrase {
kind,
path: path.clone(),
entry: PassphraseEntry::new(),
};
}
}
KeyCode::Backspace => {
prompt.on_char('\u{8}');
}
_ => {}
}
}
Screen::Passphrase { kind, path, entry } => match key.code {
KeyCode::Esc => {
entry.close();
self.screen = Screen::Main;
}
KeyCode::Backspace => entry.backspace(),
KeyCode::Enter => {
pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
_ => {}
},
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(),
// The node's own keys (start/stop/probe, chain source) are F7's.
// F6 is the wallet: receive, balance, transfers, create/import.
KeyCode::Char('c') => {
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
});
}
KeyCode::Char('i') => {
self.screen = Screen::WalletSetup(WalletSetup::ImportSeed {
buf: Zeroizing::new(String::new()),
});
}
_ => {}
},
Screen::WalletSetup(_) => self.handle_wallet_setup(key)?,
Screen::WalletSetupConfig { .. } => self.handle_wallet_setup_config(key),
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::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') {
QuitDecision::ClearAndQuit => quit_clear = Some(true),
QuitDecision::Quit => quit_clear = Some(false),
_ => {}
},
KeyCode::Backspace => {
prompt.on_char('\u{8}');
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
prompt.on_char(c);
}
_ => {}
},
}
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 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()?;
}
if let Some(clear) = quit_clear {
if clear {
self.node.wipe_messages()?;
}
return Ok(Some(AppExit::Quit));
}
if open_profile {
self.open_profile()?;
}
if let Some(draft) = profile_save {
self.save_profile(draft)?;
}
if let Some((atomic, memo)) = pay_cmd {
self.send_pay(&atomic, &memo)?;
}
if let Some((atomic, memo)) = tip_cmd {
self.send_tip(&atomic, &memo)?;
}
if let Some(path) = file_cmd {
self.send_file(&path)?;
}
if let Some(text) = chat_send {
self.send_chat(&text)?;
}
if let Some((kind, path, first, pass)) = pass_submit {
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
}
Ok(None)
}
fn handle_main_char(&mut self, c: char) {
if self.focus != Pane::Composer {
match c {
'1' => self.focus = Pane::Roster,
'2' => self.focus = Pane::Chat,
'3' => self.focus = Pane::Composer,
'j' => self.nav_down(),
'k' => self.nav_up(),
'g' => self.nav_top(),
'G' => self.nav_bottom(),
_ => {}
}
return;
}
self.composer.push(c);
}
fn nav_up(&mut self) {
match self.focus {
Pane::Roster => {
self.selected = self.selected.saturating_sub(1);
self.chat_scroll = u16::MAX;
}
Pane::Chat => {
self.chat_scroll = self.chat_scroll.saturating_sub(1);
}
Pane::Composer => {}
}
}
fn nav_down(&mut self) {
match self.focus {
Pane::Roster => {
if !self.friends.is_empty() {
self.selected = (self.selected + 1).min(self.friends.len() - 1);
self.chat_scroll = u16::MAX;
}
}
Pane::Chat => {
self.chat_scroll = self.chat_scroll.saturating_add(1);
}
Pane::Composer => {}
}
}
fn nav_top(&mut self) {
match self.focus {
Pane::Roster => {
self.selected = 0;
self.chat_scroll = u16::MAX;
}
Pane::Chat => self.chat_scroll = 0,
Pane::Composer => {}
}
}
fn nav_bottom(&mut self) {
match self.focus {
Pane::Roster => {
if !self.friends.is_empty() {
self.selected = self.friends.len() - 1;
self.chat_scroll = u16::MAX;
}
}
Pane::Chat => self.chat_scroll = u16::MAX,
Pane::Composer => {}
}
}
fn confirm_wipe(&mut self, kind: WipeKind) -> Result<Option<AppExit>, String> {
match kind {
WipeKind::Messages => {
self.node.wipe_messages()?;
self.status_note = Some("wiped messages".into());
self.screen = Screen::Main;
Ok(None)
}
WipeKind::All => Ok(Some(AppExit::WipeAll)),
}
}
fn submit_passphrase(
&mut self,
kind: BackupKind,
path: &str,
first: Option<&str>,
pass: &str,
) -> Result<(), String> {
match kind {
BackupKind::Backup => {
if let Some(first) = first {
if first != pass {
self.alert = Some("passphrases do not match".into());
self.screen = Screen::Main;
return Ok(());
}
match self.node.write_backup(path, pass) {
Ok(()) => {
self.status_note = Some(format!("backup written {path}"));
self.screen = Screen::Main;
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
}
} else {
self.screen = Screen::Passphrase {
kind,
path: path.to_string(),
entry: PassphraseEntry::with_first(pass),
};
}
}
BackupKind::Restore => match self.node.restore_backup(path, pass) {
Ok(()) => {
self.me_fp = to_hex(&self.node.identity_pk());
self.status_note = Some("identity restored — roster unchanged".into());
self.screen = Screen::Main;
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
},
}
Ok(())
}
fn confirm_rotate(&mut self) -> Result<(), String> {
let node = Arc::clone(&self.node);
match self.rt.block_on(node.rotate()) {
Ok(outcome) => {
self.me_onion = node.onion();
self.status_note = Some(format!(
"rotated · notified {}/{} friends",
outcome.notified, outcome.friends
));
self.open_share()
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
Ok(())
}
}
}
/// F8. Local and synchronous: nothing is pushed to peers — the new prekey
/// only travels inside a fresh signed invite — so the screen goes straight
/// to that invite (the F2 share path) for the user to hand out.
fn confirm_rotate_prekey(&mut self) -> Result<(), String> {
match self.node.rotate_prekey() {
Ok(_) => {
self.status_note =
Some("prekey rotated · friends must F3-paste your new invite".into());
self.open_share()
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
Ok(())
}
}
}
fn open_share(&mut self) -> Result<(), String> {
let payload = self.node.qr_payload()?;
self.screen = Screen::Share { payload };
Ok(())
}
/// What `F6` says on an install it cannot name a receive address for. It
/// points at this screen's own create/import keys, which exist today, rather
/// than at the in-TUI setup screen (a sibling card's work that may not have
/// landed yet): the note has to be true on every install that renders it.
const WALLET_SETUP_NOTE: &str =
"no wallet configured · c create or i import, or set ONIONWIRE_WALLET_RPC";
fn open_wallet(&mut self) -> Result<(), String> {
// An install with no wallet is a normal state on this screen, not a
// fatal one: the call degrades to an empty address and the screen's
// own create/import keys. Propagating the `Err` here ran out of
// `App::run` and out of `main`, so pressing `F6` killed the process.
let addr = match self.rt.block_on(self.node.wallet_receive_address()) {
Ok(addr) => addr,
Err(_) => {
self.status_note = Some(if self.node.wallet_status().configured {
// Configured but the call failed: the endpoint is what is
// wrong, not the absence of a wallet.
wallet::NOT_CONNECTED_MSG.to_string()
} else {
Self::WALLET_SETUP_NOTE.to_string()
});
String::new()
}
};
let balance = self.rt.block_on(self.node.wallet_balance());
let transfers = self.rt.block_on(self.node.wallet_recent_transfers(8)).unwrap_or_default();
self.screen = Screen::Wallet {
receive_addr: addr,
balance,
transfers,
qr_modal: None,
};
Ok(())
}
/// `p` on Main: 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. No selected friend
/// still opens the screen: the body says `no friend selected`, which is a
/// different statement from an empty history.
fn open_peer_payments(&mut self) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.screen = Screen::PeerPayments {
state: PeerPaymentsState::default(),
};
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(())
}
/// Enter on the wallet selection screen: `create new wallet` starts the
/// existing creation flow, and a wallet row switches the wallet child to
/// that row's file.
///
/// `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(());
};
match state.choice() {
WalletChoice::Create => {
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
});
}
WalletChoice::Open(index) => {
let opened = self.select_wallet(index);
match opened {
Ok(label) => {
// The child is pointed at the file either way; whether
// it could *open* it is a separate fact, and the one the
// user has to answer for when this install holds no
// passphrase (a wallet created before one was stored).
if self.node.wallet_child_status().needs_passphrase {
let filename = self
.node
.active_wallet_filename()
.ok()
.flatten()
.unwrap_or_default();
self.status_note = Some(format!("wallet {label} needs its passphrase"));
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
filename,
entry: PassphraseEntry::new(),
});
} else {
self.status_note = Some(format!("opened wallet {label}"));
self.screen = Screen::Main;
}
}
Err(e) => self.alert = Some(e),
}
}
}
Ok(())
}
/// 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 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<String, String> {
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) {
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 invite screen: OSC 52, so a terminal that blocks the write
/// still leaves the mouse selection as the way out. The payload never
/// touches a file.
/// 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
/// it is not.
fn wallet_ready(&mut self, is_tip: bool) -> bool {
match self
.rt
.block_on(self.node.wallet_readiness(is_tip))
.refusal()
{
Some(refusal) => {
self.status_note = Some(refusal.to_string());
false
}
None => true,
}
}
/// The wallet screen's chain-source line: the child status, plus the
/// caveat the configured source carries.
///
/// The in-process daemon is **testnet only** in this build, and this line is
/// the only place the wallet screen names the configured chain source (the
/// source itself is a stored setting), so the caveat travels with it — a
/// user who reads it as a mainnet node would be misled.
fn wallet_child_screen_line(&self) -> String {
let mut line = self.node.wallet_child_line();
if matches!(
self.node.wallet_child_config().source,
ChainSource::InProcessCuprate { .. }
) {
if !line.is_empty() {
line.push_str(" · ");
}
line.push_str(crate::cuprate::TESTNET_ONLY);
}
line
}
/// Key `s` on the wallet screen: start the app-owned wallet child. The
/// balance/address readouts refresh on the next F6 — the child's RPC is not
/// answering in the same breath — so this reports the state it reached.
fn wallet_child_start(&mut self) {
self.status_note = Some(match self.node.start_wallet_child() {
Ok(()) => self.wallet_child_note(),
Err(e) => format!("wallet child: {e}"),
});
self.prompt_for_wallet_passphrase();
}
/// A started child whose wallet file is not open: ask for the passphrase
/// instead of leaving the user with a child that answers `-13` to every
/// read. Reuses the create path's prompt.
fn prompt_for_wallet_passphrase(&mut self) {
if !self.node.wallet_child_status().needs_passphrase {
return;
}
let filename = self
.node
.active_wallet_filename()
.ok()
.flatten()
.unwrap_or_default();
self.screen = Screen::WalletSetup(WalletSetup::UnlockPass {
filename,
entry: PassphraseEntry::new(),
});
}
/// Key `x`: stop the child (idempotent) and drop back to the stored/env
/// wallet config.
fn wallet_child_stop(&mut self) {
self.status_note = Some(match self.node.stop_wallet_child() {
Ok(()) => "wallet child stopped".into(),
Err(e) => format!("wallet child: {e}"),
});
}
/// F7: open the setup screen with the stored (or env-derived) values as the
/// draft. Nothing is read from the store while the screen is open.
fn open_setup_config(&mut self) {
let mut state = WalletSetupConfigState::from_node(&self.node);
state.refresh_status(&self.node);
self.screen = Screen::WalletSetupConfig { state };
}
/// Keys on the F7 screen: `Tab` moves, `Enter` saves, `Ctrl-T` tests the
/// wallet RPC endpoint, `Ctrl-S` saves and starts the node/wallet child,
/// `Ctrl-X` stops it, `Ctrl-R` re-reads the live node line, `Ctrl-U` clears
/// the focused field, `Esc` leaves and wipes the login buffer.
fn handle_wallet_setup_config(&mut self, key: KeyEvent) {
if key.code == KeyCode::Esc {
if let Screen::WalletSetupConfig { state } = &mut self.screen {
state.close();
}
self.screen = Screen::Main;
return;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if ctrl && key.code == KeyCode::Char('t') {
let Screen::WalletSetupConfig { state } = &mut self.screen else {
return;
};
let note = state.test_connection(&self.node, &self.rt);
state.note = Some(note);
return;
}
// Start/stop go through `App`'s own child helpers so this screen and the
// wallet screen that used to own them cannot drift: same start, same
// passphrase prompt, same status line.
if ctrl && key.code == KeyCode::Char('s') {
let Screen::WalletSetupConfig { state } = &mut self.screen else {
return;
};
let note = state.save(&self.node);
state.note = Some(note);
self.wallet_child_start();
self.refresh_setup_status();
return;
}
if ctrl && key.code == KeyCode::Char('x') {
self.wallet_child_stop();
self.refresh_setup_status();
return;
}
if ctrl && key.code == KeyCode::Char('r') {
self.chain_probe_at = None;
self.kick_chain_probe();
self.refresh_setup_status();
return;
}
let Screen::WalletSetupConfig { state } = &mut self.screen else {
return;
};
match key.code {
KeyCode::Tab | KeyCode::Down => state.next_field(),
KeyCode::BackTab | KeyCode::Up => state.prev_field(),
KeyCode::Enter => {
let note = state.save(&self.node);
state.note = Some(note);
}
KeyCode::Backspace => state.backspace(),
KeyCode::Char('u') if ctrl => state.clear_field(),
KeyCode::Char(' ') => state.space(),
KeyCode::Char(c) if !ctrl => state.push(c),
_ => {}
}
}
/// Re-read the live node line into the F7 screen, if it is still the screen
/// on show. A start that needed a passphrase has already moved the app to
/// the unlock prompt, and this must not drag it back.
fn refresh_setup_status(&mut self) {
if let Screen::WalletSetupConfig { state } = &mut self.screen {
state.refresh_status(&self.node);
}
}
/// The child status line, or the copy that names what is missing.
fn wallet_child_note(&mut self) -> String {
let line = self.rt.block_on(self.node.wallet_child_refresh()).line();
if line.is_empty() {
"no wallet child configured — set a chain source first".into()
} else {
line
}
}
fn wallet_toggle_qr(&mut self) {
let Screen::Wallet {
ref mut qr_modal,
ref receive_addr,
..
} = self.screen
else {
return;
};
if let Some(modal) = qr_modal {
*qr_modal = if modal.closed {
qr_modal.take()
} else {
None
};
return;
}
let uri = if receive_addr.starts_with('4') || receive_addr.starts_with('8') {
format!("monero:{receive_addr}")
} else {
receive_addr.clone()
};
let m = match qrcode::QrCode::new(uri.as_bytes()) {
Ok(m) => m,
Err(_) => {
qr_modal.replace(QrModal {
closed: false,
matrix_rows: Vec::new(),
uri: receive_addr.clone(),
});
return;
}
};
let cols = m.to_colors();
let w = m.width();
let rows: Vec<String> = (0..w)
.map(|y| {
(0..w)
.map(|x| {
cols[y * w + x].select('█', ' ')
})
.collect()
})
.collect();
qr_modal.replace(QrModal {
closed: false,
matrix_rows: rows,
uri: receive_addr.clone(),
});
}
fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> {
let Screen::WalletSetup(setup) = &mut self.screen else {
return Ok(());
};
if key.code == KeyCode::Esc {
match setup {
// The wallet file already exists at this point, and the offset
// is not saved anywhere: Esc must not silently drop the one
// notice that says so. Only `SEEN` leaves this screen.
WalletSetup::ImportOffsetSeen { .. } => return Ok(()),
WalletSetup::CreatePass { entry } | WalletSetup::UnlockPass { entry, .. } => {
entry.close();
}
WalletSetup::ImportPass {
seed,
offset,
entry,
} => {
entry.close();
seed.zeroize();
offset.zeroize();
}
WalletSetup::ImportOffset { seed, entry } => {
entry.close();
seed.zeroize();
}
WalletSetup::CreateSeed { seed, .. } => seed.zeroize(),
WalletSetup::ImportSeed { buf } => buf.zeroize(),
WalletSetup::CreateWarn { .. } => {}
}
self.screen = Screen::Main;
return Ok(());
}
match setup {
WalletSetup::CreateWarn { typed } => match key.code {
KeyCode::Char(c) if c.is_ascii_alphabetic() => {
typed.push(c);
if typed.eq_ignore_ascii_case("SPEND") {
self.screen = Screen::WalletSetup(WalletSetup::CreatePass {
entry: PassphraseEntry::new(),
});
}
}
KeyCode::Backspace => {
typed.pop();
}
_ => {}
},
WalletSetup::CreatePass { entry } => match key.code {
KeyCode::Backspace => entry.backspace(),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
KeyCode::Enter => {
let first = entry.take_first();
let pass = entry.take_buf();
if let Some(first) = first {
if first.as_str() != pass.as_str() {
entry.close();
self.alert = Some("passphrases do not match".into());
self.screen = Screen::Main;
return Ok(());
}
match self.rt.block_on(self.node.wallet_create(pass.as_str())) {
Ok(created) => {
self.screen = Screen::WalletSetup(WalletSetup::CreateSeed {
seed: Zeroizing::new(created.seed),
typed: String::new(),
});
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
}
} else {
self.screen = Screen::WalletSetup(WalletSetup::CreatePass {
entry: PassphraseEntry::with_first(pass.as_str()),
});
}
}
_ => {}
},
WalletSetup::CreateSeed { typed, seed } => match key.code {
KeyCode::Char(c) if c.is_ascii_alphabetic() => {
typed.push(c);
if typed.eq_ignore_ascii_case("SEEN") {
seed.zeroize();
self.status_note = Some("wallet created — seed shown once".into());
return self.open_wallet();
}
}
KeyCode::Backspace => {
typed.pop();
}
_ => {}
},
WalletSetup::ImportSeed { buf } => match key.code {
KeyCode::Backspace => {
buf.pop();
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
}
KeyCode::Enter => {
let seed = std::mem::replace(buf, Zeroizing::new(String::new()));
if seed.trim().is_empty() {
self.alert = Some("seed required to import a wallet".into());
self.screen = Screen::Main;
return Ok(());
}
self.screen = Screen::WalletSetup(WalletSetup::ImportOffset {
seed,
entry: PassphraseEntry::new(),
});
}
_ => {}
},
WalletSetup::ImportOffset { seed, entry } => match key.code {
KeyCode::Backspace => entry.backspace(),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
KeyCode::Enter => {
let first = entry.take_first();
let offset = entry.take_buf();
if let Some(first) = first {
if first.as_str() != offset.as_str() {
entry.close();
seed.zeroize();
self.alert = Some("offset passphrases do not match".into());
self.screen = Screen::Main;
return Ok(());
}
entry.close();
let seed = std::mem::replace(seed, Zeroizing::new(String::new()));
self.screen = Screen::WalletSetup(WalletSetup::ImportPass {
seed,
offset,
entry: PassphraseEntry::new(),
});
} else if offset.trim().is_empty() {
// Blank Enter skips the offset: no confirm, no RPC field.
entry.close();
let seed = std::mem::replace(seed, Zeroizing::new(String::new()));
self.screen = Screen::WalletSetup(WalletSetup::ImportPass {
seed,
offset: Zeroizing::new(String::new()),
entry: PassphraseEntry::new(),
});
} else {
self.screen = Screen::WalletSetup(WalletSetup::ImportOffset {
seed: std::mem::replace(seed, Zeroizing::new(String::new())),
entry: PassphraseEntry::with_first(offset.as_str()),
});
}
}
_ => {}
},
WalletSetup::ImportPass {
entry,
seed,
offset,
} => match key.code {
KeyCode::Backspace => entry.backspace(),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
KeyCode::Enter => {
let first = entry.take_first();
let pass = entry.take_buf();
if let Some(first) = first {
if first.as_str() != pass.as_str() {
entry.close();
seed.zeroize();
offset.zeroize();
self.alert = Some("passphrases do not match".into());
self.screen = Screen::Main;
return Ok(());
}
// Empty or whitespace-only means "no offset", and the
// core then leaves the field out of the request.
let offset_arg = match offset.trim() {
"" => None,
other => Some(other),
};
let used_offset = offset_arg.is_some();
let result = self.rt.block_on(self.node.wallet_restore(
pass.as_str(),
seed.as_str(),
offset_arg,
));
seed.zeroize();
offset.zeroize();
match result {
Ok(_) => {
self.status_note = Some("wallet imported".into());
if used_offset {
// The offset is not saved anywhere: hold on
// the notice until the user types SEEN.
self.screen =
Screen::WalletSetup(WalletSetup::ImportOffsetSeen {
typed: String::new(),
});
return Ok(());
}
return self.open_wallet();
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
}
} else {
let seed = std::mem::replace(seed, Zeroizing::new(String::new()));
let offset = std::mem::replace(offset, Zeroizing::new(String::new()));
self.screen = Screen::WalletSetup(WalletSetup::ImportPass {
seed,
offset,
entry: PassphraseEntry::with_first(pass.as_str()),
});
}
}
_ => {}
},
WalletSetup::ImportOffsetSeen { typed } => match key.code {
KeyCode::Char(c) if c.is_ascii_alphabetic() => {
typed.push(c);
if typed.eq_ignore_ascii_case("SEEN") {
return self.open_wallet();
}
}
KeyCode::Backspace => {
typed.pop();
}
_ => {}
},
WalletSetup::UnlockPass { filename, entry } => match key.code {
KeyCode::Backspace => entry.backspace(),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
entry.push(c);
}
KeyCode::Enter => {
// One entry, no confirm: this passphrase is already the
// file's, and a re-type would only be a second chance to
// typo it.
let pass = entry.take_buf();
let filename = filename.clone();
match self
.node
.open_wallet_with_passphrase(&filename, pass.as_str())
{
Ok(()) => {
self.status_note = Some(format!("opened wallet {filename}"));
self.screen = Screen::Main;
}
Err(e) => {
self.alert = Some(e);
self.screen = Screen::Main;
}
}
}
_ => {}
},
}
Ok(())
}
fn submit_paste(&mut self, raw: &str) -> Result<(), String> {
match qr::decode(raw.trim()) {
Err(e) => {
self.screen = Screen::Paste {
buf: raw.to_string(),
err: Some(e.to_string()),
};
}
Ok(payload) => {
let known = self.node.get_friend(&payload.pubkey)?.is_some();
if known {
self.accept_friend(&payload)?;
} else {
self.screen = Screen::Approve { payload };
}
}
}
Ok(())
}
fn accept_friend(&mut self, payload: &QrPayload) -> Result<(), String> {
self.node.add_friend_payload(payload)?;
self.reload_friends()?;
self.screen = Screen::Main;
Ok(())
}
fn reload_friends(&mut self) -> Result<(), String> {
self.friends = self.node.list_friends()?;
if self.friends.is_empty() {
self.selected = 0;
} else {
self.selected = self.selected.min(self.friends.len() - 1);
}
self.chat_scroll = u16::MAX;
Ok(())
}
fn open_profile(&mut self) -> Result<(), String> {
let p = self.node.self_profile()?;
self.screen = Screen::Profile {
editor: ProfileEditor::new(&p.display_name, &p.bio, &p.xmr_addr),
};
Ok(())
}
fn save_profile(&mut self, draft: ProfileDraft) -> Result<(), String> {
if let Err(e) = self
.node
.set_self_profile(&draft.display_name, &draft.bio, &draft.xmr_addr)
{
self.alert = Some(e);
return Ok(());
}
self.screen = Screen::Main;
if let Some(friend) = self.friends.get(self.selected) {
let pk = friend.pubkey.clone();
match self.rt.block_on(self.node.push_self_profile(&pk)) {
Ok(()) => self.status_note = Some("profile saved · sent".into()),
Err(e) => self.status_note = Some(format!("profile send failed: {e}")),
}
} else {
self.status_note = Some("profile saved".into());
}
Ok(())
}
fn send_pay(&mut self, atomic: &str, memo: &str) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.status_note = Some("no friend selected".into());
return Ok(());
};
let pk = friend.pubkey.clone();
if !self.wallet_ready(false) {
return Ok(());
}
match self.rt.block_on(self.node.pay_invoice(&pk, atomic, memo)) {
Ok(()) => self.status_note = Some("invoice sent".into()),
Err(e) => self.status_note = Some(e),
}
Ok(())
}
fn send_tip(&mut self, atomic: &str, memo: &str) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.status_note = Some("no friend selected".into());
return Ok(());
};
let pk = friend.pubkey.clone();
if !self.wallet_ready(true) {
return Ok(());
}
match self.rt.block_on(self.node.tip(&pk, atomic, memo)) {
Ok(()) => self.status_note = Some("tip sent".into()),
Err(e) => self.status_note = Some(e),
}
Ok(())
}
fn send_file(&mut self, path: &str) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.status_note = Some("no friend selected".into());
return Ok(());
};
let pk = friend.pubkey.clone();
self.status_note = Some("sending".into());
match self
.rt
.block_on(self.node.send_file(&pk, std::path::Path::new(path)))
{
Ok(name) => self.status_note = Some(format!("sent file {name}")),
Err(e) => self.status_note = Some(format!("send failed: {e}")),
}
Ok(())
}
fn send_chat(&mut self, text: &str) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.status_note = Some("no friend selected".into());
return Ok(());
};
if self.job_rx.is_some() {
self.status_note = Some("already sending".into());
return Ok(());
}
let pk = friend.pubkey.clone();
let body = text.as_bytes().to_vec();
let node = Arc::clone(&self.node);
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
let _j = self.rt.spawn(async move {
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await {
Ok(OutboxStatus::Sent) => "sent".to_string(),
Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
});
self.job_rx = Some(rx);
Ok(())
}
fn drain_job(&mut self) {
let Some(note) = self.job_rx.as_ref().and_then(take_job_result) else {
return;
};
self.status_note = Some(note);
self.job_rx = None;
}
/// F7 and the wallet screen are the only places the chain height is drawn.
fn screen_shows_chain_status(&self) -> bool {
matches!(
self.screen,
Screen::WalletSetupConfig { .. } | Screen::Wallet { .. }
)
}
/// Ask the daemon again, off the UI thread. A probe already in flight is
/// left alone: the next poll applies it. Does nothing when no child is up,
/// so an unconfigured install never dials.
fn kick_chain_probe(&mut self) {
if self.chain_probe_rx.is_some() {
return;
}
if !self.node.wallet_child_status().running {
return;
}
let node = Arc::clone(&self.node);
let (tx, rx) = mpsc::channel();
self.chain_probe_rx = Some(rx);
self.chain_probe_at = Some(Instant::now());
let _j = self.rt.spawn(async move {
let _ = node.wallet_child_refresh().await;
let _ = tx.send(());
});
}
/// Copy a finished probe into the F7 snapshot. The wallet screen reads the
/// same atomics at draw time, so it needs no copy.
fn apply_chain_status(&mut self) {
let done = self.chain_probe_rx.as_ref().is_some_and(|rx| {
matches!(
rx.try_recv(),
Ok(()) | Err(mpsc::TryRecvError::Disconnected)
)
});
if !done {
return;
}
self.chain_probe_rx = None;
if let Screen::WalletSetupConfig { state } = &mut self.screen {
state.refresh_status(&self.node);
}
}
/// One turn of the chain-status poll: apply a finished probe, and start
/// another when the interval has elapsed and a screen is showing the line.
fn pump_chain_status(&mut self) {
self.apply_chain_status();
if !self.screen_shows_chain_status() {
return;
}
let due = self
.chain_probe_at
.is_none_or(|t| t.elapsed() >= self.chain_status_every);
if due {
self.kick_chain_probe();
}
}
fn who_body(&self) -> String {
let Some(friend) = self.friends.get(self.selected) else {
return "no friend selected\n\nEsc closes".into();
};
let profile = self.node.friend_profile(&friend.pubkey).ok().flatten();
who_overlay_text(&friend.fingerprint, &friend.onion, profile.as_ref())
}
fn draw(&self, f: &mut Frame) {
match &self.screen {
Screen::Main => self.draw_main(f),
Screen::Share { payload } => draw_share(f, payload),
Screen::Paste { buf, err } => draw_paste(f, buf, err.as_deref()),
Screen::Approve { payload } => draw_approve(f, payload),
Screen::Rotate { prompt } => draw_rotate(f, prompt.typed()),
Screen::RotatePrekey { prompt } => draw_rotate_prekey(f, prompt.typed()),
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
Screen::Profile { editor } => draw_profile(f, editor),
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
Screen::Passphrase { kind, entry, .. } => {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
Screen::Wallet {
receive_addr,
balance,
transfers,
qr_modal,
} => {
let child = self.wallet_child_screen_line();
draw_wallet(
f,
receive_addr,
balance,
transfers,
qr_modal.as_ref(),
&child,
)
}
Screen::WalletSetup(setup) => draw_wallet_setup(f, setup),
Screen::WalletSetupConfig { state } => {
let footer = status_footer_phased(
f.area().width,
&self.me_fp,
&self.me_onion,
Some(TorPhase::of(self.node.tor_state())),
self.status_note.as_deref(),
footer_hints(&self.screen),
);
draw_wallet_setup_config(f, state, &footer)
}
Screen::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)
}
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());
} else if self.who_open {
draw_text_overlay(f, "/who", &self.who_body());
}
}
fn draw_main(&self, f: &mut Frame) {
let phase = Some(TorPhase::of(self.node.tor_state()));
let (chat_lines, summary, chat_style) = self.chat_view(phase);
let rows: Vec<FriendRow> = self.friends.iter().map(friend_row).collect();
let chat_name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
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);
}
/// 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<TorPhase>) -> (Vec<String>, OutboxSummary, ChatRowStyle) {
let Some(friend) = self.friends.get(self.selected) else {
return (
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();
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(), ChatRowStyle::Error),
}
}
}
/// 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<TorPhase>,
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<ListItem> = 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()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
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<Line<'static>> {
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();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.to_vec())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// 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<TorPhase>) -> Vec<String> {
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,
/// Friend row has an ML-KEM key (v2 invite). `false` means sessions to
/// this friend are the classical `onionwire-v1` transport, and the roster
/// says so in words — no pretending it is hybrid.
pub pq: 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,
pq: friend.kem_pk.is_some(),
}
}
/// 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<TorPhase>) -> 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<TorPhase>,
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<TorPhase>,
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<TorPhase>,
status_note: Option<&str>,
hints: &str,
) -> String {
let w = width as usize;
let gap = if w >= 120 { " " } else { " " };
let help = "? help";
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
&& (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ")
{
note = format!("! {note}");
}
if !note.is_empty() {
let fixed = cell_width(&me) + cell_width(help) + 2 * cell_width(gap);
let budget = w.saturating_sub(fixed);
if cell_width(&note) > budget {
note = fit_cells(&note, budget.max(12));
}
}
let mut parts: Vec<String> = Vec::new();
if !note.is_empty() {
parts.push(note);
}
parts.push(me);
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", "");
let mut hint_tokens: Vec<&str> = extra.split_whitespace().collect();
while !hint_tokens.is_empty() {
let hint_str = hint_tokens.join(" ");
if footer_fits(&parts, &[&hint_str], help, gap, w) {
parts.push(hint_str);
break;
}
hint_tokens.remove(0);
}
parts.push(help.to_string());
let line = parts.join(gap);
if cell_width(&line) <= w {
line
} else {
fit_cells(&line, w)
}
}
fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize) -> bool {
let mut all: Vec<&str> = parts.iter().map(String::as_str).collect();
all.extend(extra.iter().copied());
all.push(help);
cell_width(&all.join(gap)) <= w
}
/// Main-screen key hints. `F6` is the wallet and `F7` is the node. They sit at
/// the tail so the compactor, which drops tokens from the front, still shows
/// both at 80 columns. There is no F9: that key was a menu that restated these.
pub fn main_footer_hints() -> &'static str {
"Tab F2 F3 F4 F5 Ctrl-Q F6 F7 ? help"
}
/// Footer hints for one focused main pane.
///
/// The status line is drawn from the focused pane's hint, so a key only in
/// `main_footer_hints` never reaches an 80-column terminal. Every pane therefore
/// names `F6` and `F7` at the tail. `p` is named only on the panes where it
/// opens peer payments — the composer types the letter, so it must not print it.
pub fn pane_footer_hints(pane: Pane) -> &'static str {
match pane {
Pane::Roster => "j k p pay F3 add F6 wallet F7 setup ? help",
Pane::Chat => "j k g G p pay F6 wallet F7 setup ? help",
Pane::Composer => "Enter send / commands F6 wallet F7 setup ? help",
}
}
fn footer_hints(screen: &Screen) -> &'static str {
match screen {
Screen::Main => main_footer_hints(),
Screen::Share { .. } => "Esc back ? help",
Screen::Paste { .. } => "Enter submit Esc back ? help",
Screen::Approve { .. } => "y accept n reject ? help",
Screen::Rotate { .. } => "type ROTATE Esc cancel ? help",
Screen::RotatePrekey { .. } => "type ROTATE Esc cancel ? help",
Screen::Wipe { kind, .. } => match kind {
WipeKind::Messages => "type WIPE Esc cancel ? help",
WipeKind::All => "type WIPEALL Esc cancel ? help",
},
Screen::Profile { .. } => "Enter save Tab field Esc cancel ? help",
Screen::ConfirmKeys { kind, .. } => match kind {
BackupKind::Backup => "type BACKUP Esc cancel ? help",
BackupKind::Restore => "type RESTORE Esc cancel ? help",
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Wallet { .. } => {
"c create i import r qr w wallets F7 node Esc back ? help"
}
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::UnlockPass { .. }) => {
"Enter submit Esc cancel ? help"
}
Screen::WalletSetup(WalletSetup::ImportOffset { entry, .. }) => {
if entry.first().is_some() {
"Enter submit Esc cancel ? help"
} else {
"blank Enter skips Esc cancel ? help"
}
}
Screen::WalletSetup(WalletSetup::ImportPass { .. }) => "Enter submit Esc cancel ? help",
Screen::WalletSetup(WalletSetup::ImportOffsetSeen { .. }) => "type SEEN ? help",
Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help",
Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help",
Screen::PeerPayments { .. } => peer_payments_footer_hint(),
Screen::WalletSetupConfig { .. } => wallet_setup_config_footer_hint(),
Screen::WalletSelect { .. } => wallet_select_footer_hint(),
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
}
}
/// 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 ? help";
/// The hint line the F7 setup screen prints, single-sourced like the other
/// screens': its frame test builds the fixture from this, so a dumped frame can
/// never show a footer the app does not render.
pub fn wallet_setup_config_footer_hint() -> &'static str {
WALLET_SETUP_CONFIG_FOOTER_HINT
}
/// The F7 screen's hint. Short on purpose: the status line already carries TOR,
/// the fingerprint and the locator, which leaves about 25 cells at 80 columns —
/// and the compactor drops tokens from the front, so `Esc back` goes first and
/// the two keys a save actually needs are the ones that survive. Tab and `?`
/// are universal and named elsewhere; `Ctrl-U` is named on the login row it
/// clears.
const WALLET_SETUP_CONFIG_FOOTER_HINT: &str = "Esc back Enter save Ctrl-T test";
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
let block = block.borders(Borders::ALL);
if ascii_chrome() {
block.border_set(ASCII_BORDERS)
} else {
block
}
}
fn themed_block(title: &str) -> Block<'_> {
apply_chrome_borders(Block::default())
.border_style(style_accent())
.title(title)
.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 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())
.block(themed_block("(o) invite")),
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<Line<'static>> {
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>) {
let inner = f.area().width.saturating_sub(2) as usize;
let shown = wrap_invite(buf, inner.max(1));
let body = paste_screen_text(&shown, err);
let style = if err.is_some() {
style_alert()
} else {
style_text()
};
f.render_widget(
Paragraph::new(body)
.style(style)
.wrap(Wrap { trim: false })
.block(themed_block("(o) paste invite")),
f.area(),
);
}
fn draw_approve(f: &mut Frame, payload: &QrPayload) {
let fp = to_hex(&payload.pubkey);
let body = format!(
"Unknown key. Add this friend?\n\nfp {}\nonion {}\n\ny accept n / Esc reject",
truncate_fp(&fp),
payload.onion
);
f.render_widget(
Paragraph::new(body)
.style(style_text())
.block(themed_block("(o) approve")),
f.area(),
);
}
fn draw_rotate(f: &mut Frame, typed: &str) {
let body = format!("{}\n\n{typed}", rotate_screen_text());
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block("(o) rotate locator")),
f.area(),
);
}
fn draw_rotate_prekey(f: &mut Frame, typed: &str) {
let body = format!("{}\n\n{typed}", prekey_screen_text());
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block("(o) rotate prekey")),
f.area(),
);
}
fn draw_wipe(f: &mut Frame, kind: WipeKind, typed: &str) {
let title = match kind {
WipeKind::Messages => "(o) wipe",
WipeKind::All => "(o) wipe all",
};
let body = format!("{}\n\n{typed}", wipe_screen_text(kind));
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block(title)),
f.area(),
);
}
fn draw_quit(f: &mut Frame, typed: &str) {
let body = format!("{}\n\n{typed}", quit_screen_text());
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block("(o) quit")),
f.area(),
);
}
fn draw_profile(f: &mut Frame, editor: &ProfileEditor) {
let labels = ["name", "bio", "xmr"];
let values = [editor.display_name(), editor.bio(), editor.xmr_addr()];
let mut body = String::from(
"Your profile (friend-visible)\nEnter saves Esc cancels Tab next field\n",
);
for (i, (label, value)) in labels.iter().zip(values).enumerate() {
let mark = if editor.field() == i { ">" } else { " " };
body.push_str(&format!("\n{mark} {label}: {value}"));
}
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block("(o) profile")),
f.area(),
);
}
fn draw_confirm_keys(f: &mut Frame, kind: BackupKind, typed: &str) {
let (title, text) = match kind {
BackupKind::Backup => ("(o) backup", backup_screen_text()),
BackupKind::Restore => ("(o) restore", restore_screen_text()),
};
let body = format!("{text}\n\n{typed}");
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block(title)),
f.area(),
);
}
fn draw_passphrase(f: &mut Frame, kind: BackupKind, second: bool, buf: &str) {
let stars: String = buf.chars().map(|_| '*').collect();
let hint = match (kind, second) {
(BackupKind::Backup, false) => "Enter passphrase",
(BackupKind::Backup, true) => "Re-enter passphrase",
(BackupKind::Restore, _) => "Enter passphrase",
};
let body = format!("{hint}\n\n{stars}\n\nEnter submit Esc cancel");
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(themed_block("(o) passphrase")),
f.area(),
);
}
/// 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 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 {
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);
let inner_w = popup.width.saturating_sub(2).max(1);
let inner_h = popup.height.saturating_sub(2);
let wrapped: u16 = text
.lines()
.map(|l| {
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);
f.render_widget(
Paragraph::new(text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(themed_block(title)),
popup,
);
}
// ---------------------------------------------------------------------------
// Cell measurement and one-line sanitizing. Shared by the wallet, the node
// screen and peer payments. `unicode-width` is not a dependency; `Span::width`
// is the same measurement the renderer truncates with.
// ---------------------------------------------------------------------------
/// Width of `s` in terminal **cells**, measured by ratatui's own text type.
///
/// CJK and emoji are double-width, combining marks zero-width, and a char
/// count gets both wrong.
pub fn cell_width(s: &str) -> usize {
ratatui::text::Span::raw(s).width()
}
/// Truncate `s` to at most `max` cells, closed with the chrome's ellipsis.
pub fn fit_cells(s: &str, max: usize) -> String {
if cell_width(s) <= max {
return s.to_string();
}
let e = ellipsis();
let el = cell_width(e);
if max <= el {
return e.chars().take(max).collect();
}
let budget = max - el;
let mut out = String::new();
let mut used = 0;
for ch in s.chars() {
let w = cell_width(&ch.to_string());
if used + w > budget {
break;
}
used += w;
out.push(ch);
}
format!("{out}{e}")
}
/// One row of untrusted text, made safe to place in a single line: control and
/// bidi characters stripped (newlines and tabs included, or they would break
/// the row) and the rest left to `fit_cells`.
fn menu_cell_text(raw: &str) -> String {
sanitize::display_text(raw.as_bytes())
.chars()
.filter(|c| !matches!(c, '\n' | '\r' | '\t'))
.collect()
}
/// Section header: the title in the accent, ruled off in the dim tone. The rule
/// glyph degrades to `-` under `ONIONWIRE_ASCII` / `NO_COLOR`.
fn menu_section_line(width: usize, title: &str) -> Line<'static> {
let used = cell_width(title) + 1;
let rule = if ascii_chrome() { "-" } else { "─" };
Line::from(vec![
Span::styled(
format!("{title} "),
style_accent().add_modifier(Modifier::BOLD),
),
Span::styled(rule.repeat(width.saturating_sub(used)), style_dim()),
])
}
// ---------------------------------------------------------------------------
// F7 wallet setup: the RPC endpoint and the chain source, on screen.
//
// Three rules, all of them load-bearing:
// * the login row never renders the login — only whether one is set;
// * the endpoint is validated by `Node::wallet_save_config` (loopback-only,
// login required) and a rejected form writes nothing;
// * a remote daemon is a trust move, and the screen says so in one line at the
// moment the user makes it.
// ---------------------------------------------------------------------------
/// One row: `> label value`, the value truncated in cells so no row can wrap.
fn setup_row_line(
width: usize,
state: &WalletSetupConfigState,
row: usize,
label: &str,
value: &str,
) -> Line<'static> {
let mark = if state.field == row { ">" } else { " " };
let value = if value.trim().is_empty() { "(none)" } else { value };
let text = fit_cells(&format!("{mark} {label:<9} {value}"), width);
let style = if state.field == row {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_text()
};
Line::from(Span::raw(text).style(style))
}
/// The F7 body, as lines. Widths are clamped with `fit_cells` (cells, not
/// chars), so every row fits the frame it is drawn in.
pub fn wallet_setup_config_lines(width: u16, s: &WalletSetupConfigState) -> Vec<Line<'static>> {
let w = width as usize;
let mut out = vec![menu_section_line(w, "WALLET RPC")];
out.push(setup_row_line(w, s, SETUP_ROW_URL, "url", &s.rpc_url));
out.push(setup_row_line(
w,
s,
SETUP_ROW_LOGIN,
"login",
s.login_display(),
));
out.push(setup_row_line(
w,
s,
SETUP_ROW_NO_SPEND,
"view-only",
s.no_spend_display(),
));
out.push(Line::default());
out.push(menu_section_line(w, "CHAIN SOURCE"));
out.push(setup_row_line(
w,
s,
SETUP_ROW_CHAIN,
"chain",
&format!("{} (space changes)", s.chain_display()),
));
if s.source == SetupSource::Remote {
out.push(Line::from(
Span::raw(fit_cells(
" a daemon you do not run sees this wallet's chain traffic",
w,
))
.style(style_dim()),
));
}
out.push(setup_row_line(w, s, SETUP_ROW_DAEMON, "daemon", &s.daemon));
out.push(setup_row_line(
w,
s,
SETUP_ROW_MONEROD,
"monerod",
&s.monerod_bin,
));
out.push(setup_row_line(
w,
s,
SETUP_ROW_DATADIR,
"datadir",
&s.datadir,
));
out.push(setup_row_line(
w,
s,
SETUP_ROW_PRUNE,
"prune",
s.prune_display(),
));
out.push(setup_row_line(
w,
s,
SETUP_ROW_NETWORK,
"network",
&format!("{} (space changes)", s.network_display()),
));
out.push(Line::default());
out.push(menu_section_line(w, "NODE"));
// What the node answered, not what the draft claims: the row is filled from
// `Node::wallet_child_status` and says so when nothing is configured yet.
out.push(Line::from(
Span::raw(fit_cells(
s.status
.as_deref()
.unwrap_or("node unknown — ctrl-r re-reads the live state"),
w,
))
.style(style_dim()),
));
// The node's own keys are named here, on the section they act on, for the
// same reason the login row names `ctrl-u`: at 80 columns the footer has
// room for one group and the status line already spends half the width.
out.push(Line::from(
Span::raw(fit_cells(wallet_setup_keys_line(), w))
.style(style_dim()),
));
out.push(Line::from(
Span::raw(fit_cells(&format!("last {}", s.status_display()), w)).style(style_dim()),
));
out
}
/// The F7 line that names start. The screen renders this on the NODE section,
/// because at 80 columns the footer has no room for it.
pub fn wallet_setup_keys_line() -> &'static str {
"keys ctrl-s save + start ctrl-x stop ctrl-r re-read"
}
/// The F7 body as plain text, for width and needle assertions.
pub fn wallet_setup_config_text(width: u16, s: &WalletSetupConfigState) -> String {
wallet_setup_config_lines(width, s)
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
/// F7: setup is a full screen like the other editors — body plus the one
/// status line every screen shares.
pub fn draw_wallet_setup_config(f: &mut Frame, state: &WalletSetupConfigState, footer: &str) {
let area = f.area();
let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
let inner = rows[0].width.saturating_sub(2);
f.render_widget(
Paragraph::new(wallet_setup_config_lines(inner, state))
.block(themed_block("(o) wallet setup · F7")),
rows[0],
);
f.render_widget(
Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()),
rows[1],
);
}
// ---------------------------------------------------------------------------
// Peer payment history: the F9 menu's `payments` row.
//
// 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<String>,
/// 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<PeerPaymentRow>,
pub error: Option<String>,
/// 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<PeerPaymentRow> = 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<Line<'static>> {
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);
// An empty peer is "no friend selected", not an empty history with a blank
// name. `p` opens this screen either way, so the frame always has a line.
if peer.is_empty() && s.rows.is_empty() {
return vec![
Line::from(vec![Span::styled(
fit_cells(" no friend selected", w.max(1)),
style_dim(),
)]),
Line::from(vec![Span::styled(
fit_cells(" select a friend, then p", w.max(1)),
style_dim(),
)]),
];
}
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<Line<'static>> = 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::<String>()
})
.collect::<Vec<_>>()
.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],
);
}
/// 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<WalletRow>,
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<String>,
}
impl WalletSelectState {
/// The list a read returned. An empty list is the first-run state.
pub fn from_rows(rows: Vec<WalletRow>) -> 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,
}
}
}
/// 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<WalletRecord>) -> Vec<WalletRow> {
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
/// 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<Line<'static>> {
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<Line<'static>> {
let w = width as usize;
let h = height as usize;
let mut out: Vec<Line<'static>> = 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::<String>()
})
.collect::<Vec<_>>()
.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";
/// 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.
pub fn osc52_copy_sequence(text: &str) -> String {
let clean = menu_cell_text(text);
let trimmed = clean.trim();
format!("\x1b]52;c;{}\x07", base64_encode(trimmed.as_bytes()))
}
/// Plain RFC 4648 base64 (standard alphabet, `=` padded). Hand-rolled because
/// this crate has no base64 dependency and the menu needs exactly one call site.
fn base64_encode(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = *chunk.get(1).unwrap_or(&0) as u32;
let b2 = *chunk.get(2).unwrap_or(&0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(ALPHABET[((n >> 18) & 63) as usize] as char);
out.push(ALPHABET[((n >> 12) & 63) as usize] as char);
out.push(if chunk.len() > 1 {
ALPHABET[((n >> 6) & 63) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
ALPHABET[(n & 63) as usize] as char
} else {
'='
});
}
out
}
fn truncate_fp(fp: &str) -> String {
let s: String = fp.chars().take(8).collect();
format!("{s}{}", ellipsis())
}
fn roster_row_text(row: &FriendRow, inner_width: u16) -> String {
let budget = (inner_width as usize).saturating_sub(2);
let stale_s = if row.stale { " stale" } else { "" };
// A legacy v1 friend has no PQ transport; say the word rather than let the
// roster imply protection it does not have.
let pq_s = if row.pq { "" } else { " classical" };
let avail = budget.saturating_sub(cell_width(stale_s) + cell_width(pq_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 {
(fit_cells(&row.label, avail), String::new())
};
fit_cells(&format!("{shown}{fp_part}{pq_s}{stale_s}"), budget)
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[derive(Clone, Debug)]
struct QrModal {
closed: bool,
matrix_rows: Vec<String>,
#[allow(dead_code)]
uri: String,
}
fn draw_wallet(
f: &mut Frame,
receive_addr: &str,
balance: &str,
transfers: &[wallet::TransferRow],
modal: Option<&QrModal>,
child: &str,
) {
let area = f.area();
if let Some(m) = modal {
// Clear behind the popup so the body does not bleed through.
f.render_widget(Clear, area);
let inner_w = area.width.saturating_sub(2).max(1);
let inner_h = area.height.saturating_sub(2).max(1);
let rows = m.matrix_rows.len().max(1);
let content_h = rows.min(inner_h as usize);
let popup_h = content_h as u16 + 2;
let popup_w = inner_w.max(6);
let x = area.x + (area.width.saturating_sub(popup_w)) / 2;
let y = area.y + (area.height.saturating_sub(popup_h)) / 2;
let popup = Rect {
x,
y,
width: popup_w,
height: popup_h,
};
f.render_widget(Clear, popup);
let mut body = String::from("receive address\nEsc or R closes\n\n");
if m.matrix_rows.is_empty() {
body.push_str("(qr error)");
} else {
for row in m.matrix_rows.iter().take(content_h) {
body.push_str(row);
body.push('\n');
}
}
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(
apply_chrome_borders(Block::default())
.border_style(style_accent())
.title("qr — monero:receive"),
),
popup,
);
return;
}
// The body needs the height, so it is the `Min` slot: it used to sit in a
// `Length(2)` slot of its own below this one, where the block's two borders
// ate both rows and the tall slot above stayed blank.
let cols = Layout::vertical([
Constraint::Length(2),
Constraint::Min(4),
Constraint::Length(1),
])
.split(area);
f.render_widget(
Paragraph::new("wallet")
.style(style_accent())
.block(pane_block_for("wallet", true)),
cols[0],
);
let mut lines: Vec<String> = wallet_screen_text(receive_addr, balance)
.lines()
.map(str::to_string)
.collect();
// Only rendered when a chain source is configured or a child was started, so
// an unconfigured install shows the same screen it always did.
if !child.is_empty() {
lines.push(String::new());
lines.push(format!(" {child}"));
}
lines.push(String::new());
lines.push("recent transfers".into());
if transfers.is_empty() {
lines.push(" (none)".into());
} else {
for t in transfers.iter().take(5) {
let xmr = crate::pay::atomic_to_xmr_str(&t.amount);
lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::<String>(), xmr));
}
}
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.block(apply_chrome_borders(Block::default()).border_style(style_border())),
cols[1],
);
f.render_widget(Paragraph::new(wallet_screen_hint()).style(style_dim()), cols[2]);
}
/// The wallet screen's receive and balance rows. The hint (`c create`) is drawn
/// under them; together they are what F6 shows.
pub fn wallet_screen_text(receive_addr: &str, balance: &str) -> String {
let addr_line = if receive_addr.is_empty() {
"no address"
} else {
receive_addr
};
format!("address\n {addr_line}\n\nbalance\n {balance}\n")
}
/// The hint the wallet screen prints. `c` creates, `F7` is the node. One source
/// so a test can pin the words the screen actually shows.
pub fn wallet_screen_hint() -> &'static str {
"c create i import r qr w wallets F7 node Esc back"
}
fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) {
let (title, body) = match setup {
WalletSetup::CreateWarn { typed } => (
"create spend wallet",
format!(
"{}\n\nType SPEND to confirm Esc to cancel\n{typed}",
wallet::SPEND_AUTHORITY_WARNING
),
),
WalletSetup::CreatePass { entry } => (
"wallet passphrase",
if entry.first().is_some() {
"re-type passphrase\n\nEnter submits Esc cancels".into()
} else {
"set a passphrase for the wallet file\n\nEnter continues Esc cancels".into()
},
),
WalletSetup::CreateSeed { seed, typed } => (
"write down this seed",
format!(
"{}\n\nthis is shown once. anyone with it can spend.\nType SEEN when you have written it down\n{typed}",
seed.as_str()
),
),
WalletSetup::ImportSeed { buf } => (
"import wallet",
format!(
"paste the 25-word seed. this is the only path that takes an existing key.\n\n{}\n\nEnter continues Esc cancels",
buf.as_str()
),
),
WalletSetup::ImportPass { entry, .. } => (
"wallet passphrase",
if entry.first().is_some() {
"re-type passphrase\n\nEnter submits Esc cancels".into()
} else {
"passphrase for the imported wallet file\n\nEnter continues Esc cancels".into()
},
),
WalletSetup::ImportOffset { entry, .. } => (
"seed offset passphrase",
if entry.first().is_some() {
"re-type offset passphrase\n\nEnter submits Esc cancels".into()
} else {
"optional. not the wallet file passphrase. blank Enter skips. a wrong offset \
opens a different wallet and does not error.\n\nEnter continues Esc cancels"
.into()
},
),
WalletSetup::ImportOffsetSeen { typed } => (
"offset not saved",
format!(
"this offset was not saved. write it down. a later seed backup is a different \
25 words that open this wallet without the offset. type SEEN\n{typed}"
),
),
WalletSetup::UnlockPass { filename, .. } => (
"wallet passphrase",
format!(
"the wallet file {filename} is not open\n\
enter its passphrase to open it (it is then remembered, sealed)\n\n\
Enter submits Esc cancels"
),
),
};
draw_text_overlay(f, title, &body);
}
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(),
}
}
/// F9 was the menu. The peer-payments screen no longer names it, so it must
/// not answer it — a printed dead key is worse, and an unanswered key that
/// the footer does not name is the other half of the same rule.
#[test]
fn f9_is_not_a_key_on_peer_payments_or_main() {
assert!(
!peer_payments_footer_hint().contains("F9"),
"peer payments still prints F9: {}",
peer_payments_footer_hint()
);
assert_eq!(function_key_for(&peer_payments_screen(), KeyCode::F(9)), None);
assert_eq!(function_key_for(&Screen::Main, KeyCode::F(9)), None);
}
/// Copy and behaviour agree: every `F<n>` 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::<u8>() 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_eq!(
named, 0,
"peer payments names a function key it should not: {hint:?}"
);
}
/// The wallet screen prints `F7 node`. That key has to open the node screen,
/// and F9 — which this screen does not print — must not be answered.
#[test]
fn the_wallet_screen_answers_f7_and_not_the_removed_menu_key() {
let screen = Screen::Wallet {
receive_addr: String::new(),
balance: String::new(),
transfers: Vec::new(),
qr_modal: None,
};
assert_eq!(
function_key_for(&screen, KeyCode::F(7)),
Some(FunctionKey::Setup)
);
assert_eq!(function_key_for(&screen, KeyCode::F(9)), None);
assert!(wallet_screen_hint().contains("F7"));
assert!(wallet_screen_hint().contains("create"));
}
/// 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]
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::*;
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
/// `String`s that sit in the heap for the life of the screen.
#[test]
fn passphrase_buffers_are_zeroizing() {
let mut entry = PassphraseEntry::new();
entry.push('x');
let _: &Zeroizing<String> = &entry.buf;
let _: &Option<Zeroizing<String>> = &entry.first;
assert_zeroize_on_drop::<Zeroizing<String>>();
}
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
/// the typed passphrase behind in its heap buffer.
#[test]
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
let mut entry = PassphraseEntry::new();
for c in "hunter2-secret".chars() {
entry.push(c);
}
assert_eq!(entry.buf(), "hunter2-secret");
let ptr = entry.buf.as_ptr();
let cap = entry.buf.capacity();
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
entry.close();
assert!(entry.buf().is_empty(), "buffer not cleared");
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
// elements, clear the length, zero the spare capacity). `entry` still
// owns that buffer, so these `cap` bytes are live memory.
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
assert!(
bytes.iter().all(|b| *b == 0),
"typed passphrase survived close(): {bytes:?}"
);
}
/// The first entry of the two-step backup flow is a secret too, and the
/// screen holds it across the second prompt.
#[test]
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
let mut entry = PassphraseEntry::with_first("first-typed");
assert_eq!(entry.first(), Some("first-typed"));
entry.close();
assert_eq!(
entry.first(),
None,
"first passphrase copy survived close()"
);
}
}
/// 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<String> {
let Screen::WalletSelect { state } = &app.screen else {
panic!("not on the wallet selection screen");
};
state
.rows
.iter()
.map(|r| r.name.clone())
.collect::<Vec<_>>()
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
/// The frame the real `App::draw` path puts on a terminal of this size.
fn frame_on(app: &App, width: u16, height: u16) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
.expect("test terminal");
term.draw(|f| app.draw(f)).expect("draw");
let buf = term.backend().buffer().clone();
let mut drawn = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
drawn.push_str(buf[(x, y)].symbol());
}
drawn.push('\n');
}
drawn
}
/// The first frame on the standard 80x24 terminal.
fn first_frame(app: &App) -> String {
frame_on(app, 80, 24)
}
/// Nothing remembered means nothing to warn about: a first run opens on the
/// main view, not on the create flow's spend-authority warning. Asserting
/// the screen alone would pass with the warning merely drawn behind Main, so
/// the second half reads the first frame the app actually renders.
#[test]
fn a_fresh_install_starts_on_main_not_the_spend_warning() {
let dir = tempfile::tempdir().unwrap();
let (app, _rt) = app(&dir.path().join("home"), &[]);
assert!(
matches!(app.screen, Screen::Main),
"a first run must start on the main view"
);
let frame = first_frame(&app);
assert!(
!flattened(&frame).contains(&flattened(wallet::SPEND_AUTHORITY_WARNING)),
"the spend-authority warning must not be on the first frame:\n{frame}"
);
}
/// Moving the entry point did not weaken the warning: `/wallet create` on a
/// fresh install still lands on `CreateWarn`, and the frame really carries
/// the spend-authority copy.
#[test]
fn the_create_flow_is_still_reachable_and_still_warns() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[]);
assert!(matches!(app.screen, Screen::Main));
for c in "/wallet create".chars() {
app.handle_key(key(KeyCode::Char(c))).expect("typed key");
}
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
matches!(
app.screen,
Screen::WalletSetup(WalletSetup::CreateWarn { .. })
),
"the create command must still warn before anything is created"
);
// The overlay is taller than its body and scrolls to its tail, so the
// 80x24 frame carries only the warning's closing words; the whole
// sentence needs a frame wide enough to hold it on one row.
let narrow = first_frame(&app);
assert!(
flattened(&narrow).contains("trust."),
"the create flow must warn on the standard frame:\n{narrow}"
);
let wide = frame_on(&app, 200, 60);
assert!(
flattened(&wide).contains(&flattened(wallet::SPEND_AUTHORITY_WARNING)),
"the spend-authority warning must be drawn on the create flow:\n{wide}"
);
}
/// 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::Main),
"a fresh install starts on the main view"
);
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"));
}
/// What the real render path puts on an 80x24 terminal — `App::draw`, not a
/// stand-in widget.
fn frame_text(app: &App) -> String {
frame_at(app, 80, 24)
}
/// The same real render path on any terminal size, so a screen that clips on
/// the standard frame is also checked where there is room to spare.
fn frame_at(app: &App, width: u16, height: u16) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
.expect("test terminal");
term.draw(|f| app.draw(f)).expect("draw");
let buf = term.backend().buffer().clone();
let mut out = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
/// Whitespace-collapsed copy of the frame with its pane borders dropped, so a
/// sentence the renderer wrapped across rows still reads as the one string
/// that produced it (a border glyph between two rows would split it).
fn flattened(frame: &str) -> String {
frame
.chars()
.filter(|c| !BORDER_GLYPHS.contains(c))
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
/// The frame with its borders and its line breaks dropped and nothing else
/// touched: a value the renderer hard-wrapped (an address wider than the
/// pane) reads as the one string again. Whitespace cannot be collapsed here,
/// because that is what would re-split the wrapped value.
fn unwrapped(frame: &str) -> String {
frame
.chars()
.filter(|c| *c != '\n' && !BORDER_GLYPHS.contains(c))
.collect()
}
const BORDER_GLYPHS: [char; 6] = ['│', '┌', '┐', '└', '┘', '─'];
/// `F6` on an install with no wallet is a normal state, not a fatal one: the
/// address call fails there by design. Propagating that `Err` ran out of
/// `App::run` and out of `main`, so pressing the key killed the process.
#[test]
fn f6_on_a_bare_install_opens_the_wallet_screen_instead_of_exiting() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[]);
// A first run opens on the create flow; the key in the bug report is
// pressed from the main view (`Esc` leaves the create prompt, and is
// harmless once a fresh install starts on `Main` itself).
app.handle_key(key(KeyCode::Esc))
.expect("leave the create flow");
assert!(matches!(app.screen, Screen::Main));
app.handle_key(key(KeyCode::F(6)))
.expect("F6 must not fail on an install with no wallet");
let Screen::Wallet { receive_addr, .. } = &app.screen else {
panic!("F6 must open the wallet screen");
};
assert!(
receive_addr.is_empty(),
"the field must be empty, not the error text: {receive_addr:?}"
);
assert!(
app.status_note
.as_deref()
.is_some_and(|n| n.contains("no wallet configured")),
"the screen must name the way forward: {:?}",
app.status_note
);
}
/// The frame the user actually gets. The node's error string never reaches
/// it, and the note is rendered on the status line of the main view — which
/// is where this screen's footer lives.
///
/// The wallet screen's own body (`address` / `balance` / `recent transfers`)
/// is pinned by the frame tests below, which used to show that body clipped
/// away on every install.
#[test]
fn f6_on_a_bare_install_never_draws_the_error_and_states_the_way_forward() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[]);
app.handle_key(key(KeyCode::Esc))
.expect("leave the create flow");
app.handle_key(key(KeyCode::F(6))).expect("F6");
let wallet_frame = frame_text(&app);
assert!(
wallet_frame.contains("wallet") && wallet_frame.contains("Esc back"),
"the F6 screen must be what is on screen: {wallet_frame}"
);
assert!(
!wallet_frame.contains("no receive address"),
"the node's error must not reach the screen: {wallet_frame}"
);
app.handle_key(key(KeyCode::Esc)).expect("back to main");
assert!(matches!(app.screen, Screen::Main));
let main_frame = frame_text(&app);
assert!(
main_frame.contains("no wallet configured"),
"the note must be rendered, not only stored: {main_frame}"
);
}
/// The control: when the node can name an address, `F6` fills the screen
/// with it exactly as before — no note, no empty field.
#[test]
fn f6_on_an_install_with_a_wallet_still_fills_the_receive_address() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]);
// Same documented mainnet standard address `tests/wallet.rs` uses.
let addr = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
app.node
.set_self_profile("", "", addr)
.expect("set profile");
app.handle_key(key(KeyCode::Esc)).expect("leave the list");
assert!(matches!(app.screen, Screen::Main));
app.handle_key(key(KeyCode::F(6))).expect("F6");
let Screen::Wallet { receive_addr, .. } = &app.screen else {
panic!("F6 must open the wallet screen");
};
assert_eq!(receive_addr, addr);
assert!(
app.status_note.is_none(),
"an address is no reason to warn: {:?}",
app.status_note
);
}
/// The wallet screen's body is the point of the screen, and it used to be
/// clipped away on every install: `draw_wallet` rendered the paragraph into
/// a `Constraint::Length(2)` slot whose two borders ate both rows, leaving
/// the `Min(4)` slot above it blank. On a bare install the address line must
/// read `no address` — and must not be replaced by the node's refusal text.
#[test]
fn the_wallet_screen_draws_its_body_on_a_bare_install() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[]);
app.handle_key(key(KeyCode::Esc))
.expect("leave the create flow");
// The same refusal `F6` swallows into a status note; it is an operator
// message for the endpoint, not the body of the screen.
let refusal = app
.rt
.block_on(app.node.wallet_receive_address())
.expect_err("an install with no wallet has no receive address");
app.handle_key(key(KeyCode::F(6))).expect("F6");
for (width, height) in [(80, 24), (120, 40), (200, 60)] {
let frame = frame_at(&app, width, height);
let flat = flattened(&frame);
for needle in [
"address",
"no address",
"balance",
"recent transfers",
"(none)",
"Esc back",
] {
assert!(
flat.contains(needle),
"the wallet body is missing {needle:?} at {width}x{height}:\n{frame}"
);
}
assert!(
!flat.contains(&flattened(&refusal)),
"the node's refusal must not stand in for the body at {width}x{height}:\n{frame}"
);
}
}
/// A configured install: the address the node hands over is what the screen
/// shows, on the standard frame and on a wide one. The address is longer than
/// 80 columns, so the standard case also pins that its wrap is not a loss.
#[test]
fn the_wallet_screen_shows_the_filled_address() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]);
// Same documented mainnet standard address `tests/wallet.rs` uses.
let addr = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
app.node
.set_self_profile("", "", addr)
.expect("set profile");
app.handle_key(key(KeyCode::Esc)).expect("leave the list");
app.handle_key(key(KeyCode::F(6))).expect("F6");
let Screen::Wallet { receive_addr, .. } = &app.screen else {
panic!("F6 must open the wallet screen");
};
assert_eq!(receive_addr, addr);
for (width, height) in [(80, 24), (200, 60)] {
let frame = frame_at(&app, width, height);
let flat = flattened(&frame);
assert!(
unwrapped(&frame).contains(addr),
"the receive address must be on screen at {width}x{height}:\n{frame}"
);
assert!(
flat.contains("recent transfers"),
"the body must run to the transfers section at {width}x{height}:\n{frame}"
);
assert!(
frame.contains("Esc back"),
"the help line must survive the taller body at {width}x{height}:\n{frame}"
);
}
}
/// An empty list is a fact the screen states, not a section it drops: the
/// transfers heading and its `(none)` row used to be off screen entirely.
#[test]
fn an_empty_transfer_list_still_names_recent_transfers() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]);
app.screen = Screen::Wallet {
receive_addr: "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge".into(),
balance: "0.000000000000".into(),
transfers: Vec::new(),
qr_modal: None,
};
for (width, height) in [(80, 24), (120, 40)] {
let frame = frame_at(&app, width, height);
assert!(
flattened(&frame).contains("recent transfers (none)"),
"an empty history must still be named at {width}x{height}:\n{frame}"
);
}
}
}
/// The optional seed-offset step sits between the pasted seed and the wallet-file
/// passphrase, and the notice it ends on is the only copy of a secret the app
/// deliberately does not keep.
#[cfg(test)]
mod wallet_offset_tests {
use super::*;
use crate::node::test_node_with_wallets;
/// The wallet is off in this harness (`test_node_with_wallets` uses
/// `Wallet::disabled()`), so the RPC step is not reachable here: these tests
/// pin the screen transitions, the locked footer strings, and the fact that a
/// mismatch never reaches the node. The request bytes are `tests/wallet.rs`.
fn app(home: &std::path::Path) -> (App, tokio::runtime::Runtime) {
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
let _guard = rt.enter();
let node = test_node_with_wallets(home, &[]);
let app = App::new(node, rt.handle().clone()).expect("app");
(app, rt)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn type_str(app: &mut App, s: &str) {
for c in s.chars() {
app.handle_key(key(KeyCode::Char(c))).expect("typed key");
}
}
fn offset_screen(seed: &str) -> Screen {
Screen::WalletSetup(WalletSetup::ImportOffset {
seed: Zeroizing::new(seed.to_string()),
entry: PassphraseEntry::new(),
})
}
/// The seed step is untouched and leads to the offset, whose first prompt
/// advertises exactly the blank-Enter skip.
#[test]
fn the_seed_step_leads_to_the_offset_step() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = Screen::WalletSetup(WalletSetup::ImportSeed {
buf: Zeroizing::new("lumber tacit lemon ivory risk".into()),
});
assert_eq!(footer_hints(&app.screen), "paste seed Enter Esc ? help");
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
matches!(
app.screen,
Screen::WalletSetup(WalletSetup::ImportOffset { .. })
),
"the seed goes to the offset prompt, not straight to the passphrase"
);
assert_eq!(
footer_hints(&app.screen),
"blank Enter skips Esc cancel ? help"
);
}
/// A blank (or whitespace-only) offset is skipped without a confirm, and the
/// passphrase step carries an empty offset — which means "no field" later.
#[test]
fn a_blank_offset_enter_skips_the_confirm() {
for blank in ["", " "] {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = offset_screen("lumber tacit lemon ivory risk");
type_str(&mut app, blank);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let Screen::WalletSetup(WalletSetup::ImportPass { offset, entry, .. }) = &app.screen
else {
panic!("a blank offset must go straight to the file passphrase");
};
assert!(offset.is_empty(), "blank {blank:?} became {offset:?}");
assert!(
entry.first().is_none(),
"a blank offset must not be confirmed"
);
}
}
/// A real offset is asked twice; the second prompt offers submit and Esc.
#[test]
fn a_non_empty_offset_is_confirmed() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = offset_screen("lumber tacit lemon ivory risk");
type_str(&mut app, "harbor-offset");
app.handle_key(key(KeyCode::Enter)).expect("enter");
let Screen::WalletSetup(WalletSetup::ImportOffset { entry, .. }) = &app.screen else {
panic!("a non-empty offset must be confirmed");
};
assert_eq!(entry.first(), Some("harbor-offset"));
assert_eq!(
footer_hints(&app.screen),
"Enter submit Esc cancel ? help"
);
}
/// A mismatch returns to the main view with the locked alert and never asks
/// the node for anything.
#[test]
fn a_mismatched_offset_never_reaches_the_node() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = offset_screen("lumber tacit lemon ivory risk");
type_str(&mut app, "harbor-offset");
app.handle_key(key(KeyCode::Enter)).expect("enter");
type_str(&mut app, "harbor-offse");
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(matches!(app.screen, Screen::Main));
assert_eq!(
app.alert.as_deref(),
Some("offset passphrases do not match")
);
}
/// The offset prompt does not echo what was typed, the same way the file
/// passphrase does not.
#[test]
fn the_offset_is_not_drawn() {
let mut entry = PassphraseEntry::new();
for c in "harbor-offset".chars() {
entry.push(c);
}
let setup = WalletSetup::ImportOffset {
seed: Zeroizing::new("lumber tacit lemon ivory risk".to_string()),
entry,
};
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24))
.expect("test terminal");
term.draw(|f| draw_wallet_setup(f, &setup)).expect("draw");
let frame = term.backend().buffer().clone();
let mut drawn = String::new();
for y in 0..frame.area.height {
for x in 0..frame.area.width {
drawn.push_str(frame[(x, y)].symbol());
}
}
assert!(
!drawn.contains("harbor-offset"),
"the offset must never be drawn: {drawn}"
);
assert!(
drawn.contains("seed offset passphrase"),
"the prompt itself is shown: {drawn}"
);
}
/// The notice is the one thing Esc cannot dismiss: the wallet file exists,
/// and neither the offset nor the pasted words are stored anywhere.
#[test]
fn esc_does_not_leave_the_offset_notice() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = Screen::WalletSetup(WalletSetup::ImportOffsetSeen {
typed: String::new(),
});
assert_eq!(footer_hints(&app.screen), "type SEEN ? help");
app.handle_key(key(KeyCode::Esc)).expect("esc");
assert!(
matches!(
app.screen,
Screen::WalletSetup(WalletSetup::ImportOffsetSeen { .. })
),
"Esc must not leave the offset notice"
);
}
/// Only `SEEN` (case-insensitively, like the create path) moves on, and it
/// moves on by opening the wallet.
#[test]
fn only_seen_leaves_the_offset_notice_for_the_wallet() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.screen = Screen::WalletSetup(WalletSetup::ImportOffsetSeen {
typed: String::new(),
});
type_str(&mut app, "see");
assert!(
matches!(
app.screen,
Screen::WalletSetup(WalletSetup::ImportOffsetSeen { .. })
),
"a prefix is not the word"
);
// The fourth letter is the one that proceeds: it opens the wallet. This
// install has none, so the screen opens address-less — the open itself
// must not fail (the same degradation `F6` needs). Nothing before the
// full word gets that far.
assert!(
app.status_note.is_none(),
"a prefix must not run any import side effect"
);
app.handle_key(key(KeyCode::Char('n')))
.expect("SEEN must open the wallet screen");
assert!(
matches!(app.screen, Screen::Wallet { .. }),
"only the full word proceeds"
);
}
}
/// F7 is the screen that puts the wallet RPC endpoint and the chain source in
/// the user's hands. These tests drive it through the real key path and the
/// real node, and read the frames the app actually paints.
#[cfg(test)]
mod wallet_setup_config_tests {
use super::*;
use crate::node::test_node_with_wallets;
fn app(home: &std::path::Path) -> (App, tokio::runtime::Runtime) {
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
let _guard = rt.enter();
let node = test_node_with_wallets(home, &[]);
let app = App::new(node, rt.handle().clone()).expect("app");
(app, rt)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn type_str(app: &mut App, s: &str) {
for c in s.chars() {
app.handle_key(key(KeyCode::Char(c))).expect("typed key");
}
}
/// The frame the real `App::draw` path paints on a terminal of this size.
fn frame_on(app: &App, width: u16, height: u16) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
.expect("test terminal");
term.draw(|f| app.draw(f)).expect("draw");
let buf = term.backend().buffer().clone();
let mut drawn = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
drawn.push_str(buf[(x, y)].symbol());
}
drawn.push('\n');
}
drawn
}
fn state_of(app: &App) -> &WalletSetupConfigState {
let Screen::WalletSetupConfig { state } = &app.screen else {
panic!("not on the F7 setup screen");
};
state
}
/// The endpoint a form types by hand: loopback, `host:port`, with a login,
/// because those are the two things `wallet_save_config` checks.
const URL: &str = "http://127.0.0.1:18083/json_rpc";
const LOGIN: &str = "ow:hunter2";
fn fill_endpoint(app: &mut App) {
type_str(app, URL);
app.handle_key(key(KeyCode::Tab)).expect("tab");
type_str(app, LOGIN);
}
/// F7 opens it, it opens on the stored values, and Esc is the way back.
#[test]
fn f7_opens_the_setup_screen_and_esc_leaves_it() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
assert_eq!(
function_key_for(&app.screen, KeyCode::F(7)),
Some(FunctionKey::Setup)
);
app.handle_key(key(KeyCode::F(7))).expect("F7");
assert!(
matches!(app.screen, Screen::WalletSetupConfig { .. }),
"F7 must land on the setup screen"
);
app.handle_key(key(KeyCode::Esc)).expect("esc");
assert!(matches!(app.screen, Screen::Main), "esc leaves for main");
}
/// A fresh install prefills from the environment, and the screen says where
/// the picks are: F6's in-process source is shown, not hidden.
#[test]
fn the_screen_opens_on_what_is_already_stored() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, true))
.expect("seed the store");
app.handle_key(key(KeyCode::F(7))).expect("F7");
let state = state_of(&app);
assert_eq!(state.rpc_url, URL);
assert_eq!(state.rpc_login.as_str(), LOGIN);
assert!(state.no_spend, "view-only comes back as it was stored");
assert_eq!(state.source, SetupSource::ReceiveOnly);
}
/// The login row says a password is set, never what it is. This is the one
/// secret on the screen; it must not come back out.
#[test]
fn the_setup_screen_never_renders_the_login() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, true))
.expect("seed the store");
app.handle_key(key(KeyCode::F(7))).expect("F7");
let body = wallet_setup_config_text(70, state_of(&app));
assert!(
!body.contains(LOGIN) && !body.contains("hunter2"),
"the login row rendered the login:\n{body}"
);
assert!(
body.contains("hidden"),
"the login row must say one is set:\n{body}"
);
for width in [40u16, 80, 120] {
let frame = frame_on(&app, width, 24);
assert!(
!frame.contains(LOGIN) && !frame.contains("hunter2"),
"the login leaked into the {width}-column frame:\n{frame}"
);
assert!(
frame.contains("hidden"),
"the {width}-column frame lost the login row:\n{frame}"
);
}
}
/// Enter writes exactly what the form holds — and the running wallet is not
/// dialled at save time, so a typo cannot take the wallet down with it.
#[test]
fn enter_saves_the_form_through_the_node() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let cfg = app.node.wallet_config().expect("the save is readable");
assert_eq!(cfg.rpc_url, URL);
assert_eq!(cfg.rpc_login.as_str(), LOGIN);
assert!(!cfg.no_spend);
assert!(
state_of(&app)
.note
.as_deref()
.expect("a status line")
.starts_with("saved"),
"the status row must say the save landed: {:?}",
state_of(&app).note
);
}
/// A rejected form is rejected before it is written: the store keeps what it
/// had, and the status row says why in the node's own words.
#[test]
fn a_rejected_form_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, false))
.expect("seed the store");
app.handle_key(key(KeyCode::F(7))).expect("F7");
// Row 0 is focused; replace the endpoint with a clearnet one, which the
// node refuses (the wallet RPC is loopback-only).
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, "http://198.51.100.7:18083/json_rpc");
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
state_of(&app)
.note
.as_deref()
.expect("a status line")
.starts_with("not saved"),
"a refused form must not report a save: {:?}",
state_of(&app).note
);
assert_eq!(
app.node.wallet_config().expect("still stored").rpc_url,
URL,
"a refused form must leave the stored endpoint alone"
);
}
/// A remote daemon is a trust move, and the screen says who is trusted at
/// the moment the pick is made. The address itself is validated first: a
/// daemon the child cannot dial is not written.
#[test]
fn a_remote_daemon_is_named_trusted_and_needs_an_address() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, false))
.expect("seed the store");
app.handle_key(key(KeyCode::F(7))).expect("F7");
for _ in 0..SETUP_ROW_CHAIN {
app.handle_key(key(KeyCode::Tab)).expect("tab");
}
assert_eq!(state_of(&app).field, SETUP_ROW_CHAIN, "the chain row is focused");
app.handle_key(key(KeyCode::Char(' '))).expect("space");
app.handle_key(key(KeyCode::Char(' '))).expect("space");
assert_eq!(state_of(&app).source, SetupSource::Remote);
let body = wallet_setup_config_text(78, state_of(&app));
assert!(
body.contains("a daemon you do not run"),
"the remote pick must say what it trusts:\n{body}"
);
// Row 4 is the daemon address; clear the loopback default and type junk.
app.handle_key(key(KeyCode::Tab)).expect("tab");
assert_eq!(state_of(&app).field, SETUP_ROW_DAEMON);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, "daemon.invalid");
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
state_of(&app)
.note
.as_deref()
.expect("a status line")
.contains("host:port"),
"a portless daemon must be refused with the reason: {:?}",
state_of(&app).note
);
assert_eq!(
app.node.wallet_child_config().source,
ChainSource::None,
"nothing is written until the address parses"
);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, "127.0.0.1:18089");
app.handle_key(key(KeyCode::Enter)).expect("enter");
match &app.node.wallet_child_config().source {
ChainSource::Remote { host, port } => {
assert_eq!(host, "127.0.0.1");
assert_eq!(*port, 18089);
}
other => panic!("expected the remote daemon to be stored, got {other:?}"),
}
}
/// F6 sets the in-process chain source; F7 must not silently undo it. An
/// untouched chain row is not part of the save.
#[test]
fn an_untouched_chain_row_leaves_the_in_process_source_alone() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.set_in_process_cuprate(ChainNetwork::Mainnet, false)
.expect("F6's choice");
assert!(matches!(
app.node.wallet_child_config().source,
ChainSource::InProcessCuprate { .. }
));
app.handle_key(key(KeyCode::F(7))).expect("F7");
assert_eq!(
state_of(&app).source,
SetupSource::InProcess,
"the picker opens on what F6 stored"
);
assert!(!state_of(&app).chain_touched);
fill_endpoint(&mut app);
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
matches!(
app.node.wallet_child_config().source,
ChainSource::InProcessCuprate { .. }
),
"an untouched chain row must not overwrite F6's choice"
);
assert_eq!(
app.node.wallet_config().expect("the endpoint saved").rpc_url,
URL
);
}
/// Esc is the single exit, and the login buffer goes with it: `close()`
/// wipes it by hand and the `Zeroizing` buffer wipes again on drop.
#[test]
fn esc_wipes_the_login_buffer() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
assert_eq!(state_of(&app).rpc_login.as_str(), LOGIN);
app.handle_key(key(KeyCode::Esc)).expect("esc");
assert!(matches!(app.screen, Screen::Main));
let mut state = WalletSetupConfigState::from_node(&app.node);
state.rpc_login = Zeroizing::new(LOGIN.to_string());
state.close();
assert!(
state.rpc_login.is_empty(),
"leaving the screen must wipe the login buffer"
);
}
/// Every row is clamped in cells, so no width wraps a row into the next one
/// or pushes the block border off the frame.
#[test]
fn every_row_fits_the_frame_at_any_width() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
let mut state = state_of(&app).clone();
state.rpc_url = "http://127.0.0.1:18083/json_rpc-with-a-long-tail".to_string();
state.source = SetupSource::Remote;
state.daemon = "a-very-long-daemon-name.onion:18089".to_string();
for width in [20usize, 24, 33, 40, 60, 78, 120] {
for line in wallet_setup_config_lines(width as u16, &state) {
let cells: usize = line.spans.iter().map(|s| cell_width(&s.content)).sum();
assert!(
cells <= width,
"a {cells}-cell row does not fit {width} columns: {:?}",
line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()
);
}
}
// And on the real frame, at the standard size and at the tightest.
for (w, h) in [(80u16, 24u16), (40, 24)] {
let frame = frame_on(&app, w, h);
assert!(frame.contains("wallet setup"), "the title got lost at {w}x{h}:\n{frame}");
assert!(
frame.lines().count() == h as usize,
"the frame lost rows at {w}x{h}"
);
}
}
/// F7 is named where the screen is reachable, and it survives the compact
/// footer at the standard 80 columns.
#[test]
fn the_footer_offers_f7_where_the_screen_is_reachable() {
assert!(main_footer_hints().contains("F7"));
assert!(pane_footer_hints(Pane::Roster).contains("F7"));
assert!(help_overlay_text().contains("F7"));
let dir = tempfile::tempdir().unwrap();
let (app, _rt) = app(&dir.path().join("home"));
let frame = frame_on(&app, 80, 24);
assert!(
frame.contains("F7"),
"the main footer must still name F7 at 80 columns:\n{frame}"
);
for line in frame.lines() {
assert!(
cell_width(line) <= 80,
"a footer line overran 80 columns: {line:?}"
);
}
}
/// The F7 hint is a single source: the screen renders the string the footer
/// test asserts on, so a dumped frame cannot show a footer the app does not.
#[test]
fn the_setup_screen_prints_its_own_hint() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
assert_eq!(
footer_hints(&app.screen),
wallet_setup_config_footer_hint()
);
let frame = frame_on(&app, 120, 24);
for needle in ["Enter save", "Ctrl-T test", "Esc back"] {
assert!(
frame.contains(needle),
"{needle:?} must be on the 120-column frame:\n{frame}"
);
}
// 80 columns is the default terminal and the tight one: the status line
// spends half the width on TOR, the fingerprint and the locator, so only
// the tail of the hint survives. The two keys a save needs are the tail.
let frame = frame_on(&app, 80, 24);
for needle in ["Enter save", "Ctrl-T test"] {
assert!(
frame.contains(needle),
"{needle:?} was dropped from the 80-column footer:\n{frame}"
);
}
// And the screen's own hint is what the frame was built from.
assert_eq!(
footer_hints(&app.screen),
wallet_setup_config_footer_hint()
);
}
/// F7 is named on Main and on the wallet screen, so it opens the node there.
/// F9 is not a key. Peer payments does not name F7, so F7 must not leave it.
#[test]
fn f7_is_live_where_it_is_named_and_f9_is_gone() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
assert!(matches!(app.screen, Screen::WalletSetupConfig { .. }));
app.handle_key(key(KeyCode::Esc)).expect("esc");
app.handle_key(key(KeyCode::F(9))).expect("F9");
assert!(
matches!(app.screen, Screen::Main),
"F9 must not open a menu"
);
app.handle_key(key(KeyCode::F(6))).expect("F6");
assert!(matches!(app.screen, Screen::Wallet { .. }));
app.handle_key(key(KeyCode::F(7))).expect("F7 from wallet");
assert!(
matches!(app.screen, Screen::WalletSetupConfig { .. }),
"F7 is printed on the wallet screen and must open the node"
);
app.handle_key(key(KeyCode::Esc)).expect("esc");
app.screen = Screen::PeerPayments {
state: PeerPaymentsState::from_payments("alice".to_string(), &[]),
};
app.handle_key(key(KeyCode::F(7))).expect("F7");
assert!(
matches!(app.screen, Screen::PeerPayments { .. }),
"peer payments does not name F7, so F7 must not leave it"
);
}
/// `p` on the roster opens peer payments. With no friend, the frame says so
/// rather than sitting on Main with a note that the next paint can hide.
#[test]
fn p_on_the_roster_opens_peer_payments() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.focus = Pane::Roster;
app.handle_key(key(KeyCode::Char('p'))).expect("p");
assert!(matches!(app.screen, Screen::PeerPayments { .. }));
let frame = frame_on(&app, 80, 24);
assert!(
frame.contains("no friend selected"),
"empty-friend line missing:\n{frame}"
);
assert!(!frame.contains("F9"), "dead menu key on the payments frame:\n{frame}");
// The composer still types the letter.
app.handle_key(key(KeyCode::Esc)).expect("esc");
app.focus = Pane::Composer;
app.handle_key(key(KeyCode::Char('p'))).expect("typed p");
assert!(matches!(app.screen, Screen::Main));
assert_eq!(app.composer, "p");
}
/// Real `App::draw` frames of the two screens that remain: the wallet and
/// the node. 80x24 is the floor, 120x40 the target.
#[test]
fn f6_and_f7_frames_fit_and_name_their_own_actions() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(6))).expect("F6");
for (w, h) in [(80u16, 24u16), (120, 40)] {
let frame = frame_on(&app, w, h);
println!("===== F6 WALLET {w}x{h} =====\n{frame}");
assert!(frame.contains("address"), "receive row missing at {w}x{h}:\n{frame}");
assert!(frame.contains("balance"), "balance missing at {w}x{h}:\n{frame}");
assert!(frame.contains("create"), "create missing at {w}x{h}:\n{frame}");
assert!(!frame.contains("F9"), "menu key on the wallet frame:\n{frame}");
for line in frame.lines() {
assert!(
cell_width(line) <= w as usize,
"F6 line wider than {w}: {line:?}"
);
}
}
app.handle_key(key(KeyCode::Esc)).expect("esc");
app.handle_key(key(KeyCode::F(7))).expect("F7");
for (w, h) in [(80u16, 24u16), (120, 40)] {
let frame = frame_on(&app, w, h);
println!("===== F7 NODE {w}x{h} =====\n{frame}");
assert!(
frame.contains("ctrl-s"),
"start key missing at {w}x{h}:\n{frame}"
);
assert!(!frame.contains("F9"), "menu key on the node frame:\n{frame}");
for line in frame.lines() {
assert!(
cell_width(line) <= w as usize,
"F7 line wider than {w}: {line:?}"
);
}
}
}
/// The login never leaves in a message: not in the frame, not in the app's
/// status line, not in a `PingResult::line()`, and not through `Debug`.
#[test]
fn the_login_never_leaves_in_a_message() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, false))
.expect("seed the store");
app.handle_key(key(KeyCode::F(7))).expect("F7");
app.handle_key(key(KeyCode::Enter)).expect("enter");
let state = state_of(&app);
assert_eq!(state.rpc_login.as_str(), LOGIN, "the draft really holds it");
assert!(
!format!("{state:?}").contains(LOGIN),
"Debug printed the login: {state:?}"
);
assert!(
!state.status_display().contains(LOGIN),
"the status row carried the login"
);
assert!(
!app.status_note.clone().unwrap_or_default().contains(LOGIN),
"the app's status note carried the login"
);
let answer = state.test_connection(&app.node, &app.rt);
assert!(
!answer.contains(LOGIN) && !answer.contains("hunter2"),
"the test-connection answer carried the login: {answer}"
);
assert!(
!answer.is_empty(),
"a test that answers nothing is a broken test"
);
}
/// The env vars stay optional. With no store and no env, the app still boots,
/// receive-only, and the screen is the way in: what it saves is what the next
/// boot reads.
#[test]
fn a_fresh_install_needs_no_env_vars_to_reach_a_saved_config() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let (mut fresh, _rt) = app(&home);
assert!(matches!(fresh.screen, Screen::Main), "the app still boots");
assert_eq!(
fresh.node.wallet_child_config().source,
ChainSource::None,
"receive-only is the default, and it needs no wallet at all"
);
fresh.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut fresh);
fresh.handle_key(key(KeyCode::Enter)).expect("enter");
let saved = fresh.node.wallet_config().expect("saved on screen");
assert_eq!(saved.rpc_url, URL);
assert!(fresh.node.wallet_status().configured());
// A second boot over the same home reads the screen's save: the store is
// the path that boots, not the environment.
let (next, _rt2) = app(&home);
assert_eq!(
next.node.wallet_config().expect("the save boots").rpc_url,
URL
);
}
/// A rejected form leaves the stored config exactly as it was — all three
/// fields, not just the one the test typed.
#[test]
fn a_rejected_form_leaves_the_whole_stored_config_alone() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.node
.wallet_save_config(&WalletConfig::new(URL, LOGIN, true))
.expect("seed the store");
let before = app.node.wallet_config().expect("stored");
app.handle_key(key(KeyCode::F(7))).expect("F7");
// Empty the endpoint: `wallet_save_config` refuses it.
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
// And flip a toggle on the way past, so "nothing moved" means the whole
// form, not a form that was already equal.
for _ in 0..SETUP_ROW_NO_SPEND {
app.handle_key(key(KeyCode::Tab)).expect("tab");
}
app.handle_key(key(KeyCode::Char(' '))).expect("space");
app.handle_key(key(KeyCode::Enter)).expect("enter");
let after = app.node.wallet_config().expect("still stored");
assert_eq!(after, before, "a rejected form wrote something");
assert!(after.no_spend, "the stored view-only flag is untouched");
}
/// `Tab` from wherever the form is focused until `row` has it. The tests
/// below drive the real key path, not the state directly.
fn focus_row(app: &mut App, row: usize) {
let mut guard = 0;
while state_of(app).field != row {
app.handle_key(key(KeyCode::Tab)).expect("tab");
guard += 1;
assert!(guard <= SETUP_ROWS, "row {row} is unreachable by Tab");
}
}
/// Pick the `chain` row's source by cycling it with `space`.
fn pick_source(app: &mut App, want: SetupSource) {
focus_row(app, SETUP_ROW_CHAIN);
for _ in 0..4 {
if state_of(app).source == want {
return;
}
app.handle_key(key(KeyCode::Char(' '))).expect("space");
}
panic!("the picker never reached {want:?}");
}
/// The point of the datadir row: a local node goes where the user says, not
/// where the default was. This is the node-setup path the app lacked —
/// `set_local_monerod` was reachable only from Kotlin.
#[test]
fn a_local_node_saves_the_datadir_the_user_typed() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let (mut app, _rt) = app(&home);
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
pick_source(&mut app, SetupSource::Local);
focus_row(&mut app, SETUP_ROW_MONEROD);
for _ in 0.."monerod".len() {
app.handle_key(key(KeyCode::Backspace)).expect("backspace");
}
type_str(&mut app, "/opt/monero/monerod");
let typed = home.join("chain-tank");
focus_row(&mut app, SETUP_ROW_DATADIR);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, typed.to_str().expect("utf8 path"));
app.handle_key(key(KeyCode::Enter)).expect("enter");
assert!(
state_of(&app)
.note
.as_deref()
.expect("a status line")
.starts_with("saved"),
"the save must land: {:?}",
state_of(&app).note
);
match &app.node.wallet_child_config().source {
ChainSource::Local {
monerod_bin,
datadir,
prune,
} => {
assert_eq!(monerod_bin.to_str(), Some("/opt/monero/monerod"));
assert_eq!(
datadir, &typed,
"the node must store its chain where the user said"
);
assert!(!prune);
}
other => panic!("expected a local node, got {other:?}"),
}
}
/// An empty datadir is refused rather than silently replaced with the
/// default: a store that moved without being asked looks like a vanished
/// chain, and the resync lands somewhere the user did not choose.
#[test]
fn an_empty_datadir_is_refused_and_the_source_is_not_written() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
pick_source(&mut app, SetupSource::Local);
focus_row(&mut app, SETUP_ROW_DATADIR);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app).note.as_deref().expect("a status line");
assert!(
note.contains("datadir required"),
"the refusal must name the missing field: {note}"
);
assert_eq!(
app.node.wallet_child_config().source,
ChainSource::None,
"a refused chain source must not be stored"
);
}
/// The row answers with what the node says, not with what the draft above it
/// claims: on a fresh install that is "nothing configured yet".
#[test]
fn the_node_row_shows_the_live_state_on_open() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
let status = state_of(&app)
.status
.as_deref()
.expect("the screen reads the node on open");
assert!(
status.starts_with("node"),
"the live row must be the node's answer: {status}"
);
let body = wallet_setup_config_text(78, state_of(&app));
assert!(
body.contains("not configured"),
"an unconfigured install must say so, not print a blank row:\n{body}"
);
// The node's keys are discoverable from the body: at 80 columns the
// footer has no room for them.
for needle in ["ctrl-s save + start", "ctrl-x stop", "ctrl-r re-read"] {
assert!(
body.contains(needle),
"{needle:?} must be named on the screen that uses it:\n{body}"
);
}
}
/// `Ctrl-S` is the key that actually brings the node up: it saves the form
/// and then asks the node to start. With no chain source the start refuses
/// in the node's own words and the screen stays put.
#[test]
fn ctrl_s_saves_then_reports_the_nodes_own_refusal() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL))
.expect("ctrl-s");
assert!(
state_of(&app)
.note
.as_deref()
.expect("a status line")
.starts_with("saved"),
"ctrl-s must save first: {:?}",
state_of(&app).note
);
assert_eq!(
app.node
.wallet_config()
.expect("the endpoint saved")
.rpc_url,
URL
);
let note = app.status_note.as_deref().expect("the start reported");
assert!(
note.contains("receive-only"),
"a receive-only install must be told why nothing started: {note}"
);
assert!(
matches!(app.screen, Screen::WalletSetupConfig { .. }),
"a start that needs no passphrase must leave the user on F7"
);
}
/// F6's `1`/`2`/`3` keys were also the only way to pick the in-process node's
/// network. That choice moved here with the picker instead of being lost.
#[test]
fn the_in_process_network_is_still_selectable() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
fill_endpoint(&mut app);
pick_source(&mut app, SetupSource::InProcess);
assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Mainnet);
focus_row(&mut app, SETUP_ROW_NETWORK);
let body = wallet_setup_config_text(78, state_of(&app));
assert!(
body.contains("unvalidated"),
"mainnet must say it is unvalidated before it is picked:\n{body}"
);
app.handle_key(key(KeyCode::Char(' '))).expect("space");
assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Testnet);
app.handle_key(key(KeyCode::Enter)).expect("enter");
match &app.node.wallet_child_config().source {
ChainSource::InProcessCuprate { network, .. } => assert_eq!(
*network,
ChainNetwork::Testnet,
"the network pick must reach the stored source"
),
other => panic!("expected an in-process source, got {other:?}"),
}
}
/// The app-owned chain source is the one path that needs no external wallet
/// RPC: `url`/`login` name an endpoint only `monero-wallet-rpc` uses, and on
/// this path the app spawns the child with its own generated creds and port
/// (`Node::start_wallet_child_with` replaces the stored client after the
/// spawn). An empty pair must therefore not veto the save — that refusal is
/// `Wallet::from_config`'s, and it is about an *externally run* endpoint.
#[test]
fn an_app_owned_source_saves_without_a_typed_wallet_rpc() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let (mut app, _rt) = app(&home);
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
focus_row(&mut app, SETUP_ROW_NETWORK);
app.handle_key(key(KeyCode::Char(' '))).expect("space");
assert_eq!(state_of(&app).cuprate_network, ChainNetwork::Testnet);
let state = state_of(&app);
assert!(
state.rpc_url.is_empty() && state.rpc_login.is_empty(),
"this test is only meaningful with an empty endpoint: {state:?}"
);
assert_eq!(
app.node.wallet_child_config().source,
ChainSource::None,
"nothing is stored before the save"
);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(note.starts_with("saved"), "the save must land: {note}");
match &app.node.wallet_child_config().source {
ChainSource::InProcessCuprate { network, .. } => assert_eq!(
*network,
ChainNetwork::Testnet,
"the network pick must reach the stored source"
),
other => panic!("expected the in-process source to be stored, got {other:?}"),
}
}
/// One write must not cancel the other: a wallet-config refusal still leaves
/// the chain-source write done, and the `last` line says both.
#[test]
fn a_wallet_rpc_refusal_does_not_cancel_the_chain_source_write() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::Remote);
focus_row(&mut app, SETUP_ROW_DAEMON);
app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL))
.expect("ctrl-u");
type_str(&mut app, "127.0.0.1:18089");
assert!(state_of(&app).rpc_url.is_empty());
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(
note.contains("wallet RPC endpoint required"),
"the endpoint refusal must be reported: {note}"
);
assert!(
note.contains("chain source saved"),
"the chain-source write must be reported, not dropped: {note}"
);
match &app.node.wallet_child_config().source {
ChainSource::Remote { host, port } => {
assert_eq!(host, "127.0.0.1");
assert_eq!(*port, 18089);
}
other => panic!("the remote source must still be written, got {other:?}"),
}
}
/// The other half of the same rule: a *typed* endpoint with no login is a
/// broken wallet config, and saying so is the point. The app-owned source
/// does not excuse a half-typed endpoint.
#[test]
fn a_typed_endpoint_without_a_login_is_still_refused() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
type_str(&mut app, URL);
pick_source(&mut app, SetupSource::InProcess);
app.handle_key(key(KeyCode::Enter)).expect("enter");
let note = state_of(&app)
.note
.as_deref()
.expect("a status line")
.to_string();
assert!(
note.contains("credentials"),
"a typed endpoint with no login must still be refused: {note}"
);
assert!(
app.node.wallet_config().is_none(),
"a refused endpoint must not be stored"
);
}
/// A build without `cuprate-daemon` cannot start the in-process daemon at
/// all, so the `chain` row has to say that where the choice is made rather
/// than offering one whose only answer is `cuprate::NO_FEATURE_MSG`.
#[cfg(not(feature = "cuprate-daemon"))]
#[test]
fn a_build_without_the_daemon_says_so_on_the_chain_row() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
let body = wallet_setup_config_text(200, state_of(&app));
assert!(
body.contains("in-process node"),
"the choice is still offered:\n{body}"
);
assert!(
body.contains("--features cuprate-daemon"),
"the row must name the feature this build lacks:\n{body}"
);
}
/// The same row in a build that *can* start it: no unavailable wording, and
/// the choice still reaches the store.
#[cfg(feature = "cuprate-daemon")]
#[test]
fn a_build_with_the_daemon_does_not_disown_the_in_process_choice() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(7))).expect("F7");
pick_source(&mut app, SetupSource::InProcess);
let body = wallet_setup_config_text(200, state_of(&app));
assert!(
body.contains("in-process node · cuprate in this app"),
"the row keeps the plain wording:\n{body}"
);
assert!(
!body.contains("rebuild with --features cuprate-daemon"),
"a build that can start it must not say it cannot:\n{body}"
);
}
/// F6 is the wallet again: the chain picker and the child's start/stop keys
/// moved to F7, so pressing them there changes nothing and the store is not
/// touched behind the user's back.
#[test]
fn f6_no_longer_owns_the_chain_picker_or_the_child_keys() {
let dir = tempfile::tempdir().unwrap();
let (mut app, _rt) = app(&dir.path().join("home"));
app.handle_key(key(KeyCode::F(6))).expect("F6");
assert!(matches!(app.screen, Screen::Wallet { .. }));
for c in ['s', 'x', 'p', '1', '2', '3'] {
app.handle_key(key(KeyCode::Char(c))).expect("key");
assert!(
matches!(app.screen, Screen::Wallet { .. }),
"`{c}` must not leave the wallet screen"
);
}
assert_eq!(
app.node.wallet_child_config().source,
ChainSource::None,
"keys F6 no longer owns must not write a chain source"
);
// And the footer no longer advertises them.
let footer = footer_hints(&app.screen);
assert!(
footer.contains("F7 node"),
"F6 must point at F7 for the node: {footer}"
);
assert!(
!footer.contains("1 pruned") && !footer.contains("s/x child"),
"F6 must not still advertise the keys it lost: {footer}"
);
}
/// The NODE row is a snapshot. A daemon whose height moves must show up on
/// the next poll, with no keypress — a one-shot probe at start is how the
/// row sat on a stale `sync h/target` while the chain kept moving.
#[test]
fn the_setup_screen_sync_line_follows_a_later_probe() {
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::node::tests::{fake_child_bin, mock_wallet_at, test_install_wallet};
use crate::wallet_child::ChildConfig;
use crate::wallet_child::test_support::PublishedPortHold;
let dir = tempfile::tempdir().unwrap();
let (mut app, rt) = app(&dir.path().join("home"));
// The poll interval is for the event loop. This test asks directly.
app.chain_status_every = Duration::ZERO;
let log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&log,
"sleep 30",
);
app.node
.set_wallet_child_config(&ChildConfig {
source: ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18089,
},
wallet_rpc_bin: bin,
arti_bin: std::path::PathBuf::from("arti"),
wallet_filename: "onionwire".into(),
})
.expect("set config");
// The start gate dials the port the fake was told to bind. A shell
// fake cannot bind one, so hold it here. Not 18081 — that is the
// user's live daemon when this suite runs beside it.
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
app.node.start_wallet_child().expect("start");
let height = Arc::new(AtomicU64::new(1111));
let (wallet, daemon) = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000));
test_install_wallet(&app.node, wallet);
// Readiness compares the wallet's scanned height with a daemon tip, so
// point the chain source at the stub the wallet mock returned.
let (host, port) = daemon.rsplit_once(':').expect("host:port");
app.node
.set_wallet_child_config(&ChildConfig {
source: ChainSource::Remote {
host: host.to_string(),
port: port.parse().expect("daemon port"),
},
wallet_rpc_bin: std::path::PathBuf::from("monero-wallet-rpc"),
arti_bin: std::path::PathBuf::from("arti"),
wallet_filename: "onionwire".into(),
})
.expect("point the chain source at the daemon stub");
app.handle_key(key(KeyCode::F(7))).expect("F7");
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
// A redraw alone must not invent a new probe. The number moves only
// when the poll asks again.
height.store(2222, Ordering::Relaxed);
let stale = wallet_setup_config_text(120, state_of(&app));
assert!(
stale.contains("sync 1111/9000"),
"a redraw must not skip the probe:\n{stale}"
);
assert!(
!stale.contains("sync 2222/9000"),
"the row moved without a probe:\n{stale}"
);
wait_for_sync_line(&mut app, &rt, "sync 2222/9000");
app.node.stop_wallet_child().expect("stop");
}
fn wait_for_sync_line(app: &mut App, rt: &tokio::runtime::Runtime, needle: &str) {
let deadline = std::time::Instant::now() + Duration::from_secs(3);
loop {
app.pump_chain_status();
let body = wallet_setup_config_text(120, state_of(app));
if body.contains(needle) {
return;
}
if std::time::Instant::now() > deadline {
panic!("NODE row never showed {needle}:\n{body}");
}
rt.block_on(async {
tokio::time::sleep(Duration::from_millis(20)).await;
});
}
}
}