provekit_acvm 1.0.0-beta.20

The virtual machine that processes ACIR given a backend/proof system.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use crate::pwg::{
    ErrorLocation, OpcodeNotSolvable, OpcodeResolutionError, ResolvedAssertionPayload,
    arithmetic::ExpressionSolver,
    blackbox::embedded_curve_ops::{execute_embedded_curve_add, execute_multi_scalar_mul},
    blackbox::{self, hash::get_hash_input},
    get_value, input_to_value,
    memory_op::MemoryOpSolver,
};
use acir::{
    AcirField,
    circuit::{
        Circuit, Opcode, OpcodeLocation,
        opcodes::{BlackBoxFuncCall, BlockId, MemOp},
    },
    native_types::{Witness, WitnessMap},
};
use acvm_blackbox_solver::{
    BlackBoxFunctionSolver, bit_and, bit_xor, blake2s, blake3, keccakf1600,
};
use itertools::Itertools;
use std::collections::HashMap;

fn unsatisfied_constraint<F>(opcode_index: usize, message: String) -> OpcodeResolutionError<F> {
    OpcodeResolutionError::UnsatisfiedConstrain {
        opcode_location: ErrorLocation::Resolved(OpcodeLocation::Acir(opcode_index)),
        payload: Some(ResolvedAssertionPayload::String(message)),
    }
}

fn witness_value<F: AcirField>(
    w: &Witness,
    witness_map: &WitnessMap<F>,
) -> Result<F, OpcodeResolutionError<F>> {
    Ok(*witness_map.get(w).ok_or(OpcodeNotSolvable::MissingAssignment(w.witness_index()))?)
}

fn check_fits_in_bits<F: AcirField>(
    value: F,
    num_bits: u32,
    opcode_index: usize,
    opcode_name: &str,
) -> Result<(), OpcodeResolutionError<F>> {
    if value.num_bits() > num_bits {
        return Err(unsatisfied_constraint(
            opcode_index,
            format!(
                "{opcode_name} opcode violation: value {value} does not fit in {num_bits} bits"
            ),
        ));
    }
    Ok(())
}

