Merge branch 'main' into onionwire/t_af8b509e-onionwire-tui-invite-mouse-copy-must-not
All checks were successful
ci / test (pull_request) Successful in 5m17s
ci / sdk (pull_request) Successful in 1m11s
ci / fuzz (pull_request) Successful in 4m52s
android-ci / android (pull_request) Successful in 12m17s

This commit is contained in:
sirius 2026-09-19 14:46:33 +00:00
commit 87196e2297
7 changed files with 1435 additions and 52 deletions

View file

@ -28,7 +28,7 @@ use crate::ratchet::{RatchetKeyPair, RatchetState};
use crate::ratelimit::TokenBucket;
use crate::sanitize;
use crate::session::{self, Keys};
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
@ -500,6 +500,23 @@ impl Node {
.map_err(|e| e.to_string())
}
/// The signed `/pay` invoices and `/tip` receipts that came from one peer,
/// oldest row first. A friend with no payment rows is an empty vector, not
/// an error.
///
/// Read-only and fail-closed: it locks the store and nothing else — no Tor
/// dial, no wallet RPC. `memo` is the text the peer signed, stored and
/// returned as it arrived; a renderer sanitizes it with
/// [`crate::sanitize::display_text`] at draw time, exactly as the chat
/// bodies from [`Self::list_messages`] are.
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>, String> {
self.store
.lock()
.map_err(|e| e.to_string())?
.list_payments(friend_pk)
.map_err(|e| e.to_string())
}
/// The live wallet, cloned out of its lock. Every wallet call goes through
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
/// the F7 screen can re-point the wallet mid-session.
@ -2314,6 +2331,70 @@ mod tests {
assert_eq!(rows[0].kind, "tip");
}
/// The peer payment history the TUI needs: `Store::list_payments` existed but
/// nothing on `Node` reached it, so the signed invoice/receipt frames a peer
/// sent were invisible to the app. One row per stored frame, oldest first,
/// and a friend with no rows is an empty vector, not an error.
#[tokio::test]
async fn list_payments_round_trips_a_peers_invoice_and_receipt() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let peer = Keys::generate();
let stranger = Keys::generate();
let addr = xmr_addr();
befriend(
&node.store.lock().unwrap(),
&peer.identity_pk,
&peer.prekey_pk,
"peer.onion",
);
{
let store = node.store.lock().unwrap();
store
.insert_payment(
&peer.identity_pk,
PaymentWrite {
dir: "in",
kind: "invoice",
amount_atomic: "500000000000",
address: &addr,
memo: "rent",
txid: None,
verified: false,
},
)
.expect("store inbound invoice");
store
.insert_payment(
&peer.identity_pk,
PaymentWrite {
dir: "in",
kind: "receipt",
amount_atomic: "250000000000",
address: &addr,
memo: "",
txid: Some("deadbeef"),
verified: false,
},
)
.expect("store inbound receipt");
}
let rows = node.list_payments(&peer.identity_pk).expect("payments");
assert_eq!(rows.len(), 2, "one row per stored frame");
assert_eq!(rows[0].kind, "invoice", "oldest row first");
assert_eq!(rows[0].dir, "in");
assert_eq!(rows[0].amount_atomic, "500000000000");
assert_eq!(rows[0].memo, "rent");
assert_eq!(rows[1].kind, "receipt");
assert_eq!(rows[1].txid.as_deref(), Some("deadbeef"));
let none = node
.list_payments(&stranger.identity_pk)
.expect("a friend with no rows is an empty vector, not an error");
assert!(none.is_empty());
}
/// A stand-in for `monero-wallet-rpc`: it records its argv, then does what
/// the test needs. The wallet child spawns a real process, so this is the
/// only honest way to drive the start path offline.

View file

