1use acir::brillig::{BlackBoxOp, HeapArray};
3use acir::{AcirField, BlackBoxFunc};
4use acvm_blackbox_solver::{
5 BlackBoxFunctionSolver, BlackBoxResolutionError, aes128_encrypt, blake2s, blake3,
6 ecdsa_secp256k1_verify, ecdsa_secp256r1_verify, keccakf1600, sha256_compression,
7};
8use num_bigint::BigUint;
9use num_traits::Zero;
10
11use crate::Memory;
12use crate::assert_usize;
13use crate::memory::MemoryValue;
14
15fn read_heap_array<'a, F: AcirField>(
19 memory: &'a Memory<F>,
20 array: &HeapArray,
21) -> &'a [MemoryValue<F>] {
22 let items_start = memory.read_ref(array.pointer);
23 memory.read_slice(items_start, assert_usize(array.size.0))
24}
25
26fn write_heap_array<F: AcirField>(
28 memory: &mut Memory<F>,
29 array: &HeapArray,
30 values: &[MemoryValue<F>],
31) {
32 let items_start = memory.read_ref(array.pointer);
33 memory.write_slice(items_start, values);
34}
35
36fn to_u8_vec<F: AcirField>(inputs: &[MemoryValue<F>]) -> Vec<u8> {
38 let mut result = Vec::with_capacity(inputs.len());
39 for &input in inputs {
40 result.push(input.expect_u8().unwrap());
41 }
42 result
43}
44
45fn to_value_vec<F: AcirField>(input: &[u8]) -> Vec<MemoryValue<F>> {
48 input.iter().map(|&x| x.into()).collect()
49}
50
51pub(crate) fn evaluate_black_box<F: AcirField, Solver: BlackBoxFunctionSolver<F>>(
71 op: &BlackBoxOp,
72 solver: &Solver,
73 memory: &mut Memory<F>,
74) -> Result<(), BlackBoxResolutionError> {
75 match op {
76 BlackBoxOp::AES128Encrypt { inputs, iv, key, outputs } => {
77 let bb_func = black_box_function_from_op(op);
78
79 let inputs = to_u8_vec(read_heap_array(memory, inputs));
80
81 let iv: [u8; 16] = to_u8_vec(read_heap_array(memory, iv)).try_into().map_err(|_| {
82 BlackBoxResolutionError::Failed(bb_func, "Invalid iv length".to_string())
83 })?;
84 let key: [u8; 16] =
85 to_u8_vec(read_heap_array(memory, key)).try_into().map_err(|_| {
86 BlackBoxResolutionError::Failed(bb_func, "Invalid key length".to_string())
87 })?;
88 let ciphertext = aes128_encrypt(&inputs, iv, key)?;
89
90 write_heap_array(memory, outputs, &to_value_vec(&ciphertext));
91
92 Ok(())
93 }
94 BlackBoxOp::Blake2s { message, output } => {
95 let message = to_u8_vec(read_heap_array(memory, message));
96 let bytes = blake2s(message.as_slice())?;
97 write_heap_array(memory, output, &to_value_vec(&bytes));
98 Ok(())
99 }
100 BlackBoxOp::Blake3 { message, output } => {
101 let message = to_u8_vec(read_heap_array(memory, message));
102 let bytes = blake3(message.as_slice())?;
103 write_heap_array(memory, output, &to_value_vec(&bytes));
104 Ok(())
105 }
106 BlackBoxOp::Keccakf1600 { input, output } => {
107 let state_vec: Vec<u64> = read_heap_array(memory, input)
108 .iter()
109 .map(|&memory_value| memory_value.expect_u64().unwrap())
110 .collect();
111 let state: [u64; 25] = state_vec.try_into().unwrap();
112
113 let new_state = keccakf1600(state)?;
114
115 let new_state: Vec<MemoryValue<F>> = new_state.into_iter().map(|x| x.into()).collect();
116 write_heap_array(memory, output, &new_state);
117 Ok(())
118 }
119 BlackBoxOp::EcdsaSecp256k1 {
120 hashed_msg,
121 public_key_x,
122 public_key_y,
123 signature,
124 result: result_address,
125 }
126 | BlackBoxOp::EcdsaSecp256r1 {
127 hashed_msg,
128 public_key_x,
129 public_key_y,
130 signature,
131 result: result_address,
132 } => {
133 let bb_func = black_box_function_from_op(op);
134
135 let public_key_x: [u8; 32] =
136 to_u8_vec(read_heap_array(memory, public_key_x)).try_into().map_err(|_| {
137 BlackBoxResolutionError::Failed(
138 bb_func,
139 "Invalid public key x length".to_string(),
140 )
141 })?;
142 let public_key_y: [u8; 32] =
143 to_u8_vec(read_heap_array(memory, public_key_y)).try_into().map_err(|_| {
144 BlackBoxResolutionError::Failed(
145 bb_func,
146 "Invalid public key y length".to_string(),
147 )
148 })?;
149 let signature: [u8; 64] =
150 to_u8_vec(read_heap_array(memory, signature)).try_into().map_err(|_| {
151 BlackBoxResolutionError::Failed(bb_func, "Invalid signature length".to_string())
152 })?;
153
154 let hashed_msg = to_u8_vec(read_heap_array(memory, hashed_msg));
155
156 let result = match op {
157 BlackBoxOp::EcdsaSecp256k1 { .. } => ecdsa_secp256k1_verify(
158 &hashed_msg.try_into().unwrap(),
159 &public_key_x,
160 &public_key_y,
161 &signature,
162 )?,
163 BlackBoxOp::EcdsaSecp256r1 { .. } => ecdsa_secp256r1_verify(
164 &hashed_msg.try_into().unwrap(),
165 &public_key_x,
166 &public_key_y,
167 &signature,
168 )?,
169 _ => unreachable!("`BlackBoxOp` is guarded against being a non-ecdsa operation"),
170 };
171
172 memory.write(*result_address, result.into());
173 Ok(())
174 }
175 BlackBoxOp::MultiScalarMul { points, scalars, outputs: result } => {
176 let points: Vec<F> = read_heap_array(memory, points)
177 .iter()
178 .enumerate()
179 .map(|(i, x)| {
180 if i % 3 == 2 {
181 let is_infinite: bool = x.expect_u1().unwrap();
182 F::from(is_infinite)
183 } else {
184 x.expect_field().unwrap()
185 }
186 })
187 .collect();
188 let scalars: Vec<F> = read_heap_array(memory, scalars)
189 .iter()
190 .map(|x| x.expect_field().unwrap())
191 .collect();
192 let mut scalars_lo = Vec::with_capacity(scalars.len() / 2);
193 let mut scalars_hi = Vec::with_capacity(scalars.len() / 2);
194 for (i, scalar) in scalars.iter().enumerate() {
195 if i % 2 == 0 {
196 scalars_lo.push(*scalar);
197 } else {
198 scalars_hi.push(*scalar);
199 }
200 }
201 let (x, y, is_infinite) = solver.multi_scalar_mul(
202 &points,
203 &scalars_lo,
204 &scalars_hi,
205 true, )?;
207 write_heap_array(
208 memory,
209 result,
210 &[
211 MemoryValue::new_field(x),
212 MemoryValue::new_field(y),
213 MemoryValue::U1(is_infinite != F::zero()),
214 ],
215 );
216 Ok(())
217 }
218 BlackBoxOp::EmbeddedCurveAdd {
219 input1_x,
220 input1_y,
221 input2_x,
222 input2_y,
223 result,
224 input1_infinite,
225 input2_infinite,
226 } => {
227 let input1_x = memory.read(*input1_x).expect_field().unwrap();
228 let input1_y = memory.read(*input1_y).expect_field().unwrap();
229 let input1_infinite: bool = memory.read(*input1_infinite).expect_u1().unwrap();
230 let input2_x = memory.read(*input2_x).expect_field().unwrap();
231 let input2_y = memory.read(*input2_y).expect_field().unwrap();
232 let input2_infinite: bool = memory.read(*input2_infinite).expect_u1().unwrap();
233 let (x, y, infinite) = solver.ec_add(
234 &input1_x,
235 &input1_y,
236 &input1_infinite.into(),
237 &input2_x,
238 &input2_y,
239 &input2_infinite.into(),
240 true, )?;
242
243 write_heap_array(
244 memory,
245 result,
246 &[
247 MemoryValue::new_field(x),
248 MemoryValue::new_field(y),
249 MemoryValue::U1(infinite != F::zero()),
250 ],
251 );
252 Ok(())
253 }
254 BlackBoxOp::Poseidon2Permutation { message, output } => {
255 let input = read_heap_array(memory, message);
256 let input: Vec<F> = input.iter().map(|x| x.expect_field().unwrap()).collect();
257 let result = solver.poseidon2_permutation(&input)?;
258 let mut values = Vec::new();
259 for i in result {
260 values.push(MemoryValue::new_field(i));
261 }
262 write_heap_array(memory, output, &values);
263 Ok(())
264 }
265 BlackBoxOp::Sha256Compression { input, hash_values, output } => {
266 let mut message = [0; 16];
267 let inputs = read_heap_array(memory, input);
268 if inputs.len() != 16 {
269 return Err(BlackBoxResolutionError::Failed(
270 BlackBoxFunc::Sha256Compression,
271 format!("Expected 16 inputs but encountered {}", &inputs.len()),
272 ));
273 }
274 for (i, &input) in inputs.iter().enumerate() {
275 message[i] = input.expect_u32().unwrap();
276 }
277 let mut state = [0; 8];
278 let values = read_heap_array(memory, hash_values);
279 if values.len() != 8 {
280 return Err(BlackBoxResolutionError::Failed(
281 BlackBoxFunc::Sha256Compression,
282 format!("Expected 8 values but encountered {}", &values.len()),
283 ));
284 }
285 for (i, &value) in values.iter().enumerate() {
286 state[i] = value.expect_u32().unwrap();
287 }
288
289 sha256_compression(&mut state, &message);
290 let state = state.map(|x| x.into());
291
292 write_heap_array(memory, output, &state);
293 Ok(())
294 }
295 BlackBoxOp::ToRadix { input, radix, output_pointer, num_limbs, output_bits } => {
296 let input: F = memory.read(*input).expect_field().expect("ToRadix input not a field");
297 let MemoryValue::U32(radix) = memory.read(*radix) else {
298 panic!("ToRadix opcode's radix bit size does not match expected bit size 32")
299 };
300 let num_limbs = memory.read(*num_limbs).to_u32();
301 let MemoryValue::U1(output_bits) = memory.read(*output_bits) else {
302 panic!("ToRadix opcode's output_bits size does not match expected bit size 1")
303 };
304
305 let output = to_be_radix(input, radix, assert_usize(num_limbs), output_bits)?;
306
307 memory.write_slice(memory.read_ref(*output_pointer), &output);
308
309 Ok(())
310 }
311 }
312}
313
314fn black_box_function_from_op(op: &BlackBoxOp) -> BlackBoxFunc {
320 match op {
321 BlackBoxOp::AES128Encrypt { .. } => BlackBoxFunc::AES128Encrypt,
322 BlackBoxOp::Blake2s { .. } => BlackBoxFunc::Blake2s,
323 BlackBoxOp::Blake3 { .. } => BlackBoxFunc::Blake3,
324 BlackBoxOp::Keccakf1600 { .. } => BlackBoxFunc::Keccakf1600,
325 BlackBoxOp::EcdsaSecp256k1 { .. } => BlackBoxFunc::EcdsaSecp256k1,
326 BlackBoxOp::EcdsaSecp256r1 { .. } => BlackBoxFunc::EcdsaSecp256r1,
327 BlackBoxOp::MultiScalarMul { .. } => BlackBoxFunc::MultiScalarMul,
328 BlackBoxOp::EmbeddedCurveAdd { .. } => BlackBoxFunc::EmbeddedCurveAdd,
329 BlackBoxOp::Poseidon2Permutation { .. } => BlackBoxFunc::Poseidon2Permutation,
330 BlackBoxOp::Sha256Compression { .. } => BlackBoxFunc::Sha256Compression,
331 BlackBoxOp::ToRadix { .. } => unreachable!("ToRadix is not an ACIR BlackBoxFunc"),
332 }
333}
334
335fn to_be_radix<F: AcirField>(
336 input: F,
337 radix: u32,
338 num_limbs: usize,
339 output_bits: bool,
340) -> Result<Vec<MemoryValue<F>>, BlackBoxResolutionError> {
341 assert!(
342 (2u32..=256u32).contains(&radix),
343 "Radix out of the valid range [2,256]. Value: {radix}"
344 );
345
346 assert!(
347 num_limbs >= 1 || input.is_zero(),
348 "Input value {input} is not zero but number of limbs is zero."
349 );
350
351 assert!(
352 !output_bits || radix == 2u32,
353 "Radix {radix} is not equal to 2 and bit mode is activated."
354 );
355
356 let mut input = BigUint::from_bytes_be(&input.to_be_bytes());
357 let radix = BigUint::from(radix);
358
359 let mut limbs: Vec<MemoryValue<F>> = vec![MemoryValue::default(); num_limbs];
360 for i in (0..num_limbs).rev() {
361 let limb = &input % &radix;
362 limbs[i] = if output_bits {
363 MemoryValue::U1(!limb.is_zero())
364 } else {
365 let limb: u8 = limb.try_into().unwrap();
366 MemoryValue::U8(limb)
367 };
368 input /= &radix;
369 }
370
371 if !input.is_zero() {
374 return Err(BlackBoxResolutionError::AssertFailed(format!(
375 "Field failed to decompose into specified {num_limbs} limbs"
376 )));
377 }
378
379 Ok(limbs)
380}
381
382#[cfg(test)]
383mod to_be_radix_tests {
384 use crate::black_box::to_be_radix;
385
386 use acir::{AcirField, FieldElement};
387
388 use proptest::prelude::*;
389
390 acir::acir_field::field_wrapper!(TestField, FieldElement);
394
395 impl Arbitrary for TestField {
396 type Parameters = ();
397 type Strategy = BoxedStrategy<Self>;
398
399 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
400 any::<u128>().prop_map(|v| Self(FieldElement::from(v))).boxed()
401 }
402 }
403
404 proptest! {
405 #[test]
406 fn matches_byte_decomposition(param: TestField) {
407 let bytes: Vec<u8> = to_be_radix(param.0, 256, 32, false).unwrap().into_iter().map(|byte| byte.expect_u8().unwrap()).collect();
408 let expected_bytes = param.0.to_be_bytes();
409 prop_assert_eq!(bytes, expected_bytes);
410 }
411 }
412
413 #[test]
414 fn correctly_handles_unusual_radices() {
415 let value = FieldElement::from(65024u128);
416 let expected_limbs = vec![254, 254];
417
418 let limbs: Vec<u8> = to_be_radix(value, 255, 2, false)
419 .unwrap()
420 .into_iter()
421 .map(|byte| byte.expect_u8().unwrap())
422 .collect();
423 assert_eq!(limbs, expected_limbs);
424 }
425
426 #[test]
427 fn matches_decimal_decomposition() {
428 let value = FieldElement::from(123456789u128);
429 let expected_limbs = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
430
431 let limbs: Vec<u8> = to_be_radix(value, 10, 9, false)
432 .unwrap()
433 .into_iter()
434 .map(|byte| byte.expect_u8().unwrap())
435 .collect();
436 assert_eq!(limbs, expected_limbs);
437 }
438}