#![allow(unused_imports)]
use super::*;
#[derive(Debug, Clone)]
pub struct HashConfig {
pub active_algorithm: &'static str,
pub collision_threshold: u32,
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 {
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)
}
pub fn config() -> &'static HashConfig {
global_config()
}
pub fn extract_prefix(prefixed: &str) -> Option<&str> {
prefixed.find(':').map(|pos| &prefixed[..=pos])
}
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)]
))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollisionCheckResult {
NoCollision,
Collision { hash: String, collision_count: u32 },
ThresholdExceeded {
hash: String,
collision_count: u32,
recommended_algorithm: &'static str,
},
}
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 {
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,
}
}
}
}
}
pub fn raw_hash_bytes(content: &[u8]) -> String {
let reg = global_registry().lock().unwrap();
reg.active(config().active_algorithm).hash(content)
}
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))
}
pub fn raw_hash_string(s: &str) -> String {
raw_hash_bytes(s.as_bytes())
}
pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
let reg = global_registry().lock().unwrap();
reg.active(config().active_algorithm).hash_bytes(content)
}
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))
}
pub fn prefixed_hash_string(s: &str) -> String {
prefixed_hash_bytes(s.as_bytes())
}
pub fn prefixed(raw_hex: &str) -> String {
format!("{}{}", config().active_algorithm, raw_hex)
}
pub fn strip_prefix(prefixed: &str) -> &str {
let active = config().active_algorithm;
if let Some(rest) = prefixed.strip_prefix(active) {
return rest;
}
if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
return rest;
}
if let Some(pos) = prefixed.find(':')
&& pos + 1 < prefixed.len() {
return &prefixed[pos + 1..];
}
prefixed
}
pub fn default_provider() -> impl HashProvider {
Blake3Provider
}
#[cfg(feature = "native")]
pub fn content_equivalent(
conn: &rusqlite::Connection,
hash_a: &str,
hash_b: &str,
) -> Result<bool, String> {
if hash_a == hash_b {
return Ok(true);
}
let content_a = lookup_content(conn, hash_a);
let content_b = lookup_content(conn, hash_b);
match (content_a, content_b) {
(Some(a), Some(b)) => Ok(a == b),
_ => Ok(false),
}
}
#[cfg(feature = "native")]
pub(super) fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
let raw = strip_prefix(reference);
let mut candidates = vec![reference];
if raw != reference {
candidates.push(raw);
}
for candidate in candidates {
if let Ok(content) = conn.query_row(
"SELECT content FROM card WHERE hash = ?",
rusqlite::params![candidate],
|row| row.get::<_, Vec<u8>>(0),
) {
return Some(content);
}
}
None
}
#[cfg(feature = "native")]
pub fn migrate_handle_hash(
conn: &mut rusqlite::Connection,
handle: &str,
target_algo: &str,
) -> Result<String, String> {
{
let reg = global_registry().lock().unwrap();
if reg.get(target_algo).is_none() {
return Err(format!(
"Unsupported target algorithm: '{}' (registered: {:?})",
target_algo,
reg.algorithms()
));
}
}
let current_hash: String = conn
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?",
rusqlite::params![handle],
|row| row.get(0),
)
.map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
let content: Vec<u8> = lookup_content(conn, ¤t_hash)
.ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;
let now_utc = chrono::Utc::now().to_rfc3339();
let record = crate::layer0::mcard_record::MCardRecord::create_at(
&content,
Some(target_algo),
Some(&now_utc),
"UTC",
)?;
if !matches!(
crate::layer0::mcard_record::verify_record(&record),
crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
) {
return Err("hash migration produced an invalid self-verifying record".to_string());
}
let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);
let max_attempts = 3;
let mut last_err = String::new();
for attempt in 0..max_attempts {
let tx = match conn.transaction() {
Ok(tx) => tx,
Err(e) => {
last_err = e.to_string();
std::thread::sleep(std::time::Duration::from_millis(200));
continue;
}
};
let result = (|| {
tx.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
rusqlite::params![&record.hash, &record.content, &record.g_time],
)
.map_err(|e| e.to_string())?;
tx.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
rusqlite::params![handle, ¤t_hash, &now_utc],
)
.map_err(|e| e.to_string())?;
tx.execute(
"UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
rusqlite::params![&new_hash, &now_utc, handle],
)
.map_err(|e| e.to_string())?;
tx.commit().map_err(|e| e.to_string())
})();
match result {
Ok(()) => return Ok(new_hash),
Err(e) => {
last_err = e;
if attempt + 1 < max_attempts {
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
}
}
Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
}