snarkvm_console_account/graph_key/
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 GraphKey<N> {
19    /// Serializes an account graph key into bytes.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        ToBytesSerializer::serialize(self, serializer)
22    }
23}
24
25impl<'de, N: Network> Deserialize<'de> for GraphKey<N> {
26    /// Deserializes an account graph key from bytes.
27    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
28        FromBytesDeserializer::<Self>::deserialize(deserializer, "graph key", (N::Field::size_in_bits() + 7) / 8)
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35    use crate::PrivateKey;
36    use snarkvm_console_network::MainnetV0;
37
38    type CurrentNetwork = MainnetV0;
39
40    const ITERATIONS: u64 = 1000;
41
42    #[test]
43    fn test_bincode() -> Result<()> {
44        let mut rng = TestRng::default();
45
46        for _ in 0..ITERATIONS {
47            // Sample a new graph key.
48            let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
49            let view_key = ViewKey::try_from(private_key)?;
50            let expected = GraphKey::try_from(view_key)?;
51
52            // Serialize
53            let expected_bytes = expected.to_bytes_le()?;
54            assert_eq!(&expected_bytes[..], &bincode::serialize(&expected)?[..]);
55
56            // Deserialize
57            assert_eq!(expected, GraphKey::read_le(&expected_bytes[..])?);
58            assert_eq!(expected, bincode::deserialize(&expected_bytes[..])?);
59        }
60        Ok(())
61    }
62}