Skip to main content

snarkvm_ledger_block/transition/input/
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 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                Self::DynamicRecord(id) => {
64                    let mut input = serializer.serialize_struct("Input", 2)?;
65                    input.serialize_field("type", "record_dynamic")?;
66                    input.serialize_field("id", &id)?;
67                    input.end()
68                }
69                Self::RecordWithDynamicID(id, tag, dynamic_id) => {
70                    let mut input = serializer.serialize_struct("Input", 4)?;
71                    input.serialize_field("type", "record_with_dynamic_id")?;
72                    input.serialize_field("id", &id)?;
73                    input.serialize_field("tag", &tag)?;
74                    input.serialize_field("dynamic_id", &dynamic_id)?;
75                    input.end()
76                }
77                Self::ExternalRecordWithDynamicID(id, dynamic_id) => {
78                    let mut input = serializer.serialize_struct("Input", 3)?;
79                    input.serialize_field("type", "external_record_with_dynamic_id")?;
80                    input.serialize_field("id", &id)?;
81                    input.serialize_field("dynamic_id", &dynamic_id)?;
82                    input.end()
83                }
84            },
85            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
86        }
87    }
88}
89
90impl<'de, N: Network> Deserialize<'de> for Input<N> {
91    /// Deserializes the transition input from a string or bytes.
92    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
93        match deserializer.is_human_readable() {
94            true => {
95                // Parse the input from a string into a value.
96                let mut input = serde_json::Value::deserialize(deserializer)?;
97                // Retrieve the ID.
98                let id: Field<N> = DeserializeExt::take_from_value::<D>(&mut input, "id")?;
99
100                // Recover the input.
101                let input = match input.get("type").and_then(|t| t.as_str()) {
102                    Some("constant") => Input::Constant(id, match input.get("value").and_then(|v| v.as_str()) {
103                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
104                        None => None,
105                    }),
106                    Some("public") => Input::Public(id, match input.get("value").and_then(|v| v.as_str()) {
107                        Some(value) => Some(Plaintext::<N>::from_str(value).map_err(de::Error::custom)?),
108                        None => None,
109                    }),
110                    Some("private") => Input::Private(id, match input.get("value").and_then(|v| v.as_str()) {
111                        Some(value) => Some(Ciphertext::<N>::from_str(value).map_err(de::Error::custom)?),
112                        None => None,
113                    }),
114                    Some("record") => Input::Record(id, DeserializeExt::take_from_value::<D>(&mut input, "tag")?),
115                    Some("external_record") => Input::ExternalRecord(id),
116                    Some("record_dynamic") => Input::DynamicRecord(id),
117                    Some("record_with_dynamic_id") => Input::RecordWithDynamicID(
118                        id,
119                        DeserializeExt::take_from_value::<D>(&mut input, "tag")?,
120                        DeserializeExt::take_from_value::<D>(&mut input, "dynamic_id")?,
121                    ),
122                    Some("external_record_with_dynamic_id") => Input::ExternalRecordWithDynamicID(
123                        id,
124                        DeserializeExt::take_from_value::<D>(&mut input, "dynamic_id")?,
125                    ),
126                    _ => return Err(de::Error::custom("Invalid transition input type")),
127                };
128                // Return the input.
129                Ok(input)
130            }
131            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "transition input"),
132        }
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    fn check_serde_json<
141        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
142    >(
143        expected: T,
144    ) {
145        // Serialize
146        let expected_string = expected.to_string();
147        let candidate_string = serde_json::to_string(&expected).unwrap();
148        let candidate = serde_json::from_str::<T>(&candidate_string).unwrap();
149        assert_eq!(expected, candidate);
150        assert_eq!(expected_string, candidate_string);
151        assert_eq!(expected_string, candidate.to_string());
152
153        // Deserialize
154        assert_eq!(expected, T::from_str(&expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
155        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
156    }
157
158    fn check_bincode<
159        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
160    >(
161        expected: T,
162    ) {
163        // Serialize
164        let expected_bytes = expected.to_bytes_le().unwrap();
165        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
166        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
167
168        // Deserialize
169        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
170        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
171    }
172
173    #[test]
174    fn test_serde_json() {
175        for (_, input) in crate::transition::input::test_helpers::sample_inputs() {
176            check_serde_json(input);
177        }
178    }
179
180    #[test]
181    fn test_bincode() {
182        for (_, input) in crate::transition::input::test_helpers::sample_inputs() {
183            check_bincode(input);
184        }
185    }
186}