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 a bounded 64-byte opaque 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/// Syntax-validated CID, independent of the upstream CID type.
66///
67/// CIDv1 hash codes and digest lengths remain opaque. This type establishes
68/// framing and resource bounds; hash support and content integrity require a
69/// separate verifier such as [`verify_dag_cbor_cid`].
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct ParsedCid(Cid);
72
73impl ParsedCid {
74    /// Return the syntax-validated CID's canonical binary representation.
75    pub fn to_bytes(&self) -> Vec<u8> {
76        self.0.to_bytes()
77    }
78}
79
80impl core::fmt::Display for ParsedCid {
81    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
82        self.0.fmt(formatter)
83    }
84}
85
86/// Returns the raw sha2-256 digest of `bytes`.
87pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
88    Sha256::digest(bytes).into()
89}
90
91/// Returns a sha2-256 multihash of `bytes` for use in a CID.
92pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
93    DagCborMultihash(Code::Sha2_256.digest(bytes))
94}
95
96/// Computes the CIDv1 (dag-cbor, sha2-256) of `bytes` in canonical
97/// base32-lower string form.
98///
99/// Hashes the supplied bytes as-is, without parsing CBOR or applying the
100/// encoder/decoder size limit. Encode a value first to obtain a canonical block.
101pub fn compute_cid_dag_cbor(bytes: &[u8]) -> String {
102    dag_cbor_cid(dag_cbor_multihash(bytes)).to_string()
103}
104
105fn dag_cbor_cid(hash: DagCborMultihash) -> Cid {
106    Cid::new_v1(DAG_CBOR_CODEC, hash.0)
107}
108
109/// Outcome of comparing a canonical DAG-CBOR block with a CID string.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum CidVerificationStatus {
112    /// The canonical CID matches the validated block.
113    Match,
114    /// A canonical CID differs in version, codec, hash parameters, or digest.
115    Mismatch,
116    /// The CID parses but its textual representation is not canonical.
117    NonCanonical,
118    /// The supplied text is not a valid CID.
119    InvalidCid,
120}
121
122/// Validated CID comparison with canonical, input-independent diagnostics.
123#[must_use]
124pub struct DagCborCidVerification {
125    status: CidVerificationStatus,
126    expected_cid: String,
127    actual_cid: String,
128}
129
130impl DagCborCidVerification {
131    /// Return the exact verification outcome.
132    pub const fn status(&self) -> CidVerificationStatus {
133        self.status
134    }
135
136    /// Return the canonical CID computed from the block.
137    pub fn expected_cid(&self) -> &str {
138        self.expected_cid.as_str()
139    }
140
141    /// Return the parsed CID in canonical form, or empty for invalid text.
142    pub fn actual_cid(&self) -> &str {
143        self.actual_cid.as_str()
144    }
145
146    /// Transfer the canonical strings to a transport adapter without copying.
147    pub fn into_parts(self) -> (CidVerificationStatus, String, String) {
148        (self.status, self.expected_cid, self.actual_cid)
149    }
150}
151
152/// Validate one canonical DAG-CBOR block and compare its CID text.
153///
154/// A match requires CIDv1, the DAG-CBOR codec, and the complete 32-byte SHA-256
155/// digest of the validated block. Syntax-only CID admission does not relax any
156/// of these verification requirements.
157///
158/// # Errors
159///
160/// Returns a typed DAG-CBOR error when the payload is malformed, noncanonical,
161/// or exceeds the parser's resource limits. Use [`compute_cid_dag_cbor`] when
162/// intentionally hashing opaque bytes without validating a DAG-CBOR block.
163pub fn verify_dag_cbor_cid(
164    cid_str: &str,
165    bytes: &[u8],
166) -> Result<DagCborCidVerification, CborError> {
167    let _validated = Zeroizing::new(decode_dag_cbor(bytes)?);
168    let expected_cid = dag_cbor_cid(dag_cbor_multihash(bytes));
169    let expected = expected_cid.to_string();
170    let Some((actual_cid, _base)) = parse_cid_string(cid_str) else {
171        return Ok(DagCborCidVerification {
172            status: CidVerificationStatus::InvalidCid,
173            expected_cid: expected,
174            actual_cid: String::new(),
175        });
176    };
177    let actual = actual_cid.to_string();
178    Ok(DagCborCidVerification {
179        status: classify_parsed_cid(cid_str, &actual, &expected_cid, &actual_cid),
180        expected_cid: expected,
181        actual_cid: actual,
182    })
183}
184
185fn classify_parsed_cid(
186    supplied: &str,
187    canonical: &str,
188    expected: &Cid,
189    actual: &Cid,
190) -> CidVerificationStatus {
191    // Textual canonicality is checked first so alternate representations
192    // produce the same diagnostic whether or not the digest matches.
193    if supplied != canonical {
194        CidVerificationStatus::NonCanonical
195    } else if expected == actual {
196        CidVerificationStatus::Match
197    } else {
198        CidVerificationStatus::Mismatch
199    }
200}
201
202/// Returns whether `s` has valid, bounded CID syntax.
203///
204/// CIDv1 hash codes and lengths are opaque: unknown codes, truncated digests,
205/// and identity digests can pass. Use [`verify_dag_cbor_cid`] to verify content
206/// against the DAG-CBOR/SHA-256 profile.
207pub fn is_valid_cid_string(s: &str) -> bool {
208    try_parse_cid(s).is_some()
209}
210
211/// Parses bounded CID syntax, returning `None` on a framing or limit failure.
212///
213/// Accepts CIDv0 and multibase CID strings up to [`MAX_CID_STRING_LEN`]. Paths,
214/// non-minimal binary encodings, and trailing decoded bytes are rejected.
215/// CIDv0 requires the full 32-byte SHA-256 multihash. CIDv1 accepts opaque hash
216/// codes and 0..=64 digest bytes when the declared length matches the suffix;
217/// successful parsing makes no hash-support or content-integrity claim.
218pub fn try_parse_cid(s: &str) -> Option<ParsedCid> {
219    parse_cid_string(s).map(|(cid, _base)| ParsedCid(cid))
220}
221
222fn parse_cid_string(s: &str) -> Option<(Cid, Option<Base>)> {
223    if s.len() > MAX_CID_STRING_LEN {
224        return None;
225    }
226    // The upstream string convenience parser also extracts CIDs from paths.
227    // Decode the entire identifier ourselves so no prefix can be discarded.
228    let (base, decoded) = if s.len() == CID_V0_STRING_LEN && s.starts_with("Qm") {
229        (None, Base::Base58Btc.decode(s).ok()?)
230    } else {
231        let (base, bytes) = multibase_decode(s).ok()?;
232        (Some(base), bytes)
233    };
234    let cid = parse_cid_wire(&decoded, base.is_some())?;
235    Some((cid, base))
236}
237
238fn parse_cid_wire(bytes: &[u8], has_multibase_prefix: bool) -> Option<Cid> {
239    if let Some(digest) = bytes.strip_prefix(&CID_V0_PREFIX) {
240        // CIDv0 is exactly one full SHA-256 multihash with no multibase prefix.
241        if has_multibase_prefix || digest.len() != CID_V0_DIGEST_BYTES {
242            return None;
243        }
244        let hash = Multihash::wrap(u64::from(Code::Sha2_256), digest).ok()?;
245        return Cid::new_v0(hash).ok();
246    }
247
248    // The only admitted explicit version has a one-octet wire encoding.
249    let fields = bytes.strip_prefix(&[CID_V1_VERSION])?;
250    let (codec, fields) = take_varint(fields)?;
251    let (algorithm, fields) = take_varint(fields)?;
252    let (declared, digest) = take_varint(fields)?;
253    // CIDv1 syntax carries hash code and digest length independently. Preserve
254    // opaque codes and bounded lengths here; content verifiers enforce their
255    // own algorithm and full-digest requirements. The declared digest must
256    // occupy the entire suffix before the storage-capacity check below.
257    if usize::try_from(declared).ok()? != digest.len() {
258        return None;
259    }
260    let hash = Multihash::wrap(algorithm, digest).ok()?;
261    Some(Cid::new_v1(codec, hash))
262}
263
264fn take_varint(mut input: &[u8]) -> Option<(u64, &[u8])> {
265    let mut value = 0;
266    for shift in (0..u64::BITS).step_by(VARINT_GROUP_BITS) {
267        let (&octet, remaining) = input.split_first()?;
268        let payload = u64::from(octet & VARINT_PAYLOAD);
269        // A shift by 63 is valid for u64 but silently discards all except the
270        // lowest payload bit. Reject both overflow and continuation there.
271        if shift == u64::BITS - 1 && octet > 1 {
272            return None;
273        }
274        value |= payload << shift;
275        if octet & VARINT_CONTINUATION == 0 {
276            return (shift == 0 || payload != 0).then_some((value, remaining));
277        }
278        input = remaining;
279    }
280    None
281}
282
283#[cfg(kani)]
284#[path = "cid_proof_tests.rs"]
285mod proofs;