use super::*;
#[cfg(feature = "native")]
use crate::layer2::collision_migration::{content_equivalent, migrate_handle_hash};
#[test]
fn test_raw_hash_bytes() {
assert_eq!(
raw_hash_bytes(b"hello"),
"ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
);
}
#[test]
fn test_sha256_provider() {
let provider = Sha256Provider;
assert_eq!(
provider.hash(b"hello"),
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
);
}
#[test]
fn test_raw_hash_string() {
assert_eq!(
raw_hash_string("hello"),
"ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
);
}
#[test]
fn test_raw_hash_bytes_32() {
let expected = [
0xea, 0x8f, 0x16, 0x3d, 0xb3, 0x86, 0x82, 0x92, 0x5e, 0x44, 0x91, 0xc5, 0xe5, 0x8d,
0x4b, 0xb3, 0x50, 0x6e, 0xf8, 0xc1, 0x4e, 0xb7, 0x8a, 0x86, 0xe9, 0x08, 0xc5, 0x62,
0x4a, 0x67, 0x20, 0x0f,
];
assert_eq!(raw_hash_bytes_32(b"hello"), expected);
}
#[test]
fn test_prefixed_hash_string() {
let h = prefixed_hash_string("hello");
assert!(h.starts_with("blake3:"));
assert_eq!(
h,
"blake3:ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
);
}
#[test]
fn test_strip_prefix() {
assert_eq!(strip_prefix("sha256:abcdef"), "abcdef");
assert_eq!(strip_prefix("sha3-256:abcdef"), "abcdef");
assert_eq!(strip_prefix("noprefix"), "noprefix");
}
#[test]
fn test_extract_prefix() {
assert_eq!(extract_prefix("sha256:abc"), Some("sha256:"));
assert_eq!(extract_prefix("sha3-256:abc"), Some("sha3-256:"));
assert_eq!(extract_prefix("noprefix"), None);
}
#[test]
fn test_verify_hash_match() {
let content = b"hello";
let stored = prefixed_hash_bytes(content);
assert!(verify_hash(&stored, content).is_ok());
}
#[test]
fn test_verify_hash_mismatch() {
let stored = prefixed_hash_bytes(b"hello");
assert!(verify_hash(&stored, b"world").is_err());
}
#[test]
fn test_verify_hash_unknown_prefix() {
assert!(verify_hash("unknown:abc", b"hello").is_err());
}
#[test]
fn test_provider_registry() {
let algorithms = list_algorithms();
assert!(algorithms.contains(&"sha256:"));
}
#[test]
fn test_collision_no_collision() {
let result = check_collision("abc", b"hello", None, 0);
assert_eq!(result, CollisionCheckResult::NoCollision);
}
#[test]
fn test_collision_same_content() {
let result = check_collision("abc", b"hello", Some(b"hello"), 0);
assert_eq!(result, CollisionCheckResult::NoCollision);
}
#[test]
fn test_collision_detected() {
let result = check_collision("abc", b"hello", Some(b"world"), 0);
assert_eq!(
result,
CollisionCheckResult::Collision {
hash: "abc".to_string(),
collision_count: 1
}
);
}
#[test]
fn test_collision_threshold_exceeded() {
let result = check_collision("abc", b"hello", Some(b"world"), 1);
match result {
CollisionCheckResult::ThresholdExceeded {
recommended_algorithm,
..
} => {
assert_eq!(recommended_algorithm, "sha256:");
}
other => panic!("Expected ThresholdExceeded, got {:?}", other),
}
}
#[test]
fn test_hash_config_default() {
let cfg = HashConfig::default();
assert_eq!(cfg.active_algorithm, DEFAULT_HASH_PREFIX);
assert_eq!(cfg.collision_threshold, DEFAULT_COLLISION_THRESHOLD);
}
#[test]
fn test_hash_config_parse() {
let cfg = HashConfig::parse_config("sha256:|3|sha256:,sha3-256:");
assert_eq!(cfg.active_algorithm, "sha256:");
assert_eq!(cfg.collision_threshold, 3);
assert_eq!(cfg.fallback_order, vec!["sha256:", "sha3-256:"]);
}
#[test]
fn test_shake256_provider() {
let provider = Shake256Provider::new(256);
let h = provider.hash(b"hello");
assert_eq!(h.len(), 64);
assert_eq!(provider.prefix(), "custom-256:");
}
#[test]
fn test_shake256_provider_1024() {
let provider = Shake256Provider::new(1024);
let h = provider.hash(b"hello");
assert_eq!(h.len(), 256);
assert_eq!(provider.prefix(), "custom-1024:");
}
#[test]
fn test_register_custom_provider() {
register_custom_provider(512);
let algorithms = list_algorithms();
assert!(algorithms.contains(&"custom-512:"));
}
#[test]
fn test_next_stronger_algorithm() {
assert_eq!(next_stronger_algorithm("md5:"), "sha1:");
assert_eq!(next_stronger_algorithm("sha1:"), "sha256:");
assert_eq!(next_stronger_algorithm("sha256:"), "blake3:");
assert_eq!(next_stronger_algorithm("blake3:"), "sha512:");
assert_eq!(next_stronger_algorithm("sha512:"), "custom-1024:");
}
#[test]
fn test_next_stronger_custom_doubling() {
assert_eq!(next_stronger_algorithm("custom-1024:"), "custom-2048:");
assert_eq!(next_stronger_algorithm("custom-2048:"), "custom-4096:");
}
#[test]
fn test_verify_hash_custom_n() {
register_custom_provider(256);
let provider = Shake256Provider::new(256);
let content = b"hello";
let raw = provider.hash(content);
let prefixed = format!("custom-256:{}", raw);
assert!(verify_hash(&prefixed, content).is_ok());
assert!(verify_hash(&prefixed, b"world").is_err());
}
#[test]
fn test_md5_provider() {
let provider = Md5Provider;
let h = provider.hash(b"hello");
assert_eq!(h.len(), 32); assert_eq!(h, "5d41402abc4b2a76b9719d911017c592");
assert_eq!(provider.prefix(), "md5:");
}
#[test]
fn test_sha1_provider() {
let provider = Sha1Provider;
let h = provider.hash(b"hello");
assert_eq!(h.len(), 40); assert_eq!(h, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
assert_eq!(provider.prefix(), "sha1:");
}
#[test]
fn test_sha512_provider() {
let provider = Sha512Provider;
let h = provider.hash(b"hello");
assert_eq!(h.len(), 128); assert_eq!(
h,
"9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
);
assert_eq!(provider.prefix(), "sha512:");
}
#[test]
fn test_blake3_provider() {
let provider = Blake3Provider;
let h = provider.hash(b"hello");
assert_eq!(h.len(), 64);
assert_eq!(
h,
"ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
);
assert_eq!(provider.prefix(), "blake3:");
}
#[test]
fn test_all_providers_registered() {
let algorithms = list_algorithms();
assert!(algorithms.contains(&"blake3:"));
assert!(algorithms.contains(&"sha256:"));
assert!(algorithms.contains(&"md5:"));
assert!(algorithms.contains(&"sha1:"));
assert!(algorithms.contains(&"sha512:"));
}
#[test]
fn test_verify_hash_blake3() {
let provider = Blake3Provider;
let content = b"hello";
let prefixed = format!("blake3:{}", provider.hash(content));
assert!(verify_hash(&prefixed, content).is_ok());
assert!(verify_hash(&prefixed, b"world").is_err());
}
#[test]
fn test_verify_hash_md5() {
let provider = Md5Provider;
let content = b"hello";
let prefixed = format!("md5:{}", provider.hash(content));
assert!(verify_hash(&prefixed, content).is_ok());
assert!(verify_hash(&prefixed, b"world").is_err());
}
#[test]
fn test_verify_hash_sha512() {
let provider = Sha512Provider;
let content = b"hello";
let prefixed = format!("sha512:{}", provider.hash(content));
assert!(verify_hash(&prefixed, content).is_ok());
assert!(verify_hash(&prefixed, b"world").is_err());
}
#[test]
#[cfg(feature = "native")]
fn test_migrate_through_hierarchy() {
use rusqlite::Connection;
register_custom_provider(1024);
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
).unwrap();
let content = b"hierarchy_test_payload";
let h = prefixed_hash_bytes(content);
let g_time = format!("{}|2025-01-01T00:00:00Z|UTC", h.split(':').next().unwrap());
conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)", rusqlite::params![h, content, g_time]).unwrap();
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();
let h512 = migrate_handle_hash(&mut conn, "test:hier_handle", "sha512:").unwrap();
assert!(h512.starts_with("sha512:"));
assert!(content_equivalent(&conn, &h, &h512).unwrap());
let h_custom = migrate_handle_hash(&mut conn, "test:hier_handle", "custom-1024:").unwrap();
assert!(h_custom.starts_with("custom-1024:"));
assert!(content_equivalent(&conn, &h, &h_custom).unwrap());
let count: i64 = conn.query_row("SELECT count(*) FROM card WHERE content = ?", rusqlite::params![content], |r| r.get(0)).unwrap();
assert_eq!(count, 3);
let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:hier_handle'", [], |r| r.get(0)).unwrap();
assert_eq!(hist, 2);
}
#[test]
#[cfg(feature = "native")]
fn test_content_equivalent() {
use rusqlite::Connection;
let conn = Connection::open_in_memory().unwrap();
conn.execute(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL)",
[],
)
.unwrap();
let a = crate::layer0::mcard_record::MCardRecord::create(b"hello world", Some("sha256")).unwrap();
let b = crate::layer0::mcard_record::MCardRecord::create(b"hello world", Some("sha512")).unwrap();
let c = crate::layer0::mcard_record::MCardRecord::create(b"different", Some("sha256")).unwrap();
for record in [&a, &b, &c] { crate::layer2::record_store::insert_record(&conn, record).unwrap(); }
assert!(content_equivalent(&conn, &a.hash, &b.hash).unwrap());
assert!(content_equivalent(&conn, &a.hash, &a.hash).unwrap());
assert!(!content_equivalent(&conn, &a.hash, &c.hash).unwrap());
assert!(!content_equivalent(&conn, &a.hash, "missing").unwrap());
conn.execute("UPDATE card SET content = 'corrupt' WHERE hash = ?", [&a.hash]).unwrap();
assert!(content_equivalent(&conn, &a.hash, &a.hash).is_err());
}
#[test]
#[cfg(feature = "native")]
fn test_migrate_handle_hash() {
use rusqlite::Connection;
register_custom_provider(256);
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
).unwrap();
let content = b"migration_test_payload";
let h = prefixed_hash_bytes(content);
let g_time = format!("{}|2025-01-01T00:00:00Z|UTC", h.split(':').next().unwrap());
conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)", rusqlite::params![h, content, g_time]).unwrap();
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();
let new_h = migrate_handle_hash(&mut conn, "test:handle", "custom-256:").unwrap();
assert!(new_h.starts_with("custom-256:"));
let updated: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
assert_eq!(updated, new_h);
let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
assert_eq!(hist, 1);
assert!(content_equivalent(&conn, &h, &new_h).unwrap());
}
#[test]
#[cfg(feature = "native")]
fn migration_rejects_algorithm_less_source_without_mutation() {
use rusqlite::Connection;
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
).unwrap();
let content = b"legacy_data";
let hash = prefixed_hash_bytes(content);
conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![hash, content, "2025-01-01T00:00:00Z"]).unwrap();
conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["legacy", hash, "2025-01-01", "2025-01-01"]).unwrap();
assert!(migrate_handle_hash(&mut conn, "legacy", "sha512:").is_err());
let (stored_hash, stored_time): (String, String) = conn.query_row("SELECT hash, g_time FROM card", [], |row| Ok((row.get(0)?, row.get(1)?))).unwrap();
assert_eq!((stored_hash, stored_time), (hash.clone(), "2025-01-01T00:00:00Z".to_string()));
let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'legacy'", [], |row| row.get(0)).unwrap();
assert_eq!(head, hash);
assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
}
#[test]
fn registered_provider_requires_valid_declared_metadata() {
use crate::layer0::mcard_record::{MCardRecord, RecordVerification, verify_record};
register_custom_provider(2048);
let record = MCardRecord::create_at(b"custom", Some("custom-2048"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
assert!(matches!(verify_record(&record), RecordVerification::DeclaredOk { .. }));
let mut malformed = record.clone();
malformed.g_time.push_str("|not-an-extension");
assert!(matches!(verify_record(&malformed), RecordVerification::Malformed { .. }));
malformed.g_time = "custom-2049|2025-01-01T00:00:00Z|UTC".to_string();
assert!(matches!(verify_record(&malformed), RecordVerification::Malformed { .. }));
}
#[test]
#[cfg(feature = "native")]
fn migration_rejects_corrupt_existing_target_without_changing_head() {
use rusqlite::Connection;
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
).unwrap();
let content = b"migration content";
let source = crate::layer0::mcard_record::MCardRecord::create_at(content, Some("blake3"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
let target = crate::hash::raw_hash_bytes_for("sha512", content).unwrap();
conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![source.hash, source.content, source.g_time]).unwrap();
conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![target, b"corrupt", "sha512|2025-01-01T00:00:00Z|UTC"]).unwrap();
conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["test", source.hash, "2025", "2025"]).unwrap();
assert!(migrate_handle_hash(&mut conn, "test", "sha512:").is_err());
let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test'", [], |row| row.get(0)).unwrap();
assert_eq!(head, source.hash);
let stored: Vec<u8> = conn.query_row("SELECT content FROM card WHERE hash = ?", [&target], |row| row.get(0)).unwrap();
assert_eq!(stored, b"corrupt");
assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
}
#[test]
#[cfg(feature = "native")]
fn migration_rejects_conflicting_source_reference() {
use rusqlite::Connection;
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
).unwrap();
let source = crate::layer0::mcard_record::MCardRecord::create_at(b"content", Some("blake3"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![source.hash, source.content, source.g_time]).unwrap();
let conflicting = format!("sha256:{}", source.hash);
conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["test", conflicting, "2025", "2025"]).unwrap();
assert!(migrate_handle_hash(&mut conn, "test", "sha512:").is_err());
let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test'", [], |row| row.get(0)).unwrap();
assert_eq!(head, conflicting);
assert_eq!(conn.query_row("SELECT count(*) FROM card", [], |row| row.get::<_, i64>(0)).unwrap(), 1);
assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
}