/ console / program / src / owner / bytes.rs
bytes.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the alphavm 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  
16  use super::*;
17  
18  impl<N: Network> FromBytes for ProgramOwner<N> {
19      /// Reads the program owner from a 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 program owner version"));
26          }
27  
28          // Read the address.
29          let address = Address::read_le(&mut reader)?;
30          // Read the signature.
31          let signature = Signature::read_le(&mut reader)?;
32  
33          // Return the program owner.
34          Ok(Self::from(address, signature))
35      }
36  }
37  
38  impl<N: Network> ToBytes for ProgramOwner<N> {
39      /// Writes the program owner to a buffer.
40      fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
41          // Write the version.
42          1u8.write_le(&mut writer)?;
43          // Write the address.
44          self.address.write_le(&mut writer)?;
45          // Write the signature.
46          self.signature.write_le(&mut writer)
47      }
48  }
49  
50  #[cfg(test)]
51  mod tests {
52      use super::*;
53      use alphavm_console_network::MainnetV0;
54  
55      type CurrentNetwork = MainnetV0;
56  
57      #[test]
58      fn test_bytes() -> Result<()> {
59          // Construct a new program owner.
60          let expected = test_helpers::sample_program_owner();
61  
62          // Check the byte representation.
63          let expected_bytes = expected.to_bytes_le()?;
64          assert_eq!(expected, ProgramOwner::read_le(&expected_bytes[..])?);
65          assert!(ProgramOwner::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
66          Ok(())
67      }
68  }