clm-kernel 0.0.2

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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use rand::RngCore;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DcaRecord {
    pub asset_id: String,
    pub token_id: String,
    pub content_hash: String,
    pub owner_did: String,
    pub token_policy: String,
    pub timestamp: String,
    pub handle: String,
    pub content_hash_mcard: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NftTransferRecord {
    pub token_id: String,
    pub previous_owner_did: String,
    pub new_owner_did: String,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SbtRecord {
    pub credential_id: String,
    pub recipient_did: String,
    pub role_name: String,
    pub is_transferable: bool,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CommunityCreditsRecord {
    pub did: String,
    pub balance: f64,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EditionRecord {
    pub edition_id: String,
    pub asset_id: String,
    pub owner_did: String,
    pub edition_number: u32,
    pub max_editions: u32,
    pub timestamp: String,
    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())
}

/// Mints a Digital Content Asset (DCA) with an attached transferable Content Ownership NFT (`mcard:token/dca/{asset_id}`).
pub fn mint_dca_nft(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    content_hash: &str,
    owner_did: &str,
) -> Result<DcaRecord, String> {
    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 asset_bytes = [0u8; 8];
    rand::thread_rng().fill_bytes(&mut asset_bytes);
    let asset_id = format!("dca_{}", hex::encode(asset_bytes));
    let token_id = format!("nft_{}", hex::encode(asset_bytes));
    let handle = format!("mcard:token/dca/{}", asset_id);
    let timestamp = chrono::Utc::now().to_rfc3339();
    let token_policy = "transferable_nft".to_string();

    let json_val = serde_json::json!({
        "type": "digital_content_asset",
        "asset_id": asset_id,
        "token_id": token_id,
        "content_hash": content_hash,
        "owner_did": owner_did,
        "token_policy": token_policy,
        "timestamp": timestamp
    });

    let content_json = json_val.to_string();
    let content_hash_mcard = 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_mcard, 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_mcard],
    ).map_err(|e| e.to_string())?;

    // Also register NFT handle
    let nft_handle = format!("mcard:token/nft/{}", token_id);
    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![nft_handle, content_hash_mcard],
    ).map_err(|e| e.to_string())?;

    Ok(DcaRecord {
        asset_id,
        token_id,
        content_hash: content_hash.to_string(),
        owner_did: owner_did.to_string(),
        token_policy,
        timestamp,
        handle,
        content_hash_mcard,
    })
}

/// Transfers a Content Ownership NFT to a new owner DID while preserving the invariant content hash.
pub fn transfer_nft(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    token_id: &str,
    current_owner_did: &str,
    new_owner_did: &str,
) -> Result<NftTransferRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if !db_path.exists() {
        return Err(format!("Database not found for token {}", token_id));
    }

    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    let nft_handle = format!("mcard:token/nft/{}", token_id);

    let (content, _): (String, String) = conn.query_row(
        "SELECT c.content, c.hash FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
        rusqlite::params![nft_handle],
        |row| Ok((row.get(0)?, row.get(1)?)),
    ).map_err(|_| format!("NFT token {} not found", token_id))?;

    let mut v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
    let policy = v.get("token_policy").and_then(|x| x.as_str()).unwrap_or("");
    if policy == "soulbound" {
        return Err("Cannot transfer Soulbound Credential".to_string());
    }

    let existing_owner = v.get("owner_did").and_then(|x| x.as_str()).unwrap_or("");
    if existing_owner != current_owner_did {
        return Err(format!("Current owner mismatch: expected {}, found {}", current_owner_did, existing_owner));
    }

    v["owner_did"] = serde_json::Value::String(new_owner_did.to_string());
    let timestamp = chrono::Utc::now().to_rfc3339();
    v["timestamp"] = serde_json::Value::String(timestamp.clone());

    let updated_json = v.to_string();
    let updated_hash = generate_sha256(&updated_json);

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![updated_hash, updated_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![nft_handle, updated_hash],
    ).map_err(|e| e.to_string())?;

    Ok(NftTransferRecord {
        token_id: token_id.to_string(),
        previous_owner_did: current_owner_did.to_string(),
        new_owner_did: new_owner_did.to_string(),
        timestamp,
        handle: nft_handle,
        content_hash: updated_hash,
    })
}

