Skip to main content

coven_crypto/
object_digest.rs

1//! Incremental hashing of the bytes covered by an object's signature (Appendix D.3).
2
3use sha2::{Digest, Sha256};
4
5/// SHA-256 of every object byte before its signature, including its sealed chunks.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub struct ObjectDigest([u8; 32]);
8
9impl ObjectDigest {
10    /// The digest bytes authenticated with the object's path and signature domain.
11    pub fn as_bytes(&self) -> &[u8; 32] {
12        &self.0
13    }
14}
15
16/// Incremental SHA-256 state for an object's bytes in storage order.
17#[derive(Clone)]
18pub struct ObjectHasher(Sha256);
19
20impl ObjectHasher {
21    /// Start hashing the object before reading or writing its prefix.
22    pub fn new() -> Self {
23        Self(Sha256::new())
24    }
25
26    /// Feed the next prefix, length field or sealed chunk bytes in order.
27    pub fn update(&mut self, bytes: &[u8]) {
28        #[cfg(any(test, feature = "test-utils"))]
29        coven_foundation::test_work::object_hashed(bytes.len());
30        self.0.update(bytes);
31    }
32
33    /// Finish the digest after the last sealed chunk, before the signature.
34    pub fn finish(self) -> ObjectDigest {
35        ObjectDigest(self.0.finalize().into())
36    }
37}
38
39impl std::fmt::Debug for ObjectHasher {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.write_str("ObjectHasher(..)")
42    }
43}
44
45#[cfg(test)]
46#[path = "object_digest_tests.rs"]
47mod tests;