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