clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Authenticated Noise Transport (`Noise_XX_25519_ChaChaPoly_BLAKE3`)
//! Canonical Path: kernel/clm_rust_core/src/mesh/noise.rs
//!
//! Implements:
//! 1. SovereignNodeIdentity with Ed25519 signing and Curve25519 (X25519) key agreement.
//! 2. Noise_XX 3-message mutual authentication handshake state machine.
//! 3. ChaCha20-Poly1305 AEAD symmetric framing with 2-byte big-endian length prefix.
//! 4. BLAKE3 hash mixing, HMAC-BLAKE3, and HKDF key derivation matching TypeScript core.
//! 5. Zero-leak buffer wiping on MAC verification failures (`INV-257-01`).
//! 6. Forward secrecy via ephemeral Curve25519 key agreements (`INV-257-02`).

use chacha20poly1305::{
    aead::{Aead, KeyInit, Payload},
    ChaCha20Poly1305, Key, Nonce,
};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::rngs::OsRng;
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519StaticSecret};
use zeroize::Zeroize;

pub const NOISE_PROTOCOL_NAME: &str = "Noise_XX_25519_ChaChaPoly_BLAKE3";
pub const NOISE_HASHLEN: usize = 32;
pub const NOISE_BLOCKLEN: usize = 64;
pub const NOISE_KEYLEN: usize = 32;
pub const NOISE_TAGLEN: usize = 16;
pub const NOISE_NONCELEN: usize = 12;
pub const NOISE_FRAME_HEADER_LEN: usize = 2;

// ── BLAKE3 Cryptographic Helpers ──────────────────────────────────────────

/// Compute 32-byte BLAKE3 hash.
pub fn blake3_digest(data: &[u8]) -> [u8; 32] {
    let hash = blake3::hash(data);
    *hash.as_bytes()
}

/// HMAC using BLAKE3 with 64-byte block size.
pub fn hmac_blake3(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut k = [0u8; NOISE_BLOCKLEN];
    if key.len() > NOISE_BLOCKLEN {
        let digest = blake3_digest(key);
        k[..32].copy_from_slice(&digest);
    } else {
        k[..key.len()].copy_from_slice(key);
    }

    let mut ipad = [0u8; NOISE_BLOCKLEN];
    let mut opad = [0u8; NOISE_BLOCKLEN];
    for i in 0..NOISE_BLOCKLEN {
        ipad[i] = k[i] ^ 0x36;
        opad[i] = k[i] ^ 0x5c;
    }

    let mut inner_input = Vec::with_capacity(NOISE_BLOCKLEN + data.len());
    inner_input.extend_from_slice(&ipad);
    inner_input.extend_from_slice(data);
    let inner_hash = blake3_digest(&inner_input);

    let mut outer_input = Vec::with_capacity(NOISE_BLOCKLEN + 32);
    outer_input.extend_from_slice(&opad);
    outer_input.extend_from_slice(&inner_hash);
    blake3_digest(&outer_input)
}

/// HKDF-2 using BLAKE3.
pub fn hkdf2(ck: &[u8; 32], ikm: &[u8]) -> ([u8; 32], [u8; 32]) {
    let prk = hmac_blake3(ck, ikm);
    let out1 = hmac_blake3(&prk, &[0x01]);
    let mut info2 = Vec::with_capacity(33);
    info2.extend_from_slice(&out1);
    info2.push(0x02);
    let out2 = hmac_blake3(&prk, &info2);
    (out1, out2)
}

/// HKDF-3 using BLAKE3.
pub fn hkdf3(ck: &[u8; 32], ikm: &[u8]) -> ([u8; 32], [u8; 32], [u8; 32]) {
    let prk = hmac_blake3(ck, ikm);
    let out1 = hmac_blake3(&prk, &[0x01]);
    let mut info2 = Vec::with_capacity(33);
    info2.extend_from_slice(&out1);
    info2.push(0x02);
    let out2 = hmac_blake3(&prk, &info2);
    let mut info3 = Vec::with_capacity(33);
    info3.extend_from_slice(&out2);
    info3.push(0x03);
    let out3 = hmac_blake3(&prk, &info3);
    (out1, out2, out3)
}

// ── Sovereign Node Identity ────────────────────────────────────────────────

#[derive(Clone)]
pub struct SovereignNodeIdentity {
    pub did: String,
    pub ed25519_public_key: [u8; 32],
    pub ed25519_private_key: [u8; 32],
    pub x25519_public_key: [u8; 32],
    pub x25519_private_key: [u8; 32],
    signing_key: SigningKey,
    x25519_secret: X25519StaticSecret,
}

