Skip to main content

snarkvm_ledger_block/transition/output/
serialize.rs

1// Copyright (c) 2019-2026 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                Self::DynamicRecord(id) => {
82                    let mut output = serializer.serialize_struct("Output", 2)?;
83                    output.serialize_field("type", "record_dynamic")?;
84                    output.serialize_field("id", &id)?;
85                    output.end()
86                }
87                Self::RecordWithDynamicID(id, checksum, value, sender_ciphertext, dynamic_id) => {
88                    let mut output = serializer.serialize_struct(
89                        "Output",
90                        4 + value.is_some() as usize + sender_ciphertext.is_some() as usize,
91                    )?;
92                    output.serialize_field("type", "record_with_dynamic_id")?;
93                    output.serialize_field("id", &id)?;
94                    output.serialize_field("checksum", &checksum)?;
95                    if let Some(value) = value {
96                        output.serialize_field("value", &value)?;
97                    }
98                    if let Some(sender_ciphertext) = sender_ciphertext {
99                        output.serialize_field("sender_ciphertext", &sender_ciphertext)?;
100                    }
101                    output.serialize_field("dynamic_id", &dynamic_id)?;
102                    output.end()
103                }
104                Self::ExternalRecordWithDynamicID(id, dynamic_id) => {
105                    let mut output = serializer.serialize_struct("Output", 3)?;
106                    output.serialize_field("type", "external_record_with_dynamic_id")?;
107                    output.serialize_field("id", &id)?;
108                    output.serialize_field("dynamic_id", &dynamic_id)?;
109                    output.end()
110                }
111            },
112            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
113        }
114    }
115}
116
117impl<'de, N: Network> Deserialize<'de> for Output<N> {
118    /// Deserializes the transition output from a string or bytes.
119    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
120        match deserializer.is_human_readable() {
121            true => {
122                // Parse the output from a string into a value.
123                let mut output = serde_json::Value::deserialize(deserializer)?;
124                // Retrieve the ID.
125                let id: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "id")?;
126
127                // Recover the output.
128                let output = match output.get("type").and_then(|t| t.as_str()) {
129                    Some("constant") => Output::Constant(id, match output.get("value").and_then(|v| v.as_str()) {
130                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
131                        None => None,
132                    }),
133                    Some("public") => Output::Public(id, match output.get("value").and_then(|v| v.as_str()) {
134                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
135                        None => None,
136                    }),
137                    Some("private") => Output::Private(id, match output.get("value").and_then(|v| v.as_str()) {
138                        Some(value) => Some(Ciphertext::<N>::from_str(value).map_err(de::Error::custom)?),
139                        None => None,
140                    }),
141                    Some("record") => {
142                        // Retrieve the checksum.
143                        let checksum: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "checksum")?;
144                        // Return the record.
145                        Output::Record(
146                            id,
147                            checksum,
148                            match output.get("value").and_then(|v| v.as_str()) {
149                                Some(value) => {
150                                    Some(Record::<N, Ciphertext<N>>::from_str(value).map_err(de::Error::custom)?)
151                                }
152                                None => None,
153                            },
154                            match output.get("sender_ciphertext").and_then(|v| v.as_str()) {
155                                Some(value) => Some(Field::<N>::from_str(value).map_err(de::Error::custom)?),
156                                None => None,
157                            },
158                        )
159                    }
160                    Some("external_record") => Output::ExternalRecord(id),
161                    Some("future") => Output::Future(id, match output.get("value").and_then(|v| v.as_str()) {
162                        Some(value) => Some(Future::<N>::from_str(value).map_err(de::Error::custom)?),
163                        None => None,
164                    }),
165                    Some("record_dynamic") => Output::DynamicRecord(id),
166                    Some("record_with_dynamic_id") => {
167                        // Retrieve the checksum.
168                        let checksum: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "checksum")?;
169                        // Retrieve the dynamic ID.
170                        let dynamic_id: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "dynamic_id")?;
171                        // Return the record with dynamic ID.
172                        Output::RecordWithDynamicID(
173                            id,
174                            checksum,
175                            match output.get("value").and_then(|v| v.as_str()) {
176                                Some(value) => {
177                                    Some(Record::<N, Ciphertext<N>>::from_str(value).map_err(de::Error::custom)?)
178                                }
179                                None => None,
180                            },
181                            match output.get("sender_ciphertext").and_then(|v| v.as_str()) {
182                                Some(value) => Some(Field::<N>::from_str(value).map_err(de::Error::custom)?),
183                                None => None,
184                            },
185                            dynamic_id,
186                        )
187                    }
188                    Some("external_record_with_dynamic_id") => {
189                        // Retrieve the dynamic ID.
190                        let dynamic_id: Field<N> = DeserializeExt::take_from_value::<D>(&mut output, "dynamic_id")?;
191                        Output::ExternalRecordWithDynamicID(id, dynamic_id)
192                    }
193                    _ => return Err(de::Error::custom("Invalid output type")),
194                };
195
196                // Return the output.
197                Ok(output)
198            }
199            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "transition output"),
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn check_serde_json<
209        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
210    >(
211        expected: T,
212    ) {
213        // Serialize
214        let expected_string = expected.to_string();
215        let candidate_string = serde_json::to_string(&expected).unwrap();
216        let candidate = serde_json::from_str::<T>(&candidate_string).unwrap();
217        assert_eq!(expected, candidate);
218        assert_eq!(expected_string, candidate_string);
219        assert_eq!(expected_string, candidate.to_string());
220
221        // Deserialize
222        assert_eq!(expected, T::from_str(&expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
223        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
224    }
225
226    fn check_bincode<
227        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
228    >(
229        expected: T,
230    ) {
231        // Serialize
232        let expected_bytes = expected.to_bytes_le().unwrap();
233        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
234        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
235
236        // Deserialize
237        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
238        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
239    }
240
241    #[test]
242    fn test_serde_json() {
243        for (_, expected) in crate::transition::output::test_helpers::sample_outputs() {
244            check_serde_json(expected);
245        }
246    }
247
248    #[test]
249    fn test_bincode() {
250        for (_, expected) in crate::transition::output::test_helpers::sample_outputs() {
251            check_bincode(expected);
252        }
253    }
254}