/// Mints a non-transferable Soulbound Credential (`mcard:token/sbt/{credential_id}`).
pub fn mint_soulbound_credential(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    recipient_did: &str,
    role_name: &str,
) -> Result<SbtRecord, String> {
    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 sbt_bytes = [0u8; 8];
    rand::thread_rng().fill_bytes(&mut sbt_bytes);
    let credential_id = format!("sbt_{}", hex::encode(sbt_bytes));
    let handle = format!("mcard:token/sbt/{}", credential_id);
    let timestamp = chrono::Utc::now().to_rfc3339();

    let json_val = serde_json::json!({
        "type": "soulbound_credential",
        "credential_id": credential_id,
        "token_policy": "soulbound",
        "recipient_did": recipient_did,
        "owner_did": recipient_did,
        "role_name": role_name,
        "is_transferable": false,
        "timestamp": timestamp
    });

    let content_json = json_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())?;

    // Also register under nft handle to test transfer rejection
    let nft_handle = format!("mcard:token/nft/{}", credential_id);
    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![nft_handle, content_hash],
    ).map_err(|e| e.to_string())?;

    Ok(SbtRecord {
        credential_id,
        recipient_did: recipient_did.to_string(),
        role_name: role_name.to_string(),
        is_transferable: false,
        timestamp,
        handle,
        content_hash,
    })
}

/// Mints fungible Community Credits (`mcard:token/credits/{did}`).
pub fn mint_community_credits(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    recipient_did: &str,
    amount: f64,
) -> Result<CommunityCreditsRecord, String> {
    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:token/credits/{}", recipient_did);
    let existing_balance: f64 = 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),
    ).map(|content| {
        let v: serde_json::Value = serde_json::from_str(&content).unwrap_or_default();
        v.get("balance").and_then(|x| x.as_f64()).unwrap_or(0.0)
    }).unwrap_or(0.0);

    let new_balance = existing_balance + amount;
    let timestamp = chrono::Utc::now().to_rfc3339();

    let json_val = serde_json::json!({
        "type": "community_credits",
        "did": recipient_did,
        "balance": new_balance,
        "token_policy": "fungible",
        "timestamp": timestamp
    });

    let content_json = json_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(CommunityCreditsRecord {
        did: recipient_did.to_string(),
        balance: new_balance,
        timestamp,
        handle,
        content_hash,
    })
}

/// Mints limited-run semi-fungible Edition Tokens (`mcard:token/edition/{edition_id}`).
pub fn mint_edition_token(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    asset_id: &str,
    owner_did: &str,
    edition_number: u32,
    max_editions: u32,
) -> Result<EditionRecord, String> {
    if edition_number > max_editions || edition_number == 0 {
        return Err(format!("Edition number {} exceeds maximum edition limit {}", edition_number, max_editions));
    }

    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 edition_id = format!("ed_{}_{}", asset_id, edition_number);
    let handle = format!("mcard:token/edition/{}", edition_id);
    let timestamp = chrono::Utc::now().to_rfc3339();

    let json_val = serde_json::json!({
        "type": "edition_token",
        "edition_id": edition_id,
        "asset_id": asset_id,
        "owner_did": owner_did,
        "edition_number": edition_number,
        "max_editions": max_editions,
        "token_policy": "semi_fungible",
        "timestamp": timestamp
    });

    let content_json = json_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(EditionRecord {
        edition_id,
        asset_id: asset_id.to_string(),
        owner_did: owner_did.to_string(),
        edition_number,
        max_editions,
        timestamp,
        handle,
        content_hash,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_token_economics_pipeline() {
        let db_path = "/tmp/test_tokens.db";
        let _ = std::fs::remove_file(db_path);

        // 1. Mint DCA
        let dca = mint_dca_nft(db_path, None, "0xcontent_hash_123", "did:key:z6MkCreator").unwrap();
        assert_eq!(dca.owner_did, "did:key:z6MkCreator");

        // 2. Transfer NFT
        let tx = transfer_nft(db_path, None, &dca.token_id, "did:key:z6MkCreator", "did:key:z6MkBuyer").unwrap();
        assert_eq!(tx.new_owner_did, "did:key:z6MkBuyer");

        // 3. Mint Soulbound Credential
        let sbt = mint_soulbound_credential(db_path, None, "did:key:z6MkMember", "Core Contributor").unwrap();
        assert_eq!(sbt.role_name, "Core Contributor");

        // 4. Verify SBT transfer failure
        let sbt_err = transfer_nft(db_path, None, &sbt.credential_id, "did:key:z6MkMember", "did:key:z6MkOther");
        assert!(sbt_err.is_err());

        // 5. Mint Community Credits
        let credits = mint_community_credits(db_path, None, "did:key:z6MkContributor", 50.0).unwrap();
        assert_eq!(credits.balance, 50.0);

        let credits2 = mint_community_credits(db_path, None, "did:key:z6MkContributor", 25.0).unwrap();
        assert_eq!(credits2.balance, 75.0);

        // 6. Edition Tokens & Limit Enforcement
        let ed1 = mint_edition_token(db_path, None, "dca_001", "did:key:z6MkCollector", 1, 10).unwrap();
        assert_eq!(ed1.edition_number, 1);

        let ed_err = mint_edition_token(db_path, None, "dca_001", "did:key:z6MkCollector", 11, 10);
        assert!(ed_err.is_err());

        let _ = std::fs::remove_file(db_path);
    }
}