feat: tip frame (sign/verify/encode/decode), wallet balance + receive address, F6 wallet screen with QR, dispatch Kind::Tip
Some checks failed
ci / test (push) Failing after 9m39s
ci / sdk (push) Failing after 20s

This commit is contained in:
agent 2026-09-12 22:53:58 -04:00
commit 10d81964a5
No known key found for this signature in database
10 changed files with 511 additions and 24 deletions

7
Cargo.lock generated
View file

@ -2638,6 +2638,7 @@ dependencies = [
"ed25519-dalek",
"futures",
"md-5",
"qrcode",
"rand 0.8.8",
"ratatui",
"rpassword",
@ -3106,6 +3107,12 @@ dependencies = [
"thiserror 2.0.20",
]
[[package]]
name = "qrcode"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
[[package]]
name = "quote"
version = "1.0.47"

View file

@ -48,6 +48,7 @@ sha2 = "0.10"
md-5 = "0.10"
rpassword = "7"
zeroize = { version = "1", features = ["derive"] }
qrcode = { version = "0.14", default-features = false }
[dev-dependencies]
tempfile = "3"

View file

@ -7,6 +7,7 @@ pub enum Kind {
Profile,
Invoice,
Receipt,
Tip,
Ping,
File,
Drop,
@ -25,6 +26,9 @@ pub fn classify(pt: &[u8]) -> Kind {
if pt.starts_with(b"rcp ") {
return Kind::Receipt;
}
if pt.starts_with(b"tip ") {
return Kind::Tip;
}
if pt.starts_with(b"png ") {
return Kind::Ping;
}

View file

@ -447,6 +447,19 @@ impl Node {
.map_err(|e| e.to_string())
}
/// Current wallet balance as a human-readable XMR string, or `off` when the
/// wallet is not configured.
pub async fn wallet_balance(&self) -> String {
if !self.wallet.configured() {
return "off".into();
}
match self.wallet.get_balance().await {
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
Err(_) => "err".into(),
}
}
pub fn wipe_messages(&self) -> Result<(), String> {
self.store
.lock()
@ -569,8 +582,12 @@ impl Node {
let k = self.keys()?;
let rcp = pay::sign_receipt(&k.identity_sk, &txid, atomic, &address, unix_now())
.map_err(|e| e.to_string())?;
let pt = pay::encode_receipt(&rcp);
self.send_once(friend_pk, &pt).await?;
let rcp_pt = pay::encode_receipt(&rcp);
let tip = pay::sign_tip(&k.identity_sk, &txid, atomic, &address, _memo, unix_now())
.map_err(|e| e.to_string())?;
let tip_pt = pay::encode_tip(&tip);
self.send_once(friend_pk, &rcp_pt).await?;
self.send_once(friend_pk, &tip_pt).await?;
let store = self.store.lock().map_err(|e| e.to_string())?;
store
.insert_payment(
@ -611,6 +628,63 @@ impl Node {
Ok(profile_addr)
}
/// Receive address for the wallet screen: a freshly created subaddress when
/// the wallet is configured, else the profile `xmr_addr` fallback. Returns
/// the raw address (not a `monero:` URI) so the QR render path can decide
/// how to wrap it.
pub async fn wallet_receive_address(&self) -> Result<String, String> {
let profile_addr = self.self_profile()?.xmr_addr;
if self
.wallet
.configured()
&& let Ok(addr) = self.wallet.get_address().await
&& pay::check_address(&addr).is_ok()
{
return Ok(addr);
}
if !profile_addr.is_empty() {
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
return Ok(profile_addr);
}
Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into())
}
/// Formatted balance for the wallet screen, or "off" when the wallet is not
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
/// piconero itself.
pub async fn wallet_balance_line(&self) -> String {
if self.wallet.configured() {
match self.wallet.get_balance().await {
Ok(b) if !b.is_empty() => {
let xmr = pay::atomic_to_xmr_str(&b);
if xmr == "0" {
"balance 0 XMR".to_string()
} else {
format!("balance {xmr} XMR")
}
}
Ok(_) => "balance —".to_string(),
Err(_) => "balance —".to_string(),
}
} else {
"wallet off".to_string()
}
}
/// Recent in/out transfers for the wallet screen, newest first, capped to a
/// small window. Returns the same `TransferRow` shape the existing tests
/// already cover.
pub async fn wallet_recent_transfers(&self, cap: usize) -> Result<Vec<wallet::TransferRow>, String> {
if !self.wallet.configured() {
return Ok(Vec::new());
}
let rows = self.wallet.get_transfers().await.map_err(|e| e.to_string())?;
let mut rows = rows;
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
Ok(rows.into_iter().take(cap).collect())
}
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?;
let (onion, prekey) = {
@ -860,6 +934,7 @@ impl Node {
}
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
Kind::File => self.ingest_file(&sess.peer_identity, &pt),
Kind::Ping | Kind::Drop => Ok(()),
}
@ -993,6 +1068,42 @@ impl Node {
.map_err(|e| e.to_string())?;
Ok(())
}
async fn ingest_tip(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
let Some(tip) = pay::decode_tip(pt) else {
return Ok(());
};
if !pay::verify_tip(peer, &tip) {
eprintln!("tip dropped (bad sig)");
return Ok(());
}
self.store
.lock()
.map_err(|e| e.to_string())?
.insert_payment(
peer,
PaymentWrite {
dir: "in",
kind: "tip",
amount_atomic: &tip.amount_atomic,
address: &tip.address,
memo: &tip.memo,
txid: Some(&tip.txid),
verified: false,
},
)
.map_err(|e| e.to_string())?;
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(
peer,
"in",
pay::tip_chat_line(&tip.amount_atomic, &tip.memo, false).as_bytes(),
)
.map_err(|e| e.to_string())?;
Ok(())
}
}
fn spawn_rend(

View file

@ -35,6 +35,7 @@ pub struct Receipt {
const INV_PREFIX: &[u8] = b"inv ";
const RCP_PREFIX: &[u8] = b"rcp ";
const TIP_PREFIX: &[u8] = b"tip ";
const PICONERO: u128 = 1_000_000_000_000;
/// Bitcoin-style alphabet; Monero encodes 8-byte blocks (11 chars), not raw base58.
@ -314,6 +315,128 @@ pub fn decode_receipt(pt: &[u8]) -> Option<Receipt> {
})
}
// ---- tip (scope C: both rcp + tip frames are sent/received) ----
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tip {
pub txid: String,
pub amount_atomic: String,
pub address: String,
pub memo: String,
pub ts: i64,
pub sig: Vec<u8>,
}
fn check_tip_fields(txid: &str, amount_atomic: &str, address: &str, memo: &str) -> Result<()> {
if txid.is_empty() || txid.contains('\n') {
return Err(Error("invalid txid".into()));
}
parse_atomic(amount_atomic)?;
check_address(address)?;
if memo.contains('\n') {
return Err(Error("memo must not contain newlines".into()));
}
Ok(())
}
fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(txid.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(amount_atomic.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(address.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(memo.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
msg
}
pub fn sign_tip(
identity_sk: &[u8],
txid: &str,
amount_atomic: &str,
address: &str,
memo: &str,
ts: i64,
) -> Result<Tip> {
check_tip_fields(txid, amount_atomic, address, memo)?;
let sig = sign_bytes(identity_sk, &tip_sign_msg_v1(txid, amount_atomic, address, memo, ts))?;
Ok(Tip {
txid: txid.to_string(),
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
memo: memo.to_string(),
ts,
sig,
})
}
pub fn verify_tip(identity_pk: &[u8], tip: &Tip) -> bool {
if check_tip_fields(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo).is_err() {
return false;
}
verify_bytes(
identity_pk,
&tip_sign_msg_v1(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo, tip.ts),
&tip.sig,
)
}
pub fn encode_tip(tip: &Tip) -> Vec<u8> {
let mut out = Vec::from(TIP_PREFIX);
out.extend_from_slice(tip.txid.as_bytes());
out.push(b'\n');
out.extend_from_slice(tip.amount_atomic.as_bytes());
out.push(b'\n');
out.extend_from_slice(tip.address.as_bytes());
out.push(b'\n');
out.extend_from_slice(tip.memo.as_bytes());
out.push(b'\n');
out.extend_from_slice(tip.ts.to_string().as_bytes());
out.push(b'\n');
out.extend_from_slice(to_hex(&tip.sig).as_bytes());
out
}
pub fn decode_tip(pt: &[u8]) -> Option<Tip> {
let rest = pt.strip_prefix(TIP_PREFIX)?;
let text = std::str::from_utf8(rest).ok()?;
let mut parts = text.splitn(6, '\n');
let txid = parts.next()?.to_string();
let amount_atomic = parts.next()?.to_string();
let address = parts.next()?.to_string();
let memo = parts.next()?.to_string();
let ts = parts.next()?.parse::<i64>().ok()?;
let sig = from_hex(parts.next()?)?;
if check_tip_fields(&txid, &amount_atomic, &address, &memo).is_err() {
return None;
}
Some(Tip {
txid,
amount_atomic,
address,
memo,
ts,
sig,
})
}
pub fn tip_chat_line(amount_atomic: &str, memo: &str, verified: bool) -> String {
let xmr = atomic_to_xmr_str(amount_atomic);
if memo.is_empty() {
if verified {
format!("[tip] {xmr} XMR")
} else {
format!("[tip] {xmr} XMR — pending")
}
} else if verified {
format!("[tip] {xmr} XMR — {memo}")
} else {
format!("[tip] {xmr} XMR — {memo} (pending)")
}
}
fn check_invoice_fields(amount_atomic: &str, address: &str, memo: &str) -> Result<()> {
parse_atomic(amount_atomic)?;
check_address(address)?;

View file

@ -746,8 +746,8 @@ impl Store {
if p.dir != "in" && p.dir != "out" {
return Err(Error("dir must be in or out".into()));
}
if p.kind != "invoice" && p.kind != "receipt" {
return Err(Error("kind must be invoice or receipt".into()));
if p.kind != "invoice" && p.kind != "receipt" && p.kind != "tip" {
return Err(Error("kind must be invoice, receipt, or tip".into()));
}
crate::pay::parse_atomic(p.amount_atomic).map_err(|e| Error(e.to_string()))?;
crate::pay::check_address(p.address).map_err(|e| Error(e.to_string()))?;

View file

@ -16,6 +16,7 @@ use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
use crate::wallet;
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -1111,6 +1112,12 @@ enum Screen {
path: String,
entry: PassphraseEntry,
},
Wallet {
receive_addr: String,
balance: String,
transfers: Vec<wallet::TransferRow>,
qr_modal: Option<QrModal>,
},
Quit {
prompt: QuitPrompt,
},
@ -1217,6 +1224,7 @@ impl App {
};
}
KeyCode::F(5) => self.who_open = true,
KeyCode::F(6) => self.open_wallet()?,
KeyCode::Esc => self.composer.clear(),
KeyCode::Backspace => {
if self.focus == Pane::Composer {
@ -1383,6 +1391,11 @@ impl App {
}
_ => {}
},
Screen::Wallet { .. } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(),
_ => {}
},
Screen::Quit { prompt } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Enter => match prompt.on_char('\n') {
@ -1586,6 +1599,76 @@ impl App {
Ok(())
}
fn open_wallet(&mut self) -> Result<(), String> {
let addr = match self.rt.block_on(self.node.wallet_receive_address()) {
Ok(a) => a,
Err(e) => return Err(e),
};
let balance = self.rt.block_on(self.node.wallet_balance());
let transfers = match self.rt.block_on(self.node.wallet_recent_transfers(8)) {
Ok(t) => t,
Err(_) => Vec::new(),
};
self.screen = Screen::Wallet {
receive_addr: addr,
balance,
transfers,
qr_modal: None,
};
Ok(())
}
fn wallet_toggle_qr(&mut self) {
let Screen::Wallet {
ref mut qr_modal,
ref receive_addr,
..
} = self.screen
else {
return;
};
if let Some(modal) = qr_modal {
*qr_modal = if modal.closed {
qr_modal.take()
} else {
None
};
return;
}
let uri = if receive_addr.starts_with('4') || receive_addr.starts_with('8') {
format!("monero:{receive_addr}")
} else {
receive_addr.clone()
};
let m = match qrcode::QrCode::new(uri.as_bytes()) {
Ok(m) => m,
Err(_) => {
qr_modal.replace(QrModal {
closed: false,
matrix_rows: Vec::new(),
uri: receive_addr.clone(),
});
return;
}
};
let cols = m.to_colors();
let w = m.width();
let rows: Vec<String> = (0..w)
.map(|y| {
(0..w)
.map(|x| {
cols[y * w + x].select('█', ' ')
})
.collect()
})
.collect();
qr_modal.replace(QrModal {
closed: false,
matrix_rows: rows,
uri: receive_addr.clone(),
});
}
fn submit_paste(&mut self, raw: &str) -> Result<(), String> {
match qr::decode(raw.trim()) {
Err(e) => {
@ -1710,7 +1793,7 @@ impl App {
let node = Arc::clone(&self.node);
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
let _j = self.rt.spawn(async move {
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
@ -1720,7 +1803,7 @@ impl App {
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
}));
});
self.job_rx = Some(rx);
Ok(())
}
@ -1755,6 +1838,9 @@ impl App {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
Screen::Wallet { receive_addr, balance, transfers, qr_modal } => {
draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref())
}
}
if self.help_open {
draw_text_overlay(f, "? help", help_overlay_text());
@ -2056,24 +2142,25 @@ pub fn main_footer_hints() -> &'static str {
}
fn footer_hints(screen: &Screen) -> &'static str {
match screen {
Screen::Main => main_footer_hints(),
Screen::Share { .. } => "Esc back ? help",
Screen::Paste { .. } => "Enter submit Esc back ? help",
Screen::Approve { .. } => "y accept n reject ? help",
Screen::Rotate { .. } => "type ROTATE Esc cancel ? help",
Screen::Wipe { kind, .. } => match kind {
WipeKind::Messages => "type WIPE Esc cancel ? help",
WipeKind::All => "type WIPEALL Esc cancel ? help",
},
Screen::Profile { .. } => "Enter save Tab field Esc cancel ? help",
Screen::ConfirmKeys { kind, .. } => match kind {
BackupKind::Backup => "type BACKUP Esc cancel ? help",
BackupKind::Restore => "type RESTORE Esc cancel ? help",
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
}
match screen {
Screen::Main => main_footer_hints(),
Screen::Share { .. } => "Esc back ? help",
Screen::Paste { .. } => "Enter submit Esc back ? help",
Screen::Approve { .. } => "y accept n reject ? help",
Screen::Rotate { .. } => "type ROTATE Esc cancel ? help",
Screen::Wipe { kind, .. } => match kind {
WipeKind::Messages => "type WIPE Esc cancel ? help",
WipeKind::All => "type WIPEALL Esc cancel ? help",
},
Screen::Profile { .. } => "Enter save Tab field Esc cancel ? help",
Screen::ConfirmKeys { kind, .. } => match kind {
BackupKind::Backup => "type BACKUP Esc cancel ? help",
BackupKind::Restore => "type RESTORE Esc cancel ? help",
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Wallet { .. } => "r toggle qr Esc back ? help",
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
}
}
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
@ -2308,6 +2395,119 @@ fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[derive(Clone, Debug)]
struct QrModal {
closed: bool,
matrix_rows: Vec<String>,
#[allow(dead_code)]
uri: String,
}
fn draw_wallet(
f: &mut Frame,
receive_addr: &str,
balance: &str,
transfers: &[wallet::TransferRow],
modal: Option<&QrModal>,
) {
let area = f.area();
if let Some(m) = modal {
// Clear behind the popup so the body does not bleed through.
f.render_widget(Clear, area);
let inner_w = area.width.saturating_sub(2).max(1);
let inner_h = area.height.saturating_sub(2).max(1);
let rows = m.matrix_rows.len().max(1);
let content_h = rows.min(inner_h as usize);
let popup_h = content_h as u16 + 2;
let popup_w = inner_w.max(6);
let x = area.x + (area.width.saturating_sub(popup_w)) / 2;
let y = area.y + (area.height.saturating_sub(popup_h)) / 2;
let popup = Rect {
x,
y,
width: popup_w,
height: popup_h,
};
f.render_widget(Clear, popup);
let mut body = String::from("receive address\nEsc or R closes\n\n");
if m.matrix_rows.is_empty() {
body.push_str("(qr error)");
} else {
for row in m.matrix_rows.iter().take(content_h) {
body.push_str(row);
body.push('\n');
}
}
f.render_widget(
Paragraph::new(body)
.style(style_text())
.wrap(Wrap { trim: false })
.block(
apply_chrome_borders(Block::default())
.border_style(style_accent())
.title("qr — monero:receive"),
),
popup,
);
return;
}
let cols = Layout::vertical([
Constraint::Length(2),
Constraint::Min(4),
Constraint::Length(2),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
f.render_widget(
Paragraph::new("wallet")
.style(style_accent())
.block(pane_block_for("wallet", true)),
cols[0],
);
let addr_line = if receive_addr.is_empty() {
"no address".into()
} else {
receive_addr.to_string()
};
let body = format!(
"address
{addr_line}
balance
{balance}
recent transfers
"
);
let mut lines: Vec<String> = body
.lines()
.map(str::to_string)
.collect();
if transfers.is_empty() {
lines.push(" (none)".into());
} else {
for t in transfers.iter().take(5) {
let xmr = crate::pay::atomic_to_xmr_str(&t.amount);
lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::<String>(), xmr));
}
}
let help = "r toggle qr Esc back";
lines.push("".into());
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.block(apply_chrome_borders(Block::default()).border_style(style_border())),
cols[2],
);
f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]);
}
fn io_err(e: io::Error) -> String {
e.to_string()
}

View file

@ -205,6 +205,16 @@ impl Wallet {
Ok(out)
}
/// Monero-wallet-rpc `get_balance`, account_index 0. Returns the "balance"
/// field as a piconero string on success; the caller can format it with
/// `pay::atomic_to_xmr_str` if it wants a human-readable form.
pub async fn get_balance(&self) -> Result<String> {
let v = self
.rpc("get_balance", serde_json::json!({"account_index": 0}))
.await?;
json_str(&v, "balance")
}
async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
let ep = self
.endpoint

View file

@ -28,6 +28,7 @@ fn known_prefixes_are_typed() {
assert_eq!(classify(b"prf name"), Kind::Profile);
assert_eq!(classify(b"inv 1"), Kind::Invoice);
assert_eq!(classify(b"rcp tx"), Kind::Receipt);
assert_eq!(classify(b"tip tx"), Kind::Tip);
assert_eq!(classify(b"png 1"), Kind::Ping);
}

View file

@ -207,3 +207,33 @@ fn slash_pay_tip_and_wipe_still_parse() {
assert_eq!(parse_slash("/wipe-all"), Some(WipeKind::All));
assert_eq!(parse_slash("/pay 0.12"), None);
}
#[test]
fn tip_frame_roundtrip_and_wrong_key() {
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
let addr = addr_std();
let tip = pay::sign_tip(&sk.to_bytes(), "abc123", "1", &addr, "coffee", 42).unwrap();
assert!(pay::verify_tip(&pk, &tip));
let other = SigningKey::generate(&mut OsRng);
assert!(!pay::verify_tip(&other.verifying_key().to_bytes(), &tip));
let bytes = pay::encode_tip(&tip);
assert!(bytes.starts_with(b"tip "));
let parsed = pay::decode_tip(&bytes).expect("tip frame");
assert_eq!(parsed.txid, "abc123");
assert_eq!(parsed.amount_atomic, "1");
assert_eq!(parsed.address, addr);
assert_eq!(parsed.memo, "coffee");
assert_eq!(parsed.ts, 42);
assert_eq!(&parsed.sig, &tip.sig);
let bad = b"tip bad\n1\naddr\nmemo\n1\n00";
assert!(pay::decode_tip(bad).is_none());
let line = pay::tip_chat_line("120000000000", "coffee", false);
assert_eq!(line, "[tip] 0.12 XMR — coffee (pending)");
let line_v = pay::tip_chat_line("120000000000", "coffee", true);
assert_eq!(line_v, "[tip] 0.12 XMR — coffee");
let bare = pay::tip_chat_line("120000000000", "", false);
assert_eq!(bare, "[tip] 0.12 XMR — pending");
assert!(!line.contains("tip "));
assert!(!line_v.contains("tip "));
}