ifc_lite_git/
address.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Content addresses, and the canonical writer every object is hashed through.
6//!
7//! An address is `blake3:<64 hex>`. The tagged spelling is the repo's existing
8//! convention — `computeLayerId` and `computeStackHash` in
9//! `packages/ifcx/src/canonical.ts` emit the same shape — so an address is
10//! self-describing and a future algorithm change is visible rather than silent.
11//!
12//! BLAKE3 over SHA-256 for throughput at model scale, and over the faster
13//! non-cryptographic options because a content address must be
14//! collision-resistant: an attacker-supplied IFC must not be able to forge a
15//! node id that collides with one already in the store.
16
17use std::fmt;
18
19/// Algorithm tag carried by every address this crate mints.
20pub const ADDRESS_ALGORITHM: &str = "blake3";
21
22/// A content address: the digest of an object's canonical encoding.
23#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct Address([u8; 32]);
25
26impl Address {
27    /// Hash a canonical byte stream.
28    pub fn of(bytes: &[u8]) -> Self {
29        Address(*blake3::hash(bytes).as_bytes())
30    }
31
32    /// The raw digest.
33    pub fn as_bytes(&self) -> &[u8; 32] {
34        &self.0
35    }
36
37    /// `blake3:<64 hex>`, the form that goes on the wire and into a manifest.
38    pub fn tagged(&self) -> String {
39        let mut out = String::with_capacity(ADDRESS_ALGORITHM.len() + 1 + 64);
40        out.push_str(ADDRESS_ALGORITHM);
41        out.push(':');
42        for byte in self.0 {
43            out.push_str(&format!("{byte:02x}"));
44        }
45        out
46    }
47
48    /// Parse a tagged address. Rejects a different algorithm rather than
49    /// guessing, so a format migration cannot read as a corrupt digest.
50    pub fn parse(tagged: &str) -> Result<Self, AddressError> {
51        let (algorithm, hex) = tagged.split_once(':').ok_or(AddressError::Untagged)?;
52        if algorithm != ADDRESS_ALGORITHM {
53            return Err(AddressError::Algorithm(algorithm.to_owned()));
54        }
55        if hex.len() != 64 {
56            return Err(AddressError::Length(hex.len()));
57        }
58        // `u8::from_str_radix` accepts a leading sign and uppercase digits, so
59        // decoding alone would give one address several accepted spellings:
60        // `+f` pairs and `AB` pairs both parsed, and the second parsed to the
61        // same address as `ab`. For a content address that is a defect twice
62        // over — a `parse` → `tagged` round trip stopped being byte-identical,
63        // and a string-keyed lookup against `tagged()` output could miss a
64        // value that parsed. The digit set is the contract `NotHex` already
65        // documents, so enforce it here rather than leaning on the decoder.
66        if !hex
67            .bytes()
68            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
69        {
70            return Err(AddressError::NotHex);
71        }
72        let mut bytes = [0u8; 32];
73        for (index, pair) in hex.as_bytes().chunks_exact(2).enumerate() {
74            let text = std::str::from_utf8(pair).map_err(|_| AddressError::NotHex)?;
75            bytes[index] = u8::from_str_radix(text, 16).map_err(|_| AddressError::NotHex)?;
76        }
77        Ok(Address(bytes))
78    }
79}
80
81impl fmt::Debug for Address {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.write_str(&self.tagged())
84    }
85}
86
87impl fmt::Display for Address {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(&self.tagged())
90    }
91}
92
93/// Why a tagged address could not be read.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum AddressError {
96    /// No `<algorithm>:` prefix.
97    Untagged,
98    /// A tag this crate does not mint.
99    Algorithm(String),
100    /// Wrong number of hex digits.
101    Length(usize),
102    /// A digit outside `0-9a-f`.
103    NotHex,
104}
105
106impl fmt::Display for AddressError {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            AddressError::Untagged => write!(f, "address is missing an `<algorithm>:` prefix"),
110            AddressError::Algorithm(found) => {
111                write!(
112                    f,
113                    "address algorithm {found:?} is not {ADDRESS_ALGORITHM:?}"
114                )
115            }
116            AddressError::Length(found) => {
117                write!(f, "address needs 64 hex digits, found {found}")
118            }
119            AddressError::NotHex => write!(f, "address contains a non-hex digit"),
120        }
121    }
122}
123
124impl std::error::Error for AddressError {}
125
126/// The canonical byte writer.
127///
128/// Every object kind is encoded through this, so the framing rules live in one
129/// place:
130///
131/// - **A fixed 6-byte header**: 4-byte ASCII magic, 1-byte kind tag, 1-byte
132///   format version. A format change mints a new magic rather than reusing
133///   this one, which is how `node-hash-v0` says a successor must announce
134///   itself.
135/// - **Counts precede members**, so a truncated stream cannot be mistaken for
136///   a shorter valid one.
137/// - **Strings are length-prefixed**, never terminated, so a string containing
138///   any byte — a separator included — cannot be read as two fields. A
139///   delimiter-based encoding has exactly this collision, and it is the defect
140///   class tracked for the TypeScript side in #8088.
141///
142/// No [`Default`]: [`new`](Self::new) is the only constructor, so a
143/// header-less buffer — one with no magic, kind or version — cannot be built.
144/// (Review on #8265 also asked about `pub(crate)`: left `pub`, because
145/// `optional_string` and `i64` have no caller yet outside tests — the adapter
146/// and commit object that will call them are later PRs on #8262 — and
147/// `pub(crate)` turns that into a `dead_code` warning this crate would then
148/// have to silence rather than earn.)
149#[derive(Debug)]
150pub struct CanonicalWriter {
151    buffer: Vec<u8>,
152}
153
154impl CanonicalWriter {
155    /// Start an object: magic, kind tag, format version.
156    pub fn new(magic: &[u8; 4], kind: u8, format_version: u8) -> Self {
157        let mut buffer = Vec::with_capacity(64);
158        buffer.extend_from_slice(magic);
159        buffer.push(kind);
160        buffer.push(format_version);
161        CanonicalWriter { buffer }
162    }
163
164    /// An NFC-normalized UTF-8 string, length-prefixed with its byte length.
165    ///
166    /// Normalization happens here, in the one place every string passes
167    /// through, so no caller can encode a raw spelling by forgetting to.
168    pub fn string(&mut self, value: &str) -> &mut Self {
169        let bytes = canonical_bytes(value);
170        self.u32(u32::try_from(bytes.len()).expect("string longer than u32::MAX bytes"));
171        self.buffer.extend_from_slice(&bytes);
172        self
173    }
174
175    /// An optional string. Absent and empty are **distinct**: absent writes a
176    /// `0` tag and no payload, empty writes a `1` tag and a zero length.
177    pub fn optional_string(&mut self, value: Option<&str>) -> &mut Self {
178        match value {
179            None => {
180                self.buffer.push(0);
181            }
182            Some(text) => {
183                self.buffer.push(1);
184                self.string(text);
185            }
186        }
187        self
188    }
189
190    /// A member count. Always written before the members it counts.
191    pub fn u32(&mut self, value: u32) -> &mut Self {
192        self.buffer.extend_from_slice(&value.to_le_bytes());
193        self
194    }
195
196    /// A single byte: a kind or boolean tag. Narrower than [`u32`](Self::u32)
197    /// because a tag is a closed, small set — v0's rules (§2.5, as `node.rs`
198    /// keeps them) use one byte for exactly this, and a count is the only
199    /// field wide enough to need four.
200    pub fn u8(&mut self, value: u8) -> &mut Self {
201        self.buffer.push(value);
202        self
203    }
204
205    /// An `f64` as its raw IEEE-754 bit pattern, little-endian.
206    ///
207    /// v0's rule, and it avoids a decision rather than making one: encoding a
208    /// float as text means choosing a rendering, and two renderings of one
209    /// value hash differently. Bits have no such choice.
210    ///
211    /// Two values that compare equal must not hash differently, so this
212    /// canonicalises before taking bits: `-0.0` becomes `0.0` (IFC writers
213    /// emit `-0.` routinely, and it compares equal to `0.0` while differing in
214    /// its sign bit), and every `NaN` payload — signalling or quiet, any
215    /// mantissa — becomes one quiet pattern (they all compare *unequal* to
216    /// everything, including each other, so bits are the only identity they
217    /// have, and two authoring tools are not guaranteed to agree on one).
218    /// Canonicalising here, the one place every float passes through, means
219    /// no caller can forget to.
220    pub fn f64_bits(&mut self, value: f64) -> &mut Self {
221        let value = canonical_f64(value);
222        self.buffer
223            .extend_from_slice(&value.to_bits().to_le_bytes());
224        self
225    }
226
227    /// A 64-bit integer, for timestamps.
228    pub fn i64(&mut self, value: i64) -> &mut Self {
229        self.buffer.extend_from_slice(&value.to_le_bytes());
230        self
231    }
232
233    /// A child address, by its raw digest rather than its tagged string: the
234    /// Merkle rule is over bytes, and the tag is presentation.
235    pub fn address(&mut self, value: &Address) -> &mut Self {
236        self.buffer.extend_from_slice(value.as_bytes());
237        self
238    }
239
240    /// Finish, returning the object's address and its canonical bytes.
241    pub fn finish(self) -> (Address, Vec<u8>) {
242        (Address::of(&self.buffer), self.buffer)
243    }
244}
245
246/// Collapse the float identities that IEEE-754 equality already treats as one
247/// value but raw bits do not: `-0.0 == 0.0`, and every `NaN` compares unequal
248/// to everything including itself. See [`CanonicalWriter::f64_bits`].
249pub(crate) fn canonical_f64(value: f64) -> f64 {
250    if value.is_nan() {
251        f64::NAN
252    } else if value == 0.0 {
253        // Covers `-0.0`: IEEE-754 equality makes it equal to `0.0`, and this
254        // branch is reached only by the two zeros, so the literal replaces
255        // both with the same positive bit pattern.
256        0.0
257    } else {
258        value
259    }
260}
261
262/// NFC-normalized UTF-8 bytes: the sort key, and the bytes the encoder writes.
263///
264/// This is v0's rule, and following it is a correctness requirement rather than
265/// a compatibility nicety. `packages/provenance/SPEC.md` §3 normalizes every
266/// string before hashing and sorts sets by **those same normalized bytes**,
267/// with the reason stated: sorting raw while encoding normalized lets the
268/// producer's *spelling* pick the order. `Pset_Béton` spelled NFC
269/// (`…c3a9…`) and NFD (`…65cc81…`) is one string canonically and two byte
270/// sequences rawly, so a raw sort against `Pset_Z` orders the same set two ways
271/// and one canonical input yields two hashes — "worse than a collision for a
272/// verifier", since recompute-and-compare then fails on honest data.
273///
274/// An earlier draft of this crate sorted by UTF-16 code unit and normalized
275/// nothing, on the mistaken belief that it was inheriting v0's rule. It was
276/// inheriting `rust/diff`'s, which is a different compatibility format: that
277/// one exists to reproduce V8's `JSON.stringify` byte for byte and has no
278/// bearing here.
279pub fn canonical_bytes(value: &str) -> Vec<u8> {
280    use unicode_normalization::UnicodeNormalization;
281    value.nfc().collect::<String>().into_bytes()
282}
283
284/// Sort key over [`canonical_bytes`]. Named separately because the call sites
285/// read better, and because sorting and encoding must demonstrably use one
286/// function — that identity is the whole point of the rule above.
287pub fn sort_key(value: &str) -> Vec<u8> {
288    canonical_bytes(value)
289}
290
291#[cfg(test)]
292#[path = "address_tests.rs"]
293mod tests;