acvm/compiler/
simulator.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
use acir::{
    AcirField,
    circuit::{
        Circuit, Opcode,
        brillig::{BrilligInputs, BrilligOutputs},
        opcodes::{BlockId, FunctionInput},
    },
    native_types::{Expression, Witness},
};
use std::collections::HashSet;

/// Simulate a symbolic solve for a circuit
/// Instead of evaluating witness values from the inputs, like the PWG module is doing,
/// this pass simply mark the witness that can be evaluated, from the known inputs,
/// and incrementally from the previously marked witnesses.
/// This avoid any computation on a big field which makes the process efficient.
/// When all the witness of an opcode are marked as solvable, it means that the
/// opcode is solvable.
#[derive(Default)]
pub struct CircuitSimulator {
    /// Track the witnesses that can be solved
    solvable_witness: HashSet<Witness>,

    /// Track whether a [`BlockId`] has been initialized
    initialized_blocks: HashSet<BlockId>,
}

impl CircuitSimulator {
    /// Simulate a symbolic solve for a circuit by keeping track of the witnesses that can be solved.
    /// Returns the index of the opcode that cannot be solved, if any.
    #[tracing::instrument(level = "trace", skip_all)]
    pub fn check_circuit<F: AcirField>(&mut self, circuit: &Circuit<F>) -> Option<usize> {
        let circuit_inputs = circuit.circuit_arguments();
        self.solvable_witness.extend(circuit_inputs.iter());
        for (i, op) in circuit.opcodes.iter().enumerate() {
            if !self.try_solve(op) {
                return Some(i);
            }
        }
        None
    }

    /// Check if the Opcode can be solved, and if yes, add the solved witness to set of solvable witness
    fn try_solve<F: AcirField>(&mut self, opcode: &Opcode<F>) -> bool {
        let mut unresolved = HashSet::new();
        match opcode {
            Opcode::AssertZero(expr) => {
                for (_, w1, w2) in &expr.mul_terms {
                    if !self.solvable_witness.contains(w1) {
                        if !self.solvable_witness.contains(w2) {
                            return false;
                        }
                        unresolved.insert(*w1);
                    }
                    if !self.solvable_witness.contains(w2) && w1 != w2 {
                        unresolved.insert(*w2);
                    }
                }
                for (_, w) in &expr.linear_combinations {
                    if !self.solvable_witness.contains(w) {
                        unresolved.insert(*w);
                    }
                }
                if unresolved.len() == 1 {
                    self.mark_solvable(*unresolved.iter().next().unwrap());
                    return true;
                }
                unresolved.is_empty()
            }
            Opcode::BlackBoxFuncCall(black_box_func_call) => {
                let inputs = black_box_func_call.get_inputs_vec();
                for input in inputs {
                    if !self.can_solve_function_input(&input) {
                        return false;
                    }
                }
                let outputs = black_box_func_call.get_outputs_vec();
                for output in outputs {
                    self.mark_solvable(output);
                }
                true
            }
            Opcode::MemoryOp { block_id, op } => {
                if !self.initialized_blocks.contains(block_id) {
                    // Memory must be initialized before it can be used.
                    return false;
                }
                if !self.can_solve_expression(&op.index) {
                    return false;
                }
                if op.operation.is_zero() {
                    let Some(w) = op.value.to_witness() else {
                        return false;
                    };
                    self.mark_solvable(w);
                    true
                } else {
                    self.try_solve(&Opcode::AssertZero(op.value.clone()))
                }
            }
            Opcode::MemoryInit { block_id, init, .. } => {
                for w in init {
                    if !self.solvable_witness.contains(w) {
                        return false;
                    }
                }
                self.initialized_blocks.insert(*block_id)
            }
            Opcode::BrilligCall { id: _, inputs, outputs, predicate } => {
                for input in inputs {
                    if !self.can_solve_brillig_input(input) {
                        return false;
                    }
                }
                if let Some(predicate) = predicate {
                    if !self.can_solve_expression(predicate) {
                        return false;
                    }
                }
                for output in outputs {
                    match output {
                        BrilligOutputs::Simple(w) => self.mark_solvable(*w),
                        BrilligOutputs::Array(arr) => {
                            for w in arr {
                                self.mark_solvable(*w);
                            }
                        }
                    }
                }
                true
            }
            Opcode::Call { id: _, inputs, outputs, predicate } => {
                for w in inputs {
                    if !self.solvable_witness.contains(w) {
                        return false;
                    }
                }
                if let Some(predicate) = predicate {
                    if !self.can_solve_expression(predicate) {
                        return false;
                    }
                }
                for w in outputs {
                    self.mark_solvable(*w);
                }
                true
            }
        }
    }

    /// Adds the witness to set of solvable witness
    pub(crate) fn mark_solvable(&mut self, witness: Witness) {
        self.solvable_witness.insert(witness);
    }

