clm-kernel 0.0.9

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
//! Threshold Signature Scheme scaffold for Stage 3.
//!
//! This module uses Shamir's Secret Sharing over GF(256) (via the
//! `shamir-algorithm` crate) to split an Ed25519 signing key seed into M-of-N
//! shares. Reconstructing the seed from M shares produces a standard Ed25519
//! signature, making threshold signatures structurally indistinguishable from
//! single-key signatures.
//!
//! NOTE: This is a functional scaffold, not a full distributed MPC protocol.
//! A production TSS (e.g., FROST) would avoid ever reconstructing the secret
//! in one place. That upgrade is tracked by ADR-005.

use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
use shamir_algorithm::ShamirSS;
use std::collections::BTreeMap;
use zeroize::Zeroize;
use zeroize::Zeroizing;

/// A single share of a threshold secret.
#[derive(Debug, Clone, PartialEq)]
pub struct Share {
    pub index: u8,
    /// Threshold M required to reconstruct the secret.
    pub m: u8,
    pub data: Vec<u8>,
}

/// Configuration for an M-of-N threshold scheme.
#[derive(Debug, Clone)]
pub struct ThresholdConfig {
    pub m: u8,
    pub n: u8,
    pub guardian_dids: Vec<String>,
}

impl ThresholdConfig {
    pub fn validate(&self) -> Result<(), String> {
        if self.m == 0 {
            return Err("threshold M cannot be zero".to_string());
        }
        if self.n == 0 {
            return Err("share count N cannot be zero".to_string());
        }
        if self.m > self.n {
            return Err(format!(
                "threshold M ({}) cannot exceed share count N ({})",
                self.m, self.n
            ));
        }
        if self.guardian_dids.len() != self.n as usize {
            return Err(format!(
                "expected {} guardian DIDs, got {}",
                self.n,
                self.guardian_dids.len()
            ));
        }
        Ok(())
    }
}

/// Split a 32-byte Ed25519 signing key seed into N shares requiring M to
/// reconstruct.
pub fn split_key(secret: &[u8], m: u8, n: u8) -> Result<Vec<Share>, String> {
    if m == 0 {
        return Err("threshold M cannot be zero".to_string());
    }
    if n == 0 || m > n {
        return Err("invalid M-of-N configuration".to_string());
    }
    if secret.len() != 32 {
        return Err(format!(
            "Ed25519 seed must be 32 bytes, got {}",
            secret.len()
        ));
    }

    let shares = ShamirSS::split(n as i32, m as i32, secret.to_vec())
        .map_err(|e| format!("shamir split failed: {}", e))?;

    Ok(shares
        .into_iter()
        .map(|(index, data)| Share {
            index: index as u8,
            m,
            data,
        })
        .collect())
}

/// Reconstruct a secret from at least M shares.
pub fn reconstruct_secret(shares: &[Share]) -> Result<Vec<u8>, String> {
    if shares.len() < 2 {
        return Err("need at least 2 shares to reconstruct".to_string());
    }
    let mut parts: BTreeMap<i32, Vec<u8>> = BTreeMap::new();
    for share in shares {
        parts.insert(share.index as i32, share.data.clone());
    }
    ShamirSS::join(parts).map_err(|e| format!("shamir join failed: {}", e))
}

/// Sign a message by reconstructing the key from M shares and using standard
/// Ed25519 signing.
pub fn threshold_sign(shares: &[Share], message: &[u8]) -> Result<ed25519_dalek::Signature, String> {
    if shares.is_empty() {
        return Err("no shares provided".to_string());
    }
    let m = shares[0].m;
    if (shares.len() as u8) < m {
        return Err(format!(
            "insufficient shares: need {}, got {}",
            m,
            shares.len()
        ));
    }
    let secret = reconstruct_secret(shares)?;
    let seed: [u8; 32] = secret
        .try_into()
        .map_err(|_| "reconstructed secret is not 32 bytes".to_string())?;
    let signing_key = SigningKey::from_bytes(&seed);
    Ok(signing_key.sign(message))
}

/// Verify a threshold signature using a standard Ed25519 verifying key.
pub fn threshold_verify(
    public_key: &VerifyingKey,
    signature: &ed25519_dalek::Signature,
    message: &[u8],
) -> bool {
    public_key.verify(message, signature).is_ok()
}

