snarkvm_console_program/data/record/
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 Record<N, Plaintext<N>> {
19    /// Serializes the record plaintext into a string or as bytes.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => serializer.collect_str(self),
23            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
24        }
25    }
26}
27
28impl<'de, N: Network> Deserialize<'de> for Record<N, Plaintext<N>> {
29    /// Deserializes the record plaintext from a string or bytes.
30    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
31        match deserializer.is_human_readable() {
32            true => FromStr::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom),
33            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "record plaintext"),
34        }
35    }
36}
37
38impl<N: Network> Serialize for Record<N, Ciphertext<N>> {
39    /// Serializes the record ciphertext into a string or as bytes.
40    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41        match serializer.is_human_readable() {
42            true => serializer.collect_str(self),
43            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
44        }
45    }
46}
47
48impl<'de, N: Network> Deserialize<'de> for Record<N, Ciphertext<N>> {
49    /// Deserializes the record ciphertext from a string or bytes.
50    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
51        match deserializer.is_human_readable() {
52            true => FromStr::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom),
53            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "record ciphertext"),
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use snarkvm_console_network::MainnetV0;
62
63    type CurrentNetwork = MainnetV0;
64
65    const ITERATIONS: u64 = 1;
66
67    #[test]
68    fn test_serde_json() -> Result<()> {
69        for _ in 0..ITERATIONS {
70            // Sample a new record.
71            let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
72                "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah.private, token_amount: 100u64.private, _nonce: 0group.public }",
73            )?;
74            println!("{}", serde_json::to_string_pretty(&expected)?);
75
76            // Serialize
77            let expected_string = &expected.to_string();
78            let candidate_string = serde_json::to_string(&expected)?;
79            assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
80
81            // Deserialize
82            assert_eq!(expected, Record::from_str(expected_string)?);
83            assert_eq!(expected, serde_json::from_str(&candidate_string)?);
84        }
85        Ok(())
86    }
87
88    #[test]
89    fn test_bincode() -> Result<()> {
90        for _ in 0..ITERATIONS {
91            // Sample a new record.
92            let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
93                "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah.private, token_amount: 100u64.private, _nonce: 0group.public }",
94            )?;
95
96            // Serialize
97            let expected_bytes = expected.to_bytes_le()?;
98            let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
99            assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
100
101            // Deserialize
102            assert_eq!(expected, Record::read_le(&expected_bytes[..])?);
103            assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
104        }
105        Ok(())
106    }
107}