clm-kernel 0.0.24

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
444
445
446
447
448
449
//! Self-verifying CAS records, distinct from the legacy bare-BLAKE3 `MCard` domain type.
//!
//! The algorithm is resolved once at write time and used for both the digest and the canonical
//! `g_time` coordinate. Readers derive the declared algorithm from stored `g_time`; an ISO-only
//! legacy coordinate is classified only by digest recomputation and is never defaulted.
use crate::layer0::gtime::{DEFAULT_G_TIME_LOCALE, LEGACY_G_TIME_PREFIX};

#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub const CLM_SCHEMA_PCARD_DESCRIPTOR_V1: &str =
    crate::layer0::vocabulary::HANDLE_CLM_LAYER1_PCARD_DESCRIPTOR_V1;
pub const CLM_SCHEMA_DIRECTORY_MANIFEST_V1: &str =
    crate::layer0::vocabulary::HANDLE_CLM_LAYER2_DIRECTORY_MANIFEST_V1;
pub const CLM_SCHEMA_CHUNK_MANIFEST_V1: &str =
    crate::layer0::vocabulary::HANDLE_CLM_LAYER2_CHUNK_MANIFEST_V1;
pub const CLM_SCHEMA_PRUNING_ANCHOR_V1: &str =
    crate::layer0::vocabulary::HANDLE_CLM_LAYER2_PRUNING_ANCHOR_V1;
pub const CLM_SCHEMA_CONVERSATIONAL_TURN_V1: &str =
    crate::layer0::vocabulary::HANDLE_CLM_LAYER4_CONVERSATIONAL_TURN_V1;

pub fn normalize_schema_uri(uri: &str) -> String {
    match uri {
        crate::layer0::vocabulary::HANDLE_MCARD_SCHEMAS_CONVERSATIONAL_TURN_V1 => {
            CLM_SCHEMA_CONVERSATIONAL_TURN_V1.to_string()
        }
        _ => uri.to_string(),
    }
}

pub fn is_valid_clm_schema_uri(uri: &str) -> bool {
    let Some(rest) = uri.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_LAYER) else {
        return false;
    };
    let Some((layer, rest)) = rest.split_once('/') else {
        return false;
    };
    if layer.len() != 1 || !layer.as_bytes()[0].is_ascii_digit() || layer.as_bytes()[0] > b'5' {
        return false;
    }
    let Some((artifact, version)) = rest.rsplit_once("/v") else {
        return false;
    };
    !artifact.is_empty()
        && artifact
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        && !version.is_empty()
        && version.chars().all(|c| c.is_ascii_digit())
}

