1#![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 = std::env::var("CLM_HASH_CONFIG")
52 .ok()
53 .filter(|raw| !raw.trim().is_empty())
54 .map(|raw| Self::parse_config(&raw))
55 .or_else(|| {
56 std::env::var("CLM_HASH_ALGO")
57 .or_else(|_| std::env::var("MCARD_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}
291
292#[cfg(feature = "native")]
305pub fn content_equivalent(
306 conn: &rusqlite::Connection,
307 hash_a: &str,
308 hash_b: &str,
309) -> Result<bool, String> {
310 if hash_a == hash_b {
311 return Ok(true);
312 }
313 let content_a = lookup_content(conn, hash_a);
314 let content_b = lookup_content(conn, hash_b);
315 match (content_a, content_b) {
316 (Some(a), Some(b)) => Ok(a == b),
317 _ => Ok(false),
318 }
319}
320
321#[cfg(feature = "native")]
327pub(super) fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
328 let raw = strip_prefix(reference);
329 let mut candidates = vec![reference];
330 if raw != reference {
331 candidates.push(raw);
332 }
333 for candidate in candidates {
334 if let Ok(content) = conn.query_row(
335 "SELECT content FROM card WHERE hash = ?",
336 rusqlite::params![candidate],
337 |row| row.get::<_, Vec<u8>>(0),
338 ) {
339 return Some(content);
340 }
341 }
342 None
343}
344
345#[cfg(feature = "native")]
362pub fn migrate_handle_hash(
363 conn: &mut rusqlite::Connection,
364 handle: &str,
365 target_algo: &str,
366) -> Result<String, String> {
367 {
369 let reg = global_registry().lock().unwrap();
370 if reg.get(target_algo).is_none() {
371 return Err(format!(
372 "Unsupported target algorithm: '{}' (registered: {:?})",
373 target_algo,
374 reg.algorithms()
375 ));
376 }
377 }
378
379 let current_hash: String = conn
381 .query_row(
382 "SELECT current_hash FROM handle_registry WHERE handle = ?",
383 rusqlite::params![handle],
384 |row| row.get(0),
385 )
386 .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
387
388 let content: Vec<u8> = lookup_content(conn, ¤t_hash)
390 .ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;
391
392 let now_utc = chrono::Utc::now().to_rfc3339();
394 let record = crate::layer0::mcard_record::MCardRecord::create_at(
395 &content,
396 Some(target_algo),
397 Some(&now_utc),
398 "UTC",
399 )?;
400 if !matches!(
401 crate::layer0::mcard_record::verify_record(&record),
402 crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
403 ) {
404 return Err("hash migration produced an invalid self-verifying record".to_string());
405 }
406 let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);
407
408 let max_attempts = 3;
411 let mut last_err = String::new();
412 for attempt in 0..max_attempts {
413 let tx = match conn.transaction() {
414 Ok(tx) => tx,
415 Err(e) => {
416 last_err = e.to_string();
417 std::thread::sleep(std::time::Duration::from_millis(200));
418 continue;
419 }
420 };
421 let result = (|| {
422 tx.execute(
423 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
424 rusqlite::params![&record.hash, &record.content, &record.g_time],
425 )
426 .map_err(|e| e.to_string())?;
427 tx.execute(
428 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
429 rusqlite::params![handle, ¤t_hash, &now_utc],
430 )
431 .map_err(|e| e.to_string())?;
432 tx.execute(
433 "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
434 rusqlite::params![&new_hash, &now_utc, handle],
435 )
436 .map_err(|e| e.to_string())?;
437 tx.commit().map_err(|e| e.to_string())
438 })();
439
440 match result {
441 Ok(()) => return Ok(new_hash),
442 Err(e) => {
443 last_err = e;
444 if attempt + 1 < max_attempts {
445 std::thread::sleep(std::time::Duration::from_millis(200));
446 }
447 }
448 }
449 }
450
451 Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
452}
453