snarkvm_console_account/compute_key/
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 ComputeKey<N> {
19    /// Reads an account compute key from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        let pk_sig = Group::from_x_coordinate(Field::new(N::Field::read_le(&mut reader)?)).map_err(into_io_error)?;
23        let pr_sig = Group::from_x_coordinate(Field::new(N::Field::read_le(&mut reader)?)).map_err(into_io_error)?;
24        Self::try_from((pk_sig, pr_sig)).map_err(into_io_error)
25    }
26}
27
28impl<N: Network> ToBytes for ComputeKey<N> {
29    /// Writes an account compute key to a buffer.
30    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
31        self.pk_sig.to_x_coordinate().write_le(&mut writer)?;
32        self.pr_sig.to_x_coordinate().write_le(&mut writer)
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39    use snarkvm_console_network::MainnetV0;
40
41    type CurrentNetwork = MainnetV0;
42
43    const ITERATIONS: u64 = 1000;
44
45    #[test]
46    fn test_bytes() -> Result<()> {
47        let mut rng = TestRng::default();
48
49        for _ in 0..ITERATIONS {
50            // Sample a new compute key.
51            let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
52            let expected = ComputeKey::try_from(private_key)?;
53
54            // Check the byte representation.
55            let expected_bytes = expected.to_bytes_le()?;
56            assert_eq!(expected, ComputeKey::read_le(&expected_bytes[..])?);
57            assert!(ComputeKey::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err());
58        }
59        Ok(())
60    }
61}