snarkvm_ledger_coinbase/helpers/coinbase_solution/
bytes.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
17impl<N: Network> FromBytes for CoinbaseSolution<N> {
18    /// Reads the solutions from the buffer.
19    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
20        // Read the number of solutions.
21        let num_solutions: u16 = FromBytes::read_le(&mut reader)?;
22        // Read the solutions.
23        let mut prover_solutions = Vec::with_capacity(num_solutions as usize);
24        for _ in 0..num_solutions {
25            prover_solutions.push(ProverSolution::read_le(&mut reader)?);
26        }
27        // Return the solutions.
28        Self::new(prover_solutions).map_err(error)
29    }
30}
31
32impl<N: Network> ToBytes for CoinbaseSolution<N> {
33    /// Writes the solutions to the buffer.
34    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
35        // Write the number of solutions.
36        (u16::try_from(self.solutions.len()).map_err(|e| error(e.to_string()))?).write_le(&mut writer)?;
37        // Write the solutions.
38        for solution in self.solutions.values() {
39            solution.write_le(&mut writer)?;
40        }
41        Ok(())
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_bytes() -> Result<()> {
51        let mut rng = TestRng::default();
52
53        // Sample random solutions.
54        let expected = crate::helpers::coinbase_solution::serialize::tests::sample_solutions(&mut rng);
55
56        // Check the byte representation.
57        let expected_bytes = expected.to_bytes_le()?;
58        assert_eq!(expected, CoinbaseSolution::read_le(&expected_bytes[..])?);
59        Ok(())
60    }
61}