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