Skip to main content

clm_rust_core/layer0/
hash_config.rs

1#![allow(unused_imports)]
2use super::*;
3
4/// Configuration policy for hash algorithm selection and collision handling.
5///
6/// This struct governs:
7/// - Which algorithm is used for **new** content (`active_algorithm`)
8/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
9/// - The order of fallback algorithms if the active one is compromised
10///
11/// The config is stored in a global `OnceLock` and can be loaded from a
12/// configuration file or environment variable at startup.
13#[derive(Debug, Clone)]
14pub struct HashConfig {
15    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
16    pub active_algorithm: &'static str,
17    /// Number of collisions before triggering an upgrade.
18    pub collision_threshold: u32,
19    /// Ordered list of fallback algorithm prefixes.
20    /// If the active algorithm is compromised, the first available fallback
21    /// becomes the new active algorithm.
22    pub fallback_order: Vec<&'static str>,
23}
24
25impl Default for HashConfig {
26    fn default() -> Self {
27        Self {
28            active_algorithm: DEFAULT_HASH_PREFIX,
29            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
30            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
31        }
32    }
33}
34
35pub(super) fn normalize_prefix(value: &str) -> &'static str {
36    let normalized = value.trim().trim_end_matches(':').to_lowercase();
37    Box::leak(format!("{}:", normalized).into_boxed_str())
38}
39
40impl HashConfig {
41    /// Load hash configuration from environment variables.
42    ///
43    /// Checks in order:
44    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
45    ///    Example: `blake3:|2|blake3:,sha256:`
46    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
47    ///
48    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
49    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
50    pub fn from_env() -> Self {
51        let configured = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_HASH_CONFIG)
52            .ok()
53            .filter(|raw| !raw.trim().is_empty())
54            .map(|raw| Self::parse_config(&raw))
55            .or_else(|| {
56                crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_HASH_ALGO)
57                    .or_else(|_| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_HASH_ALGORITHM))
58                    .ok()
59                    .filter(|algo| !algo.trim().is_empty())
60                    .map(|algo| {
61                        let prefix = normalize_prefix(&algo);
62                        Self {
63                            active_algorithm: prefix,
64                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
65                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
66                        }
67                    })
68            });
69
70        let Some(config) = configured else {
71            return Self::default();
72        };
73        config
74    }
75
76    pub(super) fn parse_config(raw: &str) -> Self {
77        let parts: Vec<&str> = raw.splitn(3, '|').collect();
78        if parts.len() < 2 {
79            return Self::default();
80        }
81        let active = if parts[0].is_empty() {
82            DEFAULT_HASH_PREFIX
83        } else {
84            normalize_prefix(parts[0])
85        };
86        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
87        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
88            parts[2]
89                .split(',')
90                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
91                .collect()
92        } else {
93            vec![active]
94        };
95        Self {
96            active_algorithm: active,
97            collision_threshold: threshold,
98            fallback_order: fallbacks,
99        }
100    }
101}
102
103pub(super) fn global_config() -> &'static HashConfig {
104    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
105    CONFIG.get_or_init(HashConfig::from_env)
106}
107
108/// Get the current hash configuration.
109pub fn config() -> &'static HashConfig {
110    global_config()
111}
112
113// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────
114
115/// Extract the algorithm prefix from a stored hash string.
116///
117/// Returns `Some(prefix)` if the string contains a `:` separator,
118/// `None` if there is no prefix (assumed to be the default algorithm).
119pub fn extract_prefix(prefixed: &str) -> Option<&str> {
120    prefixed.find(':').map(|pos| &prefixed[..=pos])
121}
122
123/// Verify a stored hash against content by dispatching to the correct provider.
124///
125/// This function parses the algorithm prefix from `stored_hash`, looks up
126/// the corresponding provider in the registry, and checks whether the
127/// content matches.
128///
129/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
130/// or the provider is unknown.
131pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
132    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
133    let reg = global_registry().lock().unwrap();
134    let provider = reg.get(prefix).ok_or_else(|| {
135        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
136    })?;
137    let computed = provider.hash(content);
138    let stored_raw = strip_prefix(stored_hash);
139    if computed == stored_raw {
140        Ok(())
141    } else {
142        Err(format!(
143            "Hash mismatch: expected {}..., got {}...",
144            &stored_raw[..stored_raw.len().min(16)],
145            &computed[..computed.len().min(16)]
146        ))
147    }
148}
149
150// ── Collision detection (Step 5) ──────────────────────────────────────────
151
152/// Result of a collision check.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum CollisionCheckResult {
155    /// No collision — the hash is unique.
156    NoCollision,
157    /// Collision detected — the same hash already exists with different content.
158    Collision { hash: String, collision_count: u32 },
159    /// Threshold exceeded — the active algorithm should be upgraded.
160    ThresholdExceeded {
161        hash: String,
162        collision_count: u32,
163        recommended_algorithm: &'static str,
164    },
165}
166
167/// Check whether a hash collision has occurred and whether the threshold
168/// for algorithm upgrade has been exceeded.
169///
170/// Callers should invoke this *before* inserting a new card into the database.
171/// If `existing_content` is `Some` and differs from `new_content`, a collision
172/// is recorded. When the collision count for the active algorithm reaches
173/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
174/// with the recommended fallback algorithm.
175pub fn check_collision(
176    hash: &str,
177    new_content: &[u8],
178    existing_content: Option<&[u8]>,
179    collision_count: u32,
180) -> CollisionCheckResult {
181    match existing_content {
182        None => CollisionCheckResult::NoCollision,
183        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
184        Some(_) => {
185            let count = collision_count + 1;
186            let cfg = config();
187            if count >= cfg.collision_threshold {
188                // Find the first fallback that isn't the current active algorithm
189                let recommended = cfg
190                    .fallback_order
191                    .iter()
192                    .find(|&&algo| algo != cfg.active_algorithm)
193                    .copied()
194                    .unwrap_or(cfg.active_algorithm);
195                CollisionCheckResult::ThresholdExceeded {
196                    hash: hash.to_string(),
197                    collision_count: count,
198                    recommended_algorithm: recommended,
199                }
200            } else {
201                CollisionCheckResult::Collision {
202                    hash: hash.to_string(),
203                    collision_count: count,
204                }
205            }
206        }
207    }
208}
209
210// ── Convenience functions (delegate to the active provider) ──────────────
211
212/// Compute the raw hex digest of bytes using the active provider (no prefix).
213///
214/// This is the canonical "common function signature" shared with Python's
215/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
216pub fn raw_hash_bytes(content: &[u8]) -> String {
217    let reg = global_registry().lock().unwrap();
218    reg.active(config().active_algorithm).hash(content)
219}
220
221/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
222pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
223    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
224    let prefix = format!("{}:", normalized);
225    let reg = global_registry().lock().map_err(|e| e.to_string())?;
226    let provider = reg.get(&prefix).ok_or_else(|| {
227        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
228    })?;
229    Ok(provider.hash(content))
230}
231
232/// Compute the raw hex digest of a string using the active provider (no prefix).
233pub fn raw_hash_string(s: &str) -> String {
234    raw_hash_bytes(s.as_bytes())
235}
236
237/// Compute the raw digest as a 32-byte array using the active provider.
238///
239/// Used by Merkle tree and type lattice code that needs the raw bytes
240/// rather than a hex string.
241pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
242    let reg = global_registry().lock().unwrap();
243    reg.active(config().active_algorithm).hash_bytes(content)
244}
245
246/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
247pub fn prefixed_hash_bytes(content: &[u8]) -> String {
248    let reg = global_registry().lock().unwrap();
249    let provider = reg.active(config().active_algorithm);
250    format!("{}{}", provider.prefix(), provider.hash(content))
251}
252
253/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
254pub fn prefixed_hash_string(s: &str) -> String {
255    prefixed_hash_bytes(s.as_bytes())
256}
257
258/// Prepend the active algorithm prefix to an already-computed raw hex digest.
259pub fn prefixed(raw_hex: &str) -> String {
260    format!("{}{}", config().active_algorithm, raw_hex)
261}
262
263/// Strip a known algorithm prefix from a hash string.
264///
265/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
266/// the unprefixed hex is returned. Otherwise the input is returned as-is.
267pub fn strip_prefix(prefixed: &str) -> &str {
268    // Try the active algorithm prefix first
269    let active = config().active_algorithm;
270    if let Some(rest) = prefixed.strip_prefix(active) {
271        return rest;
272    }
273    // Try the default prefix
274    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
275        return rest;
276    }
277    // Generic fallback: strip any `<algo>:` prefix
278    if let Some(pos) = prefixed.find(':')
279        && pos + 1 < prefixed.len() {
280            return &prefixed[pos + 1..];
281        }
282    prefixed
283}
284
285/// Returns the default hash provider (currently `Blake3Provider`).
286///
287/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
288pub fn default_provider() -> impl HashProvider {
289    Blake3Provider
290}