use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use rand::RngCore;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BackupSnapshotRecord {
pub snapshot_id: String,
pub tier: String,
pub card_count: u64,
pub merkle_dag_root: String,
pub timestamp: String,
pub handle: String,
pub content_hash: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RestoreRecord {
pub snapshot_id: String,
pub cards_restored: u64,
pub verification_verdict: bool,
pub handle: String,
pub content_hash: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecoveryShard {
pub index: u8,
pub value: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecoveryRecord {
pub did: String,
pub guardian_count: u8,
pub threshold: u8,
pub shards: Vec<RecoveryShard>,
pub handle: String,
pub content_hash: String,
}
fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
if db_name_or_path.contains('/') || db_name_or_path.contains('\\') {
PathBuf::from(db_name_or_path)
} else {
let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
});
root.join("data").join("execution_logs").join(db_name_or_path)
}
}
fn init_db_tables(conn: &Connection) -> Result<(), String> {
conn.execute(
"CREATE TABLE IF NOT EXISTS card (
hash TEXT PRIMARY KEY,
content TEXT NOT NULL,
g_time TEXT
);",
[],
).map_err(|e| e.to_string())?;
conn.execute(
"CREATE TABLE IF NOT EXISTS handle_registry (
handle TEXT PRIMARY KEY,
hash TEXT NOT NULL
);",
[],
).map_err(|e| e.to_string())?;
Ok(())
}
fn generate_sha256(content: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(content.as_bytes());
hex::encode(hasher.finalize())
}
pub fn create_backup_snapshot(
db_name_or_path: &str,
clm_root: Option<&str>,
tier: &str,
backup_dir: &str,
) -> Result<BackupSnapshotRecord, String> {
let db_path = resolve_db_path(db_name_or_path, clm_root);
if !db_path.exists() {
return Err(format!("Database file {} does not exist", db_path.display()));
}
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
init_db_tables(&conn)?;
let mut stmt = conn.prepare("SELECT hash, content FROM card ORDER BY hash ASC;").map_err(|e| e.to_string())?;
let rows = stmt.query_map([], |row| {
let h: String = row.get(0)?;
let c: String = row.get(1)?;
Ok((h, c))
}).map_err(|e| e.to_string())?;
let mut cards: Vec<(String, String)> = Vec::new();
let mut combined_hashes = String::new();
for r in rows {
if let Ok((h, c)) = r {
combined_hashes.push_str(&h);
cards.push((h, c));
}
}
let card_count = cards.len() as u64;
let merkle_dag_root = generate_sha256(&combined_hashes);
let mut snap_bytes = [0u8; 8];
rand::thread_rng().fill_bytes(&mut snap_bytes);
let snapshot_id = format!("snap_{}_{}", tier, hex::encode(snap_bytes));
let backup_path = PathBuf::from(backup_dir);
std::fs::create_dir_all(&backup_path).map_err(|e| e.to_string())?;
let snapshot_file = backup_path.join(format!("{}.json", snapshot_id));
let snapshot_payload = serde_json::json!({
"snapshot_id": snapshot_id,
"tier": tier,
"card_count": card_count,
"merkle_dag_root": merkle_dag_root,
"cards": cards
});
let payload_str = serde_json::to_string_pretty(&snapshot_payload).map_err(|e| e.to_string())?;
std::fs::write(&snapshot_file, payload_str).map_err(|e| e.to_string())?;
let timestamp = chrono::Utc::now().to_rfc3339();
let handle = format!("mcard:backup/snapshot/{}", snapshot_id);
let mcard_val = serde_json::json!({
"type": "backup_snapshot",
"snapshot_id": snapshot_id,
"tier": tier,
"card_count": card_count,
"merkle_dag_root": merkle_dag_root,
"backup_file": snapshot_file.to_string_lossy(),
"timestamp": timestamp
});
let content_json = mcard_val.to_string();
let content_hash = generate_sha256(&content_json);
conn.execute(
"INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
rusqlite::params![content_hash, content_json],
).map_err(|e| e.to_string())?;
conn.execute(
"INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
rusqlite::params![handle, content_hash],
).map_err(|e| e.to_string())?;
Ok(BackupSnapshotRecord {
snapshot_id,
tier: tier.to_string(),
card_count,
merkle_dag_root,
timestamp,
handle,
content_hash,
})
}
pub fn restore_backup_snapshot(
db_name_or_path: &str,
clm_root: Option<&str>,
snapshot_id: &str,
backup_dir: &str,
) -> Result<RestoreRecord, String> {
let backup_path = PathBuf::from(backup_dir).join(format!("{}.json", snapshot_id));
if !backup_path.exists() {
return Err(format!("Snapshot file {} not found", backup_path.display()));
}
let payload_str = std::fs::read_to_string(&backup_path).map_err(|e| e.to_string())?;
let val: serde_json::Value = serde_json::from_str(&payload_str).map_err(|e| e.to_string())?;
let expected_root = val.get("merkle_dag_root").and_then(|x| x.as_str()).unwrap_or("");
let cards_array = val.get("cards").and_then(|x| x.as_array()).ok_or("Invalid cards array in snapshot")?;
let db_path = resolve_db_path(db_name_or_path, clm_root);
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
init_db_tables(&conn)?;
let mut combined_hashes = String::new();
let mut restored_count = 0u64;
for item in cards_array {
if let (Some(h), Some(c)) = (item.get(0).and_then(|x| x.as_str()), item.get(1).and_then(|x| x.as_str())) {
combined_hashes.push_str(h);
conn.execute(
"INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
rusqlite::params![h, c],
).map_err(|e| e.to_string())?;
restored_count += 1;
}
}
let calculated_root = generate_sha256(&combined_hashes);
let verification_verdict = calculated_root == expected_root;
let handle = format!("mcard:backup/restore/{}", snapshot_id);
let timestamp = chrono::Utc::now().to_rfc3339();
let mcard_val = serde_json::json!({
"type": "backup_restore",
"snapshot_id": snapshot_id,
"cards_restored": restored_count,
"verification_verdict": verification_verdict,
"timestamp": timestamp
});
let content_json = mcard_val.to_string();
let content_hash = generate_sha256(&content_json);
conn.execute(
"INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
rusqlite::params![content_hash, content_json],
).map_err(|e| e.to_string())?;
conn.execute(
"INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
rusqlite::params![handle, content_hash],
).map_err(|e| e.to_string())?;
Ok(RestoreRecord {
snapshot_id: snapshot_id.to_string(),
cards_restored: restored_count,
verification_verdict,
handle,
content_hash,
})
}
pub fn verify_backup_snapshot(
db_name_or_path: &str,
clm_root: Option<&str>,
snapshot_id: &str,
) -> Result<bool, String> {
let db_path = resolve_db_path(db_name_or_path, clm_root);
if !db_path.exists() {
return Ok(false);
}
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
let handle = format!("mcard:backup/restore/{}", snapshot_id);
let content: String = match conn.query_row(
"SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
rusqlite::params![handle],
|row| row.get::<usize, String>(0),
) {
Ok(c) => c,
Err(_) => return Ok(false),
};
let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
let verdict = v.get("verification_verdict").and_then(|x| x.as_bool()).unwrap_or(false);
Ok(verdict)
}
pub fn generate_recovery_shards(
db_name_or_path: &str,
clm_root: Option<&str>,
did: &str,
secret_hex: &str,
n_guardians: u8,
k_threshold: u8,
) -> Result<RecoveryRecord, String> {
if k_threshold > n_guardians || k_threshold == 0 {
return Err("Invalid threshold k for n guardians".to_string());
}
let secret_bytes = hex::decode(secret_hex).map_err(|_| "Invalid hex secret".to_string())?;
let mut shards: Vec<RecoveryShard> = Vec::new();
for i in 1..=n_guardians {
let mut shard_data = Vec::new();
for b in &secret_bytes {
let masked = b ^ (i * 17);
shard_data.push(masked);
}
shards.push(RecoveryShard {
index: i,
value: hex::encode(shard_data),
});
}
let db_path = resolve_db_path(db_name_or_path, clm_root);
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
init_db_tables(&conn)?;
let handle = format!("mcard:backup/recovery/{}", did);
let mcard_val = serde_json::json!({
"type": "social_recovery",
"did": did,
"guardian_count": n_guardians,
"threshold": k_threshold,
"shards": shards
});
let content_json = mcard_val.to_string();
let content_hash = generate_sha256(&content_json);
conn.execute(
"INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
rusqlite::params![content_hash, content_json],
).map_err(|e| e.to_string())?;
conn.execute(
"INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
rusqlite::params![handle, content_hash],
).map_err(|e| e.to_string())?;
Ok(RecoveryRecord {
did: did.to_string(),
guardian_count: n_guardians,
threshold: k_threshold,
shards,
handle,
content_hash,
})
}
pub fn reassemble_recovery_key(
shards_json: &str,
) -> Result<String, String> {
let shards: Vec<RecoveryShard> = serde_json::from_str(shards_json).map_err(|e| e.to_string())?;
if shards.is_empty() {
return Err("No shards provided".to_string());
}
let first = &shards[0];
let shard_bytes = hex::decode(&first.value).map_err(|_| "Invalid shard hex".to_string())?;
let mut secret = Vec::new();
for (_idx, b) in shard_bytes.iter().enumerate() {
let unmasked = b ^ (first.index * 17);
secret.push(unmasked);
}
Ok(hex::encode(secret))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_backup_restore_and_recovery_flow() {
let db_path = "/tmp/test_backup.db";
let backup_dir = "/tmp/test_backups_dir";
let _ = std::fs::remove_file(db_path);
let _ = std::fs::remove_dir_all(backup_dir);
{
let conn = Connection::open(db_path).unwrap();
init_db_tables(&conn).unwrap();
conn.execute("INSERT INTO card (hash, content) VALUES ('h1', 'content_1');", []).unwrap();
conn.execute("INSERT INTO card (hash, content) VALUES ('h2', 'content_2');", []).unwrap();
}
let snap = create_backup_snapshot(db_path, None, "warm", backup_dir).unwrap();
assert_eq!(snap.card_count, 2);
let db_restore_path = "/tmp/test_backup_restored.db";
let _ = std::fs::remove_file(db_restore_path);
let restore_rec = restore_backup_snapshot(db_restore_path, None, &snap.snapshot_id, backup_dir).unwrap();
assert_eq!(restore_rec.cards_restored, 2);
assert!(restore_rec.verification_verdict);
let verified = verify_backup_snapshot(db_restore_path, None, &snap.snapshot_id).unwrap();
assert!(verified);
let secret = "0102030405060708090a0b0c0d0e0f10";
let rec = generate_recovery_shards(db_path, None, "did:key:z6MkAgent", secret, 5, 3).unwrap();
assert_eq!(rec.shards.len(), 5);
let shards_json = serde_json::to_string(&vec![rec.shards[0].clone()]).unwrap();
let reassembled = reassemble_recovery_key(&shards_json).unwrap();
assert_eq!(reassembled, secret);
let _ = std::fs::remove_file(db_path);
let _ = std::fs::remove_file(db_restore_path);
let _ = std::fs::remove_dir_all(backup_dir);
}
}