snarkvm_ledger_committee/
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 Committee<N> {
19    /// Reads the committee from the buffer.
20    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21        // Read the version.
22        let version = u8::read_le(&mut reader)?;
23        // Ensure the version is valid.
24        if version != 1 {
25            return Err(error("Invalid committee version"));
26        }
27
28        // Read the committee ID.
29        let id = Field::read_le(&mut reader)?;
30        // Read the starting round.
31        let starting_round = u64::read_le(&mut reader)?;
32        // Read the number of members.
33        let num_members = u16::read_le(&mut reader)?;
34        // Ensure the number of members is within the allowed limit.
35        if num_members > Self::max_committee_size().map_err(error)? {
36            return Err(error(format!(
37                "Committee cannot exceed {} members, found {num_members}",
38                Self::max_committee_size().map_err(error)?,
39            )));
40        }
41
42        // Calculate the number of bytes per member. Each member is a (address, stake, is_open, commission) tuple.
43        let member_byte_size = Address::<N>::size_in_bytes() + 8 + 1 + 1;
44        // Read the member bytes.
45        let mut member_bytes = vec![0u8; num_members as usize * member_byte_size];
46        reader.read_exact(&mut member_bytes)?;
47        // Read the members.
48        let members = cfg_chunks!(member_bytes, member_byte_size)
49            .map(|mut bytes| {
50                // Read the address.
51                let member = Address::<N>::read_le(&mut bytes)?;
52                // Read the stake.
53                let stake = u64::read_le(&mut bytes)?;
54                // Read the is_open flag.
55                let is_open = bool::read_le(&mut bytes)?;
56                // Read the commission.
57                let commission = u8::read_le(&mut bytes)?;
58                // Insert the member and (stake, is_open).
59                Ok((member, (stake, is_open, commission)))
60            })
61            .collect::<Result<IndexMap<_, _>, std::io::Error>>()?;
62
63        // Read the total stake.
64        let total_stake = u64::read_le(&mut reader)?;
65        // Construct the committee.
66        let committee = Self::new(starting_round, members).map_err(|e| error(e.to_string()))?;
67        // Ensure the committee ID matches.
68        if committee.id() != id {
69            return Err(error("Invalid committee ID during deserialization"));
70        }
71        // Ensure the total stake matches.
72        match committee.total_stake() == total_stake {
73            true => Ok(committee),
74            false => Err(error("Invalid total stake in committee during deserialization")),
75        }
76    }
77}
78
79impl<N: Network> ToBytes for Committee<N> {
80    /// Writes the committee to the buffer.
81    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
82        // Write the version.
83        1u8.write_le(&mut writer)?;
84        // Write the committee ID.
85        self.id().write_le(&mut writer)?;
86        // Write the starting round.
87        self.starting_round.write_le(&mut writer)?;
88        // Write the number of members.
89        u16::try_from(self.members.len()).map_err(|e| error(e.to_string()))?.write_le(&mut writer)?;
90        // Write the members.
91        for (address, (stake, is_open, commission)) in &self.members {
92            // Write the address.
93            address.write_le(&mut writer)?;
94            // Write the stake.
95            stake.write_le(&mut writer)?;
96            // Write the is_open flag.
97            is_open.write_le(&mut writer)?;
98            // Write the commission.
99            commission.write_le(&mut writer)?;
100        }
101        // Write the total stake.
102        self.total_stake.write_le(&mut writer)
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn test_bytes() {
112        let rng = &mut TestRng::default();
113
114        for expected in crate::test_helpers::sample_committees(rng) {
115            // Check the byte representation.
116            let expected_bytes = expected.to_bytes_le().unwrap();
117            assert_eq!(expected, Committee::read_le(&expected_bytes[..]).unwrap());
118        }
119    }
120}