brillig_vm/
black_box.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Implementations for VM native [black box functions][acir::brillig::Opcode::BlackBox].
use acir::brillig::{BlackBoxOp, HeapArray, HeapVector};
use acir::{AcirField, BlackBoxFunc};
use acvm_blackbox_solver::{
    BigIntSolverWithId, BlackBoxFunctionSolver, BlackBoxResolutionError, aes128_encrypt, blake2s,
    blake3, ecdsa_secp256k1_verify, ecdsa_secp256r1_verify, keccakf1600, sha256_compression,
};
use num_bigint::BigUint;
use num_traits::Zero;

use crate::Memory;
use crate::memory::MemoryValue;

/// Reads a dynamically-sized [vector][HeapVector] from memory.
fn read_heap_vector<'a, F: AcirField>(
    memory: &'a Memory<F>,
    vector: &HeapVector,
) -> &'a [MemoryValue<F>] {
    let size = memory.read(vector.size);
    memory.read_slice(memory.read_ref(vector.pointer), size.to_usize())
}

/// Reads a fixed-size [array][HeapArray] from memory.
fn read_heap_array<'a, F: AcirField>(
    memory: &'a Memory<F>,
    array: &HeapArray,
) -> &'a [MemoryValue<F>] {
    memory.read_slice(memory.read_ref(array.pointer), array.size)
}

/// Extracts the last byte of every value
fn to_u8_vec<F: AcirField>(inputs: &[MemoryValue<F>]) -> Vec<u8> {
    let mut result = Vec::with_capacity(inputs.len());
    for &input in inputs {
        result.push(input.expect_u8().unwrap());
    }
    result
}

/// Converts a slice of u8 values into a Vec<[`MemoryValue<F>`]>,
/// wrapping each byte as a [MemoryValue::U8].
fn to_value_vec<F: AcirField>(input: &[u8]) -> Vec<MemoryValue<F>> {
    input.iter().map(|&x| x.into()).collect()
}

pub(crate) type BrilligBigIntSolver = BigIntSolverWithId;

