clm_rust_core/layer0/
hash_config.rs1#![allow(unused_imports)]
2use super::*;
3
4#[derive(Debug, Clone)]
14pub struct HashConfig {
15 pub active_algorithm: &'static str,
17 pub collision_threshold: u32,
19 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 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
108pub fn config() -> &'static HashConfig {
110 global_config()
111}
112
113pub fn extract_prefix(prefixed: &str) -> Option<&str> {
120 prefixed.find(':').map(|pos| &prefixed[..=pos])
121}
122
123pub 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#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum CollisionCheckResult {
155 NoCollision,
157 Collision { hash: String, collision_count: u32 },
159 ThresholdExceeded {
161 hash: String,
162 collision_count: u32,
163 recommended_algorithm: &'static str,
164 },
165}
166
167pub 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 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
210pub fn raw_hash_bytes(content: &[u8]) -> String {
217 let reg = global_registry().lock().unwrap();
218 reg.active(config().active_algorithm).hash(content)
219}
220
221pub 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
232pub fn raw_hash_string(s: &str) -> String {
234 raw_hash_bytes(s.as_bytes())
235}
236
237pub 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
246pub 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
253pub fn prefixed_hash_string(s: &str) -> String {
255 prefixed_hash_bytes(s.as_bytes())
256}
257
258pub fn prefixed(raw_hex: &str) -> String {
260 format!("{}{}", config().active_algorithm, raw_hex)
261}
262
263pub fn strip_prefix(prefixed: &str) -> &str {
268 let active = config().active_algorithm;
270 if let Some(rest) = prefixed.strip_prefix(active) {
271 return rest;
272 }
273 if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
275 return rest;
276 }
277 if let Some(pos) = prefixed.find(':')
279 && pos + 1 < prefixed.len() {
280 return &prefixed[pos + 1..];
281 }
282 prefixed
283}
284
285pub fn default_provider() -> impl HashProvider {
289 Blake3Provider
290}