snarkvm_console_account/signature/
bytes.rs

1// Copyright 2024 Aleo Network Foundation
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 Signature<N> {
19    /// Reads an account signature from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        let challenge = Scalar::new(FromBytes::read_le(&mut reader)?);
23        let response = Scalar::new(FromBytes::read_le(&mut reader)?);
24        let compute_key = ComputeKey::read_le(&mut reader)?;
25        Ok(Self { challenge, response, compute_key })
26    }
27}
28
29impl<N: Network> ToBytes for Signature<N> {
30    /// Writes an account signature to a buffer.
31    #[inline]
32    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
33        self.challenge.write_le(&mut writer)?;
34        self.response.write_le(&mut writer)?;
35        self.compute_key.write_le(&mut writer)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    use snarkvm_console_network::MainnetV0;
43
44    type CurrentNetwork = MainnetV0;
45
46    const ITERATIONS: u64 = 100;
47
48    #[test]
49    fn test_bytes() -> Result<()> {
50        let mut rng = TestRng::default();
51
52        for i in 0..ITERATIONS {
53            // Sample a new signature.
54            let signature = test_helpers::sample_signature(i, &mut rng);
55
56            // Check the byte representation.
57            let signature_bytes = signature.to_bytes_le()?;
58            assert_eq!(signature, Signature::read_le(&signature_bytes[..])?);
59            assert!(Signature::<CurrentNetwork>::read_le(&signature_bytes[1..]).is_err());
60        }
61        Ok(())
62    }
63}