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