diff --git a/Cargo.lock b/Cargo.lock index 0fda175..daccb1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,9 +151,9 @@ dependencies = [ [[package]] name = "actix-web" -version = "4.19.0" +version = "4.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acd6966acfcc7b66b37bdeea7d11665d5accac89333767e1784d2cecd33984e7" +checksum = "618475ea8d22e5ad6e8aefaf9f56253b6ad856a7522716bea0b48bbb772341ff" dependencies = [ "actix-codec", "actix-http", @@ -194,9 +194,9 @@ dependencies = [ [[package]] name = "actix-web-codegen" -version = "4.5.0" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c9f4c52b954a73c76757a3952d3437fca00a2fbcb49704f8a6ea9f767e73f0" +checksum = "4357272ed7e7ed928f2e6bbb4e422257d0bd4e36f80477faa2f794984b16e386" dependencies = [ "actix-router", "proc-macro2", @@ -1087,7 +1087,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1198,9 +1198,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2671,7 +2671,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3304,7 +3304,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3732,9 +3732,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/README.md b/README.md index 966b78e..65cb8c5 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ Signature = HMAC-SHA256(`timestamp.body`, `webhook_secret`) | `PATCH` | `/api/invoices/{id}/refund-address` | — | Set refund address | | `GET` | `/api/invoices/{id}/stream` | — | SSE payment stream | | `GET` | `/api/invoices/{id}/status` | — | Poll payment status | +| `GET` | `/api/invoices/{id}/payment-request` | — | Machine-readable payment request for agents and wallets: `payable`, `not_payable_reason`, outputs in integer zatoshis with decoded memos (invoice output required, platform fee output optional) | | `GET` | `/api/invoices/{id}/qr` | — | QR code image | | **Subscriptions** | | | | | `POST` | `/api/subscriptions` | API key | Create subscription | diff --git a/src/api/invoices.rs b/src/api/invoices.rs index 517fdb8..9e7fee2 100644 --- a/src/api/invoices.rs +++ b/src/api/invoices.rs @@ -206,6 +206,91 @@ pub async fn get(pool: web::Data, path: web::Path) -> HttpRe } } +/// Public, machine-readable payment request for agents and wallets. +/// Looks up by invoice ID only (not memo code) and exposes no shipping data, +/// refund address or checkout capability token. +pub async fn payment_request( + pool: web::Data, + config: web::Data, + path: web::Path, +) -> HttpResponse { + use crate::invoices::payment_request as pr; + let id = path.into_inner(); + let inv = match invoices::get_invoice(pool.get_ref(), &id).await { + Ok(Some(inv)) => inv, + Ok(None) => { + return HttpResponse::NotFound().json(serde_json::json!({"error": "Invoice not found"})) + } + Err(e) => { + tracing::error!(error = %e, "Failed to get invoice for payment request"); + return HttpResponse::InternalServerError() + .json(serde_json::json!({"error": "Internal error"})); + } + }; + let flags = sqlx::query_as::<_, (bool, bool)>( + "SELECT expires_at > strftime('%Y-%m-%dT%H:%M:%SZ','now'), + EXISTS(SELECT 1 FROM crosschain_attempts WHERE invoice_id = invoices.id) + FROM invoices WHERE id = ?", + ) + .bind(&inv.id) + .fetch_one(pool.get_ref()) + .await; + let (unexpired, crosschain_started) = match flags { + Ok(f) => f, + Err(e) => { + tracing::error!(error = %e, "Failed to read payment request state"); + return HttpResponse::InternalServerError() + .json(serde_json::json!({"error": "Internal error"})); + } + }; + + let outputs = pr::outputs( + &inv.zcash_uri, + &inv.id, + &inv.payment_address, + &inv.memo_code, + inv.price_zatoshis, + ); + let mut reason = pr::not_payable_reason( + &inv.status, + unexpired, + inv.received_zatoshis, + inv.detected_txid.is_some(), + crosschain_started, + ); + if reason.is_none() && outputs.is_none() { + reason = Some("invalid_payment_request"); + } + let payable = reason.is_none(); + let outputs = if payable { outputs.unwrap_or_default() } else { Vec::new() }; + let total: i64 = outputs.iter().map(|o| o.amount_zatoshis).sum(); + let frontend = config.frontend_url.as_deref().unwrap_or("https://cipherpay.app"); + let merchant_origin = get_merchant_webhook_origin(pool.get_ref(), &inv.merchant_id).await; + + HttpResponse::Ok() + .insert_header(("Cache-Control", "no-store")) + .insert_header(("Access-Control-Allow-Origin", "*")) + .json(serde_json::json!({ + "version": pr::VERSION, + "invoice_id": inv.id, + "network": if config.is_testnet() { "zcash:testnet" } else { "zcash:mainnet" }, + "status": inv.status, + "payable": payable, + "not_payable_reason": reason, + "expires_at": inv.expires_at, + "merchant": { "name": inv.merchant_name, "origin": merchant_origin }, + "description": inv.product_name, + "price": { "amount": inv.amount.unwrap_or(inv.price_eur), "currency": inv.currency.as_deref().unwrap_or("EUR") }, + "price_zatoshis": inv.price_zatoshis, + "total_zatoshis": total, + "outputs": outputs, + "zcash_uri": if payable { Some(inv.zcash_uri.as_str()) } else { None }, + "instructions": "Pay each required output (and optionally the platform fee output) in one shielded transaction, with the exact amount and memo. Do not pay when payable is false.", + "status_url": format!("/api/invoices/{}/status", inv.id), + "checkout_url": format!("{}/pay/{}", frontend, inv.id), + })) +} + /// Extract the origin (scheme+host+port) from a merchant's webhook URL. async fn get_merchant_webhook_origin(pool: &SqlitePool, merchant_id: &str) -> Option { let row: Option<(Option,)> = @@ -361,3 +446,71 @@ fn validate_invoice_request(req: &CreateInvoiceRequest) -> Result<(), validation } Ok(()) } + +#[cfg(test)] +mod payment_request_tests { + use super::*; + use actix_web::{test, App}; + use base64::Engine; + + fn b64(s: &str) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s) + } + + #[actix_web::test] + async fn payment_request_reports_outputs_and_refuses_unsafe_states() { + let pool = crate::repair_tests::pool().await; + crate::repair_tests::merchant(&pool, "m").await; + crate::repair_tests::invoice(&pool, "i", "m").await; + let uri = format!( + "zcash:?address=u1inv&amount=0.00001000&memo={}&address.1=u1fee&amount.1=0.00000100&memo.1={}", + b64("CP-i"), + b64("FEE-i") + ); + sqlx::query("UPDATE invoices SET payment_address='u1inv', zcash_uri=?, product_name='Ice', status='pending' WHERE id='i'") + .bind(&uri).execute(&pool).await.unwrap(); + let config = crate::config::Config::from_env().unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool.clone())) + .app_data(web::Data::new(config)) + .route("/{id}", web::get().to(payment_request)), + ) + .await; + let get = |path: &'static str| test::TestRequest::get().uri(path).to_request(); + + let body: serde_json::Value = test::call_and_read_body_json(&app, get("/i")).await; + assert_eq!(body["payable"], true); + assert_eq!(body["total_zatoshis"], 1100); + assert_eq!(body["outputs"][0]["amount_zatoshis"], 1000); + assert_eq!(body["outputs"][0]["memo"], "CP-i"); + assert_eq!(body["outputs"][0]["required"], true); + assert_eq!(body["outputs"][1]["purpose"], "platform_fee"); + assert_eq!(body["outputs"][1]["required"], false); + assert!(body.get("checkout_token").is_none()); + assert!(!body.to_string().contains("refund_address\":\"")); + + // Memo codes are not accepted as lookup keys. + assert_eq!(test::call_service(&app, get("/CP-i")).await.status(), 404); + + // A started cross-chain quote makes direct payment unsafe. + sqlx::query("INSERT INTO crosschain_attempts (invoice_id,state) VALUES ('i','CREATING')") + .execute(&pool).await.unwrap(); + let body: serde_json::Value = test::call_and_read_body_json(&app, get("/i")).await; + assert_eq!(body["payable"], false); + assert_eq!(body["not_payable_reason"], "crosschain_in_progress"); + assert_eq!(body["outputs"].as_array().unwrap().len(), 0); + assert!(body["zcash_uri"].is_null()); + sqlx::query("DELETE FROM crosschain_attempts").execute(&pool).await.unwrap(); + + sqlx::query("UPDATE invoices SET expires_at='2000-01-01T00:00:00Z' WHERE id='i'") + .execute(&pool).await.unwrap(); + let body: serde_json::Value = test::call_and_read_body_json(&app, get("/i")).await; + assert_eq!(body["not_payable_reason"], "expired"); + + sqlx::query("UPDATE invoices SET expires_at='2099-01-01T00:00:00Z', zcash_uri='zcash:u1evil?amount=0.00001&memo=' WHERE id='i'") + .execute(&pool).await.unwrap(); + let body: serde_json::Value = test::call_and_read_body_json(&app, get("/i")).await; + assert_eq!(body["not_payable_reason"], "invalid_payment_request"); + } +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 09a8220..da37386 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -281,6 +281,11 @@ pub fn configure(cfg: &mut web::ServiceConfig) { ) .route("/invoices/{id}", web::get().to(invoices::get)) .route("/invoices/{id}/status", web::get().to(status::get)) + .service( + web::resource("/invoices/{id}/payment-request") + .wrap(Governor::new(&public_read_limit)) + .route(web::get().to(invoices::payment_request)), + ) .route( "/invoices/{id}/stream", web::get().to(invoice_routes::invoice_stream), diff --git a/src/invoices/mod.rs b/src/invoices/mod.rs index 0cb5a80..c4b2b1b 100644 --- a/src/invoices/mod.rs +++ b/src/invoices/mod.rs @@ -1,6 +1,7 @@ use crate::timefmt::TimestampExt; mod amounts; pub mod matching; +pub mod payment_request; pub mod pricing; mod queries; mod types; diff --git a/src/invoices/payment_request.rs b/src/invoices/payment_request.rs new file mode 100644 index 0000000..ac7eef5 --- /dev/null +++ b/src/invoices/payment_request.rs @@ -0,0 +1,213 @@ +//! Machine-readable payment request for agents and wallets. +//! +//! The stored ZIP-321 URI stays the authority for what a wallet pays; this +//! module only restates it with integer zatoshis and decoded memos, and says +//! whether a direct shielded payment would be accepted right now. +use base64::Engine; +use serde::Serialize; + +pub const VERSION: u32 = 1; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Output { + pub address: String, + pub amount_zatoshis: i64, + pub memo: String, + pub purpose: &'static str, + /// The invoice output must be paid. The platform fee output is optional: + /// when a payer omits it, the fee is billed to the merchant instead. + pub required: bool, +} + +/// Why a direct payment must not be sent. `None` means payable. +pub fn not_payable_reason( + status: &str, + unexpired: bool, + received_zatoshis: i64, + detected: bool, + crosschain_started: bool, +) -> Option<&'static str> { + match status { + "pending" => {} + "draft" => return Some("draft"), + "expired" => return Some("expired"), + "underpaid" => return Some("underpaid"), + "detected" | "confirmed" => return Some("already_paid"), + "refunded" => return Some("refunded"), + "cancelled" | "canceled" | "void" => return Some("cancelled"), + _ => return Some("unsupported_status"), + } + if !unexpired { + return Some("expired"); + } + if received_zatoshis > 0 || detected { + return Some("payment_in_progress"); + } + // The scanner can refuse direct transfers once a cross-chain quote exists. + if crosschain_started { + return Some("crosschain_in_progress"); + } + None +} + +/// Exact decimal ZEC (at most 8 fractional digits) to zatoshis, no floats. +pub fn decimal_zec_to_zatoshis(value: &str) -> Option { + let (whole, frac) = value.split_once('.').unwrap_or((value, "")); + if whole.is_empty() || whole.len() > 8 || frac.len() > 8 { + return None; + } + if !whole.bytes().chain(frac.bytes()).all(|b| b.is_ascii_digit()) { + return None; + } + let whole: i64 = whole.parse().ok()?; + let frac: i64 = if frac.is_empty() { + 0 + } else { + format!("{frac:0<8}").parse().ok()? + }; + whole.checked_mul(100_000_000)?.checked_add(frac) +} + +fn memo_text(b64: &str) -> Option { + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(b64.trim_end_matches('=')) + .ok()?; + String::from_utf8(bytes).ok() +} + +/// Parse the ZIP-321 URIs this service writes: a single payment +/// (`zcash:ADDR?amount=&memo=`) or indexed payments (`zcash:?address=...&address.1=...`). +pub fn parse_uri(uri: &str) -> Option> { + let rest = uri.strip_prefix("zcash:")?; + let (path, query) = rest.split_once('?').unwrap_or((rest, "")); + let mut slots: std::collections::BTreeMap; 3]> = Default::default(); + if !path.is_empty() { + slots.entry(0).or_default()[0] = Some(path.to_string()); + } + for pair in query.split('&').filter(|p| !p.is_empty()) { + let (key, value) = pair.split_once('=')?; + let (name, index) = match key.split_once('.') { + Some((name, idx)) => { + if idx.is_empty() || idx.starts_with('0') || !idx.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + (name, idx.parse::().ok()?) + } + None => (key, 0), + }; + let field = match name { + "address" => 0, + "amount" => 1, + "memo" => 2, + _ => return None, + }; + let slot = &mut slots.entry(index).or_default()[field]; + if slot.is_some() { + return None; + } + *slot = Some(value.to_string()); + } + let mut out = Vec::new(); + for [address, amount, memo] in slots.into_values() { + let amount = decimal_zec_to_zatoshis(&amount?)?; + let memo = memo_text(&memo?)?; + out.push((address?, amount, memo)); + } + (!out.is_empty()).then_some(out) +} + +/// Outputs of the invoice's payment request. The invoice output +/// uses the stored integer `price_zatoshis`; any extra output must be the +/// platform fee for this invoice. +pub fn outputs( + uri: &str, + invoice_id: &str, + payment_address: &str, + memo_code: &str, + price_zatoshis: i64, +) -> Option> { + let parsed = parse_uri(uri)?; + let fee_memo = format!("FEE-{invoice_id}"); + let mut result = Vec::with_capacity(parsed.len()); + for (index, (address, amount, memo)) in parsed.into_iter().enumerate() { + if index == 0 { + // URI amounts are formatted from a float; allow 1 zatoshi of + // formatting difference but never pay less than the stored price. + if address != payment_address || memo != memo_code || (amount - price_zatoshis).abs() > 1 { + return None; + } + result.push(Output { address, amount_zatoshis: price_zatoshis, memo, purpose: "invoice", required: true }); + } else if index == 1 && memo == fee_memo && amount > 0 { + result.push(Output { address, amount_zatoshis: amount, memo, purpose: "platform_fee", required: false }); + } else { + return None; + } + } + (price_zatoshis > 0).then_some(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn b64(s: &str) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s) + } + + #[test] + fn decimal_amounts_are_exact() { + assert_eq!(decimal_zec_to_zatoshis("0.00000001"), Some(1)); + assert_eq!(decimal_zec_to_zatoshis("1.5"), Some(150_000_000)); + assert_eq!(decimal_zec_to_zatoshis("12"), Some(1_200_000_000)); + assert_eq!(decimal_zec_to_zatoshis("0.123456789"), None); + assert_eq!(decimal_zec_to_zatoshis("-1"), None); + assert_eq!(decimal_zec_to_zatoshis(".5"), None); + assert_eq!(decimal_zec_to_zatoshis("1e3"), None); + } + + #[test] + fn single_and_fee_uris_parse_to_outputs() { + let single = format!("zcash:u1merchant?amount={:.8}&memo={}", 0.1234_f64, b64("CP-AB12")); + assert_eq!( + outputs(&single, "inv", "u1merchant", "CP-AB12", 12_340_000).unwrap(), + vec![Output { address: "u1merchant".into(), amount_zatoshis: 12_340_000, memo: "CP-AB12".into(), purpose: "invoice", required: true }] + ); + let fee = format!( + "zcash:?address=u1merchant&amount={:.8}&memo={}&address.1=u1fee&amount.1={:.8}&memo.1={}", + 0.1234_f64, b64("CP-AB12"), 0.001234_f64, b64("FEE-inv") + ); + let out = outputs(&fee, "inv", "u1merchant", "CP-AB12", 12_340_000).unwrap(); + assert_eq!(out.len(), 2); + assert_eq!(out[1], Output { address: "u1fee".into(), amount_zatoshis: 123_400, memo: "FEE-inv".into(), purpose: "platform_fee", required: false }); + } + + #[test] + fn inconsistent_or_unknown_uris_are_refused() { + let memo = b64("CP-AB12"); + // Wrong address, memo, amount, foreign fee memo, unknown parameter, duplicate key. + for uri in [ + format!("zcash:u1other?amount=0.1&memo={memo}"), + format!("zcash:u1merchant?amount=0.1&memo={}", b64("CP-OTHER")), + format!("zcash:u1merchant?amount=0.2&memo={memo}"), + format!("zcash:?address=u1merchant&amount=0.1&memo={memo}&address.1=u1fee&amount.1=0.001&memo.1={}", b64("FEE-other")), + format!("zcash:u1merchant?amount=0.1&memo={memo}&label=x"), + format!("zcash:u1merchant?amount=0.1&amount=0.1&memo={memo}"), + "zcash:u1merchant?amount=0.1".to_string(), + ] { + assert!(outputs(&uri, "inv", "u1merchant", "CP-AB12", 10_000_000).is_none(), "{uri}"); + } + } + + #[test] + fn only_fresh_untouched_pending_invoices_are_payable() { + assert_eq!(not_payable_reason("pending", true, 0, false, false), None); + assert_eq!(not_payable_reason("pending", false, 0, false, false), Some("expired")); + assert_eq!(not_payable_reason("pending", true, 5, false, false), Some("payment_in_progress")); + assert_eq!(not_payable_reason("pending", true, 0, true, false), Some("payment_in_progress")); + assert_eq!(not_payable_reason("pending", true, 0, false, true), Some("crosschain_in_progress")); + assert_eq!(not_payable_reason("underpaid", true, 5, false, false), Some("underpaid")); + assert_eq!(not_payable_reason("confirmed", true, 0, false, false), Some("already_paid")); + assert_eq!(not_payable_reason("draft", true, 0, false, false), Some("draft")); + assert_eq!(not_payable_reason("mystery", true, 0, false, false), Some("unsupported_status")); + } +}