impl SovereignNodeIdentity {
    /// Generate a random sovereign node identity.
    pub fn generate() -> Self {
        let mut seed = [0u8; 32];
        let mut rng = OsRng;
        rand::RngCore::fill_bytes(&mut rng, &mut seed);
        Self::from_seed(&seed)
    }

    /// Deterministically derive identity from a 32-byte seed.
    pub fn from_seed(seed: &[u8; 32]) -> Self {
        let mut ed_input = Vec::with_capacity(44);
        ed_input.extend_from_slice(seed);
        ed_input.extend_from_slice(b"ed25519:seed");
        let ed_seed = blake3_digest(&ed_input);

        let mut x_input = Vec::with_capacity(42);
        x_input.extend_from_slice(seed);
        x_input.extend_from_slice(b"x25519:seed");
        let x_seed = blake3_digest(&x_input);

        let signing_key = SigningKey::from_bytes(&ed_seed);
        let verifying_key = signing_key.verifying_key();
        let ed_pub = verifying_key.to_bytes();

        let x_secret = X25519StaticSecret::from(x_seed);
        let x_pub = X25519PublicKey::from(&x_secret).to_bytes();

        let did = format!("did:pkc:{}", bs58::encode(&ed_pub).into_string());

        Self {
            did,
            ed25519_public_key: ed_pub,
            ed25519_private_key: ed_seed,
            x25519_public_key: x_pub,
            x25519_private_key: x_seed,
            signing_key,
            x25519_secret: x_secret,
        }
    }

    /// Sign data using Ed25519.
    pub fn sign(&self, message: &[u8]) -> [u8; 64] {
        let sig: Signature = self.signing_key.sign(message);
        sig.to_bytes()
    }

    /// Derives the Ed25519 public key bytes from a did:pkc:* identifier.
    pub fn did_to_public_key(did: &str) -> Result<[u8; 32], String> {
        if !did.starts_with("did:pkc:") {
            return Err(format!("Invalid DID prefix for '{}'", did));
        }
        let rest = &did["did:pkc:".len()..];
        let bytes = if rest.starts_with('z') {
            let decoded = bs58::decode(&rest[1..]).into_vec().map_err(|e| e.to_string())?;
            if decoded.len() >= 2 && decoded[0] == 0xed && decoded[1] == 0x01 {
                decoded[2..].to_vec()
            } else {
                decoded
            }
        } else {
            bs58::decode(rest).into_vec().map_err(|e| e.to_string())?
        };

        if bytes.len() != 32 {
            return Err(format!("Invalid public key length from DID: {}", bytes.len()));
        }
        let mut arr = [0u8; 32];
        arr.copy_from_slice(&bytes);
        Ok(arr)
    }

    /// Derives the did:pkc:* identifier from an Ed25519 public key.
    pub fn public_key_to_did(pubkey: &[u8; 32]) -> String {
        format!("did:pkc:{}", bs58::encode(pubkey).into_string())
    }


    /// Verify signature on data using Ed25519.
    pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
        Self::verify_signature(&self.ed25519_public_key, message, signature)
    }

    /// Static signature verification.
    pub fn verify_signature(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
        if let Ok(vk) = VerifyingKey::from_bytes(public_key) {
            let sig = Signature::from_bytes(signature);
            vk.verify(message, &sig).is_ok()
        } else {
            false
        }
    }

    /// Diffie-Hellman against peer X25519 public key.
    pub fn diffie_hellman(&self, peer_x25519_public: &[u8; 32]) -> [u8; 32] {
        let peer_pub = X25519PublicKey::from(*peer_x25519_public);
        *self.x25519_secret.diffie_hellman(&peer_pub).as_bytes()
    }
}

// ── Noise CipherState ──────────────────────────────────────────────────────

#[derive(Clone, Default)]
pub struct NoiseCipherState {
    pub key: Option<[u8; 32]>,
    pub nonce: u64,
}

impl NoiseCipherState {
    pub fn new() -> Self {
        Self { key: None, nonce: 0 }
    }

    pub fn initialize_key(&mut self, key: Option<[u8; 32]>) {
        self.key = key;
        self.nonce = 0;
    }

    pub fn has_key(&self) -> bool {
        self.key.is_some()
    }

