clm-kernel 0.0.21

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Central content-hash module — upgradable hash function abstraction (INV-02).
//!
//! All content hashing in CLM must route through this module. The current default
//! algorithm is SHA-256, but the `HashProvider` trait allows any conforming
//! implementation to be substituted without changing call sites. Stored hash
//! values carry an algorithm prefix (e.g. `sha256:<hex>`) so multiple algorithms
//! can coexist in the same namespace.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────┐
//! │                    HashConfig                            │
//! │  active_algorithm: "sha256:"                             │
//! │  collision_threshold: 2                                  │
//! │  fallback_order: ["sha256:", "sha3-256:"]               │
//! └──────────────────────┬──────────────────────────────────┘
//!                        │
//!                        ▼
//! ┌─────────────────────────────────────────────────────────┐
//! │               ProviderRegistry                           │
//! │  "sha256:"    → Sha256Provider                           │
//! │  "sha3-256:"  → Sha3_256Provider (future)               │
//! └──────────────────────┬──────────────────────────────────┘
//!                        │
//!         ┌──────────────┼──────────────┐
//!         ▼              ▼              ▼
//!    raw_hash_*    prefixed_hash_*   verify_hash
//!    (compute)     (compute+prefix)  (dispatch by prefix)
//! ```
//!
//! Common function signature (matches Python `clm_hash_string`):
//!   `fn(content: &[u8]) -> String`  →  raw hex digest, no prefix
//!
//! To get a prefixed hash (for storage), use `prefixed_hash_bytes` / `prefixed_hash_string`.

#[cfg(feature = "native")]
use md5::Md5;
#[cfg(feature = "native")]
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
use sha3::{Shake256, digest::{ExtendableOutput, XofReader}};
use std::sync::{Mutex, OnceLock};

// ── Constants ─────────────────────────────────────────────────────────────

/// Algorithm prefix for BLAKE3 hash provider (INV-02).
pub const BLAKE3_HASH_PREFIX: &str = crate::layer0::vocabulary::HASH_PREFIX_BLAKE3;

/// Algorithm prefix for legacy SHA-256 hash provider.
pub const SHA256_HASH_PREFIX: &str = crate::layer0::vocabulary::HASH_PREFIX_SHA256;

/// Algorithm prefix for the default hash provider (BLAKE3 is default).
pub const DEFAULT_HASH_PREFIX: &str = BLAKE3_HASH_PREFIX;

/// Default collision threshold before triggering an algorithm upgrade.
pub const DEFAULT_COLLISION_THRESHOLD: u32 = 2;

// ── HashProvider trait ────────────────────────────────────────────────────

/// Trait for pluggable content-hash algorithms.
///
/// Any type implementing this trait can serve as CLM's content hash function.
/// The trait is intentionally minimal: `hash` returns the raw hex digest,
/// and `prefix` returns the algorithm tag used in prefixed storage format.
pub trait HashProvider: Send + Sync {
    /// Compute the raw hex digest of `content`.
    fn hash(&self, content: &[u8]) -> String;

    /// Algorithm prefix (e.g. `"blake3:"`, `"sha256:"`).
    fn prefix(&self) -> &'static str;

    /// Compute the raw digest as a fixed-size byte array (for Merkle trees, etc.).
    /// Default implementation parses the hex digest; providers may override
    /// for efficiency.
    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        let hex = self.hash(content);
        let mut out = [0u8; 32];
        let bytes = hex.as_bytes();
        for i in 0..32 {
            out[i] = u8::from_str_radix(
                std::str::from_utf8(&bytes[i * 2..i * 2 + 2]).unwrap_or("00"),
                16,
            )
            .unwrap_or(0);
        }
        out
    }
}

// ── Built-in providers ────────────────────────────────────────────────────

/// Default BLAKE3 hash provider (INV-02: high-performance, tree-hashable 256-bit).
pub struct Blake3Provider;

impl HashProvider for Blake3Provider {
    fn hash(&self, content: &[u8]) -> String {
        blake3::hash(content).to_hex().to_string()
    }

    fn prefix(&self) -> &'static str {
        BLAKE3_HASH_PREFIX
    }

    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        *blake3::hash(content).as_bytes()
    }
}

/// Legacy SHA-256 hash provider.
pub struct Sha256Provider;

impl HashProvider for Sha256Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha256::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        SHA256_HASH_PREFIX
    }

    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(content);
        hasher.finalize().into()
    }
}

/// MD5 hash provider (weakest in the hierarchy, for legacy compatibility).
#[cfg(feature = "native")]
pub struct Md5Provider;

#[cfg(feature = "native")]
impl HashProvider for Md5Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Md5::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "md5:"
    }
}

/// SHA-1 hash provider (legacy, for migration path compatibility).
#[cfg(feature = "native")]
pub struct Sha1Provider;

#[cfg(feature = "native")]
impl HashProvider for Sha1Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha1::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "sha1:"
    }
}


/// SHA-512 hash provider (stronger than SHA-256).
pub struct Sha512Provider;

impl HashProvider for Sha512Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha512::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "sha512:"
    }
}

/// Keccak SHAKE-256 provider with configurable output bit-length (`custom-N`).
///
/// Uses the SHAKE-256 extendable-output function (XOF) to produce a digest
/// of `N` bits. The prefix is `custom-N:` (e.g. `custom-1024:`).
/// This provides future-proofing: if `custom-N` is exhausted, upgrade to
/// `custom-2N` by registering a new provider with doubled bit-length.
pub struct Shake256Provider {
    bits: usize,
    prefix_str: &'static str,
}

