Skip to main content

verit_core/
hash.rs

1//! Content hashing for schema ids.
2//!
3//! The schema id is a **content address**: two parties that build the same
4//! logical schema must derive the same id, and an adversary must not be able
5//! to cheaply find two schemas sharing one id (schema-confusion resistance,
6//! and safe use as a registry key). That rules out a fast non-cryptographic
7//! hash like FNV, whose structure makes collisions trivial to construct.
8//!
9//! We use SHA-256 truncated to 128 bits. (BLAKE3 would be a fine choice too;
10//! SHA-256 is chosen here because it is simple enough to implement correctly
11//! with zero dependencies — the whole crate stays dependency-free — and the
12//! schema hash is computed once per schema build, never on the hot path.)
13//!
14//! 128 bits gives ~2^64 birthday-collision resistance; a 64-bit id would give
15//! only ~2^32, which is within reach of a determined adversary — hence the
16//! wider id.
17
18/// The schema id: the first 128 bits of SHA-256 over the canonical schema
19/// bytes, read big-endian.
20pub fn schema_id(bytes: &[u8]) -> u128 {
21    let digest = sha256(bytes);
22    let mut id = [0u8; 16];
23    id.copy_from_slice(&digest[..16]);
24    u128::from_be_bytes(id)
25}
26
27const K: [u32; 64] = [
28    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
29    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
30    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
31    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
32    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
33    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
34    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
35    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
36];
37
38const H0: [u32; 8] = [
39    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
40];
41
42/// A straightforward, allocation-free SHA-256 (FIPS 180-4). Not constant-time
43/// — it hashes public schema bytes, not secrets.
44pub fn sha256(input: &[u8]) -> [u8; 32] {
45    let mut h = H0;
46
47    // Message schedule padding: len is fine as u64 bit-count.
48    let bit_len = (input.len() as u64).wrapping_mul(8);
49    let mut padded = Vec::with_capacity(input.len() + 9 + 63);
50    padded.extend_from_slice(input);
51    padded.push(0x80);
52    while padded.len() % 64 != 56 {
53        padded.push(0);
54    }
55    padded.extend_from_slice(&bit_len.to_be_bytes());
56
57    let mut w = [0u32; 64];
58    for block in padded.chunks_exact(64) {
59        for i in 0..16 {
60            w[i] = u32::from_be_bytes([
61                block[i * 4],
62                block[i * 4 + 1],
63                block[i * 4 + 2],
64                block[i * 4 + 3],
65            ]);
66        }
67        for i in 16..64 {
68            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
69            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
70            w[i] = w[i - 16]
71                .wrapping_add(s0)
72                .wrapping_add(w[i - 7])
73                .wrapping_add(s1);
74        }
75
76        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
77        for i in 0..64 {
78            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
79            let ch = (e & f) ^ ((!e) & g);
80            let t1 = hh
81                .wrapping_add(s1)
82                .wrapping_add(ch)
83                .wrapping_add(K[i])
84                .wrapping_add(w[i]);
85            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
86            let maj = (a & b) ^ (a & c) ^ (b & c);
87            let t2 = s0.wrapping_add(maj);
88            hh = g;
89            g = f;
90            f = e;
91            e = d.wrapping_add(t1);
92            d = c;
93            c = b;
94            b = a;
95            a = t1.wrapping_add(t2);
96        }
97        h[0] = h[0].wrapping_add(a);
98        h[1] = h[1].wrapping_add(b);
99        h[2] = h[2].wrapping_add(c);
100        h[3] = h[3].wrapping_add(d);
101        h[4] = h[4].wrapping_add(e);
102        h[5] = h[5].wrapping_add(f);
103        h[6] = h[6].wrapping_add(g);
104        h[7] = h[7].wrapping_add(hh);
105    }
106
107    let mut out = [0u8; 32];
108    for (i, word) in h.iter().enumerate() {
109        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
110    }
111    out
112}
113
114/// CRC-32 (IEEE 802.3): reflected, polynomial `0xEDB8_8320`, init and final
115/// XOR `0xFFFF_FFFF`. Used by the `.verit` file footer to prove a commit was
116/// not torn by a crash (File Format Specification §7).
117///
118/// Bitwise rather than table-driven on purpose: it only ever covers the 40-byte
119/// footer prefix, so a 256-entry table would cost more than it saves, and the
120/// loop is trivially portable — every implementation has to reproduce it.
121pub fn crc32(bytes: &[u8]) -> u32 {
122    let mut crc: u32 = 0xFFFF_FFFF;
123    for &byte in bytes {
124        crc ^= byte as u32;
125        for _ in 0..8 {
126            // Branchless: mask is all-ones when the low bit is set, else zero.
127            let mask = (crc & 1).wrapping_neg();
128            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
129        }
130    }
131    !crc
132}
133
134#[cfg(test)]
135mod tests {
136    use super::{crc32, sha256};
137
138    fn hex(d: &[u8]) -> String {
139        d.iter().map(|b| format!("{b:02x}")).collect()
140    }
141
142    #[test]
143    fn nist_vectors() {
144        // FIPS 180-4 / standard test vectors.
145        assert_eq!(
146            hex(&sha256(b"")),
147            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
148        );
149        assert_eq!(
150            hex(&sha256(b"abc")),
151            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
152        );
153        assert_eq!(
154            hex(&sha256(
155                b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
156            )),
157            "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
158        );
159    }
160
161    #[test]
162    fn multi_block_and_length_boundaries() {
163        // 64 bytes: exactly one block of input forces a second padding block.
164        let a64 = vec![b'a'; 64];
165        assert_eq!(
166            hex(&sha256(&a64)),
167            "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"
168        );
169        // 1,000,000 'a' — the classic long vector.
170        let million = vec![b'a'; 1_000_000];
171        assert_eq!(
172            hex(&sha256(&million)),
173            "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
174        );
175    }
176
177    #[test]
178    fn crc32_known_vectors() {
179        // The canonical IEEE CRC-32 check values every implementation agrees on.
180        assert_eq!(crc32(b""), 0x0000_0000);
181        assert_eq!(crc32(b"a"), 0xE8B7_BE43);
182        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
183        assert_eq!(
184            crc32(b"The quick brown fox jumps over the lazy dog"),
185            0x414F_A339
186        );
187    }
188
189    #[test]
190    fn crc32_detects_single_bit_flips() {
191        let base = [0xA5u8; 40];
192        let good = crc32(&base);
193        for byte in 0..base.len() {
194            for bit in 0..8 {
195                let mut torn = base;
196                torn[byte] ^= 1 << bit;
197                assert_ne!(crc32(&torn), good, "bit {bit} of byte {byte} undetected");
198            }
199        }
200    }
201}