Skip to main content

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).
40const 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    #[must_use]
308    pub fn from_blake3_content_digest(digest: [u8; BLAKE3_DIGEST_LEN]) -> Self {
309        Self::wrap_blake3_digest(digest)
310    }
311
312    /// Wrap a 32-byte BLAKE3 digest as a [`ContentId`]: the frozen tail shared
313    /// by [`from_canonical_bytes`] (which hashes first) and
314    /// [`from_blake3_content_digest`] (which does not). Keeping the
315    /// `Multihash::wrap(0x1e, ..)` + `Cid::new_v1(0x71, ..)` construction in
316    /// exactly one place guarantees both doors emit **byte-identical** CIDs for
317    /// the same digest — the property the no-rehash bridge depends on.
318    fn wrap_blake3_digest(digest: [u8; BLAKE3_DIGEST_LEN]) -> Self {
319        let mh = Multihash::wrap(BLAKE3_HASH_CODE, &digest)
320            .expect("BLAKE3 digest is 32 bytes and always fits a 64-byte multihash");
321        ContentId(Cid::new_v1(DAG_CBOR_CODEC, mh))
322    }
323
324    /// Borrow the underlying IPLD [`Cid`].
325    #[must_use]
326    pub fn as_cid(&self) -> &Cid {
327        &self.0
328    }
329
330    /// The raw 32-byte BLAKE3 content digest, copied out of the multihash.
331    ///
332    /// This is the **bare hash** — *not* the CID envelope. It is the sovereign
333    /// hash an adopter joins on across systems (the same digest a BLAKE3-native
334    /// upstream would hand to [`from_blake3_content_digest`](Self::from_blake3_content_digest)).
335    ///
336    /// The length is a **frozen, enforced invariant**: every `ContentId` carries
337    /// exactly `BLAKE3_DIGEST_LEN` (32) digest bytes (see the
338    /// [CID-parameters contract](ContentId#cid-parameters-frozen-at-010)), so
339    /// this accessor is infallible and returns a fixed-size array. The copy
340    /// (`try_into`) can never fail; the `expect` is unreachable for *any*
341    /// `ContentId` — every ingress path (`from_bytes`, `FromStr`, `TryFrom<Cid>`,
342    /// binary `Deserialize`) validates the profile, so an off-profile CID can never
343    /// become a `ContentId` and reach this method.
344    ///
345    /// Part of the **frozen presentation contract** — see the
346    /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
347    #[must_use]
348    pub fn digest_bytes(&self) -> [u8; BLAKE3_DIGEST_LEN] {
349        self.0
350            .hash()
351            .digest()
352            .try_into()
353            .expect("a ContentId multihash always carries a 32-byte BLAKE3 digest")
354    }
355
356    /// Lowercase hex of the raw 32-byte BLAKE3 digest: 64 hex chars, **no**
357    /// `0x` or multibase prefix.
358    ///
359    /// This is the **"bare-digest-hex"** convention (the shortest, hash-only
360    /// "hex" form an adopter reaches for, e.g. kyln's `to_hex()`). It is hex of
361    /// [`digest_bytes`](Self::digest_bytes) — *not* hex of the full CID. The
362    /// three "hex" forms in the wild are mutually incompatible; this crate names
363    /// each so they cannot be confused:
364    ///
365    /// - **bare-digest-hex** = this method = `digest_hex()` (64 chars, hash
366    ///   only).
367    /// - **full-CID-bytes-hex** = `hex::encode(id.to_bytes())` — the whole CID
368    ///   envelope (version + codec + multihash header + digest) as base16.
369    ///   *Deliberately not provided as a method* (see the
370    ///   [presentation contract](ContentId#presentation-contract-frozen-at-010));
371    ///   a caller who truly needs it hex-encodes [`to_bytes`](Self::to_bytes)
372    ///   and owns that choice.
373    /// - **multibase base32-lower** = the [`Display`](fmt::Display) /
374    ///   [`to_string`](ToString::to_string) string (`b…`), the IPLD-canonical
375    ///   text form.
376    ///
377    /// Part of the **frozen presentation contract** — see the
378    /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
379    #[must_use]
380    pub fn digest_hex(&self) -> String {
381        let digest = self.digest_bytes();
382        let mut s = String::with_capacity(digest.len() * 2);
383        for b in digest {
384            // Hand-rolled 32->64 lowercase hex: avoids taking a `hex` crate
385            // dependency for a byte-frozen surface (issue #6: "hand-roll
386            // 32->64 hex to avoid the dep — implementer's call").
387            s.push(char::from_digit((b >> 4) as u32, 16).expect("nibble < 16 is a hex digit"));
388            s.push(char::from_digit((b & 0x0f) as u32, 16).expect("nibble < 16 is a hex digit"));
389        }
390        s
391    }
392
393    /// Encode this id as its canonical CID binary form.
394    ///
395    /// This is the full **CID envelope**: version + codec (`0x71`) + multihash
396    /// header + digest — *not* the bare hash. It round-trips through
397    /// [`from_bytes`](Self::from_bytes). For the hex of *this* form ("full-CID-
398    /// bytes-hex"), a caller hex-encodes the result explicitly; the crate
399    /// deliberately does not bless a `cid_hex()` method (see the
400    /// [presentation contract](ContentId#presentation-contract-frozen-at-010)).
401    ///
402    /// Part of the **frozen presentation contract** — see the
403    /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
404    #[must_use]
405    pub fn to_bytes(&self) -> Vec<u8> {
406        self.0.to_bytes()
407    }
408
409    /// Parse an id from its canonical CID binary form.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`ContentError::InvalidCid`] if the bytes are not a valid CID.
414    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ContentError> {
415        let cid = Cid::read_bytes(bytes).map_err(|e| ContentError::InvalidCid {
416            reason: e.to_string(),
417            source: Box::new(e),
418        })?;
419        validate_profile(&cid)?;
420        Ok(ContentId(cid))
421    }
422}
423
424/// Reject any [`Cid`] that is not this crate's frozen profile: CIDv1 + dag-cbor
425/// (`0x71`) + BLAKE3 (`0x1e`) + a 32-byte digest.
426///
427/// **Every** ingress path — [`from_bytes`](ContentId::from_bytes), the
428/// [`FromStr`] impl, [`TryFrom<Cid>`], and the binary/IPLD [`Deserialize`] —
429/// routes through this, so a parsed / deserialized / converted `ContentId` carries
430/// the same invariant a *minted* one does. That is what makes the presentation
431/// accessors ([`digest_bytes`](ContentId::digest_bytes) etc.) total: a foreign CID
432/// (a CIDv0, a non-dag-cbor codec, a SHA-256 hash, a non-32-byte digest) can never
433/// become a `ContentId`, so it can never reach an accessor and panic.
434fn validate_profile(cid: &Cid) -> Result<(), ContentError> {
435    if cid.version() != Version::V1 {
436        return Err(ContentError::InvalidCidProfile {
437            reason: format!("expected CIDv1, got {:?}", cid.version()),
438        });
439    }
440    if cid.codec() != DAG_CBOR_CODEC {
441        return Err(ContentError::InvalidCidProfile {
442            reason: format!(
443                "expected dag-cbor codec 0x{DAG_CBOR_CODEC:x}, got 0x{:x}",
444                cid.codec()
445            ),
446        });
447    }
448    if cid.hash().code() != BLAKE3_HASH_CODE {
449        return Err(ContentError::InvalidCidProfile {
450            reason: format!(
451                "expected BLAKE3 multihash 0x{BLAKE3_HASH_CODE:x}, got 0x{:x}",
452                cid.hash().code()
453            ),
454        });
455    }
456    let digest_len = cid.hash().digest().len();
457    if digest_len != BLAKE3_DIGEST_LEN {
458        return Err(ContentError::InvalidCidProfile {
459            reason: format!("expected a {BLAKE3_DIGEST_LEN}-byte digest, got {digest_len} bytes"),
460        });
461    }
462    Ok(())
463}
464
465impl TryFrom<Cid> for ContentId {
466    type Error = ContentError;
467
468    /// Wrap a [`Cid`] **iff** it is this crate's frozen profile; a foreign CID is
469    /// rejected with [`ContentError::InvalidCidProfile`].
470    ///
471    /// This is `TryFrom`, not `From`, on purpose: an infallible `From<Cid>` would
472    /// let an off-profile CID become a `ContentId` and later panic in a
473    /// presentation accessor. (The outward [`From<ContentId>`] for [`Cid`] stays
474    /// infallible — dropping the newtype is always safe.)
475    fn try_from(cid: Cid) -> Result<Self, Self::Error> {
476        validate_profile(&cid)?;
477        Ok(ContentId(cid))
478    }
479}
480
481impl From<ContentId> for Cid {
482    fn from(id: ContentId) -> Self {
483        id.0
484    }
485}
486
487impl fmt::Display for ContentId {
488    /// Render as multibase **base32-lower** (the `b…` CIDv1 string).
489    ///
490    /// This is the crate's **canonical text form** and is **frozen** for the
491    /// `0.1.x` line — see the
492    /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
493    /// It is the IPLD-canonical CID string and the same text the human-readable
494    /// serde form emits. It is the inverse of [`FromStr`] for base32-lower:
495    /// `id.to_string().parse() == Ok(id)` is a tested, frozen round-trip. A unit
496    /// test and the conformance vectors pin the exact string for fixed inputs,
497    /// so any drift in the inner CID's rendering fails loudly. Changing this
498    /// form is a major version bump.
499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500        fmt::Display::fmt(&self.0, f)
501    }
502}
503
504impl FromStr for ContentId {
505    type Err = ContentError;
506
507    /// Parse an id from a multibase CID string.
508    ///
509    /// The frozen contract is narrow: `FromStr` is the **inverse of
510    /// [`Display`](fmt::Display)** for the base32-lower form, and that round-trip
511    /// (`id.to_string().parse() == Ok(id)`) is the part pinned by the
512    /// [presentation contract](ContentId#presentation-contract-frozen-at-010).
513    /// As a **convenience (not a contract)** this also accepts other valid
514    /// multibases (base58, base16, …), since the inner [`Cid::from_str`] does;
515    /// that tolerance is *not* frozen and may be tightened later without
516    /// breaking the frozen base32-lower round-trip — so do not depend on parsing
517    /// non-base32 CID strings.
518    fn from_str(s: &str) -> Result<Self, Self::Err> {
519        let cid = Cid::from_str(s).map_err(|e| ContentError::InvalidCid {
520            reason: e.to_string(),
521            source: Box::new(e),
522        })?;
523        validate_profile(&cid)?;
524        Ok(ContentId(cid))
525    }
526}
527
528impl Serialize for ContentId {
529    /// Serialize per the frozen serde contract: the multibase base32 string in
530    /// human-readable formats (e.g. `serde_json`, TOML), the inner [`Cid`] (a
531    /// dag-cbor tag-42 link) in binary/IPLD formats.
532    ///
533    /// This representation is **frozen** for the `0.1.x` line; see the
534    /// [type-level serde contract](ContentId#serde-representation-frozen-at-010).
535    /// Changing it is a major version bump.
536    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
537        if serializer.is_human_readable() {
538            serializer.serialize_str(&self.to_string())
539        } else {
540            self.0.serialize(serializer)
541        }
542    }
543}
544
545impl<'de> Deserialize<'de> for ContentId {
546    /// Deserialize per the frozen serde contract: a multibase base32 string from
547    /// human-readable formats, the inner [`Cid`] (a dag-cbor tag-42 link) from
548    /// binary/IPLD formats.
549    ///
550    /// The accepted representation is **frozen** for the `0.1.x` line; see the
551    /// [type-level serde contract](ContentId#serde-representation-frozen-at-010).
552    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
553        if deserializer.is_human_readable() {
554            let s = String::deserialize(deserializer)?;
555            s.parse::<ContentId>()
556                .map_err(<D::Error as serde::de::Error>::custom)
557        } else {
558            // Binary/IPLD: a decoded tag-42 link is an arbitrary CID until proven
559            // on-profile — reject a foreign link here, not later in an accessor.
560            let cid = Cid::deserialize(deserializer)?;
561            validate_profile(&cid).map_err(<D::Error as serde::de::Error>::custom)?;
562            Ok(ContentId(cid))
563        }
564    }
565}
566
567#[cfg(test)]
568mod cid_param_lock_tests {
569    //! Locks the frozen v1 CID parameters (issue #4) so they cannot drift
570    //! silently. These assertions live in the `content_id` module itself, next
571    //! to the definitions, so the freeze is self-evident at the source. They use
572    //! **literal** values (`0x71`, `0x1e`, `V1`, `32`), not the crate constants,
573    //! so an accidental edit to a `const` is caught by a failing test rather
574    //! than silently followed.
575
576    use super::{ContentId, BLAKE3_DIGEST_LEN, BLAKE3_HASH_CODE, DAG_CBOR_CODEC};
577    use ipld_core::cid::Version;
578
579    /// A freshly produced id, from the empty-map canonical dag-cbor (`0xa0`).
580    /// This is the documented fixed input also used by the embedded-link golden
581    /// and the `empty_map` conformance vector, so the three pins agree.
582    fn empty_map_id() -> ContentId {
583        ContentId::from_canonical_bytes(&[0xa0])
584    }
585
586    #[test]
587    fn cid_params_are_literally_v1_dagcbor_blake3_32() {
588        // Assert against LITERALS, not the constants: editing a `const` must
589        // break this test, not be silently followed.
590        let id = empty_map_id();
591        let cid = id.as_cid();
592        assert_eq!(cid.version(), Version::V1, "CID version is frozen at V1");
593        assert_eq!(cid.codec(), 0x71, "codec is frozen at dag-cbor (0x71)");
594        assert_eq!(
595            cid.hash().code(),
596            0x1e,
597            "multihash is frozen at BLAKE3 (0x1e)"
598        );
599        assert_eq!(
600            cid.hash().digest().len(),
601            32,
602            "BLAKE3 digest length is frozen at 32 bytes"
603        );
604    }
605
606    #[test]
607    fn frozen_constants_hold_their_documented_values() {
608        // The public/private constants must equal the frozen literals, so the
609        // doc and the re-exported surface cannot drift from the contract.
610        assert_eq!(DAG_CBOR_CODEC, 0x71);
611        assert_eq!(BLAKE3_HASH_CODE, 0x1e);
612        assert_eq!(BLAKE3_DIGEST_LEN, 32);
613    }
614
615    #[test]
616    fn cid_binary_prefix_is_frozen() {
617        // The leading bytes of the CIDv1 binary form encode the frozen shape:
618        //   0x01 = CIDv1
619        //   0x71 = multicodec dag-cbor
620        //   0x1e = multihash code BLAKE3
621        //   0x20 = digest length 32 (varint; 0x20 == 32)
622        // Pinning the prefix means the on-wire identifier head cannot drift even
623        // if the digest payload changes.
624        let bytes = empty_map_id().to_bytes();
625        assert_eq!(
626            &bytes[..4],
627            &[0x01, 0x71, 0x1e, 0x20],
628            "CIDv1/dag-cbor/BLAKE3/len-32 binary prefix is frozen"
629        );
630        assert_eq!(
631            bytes.len(),
632            4 + BLAKE3_DIGEST_LEN,
633            "CID binary form is the 4-byte prefix plus the 32-byte digest"
634        );
635    }
636}
637
638#[cfg(test)]
639mod no_rehash_digest_tests {
640    //! Tests for [`ContentId::from_blake3_content_digest`] (issue #10): the
641    //! guarded, no-rehash escape hatch that wraps an already-computed BLAKE3
642    //! content digest as a `ContentId` **without hashing it again**. These pin
643    //! both the produced CID shape and — critically — the *no-rehash invariant*
644    //! that distinguishes this door from `from_canonical_bytes` (which hashes).
645
646    use super::{ContentId, BLAKE3_DIGEST_LEN};
647    use ipld_core::cid::Version;
648
649    /// A non-trivial, fixed 32-byte digest (`[1, 2, 3, ..., 32]`). Deliberately
650    /// not all-zero so that the no-rehash invariant below is a meaningful test.
651    fn sample_digest() -> [u8; BLAKE3_DIGEST_LEN] {
652        let mut d = [0u8; BLAKE3_DIGEST_LEN];
653        for (i, b) in d.iter_mut().enumerate() {
654            *b = (i as u8) + 1;
655        }
656        d
657    }
658
659    #[test]
660    fn produces_v1_dagcbor_blake3_cid_carrying_the_exact_digest() {
661        // Assert against LITERALS, matching the frozen-parameter lock tests.
662        let d = sample_digest();
663        let id = ContentId::from_blake3_content_digest(d);
664        let cid = id.as_cid();
665        assert_eq!(cid.version(), Version::V1, "must be a CIDv1");
666        assert_eq!(cid.codec(), 0x71, "codec must be dag-cbor (0x71)");
667        assert_eq!(cid.hash().code(), 0x1e, "multihash must be BLAKE3 (0x1e)");
668        assert_eq!(
669            cid.hash().digest().len(),
670            BLAKE3_DIGEST_LEN,
671            "digest must be 32 bytes"
672        );
673        // The wrapped digest bytes must be EXACTLY the input — the whole point
674        // of a no-rehash door is that the digest passes through untouched.
675        assert_eq!(
676            cid.hash().digest(),
677            &d,
678            "the CID must carry the caller's digest verbatim"
679        );
680    }
681
682    #[test]
683    fn does_not_rehash_the_digest() {
684        // THE CRITICAL INVARIANT (must-fix gate): for a non-trivial digest `d`,
685        // wrapping it must NOT equal hashing it. `from_canonical_bytes(&d)`
686        // computes BLAKE3(d) — a second hash — whereas
687        // `from_blake3_content_digest(d)` wraps `d` as-is. If these were ever
688        // equal, the constructor would secretly be re-hashing.
689        let d = sample_digest();
690        let wrapped = ContentId::from_blake3_content_digest(d);
691        let hashed_again = ContentId::from_canonical_bytes(&d);
692        assert_ne!(
693            wrapped, hashed_again,
694            "from_blake3_content_digest must NOT re-hash: wrapping d must differ \
695             from BLAKE3(d)"
696        );
697        // Tighter: the wrapped id's digest is `d` itself, while the re-hashed
698        // id's digest is BLAKE3(d) — explicitly different bytes.
699        assert_eq!(wrapped.as_cid().hash().digest(), &d);
700        assert_eq!(
701            hashed_again.as_cid().hash().digest(),
702            blake3::hash(&d).as_bytes(),
703        );
704    }
705
706    #[test]
707    fn digest_survives_a_byte_roundtrip() {
708        // Building from a digest, serializing to CID bytes, and reading the
709        // digest back must recover the original `d` exactly.
710        let d = sample_digest();
711        let id = ContentId::from_blake3_content_digest(d);
712
713        // Via the live CID handle.
714        assert_eq!(id.as_cid().hash().digest(), &d);
715
716        // Via the full CID binary form: tail 32 bytes are the digest, and a
717        // from_bytes parse lands on the same id.
718        let bytes = id.to_bytes();
719        assert_eq!(
720            &bytes[bytes.len() - BLAKE3_DIGEST_LEN..],
721            &d,
722            "the trailing 32 bytes of the CID binary form are the digest"
723        );
724        let reparsed = ContentId::from_bytes(&bytes).expect("CID bytes must reparse");
725        assert_eq!(reparsed, id);
726        assert_eq!(reparsed.as_cid().hash().digest(), &d);
727    }
728
729    #[test]
730    fn converges_with_from_canonical_bytes_when_caller_hashes_correctly() {
731        // The two doors meet in the middle: if a caller hashes the real content
732        // with BLAKE3 and feeds the digest here, they get the SAME id as
733        // hashing the content via from_canonical_bytes. This is the bridge
734        // property the no-rehash primitive exists to provide.
735        for content in [
736            &b""[..],
737            &[0xa0][..], // empty-map canonical dag-cbor
738            b"the quick brown fox",
739            b"\x00\x01\x02\x03 arbitrary canonical bytes",
740        ] {
741            let digest: [u8; BLAKE3_DIGEST_LEN] = blake3::hash(content).into();
742            let via_digest = ContentId::from_blake3_content_digest(digest);
743            let via_hash = ContentId::from_canonical_bytes(content);
744            assert_eq!(
745                via_digest, via_hash,
746                "from_blake3_content_digest(blake3(x)) must equal \
747                 from_canonical_bytes(x)"
748            );
749        }
750    }
751}
752
753#[cfg(test)]
754mod presentation_tests {
755    //! Tests for the **frozen presentation contract** (issue #6): the named,
756    //! separately-frozen string/byte forms a `ContentId` emits. These pin the
757    //! exact values for fixed inputs so any drift in the inner CID's rendering,
758    //! the multihash digest, or the hex encoder fails loudly. The cross-language
759    //! `tests/vectors.json` gate additionally pins `digest_hex` (and the base32
760    //! string + CID bytes) so Python parity is enforced too; these in-crate
761    //! tests assert the *accessor semantics* that the vectors cannot (the array
762    //! return, the no-prefix rule, the Display/FromStr round-trip).
763
764    use super::{ContentId, BLAKE3_DIGEST_LEN};
765
766    /// The documented fixed input: the empty-map canonical dag-cbor (`0xa0`).
767    /// This is the same id as the `empty_map` conformance vector and the
768    /// embedded-link golden, so all the pins agree.
769    fn empty_map_id() -> ContentId {
770        ContentId::from_canonical_bytes(&[0xa0])
771    }
772
773    /// The frozen `empty_map` digest (the BLAKE3 of `0xa0`), as bare-digest-hex.
774    /// Equals the tail of the `empty_map` vector's `content_id_bytes_hex`
775    /// (`01711e20` CID prefix, then this 64-char digest).
776    const EMPTY_MAP_DIGEST_HEX: &str =
777        "1f94cbf313b3ce23257a7251ea0fc95a24556ea611e4f8f475e549971baedb02";
778
779    #[test]
780    fn display_is_frozen_base32_lower() {
781        // The canonical text form is multibase base32-lower (`b…`), frozen.
782        let id = empty_map_id();
783        let s = id.to_string();
784        assert_eq!(
785            s, "bafyr4ia7stf7ge5tzyrsk6tskhva7sk2erkw5jqr4t4pi5pfjglrxlw3ai",
786            "Display must be the frozen base32-lower CID string"
787        );
788        assert!(s.starts_with('b'), "base32-lower multibase prefix is 'b'");
789    }
790
791    #[test]
792    fn display_fromstr_roundtrip_is_frozen() {
793        // The frozen guarantee: Display -> FromStr lands back on the same id.
794        let id = empty_map_id();
795        let parsed: ContentId = id.to_string().parse().expect("base32 string must reparse");
796        assert_eq!(parsed, id, "Display -> FromStr must round-trip");
797    }
798
799    #[test]
800    fn digest_bytes_is_the_raw_32_byte_blake3_hash() {
801        let id = empty_map_id();
802        let d = id.digest_bytes();
803        // It is a fixed-size 32-byte array...
804        assert_eq!(d.len(), BLAKE3_DIGEST_LEN);
805        // ...equal to the multihash's digest (the bare hash, no envelope)...
806        assert_eq!(&d[..], id.as_cid().hash().digest());
807        // ...and equal to an independent BLAKE3 of the input bytes.
808        assert_eq!(d, *blake3::hash(&[0xa0]).as_bytes());
809    }
810
811    #[test]
812    fn digest_hex_is_frozen_64_char_lower_hex_no_prefix() {
813        let id = empty_map_id();
814        let h = id.digest_hex();
815        // Exactly 64 lowercase hex chars, no `0x` prefix. (A hex digest may
816        // legitimately begin with the digit `b`; that is NOT the base32
817        // multibase prefix, which belongs only to the Display string.)
818        assert_eq!(h.len(), 64, "digest_hex is 64 chars (32 bytes)");
819        assert!(!h.starts_with("0x"), "digest_hex carries no 0x prefix");
820        assert!(
821            h.chars()
822                .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
823            "digest_hex is lowercase hex only"
824        );
825        // The exact frozen value for the empty map.
826        assert_eq!(
827            h, EMPTY_MAP_DIGEST_HEX,
828            "frozen empty-map digest_hex drifted"
829        );
830    }
831
832    #[test]
833    fn digest_hex_is_hex_of_digest_bytes_not_of_the_cid() {
834        // digest_hex names convention #1 (bare-digest-hex): it is hex of the
835        // bare digest, and is STRICTLY SHORTER than full-CID-bytes-hex
836        // (`hex::encode(to_bytes())`), which carries the 4-byte CID prefix too.
837        let id = empty_map_id();
838        let digest = id.digest_bytes();
839        let mut expected = String::new();
840        for b in digest {
841            expected.push_str(&format!("{b:02x}"));
842        }
843        assert_eq!(id.digest_hex(), expected);
844
845        // The full-CID-bytes-hex (the deliberately-unmethodd convention #2) is
846        // longer and ENDS WITH the digest hex, after the CID envelope prefix.
847        let cid_bytes_hex: String = id.to_bytes().iter().map(|b| format!("{b:02x}")).collect();
848        assert!(
849            cid_bytes_hex.ends_with(&id.digest_hex()),
850            "the full-CID-bytes-hex ends with the bare-digest-hex"
851        );
852        assert!(
853            cid_bytes_hex.len() > id.digest_hex().len(),
854            "full-CID-bytes-hex is longer than bare-digest-hex (it has the envelope)"
855        );
856        // Concretely: the 4-byte CIDv1/dag-cbor/BLAKE3/len-32 prefix, then digest.
857        assert_eq!(cid_bytes_hex, format!("01711e20{}", id.digest_hex()));
858    }
859}
860
861#[cfg(test)]
862mod checked_input_tests {
863    //! Tests for [`ContentId::from_canonical_bytes_checked`] (issue #5): the
864    //! opt-in, round-trip-validating sibling of the fast `from_canonical_bytes`
865    //! primitive. They pin the four behaviors the issue's AC names: (a) canonical
866    //! bytes accepted and yielding the *same* id as the unchecked door, (b)
867    //! non-canonical-but-valid CBOR rejected, (c) non-dag-cbor garbage rejected,
868    //! and (d) a regression test documenting that the *unchecked* primitive still
869    //! happily mints an id for non-canonical bytes (the precondition is real and
870    //! unenforced by design).
871
872    use super::ContentId;
873    use crate::canonical::to_canonical_dagcbor;
874    use crate::error::ContentError;
875
876    #[test]
877    fn checked_accepts_canonical_bytes_and_matches_the_unchecked_door() {
878        // The always-canonical path: canonicalize a value, then both doors must
879        // agree on the id (the check changes fallibility, never the bytes).
880        for value in [
881            &serde_json::json!({}),
882            &serde_json::json!({"alpha": 1, "zeta": 26}),
883            &serde_json::json!({"name": "hello", "n": [1, 2, 3], "nested": {"a": 1}}),
884            &serde_json::json!([1, "two", [3, 4], null]),
885        ] {
886            // Drive canonical bytes through Ipld so the encoding is the codec's
887            // canonical form, then assert the two doors converge.
888            let ipld: ipld_core::ipld::Ipld =
889                serde_json::from_value((*value).clone()).expect("json -> ipld");
890            let canonical = to_canonical_dagcbor(&ipld).expect("encode canonical");
891
892            let via_checked =
893                ContentId::from_canonical_bytes_checked(&canonical).expect("canonical accepted");
894            let via_unchecked = ContentId::from_canonical_bytes(&canonical);
895            assert_eq!(
896                via_checked, via_unchecked,
897                "checked(canonical) must equal the unchecked id for the same bytes"
898            );
899        }
900    }
901
902    #[test]
903    fn always_canonical_path_equals_from_canonical_bytes_of_to_canonical_dagcbor() {
904        // The exact identity the issue calls out: the always-canonical path
905        // (to_canonical_dagcbor then mint) and the checked door produce the same
906        // id, and that id is from_canonical_bytes(to_canonical_dagcbor(x)).
907        let ipld: ipld_core::ipld::Ipld = serde_json::from_value(serde_json::json!(
908            {"alpha": 1, "zeta": 26, "list": [true, false, null]}
909        ))
910        .expect("json -> ipld");
911
912        let canonical = to_canonical_dagcbor(&ipld).expect("encode canonical");
913        let from_unchecked = ContentId::from_canonical_bytes(&canonical);
914        let from_checked =
915            ContentId::from_canonical_bytes_checked(&canonical).expect("canonical accepted");
916
917        assert_eq!(
918            from_checked, from_unchecked,
919            "from_canonical_bytes_checked(to_canonical_dagcbor(x)) == \
920             from_canonical_bytes(to_canonical_dagcbor(x))"
921        );
922    }
923
924    #[test]
925    fn checked_rejects_non_canonical_but_valid_cbor() {
926        // A map with two string keys encoded in NON-canonical (descending) key
927        // order. dag-cbor canonical order is by length-then-bytewise, so {"a",
928        // "bb"} canonical is a2 [a] .. [bb]; we hand-build the reverse order.
929        // Hand-built CBOR:
930        //   a2                      map(2)
931        //   62 6262                 text(2) "bb"   <- emitted FIRST (non-canonical)
932        //   01                      1
933        //   61 61                   text(1) "a"
934        //   02                      2
935        let non_canonical = [0xa2, 0x62, 0x62, 0x62, 0x01, 0x61, 0x61, 0x02];
936
937        // Sanity: it IS valid CBOR (decodes fine), so this exercises the
938        // re-encode-compare path, not the decode path.
939        let decoded: ipld_core::ipld::Ipld =
940            crate::canonical::from_canonical_dagcbor(&non_canonical)
941                .expect("non-canonical bytes are still valid CBOR and decode");
942        // And its canonical re-encoding genuinely differs (proving our fixture is
943        // really non-canonical, not an accidental canonical form).
944        let recanon = to_canonical_dagcbor(&decoded).expect("re-encode");
945        assert_ne!(
946            &recanon[..],
947            &non_canonical[..],
948            "fixture must actually be non-canonical"
949        );
950
951        let err = ContentId::from_canonical_bytes_checked(&non_canonical)
952            .expect_err("non-canonical CBOR must be rejected");
953        assert!(
954            matches!(err, ContentError::NonCanonical),
955            "non-canonical valid CBOR must map to ContentError::NonCanonical, got {err:?}"
956        );
957    }
958
959    #[test]
960    fn checked_rejects_indefinite_length_cbor() {
961        // An indefinite-length CBOR array (0x9f .. 0xff) is valid CBOR but
962        // forbidden in canonical dag-cbor (definite-length only). dag-cbor's
963        // decoder may already refuse it; either way the checked door must error
964        // (decode failure OR non-canonical), never silently mint an id.
965        //   9f        array(*)  (indefinite)
966        //   01 02 03  1, 2, 3
967        //   ff        break
968        let indefinite = [0x9f, 0x01, 0x02, 0x03, 0xff];
969        let err = ContentId::from_canonical_bytes_checked(&indefinite)
970            .expect_err("indefinite-length CBOR must be rejected");
971        assert!(
972            matches!(
973                err,
974                ContentError::NonCanonical | ContentError::DecodingError { .. }
975            ),
976            "indefinite-length CBOR must be rejected (NonCanonical or DecodingError), got {err:?}"
977        );
978    }
979
980    #[test]
981    fn checked_rejects_non_dagcbor_garbage() {
982        // Arbitrary non-CBOR bytes must fail at the decode step.
983        let garbage = [0xff, 0xff, 0xff, 0xff];
984        let err = ContentId::from_canonical_bytes_checked(&garbage)
985            .expect_err("non-dag-cbor garbage must be rejected");
986        assert!(
987            matches!(err, ContentError::DecodingError { .. }),
988            "non-dag-cbor garbage must map to ContentError::DecodingError, got {err:?}"
989        );
990    }
991
992    #[test]
993    fn unchecked_still_mints_an_id_for_non_canonical_bytes() {
994        // REGRESSION / documentation test (issue #5 AC item d): the FAST,
995        // unchecked primitive does NOT validate — it mints a (misleading) id even
996        // for non-canonical bytes. This pins that the precondition is real and
997        // unenforced by design: the unchecked door succeeds where the checked one
998        // refuses, and the two ids necessarily differ (the unchecked id hashes
999        // the non-canonical bytes; the canonical bytes hash to something else).
1000        let non_canonical = [0xa2, 0x62, 0x62, 0x62, 0x01, 0x61, 0x61, 0x02];
1001
1002        // Unchecked: succeeds, no error, no panic — mints over the raw bytes.
1003        let misleading = ContentId::from_canonical_bytes(&non_canonical);
1004        assert_eq!(
1005            misleading.digest_bytes(),
1006            *blake3::hash(&non_canonical).as_bytes(),
1007            "the unchecked door hashes exactly the bytes it was given"
1008        );
1009
1010        // Checked: refuses.
1011        assert!(ContentId::from_canonical_bytes_checked(&non_canonical).is_err());
1012
1013        // The misleading id differs from the id of the *canonical* form of the
1014        // same value — the silent integrity hole the precondition warns about.
1015        let decoded: ipld_core::ipld::Ipld =
1016            crate::canonical::from_canonical_dagcbor(&non_canonical).expect("valid CBOR");
1017        let canonical = to_canonical_dagcbor(&decoded).expect("re-encode");
1018        let honest = ContentId::from_canonical_bytes(&canonical);
1019        assert_ne!(
1020            misleading, honest,
1021            "minting over non-canonical bytes names a different id than the \
1022             canonical form would — exactly the hazard from_canonical_bytes warns of"
1023        );
1024    }
1025}
1026
1027#[cfg(test)]
1028mod profile_validation_tests {
1029    //! Every ingress path (`from_bytes`, `FromStr`, `TryFrom<Cid>`, binary
1030    //! `Deserialize`) admits ONLY the frozen profile — CIDv1 + dag-cbor (`0x71`) +
1031    //! BLAKE3 (`0x1e`) + 32-byte digest. A foreign CID is rejected with
1032    //! [`ContentError::InvalidCidProfile`] rather than smuggled in to panic later in
1033    //! a presentation accessor. (Closes the ContentId profile-validation hole.)
1034    use super::*;
1035    use ipld_core::cid::multihash::Multihash;
1036    use ipld_core::cid::Cid;
1037
1038    const SHA2_256: u64 = 0x12;
1039    const RAW_CODEC: u64 = 0x55;
1040
1041    fn blake3_mh(digest: &[u8]) -> Multihash<64> {
1042        Multihash::wrap(BLAKE3_HASH_CODE, digest).expect("wrap blake3")
1043    }
1044
1045    // Well-formed CIDs that are NOT this crate's profile, one per parameter.
1046    fn cidv0_sha256() -> Cid {
1047        Cid::new_v0(Multihash::wrap(SHA2_256, &[7u8; 32]).expect("wrap sha256")).expect("v0")
1048    }
1049    fn v1_non_dagcbor_codec() -> Cid {
1050        Cid::new_v1(RAW_CODEC, blake3_mh(&[7u8; 32]))
1051    }
1052    fn v1_sha256_hash() -> Cid {
1053        Cid::new_v1(
1054            DAG_CBOR_CODEC,
1055            Multihash::wrap(SHA2_256, &[7u8; 32]).expect("wrap sha256"),
1056        )
1057    }
1058    fn v1_short_digest() -> Cid {
1059        Cid::new_v1(DAG_CBOR_CODEC, blake3_mh(&[7u8; 16]))
1060    }
1061
1062    /// A foreign CID is rejected identically by TryFrom, from_bytes, and FromStr.
1063    fn assert_all_ingress_reject(cid: Cid) {
1064        assert!(
1065            matches!(
1066                ContentId::try_from(cid),
1067                Err(ContentError::InvalidCidProfile { .. })
1068            ),
1069            "TryFrom<Cid> must reject a foreign CID"
1070        );
1071        assert!(
1072            matches!(
1073                ContentId::from_bytes(&cid.to_bytes()),
1074                Err(ContentError::InvalidCidProfile { .. })
1075            ),
1076            "from_bytes must reject a foreign CID envelope"
1077        );
1078        assert!(
1079            matches!(
1080                cid.to_string().parse::<ContentId>(),
1081                Err(ContentError::InvalidCidProfile { .. })
1082            ),
1083            "FromStr must reject a foreign CID string"
1084        );
1085    }
1086
1087    #[test]
1088    fn cidv0_sha256_is_rejected() {
1089        assert_all_ingress_reject(cidv0_sha256());
1090    }
1091
1092    #[test]
1093    fn v1_non_dagcbor_codec_is_rejected() {
1094        assert_all_ingress_reject(v1_non_dagcbor_codec());
1095    }
1096
1097    #[test]
1098    fn v1_sha256_hash_is_rejected() {
1099        assert_all_ingress_reject(v1_sha256_hash());
1100    }
1101
1102    #[test]
1103    fn v1_short_digest_is_rejected() {
1104        assert_all_ingress_reject(v1_short_digest());
1105    }
1106
1107    #[test]
1108    fn a_foreign_cid_link_in_dagcbor_is_rejected_on_deserialize() {
1109        // A tag-42 link to a foreign (sha256) CID, encoded as dag-cbor, must NOT
1110        // deserialize as a ContentId through the binary/IPLD path.
1111        let foreign = v1_sha256_hash();
1112        let bytes = serde_ipld_dagcbor::to_vec(&foreign).expect("encode a tag-42 link");
1113        let decoded: Result<ContentId, _> = serde_ipld_dagcbor::from_slice(&bytes);
1114        assert!(
1115            decoded.is_err(),
1116            "a foreign CID link must not deserialize as a ContentId"
1117        );
1118    }
1119
1120    #[test]
1121    fn an_on_profile_id_passes_every_ingress_path() {
1122        // A genuine, minted id round-trips through all validated ingress paths.
1123        let id = ContentId::from_canonical_bytes(&[0xa0]); // canonical empty map
1124        assert_eq!(ContentId::try_from(*id.as_cid()).expect("try_from"), id);
1125        assert_eq!(
1126            ContentId::from_bytes(&id.to_bytes()).expect("from_bytes"),
1127            id
1128        );
1129        assert_eq!(id.to_string().parse::<ContentId>().expect("parse"), id);
1130        // And the presentation accessor is now provably total.
1131        assert_eq!(id.digest_bytes().len(), BLAKE3_DIGEST_LEN);
1132    }
1133}