snarkvm_ledger_block/transition/output/
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 Output<N> {
19    /// Serializes the transition output into string or bytes.
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::Constant(id, value) => {
24                    let mut output = serializer.serialize_struct("Output", 2 + value.is_some() as usize)?;
25                    output.serialize_field("type", "constant")?;
26                    output.serialize_field("id", &id)?;
27                    if let Some(value) = value {
28                        output.serialize_field("value", &value)?;
29                    }
30                    output.end()
31                }
32                Self::Public(id, value) => {
33                    let mut output = serializer.serialize_struct("Output", 2 + value.is_some() as usize)?;
34                    output.serialize_field("type", "public")?;
35                    output.serialize_field("id", &id)?;
36                    if let Some(value) = value {
37                        output.serialize_field("value", &value)?;
38                    }
39                    output.end()
40                }
41                Self::Private(id, value) => {
42                    let mut output = serializer.serialize_struct("Output", 2 + value.is_some() as usize)?;
43                    output.serialize_field("type", "private")?;
44                    output.serialize_field("id", &id)?;
45                    if let Some(value) = value {
46                        output.serialize_field("value", &value)?;
47                    }
48                    output.end()
49                }
50                Self::Record(id, checksum, value, sender_ciphertext) => {
51                    let mut output = serializer.serialize_struct(
52                        "Output",
53                        3 + value.is_some() as usize + sender_ciphertext.is_some() as usize,
54                    )?;
55                    output.serialize_field("type", "record")?;
56                    output.serialize_field("id", &id)?;
57                    output.serialize_field("checksum", &checksum)?;
58                    if let Some(value) = value {
59                        output.serialize_field("value", &value)?;
60                    }
61                    if let Some(sender_ciphertext) = sender_ciphertext {
62                        output.serialize_field("sender_ciphertext", &sender_ciphertext)?;
63                    }
64                    output.end()
65                }
66                Self::ExternalRecord(id) => {
67                    let mut output = serializer.serialize_struct("Output", 2)?;
68                    output.serialize_field("type", "external_record")?;
69                    output.serialize_field("id", &id)?;
70                    output.end()
71                }
72                Self::Future(id, value) => {
73                    let mut output = serializer.serialize_struct("Output", 2 + value.is_some() as usize)?;
74                    output.serialize_field("type", "future")?;
75                    output.serialize_field("id", &id)?;
76                    if let Some(value) = value {
77                        output.serialize_field("value", &value)?;
78                    }
79                    output.end()
80                }
81            },
82            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
83        }
84    }
85}
86
87impl<'de, N: Network> Deserialize<'de> for Output<N> {
88    /// Deserializes the transition output from a string or bytes.
89    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
90        match deserializer.is_human_readable() {
91            true => {
92                // Parse the output from a string into a value.
93                let mut output = serde_json::Value::deserialize(deserializer)?;
94                // Retrieve the ID.
95                let id: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "id")?;
96
97                // Recover the output.
98                let output = match output.get("type").and_then(|t| t.as_str()) {
99                    Some("constant") => Output::Constant(id, match output.get("value").and_then(|v| v.as_str()) {
100                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
101                        None => None,
102                    }),
103                    Some("public") => Output::Public(id, match output.get("value").and_then(|v| v.as_str()) {
104                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
105                        None => None,
106                    }),
107                    Some("private") => Output::Private(id, match output.get("value").and_then(|v| v.as_str()) {
108                        Some(value) => Some(Ciphertext::<N>::from_str(value).map_err(de::Error::custom)?),
109                        None => None,
110                    }),
111                    Some("record") => {
112                        // Retrieve the checksum.
113                        let checksum: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "checksum")?;
114                        // Return the record.
115                        Output::Record(
116                            id,
117                            checksum,
118                            match output.get("value").and_then(|v| v.as_str()) {
119                                Some(value) => {
120                                    Some(Record::<N, Ciphertext<N>>::from_str(value).map_err(de::Error::custom)?)
121                                }
122                                None => None,
123                            },
124                            match output.get("sender_ciphertext").and_then(|v| v.as_str()) {
125                                Some(value) => Some(Field::<N>::from_str(value).map_err(de::Error::custom)?),
126                                None => None,
127                            },
128                        )
129                    }
130                    Some("external_record") => Output::ExternalRecord(id),
131                    Some("future") => Output::Future(id, match output.get("value").and_then(|v| v.as_str()) {
132                        Some(value) => Some(Future::<N>::from_str(value).map_err(de::Error::custom)?),
133                        None => None,
134                    }),
135                    _ => return Err(de::Error::custom("Invalid output type")),
136                };
137
138                // Return the output.
139                Ok(output)
140            }
141            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "transition output"),
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn check_serde_json<
151        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
152    >(
153        expected: T,
154    ) {
155        // Serialize
156        let expected_string = expected.to_string();
157        let candidate_string = serde_json::to_string(&expected).unwrap();
158        let candidate = serde_json::from_str::<T>(&candidate_string).unwrap();
159        assert_eq!(expected, candidate);
160        assert_eq!(expected_string, candidate_string);
161        assert_eq!(expected_string, candidate.to_string());
162
163        // Deserialize
164        assert_eq!(expected, T::from_str(&expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
165        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
166    }
167
168    fn check_bincode<
169        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
170    >(
171        expected: T,
172    ) {
173        // Serialize
174        let expected_bytes = expected.to_bytes_le().unwrap();
175        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
176        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
177
178        // Deserialize
179        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
180        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
181    }
182
183    #[test]
184    fn test_serde_json() {
185        for (_, expected) in crate::transition::output::test_helpers::sample_outputs() {
186            check_serde_json(expected);
187        }
188    }
189
190    #[test]
191    fn test_bincode() {
192        for (_, expected) in crate::transition::output::test_helpers::sample_outputs() {
193            check_bincode(expected);
194        }
195    }
196}