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 24s
ci / sdk (push) Failing after 17s

This commit is contained in:
agent 2026-09-12 22:53:58 -04:00
commit 7af0c7ab99
No known key found for this signature in database
10 changed files with 371 additions and 4 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,62 @@ 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 fn wallet_receive_address(&self) -> Result<String, String> {
let profile_addr = self.self_profile()?.xmr_addr;
if self.wallet.configured() {
if let Ok(addr) = self.wallet.get_address() {
if 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" {
format!("balance 0 XMR")
} 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 +933,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 +1067,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::{self, TransferRow};
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,71 @@ impl App {
Ok(())
}
fn open_wallet(&mut self) -> Result<(), String> {
let addr = match 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,
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()
};
// Small matrix keeps the popup visibly crisp in a narrow column.
let matrix = 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 rows = matrix
.blocks_to_slice()
.iter()
.map(|row| row.iter().map(|&on| if on { '█' } else { ' ' }).collect::<String>())
.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) => {
@ -1755,6 +1833,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());

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 "));
}