1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::shim::address::Address;
use blake2b_simd::Params;
use fil_actors_shared::filecoin_proofs_api::ProverId;
use fvm_ipld_encoding::strict_bytes::{Deserialize, Serialize};
use serde::{de, ser, Deserializer, Serializer};

mod fallback_de_ipld_dagcbor;

/// This method will attempt to de-serialize given bytes using the regular
/// `serde_ipld_dagcbor::from_slice`. Due to a historical issue in Lotus (see more in
/// [FIP-0027](https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0027.md), we must still
/// support strings with invalid UTF-8 bytes. On a failure, it
/// will retry the operation using the fallback that will de-serialize
/// strings with invalid UTF-8 bytes as bytes.
pub fn from_slice_with_fallback<'a, T: serde::de::Deserialize<'a>>(
    bytes: &'a [u8],
) -> anyhow::Result<T> {
    match serde_ipld_dagcbor::from_slice(bytes) {
        Ok(v) => Ok(v),
        Err(err) => fallback_de_ipld_dagcbor::from_slice(bytes).map_err(|fallback_err| {
            anyhow::anyhow!(
                "Fallback deserialization failed: {fallback_err}. Original error: {err}"
            )
        }),
    }
}

mod cid_de_cbor;
pub use cid_de_cbor::extract_cids;

/// `serde_bytes` with max length check
pub mod serde_byte_array {
    use super::*;
    /// lotus use cbor-gen for generating codec for types, it has a length limit
    /// for byte array as `2 << 20`
    ///
    /// <https://github.com/whyrusleeping/cbor-gen/blob/f57984553008dd4285df16d4ec2760f97977d713/gen.go#L16>
    pub const BYTE_ARRAY_MAX_LEN: usize = 2 << 20;

