snarkvm_ledger_coinbase/helpers/partial_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 PartialSolution<N> {
18    /// Reads the partial solution from the buffer.
19    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
20        let address: Address<N> = FromBytes::read_le(&mut reader)?;
21        let nonce = u64::read_le(&mut reader)?;
22        let commitment = KZGCommitment::read_le(&mut reader)?;
23
24        Ok(Self::new(address, nonce, commitment))
25    }
26}
27
28impl<N: Network> ToBytes for PartialSolution<N> {
29    /// Writes the partial solution to the buffer.
30    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
31        self.address.write_le(&mut writer)?;
32        self.nonce.write_le(&mut writer)?;
33        self.commitment.write_le(&mut writer)
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use console::{account::PrivateKey, network::Testnet3};
41
42    type CurrentNetwork = Testnet3;
43
44    #[test]
45    fn test_bytes() -> Result<()> {
46        let mut rng = TestRng::default();
47        let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
48        let address = Address::try_from(private_key)?;
49
50        // Sample a new partial solution.
51        let expected = PartialSolution::new(address, u64::rand(&mut rng), KZGCommitment(rng.gen()));
52
53        // Check the byte representation.
54        let expected_bytes = expected.to_bytes_le()?;
55        assert_eq!(expected, PartialSolution::read_le(&expected_bytes[..])?);
56        assert!(PartialSolution::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
57
58        Ok(())
59    }
60}