From 96d582153afe1baf9b906f279be68af5cfcf69d9 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 15 Sep 2026 12:45:49 -0400 Subject: [PATCH] feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames The SDK could already send an invoice or a tip through Node::pay_invoice / Node::tip, but it could not touch the payment frames themselves: pay::sign_* take the ed25519 identity secret and Node exposed only identity_pk(), so the signing half lived nowhere the SDK could reach. Add the signing surface to the node instead of exporting the key: * Node::sign_invoice / sign_receipt / sign_tip sign with the node's own identity key and return the core frame struct. The secret never leaves the process and there is no API that hands it out. * pay_invoice and tip now call those methods rather than signing inline, so there is one signing path, not two. SDK (crates/onionwire-sdk), all backward compatible: * Records Invoice, Receipt, Tip mirroring src/pay.rs, sig as raw bytes so a frame re-encodes byte-for-byte. * Wire::sign_invoice / sign_receipt / sign_tip (async, over the node). * Free functions encode_invoice / encode_receipt / encode_tip, decode_invoice / decode_receipt / decode_tip (None on a foreign or truncated frame), verify_invoice / verify_receipt / verify_tip against the sender's pubkey hex (false on a bad key, never a panic). Tests: 8 new SDK unit tests (record round-trips through the core encoders, signer-key-only verification, tamper rejection, foreign/truncated frame, typed Stopped error after shutdown). SDK 27 passed, 0 failed; SDK clippy --all-targets -D warnings clean; root clippy --all-targets -D warnings clean; root lib tests 14 passed; tests/pay.rs 11 passed. --- crates/onionwire-sdk/src/lib.rs | 379 ++++++++++++++++++++++++++++++++ src/node.rs | 62 +++++- 2 files changed, 433 insertions(+), 8 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 136b815..a28e804 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -595,6 +595,55 @@ impl Wire { .map_err(WireError::new) } + /// Sign an invoice frame with this node's identity key. + /// + /// The ed25519 secret stays inside the node: this is the only way the SDK + /// signs a payment frame and there is no method that hands the key out. + /// `amount_atomic` is piconero (`xmr_to_atomic` converts a typed amount). + /// Signing does not touch the network — carry the result with + /// [`encode_invoice`] and send it as chat bytes, or use the one-shot + /// [`Wire::send_invoice`], which signs, sends and records the chat line. + pub async fn sign_invoice( + &self, + amount_atomic: String, + address: String, + memo: String, + ) -> WResult { + self.node()? + .sign_invoice(&amount_atomic, &address, &memo) + .map(invoice_record) + .map_err(WireError::new) + } + + /// Sign a receipt frame for a transfer that already happened. Signing only, + /// never a transfer: this does not move funds. + pub async fn sign_receipt( + &self, + txid: String, + amount_atomic: String, + address: String, + ) -> WResult { + self.node()? + .sign_receipt(&txid, &amount_atomic, &address) + .map(receipt_record) + .map_err(WireError::new) + } + + /// Sign a tip frame (receipt plus memo) for a transfer that already + /// happened. Signing only, never a transfer. + pub async fn sign_tip( + &self, + txid: String, + amount_atomic: String, + address: String, + memo: String, + ) -> WResult { + self.node()? + .sign_tip(&txid, &amount_atomic, &address, &memo) + .map(tip_record) + .map_err(WireError::new) + } + /// Spend-authority warning shown before create. Not a tooltip. pub fn spend_authority_warning(&self) -> String { onionwire::wallet::SPEND_AUTHORITY_WARNING.to_string() @@ -691,6 +740,178 @@ pub struct TransferRow { pub address: String, } +/// One signed invoice frame: "pay me `amount_atomic` piconero at `address`". +/// +/// Mirrors `pay::Invoice`. `sig` is the raw 64-byte ed25519 signature, not hex, +/// so the frame re-encodes byte-for-byte. Sign it with [`Wire::sign_invoice`] +/// (the identity key never leaves the node), carry it with [`encode_invoice`], +/// and check an inbound one against the sender's pubkey with [`verify_invoice`]. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct Invoice { + /// Piconero as a decimal string. `xmr_to_atomic("0.5")` is the form to + /// build this from a typed amount. + pub amount_atomic: String, + pub address: String, + /// May be empty; must not contain a newline. + pub memo: String, + /// Unix seconds the frame was signed at. + pub ts: i64, + pub sig: Vec, +} + +/// One signed receipt frame: "transaction `txid` paid `amount_atomic` to +/// `address`". Mirrors `pay::Receipt`; same signing rules as [`Invoice`]. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct Receipt { + pub txid: String, + pub amount_atomic: String, + pub address: String, + pub ts: i64, + pub sig: Vec, +} + +/// One signed tip frame: a receipt plus the memo the sender attached. Mirrors +/// `pay::Tip`; same signing rules as [`Invoice`]. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct Tip { + pub txid: String, + pub amount_atomic: String, + pub address: String, + pub memo: String, + pub ts: i64, + pub sig: Vec, +} + +fn invoice_record(inv: pay::Invoice) -> Invoice { + Invoice { + amount_atomic: inv.amount_atomic, + address: inv.address, + memo: inv.memo, + ts: inv.ts, + sig: inv.sig, + } +} + +fn invoice_core(rec: Invoice) -> pay::Invoice { + pay::Invoice { + amount_atomic: rec.amount_atomic, + address: rec.address, + memo: rec.memo, + ts: rec.ts, + sig: rec.sig, + } +} + +fn receipt_record(rcp: pay::Receipt) -> Receipt { + Receipt { + txid: rcp.txid, + amount_atomic: rcp.amount_atomic, + address: rcp.address, + ts: rcp.ts, + sig: rcp.sig, + } +} + +fn receipt_core(rec: Receipt) -> pay::Receipt { + pay::Receipt { + txid: rec.txid, + amount_atomic: rec.amount_atomic, + address: rec.address, + ts: rec.ts, + sig: rec.sig, + } +} + +fn tip_record(tip: pay::Tip) -> Tip { + Tip { + txid: tip.txid, + amount_atomic: tip.amount_atomic, + address: tip.address, + memo: tip.memo, + ts: tip.ts, + sig: tip.sig, + } +} + +fn tip_core(rec: Tip) -> pay::Tip { + pay::Tip { + txid: rec.txid, + amount_atomic: rec.amount_atomic, + address: rec.address, + memo: rec.memo, + ts: rec.ts, + sig: rec.sig, + } +} + +/// Encode an invoice as the wire frame the peer decodes with +/// [`decode_invoice`]. Pass the bytes to [`Wire::send`]. +#[uniffi::export] +pub fn encode_invoice(invoice: Invoice) -> Vec { + pay::encode_invoice(&invoice_core(invoice)) +} + +/// Decode an invoice frame. `None` for another frame kind, a truncated frame or +/// other malformed bytes — decoding never panics. +#[uniffi::export] +pub fn decode_invoice(frame: Vec) -> Option { + pay::decode_invoice(&frame).map(invoice_record) +} + +/// Verify an invoice against the sender's ed25519 identity pubkey (lowercase +/// hex — the same key [`FriendInfo::pubkey_hex`] carries). `false` for a bad +/// signature, an edited frame, or a malformed key. +#[uniffi::export] +pub fn verify_invoice(pubkey_hex: String, invoice: Invoice) -> bool { + match unhex(&pubkey_hex) { + Ok(pk) => pay::verify_invoice(&pk, &invoice_core(invoice)), + Err(_) => false, + } +} + +/// Encode a receipt as the wire frame the peer decodes with +/// [`decode_receipt`]. +#[uniffi::export] +pub fn encode_receipt(receipt: Receipt) -> Vec { + pay::encode_receipt(&receipt_core(receipt)) +} + +/// Decode a receipt frame. `None` for another frame kind or malformed bytes. +#[uniffi::export] +pub fn decode_receipt(frame: Vec) -> Option { + pay::decode_receipt(&frame).map(receipt_record) +} + +/// Verify a receipt against the sender's ed25519 identity pubkey (hex). +#[uniffi::export] +pub fn verify_receipt(pubkey_hex: String, receipt: Receipt) -> bool { + match unhex(&pubkey_hex) { + Ok(pk) => pay::verify_receipt(&pk, &receipt_core(receipt)), + Err(_) => false, + } +} + +/// Encode a tip as the wire frame the peer decodes with [`decode_tip`]. +#[uniffi::export] +pub fn encode_tip(tip: Tip) -> Vec { + pay::encode_tip(&tip_core(tip)) +} + +/// Decode a tip frame. `None` for another frame kind or malformed bytes. +#[uniffi::export] +pub fn decode_tip(frame: Vec) -> Option { + pay::decode_tip(&frame).map(tip_record) +} + +/// Verify a tip against the sender's ed25519 identity pubkey (hex). +#[uniffi::export] +pub fn verify_tip(pubkey_hex: String, tip: Tip) -> bool { + match unhex(&pubkey_hex) { + Ok(pk) => pay::verify_tip(&pk, &tip_core(tip)), + Err(_) => false, + } +} + /// Convert a user-facing XMR amount string to a piconero string. /// /// Accepts `"0.5"`, `"1"`, `"0.001"` etc. Returns the piconero string on @@ -1017,4 +1238,162 @@ mod tests { fn check_address_rejects_invalid_address() { assert!(check_address("not-an-address".to_string()).is_err()); } + + // ---- pay.rs surface: Invoice / Receipt / Tip frames ---- + + /// A throwaway identity for the signing half, without Arti or a store: + /// `session::Keys::generate` is the core's own generator and hands out both + /// the secret half the signer needs and the public half a verifier needs. + fn test_keys() -> onionwire::session::Keys { + onionwire::session::Keys::generate() + } + + /// Same mainnet address the address tests use. + const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"; + + fn signed_invoice(k: &onionwire::session::Keys) -> pay::Invoice { + pay::sign_invoice(&k.identity_sk, "500000000000", ADDR, "lunch", 1_700_000_000) + .expect("sign_invoice") + } + + fn signed_receipt(k: &onionwire::session::Keys) -> pay::Receipt { + pay::sign_receipt(&k.identity_sk, "ab12", "500000000000", ADDR, 1_700_000_000) + .expect("sign_receipt") + } + + fn signed_tip(k: &onionwire::session::Keys) -> pay::Tip { + pay::sign_tip( + &k.identity_sk, + "ab12", + "500000000000", + ADDR, + "lunch", + 1_700_000_000, + ) + .expect("sign_tip") + } + + #[test] + fn invoice_record_round_trips_through_encode_and_decode() { + let k = test_keys(); + let core = signed_invoice(&k); + let rec = invoice_record(core.clone()); + + // The record carries the core's fields, not defaults. + assert_eq!(rec.amount_atomic, "500000000000"); + assert_eq!(rec.address, ADDR); + assert_eq!(rec.memo, "lunch"); + assert_eq!(rec.ts, 1_700_000_000); + assert_eq!(rec.sig, core.sig); + + // Encoding the record is byte-identical to encoding the core frame … + let pt = encode_invoice(rec.clone()); + assert_eq!(pt, pay::encode_invoice(&core)); + // … and the frame decodes back to the same record. + assert_eq!(decode_invoice(pt).as_ref(), Some(&rec)); + } + + #[test] + fn receipt_record_round_trips_through_encode_and_decode() { + let k = test_keys(); + let core = signed_receipt(&k); + let rec = receipt_record(core.clone()); + + assert_eq!(rec.txid, "ab12"); + assert_eq!(rec.amount_atomic, "500000000000"); + assert_eq!(rec.address, ADDR); + assert_eq!(rec.ts, 1_700_000_000); + + let pt = encode_receipt(rec.clone()); + assert_eq!(pt, pay::encode_receipt(&core)); + assert_eq!(decode_receipt(pt).as_ref(), Some(&rec)); + } + + #[test] + fn tip_record_round_trips_through_encode_and_decode() { + let k = test_keys(); + let core = signed_tip(&k); + let rec = tip_record(core.clone()); + + assert_eq!(rec.txid, "ab12"); + assert_eq!(rec.memo, "lunch"); + + let pt = encode_tip(rec.clone()); + assert_eq!(pt, pay::encode_tip(&core)); + assert_eq!(decode_tip(pt).as_ref(), Some(&rec)); + } + + #[test] + fn a_frame_verifies_against_the_signers_pubkey_only() { + let k = test_keys(); + let other = test_keys(); + let rec = invoice_record(signed_invoice(&k)); + + assert!(verify_invoice(hex(&k.identity_pk), rec.clone())); + assert!(!verify_invoice(hex(&other.identity_pk), rec.clone())); + // A malformed key is a failed verification, not a panic. + assert!(!verify_invoice("zz".to_string(), rec)); + } + + #[test] + fn receipt_and_tip_verify_against_the_signers_pubkey_only() { + let k = test_keys(); + let other = test_keys(); + let pk = hex(&k.identity_pk); + let wrong = hex(&other.identity_pk); + + let rcp = receipt_record(signed_receipt(&k)); + assert!(verify_receipt(pk.clone(), rcp.clone())); + assert!(!verify_receipt(wrong.clone(), rcp)); + + let tip = tip_record(signed_tip(&k)); + assert!(verify_tip(pk, tip.clone())); + assert!(!verify_tip(wrong, tip)); + } + + #[test] + fn verification_rejects_a_frame_whose_amount_was_edited() { + let k = test_keys(); + let pk = hex(&k.identity_pk); + + let mut inv = invoice_record(signed_invoice(&k)); + inv.amount_atomic = "900000000000".to_string(); + assert!(!verify_invoice(pk.clone(), inv)); + + let mut tip = tip_record(signed_tip(&k)); + tip.address = ADDR.replace("4AdUnd", "4AdUne"); + assert!(!verify_tip(pk, tip)); + } + + #[test] + fn decode_rejects_a_foreign_or_truncated_frame() { + let k = test_keys(); + assert_eq!(decode_invoice(b"nonsense".to_vec()), None); + // A tip frame is not an invoice frame. + assert_eq!(decode_invoice(encode_tip(tip_record(signed_tip(&k)))), None); + // The prefix without its fields is not a frame either. + let mut truncated = encode_receipt(receipt_record(signed_receipt(&k))); + truncated.truncate(10); + assert_eq!(decode_receipt(truncated), None); + } + + #[test] + fn payment_signing_after_shutdown_is_a_typed_error() { + let wire = stopped_wire(); + for err in [ + block_on(wire.sign_invoice("500000000000".into(), ADDR.into(), String::new())) + .unwrap_err(), + block_on(wire.sign_receipt("ab12".into(), "500000000000".into(), ADDR.into())) + .unwrap_err(), + block_on(wire.sign_tip( + "ab12".into(), + "500000000000".into(), + ADDR.into(), + String::new(), + )) + .unwrap_err(), + ] { + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + } } diff --git a/src/node.rs b/src/node.rs index 5ca5bbe..c6e3fd5 100644 --- a/src/node.rs +++ b/src/node.rs @@ -520,6 +520,57 @@ impl Node { self.try_send(&onion, friend_pk, &prekey, &pt).await } + /// Sign an invoice with this node's identity key. + /// + /// The signing half of [`Self::pay_invoice`], for callers that build the + /// frame themselves (the Android SDK). The ed25519 secret never leaves the + /// node: it is signed with here and not handed out. `amount_atomic` is + /// piconero; `address` must be a valid Monero address; `memo` may be empty. + pub fn sign_invoice( + &self, + amount_atomic: &str, + address: &str, + memo: &str, + ) -> Result { + let k = self.keys()?; + pay::sign_invoice(&k.identity_sk, amount_atomic, address, memo, unix_now()) + .map_err(|e| e.to_string()) + } + + /// Sign a receipt for a transfer that already happened: the signing half of + /// [`Self::tip`]. Same key discipline as [`Self::sign_invoice`]. + pub fn sign_receipt( + &self, + txid: &str, + amount_atomic: &str, + address: &str, + ) -> Result { + let k = self.keys()?; + pay::sign_receipt(&k.identity_sk, txid, amount_atomic, address, unix_now()) + .map_err(|e| e.to_string()) + } + + /// Sign a tip frame (receipt + memo) for a transfer that already happened. + /// This signs only — it does not move funds; that is [`Self::tip`]. + pub fn sign_tip( + &self, + txid: &str, + amount_atomic: &str, + address: &str, + memo: &str, + ) -> Result { + let k = self.keys()?; + pay::sign_tip( + &k.identity_sk, + txid, + amount_atomic, + address, + memo, + unix_now(), + ) + .map_err(|e| e.to_string()) + } + /// Invoice to receive. Wallet subaddress if up, else self_profile.xmr_addr. pub async fn pay_invoice( &self, @@ -528,9 +579,7 @@ impl Node { memo: &str, ) -> Result<(), String> { let address = self.invoice_address().await?; - let k = self.keys()?; - let inv = pay::sign_invoice(&k.identity_sk, atomic, &address, memo, unix_now()) - .map_err(|e| e.to_string())?; + let inv = self.sign_invoice(atomic, &address, memo)?; let pt = pay::encode_invoice(&inv); self.send_once(friend_pk, &pt).await?; let store = self.store.lock().map_err(|e| e.to_string())?; @@ -579,12 +628,9 @@ impl Node { .transfer(&address, amount) .await .map_err(|e| e.to_string())?; - let k = self.keys()?; - let rcp = pay::sign_receipt(&k.identity_sk, &txid, atomic, &address, unix_now()) - .map_err(|e| e.to_string())?; + let rcp = self.sign_receipt(&txid, atomic, &address)?; 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 = self.sign_tip(&txid, atomic, &address, _memo)?; let tip_pt = pay::encode_tip(&tip); self.send_once(friend_pk, &rcp_pt).await?; self.send_once(friend_pk, &tip_pt).await?; -- 2.52.0