clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Payment PCard — Multi-Rail Abstraction Engine
//! Polymorphic payment processing across Stripe, QRIS, Indonesian Banks, and Cryptocurrency On-Chain.

use rand::RngCore;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use rusqlite::Connection;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentRailRecord {
    pub rail_id: String,
    pub rail_type: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentInvoiceRecord {
    pub invoice_id: String,
    pub handle: String,
    pub buyer_did: String,
    pub merchant_did: String,
    pub amount: f64,
    pub currency: String,
    pub content_hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentReceiptRecord {
    pub tx_id: String,
    pub handle: String,
    pub invoice_id: String,
    pub invoice_hash: String,
    pub buyer_did: String,
    pub merchant_did: String,
    pub rail_id: String,
    pub rail_type: String,
    pub amount: f64,
    pub currency: String,
    pub status: String,
    pub content_hash: String,
}

fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
    let p = Path::new(db_name_or_path);
    if p.is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
        p.to_path_buf()
    } else {
        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
            std::env::var("CLM_ROOT").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
        });
        root.join("db").join(db_name_or_path)
    }
}

fn init_db_tables(conn: &Connection) -> Result<(), String> {
    let _ = conn.execute_batch("PRAGMA busy_timeout = 5000;");
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS card (
            hash TEXT PRIMARY KEY,
            content TEXT NOT NULL,
            g_time TEXT
        );
        CREATE TABLE IF NOT EXISTS handle_registry (
            handle TEXT PRIMARY KEY,
            current_hash TEXT NOT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (current_hash) REFERENCES card(hash)
        );"
    ).map_err(|e| e.to_string())?;

    // Idempotent migration from legacy `hash` column
    let has_hash: bool = conn
        .query_row(
            "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'hash'",
            [],
            |r| r.get(0),
        )
        .unwrap_or(false);
    if has_hash {
        let has_curr: bool = conn
            .query_row(
                "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
                [],
                |r| r.get(0),
            )
            .unwrap_or(false);
        if !has_curr {
            let _ = conn.execute_batch("ALTER TABLE handle_registry RENAME COLUMN hash TO current_hash;");
        }
    }
    Ok(())
}

/// Registers a payment rail configuration under `mcard:payment/rail/{rail_id}`.
pub fn register_payment_rail(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    rail_id: &str,
    rail_type: &str,
    _config_json: Option<&str>,
) -> Result<PaymentRailRecord, String> {
    let handle = format!("mcard:payment/rail/{}", rail_id);
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let content_json = serde_json::json!({
        "rail_id": rail_id,
        "rail_type": rail_type,
        "status": "active",
    }).to_string();

    let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(content_json.as_bytes()));

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    let now = chrono::Utc::now().to_rfc3339();
    conn.execute(
        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
        rusqlite::params![handle, content_hash, now],
    ).map_err(|e| e.to_string())?;

    Ok(PaymentRailRecord {
        rail_id: rail_id.to_string(),
        rail_type: rail_type.to_string(),
        handle,
        content_hash,
    })
}

/// Creates a payment invoice under `mcard:payment/invoice/{invoice_id}`.
pub fn create_payment_invoice(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    buyer_did: &str,
    merchant_did: &str,
    amount: f64,
    currency: &str,
) -> Result<PaymentInvoiceRecord, String> {
    let mut inv_bytes = [0u8; 12];
    rand::thread_rng().fill_bytes(&mut inv_bytes);
    let invoice_id = format!("inv_{}", hex::encode(inv_bytes));
    let handle = format!("mcard:payment/invoice/{}", invoice_id);

    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let content_json = serde_json::json!({
        "invoice_id": invoice_id,
        "buyer_did": buyer_did,
        "merchant_did": merchant_did,
        "amount": amount,
        "currency": currency,
        "created_at": chrono::Utc::now().to_rfc3339(),
    }).to_string();

    let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(content_json.as_bytes()));

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    let now = chrono::Utc::now().to_rfc3339();
    conn.execute(
        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
        rusqlite::params![handle, content_hash, now],
    ).map_err(|e| e.to_string())?;

    Ok(PaymentInvoiceRecord {
        invoice_id,
        handle,
        buyer_did: buyer_did.to_string(),
        merchant_did: merchant_did.to_string(),
        amount,
        currency: currency.to_string(),
        content_hash,
    })
}

