/ ledger / block / src / transaction / execution / 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 Execution<N> {
 19      /// Serializes the execution 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 => {
 23                  let mut execution = serializer.serialize_struct("Execution", 2 + self.proof.is_some() as usize)?;
 24                  execution
 25                      .serialize_field("transitions", &self.transitions.values().collect::<Vec<&Transition<N>>>())?;
 26                  execution.serialize_field("global_state_root", &self.global_state_root)?;
 27                  if let Some(proof) = &self.proof {
 28                      execution.serialize_field("proof", proof)?;
 29                  }
 30                  execution.end()
 31              }
 32              false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
 33          }
 34      }
 35  }
 36  
 37  impl<'de, N: Network> Deserialize<'de> for Execution<N> {
 38      /// Deserializes the execution from a string or bytes.
 39      fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
 40          match deserializer.is_human_readable() {
 41              true => {
 42                  // Parse the execution from a string into a value.
 43                  let mut execution = serde_json::Value::deserialize(deserializer)?;
 44                  // Retrieve the transitions.
 45                  let transitions: Vec<_> = DeserializeExt::take_from_value::<D>(&mut execution, "transitions")?;
 46                  // Retrieve the global state root.
 47                  let global_state_root = DeserializeExt::take_from_value::<D>(&mut execution, "global_state_root")?;
 48                  // Retrieve the proof.
 49                  let proof =
 50                      serde_json::from_value(execution.get_mut("proof").unwrap_or(&mut serde_json::Value::Null).take())
 51                          .map_err(de::Error::custom)?;
 52                  // Recover the execution.
 53                  Self::from(transitions.into_iter(), global_state_root, proof).map_err(de::Error::custom)
 54              }
 55              false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "execution"),
 56          }
 57      }
 58  }
 59  
 60  #[cfg(test)]
 61  mod tests {
 62      use super::*;
 63  
 64      #[test]
 65      fn test_serde_json() -> Result<()> {
 66          let rng = &mut TestRng::default();
 67  
 68          // Sample the execution.
 69          let expected = crate::transaction::execution::test_helpers::sample_execution(rng, 0);
 70  
 71          // Serialize
 72          let expected_string = &expected.to_string();
 73          let candidate_string = serde_json::to_string(&expected)?;
 74          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 75  
 76          // Deserialize
 77          assert_eq!(expected, Execution::from_str(expected_string)?);
 78          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 79  
 80          Ok(())
 81      }
 82  
 83      #[test]
 84      fn test_bincode() -> Result<()> {
 85          let rng = &mut TestRng::default();
 86  
 87          // Sample the execution.
 88          let expected = crate::transaction::execution::test_helpers::sample_execution(rng, 0);
 89  
 90          // Serialize
 91          let expected_bytes = expected.to_bytes_le()?;
 92          let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
 93          assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
 94  
 95          // Deserialize
 96          assert_eq!(expected, Execution::read_le(&expected_bytes[..])?);
 97          assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
 98  
 99          Ok(())
100      }
101  }