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