Skip to main content

clm_rust_core/layer4/
payment.rs

1//! Payment PCard — Multi-Rail Abstraction Engine
2//! Polymorphic payment processing across Stripe, QRIS, Indonesian Banks, and Cryptocurrency On-Chain.
3
4use crate::layer0::vocabulary::{HANDLE_MCARD_PAYMENT_INVOICE, HANDLE_MCARD_PAYMENT_RAIL, HANDLE_MCARD_PAYMENT_RECEIPT, HASH_PREFIX_SHA256};
5use rand::RngCore;
6use serde::{Deserialize, Serialize};
7use std::path::{Path, PathBuf};
8use rusqlite::Connection;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct PaymentRailRecord {
12    pub rail_id: String,
13    pub rail_type: String,
14    pub handle: String,
15    pub content_hash: String,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct PaymentInvoiceRecord {
20    pub invoice_id: String,
21    pub handle: String,
22    pub buyer_did: String,
23    pub merchant_did: String,
24    pub amount: f64,
25    pub currency: String,
26    pub content_hash: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct PaymentReceiptRecord {
31    pub tx_id: String,
32    pub handle: String,
33    pub invoice_id: String,
34    pub invoice_hash: String,
35    pub buyer_did: String,
36    pub merchant_did: String,
37    pub rail_id: String,
38    pub rail_type: String,
39    pub amount: f64,
40    pub currency: String,
41    pub status: String,
42    pub content_hash: String,
43}
44
45fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
46    let p = Path::new(db_name_or_path);
47    if p.is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
48        p.to_path_buf()
49    } else {
50        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
51            crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ROOT).map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
52        });
53        root.join("db").join(db_name_or_path)
54    }
55}
56
57fn init_db_tables(conn: &Connection) -> Result<(), String> {
58    let _ = conn.busy_timeout(std::time::Duration::from_millis(u64::from(crate::layer0::runtime_contract::SQLITE_BUSY_TIMEOUT_MS)));
59    conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1).map_err(|e| e.to_string())?;
60
61    // Idempotent migration from legacy `hash` column
62    let has_hash: bool = conn
63        .query_row(
64            "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'hash'",
65            [],
66            |r| r.get(0),
67        )
68        .unwrap_or(false);
69    if has_hash {
70        let has_curr: bool = conn
71            .query_row(
72                "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
73                [],
74                |r| r.get(0),
75            )
76            .unwrap_or(false);
77        if !has_curr {
78            let _ = conn.execute_batch("ALTER TABLE handle_registry RENAME COLUMN hash TO current_hash;");
79        }
80    }
81    Ok(())
82}
83
84/// Registers a payment rail configuration under `mcard:payment/rail/{rail_id}`.
85pub fn register_payment_rail(
86    db_name_or_path: &str,
87    clm_root: Option<&str>,
88    rail_id: &str,
89    rail_type: &str,
90    _config_json: Option<&str>,
91) -> Result<PaymentRailRecord, String> {
92    let handle = format!("{HANDLE_MCARD_PAYMENT_RAIL}{}", rail_id);
93    let db_path = resolve_db_path(db_name_or_path, clm_root);
94    if let Some(parent) = db_path.parent() {
95        let _ = std::fs::create_dir_all(parent);
96    }
97    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
98    init_db_tables(&conn)?;
99
100    let content_json = serde_json::json!({
101        "rail_id": rail_id,
102        "rail_type": rail_type,
103        "status": "active",
104    }).to_string();
105
106    let content_hash = format!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(content_json.as_bytes()));
107
108    conn.execute(
109        "INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
110        rusqlite::params![content_hash, content_json, crate::fs_utils::compute_g_time()],
111    ).map_err(|e| e.to_string())?;
112
113    let now = chrono::Utc::now().to_rfc3339();
114    conn.execute(
115        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
116         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
117        rusqlite::params![handle, content_hash, now],
118    ).map_err(|e| e.to_string())?;
119
120    Ok(PaymentRailRecord {
121        rail_id: rail_id.to_string(),
122        rail_type: rail_type.to_string(),
123        handle,
124        content_hash,
125    })
126}
127
128/// Creates a payment invoice under `mcard:payment/invoice/{invoice_id}`.
129pub fn create_payment_invoice(
130    db_name_or_path: &str,
131    clm_root: Option<&str>,
132    buyer_did: &str,
133    merchant_did: &str,
134    amount: f64,
135    currency: &str,
136) -> Result<PaymentInvoiceRecord, String> {
137    let mut inv_bytes = [0u8; 12];
138    rand::thread_rng().fill_bytes(&mut inv_bytes);
139    let invoice_id = format!("inv_{}", hex::encode(inv_bytes));
140    let handle = format!("{HANDLE_MCARD_PAYMENT_INVOICE}{}", invoice_id);
141
142    let db_path = resolve_db_path(db_name_or_path, clm_root);
143    if let Some(parent) = db_path.parent() {
144        let _ = std::fs::create_dir_all(parent);
145    }
146    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
147    init_db_tables(&conn)?;
148
149    let content_json = serde_json::json!({
150        "invoice_id": invoice_id,
151        "buyer_did": buyer_did,
152        "merchant_did": merchant_did,
153        "amount": amount,
154        "currency": currency,
155        "created_at": chrono::Utc::now().to_rfc3339(),
156    }).to_string();
157
158    let content_hash = format!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(content_json.as_bytes()));
159
160    conn.execute(
161        "INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
162        rusqlite::params![content_hash, content_json, crate::fs_utils::compute_g_time()],
163    ).map_err(|e| e.to_string())?;
164
165    let now = chrono::Utc::now().to_rfc3339();
166    conn.execute(
167        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
168         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
169        rusqlite::params![handle, content_hash, now],
170    ).map_err(|e| e.to_string())?;
171
172    Ok(PaymentInvoiceRecord {
173        invoice_id,
174        handle,
175        buyer_did: buyer_did.to_string(),
176        merchant_did: merchant_did.to_string(),
177        amount,
178        currency: currency.to_string(),
179        content_hash,
180    })
181}
182
183/// Processes a payment through a Payment PCard rail and mints a VCard receipt under `mcard:payment/receipt/{tx_id}`.
184pub fn process_payment_pcard(
185    db_name_or_path: &str,
186    clm_root: Option<&str>,
187    invoice_id: &str,
188    rail_id: &str,
189    _payment_payload: Option<&str>,
190) -> Result<PaymentReceiptRecord, String> {
191    let db_path = resolve_db_path(db_name_or_path, clm_root);
192    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
193    init_db_tables(&conn)?;
194
195    let inv_handle = format!("{HANDLE_MCARD_PAYMENT_INVOICE}{}", invoice_id);
196    let query = if conn.query_row(
197        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
198        [],
199        |r| r.get(0),
200    ).unwrap_or(false) {
201        "SELECT c.hash, c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
202    } else {
203        "SELECT c.hash, c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
204    };
205    let (inv_hash, inv_content): (String, String) = conn.query_row(
206        query,
207        rusqlite::params![inv_handle],
208        |row| {
209            let h: String = row.get(0)?;
210            let c: String = row.get(1)?;
211            Ok((h, c))
212        },
213    ).map_err(|_| format!("Invoice {} not found", invoice_id))?;
214
215    let inv_val: serde_json::Value = serde_json::from_str(&inv_content).map_err(|e| e.to_string())?;
216    let buyer_did = inv_val.get("buyer_did").and_then(|x| x.as_str()).unwrap_or(crate::layer0::vocabulary_identities::DID_KEY_UNKNOWN);
217    let merchant_did = inv_val.get("merchant_did").and_then(|x| x.as_str()).unwrap_or(crate::layer0::vocabulary_identities::DID_KEY_UNKNOWN);
218    let amount = inv_val.get("amount").and_then(|x| x.as_f64()).unwrap_or(0.0);
219    let currency = inv_val.get("currency").and_then(|x| x.as_str()).unwrap_or("USD");
220
221    let rail_handle = format!("{HANDLE_MCARD_PAYMENT_RAIL}{}", rail_id);
222    let rail_query = if conn.query_row(
223        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
224        [],
225        |r| r.get(0),
226    ).unwrap_or(false) {
227        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
228    } else {
229        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
230    };
231    let rail_type: String = conn.query_row(
232        rail_query,
233        rusqlite::params![rail_handle],
234        |row| row.get::<usize, String>(0),
235    ).map(|content| {
236        let v: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();
237        v.get("rail_type").and_then(|x| x.as_str()).unwrap_or(rail_id).to_string()
238    }).unwrap_or_else(|_| rail_id.to_string());
239
240    let mut tx_bytes = [0u8; 16];
241    rand::thread_rng().fill_bytes(&mut tx_bytes);
242    let tx_id = format!("tx_{}", hex::encode(tx_bytes));
243    let handle = format!("{HANDLE_MCARD_PAYMENT_RECEIPT}{}", tx_id);
244
245    let receipt_json = serde_json::json!({
246        "tx_id": tx_id,
247        "invoice_id": invoice_id,
248        "invoice_hash": inv_hash,
249        "buyer_did": buyer_did,
250        "merchant_did": merchant_did,
251        "rail_id": rail_id,
252        "rail_type": rail_type,
253        "amount": amount,
254        "currency": currency,
255        "status": "settled",
256        "timestamp": chrono::Utc::now().to_rfc3339(),
257    }).to_string();
258
259    let content_hash = format!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(receipt_json.as_bytes()));
260
261    conn.execute(
262        "INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
263        rusqlite::params![content_hash, receipt_json, crate::fs_utils::compute_g_time()],
264    ).map_err(|e| e.to_string())?;
265
266    let now = chrono::Utc::now().to_rfc3339();
267    conn.execute(
268        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
269         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
270        rusqlite::params![handle, content_hash, now],
271    ).map_err(|e| e.to_string())?;
272
273    Ok(PaymentReceiptRecord {
274        tx_id,
275        handle,
276        invoice_id: invoice_id.to_string(),
277        invoice_hash: inv_hash,
278        buyer_did: buyer_did.to_string(),
279        merchant_did: merchant_did.to_string(),
280        rail_id: rail_id.to_string(),
281        rail_type,
282        amount,
283        currency: currency.to_string(),
284        status: "settled".to_string(),
285        content_hash,
286    })
287}
288
289/// Verifies if a payment receipt is valid, immutable, and settled in SQLite.
290pub fn verify_payment_receipt(
291    db_name_or_path: &str,
292    clm_root: Option<&str>,
293    tx_id: &str,
294) -> Result<bool, String> {
295    let handle = format!("{HANDLE_MCARD_PAYMENT_RECEIPT}{}", tx_id);
296    let db_path = resolve_db_path(db_name_or_path, clm_root);
297
298    if !db_path.exists() {
299        return Ok(false);
300    }
301
302    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
303    let query = if conn.query_row(
304        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
305        [],
306        |r| r.get(0),
307    ).unwrap_or(false) {
308        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
309    } else {
310        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
311    };
312    let content: String = match conn.query_row(
313        query,
314        rusqlite::params![handle],
315        |row| row.get::<usize, String>(0),
316    ) {
317        Ok(c) => c,
318        Err(_) => return Ok(false),
319    };
320
321    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
322    let status = v.get("status").and_then(|x| x.as_str()).unwrap_or("");
323    let inv_hash = v.get("invoice_hash").and_then(|x| x.as_str()).unwrap_or("");
324
325    Ok(status == "settled" && !inv_hash.is_empty())
326}
327
328use sha2::Digest;
329
330// ── Unit Tests ─────────────────────────────────────────────────────────────────
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn test_multi_rail_payment_flow() {
338        let tmp_db = std::env::temp_dir().join("clm_test_payment_flow.db");
339        let _ = std::fs::remove_file(&tmp_db);
340        let db_str = tmp_db.to_str().unwrap();
341
342        // 1. Register rails
343        let stripe = register_payment_rail(db_str, None, "stripe_global", "stripe", None).unwrap();
344        assert_eq!(stripe.handle, "mcard:payment/rail/stripe_global");
345
346        let qris = register_payment_rail(db_str, None, "qris_indo", "qris", None).unwrap();
347        assert_eq!(qris.handle, "mcard:payment/rail/qris_indo");
348
349        // 2. Create invoice
350        let buyer = "did:key:z6MkBuyer123";
351        let merchant = "did:key:z6MkMerchant456";
352        let inv = create_payment_invoice(db_str, None, buyer, merchant, 250.0, "USD").unwrap();
353        assert!(inv.handle.starts_with("mcard:payment/invoice/inv_"));
354
355        // 3. Process payment
356        let receipt = process_payment_pcard(db_str, None, &inv.invoice_id, "stripe_global", None).unwrap();
357        assert!(receipt.handle.starts_with("mcard:payment/receipt/tx_"));
358        assert_eq!(receipt.status, "settled");
359
360        // 4. Verify receipt
361        let is_valid = verify_payment_receipt(db_str, None, &receipt.tx_id).unwrap();
362        assert!(is_valid);
363
364        let _ = std::fs::remove_file(&tmp_db);
365    }
366}