snarkvm_ledger_coinbase/helpers/prover_solution/
serialize.rs

1// Copyright (C) 2019-2023 Aleo Systems 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// http://www.apache.org/licenses/LICENSE-2.0
8
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::*;
16
17use snarkvm_utilities::DeserializeExt;
18
19impl<N: Network> Serialize for ProverSolution<N> {
20    /// Serializes the prover solution to a JSON-string or buffer.
21    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
22        match serializer.is_human_readable() {
23            true => {
24                let mut prover_solution =
25                    serializer.serialize_struct("ProverSolution", 2 + self.proof.random_v.is_some() as usize)?;
26                prover_solution.serialize_field("partial_solution", &self.partial_solution)?;
27                prover_solution.serialize_field("proof.w", &self.proof.w)?;
28                if let Some(random_v) = &self.proof.random_v {
29                    prover_solution.serialize_field("proof.random_v", &random_v)?;
30                }
31                prover_solution.end()
32            }
33            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
34        }
35    }
36}
37
38impl<'de, N: Network> Deserialize<'de> for ProverSolution<N> {
39    /// Deserializes the prover solution from a JSON-string or buffer.
40    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
41        match deserializer.is_human_readable() {
42            true => {
43                let mut prover_solution = serde_json::Value::deserialize(deserializer)?;
44                Ok(Self::new(
45                    DeserializeExt::take_from_value::<D>(&mut prover_solution, "partial_solution")?,
46                    KZGProof {
47                        w: DeserializeExt::take_from_value::<D>(&mut prover_solution, "proof.w")?,
48                        random_v: serde_json::from_value(
49                            prover_solution.get_mut("proof.random_v").unwrap_or(&mut serde_json::Value::Null).take(),
50                        )
51                        .map_err(de::Error::custom)?,
52                    },
53                ))
54            }
55            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "prover solution"),
56        }
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use console::{account::PrivateKey, network::Testnet3};
64
65    type CurrentNetwork = Testnet3;
66
67    #[test]
68    fn test_serde_json() -> Result<()> {
69        let mut rng = TestRng::default();
70        let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
71        let address = Address::try_from(private_key)?;
72
73        // Sample a new prover puzzle solution.
74        let partial_solution = PartialSolution::new(address, u64::rand(&mut rng), KZGCommitment(rng.gen()));
75        let expected = ProverSolution::new(partial_solution, KZGProof { w: rng.gen(), random_v: None });
76
77        // Serialize
78        let expected_string = &expected.to_string();
79        let candidate_string = serde_json::to_string(&expected)?;
80        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
81
82        // Deserialize
83        assert_eq!(expected, ProverSolution::from_str(expected_string)?);
84        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
85
86        Ok(())
87    }
88
89    #[test]
90    fn test_bincode() -> Result<()> {
91        let mut rng = TestRng::default();
92        let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
93        let address = Address::try_from(private_key)?;
94
95        // Sample a new prover puzzle solution.
96        let partial_solution = PartialSolution::new(address, u64::rand(&mut rng), KZGCommitment(rng.gen()));
97        let expected = ProverSolution::new(partial_solution, KZGProof { w: rng.gen(), random_v: None });
98
99        // Serialize
100        let expected_bytes = expected.to_bytes_le()?;
101        let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
102        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
103
104        // Deserialize
105        assert_eq!(expected, ProverSolution::read_le(&expected_bytes[..])?);
106        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
107
108        Ok(())
109    }
110}