use crate::layer0::vocabulary::{HANDLE_MCARD_PAYMENT_INVOICE, HANDLE_MCARD_PAYMENT_RAIL, HANDLE_MCARD_PAYMENT_RECEIPT, HASH_PREFIX_SHA256};
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(|| {
crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_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.busy_timeout(std::time::Duration::from_millis(u64::from(crate::layer0::runtime_contract::SQLITE_BUSY_TIMEOUT_MS)));
conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1).map_err(|e| e.to_string())?;
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(())
}
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!("{HANDLE_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!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(content_json.as_bytes()));
crate::layer2::record_store::insert_new_content(&conn, &content_hash, content_json.as_bytes(), crate::layer0::vocabulary::HASH_ALGORITHM_SHA256).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,
})
}
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!("{HANDLE_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!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(content_json.as_bytes()));
crate::layer2::record_store::insert_new_content(&conn, &content_hash, content_json.as_bytes(), crate::layer0::vocabulary::HASH_ALGORITHM_SHA256).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,
})
}
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!("{HANDLE_MCARD_PAYMENT_INVOICE}{}", invoice_id);
let record = crate::layer2::record_store::read_handle_record(&conn, &inv_handle)
.map_err(|error| error.to_string())?.ok_or("invoice is missing")?;
let inv_hash = record.hash;
let inv_content = String::from_utf8(record.content).map_err(|error| error.to_string())?;
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(crate::layer0::vocabulary_identities::DID_KEY_UNKNOWN);
let merchant_did = inv_val.get("merchant_did").and_then(|x| x.as_str()).unwrap_or(crate::layer0::vocabulary_identities::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!("{HANDLE_MCARD_PAYMENT_RAIL}{}", rail_id);
let rail_type = crate::layer2::record_store::read_handle_text(&conn, &rail_handle)
.map_err(|error| error.to_string())?.map(|content| {
let value: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();
value.get("rail_type").and_then(|value| value.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!("{HANDLE_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!("{HASH_PREFIX_SHA256}{:x}", sha2::Sha256::digest(receipt_json.as_bytes()));
crate::layer2::record_store::insert_new_content(&conn, &content_hash, receipt_json.as_bytes(), crate::layer0::vocabulary::HASH_ALGORITHM_SHA256).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,
})
}
pub fn verify_payment_receipt(
db_name_or_path: &str,
clm_root: Option<&str>,
tx_id: &str,
) -> Result<bool, String> {
let handle = format!("{HANDLE_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 Some(content) = crate::layer2::record_store::read_handle_text(&conn, handle.as_ref())
.map_err(|error| error.to_string())? else { 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;
#[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();
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");
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_"));
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");
let is_valid = verify_payment_receipt(db_str, None, &receipt.tx_id).unwrap();
assert!(is_valid);
let _ = std::fs::remove_file(&tmp_db);
}
}