    /// checked if `input > crate::utils::BYTE_ARRAY_MAX_LEN`
    pub fn serialize<T, S>(bytes: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: ?Sized + Serialize + AsRef<[u8]>,
        S: Serializer,
    {
        let len = bytes.as_ref().len();
        if len > BYTE_ARRAY_MAX_LEN {
            return Err(ser::Error::custom::<String>(
                "Array exceed max length".into(),
            ));
        }

        Serialize::serialize(bytes, serializer)
    }

    /// checked if `output > crate::utils::ByteArrayMaxLen`
    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
    where
        T: Deserialize<'de> + AsRef<[u8]>,
        D: Deserializer<'de>,
    {
        Deserialize::deserialize(deserializer).and_then(|bytes: T| {
            if bytes.as_ref().len() > BYTE_ARRAY_MAX_LEN {
                Err(de::Error::custom::<String>(
                    "Array exceed max length".into(),
                ))
            } else {
                Ok(bytes)
            }
        })
    }
}

/// Generates BLAKE2b hash of fixed 32 bytes size.
///
/// # Example
/// ```
/// # use forest_filecoin::doctest_private::blake2b_256;
///
/// let ingest: Vec<u8> = vec![];
/// let hash = blake2b_256(&ingest);
/// assert_eq!(hash.len(), 32);
/// ```
pub fn blake2b_256(ingest: &[u8]) -> [u8; 32] {
    let digest = Params::new()
        .hash_length(32)
        .to_state()
        .update(ingest)
        .finalize();

    let mut ret = [0u8; 32];
    ret.clone_from_slice(digest.as_bytes());
    ret
}

pub fn prover_id_from_u64(id: u64) -> ProverId {
    let mut prover_id = ProverId::default();
    let prover_bytes = Address::new_id(id).payload().to_raw_bytes();
    assert!(prover_bytes.len() <= prover_id.len());
    #[allow(clippy::indexing_slicing)]
    prover_id[..prover_bytes.len()].copy_from_slice(&prover_bytes);
    prover_id
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;
    use libipld::Ipld;
    use rand::Rng;
    use serde::{Deserialize, Serialize};
    use serde_ipld_dagcbor::to_vec;

    use super::*;
    use crate::utils::encoding::serde_byte_array::BYTE_ARRAY_MAX_LEN;

    #[test]
    fn vector_hashing() {
        let ing_vec = vec![1, 2, 3];

        assert_eq!(blake2b_256(&ing_vec), blake2b_256(&[1, 2, 3]));
        assert_ne!(blake2b_256(&ing_vec), blake2b_256(&[1, 2, 3, 4]));
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
    struct ByteArray {
        #[serde(with = "serde_byte_array")]
        pub inner: Vec<u8>,
    }

    #[test]
    fn can_serialize_byte_array() {
        for len in [0, 1, BYTE_ARRAY_MAX_LEN] {
            let bytes = ByteArray {
                inner: vec![0; len],
            };

            assert!(serde_ipld_dagcbor::to_vec(&bytes).is_ok());
        }
    }

    #[test]
    fn cannot_serialize_byte_array_overflow() {
        let bytes = ByteArray {
            inner: vec![0; BYTE_ARRAY_MAX_LEN + 1],
        };

        assert!(
            format!("{}", serde_ipld_dagcbor::to_vec(&bytes).err().unwrap())
                .contains("Array exceed max length")
        );
    }

    #[test]
    fn can_deserialize_byte_array() {
        for len in [0, 1, BYTE_ARRAY_MAX_LEN] {
            let bytes = ByteArray {
                inner: vec![0; len],
            };

            let encoding = serde_ipld_dagcbor::to_vec(&bytes).unwrap();
            assert_eq!(
                from_slice_with_fallback::<ByteArray>(&encoding).unwrap(),
                bytes
            );
        }
    }

    #[test]
    fn cannot_deserialize_byte_array_overflow() {
        let max_length_bytes = ByteArray {
            inner: vec![0; BYTE_ARRAY_MAX_LEN],
        };

        // prefix: 2 ^ 21 -> 2 ^ 21 + 1
        let mut overflow_encoding = serde_ipld_dagcbor::to_vec(&max_length_bytes).unwrap();
        let encoding_len = overflow_encoding.len();
        overflow_encoding[encoding_len - BYTE_ARRAY_MAX_LEN - 1] = 1;
        overflow_encoding.push(0);

        assert!(format!(
            "{}",
            from_slice_with_fallback::<ByteArray>(&overflow_encoding)
                .err()
                .unwrap()
        )
        .contains("Array exceed max length"));
    }

    #[test]
    fn parity_tests() {
        use cs_serde_bytes;

        #[derive(Deserialize, Serialize)]
        struct A(#[serde(with = "fvm_ipld_encoding::strict_bytes")] Vec<u8>);

        #[derive(Deserialize, Serialize)]
        struct B(#[serde(with = "cs_serde_bytes")] Vec<u8>);

        let mut array = [0; 1024];
        rand::rngs::OsRng.fill(&mut array);

        let a = A(array.to_vec());
        let b = B(array.to_vec());

        assert_eq!(
            serde_json::to_string_pretty(&a).unwrap(),
            serde_json::to_string_pretty(&b).unwrap()
        );
    }

    #[test]
    fn test_fallback_deserialization() {
        // where the regular deserialization fails with invalid UTF-8 strings, the fallback should
        // succeed.

        // Valid UTF-8, should return the same results.
        let ipld_string = Ipld::String("cthulhu".to_string());
        let serialized = to_vec(&ipld_string).unwrap();
        assert_eq!(
            ipld_string,
            serde_ipld_dagcbor::from_slice::<Ipld>(&serialized).unwrap()
        );
        assert_eq!(
            ipld_string,
            from_slice_with_fallback::<Ipld>(&serialized).unwrap()
        );

        // Invalid UTF-8, regular deserialization fails, fallback succeeds. We can
        // extract the bytes.
        let corrupted = serialized
            .iter()
            .take(serialized.len() - 2)
            .chain(&[0xa0, 0xa1])
            .copied()
            .collect_vec();
        assert!(
            matches!(from_slice_with_fallback::<Ipld>(&corrupted).unwrap(), Ipld::Bytes(bytes) if bytes == [0x63, 0x74, 0x68, 0x75, 0x6c, 0xa0, 0xa1])
        )
    }
}