Skip to main content

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