Skip to main content

snarkvm_synthesizer_program/logic/command/
rand_chacha.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 crate::{FinalizeRegistersState, Opcode, Operand, StackTrait};
17use console::{
18    network::prelude::*,
19    program::{Literal, LiteralType, Plaintext, Register, Value},
20    types::{Address, Boolean, Field, Group, I8, I16, I32, I64, I128, Scalar, U8, U16, U32, U64, U128},
21};
22
23use rand::SeedableRng;
24
25/// The maximum number of additional seeds that can be provided.
26pub const MAX_ADDITIONAL_SEEDS: usize = 2;
27
28/// A random-number generator command, e.g. `rand.chacha into r1 as field;` or
29/// `rand.chacha r0 into r1 as field;`, with the latter including an optional additional seed(s).
30///
31/// This command samples a deterministic and unique element, and stores the result in `destination`.
32/// When the optional operand(s) are provided, it is used as additional seed(s) to the
33/// random-number generator. Note that the maximum number of additional seeds is currently 2.
34#[derive(Clone, PartialEq, Eq, Hash)]
35pub struct RandChaCha<N: Network> {
36    /// The operand(s) as `seed(s)`.
37    operands: Vec<Operand<N>>,
38    /// The destination register.
39    destination: Register<N>,
40    /// The destination register type.
41    destination_type: LiteralType,
42}
43
44impl<N: Network> RandChaCha<N> {
45    /// Returns the opcode.
46    #[inline]
47    pub const fn opcode() -> Opcode {
48        Opcode::Command("rand.chacha")
49    }
50
51    /// Returns the operands in the operation.
52    #[inline]
53    pub fn operands(&self) -> &[Operand<N>] {
54        &self.operands
55    }
56
57    /// Returns the destination register.
58    #[inline]
59    pub const fn destination(&self) -> &Register<N> {
60        &self.destination
61    }
62
63    /// Returns the destination register type.
64    #[inline]
65    pub const fn destination_type(&self) -> LiteralType {
66        self.destination_type
67    }
68
69    /// Returns whether this command refers to an external struct.
70    #[inline]
71    pub fn contains_external_struct(&self) -> bool {
72        false
73    }
74}
75
76impl<N: Network> RandChaCha<N> {
77    /// Finalizes the command.
78    #[inline]
79    pub fn finalize(&self, stack: &impl StackTrait<N>, registers: &mut impl FinalizeRegistersState<N>) -> Result<()> {
80        // Ensure the number of operands is within bounds.
81        if self.operands.len() > MAX_ADDITIONAL_SEEDS {
82            bail!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")
83        }
84
85        // Load the operands values.
86        let seeds: Vec<_> = self.operands.iter().map(|operand| registers.load(stack, operand)).try_collect()?;
87
88        // Construct the random seed.
89        // If the height is greater than or equal to consensus V3, then use the new preimage definition.
90        // The difference is that a nonce is also included in the new definition.
91        let consensus_version = N::CONSENSUS_VERSION(registers.state().block_height())?;
92        let preimage = if (ConsensusVersion::V1..=ConsensusVersion::V2).contains(&consensus_version) {
93            to_bits_le![
94                registers.state().random_seed(),
95                **registers.transition_id(),
96                stack.program_id(),
97                registers.function_name(),
98                self.destination.locator(),
99                self.destination_type.type_id(),
100                seeds
101            ]
102        } else {
103            to_bits_le![
104                registers.state().random_seed(),
105                **registers.transition_id(),
106                stack.program_id(),
107                registers.function_name(),
108                registers.nonce(),
109                self.destination.locator(),
110                self.destination_type.type_id(),
111                seeds
112            ]
113        };
114
115        // Hash the preimage.
116        let digest = N::hash_bhp1024(&preimage)?.to_bytes_le()?;
117        // Ensure the digest is 32-bytes.
118        ensure!(digest.len() == 32, "The digest for the ChaChaRng seed must be 32-bytes");
119
120        // Construct the ChaChaRng seed.
121        let mut chacha_seed = [0u8; 32];
122        chacha_seed.copy_from_slice(&digest[..32]);
123
124        // Construct the ChaChaRng.
125        let mut rng = rand_chacha::ChaCha20Rng::from_seed(chacha_seed);
126
127        // Sample a random element.
128        let output = match self.destination_type {
129            LiteralType::Address => Literal::Address(Address::new(Group::rand(&mut rng))),
130            LiteralType::Boolean => Literal::Boolean(Boolean::rand(&mut rng)),
131            LiteralType::Field => Literal::Field(Field::rand(&mut rng)),
132            LiteralType::Group => Literal::Group(Group::rand(&mut rng)),
133            LiteralType::I8 => Literal::I8(I8::rand(&mut rng)),
134            LiteralType::I16 => Literal::I16(I16::rand(&mut rng)),
135            LiteralType::I32 => Literal::I32(I32::rand(&mut rng)),
136            LiteralType::I64 => Literal::I64(I64::rand(&mut rng)),
137            LiteralType::I128 => Literal::I128(I128::rand(&mut rng)),
138            LiteralType::U8 => Literal::U8(U8::rand(&mut rng)),
139            LiteralType::U16 => Literal::U16(U16::rand(&mut rng)),
140            LiteralType::U32 => Literal::U32(U32::rand(&mut rng)),
141            LiteralType::U64 => Literal::U64(U64::rand(&mut rng)),
142            LiteralType::U128 => Literal::U128(U128::rand(&mut rng)),
143            LiteralType::Scalar => Literal::Scalar(Scalar::rand(&mut rng)),
144            LiteralType::Signature => bail!("Cannot 'rand.chacha' into a 'signature'"),
145            LiteralType::String => bail!("Cannot 'rand.chacha' into a 'string'"),
146            LiteralType::Identifier => bail!("Cannot 'rand.chacha' into an 'identifier'"),
147        };
148
149        // Assign the value to the destination register.
150        registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
151    }
152}
153
154impl<N: Network> Parser for RandChaCha<N> {
155    /// Parses a string into an operation.
156    #[inline]
157    fn parse(string: &str) -> ParserResult<Self> {
158        /// Parses an operand from the string.
159        fn parse_operand<N: Network>(string: &str) -> ParserResult<Operand<N>> {
160            // Parse the whitespace from the string.
161            let (string, _) = Sanitizer::parse_whitespaces(string)?;
162            // Parse the operand from the string.
163            Operand::parse(string)
164        }
165
166        // Parse the whitespace and comments from the string.
167        let (string, _) = Sanitizer::parse(string)?;
168        // Parse the opcode from the string.
169        let (string, _) = tag(*Self::opcode())(string)?;
170        // Parse the operands from the string.
171        let (string, operands) = many0(parse_operand)(string)?;
172
173        // Parse the whitespace from the string.
174        let (string, _) = Sanitizer::parse_whitespaces(string)?;
175        // Parse the "into" keyword from the string.
176        let (string, _) = tag("into")(string)?;
177        // Parse the whitespace from the string.
178        let (string, _) = Sanitizer::parse_whitespaces(string)?;
179        // Parse the destination register from the string.
180        let (string, destination) = Register::parse(string)?;
181        // Parse the whitespace from the string.
182        let (string, _) = Sanitizer::parse_whitespaces(string)?;
183        // Parse the "as" from the string.
184        let (string, _) = tag("as")(string)?;
185        // Parse the whitespace from the string.
186        let (string, _) = Sanitizer::parse_whitespaces(string)?;
187        // Parse the destination register type from the string.
188        let (string, destination_type) = LiteralType::parse(string)?;
189
190        // Parse the whitespace from the string.
191        let (string, _) = Sanitizer::parse_whitespaces(string)?;
192        // Parse the ";" from the string.
193        let (string, _) = tag(";")(string)?;
194
195        // Ensure the destination type is allowed.
196        if matches!(destination_type, LiteralType::String | LiteralType::Identifier) {
197            return map_res(fail, |_: ParserResult<Self>| {
198                Err(error(format!("Failed to parse 'rand.chacha': '{destination_type}' is invalid")))
199            })(string);
200        }
201
202        match operands.len() <= MAX_ADDITIONAL_SEEDS {
203            true => Ok((string, Self { operands, destination, destination_type })),
204            false => map_res(fail, |_: ParserResult<Self>| {
205                Err(error("Failed to parse 'rand.chacha' opcode: too many operands"))
206            })(string),
207        }
208    }
209}
210
211impl<N: Network> FromStr for RandChaCha<N> {
212    type Err = Error;
213
214    /// Parses a string into the command.
215    #[inline]
216    fn from_str(string: &str) -> Result<Self> {
217        match Self::parse(string) {
218            Ok((remainder, object)) => {
219                // Ensure the remainder is empty.
220                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
221                // Return the object.
222                Ok(object)
223            }
224            Err(error) => bail!("Failed to parse string. {error}"),
225        }
226    }
227}
228
229impl<N: Network> Debug for RandChaCha<N> {
230    /// Prints the command as a string.
231    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
232        Display::fmt(self, f)
233    }
234}
235
236impl<N: Network> Display for RandChaCha<N> {
237    /// Prints the command to a string.
238    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
239        // Ensure the number of operands is within the bounds.
240        if self.operands.len() > MAX_ADDITIONAL_SEEDS {
241            return Err(fmt::Error);
242        }
243
244        // Print the command.
245        write!(f, "{} ", Self::opcode())?;
246        self.operands.iter().try_for_each(|operand| write!(f, "{operand} "))?;
247        write!(f, "into {} as {};", self.destination, self.destination_type)
248    }
249}
250
251impl<N: Network> FromBytes for RandChaCha<N> {
252    /// Reads the command from a buffer.
253    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
254        // Read the number of operands.
255        let num_operands = u8::read_le(&mut reader)? as usize;
256
257        // Ensure that the number of operands does not exceed the upper bound.
258        if num_operands > MAX_ADDITIONAL_SEEDS {
259            return Err(error(format!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")));
260        }
261
262        // Initialize the vector for the operands.
263        let mut operands = Vec::with_capacity(num_operands);
264        // Read the operands.
265        for _ in 0..num_operands {
266            operands.push(Operand::read_le(&mut reader)?);
267        }
268
269        // Read the destination register.
270        let destination = Register::read_le(&mut reader)?;
271        // Read the destination register type.
272        let destination_type = LiteralType::read_le(&mut reader)?;
273
274        // Ensure the destination type is allowed.
275        if matches!(destination_type, LiteralType::String | LiteralType::Identifier) {
276            return Err(error(format!("Failed to parse 'rand.chacha': '{destination_type}' is invalid")));
277        }
278
279        // Return the command.
280        Ok(Self { operands, destination, destination_type })
281    }
282}
283
284impl<N: Network> ToBytes for RandChaCha<N> {
285    /// Writes the operation to a buffer.
286    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
287        // Ensure the number of operands is within the bounds.
288        if self.operands.len() > MAX_ADDITIONAL_SEEDS {
289            return Err(error(format!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")));
290        }
291
292        // Write the number of operands.
293        u8::try_from(self.operands.len()).map_err(|e| error(e.to_string()))?.write_le(&mut writer)?;
294        // Write the operands.
295        self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
296        // Write the destination register.
297        self.destination.write_le(&mut writer)?;
298        // Write the destination register type.
299        self.destination_type.write_le(&mut writer)
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    use console::{network::MainnetV0, program::Register};
307
308    type CurrentNetwork = MainnetV0;
309
310    fn valid_destination_types() -> &'static [LiteralType] {
311        &[
312            LiteralType::Address,
313            LiteralType::Boolean,
314            LiteralType::Field,
315            LiteralType::Group,
316            LiteralType::I8,
317            LiteralType::I16,
318            LiteralType::I32,
319            LiteralType::I64,
320            LiteralType::I128,
321            LiteralType::U8,
322            LiteralType::U16,
323            LiteralType::U32,
324            LiteralType::U64,
325            LiteralType::U128,
326            LiteralType::Scalar,
327        ]
328    }
329
330    #[test]
331    fn test_parse() {
332        for destination_type in valid_destination_types() {
333            let instruction = format!("rand.chacha into r1 as {destination_type};");
334            let (string, rand) = RandChaCha::<CurrentNetwork>::parse(&instruction).unwrap();
335            assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
336            assert_eq!(rand.operands.len(), 0, "The number of operands is incorrect");
337            assert_eq!(rand.destination, Register::Locator(1), "The destination is incorrect");
338            assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
339
340            let instruction = format!("rand.chacha r0 into r1 as {destination_type};");
341            let (string, rand) = RandChaCha::<CurrentNetwork>::parse(&instruction).unwrap();
342            assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
343            assert_eq!(rand.operands.len(), 1, "The number of operands is incorrect");
344            assert_eq!(rand.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
345            assert_eq!(rand.destination, Register::Locator(1), "The second operand is incorrect");
346            assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
347
348            let instruction = format!("rand.chacha r0 r1 into r2 as {destination_type};");
349            let (string, rand) = RandChaCha::<CurrentNetwork>::parse(&instruction).unwrap();
350            assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
351            assert_eq!(rand.operands.len(), 2, "The number of operands is incorrect");
352            assert_eq!(rand.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
353            assert_eq!(rand.operands[1], Operand::Register(Register::Locator(1)), "The first operand is incorrect");
354            assert_eq!(rand.destination, Register::Locator(2), "The second operand is incorrect");
355            assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
356        }
357    }
358}