diff --git a/src/api/mod.rs b/src/api/mod.rs index 4992ec4..289603f 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -66,6 +66,7 @@ pub fn configure(cfg: &mut web::ServiceConfig) { web::scope("/api") .route("/admin/crosschain", web::get().to(crate::crosschain::operations::admin_issues)) .route("/admin/crosschain/{id}/retry", web::post().to(crate::crosschain::operations::retry)) + .route("/admin/crosschain/{id}/dismiss", web::post().to(crate::crosschain::operations::dismiss)) .route("/health", web::get().to(system::health)) .route("/invoices/{id}/checkout-access", web::get().to(crate::crosschain::security::access)) .service( diff --git a/src/crosschain.rs b/src/crosschain.rs index 9f28103..e1be1da 100644 --- a/src/crosschain.rs +++ b/src/crosschain.rs @@ -255,7 +255,7 @@ impl Gateway { if let Some(error) = minimum_swap_usd_error(status, &body) { return Err(error.into()); } - bail!("No quote available for this route and amount"); + bail!(NO_QUOTE); } let response: Value = res.json().await?; signatures::verify_fresh(&response)?; @@ -264,6 +264,8 @@ impl Gateway { } } +const NO_QUOTE: &str = "No quote available for this route and amount"; + pub async fn migrate(pool: &SqlitePool) -> anyhow::Result<()> { let mut tx = pool.begin().await?; sqlx::query("ALTER TABLE invoices ADD COLUMN exact_payment INTEGER NOT NULL DEFAULT 0") @@ -868,8 +870,8 @@ pub async fn create( Ok(a) => HttpResponse::Ok() .insert_header(("Cache-Control", "no-store")) .json(a), - Err(_) => { - tracing::warn!(invoice_id = %id, stage = setup_stage, "Cross-chain payment setup failed; reservation preserved"); + Err(e) => { + tracing::warn!(invoice_id = %id, stage = setup_stage, kind = %setup_error_kind(&e), "Cross-chain payment setup failed; reservation preserved"); // Outcome may be ambiguous: keep the reservation rather than risk a // second swap. No deposit instructions have been shown to the buyer. let _ = sqlx::query("UPDATE crosschain_attempts SET state='NEEDS_REVIEW' WHERE invoice_id=? AND payload IS NULL") @@ -882,6 +884,32 @@ pub async fn create( } } +/// Coarse failure class for setup logs. Never includes provider messages, +/// which may echo destination or refund data. +fn setup_error_kind(e: &anyhow::Error) -> String { + if e.downcast_ref::().is_some() { + return "slot_timeout".into(); + } + if e.downcast_ref::().is_some() || e.downcast_ref::().is_some() { + return "below_minimum".into(); + } + if let Some(r) = e.downcast_ref::() { + return if r.is_timeout() { "provider_timeout".into() } + else if r.is_connect() { "provider_connect".into() } + else if r.is_decode() { "provider_decode".into() } + else if let Some(s) = r.status() { format!("provider_http_{}", s.as_u16()) } + else { "provider_request".into() }; + } + if e.downcast_ref::().is_some() { + return "database".into(); + } + // Our own message for a non-success provider status (see `Gateway::quote`). + if e.to_string() == NO_QUOTE { + return "provider_rejected".into(); + } + "other".into() +} + async fn read_attempt(pool: &SqlitePool, id: &str, key: &str) -> anyhow::Result> { let row: Option<(String, Option, i64, Option, Option, bool)> = sqlx::query_as( "SELECT state,payload,last_success,send_token,sent_txid, diff --git a/src/crosschain/operations.rs b/src/crosschain/operations.rs index f1c2cc1..7784cd4 100644 --- a/src/crosschain/operations.rs +++ b/src/crosschain/operations.rs @@ -5,6 +5,13 @@ pub async fn migrate(pool: &SqlitePool) -> anyhow::Result<()> { sqlx::query("ALTER TABLE merchants ADD COLUMN crosschain_enabled INTEGER NOT NULL DEFAULT 1 CHECK(crosschain_enabled IN (0,1))").execute(pool).await?; Ok(()) } +pub async fn migrate_dismissals(pool: &SqlitePool) -> anyhow::Result<()> { + sqlx::query("CREATE TABLE crosschain_dismissals ( + invoice_id TEXT PRIMARY KEY REFERENCES invoices(id) ON DELETE CASCADE, + prior_state TEXT NOT NULL, reason TEXT NOT NULL, + dismissed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')))").execute(pool).await?; + Ok(()) +} pub async fn enabled(pool: &SqlitePool, invoice: &str) -> anyhow::Result { Ok(sqlx::query_scalar("SELECT m.crosschain_enabled FROM merchants m JOIN invoices i ON i.merchant_id=m.id WHERE i.id=?") .bind(invoice).fetch_optional(pool).await?.unwrap_or(false)) @@ -25,6 +32,7 @@ pub async fn issues(pool: &SqlitePool) -> anyhow::Result> { OR (a.state IN ('FAILED','INCOMPLETE_DEPOSIT') AND i.status NOT IN ('cancelled','refunded')) OR (a.state IN ('KNOWN_DEPOSIT_TX','PROCESSING','SUCCESS') AND i.status NOT IN ('confirmed','refunded','cancelled') AND i.expires_at,path:w Err(e)=>HttpResponse::Conflict().json(json!({"error":e.to_string()})), } } + +#[derive(serde::Deserialize)] +pub struct DismissInput { + reason: String, +} + +/// Close a setup review that provably never produced a payable quote. +/// Only an attempt with no saved quote, no wallet send, an expired or +/// cancelled invoice and no received ZEC qualifies. Nothing is deleted: +/// the attempt and fee reservation stay as they are, and the dismissal +/// row records why. A later confirmation of the invoice re-surfaces it. +pub(crate) async fn dismiss_unquoted(pool: &SqlitePool, id: &str, reason: &str) -> anyhow::Result<()> { + let reason = reason.trim(); + ensure!((3..=500).contains(&reason.chars().count()), "Give a reason of 3 to 500 characters"); + let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?; + let row: Option<(String, bool, bool, String, i64, i64)> = sqlx::query_as( + "SELECT a.state, a.payload IS NULL, a.send_token IS NULL AND a.sent_txid IS NULL, i.status, i.received_zatoshis, + (SELECT COUNT(*) FROM invoice_payments p WHERE p.invoice_id=i.id) + FROM crosschain_attempts a JOIN invoices i ON i.id=a.invoice_id WHERE a.invoice_id=?") + .bind(id).fetch_optional(&mut *tx).await?; + let (state, unquoted, unsent, status, received, payments) = row.context("No cross-chain attempt for this invoice")?; + ensure!(matches!(state.as_str(), "NEEDS_REVIEW" | "CREATING"), "Only setup reviews can be dismissed"); + ensure!(unquoted && unsent, "A quote or wallet send exists; review it with the provider instead"); + ensure!(matches!(status.as_str(), "expired" | "cancelled"), "Invoice must be expired or cancelled"); + ensure!(received == 0 && payments == 0, "Invoice has received ZEC"); + let fee_ok: bool = sqlx::query_scalar( + "SELECT NOT EXISTS(SELECT 1 FROM crosschain_fees WHERE invoice_id=? AND (state!='reserved' OR correlation_id IS NOT NULL))") + .bind(id).fetch_one(&mut *tx).await?; + ensure!(fee_ok, "Fee record is bound to a quote"); + let inserted = sqlx::query("INSERT OR IGNORE INTO crosschain_dismissals(invoice_id,prior_state,reason) VALUES (?,?,?)") + .bind(id).bind(&state).bind(reason).execute(&mut *tx).await?; + ensure!(inserted.rows_affected() == 1, "Already dismissed"); + tx.commit().await?; + tracing::info!(invoice_id = %id, prior_state = %state, "Cross-chain setup review dismissed"); + Ok(()) +} + +pub async fn dismiss(req: actix_web::HttpRequest, pool: web::Data, path: web::Path, input: web::Json) -> HttpResponse { + if !crate::api::admin::authenticate_admin(&req) { return HttpResponse::Unauthorized().finish(); } + match dismiss_unquoted(&pool, path.as_str(), &input.reason).await { + Ok(()) => HttpResponse::Ok().json(json!({"ok":true})), + Err(e) => HttpResponse::Conflict().json(json!({"error":e.to_string()})), + } +} + +#[cfg(test)] +mod dismiss_tests { + use super::*; + use crate::repair_tests::{invoice, merchant, pool}; + + async fn unquoted_review(p: &SqlitePool, id: &str) { + invoice(p, id, "m").await; + sqlx::query("UPDATE invoices SET status='expired' WHERE id=?").bind(id).execute(p).await.unwrap(); + sqlx::query("INSERT INTO crosschain_attempts(invoice_id,state) VALUES (?,'NEEDS_REVIEW')").bind(id).execute(p).await.unwrap(); + sqlx::query("INSERT INTO crosschain_fees(invoice_id,asset_id,recipient,total_bps,cipherpay_bps,failures) VALUES (?,'usdc','cipherscan.near',145,125,564)") + .bind(id).execute(p).await.unwrap(); + } + async fn listed(p: &SqlitePool, id: &str) -> bool { + issues(p).await.unwrap().iter().any(|i| i["invoice_id"] == id) + } + + #[tokio::test] + async fn dismisses_only_unquoted_unpaid_expired_setup_and_keeps_records() { + let p = pool().await; + merchant(&p, "m").await; + unquoted_review(&p, "a").await; + assert!(listed(&p, "a").await); + assert!(dismiss_unquoted(&p, "a", " ").await.unwrap_err().to_string().contains("reason")); + dismiss_unquoted(&p, "a", "Provider never returned a quote; no deposit address issued").await.unwrap(); + assert!(!listed(&p, "a").await); + assert!(dismiss_unquoted(&p, "a", "again please").await.unwrap_err().to_string().contains("Already dismissed")); + // Attempt and fee reservation are untouched; the dismissal is recorded. + let attempt: (String, Option) = sqlx::query_as("SELECT state,payload FROM crosschain_attempts WHERE invoice_id='a'").fetch_one(&p).await.unwrap(); + assert_eq!(attempt, ("NEEDS_REVIEW".to_string(), None)); + let fee: (String, i64) = sqlx::query_as("SELECT state,failures FROM crosschain_fees WHERE invoice_id='a'").fetch_one(&p).await.unwrap(); + assert_eq!(fee, ("reserved".to_string(), 564)); + let d: (String, String) = sqlx::query_as("SELECT prior_state,reason FROM crosschain_dismissals WHERE invoice_id='a'").fetch_one(&p).await.unwrap(); + assert_eq!(d.0, "NEEDS_REVIEW"); + // A later confirmation re-surfaces it for review. + sqlx::query("UPDATE invoices SET status='confirmed' WHERE id='a'").execute(&p).await.unwrap(); + assert!(listed(&p, "a").await); + } + + #[tokio::test] + async fn refuses_quoted_sent_unexpired_or_paid_attempts() { + let p = pool().await; + merchant(&p, "m").await; + let reason = "test dismissal"; + unquoted_review(&p, "quoted").await; + sqlx::query("UPDATE crosschain_attempts SET payload='enc' WHERE invoice_id='quoted'").execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "quoted", reason).await.unwrap_err().to_string().contains("quote or wallet send")); + unquoted_review(&p, "sent").await; + sqlx::query("UPDATE crosschain_attempts SET send_token='t' WHERE invoice_id='sent'").execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "sent", reason).await.is_err()); + unquoted_review(&p, "pending").await; + sqlx::query("UPDATE invoices SET status='pending' WHERE id='pending'").execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "pending", reason).await.unwrap_err().to_string().contains("expired or cancelled")); + unquoted_review(&p, "paid").await; + sqlx::query("INSERT INTO invoice_payments(invoice_id,txid,zatoshis) VALUES ('paid',?,10)").bind("ab".repeat(32)).execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "paid", reason).await.unwrap_err().to_string().contains("received ZEC")); + unquoted_review(&p, "bound").await; + sqlx::query("UPDATE crosschain_fees SET correlation_id='c' WHERE invoice_id='bound'").execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "bound", reason).await.unwrap_err().to_string().contains("Fee record")); + unquoted_review(&p, "failed").await; + sqlx::query("UPDATE crosschain_attempts SET state='FAILED' WHERE invoice_id='failed'").execute(&p).await.unwrap(); + assert!(dismiss_unquoted(&p, "failed", reason).await.unwrap_err().to_string().contains("setup reviews")); + assert!(dismiss_unquoted(&p, "missing", reason).await.is_err()); + for id in ["quoted", "sent", "pending", "paid", "bound", "failed"] { + assert!(listed(&p, id).await || id == "pending", "{id} should stay flagged"); + } + assert_eq!(sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM crosschain_dismissals").fetch_one(&p).await.unwrap(), 0); + } +} diff --git a/src/crosschain/tests.rs b/src/crosschain/tests.rs index 86e62b0..ca701c7 100644 --- a/src/crosschain/tests.rs +++ b/src/crosschain/tests.rs @@ -1140,3 +1140,13 @@ fn real_provider_confidential_quote() { let quote = checked_quote(&response, &body, &asset(), true).unwrap(); assert_eq!(quote["confidentiality"], "basic"); } + +#[tokio::test] +async fn setup_errors_are_classified_without_provider_text() { + let elapsed = tokio::time::timeout(std::time::Duration::from_millis(1), std::future::pending::<()>()).await.unwrap_err(); + assert_eq!(setup_error_kind(&anyhow::Error::from(elapsed)), "slot_timeout"); + assert_eq!(setup_error_kind(&anyhow::Error::from(BelowMinimumOutput(5))), "below_minimum"); + assert_eq!(setup_error_kind(&anyhow::anyhow!(NO_QUOTE)), "provider_rejected"); + assert_eq!(setup_error_kind(&anyhow::anyhow!("signature mismatch")), "other"); +} + diff --git a/src/db.rs b/src/db.rs index e48333f..df72198 100644 --- a/src/db.rs +++ b/src/db.rs @@ -377,6 +377,8 @@ pub async fn create_pool(database_url: &str) -> anyhow::Result { run_tracked_migration(&pool, "crosschain_provider_handled_v2026_10_14", || crate::crosschain::fees::migrate_provider_handled(&pool)).await?; + run_tracked_migration(&pool, "crosschain_dismissals_v2026_11_15", || crate::crosschain::operations::migrate_dismissals(&pool)).await?; + Ok(pool) }