bytes.rs
 1  // Copyright (c) 2025-2026 ACDC Network
 2  // This file is part of the alphavm library.
 3  //
 4  // Alpha Chain | Delta Chain Protocol
 5  // International Monetary Graphite.
 6  //
 7  // Derived from Aleo (https://aleo.org) and ProvableHQ (https://provable.com).
 8  // They built world-class ZK infrastructure. We installed the EASY button.
 9  // Their cryptography: elegant. Our modifications: bureaucracy-compatible.
10  // Original brilliance: theirs. Robert's Rules: ours. Bugs: definitely ours.
11  //
12  // Original Aleo/ProvableHQ code subject to Apache 2.0 https://www.apache.org/licenses/LICENSE-2.0
13  // All modifications and new work: CC0 1.0 Universal Public Domain Dedication.
14  // No rights reserved. No permission required. No warranty. No refunds.
15  //
16  // https://creativecommons.org/publicdomain/zero/1.0/
17  // SPDX-License-Identifier: CC0-1.0
18  
19  use super::*;
20  
21  impl<N: Network> FromBytes for TransitionLeaf<N> {
22      /// Reads the transition leaf from a buffer.
23      fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
24          // Read the version.
25          let version = FromBytes::read_le(&mut reader)?;
26          // Ensure the version is valid.
27          if version != TRANSITION_LEAF_VERSION {
28              return Err(error("Invalid transition leaf version"));
29          }
30          // Read the index.
31          let index = FromBytes::read_le(&mut reader)?;
32          // Read the variant.
33          let variant = FromBytes::read_le(&mut reader)?;
34          // Read the ID.
35          let id = FromBytes::read_le(&mut reader)?;
36          // Return the transition leaf.
37          Ok(Self::from(version, index, variant, id))
38      }
39  }
40  
41  impl<N: Network> ToBytes for TransitionLeaf<N> {
42      /// Writes the transition leaf to a buffer.
43      fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
44          // Write the version.
45          self.version.write_le(&mut writer)?;
46          // Write the index.
47          self.index.write_le(&mut writer)?;
48          // Write the variant.
49          self.variant.write_le(&mut writer)?;
50          // Write the ID.
51          self.id.write_le(&mut writer)
52      }
53  }
54  
55  #[cfg(test)]
56  mod tests {
57      use super::*;
58  
59      const ITERATIONS: u64 = 1000;
60  
61      #[test]
62      fn test_bytes() -> Result<()> {
63          let mut rng = TestRng::default();
64  
65          for _ in 0..ITERATIONS {
66              // Sample the leaf.
67              let expected = test_helpers::sample_leaf(&mut rng);
68  
69              // Check the byte representation.
70              let expected_bytes = expected.to_bytes_le()?;
71              assert_eq!(expected, TransitionLeaf::read_le(&expected_bytes[..])?);
72          }
73          Ok(())
74      }
75  }