clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Cryptographic Hasher ambient service provider (CRD-03).
//!
//! Normative Reference:
//!   clm/docs/spec/60-verification/crd_coeffect_taxonomy.yaml (service: crypto_hasher)

use sha2::{Digest, Sha256};

pub trait CryptoHasherService: Send + Sync {
    fn hash(&self, data: &[u8], algo: Option<&str>) -> String;
    fn verify(&self, data: &[u8], expected: &str) -> bool;
}

#[derive(Default)]
pub struct SovereignCryptoHasher;

impl SovereignCryptoHasher {
    pub fn new() -> Self {
        Self
    }
}

impl CryptoHasherService for SovereignCryptoHasher {
    fn hash(&self, data: &[u8], algo: Option<&str>) -> String {
        let algo_choice = algo.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3).to_lowercase();
        if algo_choice == crate::layer0::vocabulary::HASH_ALGORITHM_SHA256 {
            let mut hasher = Sha256::new();
            hasher.update(data);
            hex::encode(hasher.finalize())
        } else {
            blake3::hash(data).to_hex().to_string()
        }
    }

    fn verify(&self, data: &[u8], expected: &str) -> bool {
        let clean = expected.trim().to_lowercase();
        let (algo, target) = if clean.contains(':') {
            let parts: Vec<&str> = clean.splitn(2, ':').collect();
            (Some(parts[0]), parts[1])
        } else if clean.len() == 64 {
            (Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3), clean.as_str())
        } else {
            (Some(crate::layer0::vocabulary::HASH_ALGORITHM_SHA256), clean.as_str())
        };

        let computed = self.hash(data, algo).to_lowercase();
        computed == target
    }
}