/ ledger / puzzle / src / partial_solution / serialize.rs
serialize.rs
  1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
  2  // This file is part of the deltavm 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 PartialSolution<N> {
 19      /// Serializes the partial solution 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 partial_solution = serializer.serialize_struct("PartialSolution", 4)?;
 24                  partial_solution.serialize_field("solution_id", &self.solution_id)?;
 25                  partial_solution.serialize_field("epoch_hash", &self.epoch_hash)?;
 26                  partial_solution.serialize_field("address", &self.address)?;
 27                  partial_solution.serialize_field("counter", &self.counter)?;
 28                  partial_solution.end()
 29              }
 30              false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
 31          }
 32      }
 33  }
 34  
 35  impl<'de, N: Network> Deserialize<'de> for PartialSolution<N> {
 36      /// Deserializes the partial solution 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                  let mut partial_solution = serde_json::Value::deserialize(deserializer)?;
 41                  let solution_id: SolutionID<N> =
 42                      DeserializeExt::take_from_value::<D>(&mut partial_solution, "solution_id")?;
 43  
 44                  // Recover the partial solution.
 45                  let partial_solution = Self::new(
 46                      DeserializeExt::take_from_value::<D>(&mut partial_solution, "epoch_hash")?,
 47                      DeserializeExt::take_from_value::<D>(&mut partial_solution, "address")?,
 48                      DeserializeExt::take_from_value::<D>(&mut partial_solution, "counter")?,
 49                  )
 50                  .map_err(de::Error::custom)?;
 51  
 52                  // Ensure the solution ID matches.
 53                  match solution_id == partial_solution.id() {
 54                      true => Ok(partial_solution),
 55                      false => Err(de::Error::custom(error("Mismatching solution ID, possible data corruption"))),
 56                  }
 57              }
 58              false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "solution"),
 59          }
 60      }
 61  }
 62  
 63  #[cfg(test)]
 64  mod tests {
 65      use super::*;
 66      use console::{account::PrivateKey, network::MainnetV0};
 67  
 68      type CurrentNetwork = MainnetV0;
 69  
 70      #[test]
 71      fn test_serde_json() -> Result<()> {
 72          let mut rng = TestRng::default();
 73          let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
 74          let address = Address::try_from(private_key)?;
 75  
 76          // Sample a new partial solution.
 77          let expected = PartialSolution::new(rng.r#gen(), address, u64::rand(&mut rng)).unwrap();
 78  
 79          // Serialize
 80          let expected_string = &expected.to_string();
 81          let candidate_string = serde_json::to_string(&expected)?;
 82          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 83  
 84          // Deserialize
 85          assert_eq!(expected, PartialSolution::from_str(expected_string)?);
 86          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 87  
 88          Ok(())
 89      }
 90  
 91      #[test]
 92      fn test_bincode() -> Result<()> {
 93          let mut rng = TestRng::default();
 94          let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
 95          let address = Address::try_from(private_key)?;
 96  
 97          // Sample a new partial solution.
 98          let expected = PartialSolution::new(rng.r#gen(), address, u64::rand(&mut rng)).unwrap();
 99  
100          // Serialize
101          let expected_bytes = expected.to_bytes_le()?;
102          let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
103          assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
104  
105          // Deserialize
106          assert_eq!(expected, PartialSolution::read_le(&expected_bytes[..])?);
107          assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
108  
109          Ok(())
110      }
111  }