pub fn validate_schema_fields(
    schema: Option<&str>,
    schema_uri: Option<&str>,
) -> Result<(), String> {
    if let (Some(schema), Some(schema_uri)) = (schema, schema_uri) {
        if normalize_schema_uri(schema) != normalize_schema_uri(schema_uri) {
            return Err(format!("Schema mismatch: {schema} vs {schema_uri}"));
        }
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct MCardRecord {
    pub hash: String,
    pub content: Vec<u8>,
    #[serde(alias = "gTime")]
    pub g_time: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordVerification {
    DeclaredOk {
        algorithm: String,
    },
    DeclaredMismatch {
        algorithm: String,
        computed_hash: String,
    },
    LegacyClassified {
        algorithm: String,
    },
    LegacyUnclassified,
    LegacyAmbiguous,
    Malformed {
        reason: String,
    },
}

fn valid_timestamp(timestamp: &str) -> bool {
    timestamp == timestamp.trim()
        && crate::layer0::gtime::normalize_g_time_timestamp(timestamp).is_ok()
}

impl MCardRecord {
    /// Create a fresh record using an explicit algorithm or the runtime configuration.
    pub fn create(content: &[u8], algorithm: Option<&str>) -> Result<Self, String> {
        Self::create_at(content, algorithm, None, DEFAULT_G_TIME_LOCALE)
    }

    /// Create a record with a caller-supplied timestamp and locale, canonicalized through the shared codec.
    pub fn create_at(
        content: &[u8],
        algorithm: Option<&str>,
        timestamp: Option<&str>,
        locale: &str,
    ) -> Result<Self, String> {
        let selected = algorithm
            .unwrap_or(crate::hash::config().active_algorithm)
            .trim()
            .trim_end_matches(':')
            .to_lowercase();
        let hash = crate::hash::raw_hash_bytes_for(&selected, content)?;
        let g_time = match timestamp {
            Some(value) => {
                crate::layer0::gtime::format_canonical_g_time(&selected, value, locale, None)
            }
            None => crate::layer0::gtime::stamp_g_time(&selected, None, Some(locale), None),
        };

        Ok(Self {
            hash,
            content: content.to_vec(),
            g_time,
        })
    }
}

pub fn create_record(content: &[u8], algorithm: Option<&str>) -> Result<MCardRecord, String> {
    MCardRecord::create(content, algorithm)
}

/// Verify an existing record using only its stored hash, content, and `g_time`.
pub fn verify_record(record: &MCardRecord) -> RecordVerification {
    if record.hash.trim().is_empty() || record.g_time.trim().is_empty() {
        return RecordVerification::Malformed {
            reason: "empty hash or g_time".to_string(),
        };
    }

    let (hash_prefix, target_hash) = match record.hash.split_once(':') {
        Some((prefix, raw)) if prefix == prefix.trim() => (
            Some(crate::layer0::gtime::canonical_algorithm_name(prefix)),
            raw.to_lowercase(),
        ),
        Some(_) => {
            return RecordVerification::Malformed {
                reason: "invalid hash prefix".to_string(),
            };
        }
        None => (None, record.hash.to_lowercase()),
    };

    // Algorithm-bearing coordinates must satisfy the full shared codec, including
    // extension and timestamp validation, before they can authorize an address.
    let is_pipe = record.g_time.contains('|');
    if is_pipe || record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
        if let crate::layer0::gtime::ParsedGTime::Malformed(error) =
            crate::layer0::gtime::parse_g_time(&record.g_time)
        {
            return RecordVerification::Malformed {
                reason: error.reason,
            };
        }
    }

    if is_pipe {
        let mut parts = record.g_time.split('|');
        let algorithm =
            crate::layer0::gtime::canonical_algorithm_name(parts.next().unwrap_or_default());
        let timestamp = parts.next().unwrap_or_default().trim();
        let locale = parts.next();
        if algorithm.is_empty() || locale.is_none() || !valid_timestamp(timestamp) {
            return RecordVerification::Malformed {
                reason: "invalid canonical pipe g_time".to_string(),
            };
        }
        if hash_prefix
            .as_deref()
            .is_some_and(|prefix| prefix != algorithm)
        {
            return RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: String::new(),
            };
        }
        let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
            Ok(value) => value,
            Err(reason) => return RecordVerification::Malformed { reason },
        };
        return if computed == target_hash {
            RecordVerification::DeclaredOk { algorithm }
        } else {
            RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: computed,
            }
        };
    }

    // Read-only compatibility for the pre-convergence TypeScript coordinate. It declares its own
    // algorithm and is verified under that value; the writer below never emits this grammar.
    if record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
        let mut fields = HashMap::new();
        for segment in record.g_time.split(';') {
            let Some((key, value)) = segment.split_once(':') else {
                return RecordVerification::Malformed {
                    reason: "invalid legacy TypeScript g_time segment".to_string(),
                };
            };
            if fields.insert(key, value).is_some() {
                return RecordVerification::Malformed {
                    reason: "duplicate legacy TypeScript g_time key".to_string(),
                };
            }
        }
        let algorithm = crate::layer0::gtime::canonical_algorithm_name(
            fields.get("a").copied().unwrap_or_default(),
        );
        let timestamp = fields.get("t").copied().unwrap_or_default();
        if algorithm.is_empty() || !valid_timestamp(timestamp) {
            return RecordVerification::Malformed {
                reason: "invalid legacy TypeScript g_time coordinates".to_string(),
            };
        }
        if hash_prefix
            .as_deref()
            .is_some_and(|prefix| prefix != algorithm)
        {
            return RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: String::new(),
            };
        }
        let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
            Ok(value) => value,
            Err(reason) => return RecordVerification::Malformed { reason },
        };
        return if computed == target_hash {
            RecordVerification::DeclaredOk { algorithm }
        } else {
            RecordVerification::DeclaredMismatch {
                algorithm,
                computed_hash: computed,
            }
        };
    }

    // Bare ISO timestamp carries no algorithm. Do not consult the configured default here.
    if !valid_timestamp(record.g_time.trim()) {
        return RecordVerification::Malformed {
            reason: "unrecognized g_time shape".to_string(),
        };
    }
    let mut matches = Vec::new();
    for prefix in crate::hash::list_algorithms() {
        let algorithm = prefix.trim_end_matches(':');
        if let Ok(computed) = crate::hash::raw_hash_bytes_for(algorithm, &record.content) {
            if computed == target_hash {
                matches.push(algorithm.to_string());
            }
        }
    }
    match matches.len() {
        1 => RecordVerification::LegacyClassified {
            algorithm: matches.remove(0),
        },
        n if n > 1 => RecordVerification::LegacyAmbiguous,
        _ => RecordVerification::LegacyUnclassified,
    }
}