    pub fn can_solve_function_input<F: AcirField>(&self, input: &FunctionInput<F>) -> bool {
        if let FunctionInput::Witness(w) = input {
            return self.solvable_witness.contains(w);
        }
        true
    }
    fn can_solve_expression<F>(&self, expr: &Expression<F>) -> bool {
        for w in Self::expr_wit(expr) {
            if !self.solvable_witness.contains(&w) {
                return false;
            }
        }
        true
    }
    fn can_solve_brillig_input<F>(&mut self, input: &BrilligInputs<F>) -> bool {
        match input {
            BrilligInputs::Single(expr) => self.can_solve_expression(expr),
            BrilligInputs::Array(exprs) => {
                for expr in exprs {
                    if !self.can_solve_expression(expr) {
                        return false;
                    }
                }
                true
            }

            BrilligInputs::MemoryArray(block_id) => self.initialized_blocks.contains(block_id),
        }
    }

    pub(crate) fn expr_wit<F>(expr: &Expression<F>) -> impl Iterator<Item = Witness> {
        expr.mul_terms
            .iter()
            .flat_map(|i| [i.1, i.2])
            .chain(expr.linear_combinations.iter().map(|i| i.1))
    }
}

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

    use crate::compiler::CircuitSimulator;
    use acir::{
        FieldElement,
        acir_field::AcirField,
        circuit::{
            Circuit, Opcode, PublicInputs,
            brillig::{BrilligFunctionId, BrilligInputs},
            opcodes::{BlockId, BlockType, MemOp},
        },
        native_types::{Expression, Witness},
    };

    fn test_circuit(
        opcodes: Vec<Opcode<FieldElement>>,
        private_parameters: BTreeSet<Witness>,
        public_parameters: PublicInputs,
    ) -> Circuit<FieldElement> {
        Circuit {
            function_name: "test_circuit".to_string(),
            current_witness_index: 1,
            opcodes,
            private_parameters,
            public_parameters,
            return_values: PublicInputs::default(),
            assert_messages: Default::default(),
        }
    }

    #[test]
    fn reports_true_for_empty_circuit() {
        let empty_circuit = test_circuit(vec![], BTreeSet::default(), PublicInputs::default());

        assert!(CircuitSimulator::default().check_circuit(&empty_circuit).is_none());
    }

    #[test]
    fn reports_true_for_connected_circuit() {
        let connected_circuit = test_circuit(
            vec![Opcode::AssertZero(Expression {
                mul_terms: Vec::new(),
                linear_combinations: vec![
                    (FieldElement::one(), Witness(1)),
                    (-FieldElement::one(), Witness(2)),
                ],
                q_c: FieldElement::zero(),
            })],
            BTreeSet::from([Witness(1)]),
            PublicInputs::default(),
        );

        assert!(CircuitSimulator::default().check_circuit(&connected_circuit).is_none());
    }

    #[test]
    fn reports_false_for_disconnected_circuit() {
        let disconnected_circuit = test_circuit(
            vec![
                Opcode::AssertZero(Expression {
                    mul_terms: Vec::new(),
                    linear_combinations: vec![
                        (FieldElement::one(), Witness(1)),
                        (-FieldElement::one(), Witness(2)),
                    ],
                    q_c: FieldElement::zero(),
                }),
                Opcode::AssertZero(Expression {
                    mul_terms: Vec::new(),
                    linear_combinations: vec![
                        (FieldElement::one(), Witness(3)),
                        (-FieldElement::one(), Witness(4)),
                    ],
                    q_c: FieldElement::zero(),
                }),
            ],
            BTreeSet::from([Witness(1)]),
            PublicInputs::default(),
        );

        assert!(CircuitSimulator::default().check_circuit(&disconnected_circuit).is_some());
    }

    #[test]
    fn reports_true_when_memory_block_passed_to_brillig_and_then_written_to() {
        let circuit = test_circuit(
            vec![
                Opcode::AssertZero(Expression {
                    mul_terms: Vec::new(),
                    linear_combinations: vec![(FieldElement::one(), Witness(1))],
                    q_c: FieldElement::zero(),
                }),
                Opcode::MemoryInit {
                    block_id: BlockId(0),
                    init: vec![Witness(0)],
                    block_type: BlockType::Memory,
                },
                Opcode::BrilligCall {
                    id: BrilligFunctionId(0),
                    inputs: vec![BrilligInputs::MemoryArray(BlockId(0))],
                    outputs: Vec::new(),
                    predicate: None,
                },
                Opcode::MemoryOp {
                    block_id: BlockId(0),
                    op: MemOp::read_at_mem_index(
                        Expression {
                            mul_terms: Vec::new(),
                            linear_combinations: Vec::new(),
                            q_c: FieldElement::one(),
                        },
                        Witness(2),
                    ),
                },
            ],
            BTreeSet::from([Witness(1)]),
            PublicInputs::default(),
        );

        assert!(CircuitSimulator::default().check_circuit(&circuit).is_some());
    }

    #[test]
    fn reports_false_when_attempting_to_reinitialize_memory_block() {
        let circuit = test_circuit(
            vec![
                Opcode::MemoryInit {
                    block_id: BlockId(0),
                    init: vec![Witness(0)],
                    block_type: BlockType::Memory,
                },
                Opcode::MemoryInit {
                    block_id: BlockId(0),
                    init: vec![Witness(0)],
                    block_type: BlockType::Memory,
                },
            ],
            BTreeSet::from([Witness(0)]),
            PublicInputs::default(),
        );

        assert!(CircuitSimulator::default().check_circuit(&circuit).is_some());
    }
}