/// Evaluates a black box function inside the VM, performing the actual native computation.
///
/// Delegates the execution to the corresponding cryptographic or arithmetic
/// function, depending on the [BlackBoxOp] variant.
/// Handles input conversion, writing the result to memory, and error propagation.
///
/// # Arguments
/// - op: The black box operation to evaluate.
/// - solver: An implementation of [BlackBoxFunctionSolver] providing external function behavior.
/// - memory: The VM memory from which inputs are read and to which results are written.
/// - bigint_solver: A solver used for big integer operations.
///
/// # Returns
/// - Ok(()) if evaluation succeeds.
/// - Err([BlackBoxResolutionError]) if an error occurs during execution or input is invalid.
///
/// # Panics
/// If any required memory value cannot be converted to the expected type (e.g., [expect_u8][MemoryValue::expect_u8])
/// or if the [radix decomposition][BlackBoxOp::ToRadix] constraints are violated internally, such as an invalid radix range (e.g., radix of 1).
pub(crate) fn evaluate_black_box<F: AcirField, Solver: BlackBoxFunctionSolver<F>>(
    op: &BlackBoxOp,
    solver: &Solver,
    memory: &mut Memory<F>,
    bigint_solver: &mut BrilligBigIntSolver,
) -> Result<(), BlackBoxResolutionError> {
    match op {
        BlackBoxOp::AES128Encrypt { inputs, iv, key, outputs } => {
            let bb_func = black_box_function_from_op(op);

            let inputs = to_u8_vec(read_heap_vector(memory, inputs));

            let iv: [u8; 16] = to_u8_vec(read_heap_array(memory, iv)).try_into().map_err(|_| {
                BlackBoxResolutionError::Failed(bb_func, "Invalid iv length".to_string())
            })?;
            let key: [u8; 16] =
                to_u8_vec(read_heap_array(memory, key)).try_into().map_err(|_| {
                    BlackBoxResolutionError::Failed(bb_func, "Invalid key length".to_string())
                })?;
            let ciphertext = aes128_encrypt(&inputs, iv, key)?;

            memory.write(outputs.size, ciphertext.len().into());
            memory.write_slice(memory.read_ref(outputs.pointer), &to_value_vec(&ciphertext));

            Ok(())
        }
        BlackBoxOp::Blake2s { message, output } => {
            let message = to_u8_vec(read_heap_vector(memory, message));
            let bytes = blake2s(message.as_slice())?;
            memory.write_slice(memory.read_ref(output.pointer), &to_value_vec(&bytes));
            Ok(())
        }
        BlackBoxOp::Blake3 { message, output } => {
            let message = to_u8_vec(read_heap_vector(memory, message));
            let bytes = blake3(message.as_slice())?;
            memory.write_slice(memory.read_ref(output.pointer), &to_value_vec(&bytes));
            Ok(())
        }
        BlackBoxOp::Keccakf1600 { input, output } => {
            let state_vec: Vec<u64> = read_heap_array(memory, input)
                .iter()
                .map(|&memory_value| memory_value.expect_u64().unwrap())
                .collect();
            let state: [u64; 25] = state_vec.try_into().unwrap();

            let new_state = keccakf1600(state)?;

            let new_state: Vec<MemoryValue<F>> = new_state.into_iter().map(|x| x.into()).collect();
            memory.write_slice(memory.read_ref(output.pointer), &new_state);
            Ok(())
        }
        BlackBoxOp::EcdsaSecp256k1 {
            hashed_msg,
            public_key_x,
            public_key_y,
            signature,
            result: result_address,
        }
        | BlackBoxOp::EcdsaSecp256r1 {
            hashed_msg,
            public_key_x,
            public_key_y,
            signature,
            result: result_address,
        } => {
            let bb_func = black_box_function_from_op(op);

            let public_key_x: [u8; 32] =
                to_u8_vec(read_heap_array(memory, public_key_x)).try_into().map_err(|_| {
                    BlackBoxResolutionError::Failed(
                        bb_func,
                        "Invalid public key x length".to_string(),
                    )
                })?;
            let public_key_y: [u8; 32] =
                to_u8_vec(read_heap_array(memory, public_key_y)).try_into().map_err(|_| {
                    BlackBoxResolutionError::Failed(
                        bb_func,
                        "Invalid public key y length".to_string(),
                    )
                })?;
            let signature: [u8; 64] =
                to_u8_vec(read_heap_array(memory, signature)).try_into().map_err(|_| {
                    BlackBoxResolutionError::Failed(bb_func, "Invalid signature length".to_string())
                })?;

            let hashed_msg = to_u8_vec(read_heap_vector(memory, hashed_msg));

            let result = match op {
                BlackBoxOp::EcdsaSecp256k1 { .. } => {
                    ecdsa_secp256k1_verify(&hashed_msg, &public_key_x, &public_key_y, &signature)?
                }
                BlackBoxOp::EcdsaSecp256r1 { .. } => {
                    ecdsa_secp256r1_verify(&hashed_msg, &public_key_x, &public_key_y, &signature)?
                }
                _ => unreachable!("`BlackBoxOp` is guarded against being a non-ecdsa operation"),
            };

            memory.write(*result_address, result.into());
            Ok(())
        }
        BlackBoxOp::MultiScalarMul { points, scalars, outputs: result } => {
            let points: Vec<F> = read_heap_vector(memory, points)
                .iter()
                .enumerate()
                .map(|(i, x)| {
                    if i % 3 == 2 {
                        let is_infinite: bool = x.expect_u1().unwrap();
                        F::from(is_infinite)
                    } else {
                        x.expect_field().unwrap()
                    }
                })
                .collect();
            let scalars: Vec<F> = read_heap_vector(memory, scalars)
                .iter()
                .map(|x| x.expect_field().unwrap())
                .collect();
            let mut scalars_lo = Vec::with_capacity(scalars.len() / 2);
            let mut scalars_hi = Vec::with_capacity(scalars.len() / 2);
            for (i, scalar) in scalars.iter().enumerate() {
                if i % 2 == 0 {
                    scalars_lo.push(*scalar);
                } else {
                    scalars_hi.push(*scalar);
                }
            }
            let (x, y, is_infinite) = solver.multi_scalar_mul(&points, &scalars_lo, &scalars_hi)?;
            memory.write_slice(
                memory.read_ref(result.pointer),
                &[
                    MemoryValue::new_field(x),
                    MemoryValue::new_field(y),
                    MemoryValue::U1(is_infinite != F::zero()),
                ],
            );
            Ok(())
        }
        BlackBoxOp::EmbeddedCurveAdd {
            input1_x,
            input1_y,
            input2_x,
            input2_y,
            result,
            input1_infinite,
            input2_infinite,
        } => {
            let input1_x = memory.read(*input1_x).expect_field().unwrap();
            let input1_y = memory.read(*input1_y).expect_field().unwrap();
            let input1_infinite: bool = memory.read(*input1_infinite).expect_u1().unwrap();
            let input2_x = memory.read(*input2_x).expect_field().unwrap();
            let input2_y = memory.read(*input2_y).expect_field().unwrap();
            let input2_infinite: bool = memory.read(*input2_infinite).expect_u1().unwrap();
            let (x, y, infinite) = solver.ec_add(
                &input1_x,
                &input1_y,
                &input1_infinite.into(),
                &input2_x,
                &input2_y,
                &input2_infinite.into(),
            )?;
            memory.write_slice(
                memory.read_ref(result.pointer),
                &[
                    MemoryValue::new_field(x),
                    MemoryValue::new_field(y),
                    MemoryValue::U1(infinite != F::zero()),
                ],
            );
            Ok(())
        }
        BlackBoxOp::BigIntAdd { lhs, rhs, output } => {
            let lhs = memory.read(*lhs).expect_u32().unwrap();
            let rhs = memory.read(*rhs).expect_u32().unwrap();

            let new_id = bigint_solver.bigint_op(lhs, rhs, BlackBoxFunc::BigIntAdd)?;
            memory.write(*output, new_id.into());
            Ok(())
        }
        BlackBoxOp::BigIntSub { lhs, rhs, output } => {
            let lhs = memory.read(*lhs).expect_u32().unwrap();
            let rhs = memory.read(*rhs).expect_u32().unwrap();

            let new_id = bigint_solver.bigint_op(lhs, rhs, BlackBoxFunc::BigIntSub)?;
            memory.write(*output, new_id.into());
            Ok(())
        }
        BlackBoxOp::BigIntMul { lhs, rhs, output } => {
            let lhs = memory.read(*lhs).expect_u32().unwrap();
            let rhs = memory.read(*rhs).expect_u32().unwrap();

            let new_id = bigint_solver.bigint_op(lhs, rhs, BlackBoxFunc::BigIntMul)?;
            memory.write(*output, new_id.into());
            Ok(())
        }
        BlackBoxOp::BigIntDiv { lhs, rhs, output } => {
            let lhs = memory.read(*lhs).expect_u32().unwrap();
            let rhs = memory.read(*rhs).expect_u32().unwrap();

            let new_id = bigint_solver.bigint_op(lhs, rhs, BlackBoxFunc::BigIntDiv)?;
            memory.write(*output, new_id.into());
            Ok(())
        }
        BlackBoxOp::BigIntFromLeBytes { inputs, modulus, output } => {
            let input = read_heap_vector(memory, inputs);
            let input: Vec<u8> = input.iter().map(|x| x.expect_u8().unwrap()).collect();
            let modulus = read_heap_vector(memory, modulus);
            let modulus: Vec<u8> = modulus.iter().map(|x| x.expect_u8().unwrap()).collect();

            let new_id = bigint_solver.bigint_from_bytes(&input, &modulus)?;
            memory.write(*output, new_id.into());

            Ok(())
        }
        BlackBoxOp::BigIntToLeBytes { input, output } => {
            let input: u32 = memory.read(*input).expect_u32().unwrap();
            let bytes = bigint_solver.bigint_to_bytes(input)?;
            let mut values = Vec::new();
            for i in 0..32 {
                if i < bytes.len() {
                    values.push(bytes[i].into());
                } else {
                    values.push(0_u8.into());
                }
            }
            memory.write_slice(memory.read_ref(output.pointer), &values);
            Ok(())
        }
        BlackBoxOp::Poseidon2Permutation { message, output, len } => {
            let input = read_heap_vector(memory, message);
            let input: Vec<F> = input.iter().map(|x| x.expect_field().unwrap()).collect();
            let len = memory.read(*len).expect_u32().unwrap();
            let result = solver.poseidon2_permutation(&input, len)?;
            let mut values = Vec::new();
            for i in result {
                values.push(MemoryValue::new_field(i));
            }
            memory.write_slice(memory.read_ref(output.pointer), &values);
            Ok(())
        }
        BlackBoxOp::Sha256Compression { input, hash_values, output } => {
            let mut message = [0; 16];
            let inputs = read_heap_array(memory, input);
            if inputs.len() != 16 {
                return Err(BlackBoxResolutionError::Failed(
                    BlackBoxFunc::Sha256Compression,
                    format!("Expected 16 inputs but encountered {}", &inputs.len()),
                ));
            }
            for (i, &input) in inputs.iter().enumerate() {
                message[i] = input.expect_u32().unwrap();
            }
            let mut state = [0; 8];
            let values = read_heap_array(memory, hash_values);
            if values.len() != 8 {
                return Err(BlackBoxResolutionError::Failed(
                    BlackBoxFunc::Sha256Compression,
                    format!("Expected 8 values but encountered {}", &values.len()),
                ));
            }
            for (i, &value) in values.iter().enumerate() {
                state[i] = value.expect_u32().unwrap();
            }

            sha256_compression(&mut state, &message);
            let state = state.map(|x| x.into());

            memory.write_slice(memory.read_ref(output.pointer), &state);
            Ok(())
        }
        BlackBoxOp::ToRadix { input, radix, output_pointer, num_limbs, output_bits } => {
            let input: F = memory.read(*input).expect_field().expect("ToRadix input not a field");
            let MemoryValue::U32(radix) = memory.read(*radix) else {
                panic!("ToRadix opcode's radix bit size does not match expected bit size 32")
            };
            let num_limbs = memory.read(*num_limbs).to_usize();
            let MemoryValue::U1(output_bits) = memory.read(*output_bits) else {
                panic!("ToRadix opcode's output_bits size does not match expected bit size 1")
            };

            let mut input = BigUint::from_bytes_be(&input.to_be_bytes());

            // maximum number of bits that the limbs can hold
            let max_bit_size = radix.ilog2() * num_limbs as u32;
            let radix = BigUint::from_bytes_be(&radix.to_be_bytes());
            let mut limbs: Vec<MemoryValue<F>> = vec![MemoryValue::default(); num_limbs];

            assert!(
                radix >= BigUint::from(2u32) && radix <= BigUint::from(256u32),
                "Radix out of the valid range [2,256]. Value: {radix}"
            );

            assert!(
                num_limbs >= 1 || input == BigUint::from(0u32),
                "Input value {input} is not zero but number of limbs is zero."
            );

            assert!(
                !output_bits || radix == BigUint::from(2u32),
                "Radix {radix} is not equal to 2 and bit mode is activated."
            );

            if (input.bits() as u32) > max_bit_size {
                return Err(BlackBoxResolutionError::AssertFailed(format!(
                    "Field failed to decompose into specified {num_limbs} limbs"
                )));
            }
            for i in (0..num_limbs).rev() {
                let limb = &input % &radix;
                if output_bits {
                    limbs[i] = MemoryValue::U1(!limb.is_zero());
                } else {
                    let limb: u8 = limb.try_into().unwrap();
                    limbs[i] = MemoryValue::U8(limb);
                };
                input /= &radix;
            }

            memory.write_slice(memory.read_ref(*output_pointer), &limbs);

            Ok(())
        }
    }
}

