Skip to main content

byteflow/
attest.rs

1//! Host-side bytecode **integrity fingerprint** (Phase 4).
2//!
3//! [`fingerprint_bf`] is a deterministic 32-byte digest over a `.bf` buffer.
4//! It is an **integrity fingerprint**, not cryptographic attestation: it does
5//! not use a secret key, MAC, or signature scheme. Hosts that want signed
6//! module attestation must layer that on top (non-goal for Byteflow itself).
7
8use std::collections::hash_map::DefaultHasher;
9use std::fmt;
10use std::hash::{Hash, Hasher};
11
12use crate::bytecode::{decode, Chunk, FormatError};
13
14/// Fixed domain separator mixed into every round (not a secret).
15const FINGERPRINT_DOMAIN: u64 = 0xBF01_464C_4F57_7630; // "BF01FLOW v0"
16
17/// Deterministic 32-byte integrity fingerprint of a BFV0 module buffer.
18///
19/// Built by expanding several [`DefaultHasher`] rounds (SipHash-1-3 with the
20/// hasher's fixed constructor keys) into 32 bytes. Suitable for host-side
21/// "did this buffer change?" checks — **not** for cryptographic attestation.
22pub fn fingerprint_bf(bytes: &[u8]) -> [u8; 32] {
23    let mut out = [0u8; 32];
24    for (lane, chunk) in out.chunks_mut(8).enumerate() {
25        let mut state = mix_lane(bytes, lane as u64, 0);
26        for round in 1u64..=4 {
27            state = mix_lane(bytes, lane as u64, round ^ state);
28        }
29        chunk.copy_from_slice(&state.to_le_bytes());
30    }
31    out
32}
33
34fn mix_lane(bytes: &[u8], lane: u64, round: u64) -> u64 {
35    let mut hasher = DefaultHasher::new();
36    FINGERPRINT_DOMAIN.hash(&mut hasher);
37    lane.hash(&mut hasher);
38    round.hash(&mut hasher);
39    (bytes.len() as u64).hash(&mut hasher);
40    bytes.hash(&mut hasher);
41    hasher.finish()
42}
43
44/// Failure of [`decode_attested`].
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum AttestError {
47    /// Buffer fingerprint did not match the expected digest.
48    DigestMismatch {
49        expected: [u8; 32],
50        actual: [u8; 32],
51    },
52    /// Fingerprint matched but BFV0 decode failed (`TrustLevel::Untrusted`).
53    Decode(String),
54}
55
56impl fmt::Display for AttestError {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            AttestError::DigestMismatch { expected, actual } => {
60                write!(
61                    f,
62                    "bytecode fingerprint mismatch: expected {}, actual {}",
63                    hex32(expected),
64                    hex32(actual)
65                )
66            }
67            AttestError::Decode(msg) => write!(f, "attested decode failed: {msg}"),
68        }
69    }
70}
71
72impl std::error::Error for AttestError {}
73
74fn hex32(bytes: &[u8; 32]) -> String {
75    let mut s = String::with_capacity(64);
76    for b in bytes {
77        use std::fmt::Write as _;
78        let _ = write!(s, "{b:02x}");
79    }
80    s
81}
82
83/// Fingerprint `bytes`, compare to `expected`, then [`decode`] (untrusted).
84///
85/// Digest is checked **before** decode so a wrong expected digest never
86/// spends work on a hostile buffer beyond the fingerprint pass.
87pub fn decode_attested(bytes: &[u8], expected: &[u8; 32]) -> Result<Chunk, AttestError> {
88    let actual = fingerprint_bf(bytes);
89    if &actual != expected {
90        return Err(AttestError::DigestMismatch {
91            expected: *expected,
92            actual,
93        });
94    }
95    decode(bytes).map_err(|e: FormatError| AttestError::Decode(e.to_string()))
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::bytecode::{encode, Program};
102
103    #[test]
104    fn roundtrip_fingerprint_then_decode_attested() -> Result<(), AttestError> {
105        let mut program = Program::new("attest-demo");
106        program.function("main", 0, |f| {
107            let a = f.load_i32(41);
108            let b = f.load_i32(1);
109            let sum = f.add(a, b);
110            f.return_(sum);
111        });
112        let chunk = program.build();
113        let bytes = encode(&chunk);
114        let digest = fingerprint_bf(&bytes);
115        let decoded = decode_attested(&bytes, &digest)?;
116        assert_eq!(decoded.name, chunk.name);
117        assert_eq!(decoded.code.len(), chunk.code.len());
118        Ok(())
119    }
120
121    #[test]
122    fn wrong_digest_fails_before_decode() {
123        let mut program = Program::new("attest-bad");
124        program.function("main", 0, |f| {
125            let v = f.load_i32(1);
126            f.return_(v);
127        });
128        let bytes = encode(&program.build());
129        let mut bad = fingerprint_bf(&bytes);
130        bad[0] ^= 0xFF;
131        match decode_attested(&bytes, &bad) {
132            Err(AttestError::DigestMismatch { .. }) => {}
133            other => panic!("expected DigestMismatch, got {other:?}"),
134        }
135    }
136
137    #[test]
138    fn fingerprint_is_deterministic() {
139        let bytes = b"BFV0-not-a-real-module-but-stable";
140        assert_eq!(fingerprint_bf(bytes), fingerprint_bf(bytes));
141    }
142}