onionwire/tests/tui_spec.rs
rust-dev 159ac57da9
wallet: in-process Cuprate chain daemon behind the cuprate-daemon feature
Phase 1 of the Cuprate integration strategy: the chain daemon can run inside
the OnionWire process instead of a spawned `monerod`. `monero-wallet-rpc` is
unchanged — it still dials the unrestricted loopback RPC on 127.0.0.1:18081,
which is the address `WalletChild::daemon_address` already returned — so no
wallet-layer code moves.

- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind a
  `cuprate-daemon` feature that is OFF by default. Cuprate's own `arti` feature
  stays off: its arti-client 0.44 cannot unify with this crate's 0.46, and the
  in-process daemon is clearnet-only, so this keeps one Tor stack in the
  process. `Cargo.lock` gains the graph; no arti 0.44 appears in it.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
  (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
  off), launches it, and owns it. Dropping the value is the teardown;
  `shutdown()` is called before the drop so the services can drain. The type
  exists in every build: without the feature `launch` fails with the feature
  name instead of silently doing nothing, so the chain-source type, its stored
  record and the picker do not fork on a cargo feature.
- src/wallet.rs: `ChainSource::InProcessCuprate { datadir }`.
- src/wallet_child.rs: starts/holds/stops the node, serializes the choice as
  `kind = "cuprate"`, and adds `chain_datadir` so the storage gate covers both
  local sources. It takes the app's Tokio handle (`with_runtime`): the launch is
  async and `start()` runs on the TUI's blocking thread.
- src/node.rs: `wallet_child_start(runtime)`, `default_in_process_chain_source`.
- src/tui.rs: a fourth picker row, its testnet caveat, the chain block copy, and
  a stop of the app-owned children on the quit path so they are not orphaned.
- tests/wallet.rs: a `cuprate-daemon`-gated end-to-end test that launches the
  node and drives get_info / get_height / get_block through the typed daemon
  client, including the above-the-tip 500 and the listener closing on drop.
- docs/WALLET.md: the fourth chain source, the feature flag, the +5.6 MB
  stripped overhead, and the two limits (testnet only, no Tor in the chain
  path).

Also repaired tests/tui_spec.rs, which the parent commit left un-compilable
(the Phase 2a commit had dropped all but the new imports and four new tests,
1221 lines of body); it is restored from the pre-breakage version, with the
Phase 2a imports and tests re-applied.
2026-09-17 13:17:32 -04:00

1787 lines
55 KiB
Rust

