clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

/// Configuration policy for hash algorithm selection and collision handling.
///
/// This struct governs:
/// - Which algorithm is used for **new** content (`active_algorithm`)
/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
/// - The order of fallback algorithms if the active one is compromised
///
/// The config is stored in a global `OnceLock` and can be loaded from a
/// configuration file or environment variable at startup.
#[derive(Debug, Clone)]
pub struct HashConfig {
    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
    pub active_algorithm: &'static str,
    /// Number of collisions before triggering an upgrade.
    pub collision_threshold: u32,
    /// Ordered list of fallback algorithm prefixes.
    /// If the active algorithm is compromised, the first available fallback
    /// becomes the new active algorithm.
    pub fallback_order: Vec<&'static str>,
}

impl Default for HashConfig {
    fn default() -> Self {
        Self {
            active_algorithm: DEFAULT_HASH_PREFIX,
            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
        }
    }
}

pub(super) fn normalize_prefix(value: &str) -> &'static str {
    let normalized = value.trim().trim_end_matches(':').to_lowercase();
    Box::leak(format!("{}:", normalized).into_boxed_str())
}

impl HashConfig {
    /// Load hash configuration from environment variables.
    ///
    /// Checks in order:
    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
    ///    Example: `blake3:|2|blake3:,sha256:`
    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
    ///
    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
    pub fn from_env() -> Self {
        let configured = std::env::var("CLM_HASH_CONFIG")
            .ok()
            .filter(|raw| !raw.trim().is_empty())
            .map(|raw| Self::parse_config(&raw))
            .or_else(|| {
                std::env::var("CLM_HASH_ALGO")
                    .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
                    .ok()
                    .filter(|algo| !algo.trim().is_empty())
                    .map(|algo| {
                        let prefix = normalize_prefix(&algo);
                        Self {
                            active_algorithm: prefix,
                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
                        }
                    })
            });

        let Some(config) = configured else {
            return Self::default();
        };
        config
    }

    pub(super) fn parse_config(raw: &str) -> Self {
        let parts: Vec<&str> = raw.splitn(3, '|').collect();
        if parts.len() < 2 {
            return Self::default();
        }
        let active = if parts[0].is_empty() {
            DEFAULT_HASH_PREFIX
        } else {
            normalize_prefix(parts[0])
        };
        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
            parts[2]
                .split(',')
                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
                .collect()
        } else {
            vec![active]
        };
        Self {
            active_algorithm: active,
            collision_threshold: threshold,
            fallback_order: fallbacks,
        }
    }
}

pub(super) fn global_config() -> &'static HashConfig {
    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
    CONFIG.get_or_init(HashConfig::from_env)
}

/// Get the current hash configuration.
pub fn config() -> &'static HashConfig {
    global_config()
}

// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────

/// Extract the algorithm prefix from a stored hash string.
///
/// Returns `Some(prefix)` if the string contains a `:` separator,
/// `None` if there is no prefix (assumed to be the default algorithm).
pub fn extract_prefix(prefixed: &str) -> Option<&str> {
    prefixed.find(':').map(|pos| &prefixed[..=pos])
}

/// Verify a stored hash against content by dispatching to the correct provider.
///
/// This function parses the algorithm prefix from `stored_hash`, looks up
/// the corresponding provider in the registry, and checks whether the
/// content matches.
///
/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
/// or the provider is unknown.
pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
    let reg = global_registry().lock().unwrap();
    let provider = reg.get(prefix).ok_or_else(|| {
        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
    })?;
    let computed = provider.hash(content);
    let stored_raw = strip_prefix(stored_hash);
    if computed == stored_raw {
        Ok(())
    } else {
        Err(format!(
            "Hash mismatch: expected {}..., got {}...",
            &stored_raw[..stored_raw.len().min(16)],
            &computed[..computed.len().min(16)]
        ))
    }
}

// ── Collision detection (Step 5) ──────────────────────────────────────────

/// Result of a collision check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollisionCheckResult {
    /// No collision — the hash is unique.
    NoCollision,
    /// Collision detected — the same hash already exists with different content.
    Collision { hash: String, collision_count: u32 },
    /// Threshold exceeded — the active algorithm should be upgraded.
    ThresholdExceeded {
        hash: String,
        collision_count: u32,
        recommended_algorithm: &'static str,
    },
}

/// Check whether a hash collision has occurred and whether the threshold
/// for algorithm upgrade has been exceeded.
///
/// Callers should invoke this *before* inserting a new card into the database.
/// If `existing_content` is `Some` and differs from `new_content`, a collision
/// is recorded. When the collision count for the active algorithm reaches
/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
/// with the recommended fallback algorithm.
pub fn check_collision(
    hash: &str,
    new_content: &[u8],
    existing_content: Option<&[u8]>,
    collision_count: u32,
) -> CollisionCheckResult {
    match existing_content {
        None => CollisionCheckResult::NoCollision,
        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
        Some(_) => {
            let count = collision_count + 1;
            let cfg = config();
            if count >= cfg.collision_threshold {
                // Find the first fallback that isn't the current active algorithm
                let recommended = cfg
                    .fallback_order
                    .iter()
                    .find(|&&algo| algo != cfg.active_algorithm)
                    .copied()
                    .unwrap_or(cfg.active_algorithm);
                CollisionCheckResult::ThresholdExceeded {
                    hash: hash.to_string(),
                    collision_count: count,
                    recommended_algorithm: recommended,
                }
            } else {
                CollisionCheckResult::Collision {
                    hash: hash.to_string(),
                    collision_count: count,
                }
            }
        }
    }
}

// ── Convenience functions (delegate to the active provider) ──────────────

/// Compute the raw hex digest of bytes using the active provider (no prefix).
///
/// This is the canonical "common function signature" shared with Python's
/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
pub fn raw_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash(content)
}

/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
    let prefix = format!("{}:", normalized);
    let reg = global_registry().lock().map_err(|e| e.to_string())?;
    let provider = reg.get(&prefix).ok_or_else(|| {
        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
    })?;
    Ok(provider.hash(content))
}

/// Compute the raw hex digest of a string using the active provider (no prefix).
pub fn raw_hash_string(s: &str) -> String {
    raw_hash_bytes(s.as_bytes())
}

/// Compute the raw digest as a 32-byte array using the active provider.
///
/// Used by Merkle tree and type lattice code that needs the raw bytes
/// rather than a hex string.
pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash_bytes(content)
}

/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    let provider = reg.active(config().active_algorithm);
    format!("{}{}", provider.prefix(), provider.hash(content))
}

/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_string(s: &str) -> String {
    prefixed_hash_bytes(s.as_bytes())
}

/// Prepend the active algorithm prefix to an already-computed raw hex digest.
pub fn prefixed(raw_hex: &str) -> String {
    format!("{}{}", config().active_algorithm, raw_hex)
}

/// Strip a known algorithm prefix from a hash string.
///
/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
/// the unprefixed hex is returned. Otherwise the input is returned as-is.
pub fn strip_prefix(prefixed: &str) -> &str {
    // Try the active algorithm prefix first
    let active = config().active_algorithm;
    if let Some(rest) = prefixed.strip_prefix(active) {
        return rest;
    }
    // Try the default prefix
    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
        return rest;
    }
    // Generic fallback: strip any `<algo>:` prefix
    if let Some(pos) = prefixed.find(':')
        && pos + 1 < prefixed.len() {
            return &prefixed[pos + 1..];
        }
    prefixed
}

/// Returns the default hash provider (currently `Blake3Provider`).
///
/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
pub fn default_provider() -> impl HashProvider {
    Blake3Provider
}