clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use super::*;
#[cfg(feature = "native")]
use crate::layer2::collision_migration::{content_equivalent, migrate_handle_hash};

    #[test]
    fn test_raw_hash_bytes() {
        // Default active algorithm is blake3:
        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,
                ..
            } => {
                // With default config, fallback order is ["blake3:", "sha256:"], so recommended == sha256:
                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");
        // 256 bits = 32 bytes = 64 hex chars
        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");
        // 1024 bits = 128 bytes = 256 hex chars
        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); // 128 bits = 16 bytes = 32 hex chars
        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); // 160 bits = 20 bytes = 40 hex chars
        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); // 512 bits = 64 bytes = 128 hex chars
        assert_eq!(
            h,
            "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
        );
        assert_eq!(provider.prefix(), "sha512:");
    }

    #[test]
    fn test_blake3_provider() {
        let provider = Blake3Provider;
        let h = provider.hash(b"hello");
        // 256 bits = 32 bytes = 64 hex chars
        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);
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).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();
        // Migrate sha256 -> sha512
        let h512 = migrate_handle_hash(&mut conn, "test:hier_handle", "sha512:").unwrap();
        assert!(h512.starts_with("sha512:"));
        assert!(content_equivalent(&conn, &h, &h512).unwrap());
        // Migrate sha512 -> custom-1024
        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());
        // Verify 3 cards coexist. A migration writes the new digest in the canonical bare form
        // (DEC-12) while the pre-migration row keeps whatever form it was stored under, so the
        // coexistence check counts rows by content rather than by reference form.
        let count: i64 = conn.query_row("SELECT count(*) FROM card WHERE content = ?", rusqlite::params![content], |r| r.get(0)).unwrap();
        assert_eq!(count, 3);
        // Verify 2 history entries
        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 content = b"hello world";
        let hash_a = "sha256:aaa";
        let hash_b = "sha512:bbb";
        let hash_c = "sha256:ccc";
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_a, content],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_b, content],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_c, b"different"],
        )
        .unwrap();

        // Same content, different hashes → equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_b).unwrap(), true);
        // Same hash → equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_a).unwrap(), true);
        // Different content → not equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_c).unwrap(), false);
        // Missing hash → not equivalent
        assert_eq!(content_equivalent(&conn, hash_a, "missing").unwrap(), false);
    }

    #[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);
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).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());
    }