Skip to main content

rite_runtime/
transcript.rs

1//! Fingerprint helpers used across the runtime.
2
3use std::io;
4use std::path::Path;
5
6use sha2::{Digest, Sha256};
7
8/// Lower-hex SHA-256 of a byte slice, the raw primitive without any prefix.
9#[must_use]
10pub fn sha256_hex(data: &[u8]) -> String {
11    let mut hasher = Sha256::new();
12    hasher.update(data);
13    base16ct::lower::encode_string(&hasher.finalize())
14}
15
16/// SHA-256 fingerprint of an in-memory byte slice.
17///
18/// Returns `"sha256:{lowercase_hex}"`, the convention used throughout
19/// the runtime for artifact and transcript fingerprints.
20#[must_use]
21pub fn compute_fingerprint(data: &[u8]) -> String {
22    format!("sha256:{}", sha256_hex(data))
23}
24
25/// SHA-256 fingerprint of a file's contents.
26///
27/// # Errors
28///
29/// Returns the underlying I/O error if the file cannot be read.
30pub fn compute_file_fingerprint(path: &Path) -> io::Result<String> {
31    let data = std::fs::read(path)?;
32    Ok(compute_fingerprint(&data))
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn fingerprint_of_known_bytes() {
41        let fp = compute_fingerprint(b"hello world");
42        assert_eq!(
43            fp,
44            "sha256:b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
45        );
46    }
47}