/ console / program / src / data / record / serialize.rs
serialize.rs
  1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
  2  // This file is part of the alphavm 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  
 16  use super::*;
 17  
 18  impl<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  
 28  impl<'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  
 38  impl<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  
 48  impl<'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)]
 59  mod tests {
 60      use super::*;
 61      use alphavm_console_network::MainnetV0;
 62  
 63      type CurrentNetwork = MainnetV0;
 64  
 65      const ITERATIONS: u64 = 1;
 66  
 67      #[test]
 68      fn test_serde_json_without_version() -> Result<()> {
 69          for _ in 0..ITERATIONS {
 70              // Sample a new record.
 71              let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
 72                  "{ owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.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_serde_json_with_version() -> Result<()> {
 90          for _ in 0..ITERATIONS {
 91              // Sample a new record.
 92              let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
 93                  "{ owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.private, token_amount: 100u64.private, _nonce: 0group.public, _version: 1u8.public }",
 94              )?;
 95              println!("{}", serde_json::to_string_pretty(&expected)?);
 96  
 97              // Serialize
 98              let expected_string = &expected.to_string();
 99              let candidate_string = serde_json::to_string(&expected)?;
100              assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
101  
102              // Deserialize
103              assert_eq!(expected, Record::from_str(expected_string)?);
104              assert_eq!(expected, serde_json::from_str(&candidate_string)?);
105          }
106          Ok(())
107      }
108  
109      #[test]
110      fn test_bincode_without_version() -> Result<()> {
111          for _ in 0..ITERATIONS {
112              // Sample a new record.
113              let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
114                  "{ owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.private, token_amount: 100u64.private, _nonce: 0group.public }",
115              )?;
116  
117              // Serialize
118              let expected_bytes = expected.to_bytes_le()?;
119              let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
120              assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
121  
122              // Deserialize
123              assert_eq!(expected, Record::read_le(&expected_bytes[..])?);
124              assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
125          }
126          Ok(())
127      }
128  
129      #[test]
130      fn test_bincode_with_version() -> Result<()> {
131          for _ in 0..ITERATIONS {
132              // Sample a new record.
133              let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
134                  "{ owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.private, token_amount: 100u64.private, _nonce: 0group.public, _version: 1u8.public }",
135              )?;
136  
137              // Serialize
138              let expected_bytes = expected.to_bytes_le()?;
139              let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
140              assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
141  
142              // Deserialize
143              assert_eq!(expected, Record::read_le(&expected_bytes[..])?);
144              assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
145          }
146          Ok(())
147      }
148  }