impl Shake256Provider {
    /// Create a new `custom-N` provider for the given bit-length.
    ///
    /// `bits` must be > 0. The byte-length of the digest is `(bits + 7) / 8`.
    pub fn new(bits: usize) -> Self {
        let prefix_str: &'static str = Box::leak(
            format!("custom-{}:", bits).into_boxed_str(),
        );
        Self { bits, prefix_str }
    }

    fn byte_len(&self) -> usize {
        self.bits.div_ceil(8)
    }
}

impl HashProvider for Shake256Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Shake256::default();
        sha3::digest::Update::update(&mut hasher, content);
        let mut reader = hasher.finalize_xof();
        let byte_len = self.byte_len();
        let mut buf = vec![0u8; byte_len];
        reader.read(&mut buf);
        hex::encode(&buf)
    }

    fn prefix(&self) -> &'static str {
        self.prefix_str
    }
}

// ── Provider registry (Step 2) ────────────────────────────────────────────

/// Registry of available hash providers, keyed by algorithm prefix.
///
/// The registry allows multiple algorithms to coexist. New providers can be
/// registered at startup or at runtime. The active algorithm (used for new
/// content) is determined by `HashConfig.active_algorithm`.
pub struct ProviderRegistry {
    providers: Vec<(&'static str, Box<dyn HashProvider>)>,
}

impl ProviderRegistry {
    fn new() -> Self {
        Self {
            providers: Vec::new(),
        }
    }

    /// Register a new hash provider under its algorithm prefix.
    pub fn register(&mut self, provider: Box<dyn HashProvider>) {
        let prefix = provider.prefix();
        self.providers.push((prefix, provider));
    }

    /// Look up a provider by algorithm prefix.
    pub fn get(&self, prefix: &str) -> Option<&dyn HashProvider> {
        self.providers
            .iter()
            .find(|(p, _)| *p == prefix)
            .map(|(_, provider)| provider.as_ref())
    }

    /// Get the active provider (determined by `HashConfig`).
    pub fn active(&self, active_prefix: &str) -> &dyn HashProvider {
        self.get(active_prefix)
            .unwrap_or_else(|| self.get(DEFAULT_HASH_PREFIX).expect("default provider must be registered"))
    }

    /// List all registered algorithm prefixes.
    pub fn algorithms(&self) -> Vec<&'static str> {
        self.providers.iter().map(|(p, _)| *p).collect()
    }
}

pub fn global_registry() -> &'static Mutex<ProviderRegistry> {
    static REGISTRY: OnceLock<Mutex<ProviderRegistry>> = OnceLock::new();
    REGISTRY.get_or_init(|| {
        let mut reg = ProviderRegistry::new();
        reg.register(Box::new(Blake3Provider));
        reg.register(Box::new(Sha256Provider));
        #[cfg(feature = "native")]
        reg.register(Box::new(Md5Provider));
        #[cfg(feature = "native")]
        reg.register(Box::new(Sha1Provider));
        reg.register(Box::new(Sha512Provider));
        Mutex::new(reg)
    })
}

/// Register an additional hash provider at runtime.
pub fn register_provider(provider: Box<dyn HashProvider>) {
    let mut reg = global_registry().lock().unwrap();
    reg.register(provider);
}

/// Register a `custom-N` (SHAKE-256) provider with the given bit-length.
///
/// Convenience wrapper around `register_provider` for the `custom-N` family.
/// Example: `register_custom_provider(1024)` registers a `custom-1024:` provider.
pub fn register_custom_provider(bits: usize) {
    register_provider(Box::new(Shake256Provider::new(bits)));
}

/// Algorithm strength hierarchy (weakest → strongest).
///
/// Used by the collision remediation system to determine the next algorithm
/// when the current one exceeds its collision threshold. For `custom-N`,
/// the upgrade path is `custom-2N` (recursive doubling).
pub const STRENGTH_HIERARCHY: &[&str] = &[
    "md5:",
    "sha1:",
    crate::layer0::vocabulary::HASH_PREFIX_SHA256,
    crate::layer0::vocabulary::HASH_PREFIX_BLAKE3,
    "sha512:",
    "custom-1024:",
];

/// Recommend the next stronger algorithm in the hierarchy.
///
/// If the current algorithm is `custom-N`, returns `custom-2N` (recursive doubling).
/// If the current algorithm is not in the hierarchy, returns `blake3:` as a safe default.
pub fn next_stronger_algorithm(current: &str) -> &'static str {
    // Handle custom-N recursive doubling
    if let Some(rest) = current.strip_prefix("custom-")
        && let Some(num_str) = rest.strip_suffix(':')
            && let Ok(n) = num_str.parse::<usize>() {
                let doubled = n * 2;
                return Box::leak(format!("custom-{}:", doubled).into_boxed_str());
            }
    // Find current in the standard hierarchy
    let pos = STRENGTH_HIERARCHY.iter().position(|&algo| algo == current);
    match pos {
        Some(i) if i + 1 < STRENGTH_HIERARCHY.len() => STRENGTH_HIERARCHY[i + 1],
        _ => DEFAULT_HASH_PREFIX,
    }
}

/// List all registered algorithm prefixes.
pub fn list_algorithms() -> Vec<&'static str> {
    let reg = global_registry().lock().unwrap();
    reg.algorithms()
}

// ── Hash configuration policy (Step 4) ────────────────────────────────────


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