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
pub mod optimizers;
pub mod transformers;
use crate::Language;
use acir::{
circuit::{Circuit, Opcode},
native_types::{Expression, Witness},
BlackBoxFunc,
};
use indexmap::IndexMap;
use optimizers::GeneralOptimizer;
use thiserror::Error;
use transformers::{CSatTransformer, FallbackTransformer, IsBlackBoxSupported, R1CSTransformer};
#[derive(PartialEq, Eq, Debug, Error)]
pub enum CompileError {
#[error("The blackbox function {0} is not supported by the backend and acvm does not have a fallback implementation")]
UnsupportedBlackBox(BlackBoxFunc),
}
pub fn compile(
acir: Circuit,
np_language: Language,
is_black_box_supported: IsBlackBoxSupported,
) -> Result<Circuit, CompileError> {
let acir = FallbackTransformer::transform(acir, is_black_box_supported)?;
let mut opcodes: Vec<Opcode> = Vec::new();
for opcode in acir.opcodes {
match opcode {
Opcode::Arithmetic(arith_expr) => {
opcodes.push(Opcode::Arithmetic(GeneralOptimizer::optimize(arith_expr)))
}
other_gate => opcodes.push(other_gate),
};
}
let acir = Circuit { opcodes, ..acir };
let transformer = match &np_language {
crate::Language::R1CS => {
let transformer = R1CSTransformer::new(acir);
return Ok(transformer.transform());
}
crate::Language::PLONKCSat { width } => CSatTransformer::new(*width),
};
let mut transformed_gates = Vec::new();
let mut next_witness_index = acir.current_witness_index + 1;
for opcode in acir.opcodes {
match opcode {
Opcode::Arithmetic(arith_expr) => {
let mut intermediate_variables: IndexMap<Witness, Expression> = IndexMap::new();
let arith_expr = transformer.transform(
arith_expr,
&mut intermediate_variables,
next_witness_index,
);
next_witness_index += intermediate_variables.len() as u32;
let mut new_gates = Vec::new();
for (_, mut g) in intermediate_variables {
g.sort();
new_gates.push(g);
}
new_gates.push(arith_expr);
new_gates.sort();
for gate in new_gates {
transformed_gates.push(Opcode::Arithmetic(gate));
}
}
other_gate => transformed_gates.push(other_gate),
}
}
let current_witness_index = next_witness_index - 1;
Ok(Circuit {
current_witness_index,
opcodes: transformed_gates,
public_inputs: acir.public_inputs, })
}