clm-kernel 0.0.3

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 0: Stateless Kenotic Cryptographic Hashing
//! Canonical Path: kernel/clm_rust_core/src/layer0/hash.rs

use sha2::{Digest, Sha256};

pub const BLAKE3_PREFIX: &str = "blake3:";
pub const SHA256_PREFIX: &str = "sha256:";

/// Compute raw BLAKE3 64-character lowercase hex digest over arbitrary bytes.
pub fn compute_blake3(bytes: &[u8]) -> String {
    let hash = blake3::hash(bytes);
    hash.to_hex().to_string()
}

/// Compute raw SHA-256 64-character lowercase hex digest over arbitrary bytes.
pub fn compute_sha256(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

/// Compute prefixed hash using default algorithm (BLAKE3).
pub fn prefixed_hash(bytes: &[u8]) -> String {
    format!("{}{}", BLAKE3_PREFIX, compute_blake3(bytes))
}

/// Verify that an arbitrary byte payload matches the expected hash.
/// Supports prefixed ("blake3:<hex>", "sha256:<hex>") or unprefixed 64-char hex strings (assumed BLAKE3).
pub fn verify_hash(bytes: &[u8], expected_hash: &str) -> bool {
    let expected = expected_hash.trim();
    if let Some(stripped) = expected.strip_prefix(BLAKE3_PREFIX) {
        compute_blake3(bytes).eq_ignore_ascii_case(stripped)
    } else if let Some(stripped) = expected.strip_prefix(SHA256_PREFIX) {
        compute_sha256(bytes).eq_ignore_ascii_case(stripped)
    } else if expected.len() == 64 {
        // Default to BLAKE3, but accept SHA-256 fallback if it matches
        compute_blake3(bytes).eq_ignore_ascii_case(expected)
            || compute_sha256(bytes).eq_ignore_ascii_case(expected)
    } else {
        false
    }
}