/// Generate a fresh Ed25519 keypair and split the seed into M-of-N shares.
pub fn generate_threshold_keypair(
    m: u8,
    n: u8,
) -> Result<(VerifyingKey, Vec<Share>), String> {
    use rand::rngs::OsRng;
    let signing_key = SigningKey::generate(&mut OsRng);
    let verifying_key = signing_key.verifying_key();
    let shares = split_key(signing_key.as_bytes(), m, n)?;
    Ok((verifying_key, shares))
}

// ─────────────────────────────────────────────────────────────────────
// EphemeralCA — ephemeral Contract Agent with secure key zeroization
// ─────────────────────────────────────────────────────────────────────

/// An ephemeral Contract Agent with an Ed25519 keypair that lives only in
/// volatile memory. The signing key is wrapped in `Zeroizing<>` so it is
/// securely erased when dropped. Call `shred()` for explicit zeroization.
pub struct EphemeralCA {
    pub did: String,
    seed: Zeroizing<[u8; 32]>,
    pub verifying_key: VerifyingKey,
    pub capabilities: Vec<String>,
    pub delegation_vcard: Option<String>,
    shredded: bool,
}

impl EphemeralCA {
    /// Generate a fresh ephemeral keypair and derive a `did:key` DID.
    pub fn new(capabilities: Vec<String>) -> Self {
        use rand::rngs::OsRng;
        let signing_key = SigningKey::generate(&mut OsRng);
        let verifying_key = signing_key.verifying_key();
        let did = format!(
            "did:key:{}",
            base64_url_encode(&verifying_key.to_bytes())
        );
        EphemeralCA {
            did,
            seed: Zeroizing::new(signing_key.to_bytes()),
            verifying_key,
            capabilities,
            delegation_vcard: None,
            shredded: false,
        }
    }

    /// Reconstruct the SigningKey from the stored seed.
    fn signing_key(&self) -> Result<SigningKey, String> {
        if self.shredded {
            return Err("EphemeralCA has been shredded".to_string());
        }
        Ok(SigningKey::from_bytes(&self.seed))
    }

    /// Create a short-lived delegation VCard signed by the ephemeral key.
    pub fn issue_delegation(&mut self) -> Result<String, String> {
        if self.shredded {
            return Err("EphemeralCA has been shredded".to_string());
        }
        let signing_key = self.signing_key()?;
        let timestamp = chrono::Utc::now().to_rfc3339();
        let vcard_without_sig = format!(
            "vcard_token:\n  agent_did: {}\n  capabilities: {:?}\n  timestamp: {}\n  verifying_key: {}",
            self.did,
            self.capabilities,
            timestamp,
            hex::encode(self.verifying_key.to_bytes())
        );
        let signature = signing_key.sign(vcard_without_sig.as_bytes());
        let vcard = format!(
            "{}\n  signature: {}",
            vcard_without_sig,
            hex::encode(signature.to_bytes())
        );
        self.delegation_vcard = Some(vcard.clone());
        Ok(vcard)
    }

    /// Sign an arbitrary message with the ephemeral signing key.
    pub fn sign(&self, message: &[u8]) -> Result<ed25519_dalek::Signature, String> {
        let signing_key = self.signing_key()?;
        Ok(signing_key.sign(message))
    }

    /// Verify a signature against this CA's public key.
    pub fn verify(
        &self,
        signature: &ed25519_dalek::Signature,
        message: &[u8],
    ) -> bool {
        self.verifying_key.verify(message, signature).is_ok()
    }

    /// Explicitly zeroize the seed and clear all fields.
    pub fn shred(&mut self) {
        if self.shredded {
            return;
        }
        self.seed.zeroize();
        self.capabilities.clear();
        self.delegation_vcard = None;
        self.shredded = true;
    }

    /// Returns true if this CA has been shredded.
    pub fn is_shredded(&self) -> bool {
        self.shredded
    }
}

impl Drop for EphemeralCA {
    fn drop(&mut self) {
        self.shred();
    }
}

/// Verify a delegation VCard signed by an EphemeralCA.
pub fn verify_delegation(
    vcard_yaml: &str,
    ca_verifying_key: &VerifyingKey,
) -> bool {
    // The signed payload is the entire VCard YAML minus the signature line.
    let mut payload_lines = Vec::new();
    let mut signature_hex = String::new();
    for line in vcard_yaml.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("signature:") {
            signature_hex = rest.trim().to_string();
        } else {
            payload_lines.push(line);
        }
    }
    if signature_hex.is_empty() {
        return false;
    }
    let sig_bytes = match hex::decode(&signature_hex) {
        Ok(b) => b,
        Err(_) => return false,
    };
    let sig = match ed25519_dalek::Signature::from_slice(&sig_bytes) {
        Ok(s) => s,
        Err(_) => return false,
    };
    let payload = payload_lines.join("\n");
    ca_verifying_key.verify(payload.as_bytes(), &sig).is_ok()
}