/// Persist a declared record to an existing `card` table and verify the database read-back.
#[cfg(any(feature = "native", feature = "db"))]
pub fn write_record(
    connection: &Connection,
    content: &[u8],
    algorithm: Option<&str>,
) -> Result<MCardRecord, String> {
    let record = create_record(content, algorithm)?;
    if !matches!(
        verify_record(&record),
        RecordVerification::DeclaredOk { .. }
    ) {
        return Err("new Rust record did not verify before persistence".to_string());
    }

    let persisted_hash = crate::tape::put(connection, &record.content, &record.g_time)?;
    if persisted_hash != record.hash {
        return Err("tape writer changed the selected MCardRecord digest".to_string());
    }

    let read_back = connection
        .query_row(
            "SELECT hash, content, g_time FROM card WHERE hash = ?1",
            [&record.hash],
            |row| {
                Ok(MCardRecord {
                    hash: row.get(0)?,
                    content: row.get(1)?,
                    g_time: row.get(2)?,
                })
            },
        )
        .map_err(|error| format!("failed to read back MCardRecord: {error}"))?;

    match verify_record(&read_back) {
        RecordVerification::DeclaredOk { .. } => Ok(read_back),
        verdict => Err(format!(
            "persisted MCardRecord failed verification: {verdict:?}"
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::{Signature, Verifier, VerifyingKey};
    use sha2::{Digest, Sha256};

    fn decode_b64url(input: &str) -> Vec<u8> {
        let mut buf: u32 = 0;
        let mut bits: u32 = 0;
        let mut out = Vec::with_capacity((input.len() * 3) / 4);
        for b in input.bytes() {
            let val: u32 = match b {
                b'A'..=b'Z' => (b - b'A') as u32,
                b'a'..=b'z' => (b - b'a' + 26) as u32,
                b'0'..=b'9' => (b - b'0' + 52) as u32,
                b'-' => 62,
                b'_' => 63,
                _ => panic!("invalid base64url byte {b}"),
            };
            buf = (buf << 6) | val;
            bits += 6;
            if bits >= 8 {
                bits -= 8;
                out.push(((buf >> bits) & 0xff) as u8);
            }
        }
        out
    }

    fn encode_vcard_signing_bytes(
        expression: &str,
        subject_uri: &str,
        subject_hash: &str,
        snapshot_digest: &str,
        signer: &str,
    ) -> Vec<u8> {
        let mut out = Vec::from(&b"CLM-VCARD-1\0"[..]);
        for field in [
            expression,
            subject_uri,
            subject_hash,
            snapshot_digest,
            signer,
        ] {
            let bytes = field.as_bytes();
            out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
            out.extend_from_slice(bytes);
        }
        out
    }

    fn verification_status_label(verdict: &RecordVerification) -> &'static str {
        match verdict {
            RecordVerification::DeclaredOk { .. } => "declared-ok",
            RecordVerification::DeclaredMismatch { .. } => "declared-mismatch",
            RecordVerification::LegacyClassified { .. } => "legacy-classified",
            RecordVerification::LegacyUnclassified => "legacy-unclassified",
            RecordVerification::LegacyAmbiguous => "legacy-ambiguous",
            RecordVerification::Malformed { .. } => "malformed",
        }
    }

    #[test]
    fn verifies_cross_runtime_inv609_golden_vectors_fail_closed() {
        let raw = include_str!("../../../../tests/golden/vcard_signature_and_snapshot_v1.json");
        let doc: serde_json::Value = serde_json::from_str(raw).expect("parse golden json");

        for vec in doc["snapshot_vectors"]
            .as_array()
            .expect("snapshot_vectors")
        {
            let snap_b64 = vec["snapshot_base64url"].as_str().unwrap();
            let wire = decode_b64url(snap_b64);
            assert_eq!(hex::encode(&wire), vec["wire_hex"].as_str().unwrap());
            assert!(wire.len() >= 2 && wire[0] == 1);
            let digest = format!("sha256:{}", hex::encode(Sha256::digest(&wire)));
            assert_eq!(digest, vec["snapshot_digest"].as_str().unwrap());
        }

        assert_ne!(
            doc["map_collision_pair"]["digest_ba"].as_str().unwrap(),
            doc["map_collision_pair"]["digest_ab"].as_str().unwrap(),
        );

        let sv = &doc["vcard_signing_vector"];
        let signing_bytes = encode_vcard_signing_bytes(
            sv["expression"].as_str().unwrap(),
            sv["subject_uri"].as_str().unwrap(),
            sv["subject_hash"].as_str().unwrap(),
            sv["snapshot_digest"].as_str().unwrap(),
            sv["signer_did_key"].as_str().unwrap(),
        );
        assert_eq!(
            hex::encode(&signing_bytes),
            sv["signing_bytes_hex"].as_str().unwrap()
        );
        let pub_bytes: [u8; 32] = hex::decode(sv["signer_pubkey_hex"].as_str().unwrap())
            .unwrap()
            .try_into()
            .unwrap();
        let sig_bytes: [u8; 64] = decode_b64url(sv["signature_base64url"].as_str().unwrap())
            .try_into()
            .unwrap();
        let verifying_key = VerifyingKey::from_bytes(&pub_bytes).expect("valid ed25519 pubkey");
        let sig = Signature::from_bytes(&sig_bytes);
        verifying_key
            .verify(&signing_bytes, &sig)
            .expect("signature verifies");
        let mut tampered = signing_bytes.clone();
        tampered.push(0);
        assert!(verifying_key.verify(&tampered, &sig).is_err());

        for cas_vec in doc["content_address_vectors"]
            .as_array()
            .expect("cas vectors")
        {
            let record = MCardRecord {
                hash: cas_vec["hash"].as_str().unwrap().to_string(),
                content: hex::decode(cas_vec["content_hex"].as_str().unwrap()).unwrap(),
                g_time: cas_vec["g_time"].as_str().unwrap().to_string(),
            };
            let verdict = verify_record(&record);
            let label = verification_status_label(&verdict);
            assert_eq!(label, cas_vec["expected_status"].as_str().unwrap());
            let authoritative = matches!(verdict, RecordVerification::DeclaredOk { .. });
            assert_eq!(
                authoritative,
                cas_vec["authoritative_for_commit"].as_bool().unwrap()
            );
        }
    }
}