snarkvm_console_program/state_path/transaction_leaf/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 TransactionLeaf<N> {
19 /// Reads the transaction leaf from a buffer.
20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21 // Read the variant.
22 let variant = FromBytes::read_le(&mut reader)?;
23 // Read the index.
24 let index = FromBytes::read_le(&mut reader)?;
25 // Read the ID.
26 let id = FromBytes::read_le(&mut reader)?;
27 // Return the transaction leaf.
28 Ok(Self::from(variant, index, id))
29 }
30}
31
32impl<N: Network> ToBytes for TransactionLeaf<N> {
33 /// Writes the transaction leaf to a buffer.
34 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
35 // Write the variant.
36 self.variant.write_le(&mut writer)?;
37 // Write the index.
38 self.index.write_le(&mut writer)?;
39 // Write the ID.
40 self.id.write_le(&mut writer)
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 const ITERATIONS: u64 = 1000;
49
50 #[test]
51 fn test_bytes() -> Result<()> {
52 let mut rng = TestRng::default();
53
54 for _ in 0..ITERATIONS {
55 // Sample the leaf.
56 let expected = test_helpers::sample_leaf(&mut rng);
57
58 // Check the byte representation.
59 let expected_bytes = expected.to_bytes_le()?;
60 assert_eq!(expected, TransactionLeaf::read_le(&expected_bytes[..])?);
61 }
62 Ok(())
63 }
64}