clm-kernel 0.0.20

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reticulum Sovereign Identity Subsystem for CLM Layer 3 Mesh.
//! Canonical Path: kernel/clm_rust_core/src/mesh/reticulum_identity.rs
//!
//! Provides deterministic derivation of 16-byte Reticulum destination hashes
//! from AgentDid (did:key:z6Mk... and generic DIDs) ensuring polyglot parity (INV-L3-RET-355-01).

use sha2::{Digest, Sha256};

/// Extracts raw 32-byte Ed25519 public key bytes from a did:key string.
/// Format: did:key:z6Mk...
pub fn extract_raw_pubkey_from_did(did: &str) -> [u8; 32] {
    if let Some(b58_str) = did.strip_prefix("did:key:z")
        && let Ok(decoded) = bs58::decode(b58_str).into_vec() {
            // Multicodec 0xed, 0x01 prefix (2 bytes)
            if decoded.len() >= 34 && decoded[0] == 0xed && decoded[1] == 0x01 {
                let mut out = [0u8; 32];
                out.copy_from_slice(&decoded[2..34]);
                return out;
            } else if decoded.len() == 32 {
                let mut out = [0u8; 32];
                out.copy_from_slice(&decoded);
                return out;
            }
        }

    let mut hasher = Sha256::new();
    hasher.update(did.as_bytes());
    let res = hasher.finalize();
    let mut out = [0u8; 32];
    out.copy_from_slice(&res);
    out
}

/// Deterministically derives a 16-byte Reticulum destination hash from an
/// AgentDid string or raw public key bytes according to INV-L3-RET-355-01.
pub fn derive_destination_hash(
    did_or_material: &[u8],
    app_name: &str,
    aspects: &[&str],
) -> [u8; 16] {
    let full_name = if aspects.is_empty() {
        app_name.to_string()
    } else {
        format!("{}.{}", app_name, aspects.join("."))
    };

    let mut name_hasher = Sha256::new();
    name_hasher.update(full_name.as_bytes());
    let name_hash_full = name_hasher.finalize();
    let name_hash = &name_hash_full[..10]; // 80-bit name hash

    let raw_key = if let Ok(s) = std::str::from_utf8(did_or_material) {
        if s.starts_with("did:") {
            extract_raw_pubkey_from_did(s)
        } else if did_or_material.len() == 32 {
            let mut arr = [0u8; 32];
            arr.copy_from_slice(did_or_material);
            arr
        } else {
            let mut hasher = Sha256::new();
            hasher.update(did_or_material);
            let res = hasher.finalize();
            let mut arr = [0u8; 32];
            arr.copy_from_slice(&res);
            arr
        }
    } else if did_or_material.len() == 32 {
        let mut arr = [0u8; 32];
        arr.copy_from_slice(did_or_material);
        arr
    } else {
        let mut hasher = Sha256::new();
        hasher.update(did_or_material);
        let res = hasher.finalize();
        let mut arr = [0u8; 32];
        arr.copy_from_slice(&res);
        arr
    };

    let mut id_hasher = Sha256::new();
    id_hasher.update(raw_key);
    let id_hash_full = id_hasher.finalize();
    let id_hash = &id_hash_full[..16]; // 128-bit identity hash

    let mut addr_hasher = Sha256::new();
    addr_hasher.update(name_hash);
    addr_hasher.update(id_hash);
    let final_hash = addr_hasher.finalize();

    let mut out = [0u8; 16];
    out.copy_from_slice(&final_hash[..16]);
    out
}

/// Returns 32-character lowercase hex string of the derived destination hash.
pub fn derive_destination_hex(
    did_or_material: &[u8],
    app_name: &str,
    aspects: &[&str],
) -> String {
    let hash = derive_destination_hash(did_or_material, app_name, aspects);
    hex::encode(hash)
}

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

    #[test]
    fn test_destination_derivation_consistency() {
        let did = "did:key:z6Mku7Gk6gY7bV1bXzJ5k6q1Y8K9v0X4";
        let h1 = derive_destination_hash(did.as_bytes(), "clm", &["pkc", "node"]);
        let h2 = derive_destination_hash(did.as_bytes(), "clm", &["pkc", "node"]);
        assert_eq!(h1, h2);
        assert_eq!(derive_destination_hex(did.as_bytes(), "clm", &["pkc", "node"]), hex::encode(h1));
    }
}