clm-kernel 0.0.7

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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())
}

/// Creates a tier-aware Merkle-DAG backup snapshot and registers `mcard:backup/snapshot/{snapshot_id}`.
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 (h, c) in rows.flatten() {
        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,
    })
}

/// Restores account MCards from a snapshot backup file and registers `mcard:backup/restore/{snapshot_id}`.
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,
    })
}

/// Verifies restore integrity and idempotency.
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)
}

/// Generates $k$-of-$n$ Shamir Social Recovery shards for an EOA DID key seed.
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();

    // Simple polynomial evaluation over GF(256) XOR distribution
    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,
    })
}

/// Reassembles secret key seed from $k$-of-$n$ guardian shards.
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 b in shard_bytes.iter() {
        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);

        // Populate mock db
        {
            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();
        }

        // 1. Create backup snapshot
        let snap = create_backup_snapshot(db_path, None, "warm", backup_dir).unwrap();
        assert_eq!(snap.card_count, 2);

        // 2. Restore into a new DB
        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);

        // 3. Verify restore idempotency
        let verified = verify_backup_snapshot(db_restore_path, None, &snap.snapshot_id).unwrap();
        assert!(verified);

        // 4. Social recovery shards
        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);
    }
}