Skip to main content

codec_cbor/
cid.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use cid::Cid;
6use multihash::Multihash;
7use multihash_codetable::{Code, MultihashDigest};
8use sha2::{Digest, Sha256};
9
10/// dag-cbor multicodec code (IPLD)
11pub const DAG_CBOR_CODEC: u64 = 0x71;
12
13/// Hash output for sha2-256
14pub type ContentHash = [u8; 32];
15
16/// Multihash envelope size used by the CID stack for sha2-256 digests.
17pub type DagCborMultihash = Multihash<64>;
18
19/// Returns the raw sha2-256 digest of `bytes`.
20pub fn sha2_256_content_hash(bytes: &[u8]) -> ContentHash {
21    Sha256::digest(bytes).into()
22}
23
24/// Returns a sha2-256 multihash of `bytes` for use in a CID.
25pub fn dag_cbor_multihash(bytes: &[u8]) -> DagCborMultihash {
26    Code::Sha2_256.digest(bytes)
27}
28
29/// Computes the CIDv1 (dag-cbor, sha2-256) of `bytes` as a lowercase string.
30pub fn compute_cid_dag_cbor(bytes: &[u8]) -> String {
31    let hash = dag_cbor_multihash(bytes);
32    let cid = Cid::new_v1(DAG_CBOR_CODEC, hash);
33    cid.to_string().to_lowercase()
34}
35
36/// Recomputes the CID of `bytes` and compares it to `cid_str`.
37///
38/// Returns whether they match (case-insensitively), plus the expected and
39/// actual (lowercased) CID strings.
40pub fn verify_dag_cbor_cid(cid_str: &str, bytes: &[u8]) -> (bool, String, String) {
41    let expected = compute_cid_dag_cbor(bytes);
42    let actual = cid_str.to_lowercase();
43    (expected == actual, expected, actual)
44}
45
46/// Returns whether `s` parses as a valid CID string.
47pub fn is_valid_cid_string(s: &str) -> bool {
48    Cid::try_from(s).is_ok()
49}
50
51/// Parses `s` as a CID, returning `None` if it is not a valid CID string.
52pub fn try_parse_cid(s: &str) -> Option<Cid> {
53    Cid::try_from(s).ok()
54}