1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#![allow(unused_imports)]
use super::*;
/// Configuration policy for hash algorithm selection and collision handling.
///
/// This struct governs:
/// - Which algorithm is used for **new** content (`active_algorithm`)
/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
/// - The order of fallback algorithms if the active one is compromised
///
/// The config is stored in a global `OnceLock` and can be loaded from a
/// configuration file or environment variable at startup.
#[derive(Debug, Clone)]
pub struct HashConfig {
/// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
pub active_algorithm: &'static str,
/// Number of collisions before triggering an upgrade.
pub collision_threshold: u32,
/// Ordered list of fallback algorithm prefixes.
/// If the active algorithm is compromised, the first available fallback
/// becomes the new active algorithm.
pub fallback_order: Vec<&'static str>,
}
impl Default for HashConfig {
fn default() -> Self {
Self {
active_algorithm: DEFAULT_HASH_PREFIX,
collision_threshold: DEFAULT_COLLISION_THRESHOLD,
fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
}
}
}
pub(super) fn normalize_prefix(value: &str) -> &'static str {
let normalized = value.trim().trim_end_matches(':').to_lowercase();
Box::leak(format!("{}:", normalized).into_boxed_str())
}
impl HashConfig {
/// Load hash configuration from environment variables.
///
/// Checks in order:
/// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
/// Example: `blake3:|2|blake3:,sha256:`
/// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
///
/// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
/// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
pub fn from_env() -> Self {
let configured = std::env::var("CLM_HASH_CONFIG")
.ok()
.filter(|raw| !raw.trim().is_empty())
.map(|raw| Self::parse_config(&raw))
.or_else(|| {
std::env::var("CLM_HASH_ALGO")
.or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
.ok()
.filter(|algo| !algo.trim().is_empty())
.map(|algo| {
let prefix = normalize_prefix(&algo);
Self {
active_algorithm: prefix,
collision_threshold: DEFAULT_COLLISION_THRESHOLD,
fallback_order: vec![prefix, SHA256_HASH_PREFIX],
}
})
});
let Some(config) = configured else {
return Self::default();
};
config
}
pub(super) fn parse_config(raw: &str) -> Self {
let parts: Vec<&str> = raw.splitn(3, '|').collect();
if parts.len() < 2 {
return Self::default();
}
let active = if parts[0].is_empty() {
DEFAULT_HASH_PREFIX
} else {
normalize_prefix(parts[0])
};
let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
parts[2]
.split(',')
.map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
.collect()
} else {
vec![active]
};
Self {
active_algorithm: active,
collision_threshold: threshold,
fallback_order: fallbacks,
}
}
}
pub(super) fn global_config() -> &'static HashConfig {
static CONFIG: OnceLock<HashConfig> = OnceLock::new();
CONFIG.get_or_init(HashConfig::from_env)
}
/// Get the current hash configuration.
pub fn config() -> &'static HashConfig {
global_config()
}
// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────
/// Extract the algorithm prefix from a stored hash string.
///
/// Returns `Some(prefix)` if the string contains a `:` separator,
/// `None` if there is no prefix (assumed to be the default algorithm).
pub fn extract_prefix(prefixed: &str) -> Option<&str> {
prefixed.find(':').map(|pos| &prefixed[..=pos])
}
/// Verify a stored hash against content by dispatching to the correct provider.
///
/// This function parses the algorithm prefix from `stored_hash`, looks up
/// the corresponding provider in the registry, and checks whether the
/// content matches.
///
/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
/// or the provider is unknown.
pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
let reg = global_registry().lock().unwrap();
let provider = reg.get(prefix).ok_or_else(|| {
format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
})?;
let computed = provider.hash(content);
let stored_raw = strip_prefix(stored_hash);
if computed == stored_raw {
Ok(())
} else {
Err(format!(
"Hash mismatch: expected {}..., got {}...",
&stored_raw[..stored_raw.len().min(16)],
&computed[..computed.len().min(16)]
))
}
}
// ── Collision detection (Step 5) ──────────────────────────────────────────
/// Result of a collision check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollisionCheckResult {
/// No collision — the hash is unique.
NoCollision,
/// Collision detected — the same hash already exists with different content.
Collision { hash: String, collision_count: u32 },
/// Threshold exceeded — the active algorithm should be upgraded.
ThresholdExceeded {
hash: String,
collision_count: u32,
recommended_algorithm: &'static str,
},
}
/// Check whether a hash collision has occurred and whether the threshold
/// for algorithm upgrade has been exceeded.
///
/// Callers should invoke this *before* inserting a new card into the database.
/// If `existing_content` is `Some` and differs from `new_content`, a collision
/// is recorded. When the collision count for the active algorithm reaches
/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
/// with the recommended fallback algorithm.
pub fn check_collision(
hash: &str,
new_content: &[u8],
existing_content: Option<&[u8]>,
collision_count: u32,
) -> CollisionCheckResult {
match existing_content {
None => CollisionCheckResult::NoCollision,
Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
Some(_) => {
let count = collision_count + 1;
let cfg = config();
if count >= cfg.collision_threshold {
// Find the first fallback that isn't the current active algorithm
let recommended = cfg
.fallback_order
.iter()
.find(|&&algo| algo != cfg.active_algorithm)
.copied()
.unwrap_or(cfg.active_algorithm);
CollisionCheckResult::ThresholdExceeded {
hash: hash.to_string(),
collision_count: count,
recommended_algorithm: recommended,
}
} else {
CollisionCheckResult::Collision {
hash: hash.to_string(),
collision_count: count,
}
}
}
}
}
// ── Convenience functions (delegate to the active provider) ──────────────
/// Compute the raw hex digest of bytes using the active provider (no prefix).
///
/// This is the canonical "common function signature" shared with Python's
/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
pub fn raw_hash_bytes(content: &[u8]) -> String {
let reg = global_registry().lock().unwrap();
reg.active(config().active_algorithm).hash(content)
}
/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
let prefix = format!("{}:", normalized);
let reg = global_registry().lock().map_err(|e| e.to_string())?;
let provider = reg.get(&prefix).ok_or_else(|| {
format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
})?;
Ok(provider.hash(content))
}
/// Compute the raw hex digest of a string using the active provider (no prefix).
pub fn raw_hash_string(s: &str) -> String {
raw_hash_bytes(s.as_bytes())
}
/// Compute the raw digest as a 32-byte array using the active provider.
///
/// Used by Merkle tree and type lattice code that needs the raw bytes
/// rather than a hex string.
pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
let reg = global_registry().lock().unwrap();
reg.active(config().active_algorithm).hash_bytes(content)
}
/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_bytes(content: &[u8]) -> String {
let reg = global_registry().lock().unwrap();
let provider = reg.active(config().active_algorithm);
format!("{}{}", provider.prefix(), provider.hash(content))
}
/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_string(s: &str) -> String {
prefixed_hash_bytes(s.as_bytes())
}
/// Prepend the active algorithm prefix to an already-computed raw hex digest.
pub fn prefixed(raw_hex: &str) -> String {
format!("{}{}", config().active_algorithm, raw_hex)
}
/// Strip a known algorithm prefix from a hash string.
///
/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
/// the unprefixed hex is returned. Otherwise the input is returned as-is.
pub fn strip_prefix(prefixed: &str) -> &str {
// Try the active algorithm prefix first
let active = config().active_algorithm;
if let Some(rest) = prefixed.strip_prefix(active) {
return rest;
}
// Try the default prefix
if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
return rest;
}
// Generic fallback: strip any `<algo>:` prefix
if let Some(pos) = prefixed.find(':')
&& pos + 1 < prefixed.len() {
return &prefixed[pos + 1..];
}
prefixed
}
/// Returns the default hash provider (currently `Blake3Provider`).
///
/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
pub fn default_provider() -> impl HashProvider {
Blake3Provider
}