clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reticulum Announce Codec for CLM Layer 3 Mesh.
//! Canonical Path: kernel/clm_rust_core/src/mesh/reticulum_codec.rs
//!
//! Provides zero-copy parsing and serialization of Reticulum Announce frames,
//! Ed25519 signature verification, and MCard capability manifest unpacking.

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ReticulumCodecError {
    #[error("Announce packet too short: expected at least {expected}, got {got}")]
    BufferTooShort { expected: usize, got: usize },

    #[error("Unsupported packet type: {0}")]
    UnsupportedPacketType(u8),

    #[error("Malformed app data length header or payload truncated")]
    PayloadTruncated,

    #[error("Invalid Ed25519 public key")]
    InvalidPublicKey,

    #[error("Invalid Ed25519 signature")]
    InvalidSignature,

    #[error("JSON deserialization error: {0}")]
    JsonError(#[from] serde_json::Error),
}

/// Parsed Reticulum announce frame components
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReticulumAnnounceData {
    pub destination_hash: [u8; 16],
    pub public_key: [u8; 32],
    pub app_data: Vec<u8>,
    pub signature: [u8; 64],
}

/// Structured PKC capability manifest within announce app-data
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PkcAnnouncePayload {
    pub did: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default)]
    pub namespaces: Vec<String>,
    #[serde(default)]
    pub timestamp: f64,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Verified and decoded peer record
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DecodedPkcPeer {
    pub destination_hex: String,
    pub identity_public_key_hex: String,
    pub payload: PkcAnnouncePayload,
    pub verified: bool,
}

/// Encodes an announce packet into a canonical binary frame.
/// Framing: [0x01 (1B)][dest (16B)][pubkey (32B)][appData_len (2B BE)][appData (NB)][sig (64B)]
pub fn encode_announce_packet(data: &ReticulumAnnounceData) -> Vec<u8> {
    let mut buf = Vec::with_capacity(1 + 16 + 32 + 2 + data.app_data.len() + 64);
    buf.push(0x01); // Announce packet type
    buf.extend_from_slice(&data.destination_hash);
    buf.extend_from_slice(&data.public_key);
    let app_data_len = data.app_data.len() as u16;
    buf.extend_from_slice(&app_data_len.to_be_bytes());
    buf.extend_from_slice(&data.app_data);
    buf.extend_from_slice(&data.signature);
    buf
}

/// Decodes a binary frame into Reticulum announce components.
pub fn decode_announce_packet(buffer: &[u8]) -> Result<ReticulumAnnounceData, ReticulumCodecError> {
    const MIN_LEN: usize = 1 + 16 + 32 + 2 + 64; // 115 bytes
    if buffer.len() < MIN_LEN {
        return Err(ReticulumCodecError::BufferTooShort {
            expected: MIN_LEN,
            got: buffer.len(),
        });
    }

    if buffer[0] != 0x01 {
        return Err(ReticulumCodecError::UnsupportedPacketType(buffer[0]));
    }

    let mut offset = 1;
    let mut destination_hash = [0u8; 16];
    destination_hash.copy_from_slice(&buffer[offset..offset + 16]);
    offset += 16;

    let mut public_key = [0u8; 32];
    public_key.copy_from_slice(&buffer[offset..offset + 32]);
    offset += 32;

    let app_data_len = u16::from_be_bytes([buffer[offset], buffer[offset + 1]]) as usize;
    offset += 2;

    if buffer.len() < offset + app_data_len + 64 {
        return Err(ReticulumCodecError::PayloadTruncated);
    }

    let app_data = buffer[offset..offset + app_data_len].to_vec();
    offset += app_data_len;

    let mut signature = [0u8; 64];
    signature.copy_from_slice(&buffer[offset..offset + 64]);

    Ok(ReticulumAnnounceData {
        destination_hash,
        public_key,
        app_data,
        signature,
    })
}

/// Signs announce components using an Ed25519 signing key.
/// Signed payload = destination_hash + public_key + app_data
pub fn sign_announce_data(
    destination_hash: &[u8; 16],
    public_key: &[u8; 32],
    app_data: &[u8],
    signing_key: &SigningKey,
) -> [u8; 64] {
    let mut payload = Vec::with_capacity(16 + 32 + app_data.len());
    payload.extend_from_slice(destination_hash);
    payload.extend_from_slice(public_key);
    payload.extend_from_slice(app_data);

    let signature = signing_key.sign(&payload);
    signature.to_bytes()
}

/// Verifies Ed25519 signature over destination_hash + public_key + app_data.
pub fn verify_announce_signature(data: &ReticulumAnnounceData) -> bool {
    let verifying_key = match VerifyingKey::from_bytes(&data.public_key) {
        Ok(k) => k,
        Err(_) => return false,
    };

    let signature = match Signature::from_slice(&data.signature) {
        Ok(s) => s,
        Err(_) => return false,
    };

    let mut payload = Vec::with_capacity(16 + 32 + data.app_data.len());
    payload.extend_from_slice(&data.destination_hash);
    payload.extend_from_slice(&data.public_key);
    payload.extend_from_slice(&data.app_data);

    verifying_key.verify(&payload, &signature).is_ok()
}

/// Parses and verifies an announce frame into a DecodedPkcPeer.
pub fn parse_and_verify_peer(buffer: &[u8]) -> Result<DecodedPkcPeer, ReticulumCodecError> {
    let announce = decode_announce_packet(buffer)?;
    let verified = verify_announce_signature(&announce);
    if !verified {
        return Err(ReticulumCodecError::InvalidSignature);
    }

    let payload: PkcAnnouncePayload = serde_json::from_slice(&announce.app_data)?;

    Ok(DecodedPkcPeer {
        destination_hex: hex::encode(announce.destination_hash),
        identity_public_key_hex: hex::encode(announce.public_key),
        payload,
        verified,
    })
}

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

    #[test]
    fn test_codec_roundtrip_and_signature_verification() {
        let mut csprng = OsRng;
        let signing_key = SigningKey::generate(&mut csprng);
        let verifying_key = signing_key.verifying_key();
        let pub_bytes = verifying_key.to_bytes();

        let dest_hash = [0x42u8; 16];
        let app_payload = PkcAnnouncePayload {
            did: "did:clm:peer1".into(),
            capabilities: vec!["mcard:text".into(), "satori:dialogue".into()],
            namespaces: vec!["clm:pkc/local".into()],
            timestamp: 1726500000.0,
            extra: serde_json::Map::new(),
        };
        let app_data = serde_json::to_vec(&app_payload).unwrap();

        let sig = sign_announce_data(&dest_hash, &pub_bytes, &app_data, &signing_key);

        let announce = ReticulumAnnounceData {
            destination_hash: dest_hash,
            public_key: pub_bytes,
            app_data: app_data.clone(),
            signature: sig,
        };

        let encoded = encode_announce_packet(&announce);
        assert_eq!(encoded[0], 0x01);

        let decoded = decode_announce_packet(&encoded).unwrap();
        assert_eq!(decoded.destination_hash, dest_hash);
        assert_eq!(decoded.public_key, pub_bytes);
        assert_eq!(decoded.app_data, app_data);
        assert_eq!(decoded.signature, sig);

        assert!(verify_announce_signature(&decoded));

        // Tamper test
        let mut tampered = encoded.clone();
        tampered[51] ^= 0xff; // Alter byte inside app_data
        let tampered_decoded = decode_announce_packet(&tampered).unwrap();
        assert!(!verify_announce_signature(&tampered_decoded));
    }
}