pub fn validate_witness<F: AcirField>(
    backend: &impl BlackBoxFunctionSolver<F>,
    witness_map: WitnessMap<F>,
    circuit: &Circuit<F>,
) -> Result<(), OpcodeResolutionError<F>> {
    let mut block_solvers: HashMap<BlockId, MemoryOpSolver<F>> = HashMap::new();

    for (opcode_index, opcode) in circuit.opcodes.iter().enumerate() {
        match opcode {
            Opcode::AssertZero(expression) => {
                let result = &ExpressionSolver::evaluate(expression, &witness_map);
                if !result.is_zero() {
                    return Err(unsatisfied_constraint(
                        opcode_index,
                        format!("Invalid witness assignment: {expression}"),
                    ));
                }
            }
            Opcode::BlackBoxFuncCall(black_box_func_call) => {
                match black_box_func_call {
                    BlackBoxFuncCall::AES128Encrypt { inputs, iv, key, outputs } => {
                        let ciphertext = blackbox::aes128::execute_aes128_encryption_opcode(
                            &witness_map,
                            inputs,
                            iv,
                            key,
                        )?;
                        for (output_witness, value) in outputs.iter().zip_eq(ciphertext.into_iter())
                        {
                            let witness_value = witness_value(output_witness, &witness_map)?;
                            let output_value = F::from(u128::from(value));
                            if witness_value != output_value {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "AES128 opcode violation: expected {output_value} but found {witness_value} for output witness {output_witness}",
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::AND { lhs, rhs, num_bits, output } => {
                        let lhs_value = input_to_value(&witness_map, *lhs)?;
                        let rhs_value = input_to_value(&witness_map, *rhs)?;
                        check_fits_in_bits(lhs_value, *num_bits, opcode_index, "AND")?;
                        check_fits_in_bits(rhs_value, *num_bits, opcode_index, "AND")?;
                        let and_result = bit_and(lhs_value, rhs_value, *num_bits);
                        let output_value = witness_map
                            .get(output)
                            .ok_or(OpcodeNotSolvable::MissingAssignment(output.0))?;
                        if and_result != *output_value {
                            return Err(unsatisfied_constraint(
                                opcode_index,
                                format!(
                                    "AND opcode violation: {lhs_value} AND {rhs_value} != {output_value} for {num_bits} bits"
                                ),
                            ));
                        }
                    }
                    BlackBoxFuncCall::XOR { lhs, rhs, num_bits, output } => {
                        let lhs_value = input_to_value(&witness_map, *lhs)?;
                        let rhs_value = input_to_value(&witness_map, *rhs)?;
                        check_fits_in_bits(lhs_value, *num_bits, opcode_index, "XOR")?;
                        check_fits_in_bits(rhs_value, *num_bits, opcode_index, "XOR")?;
                        let xor_result = bit_xor(lhs_value, rhs_value, *num_bits);
                        let output_value = witness_map
                            .get(output)
                            .ok_or(OpcodeNotSolvable::MissingAssignment(output.0))?;
                        if xor_result != *output_value {
                            return Err(unsatisfied_constraint(
                                opcode_index,
                                format!(
                                    "XOR opcode violation: {lhs_value} XOR {rhs_value} != {output_value} for {num_bits} bits"
                                ),
                            ));
                        }
                    }
                    BlackBoxFuncCall::RANGE { input, num_bits } => {
                        let value = input_to_value(&witness_map, *input)?;
                        check_fits_in_bits(value, *num_bits, opcode_index, "RANGE")?;
                    }
                    BlackBoxFuncCall::Blake2s { inputs, outputs } => {
                        let message_input = get_hash_input(&witness_map, inputs, None, 8)?;
                        let digest: [u8; 32] = blake2s(&message_input)?;
                        for i in 0..32 {
                            let output_witness = &outputs[i];
                            let witness_value = witness_map
                                .get(output_witness)
                                .ok_or(OpcodeNotSolvable::MissingAssignment(output_witness.0))?;
                            if *witness_value != F::from_be_bytes_reduce(&[digest[i]]) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "BLAKE2s opcode violation: expected {:?} but found {:?} for output witness {:?}",
                                        F::from_be_bytes_reduce(&[digest[i]]),
                                        witness_value,
                                        output_witness
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::Blake3 { inputs, outputs } => {
                        let message_input = get_hash_input(&witness_map, inputs, None, 8)?;
                        let digest: [u8; 32] = blake3(&message_input)?;
                        for i in 0..32 {
                            let output_witness = &outputs[i];
                            let witness_value = witness_value(output_witness, &witness_map)?;
                            if witness_value != F::from_be_bytes_reduce(&[digest[i]]) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "BLAKE3 opcode violation: expected {:?} but found {:?} for output witness {:?}",
                                        F::from_be_bytes_reduce(&[digest[i]]),
                                        witness_value,
                                        output_witness
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::EcdsaSecp256k1 {
                        public_key_x,
                        public_key_y,
                        signature,
                        hashed_message,
                        predicate,
                        output,
                    } => {
                        let predicate_value = input_to_value(&witness_map, *predicate)?.is_one();
                        if predicate_value {
                            let is_valid = blackbox::signature::ecdsa::execute_ecdsa(
                                &witness_map,
                                public_key_x,
                                public_key_y,
                                signature,
                                hashed_message,
                                predicate,
                                true,
                            )?;
                            let output_value = witness_value(output, &witness_map)?;
                            if output_value != F::from(is_valid) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "EcdsaSecp256k1 opcode violation: expected {:?} but found {:?} for output witness {:?}",
                                        F::from(is_valid),
                                        output_value,
                                        output
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::EcdsaSecp256r1 {
                        public_key_x,
                        public_key_y,
                        signature,
                        hashed_message,
                        predicate,
                        output,
                    } => {
                        let predicate_value = input_to_value(&witness_map, *predicate)?.is_one();
                        if predicate_value {
                            let is_valid = blackbox::signature::ecdsa::execute_ecdsa(
                                &witness_map,
                                public_key_x,
                                public_key_y,
                                signature,
                                hashed_message,
                                predicate,
                                false,
                            )?;
                            let output_value = witness_value(output, &witness_map)?;
                            if output_value != F::from(is_valid) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "EcdsaSecp256r1 opcode violation: expected {:?} but found {:?} for output witness {:?}",
                                        F::from(is_valid),
                                        output_value,
                                        output
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::MultiScalarMul { points, scalars, predicate, outputs } => {
                        let predicate_value = input_to_value(&witness_map, *predicate)?.is_one();
                        if predicate_value {
                            let (res_x, res_y, res_infinite) = execute_multi_scalar_mul(
                                backend,
                                &witness_map,
                                points,
                                scalars,
                                *predicate,
                            )?;
                            let output_x_value = witness_value(&outputs.0, &witness_map)?;
                            let output_y_value = witness_value(&outputs.1, &witness_map)?;
                            let output_infinite_value = witness_value(&outputs.2, &witness_map)?;
                            if res_x != output_x_value
                                || res_y != output_y_value
                                || res_infinite != output_infinite_value
                            {
                                //TODO: should we check x,y values if infinite is true?
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "MultiScalarMul opcode violation: expected ({res_x}, {res_y}, {res_infinite}) but found ({output_x_value}, {output_y_value}, {output_infinite_value})"
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::EmbeddedCurveAdd { input1, input2, predicate, outputs } => {
                        let predicate_value = input_to_value(&witness_map, *predicate)?.is_one();
                        if predicate_value {
                            let (res_x, res_y, res_infinite) = execute_embedded_curve_add(
                                backend,
                                &witness_map,
                                **input1,
                                **input2,
                                *predicate,
                            )?;
                            let output_x_value = witness_value(&outputs.0, &witness_map)?;
                            let output_y_value = witness_value(&outputs.1, &witness_map)?;
                            let output_infinite_value = witness_value(&outputs.2, &witness_map)?;
                            if res_x != output_x_value
                                || res_y != output_y_value
                                || res_infinite != output_infinite_value
                            {
                                //TODO: should we check x,y values if infinite is true?
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "EmbeddedCurveAdd opcode violation: expected ({res_x}, {res_y}, {res_infinite}) but found ({output_x_value}, {output_y_value}, {output_infinite_value})"
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::Keccakf1600 { inputs, outputs } => {
                        let mut state = [0; 25];
                        for (it, input) in state.iter_mut().zip_eq(inputs.as_ref()) {
                            let witness_assignment = input_to_value(&witness_map, *input)?;
                            let lane = witness_assignment.try_to_u64();
                            *it = lane.unwrap();
                        }
                        let output_state = keccakf1600(state)?;
                        for (output_witness, value) in
                            outputs.iter().zip_eq(output_state.into_iter())
                        {
                            let witness_value = witness_value(output_witness, &witness_map)?;
                            if witness_value != F::from(u128::from(value)) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "Keccakf1600 opcode violation: expected {value} but found {witness_value} for output witness {output_witness}",
                                    ),
                                ));
                            }
                        }
                    }
                    // Recursive aggregation is checked outside of ACVM
                    BlackBoxFuncCall::RecursiveAggregation { .. } => (),
                    BlackBoxFuncCall::Poseidon2Permutation { inputs, outputs } => {
                        let state = blackbox::hash::execute_poseidon2_permutation_opcode(
                            backend,
                            &witness_map,
                            inputs,
                        )?;
                        for (output_witness, value) in outputs.iter().zip_eq(state.into_iter()) {
                            let witness_value = witness_map
                                .get(output_witness)
                                .ok_or(OpcodeNotSolvable::MissingAssignment(output_witness.0))?;
                            if *witness_value != value {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "Poseidon2 opcode violation: expected {value} but found {witness_value} for output witness {output_witness}",
                                    ),
                                ));
                            }
                        }
                    }
                    BlackBoxFuncCall::Sha256Compression { inputs, hash_values, outputs } => {
                        let state = blackbox::hash::execute_sha_256_permutation_opcode(
                            &witness_map,
                            inputs,
                            hash_values,
                        )?;

                        for (output_witness, value) in outputs.iter().zip_eq(state.into_iter()) {
                            let witness_value = witness_map
                                .get(output_witness)
                                .ok_or(OpcodeNotSolvable::MissingAssignment(output_witness.0))?;
                            if *witness_value != F::from(u128::from(value)) {
                                return Err(unsatisfied_constraint(
                                    opcode_index,
                                    format!(
                                        "SHA256 Compression opcode violation: expected {:?} but found {:?} for output witness {:?}",
                                        F::from(u128::from(value)),
                                        witness_value,
                                        output_witness
                                    ),
                                ));
                            }
                        }
                    }
                }
            }
            Opcode::MemoryOp { block_id, op } => {
                let solver = block_solvers
                    .get_mut(block_id)
                    .expect("Memory block should have been initialized");
                solver.check_memory_op(op, &witness_map, opcode_index)?;
            }
            Opcode::MemoryInit { block_id, init, .. } => {
                MemoryOpSolver::new(init, &witness_map).map(|solver| {
                    let existing_block_id = block_solvers.insert(*block_id, solver);
                    assert!(existing_block_id.is_none(), "Memory block already initialized");
                })?;
            }
            // BrilligCall is unconstrained
            Opcode::BrilligCall { .. } => (),
            Opcode::Call { id: _, inputs, outputs, predicate } => {
                // Skip validation when predicate is false
                let pred_value = get_value(predicate, &witness_map)?;
                if pred_value.is_zero() {
                    continue;
                }

                // Verify input witnesses exist
                for input in inputs {
                    if witness_map.get(input).is_none() {
                        return Err(OpcodeNotSolvable::MissingAssignment(input.0).into());
                    }
                }

                // Verify output witnesses exist (value should have been validated by the called function)
                for output in outputs {
                    if witness_map.get(output).is_none() {
                        return Err(OpcodeNotSolvable::MissingAssignment(output.0).into());
                    }
                }
            }
        }
    }

    Ok(())
}

impl<F: AcirField> MemoryOpSolver<F> {
    pub(crate) fn check_memory_op(
        &mut self,
        op: &MemOp<F>,
        witness_map: &WitnessMap<F>,
        opcode_index: usize,
    ) -> Result<(), OpcodeResolutionError<F>> {
        let operation = get_value(&op.operation, witness_map)?;

        // Find the memory index associated with this memory operation.
        let index = get_value(&op.index, witness_map)?;
        let memory_index = self.index_from_field(index)?;

        // Calculate the value associated with this memory operation.
        let value = get_value(&op.value, witness_map)?;

        // `operation == 0` for read operation, `operation == 1` for write operation.
        let is_read_operation = operation.is_zero();

        if is_read_operation {
            // `value = arr[memory_index]`
            let value_in_array = self.read_memory_index(memory_index)?;
            if value != value_in_array {
                return Err(unsatisfied_constraint(
                    opcode_index,
                    format!(
                        "Memory read opcode violation at index {memory_index}: expected {value_in_array} but found {value}",
                    ),
                ));
            }
            Ok(())
        } else {
            // `arr[memory_index] = value`
            self.write_memory_index(memory_index, value)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use acir::{
        AcirField, FieldElement,
        circuit::{
            Circuit, Opcode, PublicInputs,
            opcodes::{BlackBoxFuncCall, FunctionInput},
        },
        native_types::{Expression, Witness, WitnessMap},
    };
    use bn254_blackbox_solver::Bn254BlackBoxSolver;

    use super::validate_witness;

    /// Helper to create a simple circuit with the given opcodes
    fn make_circuit(opcodes: Vec<Opcode<FieldElement>>) -> Circuit<FieldElement> {
        Circuit {
            current_witness_index: 10,
            opcodes,
            private_parameters: Default::default(),
            public_parameters: PublicInputs::default(),
            return_values: PublicInputs::default(),
            assert_messages: Default::default(),
            function_name: "test".to_string(),
        }
    }

    #[test]
    fn test_assert_zero_valid() {
        // w1 + w2 - w3 = 0, where w1=2, w2=3, w3=5
        let expr = Expression {
            mul_terms: vec![],
            linear_combinations: vec![
                (FieldElement::one(), Witness(1)),
                (FieldElement::one(), Witness(2)),
                (-FieldElement::one(), Witness(3)),
            ],
            q_c: FieldElement::zero(),
        };

        let circuit = make_circuit(vec![Opcode::AssertZero(expr)]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(2u128)),
            (Witness(2), FieldElement::from(3u128)),
            (Witness(3), FieldElement::from(5u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_assert_zero_invalid() {
        // w1 + w2 - w3 = 0, but w1=2, w2=3, w3=6 (should be 5)
        let expr = Expression {
            mul_terms: vec![],
            linear_combinations: vec![
                (FieldElement::one(), Witness(1)),
                (FieldElement::one(), Witness(2)),
                (-FieldElement::one(), Witness(3)),
            ],
            q_c: FieldElement::zero(),
        };

        let circuit = make_circuit(vec![Opcode::AssertZero(expr)]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(2u128)),
            (Witness(2), FieldElement::from(3u128)),
            (Witness(3), FieldElement::from(6u128)), // Wrong value!
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_assert_zero_with_multiplication() {
        // w1 * w2 - w3 = 0, where w1=3, w2=4, w3=12
        let expr = Expression {
            mul_terms: vec![(FieldElement::one(), Witness(1), Witness(2))],
            linear_combinations: vec![(-FieldElement::one(), Witness(3))],
            q_c: FieldElement::zero(),
        };

        let circuit = make_circuit(vec![Opcode::AssertZero(expr)]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(3u128)),
            (Witness(2), FieldElement::from(4u128)),
            (Witness(3), FieldElement::from(12u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_range_valid() {
        // w1 should fit in 8 bits
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::RANGE {
            input: FunctionInput::Witness(Witness(1)),
            num_bits: 8,
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(255u128)), // Max 8-bit value
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_range_invalid() {
        // w1 should fit in 8 bits, but 256 doesn't
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::RANGE {
            input: FunctionInput::Witness(Witness(1)),
            num_bits: 8,
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(256u128)), // Too large for 8 bits
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_and_valid() {
        // w1 AND w2 = w3, where w1=0b1010, w2=0b1100, w3=0b1000
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::AND {
            lhs: FunctionInput::Witness(Witness(1)),
            rhs: FunctionInput::Witness(Witness(2)),
            num_bits: 8,
            output: Witness(3),
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(0b1010u128)),
            (Witness(2), FieldElement::from(0b1100u128)),
            (Witness(3), FieldElement::from(0b1000u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_and_invalid() {
        // w1 AND w2 = w3, but w3 has wrong value
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::AND {
            lhs: FunctionInput::Witness(Witness(1)),
            rhs: FunctionInput::Witness(Witness(2)),
            num_bits: 8,
            output: Witness(3),
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(0b1010u128)),
            (Witness(2), FieldElement::from(0b1100u128)),
            (Witness(3), FieldElement::from(0b1111u128)), // Wrong!
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_xor_valid() {
        // w1 XOR w2 = w3, where w1=0b1010, w2=0b1100, w3=0b0110
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::XOR {
            lhs: FunctionInput::Witness(Witness(1)),
            rhs: FunctionInput::Witness(Witness(2)),
            num_bits: 8,
            output: Witness(3),
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(0b1010u128)),
            (Witness(2), FieldElement::from(0b1100u128)),
            (Witness(3), FieldElement::from(0b0110u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_xor_invalid() {
        // w1 XOR w2 = w3, but w3 has wrong value
        let circuit = make_circuit(vec![Opcode::BlackBoxFuncCall(BlackBoxFuncCall::XOR {
            lhs: FunctionInput::Witness(Witness(1)),
            rhs: FunctionInput::Witness(Witness(2)),
            num_bits: 8,
            output: Witness(3),
        })]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(0b1010u128)),
            (Witness(2), FieldElement::from(0b1100u128)),
            (Witness(3), FieldElement::from(0b1111u128)), // Wrong!
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_missing_witness_in_expression() {
        let expr = Expression {
            mul_terms: vec![],
            linear_combinations: vec![(FieldElement::one(), Witness(1))],
            q_c: FieldElement::zero(),
        };

        let circuit = make_circuit(vec![Opcode::AssertZero(expr)]);

        // Empty witness map - missing w1
        let witness_map = WitnessMap::default();

        let backend = Bn254BlackBoxSolver;
        // The expression evaluates with missing witness, but won't be zero
        // so this should fail
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_call_opcode_valid() {
        use acir::circuit::opcodes::AcirFunctionId;

        let circuit = make_circuit(vec![Opcode::Call {
            id: AcirFunctionId(1),
            inputs: vec![Witness(1), Witness(2)],
            outputs: vec![Witness(3)],
            predicate: Expression::one(),
        }]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(1u128)),
            (Witness(2), FieldElement::from(2u128)),
            (Witness(3), FieldElement::from(3u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_call_opcode_missing_input() {
        use acir::circuit::opcodes::AcirFunctionId;

        let circuit = make_circuit(vec![Opcode::Call {
            id: AcirFunctionId(1),
            inputs: vec![Witness(1), Witness(2)],
            outputs: vec![Witness(3)],
            predicate: Expression::one(),
        }]);

        // Missing Witness(2)
        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(1u128)),
            (Witness(3), FieldElement::from(3u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_call_opcode_missing_output() {
        use acir::circuit::opcodes::AcirFunctionId;

        let circuit = make_circuit(vec![Opcode::Call {
            id: AcirFunctionId(1),
            inputs: vec![Witness(1), Witness(2)],
            outputs: vec![Witness(3)],
            predicate: Expression::one(),
        }]);

        // Missing Witness(3) output
        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(1u128)),
            (Witness(2), FieldElement::from(2u128)),
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_call_opcode_skipped_with_zero_predicate() {
        use acir::circuit::opcodes::AcirFunctionId;

        // Predicate is zero, so call should be skipped even with missing witnesses
        let circuit = make_circuit(vec![Opcode::Call {
            id: AcirFunctionId(1),
            inputs: vec![Witness(1), Witness(2)],
            outputs: vec![Witness(3)],
            predicate: Expression {
                mul_terms: vec![],
                linear_combinations: vec![(FieldElement::one(), Witness(4))],
                q_c: FieldElement::zero(),
            },
        }]);

        // Witness(4) = 0, so predicate is false, call is skipped
        // Missing input/output witnesses should not cause an error
        let witness_map =
            WitnessMap::from(BTreeMap::from_iter([(Witness(4), FieldElement::zero())]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_memory_init_and_read() {
        use acir::circuit::opcodes::{BlockId, MemOp};

        let block_id = BlockId(0);

        let circuit = make_circuit(vec![
            // Initialize memory block with witnesses 1 and 2
            Opcode::MemoryInit {
                block_id,
                init: vec![Witness(1), Witness(2)],
                block_type: acir::circuit::opcodes::BlockType::Memory,
            },
            // Read from index 0 into witness 3
            Opcode::MemoryOp {
                block_id,
                op: MemOp::read_at_mem_index(FieldElement::zero().into(), Witness(3)),
            },
        ]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(42u128)),
            (Witness(2), FieldElement::from(43u128)),
            (Witness(3), FieldElement::from(42u128)), // Should match value at index 0
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_memory_read_wrong_value() {
        use acir::circuit::opcodes::{BlockId, MemOp};

        let block_id = BlockId(0);

        let circuit = make_circuit(vec![
            Opcode::MemoryInit {
                block_id,
                init: vec![Witness(1), Witness(2)],
                block_type: acir::circuit::opcodes::BlockType::Memory,
            },
            Opcode::MemoryOp {
                block_id,
                op: MemOp::read_at_mem_index(FieldElement::zero().into(), Witness(3)),
            },
        ]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(42u128)),
            (Witness(2), FieldElement::from(43u128)),
            (Witness(3), FieldElement::from(99u128)), // Wrong! Should be 42
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_err());
    }

    #[test]
    fn test_memory_write_then_read() {
        use acir::circuit::opcodes::{BlockId, MemOp};

        let block_id = BlockId(0);

        let circuit = make_circuit(vec![
            // Initialize memory block
            Opcode::MemoryInit {
                block_id,
                init: vec![Witness(1), Witness(2)],
                block_type: acir::circuit::opcodes::BlockType::Memory,
            },
            // Write value from witness 3 to index 0
            Opcode::MemoryOp {
                block_id,
                op: MemOp::write_to_mem_index(FieldElement::zero().into(), Witness(3).into()),
            },
            // Read from index 0 into witness 4
            Opcode::MemoryOp {
                block_id,
                op: MemOp::read_at_mem_index(FieldElement::zero().into(), Witness(4)),
            },
        ]);

        let witness_map = WitnessMap::from(BTreeMap::from_iter([
            (Witness(1), FieldElement::from(42u128)), // Initial value at index 0
            (Witness(2), FieldElement::from(43u128)), // Initial value at index 1
            (Witness(3), FieldElement::from(100u128)), // Value to write
            (Witness(4), FieldElement::from(100u128)), // Read should get written value
        ]));

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }

    #[test]
    fn test_brillig_call_with_empty_witness_map() {
        use acir::circuit::brillig::{BrilligFunctionId, BrilligInputs, BrilligOutputs};

        // Create a BrilligCall opcode with input and output witnesses
        // Brillig calls are unconstrained and should be skipped during validation,
        // so this should pass even with an empty witness map
        let circuit = make_circuit(vec![Opcode::BrilligCall {
            id: BrilligFunctionId(0),
            inputs: vec![
                BrilligInputs::Single(Witness(1).into()),
                BrilligInputs::Single(Witness(2).into()),
            ],
            outputs: vec![BrilligOutputs::Simple(Witness(3))],
            predicate: Expression::one(),
        }]);

        // Empty witness map
        let witness_map = WitnessMap::default();

        let backend = Bn254BlackBoxSolver;
        assert!(validate_witness(&backend, witness_map, &circuit).is_ok());
    }
}