clm_rust_core/layer0/
hash_registry.rs1#[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
45pub const BLAKE3_HASH_PREFIX: &str = crate::layer0::vocabulary::HASH_PREFIX_BLAKE3;
49
50pub const SHA256_HASH_PREFIX: &str = crate::layer0::vocabulary::HASH_PREFIX_SHA256;
52
53pub const DEFAULT_HASH_PREFIX: &str = BLAKE3_HASH_PREFIX;
55
56pub const DEFAULT_COLLISION_THRESHOLD: u32 = 2;
58
59pub trait HashProvider: Send + Sync {
67 fn hash(&self, content: &[u8]) -> String;
69
70 fn prefix(&self) -> &'static str;
72
73 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
91pub 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
110pub 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#[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#[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
166pub 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
181pub struct Shake256Provider {
188 bits: usize,
189 prefix_str: &'static str,
190}
191
192impl Shake256Provider {
193 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
224pub 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 pub fn register(&mut self, provider: Box<dyn HashProvider>) {
244 let prefix = provider.prefix();
245 self.providers.push((prefix, provider));
246 }
247
248 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 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 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
283pub fn register_provider(provider: Box<dyn HashProvider>) {
285 let mut reg = global_registry().lock().unwrap();
286 reg.register(provider);
287}
288
289pub fn register_custom_provider(bits: usize) {
294 register_provider(Box::new(Shake256Provider::new(bits)));
295}
296
297pub 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
311pub fn next_stronger_algorithm(current: &str) -> &'static str {
316 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 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
331pub fn list_algorithms() -> Vec<&'static str> {
333 let reg = global_registry().lock().unwrap();
334 reg.algorithms()
335}
336
337#[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