Skip to main content

moonproof_utils/
hash.rs

1//! SHA-256 helpers — replace the
2//! `Sha256::new(); hasher.update(...); hex::encode(hasher.finalize())`
3//! pattern repeated across runtime / keystore / cli / codegen.
4//!
5//! Two surface levels:
6//!
7//! - [`sha256`] / [`sha256_hex`] — single-shot single-buffer hashing.
8//! - [`sha256_file`] / [`sha256_file_hex`] — single-shot file
9//!   hashing.
10//! - [`Sha256Builder`] — multi-update (namespace prefixes, separator
11//!   bytes) for domain-specific hashes that need more than one
12//!   buffer fed in.
13//!
14//! Sites with truly domain-specific shapes (e.g. cli's `sha256_dir`
15//! that walks a directory and folds filename + bytes per entry) stay
16//! in their crates — the builder lets them share the hash primitive
17//! without forcing a one-size-fits-all directory hasher.
18
19use std::io;
20use std::path::Path;
21
22use sha2::{Digest, Sha256};
23
24/// Hash `data` once. Returns the raw 32-byte digest.
25#[must_use]
26pub fn sha256(data: &[u8]) -> [u8; 32] {
27    let mut h = Sha256::new();
28    h.update(data);
29    h.finalize().into()
30}
31
32/// Hash `data` once. Returns lowercase hex of the digest.
33#[must_use]
34pub fn sha256_hex(data: &[u8]) -> String {
35    crate::hex::to_hex(&sha256(data))
36}
37
38/// Read `path` and return the raw 32-byte SHA-256 of its contents.
39pub fn sha256_file(path: &Path) -> io::Result<[u8; 32]> {
40    let bytes = std::fs::read(path)?;
41    Ok(sha256(&bytes))
42}
43
44/// Read `path` and return the lowercase hex SHA-256 of its contents.
45pub fn sha256_file_hex(path: &Path) -> io::Result<String> {
46    Ok(crate::hex::to_hex(&sha256_file(path)?))
47}
48
49/// Hash a directory's flat file contents in name-sorted order.
50/// Empty / missing dirs hash to the empty string. Each entry is
51/// folded as `<filename>:<bytes>\n` so reorderings on disk don't
52/// change the digest. Used by deployment-cache reconciliation
53/// (matches `moonproof deploy --resume`'s manifest-hash check) +
54/// any caller that needs a stable identity for a `keys/` /
55/// `zkir/` directory.
56pub fn sha256_dir(path: &Path) -> io::Result<String> {
57    if !path.exists() {
58        return Ok(String::new());
59    }
60    let mut h = Sha256Builder::new();
61    let mut entries: Vec<_> = std::fs::read_dir(path)?
62        .filter_map(std::result::Result::ok)
63        .collect();
64    entries.sort_by_key(std::fs::DirEntry::file_name);
65    for e in entries {
66        let bytes = std::fs::read(e.path())?;
67        h = h
68            .add(e.file_name().to_string_lossy().as_bytes())
69            .add(b":")
70            .add(&bytes)
71            .add(b"\n");
72    }
73    Ok(h.finalize_hex())
74}
75
76/// Multi-update SHA-256 builder. Use when the hash semantics require
77/// multiple buffers (namespace prefixes, separators, multi-field
78/// derivation):
79///
80/// ```ignore
81/// let h = Sha256Builder::new()
82///     .add(b"moonproof:disk-private-state-v1")
83///     .add(&signing_key_bytes)
84///     .add(owner_bytes)
85///     .finalize_hex();
86/// ```
87#[derive(Debug, Default)]
88pub struct Sha256Builder {
89    inner: Sha256,
90}
91
92impl Sha256Builder {
93    #[must_use]
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// Feed bytes into the running hash. Returns `self` for chaining.
99    #[must_use]
100    #[allow(clippy::should_implement_trait)] // a builder `add`, not `std::ops::Add`
101    pub fn add(mut self, bytes: impl AsRef<[u8]>) -> Self {
102        self.inner.update(bytes.as_ref());
103        self
104    }
105
106    /// Finalize, returning the raw 32-byte digest.
107    #[must_use]
108    pub fn finalize(self) -> [u8; 32] {
109        self.inner.finalize().into()
110    }
111
112    /// Finalize, returning lowercase hex.
113    #[must_use]
114    pub fn finalize_hex(self) -> String {
115        crate::hex::to_hex(&self.finalize())
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn sha256_round_trip_known_vector() {
125        // SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
126        assert_eq!(
127            sha256_hex(b"abc"),
128            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
129        );
130    }
131
132    #[test]
133    fn builder_matches_single_shot() {
134        let one_shot = sha256_hex(b"hello world");
135        let chained = Sha256Builder::new()
136            .add(b"hello ")
137            .add(b"world")
138            .finalize_hex();
139        assert_eq!(one_shot, chained);
140    }
141
142    #[test]
143    fn sha256_file_reads_contents() {
144        let dir = tempfile::TempDir::new().unwrap();
145        let p = dir.path().join("data.bin");
146        std::fs::write(&p, b"abc").unwrap();
147        let h = sha256_file_hex(&p).unwrap();
148        assert_eq!(
149            h,
150            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
151        );
152    }
153}