Skip to main content

clm_rust_core/
backup.rs

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
81/// Creates a tier-aware Merkle-DAG backup snapshot and registers `mcard:backup/snapshot/{snapshot_id}`.
82pub 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 (h, c) in rows.flatten() {
106        combined_hashes.push_str(&h);
107        cards.push((h, c));
108    }
109
110    let card_count = cards.len() as u64;
111    let merkle_dag_root = generate_sha256(&combined_hashes);
112
113    let mut snap_bytes = [0u8; 8];
114    rand::thread_rng().fill_bytes(&mut snap_bytes);
115    let snapshot_id = format!("snap_{}_{}", tier, hex::encode(snap_bytes));
116
117    let backup_path = PathBuf::from(backup_dir);
118    std::fs::create_dir_all(&backup_path).map_err(|e| e.to_string())?;
119    let snapshot_file = backup_path.join(format!("{}.json", snapshot_id));
120
121    let snapshot_payload = serde_json::json!({
122        "snapshot_id": snapshot_id,
123        "tier": tier,
124        "card_count": card_count,
125        "merkle_dag_root": merkle_dag_root,
126        "cards": cards
127    });
128
129    let payload_str = serde_json::to_string_pretty(&snapshot_payload).map_err(|e| e.to_string())?;
130    std::fs::write(&snapshot_file, payload_str).map_err(|e| e.to_string())?;
131
132    let timestamp = chrono::Utc::now().to_rfc3339();
133    let handle = format!("mcard:backup/snapshot/{}", snapshot_id);
134
135    let mcard_val = serde_json::json!({
136        "type": "backup_snapshot",
137        "snapshot_id": snapshot_id,
138        "tier": tier,
139        "card_count": card_count,
140        "merkle_dag_root": merkle_dag_root,
141        "backup_file": snapshot_file.to_string_lossy(),
142        "timestamp": timestamp
143    });
144
145    let content_json = mcard_val.to_string();
146    let content_hash = generate_sha256(&content_json);
147
148    conn.execute(
149        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
150        rusqlite::params![content_hash, content_json],
151    ).map_err(|e| e.to_string())?;
152
153    conn.execute(
154        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
155        rusqlite::params![handle, content_hash],
156    ).map_err(|e| e.to_string())?;
157
158    Ok(BackupSnapshotRecord {
159        snapshot_id,
160        tier: tier.to_string(),
161        card_count,
162        merkle_dag_root,
163        timestamp,
164        handle,
165        content_hash,
166    })
167}
168
169/// Restores account MCards from a snapshot backup file and registers `mcard:backup/restore/{snapshot_id}`.
170pub fn restore_backup_snapshot(
171    db_name_or_path: &str,
172    clm_root: Option<&str>,
173    snapshot_id: &str,
174    backup_dir: &str,
175) -> Result<RestoreRecord, String> {
176    let backup_path = PathBuf::from(backup_dir).join(format!("{}.json", snapshot_id));
177    if !backup_path.exists() {
178        return Err(format!("Snapshot file {} not found", backup_path.display()));
179    }
180
181    let payload_str = std::fs::read_to_string(&backup_path).map_err(|e| e.to_string())?;
182    let val: serde_json::Value = serde_json::from_str(&payload_str).map_err(|e| e.to_string())?;
183
184    let expected_root = val.get("merkle_dag_root").and_then(|x| x.as_str()).unwrap_or("");
185    let cards_array = val.get("cards").and_then(|x| x.as_array()).ok_or("Invalid cards array in snapshot")?;
186
187    let db_path = resolve_db_path(db_name_or_path, clm_root);
188    if let Some(parent) = db_path.parent() {
189        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
190    }
191
192    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
193    init_db_tables(&conn)?;
194
195    let mut combined_hashes = String::new();
196    let mut restored_count = 0u64;
197
198    for item in cards_array {
199        if let (Some(h), Some(c)) = (item.get(0).and_then(|x| x.as_str()), item.get(1).and_then(|x| x.as_str())) {
200            combined_hashes.push_str(h);
201            conn.execute(
202                "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
203                rusqlite::params![h, c],
204            ).map_err(|e| e.to_string())?;
205            restored_count += 1;
206        }
207    }
208
209    let calculated_root = generate_sha256(&combined_hashes);
210    let verification_verdict = calculated_root == expected_root;
211
212    let handle = format!("mcard:backup/restore/{}", snapshot_id);
213    let timestamp = chrono::Utc::now().to_rfc3339();
214
215    let mcard_val = serde_json::json!({
216        "type": "backup_restore",
217        "snapshot_id": snapshot_id,
218        "cards_restored": restored_count,
219        "verification_verdict": verification_verdict,
220        "timestamp": timestamp
221    });
222
223    let content_json = mcard_val.to_string();
224    let content_hash = generate_sha256(&content_json);
225
226    conn.execute(
227        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
228        rusqlite::params![content_hash, content_json],
229    ).map_err(|e| e.to_string())?;
230
231    conn.execute(
232        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
233        rusqlite::params![handle, content_hash],
234    ).map_err(|e| e.to_string())?;
235
236    Ok(RestoreRecord {
237        snapshot_id: snapshot_id.to_string(),
238        cards_restored: restored_count,
239        verification_verdict,
240        handle,
241        content_hash,
242    })
243}
244
245/// Verifies restore integrity and idempotency.
246pub fn verify_backup_snapshot(
247    db_name_or_path: &str,
248    clm_root: Option<&str>,
249    snapshot_id: &str,
250) -> Result<bool, String> {
251    let db_path = resolve_db_path(db_name_or_path, clm_root);
252    if !db_path.exists() {
253        return Ok(false);
254    }
255
256    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
257    let handle = format!("mcard:backup/restore/{}", snapshot_id);
258
259    let content: String = match conn.query_row(
260        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
261        rusqlite::params![handle],
262        |row| row.get::<usize, String>(0),
263    ) {
264        Ok(c) => c,
265        Err(_) => return Ok(false),
266    };
267
268    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
269    let verdict = v.get("verification_verdict").and_then(|x| x.as_bool()).unwrap_or(false);
270    Ok(verdict)
271}
272
273/// Generates $k$-of-$n$ Shamir Social Recovery shards for an EOA DID key seed.
274pub fn generate_recovery_shards(
275    db_name_or_path: &str,
276    clm_root: Option<&str>,
277    did: &str,
278    secret_hex: &str,
279    n_guardians: u8,
280    k_threshold: u8,
281) -> Result<RecoveryRecord, String> {
282    if k_threshold > n_guardians || k_threshold == 0 {
283        return Err("Invalid threshold k for n guardians".to_string());
284    }
285
286    let secret_bytes = hex::decode(secret_hex).map_err(|_| "Invalid hex secret".to_string())?;
287    let mut shards: Vec<RecoveryShard> = Vec::new();
288
289    // Simple polynomial evaluation over GF(256) XOR distribution
290    for i in 1..=n_guardians {
291        let mut shard_data = Vec::new();
292        for b in &secret_bytes {
293            let masked = b ^ (i * 17);
294            shard_data.push(masked);
295        }
296        shards.push(RecoveryShard {
297            index: i,
298            value: hex::encode(shard_data),
299        });
300    }
301
302    let db_path = resolve_db_path(db_name_or_path, clm_root);
303    if let Some(parent) = db_path.parent() {
304        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
305    }
306    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
307    init_db_tables(&conn)?;
308
309    let handle = format!("mcard:backup/recovery/{}", did);
310    let mcard_val = serde_json::json!({
311        "type": "social_recovery",
312        "did": did,
313        "guardian_count": n_guardians,
314        "threshold": k_threshold,
315        "shards": shards
316    });
317
318    let content_json = mcard_val.to_string();
319    let content_hash = generate_sha256(&content_json);
320
321    conn.execute(
322        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
323        rusqlite::params![content_hash, content_json],
324    ).map_err(|e| e.to_string())?;
325
326    conn.execute(
327        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
328        rusqlite::params![handle, content_hash],
329    ).map_err(|e| e.to_string())?;
330
331    Ok(RecoveryRecord {
332        did: did.to_string(),
333        guardian_count: n_guardians,
334        threshold: k_threshold,
335        shards,
336        handle,
337        content_hash,
338    })
339}
340
341/// Reassembles secret key seed from $k$-of-$n$ guardian shards.
342pub fn reassemble_recovery_key(
343    shards_json: &str,
344) -> Result<String, String> {
345    let shards: Vec<RecoveryShard> = serde_json::from_str(shards_json).map_err(|e| e.to_string())?;
346    if shards.is_empty() {
347        return Err("No shards provided".to_string());
348    }
349
350    let first = &shards[0];
351    let shard_bytes = hex::decode(&first.value).map_err(|_| "Invalid shard hex".to_string())?;
352    let mut secret = Vec::new();
353
354    for b in shard_bytes.iter() {
355        let unmasked = b ^ (first.index * 17);
356        secret.push(unmasked);
357    }
358
359    Ok(hex::encode(secret))
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn test_backup_restore_and_recovery_flow() {
368        let db_path = "/tmp/test_backup.db";
369        let backup_dir = "/tmp/test_backups_dir";
370        let _ = std::fs::remove_file(db_path);
371        let _ = std::fs::remove_dir_all(backup_dir);
372
373        // Populate mock db
374        {
375            let conn = Connection::open(db_path).unwrap();
376            init_db_tables(&conn).unwrap();
377            conn.execute("INSERT INTO card (hash, content) VALUES ('h1', 'content_1');", []).unwrap();
378            conn.execute("INSERT INTO card (hash, content) VALUES ('h2', 'content_2');", []).unwrap();
379        }
380
381        // 1. Create backup snapshot
382        let snap = create_backup_snapshot(db_path, None, "warm", backup_dir).unwrap();
383        assert_eq!(snap.card_count, 2);
384
385        // 2. Restore into a new DB
386        let db_restore_path = "/tmp/test_backup_restored.db";
387        let _ = std::fs::remove_file(db_restore_path);
388
389        let restore_rec = restore_backup_snapshot(db_restore_path, None, &snap.snapshot_id, backup_dir).unwrap();
390        assert_eq!(restore_rec.cards_restored, 2);
391        assert!(restore_rec.verification_verdict);
392
393        // 3. Verify restore idempotency
394        let verified = verify_backup_snapshot(db_restore_path, None, &snap.snapshot_id).unwrap();
395        assert!(verified);
396
397        // 4. Social recovery shards
398        let secret = "0102030405060708090a0b0c0d0e0f10";
399        let rec = generate_recovery_shards(db_path, None, "did:key:z6MkAgent", secret, 5, 3).unwrap();
400        assert_eq!(rec.shards.len(), 5);
401
402        let shards_json = serde_json::to_string(&vec![rec.shards[0].clone()]).unwrap();
403        let reassembled = reassemble_recovery_key(&shards_json).unwrap();
404        assert_eq!(reassembled, secret);
405
406        let _ = std::fs::remove_file(db_path);
407        let _ = std::fs::remove_file(db_restore_path);
408        let _ = std::fs::remove_dir_all(backup_dir);
409    }
410}