snarkvm_ledger_authority/
bytes.rs

1// Copyright 2024 Aleo Network Foundation
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 Authority<N> {
19    /// Reads the authority from the buffer.
20    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21        // Read the variant.
22        let variant = u8::read_le(&mut reader)?;
23        // Match the variant.
24        match variant {
25            0 => Ok(Self::Beacon(FromBytes::read_le(&mut reader)?)),
26            1 => Ok(Self::Quorum(FromBytes::read_le(&mut reader)?)),
27            2.. => Err(error("Invalid authority variant")),
28        }
29    }
30}
31
32impl<N: Network> ToBytes for Authority<N> {
33    /// Writes the authority to the buffer.
34    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
35        // Write the authority.
36        match self {
37            Self::Beacon(signature) => {
38                // Write the variant.
39                0u8.write_le(&mut writer)?;
40                // Write the signature.
41                signature.write_le(&mut writer)
42            }
43            Self::Quorum(subdag) => {
44                // Write the variant.
45                1u8.write_le(&mut writer)?;
46                // Write the subdag.
47                subdag.write_le(&mut writer)
48            }
49        }
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use console::prelude::TestRng;
57
58    #[test]
59    fn test_bytes() {
60        let rng = &mut TestRng::default();
61
62        for expected in crate::test_helpers::sample_authorities(rng) {
63            // Check the byte representation.
64            let expected_bytes = expected.to_bytes_le().unwrap();
65            assert_eq!(expected, Authority::read_le(&expected_bytes[..]).unwrap());
66        }
67    }
68}