/// Processes a payment through a Payment PCard rail and mints a VCard receipt under `mcard:payment/receipt/{tx_id}`.
pub fn process_payment_pcard(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    invoice_id: &str,
    rail_id: &str,
    _payment_payload: Option<&str>,
) -> Result<PaymentReceiptRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let inv_handle = format!("mcard:payment/invoice/{}", invoice_id);
    let query = if conn.query_row(
        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
        [],
        |r| r.get(0),
    ).unwrap_or(false) {
        "SELECT c.hash, c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
    } else {
        "SELECT c.hash, c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
    };
    let (inv_hash, inv_content): (String, String) = conn.query_row(
        query,
        rusqlite::params![inv_handle],
        |row| {
            let h: String = row.get(0)?;
            let c: String = row.get(1)?;
            Ok((h, c))
        },
    ).map_err(|_| format!("Invoice {} not found", invoice_id))?;

    let inv_val: serde_json::Value = serde_json::from_str(&inv_content).map_err(|e| e.to_string())?;
    let buyer_did = inv_val.get("buyer_did").and_then(|x| x.as_str()).unwrap_or("did:key:unknown");
    let merchant_did = inv_val.get("merchant_did").and_then(|x| x.as_str()).unwrap_or("did:key:unknown");
    let amount = inv_val.get("amount").and_then(|x| x.as_f64()).unwrap_or(0.0);
    let currency = inv_val.get("currency").and_then(|x| x.as_str()).unwrap_or("USD");

    let rail_handle = format!("mcard:payment/rail/{}", rail_id);
    let rail_query = if conn.query_row(
        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
        [],
        |r| r.get(0),
    ).unwrap_or(false) {
        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
    } else {
        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
    };
    let rail_type: String = conn.query_row(
        rail_query,
        rusqlite::params![rail_handle],
        |row| row.get::<usize, String>(0),
    ).map(|content| {
        let v: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();
        v.get("rail_type").and_then(|x| x.as_str()).unwrap_or(rail_id).to_string()
    }).unwrap_or_else(|_| rail_id.to_string());

    let mut tx_bytes = [0u8; 16];
    rand::thread_rng().fill_bytes(&mut tx_bytes);
    let tx_id = format!("tx_{}", hex::encode(tx_bytes));
    let handle = format!("mcard:payment/receipt/{}", tx_id);

    let receipt_json = serde_json::json!({
        "tx_id": tx_id,
        "invoice_id": invoice_id,
        "invoice_hash": inv_hash,
        "buyer_did": buyer_did,
        "merchant_did": merchant_did,
        "rail_id": rail_id,
        "rail_type": rail_type,
        "amount": amount,
        "currency": currency,
        "status": "settled",
        "timestamp": chrono::Utc::now().to_rfc3339(),
    }).to_string();

    let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(receipt_json.as_bytes()));

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, receipt_json],
    ).map_err(|e| e.to_string())?;

    let now = chrono::Utc::now().to_rfc3339();
    conn.execute(
        "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3) \
         ON CONFLICT(handle) DO UPDATE SET current_hash=excluded.current_hash, updated_at=excluded.updated_at;",
        rusqlite::params![handle, content_hash, now],
    ).map_err(|e| e.to_string())?;

    Ok(PaymentReceiptRecord {
        tx_id,
        handle,
        invoice_id: invoice_id.to_string(),
        invoice_hash: inv_hash,
        buyer_did: buyer_did.to_string(),
        merchant_did: merchant_did.to_string(),
        rail_id: rail_id.to_string(),
        rail_type,
        amount,
        currency: currency.to_string(),
        status: "settled".to_string(),
        content_hash,
    })
}

/// Verifies if a payment receipt is valid, immutable, and settled in SQLite.
pub fn verify_payment_receipt(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    tx_id: &str,
) -> Result<bool, String> {
    let handle = format!("mcard:payment/receipt/{}", tx_id);
    let db_path = resolve_db_path(db_name_or_path, clm_root);

    if !db_path.exists() {
        return Ok(false);
    }

    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    let query = if conn.query_row(
        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
        [],
        |r| r.get(0),
    ).unwrap_or(false) {
        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
    } else {
        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
    };
    let content: String = match conn.query_row(
        query,
        rusqlite::params![handle],
        |row| row.get::<usize, String>(0),
    ) {
        Ok(c) => c,
        Err(_) => return Ok(false),
    };

    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
    let status = v.get("status").and_then(|x| x.as_str()).unwrap_or("");
    let inv_hash = v.get("invoice_hash").and_then(|x| x.as_str()).unwrap_or("");

    Ok(status == "settled" && !inv_hash.is_empty())
}

use sha2::Digest;

// ── Unit Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_multi_rail_payment_flow() {
        let tmp_db = std::env::temp_dir().join("clm_test_payment_flow.db");
        let _ = std::fs::remove_file(&tmp_db);
        let db_str = tmp_db.to_str().unwrap();

        // 1. Register rails
        let stripe = register_payment_rail(db_str, None, "stripe_global", "stripe", None).unwrap();
        assert_eq!(stripe.handle, "mcard:payment/rail/stripe_global");

        let qris = register_payment_rail(db_str, None, "qris_indo", "qris", None).unwrap();
        assert_eq!(qris.handle, "mcard:payment/rail/qris_indo");

        // 2. Create invoice
        let buyer = "did:key:z6MkBuyer123";
        let merchant = "did:key:z6MkMerchant456";
        let inv = create_payment_invoice(db_str, None, buyer, merchant, 250.0, "USD").unwrap();
        assert!(inv.handle.starts_with("mcard:payment/invoice/inv_"));

        // 3. Process payment
        let receipt = process_payment_pcard(db_str, None, &inv.invoice_id, "stripe_global", None).unwrap();
        assert!(receipt.handle.starts_with("mcard:payment/receipt/tx_"));
        assert_eq!(receipt.status, "settled");

        // 4. Verify receipt
        let is_valid = verify_payment_receipt(db_str, None, &receipt.tx_id).unwrap();
        assert!(is_valid);

        let _ = std::fs::remove_file(&tmp_db);
    }
}