snarkvm_ledger_block/ratifications/
bytes.rs

1// Copyright (c) 2019-2025 Provable 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
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> FromBytes for Ratifications<N> {
19    /// Reads the ratifications from buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        // Read the version.
23        let version = u8::read_le(&mut reader)?;
24        // Ensure the version is valid.
25        if version != 1 {
26            return Err(error("Invalid ratifications version"));
27        }
28        // Read the number of ratifications.
29        let num_ratify: u32 = FromBytes::read_le(&mut reader)?;
30        // Ensure the number of ratifications is within bounds.
31        if num_ratify as usize > Self::MAX_RATIFICATIONS {
32            return Err(error("Failed to read ratifications: too many ratifications"));
33        }
34        // Read the ratifications.
35        let ratifications = (0..num_ratify).map(|_| FromBytes::read_le(&mut reader)).collect::<Result<Vec<_>, _>>()?;
36        // Return the ratifications.
37        Self::try_from(ratifications).map_err(into_io_error)
38    }
39}
40
41impl<N: Network> ToBytes for Ratifications<N> {
42    /// Writes the ratifications to a buffer.
43    #[inline]
44    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
45        // Write the version.
46        1u8.write_le(&mut writer)?;
47        // Write the number of ratifications.
48        u32::try_from(self.ratifications.len()).map_err(error)?.write_le(&mut writer)?;
49        // Write the ratifications.
50        self.ratifications.values().try_for_each(|ratification| ratification.write_le(&mut writer))
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    const ITERATIONS: u32 = 100;
59
60    #[test]
61    fn test_bytes() -> Result<()> {
62        let rng = &mut TestRng::default();
63
64        for _ in 0..ITERATIONS {
65            let expected = crate::ratifications::test_helpers::sample_block_ratifications(rng);
66            // Check the byte representation.
67            let expected_bytes = expected.to_bytes_le()?;
68            assert_eq!(expected, Ratifications::read_le(&expected_bytes[..])?);
69        }
70        Ok(())
71    }
72}