content_addressable/content_id.rs
1//! [`ContentId`] — the self-certifying identity of a value.
2//!
3//! A `ContentId` is a newtype over an IPLD [`Cid`] (content identifier, v1).
4//! It is computed directly from a value's canonical bytes, so it *is* a proof
5//! of integrity: anyone holding the bytes can recompute the id and confirm the
6//! bytes are exactly what the id names. Nothing trusted needs to vouch for the
7//! association — it is intrinsic.
8
9use std::fmt;
10use std::str::FromStr;
11
12use ipld_core::cid::multihash::Multihash;
13use ipld_core::cid::{Cid, Version};
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16use crate::error::ContentError;
17
18/// Multicodec code for the `dag-cbor` content type (`0x71`).
19///
20/// This is the codec field of every [`ContentId`]'s CID: it declares that the
21/// bytes the id names are canonical dag-cbor. **Frozen** for the `0.1.x` line —
22/// see the [`ContentId` CID-parameters contract](ContentId#cid-parameters-frozen-at-010).
23pub const DAG_CBOR_CODEC: u64 = 0x71;
24
25/// Multihash code for BLAKE3 (`0x1e`).
26///
27/// This is the hash function field of every [`ContentId`]'s multihash.
28/// **Frozen** for the `0.1.x` line — see the
29/// [`ContentId` CID-parameters contract](ContentId#cid-parameters-frozen-at-010).
30pub const BLAKE3_HASH_CODE: u64 = 0x1e;
31
32/// Length of a BLAKE3 digest in bytes (256 bits).
33///
34/// Part of the **frozen** v1 CID-parameter contract: every [`ContentId`]'s
35/// multihash carries exactly 32 digest bytes. Kept private (no new public
36/// surface, gate item 9); the value is asserted by the CID-shape tests and is
37/// implied on the wire by the `0x20` multihash length prefix. Changing it is a
38/// major version bump — see the
39/// [`ContentId` CID-parameters contract](ContentId#cid-parameters-frozen-at-010).
40pub(crate) const BLAKE3_DIGEST_LEN: usize = 32;
41
42/// The self-certifying identity of a value.
43///
44/// A `ContentId` wraps an IPLD CIDv1 whose codec is `dag-cbor` (`0x71`) and
45/// whose multihash is BLAKE3 (`0x1e`) over the value's canonical dag-cbor
46/// bytes. See [`from_canonical_bytes`](Self::from_canonical_bytes).
47///
48/// Ordering is defined by the CID's binary representation, which makes
49/// `ContentId` usable as a key in ordered maps and sets with a stable,
50/// content-derived sort.
51///
52/// # CID parameters (FROZEN at 0.1.0)
53///
54/// The three fields that determine every address this crate emits are a
55/// **fixed v1 contract**, not configuration (gate items 3, 4, 5 — see
56/// `README.md`):
57///
58/// - **CID version: `V1`** (`Cid::new_v1`). There is no v0 / agility path.
59/// - **Multicodec: `dag-cbor` (`0x71`)** — see [`DAG_CBOR_CODEC`].
60/// - **Multihash: `BLAKE3` (`0x1e`)** — see [`BLAKE3_HASH_CODE`] — over a
61/// **fixed 32-byte digest** (`BLAKE3_DIGEST_LEN`, 256 bits).
62///
63/// These values are **not selectable**. [`from_canonical_bytes`](Self::from_canonical_bytes)
64/// is the single mint site and always produces this shape. Changing the
65/// version, codec, hash function, or digest length is a **new representation =
66/// major version bump**, never a patch — every previously emitted address would
67/// become unreachable. CIDs are self-describing, so a future hash/codec can
68/// ship as a *new* representation under a *new* major without retrofitting
69/// agility now. A raw [`Cid`] is admitted only if it matches this profile —
70/// [`TryFrom<Cid>`](#impl-TryFrom%3CCid%3E-for-ContentId) validates it — and the
71/// inner CID is readable via [`as_cid`](Self::as_cid).
72///
73/// # Serde representation (FROZEN at 0.1.0)
74///
75/// `ContentId` has two serde forms, chosen by the serializer via
76/// `is_human_readable`, and **both are a stability contract across the entire
77/// `0.1.x` line** — changing either is a **major version bump**. The committed
78/// golden vectors (`tests/vectors.json`) plus the in-crate golden test pin
79/// these exact bytes so a dependency bump cannot silently perturb them:
80///
81/// - **Binary / IPLD form (e.g. dag-cbor): a tag-42 link.** Through
82/// [`serde_ipld_dagcbor`] a `ContentId` is encoded as a CBOR **tag-42 link**
83/// (major-type-6 head `0xd8 0x2a`, then a byte string carrying the `0x00`
84/// multibase-identity prefix followed by the CID binary form). This is the
85/// natural IPLD encoding and makes `ContentId` fields inside other
86/// content-addressed structures behave as real links — the crate's
87/// IPLD-native thesis. See [`canonical`](crate::canonical).
88/// - **Human-readable form (e.g. `serde_json`, TOML): the multibase base32
89/// string.** In a human-readable serializer a `ContentId` is the
90/// base32-lower `b…` CID string — the same text
91/// [`Display`](fmt::Display)/[`FromStr`] produce — so JSON and config files
92/// carry a readable, portable CID rather than a raw byte array. The crate
93/// adds a thin `is_human_readable` branch over the inner `Cid` to guarantee
94/// this; the IPLD/binary path is unchanged.
95///
96/// # Presentation contract (FROZEN at 0.1.0)
97///
98/// Whatever string and byte forms this type emits become a **byte/wire
99/// contract** at `0.1.0`: changing any of them afterward is a **major version
100/// bump**, never a patch (issue #6, gate item 2). The full presentation
101/// surface is therefore named and frozen explicitly, with conformance vectors
102/// (`tests/vectors.json` + the in-crate goldens) pinning the exact bytes. There
103/// are **four** distinct presentation forms, each load-bearing for a different
104/// reason — do not confuse them:
105///
106/// | Form | Method | What it is |
107/// |------|--------|------------|
108/// | **Canonical text** | [`Display`](fmt::Display) / [`to_string`](ToString::to_string) | multibase **base32-lower** (`b…`), the IPLD-canonical CID string |
109/// | **Binary envelope** | [`to_bytes`](Self::to_bytes) / [`from_bytes`](Self::from_bytes) | the full **CID binary** form (version + codec + multihash + digest) |
110/// | **Bare digest** | [`digest_bytes`](Self::digest_bytes) | the raw **32-byte BLAKE3** hash (no envelope) |
111/// | **Bare-digest-hex** | [`digest_hex`](Self::digest_hex) | lowercase **hex of the 32-byte digest** (64 chars, no prefix) |
112///
113/// **Three incompatible "hex" conventions** exist in the wild for a CID; an
114/// adopter must pick one, so the crate names them to end the ambiguity:
115///
116/// 1. **bare-digest-hex** — hex of the raw 32-byte BLAKE3 digest. *This is what
117/// [`digest_hex`](Self::digest_hex) returns* (the "swarm" / kyln `to_hex()`
118/// convention: shortest, hash-only).
119/// 2. **full-CID-bytes-hex** — hex of [`to_bytes`](Self::to_bytes) (the whole
120/// CID envelope as base16). *Deliberately **not** a method.* Convention #2 is
121/// just `hex::encode(id.to_bytes())`; blessing it as `cid_hex()` would add a
122/// third "hex" accessor that invites exactly the confusion this contract
123/// exists to end. A caller who genuinely needs CID-bytes-as-hex hex-encodes
124/// [`to_bytes`](Self::to_bytes) explicitly and owns that choice. (This
125/// non-decision is recorded so it is not re-litigated; it can be added later
126/// additively without breaking the frozen surface.)
127/// 3. **multibase base32-lower** — the [`Display`](fmt::Display) string. Use
128/// this, not a hex form, as the canonical text representation.
129///
130/// `Display` emits base32-lower and is the **inverse of [`FromStr`] for that
131/// form**: the `Display`→`FromStr` round-trip is frozen and tested. `FromStr`
132/// *also* tolerates other multibases (base58, base16, …) as a **convenience,
133/// not a contract** — that tolerance may be tightened later without breaking
134/// the frozen base32-lower round-trip.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
136pub struct ContentId(Cid);
137
138impl ContentId {
139 /// Compute the content id of bytes that **are already canonical dag-cbor**.
140 ///
141 /// This is the crate's fast, unchecked minting primitive — the hot path that
142 /// [`ContentAddressable::content_id`](crate::ContentAddressable::content_id)
143 /// leans on. The pipeline is, end to end:
144 ///
145 /// 1. `digest = BLAKE3(bytes)` — a 32-byte hash.
146 /// 2. `mh = Multihash::wrap(0x1e, digest)` — tag the digest with the
147 /// BLAKE3 multihash code.
148 /// 3. `cid = Cid::new_v1(0x71, mh)` — a CIDv1 declaring the bytes are
149 /// dag-cbor.
150 ///
151 /// # Precondition — CALLER MUST PASS CANONICAL DAG-CBOR
152 ///
153 /// **The bytes you pass MUST already be canonical dag-cbor** — typically the
154 /// output of
155 /// [`to_canonical_dagcbor`](crate::canonical::to_canonical_dagcbor) or, for a
156 /// whole value, [`ContentAddressable::canonical_form`](crate::ContentAddressable::canonical_form).
157 /// This function **does not re-canonicalize and does not validate**; it only
158 /// hashes whatever it is handed and stamps the result with the `0x71`
159 /// (dag-cbor) codec.
160 ///
161 /// Passing **non-canonical** CBOR (wrong map-key order, indefinite-length
162 /// items, non-smallest integers), hand-rolled CBOR, or arbitrary non-dag-cbor
163 /// bytes is a **logic error, not handled at runtime**: you get back a
164 /// perfectly valid-looking [`ContentId`] whose `0x71` codec is a **lie** —
165 /// the bytes it names are not canonical dag-cbor. A second party who
166 /// canonicalizes "the same value" will compute a **different** id, and
167 /// nothing here will have told you. This is silent and by design (validation
168 /// is not free, so it is opt-in — see below), so honor the precondition.
169 ///
170 /// # Which door to use
171 ///
172 /// - **Have a value?** Use
173 /// [`ContentAddressable::content_id`](crate::ContentAddressable::content_id)
174 /// (the documented default). It canonicalizes *then* hashes, so it can
175 /// never hand this function non-canonical bytes — the precondition holds by
176 /// construction and there is no per-call validation tax on the safe path.
177 /// - **Have bytes you canonicalized yourself** (via
178 /// [`to_canonical_dagcbor`](crate::canonical::to_canonical_dagcbor))?
179 /// This primitive is correct and fastest.
180 /// - **Have foreign / untrusted bytes you did *not* canonicalize?** Use the
181 /// checked sibling
182 /// [`from_canonical_bytes_checked`](Self::from_canonical_bytes_checked),
183 /// which re-encodes and rejects non-canonical input with a typed error.
184 ///
185 /// # Naming (FROZEN at 0.1.0)
186 ///
187 /// This door keeps the name `from_canonical_bytes` (the fast primitive) and
188 /// is **not** renamed to `_unchecked`; the checked variant is the explicitly
189 /// suffixed [`from_canonical_bytes_checked`](Self::from_canonical_bytes_checked).
190 /// This pairing is a frozen `0.1.0` decision (README gate item #6) — it
191 /// cannot change cheaply after `0.1.0`.
192 ///
193 /// # Panics
194 ///
195 /// Does not panic. BLAKE3 always produces a 32-byte digest, which always
196 /// fits the multihash's 64-byte capacity, so the `wrap` call cannot fail.
197 #[must_use]
198 pub fn from_canonical_bytes(bytes: &[u8]) -> Self {
199 let digest = blake3::hash(bytes);
200 Self::wrap_blake3_digest(*digest.as_bytes())
201 }
202
203 /// Compute the content id of bytes, **first verifying they are canonical
204 /// dag-cbor**.
205 ///
206 /// This is the opt-in, *checked* sibling of
207 /// [`from_canonical_bytes`](Self::from_canonical_bytes). It is for callers
208 /// minting an id from bytes they did **not** canonicalize themselves
209 /// (foreign, untrusted, hand-rolled, or stored input) and who therefore
210 /// cannot rely on the precondition by construction. It closes the silent
211 /// integrity hole the fast primitive leaves open, at the cost of a decode +
212 /// re-encode + compare on every call — pay it only when byte provenance is
213 /// not yours.
214 ///
215 /// The check is a **round-trip**: decode the bytes as an
216 /// [`Ipld`](ipld_core::ipld::Ipld) value, re-encode that value via
217 /// [`to_canonical_dagcbor`](crate::canonical::to_canonical_dagcbor), and
218 /// require the re-encoding to equal the input byte-for-byte. Because the
219 /// dag-cbor codec is canonical by construction (strict key order,
220 /// definite-length, smallest-form integers — see
221 /// [`canonical`](crate::canonical)), equality proves the input was *already*
222 /// the unique canonical encoding of that value. On success the id is computed
223 /// over the (canonical) input bytes, so it is **byte-identical** to what
224 /// [`from_canonical_bytes`](Self::from_canonical_bytes) would return for the
225 /// same bytes — the check changes the fallibility, never the emitted id.
226 ///
227 /// # Errors
228 ///
229 /// - [`ContentError::DecodingError`] if `bytes` are not dag-cbor at all.
230 /// - [`ContentError::NonCanonical`] if `bytes` decode but are *not* the
231 /// canonical encoding (wrong map-key order, indefinite-length items,
232 /// non-smallest integers, …) — i.e. re-encoding differs from the input.
233 /// - [`ContentError::EncodingError`] in the unlikely event the decoded value
234 /// cannot be re-encoded.
235 pub fn from_canonical_bytes_checked(bytes: &[u8]) -> Result<Self, ContentError> {
236 // 1. Decode to the generic Ipld value. Non-dag-cbor garbage fails here.
237 let value: ipld_core::ipld::Ipld = crate::canonical::from_canonical_dagcbor(bytes)?;
238 // 2. Re-encode canonically. The codec emits the *unique* canonical form.
239 let reencoded = crate::canonical::to_canonical_dagcbor(&value)?;
240 // 3. The input was canonical iff it equals its own canonical re-encoding.
241 if reencoded != bytes {
242 return Err(ContentError::NonCanonical);
243 }
244 // The bytes are proven canonical: minting over them is identical to the
245 // unchecked primitive, so reuse it (no second decode/encode).
246 Ok(Self::from_canonical_bytes(bytes))
247 }
248
249 /// Wrap an **already-computed** 32-byte BLAKE3 content digest as a
250 /// `ContentId` — **without hashing**.
251 ///
252 /// This is a deliberately narrow, *unchecked* escape hatch for
253 /// **BLAKE3-native upstreams** that have already hashed their content and
254 /// hold only the 32-byte digest (a signature, an address) — not the
255 /// original canonical bytes. For them,
256 /// [`from_canonical_bytes`](Self::from_canonical_bytes) is not just
257 /// wasteful, it is *impossible*: there are no bytes left to hash. This
258 /// constructor takes the digest they already have and wraps it directly:
259 /// `Multihash::wrap(0x1e, digest)` → `Cid::new_v1(0x71, mh)`. No BLAKE3
260 /// step runs, and the result is byte-identical to what
261 /// [`from_canonical_bytes`](Self::from_canonical_bytes) would have produced
262 /// *had the caller hashed the real content correctly*.
263 ///
264 /// The `[u8; 32]` argument makes the 32-byte length a **compile-time**
265 /// guarantee: it is impossible to call with a wrong-length digest, so no
266 /// runtime length check, no fallible signature, and no new error variant
267 /// are needed. Callers holding a `&[u8]` convert with `try_into()` and own
268 /// that fallibility.
269 ///
270 /// # ⚠️ UNCHECKED ESCAPE HATCH — CALLER ASSERTS THE PRECONDITION ⚠️
271 ///
272 /// This constructor **does not hash and does not canonicalize**. It trusts
273 /// the caller completely. By calling it you **assert** that `digest` is
274 /// exactly `BLAKE3` over the value's **canonical dag-cbor** bytes — the same
275 /// input domain [`from_canonical_bytes`](Self::from_canonical_bytes) would
276 /// hash.
277 ///
278 /// If that assertion is false — the digest was computed over non-canonical
279 /// bytes, over a different encoding, with a different hash, or is simply
280 /// arbitrary — the result is a `ContentId` that **names content nothing
281 /// actually hashed**. Such an id is silently wrong: there is no error, and
282 /// verifying it against the real bytes returns `Ok(false)`, never an `Err`.
283 ///
284 /// **If you have the content bytes, use
285 /// [`from_canonical_bytes`](Self::from_canonical_bytes) instead** — it
286 /// hashes them for you and cannot be wrong this way. Do *not* reach for
287 /// this constructor merely to avoid a hash; reach for it only when you
288 /// genuinely hold a precomputed, canonical-dag-cbor BLAKE3 digest and the
289 /// content itself is gone.
290 ///
291 /// # Motivation
292 ///
293 /// The kyln-lore `address.rs` bridge (`blake3_digest_to_content_id` /
294 /// `signature_to_content_id`) does exactly this: a lore revision signature
295 /// *is* a raw 32-byte BLAKE3 digest of the content, so it becomes a kyln
296 /// `ContentId` by wrapping it — minus the `blake3::hash` step, because lore
297 /// already hashed the content. That bridge is what makes a projected git
298 /// commit's provenance note `content_id` *equal* the originating lore
299 /// revision signature. kyln's adoption (kyln #303) and any other
300 /// BLAKE3-native source needs this primitive so a system that already
301 /// hashed with BLAKE3 gets an *exact* `ContentId` with no re-hash.
302 ///
303 /// # Panics
304 ///
305 /// Does not panic. A 32-byte digest always fits the multihash's 64-byte
306 /// capacity, so the `wrap` call cannot fail.
307 ///
308 /// # Deprecated — the codec was a guess
309 ///
310 /// This door stamps the `dag-cbor` (`0x71`) codec on a digest it **cannot
311 /// know** came from canonical dag-cbor. Every real caller (kyln-lore
312 /// signatures, bare `blake3::hash` outputs, `blake3:<hex>` digests) held a
313 /// digest of *opaque bytes*, for which the honest identity is
314 /// [`RawContentId::from_blake3_digest`](crate::RawContentId::from_blake3_digest)
315 /// (CIDv1 · `raw` · BLAKE3) — byte-identical to those systems' existing raw
316 /// CIDs. If you genuinely hold a digest of canonical dag-cbor and the value
317 /// is gone, say so explicitly with
318 /// [`from_dag_cbor_digest`](Self::from_dag_cbor_digest). See decision record
319 /// `docs/adr/0003` (question 5).
320 #[deprecated(
321 since = "0.1.1",
322 note = "use RawContentId::from_blake3_digest for a digest of opaque bytes (the honest \
323 profile), or ContentId::from_dag_cbor_digest when the digest is known to be \
324 over canonical dag-cbor"
325 )]
326 #[must_use]
327 pub fn from_blake3_content_digest(digest: [u8; BLAKE3_DIGEST_LEN]) -> Self {
328 Self::wrap_blake3_digest(digest)
329 }
330
331 /// Wrap a precomputed 32-byte BLAKE3 digest **of canonical dag-cbor bytes**
332 /// as a `ContentId`, with no re-hash.
333 ///
334 /// The name asserts the precondition: the digest MUST be BLAKE3 over the
335 /// canonical dag-cbor encoding of a value — the same bytes
336 /// [`from_canonical_bytes`](Self::from_canonical_bytes) would have hashed.
337 /// This function cannot check that; a digest of anything else mints an id
338 /// whose `dag-cbor` codec is a lie (see the precondition discussion on
339 /// [`from_canonical_bytes`](Self::from_canonical_bytes)). If your digest is
340 /// over opaque bytes, you want
341 /// [`RawContentId::from_blake3_digest`](crate::RawContentId::from_blake3_digest).
342 ///
343 /// Emits exactly the bytes [`from_canonical_bytes`](Self::from_canonical_bytes)
344 /// emits for the same digest (one shared construction point), so
345 /// `from_dag_cbor_digest(blake3(c)) == from_canonical_bytes(c)`.
346 ///
347 /// # Panics
348 ///
349 /// Does not panic: a 32-byte digest always fits the multihash's 64-byte
350 /// capacity.
351 #[must_use]
352 pub fn from_dag_cbor_digest(digest: [u8; BLAKE3_DIGEST_LEN]) -> Self {
353 Self::wrap_blake3_digest(digest)
354 }
355
356 /// Wrap a 32-byte BLAKE3 digest as a [`ContentId`]: the frozen tail shared
357 /// by [`from_canonical_bytes`] (which hashes first) and
358 /// [`from_blake3_content_digest`] (which does not). Keeping the
359 /// `Multihash::wrap(0x1e, ..)` + `Cid::new_v1(0x71, ..)` construction in
360 /// exactly one place guarantees both doors emit **byte-identical** CIDs for
361 /// the same digest — the property the no-rehash bridge depends on.
362 fn wrap_blake3_digest(digest: [u8; BLAKE3_DIGEST_LEN]) -> Self {
363 let mh = Multihash::wrap(BLAKE3_HASH_CODE, &digest)
364 .expect("BLAKE3 digest is 32 bytes and always fits a 64-byte multihash");
365 ContentId(Cid::new_v1(DAG_CBOR_CODEC, mh))
366 }
367
368 /// Borrow the underlying IPLD [`Cid`].
369 #[must_use]
370 pub fn as_cid(&self) -> &Cid {
371 &self.0
372 }
373
374 /// The raw 32-byte BLAKE3 content digest, copied out of the multihash.
375 ///
376 /// This is the **bare hash** — *not* the CID envelope. It is the sovereign
377 /// hash an adopter joins on across systems (the same digest a BLAKE3-native
378 /// upstream would hand to [`from_blake3_content_digest`](Self::from_blake3_content_digest)).
379 ///
380 /// The length is a **frozen, enforced invariant**: every `ContentId` carries
381 /// exactly `BLAKE3_DIGEST_LEN` (32) digest bytes (see the
382 /// [CID-parameters contract](ContentId#cid-parameters-frozen-at-010)), so
383 /// this accessor is infallible and returns a fixed-size array. The copy
384 /// (`try_into`) can never fail; the `expect` is unreachable for *any*
385 /// `ContentId` — every ingress path (`from_bytes`, `FromStr`, `TryFrom<Cid>`,
386 /// binary `Deserialize`) validates the profile, so an off-profile CID can never
387 /// become a `ContentId` and reach this method.
388 ///
389 /// Part of the **frozen presentation contract** — see the
390 /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
391 #[must_use]
392 pub fn digest_bytes(&self) -> [u8; BLAKE3_DIGEST_LEN] {
393 self.0
394 .hash()
395 .digest()
396 .try_into()
397 .expect("a ContentId multihash always carries a 32-byte BLAKE3 digest")
398 }
399
400 /// Lowercase hex of the raw 32-byte BLAKE3 digest: 64 hex chars, **no**
401 /// `0x` or multibase prefix.
402 ///
403 /// This is the **"bare-digest-hex"** convention (the shortest, hash-only
404 /// "hex" form an adopter reaches for, e.g. kyln's `to_hex()`). It is hex of
405 /// [`digest_bytes`](Self::digest_bytes) — *not* hex of the full CID. The
406 /// three "hex" forms in the wild are mutually incompatible; this crate names
407 /// each so they cannot be confused:
408 ///
409 /// - **bare-digest-hex** = this method = `digest_hex()` (64 chars, hash
410 /// only).
411 /// - **full-CID-bytes-hex** = `hex::encode(id.to_bytes())` — the whole CID
412 /// envelope (version + codec + multihash header + digest) as base16.
413 /// *Deliberately not provided as a method* (see the
414 /// [presentation contract](ContentId#presentation-contract-frozen-at-010));
415 /// a caller who truly needs it hex-encodes [`to_bytes`](Self::to_bytes)
416 /// and owns that choice.
417 /// - **multibase base32-lower** = the [`Display`](fmt::Display) /
418 /// [`to_string`](ToString::to_string) string (`b…`), the IPLD-canonical
419 /// text form.
420 ///
421 /// Part of the **frozen presentation contract** — see the
422 /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
423 #[must_use]
424 pub fn digest_hex(&self) -> String {
425 let digest = self.digest_bytes();
426 let mut s = String::with_capacity(digest.len() * 2);
427 for b in digest {
428 // Hand-rolled 32->64 lowercase hex: avoids taking a `hex` crate
429 // dependency for a byte-frozen surface (issue #6: "hand-roll
430 // 32->64 hex to avoid the dep — implementer's call").
431 s.push(char::from_digit((b >> 4) as u32, 16).expect("nibble < 16 is a hex digit"));
432 s.push(char::from_digit((b & 0x0f) as u32, 16).expect("nibble < 16 is a hex digit"));
433 }
434 s
435 }
436
437 /// Encode this id as its canonical CID binary form.
438 ///
439 /// This is the full **CID envelope**: version + codec (`0x71`) + multihash
440 /// header + digest — *not* the bare hash. It round-trips through
441 /// [`from_bytes`](Self::from_bytes). For the hex of *this* form ("full-CID-
442 /// bytes-hex"), a caller hex-encodes the result explicitly; the crate
443 /// deliberately does not bless a `cid_hex()` method (see the
444 /// [presentation contract](ContentId#presentation-contract-frozen-at-010)).
445 ///
446 /// Part of the **frozen presentation contract** — see the
447 /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
448 #[must_use]
449 pub fn to_bytes(&self) -> Vec<u8> {
450 self.0.to_bytes()
451 }
452
453 /// Parse an id from its canonical CID binary form.
454 ///
455 /// # Errors
456 ///
457 /// Returns [`ContentError::InvalidCid`] if the bytes are not a valid CID.
458 pub fn from_bytes(bytes: &[u8]) -> Result<Self, ContentError> {
459 let cid = Cid::read_bytes(bytes).map_err(|e| ContentError::InvalidCid {
460 reason: e.to_string(),
461 source: Box::new(e),
462 })?;
463 validate_profile(&cid)?;
464 Ok(ContentId(cid))
465 }
466}
467
468/// Reject any [`Cid`] that is not this crate's frozen profile: CIDv1 + dag-cbor
469/// (`0x71`) + BLAKE3 (`0x1e`) + a 32-byte digest.
470///
471/// **Every** ingress path — [`from_bytes`](ContentId::from_bytes), the
472/// [`FromStr`] impl, [`TryFrom<Cid>`], and the binary/IPLD [`Deserialize`] —
473/// routes through this, so a parsed / deserialized / converted `ContentId` carries
474/// the same invariant a *minted* one does. That is what makes the presentation
475/// accessors ([`digest_bytes`](ContentId::digest_bytes) etc.) total: a foreign CID
476/// (a CIDv0, a non-dag-cbor codec, a SHA-256 hash, a non-32-byte digest) can never
477/// become a `ContentId`, so it can never reach an accessor and panic.
478fn validate_profile(cid: &Cid) -> Result<(), ContentError> {
479 if cid.version() != Version::V1 {
480 return Err(ContentError::InvalidCidProfile {
481 reason: format!("expected CIDv1, got {:?}", cid.version()),
482 });
483 }
484 if cid.codec() != DAG_CBOR_CODEC {
485 return Err(ContentError::InvalidCidProfile {
486 reason: format!(
487 "expected dag-cbor codec 0x{DAG_CBOR_CODEC:x}, got 0x{:x}",
488 cid.codec()
489 ),
490 });
491 }
492 if cid.hash().code() != BLAKE3_HASH_CODE {
493 return Err(ContentError::InvalidCidProfile {
494 reason: format!(
495 "expected BLAKE3 multihash 0x{BLAKE3_HASH_CODE:x}, got 0x{:x}",
496 cid.hash().code()
497 ),
498 });
499 }
500 let digest_len = cid.hash().digest().len();
501 if digest_len != BLAKE3_DIGEST_LEN {
502 return Err(ContentError::InvalidCidProfile {
503 reason: format!("expected a {BLAKE3_DIGEST_LEN}-byte digest, got {digest_len} bytes"),
504 });
505 }
506 Ok(())
507}
508
509impl TryFrom<Cid> for ContentId {
510 type Error = ContentError;
511
512 /// Wrap a [`Cid`] **iff** it is this crate's frozen profile; a foreign CID is
513 /// rejected with [`ContentError::InvalidCidProfile`].
514 ///
515 /// This is `TryFrom`, not `From`, on purpose: an infallible `From<Cid>` would
516 /// let an off-profile CID become a `ContentId` and later panic in a
517 /// presentation accessor. (The outward [`From<ContentId>`] for [`Cid`] stays
518 /// infallible — dropping the newtype is always safe.)
519 fn try_from(cid: Cid) -> Result<Self, Self::Error> {
520 validate_profile(&cid)?;
521 Ok(ContentId(cid))
522 }
523}
524
525impl From<ContentId> for Cid {
526 fn from(id: ContentId) -> Self {
527 id.0
528 }
529}
530
531impl fmt::Display for ContentId {
532 /// Render as multibase **base32-lower** (the `b…` CIDv1 string).
533 ///
534 /// This is the crate's **canonical text form** and is **frozen** for the
535 /// `0.1.x` line — see the
536 /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
537 /// It is the IPLD-canonical CID string and the same text the human-readable
538 /// serde form emits. It is the inverse of [`FromStr`] for base32-lower:
539 /// `id.to_string().parse() == Ok(id)` is a tested, frozen round-trip. A unit
540 /// test and the conformance vectors pin the exact string for fixed inputs,
541 /// so any drift in the inner CID's rendering fails loudly. Changing this
542 /// form is a major version bump.
543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 fmt::Display::fmt(&self.0, f)
545 }
546}
547
548impl FromStr for ContentId {
549 type Err = ContentError;
550
551 /// Parse an id from a multibase CID string.
552 ///
553 /// The frozen contract is narrow: `FromStr` is the **inverse of
554 /// [`Display`](fmt::Display)** for the base32-lower form, and that round-trip
555 /// (`id.to_string().parse() == Ok(id)`) is the part pinned by the
556 /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
557 /// As a **convenience (not a contract)** this also accepts other valid
558 /// multibases (base58, base16, …), since the inner [`Cid::from_str`] does;
559 /// that tolerance is *not* frozen and may be tightened later without
560 /// breaking the frozen base32-lower round-trip — so do not depend on parsing
561 /// non-base32 CID strings.
562 fn from_str(s: &str) -> Result<Self, Self::Err> {
563 let cid = Cid::from_str(s).map_err(|e| ContentError::InvalidCid {
564 reason: e.to_string(),
565 source: Box::new(e),
566 })?;
567 validate_profile(&cid)?;
568 Ok(ContentId(cid))
569 }
570}
571
572impl Serialize for ContentId {
573 /// Serialize per the frozen serde contract: the multibase base32 string in
574 /// human-readable formats (e.g. `serde_json`, TOML), the inner [`Cid`] (a
575 /// dag-cbor tag-42 link) in binary/IPLD formats.
576 ///
577 /// This representation is **frozen** for the `0.1.x` line; see the
578 /// [type-level serde contract](ContentId#serde-representation-frozen-at-010).
579 /// Changing it is a major version bump.
580 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
581 if serializer.is_human_readable() {
582 serializer.serialize_str(&self.to_string())
583 } else {
584 self.0.serialize(serializer)
585 }
586 }
587}
588
589impl<'de> Deserialize<'de> for ContentId {
590 /// Deserialize per the frozen serde contract: a multibase base32 string from
591 /// human-readable formats, the inner [`Cid`] (a dag-cbor tag-42 link) from
592 /// binary/IPLD formats.
593 ///
594 /// The accepted representation is **frozen** for the `0.1.x` line; see the
595 /// [type-level serde contract](ContentId#serde-representation-frozen-at-010).
596 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
597 if deserializer.is_human_readable() {
598 let s = String::deserialize(deserializer)?;
599 s.parse::<ContentId>()
600 .map_err(<D::Error as serde::de::Error>::custom)
601 } else {
602 // Binary/IPLD: a decoded tag-42 link is an arbitrary CID until proven
603 // on-profile — reject a foreign link here, not later in an accessor.
604 let cid = Cid::deserialize(deserializer)?;
605 validate_profile(&cid).map_err(<D::Error as serde::de::Error>::custom)?;
606 Ok(ContentId(cid))
607 }
608 }
609}
610
611#[cfg(test)]
612mod cid_param_lock_tests {
613 //! Locks the frozen v1 CID parameters (issue #4) so they cannot drift
614 //! silently. These assertions live in the `content_id` module itself, next
615 //! to the definitions, so the freeze is self-evident at the source. They use
616 //! **literal** values (`0x71`, `0x1e`, `V1`, `32`), not the crate constants,
617 //! so an accidental edit to a `const` is caught by a failing test rather
618 //! than silently followed.
619
620 use super::{ContentId, BLAKE3_DIGEST_LEN, BLAKE3_HASH_CODE, DAG_CBOR_CODEC};
621 use ipld_core::cid::Version;
622
623 /// A freshly produced id, from the empty-map canonical dag-cbor (`0xa0`).
624 /// This is the documented fixed input also used by the embedded-link golden
625 /// and the `empty_map` conformance vector, so the three pins agree.
626 fn empty_map_id() -> ContentId {
627 ContentId::from_canonical_bytes(&[0xa0])
628 }
629
630 #[test]
631 fn cid_params_are_literally_v1_dagcbor_blake3_32() {
632 // Assert against LITERALS, not the constants: editing a `const` must
633 // break this test, not be silently followed.
634 let id = empty_map_id();
635 let cid = id.as_cid();
636 assert_eq!(cid.version(), Version::V1, "CID version is frozen at V1");
637 assert_eq!(cid.codec(), 0x71, "codec is frozen at dag-cbor (0x71)");
638 assert_eq!(
639 cid.hash().code(),
640 0x1e,
641 "multihash is frozen at BLAKE3 (0x1e)"
642 );
643 assert_eq!(
644 cid.hash().digest().len(),
645 32,
646 "BLAKE3 digest length is frozen at 32 bytes"
647 );
648 }
649
650 #[test]
651 fn frozen_constants_hold_their_documented_values() {
652 // The public/private constants must equal the frozen literals, so the
653 // doc and the re-exported surface cannot drift from the contract.
654 assert_eq!(DAG_CBOR_CODEC, 0x71);
655 assert_eq!(BLAKE3_HASH_CODE, 0x1e);
656 assert_eq!(BLAKE3_DIGEST_LEN, 32);
657 }
658
659 #[test]
660 fn cid_binary_prefix_is_frozen() {
661 // The leading bytes of the CIDv1 binary form encode the frozen shape:
662 // 0x01 = CIDv1
663 // 0x71 = multicodec dag-cbor
664 // 0x1e = multihash code BLAKE3
665 // 0x20 = digest length 32 (varint; 0x20 == 32)
666 // Pinning the prefix means the on-wire identifier head cannot drift even
667 // if the digest payload changes.
668 let bytes = empty_map_id().to_bytes();
669 assert_eq!(
670 &bytes[..4],
671 &[0x01, 0x71, 0x1e, 0x20],
672 "CIDv1/dag-cbor/BLAKE3/len-32 binary prefix is frozen"
673 );
674 assert_eq!(
675 bytes.len(),
676 4 + BLAKE3_DIGEST_LEN,
677 "CID binary form is the 4-byte prefix plus the 32-byte digest"
678 );
679 }
680}
681
682#[cfg(test)]
683#[allow(deprecated)] // pins the deprecated door's behavior until it is removed
684mod no_rehash_digest_tests {
685 //! Tests for [`ContentId::from_blake3_content_digest`] (issue #10) and its
686 //! explicit successor [`ContentId::from_dag_cbor_digest`] (#84): the
687 //! guarded, no-rehash escape hatch that wraps an already-computed BLAKE3
688 //! content digest as a `ContentId` **without hashing it again**. These pin
689 //! both the produced CID shape and — critically — the *no-rehash invariant*
690 //! that distinguishes this door from `from_canonical_bytes` (which hashes).
691
692 use super::{ContentId, BLAKE3_DIGEST_LEN};
693
694 /// #84: `from_dag_cbor_digest` is the explicitly-named successor and emits
695 /// exactly the bytes the deprecated door emits (one shared construction
696 /// point), so migrating callers changes no ids.
697 #[test]
698 fn from_dag_cbor_digest_is_byte_identical_to_deprecated_door() {
699 let d = *blake3::hash(b"any canonical dag-cbor").as_bytes();
700 assert_eq!(
701 ContentId::from_dag_cbor_digest(d),
702 ContentId::from_blake3_content_digest(d)
703 );
704 assert_eq!(
705 ContentId::from_dag_cbor_digest(d),
706 ContentId::from_canonical_bytes(b"any canonical dag-cbor")
707 );
708 }
709 use ipld_core::cid::Version;
710
711 /// A non-trivial, fixed 32-byte digest (`[1, 2, 3, ..., 32]`). Deliberately
712 /// not all-zero so that the no-rehash invariant below is a meaningful test.
713 fn sample_digest() -> [u8; BLAKE3_DIGEST_LEN] {
714 let mut d = [0u8; BLAKE3_DIGEST_LEN];
715 for (i, b) in d.iter_mut().enumerate() {
716 *b = (i as u8) + 1;
717 }
718 d
719 }
720
721 #[test]
722 fn produces_v1_dagcbor_blake3_cid_carrying_the_exact_digest() {
723 // Assert against LITERALS, matching the frozen-parameter lock tests.
724 let d = sample_digest();
725 let id = ContentId::from_blake3_content_digest(d);
726 let cid = id.as_cid();
727 assert_eq!(cid.version(), Version::V1, "must be a CIDv1");
728 assert_eq!(cid.codec(), 0x71, "codec must be dag-cbor (0x71)");
729 assert_eq!(cid.hash().code(), 0x1e, "multihash must be BLAKE3 (0x1e)");
730 assert_eq!(
731 cid.hash().digest().len(),
732 BLAKE3_DIGEST_LEN,
733 "digest must be 32 bytes"
734 );
735 // The wrapped digest bytes must be EXACTLY the input — the whole point
736 // of a no-rehash door is that the digest passes through untouched.
737 assert_eq!(
738 cid.hash().digest(),
739 &d,
740 "the CID must carry the caller's digest verbatim"
741 );
742 }
743
744 #[test]
745 fn does_not_rehash_the_digest() {
746 // THE CRITICAL INVARIANT (must-fix gate): for a non-trivial digest `d`,
747 // wrapping it must NOT equal hashing it. `from_canonical_bytes(&d)`
748 // computes BLAKE3(d) — a second hash — whereas
749 // `from_blake3_content_digest(d)` wraps `d` as-is. If these were ever
750 // equal, the constructor would secretly be re-hashing.
751 let d = sample_digest();
752 let wrapped = ContentId::from_blake3_content_digest(d);
753 let hashed_again = ContentId::from_canonical_bytes(&d);
754 assert_ne!(
755 wrapped, hashed_again,
756 "from_blake3_content_digest must NOT re-hash: wrapping d must differ \
757 from BLAKE3(d)"
758 );
759 // Tighter: the wrapped id's digest is `d` itself, while the re-hashed
760 // id's digest is BLAKE3(d) — explicitly different bytes.
761 assert_eq!(wrapped.as_cid().hash().digest(), &d);
762 assert_eq!(
763 hashed_again.as_cid().hash().digest(),
764 blake3::hash(&d).as_bytes(),
765 );
766 }
767
768 #[test]
769 fn digest_survives_a_byte_roundtrip() {
770 // Building from a digest, serializing to CID bytes, and reading the
771 // digest back must recover the original `d` exactly.
772 let d = sample_digest();
773 let id = ContentId::from_blake3_content_digest(d);
774
775 // Via the live CID handle.
776 assert_eq!(id.as_cid().hash().digest(), &d);
777
778 // Via the full CID binary form: tail 32 bytes are the digest, and a
779 // from_bytes parse lands on the same id.
780 let bytes = id.to_bytes();
781 assert_eq!(
782 &bytes[bytes.len() - BLAKE3_DIGEST_LEN..],
783 &d,
784 "the trailing 32 bytes of the CID binary form are the digest"
785 );
786 let reparsed = ContentId::from_bytes(&bytes).expect("CID bytes must reparse");
787 assert_eq!(reparsed, id);
788 assert_eq!(reparsed.as_cid().hash().digest(), &d);
789 }
790
791 #[test]
792 fn converges_with_from_canonical_bytes_when_caller_hashes_correctly() {
793 // The two doors meet in the middle: if a caller hashes the real content
794 // with BLAKE3 and feeds the digest here, they get the SAME id as
795 // hashing the content via from_canonical_bytes. This is the bridge
796 // property the no-rehash primitive exists to provide.
797 for content in [
798 &b""[..],
799 &[0xa0][..], // empty-map canonical dag-cbor
800 b"the quick brown fox",
801 b"\x00\x01\x02\x03 arbitrary canonical bytes",
802 ] {
803 let digest: [u8; BLAKE3_DIGEST_LEN] = blake3::hash(content).into();
804 let via_digest = ContentId::from_blake3_content_digest(digest);
805 let via_hash = ContentId::from_canonical_bytes(content);
806 assert_eq!(
807 via_digest, via_hash,
808 "from_blake3_content_digest(blake3(x)) must equal \
809 from_canonical_bytes(x)"
810 );
811 }
812 }
813}
814
815#[cfg(test)]
816mod presentation_tests {
817 //! Tests for the **frozen presentation contract** (issue #6): the named,
818 //! separately-frozen string/byte forms a `ContentId` emits. These pin the
819 //! exact values for fixed inputs so any drift in the inner CID's rendering,
820 //! the multihash digest, or the hex encoder fails loudly. The cross-language
821 //! `tests/vectors.json` gate additionally pins `digest_hex` (and the base32
822 //! string + CID bytes) so Python parity is enforced too; these in-crate
823 //! tests assert the *accessor semantics* that the vectors cannot (the array
824 //! return, the no-prefix rule, the Display/FromStr round-trip).
825
826 use super::{ContentId, BLAKE3_DIGEST_LEN};
827
828 /// The documented fixed input: the empty-map canonical dag-cbor (`0xa0`).
829 /// This is the same id as the `empty_map` conformance vector and the
830 /// embedded-link golden, so all the pins agree.
831 fn empty_map_id() -> ContentId {
832 ContentId::from_canonical_bytes(&[0xa0])
833 }
834
835 /// The frozen `empty_map` digest (the BLAKE3 of `0xa0`), as bare-digest-hex.
836 /// Equals the tail of the `empty_map` vector's `content_id_bytes_hex`
837 /// (`01711e20` CID prefix, then this 64-char digest).
838 const EMPTY_MAP_DIGEST_HEX: &str =
839 "1f94cbf313b3ce23257a7251ea0fc95a24556ea611e4f8f475e549971baedb02";
840
841 #[test]
842 fn display_is_frozen_base32_lower() {
843 // The canonical text form is multibase base32-lower (`b…`), frozen.
844 let id = empty_map_id();
845 let s = id.to_string();
846 assert_eq!(
847 s, "bafyr4ia7stf7ge5tzyrsk6tskhva7sk2erkw5jqr4t4pi5pfjglrxlw3ai",
848 "Display must be the frozen base32-lower CID string"
849 );
850 assert!(s.starts_with('b'), "base32-lower multibase prefix is 'b'");
851 }
852
853 #[test]
854 fn display_fromstr_roundtrip_is_frozen() {
855 // The frozen guarantee: Display -> FromStr lands back on the same id.
856 let id = empty_map_id();
857 let parsed: ContentId = id.to_string().parse().expect("base32 string must reparse");
858 assert_eq!(parsed, id, "Display -> FromStr must round-trip");
859 }
860
861 #[test]
862 fn digest_bytes_is_the_raw_32_byte_blake3_hash() {
863 let id = empty_map_id();
864 let d = id.digest_bytes();
865 // It is a fixed-size 32-byte array...
866 assert_eq!(d.len(), BLAKE3_DIGEST_LEN);
867 // ...equal to the multihash's digest (the bare hash, no envelope)...
868 assert_eq!(&d[..], id.as_cid().hash().digest());
869 // ...and equal to an independent BLAKE3 of the input bytes.
870 assert_eq!(d, *blake3::hash(&[0xa0]).as_bytes());
871 }
872
873 #[test]
874 fn digest_hex_is_frozen_64_char_lower_hex_no_prefix() {
875 let id = empty_map_id();
876 let h = id.digest_hex();
877 // Exactly 64 lowercase hex chars, no `0x` prefix. (A hex digest may
878 // legitimately begin with the digit `b`; that is NOT the base32
879 // multibase prefix, which belongs only to the Display string.)
880 assert_eq!(h.len(), 64, "digest_hex is 64 chars (32 bytes)");
881 assert!(!h.starts_with("0x"), "digest_hex carries no 0x prefix");
882 assert!(
883 h.chars()
884 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
885 "digest_hex is lowercase hex only"
886 );
887 // The exact frozen value for the empty map.
888 assert_eq!(
889 h, EMPTY_MAP_DIGEST_HEX,
890 "frozen empty-map digest_hex drifted"
891 );
892 }
893
894 #[test]
895 fn digest_hex_is_hex_of_digest_bytes_not_of_the_cid() {
896 // digest_hex names convention #1 (bare-digest-hex): it is hex of the
897 // bare digest, and is STRICTLY SHORTER than full-CID-bytes-hex
898 // (`hex::encode(to_bytes())`), which carries the 4-byte CID prefix too.
899 let id = empty_map_id();
900 let digest = id.digest_bytes();
901 let mut expected = String::new();
902 for b in digest {
903 expected.push_str(&format!("{b:02x}"));
904 }
905 assert_eq!(id.digest_hex(), expected);
906
907 // The full-CID-bytes-hex (the deliberately-unmethodd convention #2) is
908 // longer and ENDS WITH the digest hex, after the CID envelope prefix.
909 let cid_bytes_hex: String = id.to_bytes().iter().map(|b| format!("{b:02x}")).collect();
910 assert!(
911 cid_bytes_hex.ends_with(&id.digest_hex()),
912 "the full-CID-bytes-hex ends with the bare-digest-hex"
913 );
914 assert!(
915 cid_bytes_hex.len() > id.digest_hex().len(),
916 "full-CID-bytes-hex is longer than bare-digest-hex (it has the envelope)"
917 );
918 // Concretely: the 4-byte CIDv1/dag-cbor/BLAKE3/len-32 prefix, then digest.
919 assert_eq!(cid_bytes_hex, format!("01711e20{}", id.digest_hex()));
920 }
921}
922
923#[cfg(test)]
924mod checked_input_tests {
925 //! Tests for [`ContentId::from_canonical_bytes_checked`] (issue #5): the
926 //! opt-in, round-trip-validating sibling of the fast `from_canonical_bytes`
927 //! primitive. They pin the four behaviors the issue's AC names: (a) canonical
928 //! bytes accepted and yielding the *same* id as the unchecked door, (b)
929 //! non-canonical-but-valid CBOR rejected, (c) non-dag-cbor garbage rejected,
930 //! and (d) a regression test documenting that the *unchecked* primitive still
931 //! happily mints an id for non-canonical bytes (the precondition is real and
932 //! unenforced by design).
933
934 use super::ContentId;
935 use crate::canonical::to_canonical_dagcbor;
936 use crate::error::ContentError;
937
938 #[test]
939 fn checked_accepts_canonical_bytes_and_matches_the_unchecked_door() {
940 // The always-canonical path: canonicalize a value, then both doors must
941 // agree on the id (the check changes fallibility, never the bytes).
942 for value in [
943 &serde_json::json!({}),
944 &serde_json::json!({"alpha": 1, "zeta": 26}),
945 &serde_json::json!({"name": "hello", "n": [1, 2, 3], "nested": {"a": 1}}),
946 &serde_json::json!([1, "two", [3, 4], null]),
947 ] {
948 // Drive canonical bytes through Ipld so the encoding is the codec's
949 // canonical form, then assert the two doors converge.
950 let ipld: ipld_core::ipld::Ipld =
951 serde_json::from_value((*value).clone()).expect("json -> ipld");
952 let canonical = to_canonical_dagcbor(&ipld).expect("encode canonical");
953
954 let via_checked =
955 ContentId::from_canonical_bytes_checked(&canonical).expect("canonical accepted");
956 let via_unchecked = ContentId::from_canonical_bytes(&canonical);
957 assert_eq!(
958 via_checked, via_unchecked,
959 "checked(canonical) must equal the unchecked id for the same bytes"
960 );
961 }
962 }
963
964 #[test]
965 fn always_canonical_path_equals_from_canonical_bytes_of_to_canonical_dagcbor() {
966 // The exact identity the issue calls out: the always-canonical path
967 // (to_canonical_dagcbor then mint) and the checked door produce the same
968 // id, and that id is from_canonical_bytes(to_canonical_dagcbor(x)).
969 let ipld: ipld_core::ipld::Ipld = serde_json::from_value(serde_json::json!(
970 {"alpha": 1, "zeta": 26, "list": [true, false, null]}
971 ))
972 .expect("json -> ipld");
973
974 let canonical = to_canonical_dagcbor(&ipld).expect("encode canonical");
975 let from_unchecked = ContentId::from_canonical_bytes(&canonical);
976 let from_checked =
977 ContentId::from_canonical_bytes_checked(&canonical).expect("canonical accepted");
978
979 assert_eq!(
980 from_checked, from_unchecked,
981 "from_canonical_bytes_checked(to_canonical_dagcbor(x)) == \
982 from_canonical_bytes(to_canonical_dagcbor(x))"
983 );
984 }
985
986 #[test]
987 fn checked_rejects_non_canonical_but_valid_cbor() {
988 // A map with two string keys encoded in NON-canonical (descending) key
989 // order. dag-cbor canonical order is by length-then-bytewise, so {"a",
990 // "bb"} canonical is a2 [a] .. [bb]; we hand-build the reverse order.
991 // Hand-built CBOR:
992 // a2 map(2)
993 // 62 6262 text(2) "bb" <- emitted FIRST (non-canonical)
994 // 01 1
995 // 61 61 text(1) "a"
996 // 02 2
997 let non_canonical = [0xa2, 0x62, 0x62, 0x62, 0x01, 0x61, 0x61, 0x02];
998
999 // Sanity: it IS valid CBOR (decodes fine), so this exercises the
1000 // re-encode-compare path, not the decode path.
1001 let decoded: ipld_core::ipld::Ipld =
1002 crate::canonical::from_canonical_dagcbor(&non_canonical)
1003 .expect("non-canonical bytes are still valid CBOR and decode");
1004 // And its canonical re-encoding genuinely differs (proving our fixture is
1005 // really non-canonical, not an accidental canonical form).
1006 let recanon = to_canonical_dagcbor(&decoded).expect("re-encode");
1007 assert_ne!(
1008 &recanon[..],
1009 &non_canonical[..],
1010 "fixture must actually be non-canonical"
1011 );
1012
1013 let err = ContentId::from_canonical_bytes_checked(&non_canonical)
1014 .expect_err("non-canonical CBOR must be rejected");
1015 assert!(
1016 matches!(err, ContentError::NonCanonical),
1017 "non-canonical valid CBOR must map to ContentError::NonCanonical, got {err:?}"
1018 );
1019 }
1020
1021 #[test]
1022 fn checked_rejects_indefinite_length_cbor() {
1023 // An indefinite-length CBOR array (0x9f .. 0xff) is valid CBOR but
1024 // forbidden in canonical dag-cbor (definite-length only). dag-cbor's
1025 // decoder may already refuse it; either way the checked door must error
1026 // (decode failure OR non-canonical), never silently mint an id.
1027 // 9f array(*) (indefinite)
1028 // 01 02 03 1, 2, 3
1029 // ff break
1030 let indefinite = [0x9f, 0x01, 0x02, 0x03, 0xff];
1031 let err = ContentId::from_canonical_bytes_checked(&indefinite)
1032 .expect_err("indefinite-length CBOR must be rejected");
1033 assert!(
1034 matches!(
1035 err,
1036 ContentError::NonCanonical | ContentError::DecodingError { .. }
1037 ),
1038 "indefinite-length CBOR must be rejected (NonCanonical or DecodingError), got {err:?}"
1039 );
1040 }
1041
1042 #[test]
1043 fn checked_rejects_non_dagcbor_garbage() {
1044 // Arbitrary non-CBOR bytes must fail at the decode step.
1045 let garbage = [0xff, 0xff, 0xff, 0xff];
1046 let err = ContentId::from_canonical_bytes_checked(&garbage)
1047 .expect_err("non-dag-cbor garbage must be rejected");
1048 assert!(
1049 matches!(err, ContentError::DecodingError { .. }),
1050 "non-dag-cbor garbage must map to ContentError::DecodingError, got {err:?}"
1051 );
1052 }
1053
1054 #[test]
1055 fn unchecked_still_mints_an_id_for_non_canonical_bytes() {
1056 // REGRESSION / documentation test (issue #5 AC item d): the FAST,
1057 // unchecked primitive does NOT validate — it mints a (misleading) id even
1058 // for non-canonical bytes. This pins that the precondition is real and
1059 // unenforced by design: the unchecked door succeeds where the checked one
1060 // refuses, and the two ids necessarily differ (the unchecked id hashes
1061 // the non-canonical bytes; the canonical bytes hash to something else).
1062 let non_canonical = [0xa2, 0x62, 0x62, 0x62, 0x01, 0x61, 0x61, 0x02];
1063
1064 // Unchecked: succeeds, no error, no panic — mints over the raw bytes.
1065 let misleading = ContentId::from_canonical_bytes(&non_canonical);
1066 assert_eq!(
1067 misleading.digest_bytes(),
1068 *blake3::hash(&non_canonical).as_bytes(),
1069 "the unchecked door hashes exactly the bytes it was given"
1070 );
1071
1072 // Checked: refuses.
1073 assert!(ContentId::from_canonical_bytes_checked(&non_canonical).is_err());
1074
1075 // The misleading id differs from the id of the *canonical* form of the
1076 // same value — the silent integrity hole the precondition warns about.
1077 let decoded: ipld_core::ipld::Ipld =
1078 crate::canonical::from_canonical_dagcbor(&non_canonical).expect("valid CBOR");
1079 let canonical = to_canonical_dagcbor(&decoded).expect("re-encode");
1080 let honest = ContentId::from_canonical_bytes(&canonical);
1081 assert_ne!(
1082 misleading, honest,
1083 "minting over non-canonical bytes names a different id than the \
1084 canonical form would — exactly the hazard from_canonical_bytes warns of"
1085 );
1086 }
1087}
1088
1089#[cfg(test)]
1090mod profile_validation_tests {
1091 //! Every ingress path (`from_bytes`, `FromStr`, `TryFrom<Cid>`, binary
1092 //! `Deserialize`) admits ONLY the frozen profile — CIDv1 + dag-cbor (`0x71`) +
1093 //! BLAKE3 (`0x1e`) + 32-byte digest. A foreign CID is rejected with
1094 //! [`ContentError::InvalidCidProfile`] rather than smuggled in to panic later in
1095 //! a presentation accessor. (Closes the ContentId profile-validation hole.)
1096 use super::*;
1097 use ipld_core::cid::multihash::Multihash;
1098 use ipld_core::cid::Cid;
1099
1100 const SHA2_256: u64 = 0x12;
1101 const RAW_CODEC: u64 = 0x55;
1102
1103 fn blake3_mh(digest: &[u8]) -> Multihash<64> {
1104 Multihash::wrap(BLAKE3_HASH_CODE, digest).expect("wrap blake3")
1105 }
1106
1107 // Well-formed CIDs that are NOT this crate's profile, one per parameter.
1108 fn cidv0_sha256() -> Cid {
1109 Cid::new_v0(Multihash::wrap(SHA2_256, &[7u8; 32]).expect("wrap sha256")).expect("v0")
1110 }
1111 fn v1_non_dagcbor_codec() -> Cid {
1112 Cid::new_v1(RAW_CODEC, blake3_mh(&[7u8; 32]))
1113 }
1114 fn v1_sha256_hash() -> Cid {
1115 Cid::new_v1(
1116 DAG_CBOR_CODEC,
1117 Multihash::wrap(SHA2_256, &[7u8; 32]).expect("wrap sha256"),
1118 )
1119 }
1120 fn v1_short_digest() -> Cid {
1121 Cid::new_v1(DAG_CBOR_CODEC, blake3_mh(&[7u8; 16]))
1122 }
1123
1124 /// A foreign CID is rejected identically by TryFrom, from_bytes, and FromStr.
1125 fn assert_all_ingress_reject(cid: Cid) {
1126 assert!(
1127 matches!(
1128 ContentId::try_from(cid),
1129 Err(ContentError::InvalidCidProfile { .. })
1130 ),
1131 "TryFrom<Cid> must reject a foreign CID"
1132 );
1133 assert!(
1134 matches!(
1135 ContentId::from_bytes(&cid.to_bytes()),
1136 Err(ContentError::InvalidCidProfile { .. })
1137 ),
1138 "from_bytes must reject a foreign CID envelope"
1139 );
1140 assert!(
1141 matches!(
1142 cid.to_string().parse::<ContentId>(),
1143 Err(ContentError::InvalidCidProfile { .. })
1144 ),
1145 "FromStr must reject a foreign CID string"
1146 );
1147 }
1148
1149 #[test]
1150 fn cidv0_sha256_is_rejected() {
1151 assert_all_ingress_reject(cidv0_sha256());
1152 }
1153
1154 #[test]
1155 fn v1_non_dagcbor_codec_is_rejected() {
1156 assert_all_ingress_reject(v1_non_dagcbor_codec());
1157 }
1158
1159 #[test]
1160 fn v1_sha256_hash_is_rejected() {
1161 assert_all_ingress_reject(v1_sha256_hash());
1162 }
1163
1164 #[test]
1165 fn v1_short_digest_is_rejected() {
1166 assert_all_ingress_reject(v1_short_digest());
1167 }
1168
1169 #[test]
1170 fn a_foreign_cid_link_in_dagcbor_is_rejected_on_deserialize() {
1171 // A tag-42 link to a foreign (sha256) CID, encoded as dag-cbor, must NOT
1172 // deserialize as a ContentId through the binary/IPLD path.
1173 let foreign = v1_sha256_hash();
1174 let bytes = serde_ipld_dagcbor::to_vec(&foreign).expect("encode a tag-42 link");
1175 let decoded: Result<ContentId, _> = serde_ipld_dagcbor::from_slice(&bytes);
1176 assert!(
1177 decoded.is_err(),
1178 "a foreign CID link must not deserialize as a ContentId"
1179 );
1180 }
1181
1182 #[test]
1183 fn an_on_profile_id_passes_every_ingress_path() {
1184 // A genuine, minted id round-trips through all validated ingress paths.
1185 let id = ContentId::from_canonical_bytes(&[0xa0]); // canonical empty map
1186 assert_eq!(ContentId::try_from(*id.as_cid()).expect("try_from"), id);
1187 assert_eq!(
1188 ContentId::from_bytes(&id.to_bytes()).expect("from_bytes"),
1189 id
1190 );
1191 assert_eq!(id.to_string().parse::<ContentId>().expect("parse"), id);
1192 // And the presentation accessor is now provably total.
1193 assert_eq!(id.digest_bytes().len(), BLAKE3_DIGEST_LEN);
1194 }
1195}