use cid::multibase::{decode as multibase_decode, Base};
use cid::Cid;
use multihash::Multihash;
use multihash_codetable::{Code, MultihashDigest};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use crate::{decode_dag_cbor, CborError};
pub const DAG_CBOR_CODEC: u64 = 0x71;
pub const MAX_CID_STRING_LEN: usize = 1024;
const CID_V0_STRING_LEN: usize = 46;
const CID_MAX_DIGEST_BYTES: usize = 64;
const CID_V0_DIGEST_BYTES: usize = 32;
const CID_V0_PREFIX: [u8; 2] = [0x12, 0x20];
const CID_V1_VERSION: u8 = 1;
const VARINT_GROUP_BITS: usize = 7;
const VARINT_CONTINUATION: u8 = 0x80;
const VARINT_PAYLOAD: u8 = VARINT_CONTINUATION - 1;
pub type ContentHash = [u8; CID_V0_DIGEST_BYTES];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DagCborMultihash(Multihash<CID_MAX_DIGEST_BYTES>);
impl DagCborMultihash {
pub fn code(&self) -> u64 {
self.0.code()
}
pub fn size(&self) -> u8 {
self.0.size()
}
pub fn digest(&self) -> &[u8] {
self.0.digest()
}
pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedCid(Cid);
impl ParsedCid {
pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
}
impl core::fmt::Display for ParsedCid {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(formatter)
}
}
pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
Sha256::digest(bytes).into()
}
pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
DagCborMultihash(Code::Sha2_256.digest(bytes))
}
pub fn compute_cid_dag_cbor(bytes: &[u8]) -> String {
dag_cbor_cid(dag_cbor_multihash(bytes)).to_string()
}
fn dag_cbor_cid(hash: DagCborMultihash) -> Cid {
Cid::new_v1(DAG_CBOR_CODEC, hash.0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CidVerificationStatus {
Match,
Mismatch,
NonCanonical,
InvalidCid,
}
#[must_use]
pub struct DagCborCidVerification {
status: CidVerificationStatus,
expected_cid: String,
actual_cid: String,
}
impl DagCborCidVerification {
pub const fn status(&self) -> CidVerificationStatus {
self.status
}
pub fn expected_cid(&self) -> &str {
self.expected_cid.as_str()
}
pub fn actual_cid(&self) -> &str {
self.actual_cid.as_str()
}
pub fn into_parts(self) -> (CidVerificationStatus, String, String) {
(self.status, self.expected_cid, self.actual_cid)
}
}
pub fn verify_dag_cbor_cid(
cid_str: &str,
bytes: &[u8],
) -> Result<DagCborCidVerification, CborError> {
let _validated = Zeroizing::new(decode_dag_cbor(bytes)?);
let expected_cid = dag_cbor_cid(dag_cbor_multihash(bytes));
let expected = expected_cid.to_string();
let Some((actual_cid, _base)) = parse_cid_string(cid_str) else {
return Ok(DagCborCidVerification {
status: CidVerificationStatus::InvalidCid,
expected_cid: expected,
actual_cid: String::new(),
});
};
let actual = actual_cid.to_string();
Ok(DagCborCidVerification {
status: classify_parsed_cid(cid_str, &actual, &expected_cid, &actual_cid),
expected_cid: expected,
actual_cid: actual,
})
}
fn classify_parsed_cid(
supplied: &str,
canonical: &str,
expected: &Cid,
actual: &Cid,
) -> CidVerificationStatus {
if supplied != canonical {
CidVerificationStatus::NonCanonical
} else if expected == actual {
CidVerificationStatus::Match
} else {
CidVerificationStatus::Mismatch
}
}
pub fn is_valid_cid_string(s: &str) -> bool {
try_parse_cid(s).is_some()
}
pub fn try_parse_cid(s: &str) -> Option<ParsedCid> {
parse_cid_string(s).map(|(cid, _base)| ParsedCid(cid))
}
fn parse_cid_string(s: &str) -> Option<(Cid, Option<Base>)> {
if s.len() > MAX_CID_STRING_LEN {
return None;
}
let (base, decoded) = if s.len() == CID_V0_STRING_LEN && s.starts_with("Qm") {
(None, Base::Base58Btc.decode(s).ok()?)
} else {
let (base, bytes) = multibase_decode(s).ok()?;
(Some(base), bytes)
};
let cid = parse_cid_wire(&decoded, base.is_some())?;
Some((cid, base))
}
fn parse_cid_wire(bytes: &[u8], has_multibase_prefix: bool) -> Option<Cid> {
if let Some(digest) = bytes.strip_prefix(&CID_V0_PREFIX) {
if has_multibase_prefix || digest.len() != CID_V0_DIGEST_BYTES {
return None;
}
let hash = Multihash::wrap(u64::from(Code::Sha2_256), digest).ok()?;
return Cid::new_v0(hash).ok();
}
let fields = bytes.strip_prefix(&[CID_V1_VERSION])?;
let (codec, fields) = take_varint(fields)?;
let (algorithm, fields) = take_varint(fields)?;
let (declared, digest) = take_varint(fields)?;
if usize::try_from(declared).ok()? != digest.len() {
return None;
}
let hash = Multihash::wrap(algorithm, digest).ok()?;
Some(Cid::new_v1(codec, hash))
}
fn take_varint(mut input: &[u8]) -> Option<(u64, &[u8])> {
let mut value = 0;
for shift in (0..u64::BITS).step_by(VARINT_GROUP_BITS) {
let (&octet, remaining) = input.split_first()?;
let payload = u64::from(octet & VARINT_PAYLOAD);
if shift == u64::BITS - 1 && octet > 1 {
return None;
}
value |= payload << shift;
if octet & VARINT_CONTINUATION == 0 {
return (shift == 0 || payload != 0).then_some((value, remaining));
}
input = remaining;
}
None
}
#[cfg(kani)]
#[path = "cid_proof_tests.rs"]
mod proofs;