Skip to main content

fp_runtime/asupersync/
integrity.rs

1use serde::{Deserialize, Serialize};
2
3use crate::asupersync::error::AsupersyncError;
4
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6pub struct IntegrityProof {
7    pub algorithm: String,
8    pub expected_digest: String,
9    pub observed_digest: String,
10    pub verified: bool,
11}
12
13pub trait IntegrityVerifier {
14    fn verify(
15        &self,
16        artifact_id: &str,
17        bytes: &[u8],
18        expected_digest: &str,
19    ) -> Result<IntegrityProof, AsupersyncError>;
20}
21
22#[derive(Debug, Clone, Copy, Default)]
23pub struct Fnv1aVerifier;
24
25impl IntegrityVerifier for Fnv1aVerifier {
26    fn verify(
27        &self,
28        artifact_id: &str,
29        bytes: &[u8],
30        expected_digest: &str,
31    ) -> Result<IntegrityProof, AsupersyncError> {
32        let observed_digest = fnv1a_hex(bytes);
33        if observed_digest != expected_digest {
34            return Err(AsupersyncError::IntegrityMismatch {
35                artifact_id: artifact_id.to_string(),
36                expected: expected_digest.to_string(),
37                observed: observed_digest,
38            });
39        }
40
41        Ok(IntegrityProof {
42            algorithm: "fnv1a64".to_string(),
43            expected_digest: expected_digest.to_string(),
44            observed_digest,
45            verified: true,
46        })
47    }
48}
49
50fn fnv1a_hex(bytes: &[u8]) -> String {
51    let mut hash = 0xcbf29ce484222325_u64;
52    for byte in bytes {
53        hash ^= u64::from(*byte);
54        hash = hash.wrapping_mul(0x100000001b3);
55    }
56
57    const HEX: &[u8; 16] = b"0123456789abcdef";
58    let mut digest = String::with_capacity(16);
59    for shift in (0..16).rev().map(|nibble| nibble * 4) {
60        let nibble = ((hash >> shift) & 0x0f) as usize;
61        digest.push(char::from(HEX[nibble]));
62    }
63    digest
64}
65
66#[cfg(test)]
67mod tests {
68    use std::{
69        hint::black_box,
70        time::{Duration, Instant},
71    };
72
73    use super::{Fnv1aVerifier, IntegrityVerifier, fnv1a_hex};
74
75    fn former_fnv1a_hex(bytes: &[u8]) -> String {
76        let mut hash = 0xcbf29ce484222325_u64;
77        for byte in bytes {
78            hash ^= u64::from(*byte);
79            hash = hash.wrapping_mul(0x100000001b3);
80        }
81        format!("{hash:016x}")
82    }
83
84    #[test]
85    fn fnv1a_hex_matches_former_formatter_on_digest_boundaries() {
86        for bytes in [
87            b"".as_slice(),
88            b"a".as_slice(),
89            b"hello world".as_slice(),
90            &[0_u8, 1, 15, 16, 127, 128, 255],
91        ] {
92            assert_eq!(fnv1a_hex(bytes), former_fnv1a_hex(bytes));
93        }
94
95        assert_eq!(fnv1a_hex(b""), "cbf29ce484222325");
96        assert_eq!(fnv1a_hex(b"hello"), "a430d84680aabd0b");
97    }
98
99    #[test]
100    fn verifier_preserves_exact_digest_and_mismatch_payload() {
101        let verifier = Fnv1aVerifier;
102        let bytes = b"integrity payload";
103        let expected = fnv1a_hex(bytes);
104        let proof = verifier.verify("artifact", bytes, &expected).unwrap();
105        assert_eq!(proof.expected_digest, expected);
106        assert_eq!(proof.observed_digest, expected);
107
108        let mismatch = verifier.verify("artifact", bytes, "0000000000000000");
109        assert!(matches!(
110            mismatch,
111            Err(crate::asupersync::error::AsupersyncError::IntegrityMismatch {
112                artifact_id,
113                expected,
114                observed,
115            }) if artifact_id == "artifact"
116                && expected == "0000000000000000"
117                && observed == fnv1a_hex(bytes)
118        ));
119    }
120
121    #[test]
122    #[ignore = "foreground release attribution harness"]
123    fn fnv1a_hex_fixed_width_tail_ab_1elys() {
124        const BATCH: usize = 16_384;
125        const BLOCKS: usize = 21;
126        const BOOTSTRAPS: usize = 2_000;
127
128        fn elapsed(bytes: &[u8], render: fn(&[u8]) -> String) -> Duration {
129            let started = Instant::now();
130            let mut last = 0_u8;
131            for _ in 0..BATCH {
132                let digest = black_box(render(black_box(bytes)));
133                last ^= digest.as_bytes().last().copied().unwrap_or_default();
134                black_box(&digest);
135            }
136            black_box(last);
137            started.elapsed()
138        }
139
140        fn median(values: &mut [f64]) -> f64 {
141            values.sort_by(f64::total_cmp);
142            values[values.len() / 2]
143        }
144
145        fn bootstrap_median_ci(samples: &[f64]) -> (f64, f64) {
146            let mut state = 0x9e37_79b9_7f4a_7c15_u64;
147            let mut medians = Vec::with_capacity(BOOTSTRAPS);
148            let mut resample = vec![0.0; samples.len()];
149            for _ in 0..BOOTSTRAPS {
150                for value in &mut resample {
151                    state ^= state << 7;
152                    state ^= state >> 9;
153                    *value = samples[(state as usize) % samples.len()];
154                }
155                medians.push(median(&mut resample));
156            }
157            medians.sort_by(f64::total_cmp);
158            (
159                medians[BOOTSTRAPS / 40],
160                medians[BOOTSTRAPS - BOOTSTRAPS / 40 - 1],
161            )
162        }
163
164        let bytes = b"integrity verifier fixed-width digest tail";
165        assert_eq!(former_fnv1a_hex(bytes), fnv1a_hex(bytes));
166
167        let mut aa_ratios = Vec::with_capacity(BLOCKS);
168        let mut ab_ratios = Vec::with_capacity(BLOCKS);
169        for block in 0..BLOCKS {
170            let (former, candidate) = if block.is_multiple_of(2) {
171                (elapsed(bytes, former_fnv1a_hex), elapsed(bytes, fnv1a_hex))
172            } else {
173                let candidate = elapsed(bytes, fnv1a_hex);
174                let former = elapsed(bytes, former_fnv1a_hex);
175                (former, candidate)
176            };
177            let candidate_per_call = candidate.as_secs_f64() / BATCH as f64;
178            let former_per_call = former.as_secs_f64() / BATCH as f64;
179            ab_ratios.push(former_per_call / candidate_per_call);
180
181            let first = elapsed(bytes, former_fnv1a_hex).as_secs_f64() / BATCH as f64;
182            let second = elapsed(bytes, former_fnv1a_hex).as_secs_f64() / BATCH as f64;
183            aa_ratios.push(first / second);
184        }
185
186        let aa_median = median(&mut aa_ratios);
187        let ab_median = median(&mut ab_ratios);
188        let (aa_low, aa_high) = bootstrap_median_ci(&aa_ratios);
189        let (ab_low, ab_high) = bootstrap_median_ci(&ab_ratios);
190        let executable = std::fs::read("/proc/self/exe").expect("read executing test ELF");
191        let elf_sha256 = crate::sha256_hex(&executable);
192        eprintln!(
193            "FNV1A_HEX_1ELYS elf_sha256={elf_sha256} batch={BATCH} blocks={BLOCKS} aa_median={aa_median:.4} aa_median_ci95=[{aa_low:.4},{aa_high:.4}] candidate_speedup_median={ab_median:.4} candidate_speedup_median_ci95=[{ab_low:.4},{ab_high:.4}]"
194        );
195        assert!(
196            (0.95..=1.05).contains(&aa_median) && aa_low <= 1.0 && aa_high >= 1.0,
197            "A/A null gate failed: median={aa_median:.4}, CI=[{aa_low:.4},{aa_high:.4}]"
198        );
199    }
200}