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