snarkvm_ledger_coinbase/helpers/epoch_challenge/
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 EpochChallenge<N> {
18    /// Reads the epoch challenge from a buffer.
19    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
20        // Read the epoch number.
21        let epoch_number = FromBytes::read_le(&mut reader)?;
22        // Read the epoch block hash.
23        let epoch_block_hash = FromBytes::read_le(&mut reader)?;
24        // Read the epoch degree.
25        let degree = FromBytes::read_le(&mut reader)?;
26        // Return the epoch challenge.
27        Self::new(epoch_number, epoch_block_hash, degree).map_err(|e| error(e.to_string()))
28    }
29}
30
31impl<N: Network> ToBytes for EpochChallenge<N> {
32    /// Writes the epoch challenge to a buffer.
33    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
34        // Write the epoch number.
35        self.epoch_number.write_le(&mut writer)?;
36        // Write the epoch block hash.
37        self.epoch_block_hash.write_le(&mut writer)?;
38        // Write the epoch degree.
39        self.degree().write_le(&mut writer)
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use console::network::Testnet3;
47
48    use rand::RngCore;
49
50    type CurrentNetwork = Testnet3;
51
52    const ITERATIONS: usize = 100;
53
54    #[test]
55    fn test_bytes() {
56        let mut rng = TestRng::default();
57
58        for _ in 0..ITERATIONS {
59            // Sample a new epoch challenge.
60            let degree: u16 = rng.gen(); // Bound the maximal test degree to 2^16.
61            let expected = EpochChallenge::<CurrentNetwork>::new(rng.next_u32(), rng.gen(), degree as u32).unwrap();
62
63            // Check the byte representation.
64            let expected_bytes = expected.to_bytes_le().unwrap();
65            let candidate = EpochChallenge::read_le(&expected_bytes[..]).unwrap();
66            assert_eq!(expected.epoch_number(), candidate.epoch_number());
67            assert_eq!(expected.epoch_block_hash(), candidate.epoch_block_hash());
68            assert_eq!(expected.degree(), candidate.degree());
69            assert_eq!(expected, candidate);
70
71            assert!(EpochChallenge::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
72        }
73    }
74}