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/// Configuration policy for hash algorithm selection and collision handling.
331///
332/// This struct governs:
333/// - Which algorithm is used for **new** content (`active_algorithm`)
334/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
335/// - The order of fallback algorithms if the active one is compromised
336///
337/// The config is stored in a global `OnceLock` and can be loaded from a
338/// configuration file or environment variable at startup.
339#[derive(Debug, Clone)]
340pub struct HashConfig {
341    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
342    pub active_algorithm: &'static str,
343    /// Number of collisions before triggering an upgrade.
344    pub collision_threshold: u32,
345    /// Ordered list of fallback algorithm prefixes.
346    /// If the active algorithm is compromised, the first available fallback
347    /// becomes the new active algorithm.
348    pub fallback_order: Vec<&'static str>,
349}
350
351impl Default for HashConfig {
352    fn default() -> Self {
353        Self {
354            active_algorithm: DEFAULT_HASH_PREFIX,
355            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
356            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
357        }
358    }
359}
360
361fn normalize_prefix(value: &str) -> &'static str {
362    let normalized = value.trim().trim_end_matches(':').to_lowercase();
363    Box::leak(format!("{}:", normalized).into_boxed_str())
364}
365
366impl HashConfig {
367    /// Load hash configuration from environment variables.
368    ///
369    /// Checks in order:
370    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
371    ///    Example: `blake3:|2|blake3:,sha256:`
372    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
373    ///
374    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
375    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
376    pub fn from_env() -> Self {
377        let configured = std::env::var("CLM_HASH_CONFIG")
378            .ok()
379            .filter(|raw| !raw.trim().is_empty())
380            .map(|raw| Self::parse_config(&raw))
381            .or_else(|| {
382                std::env::var("CLM_HASH_ALGO")
383                    .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
384                    .ok()
385                    .filter(|algo| !algo.trim().is_empty())
386                    .map(|algo| {
387                        let prefix = normalize_prefix(&algo);
388                        Self {
389                            active_algorithm: prefix,
390                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
391                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
392                        }
393                    })
394            });
395
396        let Some(config) = configured else {
397            return Self::default();
398        };
399        config
400    }
401
402    fn parse_config(raw: &str) -> Self {
403        let parts: Vec<&str> = raw.splitn(3, '|').collect();
404        if parts.len() < 2 {
405            return Self::default();
406        }
407        let active = if parts[0].is_empty() {
408            DEFAULT_HASH_PREFIX
409        } else {
410            normalize_prefix(parts[0])
411        };
412        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
413        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
414            parts[2]
415                .split(',')
416                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
417                .collect()
418        } else {
419            vec![active]
420        };
421        Self {
422            active_algorithm: active,
423            collision_threshold: threshold,
424            fallback_order: fallbacks,
425        }
426    }
427}
428
429fn global_config() -> &'static HashConfig {
430    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
431    CONFIG.get_or_init(HashConfig::from_env)
432}
433
434/// Get the current hash configuration.
435pub fn config() -> &'static HashConfig {
436    global_config()
437}
438
439// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────
440
441/// Extract the algorithm prefix from a stored hash string.
442///
443/// Returns `Some(prefix)` if the string contains a `:` separator,
444/// `None` if there is no prefix (assumed to be the default algorithm).
445pub fn extract_prefix(prefixed: &str) -> Option<&str> {
446    prefixed.find(':').map(|pos| &prefixed[..=pos])
447}
448
449/// Verify a stored hash against content by dispatching to the correct provider.
450///
451/// This function parses the algorithm prefix from `stored_hash`, looks up
452/// the corresponding provider in the registry, and checks whether the
453/// content matches.
454///
455/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
456/// or the provider is unknown.
457pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
458    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
459    let reg = global_registry().lock().unwrap();
460    let provider = reg.get(prefix).ok_or_else(|| {
461        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
462    })?;
463    let computed = provider.hash(content);
464    let stored_raw = strip_prefix(stored_hash);
465    if computed == stored_raw {
466        Ok(())
467    } else {
468        Err(format!(
469            "Hash mismatch: expected {}..., got {}...",
470            &stored_raw[..stored_raw.len().min(16)],
471            &computed[..computed.len().min(16)]
472        ))
473    }
474}
475
476// ── Collision detection (Step 5) ──────────────────────────────────────────
477
478/// Result of a collision check.
479#[derive(Debug, Clone, PartialEq, Eq)]
480pub enum CollisionCheckResult {
481    /// No collision — the hash is unique.
482    NoCollision,
483    /// Collision detected — the same hash already exists with different content.
484    Collision { hash: String, collision_count: u32 },
485    /// Threshold exceeded — the active algorithm should be upgraded.
486    ThresholdExceeded {
487        hash: String,
488        collision_count: u32,
489        recommended_algorithm: &'static str,
490    },
491}
492
493/// Check whether a hash collision has occurred and whether the threshold
494/// for algorithm upgrade has been exceeded.
495///
496/// Callers should invoke this *before* inserting a new card into the database.
497/// If `existing_content` is `Some` and differs from `new_content`, a collision
498/// is recorded. When the collision count for the active algorithm reaches
499/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
500/// with the recommended fallback algorithm.
501pub fn check_collision(
502    hash: &str,
503    new_content: &[u8],
504    existing_content: Option<&[u8]>,
505    collision_count: u32,
506) -> CollisionCheckResult {
507    match existing_content {
508        None => CollisionCheckResult::NoCollision,
509        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
510        Some(_) => {
511            let count = collision_count + 1;
512            let cfg = config();
513            if count >= cfg.collision_threshold {
514                // Find the first fallback that isn't the current active algorithm
515                let recommended = cfg
516                    .fallback_order
517                    .iter()
518                    .find(|&&algo| algo != cfg.active_algorithm)
519                    .copied()
520                    .unwrap_or(cfg.active_algorithm);
521                CollisionCheckResult::ThresholdExceeded {
522                    hash: hash.to_string(),
523                    collision_count: count,
524                    recommended_algorithm: recommended,
525                }
526            } else {
527                CollisionCheckResult::Collision {
528                    hash: hash.to_string(),
529                    collision_count: count,
530                }
531            }
532        }
533    }
534}
535
536// ── Convenience functions (delegate to the active provider) ──────────────
537
538/// Compute the raw hex digest of bytes using the active provider (no prefix).
539///
540/// This is the canonical "common function signature" shared with Python's
541/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
542pub fn raw_hash_bytes(content: &[u8]) -> String {
543    let reg = global_registry().lock().unwrap();
544    reg.active(config().active_algorithm).hash(content)
545}
546
547/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
548pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
549    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
550    let prefix = format!("{}:", normalized);
551    let reg = global_registry().lock().map_err(|e| e.to_string())?;
552    let provider = reg.get(&prefix).ok_or_else(|| {
553        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
554    })?;
555    Ok(provider.hash(content))
556}
557
558/// Compute the raw hex digest of a string using the active provider (no prefix).
559pub fn raw_hash_string(s: &str) -> String {
560    raw_hash_bytes(s.as_bytes())
561}
562
563/// Compute the raw digest as a 32-byte array using the active provider.
564///
565/// Used by Merkle tree and type lattice code that needs the raw bytes
566/// rather than a hex string.
567pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
568    let reg = global_registry().lock().unwrap();
569    reg.active(config().active_algorithm).hash_bytes(content)
570}
571
572/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
573pub fn prefixed_hash_bytes(content: &[u8]) -> String {
574    let reg = global_registry().lock().unwrap();
575    let provider = reg.active(config().active_algorithm);
576    format!("{}{}", provider.prefix(), provider.hash(content))
577}
578
579/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
580pub fn prefixed_hash_string(s: &str) -> String {
581    prefixed_hash_bytes(s.as_bytes())
582}
583
584/// Prepend the active algorithm prefix to an already-computed raw hex digest.
585pub fn prefixed(raw_hex: &str) -> String {
586    format!("{}{}", config().active_algorithm, raw_hex)
587}
588
589/// Strip a known algorithm prefix from a hash string.
590///
591/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
592/// the unprefixed hex is returned. Otherwise the input is returned as-is.
593pub fn strip_prefix(prefixed: &str) -> &str {
594    // Try the active algorithm prefix first
595    let active = config().active_algorithm;
596    if let Some(rest) = prefixed.strip_prefix(active) {
597        return rest;
598    }
599    // Try the default prefix
600    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
601        return rest;
602    }
603    // Generic fallback: strip any `<algo>:` prefix
604    if let Some(pos) = prefixed.find(':')
605        && pos + 1 < prefixed.len() {
606            return &prefixed[pos + 1..];
607        }
608    prefixed
609}
610
611/// Returns the default hash provider (currently `Blake3Provider`).
612///
613/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
614pub fn default_provider() -> impl HashProvider {
615    Blake3Provider
616}
617
618// ── Content-equivalence operator (Gap 2) ──────────────────────────────────
619
620/// Check whether two hashes point to the same content in the CAS.
621///
622/// This is the Rust equivalent of the shell `clm_content_equivalent` operator.
623/// Two hashes generated by different algorithms (e.g. `sha256:abc` and
624/// `sha512:def`) will never match as strings, but they may point to the same
625/// underlying content. This function resolves both hashes to their stored
626/// content and compares the raw bytes.
627///
628/// Returns `Ok(true)` if both hashes exist and point to identical content,
629/// `Ok(false)` if they differ or one is not found, `Err` on DB error.
630#[cfg(feature = "native")]
631pub fn content_equivalent(
632    conn: &rusqlite::Connection,
633    hash_a: &str,
634    hash_b: &str,
635) -> Result<bool, String> {
636    if hash_a == hash_b {
637        return Ok(true);
638    }
639    let content_a = lookup_content(conn, hash_a);
640    let content_b = lookup_content(conn, hash_b);
641    match (content_a, content_b) {
642        (Some(a), Some(b)) => Ok(a == b),
643        _ => Ok(false),
644    }
645}
646
647/// Resolve a stored row by reference, accepting either the bare digest or a qualified form.
648///
649/// The digest column holds bare hex (DEC-12); references that leave a row are qualified. A
650/// lookup therefore tries the reference as given, then its unprefixed form, so both a legacy
651/// prefixed row and a canonical bare row resolve.
652#[cfg(feature = "native")]
653fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
654    let raw = strip_prefix(reference);
655    let mut candidates = vec![reference];
656    if raw != reference {
657        candidates.push(raw);
658    }
659    for candidate in candidates {
660        if let Ok(content) = conn.query_row(
661            "SELECT content FROM card WHERE hash = ?",
662            rusqlite::params![candidate],
663            |row| row.get::<_, Vec<u8>>(0),
664        ) {
665            return Some(content);
666        }
667    }
668    None
669}
670
671// ── Handle migration lifecycle (Gap 3) ────────────────────────────────────
672
673/// Migrate a handle to use a different hash algorithm.
674///
675/// This is the Rust equivalent of the shell `clm_migrate_handle_hash` operator.
676/// It resolves the handle to its current hash, retrieves the content from the
677/// CAS, computes a new hash under the target algorithm, and transactionally
678/// inserts the new card, records handle history, and updates the handle pointer.
679///
680/// # Arguments
681/// * `conn` - SQLite connection to the content_memory database.
682/// * `handle` - The handle name to migrate (e.g. `"test:migration_handle"`).
683/// * `target_algo` - Target algorithm prefix (e.g. `"sha256:"`, `"custom-1024:"`).
684///   Must be a registered provider.
685///
686/// Returns `Ok(new_hash)` on success, `Err(message)` on failure.
687#[cfg(feature = "native")]
688pub fn migrate_handle_hash(
689    conn: &mut rusqlite::Connection,
690    handle: &str,
691    target_algo: &str,
692) -> Result<String, String> {
693    // Validate target algorithm is registered
694    {
695        let reg = global_registry().lock().unwrap();
696        if reg.get(target_algo).is_none() {
697            return Err(format!(
698                "Unsupported target algorithm: '{}' (registered: {:?})",
699                target_algo,
700                reg.algorithms()
701            ));
702        }
703    }
704
705    // 1. Resolve the handle to its current, possibly-qualified reference.
706    let current_hash: String = conn
707        .query_row(
708            "SELECT current_hash FROM handle_registry WHERE handle = ?",
709            rusqlite::params![handle],
710            |row| row.get(0),
711        )
712        .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
713
714    // 2. Retrieve the exact existing content preimage.
715    let content: Vec<u8> = lookup_content(conn, &current_hash)
716        .ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;
717
718    // 3. Create a fresh self-verifying record under the requested provider.
719    let now_utc = chrono::Utc::now().to_rfc3339();
720    let record = crate::layer0::mcard_record::MCardRecord::create_at(
721        &content,
722        Some(target_algo),
723        Some(&now_utc),
724        "UTC",
725    )?;
726    if !matches!(
727        crate::layer0::mcard_record::verify_record(&record),
728        crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
729    ) {
730        return Err("hash migration produced an invalid self-verifying record".to_string());
731    }
732    let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);
733
734    // 4. Transactional update with retry for WAL lock contention.
735
736    let max_attempts = 3;
737    let mut last_err = String::new();
738    for attempt in 0..max_attempts {
739        let tx = match conn.transaction() {
740            Ok(tx) => tx,
741            Err(e) => {
742                last_err = e.to_string();
743                std::thread::sleep(std::time::Duration::from_millis(200));
744                continue;
745            }
746        };
747        let result = (|| {
748            tx.execute(
749                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
750                rusqlite::params![&record.hash, &record.content, &record.g_time],
751            )
752            .map_err(|e| e.to_string())?;
753            tx.execute(
754                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
755                rusqlite::params![handle, &current_hash, &now_utc],
756            )
757            .map_err(|e| e.to_string())?;
758            tx.execute(
759                "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
760                rusqlite::params![&new_hash, &now_utc, handle],
761            )
762            .map_err(|e| e.to_string())?;
763            tx.commit().map_err(|e| e.to_string())
764        })();
765
766        match result {
767            Ok(()) => return Ok(new_hash),
768            Err(e) => {
769                last_err = e;
770                if attempt + 1 < max_attempts {
771                    std::thread::sleep(std::time::Duration::from_millis(200));
772                }
773            }
774        }
775    }
776
777    Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    #[test]
785    fn test_raw_hash_bytes() {
786        // Default active algorithm is blake3:
787        assert_eq!(
788            raw_hash_bytes(b"hello"),
789            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
790        );
791    }
792
793    #[test]
794    fn test_sha256_provider() {
795        let provider = Sha256Provider;
796        assert_eq!(
797            provider.hash(b"hello"),
798            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
799        );
800    }
801
802    #[test]
803    fn test_raw_hash_string() {
804        assert_eq!(
805            raw_hash_string("hello"),
806            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
807        );
808    }
809
810    #[test]
811    fn test_raw_hash_bytes_32() {
812        let expected = [
813            0xea, 0x8f, 0x16, 0x3d, 0xb3, 0x86, 0x82, 0x92, 0x5e, 0x44, 0x91, 0xc5, 0xe5, 0x8d,
814            0x4b, 0xb3, 0x50, 0x6e, 0xf8, 0xc1, 0x4e, 0xb7, 0x8a, 0x86, 0xe9, 0x08, 0xc5, 0x62,
815            0x4a, 0x67, 0x20, 0x0f,
816        ];
817        assert_eq!(raw_hash_bytes_32(b"hello"), expected);
818    }
819
820    #[test]
821    fn test_prefixed_hash_string() {
822        let h = prefixed_hash_string("hello");
823        assert!(h.starts_with("blake3:"));
824        assert_eq!(
825            h,
826            "blake3:ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
827        );
828    }
829
830    #[test]
831    fn test_strip_prefix() {
832        assert_eq!(strip_prefix("sha256:abcdef"), "abcdef");
833        assert_eq!(strip_prefix("sha3-256:abcdef"), "abcdef");
834        assert_eq!(strip_prefix("noprefix"), "noprefix");
835    }
836
837    #[test]
838    fn test_extract_prefix() {
839        assert_eq!(extract_prefix("sha256:abc"), Some("sha256:"));
840        assert_eq!(extract_prefix("sha3-256:abc"), Some("sha3-256:"));
841        assert_eq!(extract_prefix("noprefix"), None);
842    }
843
844    #[test]
845    fn test_verify_hash_match() {
846        let content = b"hello";
847        let stored = prefixed_hash_bytes(content);
848        assert!(verify_hash(&stored, content).is_ok());
849    }
850
851    #[test]
852    fn test_verify_hash_mismatch() {
853        let stored = prefixed_hash_bytes(b"hello");
854        assert!(verify_hash(&stored, b"world").is_err());
855    }
856
857    #[test]
858    fn test_verify_hash_unknown_prefix() {
859        assert!(verify_hash("unknown:abc", b"hello").is_err());
860    }
861
862    #[test]
863    fn test_provider_registry() {
864        let algorithms = list_algorithms();
865        assert!(algorithms.contains(&"sha256:"));
866    }
867
868    #[test]
869    fn test_collision_no_collision() {
870        let result = check_collision("abc", b"hello", None, 0);
871        assert_eq!(result, CollisionCheckResult::NoCollision);
872    }
873
874    #[test]
875    fn test_collision_same_content() {
876        let result = check_collision("abc", b"hello", Some(b"hello"), 0);
877        assert_eq!(result, CollisionCheckResult::NoCollision);
878    }
879
880    #[test]
881    fn test_collision_detected() {
882        let result = check_collision("abc", b"hello", Some(b"world"), 0);
883        assert_eq!(
884            result,
885            CollisionCheckResult::Collision {
886                hash: "abc".to_string(),
887                collision_count: 1
888            }
889        );
890    }
891
892    #[test]
893    fn test_collision_threshold_exceeded() {
894        let result = check_collision("abc", b"hello", Some(b"world"), 1);
895        match result {
896            CollisionCheckResult::ThresholdExceeded {
897                recommended_algorithm,
898                ..
899            } => {
900                // With default config, fallback order is ["blake3:", "sha256:"], so recommended == sha256:
901                assert_eq!(recommended_algorithm, "sha256:");
902            }
903            other => panic!("Expected ThresholdExceeded, got {:?}", other),
904        }
905    }
906
907    #[test]
908    fn test_hash_config_default() {
909        let cfg = HashConfig::default();
910        assert_eq!(cfg.active_algorithm, DEFAULT_HASH_PREFIX);
911        assert_eq!(cfg.collision_threshold, DEFAULT_COLLISION_THRESHOLD);
912    }
913
914    #[test]
915    fn test_hash_config_parse() {
916        let cfg = HashConfig::parse_config("sha256:|3|sha256:,sha3-256:");
917        assert_eq!(cfg.active_algorithm, "sha256:");
918        assert_eq!(cfg.collision_threshold, 3);
919        assert_eq!(cfg.fallback_order, vec!["sha256:", "sha3-256:"]);
920    }
921
922    #[test]
923    fn test_shake256_provider() {
924        let provider = Shake256Provider::new(256);
925        let h = provider.hash(b"hello");
926        // 256 bits = 32 bytes = 64 hex chars
927        assert_eq!(h.len(), 64);
928        assert_eq!(provider.prefix(), "custom-256:");
929    }
930
931    #[test]
932    fn test_shake256_provider_1024() {
933        let provider = Shake256Provider::new(1024);
934        let h = provider.hash(b"hello");
935        // 1024 bits = 128 bytes = 256 hex chars
936        assert_eq!(h.len(), 256);
937        assert_eq!(provider.prefix(), "custom-1024:");
938    }
939
940    #[test]
941    fn test_register_custom_provider() {
942        register_custom_provider(512);
943        let algorithms = list_algorithms();
944        assert!(algorithms.contains(&"custom-512:"));
945    }
946
947    #[test]
948    fn test_next_stronger_algorithm() {
949        assert_eq!(next_stronger_algorithm("md5:"), "sha1:");
950        assert_eq!(next_stronger_algorithm("sha1:"), "sha256:");
951        assert_eq!(next_stronger_algorithm("sha256:"), "blake3:");
952        assert_eq!(next_stronger_algorithm("blake3:"), "sha512:");
953        assert_eq!(next_stronger_algorithm("sha512:"), "custom-1024:");
954    }
955
956    #[test]
957    fn test_next_stronger_custom_doubling() {
958        assert_eq!(next_stronger_algorithm("custom-1024:"), "custom-2048:");
959        assert_eq!(next_stronger_algorithm("custom-2048:"), "custom-4096:");
960    }
961
962    #[test]
963    fn test_verify_hash_custom_n() {
964        register_custom_provider(256);
965        let provider = Shake256Provider::new(256);
966        let content = b"hello";
967        let raw = provider.hash(content);
968        let prefixed = format!("custom-256:{}", raw);
969        assert!(verify_hash(&prefixed, content).is_ok());
970        assert!(verify_hash(&prefixed, b"world").is_err());
971    }
972
973    #[test]
974    fn test_md5_provider() {
975        let provider = Md5Provider;
976        let h = provider.hash(b"hello");
977        assert_eq!(h.len(), 32); // 128 bits = 16 bytes = 32 hex chars
978        assert_eq!(h, "5d41402abc4b2a76b9719d911017c592");
979        assert_eq!(provider.prefix(), "md5:");
980    }
981
982    #[test]
983    fn test_sha1_provider() {
984        let provider = Sha1Provider;
985        let h = provider.hash(b"hello");
986        assert_eq!(h.len(), 40); // 160 bits = 20 bytes = 40 hex chars
987        assert_eq!(h, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
988        assert_eq!(provider.prefix(), "sha1:");
989    }
990
991    #[test]
992    fn test_sha512_provider() {
993        let provider = Sha512Provider;
994        let h = provider.hash(b"hello");
995        assert_eq!(h.len(), 128); // 512 bits = 64 bytes = 128 hex chars
996        assert_eq!(
997            h,
998            "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
999        );
1000        assert_eq!(provider.prefix(), "sha512:");
1001    }
1002
1003    #[test]
1004    fn test_blake3_provider() {
1005        let provider = Blake3Provider;
1006        let h = provider.hash(b"hello");
1007        // 256 bits = 32 bytes = 64 hex chars
1008        assert_eq!(h.len(), 64);
1009        assert_eq!(
1010            h,
1011            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
1012        );
1013        assert_eq!(provider.prefix(), "blake3:");
1014    }
1015
1016    #[test]
1017    fn test_all_providers_registered() {
1018        let algorithms = list_algorithms();
1019        assert!(algorithms.contains(&"blake3:"));
1020        assert!(algorithms.contains(&"sha256:"));
1021        assert!(algorithms.contains(&"md5:"));
1022        assert!(algorithms.contains(&"sha1:"));
1023        assert!(algorithms.contains(&"sha512:"));
1024    }
1025
1026    #[test]
1027    fn test_verify_hash_blake3() {
1028        let provider = Blake3Provider;
1029        let content = b"hello";
1030        let prefixed = format!("blake3:{}", provider.hash(content));
1031        assert!(verify_hash(&prefixed, content).is_ok());
1032        assert!(verify_hash(&prefixed, b"world").is_err());
1033    }
1034
1035    #[test]
1036    fn test_verify_hash_md5() {
1037        let provider = Md5Provider;
1038        let content = b"hello";
1039        let prefixed = format!("md5:{}", provider.hash(content));
1040        assert!(verify_hash(&prefixed, content).is_ok());
1041        assert!(verify_hash(&prefixed, b"world").is_err());
1042    }
1043
1044    #[test]
1045    fn test_verify_hash_sha512() {
1046        let provider = Sha512Provider;
1047        let content = b"hello";
1048        let prefixed = format!("sha512:{}", provider.hash(content));
1049        assert!(verify_hash(&prefixed, content).is_ok());
1050        assert!(verify_hash(&prefixed, b"world").is_err());
1051    }
1052
1053    #[test]
1054    #[cfg(feature = "native")]
1055    fn test_migrate_through_hierarchy() {
1056        use rusqlite::Connection;
1057        register_custom_provider(1024);
1058        let mut conn = Connection::open_in_memory().unwrap();
1059        conn.execute_batch(
1060            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
1061             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
1062             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
1063        ).unwrap();
1064        let content = b"hierarchy_test_payload";
1065        let h = prefixed_hash_bytes(content);
1066        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).unwrap();
1067        conn.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?, ?, '2025-01-01', '2025-01-01')", rusqlite::params!["test:hier_handle", h]).unwrap();
1068        // Migrate sha256 -> sha512
1069        let h512 = migrate_handle_hash(&mut conn, "test:hier_handle", "sha512:").unwrap();
1070        assert!(h512.starts_with("sha512:"));
1071        assert!(content_equivalent(&conn, &h, &h512).unwrap());
1072        // Migrate sha512 -> custom-1024
1073        let h_custom = migrate_handle_hash(&mut conn, "test:hier_handle", "custom-1024:").unwrap();
1074        assert!(h_custom.starts_with("custom-1024:"));
1075        assert!(content_equivalent(&conn, &h, &h_custom).unwrap());
1076        // Verify 3 cards coexist. A migration writes the new digest in the canonical bare form
1077        // (DEC-12) while the pre-migration row keeps whatever form it was stored under, so the
1078        // coexistence check counts rows by content rather than by reference form.
1079        let count: i64 = conn.query_row("SELECT count(*) FROM card WHERE content = ?", rusqlite::params![content], |r| r.get(0)).unwrap();
1080        assert_eq!(count, 3);
1081        // Verify 2 history entries
1082        let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:hier_handle'", [], |r| r.get(0)).unwrap();
1083        assert_eq!(hist, 2);
1084    }
1085
1086    #[test]
1087    #[cfg(feature = "native")]
1088    fn test_content_equivalent() {
1089        use rusqlite::Connection;
1090        let conn = Connection::open_in_memory().unwrap();
1091        conn.execute(
1092            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL)",
1093            [],
1094        )
1095        .unwrap();
1096        let content = b"hello world";
1097        let hash_a = "sha256:aaa";
1098        let hash_b = "sha512:bbb";
1099        let hash_c = "sha256:ccc";
1100        conn.execute(
1101            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1102            rusqlite::params![hash_a, content],
1103        )
1104        .unwrap();
1105        conn.execute(
1106            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1107            rusqlite::params![hash_b, content],
1108        )
1109        .unwrap();
1110        conn.execute(
1111            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1112            rusqlite::params![hash_c, b"different"],
1113        )
1114        .unwrap();
1115
1116        // Same content, different hashes → equivalent
1117        assert_eq!(content_equivalent(&conn, hash_a, hash_b).unwrap(), true);
1118        // Same hash → equivalent
1119        assert_eq!(content_equivalent(&conn, hash_a, hash_a).unwrap(), true);
1120        // Different content → not equivalent
1121        assert_eq!(content_equivalent(&conn, hash_a, hash_c).unwrap(), false);
1122        // Missing hash → not equivalent
1123        assert_eq!(content_equivalent(&conn, hash_a, "missing").unwrap(), false);
1124    }
1125
1126    #[test]
1127    #[cfg(feature = "native")]
1128    fn test_migrate_handle_hash() {
1129        use rusqlite::Connection;
1130        register_custom_provider(256);
1131        let mut conn = Connection::open_in_memory().unwrap();
1132        conn.execute_batch(
1133            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
1134             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
1135             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
1136        ).unwrap();
1137        let content = b"migration_test_payload";
1138        let h = prefixed_hash_bytes(content);
1139        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).unwrap();
1140        conn.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?, ?, '2025-01-01', '2025-01-01')", rusqlite::params!["test:handle", h]).unwrap();
1141        let new_h = migrate_handle_hash(&mut conn, "test:handle", "custom-256:").unwrap();
1142        assert!(new_h.starts_with("custom-256:"));
1143        let updated: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
1144        assert_eq!(updated, new_h);
1145        let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
1146        assert_eq!(hist, 1);
1147        assert!(content_equivalent(&conn, &h, &new_h).unwrap());
1148    }
1149}