Skip to main content

forest/utils/encoding/
mod.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use crate::shim::address::Address;
5use blake2b_simd::Params;
6use fil_actors_shared::filecoin_proofs_api::ProverId;
7use fvm_ipld_encoding::strict_bytes::{Deserialize, Serialize};
8use serde::{Deserializer, Serializer, de, ser};
9
10mod fallback_de_ipld_dagcbor;
11pub mod hex;
12
13/// Limit the number of bytes that are used for pre-allocating `Vec<Cid>`s. This follows what `serde` is
14/// doing internally with `serde::private::size_hint::cautious()`.
15/// The limit is set to 1 MiB, which is a reasonable upper bound for most use cases.
16fn size_hint_cautious_cid(size_hint: usize) -> usize {
17    const MAX_PREALLOC_BYTES: usize = 1024 * 1024;
18    size_hint.min(MAX_PREALLOC_BYTES / std::mem::size_of::<cid::Cid>())
19}
20
21/// This method will attempt to de-serialize given bytes using the regular
22/// `serde_ipld_dagcbor::from_slice`. Due to a historical issue in Lotus (see more in
23/// [FIP-0027](https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0027.md), we must still
24/// support strings with invalid UTF-8 bytes. On a failure, it
25/// will retry the operation using the fallback that will de-serialize
26/// strings with invalid UTF-8 bytes as bytes.
27pub fn from_slice_with_fallback<'a, T: serde::de::Deserialize<'a>>(
28    bytes: &'a [u8],
29) -> anyhow::Result<T> {
30    match serde_ipld_dagcbor::from_slice(bytes) {
31        Ok(v) => Ok(v),
32        Err(err) => fallback_de_ipld_dagcbor::from_slice(bytes).map_err(|fallback_err| {
33            anyhow::anyhow!(
34                "Fallback deserialization failed: {fallback_err}. Original error: {err}"
35            )
36        }),
37    }
38}
39
40mod cid_de_cbor;
41pub use cid_de_cbor::extract_cids;
42
43/// `io::Write` that discards the bytes and only tracks how many were written.
44#[derive(Default)]
45struct CountingSink(usize);
46
47impl std::io::Write for CountingSink {
48    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
49        self.0 += buf.len();
50        Ok(buf.len())
51    }
52
53    fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
54        let n: usize = bufs.iter().map(|b| b.len()).sum();
55        self.0 += n;
56        Ok(n)
57    }
58
59    fn flush(&mut self) -> std::io::Result<()> {
60        Ok(())
61    }
62}
63
64/// Calculate the byte length of the `DAG_CBOR` encoding of `value`, without allocating it.
65pub fn calc_encoded_len<T: serde::Serialize>(value: &T) -> Result<usize, fvm_ipld_encoding::Error> {
66    let mut sink = CountingSink::default();
67    fvm_ipld_encoding::to_writer(&mut sink, value)?;
68    Ok(sink.0)
69}
70
71/// `serde_bytes` with max length check
72pub mod serde_byte_array {
73    use super::*;
74    /// lotus use cbor-gen for generating codec for types, it has a length limit
75    /// for byte array as `2 << 20`
76    ///
77    /// <https://github.com/whyrusleeping/cbor-gen/blob/f57984553008dd4285df16d4ec2760f97977d713/gen.go#L16>
78    pub const BYTE_ARRAY_MAX_LEN: usize = 2 << 20;
79
80    /// checked if `input > crate::utils::BYTE_ARRAY_MAX_LEN`
81    pub fn serialize<T, S>(bytes: &T, serializer: S) -> Result<S::Ok, S::Error>
82    where
83        T: ?Sized + Serialize + AsRef<[u8]>,
84        S: Serializer,
85    {
86        let len = bytes.as_ref().len();
87        if len > BYTE_ARRAY_MAX_LEN {
88            return Err(ser::Error::custom::<String>(
89                "Array exceed max length".into(),
90            ));
91        }
92
93        Serialize::serialize(bytes, serializer)
94    }
95
96    /// checked if `output > crate::utils::ByteArrayMaxLen`
97    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
98    where
99        T: Deserialize<'de> + AsRef<[u8]>,
100        D: Deserializer<'de>,
101    {
102        Deserialize::deserialize(deserializer).and_then(|bytes: T| {
103            if bytes.as_ref().len() > BYTE_ARRAY_MAX_LEN {
104                Err(de::Error::custom::<String>(
105                    "Array exceed max length".into(),
106                ))
107            } else {
108                Ok(bytes)
109            }
110        })
111    }
112}
113
114/// Generates BLAKE2b hash of fixed 32 bytes size.
115///
116/// # Example
117/// ```
118/// # use forest::doctest_private::blake2b_256;
119///
120/// let ingest: Vec<u8> = vec![];
121/// let hash = blake2b_256(&ingest);
122/// assert_eq!(hash.len(), 32);
123/// ```
124pub fn blake2b_256(ingest: &[u8]) -> [u8; 32] {
125    let digest = Params::new()
126        .hash_length(32)
127        .to_state()
128        .update(ingest)
129        .finalize();
130
131    let mut ret = [0u8; 32];
132    ret.clone_from_slice(digest.as_bytes());
133    ret
134}
135
136/// Generates Keccak-256 hash of fixed 32 bytes size.
137///
138/// # Example
139/// ```
140/// # use forest::doctest_private::keccak_256;
141/// let ingest: Vec<u8> = vec![];
142/// let hash = keccak_256(&ingest);
143/// assert_eq!(hash.len(), 32);
144/// ```
145pub fn keccak_256(ingest: &[u8]) -> [u8; 32] {
146    let mut ret: [u8; 32] = Default::default();
147    keccak_hash::keccak_256(ingest, &mut ret);
148    ret
149}
150
151pub fn prover_id_from_u64(id: u64) -> ProverId {
152    let mut prover_id = ProverId::default();
153    let prover_bytes = Address::new_id(id).payload().to_raw_bytes();
154    assert!(prover_bytes.len() <= prover_id.len());
155    #[allow(clippy::indexing_slicing)]
156    prover_id[..prover_bytes.len()].copy_from_slice(&prover_bytes);
157    prover_id
158}
159
160#[cfg(test)]
161mod tests {
162    use ipld_core::ipld::Ipld;
163    use itertools::Itertools as _;
164    use quickcheck_macros::quickcheck;
165    use rand::Rng;
166    use serde::{Deserialize, Serialize};
167    use serde_ipld_dagcbor::to_vec;
168
169    use super::*;
170    use crate::message::SignedMessage;
171    use crate::utils::encoding::serde_byte_array::BYTE_ARRAY_MAX_LEN;
172
173    #[quickcheck]
174    fn calc_encoded_len_matches_to_vec(msg: SignedMessage) -> bool {
175        calc_encoded_len(&msg).unwrap() == to_vec(&msg).unwrap().len()
176    }
177
178    #[test]
179    fn vector_hashing() {
180        let ing_vec = vec![1, 2, 3];
181
182        assert_eq!(blake2b_256(&ing_vec), blake2b_256(&[1, 2, 3]));
183        assert_ne!(blake2b_256(&ing_vec), blake2b_256(&[1, 2, 3, 4]));
184    }
185
186    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
187    struct ByteArray {
188        #[serde(with = "serde_byte_array")]
189        pub inner: Vec<u8>,
190    }
191
192    #[test]
193    fn can_serialize_byte_array() {
194        for len in [0, 1, BYTE_ARRAY_MAX_LEN] {
195            let bytes = ByteArray {
196                inner: vec![0; len],
197            };
198
199            assert!(serde_ipld_dagcbor::to_vec(&bytes).is_ok());
200        }
201    }
202
203    #[test]
204    fn cannot_serialize_byte_array_overflow() {
205        let bytes = ByteArray {
206            inner: vec![0; BYTE_ARRAY_MAX_LEN + 1],
207        };
208
209        let err = serde_ipld_dagcbor::to_vec(&bytes).unwrap_err();
210        assert!(
211            format!("{err}").contains("Struct value cannot be serialized."),
212            "{err}"
213        );
214    }
215
216    #[test]
217    fn can_deserialize_byte_array() {
218        for len in [0, 1, BYTE_ARRAY_MAX_LEN] {
219            let bytes = ByteArray {
220                inner: vec![0; len],
221            };
222
223            let encoding = serde_ipld_dagcbor::to_vec(&bytes).unwrap();
224            assert_eq!(
225                from_slice_with_fallback::<ByteArray>(&encoding).unwrap(),
226                bytes
227            );
228        }
229    }
230
231    #[test]
232    fn cannot_deserialize_byte_array_overflow() {
233        let max_length_bytes = ByteArray {
234            inner: vec![0; BYTE_ARRAY_MAX_LEN],
235        };
236
237        // prefix: 2 ^ 21 -> 2 ^ 21 + 1
238        let mut overflow_encoding = serde_ipld_dagcbor::to_vec(&max_length_bytes).unwrap();
239        let encoding_len = overflow_encoding.len();
240        overflow_encoding[encoding_len - BYTE_ARRAY_MAX_LEN - 1] = 1;
241        overflow_encoding.push(0);
242
243        assert!(
244            format!(
245                "{}",
246                from_slice_with_fallback::<ByteArray>(&overflow_encoding)
247                    .err()
248                    .unwrap()
249            )
250            .contains("Array exceed max length")
251        );
252    }
253
254    #[test]
255    fn parity_tests() {
256        use cs_serde_bytes;
257
258        #[derive(Deserialize, Serialize)]
259        struct A(#[serde(with = "fvm_ipld_encoding::strict_bytes")] Vec<u8>);
260
261        #[derive(Deserialize, Serialize)]
262        struct B(#[serde(with = "cs_serde_bytes")] Vec<u8>);
263
264        let mut array = [0; 1024];
265        crate::utils::rand::forest_rng().fill(&mut array);
266
267        let a = A(array.to_vec());
268        let b = B(array.to_vec());
269
270        assert_eq!(
271            serde_json::to_string_pretty(&a).unwrap(),
272            serde_json::to_string_pretty(&b).unwrap()
273        );
274    }
275
276    #[test]
277    fn test_fallback_deserialization() {
278        // where the regular deserialization fails with invalid UTF-8 strings, the fallback should
279        // succeed.
280
281        // Valid UTF-8, should return the same results.
282        let ipld_string = Ipld::String("cthulhu".to_string());
283        let serialized = to_vec(&ipld_string).unwrap();
284        assert_eq!(
285            ipld_string,
286            serde_ipld_dagcbor::from_slice::<Ipld>(&serialized).unwrap()
287        );
288        assert_eq!(
289            ipld_string,
290            from_slice_with_fallback::<Ipld>(&serialized).unwrap()
291        );
292
293        // Invalid UTF-8, regular deserialization fails, fallback succeeds. We can
294        // extract the bytes.
295        let corrupted = serialized
296            .iter()
297            .take(serialized.len() - 2)
298            .chain(&[0xa0, 0xa1])
299            .copied()
300            .collect_vec();
301        assert!(
302            matches!(from_slice_with_fallback::<Ipld>(&corrupted).unwrap(), Ipld::Bytes(bytes) if bytes == [0x63, 0x74, 0x68, 0x75, 0x6c, 0xa0, 0xa1])
303        )
304    }
305
306    #[test]
307    fn size_hint_cautious_test() {
308        assert_eq!(size_hint_cautious_cid(0), 0);
309        assert_eq!(
310            size_hint_cautious_cid(1024 * 1024),
311            1024 * 1024 / std::mem::size_of::<cid::Cid>()
312        );
313    }
314}