snarkvm_console_program/data/ciphertext/bytes.rs
1// Copyright 2024-2025 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 Ciphertext<N> {
19 /// Reads the ciphertext from a buffer.
20 #[inline]
21 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22 // Read the number of field elements.
23 let num_fields = u16::read_le(&mut reader)?;
24 // Ensure the number of field elements does not exceed the maximum allowed size.
25 match num_fields as u32 <= N::MAX_DATA_SIZE_IN_FIELDS {
26 // Read the field elements.
27 true => {
28 Ok(Ciphertext((0..num_fields).map(|_| Field::read_le(&mut reader)).collect::<Result<Vec<_>, _>>()?))
29 }
30 false => Err(error("Ciphertext is too large to encode in field elements.")),
31 }
32 }
33}
34
35impl<N: Network> ToBytes for Ciphertext<N> {
36 /// Writes the ciphertext to a buffer.
37 #[inline]
38 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
39 // Ensure the number of field elements does not exceed the maximum allowed size.
40 if u32::try_from(self.0.len()).or_halt::<N>() > N::MAX_DATA_SIZE_IN_FIELDS || self.0.len() > u16::MAX as usize {
41 return Err(error("Ciphertext is too large to encode in field elements."));
42 }
43 // Write the number of ciphertext field elements.
44 u16::try_from(self.0.len()).or_halt::<N>().write_le(&mut writer)?;
45 // Write the ciphertext field elements.
46 self.0.write_le(&mut writer)
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53 use snarkvm_console_network::MainnetV0;
54
55 type CurrentNetwork = MainnetV0;
56
57 const ITERATIONS: u32 = 1000;
58
59 #[test]
60 fn test_bytes() -> Result<()> {
61 let mut rng = TestRng::default();
62
63 for _ in 0..ITERATIONS {
64 // Sample a new ciphertext.
65 let expected = Ciphertext::<CurrentNetwork>((0..100).map(|_| Uniform::rand(&mut rng)).collect::<Vec<_>>());
66
67 // Check the byte representation.
68 let expected_bytes = expected.to_bytes_le()?;
69 assert_eq!(expected, Ciphertext::read_le(&expected_bytes[..])?);
70 }
71 Ok(())
72 }
73}