/// Maps a [BlackBoxOp] variant to its corresponding [BlackBoxFunc].
/// Used primarily for error reporting and resolution purposes.
///
/// # Panics
/// If called with a [BlackBoxOp::ToRadix] operation, which is not part of the [BlackBoxFunc] enum.
fn black_box_function_from_op(op: &BlackBoxOp) -> BlackBoxFunc {
    match op {
        BlackBoxOp::AES128Encrypt { .. } => BlackBoxFunc::AES128Encrypt,
        BlackBoxOp::Blake2s { .. } => BlackBoxFunc::Blake2s,
        BlackBoxOp::Blake3 { .. } => BlackBoxFunc::Blake3,
        BlackBoxOp::Keccakf1600 { .. } => BlackBoxFunc::Keccakf1600,
        BlackBoxOp::EcdsaSecp256k1 { .. } => BlackBoxFunc::EcdsaSecp256k1,
        BlackBoxOp::EcdsaSecp256r1 { .. } => BlackBoxFunc::EcdsaSecp256r1,
        BlackBoxOp::MultiScalarMul { .. } => BlackBoxFunc::MultiScalarMul,
        BlackBoxOp::EmbeddedCurveAdd { .. } => BlackBoxFunc::EmbeddedCurveAdd,
        BlackBoxOp::BigIntAdd { .. } => BlackBoxFunc::BigIntAdd,
        BlackBoxOp::BigIntSub { .. } => BlackBoxFunc::BigIntSub,
        BlackBoxOp::BigIntMul { .. } => BlackBoxFunc::BigIntMul,
        BlackBoxOp::BigIntDiv { .. } => BlackBoxFunc::BigIntDiv,
        BlackBoxOp::BigIntFromLeBytes { .. } => BlackBoxFunc::BigIntFromLeBytes,
        BlackBoxOp::BigIntToLeBytes { .. } => BlackBoxFunc::BigIntToLeBytes,
        BlackBoxOp::Poseidon2Permutation { .. } => BlackBoxFunc::Poseidon2Permutation,
        BlackBoxOp::Sha256Compression { .. } => BlackBoxFunc::Sha256Compression,
        BlackBoxOp::ToRadix { .. } => unreachable!("ToRadix is not an ACIR BlackBoxFunc"),
    }
}