Skip to main content

snarkvm_synthesizer_program/finalize/
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 FinalizeCore<N> {
19    /// Reads the finalize from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        // Read the associated function name.
23        let name = Identifier::<N>::read_le(&mut reader)?;
24
25        // Read the inputs.
26        let num_inputs = u16::read_le(&mut reader)?;
27        if num_inputs > u16::try_from(N::MAX_INPUTS).map_err(error)? {
28            return Err(error(format!("Failed to deserialize finalize: too many inputs ({num_inputs})")));
29        }
30        let mut inputs = Vec::with_capacity(num_inputs as usize);
31        for _ in 0..num_inputs {
32            inputs.push(Input::read_le(&mut reader)?);
33        }
34
35        // Read the commands.
36        let num_commands = u16::read_le(&mut reader)?;
37        if num_commands.is_zero() {
38            return Err(error("Failed to deserialize finalize: needs at least one command".to_string()));
39        }
40        if num_commands > u16::try_from(N::MAX_COMMANDS).map_err(error)? {
41            return Err(error(format!("Failed to deserialize finalize: too many commands ({num_commands})")));
42        }
43        // Cap the reservation: the count is attacker-supplied, and the elements behind
44        // it may not exist.
45        let mut commands = Vec::with_capacity((num_commands as usize).min(1024));
46        for _ in 0..num_commands {
47            commands.push(Command::read_le(&mut reader)?);
48        }
49
50        // Initialize a new finalize.
51        let mut finalize = Self::new(name);
52        inputs.into_iter().try_for_each(|input| finalize.add_input(input)).map_err(error)?;
53        commands.into_iter().try_for_each(|command| finalize.add_command(command)).map_err(error)?;
54
55        Ok(finalize)
56    }
57}
58
59impl<N: Network> ToBytes for FinalizeCore<N> {
60    /// Writes the finalize to a buffer.
61    #[inline]
62    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
63        // Write the associated function name.
64        self.name.write_le(&mut writer)?;
65
66        // Write the number of inputs for the finalize.
67        let num_inputs = self.inputs.len();
68        match num_inputs <= N::MAX_INPUTS {
69            true => u16::try_from(num_inputs).map_err(error)?.write_le(&mut writer)?,
70            false => return Err(error(format!("Failed to write {num_inputs} inputs as bytes"))),
71        }
72
73        // Write the inputs.
74        for input in self.inputs.iter() {
75            input.write_le(&mut writer)?;
76        }
77
78        // Write the number of commands for the finalize.
79        let num_commands = self.commands.len();
80        match 0 < num_commands && num_commands <= N::MAX_COMMANDS {
81            true => u16::try_from(num_commands).map_err(error)?.write_le(&mut writer)?,
82            false => return Err(error(format!("Failed to write {num_commands} commands as bytes"))),
83        }
84
85        // Write the commands.
86        for command in self.commands.iter() {
87            command.write_le(&mut writer)?;
88        }
89
90        Ok(())
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::Finalize;
98    use console::network::MainnetV0;
99
100    type CurrentNetwork = MainnetV0;
101
102    #[test]
103    fn test_finalize_bytes() -> Result<()> {
104        let finalize_string = r"
105finalize main:
106    input r0 as field.public;
107    input r1 as field.public;
108    add r0 r1 into r2;
109    add r0 r1 into r3;
110    add r0 r1 into r4;
111    add r0 r1 into r5;
112    add r0 r1 into r6;
113    add r0 r1 into r7;
114    add r0 r1 into r8;
115    add r0 r1 into r9;
116    add r0 r1 into r10;
117    add r0 r1 into r11;
118    get accounts[r0] into r12;
119    get accounts[r1] into r13;";
120
121        let expected = Finalize::<CurrentNetwork>::from_str(finalize_string)?;
122        let expected_bytes = expected.to_bytes_le()?;
123        println!("String size: {:?}, Bytecode size: {:?}", finalize_string.len(), expected_bytes.len());
124
125        let candidate = Finalize::<CurrentNetwork>::from_bytes_le(&expected_bytes)?;
126        assert_eq!(expected.to_string(), candidate.to_string());
127        assert_eq!(expected_bytes, candidate.to_bytes_le()?);
128        Ok(())
129    }
130}