Skip to main content

codec_cbor/
cid.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use cid::multibase::{decode as multibase_decode, Base};
6use cid::Cid;
7use multihash::Multihash;
8use multihash_codetable::{Code, MultihashDigest};
9use sha2::{Digest, Sha256};
10use zeroize::Zeroizing;
11
12use crate::{decode_dag_cbor, CborError};
13
14/// dag-cbor multicodec code (IPLD)
15pub const DAG_CBOR_CODEC: u64 = 0x71;
16
17/// Maximum CID string size accepted before multibase decoding.
18///
19/// A CID with the supported 64-byte digest and four u64 varints occupies at
20/// most 104 binary bytes. This budget accommodates even base2 and the UTF-8
21/// base256emoji representation, while bounding quadratic base conversions.
22pub const MAX_CID_STRING_LEN: usize = 1024;
23
24const CID_V0_STRING_LEN: usize = 46;
25const CID_MAX_DIGEST_BYTES: usize = 64;
26const CID_V0_DIGEST_BYTES: usize = 32;
27const CID_V0_PREFIX: [u8; 2] = [0x12, 0x20];
28const CID_V1_VERSION: u8 = 1;
29const VARINT_GROUP_BITS: usize = 7;
30const VARINT_CONTINUATION: u8 = 0x80;
31const VARINT_PAYLOAD: u8 = VARINT_CONTINUATION - 1;
32
33/// Hash output for sha2-256
34pub type ContentHash = [u8; CID_V0_DIGEST_BYTES];
35
36/// SHA-256 multihash for a DAG-CBOR block.
37///
38/// The wrapper keeps the upstream multihash representation out of the public
39/// API while preserving the canonical wire bytes.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct DagCborMultihash(Multihash<CID_MAX_DIGEST_BYTES>);
42
43impl DagCborMultihash {
44    /// Return the multihash algorithm code.
45    pub fn code(&self) -> u64 {
46        self.0.code()
47    }
48
49    /// Return the digest length.
50    pub fn size(&self) -> u8 {
51        self.0.size()
52    }
53
54    /// Borrow the digest bytes.
55    pub fn digest(&self) -> &[u8] {
56        self.0.digest()
57    }
58
59    /// Return canonical multihash wire bytes.
60    pub fn to_bytes(&self) -> Vec<u8> {
61        self.0.to_bytes()
62    }
63}
64
65/// Validated CID, independent of the upstream CID type.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ParsedCid(Cid);
68
69impl ParsedCid {
70    /// Return the validated CID's canonical binary representation.
71    pub fn to_bytes(&self) -> Vec<u8> {
72        self.0.to_bytes()
73    }
74}
75
76impl core::fmt::Display for ParsedCid {
77    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78        self.0.fmt(formatter)
79    }
80}
81
82/// Returns the raw sha2-256 digest of `bytes`.
83pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
84    Sha256::digest(bytes).into()
85}
86
87/// Returns a sha2-256 multihash of `bytes` for use in a CID.
88pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
89    DagCborMultihash(Code::Sha2_256.digest(bytes))
90}
91
92/// Computes the CIDv1 (dag-cbor, sha2-256) of `bytes` in canonical
93/// base32-lower string form.
94///
95/// Hashes the supplied bytes as-is, without parsing CBOR or applying the
96/// encoder/decoder size limit. Encode a value first to obtain a canonical block.
97pub fn compute_cid_dag_cbor(bytes: &[u8]) -> String {
98    dag_cbor_cid(dag_cbor_multihash(bytes)).to_string()
99}
100
101fn dag_cbor_cid(hash: DagCborMultihash) -> Cid {
102    Cid::new_v1(DAG_CBOR_CODEC, hash.0)
103}
104
105/// Outcome of comparing a canonical DAG-CBOR block with a CID string.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum CidVerificationStatus {
108    /// The canonical CID matches the validated block.
109    Match,
110    /// A canonical CID identifies different bytes.
111    Mismatch,
112    /// The CID parses but its textual representation is not canonical.
113    NonCanonical,
114    /// The supplied text is not a valid CID.
115    InvalidCid,
116}
117
118/// Validated CID comparison with canonical, input-independent diagnostics.
119#[must_use]
120pub struct DagCborCidVerification {
121    status: CidVerificationStatus,
122    expected_cid: String,
123    actual_cid: String,
124}
125
126impl DagCborCidVerification {
127    /// Return the exact verification outcome.
128    pub const fn status(&self) -> CidVerificationStatus {
129        self.status
130    }
131
132    /// Return the canonical CID computed from the block.
133    pub fn expected_cid(&self) -> &str {
134        self.expected_cid.as_str()
135    }
136
137    /// Return the parsed CID in canonical form, or empty for invalid text.
138    pub fn actual_cid(&self) -> &str {
139        self.actual_cid.as_str()
140    }
141
142    /// Transfer the canonical strings to a transport adapter without copying.
143    pub fn into_parts(self) -> (CidVerificationStatus, String, String) {
144        (self.status, self.expected_cid, self.actual_cid)
145    }
146}
147
148/// Validate one canonical DAG-CBOR block and compare its CID text.
149///
150/// # Errors
151///
152/// Returns a typed DAG-CBOR error when the payload is malformed, noncanonical,
153/// or exceeds the parser's resource limits. Use [`compute_cid_dag_cbor`] when
154/// intentionally hashing opaque bytes without validating a DAG-CBOR block.
155pub fn verify_dag_cbor_cid(
156    cid_str: &str,
157    bytes: &[u8],
158) -> Result<DagCborCidVerification, CborError> {
159    let _validated = Zeroizing::new(decode_dag_cbor(bytes)?);
160    let expected_cid = dag_cbor_cid(dag_cbor_multihash(bytes));
161    let expected = expected_cid.to_string();
162    let Some((actual_cid, _base)) = parse_cid_string(cid_str) else {
163        return Ok(DagCborCidVerification {
164            status: CidVerificationStatus::InvalidCid,
165            expected_cid: expected,
166            actual_cid: String::new(),
167        });
168    };
169    let actual = actual_cid.to_string();
170    Ok(DagCborCidVerification {
171        status: classify_parsed_cid(cid_str, &actual, &expected_cid, &actual_cid),
172        expected_cid: expected,
173        actual_cid: actual,
174    })
175}
176
177fn classify_parsed_cid(
178    supplied: &str,
179    canonical: &str,
180    expected: &Cid,
181    actual: &Cid,
182) -> CidVerificationStatus {
183    // Textual canonicality is checked first so alternate representations
184    // produce the same diagnostic whether or not the digest matches.
185    if supplied != canonical {
186        CidVerificationStatus::NonCanonical
187    } else if expected == actual {
188        CidVerificationStatus::Match
189    } else {
190        CidVerificationStatus::Mismatch
191    }
192}
193
194/// Returns whether `s` parses as a valid CID string.
195pub fn is_valid_cid_string(s: &str) -> bool {
196    try_parse_cid(s).is_some()
197}
198
199/// Parses `s` as a CID, returning `None` if it is not a valid CID string.
200///
201/// Accepts CIDv0 and multibase CID strings up to [`MAX_CID_STRING_LEN`]. Paths,
202/// non-minimal binary encodings, and trailing decoded bytes are rejected.
203pub fn try_parse_cid(s: &str) -> Option<ParsedCid> {
204    parse_cid_string(s).map(|(cid, _base)| ParsedCid(cid))
205}
206
207fn parse_cid_string(s: &str) -> Option<(Cid, Option<Base>)> {
208    if s.len() > MAX_CID_STRING_LEN {
209        return None;
210    }
211    // The upstream string convenience parser also extracts CIDs from paths.
212    // Decode the entire identifier ourselves so no prefix can be discarded.
213    let (base, decoded) = if s.len() == CID_V0_STRING_LEN && s.starts_with("Qm") {
214        (None, Base::Base58Btc.decode(s).ok()?)
215    } else {
216        let (base, bytes) = multibase_decode(s).ok()?;
217        (Some(base), bytes)
218    };
219    let cid = parse_cid_wire(&decoded, base.is_some())?;
220    Some((cid, base))
221}
222
223fn parse_cid_wire(bytes: &[u8], has_multibase_prefix: bool) -> Option<Cid> {
224    if let Some(digest) = bytes.strip_prefix(&CID_V0_PREFIX) {
225        // CIDv0 is exactly one full SHA-256 multihash with no multibase prefix.
226        if has_multibase_prefix || digest.len() != CID_V0_DIGEST_BYTES {
227            return None;
228        }
229        let hash = Multihash::wrap(u64::from(Code::Sha2_256), digest).ok()?;
230        return Cid::new_v0(hash).ok();
231    }
232
233    // The only admitted explicit version has a one-octet wire encoding.
234    let fields = bytes.strip_prefix(&[CID_V1_VERSION])?;
235    let (codec, fields) = take_varint(fields)?;
236    let (algorithm, fields) = take_varint(fields)?;
237    let (declared, digest) = take_varint(fields)?;
238    // The digest occupies the entire suffix. Check the received extent before
239    // constructing a multihash, which enforces the storage capacity.
240    if usize::try_from(declared).ok()? != digest.len() {
241        return None;
242    }
243    let hash = Multihash::wrap(algorithm, digest).ok()?;
244    Some(Cid::new_v1(codec, hash))
245}
246
247fn take_varint(mut input: &[u8]) -> Option<(u64, &[u8])> {
248    let mut value = 0;
249    for shift in (0..u64::BITS).step_by(VARINT_GROUP_BITS) {
250        let (&octet, remaining) = input.split_first()?;
251        let payload = u64::from(octet & VARINT_PAYLOAD);
252        // A shift by 63 is valid for u64 but silently discards all except the
253        // lowest payload bit. Reject both overflow and continuation there.
254        if shift == u64::BITS - 1 && octet > 1 {
255            return None;
256        }
257        value |= payload << shift;
258        if octet & VARINT_CONTINUATION == 0 {
259            return (shift == 0 || payload != 0).then_some((value, remaining));
260        }
261        input = remaining;
262    }
263    None
264}
265
266#[cfg(kani)]
267#[path = "cid_proof_tests.rs"]
268mod proofs;