moonproof-utils 0.2.2

Shared helpers (hex parsing, validation) used across moonproof crates. Mirror of midnight-js/packages/utils.
Documentation
//! SHA-256 helpers — replace the
//! `Sha256::new(); hasher.update(...); hex::encode(hasher.finalize())`
//! pattern repeated across runtime / keystore / cli / codegen.
//!
//! Two surface levels:
//!
//! - [`sha256`] / [`sha256_hex`] — single-shot single-buffer hashing.
//! - [`sha256_file`] / [`sha256_file_hex`] — single-shot file
//!   hashing.
//! - [`Sha256Builder`] — multi-update (namespace prefixes, separator
//!   bytes) for domain-specific hashes that need more than one
//!   buffer fed in.
//!
//! Sites with truly domain-specific shapes (e.g. cli's `sha256_dir`
//! that walks a directory and folds filename + bytes per entry) stay
//! in their crates — the builder lets them share the hash primitive
//! without forcing a one-size-fits-all directory hasher.

use std::io;
use std::path::Path;

use sha2::{Digest, Sha256};

/// Hash `data` once. Returns the raw 32-byte digest.
#[must_use]
pub fn sha256(data: &[u8]) -> [u8; 32] {
    let mut h = Sha256::new();
    h.update(data);
    h.finalize().into()
}

/// Hash `data` once. Returns lowercase hex of the digest.
#[must_use]
pub fn sha256_hex(data: &[u8]) -> String {
    crate::hex::to_hex(&sha256(data))
}

/// Read `path` and return the raw 32-byte SHA-256 of its contents.
pub fn sha256_file(path: &Path) -> io::Result<[u8; 32]> {
    let bytes = std::fs::read(path)?;
    Ok(sha256(&bytes))
}

/// Read `path` and return the lowercase hex SHA-256 of its contents.
pub fn sha256_file_hex(path: &Path) -> io::Result<String> {
    Ok(crate::hex::to_hex(&sha256_file(path)?))
}

/// Hash a directory's flat file contents in name-sorted order.
/// Empty / missing dirs hash to the empty string. Each entry is
/// folded as `<filename>:<bytes>\n` so reorderings on disk don't
/// change the digest. Used by deployment-cache reconciliation
/// (matches `moonproof deploy --resume`'s manifest-hash check) +
/// any caller that needs a stable identity for a `keys/` /
/// `zkir/` directory.
pub fn sha256_dir(path: &Path) -> io::Result<String> {
    if !path.exists() {
        return Ok(String::new());
    }
    let mut h = Sha256Builder::new();
    let mut entries: Vec<_> = std::fs::read_dir(path)?
        .filter_map(std::result::Result::ok)
        .collect();
    entries.sort_by_key(std::fs::DirEntry::file_name);
    for e in entries {
        let bytes = std::fs::read(e.path())?;
        h = h
            .add(e.file_name().to_string_lossy().as_bytes())
            .add(b":")
            .add(&bytes)
            .add(b"\n");
    }
    Ok(h.finalize_hex())
}

/// Multi-update SHA-256 builder. Use when the hash semantics require
/// multiple buffers (namespace prefixes, separators, multi-field
/// derivation):
///
/// ```ignore
/// let h = Sha256Builder::new()
///     .add(b"moonproof:disk-private-state-v1")
///     .add(&signing_key_bytes)
///     .add(owner_bytes)
///     .finalize_hex();
/// ```
#[derive(Debug, Default)]
pub struct Sha256Builder {
    inner: Sha256,
}

impl Sha256Builder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Feed bytes into the running hash. Returns `self` for chaining.
    #[must_use]
    #[allow(clippy::should_implement_trait)] // a builder `add`, not `std::ops::Add`
    pub fn add(mut self, bytes: impl AsRef<[u8]>) -> Self {
        self.inner.update(bytes.as_ref());
        self
    }

    /// Finalize, returning the raw 32-byte digest.
    #[must_use]
    pub fn finalize(self) -> [u8; 32] {
        self.inner.finalize().into()
    }

    /// Finalize, returning lowercase hex.
    #[must_use]
    pub fn finalize_hex(self) -> String {
        crate::hex::to_hex(&self.finalize())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sha256_round_trip_known_vector() {
        // SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn builder_matches_single_shot() {
        let one_shot = sha256_hex(b"hello world");
        let chained = Sha256Builder::new()
            .add(b"hello ")
            .add(b"world")
            .finalize_hex();
        assert_eq!(one_shot, chained);
    }

    #[test]
    fn sha256_file_reads_contents() {
        let dir = tempfile::TempDir::new().unwrap();
        let p = dir.path().join("data.bin");
        std::fs::write(&p, b"abc").unwrap();
        let h = sha256_file_hex(&p).unwrap();
        assert_eq!(
            h,
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }
}