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