Skip to main content

logit_loom_core/
digest.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Domain-separated content identities.
4
5use std::fmt;
6use std::str::FromStr;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::CoreError;
11
12const DIGEST_HEX_BYTES: usize = 64;
13
14/// A domain-separated BLAKE3 digest encoded as 64 lowercase hexadecimal bytes.
15#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct Digest(String);
17
18impl Digest {
19    /// Hashes bytes under an explicit domain separator.
20    pub fn of_bytes(domain: &str, bytes: &[u8]) -> Self {
21        let mut hasher = blake3::Hasher::new();
22        hasher.update(b"logit-loom\0");
23        hasher.update(
24            &u64::try_from(domain.len())
25                .unwrap_or(u64::MAX)
26                .to_le_bytes(),
27        );
28        hasher.update(domain.as_bytes());
29        hasher.update(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_le_bytes());
30        hasher.update(bytes);
31        Self(hasher.finalize().to_hex().to_string())
32    }
33
34    /// Hashes a serializable contract using deterministic JSON bytes.
35    ///
36    /// Contract maps should use ordered collections. Changing a serialized
37    /// shape is an identity and compatibility change.
38    ///
39    /// # Errors
40    ///
41    /// Returns an error when the value cannot be serialized.
42    pub fn of_serializable<T: Serialize + ?Sized>(
43        domain: &str,
44        value: &T,
45    ) -> Result<Self, CoreError> {
46        Ok(Self::of_bytes(domain, &serde_json::to_vec(value)?))
47    }
48
49    /// Returns the lowercase hexadecimal representation.
50    pub fn as_str(&self) -> &str {
51        &self.0
52    }
53}
54
55impl FromStr for Digest {
56    type Err = CoreError;
57
58    fn from_str(value: &str) -> Result<Self, Self::Err> {
59        if value.len() != DIGEST_HEX_BYTES
60            || !value
61                .bytes()
62                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
63        {
64            return Err(CoreError::invalid(
65                "digest",
66                "expected 64 lowercase hexadecimal bytes",
67            ));
68        }
69        Ok(Self(value.to_owned()))
70    }
71}
72
73impl fmt::Display for Digest {
74    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75        formatter.write_str(self.as_str())
76    }
77}
78
79impl fmt::Debug for Digest {
80    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
81        formatter.debug_tuple("Digest").field(&self.0).finish()
82    }
83}
84
85impl Serialize for Digest {
86    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87    where
88        S: Serializer,
89    {
90        serializer.serialize_str(self.as_str())
91    }
92}
93
94impl<'de> Deserialize<'de> for Digest {
95    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
96    where
97        D: Deserializer<'de>,
98    {
99        let value = String::deserialize(deserializer)?;
100        value.parse().map_err(serde::de::Error::custom)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn domain_and_length_are_bound_into_identity() {
110        let a = Digest::of_bytes("a", b"bc");
111        let b = Digest::of_bytes("ab", b"c");
112        let c = Digest::of_bytes("a", b"bc\0");
113        assert_ne!(a, b);
114        assert_ne!(a, c);
115        assert_eq!(a.as_str().len(), DIGEST_HEX_BYTES);
116    }
117
118    #[test]
119    fn deserialize_rejects_noncanonical_text() {
120        let uppercase = format!("\"{}\"", "A".repeat(DIGEST_HEX_BYTES));
121        assert!(serde_json::from_str::<Digest>(&uppercase).is_err());
122    }
123}