onionwire/src/pay.rs
rust-dev b8c52ca97d
All checks were successful
ci / test (pull_request) Successful in 19m52s
ci / sdk (pull_request) Successful in 2m16s
pay: domain-separate tip and gate legacy signature acceptance
`tip` was the one payment frame with no domain tag: sign_tip signed the
LF-joined fields, so its signature could be confused with any other
newline-joined preimage. Mirror inv/rcp: sign_tip now emits
"onionwire-tip-v1" || 0x00-separated txid/amount/address/memo/ts, and
verify_tip tries that form then the historical layout.

Legacy acceptance is now one switch instead of nine call sites:
`pay::LEGACY_SIGS` (default true) plus `pay::legacy_sigs()`. Every v1 /
concat fallback reads it — the `onionwire:v1` invite string and its two
historical signature forms, `loc`, `inv`, `rcp`, and `tip`. `prf` is not
gated here because src/profile.rs is outside this card's file scope; the
spec says so.

Tests: legacy-on keeps every untagged form verifying (incl. a new tip
case); legacy-off rejects each untagged form while the tagged form still
verifies (loc, inv, rcp, tip, invite); sign_tip is pinned to the tagged
layout.

docs/PROTOCOL.md gains the emitted/accepted table per signed frame and
the mixed-fleet consequence.
2026-10-22 22:23:44 -04:00

