/ console / account / src / graph_key / bytes.rs
bytes.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the deltavm 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 GraphKey<N> {
19      /// Reads an account graph key from a buffer.
20      #[inline]
21      fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22          let sk_tag = Field::<N>::read_le(&mut reader).map_err(into_io_error)?;
23          Self::try_from(sk_tag).map_err(into_io_error)
24      }
25  }
26  
27  impl<N: Network> ToBytes for GraphKey<N> {
28      /// Writes an account graph key to a buffer.
29      fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
30          self.sk_tag.write_le(&mut writer)
31      }
32  }
33  
34  #[cfg(test)]
35  mod tests {
36      use super::*;
37      use crate::PrivateKey;
38      use deltavm_console_network::MainnetV0;
39  
40      type CurrentNetwork = MainnetV0;
41  
42      const ITERATIONS: u64 = 1000;
43  
44      #[test]
45      fn test_bytes() -> Result<()> {
46          let mut rng = TestRng::default();
47  
48          for _ in 0..ITERATIONS {
49              // Sample a new graph key.
50              let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
51              let view_key = ViewKey::try_from(private_key)?;
52              let expected = GraphKey::try_from(view_key)?;
53  
54              // Check the byte representation.
55              let expected_bytes = expected.to_bytes_le()?;
56              assert_eq!(expected, GraphKey::read_le(&expected_bytes[..])?);
57              assert!(GraphKey::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
58          }
59          Ok(())
60      }
61  }