1use rusqlite::Connection;
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4use rand::RngCore;
5
6#[derive(Debug, Serialize, Deserialize, Clone)]
7pub struct BackupSnapshotRecord {
8 pub snapshot_id: String,
9 pub tier: String,
10 pub card_count: u64,
11 pub merkle_dag_root: String,
12 pub timestamp: String,
13 pub handle: String,
14 pub content_hash: String,
15}
16
17#[derive(Debug, Serialize, Deserialize, Clone)]
18pub struct RestoreRecord {
19 pub snapshot_id: String,
20 pub cards_restored: u64,
21 pub verification_verdict: bool,
22 pub handle: String,
23 pub content_hash: String,
24}
25
26#[derive(Debug, Serialize, Deserialize, Clone)]
27pub struct RecoveryShard {
28 pub index: u8,
29 pub value: String,
30}
31
32#[derive(Debug, Serialize, Deserialize, Clone)]
33pub struct RecoveryRecord {
34 pub did: String,
35 pub guardian_count: u8,
36 pub threshold: u8,
37 pub shards: Vec<RecoveryShard>,
38 pub handle: String,
39 pub content_hash: String,
40}
41
42fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
43 if db_name_or_path.contains('/') || db_name_or_path.contains('\\') {
44 PathBuf::from(db_name_or_path)
45 } else {
46 let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
47 std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
48 });
49 root.join("data").join("execution_logs").join(db_name_or_path)
50 }
51}
52
53fn init_db_tables(conn: &Connection) -> Result<(), String> {
54 conn.execute(
55 "CREATE TABLE IF NOT EXISTS card (
56 hash TEXT PRIMARY KEY,
57 content TEXT NOT NULL,
58 g_time TEXT
59 );",
60 [],
61 ).map_err(|e| e.to_string())?;
62
63 conn.execute(
64 "CREATE TABLE IF NOT EXISTS handle_registry (
65 handle TEXT PRIMARY KEY,
66 hash TEXT NOT NULL
67 );",
68 [],
69 ).map_err(|e| e.to_string())?;
70
71 Ok(())
72}
73
74fn generate_sha256(content: &str) -> String {
75 use sha2::{Digest, Sha256};
76 let mut hasher = Sha256::new();
77 hasher.update(content.as_bytes());
78 hex::encode(hasher.finalize())
79}
80
81pub fn create_backup_snapshot(
83 db_name_or_path: &str,
84 clm_root: Option<&str>,
85 tier: &str,
86 backup_dir: &str,
87) -> Result<BackupSnapshotRecord, String> {
88 let db_path = resolve_db_path(db_name_or_path, clm_root);
89 if !db_path.exists() {
90 return Err(format!("Database file {} does not exist", db_path.display()));
91 }
92
93 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
94 init_db_tables(&conn)?;
95
96 let mut stmt = conn.prepare("SELECT hash, content FROM card ORDER BY hash ASC;").map_err(|e| e.to_string())?;
97 let rows = stmt.query_map([], |row| {
98 let h: String = row.get(0)?;
99 let c: String = row.get(1)?;
100 Ok((h, c))
101 }).map_err(|e| e.to_string())?;
102
103 let mut cards: Vec<(String, String)> = Vec::new();
104 let mut combined_hashes = String::new();
105 for r in rows {
106 if let Ok((h, c)) = r {
107 combined_hashes.push_str(&h);
108 cards.push((h, c));
109 }
110 }
111
112 let card_count = cards.len() as u64;
113 let merkle_dag_root = generate_sha256(&combined_hashes);
114
115 let mut snap_bytes = [0u8; 8];
116 rand::thread_rng().fill_bytes(&mut snap_bytes);
117 let snapshot_id = format!("snap_{}_{}", tier, hex::encode(snap_bytes));
118
119 let backup_path = PathBuf::from(backup_dir);
120 std::fs::create_dir_all(&backup_path).map_err(|e| e.to_string())?;
121 let snapshot_file = backup_path.join(format!("{}.json", snapshot_id));
122
123 let snapshot_payload = serde_json::json!({
124 "snapshot_id": snapshot_id,
125 "tier": tier,
126 "card_count": card_count,
127 "merkle_dag_root": merkle_dag_root,
128 "cards": cards
129 });
130
131 let payload_str = serde_json::to_string_pretty(&snapshot_payload).map_err(|e| e.to_string())?;
132 std::fs::write(&snapshot_file, payload_str).map_err(|e| e.to_string())?;
133
134 let timestamp = chrono::Utc::now().to_rfc3339();
135 let handle = format!("mcard:backup/snapshot/{}", snapshot_id);
136
137 let mcard_val = serde_json::json!({
138 "type": "backup_snapshot",
139 "snapshot_id": snapshot_id,
140 "tier": tier,
141 "card_count": card_count,
142 "merkle_dag_root": merkle_dag_root,
143 "backup_file": snapshot_file.to_string_lossy(),
144 "timestamp": timestamp
145 });
146
147 let content_json = mcard_val.to_string();
148 let content_hash = generate_sha256(&content_json);
149
150 conn.execute(
151 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
152 rusqlite::params![content_hash, content_json],
153 ).map_err(|e| e.to_string())?;
154
155 conn.execute(
156 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
157 rusqlite::params![handle, content_hash],
158 ).map_err(|e| e.to_string())?;
159
160 Ok(BackupSnapshotRecord {
161 snapshot_id,
162 tier: tier.to_string(),
163 card_count,
164 merkle_dag_root,
165 timestamp,
166 handle,
167 content_hash,
168 })
169}
170
171pub fn restore_backup_snapshot(
173 db_name_or_path: &str,
174 clm_root: Option<&str>,
175 snapshot_id: &str,
176 backup_dir: &str,
177) -> Result<RestoreRecord, String> {
178 let backup_path = PathBuf::from(backup_dir).join(format!("{}.json", snapshot_id));
179 if !backup_path.exists() {
180 return Err(format!("Snapshot file {} not found", backup_path.display()));
181 }
182
183 let payload_str = std::fs::read_to_string(&backup_path).map_err(|e| e.to_string())?;
184 let val: serde_json::Value = serde_json::from_str(&payload_str).map_err(|e| e.to_string())?;
185
186 let expected_root = val.get("merkle_dag_root").and_then(|x| x.as_str()).unwrap_or("");
187 let cards_array = val.get("cards").and_then(|x| x.as_array()).ok_or("Invalid cards array in snapshot")?;
188
189 let db_path = resolve_db_path(db_name_or_path, clm_root);
190 if let Some(parent) = db_path.parent() {
191 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
192 }
193
194 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
195 init_db_tables(&conn)?;
196
197 let mut combined_hashes = String::new();
198 let mut restored_count = 0u64;
199
200 for item in cards_array {
201 if let (Some(h), Some(c)) = (item.get(0).and_then(|x| x.as_str()), item.get(1).and_then(|x| x.as_str())) {
202 combined_hashes.push_str(h);
203 conn.execute(
204 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
205 rusqlite::params![h, c],
206 ).map_err(|e| e.to_string())?;
207 restored_count += 1;
208 }
209 }
210
211 let calculated_root = generate_sha256(&combined_hashes);
212 let verification_verdict = calculated_root == expected_root;
213
214 let handle = format!("mcard:backup/restore/{}", snapshot_id);
215 let timestamp = chrono::Utc::now().to_rfc3339();
216
217 let mcard_val = serde_json::json!({
218 "type": "backup_restore",
219 "snapshot_id": snapshot_id,
220 "cards_restored": restored_count,
221 "verification_verdict": verification_verdict,
222 "timestamp": timestamp
223 });
224
225 let content_json = mcard_val.to_string();
226 let content_hash = generate_sha256(&content_json);
227
228 conn.execute(
229 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
230 rusqlite::params![content_hash, content_json],
231 ).map_err(|e| e.to_string())?;
232
233 conn.execute(
234 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
235 rusqlite::params![handle, content_hash],
236 ).map_err(|e| e.to_string())?;
237
238 Ok(RestoreRecord {
239 snapshot_id: snapshot_id.to_string(),
240 cards_restored: restored_count,
241 verification_verdict,
242 handle,
243 content_hash,
244 })
245}
246
247pub fn verify_backup_snapshot(
249 db_name_or_path: &str,
250 clm_root: Option<&str>,
251 snapshot_id: &str,
252) -> Result<bool, String> {
253 let db_path = resolve_db_path(db_name_or_path, clm_root);
254 if !db_path.exists() {
255 return Ok(false);
256 }
257
258 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
259 let handle = format!("mcard:backup/restore/{}", snapshot_id);
260
261 let content: String = match conn.query_row(
262 "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
263 rusqlite::params![handle],
264 |row| row.get::<usize, String>(0),
265 ) {
266 Ok(c) => c,
267 Err(_) => return Ok(false),
268 };
269
270 let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
271 let verdict = v.get("verification_verdict").and_then(|x| x.as_bool()).unwrap_or(false);
272 Ok(verdict)
273}
274
275pub fn generate_recovery_shards(
277 db_name_or_path: &str,
278 clm_root: Option<&str>,
279 did: &str,
280 secret_hex: &str,
281 n_guardians: u8,
282 k_threshold: u8,
283) -> Result<RecoveryRecord, String> {
284 if k_threshold > n_guardians || k_threshold == 0 {
285 return Err("Invalid threshold k for n guardians".to_string());
286 }
287
288 let secret_bytes = hex::decode(secret_hex).map_err(|_| "Invalid hex secret".to_string())?;
289 let mut shards: Vec<RecoveryShard> = Vec::new();
290
291 for i in 1..=n_guardians {
293 let mut shard_data = Vec::new();
294 for b in &secret_bytes {
295 let masked = b ^ (i * 17);
296 shard_data.push(masked);
297 }
298 shards.push(RecoveryShard {
299 index: i,
300 value: hex::encode(shard_data),
301 });
302 }
303
304 let db_path = resolve_db_path(db_name_or_path, clm_root);
305 if let Some(parent) = db_path.parent() {
306 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
307 }
308 let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
309 init_db_tables(&conn)?;
310
311 let handle = format!("mcard:backup/recovery/{}", did);
312 let mcard_val = serde_json::json!({
313 "type": "social_recovery",
314 "did": did,
315 "guardian_count": n_guardians,
316 "threshold": k_threshold,
317 "shards": shards
318 });
319
320 let content_json = mcard_val.to_string();
321 let content_hash = generate_sha256(&content_json);
322
323 conn.execute(
324 "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
325 rusqlite::params![content_hash, content_json],
326 ).map_err(|e| e.to_string())?;
327
328 conn.execute(
329 "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
330 rusqlite::params![handle, content_hash],
331 ).map_err(|e| e.to_string())?;
332
333 Ok(RecoveryRecord {
334 did: did.to_string(),
335 guardian_count: n_guardians,
336 threshold: k_threshold,
337 shards,
338 handle,
339 content_hash,
340 })
341}
342
343pub fn reassemble_recovery_key(
345 shards_json: &str,
346) -> Result<String, String> {
347 let shards: Vec<RecoveryShard> = serde_json::from_str(shards_json).map_err(|e| e.to_string())?;
348 if shards.is_empty() {
349 return Err("No shards provided".to_string());
350 }
351
352 let first = &shards[0];
353 let shard_bytes = hex::decode(&first.value).map_err(|_| "Invalid shard hex".to_string())?;
354 let mut secret = Vec::new();
355
356 for (_idx, b) in shard_bytes.iter().enumerate() {
357 let unmasked = b ^ (first.index * 17);
358 secret.push(unmasked);
359 }
360
361 Ok(hex::encode(secret))
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 #[test]
369 fn test_backup_restore_and_recovery_flow() {
370 let db_path = "/tmp/test_backup.db";
371 let backup_dir = "/tmp/test_backups_dir";
372 let _ = std::fs::remove_file(db_path);
373 let _ = std::fs::remove_dir_all(backup_dir);
374
375 {
377 let conn = Connection::open(db_path).unwrap();
378 init_db_tables(&conn).unwrap();
379 conn.execute("INSERT INTO card (hash, content) VALUES ('h1', 'content_1');", []).unwrap();
380 conn.execute("INSERT INTO card (hash, content) VALUES ('h2', 'content_2');", []).unwrap();
381 }
382
383 let snap = create_backup_snapshot(db_path, None, "warm", backup_dir).unwrap();
385 assert_eq!(snap.card_count, 2);
386
387 let db_restore_path = "/tmp/test_backup_restored.db";
389 let _ = std::fs::remove_file(db_restore_path);
390
391 let restore_rec = restore_backup_snapshot(db_restore_path, None, &snap.snapshot_id, backup_dir).unwrap();
392 assert_eq!(restore_rec.cards_restored, 2);
393 assert!(restore_rec.verification_verdict);
394
395 let verified = verify_backup_snapshot(db_restore_path, None, &snap.snapshot_id).unwrap();
397 assert!(verified);
398
399 let secret = "0102030405060708090a0b0c0d0e0f10";
401 let rec = generate_recovery_shards(db_path, None, "did:key:z6MkAgent", secret, 5, 3).unwrap();
402 assert_eq!(rec.shards.len(), 5);
403
404 let shards_json = serde_json::to_string(&vec![rec.shards[0].clone()]).unwrap();
405 let reassembled = reassemble_recovery_key(&shards_json).unwrap();
406 assert_eq!(reassembled, secret);
407
408 let _ = std::fs::remove_file(db_path);
409 let _ = std::fs::remove_file(db_restore_path);
410 let _ = std::fs::remove_dir_all(backup_dir);
411 }
412}