Skip to main content

forest/utils/cid/
mod.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use crate::utils::multihash::prelude::*;
5use cid::Cid;
6use fvm_ipld_encoding::Error;
7use multihash_derive::Hasher as _;
8
9/// Extension methods for constructing `dag-cbor` [Cid]
10pub trait CidCborExt {
11    /// Default CID builder for Filecoin
12    ///
13    /// - The default codec is [`fvm_ipld_encoding::DAG_CBOR`]
14    /// - The default hash function is 256 bit BLAKE2b
15    ///
16    /// This matches [`abi.CidBuilder`](https://github.com/filecoin-project/go-state-types/blob/master/abi/cid.go#L49) in go
17    fn from_cbor_blake2b256<S: serde::ser::Serialize>(obj: &S) -> Result<Cid, Error> {
18        let mut hasher = multihash_codetable::Blake2b256::default();
19        fvm_ipld_encoding::to_writer(&mut hasher, obj)?;
20        let digest = MultihashCode::Blake2b256
21            .wrap(hasher.finalize())
22            .expect("BLAKE2b-256 digest is 32 bytes, within the multihash allocation");
23        Ok(Cid::new_v1(fvm_ipld_encoding::DAG_CBOR, digest))
24    }
25
26    /// Build CID v1 with `Blake2b256` hasher from `DAG_CBOR` encoded bytes
27    fn from_cbor_encoded_raw_bytes_blake2b256(bytes: &[u8]) -> Cid {
28        Cid::new_v1(
29            fvm_ipld_encoding::DAG_CBOR,
30            MultihashCode::Blake2b256.digest(bytes),
31        )
32    }
33}
34
35impl CidCborExt for Cid {}
36
37/// The BLAKE2b-256 digest a value's `DAG_CBOR` [`Cid`] is built from, and the length of that
38/// encoding.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub(crate) struct EncodedCbor {
41    digest: [u8; 32],
42    len: usize,
43}
44
45impl EncodedCbor {
46    /// Encodes `obj` once, keeping only what callers need afterwards.
47    pub(crate) fn compute<S: serde::ser::Serialize>(obj: &S) -> Result<Self, Error> {
48        let mut writer = CountingHasher::default();
49        fvm_ipld_encoding::to_writer(&mut writer, obj)?;
50        Ok(Self {
51            digest: writer
52                .hasher
53                .finalize()
54                .try_into()
55                .expect("BLAKE2b-256 produces a 32 byte digest"),
56            len: writer.written,
57        })
58    }
59
60    pub(crate) fn cid(&self) -> Cid {
61        let digest = MultihashCode::Blake2b256
62            .wrap(&self.digest)
63            .expect("BLAKE2b-256 digest is 32 bytes, within the multihash allocation");
64        Cid::new_v1(fvm_ipld_encoding::DAG_CBOR, digest)
65    }
66
67    pub(crate) fn byte_len(&self) -> usize {
68        self.len
69    }
70}
71
72/// A lazily computed [`EncodedCbor`].
73///
74/// Equality, hashing and [`Debug`] ignore it, so a type holding one derives those traits as if the
75/// field were absent. Without that, two values with identical fields would compare unequal once
76/// either computed its memo.
77#[derive(Clone, Default)]
78pub(crate) struct Memo(std::sync::OnceLock<EncodedCbor>);
79
80impl Memo {
81    pub(crate) fn get_or_init(&self, compute: impl FnOnce() -> EncodedCbor) -> &EncodedCbor {
82        self.0.get_or_init(compute)
83    }
84}
85
86impl std::fmt::Debug for Memo {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.debug_struct("Memo").finish_non_exhaustive()
89    }
90}
91
92impl PartialEq for Memo {
93    fn eq(&self, _: &Self) -> bool {
94        true
95    }
96}
97
98impl Eq for Memo {}
99
100impl std::hash::Hash for Memo {
101    fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
102}
103
104impl get_size2::GetSize for Memo {}
105
106/// Feeds the hasher while counting, so one pass yields both halves of an [`EncodedCbor`].
107#[derive(Default)]
108struct CountingHasher {
109    hasher: multihash_codetable::Blake2b256,
110    written: usize,
111}
112
113impl std::io::Write for CountingHasher {
114    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
115        self.hasher.update(buf);
116        self.written += buf.len();
117        Ok(buf.len())
118    }
119
120    fn flush(&mut self) -> std::io::Result<()> {
121        Ok(())
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::message::SignedMessage;
129    use quickcheck_macros::quickcheck;
130
131    #[quickcheck]
132    fn cid_matches_the_unmemoized_builder(payload: Vec<u8>) -> bool {
133        EncodedCbor::compute(&payload).unwrap().cid()
134            == Cid::from_cbor_blake2b256(&payload).unwrap()
135    }
136
137    #[quickcheck]
138    fn byte_len_counts_every_encoded_byte(payload: Vec<u8>) -> bool {
139        EncodedCbor::compute(&payload).unwrap().byte_len()
140            == fvm_ipld_encoding::to_vec(&payload).unwrap().len()
141    }
142
143    /// `to_writer` may hand the hasher one chunk or many, and never calls `flush`.
144    #[quickcheck]
145    fn counting_hasher_accumulates_across_writes(chunks: Vec<Vec<u8>>) -> bool {
146        use std::io::Write as _;
147
148        let mut split = CountingHasher::default();
149        for chunk in &chunks {
150            split.write_all(chunk).unwrap();
151        }
152        split.flush().unwrap();
153
154        let joined_bytes = chunks.concat();
155        let mut joined = CountingHasher::default();
156        joined.write_all(&joined_bytes).unwrap();
157
158        split.written == joined_bytes.len() && split.hasher.finalize() == joined.hasher.finalize()
159    }
160
161    #[test]
162    fn get_or_init_computes_at_most_once() {
163        let calls = std::cell::Cell::new(0);
164        let memo = Memo::default();
165        let compute = || {
166            calls.set(calls.get() + 1);
167            EncodedCbor::compute(&[0u8; 4]).unwrap()
168        };
169        assert_eq!(*memo.get_or_init(compute), *memo.get_or_init(compute));
170        assert_eq!(calls.get(), 1);
171    }
172
173    #[quickcheck]
174    fn matches_buffered_encoding(msg: SignedMessage) -> bool {
175        let bytes = fvm_ipld_encoding::to_vec(&msg).unwrap();
176        Cid::from_cbor_blake2b256(&msg).unwrap()
177            == Cid::from_cbor_encoded_raw_bytes_blake2b256(&bytes)
178    }
179}