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 Solutions<N> { 19 /// Serializes the solutions to a JSON-string or buffer. 20 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { 21 match serializer.is_human_readable() { 22 true => { 23 let mut solutions = serializer.serialize_struct("Solutions", 1 + self.solutions.is_some() as usize)?; 24 solutions.serialize_field("version", &1u8)?; 25 if let Some(s) = &self.solutions { 26 solutions.serialize_field("solutions", s)?; 27 } 28 solutions.end() 29 } 30 false => ToBytesSerializer::serialize_with_size_encoding(self, serializer), 31 } 32 } 33 } 34 35 impl<'de, N: Network> Deserialize<'de> for Solutions<N> { 36 /// Deserializes the solutions from a JSON-string or buffer. 37 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 38 match deserializer.is_human_readable() { 39 true => { 40 // Deserialize the solutions into a JSON value. 41 let mut solutions = serde_json::Value::deserialize(deserializer)?; 42 43 // Retrieve the version. 44 let version: u8 = DeserializeExt::take_from_value::<D>(&mut solutions, "version")?; 45 // Ensure the version is valid. 46 if version != 1 { 47 return Err(de::Error::custom(format!("Invalid solutions version ({version})"))); 48 } 49 50 // Retrieve the solutions, if it exists. 51 Ok(Self { 52 solutions: serde_json::from_value( 53 solutions.get_mut("solutions").unwrap_or(&mut serde_json::Value::Null).take(), 54 ) 55 .map_err(de::Error::custom)?, 56 }) 57 } 58 false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "solutions"), 59 } 60 } 61 } 62 63 #[cfg(test)] 64 pub(super) mod tests { 65 use super::*; 66 use alphavm_ledger_puzzle::{PartialSolution, Solution}; 67 use console::account::{Address, PrivateKey}; 68 69 type CurrentNetwork = console::network::MainnetV0; 70 71 pub(crate) fn sample_solutions(rng: &mut TestRng) -> Solutions<CurrentNetwork> { 72 // Sample a new solutions. 73 let mut solutions = vec![]; 74 for _ in 0..rng.gen_range(1..=CurrentNetwork::MAX_SOLUTIONS) { 75 let private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap(); 76 let address = Address::try_from(private_key).unwrap(); 77 let partial_solution = PartialSolution::new(rng.r#gen(), address, u64::rand(rng)).unwrap(); 78 solutions.push(Solution::new(partial_solution, u64::rand(rng))); 79 } 80 Solutions::new(PuzzleSolutions::new(solutions).unwrap()).unwrap() 81 } 82 83 #[test] 84 fn test_serde_json() -> Result<()> { 85 let rng = &mut TestRng::default(); 86 87 // Sample a new solutions. 88 let expected = sample_solutions(rng); 89 90 // Serialize 91 let expected_string = &expected.to_string(); 92 let candidate_string = serde_json::to_string(&expected)?; 93 assert_eq!(expected, serde_json::from_str(&candidate_string)?); 94 95 // Deserialize 96 assert_eq!(expected, Solutions::from_str(expected_string)?); 97 assert_eq!(expected, serde_json::from_str(&candidate_string)?); 98 99 Ok(()) 100 } 101 102 #[test] 103 fn test_bincode() -> Result<()> { 104 let rng = &mut TestRng::default(); 105 106 // Sample a new solutions. 107 let expected = sample_solutions(rng); 108 109 // Serialize 110 let expected_bytes = expected.to_bytes_le()?; 111 let expected_bytes_with_size_encoding = bincode::serialize(&expected)?; 112 assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]); 113 114 // Deserialize 115 assert_eq!(expected, Solutions::read_le(&expected_bytes[..])?); 116 assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?); 117 118 Ok(()) 119 } 120 }