1use 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
14pub const DAG_CBOR_CODEC: u64 = 0x71;
16
17pub 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
33pub type ContentHash = [u8; CID_V0_DIGEST_BYTES];
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct DagCborMultihash(Multihash<CID_MAX_DIGEST_BYTES>);
42
43impl DagCborMultihash {
44 pub fn code(&self) -> u64 {
46 self.0.code()
47 }
48
49 pub fn size(&self) -> u8 {
51 self.0.size()
52 }
53
54 pub fn digest(&self) -> &[u8] {
56 self.0.digest()
57 }
58
59 pub fn to_bytes(&self) -> Vec<u8> {
61 self.0.to_bytes()
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct ParsedCid(Cid);
72
73impl ParsedCid {
74 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
86pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
88 Sha256::digest(bytes).into()
89}
90
91pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
93 DagCborMultihash(Code::Sha2_256.digest(bytes))
94}
95
96pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum CidVerificationStatus {
112 Match,
114 Mismatch,
116 NonCanonical,
118 InvalidCid,
120}
121
122#[must_use]
124pub struct DagCborCidVerification {
125 status: CidVerificationStatus,
126 expected_cid: String,
127 actual_cid: String,
128}
129
130impl DagCborCidVerification {
131 pub const fn status(&self) -> CidVerificationStatus {
133 self.status
134 }
135
136 pub fn expected_cid(&self) -> &str {
138 self.expected_cid.as_str()
139 }
140
141 pub fn actual_cid(&self) -> &str {
143 self.actual_cid.as_str()
144 }
145
146 pub fn into_parts(self) -> (CidVerificationStatus, String, String) {
148 (self.status, self.expected_cid, self.actual_cid)
149 }
150}
151
152pub 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 if supplied != canonical {
194 CidVerificationStatus::NonCanonical
195 } else if expected == actual {
196 CidVerificationStatus::Match
197 } else {
198 CidVerificationStatus::Mismatch
199 }
200}
201
202pub fn is_valid_cid_string(s: &str) -> bool {
208 try_parse_cid(s).is_some()
209}
210
211pub 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 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 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 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 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 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;