snarkvm_ledger_authority/
serialize.rs

1// Copyright 2024 Aleo Network Foundation
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 Authority<N> {
19    /// Serializes the authority into string or bytes.
20    #[inline]
21    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
22        match serializer.is_human_readable() {
23            true => {
24                let mut authority = serializer.serialize_struct("Authority", 2)?;
25                match self {
26                    Self::Beacon(signature) => {
27                        authority.serialize_field("type", "beacon")?;
28                        authority.serialize_field("signature", signature)?;
29                    }
30                    Self::Quorum(subdag) => {
31                        authority.serialize_field("type", "quorum")?;
32                        authority.serialize_field("subdag", subdag)?;
33                    }
34                }
35                authority.end()
36            }
37            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
38        }
39    }
40}
41
42impl<'de, N: Network> Deserialize<'de> for Authority<N> {
43    /// Deserializes the authority from a string or bytes.
44    #[inline]
45    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
46        match deserializer.is_human_readable() {
47            true => {
48                let mut authority = serde_json::Value::deserialize(deserializer)?;
49                let type_: String = DeserializeExt::take_from_value::<D>(&mut authority, "type")?;
50
51                // Recover the authority.
52                match type_.as_str() {
53                    "beacon" => Ok(Self::from_beacon(
54                        DeserializeExt::take_from_value::<D>(&mut authority, "signature").map_err(de::Error::custom)?,
55                    )),
56                    "quorum" => Ok(Self::from_quorum(
57                        DeserializeExt::take_from_value::<D>(&mut authority, "subdag").map_err(de::Error::custom)?,
58                    )),
59                    _ => Err(de::Error::custom(error("Invalid authority type"))),
60                }
61            }
62            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "authority"),
63        }
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use console::prelude::TestRng;
71
72    fn check_serde_json<
73        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
74    >(
75        expected: T,
76    ) {
77        // Serialize
78        let expected_string = &expected.to_string();
79        let candidate_string = serde_json::to_string(&expected).unwrap();
80        assert_eq!(expected_string, &serde_json::Value::from_str(&candidate_string).unwrap().to_string());
81
82        // Deserialize
83        assert_eq!(expected, T::from_str(expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
84        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
85    }
86
87    fn check_bincode<T: Serialize + for<'a> Deserialize<'a> + Debug + PartialEq + Eq + ToBytes + FromBytes>(
88        expected: T,
89    ) {
90        // Serialize
91        let expected_bytes = expected.to_bytes_le().unwrap();
92        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
93        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
94
95        // Deserialize
96        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
97        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
98    }
99
100    #[test]
101    fn test_serde_json() {
102        let rng = &mut TestRng::default();
103
104        for expected in crate::test_helpers::sample_authorities(rng) {
105            check_serde_json(expected);
106        }
107    }
108
109    #[test]
110    fn test_bincode() {
111        let rng = &mut TestRng::default();
112
113        for expected in crate::test_helpers::sample_authorities(rng) {
114            check_bincode(expected);
115        }
116    }
117}