Skip to main content

snarkvm_synthesizer_program/constructor/
bytes.rs

1// Copyright (c) 2019-2026 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 ConstructorCore<N> {
19    /// Reads the constructor from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        // Read the commands.
23        let num_commands = u16::read_le(&mut reader)?;
24        if num_commands.is_zero() {
25            return Err(error("Failed to deserialize constructor: needs at least one command"));
26        }
27        if num_commands > u16::try_from(N::MAX_COMMANDS).map_err(error)? {
28            return Err(error(format!("Failed to deserialize constructor: too many commands ({num_commands})")));
29        }
30        // Cap the reservation: the count is attacker-supplied, and the elements behind
31        // it may not exist.
32        let mut commands = Vec::with_capacity((num_commands as usize).min(1024));
33        for _ in 0..num_commands {
34            commands.push(Command::read_le(&mut reader)?);
35        }
36        // Initialize a new constructor.
37        let mut constructor = Self { commands: Default::default(), num_writes: 0, positions: Default::default() };
38        commands.into_iter().try_for_each(|command| constructor.add_command(command)).map_err(error)?;
39
40        Ok(constructor)
41    }
42}
43
44impl<N: Network> ToBytes for ConstructorCore<N> {
45    /// Writes the constructor to a buffer.
46    #[inline]
47    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
48        // Write the number of commands for the constructor.
49        let num_commands = self.commands.len();
50        match 0 < num_commands && num_commands <= N::MAX_COMMANDS {
51            true => u16::try_from(num_commands).map_err(error)?.write_le(&mut writer)?,
52            false => return Err(error(format!("Failed to write {num_commands} commands as bytes"))),
53        }
54        // Write the commands.
55        for command in self.commands.iter() {
56            command.write_le(&mut writer)?;
57        }
58        Ok(())
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use crate::Constructor;
66    use console::network::MainnetV0;
67
68    type CurrentNetwork = MainnetV0;
69
70    #[test]
71    fn test_constructor_bytes() -> Result<()> {
72        let constructor_string = r"
73constructor:
74    add r0 r1 into r2;
75    add r0 r1 into r3;
76    add r0 r1 into r4;
77    add r0 r1 into r5;
78    add r0 r1 into r6;
79    add r0 r1 into r7;
80    add r0 r1 into r8;
81    add r0 r1 into r9;
82    add r0 r1 into r10;
83    add r0 r1 into r11;
84    get accounts[r0] into r12;
85    get accounts[r1] into r13;";
86
87        let expected = Constructor::<CurrentNetwork>::from_str(constructor_string)?;
88        let expected_bytes = expected.to_bytes_le()?;
89        println!("String size: {:?}, Bytecode size: {:?}", constructor_string.len(), expected_bytes.len());
90
91        let candidate = Constructor::<CurrentNetwork>::from_bytes_le(&expected_bytes)?;
92        assert_eq!(expected.to_string(), candidate.to_string());
93        assert_eq!(expected_bytes, candidate.to_bytes_le()?);
94        Ok(())
95    }
96}