bytes.rs
1 // Copyright (c) 2025-2026 ACDC Network 2 // This file is part of the alphavm library. 3 // 4 // Alpha Chain | Delta Chain Protocol 5 // International Monetary Graphite. 6 // 7 // Derived from Aleo (https://aleo.org) and ProvableHQ (https://provable.com). 8 // They built world-class ZK infrastructure. We installed the EASY button. 9 // Their cryptography: elegant. Our modifications: bureaucracy-compatible. 10 // Original brilliance: theirs. Robert's Rules: ours. Bugs: definitely ours. 11 // 12 // Original Aleo/ProvableHQ code subject to Apache 2.0 https://www.apache.org/licenses/LICENSE-2.0 13 // All modifications and new work: CC0 1.0 Universal Public Domain Dedication. 14 // No rights reserved. No permission required. No warranty. No refunds. 15 // 16 // https://creativecommons.org/publicdomain/zero/1.0/ 17 // SPDX-License-Identifier: CC0-1.0 18 19 use super::*; 20 21 impl<N: Network> FromBytes for Ciphertext<N> { 22 /// Reads the ciphertext from a buffer. 23 #[inline] 24 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> { 25 // Read the number of field elements. 26 let num_fields = u16::read_le(&mut reader)?; 27 // Ensure the number of field elements does not exceed the maximum allowed size. 28 match num_fields as u32 <= N::MAX_DATA_SIZE_IN_FIELDS { 29 // Read the field elements. 30 true => { 31 Ok(Ciphertext((0..num_fields).map(|_| Field::read_le(&mut reader)).collect::<Result<Vec<_>, _>>()?)) 32 } 33 false => Err(error("Ciphertext is too large to encode in field elements.")), 34 } 35 } 36 } 37 38 impl<N: Network> ToBytes for Ciphertext<N> { 39 /// Writes the ciphertext to a buffer. 40 #[inline] 41 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> { 42 // Ensure the number of field elements does not exceed the maximum allowed size. 43 if u32::try_from(self.0.len()).or_halt::<N>() > N::MAX_DATA_SIZE_IN_FIELDS || self.0.len() > u16::MAX as usize { 44 return Err(error("Ciphertext is too large to encode in field elements.")); 45 } 46 // Write the number of ciphertext field elements. 47 u16::try_from(self.0.len()).or_halt::<N>().write_le(&mut writer)?; 48 // Write the ciphertext field elements. 49 self.0.write_le(&mut writer) 50 } 51 } 52 53 #[cfg(test)] 54 mod tests { 55 use super::*; 56 use alphavm_console_network::MainnetV0; 57 58 type CurrentNetwork = MainnetV0; 59 60 const ITERATIONS: u32 = 1000; 61 62 #[test] 63 fn test_bytes() -> Result<()> { 64 let mut rng = TestRng::default(); 65 66 for _ in 0..ITERATIONS { 67 // Sample a new ciphertext. 68 let expected = Ciphertext::<CurrentNetwork>((0..100).map(|_| Uniform::rand(&mut rng)).collect::<Vec<_>>()); 69 70 // Check the byte representation. 71 let expected_bytes = expected.to_bytes_le()?; 72 assert_eq!(expected, Ciphertext::read_le(&expected_bytes[..])?); 73 } 74 Ok(()) 75 } 76 }