630 lines
18 KiB
Rust

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha3::{Digest, Keccak256};
use std::cell::Cell;
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
/// Legacy signature acceptance.
///
/// Every signed frame is **emitted** in its domain-tagged form. Inbound, the
/// historical untagged / LF-joined layout (and the `onionwire:v1` invite
/// string) is still accepted so a mixed-version fleet keeps working; that
/// fallback is gated on this one switch. Set it to `false` to fail closed on
/// legacy signatures for every frame that reads it — `loc`, the invite string,
/// `inv`, `rcp`, and `tip`. (`prf` is not yet gated; see `docs/PROTOCOL.md`.)
pub const LEGACY_SIGS: bool = true;
thread_local! {
/// Per-thread override for tests. `None` follows [`LEGACY_SIGS`].
static LEGACY_SIGS_OVERRIDE: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Whether legacy (pre-domain-tag) signatures are accepted inbound.
pub fn legacy_sigs() -> bool {
LEGACY_SIGS_OVERRIDE
.with(|o| o.get())
.unwrap_or(LEGACY_SIGS)
}
/// Run `f` with legacy acceptance forced to `on`, then restore the previous
/// thread state. A test hook, not a runtime setting: production code reads the
/// switch through [`legacy_sigs`] only.
#[doc(hidden)]
pub fn with_legacy_sigs<R>(on: bool, f: impl FnOnce() -> R) -> R {
struct Restore(Option<bool>);
impl Drop for Restore {
fn drop(&mut self) {
LEGACY_SIGS_OVERRIDE.with(|o| o.set(self.0));
}
}
let _restore = Restore(LEGACY_SIGS_OVERRIDE.with(|o| o.replace(Some(on))));
f()
}
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invoice {
pub amount_atomic: String,
pub address: String,
pub memo: String,
pub ts: i64,
pub sig: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Receipt {
pub txid: String,
pub amount_atomic: String,
pub address: String,
pub ts: i64,
pub sig: Vec<u8>,
}
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.
const B58: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const B58_ENC_LEN: [usize; 9] = [0, 2, 3, 5, 6, 7, 9, 10, 11];
pub fn check_address(addr: &str) -> Result<()> {
let raw = decode_monero_b58(addr).ok_or_else(|| Error("invalid Monero address".into()))?;
if raw.len() != 69 && raw.len() != 77 {
return Err(Error("invalid Monero address".into()));
}
let (payload, ck) = raw.split_at(raw.len() - 4);
let hash = Keccak256::digest(payload);
if hash.as_slice().get(..4) != Some(ck) {
return Err(Error("invalid Monero address".into()));
}
let ok = match (payload[0], raw.len()) {
(18 | 24 | 42 | 36, 69) => true, // mainnet/stagenet standard + subaddress
(19 | 25, 77) => true, // mainnet/stagenet integrated
_ => false,
};
if ok {
Ok(())
} else {
Err(Error("invalid Monero address".into()))
}
}
fn decode_monero_b58(addr: &str) -> Option<Vec<u8>> {
let bytes = addr.as_bytes();
if bytes.is_empty() || !bytes.iter().all(|b| B58.contains(b)) {
return None;
}
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
let rest = bytes.len() - i;
let (enc_len, dec_len) = if rest >= 11 {
(11, 8)
} else {
let dec_len = B58_ENC_LEN.iter().position(|&n| n == rest)?;
(rest, dec_len)
};
out.extend_from_slice(&decode_b58_block(&bytes[i..i + enc_len], dec_len)?);
i += enc_len;
}
Some(out)
}
fn decode_b58_block(enc: &[u8], out_len: usize) -> Option<Vec<u8>> {
let mut acc: u128 = 0;
for &c in enc {
let d = B58.iter().position(|&a| a == c)? as u128;
acc = acc.checked_mul(58)?.checked_add(d)?;
}
let max = if out_len >= 16 {
return None;
} else if out_len == 0 {
0
} else {
(1u128 << (8 * out_len)) - 1
};
if acc > max {
return None;
}
Some(acc.to_be_bytes()[16 - out_len..].to_vec())
}
pub fn parse_atomic(s: &str) -> Result<u128> {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(Error("amount must be decimal piconero".into()));
}
let n: u128 = s.parse().map_err(|_| Error("amount out of range".into()))?;
if n == 0 {
return Err(Error("amount must be > 0".into()));
}
Ok(n)
}
pub fn xmr_to_atomic(s: &str) -> Result<String> {
let s = s.trim();
let (whole, frac) = match s.split_once('.') {
Some((w, f)) => (w, f),
None => (s, ""),
};
if whole.is_empty() || !whole.bytes().all(|b| b.is_ascii_digit()) {
return Err(Error("invalid XMR amount".into()));
}
if frac.len() > 12 || !frac.bytes().all(|b| b.is_ascii_digit()) {
return Err(Error("invalid XMR amount".into()));
}
let mut frac_pad = frac.to_string();
while frac_pad.len() < 12 {
frac_pad.push('0');
}
let combined = format!("{whole}{frac_pad}");
let n: u128 = combined
.parse()
.map_err(|_| Error("amount out of range".into()))?;
if n == 0 {
return Err(Error("amount must be > 0".into()));
}
Ok(n.to_string())
}
pub fn atomic_to_xmr_str(s: &str) -> String {
let n: u128 = s.parse().unwrap_or(0);
let whole = n / PICONERO;
let frac = n % PICONERO;
if frac == 0 {
return whole.to_string();
}
let mut f = format!("{frac:012}");
while f.ends_with('0') {
f.pop();
}
format!("{whole}.{f}")
}
pub fn invoice_chat_line(amount_atomic: &str, memo: &str) -> String {
let xmr = atomic_to_xmr_str(amount_atomic);
if memo.is_empty() {
format!("[invoice] {xmr} XMR")
} else {
format!("[invoice] {xmr} XMR — {memo}")
}
}
pub fn receipt_chat_line(amount_atomic: &str, verified: bool) -> String {
let xmr = atomic_to_xmr_str(amount_atomic);
if verified {
format!("[receipt] {xmr} XMR")
} else {
format!("[receipt] {xmr} XMR — unverified")
}
}
pub fn sign_invoice(
identity_sk: &[u8],
amount_atomic: &str,
address: &str,
memo: &str,
ts: i64,
) -> Result<Invoice> {
check_invoice_fields(amount_atomic, address, memo)?;
let sig = sign_bytes(
identity_sk,
&inv_sign_msg_v2(amount_atomic, address, memo, ts),
)?;
Ok(Invoice {
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
memo: memo.to_string(),
ts,
sig,
})
}
pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool {
if check_invoice_fields(&inv.amount_atomic, &inv.address, &inv.memo).is_err() {
return false;
}
verify_bytes(
identity_pk,
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
))
}
pub fn encode_invoice(inv: &Invoice) -> Vec<u8> {
let mut out = Vec::from(INV_PREFIX);
out.extend_from_slice(inv.amount_atomic.as_bytes());
out.push(b'\n');
out.extend_from_slice(inv.address.as_bytes());
out.push(b'\n');
out.extend_from_slice(inv.memo.as_bytes());
out.push(b'\n');
out.extend_from_slice(inv.ts.to_string().as_bytes());
out.push(b'\n');
out.extend_from_slice(to_hex(&inv.sig).as_bytes());
out
}
pub fn decode_invoice(pt: &[u8]) -> Option<Invoice> {
let rest = pt.strip_prefix(INV_PREFIX)?;
let text = std::str::from_utf8(rest).ok()?;
let mut parts = text.splitn(5, '\n');
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_invoice_fields(&amount_atomic, &address, &memo).is_err() {
return None;
}
Some(Invoice {
amount_atomic,
address,
memo,
ts,
sig,
})
}
pub fn sign_receipt(
identity_sk: &[u8],
txid: &str,
amount_atomic: &str,
address: &str,
ts: i64,
) -> Result<Receipt> {
check_receipt_fields(txid, amount_atomic, address)?;
let sig = sign_bytes(
identity_sk,
&rcp_sign_msg_v2(txid, amount_atomic, address, ts),
)?;
Ok(Receipt {
txid: txid.to_string(),
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
ts,
sig,
})
}
pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool {
if check_receipt_fields(&rcp.txid, &rcp.amount_atomic, &rcp.address).is_err() {
return false;
}
verify_bytes(
identity_pk,
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
))
}
pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> {
let mut out = Vec::from(RCP_PREFIX);
out.extend_from_slice(rcp.txid.as_bytes());
out.push(b'\n');
out.extend_from_slice(rcp.amount_atomic.as_bytes());
out.push(b'\n');
out.extend_from_slice(rcp.address.as_bytes());
out.push(b'\n');
out.extend_from_slice(rcp.ts.to_string().as_bytes());
out.push(b'\n');
out.extend_from_slice(to_hex(&rcp.sig).as_bytes());
out
}
pub fn decode_receipt(pt: &[u8]) -> Option<Receipt> {
let rest = pt.strip_prefix(RCP_PREFIX)?;
let text = std::str::from_utf8(rest).ok()?;
let mut parts = text.splitn(5, '\n');
let txid = parts.next()?.to_string();
let amount_atomic = parts.next()?.to_string();
let address = parts.next()?.to_string();
let ts = parts.next()?.parse::<i64>().ok()?;
let sig = from_hex(parts.next()?)?;
if check_receipt_fields(&txid, &amount_atomic, &address).is_err() {
return None;
}
Some(Receipt {
txid,
amount_atomic,
address,
ts,
sig,
})
}
// ---- 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_v2(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-tip-v1",
&[
txid.as_bytes(),
amount_atomic.as_bytes(),
address.as_bytes(),
memo.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
/// Historical untagged form. Accept-only, and only while [`LEGACY_SIGS`] is on.
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_v2(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_v2(
&tip.txid,
&tip.amount_atomic,
&tip.address,
&tip.memo,
tip.ts,
),
&tip.sig,
) || (legacy_sigs()
&& 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)?;
if memo.contains('\n') {
return Err(Error("memo must not contain newlines".into()));
}
Ok(())
}
fn check_receipt_fields(txid: &str, amount_atomic: &str, address: &str) -> Result<()> {
if txid.is_empty() || txid.contains('\n') {
return Err(Error("invalid txid".into()));
}
parse_atomic(amount_atomic)?;
check_address(address)
}
fn inv_sign_msg_v2(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-inv-v1",
&[
amount_atomic.as_bytes(),
address.as_bytes(),
memo.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
fn inv_sign_msg_v1(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(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
}
fn rcp_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-rcp-v1",
&[
txid.as_bytes(),
amount_atomic.as_bytes(),
address.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
fn rcp_sign_msg_v1(txid: &str, amount_atomic: &str, address: &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(ts.to_string().as_bytes());
msg
}
fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
let mut msg = Vec::from(tag);
for f in fields {
msg.push(0);
msg.extend_from_slice(f);
}
msg
}
fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result<Vec<u8>> {
// ed25519-dalek's `SigningKey` wipes itself on drop (its default `zeroize`
// feature); the raw copy we make to build it is ours to wipe.
let sk_bytes = Zeroizing::new(
<[u8; 32]>::try_from(identity_sk)
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?,
);
let sk = SigningKey::from_bytes(&sk_bytes);
Ok(sk.sign(msg).to_bytes().to_vec())
}
fn verify_bytes(identity_pk: &[u8], msg: &[u8], sig: &[u8]) -> bool {
if identity_pk.len() != 32 || sig.len() != 64 {
return false;
}
let pk: [u8; 32] = match identity_pk.try_into() {
Ok(p) => p,
Err(_) => return false,
};
let sig: [u8; 64] = match sig.try_into() {
Ok(s) => s,
Err(_) => return false,
};
let Ok(vk) = VerifyingKey::from_bytes(&pk) else {
return false;
};
vk.verify(msg, &Signature::from_bytes(&sig)).is_ok()
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn from_hex(s: &str) -> Option<Vec<u8>> {
if s.is_empty() || !s.len().is_multiple_of(2) {
return None;
}
if !s.bytes().all(|c| c.is_ascii_hexdigit()) {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}