1use rand::RngCore;
5use serde::{Deserialize, Serialize};
6use std::path::{Path, PathBuf};
7use rusqlite::Connection;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct PaymentRailRecord {
11 pub rail_id: String,
12 pub rail_type: String,
13 pub handle: String,
14 pub content_hash: String,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct PaymentInvoiceRecord {
19 pub invoice_id: String,
20 pub handle: String,
21 pub buyer_did: String,
22 pub merchant_did: String,
23 pub amount: f64,
24 pub currency: String,
25 pub content_hash: String,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct PaymentReceiptRecord {
30 pub tx_id: String,
31 pub handle: String,
32 pub invoice_id: String,
33 pub invoice_hash: String,
34 pub buyer_did: String,
35 pub merchant_did: String,
36 pub rail_id: String,
37 pub rail_type: String,
38 pub amount: f64,
39 pub currency: String,
40 pub status: String,
41 pub content_hash: String,
42}
43
44fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
45 let p = Path::new(db_name_or_path);
46 if p.is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
47 p.to_path_buf()
48 } else {
49 let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
50 std::env::var("CLM_ROOT").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
51 });
52 root.join("db").join(db_name_or_path)
53 }
54}
55
56fn init_db_tables(conn: &Connection) -> Result<(), String> {
57 conn.execute_batch(
58 "CREATE TABLE IF NOT EXISTS card (
59 hash TEXT PRIMARY KEY,
60 content TEXT NOT NULL,
61 g_time TEXT
62 );
63 CREATE TABLE IF NOT EXISTS handle_registry (
64 handle TEXT PRIMARY KEY,
65 hash TEXT NOT NULL,
66 updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
67 FOREIGN KEY (hash) REFERENCES card(hash)
68 );"
69 ).map_err(|e| e.to_string())
70}
71
72pub fn register_payment_rail(
74 db_name_or_path: &str,
75 clm_root: Option<&str>,
76 rail_id: &str,
77 rail_type: &str,
78 _config_json: Option<&str>,
79) -> Result<PaymentRailRecord, String> {
80 let handle = format!("mcard:payment/rail/{}", rail_id);
81 let db_path = resolve_db_path(db_name_or_path, clm_root);
82 if let Some(parent) = db_path.parent() {
83 let _ = std::fs::create_dir_all(parent);
84 }
85 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
86 init_db_tables(&conn)?;
87
88 let content_json = serde_json::json!({
89 "rail_id": rail_id,
90 "rail_type": rail_type,
91 "status": "active",
92 }).to_string();
93
94 let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(content_json.as_bytes()));
95
96 conn.execute(
97 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
98 rusqlite::params![content_hash, content_json],
99 ).map_err(|e| e.to_string())?;
100
101 conn.execute(
102 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
103 rusqlite::params![handle, content_hash],
104 ).map_err(|e| e.to_string())?;
105
106 Ok(PaymentRailRecord {
107 rail_id: rail_id.to_string(),
108 rail_type: rail_type.to_string(),
109 handle,
110 content_hash,
111 })
112}
113
114pub fn create_payment_invoice(
116 db_name_or_path: &str,
117 clm_root: Option<&str>,
118 buyer_did: &str,
119 merchant_did: &str,
120 amount: f64,
121 currency: &str,
122) -> Result<PaymentInvoiceRecord, String> {
123 let mut inv_bytes = [0u8; 12];
124 rand::thread_rng().fill_bytes(&mut inv_bytes);
125 let invoice_id = format!("inv_{}", hex::encode(inv_bytes));
126 let handle = format!("mcard:payment/invoice/{}", invoice_id);
127
128 let db_path = resolve_db_path(db_name_or_path, clm_root);
129 if let Some(parent) = db_path.parent() {
130 let _ = std::fs::create_dir_all(parent);
131 }
132 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
133 init_db_tables(&conn)?;
134
135 let content_json = serde_json::json!({
136 "invoice_id": invoice_id,
137 "buyer_did": buyer_did,
138 "merchant_did": merchant_did,
139 "amount": amount,
140 "currency": currency,
141 "created_at": chrono::Utc::now().to_rfc3339(),
142 }).to_string();
143
144 let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(content_json.as_bytes()));
145
146 conn.execute(
147 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
148 rusqlite::params![content_hash, content_json],
149 ).map_err(|e| e.to_string())?;
150
151 conn.execute(
152 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
153 rusqlite::params![handle, content_hash],
154 ).map_err(|e| e.to_string())?;
155
156 Ok(PaymentInvoiceRecord {
157 invoice_id,
158 handle,
159 buyer_did: buyer_did.to_string(),
160 merchant_did: merchant_did.to_string(),
161 amount,
162 currency: currency.to_string(),
163 content_hash,
164 })
165}
166
167pub fn process_payment_pcard(
169 db_name_or_path: &str,
170 clm_root: Option<&str>,
171 invoice_id: &str,
172 rail_id: &str,
173 _payment_payload: Option<&str>,
174) -> Result<PaymentReceiptRecord, String> {
175 let db_path = resolve_db_path(db_name_or_path, clm_root);
176 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
177 init_db_tables(&conn)?;
178
179 let inv_handle = format!("mcard:payment/invoice/{}", invoice_id);
180 let (inv_hash, inv_content): (String, String) = conn.query_row(
181 "SELECT c.hash, c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
182 rusqlite::params![inv_handle],
183 |row| {
184 let h: String = row.get(0)?;
185 let c: String = row.get(1)?;
186 Ok((h, c))
187 },
188 ).map_err(|_| format!("Invoice {} not found", invoice_id))?;
189
190 let inv_val: serde_json::Value = serde_json::from_str(&inv_content).map_err(|e| e.to_string())?;
191 let buyer_did = inv_val.get("buyer_did").and_then(|x| x.as_str()).unwrap_or("did:key:unknown");
192 let merchant_did = inv_val.get("merchant_did").and_then(|x| x.as_str()).unwrap_or("did:key:unknown");
193 let amount = inv_val.get("amount").and_then(|x| x.as_f64()).unwrap_or(0.0);
194 let currency = inv_val.get("currency").and_then(|x| x.as_str()).unwrap_or("USD");
195
196 let rail_handle = format!("mcard:payment/rail/{}", rail_id);
197 let rail_type: String = conn.query_row(
198 "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
199 rusqlite::params![rail_handle],
200 |row| row.get::<usize, String>(0),
201 ).map(|content| {
202 let v: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();
203 v.get("rail_type").and_then(|x| x.as_str()).unwrap_or(rail_id).to_string()
204 }).unwrap_or_else(|_| rail_id.to_string());
205
206 let mut tx_bytes = [0u8; 16];
207 rand::thread_rng().fill_bytes(&mut tx_bytes);
208 let tx_id = format!("tx_{}", hex::encode(tx_bytes));
209 let handle = format!("mcard:payment/receipt/{}", tx_id);
210
211 let receipt_json = serde_json::json!({
212 "tx_id": tx_id,
213 "invoice_id": invoice_id,
214 "invoice_hash": inv_hash,
215 "buyer_did": buyer_did,
216 "merchant_did": merchant_did,
217 "rail_id": rail_id,
218 "rail_type": rail_type,
219 "amount": amount,
220 "currency": currency,
221 "status": "settled",
222 "timestamp": chrono::Utc::now().to_rfc3339(),
223 }).to_string();
224
225 let content_hash = format!("sha256:{:x}", sha2::Sha256::digest(receipt_json.as_bytes()));
226
227 conn.execute(
228 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
229 rusqlite::params![content_hash, receipt_json],
230 ).map_err(|e| e.to_string())?;
231
232 conn.execute(
233 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
234 rusqlite::params![handle, content_hash],
235 ).map_err(|e| e.to_string())?;
236
237 Ok(PaymentReceiptRecord {
238 tx_id,
239 handle,
240 invoice_id: invoice_id.to_string(),
241 invoice_hash: inv_hash,
242 buyer_did: buyer_did.to_string(),
243 merchant_did: merchant_did.to_string(),
244 rail_id: rail_id.to_string(),
245 rail_type,
246 amount,
247 currency: currency.to_string(),
248 status: "settled".to_string(),
249 content_hash,
250 })
251}
252
253pub fn verify_payment_receipt(
255 db_name_or_path: &str,
256 clm_root: Option<&str>,
257 tx_id: &str,
258) -> Result<bool, String> {
259 let handle = format!("mcard:payment/receipt/{}", tx_id);
260 let db_path = resolve_db_path(db_name_or_path, clm_root);
261
262 if !db_path.exists() {
263 return Ok(false);
264 }
265
266 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
267 let content: String = match conn.query_row(
268 "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
269 rusqlite::params![handle],
270 |row| row.get::<usize, String>(0),
271 ) {
272 Ok(c) => c,
273 Err(_) => return Ok(false),
274 };
275
276 let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
277 let status = v.get("status").and_then(|x| x.as_str()).unwrap_or("");
278 let inv_hash = v.get("invoice_hash").and_then(|x| x.as_str()).unwrap_or("");
279
280 Ok(status == "settled" && !inv_hash.is_empty())
281}
282
283use sha2::Digest;
284
285#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn test_multi_rail_payment_flow() {
293 let tmp_db = std::env::temp_dir().join("clm_test_payment_flow.db");
294 let _ = std::fs::remove_file(&tmp_db);
295 let db_str = tmp_db.to_str().unwrap();
296
297 let stripe = register_payment_rail(db_str, None, "stripe_global", "stripe", None).unwrap();
299 assert_eq!(stripe.handle, "mcard:payment/rail/stripe_global");
300
301 let qris = register_payment_rail(db_str, None, "qris_indo", "qris", None).unwrap();
302 assert_eq!(qris.handle, "mcard:payment/rail/qris_indo");
303
304 let buyer = "did:key:z6MkBuyer123";
306 let merchant = "did:key:z6MkMerchant456";
307 let inv = create_payment_invoice(db_str, None, buyer, merchant, 250.0, "USD").unwrap();
308 assert!(inv.handle.starts_with("mcard:payment/invoice/inv_"));
309
310 let receipt = process_payment_pcard(db_str, None, &inv.invoice_id, "stripe_global", None).unwrap();
312 assert!(receipt.handle.starts_with("mcard:payment/receipt/tx_"));
313 assert_eq!(receipt.status, "settled");
314
315 let is_valid = verify_payment_receipt(db_str, None, &receipt.tx_id).unwrap();
317 assert!(is_valid);
318
319 let _ = std::fs::remove_file(&tmp_db);
320 }
321}