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)]
67pub struct ParsedCid(Cid);
68
69impl ParsedCid {
70 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
82pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
84 Sha256::digest(bytes).into()
85}
86
87pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
89 DagCborMultihash(Code::Sha2_256.digest(bytes))
90}
91
92pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum CidVerificationStatus {
108 Match,
110 Mismatch,
112 NonCanonical,
114 InvalidCid,
116}
117
118#[must_use]
120pub struct DagCborCidVerification {
121 status: CidVerificationStatus,
122 expected_cid: String,
123 actual_cid: String,
124}
125
126impl DagCborCidVerification {
127 pub const fn status(&self) -> CidVerificationStatus {
129 self.status
130 }
131
132 pub fn expected_cid(&self) -> &str {
134 self.expected_cid.as_str()
135 }
136
137 pub fn actual_cid(&self) -> &str {
139 self.actual_cid.as_str()
140 }
141
142 pub fn into_parts(self) -> (CidVerificationStatus, String, String) {
144 (self.status, self.expected_cid, self.actual_cid)
145 }
146}
147
148pub 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 if supplied != canonical {
186 CidVerificationStatus::NonCanonical
187 } else if expected == actual {
188 CidVerificationStatus::Match
189 } else {
190 CidVerificationStatus::Mismatch
191 }
192}
193
194pub fn is_valid_cid_string(s: &str) -> bool {
196 try_parse_cid(s).is_some()
197}
198
199pub 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 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 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 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 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 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;