onionwire/tests/tui_payments.rs
Lance Walters 2fa3466019
All checks were successful
ci / test (pull_request) Successful in 5m47s
ci / sdk (pull_request) Successful in 1m28s
ci / fuzz (pull_request) Successful in 4m51s
android-ci / android (pull_request) Successful in 10m36s
tui: peer payment history behind the F9 payments row (key p)
The F9 / `/settings` menu's only payment row showed the wallet's own transfer
list (`Node::wallet_recent_transfers`, F6). The signed `/pay` invoices and
`/tip` receipts a peer sent live in the `payments` table and had no path from
the TUI, so they were invisible. `Node::list_payments` (PR #119) closes that
gap; this wires it into a screen.

- `Screen::PeerPayments { state }` + `PeerPaymentsState` /
  `PeerPaymentRow`, built by `PeerPaymentsState::from_payments` from
  `Node::list_payments`' rows (newest first: the store returns `payments.id`
  ascending, the screen windows the vector).
- Key handler: `p` on the F9 screen opens it (`open_peer_payments`); `up`/`down`
  (or `k`/`j`) move the selection, `Esc` goes back, `F9` reopens the menu.
- Rows carry direction, kind, amount (`pay::atomic_to_xmr_str`, the same
  piconero formatter the chat lines use), memo (sanitized at draw time) and the
  receipt's `verified` / `unverified` word; the focused row is marked with `>`
  and bold. The selected row's txid and address sit under the rows — the
  address wrapped over two lines rather than clipped.
- States: populated, `no payments with {peer}`, `could not read payments`, and
  a menu row that refuses when no friend is selected. An empty history is a
  state, never an error.
- Menu: the wallet's own list is retitled `transfers` (F6, unchanged), and the
  new `payments` row (key `p`) names the peer and the count. Two histories, two
  rows, no ambiguity.
- Widths are measured in cells (`Span::width`); trailing columns are dropped
  before they can wrap, so the body fits 80x24 (20 inner rows of 21) as well as
  120x40 and 200x60.

Tests: new `tests/tui_payments.rs` (11 tests) dumps and asserts the screen at
80x24, 120x40 and 200x60 including the empty history, asserts a memo carrying
ESC/BEL/C1/bidi/newline bytes never reaches the frame buffer, and asserts the
window/column invariants for every width from 20 to 200.

Also relaxes one width assertion in `tests/tui_spec.rs`: `fit_cells` was
asserted to start with `"abcdef"`, which only holds when another test's
in-flight `ONIONWIRE_ASCII` mutation is not visible — the suite mutates env vars
without a global lock, so that test flaked (it also fails on an unmodified tree,
1 run in 2). It now accepts either chrome's cut point, which is what the comment
already claimed.

Docs: `docs/TUI.md` gains the screen's section, the retitled/replaced rows and
the updated row count; the "peer payment history" gap entry is closed.
2026-09-18 23:53:10 -04:00

420 lines
14 KiB
Rust

