snarkvm_synthesizer_program/logic/command/
rand_chacha.rs1use 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
25pub const MAX_ADDITIONAL_SEEDS: usize = 2;
27
28#[derive(Clone, PartialEq, Eq, Hash)]
35pub struct RandChaCha<N: Network> {
36 operands: Vec<Operand<N>>,
38 destination: Register<N>,
40 destination_type: LiteralType,
42}
43
44impl<N: Network> RandChaCha<N> {
45 #[inline]
47 pub const fn opcode() -> Opcode {
48 Opcode::Command("rand.chacha")
49 }
50
51 #[inline]
53 pub fn operands(&self) -> &[Operand<N>] {
54 &self.operands
55 }
56
57 #[inline]
59 pub const fn destination(&self) -> &Register<N> {
60 &self.destination
61 }
62
63 #[inline]
65 pub const fn destination_type(&self) -> LiteralType {
66 self.destination_type
67 }
68}
69
70impl<N: Network> RandChaCha<N> {
71 #[inline]
73 pub fn finalize(&self, stack: &impl StackTrait<N>, registers: &mut impl FinalizeRegistersState<N>) -> Result<()> {
74 if self.operands.len() > MAX_ADDITIONAL_SEEDS {
76 bail!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")
77 }
78
79 let seeds: Vec<_> = self.operands.iter().map(|operand| registers.load(stack, operand)).try_collect()?;
81
82 let consensus_version = N::CONSENSUS_VERSION(registers.state().block_height())?;
86 let preimage = if (ConsensusVersion::V1..=ConsensusVersion::V2).contains(&consensus_version) {
87 to_bits_le![
88 registers.state().random_seed(),
89 **registers.transition_id(),
90 stack.program_id(),
91 registers.function_name(),
92 self.destination.locator(),
93 self.destination_type.type_id(),
94 seeds
95 ]
96 } else {
97 to_bits_le![
98 registers.state().random_seed(),
99 **registers.transition_id(),
100 stack.program_id(),
101 registers.function_name(),
102 registers.nonce(),
103 self.destination.locator(),
104 self.destination_type.type_id(),
105 seeds
106 ]
107 };
108
109 let digest = N::hash_bhp1024(&preimage)?.to_bytes_le()?;
111 ensure!(digest.len() == 32, "The digest for the ChaChaRng seed must be 32-bytes");
113
114 let mut chacha_seed = [0u8; 32];
116 chacha_seed.copy_from_slice(&digest[..32]);
117
118 let mut rng = rand_chacha::ChaCha20Rng::from_seed(chacha_seed);
120
121 let output = match self.destination_type {
123 LiteralType::Address => Literal::Address(Address::new(Group::rand(&mut rng))),
124 LiteralType::Boolean => Literal::Boolean(Boolean::rand(&mut rng)),
125 LiteralType::Field => Literal::Field(Field::rand(&mut rng)),
126 LiteralType::Group => Literal::Group(Group::rand(&mut rng)),
127 LiteralType::I8 => Literal::I8(I8::rand(&mut rng)),
128 LiteralType::I16 => Literal::I16(I16::rand(&mut rng)),
129 LiteralType::I32 => Literal::I32(I32::rand(&mut rng)),
130 LiteralType::I64 => Literal::I64(I64::rand(&mut rng)),
131 LiteralType::I128 => Literal::I128(I128::rand(&mut rng)),
132 LiteralType::U8 => Literal::U8(U8::rand(&mut rng)),
133 LiteralType::U16 => Literal::U16(U16::rand(&mut rng)),
134 LiteralType::U32 => Literal::U32(U32::rand(&mut rng)),
135 LiteralType::U64 => Literal::U64(U64::rand(&mut rng)),
136 LiteralType::U128 => Literal::U128(U128::rand(&mut rng)),
137 LiteralType::Scalar => Literal::Scalar(Scalar::rand(&mut rng)),
138 LiteralType::Signature => bail!("Cannot 'rand.chacha' into a 'signature'"),
139 LiteralType::String => bail!("Cannot 'rand.chacha' into a 'string'"),
140 };
141
142 registers.store(stack, &self.destination, Value::Plaintext(Plaintext::from(output)))
144 }
145}
146
147impl<N: Network> Parser for RandChaCha<N> {
148 #[inline]
150 fn parse(string: &str) -> ParserResult<Self> {
151 fn parse_operand<N: Network>(string: &str) -> ParserResult<Operand<N>> {
153 let (string, _) = Sanitizer::parse_whitespaces(string)?;
155 Operand::parse(string)
157 }
158
159 let (string, _) = Sanitizer::parse(string)?;
161 let (string, _) = tag(*Self::opcode())(string)?;
163 let (string, operands) = many0(parse_operand)(string)?;
165
166 let (string, _) = Sanitizer::parse_whitespaces(string)?;
168 let (string, _) = tag("into")(string)?;
170 let (string, _) = Sanitizer::parse_whitespaces(string)?;
172 let (string, destination) = Register::parse(string)?;
174 let (string, _) = Sanitizer::parse_whitespaces(string)?;
176 let (string, _) = tag("as")(string)?;
178 let (string, _) = Sanitizer::parse_whitespaces(string)?;
180 let (string, destination_type) = LiteralType::parse(string)?;
182
183 let (string, _) = Sanitizer::parse_whitespaces(string)?;
185 let (string, _) = tag(";")(string)?;
187
188 if destination_type == LiteralType::String {
190 return map_res(fail, |_: ParserResult<Self>| {
191 Err(error(format!("Failed to parse 'rand.chacha': '{destination_type}' is invalid")))
192 })(string);
193 }
194
195 match operands.len() <= MAX_ADDITIONAL_SEEDS {
196 true => Ok((string, Self { operands, destination, destination_type })),
197 false => map_res(fail, |_: ParserResult<Self>| {
198 Err(error("Failed to parse 'rand.chacha' opcode: too many operands"))
199 })(string),
200 }
201 }
202}
203
204impl<N: Network> FromStr for RandChaCha<N> {
205 type Err = Error;
206
207 #[inline]
209 fn from_str(string: &str) -> Result<Self> {
210 match Self::parse(string) {
211 Ok((remainder, object)) => {
212 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
214 Ok(object)
216 }
217 Err(error) => bail!("Failed to parse string. {error}"),
218 }
219 }
220}
221
222impl<N: Network> Debug for RandChaCha<N> {
223 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
225 Display::fmt(self, f)
226 }
227}
228
229impl<N: Network> Display for RandChaCha<N> {
230 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
232 if self.operands.len() > MAX_ADDITIONAL_SEEDS {
234 return Err(fmt::Error);
235 }
236
237 write!(f, "{} ", Self::opcode())?;
239 self.operands.iter().try_for_each(|operand| write!(f, "{operand} "))?;
240 write!(f, "into {} as {};", self.destination, self.destination_type)
241 }
242}
243
244impl<N: Network> FromBytes for RandChaCha<N> {
245 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
247 let num_operands = u8::read_le(&mut reader)? as usize;
249
250 if num_operands > MAX_ADDITIONAL_SEEDS {
252 return Err(error(format!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")));
253 }
254
255 let mut operands = Vec::with_capacity(num_operands);
257 for _ in 0..num_operands {
259 operands.push(Operand::read_le(&mut reader)?);
260 }
261
262 let destination = Register::read_le(&mut reader)?;
264 let destination_type = LiteralType::read_le(&mut reader)?;
266
267 if destination_type == LiteralType::String {
269 return Err(error(format!("Failed to parse 'rand.chacha': '{destination_type}' is invalid")));
270 }
271
272 Ok(Self { operands, destination, destination_type })
274 }
275}
276
277impl<N: Network> ToBytes for RandChaCha<N> {
278 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
280 if self.operands.len() > MAX_ADDITIONAL_SEEDS {
282 return Err(error(format!("The number of operands must be <= {MAX_ADDITIONAL_SEEDS}")));
283 }
284
285 u8::try_from(self.operands.len()).map_err(|e| error(e.to_string()))?.write_le(&mut writer)?;
287 self.operands.iter().try_for_each(|operand| operand.write_le(&mut writer))?;
289 self.destination.write_le(&mut writer)?;
291 self.destination_type.write_le(&mut writer)
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use console::{network::MainnetV0, program::Register};
300
301 type CurrentNetwork = MainnetV0;
302
303 fn valid_destination_types() -> &'static [LiteralType] {
304 &[
305 LiteralType::Address,
306 LiteralType::Boolean,
307 LiteralType::Field,
308 LiteralType::Group,
309 LiteralType::I8,
310 LiteralType::I16,
311 LiteralType::I32,
312 LiteralType::I64,
313 LiteralType::I128,
314 LiteralType::U8,
315 LiteralType::U16,
316 LiteralType::U32,
317 LiteralType::U64,
318 LiteralType::U128,
319 LiteralType::Scalar,
320 ]
321 }
322
323 #[test]
324 fn test_parse() {
325 for destination_type in valid_destination_types() {
326 let instruction = format!("rand.chacha into r1 as {destination_type};");
327 let (string, rand) = RandChaCha::<CurrentNetwork>::parse(&instruction).unwrap();
328 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
329 assert_eq!(rand.operands.len(), 0, "The number of operands is incorrect");
330 assert_eq!(rand.destination, Register::Locator(1), "The destination is incorrect");
331 assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
332
333 let instruction = format!("rand.chacha r0 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(), 1, "The number of operands is incorrect");
337 assert_eq!(rand.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
338 assert_eq!(rand.destination, Register::Locator(1), "The second operand is incorrect");
339 assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
340
341 let instruction = format!("rand.chacha r0 r1 into r2 as {destination_type};");
342 let (string, rand) = RandChaCha::<CurrentNetwork>::parse(&instruction).unwrap();
343 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
344 assert_eq!(rand.operands.len(), 2, "The number of operands is incorrect");
345 assert_eq!(rand.operands[0], Operand::Register(Register::Locator(0)), "The first operand is incorrect");
346 assert_eq!(rand.operands[1], Operand::Register(Register::Locator(1)), "The first operand is incorrect");
347 assert_eq!(rand.destination, Register::Locator(2), "The second operand is incorrect");
348 assert_eq!(rand.destination_type, *destination_type, "The destination type is incorrect");
349 }
350 }
351}