    pub fn encrypt_with_ad(&mut self, ad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
        let key_bytes = match self.key {
            Some(k) => k,
            None => return Ok(plaintext.to_vec()),
        };

        let key = Key::from(key_bytes);
        let cipher = ChaCha20Poly1305::new(&key);

        let mut nonce_bytes = [0u8; NOISE_NONCELEN];
        nonce_bytes[4..12].copy_from_slice(&self.nonce.to_be_bytes());
        let nonce = Nonce::from(nonce_bytes);

        let payload = Payload { msg: plaintext, aad: ad };
        let ciphertext = cipher
            .encrypt(&nonce, payload)
            .map_err(|e| format!("ChaCha20Poly1305 encryption failed: {}", e))?;

        self.nonce += 1;
        Ok(ciphertext)
    }

    pub fn decrypt_with_ad(&mut self, ad: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, String> {
        let key_bytes = match self.key {
            Some(k) => k,
            None => return Ok(ciphertext.to_vec()),
        };

        if ciphertext.len() < NOISE_TAGLEN {
            self.zeroize();
            return Err(format!("Ciphertext too short: {} < {}", ciphertext.len(), NOISE_TAGLEN));
        }

        let key = Key::from(key_bytes);
        let cipher = ChaCha20Poly1305::new(&key);

        let mut nonce_bytes = [0u8; NOISE_NONCELEN];
        nonce_bytes[4..12].copy_from_slice(&self.nonce.to_be_bytes());
        let nonce = Nonce::from(nonce_bytes);

        let payload = Payload { msg: ciphertext, aad: ad };
        let plaintext = cipher
            .decrypt(&nonce, payload)
            .map_err(|e| {
                self.zeroize();
                format!("MAC verification failed: {} (INV-257-01)", e)
            })?;

        self.nonce += 1;
        Ok(plaintext)
    }

    pub fn zeroize(&mut self) {
        if let Some(ref mut k) = self.key {
            k.zeroize();
        }
        self.key = None;
        self.nonce = 0;
    }
}

// ── Noise SymmetricState ───────────────────────────────────────────────────

#[derive(Clone)]
pub struct NoiseSymmetricState {
    pub cipher: NoiseCipherState,
    pub ck: [u8; 32],
    pub h: [u8; 32],
}

impl NoiseSymmetricState {
    pub fn new(protocol_name: &str) -> Self {
        let mut h = [0u8; 32];
        let name_bytes = protocol_name.as_bytes();
        if name_bytes.len() <= 32 {
            h[..name_bytes.len()].copy_from_slice(name_bytes);
        } else {
            h = blake3_digest(name_bytes);
        }
        let ck = h;
        Self {
            cipher: NoiseCipherState::new(),
            ck,
            h,
        }
    }

    pub fn mix_key(&mut self, ikm: &[u8]) {
        let (next_ck, temp_k) = hkdf2(&self.ck, ikm);
        self.ck = next_ck;
        self.cipher.initialize_key(Some(temp_k));
    }

    pub fn mix_hash(&mut self, data: &[u8]) {
        let mut input = Vec::with_capacity(self.h.len() + data.len());
        input.extend_from_slice(&self.h);
        input.extend_from_slice(data);
        self.h = blake3_digest(&input);
    }

    pub fn mix_key_and_hash(&mut self, ikm: &[u8]) {
        let (next_ck, temp_h, temp_k) = hkdf3(&self.ck, ikm);
        self.ck = next_ck;
        self.mix_hash(&temp_h);
        self.cipher.initialize_key(Some(temp_k));
    }

    pub fn encrypt_and_hash(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, String> {
        let ciphertext = self.cipher.encrypt_with_ad(&self.h, plaintext)?;
        self.mix_hash(&ciphertext);
        Ok(ciphertext)
    }

    pub fn decrypt_and_hash(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, String> {
        let plaintext = self.cipher.decrypt_with_ad(&self.h, ciphertext)?;
        self.mix_hash(ciphertext);
        Ok(plaintext)
    }

    pub fn split(&mut self) -> (NoiseCipherState, NoiseCipherState) {
        let (k1, k2) = hkdf2(&self.ck, &[]);
        let mut c1 = NoiseCipherState::new();
        c1.initialize_key(Some(k1));
        let mut c2 = NoiseCipherState::new();
        c2.initialize_key(Some(k2));
        (c1, c2)
    }

    pub fn zeroize(&mut self) {
        self.ck.zeroize();
        self.h.zeroize();
        self.cipher.zeroize();
    }
}

// ── Noise Handshake State Machine ──────────────────────────────────────────


#[path = "noise_handshake.rs"]
mod noise_handshake;
#[allow(unused_imports)]
pub use noise_handshake::*;
#[path = "noise_transport.rs"]
mod noise_transport;
#[allow(unused_imports)]
pub use noise_transport::*;
#[cfg(test)]
#[path = "noise_tests.rs"]
mod tests;