//! Peer payment history screen (F9 → `payments` row).
//!
//! The screen renders what `Node::list_payments` returns for the friend the rest
//! of the TUI acts on: signed `/pay` invoices, `/tip` receipts and tips, with
//! direction, kind, amount, memo, txid and the receipt's verified flag.
//!
//! Assertions measure in terminal **cells** (`cell_width`, which goes through
//! `Span::width`) and accept either ellipsis form / rule glyph, because
//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the two TUI test
//! binaries run in parallel.
use onionwire::Payment;
use onionwire::tui::{
PeerPaymentRow, PeerPaymentsState, WalletMenuState, cell_width, draw_peer_payments,
peer_payments_lines, peer_payments_text, status_footer, wallets_settings_menu_text,
};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
const FP: &str = "abcdef0123456789deadbeefcafebabe";
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
const TXID: &str = "3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041";
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM";
fn row(
dir: &str,
kind: &str,
xmr: &str,
memo: &str,
txid: Option<&str>,
verified: bool,
) -> PeerPaymentRow {
PeerPaymentRow {
dir: dir.into(),
kind: kind.into(),
amount_xmr: xmr.into(),
memo: memo.into(),
txid: txid.map(str::to_string),
address: ADDR.into(),
verified,
}
}
/// A peer with three rows: a receipt for a signed invoice, a tip, and the
/// invoice itself. Newest first, the way the card orders the window.
fn peer_state() -> PeerPaymentsState {
PeerPaymentsState {
peer: "lance".into(),
rows: vec![
row("in", "receipt", "0.025", "lunch money", Some(TXID), true),
row("out", "tip", "0.005", "coffee", None, false),
row("out", "invoice", "0.1", "rent", None, false),
],
error: None,
selected: 0,
}
}
fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
let footer = status_footer(w, FP, ONION, None, "Esc back up/down select ? help");
terminal
.draw(|f| draw_peer_payments(f, st, &footer))
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
screen
}
#[test]
fn peer_payments_lists_every_required_field() {
let body = peer_payments_text(78, 21, &peer_state());
for needle in [
"dir",
"kind",
"amount",
"receipt",
"memo", // column header
"in",
"out", // direction
"invoice",
"receipt",
"tip", // kind
"0.025",
"0.1",
"0.005", // amount
"lunch money",
"rent",
"coffee", // memo
"verified", // receipt flag
"tx",
TXID, // txid when present
"addr",
// destination address of the selected row (see the wrap assertions below)
] {
assert!(body.contains(needle), "missing {needle:?}:\n{body}");
}
// The address is wrapped over two lines at 80 columns, not clipped: the head
// starts on the `addr` row and the tail survives on the continuation line.
assert!(body.contains(&ADDR[..40]), "\n{body}");
assert!(
body.contains(&ADDR[ADDR.len() - 20..]),
"the address tail was clipped, not wrapped:\n{body}"
);
// Amounts carry the shared piconero formatter's units once, in the header.
assert!(body.contains("amount XMR"), "\n{body}");
}
#[test]
fn peer_payments_amount_is_the_shared_formatter_not_a_second_one() {
let rows = vec![Payment {
id: 1,
dir: "in".into(),
kind: "receipt".into(),
amount_atomic: "25000000000".into(),
address: ADDR.into(),
memo: "lunch".into(),
txid: Some(TXID.into()),
verified: true,
created_at: 0,
}];
let st = PeerPaymentsState::from_payments("lance".into(), &rows);
assert_eq!(st.rows[0].amount_xmr, "0.025", "piconero -> XMR");
assert!(
peer_payments_text(78, 21, &st).contains("0.025"),
"{}",
peer_payments_text(78, 21, &st)
);
}
#[test]
fn peer_payments_empty_history_is_an_explicit_line() {
let st = PeerPaymentsState {
peer: "lance".into(),
rows: Vec::new(),
error: None,
selected: 0,
};
let body = peer_payments_text(78, 21, &st);
assert!(
body.contains("no payments"),
"empty state not named:\n{body}"
);
assert!(body.contains("lance"), "\n{body}");
// Empty is a state, never an error.
assert!(!body.to_lowercase().contains("error"), "\n{body}");
assert!(!body.to_lowercase().contains("failed"), "\n{body}");
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
let screen = render(w, h, &st);
assert!(
screen.contains("no payments"),
"{w}x{h} blank panel:\n{screen}"
);
}
}
#[test]
fn peer_payments_error_is_named_not_blank() {
let st = PeerPaymentsState::error("lance".into(), "store lock poisoned".into());
let body = peer_payments_text(78, 21, &st);
assert!(body.contains("could not read payments"), "\n{body}");
assert!(body.contains("store lock poisoned"), "\n{body}");
}
#[test]
fn peer_payments_selection_uses_a_marker_not_colour_alone() {
let mut st = peer_state();
let first = peer_payments_text(78, 21, &st);
let marked = first
.lines()
.find(|l| l.starts_with('>'))
.expect("a selection marker");
assert!(marked.contains("0.025"), "{marked:?}");
st.select_next();
let second = peer_payments_text(78, 21, &st);
let now = second
.lines()
.find(|l| l.starts_with('>'))
.expect("a selection marker");
assert!(now.contains("0.005"), "{now:?}");
assert_eq!(
second.lines().filter(|l| l.starts_with('>')).count(),
1,
"exactly one row is focused:\n{second}"
);
}
#[test]
fn peer_payments_windows_a_long_history_and_says_so() {
let rows: Vec<PeerPaymentRow> = (0..40)
.map(|i| {
row(
"in",
"receipt",
"0.001",
&format!("row {i}"),
Some(TXID),
true,
)
})
.collect();
let st = PeerPaymentsState {
peer: "lance".into(),
rows,
error: None,
selected: 0,
};
let lines = peer_payments_lines(78, 21, &st);
assert!(
lines.len() <= 21,
"body needs {} rows for a 21-row pane",
lines.len()
);
let body = peer_payments_text(78, 21, &st);
assert!(body.contains("older"), "window not disclosed:\n{body}");
// The newest row is the one on screen, not the oldest.
assert!(body.contains("row 0"), "\n{body}");
assert!(!body.contains("row 39"), "\n{body}");
// Scrolling to the end brings the oldest row into view.
let mut st = st;
for _ in 0..39 {
st.select_next();
}
let body = peer_payments_text(78, 21, &st);
assert!(body.contains("row 39"), "\n{body}");
assert!(body.contains("newer"), "window not disclosed:\n{body}");
}
#[test]
fn peer_payments_hostile_memo_cannot_reach_the_terminal() {
// A peer-signed memo is untrusted display data: ESC/BEL/C1 controls, bidi
// overrides and newlines must not survive into the frame buffer.
let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow";
let st = PeerPaymentsState {
peer: "lance".into(),
rows: vec![row("in", "receipt", "0.025", hostile, Some(hostile), true)],
error: None,
selected: 0,
};
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = render(w, h, &st);
assert!(!screen.contains('\u{1b}'), "{w}x{h} ESC reached the frame");
assert!(!screen.contains('\u{7}'), "{w}x{h} BEL reached the frame");
assert!(!screen.contains('\u{9b}'), "{w}x{h} C1 reached the frame");
assert!(
!screen.contains('\u{202e}') && !screen.contains('\u{2066}'),
"{w}x{h} bidi reached the frame"
);
assert!(screen.contains("safe"), "{w}x{h}:\n{screen}");
}
// The control byte itself is dropped, so the rest is inert text: `[31m` can
// only ever be printed, never interpreted.
let body = peer_payments_text(78, 21, &st);
assert!(body.contains("safe[31mred"), "\n{body}");
assert!(!body.contains('\u{1b}'), "\n{body}");
}
#[test]
fn peer_payments_frames_fit_at_the_three_sizes() {
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
let screen = render(w, h, &peer_state());
assert!(screen.contains("payments"), "{w}x{h}:\n{screen}");
assert!(screen.contains("lance"), "{w}x{h}:\n{screen}");
assert!(screen.contains("? help"), "footer clipped:\n{screen}");
assert!(
screen.contains("lunch money"),
"memo clipped at {w}x{h}:\n{screen}"
);
for line in screen.lines() {
assert!(
cell_width(line) <= w as usize,
"line wider than {w} at {w}x{h}: {line:?}"
);
}
let lines = peer_payments_lines(w - 2, h - 3, &peer_state());
assert!(
lines.len() <= (h - 3) as usize,
"body needs {} rows, {w}x{h} shows {}",
lines.len(),
h - 3
);
}
// 200x60 has room for the whole txid and address, untruncated.
let wide = render(200, 60, &peer_state());
assert!(wide.contains(TXID), "200x60 truncated the txid:\n{wide}");
assert!(wide.contains(ADDR), "200x60 truncated the address:\n{wide}");
}
#[test]
fn peer_payments_columns_drop_before_they_wrap() {
// 80 columns is the floor, but a narrow terminal must still produce rows
// that never overrun the pane: trailing columns are dropped, not wrapped.
for w in 20u16..=200 {
for line in peer_payments_lines(w, 21, &peer_state()) {
let width: usize = line
.spans
.iter()
.map(|s| cell_width(s.content.as_ref()))
.sum();
assert!(width <= w as usize, "width {w}: {width} cells: {line:?}");
}
for line in peer_payments_lines(
w,
21,
&PeerPaymentsState {
peer: "lance".into(),
rows: Vec::new(),
error: None,
selected: 0,
},
) {
let width: usize = line
.spans
.iter()
.map(|s| cell_width(s.content.as_ref()))
.sum();
assert!(width <= w as usize, "empty state width {w}: {line:?}");
}
}
}
#[test]
fn wallets_settings_menu_offers_the_peer_payments_row() {
let st = WalletMenuState {
transfers: 3,
peer: "lance".into(),
peer_payments: Some(3),
..menu_state_defaults()
};
let body = wallets_settings_menu_text(78, &st);
let row = body
.lines()
.find(|l| l.contains("payments"))
.expect("payments row");
assert!(row.contains("lance"), "row does not name the peer: {row:?}");
assert!(row.contains('p'), "row does not name its key: {row:?}");
// The wallet's own transfer list keeps its F6 row; it is retitled so the
// two histories cannot be mistaken for each other.
assert!(
body.lines().any(|l| l.contains("transfers")),
"wallet transfer row lost:\n{body}"
);
// No friend selected: the row is dim and offers no key that would do
// nothing.
let st = WalletMenuState {
peer: String::new(),
peer_payments: None,
..menu_state_defaults()
};
let body = wallets_settings_menu_text(78, &st);
let row = body
.lines()
.find(|l| l.contains("payments"))
.expect("payments row");
assert!(row.contains("no friend"), "{row:?}");
// A friend with no payment rows is the empty state, not an error.
let st = WalletMenuState {
peer: "lance".into(),
peer_payments: Some(0),
..menu_state_defaults()
};
let body = wallets_settings_menu_text(78, &st);
let row = body
.lines()
.find(|l| l.contains("payments"))
.expect("payments row");
assert!(row.contains("no history"), "{row:?}");
}
/// The F9 menu state with a healthy wallet, as `tests/tui_spec.rs` builds it.
fn menu_state_defaults() -> WalletMenuState {
WalletMenuState {
configured: true,
connected: true,
wallet_error: None,
receive_addr: ADDR.into(),
balance: "0.250000000000".into(),
transfers: 3,
child_state: "ready".into(),
child_source: "local node".into(),
child_error: None,
nickname: Some("lance".into()),
bio_set: true,
xmr_set: true,
me_fp: FP.into(),
peer: String::new(),
peer_payments: None,
}
}
#[test]
fn peer_payments_frame_dumps() {
for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] {
println!("===== PEER PAYMENTS {w}x{h} =====");
print!("{}", render(w, h, &peer_state()));
println!("===== PEER PAYMENTS (empty) {w}x{h} =====");
print!(
"{}",
render(
w,
h,
&PeerPaymentsState {
peer: "lance".into(),
rows: Vec::new(),
error: None,
selected: 0,
}
)
);
}
}