Skip to main content

clm_rust_core/
hash.rs

1//! Central content-hash module — upgradable hash function abstraction (INV-02).
2//!
3//! All content hashing in CLM must route through this module. The current default
4//! algorithm is SHA-256, but the `HashProvider` trait allows any conforming
5//! implementation to be substituted without changing call sites. Stored hash
6//! values carry an algorithm prefix (e.g. `sha256:<hex>`) so multiple algorithms
7//! can coexist in the same namespace.
8//!
9//! # Architecture
10//!
11//! ```text
12//! ┌─────────────────────────────────────────────────────────┐
13//! │                    HashConfig                            │
14//! │  active_algorithm: "sha256:"                             │
15//! │  collision_threshold: 2                                  │
16//! │  fallback_order: ["sha256:", "sha3-256:"]               │
17//! └──────────────────────┬──────────────────────────────────┘
18//!                        │
19//!                        ▼
20//! ┌─────────────────────────────────────────────────────────┐
21//! │               ProviderRegistry                           │
22//! │  "sha256:"    → Sha256Provider                           │
23//! │  "sha3-256:"  → Sha3_256Provider (future)               │
24//! └──────────────────────┬──────────────────────────────────┘
25//!                        │
26//!         ┌──────────────┼──────────────┐
27//!         ▼              ▼              ▼
28//!    raw_hash_*    prefixed_hash_*   verify_hash
29//!    (compute)     (compute+prefix)  (dispatch by prefix)
30//! ```
31//!
32//! Common function signature (matches Python `clm_hash_string`):
33//!   `fn(content: &[u8]) -> String`  →  raw hex digest, no prefix
34//!
35//! To get a prefixed hash (for storage), use `prefixed_hash_bytes` / `prefixed_hash_string`.
36
37use md5::Md5;
38use sha1::Sha1;
39use sha2::{Digest, Sha256, Sha512};
40use sha3::{Shake256, digest::{ExtendableOutput, XofReader}};
41use std::sync::{Mutex, OnceLock};
42
43// ── Constants ─────────────────────────────────────────────────────────────
44
45/// Algorithm prefix for BLAKE3 hash provider (INV-02).
46pub const BLAKE3_HASH_PREFIX: &str = "blake3:";
47
48/// Algorithm prefix for legacy SHA-256 hash provider.
49pub const SHA256_HASH_PREFIX: &str = "sha256:";
50
51/// Algorithm prefix for the default hash provider (BLAKE3 is default).
52pub const DEFAULT_HASH_PREFIX: &str = BLAKE3_HASH_PREFIX;
53
54/// Default collision threshold before triggering an algorithm upgrade.
55pub const DEFAULT_COLLISION_THRESHOLD: u32 = 2;
56
57// ── HashProvider trait ────────────────────────────────────────────────────
58
59/// Trait for pluggable content-hash algorithms.
60///
61/// Any type implementing this trait can serve as CLM's content hash function.
62/// The trait is intentionally minimal: `hash` returns the raw hex digest,
63/// and `prefix` returns the algorithm tag used in prefixed storage format.
64pub trait HashProvider: Send + Sync {
65    /// Compute the raw hex digest of `content`.
66    fn hash(&self, content: &[u8]) -> String;
67
68    /// Algorithm prefix (e.g. `"blake3:"`, `"sha256:"`).
69    fn prefix(&self) -> &'static str;
70
71    /// Compute the raw digest as a fixed-size byte array (for Merkle trees, etc.).
72    /// Default implementation parses the hex digest; providers may override
73    /// for efficiency.
74    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
75        let hex = self.hash(content);
76        let mut out = [0u8; 32];
77        let bytes = hex.as_bytes();
78        for i in 0..32 {
79            out[i] = u8::from_str_radix(
80                std::str::from_utf8(&bytes[i * 2..i * 2 + 2]).unwrap_or("00"),
81                16,
82            )
83            .unwrap_or(0);
84        }
85        out
86    }
87}
88
89// ── Built-in providers ────────────────────────────────────────────────────
90
91/// Default BLAKE3 hash provider (INV-02: high-performance, tree-hashable 256-bit).
92pub struct Blake3Provider;
93
94impl HashProvider for Blake3Provider {
95    fn hash(&self, content: &[u8]) -> String {
96        blake3::hash(content).to_hex().to_string()
97    }
98
99    fn prefix(&self) -> &'static str {
100        BLAKE3_HASH_PREFIX
101    }
102
103    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
104        *blake3::hash(content).as_bytes()
105    }
106}
107
108/// Legacy SHA-256 hash provider.
109pub struct Sha256Provider;
110
111impl HashProvider for Sha256Provider {
112    fn hash(&self, content: &[u8]) -> String {
113        let mut hasher = Sha256::new();
114        hasher.update(content);
115        format!("{:x}", hasher.finalize())
116    }
117
118    fn prefix(&self) -> &'static str {
119        SHA256_HASH_PREFIX
120    }
121
122    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
123        let mut hasher = Sha256::new();
124        hasher.update(content);
125        hasher.finalize().into()
126    }
127}
128
129/// MD5 hash provider (weakest in the hierarchy, for legacy compatibility).
130pub struct Md5Provider;
131
132impl HashProvider for Md5Provider {
133    fn hash(&self, content: &[u8]) -> String {
134        let mut hasher = Md5::new();
135        hasher.update(content);
136        format!("{:x}", hasher.finalize())
137    }
138
139    fn prefix(&self) -> &'static str {
140        "md5:"
141    }
142}
143
144/// SHA-1 hash provider (legacy, for migration path compatibility).
145pub struct Sha1Provider;
146
147impl HashProvider for Sha1Provider {
148    fn hash(&self, content: &[u8]) -> String {
149        let mut hasher = Sha1::new();
150        hasher.update(content);
151        format!("{:x}", hasher.finalize())
152    }
153
154    fn prefix(&self) -> &'static str {
155        "sha1:"
156    }
157}
158
159/// SHA-512 hash provider (stronger than SHA-256).
160pub struct Sha512Provider;
161
162impl HashProvider for Sha512Provider {
163    fn hash(&self, content: &[u8]) -> String {
164        let mut hasher = Sha512::new();
165        hasher.update(content);
166        format!("{:x}", hasher.finalize())
167    }
168
169    fn prefix(&self) -> &'static str {
170        "sha512:"
171    }
172}
173
174/// Keccak SHAKE-256 provider with configurable output bit-length (`custom-N`).
175///
176/// Uses the SHAKE-256 extendable-output function (XOF) to produce a digest
177/// of `N` bits. The prefix is `custom-N:` (e.g. `custom-1024:`).
178/// This provides future-proofing: if `custom-N` is exhausted, upgrade to
179/// `custom-2N` by registering a new provider with doubled bit-length.
180pub struct Shake256Provider {
181    bits: usize,
182    prefix_str: &'static str,
183}
184
185impl Shake256Provider {
186    /// Create a new `custom-N` provider for the given bit-length.
187    ///
188    /// `bits` must be > 0. The byte-length of the digest is `(bits + 7) / 8`.
189    pub fn new(bits: usize) -> Self {
190        let prefix_str: &'static str = Box::leak(
191            format!("custom-{}:", bits).into_boxed_str(),
192        );
193        Self { bits, prefix_str }
194    }
195
196    fn byte_len(&self) -> usize {
197        self.bits.div_ceil(8)
198    }
199}
200
201impl HashProvider for Shake256Provider {
202    fn hash(&self, content: &[u8]) -> String {
203        let mut hasher = Shake256::default();
204        sha3::digest::Update::update(&mut hasher, content);
205        let mut reader = hasher.finalize_xof();
206        let byte_len = self.byte_len();
207        let mut buf = vec![0u8; byte_len];
208        reader.read(&mut buf);
209        hex::encode(&buf)
210    }
211
212    fn prefix(&self) -> &'static str {
213        self.prefix_str
214    }
215}
216
217// ── Provider registry (Step 2) ────────────────────────────────────────────
218
219/// Registry of available hash providers, keyed by algorithm prefix.
220///
221/// The registry allows multiple algorithms to coexist. New providers can be
222/// registered at startup or at runtime. The active algorithm (used for new
223/// content) is determined by `HashConfig.active_algorithm`.
224pub struct ProviderRegistry {
225    providers: Vec<(&'static str, Box<dyn HashProvider>)>,
226}
227
228impl ProviderRegistry {
229    fn new() -> Self {
230        Self {
231            providers: Vec::new(),
232        }
233    }
234
235    /// Register a new hash provider under its algorithm prefix.
236    pub fn register(&mut self, provider: Box<dyn HashProvider>) {
237        let prefix = provider.prefix();
238        self.providers.push((prefix, provider));
239    }
240
241    /// Look up a provider by algorithm prefix.
242    pub fn get(&self, prefix: &str) -> Option<&dyn HashProvider> {
243        self.providers
244            .iter()
245            .find(|(p, _)| *p == prefix)
246            .map(|(_, provider)| provider.as_ref())
247    }
248
249    /// Get the active provider (determined by `HashConfig`).
250    pub fn active(&self, active_prefix: &str) -> &dyn HashProvider {
251        self.get(active_prefix)
252            .unwrap_or_else(|| self.get(DEFAULT_HASH_PREFIX).expect("default provider must be registered"))
253    }
254
255    /// List all registered algorithm prefixes.
256    pub fn algorithms(&self) -> Vec<&'static str> {
257        self.providers.iter().map(|(p, _)| *p).collect()
258    }
259}
260
261pub fn global_registry() -> &'static Mutex<ProviderRegistry> {
262    static REGISTRY: OnceLock<Mutex<ProviderRegistry>> = OnceLock::new();
263    REGISTRY.get_or_init(|| {
264        let mut reg = ProviderRegistry::new();
265        reg.register(Box::new(Blake3Provider));
266        reg.register(Box::new(Sha256Provider));
267        reg.register(Box::new(Md5Provider));
268        reg.register(Box::new(Sha1Provider));
269        reg.register(Box::new(Sha512Provider));
270        Mutex::new(reg)
271    })
272}
273
274/// Register an additional hash provider at runtime.
275pub fn register_provider(provider: Box<dyn HashProvider>) {
276    let mut reg = global_registry().lock().unwrap();
277    reg.register(provider);
278}
279
280/// Register a `custom-N` (SHAKE-256) provider with the given bit-length.
281///
282/// Convenience wrapper around `register_provider` for the `custom-N` family.
283/// Example: `register_custom_provider(1024)` registers a `custom-1024:` provider.
284pub fn register_custom_provider(bits: usize) {
285    register_provider(Box::new(Shake256Provider::new(bits)));
286}
287
288/// Algorithm strength hierarchy (weakest → strongest).
289///
290/// Used by the collision remediation system to determine the next algorithm
291/// when the current one exceeds its collision threshold. For `custom-N`,
292/// the upgrade path is `custom-2N` (recursive doubling).
293pub const STRENGTH_HIERARCHY: &[&str] = &[
294    "md5:",
295    "sha1:",
296    "sha256:",
297    "blake3:",
298    "sha512:",
299    "custom-1024:",
300];
301
302/// Recommend the next stronger algorithm in the hierarchy.
303///
304/// If the current algorithm is `custom-N`, returns `custom-2N` (recursive doubling).
305/// If the current algorithm is not in the hierarchy, returns `blake3:` as a safe default.
306pub fn next_stronger_algorithm(current: &str) -> &'static str {
307    // Handle custom-N recursive doubling
308    if let Some(rest) = current.strip_prefix("custom-")
309        && let Some(num_str) = rest.strip_suffix(':')
310            && let Ok(n) = num_str.parse::<usize>() {
311                let doubled = n * 2;
312                return Box::leak(format!("custom-{}:", doubled).into_boxed_str());
313            }
314    // Find current in the standard hierarchy
315    let pos = STRENGTH_HIERARCHY.iter().position(|&algo| algo == current);
316    match pos {
317        Some(i) if i + 1 < STRENGTH_HIERARCHY.len() => STRENGTH_HIERARCHY[i + 1],
318        _ => DEFAULT_HASH_PREFIX,
319    }
320}
321
322/// List all registered algorithm prefixes.
323pub fn list_algorithms() -> Vec<&'static str> {
324    let reg = global_registry().lock().unwrap();
325    reg.algorithms()
326}
327
328// ── Hash configuration policy (Step 4) ────────────────────────────────────
329
330
331#[path = "hash_config.rs"]
332mod hash_config;
333#[allow(unused_imports)]
334pub use hash_config::*;
335#[cfg(test)]
336#[path = "hash_tests.rs"]
337mod tests;
338