@ -17,7 +17,7 @@ use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment};
use crate::wallet::{self, ChainSource};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
@ -1282,6 +1282,12 @@ enum Screen {
WalletsSettings {
state: WalletMenuState,
},
/// F9 → `payments`: the peer-scoped history from `Node::list_payments`.
/// Holds the same kind of snapshot as the menu (a resize re-fits it), so a
/// repaint never re-reads the store mid-frame.
PeerPayments {
state: PeerPaymentsState,
},
Quit {
prompt: QuitPrompt,
},
@ -1295,6 +1301,44 @@ enum WalletSetup {
ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry },
}
/// A function key the TUI answers before the per-screen `match`; the screen's
/// own key handler never sees it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FunctionKey {
Share,
Paste,
Rotate,
Who,
Wallet,
RotatePrekey,
OpenMenu,
}
/// The function key `screen` answers, or `None` when the key belongs to the
/// per-screen handler.
///
/// The function keys stay live on every screen that names one — in its footer
/// or in its body: a shortcut the user can read has to work while that screen
/// is open.
fn function_key_for(screen: &Screen, code: KeyCode) -> Option<FunctionKey> {
if !matches!(
screen,
Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. }
) {
return None;
}
match code {
KeyCode::F(2) => Some(FunctionKey::Share),
KeyCode::F(3) => Some(FunctionKey::Paste),
KeyCode::F(4) => Some(FunctionKey::Rotate),
KeyCode::F(5) => Some(FunctionKey::Who),
KeyCode::F(6) => Some(FunctionKey::Wallet),
KeyCode::F(8) => Some(FunctionKey::RotatePrekey),
KeyCode::F(9) => Some(FunctionKey::OpenMenu),
_ => None,
}
}
impl App {
fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> {
let friends = node.list_friends()?;
@ -1378,51 +1422,41 @@ impl App {
let mut file_cmd = None;
let mut chat_send = None;
let mut pass_submit = None;
let mut open_payments = false;
let mut payments_back = false;
let mut payments_move = 0i32;
// The function-key shortcuts stay live on the WALLETS & SETTINGS screen
// too: that screen's whole point is naming the key that fires each row,
// so a key it names has to work while it is open.
if matches!(self.screen, Screen::Main | Screen::WalletsSettings { .. }) {
match key.code {
KeyCode::F(2) => {
self.open_share()?;
return Ok(None);
}
KeyCode::F(3) => {
// and the peer history too: the settings screen's whole point is naming
// the key that fires each row, and the history's footer names `F9
// menu`, so a key a screen names has to work while it is open.
if let Some(fk) = function_key_for(&self.screen, key.code) {
match fk {
FunctionKey::Share => self.open_share()?,
FunctionKey::Paste => {
self.screen = Screen::Paste {
buf: String::new(),
err: None,
};
return Ok(None);
}
KeyCode::F(4) => {
FunctionKey::Rotate => {
self.screen = Screen::Rotate {
prompt: RotatePrompt::new(),
};
return Ok(None);
}
KeyCode::F(5) => {
self.who_open = true;
return Ok(None);
}
KeyCode::F(6) => {
self.open_wallet()?;
return Ok(None);
}
KeyCode::F(8) => {
FunctionKey::Who => self.who_open = true,
FunctionKey::Wallet => self.open_wallet()?,
FunctionKey::RotatePrekey => {
self.screen = Screen::RotatePrekey {
prompt: RotatePrompt::new(),
};
return Ok(None);
}
KeyCode::F(9) => {
if matches!(self.screen, Screen::Main) {
self.open_wallets_settings()?;
}
return Ok(None);
}
_ => {}
// One level above the screen it is pressed on: F9 from Main
// opens the menu, and from the menu or the peer history it
// reopens it rather than silently doing nothing.
FunctionKey::OpenMenu => self.open_wallets_settings()?,
}
return Ok(None);
}
match &mut self.screen {
@ -1651,6 +1685,14 @@ impl App {
Screen::WalletsSettings { .. } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char('c') => copy_addr = true,
// `p` is the key the menu's `payments` row prints.
KeyCode::Char('p') => open_payments = true,
_ => {}
},
Screen::PeerPayments { .. } => match key.code {
KeyCode::Esc => payments_back = true,
KeyCode::Up | KeyCode::Char('k') => payments_move = -1,
KeyCode::Down | KeyCode::Char('j') => payments_move = 1,
_ => {}
},
Screen::Quit { prompt } => match key.code {
@ -1672,6 +1714,21 @@ impl App {
if let Some(kind) = wipe_confirm {
return self.confirm_wipe(kind);
}
if payments_move != 0
&& let Screen::PeerPayments { state } = &mut self.screen
{
if payments_move < 0 {
state.select_prev();
} else {
state.select_next();
}
}
if payments_back {
self.screen = Screen::Main;
}
if open_payments {
self.open_peer_payments()?;
}
if copy_addr {
self.copy_receive_address();
}
@ -1918,6 +1975,19 @@ impl App {
.and_then(|p| (!p.display_name.is_empty()).then(|| p.display_name.clone()));
let bio_set = profile.as_ref().is_some_and(|p| !p.bio.is_empty());
let xmr_set = profile.as_ref().is_some_and(|p| !p.xmr_addr.is_empty());
// The friend the rest of the TUI acts on is the chat's selected friend.
// `list_payments` is a lock-only read: no dial, no RPC, so this snapshot
// stays cheap and works while Tor is still bootstrapping.
let friend = self.friends.get(self.selected);
let peer = friend
.map(|f| f.petname.clone().unwrap_or_else(|| f.fingerprint.clone()))
.unwrap_or_default();
let peer_payments = friend.and_then(|f| {
self.node
.list_payments(&f.pubkey)
.ok()
.map(|rows| rows.len())
});
self.screen = Screen::WalletsSettings {
state: WalletMenuState {
configured: wstat.configured,
@ -1933,11 +2003,37 @@ impl App {
bio_set,
xmr_set,
me_fp: self.me_fp.clone(),
peer,
peer_payments,
},
};
Ok(())
}
/// The F9 menu's `payments` row: the selected friend's payment history from
/// `Node::list_payments`.
///
/// Read-only and fail-closed: the call takes the store lock and nothing
/// else, so it never dials and is safe while offline. A friend with no rows
/// is `Ok(vec![])` — an empty history, not an error.
fn open_peer_payments(&mut self) -> Result<(), String> {
let Some(friend) = self.friends.get(self.selected) else {
self.status_note = Some("no friend selected".into());
return Ok(());
};
let peer = friend
.petname
.clone()
.unwrap_or_else(|| friend.fingerprint.clone());
let pk = friend.pubkey.clone();
let state = match self.node.list_payments(&pk) {
Ok(rows) => PeerPaymentsState::from_payments(peer, &rows),
Err(e) => PeerPaymentsState::error(peer, e),
};
self.screen = Screen::PeerPayments { state };
Ok(())
}
/// `c` on the WALLETS & SETTINGS menu: copy the receive address through the
/// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The
/// address never touches a file.
@ -2459,6 +2555,16 @@ impl App {
);
draw_wallets_settings(f, state, &footer)
}
Screen::PeerPayments { state } => {
let footer = status_footer(
f.area().width,
&self.me_fp,
&self.me_onion,
self.status_note.as_deref(),
footer_hints(&self.screen),
);
draw_peer_payments(f, state, &footer)
}
}
if self.help_open {
draw_text_overlay(f, "? help", help_overlay_text());
@ -3080,11 +3186,31 @@ match screen {
}
Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help",
Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help",
Screen::WalletsSettings { .. } => "Esc back c copy ? help",
Screen::WalletsSettings { .. } => wallets_settings_footer_hint(),
Screen::PeerPayments { .. } => peer_payments_footer_hint(),
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
}
}
/// The hint line the peer-payment-history screen prints. One source only: the
/// screen's frame tests build their fixture from this, so a dumped frame can
/// never show a footer the app does not render.
pub fn peer_payments_footer_hint() -> &'static str {
PEER_PAYMENTS_FOOTER_HINT
}
const PEER_PAYMENTS_FOOTER_HINT: &str = "Esc back up/down select F9 menu ? help";
/// The hint line the WALLETS & SETTINGS menu prints, single-sourced for the
/// same reason as [`peer_payments_footer_hint`]: the menu's frame-dump fixture
/// must not hand-copy it (and must not pair it with the phase-free footer the
/// app stopped using when the chrome redesign landed).
pub fn wallets_settings_footer_hint() -> &'static str {
WALLETS_SETTINGS_FOOTER_HINT
}
const WALLETS_SETTINGS_FOOTER_HINT: &str = "Esc back c copy ? help";
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
let block = block.borders(Borders::ALL);
if ascii_chrome() {
@ -3406,6 +3532,12 @@ pub struct WalletMenuState {
pub xmr_set: bool,
/// Our own fingerprint (identity = pubkey), full hex.
pub me_fp: String,
/// Display name of the friend the F9 screen's friend-scoped rows act on (the
/// chat's selected friend), or empty when there is none.
pub peer: String,
/// `Some(rows)` when `Node::list_payments` answered for that friend;
/// `None` when the read itself failed (which is not "no history").
pub peer_payments: Option<usize>,
}
/// Width of `s` in terminal **cells**, measured by ratatui's own text type.
@ -3486,9 +3618,9 @@ impl MenuRow {
/// The two groups, in the order the card fixes: WALLET, then SETTINGS.
///
/// Payment history here is the wallet's own transfer list (F6), which is the
/// only history `Node` exposes to the TUI. The peer `payments` table has no
/// `Node` accessor (see the card's gap list).
/// Two payment-ish rows, and they are not the same thing: `transfers` is the
/// wallet's own list (F6, `wallet_recent_transfers`), `payments` is the
/// peer-scoped history (`Node::list_payments`) opened by `p`.
fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
let endpoint_word = if !s.configured {
"not configured · receive-only"
@ -3559,7 +3691,7 @@ fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
},
),
MenuRow::new(
"payments",
"transfers",
if s.transfers == 0 {
"no transfers yet".to_string()
} else {
@ -3572,6 +3704,29 @@ fn menu_groups(s: &WalletMenuState) -> (Vec<MenuRow>, Vec<MenuRow>) {
MenuTone::Normal
},
),
// The peer-scoped history: signed `/pay` invoices and `/tip` receipts
// that peer sent. Distinct from the wallet's own transfer list above,
// and labelled so — `Payments` here means `payments` rows, not the
// wallet's `transfers`.
MenuRow::new(
"payments",
if s.peer.is_empty() {
"no friend selected".to_string()
} else {
let peer = menu_cell_text(&s.peer);
match s.peer_payments {
None => format!("history unreadable {}{peer}", "\u{b7} "),
Some(0) => format!("no history with {peer}"),
Some(n) => format!("{n} with {peer}"),
}
},
if s.peer.is_empty() { "" } else { "p" },
if s.peer.is_empty() || s.peer_payments == Some(0) {
MenuTone::Dim
} else {
MenuTone::Normal
},
),
MenuRow::new(
"create",
"/wallet create · seed shown once".to_string(),
@ -3757,6 +3912,430 @@ pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &st
);
}
// ---------------------------------------------------------------------------
// Peer payment history: the F9 menu's `payments` row.
//
// This is the *other* history. The F6 screen shows the wallet's own transfer
// list (`Node::wallet_recent_transfers`); this one shows the peer-scoped rows
// `Node::list_payments` returns — the signed `/pay` invoices and `/tip`
// receipts that peer sent, which never appear in the wallet's own transfers.
//
// Everything here is display data: `memo` is peer-signed text returned as
// stored, so it goes through `menu_cell_text` (control + bidi stripped, no
// newlines) and `fit_cells` (truncated in cells) before it can reach a frame.
// ---------------------------------------------------------------------------
/// Direction column in cells: `in` / `out`.
const PAY_DIR_W: usize = 3;
/// Kind column in cells: `invoice` / `receipt` / `tip`.
const PAY_KIND_W: usize = 7;
/// Amount column in cells, right-aligned: `0.025000000000` is 14, so 15 holds
/// every XMR string `pay::atomic_to_xmr_str` can produce from a u128 piconero.
const PAY_AMOUNT_W: usize = 15;
/// Receipt flag column in cells: `unverified` is the widest word.
const PAY_FLAG_W: usize = 10;
/// One payment row, display-ready except for `memo`/`txid`/`address`, which the
/// render path sanitizes.
#[derive(Clone, Debug, Default)]
pub struct PeerPaymentRow {
/// `"in"` or `"out"` — the peer's direction, not ours.
pub dir: String,
/// `"invoice"`, `"receipt"` or `"tip"`.
pub kind: String,
/// `pay::atomic_to_xmr_str(amount_atomic)` — the same formatter the chat
/// lines use, not a second piconero formatter.
pub amount_xmr: String,
/// Peer-signed memo, as stored. Sanitized at draw time.
pub memo: String,
/// Chain txid, when the payment has one.
pub txid: Option<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);
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],
);
}
/// 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.
@ -3988,6 +4567,98 @@ fn io_err(e: io::Error) -> String {
e.to_string()
}
#[cfg(test)]
mod function_key_tests {
use super::*;
fn peer_payments_screen() -> Screen {
Screen::PeerPayments {
state: PeerPaymentsState::default(),
}
}
/// The peer history's footer prints `F9 menu`, so F9 has to reach the menu
/// while that screen is open — not only from Main.
#[test]
fn f9_opens_the_menu_from_the_peer_payments_screen() {
assert_eq!(
function_key_for(&peer_payments_screen(), KeyCode::F(9)),
Some(FunctionKey::OpenMenu),
"the screen's footer names F9 but F9 does nothing there"
);
}
/// Copy and behaviour agree: every `F<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!(named > 0, "the hint names no function key: {hint:?}");
}
/// The menu screen names `c` and `Esc`, not the function keys, but it is
/// the screen the `payments` row came from — its own keys stay its own.
#[test]
fn function_keys_stay_live_on_the_wallets_settings_screen() {
let screen = Screen::WalletsSettings {
state: WalletMenuState::default(),
};
for key in [
KeyCode::F(2),
KeyCode::F(3),
KeyCode::F(4),
KeyCode::F(5),
KeyCode::F(6),
KeyCode::F(8),
KeyCode::F(9),
] {
assert!(
function_key_for(&screen, key).is_some(),
"{key:?} is named on the menu but is not answered there"
);
}
}
/// A screen that names no function key keeps the key to itself: the
/// composer's `F`-less screens must not steal F-keys they never advertise.
#[test]
fn screens_that_name_no_function_key_do_not_answer_one() {
for screen in [
Screen::Paste {
buf: String::new(),
err: None,
},
Screen::WalletSetup(WalletSetup::ImportSeed {
buf: Zeroizing::new(String::new()),
}),
] {
for key in [KeyCode::F(9), KeyCode::F(6)] {
assert!(
function_key_for(&screen, key).is_none(),
"{key:?} was answered on a screen that never names it"
);
}
}
}
}
#[cfg(test)]
mod passphrase_buffer_tests {
use super::*;