1use md5::Md5;
38use sha1::Sha1;
39use sha2::{Digest, Sha256, Sha512};
40use sha3::{Shake256, digest::{ExtendableOutput, XofReader}};
41use std::sync::{Mutex, OnceLock};
42
43pub const BLAKE3_HASH_PREFIX: &str = "blake3:";
47
48pub const SHA256_HASH_PREFIX: &str = "sha256:";
50
51pub const DEFAULT_HASH_PREFIX: &str = BLAKE3_HASH_PREFIX;
53
54pub const DEFAULT_COLLISION_THRESHOLD: u32 = 2;
56
57pub trait HashProvider: Send + Sync {
65 fn hash(&self, content: &[u8]) -> String;
67
68 fn prefix(&self) -> &'static str;
70
71 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
89pub 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
108pub 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
129pub 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
144pub 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
159pub 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
174pub struct Shake256Provider {
181 bits: usize,
182 prefix_str: &'static str,
183}
184
185impl Shake256Provider {
186 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 + 7) / 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
217pub 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 pub fn register(&mut self, provider: Box<dyn HashProvider>) {
237 let prefix = provider.prefix();
238 self.providers.push((prefix, provider));
239 }
240
241 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 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 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
274pub fn register_provider(provider: Box<dyn HashProvider>) {
276 let mut reg = global_registry().lock().unwrap();
277 reg.register(provider);
278}
279
280pub fn register_custom_provider(bits: usize) {
285 register_provider(Box::new(Shake256Provider::new(bits)));
286}
287
288pub const STRENGTH_HIERARCHY: &[&str] = &[
294 "md5:",
295 "sha1:",
296 "sha256:",
297 "blake3:",
298 "sha512:",
299 "custom-1024:",
300];
301
302pub fn next_stronger_algorithm(current: &str) -> &'static str {
307 if let Some(rest) = current.strip_prefix("custom-") {
309 if let Some(num_str) = rest.strip_suffix(':') {
310 if let Ok(n) = num_str.parse::<usize>() {
311 let doubled = n * 2;
312 return Box::leak(format!("custom-{}:", doubled).into_boxed_str());
313 }
314 }
315 }
316 let pos = STRENGTH_HIERARCHY.iter().position(|&algo| algo == current);
318 match pos {
319 Some(i) if i + 1 < STRENGTH_HIERARCHY.len() => STRENGTH_HIERARCHY[i + 1],
320 _ => DEFAULT_HASH_PREFIX,
321 }
322}
323
324pub fn list_algorithms() -> Vec<&'static str> {
326 let reg = global_registry().lock().unwrap();
327 reg.algorithms()
328}
329
330#[derive(Debug, Clone)]
342pub struct HashConfig {
343 pub active_algorithm: &'static str,
345 pub collision_threshold: u32,
347 pub fallback_order: Vec<&'static str>,
351}
352
353impl Default for HashConfig {
354 fn default() -> Self {
355 Self {
356 active_algorithm: DEFAULT_HASH_PREFIX,
357 collision_threshold: DEFAULT_COLLISION_THRESHOLD,
358 fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
359 }
360 }
361}
362
363impl HashConfig {
364 pub fn from_env() -> Self {
373 if let Ok(raw) = std::env::var("CLM_HASH_CONFIG") {
374 Self::parse_config(&raw)
375 } else if let Ok(algo) = std::env::var("CLM_HASH_ALGO")
376 .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
377 {
378 let trimmed = algo.trim();
379 let prefix = if trimmed.ends_with(':') {
380 trimmed.to_string()
381 } else {
382 format!("{}:", trimmed)
383 };
384 let leaked_prefix: &'static str = Box::leak(prefix.into_boxed_str());
385 Self {
386 active_algorithm: leaked_prefix,
387 collision_threshold: DEFAULT_COLLISION_THRESHOLD,
388 fallback_order: vec![leaked_prefix, SHA256_HASH_PREFIX],
389 }
390 } else {
391 Self::default()
392 }
393 }
394
395 fn parse_config(raw: &str) -> Self {
396 let parts: Vec<&str> = raw.splitn(3, '|').collect();
397 if parts.len() < 2 {
398 return Self::default();
399 }
400 let active = if parts[0].is_empty() {
401 DEFAULT_HASH_PREFIX
402 } else {
403 Box::leak(parts[0].to_string().into_boxed_str())
404 };
405 let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
406 let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
407 parts[2]
408 .split(',')
409 .map(|s| {
410 if s.is_empty() {
411 DEFAULT_HASH_PREFIX
412 } else {
413 Box::leak(s.to_string().into_boxed_str())
414 }
415 })
416 .collect()
417 } else {
418 vec![active]
419 };
420 Self {
421 active_algorithm: active,
422 collision_threshold: threshold,
423 fallback_order: fallbacks,
424 }
425 }
426}
427
428fn global_config() -> &'static HashConfig {
429 static CONFIG: OnceLock<HashConfig> = OnceLock::new();
430 CONFIG.get_or_init(HashConfig::from_env)
431}
432
433pub fn config() -> &'static HashConfig {
435 global_config()
436}
437
438pub fn extract_prefix(prefixed: &str) -> Option<&str> {
445 prefixed.find(':').map(|pos| &prefixed[..=pos])
446}
447
448pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
457 let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
458 let reg = global_registry().lock().unwrap();
459 let provider = reg.get(prefix).ok_or_else(|| {
460 format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
461 })?;
462 let computed = provider.hash(content);
463 let stored_raw = strip_prefix(stored_hash);
464 if computed == stored_raw {
465 Ok(())
466 } else {
467 Err(format!(
468 "Hash mismatch: expected {}..., got {}...",
469 &stored_raw[..stored_raw.len().min(16)],
470 &computed[..computed.len().min(16)]
471 ))
472 }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq)]
479pub enum CollisionCheckResult {
480 NoCollision,
482 Collision { hash: String, collision_count: u32 },
484 ThresholdExceeded {
486 hash: String,
487 collision_count: u32,
488 recommended_algorithm: &'static str,
489 },
490}
491
492pub fn check_collision(
501 hash: &str,
502 new_content: &[u8],
503 existing_content: Option<&[u8]>,
504 collision_count: u32,
505) -> CollisionCheckResult {
506 match existing_content {
507 None => CollisionCheckResult::NoCollision,
508 Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
509 Some(_) => {
510 let count = collision_count + 1;
511 let cfg = config();
512 if count >= cfg.collision_threshold {
513 let recommended = cfg
515 .fallback_order
516 .iter()
517 .find(|&&algo| algo != cfg.active_algorithm)
518 .copied()
519 .unwrap_or(cfg.active_algorithm);
520 CollisionCheckResult::ThresholdExceeded {
521 hash: hash.to_string(),
522 collision_count: count,
523 recommended_algorithm: recommended,
524 }
525 } else {
526 CollisionCheckResult::Collision {
527 hash: hash.to_string(),
528 collision_count: count,
529 }
530 }
531 }
532 }
533}
534
535pub fn raw_hash_bytes(content: &[u8]) -> String {
542 let reg = global_registry().lock().unwrap();
543 reg.active(config().active_algorithm).hash(content)
544}
545
546pub fn raw_hash_string(s: &str) -> String {
548 raw_hash_bytes(s.as_bytes())
549}
550
551pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
556 let reg = global_registry().lock().unwrap();
557 reg.active(config().active_algorithm).hash_bytes(content)
558}
559
560pub fn prefixed_hash_bytes(content: &[u8]) -> String {
562 let reg = global_registry().lock().unwrap();
563 let provider = reg.active(config().active_algorithm);
564 format!("{}{}", provider.prefix(), provider.hash(content))
565}
566
567pub fn prefixed_hash_string(s: &str) -> String {
569 prefixed_hash_bytes(s.as_bytes())
570}
571
572pub fn prefixed(raw_hex: &str) -> String {
574 format!("{}{}", config().active_algorithm, raw_hex)
575}
576
577pub fn strip_prefix(prefixed: &str) -> &str {
582 let active = config().active_algorithm;
584 if let Some(rest) = prefixed.strip_prefix(active) {
585 return rest;
586 }
587 if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
589 return rest;
590 }
591 if let Some(pos) = prefixed.find(':') {
593 if pos + 1 < prefixed.len() {
594 return &prefixed[pos + 1..];
595 }
596 }
597 prefixed
598}
599
600pub fn default_provider() -> impl HashProvider {
604 Blake3Provider
605}
606
607#[cfg(feature = "native")]
620pub fn content_equivalent(
621 conn: &rusqlite::Connection,
622 hash_a: &str,
623 hash_b: &str,
624) -> Result<bool, String> {
625 if hash_a == hash_b {
626 return Ok(true);
627 }
628 let content_a: Option<Vec<u8>> = conn
629 .query_row(
630 "SELECT content FROM card WHERE hash = ?",
631 rusqlite::params![hash_a],
632 |row| row.get(0),
633 )
634 .ok();
635 let content_b: Option<Vec<u8>> = conn
636 .query_row(
637 "SELECT content FROM card WHERE hash = ?",
638 rusqlite::params![hash_b],
639 |row| row.get(0),
640 )
641 .ok();
642 match (content_a, content_b) {
643 (Some(a), Some(b)) => Ok(a == b),
644 _ => Ok(false),
645 }
646}
647
648#[cfg(feature = "native")]
665pub fn migrate_handle_hash(
666 conn: &mut rusqlite::Connection,
667 handle: &str,
668 target_algo: &str,
669) -> Result<String, String> {
670 {
672 let reg = global_registry().lock().unwrap();
673 if reg.get(target_algo).is_none() {
674 return Err(format!(
675 "Unsupported target algorithm: '{}' (registered: {:?})",
676 target_algo,
677 reg.algorithms()
678 ));
679 }
680 }
681
682 let current_hash: String = conn
684 .query_row(
685 "SELECT current_hash FROM handle_registry WHERE handle = ?",
686 rusqlite::params![handle],
687 |row| row.get(0),
688 )
689 .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
690
691 let content: Vec<u8> = conn
693 .query_row(
694 "SELECT content FROM card WHERE hash = ?",
695 rusqlite::params![current_hash],
696 |row| row.get(0),
697 )
698 .map_err(|_| {
699 format!(
700 "Content not found in CAS for hash '{}'",
701 current_hash
702 )
703 })?;
704
705 let reg = global_registry().lock().unwrap();
707 let provider = reg.get(target_algo).ok_or_else(|| {
708 format!("Provider not found for algorithm '{}'", target_algo)
709 })?;
710 let new_raw_hash = provider.hash(&content);
711 let new_hash = format!("{}{}", provider.prefix(), new_raw_hash);
712 drop(reg); let now_utc = chrono::Utc::now().to_rfc3339();
716 let algo_name = target_algo.trim_end_matches(':');
717 let g_time = format!("{}|{}|UTC", algo_name, now_utc);
718
719 let max_attempts = 3;
720 let mut last_err = String::new();
721 for attempt in 0..max_attempts {
722 let tx = match conn.transaction() {
723 Ok(tx) => tx,
724 Err(e) => {
725 last_err = e.to_string();
726 std::thread::sleep(std::time::Duration::from_millis(200));
727 continue;
728 }
729 };
730 let result = (|| {
731 tx.execute(
732 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
733 rusqlite::params![new_hash, &content, &g_time],
734 )
735 .map_err(|e| e.to_string())?;
736 tx.execute(
737 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
738 rusqlite::params![handle, ¤t_hash, &now_utc],
739 )
740 .map_err(|e| e.to_string())?;
741 tx.execute(
742 "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
743 rusqlite::params![&new_hash, &now_utc, handle],
744 )
745 .map_err(|e| e.to_string())?;
746 tx.commit().map_err(|e| e.to_string())
747 })();
748
749 match result {
750 Ok(()) => return Ok(new_hash),
751 Err(e) => {
752 last_err = e;
753 if attempt + 1 < max_attempts {
754 std::thread::sleep(std::time::Duration::from_millis(200));
755 }
756 }
757 }
758 }
759
760 Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766
767 #[test]
768 fn test_raw_hash_bytes() {
769 assert_eq!(
771 raw_hash_bytes(b"hello"),
772 "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
773 );
774 }
775
776 #[test]
777 fn test_sha256_provider() {
778 let provider = Sha256Provider;
779 assert_eq!(
780 provider.hash(b"hello"),
781 "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
782 );
783 }
784
785 #[test]
786 fn test_raw_hash_string() {
787 assert_eq!(
788 raw_hash_string("hello"),
789 "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
790 );
791 }
792
793 #[test]
794 fn test_raw_hash_bytes_32() {
795 let expected = [
796 0xea, 0x8f, 0x16, 0x3d, 0xb3, 0x86, 0x82, 0x92, 0x5e, 0x44, 0x91, 0xc5, 0xe5, 0x8d,
797 0x4b, 0xb3, 0x50, 0x6e, 0xf8, 0xc1, 0x4e, 0xb7, 0x8a, 0x86, 0xe9, 0x08, 0xc5, 0x62,
798 0x4a, 0x67, 0x20, 0x0f,
799 ];
800 assert_eq!(raw_hash_bytes_32(b"hello"), expected);
801 }
802
803 #[test]
804 fn test_prefixed_hash_string() {
805 let h = prefixed_hash_string("hello");
806 assert!(h.starts_with("blake3:"));
807 assert_eq!(
808 h,
809 "blake3:ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
810 );
811 }
812
813 #[test]
814 fn test_strip_prefix() {
815 assert_eq!(strip_prefix("sha256:abcdef"), "abcdef");
816 assert_eq!(strip_prefix("sha3-256:abcdef"), "abcdef");
817 assert_eq!(strip_prefix("noprefix"), "noprefix");
818 }
819
820 #[test]
821 fn test_extract_prefix() {
822 assert_eq!(extract_prefix("sha256:abc"), Some("sha256:"));
823 assert_eq!(extract_prefix("sha3-256:abc"), Some("sha3-256:"));
824 assert_eq!(extract_prefix("noprefix"), None);
825 }
826
827 #[test]
828 fn test_verify_hash_match() {
829 let content = b"hello";
830 let stored = prefixed_hash_bytes(content);
831 assert!(verify_hash(&stored, content).is_ok());
832 }
833
834 #[test]
835 fn test_verify_hash_mismatch() {
836 let stored = prefixed_hash_bytes(b"hello");
837 assert!(verify_hash(&stored, b"world").is_err());
838 }
839
840 #[test]
841 fn test_verify_hash_unknown_prefix() {
842 assert!(verify_hash("unknown:abc", b"hello").is_err());
843 }
844
845 #[test]
846 fn test_provider_registry() {
847 let algorithms = list_algorithms();
848 assert!(algorithms.contains(&"sha256:"));
849 }
850
851 #[test]
852 fn test_collision_no_collision() {
853 let result = check_collision("abc", b"hello", None, 0);
854 assert_eq!(result, CollisionCheckResult::NoCollision);
855 }
856
857 #[test]
858 fn test_collision_same_content() {
859 let result = check_collision("abc", b"hello", Some(b"hello"), 0);
860 assert_eq!(result, CollisionCheckResult::NoCollision);
861 }
862
863 #[test]
864 fn test_collision_detected() {
865 let result = check_collision("abc", b"hello", Some(b"world"), 0);
866 assert_eq!(
867 result,
868 CollisionCheckResult::Collision {
869 hash: "abc".to_string(),
870 collision_count: 1
871 }
872 );
873 }
874
875 #[test]
876 fn test_collision_threshold_exceeded() {
877 let result = check_collision("abc", b"hello", Some(b"world"), 1);
878 match result {
879 CollisionCheckResult::ThresholdExceeded {
880 recommended_algorithm,
881 ..
882 } => {
883 assert_eq!(recommended_algorithm, "sha256:");
885 }
886 other => panic!("Expected ThresholdExceeded, got {:?}", other),
887 }
888 }
889
890 #[test]
891 fn test_hash_config_default() {
892 let cfg = HashConfig::default();
893 assert_eq!(cfg.active_algorithm, DEFAULT_HASH_PREFIX);
894 assert_eq!(cfg.collision_threshold, DEFAULT_COLLISION_THRESHOLD);
895 }
896
897 #[test]
898 fn test_hash_config_parse() {
899 let cfg = HashConfig::parse_config("sha256:|3|sha256:,sha3-256:");
900 assert_eq!(cfg.active_algorithm, "sha256:");
901 assert_eq!(cfg.collision_threshold, 3);
902 assert_eq!(cfg.fallback_order, vec!["sha256:", "sha3-256:"]);
903 }
904
905 #[test]
906 fn test_shake256_provider() {
907 let provider = Shake256Provider::new(256);
908 let h = provider.hash(b"hello");
909 assert_eq!(h.len(), 64);
911 assert_eq!(provider.prefix(), "custom-256:");
912 }
913
914 #[test]
915 fn test_shake256_provider_1024() {
916 let provider = Shake256Provider::new(1024);
917 let h = provider.hash(b"hello");
918 assert_eq!(h.len(), 256);
920 assert_eq!(provider.prefix(), "custom-1024:");
921 }
922
923 #[test]
924 fn test_register_custom_provider() {
925 register_custom_provider(512);
926 let algorithms = list_algorithms();
927 assert!(algorithms.contains(&"custom-512:"));
928 }
929
930 #[test]
931 fn test_next_stronger_algorithm() {
932 assert_eq!(next_stronger_algorithm("md5:"), "sha1:");
933 assert_eq!(next_stronger_algorithm("sha1:"), "sha256:");
934 assert_eq!(next_stronger_algorithm("sha256:"), "blake3:");
935 assert_eq!(next_stronger_algorithm("blake3:"), "sha512:");
936 assert_eq!(next_stronger_algorithm("sha512:"), "custom-1024:");
937 }
938
939 #[test]
940 fn test_next_stronger_custom_doubling() {
941 assert_eq!(next_stronger_algorithm("custom-1024:"), "custom-2048:");
942 assert_eq!(next_stronger_algorithm("custom-2048:"), "custom-4096:");
943 }
944
945 #[test]
946 fn test_verify_hash_custom_n() {
947 register_custom_provider(256);
948 let provider = Shake256Provider::new(256);
949 let content = b"hello";
950 let raw = provider.hash(content);
951 let prefixed = format!("custom-256:{}", raw);
952 assert!(verify_hash(&prefixed, content).is_ok());
953 assert!(verify_hash(&prefixed, b"world").is_err());
954 }
955
956 #[test]
957 fn test_md5_provider() {
958 let provider = Md5Provider;
959 let h = provider.hash(b"hello");
960 assert_eq!(h.len(), 32); assert_eq!(h, "5d41402abc4b2a76b9719d911017c592");
962 assert_eq!(provider.prefix(), "md5:");
963 }
964
965 #[test]
966 fn test_sha1_provider() {
967 let provider = Sha1Provider;
968 let h = provider.hash(b"hello");
969 assert_eq!(h.len(), 40); assert_eq!(h, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
971 assert_eq!(provider.prefix(), "sha1:");
972 }
973
974 #[test]
975 fn test_sha512_provider() {
976 let provider = Sha512Provider;
977 let h = provider.hash(b"hello");
978 assert_eq!(h.len(), 128); assert_eq!(
980 h,
981 "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
982 );
983 assert_eq!(provider.prefix(), "sha512:");
984 }
985
986 #[test]
987 fn test_blake3_provider() {
988 let provider = Blake3Provider;
989 let h = provider.hash(b"hello");
990 assert_eq!(h.len(), 64);
992 assert_eq!(
993 h,
994 "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
995 );
996 assert_eq!(provider.prefix(), "blake3:");
997 }
998
999 #[test]
1000 fn test_all_providers_registered() {
1001 let algorithms = list_algorithms();
1002 assert!(algorithms.contains(&"blake3:"));
1003 assert!(algorithms.contains(&"sha256:"));
1004 assert!(algorithms.contains(&"md5:"));
1005 assert!(algorithms.contains(&"sha1:"));
1006 assert!(algorithms.contains(&"sha512:"));
1007 }
1008
1009 #[test]
1010 fn test_verify_hash_blake3() {
1011 let provider = Blake3Provider;
1012 let content = b"hello";
1013 let prefixed = format!("blake3:{}", provider.hash(content));
1014 assert!(verify_hash(&prefixed, content).is_ok());
1015 assert!(verify_hash(&prefixed, b"world").is_err());
1016 }
1017
1018 #[test]
1019 fn test_verify_hash_md5() {
1020 let provider = Md5Provider;
1021 let content = b"hello";
1022 let prefixed = format!("md5:{}", provider.hash(content));
1023 assert!(verify_hash(&prefixed, content).is_ok());
1024 assert!(verify_hash(&prefixed, b"world").is_err());
1025 }
1026
1027 #[test]
1028 fn test_verify_hash_sha512() {
1029 let provider = Sha512Provider;
1030 let content = b"hello";
1031 let prefixed = format!("sha512:{}", provider.hash(content));
1032 assert!(verify_hash(&prefixed, content).is_ok());
1033 assert!(verify_hash(&prefixed, b"world").is_err());
1034 }
1035
1036 #[test]
1037 #[cfg(feature = "native")]
1038 fn test_migrate_through_hierarchy() {
1039 use rusqlite::Connection;
1040 register_custom_provider(1024);
1041 let mut conn = Connection::open_in_memory().unwrap();
1042 conn.execute_batch(
1043 "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
1044 CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
1045 CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
1046 ).unwrap();
1047 let content = b"hierarchy_test_payload";
1048 let h = prefixed_hash_bytes(content);
1049 conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).unwrap();
1050 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();
1051 let h512 = migrate_handle_hash(&mut conn, "test:hier_handle", "sha512:").unwrap();
1053 assert!(h512.starts_with("sha512:"));
1054 assert!(content_equivalent(&conn, &h, &h512).unwrap());
1055 let h_custom = migrate_handle_hash(&mut conn, "test:hier_handle", "custom-1024:").unwrap();
1057 assert!(h_custom.starts_with("custom-1024:"));
1058 assert!(content_equivalent(&conn, &h, &h_custom).unwrap());
1059 let count: i64 = conn.query_row("SELECT count(*) FROM card WHERE hash IN (?, ?, ?)", rusqlite::params![h, h512, h_custom], |r| r.get(0)).unwrap();
1061 assert_eq!(count, 3);
1062 let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:hier_handle'", [], |r| r.get(0)).unwrap();
1064 assert_eq!(hist, 2);
1065 }
1066
1067 #[test]
1068 #[cfg(feature = "native")]
1069 fn test_content_equivalent() {
1070 use rusqlite::Connection;
1071 let conn = Connection::open_in_memory().unwrap();
1072 conn.execute(
1073 "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL)",
1074 [],
1075 )
1076 .unwrap();
1077 let content = b"hello world";
1078 let hash_a = "sha256:aaa";
1079 let hash_b = "sha512:bbb";
1080 let hash_c = "sha256:ccc";
1081 conn.execute(
1082 "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1083 rusqlite::params![hash_a, content],
1084 )
1085 .unwrap();
1086 conn.execute(
1087 "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1088 rusqlite::params![hash_b, content],
1089 )
1090 .unwrap();
1091 conn.execute(
1092 "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
1093 rusqlite::params![hash_c, b"different"],
1094 )
1095 .unwrap();
1096
1097 assert_eq!(content_equivalent(&conn, hash_a, hash_b).unwrap(), true);
1099 assert_eq!(content_equivalent(&conn, hash_a, hash_a).unwrap(), true);
1101 assert_eq!(content_equivalent(&conn, hash_a, hash_c).unwrap(), false);
1103 assert_eq!(content_equivalent(&conn, hash_a, "missing").unwrap(), false);
1105 }
1106
1107 #[test]
1108 #[cfg(feature = "native")]
1109 fn test_migrate_handle_hash() {
1110 use rusqlite::Connection;
1111 register_custom_provider(256);
1112 let mut conn = Connection::open_in_memory().unwrap();
1113 conn.execute_batch(
1114 "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
1115 CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
1116 CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
1117 ).unwrap();
1118 let content = b"migration_test_payload";
1119 let h = prefixed_hash_bytes(content);
1120 conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).unwrap();
1121 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();
1122 let new_h = migrate_handle_hash(&mut conn, "test:handle", "custom-256:").unwrap();
1123 assert!(new_h.starts_with("custom-256:"));
1124 let updated: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
1125 assert_eq!(updated, new_h);
1126 let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
1127 assert_eq!(hist, 1);
1128 assert!(content_equivalent(&conn, &h, &new_h).unwrap());
1129 }
1130}