//! Spec implementation tests for docs/TUI.md.
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::Payment;
use onionwire::node::{DaemonSync, WalletChildState};
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
ChainChoice, ConfigField, ConfigStatus, OutboxSummary, WALLET_LINE_MAX, WalletConfigScreen,
alert_line, ascii_chrome, chain_view_with_progress, chat_with_delivery, delivery_tag,
draw_chat, draw_history, draw_share, draw_text_overlay, empty_friend_chat_text,
help_overlay_text, history_detail, history_row_text, is_onion_host, main_footer_hints,
main_header_line, parse_daemon_addr, paste_screen_text, retry_in_text, roster_col_width,
short_send_reason, status_footer, sync_line, wallet_readiness, wrap_invite,
};
use onionwire::wallet::{ChainSource, PingResult};
use ratatui::Frame;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout};
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap};
use std::sync::Mutex;
const FP: &str = "abcdef0123456789deadbeefcafebabe";
static ASCII_ENV: Mutex<()> = Mutex::new(());
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String {
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
screen
}
#[test]
fn status_footer_keeps_send_failed_and_chrome() {
let note = "send failed: peer onion down";
for w in [80u16, 120, 200] {
let line = status_footer(w, FP, ONION, Some(note), main_footer_hints());
assert!(
line.chars().count() <= w as usize,
"footer wider than {w}: {} {line:?}",
line.chars().count()
);
assert!(
line.contains("send failed"),
"{w} dropped fail-closed note: {line:?}"
);
assert!(line.contains("TOR"), "{w} missing TOR: {line:?}");
assert!(line.contains("me:"), "{w} missing me:: {line:?}");
assert!(line.contains("? help"), "{w} missing ? help: {line:?}");
}
}
#[test]
fn main_header_is_one_line_at_80() {
let line = main_header_line(80, FP, ONION);
assert!(!line.contains('\n'), "header must be one line: {line:?}");
assert!(
line.chars().count() <= 80,
"header wider than 80: {} {line:?}",
line.chars().count()
);
assert!(line.to_ascii_lowercase().contains("onionwire"), "{line:?}");
assert!(line.contains("me:"), "{line:?}");
}
#[test]
fn roster_is_fixed_cells_not_percent() {
assert_eq!(roster_col_width(80), 22);
assert_eq!(roster_col_width(119), 22);
assert_eq!(roster_col_width(120), 28);
assert_eq!(roster_col_width(200), 28);
}
#[test]
fn help_overlay_at_80x24_is_fullscreen_last_line_visible() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
f.render_widget(
Paragraph::new(" .-~~-. ONIONWIRE\n┌roster junk\n┌composer"),
f.area(),
);
draw_text_overlay(f, "? help", help_overlay_text());
})
.expect("draw");
let buf = terminal.backend().buffer();
let screen = screen_from(buf, 80, 24);
assert!(
screen.contains("Esc closes this overlay"),
"last help line clipped:\n{screen}"
);
assert!(
!screen.contains(".-~~-."),
"help punched through banner:\n{screen}"
);
assert!(
!screen.contains("┌roster"),
"help punched through roster:\n{screen}"
);
assert!(screen.contains("? help"), "help title missing:\n{screen}");
}
fn draw_main_standin(f: &mut Frame, empty_roster: bool, composer: &str, note: Option<&str>) {
let area = f.area();
let header = main_header_line(area.width, FP, ONION);
let cols = Layout::vertical([
Constraint::Length(1),
Constraint::Min(3),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
f.render_widget(Paragraph::new(header), cols[0]);
let roster_w = roster_col_width(area.width).min(cols[1].width.saturating_sub(10));
let panes =
Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[1]);
let items = if empty_roster {
vec![ListItem::new("no friends")]
} else {
vec![ListItem::new("alice aaaaaaaa…")]
};
f.render_stateful_widget(
List::new(items)
.highlight_symbol("> ")
.block(Block::default().borders(Borders::ALL).title("roster 0")),
panes[0],
&mut ratatui::widgets::ListState::default(),
);
f.render_widget(
Paragraph::new("no friends yet")
.wrap(Wrap { trim: false })
.block(Block::default().borders(Borders::ALL).title(" chat")),
panes[1],
);
f.render_widget(
Paragraph::new(format!("> {composer}")).wrap(Wrap { trim: false }),
cols[2],
);
let footer = status_footer(area.width, FP, ONION, note, main_footer_hints());
f.render_widget(Paragraph::new(footer), cols[3]);
}
#[test]
fn reconstructed_main_empty_roster_and_composer() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_main_standin(f, true, "message", None))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
let row0: String = screen.lines().next().unwrap_or("").to_string();
assert!(
!row0.contains(".-~~-."),
"80x24 main still uses 3-line wordmark:\n{screen}"
);
assert!(
screen.contains("no friends"),
"empty roster blank:\n{screen}"
);
assert!(
screen.contains("message"),
"composer missing placeholder:\n{screen}"
);
assert!(
!screen.contains("/wipe"),
"composer still dumps slash list:\n{screen}"
);
}
#[test]
fn reconstructed_main_keeps_send_failed_on_footer() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_main_standin(f, false, "hello", Some("send failed: peer onion down")))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
assert!(
screen.contains("send failed"),
"fail-closed missing from frame:\n{screen}"
);
}
#[test]
fn dump_spec_frames() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
for (w, h) in [(80u16, 24u16), (120, 40)] {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
draw_main_standin(
f,
false,
"hello from composer",
Some("send failed: peer onion down"),
)
})
.expect("draw");
println!("===== AFTER main {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
draw_main_standin(f, true, "message", None);
draw_text_overlay(f, "? help", help_overlay_text());
})
.expect("draw");
println!("===== AFTER help {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
let invite = sample_invite();
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
println!("===== AFTER share {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
}
}
fn sample_invite() -> String {
let sk = [7u8; 32];
qr::encode(&sk, ONION, &[1u8; 32]).expect("encode")
}
fn invite_line_ok(line: &str) -> bool {
let t = line.trim();
t.is_empty()
|| t.starts_with("onionwire:")
|| t.starts_with("k=")
|| t.starts_with("o=")
|| t.starts_with("spk=")
|| t.starts_with("sig=")
|| t.chars().all(|c| c.is_ascii_hexdigit())
}
#[test]
fn alert_line_truncates_to_frame_width() {
let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped";
let line = alert_line(long, 80);
assert!(
line.chars().count() <= 80,
"alert wider than 80: {} {line:?}",
line.chars().count()
);
assert!(
line.contains('…') || line.contains("..."),
"long alert was not truncated: {line:?}"
);
assert!(
!line.contains("roster on the next row"),
"alert still has overflow tail: {line:?}"
);
}
#[test]
fn wrap_invite_breaks_on_field_boundaries() {
let invite = sample_invite();
assert!(invite.len() > 78, "fixture too short to wrap: {invite}");
let wrapped = wrap_invite(&invite, 78);
for line in wrapped.lines() {
assert!(
line.chars().count() <= 78,
"invite line wider than 78: {} {line:?}",
line.chars().count()
);
assert!(
invite_line_ok(line),
"invite wrapped mid-token: {line:?}\n{wrapped}"
);
}
assert!(
wrapped.contains("onionwire:v1:"),
"lost invite prefix:\n{wrapped}"
);
assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}");
assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}");
let joined: String = wrapped.lines().map(str::trim).collect();
assert_eq!(
joined, invite,
"wrap must be newline-joinable back to payload"
);
}
#[test]
fn draw_share_invite_does_not_wrap_mid_token() {
let invite = sample_invite();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
assert!(
screen.contains("onionwire:v1:"),
"missing prefix:\n{screen}"
);
for raw in screen.lines() {
let inner = raw.trim_start_matches(['│', '|', ' ']);
let inner = inner.trim_end_matches(['│', '|', ' ']);
if inner.starts_with("onionwire:")
|| inner.starts_with("k=")
|| inner.starts_with("o=")
|| inner.starts_with("spk=")
|| inner.starts_with("sig=")
|| inner.chars().all(|c| c.is_ascii_hexdigit())
{
assert!(
invite_line_ok(inner),
"share pane mid-token wrap: {inner:?}\n{screen}"
);
}
if inner.starts_with('c') && inner.contains(":o=") {
panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}");
}
}
}
#[test]
fn empty_friend_chat_has_send_hint() {
let text = empty_friend_chat_text();
assert!(text.contains("no messages"), "{text:?}");
assert!(text.contains("type below, Enter sends"), "{text:?}");
}
#[test]
fn paste_error_keeps_resubmit_hint() {
let body = paste_screen_text("", Some("bad invite"));
assert!(body.contains("bad invite"), "{body:?}");
assert!(body.contains("Enter resubmits"), "{body:?}");
assert!(body.contains("Esc back"), "{body:?}");
let ok = paste_screen_text("onionwire:v1:k=x", None);
assert!(
ok.contains("paste onionwire:v1 payload"),
"happy-path hint lost: {ok:?}"
);
}
#[test]
fn ascii_switch_80x24_frame_is_pure_ascii() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
assert!(
ascii_chrome(),
"ONIONWIRE_ASCII set but ascii_chrome() is false"
);
let footer = status_footer(80, FP, ONION, None, main_footer_hints());
assert!(
footer.contains("..."),
"ASCII truncation marker missing: {footer:?}"
);
assert!(
!footer.contains('…'),
"unicode ellipsis still in footer: {footer:?}"
);
let invite = sample_invite();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
let non_ascii: Vec<char> = screen.chars().filter(|c| !c.is_ascii()).collect();
assert!(
non_ascii.is_empty(),
"ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}"
);
assert!(
screen.contains("..."),
"truncation marker missing from ASCII frame:\n{screen}"
);
assert!(
screen.contains('+') && screen.contains('|') && screen.contains('-'),
"ASCII borders missing:\n{screen}"
);
println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
message_id: i64,
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id,
body: body.as_bytes().to_vec(),
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(
message_id,
body,
OutboxStatus::Queued,
attempts,
next_in,
now,
)
}
fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(message_id: i64, body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(
message_id,
body,
OutboxStatus::Failed(why.into()),
8,
0,
now,
)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(1, "ping"), out_msg(2, "pong")];
let pending = vec![queued_row(2, "pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
/// The case the body match got wrong: the same text sent twice, only the
/// *older* send still queued. Joined by body, the (single) pending row lands on
/// the newest send and the actually-queued row shows `✓` — which is exactly
/// false delivery. The join is on `Message::id` / `OutboxEntry::message_id`.
#[test]
fn identical_bodies_join_by_message_id_not_body() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(7, "same text"), out_msg(8, "same text")];
let pending = vec![queued_row(7, "same text", 1, 30, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('◷') && lines[0].contains("queued"),
"queued marker must land on the queued row (id 7): {:?}",
lines[0]
);
assert!(
!lines[0].contains('✓'),
"queued row must not claim delivery: {:?}",
lines[0]
);
assert_eq!(
marker_of(&lines[1]),
"✓",
"delivered row (id 8) must keep its mark: {:?}",
lines[1]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg(1, "alpha"),
out_msg(2, "beta"),
out_msg(3, "gamma"),
out_msg(4, "delta"),
in_msg(5, "epsilon"),
];
let pending = vec![
failed_row(
1,
"alpha",
"connect peer.onion:80: connection timed out",
now,
),
queued_row(2, "beta", 1, 30, now),
sending_row(3, "gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
};
assert_eq!(queued.note().as_deref(), Some("2 queued"));
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
let msgs = vec![out_msg(1, "ok"), in_msg(2, "pong"), out_msg(3, long)];
let pending = vec![queued_row(3, long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("1 queued"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}
/// The chain-source picker's address field: whatever the user typed either
/// parses into exactly `host:port`, or it is refused with a reason. `.onion`,
/// loopback and clearnet are all accepted — clearnet only because the user
/// typed it here — and there is no default port.
#[test]
fn daemon_addresses_parse_or_are_refused() {
assert_eq!(
parse_daemon_addr(" 127.0.0.1:18081 ").unwrap(),
("127.0.0.1".to_string(), 18081)
);
assert_eq!(
parse_daemon_addr("abc234defghijklmnop.onion:18089").unwrap(),
("abc234defghijklmnop.onion".to_string(), 18089)
);
assert_eq!(
parse_daemon_addr("node.example.com:18089").unwrap(),
("node.example.com".to_string(), 18089)
);
assert_eq!(parse_daemon_addr("[::1]:18081").unwrap().1, 18081);
for bad in [
"",
" ",
"127.0.0.1",
"host:",
":18081",
"host:0",
"host:65536",
"host:abc",
"host:-1",
"http://host:18081",
"host/path:18081",
"ho st:18081",
] {
let err = parse_daemon_addr(bad).expect_err(&format!("{bad:?} must be refused"));
assert!(!err.is_empty(), "{bad:?} refused without a reason");
}
}
/// The picker has to *offer* the in-process daemon, and the row has to say
/// testnet: a user who reads it as a mainnet node has been misled by the app.
#[test]
fn the_chain_picker_offers_the_in_process_daemon_and_says_testnet() {
let rows: Vec<&'static str> = ChainChoice::ALL.iter().map(|c| c.label()).collect();
assert!(
rows.iter().any(|l| l.contains("in-process daemon")),
"the picker never offers it: {rows:?}"
);
assert_eq!(
ChainChoice::ALL
.iter()
.filter(|c| **c == ChainChoice::InProcessCuprate)
.count(),
1,
"one row, not two spellings of it"
);
let detail = ChainChoice::of(&ChainSource::InProcessCuprate {
datadir: std::path::PathBuf::from("/tmp/chain"),
})
.detail();
assert!(
detail.contains("testnet"),
"the caveat is the row: {detail}"
);
assert!(
detail.contains("Cuprate"),
"the row has to name what runs: {detail}"
);
for choice in ChainChoice::ALL {
assert!(!choice.label().is_empty() && !choice.detail().is_empty());
}
}
/// A remote daemon is still never preselected: the fourth row did not introduce
/// a default, and the two local rows are the only ones that mean "this device".
#[test]
fn the_fourth_picker_row_did_not_preselect_anything() {
assert_eq!(
ChainChoice::of(&ChainSource::None),
ChainChoice::ReceiveOnly
);
assert_eq!(
ChainChoice::of(&ChainSource::InProcessCuprate {
datadir: std::path::PathBuf::from("/tmp/chain"),
}),
ChainChoice::InProcessCuprate
);
assert_eq!(
ChainChoice::ALL.first(),
Some(&ChainChoice::ReceiveOnly),
"receive-only is still the first row"
);
}
/// The chain block on the in-process source: the testnet caveat is on the
/// screen, the chain is described as this device's, and nothing about it is
/// dressed up as a remote daemon.
#[test]
fn the_chain_block_names_the_in_process_daemon_and_its_testnet_limit() {
let source = ChainSource::InProcessCuprate {
datadir: std::path::PathBuf::from("/home/user/.local/share/onionwire/chain"),
};
let view = chain_view_with_progress(
&source,
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("127.0.0.1:18081: Connection refused".into()),
},
Some(50),
wallet_readiness(false, false, false),
None,
);
assert!(
view.source_line.contains("in-process daemon"),
"{}",
view.source_line
);
assert!(
view.source_line.contains(onionwire::cuprate::TESTNET_ONLY),
"the caveat must come from the one const: {}",
view.source_line
);
assert!(
!view.source_line.contains("remote daemon"),
"a local daemon must not read as someone else's: {}",
view.source_line
);
// The chain is on this device, so the storage line is the local one.
assert!(
view.storage_line.contains("free here"),
"{}",
view.storage_line
);
for line in view.lines() {
assert!(line.chars().count() <= WALLET_LINE_MAX, "too long: {line}");
}
}
#[test]
fn onion_hosts_are_recognised_before_any_spawn() {
assert!(is_onion_host("abc234.onion"));
assert!(is_onion_host("ABC234.ONION "));
assert!(!is_onion_host("127.0.0.1"));
assert!(!is_onion_host("node.example.com"));
assert!(!is_onion_host("notonion"));
}
// ---------------------------------------------------------------------------
// Payment history rows (card t_935bf84e)
//
// Tests over test-local `Payment` fixtures — no store access from the render
// path. Direction marker, amount via `pay::atomic_to_xmr_str`, verified word
// + glyph, txid truncation, "awaiting receipt" for None txid, and hostile
// memo sanitization.
// ---------------------------------------------------------------------------
#[allow(clippy::too_many_arguments)]
fn payment(
id: i64,
dir: &str,
kind: &str,
amount_atomic: &str,
address: &str,
memo: &str,
txid: Option<String>,
verified: bool,
created_at: i64,
) -> Payment {
Payment {
id,
dir: dir.to_string(),
kind: kind.to_string(),
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
memo: memo.to_string(),
txid,
verified,
created_at,
}
}
const NOW: i64 = 1_700_000_000;
#[test]
fn history_row_outbound_verified_has_marker_word_and_glyph() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
1,
"out",
"tip",
"1000000000",
"addr",
"coffee",
Some("abcd1234".into()),
true,
1_699_999_000,
);
let row = history_row_text(&p, 76, NOW);
assert!(
row.starts_with("> "),
"outbound row must start with '> ': {row:?}"
);
assert!(row.contains('✓'), "verified glyph missing: {row:?}");
assert!(row.contains("verified"), "verified word missing: {row:?}");
assert!(row.contains("0.001"), "amount missing: {row:?}");
}
#[test]
fn history_row_outbound_unverified_has_word_no_check() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
2,
"out",
"invoice",
"500000000",
"addr",
"",
Some("ef12".into()),
false,
1_700_000_000,
);
let row = history_row_text(&p, 76, NOW);
assert!(
row.starts_with("> "),
"outbound row must start with '> ': {row:?}"
);
assert!(
row.contains("unverified"),
"unverified word missing: {row:?}"
);
assert!(
!row.contains('✓'),
"unverified must not have check glyph: {row:?}"
);
}
#[test]
fn history_row_inbound_uses_left_marker() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
3,
"in",
"payment",
"2500000000",
"addr",
"",
Some("deadbeef".into()),
true,
1_700_000_000,
);
let row = history_row_text(&p, 76, NOW);
assert!(
row.starts_with("< "),
"inbound row must start with '< ': {row:?}"
);
assert!(row.contains("verified"), "verified word missing: {row:?}");
}
#[test]
fn history_row_no_txid_says_awaiting_receipt_not_dash() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
4,
"in",
"payment",
"1000000000",
"addr",
"",
None,
false,
1_700_000_000,
);
let row = history_row_text(&p, 76, NOW);
assert!(
row.contains("awaiting receipt"),
"missing 'awaiting receipt': {row:?}"
);
assert!(
!row.contains("--"),
"bare dash instead of 'awaiting receipt': {row:?}"
);
}
#[test]
fn history_row_truncates_txid_within_width() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
5,
"out",
"tip",
"1000",
"addr",
"memo",
Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3".into()),
true,
1_700_000_000,
);
let row = history_row_text(&p, 40, NOW);
assert!(
row.chars().count() <= 40,
"row wider than 40: {} {row:?}",
row.chars().count()
);
}
#[test]
fn history_row_ascii_fallback_has_no_emoji_glyphs() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
let p = payment(
1,
"out",
"tip",
"1000000000",
"addr",
"",
Some("abcd".into()),
true,
1_700_000_000,
);
let row = history_row_text(&p, 76, NOW);
assert!(row.is_ascii(), "ASCII fallback not pure ASCII: {row:?}");
assert!(
row.contains("verified"),
"ASCII verified word missing: {row:?}"
);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn history_detail_shows_all_fields_sanitized() {
let p = payment(
7,
"out",
"tip",
"2000000000",
"1A2B3C4D5E6F",
"for pizza",
Some("abcdef0123456789abcdef0123456789".into()),
true,
1_700_000_000,
);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
assert!(
all.contains("abcdef0123456789abcdef0123456789"),
"full txid missing: {all:?}"
);
assert!(all.contains("1A2B3C4D5E6F"), "address missing: {all:?}");
assert!(all.contains("for pizza"), "memo missing: {all:?}");
assert!(all.contains("0.002"), "amount missing: {all:?}");
assert!(all.contains("outbound"), "direction missing: {all:?}");
assert!(all.contains("verified"), "verified state missing: {all:?}");
assert!(
all.contains("1700000000") || all.contains("Nov"),
"timestamp missing: {all:?}"
);
for line in &detail {
assert!(
line.chars().count() <= 76,
"detail line wider than 76: {} {line:?}",
line.chars().count()
);
}
}
// F7 wallet-config screen (card t_7719eda3)
// ---------------------------------------------------------------------------
/// Fixture password that must NEVER appear in any rendered frame.
const FIXTURE_PASS: &str = "supersecret123";
/// Build a WalletConfigScreen for testing, with the given fields.
fn make_config(
rpc_url: &str,
rpc_login: &str,
no_spend: bool,
reveal: bool,
focus: ConfigField,
status: ConfigStatus,
) -> WalletConfigScreen {
WalletConfigScreen {
rpc_url: rpc_url.to_string(),
rpc_login: rpc_login.to_string(),
no_spend,
reveal,
focus,
status,
}
}
/// Render the F7 config screen through the real `draw_wallet_config` at the
/// given size and collect the result as a string.
fn config_screen_at(w: u16, h: u16, s: &WalletConfigScreen) -> String {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| onionwire::tui::draw_wallet_config(f, s))
.expect("draw");
screen_from(terminal.backend().buffer(), w, h)
}
#[test]
fn wallet_config_screen_renders_fields_and_footer() {
let s = make_config(
"http://127.0.0.1:18083",
"onionwire",
true,
false,
ConfigField::RpcUrl,
ConfigStatus::Idle,
);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = config_screen_at(w, h, &s);
for (y, row) in screen.lines().enumerate() {
if row.chars().count() > w as usize {
panic!("{w}x{h} row {y} wider than frame: {row:?}");
}
}
assert!(screen.contains("wallet config"), "{w}x{h}: title missing");
assert!(screen.contains("rpc_url"), "{w}x{h}: rpc_url label missing");
assert!(
screen.contains("http://127.0.0.1:18083"),
"{w}x{h}: url value missing"
);
assert!(
screen.contains("rpc_login"),
"{w}x{h}: rpc_login label missing"
);
assert!(
screen.contains("no_spend"),
"{w}x{h}: no_spend label missing"
);
assert!(
screen.contains("/tip disabled") || screen.contains("/tip off"),
"{w}x{h}: no_spend consequence missing"
);
assert!(screen.contains("> "), "{w}x{h}: focus marker missing");
assert!(screen.contains("Esc back"), "{w}x{h}: Esc back missing");
assert!(screen.contains("Tab"), "{w}x{h}: Tab hint missing");
}
}
#[test]
fn history_detail_hostile_memo_is_sanitized_inert_text() {
// C0 control chars + bidi override — must render as inert text, not affect
// the terminal or carry hidden directionality.
let hostile = "pay\x01now\u{202E}\u{202E}reverse";
let p = payment(
8,
"in",
"payment",
"500000000",
"addr",
hostile,
Some("cafebabe".into()),
false,
1_700_000_000,
);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
// Bidi override must be stripped — the word "reverse" must appear in
// reading order, not visually flipped by a leftover override mark.
assert!(
!all.contains('\u{202E}'),
"bidi override survived sanitize: {all:?}"
);
assert!(
!all.contains('\x01'),
"C0 control survived sanitize: {all:?}"
);
assert!(all.contains("reverse"), "sanitized memo text lost: {all:?}");
}
#[test]
fn history_detail_no_txid_shows_awaiting_receipt() {
let p = payment(
9,
"in",
"payment",
"1000",
"addr",
"",
None,
false,
1_700_000_000,
);
let detail = history_detail(&p, 76, NOW);
let all = detail.join("\n");
assert!(
all.contains("awaiting receipt"),
"detail missing 'awaiting receipt': {all:?}"
);
}
#[test]
fn draw_history_list_at_80x24_fits_and_shows_rows() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let payments = vec![
payment(
1,
"out",
"tip",
"1000000000",
"addr",
"coffee",
Some("abcd1234".into()),
true,
1_699_999_000,
),
payment(
2,
"in",
"payment",
"2500000000",
"addr",
"",
Some("deadbeef".into()),
true,
1_700_000_001,
),
payment(
3,
"out",
"invoice",
"500000000",
"addr",
"",
None,
false,
1_700_000_002,
),
];
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, &payments, 1, false, "alice", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(
line.chars().count() <= 80,
"80x24 history row wider than 80: {} {line:?}",
line.chars().count()
);
}
assert!(
screen.contains("alice"),
"friend name missing from title: {screen}"
);
assert!(screen.contains("> "), "outbound marker missing: {screen}");
assert!(screen.contains("< "), "inbound marker missing: {screen}");
assert!(
screen.contains("awaiting receipt"),
"awaiting receipt missing: {screen}"
);
assert!(screen.contains("Enter detail"), "hint missing: {screen}");
assert!(screen.contains("Esc back"), "hint missing: {screen}");
}
#[test]
fn draw_history_empty_at_80x24_shows_designed_copy() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, &[], 0, false, "bob", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(line.chars().count() <= 80, "row wider than 80: {line:?}");
}
assert!(
screen.contains("no payments with this friend yet"),
"empty copy missing: {screen}"
);
}
#[test]
fn draw_history_detail_at_80x24_fits() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let p = payment(
1,
"out",
"tip",
"1000000000",
"1A2B3C4D5E6F",
"coffee",
Some("abcdef0123456789abcdef0123456789".into()),
true,
1_700_000_000,
);
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_history(f, std::slice::from_ref(&p), 0, true, "alice", NOW))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
for line in screen.lines() {
assert!(
line.chars().count() <= 80,
"detail row wider than 80: {} {line:?}",
line.chars().count()
);
}
assert!(
screen.contains("awaiting receipt") || screen.contains("abcdef0123456789"),
"detail content missing: {screen}"
);
}
#[test]
fn wallet_config_login_is_masked_by_default() {
let s = make_config(
"http://127.0.0.1:18083",
&format!("user:{FIXTURE_PASS}"),
false,
false,
ConfigField::RpcLogin,
ConfigStatus::Idle,
);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = config_screen_at(w, h, &s);
assert!(
!screen.contains(FIXTURE_PASS),
"{w}x{h}: fixture password leaked in frame:\n{screen}"
);
assert!(screen.contains("user"), "{w}x{h}: username not shown");
}
}
#[test]
fn wallet_config_login_mask_and_reveal_are_distinguishable_in_no_color() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let masked = make_config(
"http://127.0.0.1:18083",
&format!("user:{FIXTURE_PASS}"),
false,
false,
ConfigField::RpcLogin,
ConfigStatus::Idle,
);
let screen = config_screen_at(80, 24, &masked);
assert!(
!screen.contains(FIXTURE_PASS),
"NO_COLOR frame leaked password:\n{screen}"
);
let revealed = make_config(
"http://127.0.0.1:18083",
&format!("user:{FIXTURE_PASS}"),
false,
true,
ConfigField::RpcLogin,
ConfigStatus::Idle,
);
let screen = config_screen_at(80, 24, &revealed);
assert!(
!screen.contains(FIXTURE_PASS),
"NO_COLOR revealed frame leaked password:\n{screen}"
);
let masked_ascii = config_screen_at(80, 24, &masked);
let revealed_ascii = config_screen_at(80, 24, &revealed);
assert!(
masked_ascii.contains('.') || masked_ascii.contains("reveal"),
"masked NO_COLOR frame has no distinguishing marker:\n{masked_ascii}"
);
assert!(
revealed_ascii.contains("user"),
"revealed NO_COLOR frame missing username:\n{revealed_ascii}"
);
unsafe { std::env::remove_var("NO_COLOR") };
}
#[test]
fn wallet_config_status_line_states() {
let idle = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Idle,
);
let screen = config_screen_at(80, 24, &idle);
assert!(
!screen.contains("connected") && !screen.contains("saved") && !screen.contains("error:"),
"idle should have no status line:\n{screen}"
);
let testing = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Testing,
);
let screen = config_screen_at(80, 24, &testing);
assert!(
screen.contains("testing connection"),
"testing status missing:\n{screen}"
);
let ok = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Tested(PingResult {
ok: true,
status: "connected".into(),
error: None,
}),
);
let screen = config_screen_at(80, 24, &ok);
assert!(
screen.contains("connected"),
"tested-ok status missing:\n{screen}"
);
let fail = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Tested(PingResult {
ok: false,
status: "not connected".into(),
error: Some("connection refused".into()),
}),
);
let screen = config_screen_at(80, 24, &fail);
assert!(
screen.contains("not connected"),
"tested-fail status missing:\n{screen}"
);
assert!(
screen.contains("connection refused"),
"tested-fail error detail missing:\n{screen}"
);
let saved_nc = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Saved(true, String::new()),
);
let screen = config_screen_at(80, 24, &saved_nc);
assert!(
screen.contains("saved"),
"saved-not-connected status missing:\n{screen}"
);
let saved_fail = make_config(
"",
"",
false,
false,
ConfigField::Action,
ConfigStatus::Saved(false, "bad url".into()),
);
let screen = config_screen_at(80, 24, &saved_fail);
assert!(
screen.contains("error:"),
"saved-fail status missing:\n{screen}"
);
assert!(
screen.contains("bad url"),
"saved-fail reason missing:\n{screen}"
);
}
#[test]
fn wallet_config_password_never_leaks_in_any_status() {
let cases: Vec<(&str, ConfigStatus)> = vec![
("idle", ConfigStatus::Idle),
("testing", ConfigStatus::Testing),
(
"tested-ok",
ConfigStatus::Tested(PingResult {
ok: true,
status: "connected".into(),
error: None,
}),
),
(
"tested-fail",
ConfigStatus::Tested(PingResult {
ok: false,
status: "not connected".into(),
error: Some(format!("{} leaked", FIXTURE_PASS)),
}),
),
("saved-ok", ConfigStatus::Saved(true, String::new())),
(
"saved-fail",
ConfigStatus::Saved(false, format!("error mentions {}", FIXTURE_PASS)),
),
];
for (name, status) in cases {
let s = make_config(
"http://127.0.0.1:18083",
&format!("user:{FIXTURE_PASS}"),
true,
false,
ConfigField::RpcUrl,
status,
);
let screen = config_screen_at(80, 24, &s);
assert!(
!screen.contains(FIXTURE_PASS),
"password leaked in {name} frame:\n{screen}"
);
}
}
#[test]
fn help_overlay_lists_f7_and_send_flow() {
let help = help_overlay_text();
for needle in ["F7", "F6 h", "send chat", "/pay", "/tip", "copy"] {
assert!(help.contains(needle), "help overlay missing {needle:?}");
}
}
#[test]
fn wallet_config_focus_cycles_through_fields() {
assert_eq!(ConfigField::RpcUrl.next(), ConfigField::RpcLogin);
assert_eq!(ConfigField::RpcLogin.next(), ConfigField::NoSpend);
assert_eq!(ConfigField::NoSpend.next(), ConfigField::Action);
assert_eq!(ConfigField::Action.next(), ConfigField::RpcUrl);
assert_eq!(ConfigField::RpcUrl.prev(), ConfigField::Action);
assert_eq!(ConfigField::RpcLogin.prev(), ConfigField::RpcUrl);
assert_eq!(ConfigField::NoSpend.prev(), ConfigField::RpcLogin);
assert_eq!(ConfigField::Action.prev(), ConfigField::NoSpend);
}
// ---------------------------------------------------------------------------
// The chain view against a Cuprate daemon: connectivity is inferred from
// block-height movement, never from `get_info`'s peer counts (zero while it
// downloads blocks) or from its placeholder `database_size`/`free_space`.
// ---------------------------------------------------------------------------
/// A daemon that answered, but reported no chain target: exactly what Cuprate
/// does at rest — `synchronized = true`, `target_height = 0`, zero peers. The
/// screen must not dress that up as progress (`1160/0`) or as "synced".
#[test]
fn a_daemon_with_no_chain_target_is_unknown_not_synced() {
let sync = DaemonSync {
reachable: true,
height: 1160,
target_height: 0,
note: None,
};
let line = sync_line(&sync, None);
assert_eq!(
line,
"sync: unknown — daemon reports no chain target (height 1160)"
);
assert!(!line.contains("synced"), "{line}");
assert!(!line.contains("syncing"), "{line}");
assert!(!sync.synced(), "no target is not 'caught up'");
}
#[test]
fn connectivity_follows_block_height_movement_only() {
let sync = DaemonSync {
reachable: true,
height: 23_758,
target_height: 3_090_939,
note: None,
};
// No earlier sample: the old copy, no connectivity claim.
assert_eq!(sync_line(&sync, None), "sync: syncing — 23758/3090939");
// The height moved: this is the only evidence of a P2P connection we have.
assert_eq!(
sync_line(&sync, Some(23_000)),
"sync: connected to P2P — syncing 23758/3090939"
);
// The daemon answers, but nothing arrives: do not call that connected.
let stalled = sync_line(&sync, Some(23_758));
assert_eq!(
stalled,
"sync: no new blocks — 23758/3090939 (daemon answering, no progress)"
);
assert!(!stalled.contains("connected"), "{stalled}");
}
#[test]
fn reaching_the_target_is_synced_and_an_unreachable_daemon_stays_unknown() {
let synced = DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
};
assert_eq!(
sync_line(&synced, Some(3_100_000)),
"sync: synced — height 3210000"
);
let dead = DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("127.0.0.1:18081: Connection refused".into()),
};
assert_eq!(
sync_line(&dead, Some(3_210_000)),
"sync: unknown — 127.0.0.1:18081: Connection refused"
);
}
/// The whole chain block on a Cuprate answer: real numbers, placeholders
/// nowhere. `DaemonSync` has no peer/database/free-space field to leak, and the
/// storage line comes from `df` on our own disk, not from the daemon.
#[test]
fn the_chain_block_never_shows_a_daemon_placeholder_metric() {
let view = chain_view_with_progress(
&ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18089,
},
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 23_758,
target_height: 3_090_939,
note: None,
},
None,
wallet_readiness(true, true, false),
Some(23_000),
);
let block = view.lines().join("\n");
for banned in [
"5368709120",
"peer",
"18446744073709551615",
"0.1.0-preview",
] {
assert!(!block.contains(banned), "{banned} reached the UI:\n{block}");
}
assert_eq!(
view.sync_line,
"sync: connected to P2P — syncing 23758/3090939"
);
for line in view.lines() {
assert!(
line.chars().count() <= WALLET_LINE_MAX,
"line too long: {line}"
);
}
}