snarkvm_ledger_narwhal_transmission/
serialize.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> Serialize for Transmission<N> {
19    #[inline]
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => match self {
23                Self::Ratification => {
24                    let mut transmission = serializer.serialize_struct("Transmission", 1)?;
25                    transmission.serialize_field("type", "ratification")?;
26                    transmission.end()
27                }
28                Self::Solution(solution) => {
29                    let mut transmission = serializer.serialize_struct("Transmission", 2)?;
30                    transmission.serialize_field("type", "solution")?;
31                    transmission.serialize_field("transmission", solution)?;
32                    transmission.end()
33                }
34                Self::Transaction(transaction) => {
35                    let mut transmission = serializer.serialize_struct("Transmission", 2)?;
36                    transmission.serialize_field("type", "transaction")?;
37                    transmission.serialize_field("transmission", transaction)?;
38                    transmission.end()
39                }
40            },
41            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
42        }
43    }
44}
45
46impl<'de, N: Network> Deserialize<'de> for Transmission<N> {
47    #[inline]
48    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
49        match deserializer.is_human_readable() {
50            true => {
51                let mut transmission = serde_json::Value::deserialize(deserializer)?;
52                let type_: String = DeserializeExt::take_from_value::<D>(&mut transmission, "type")?;
53
54                // Recover the transmission.
55                match type_.as_str() {
56                    "ratification" => Ok(Self::Ratification),
57                    "solution" => Ok(Self::Solution(
58                        DeserializeExt::take_from_value::<D>(&mut transmission, "transmission")
59                            .map_err(de::Error::custom)?,
60                    )),
61                    "transaction" => Ok(Self::Transaction(
62                        DeserializeExt::take_from_value::<D>(&mut transmission, "transmission")
63                            .map_err(de::Error::custom)?,
64                    )),
65                    _ => Err(de::Error::custom(error("Invalid transmission type"))),
66                }
67            }
68            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "transmission"),
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    fn check_serde_json<
78        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
79    >(
80        expected: T,
81    ) {
82        // Serialize
83        let expected_string = &expected.to_string();
84        let candidate_string = serde_json::to_string(&expected).unwrap();
85        assert_eq!(expected_string, &serde_json::Value::from_str(&candidate_string).unwrap().to_string());
86
87        // Deserialize
88        assert_eq!(expected, T::from_str(expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
89        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
90    }
91
92    fn check_bincode<T: Serialize + for<'a> Deserialize<'a> + Debug + PartialEq + Eq + ToBytes + FromBytes>(
93        expected: T,
94    ) {
95        // Serialize
96        let expected_bytes = expected.to_bytes_le().unwrap();
97        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
98        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
99
100        // Deserialize
101        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
102        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
103    }
104
105    #[test]
106    fn test_serde_json() {
107        let rng = &mut TestRng::default();
108
109        for expected in crate::test_helpers::sample_transmissions(rng) {
110            check_serde_json(expected);
111        }
112    }
113
114    #[test]
115    fn test_bincode() {
116        let rng = &mut TestRng::default();
117
118        for expected in crate::test_helpers::sample_transmissions(rng) {
119            check_bincode(expected);
120        }
121    }
122}