fn base64_url_encode(bytes: &[u8]) -> String {
    // Simple base64url encoding without padding (for did:key).
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut result = String::new();
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
        result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
        result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
        result.push(ALPHABET[((n >> 6) & 63) as usize] as char);
        result.push(ALPHABET[(n & 63) as usize] as char);
        i += 3;
    }
    let rem = bytes.len() - i;
    if rem == 1 {
        let n = (bytes[i] as u32) << 16;
        result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
        result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
    } else if rem == 2 {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
        result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
        result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
        result.push(ALPHABET[((n >> 6) & 63) as usize] as char);
    }
    result
}

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

    #[test]
    fn test_3_of_5_threshold_signing_and_verification() {
        let (vk, shares) = generate_threshold_keypair(3, 5).unwrap();
        let message = b"threshold test message";
        let sig = threshold_sign(&shares[..3], message).unwrap();
        assert!(threshold_verify(&vk, &sig, message));
    }

    #[test]
    fn test_below_threshold_fails() {
        let (_vk, shares) = generate_threshold_keypair(3, 5).unwrap();
        let message = b"threshold test message";
        assert!(threshold_sign(&shares[..2], message).is_err());
    }

    #[test]
    fn test_corrupted_share_produces_invalid_signature() {
        let (vk, mut shares) = generate_threshold_keypair(3, 5).unwrap();
        shares[0].data[0] ^= 0xFF;
        let message = b"threshold test message";
        let sig = threshold_sign(&shares[..3], message).unwrap();
        assert!(!threshold_verify(&vk, &sig, message));
    }

    #[test]
    fn test_threshold_config_validation() {
        assert!(ThresholdConfig {
            m: 3,
            n: 5,
            guardian_dids: vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string(), "e".to_string()],
        }
        .validate()
        .is_ok());
        assert!(ThresholdConfig {
            m: 0,
            n: 5,
            guardian_dids: vec!["a".to_string(); 5],
        }
        .validate()
        .is_err());
        assert!(ThresholdConfig {
            m: 6,
            n: 5,
            guardian_dids: vec!["a".to_string(); 5],
        }
        .validate()
        .is_err());
    }

    #[test]
    fn test_ephemeral_ca_sign_and_verify() {
        let ca = EphemeralCA::new(vec!["execute".to_string()]);
        let message = b"test message from CA";
        let sig = ca.sign(message).unwrap();
        assert!(ca.verify(&sig, message));
        assert!(!ca.is_shredded());
    }

    #[test]
    fn test_ephemeral_ca_delegation() {
        let mut ca = EphemeralCA::new(vec!["execute".to_string(), "delegate".to_string()]);
        let vcard = ca.issue_delegation().unwrap();
        assert!(vcard.contains("vcard_token:"));
        assert!(vcard.contains(&ca.did));
        assert!(vcard.contains("signature:"));
        assert!(verify_delegation(&vcard, &ca.verifying_key));
    }

    #[test]
    fn test_ephemeral_ca_shred_blocks_signing() {
        let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
        ca.shred();
        assert!(ca.is_shredded());
        assert!(ca.sign(b"msg").is_err());
        assert!(ca.issue_delegation().is_err());
    }

    #[test]
    fn test_ephemeral_ca_drop_calls_shred() {
        let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
        let did = ca.did.clone();
        {
            let _ca2 = EphemeralCA::new(vec!["temp".to_string()]);
            // _ca2 is dropped here — shred() should be called
        }
        // ca should still be usable before explicit shred
        assert!(!ca.is_shredded());
        ca.shred();
        assert!(ca.is_shredded());
        // DID is still accessible (it's public info)
        assert!(!did.is_empty());
    }

    #[test]
    fn test_ephemeral_ca_did_format() {
        let ca = EphemeralCA::new(vec!["execute".to_string()]);
        assert!(ca.did.starts_with("did:key:"));
        assert!(ca.did.len() > "did:key:".len() + 10);
    }

    #[test]
    fn test_verify_delegation_rejects_tampered() {
        let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
        let mut vcard = ca.issue_delegation().unwrap();
        // Tamper with the agent_did field
        vcard = vcard.replace(&ca.did, "did:key:fake");
        assert!(!verify_delegation(&vcard, &ca.verifying_key));
    }
}