-
Notifications
You must be signed in to change notification settings - Fork 200
/
acir_gen.rs
1462 lines (1355 loc) · 53.6 KB
/
acir_gen.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
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::ssa::{
builtin::Opcode,
context::SsaContext,
mem::{ArrayId, MemArray, Memory},
node::{BinaryOp, Instruction, Node, NodeId, ObjectType, Operation},
{builtin, mem, node},
};
use crate::{Evaluator, RuntimeErrorKind};
use acvm::{
acir::circuit::{
directives::Directive,
opcodes::{BlackBoxFuncCall, FunctionInput, Opcode as AcirOpcode},
},
acir::native_types::{Expression, Linear, Witness},
FieldElement,
};
use num_bigint::BigUint;
use num_traits::{One, Zero};
use std::{
cmp::Ordering,
collections::HashMap,
ops::{Mul, Neg},
};
#[derive(Default)]
pub struct Acir {
pub arith_cache: HashMap<NodeId, InternalVar>,
pub memory_map: HashMap<u32, InternalVar>, //maps memory address to expression
}
#[derive(Default, Clone, Debug)]
pub struct InternalVar {
expression: Expression,
//value: FieldElement, //not used for now
witness: Option<Witness>,
id: Option<NodeId>,
}
impl InternalVar {
fn new(expression: Expression, witness: Option<Witness>, id: NodeId) -> InternalVar {
InternalVar { expression, witness, id: Some(id) }
}
pub fn to_const(&self) -> Option<FieldElement> {
if self.expression.mul_terms.is_empty() && self.expression.linear_combinations.is_empty() {
return Some(self.expression.q_c);
}
None
}
pub fn generate_witness(&mut self, evaluator: &mut Evaluator) -> Witness {
if let Some(witness) = self.witness {
return witness;
}
if self.expression.is_const() {
todo!("Panic");
}
let witness = InternalVar::expression_to_witness(self.expression.clone(), evaluator);
self.witness = Some(witness);
witness
}
pub fn expression_to_witness(expr: Expression, evaluator: &mut Evaluator) -> Witness {
if expr.mul_terms.is_empty()
&& expr.linear_combinations.len() == 1
&& expr.q_c == FieldElement::zero()
&& expr.linear_combinations[0].0 == FieldElement::one()
{
return expr.linear_combinations[0].1;
}
evaluator.create_intermediate_variable(expr)
}
}
impl PartialEq for InternalVar {
fn eq(&self, other: &Self) -> bool {
self.expression == other.expression
|| (self.witness.is_some() && self.witness == other.witness)
|| (self.id.is_some() && self.id == other.id)
}
}
impl Eq for InternalVar {}
impl From<Expression> for InternalVar {
fn from(arith: Expression) -> InternalVar {
let w = is_unit(&arith);
InternalVar { expression: arith, witness: w, id: None }
}
}
impl From<Witness> for InternalVar {
fn from(w: Witness) -> InternalVar {
InternalVar { expression: from_witness(w), witness: Some(w), id: None }
}
}
impl From<FieldElement> for InternalVar {
fn from(f: FieldElement) -> InternalVar {
InternalVar { expression: Expression::from_field(f), witness: None, id: None }
}
}
impl Acir {
//This function stores the substitution with the arithmetic expression in the cache
//When an instruction performs arithmetic operation, its output can be represented as an arithmetic expression of its arguments
//Substitute a node object as an arithmetic expression
fn substitute(
&mut self,
id: NodeId,
evaluator: &mut Evaluator,
ctx: &SsaContext,
) -> InternalVar {
if self.arith_cache.contains_key(&id) {
return self.arith_cache[&id].clone();
}
let var = match ctx.try_get_node(id) {
Some(node::NodeObject::Const(c)) => {
let f_value = FieldElement::from_be_bytes_reduce(&c.value.to_bytes_be());
let expr = Expression::from_field(f_value);
InternalVar::new(expr, None, id)
}
Some(node::NodeObject::Obj(v)) => match v.get_type() {
node::ObjectType::Pointer(_) => InternalVar::default(),
_ => {
let w = v.witness.unwrap_or_else(|| evaluator.add_witness_to_cs());
let expr = Expression::from(&w);
InternalVar::new(expr, Some(w), id)
}
},
_ => {
let w = evaluator.add_witness_to_cs();
let expr = Expression::from(&w);
InternalVar::new(expr, Some(w), id)
}
};
self.arith_cache.insert(id, var.clone());
var
}
pub fn evaluate_instruction(
&mut self,
ins: &Instruction,
evaluator: &mut Evaluator,
ctx: &SsaContext,
) -> Result<(), RuntimeErrorKind> {
if ins.operation == Operation::Nop {
return Ok(());
}
let mut output = match &ins.operation {
Operation::Binary(binary) => self.evaluate_binary(binary, ins.res_type, evaluator, ctx),
Operation::Constrain(value, ..) => {
let value = self.substitute(*value, evaluator, ctx);
let subtract = subtract(&Expression::one(), FieldElement::one(), &value.expression);
evaluator.opcodes.push(AcirOpcode::Arithmetic(subtract));
value
}
Operation::Not(value) => {
let a = (1_u128 << ins.res_type.bits()) - 1;
let l_c = self.substitute(*value, evaluator, ctx);
subtract(
&Expression {
mul_terms: Vec::new(),
linear_combinations: Vec::new(),
q_c: FieldElement::from(a),
},
FieldElement::one(),
&l_c.expression,
)
.into()
}
Operation::Cast(value) => self.substitute(*value, evaluator, ctx),
i @ Operation::Jne(..)
| i @ Operation::Jeq(..)
| i @ Operation::Jmp(_)
| i @ Operation::Phi { .. }
| i @ Operation::Result { .. } => {
unreachable!("Invalid instruction: {:?}", i);
}
Operation::Truncate { value, bit_size, max_bit_size } => {
let value = self.substitute(*value, evaluator, ctx);
evaluate_truncate(value, *bit_size, *max_bit_size, evaluator)
}
Operation::Intrinsic(opcode, args) => {
let v = self.evaluate_opcode(ins.id, *opcode, args, ins.res_type, ctx, evaluator);
InternalVar::from(v)
}
Operation::Call { .. } => unreachable!("call instruction should have been inlined"),
Operation::Return(node_ids) => {
// XXX: When we return a node_id that was created from
// the UnitType, there is a witness associated with it
// Ideally no witnesses are created for such types.
// This can only ever be called in the main context.
// In all other context's, the return operation is transformed.
for node_id in node_ids {
// An array produces a single node_id
// We therefore need to check if the node_id is referring to an array
// and deference to get the elements
let objects = match Memory::deref(ctx, *node_id) {
Some(a) => {
let array = &ctx.mem[a];
self.load_array(array, false, evaluator)
}
None => vec![self.substitute(*node_id, evaluator, ctx)],
};
for mut object in objects {
let witness = if object.expression.is_const() {
evaluator.create_intermediate_variable(object.expression)
} else {
object.generate_witness(evaluator)
};
// Before pushing to the public inputs, we need to check that
// it was not a private ABI input
if evaluator.is_private_abi_input(witness) {
return Err(RuntimeErrorKind::Spanless(String::from(
"we do not allow private ABI inputs to be returned as public outputs",
)));
}
evaluator.public_inputs.push(witness);
}
}
InternalVar::default()
}
Operation::Cond { condition, val_true: lhs, val_false: rhs } => {
let cond = self.substitute(*condition, evaluator, ctx);
let l_c = self.substitute(*lhs, evaluator, ctx);
let r_c = self.substitute(*rhs, evaluator, ctx);
let sub = subtract(&l_c.expression, FieldElement::one(), &r_c.expression);
let result = add(
&mul_with_witness(evaluator, &cond.expression, &sub),
FieldElement::one(),
&r_c.expression,
);
result.into()
}
Operation::Nop => InternalVar::default(),
Operation::Load { array_id, index } => {
//retrieves the value from the map if address is known at compile time:
//address = l_c and should be constant
let index = self.substitute(*index, evaluator, ctx);
if let Some(index) = index.to_const() {
let idx = mem::Memory::as_u32(index);
let mem_array = &ctx.mem[*array_id];
let absolute_adr = mem_array.absolute_adr(idx);
if self.memory_map.contains_key(&absolute_adr) {
InternalVar::from(self.memory_map[&absolute_adr].expression.clone())
} else {
//if not found, then it must be a witness (else it is non-initialized memory)
let index = idx as usize;
if mem_array.values.len() > index {
mem_array.values[index].clone()
} else {
unreachable!("Could not find value at index {}", index);
}
}
} else {
unimplemented!("dynamic arrays are not implemented yet");
}
}
Operation::Store { array_id, index, value } => {
//maps the address to the rhs if address is known at compile time
let index = self.substitute(*index, evaluator, ctx);
let value = self.substitute(*value, evaluator, ctx);
if let Some(index) = index.to_const() {
let idx = mem::Memory::as_u32(index);
let absolute_adr = ctx.mem[*array_id].absolute_adr(idx);
self.memory_map.insert(absolute_adr, value);
//we do not generate constraint, so no output.
InternalVar::default()
} else {
todo!("dynamic arrays are not implemented yet");
}
}
};
output.id = Some(ins.id);
self.arith_cache.insert(ins.id, output);
Ok(())
}
fn get_predicate(
&mut self,
binary: &node::Binary,
evaluator: &mut Evaluator,
ctx: &SsaContext,
) -> InternalVar {
if let Some(pred) = binary.predicate {
self.substitute(pred, evaluator, ctx)
} else {
InternalVar::from(Expression::one())
}
}
fn evaluate_binary(
&mut self,
binary: &node::Binary,
res_type: ObjectType,
evaluator: &mut Evaluator,
ctx: &SsaContext,
) -> InternalVar {
let l_c = self.substitute(binary.lhs, evaluator, ctx);
let r_c = self.substitute(binary.rhs, evaluator, ctx);
let r_size = ctx[binary.rhs].size_in_bits();
let l_size = ctx[binary.lhs].size_in_bits();
let max_size = u32::max(r_size, l_size);
match &binary.operator {
BinaryOp::Add | BinaryOp::SafeAdd => {
InternalVar::from(add(&l_c.expression, FieldElement::one(), &r_c.expression))
}
BinaryOp::Sub { max_rhs_value } | BinaryOp::SafeSub { max_rhs_value } => {
if res_type == node::ObjectType::NativeField {
InternalVar::from(subtract(
&l_c.expression,
FieldElement::one(),
&r_c.expression,
))
} else {
//we need the type of rhs and its max value, then:
//lhs-rhs+k*2^bit_size where k=ceil(max_value/2^bit_size)
let bit_size = r_size;
let r_big = BigUint::one() << bit_size;
let mut k = max_rhs_value / &r_big;
if max_rhs_value % &r_big != BigUint::zero() {
k = &k + BigUint::one();
}
k = &k * r_big;
let f = FieldElement::from_be_bytes_reduce(&k.to_bytes_be());
let mut sub_expr =
subtract(&l_c.expression, FieldElement::one(), &r_c.expression);
sub_expr.q_c += f;
let mut sub_var = sub_expr.into();
//TODO: uses interval analysis for more precise check
if let Some(lhs_const) = l_c.to_const() {
if max_rhs_value <= &BigUint::from_bytes_be(&lhs_const.to_be_bytes()) {
sub_var = InternalVar::from(subtract(
&l_c.expression,
FieldElement::one(),
&r_c.expression,
));
}
}
sub_var
}
}
BinaryOp::Mul | BinaryOp::SafeMul => {
InternalVar::from(mul_with_witness(evaluator, &l_c.expression, &r_c.expression))
}
BinaryOp::Udiv => {
let predicate = self.get_predicate(binary, evaluator, ctx);
let (q_wit, _) = evaluate_udiv(&l_c, &r_c, max_size, &predicate, evaluator);
InternalVar::from(q_wit)
}
BinaryOp::Sdiv => InternalVar::from(evaluate_sdiv(&l_c, &r_c, evaluator).0),
BinaryOp::Urem => {
let predicate = self.get_predicate(binary, evaluator, ctx);
let (_, r_wit) = evaluate_udiv(&l_c, &r_c, max_size, &predicate, evaluator);
InternalVar::from(r_wit)
}
BinaryOp::Srem => InternalVar::from(evaluate_sdiv(&l_c, &r_c, evaluator).1),
BinaryOp::Div => {
let predicate = self.get_predicate(binary, evaluator, ctx);
let inverse = from_witness(evaluate_inverse(r_c, &predicate, evaluator));
InternalVar::from(mul_with_witness(evaluator, &l_c.expression, &inverse))
}
BinaryOp::Eq => InternalVar::from(
self.evaluate_eq(binary.lhs, binary.rhs, &l_c, &r_c, ctx, evaluator),
),
BinaryOp::Ne => InternalVar::from(
self.evaluate_neq(binary.lhs, binary.rhs, &l_c, &r_c, ctx, evaluator),
),
BinaryOp::Ult => {
let size = ctx[binary.lhs].get_type().bits();
evaluate_cmp(&l_c, &r_c, size, false, evaluator).into()
}
BinaryOp::Ule => {
let size = ctx[binary.lhs].get_type().bits();
let e = evaluate_cmp(&r_c, &l_c, size, false, evaluator);
subtract(&Expression::one(), FieldElement::one(), &e).into()
}
BinaryOp::Slt => {
let s = ctx[binary.lhs].get_type().bits();
evaluate_cmp(&l_c, &r_c, s, true, evaluator).into()
}
BinaryOp::Sle => {
let s = ctx[binary.lhs].get_type().bits();
let e = evaluate_cmp(&r_c, &l_c, s, true, evaluator);
subtract(&Expression::one(), FieldElement::one(), &e).into()
}
BinaryOp::Lt => unimplemented!(
"Field comparison is not implemented yet, try to cast arguments to integer type"
),
BinaryOp::Lte => unimplemented!(
"Field comparison is not implemented yet, try to cast arguments to integer type"
),
BinaryOp::And => InternalVar::from(evaluate_bitwise(
l_c,
r_c,
res_type.bits(),
evaluator,
BinaryOp::And,
)),
BinaryOp::Or => InternalVar::from(evaluate_bitwise(
l_c,
r_c,
res_type.bits(),
evaluator,
BinaryOp::Or,
)),
BinaryOp::Xor => InternalVar::from(evaluate_bitwise(
l_c,
r_c,
res_type.bits(),
evaluator,
BinaryOp::Xor,
)),
BinaryOp::Shl | BinaryOp::Shr => unreachable!(),
i @ BinaryOp::Assign => unreachable!("Invalid Instruction: {:?}", i),
}
}
pub fn print_circuit(opcodes: &[AcirOpcode]) {
for opcode in opcodes {
println!("{opcode:?}");
}
}
//Load array values into InternalVars
//If create_witness is true, we create witnesses for values that do not have witness
pub fn load_array(
&mut self,
array: &MemArray,
create_witness: bool,
evaluator: &mut Evaluator,
) -> Vec<InternalVar> {
(0..array.len)
.map(|i| {
let address = array.adr + i;
if let Some(memory) = self.memory_map.get_mut(&address) {
if create_witness && memory.witness.is_none() {
let w = evaluator.create_intermediate_variable(memory.expression.clone());
self.memory_map.get_mut(&address).unwrap().witness = Some(w);
}
self.memory_map[&address].clone()
} else {
array.values[i as usize].clone()
}
})
.collect()
}
//Map the outputs into the array
fn map_array(&mut self, a: ArrayId, outputs: &[Witness], ctx: &SsaContext) {
let array = &ctx.mem[a];
let adr = array.adr;
for i in 0..array.len {
if i < outputs.len() as u32 {
let var = InternalVar::from(outputs[i as usize]);
self.memory_map.insert(adr + i, var);
} else {
let var = InternalVar::from(Expression::zero());
self.memory_map.insert(adr + i, var);
}
}
}
pub fn evaluate_neq(
&mut self,
lhs: NodeId,
rhs: NodeId,
l_c: &InternalVar,
r_c: &InternalVar,
ctx: &SsaContext,
evaluator: &mut Evaluator,
) -> Expression {
if let (Some(a), Some(b)) = (Memory::deref(ctx, lhs), Memory::deref(ctx, rhs)) {
let array_a = &ctx.mem[a];
let array_b = &ctx.mem[b];
if array_a.len == array_b.len {
let mut x = InternalVar::from(self.zero_eq_array_sum(array_a, array_b, evaluator));
x.generate_witness(evaluator);
from_witness(evaluate_zero_equality(&x, evaluator))
} else {
//If length are different, then the arrays are different
Expression::one()
}
} else {
if let (Some(l), Some(r)) = (l_c.to_const(), r_c.to_const()) {
if l == r {
return Expression::default();
} else {
return Expression::one();
}
}
let mut x =
InternalVar::from(subtract(&l_c.expression, FieldElement::one(), &r_c.expression));
x.generate_witness(evaluator);
from_witness(evaluate_zero_equality(&x, evaluator))
}
}
pub fn evaluate_eq(
&mut self,
lhs: NodeId,
rhs: NodeId,
l_c: &InternalVar,
r_c: &InternalVar,
ctx: &SsaContext,
evaluator: &mut Evaluator,
) -> Expression {
let neq = self.evaluate_neq(lhs, rhs, l_c, r_c, ctx, evaluator);
subtract(&Expression::one(), FieldElement::one(), &neq)
}
//Generates gates for the expression: \sum_i(zero_eq(A[i]-B[i]))
//N.b. We assumes the lengths of a and b are the same but it is not checked inside the function.
fn zero_eq_array_sum(
&mut self,
a: &MemArray,
b: &MemArray,
evaluator: &mut Evaluator,
) -> Expression {
let mut sum = Expression::default();
let a_values = self.load_array(a, false, evaluator);
let b_values = self.load_array(b, false, evaluator);
for (a_iter, b_iter) in a_values.into_iter().zip(b_values) {
let diff_expr = subtract(&a_iter.expression, FieldElement::one(), &b_iter.expression);
let diff_witness = evaluator.add_witness_to_cs();
let diff_var = InternalVar {
//in cache??
expression: diff_expr.clone(),
witness: Some(diff_witness),
id: None,
};
evaluator.opcodes.push(AcirOpcode::Arithmetic(subtract(
&diff_expr,
FieldElement::one(),
&from_witness(diff_witness),
)));
//TODO: avoid creating witnesses for diff
sum = add(
&sum,
FieldElement::one(),
&from_witness(evaluate_zero_equality(&diff_var, evaluator)),
);
}
sum
}
//Transform the arguments of intrinsic functions into witnesses
pub fn prepare_inputs(
&mut self,
args: &[NodeId],
cfg: &SsaContext,
evaluator: &mut Evaluator,
) -> Vec<FunctionInput> {
let mut inputs: Vec<FunctionInput> = Vec::new();
for a in args {
let l_obj = cfg.try_get_node(*a).unwrap();
match l_obj {
node::NodeObject::Obj(v) => match l_obj.get_type() {
node::ObjectType::Pointer(a) => {
let array = &cfg.mem[a];
let num_bits = array.element_type.bits();
for i in 0..array.len {
let address = array.adr + i;
if self.memory_map.contains_key(&address) {
if let Some(wit) = self.memory_map[&address].witness {
inputs.push(FunctionInput { witness: wit, num_bits });
} else {
let mut var = self.memory_map[&address].clone();
if var.expression.is_const() {
let w = evaluator.create_intermediate_variable(
self.memory_map[&address].expression.clone(),
);
var.witness = Some(w);
}
let w = var.generate_witness(evaluator);
self.memory_map.insert(address, var);
inputs.push(FunctionInput { witness: w, num_bits });
}
} else {
inputs.push(FunctionInput {
witness: array.values[i as usize].witness.unwrap(),
num_bits,
});
}
}
}
_ => {
if let Some(w) = v.witness {
inputs.push(FunctionInput { witness: w, num_bits: v.size_in_bits() });
} else {
todo!("generate a witness");
}
}
},
_ => {
if self.arith_cache.contains_key(a) {
let mut var = self.arith_cache[a].clone();
let witness =
var.witness.unwrap_or_else(|| var.generate_witness(evaluator));
inputs.push(FunctionInput { witness, num_bits: l_obj.size_in_bits() });
} else {
unreachable!("invalid input: {:?}", l_obj)
}
}
}
}
inputs
}
pub fn evaluate_opcode(
&mut self,
instruction_id: NodeId,
opcode: builtin::Opcode,
args: &[NodeId],
res_type: ObjectType,
ctx: &SsaContext,
evaluator: &mut Evaluator,
) -> Expression {
let outputs;
match opcode {
Opcode::ToBits => {
let bit_size = ctx.get_as_constant(args[1]).unwrap().to_u128() as u32;
let l_c = self.substitute(args[0], evaluator, ctx);
outputs = to_radix_base(&l_c, 2, bit_size, evaluator);
if let node::ObjectType::Pointer(a) = res_type {
self.map_array(a, &outputs, ctx);
}
}
Opcode::ToRadix => {
let radix = ctx.get_as_constant(args[1]).unwrap().to_u128() as u32;
let limb_size = ctx.get_as_constant(args[2]).unwrap().to_u128() as u32;
let l_c = self.substitute(args[0], evaluator, ctx);
outputs = to_radix_base(&l_c, radix, limb_size, evaluator);
if let node::ObjectType::Pointer(a) = res_type {
self.map_array(a, &outputs, ctx);
}
}
Opcode::LowLevel(op) => {
let inputs = self.prepare_inputs(args, ctx, evaluator);
let output_count = op.definition().output_size.0 as u32;
outputs = self.prepare_outputs(instruction_id, output_count, ctx, evaluator);
let call_gate = BlackBoxFuncCall {
name: op,
inputs, //witness + bit size
outputs: outputs.clone(), //witness
};
evaluator.opcodes.push(AcirOpcode::BlackBoxFuncCall(call_gate));
}
}
if outputs.len() == 1 {
from_witness(outputs[0])
} else {
//if there are more than one witness returned, the result is inside ins.res_type as a pointer to an array
Expression::default()
}
}
pub fn prepare_outputs(
&mut self,
pointer: NodeId,
output_nb: u32,
ctx: &SsaContext,
evaluator: &mut Evaluator,
) -> Vec<Witness> {
// Create fresh variables that will link to the output
let mut outputs = Vec::with_capacity(output_nb as usize);
for _ in 0..output_nb {
let witness = evaluator.add_witness_to_cs();
outputs.push(witness);
}
let l_obj = ctx.try_get_node(pointer).unwrap();
if let node::ObjectType::Pointer(a) = l_obj.get_type() {
self.map_array(a, &outputs, ctx);
}
outputs
}
}
pub fn evaluate_sdiv(
_lhs: &InternalVar,
_rhs: &InternalVar,
_evaluator: &mut Evaluator,
) -> (Expression, Expression) {
todo!();
}
//Returns 1 if lhs < rhs
pub fn evaluate_cmp(
lhs: &InternalVar,
rhs: &InternalVar,
bit_size: u32,
signed: bool,
evaluator: &mut Evaluator,
) -> Expression {
if signed {
//TODO use range_constraints instead of bit decomposition, like in the unsigned case
let mut sub_expr = subtract(&lhs.expression, FieldElement::one(), &rhs.expression);
let two_pow = BigUint::one() << (bit_size + 1);
sub_expr.q_c += FieldElement::from_be_bytes_reduce(&two_pow.to_bytes_be());
let bits = to_radix_base(&sub_expr.into(), 2, bit_size + 2, evaluator);
from_witness(bits[(bit_size - 1) as usize])
} else {
let is_greater =
from_witness(bound_check(&lhs.expression, &rhs.expression, bit_size, evaluator));
subtract(&Expression::one(), FieldElement::one(), &is_greater)
}
}
const fn num_bits<T>() -> usize {
std::mem::size_of::<T>() * 8
}
pub fn bit_size_u32(a: u32) -> u32 where {
num_bits::<u32>() as u32 - a.leading_zeros()
}
pub fn bit_size_u128(a: u128) -> u32 where {
num_bits::<u128>() as u32 - a.leading_zeros()
}
//Decomposition into b-base: \sum ai b^i, where 0<=ai<b
// radix: the base, (it is a constant, not a witness)
// num_limbs: the number of elements in the decomposition
// output: (the elements of the decomposition as witness, the sum expression)
pub fn to_radix(
radix: u32,
num_limbs: u32,
evaluator: &mut Evaluator,
) -> (Vec<Witness>, Expression) {
let mut digits = Expression::default();
let mut radix_pow = FieldElement::one();
let shift = FieldElement::from(radix as i128);
let mut result = Vec::new();
let bit_size = bit_size_u32(radix);
for _ in 0..num_limbs {
let limb_witness = evaluator.add_witness_to_cs();
result.push(limb_witness);
let limb_expr = from_witness(limb_witness);
digits = add(&digits, radix_pow, &limb_expr);
radix_pow = radix_pow.mul(shift);
if 1_u128 << (bit_size - 1) != radix as u128 {
try_range_constraint(limb_witness, bit_size, evaluator);
}
bound_constraint_with_offset(
&from_witness(limb_witness),
&Expression::from_field(shift),
&Expression::one(),
bit_size,
evaluator,
);
}
(result, digits)
}
//decompose lhs onto radix-base with limb_size limbs
pub fn to_radix_base(
lhs: &InternalVar,
radix: u32,
limb_size: u32,
evaluator: &mut Evaluator,
) -> Vec<Witness> {
// ensure there is no overflow
let mut max = BigUint::from(radix);
max = max.pow(limb_size) - BigUint::one();
assert!(max < FieldElement::modulus());
let (result, bytes) = to_radix(radix, limb_size, evaluator);
evaluator.opcodes.push(AcirOpcode::Directive(Directive::ToRadix {
a: lhs.expression.clone(),
b: result.clone(),
radix,
}));
evaluator.opcodes.push(AcirOpcode::Arithmetic(subtract(
&lhs.expression,
FieldElement::one(),
&bytes,
)));
result
}
fn simplify_bitwise(
lhs: &InternalVar,
rhs: &InternalVar,
bit_size: u32,
opcode: &BinaryOp,
) -> Option<InternalVar> {
if lhs == rhs {
//simplify bitwise operation of the form: a OP a
return Some(match opcode {
BinaryOp::And => lhs.clone(),
BinaryOp::Or => lhs.clone(),
BinaryOp::Xor => InternalVar::from(FieldElement::zero()),
_ => unreachable!(),
});
}
assert!(bit_size < FieldElement::max_num_bits());
let max = FieldElement::from((1_u128 << bit_size) - 1);
let mut field = None;
let mut var = lhs;
if let Some(l_c) = lhs.to_const() {
if l_c == FieldElement::zero() || l_c == max {
field = Some(l_c);
var = rhs
}
} else if let Some(r_c) = rhs.to_const() {
if r_c == FieldElement::zero() || r_c == max {
field = Some(r_c);
}
}
if let Some(field) = field {
//simplify bitwise operation of the form: 0 OP var or 1 OP var
return Some(match opcode {
BinaryOp::And => {
if field.is_zero() {
InternalVar::from(field)
} else {
var.clone()
}
}
BinaryOp::Xor => {
if field.is_zero() {
var.clone()
} else {
InternalVar::from(subtract(
&Expression::from_field(field),
FieldElement::one(),
&var.expression,
))
}
}
BinaryOp::Or => {
if field.is_zero() {
var.clone()
} else {
InternalVar::from(field)
}
}
_ => unreachable!(),
});
}
None
}
fn evaluate_bitwise(
mut lhs: InternalVar,
mut rhs: InternalVar,
bit_size: u32,
evaluator: &mut Evaluator,
opcode: BinaryOp,
) -> Expression {
if let Some(var) = simplify_bitwise(&lhs, &rhs, bit_size, &opcode) {
return var.expression;
}
if bit_size == 1 {
match opcode {
BinaryOp::And => return mul_with_witness(evaluator, &lhs.expression, &rhs.expression),
BinaryOp::Xor => {
let sum = add(&lhs.expression, FieldElement::one(), &rhs.expression);
let mul = mul_with_witness(evaluator, &lhs.expression, &rhs.expression);
return subtract(&sum, FieldElement::from(2_i128), &mul);
}
BinaryOp::Or => {
let sum = add(&lhs.expression, FieldElement::one(), &rhs.expression);
let mul = mul_with_witness(evaluator, &lhs.expression, &rhs.expression);
return subtract(&sum, FieldElement::one(), &mul);
}
_ => unreachable!(),
}
}
//We generate witness from const values in order to use the ACIR bitwise gates
// If the gate is implemented, it is expected to be better than going through bit decomposition, even if one of the operand is a constant
// If the gate is not implemented, we rely on the ACIR simplification to remove these witnesses
if rhs.to_const().is_some() && rhs.witness.is_none() {
rhs.witness = Some(evaluator.create_intermediate_variable(rhs.expression.clone()));
assert!(lhs.to_const().is_none());
} else if lhs.to_const().is_some() && lhs.witness.is_none() {
assert!(rhs.to_const().is_none());
lhs.witness = Some(evaluator.create_intermediate_variable(lhs.expression.clone()));
}
let mut a_witness = lhs.generate_witness(evaluator);
let mut b_witness = rhs.generate_witness(evaluator);
let result = evaluator.add_witness_to_cs();
let bit_size = if bit_size % 2 == 1 { bit_size + 1 } else { bit_size };
assert!(bit_size < FieldElement::max_num_bits() - 1);
let max = FieldElement::from((1_u128 << bit_size) - 1);
let bit_gate = match opcode {
BinaryOp::And => acvm::acir::BlackBoxFunc::AND,
BinaryOp::Xor => acvm::acir::BlackBoxFunc::XOR,
BinaryOp::Or => {
a_witness = evaluator.create_intermediate_variable(subtract(
&Expression::from_field(max),
FieldElement::one(),
&lhs.expression,
));
b_witness = evaluator.create_intermediate_variable(subtract(
&Expression::from_field(max),
FieldElement::one(),
&rhs.expression,
));
acvm::acir::BlackBoxFunc::AND
}
_ => unreachable!(),
};
let gate = AcirOpcode::BlackBoxFuncCall(BlackBoxFuncCall {
name: bit_gate,
inputs: vec![
FunctionInput { witness: a_witness, num_bits: bit_size },
FunctionInput { witness: b_witness, num_bits: bit_size },
],
outputs: vec![result],
});
evaluator.opcodes.push(gate);
if opcode == BinaryOp::Or {
subtract(&Expression::from_field(max), FieldElement::one(), &from_witness(result))
} else {
from_witness(result)
}
}
//truncate lhs (a number whose value requires max_bits) into a rhs-bits number: i.e it returns b such that lhs mod 2^rhs is b
pub fn evaluate_truncate(
lhs: InternalVar,
rhs: u32,
max_bits: u32,
evaluator: &mut Evaluator,
) -> InternalVar {
assert!(max_bits > rhs, "max_bits = {max_bits}, rhs = {rhs}");
//0. Check for constant expression. This can happen through arithmetic simplifications
if let Some(a_c) = lhs.to_const() {
let mut a_big = BigUint::from_bytes_be(&a_c.to_be_bytes());
let two = BigUint::from(2_u32);
a_big %= two.pow(rhs);
return InternalVar::from(FieldElement::from_be_bytes_reduce(&a_big.to_bytes_be()));
}
//1. Generate witnesses a,b,c
let b_witness = evaluator.add_witness_to_cs();
let c_witness = evaluator.add_witness_to_cs();
try_range_constraint(b_witness, rhs, evaluator); //TODO propagate the error using ?
try_range_constraint(c_witness, max_bits - rhs, evaluator);
//2. Add the constraint a = b+2^Nc
let mut f = FieldElement::from(2_i128);
f = f.pow(&FieldElement::from(rhs as i128));
let b_arith = from_witness(b_witness);
let c_arith = from_witness(c_witness);
let res = add(&b_arith, f, &c_arith); //b+2^Nc
let my_constraint = add(&res, -FieldElement::one(), &lhs.expression);
evaluator.opcodes.push(AcirOpcode::Directive(Directive::Truncate {
a: lhs.expression,
b: b_witness,
c: c_witness,
bit_size: rhs,
}));
evaluator.opcodes.push(AcirOpcode::Arithmetic(my_constraint));
InternalVar::from(b_witness)
}
pub fn evaluate_udiv(
lhs: &InternalVar,
rhs: &InternalVar,
bit_size: u32,
predicate: &InternalVar,
evaluator: &mut Evaluator,
) -> (Witness, Witness) {
let q_witness = evaluator.add_witness_to_cs();
let r_witness = evaluator.add_witness_to_cs();
let pa = mul_with_witness(evaluator, &lhs.expression, &predicate.expression);
evaluator.opcodes.push(AcirOpcode::Directive(Directive::Quotient {