Skip to main content

byteflow/
attest.rs

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