Skip to main content

zblob/
hash.rs

1//! Content hashing — BLAKE3, the crate-wide algorithm since v2.
2//!
3//! v1 shipped a nominally-pluggable `Digest` trait, but every code path
4//! hardcoded SHA-256, so v2 drops the pretense: BLAKE3 everywhere. What
5//! survives is *algorithm agility on the wire*: Tier-2 chunk keys carry an
6//! `<algo>` segment (`"blake3"` since v2), so stores populated by older
7//! producers under `sha256/…` keys coexist untouched next to `blake3/…` ones.
8//!
9//! Tier-1 blob identity is the BLAKE3 *bao root* (see [`crate::verify`]) —
10//! identical to `blake3::hash` of the content; the bao block size only affects
11//! slice/outboard granularity, never the root.
12
13use std::fmt;
14use std::str::FromStr;
15
16use serde::{Deserialize, Deserializer, Serialize, Serializer};
17
18/// The hash algorithm a message or key names.
19///
20/// One variant today. It exists as a type rather than a `String` because
21/// `algo` is a wire field: as a string, `TreeIndex.algo` accepted anything and
22/// was checked — if someone called `validate()` — against `Hash::ALGO`, and
23/// the eight key builders took an `algo: &str` every caller passed the same
24/// constant to. As an enum, an index naming an algorithm this crate cannot
25/// verify fails to decode, which is the same answer one step earlier and
26/// without a convention holding it up.
27///
28/// It serializes as the bare name (`"blake3"`), so this is a source break and
29/// not a wire break. `#[non_exhaustive]` because adding an algorithm must not
30/// break a downstream `match`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
32#[serde(try_from = "String", into = "String")]
33#[non_exhaustive]
34pub enum HashAlgo {
35    /// BLAKE3 — the crate-wide algorithm since wire v2.
36    #[default]
37    Blake3,
38}
39
40impl HashAlgo {
41    /// The wire/key name.
42    #[must_use]
43    pub const fn as_str(self) -> &'static str {
44        match self {
45            HashAlgo::Blake3 => "blake3",
46        }
47    }
48}
49
50impl fmt::Display for HashAlgo {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_str(self.as_str())
53    }
54}
55
56impl FromStr for HashAlgo {
57    type Err = crate::error::BlobError;
58    fn from_str(s: &str) -> Result<Self, Self::Err> {
59        match s {
60            "blake3" => Ok(HashAlgo::Blake3),
61            other => Err(crate::error::BlobError::MalformedMessage(format!(
62                "unsupported hash algorithm {other:?}"
63            ))),
64        }
65    }
66}
67
68impl TryFrom<String> for HashAlgo {
69    type Error = crate::error::BlobError;
70    fn try_from(s: String) -> Result<Self, Self::Error> {
71        s.parse()
72    }
73}
74
75impl From<HashAlgo> for String {
76    fn from(a: HashAlgo) -> String {
77        a.as_str().to_string()
78    }
79}
80
81/// A 32-byte content hash, rendered as lowercase hex on the wire and in keys.
82#[derive(Clone, Copy, PartialEq, Eq, Hash)]
83pub struct Hash([u8; 32]);
84
85impl Hash {
86    /// The wire/key name of the crate's hash algorithm.
87    ///
88    /// Equal to `HashAlgo::Blake3.as_str()`; kept as a `&str` constant because
89    /// it is compared against raw key segments, which are strings.
90    pub const ALGO: &'static str = HashAlgo::Blake3.as_str();
91
92    /// BLAKE3 hash of `data` in one shot.
93    pub fn of(data: &[u8]) -> Hash {
94        blake3::hash(data).into()
95    }
96
97    /// The raw bytes.
98    pub fn as_bytes(&self) -> &[u8; 32] {
99        &self.0
100    }
101
102    /// Build a hash from raw bytes.
103    pub const fn from_bytes(bytes: [u8; 32]) -> Hash {
104        Hash(bytes)
105    }
106}
107
108impl From<blake3::Hash> for Hash {
109    fn from(h: blake3::Hash) -> Hash {
110        Hash(*h.as_bytes())
111    }
112}
113
114impl From<Hash> for blake3::Hash {
115    fn from(h: Hash) -> blake3::Hash {
116        blake3::Hash::from_bytes(h.0)
117    }
118}
119
120impl fmt::Display for Hash {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        for byte in self.0 {
123            write!(f, "{byte:02x}")?;
124        }
125        Ok(())
126    }
127}
128
129impl fmt::Debug for Hash {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(f, "Hash({self})")
132    }
133}
134
135/// Error parsing a [`struct@Hash`] from a hex string.
136#[derive(Debug, thiserror::Error)]
137#[error("invalid hex hash: {0}")]
138pub struct HashParseError(String);
139
140impl FromStr for Hash {
141    type Err = HashParseError;
142
143    fn from_str(s: &str) -> Result<Self, Self::Err> {
144        if s.len() != 64 {
145            return Err(HashParseError(format!(
146                "expected 64 hex chars, got {}",
147                s.len()
148            )));
149        }
150        let mut out = [0u8; 32];
151        for (i, byte) in out.iter_mut().enumerate() {
152            let hi = s.as_bytes()[i * 2];
153            let lo = s.as_bytes()[i * 2 + 1];
154            *byte = (hex_val(hi).ok_or_else(|| HashParseError(s.to_string()))? << 4)
155                | hex_val(lo).ok_or_else(|| HashParseError(s.to_string()))?;
156        }
157        Ok(Hash(out))
158    }
159}
160
161fn hex_val(c: u8) -> Option<u8> {
162    match c {
163        b'0'..=b'9' => Some(c - b'0'),
164        b'a'..=b'f' => Some(c - b'a' + 10),
165        b'A'..=b'F' => Some(c - b'A' + 10),
166        _ => None,
167    }
168}
169
170impl Serialize for Hash {
171    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
172        if s.is_human_readable() {
173            s.serialize_str(&self.to_string())
174        } else {
175            s.serialize_bytes(&self.0)
176        }
177    }
178}
179
180impl<'de> Deserialize<'de> for Hash {
181    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
182        if d.is_human_readable() {
183            let s = String::deserialize(d)?;
184            s.parse().map_err(serde::de::Error::custom)
185        } else {
186            let bytes: [u8; 32] = serde_bytes_deserialize(d)?;
187            Ok(Hash(bytes))
188        }
189    }
190}
191
192/// Deserialize exactly 32 raw bytes (postcard/binary formats).
193fn serde_bytes_deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 32], D::Error> {
194    struct V;
195    impl serde::de::Visitor<'_> for V {
196        type Value = [u8; 32];
197        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198            f.write_str("32 raw hash bytes")
199        }
200        fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
201            v.try_into()
202                .map_err(|_| E::invalid_length(v.len(), &"32 bytes"))
203        }
204    }
205    d.deserialize_bytes(V)
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn blake3_known_vector() {
214        // BLAKE3("abc") — official test vector.
215        let h = Hash::of(b"abc");
216        assert_eq!(
217            h.to_string(),
218            "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85"
219        );
220    }
221
222    #[test]
223    fn hash_hex_roundtrip() {
224        let h = Hash::of(b"abc");
225        let parsed: Hash = h.to_string().parse().unwrap();
226        assert_eq!(h, parsed);
227    }
228
229    #[test]
230    fn blake3_conversions_roundtrip() {
231        let b = blake3::hash(b"xyz");
232        let h: Hash = b.into();
233        let back: blake3::Hash = h.into();
234        assert_eq!(b, back);
235        assert_eq!(h.as_bytes(), b.as_bytes());
236    }
237
238    #[test]
239    fn human_readable_serde_is_hex_string() {
240        let h = Hash::of(b"abc");
241        let json = serde_json::to_string(&h).unwrap();
242        assert!(json.starts_with('"') && json.contains("6437b3ac"));
243        let back: Hash = serde_json::from_str(&json).unwrap();
244        assert_eq!(h, back);
245    }
246
247    #[test]
248    fn binary_serde_is_raw_bytes() {
249        let h = Hash::of(b"abc");
250        let bytes = postcard::to_stdvec(&h).unwrap();
251        // Length-prefixed 32 raw bytes, not 64 hex chars.
252        assert_eq!(bytes.len(), 33);
253        let back: Hash = postcard::from_bytes(&bytes).unwrap();
254        assert_eq!(h, back);
255    }
256
257    #[test]
258    fn bad_hex_rejected() {
259        assert!("nothex".parse::<Hash>().is_err());
260        assert!("zz".repeat(32).parse::<Hash>().is_err());
261    }
262}