byteflow-actors 0.9.25

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
//! Host-side bytecode **integrity fingerprint** (Phase 4).
//!
//! [`fingerprint_bf`] is SHA-256 over a `.bf` buffer. It is an **integrity
//! fingerprint**, not cryptographic attestation: it does not use a secret
//! key, MAC, or signature scheme. Hosts that want signed module attestation
//! must layer that on top (non-goal for Byteflow itself).
//!
//! The digest is the FIPS 180-4 hash of the raw bytes, so the same buffer
//! produces the same 32 bytes on every rustc, OS, and pointer width. A value
//! stored from the previous `DefaultHasher` expansion will not match and
//! must be recomputed.

use std::fmt;

use crate::bytecode::{decode, Chunk, FormatError};

/// SHA-256 of `bytes`.
///
/// Any SHA-256 implementation can reproduce this (no domain prefix). Suitable
/// for host-side "did this buffer change?" checks — **not** a signature.
pub fn fingerprint_bf(bytes: &[u8]) -> [u8; 32] {
    crate::digest::sha256(bytes)
}

/// Failure of [`decode_attested`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttestError {
    /// Buffer fingerprint did not match the expected digest.
    DigestMismatch {
        expected: [u8; 32],
        actual: [u8; 32],
    },
    /// Fingerprint matched but BFV0 decode failed (`TrustLevel::Untrusted`).
    Decode(String),
}

impl fmt::Display for AttestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AttestError::DigestMismatch { expected, actual } => {
                write!(
                    f,
                    "bytecode fingerprint mismatch: expected {}, actual {}",
                    hex32(expected),
                    hex32(actual)
                )
            }
            AttestError::Decode(msg) => write!(f, "attested decode failed: {msg}"),
        }
    }
}

impl std::error::Error for AttestError {}

fn hex32(bytes: &[u8; 32]) -> String {
    let mut s = String::with_capacity(64);
    for b in bytes {
        use std::fmt::Write as _;
        let _ = write!(s, "{b:02x}");
    }
    s
}

/// Fingerprint `bytes`, compare to `expected`, then [`decode`] (untrusted).
///
/// Digest is checked **before** decode so a wrong expected digest never
/// spends work on a hostile buffer beyond the fingerprint pass.
pub fn decode_attested(bytes: &[u8], expected: &[u8; 32]) -> Result<Chunk, AttestError> {
    let actual = fingerprint_bf(bytes);
    if &actual != expected {
        return Err(AttestError::DigestMismatch {
            expected: *expected,
            actual,
        });
    }
    decode(bytes).map_err(|e: FormatError| AttestError::Decode(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytecode::{encode, Program};

    #[test]
    fn roundtrip_fingerprint_then_decode_attested() -> Result<(), AttestError> {
        let mut program = Program::new("attest-demo");
        program.function("main", 0, |f| {
            let a = f.load_i32(41);
            let b = f.load_i32(1);
            let sum = f.add(a, b);
            f.return_(sum);
        });
        let chunk = program.build();
        let bytes = encode(&chunk);
        let digest = fingerprint_bf(&bytes);
        let decoded = decode_attested(&bytes, &digest)?;
        assert_eq!(decoded.name, chunk.name);
        assert_eq!(decoded.code.len(), chunk.code.len());
        Ok(())
    }

    #[test]
    fn wrong_digest_fails_before_decode() {
        let mut program = Program::new("attest-bad");
        program.function("main", 0, |f| {
            let v = f.load_i32(1);
            f.return_(v);
        });
        let bytes = encode(&program.build());
        let mut bad = fingerprint_bf(&bytes);
        bad[0] ^= 0xFF;
        match decode_attested(&bytes, &bad) {
            Err(AttestError::DigestMismatch { .. }) => {}
            other => panic!("expected DigestMismatch, got {other:?}"),
        }
    }

    #[test]
    fn fingerprint_is_sha256_of_the_bytes() {
        assert_eq!(
            hex32(&fingerprint_bf(b"")),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        assert_eq!(
            hex32(&fingerprint_bf(b"abc")),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        let bytes = b"BFV0-not-a-real-module-but-stable";
        assert_eq!(fingerprint_bf(bytes), fingerprint_bf(bytes));
    }

    fn hex32(bytes: &[u8; 32]) -> String {
        let mut s = String::with_capacity(64);
        for b in bytes {
            use std::fmt::Write as _;
            let _ = write!(s, "{b:02x}");
        }
        s
    }
}