-
Notifications
You must be signed in to change notification settings - Fork 84
/
mod.rs
1638 lines (1442 loc) · 61.9 KB
/
mod.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
// Copyright (c) 2022 Espresso Systems (espressosys.com)
// This file is part of the Jellyfish library.
// You should have received a copy of the MIT License
// along with the Jellyfish library. If not, see <https://mit-license.org/>.
//! Customized gates and gadgets for rescue hash related, elliptic curve
//! related, rescue-based transcript and lookup table etc.
use self::gates::*;
use super::{Circuit, PlonkCircuit, PlonkError, Variable};
use crate::{
circuit::gates::{ConstantAdditionGate, ConstantMultiplicationGate, FifthRootGate},
constants::{GATE_WIDTH, N_MUL_SELECTORS},
errors::CircuitError,
};
use ark_ff::{BigInteger, PrimeField};
use ark_std::{borrow::ToOwned, boxed::Box, cmp::Ordering, format, string::ToString, vec::Vec};
use num_bigint::BigUint;
pub mod ecc;
mod gates;
pub mod rescue;
pub mod transcript;
pub mod ultraplonk;
impl<F> PlonkCircuit<F>
where
F: PrimeField,
{
/// Arithmetic gates
///
/// Quadratic polynomial gate: q1 * a + q2 * b + q3 * c + q4 * d + q12 * a *
/// b + q34 * c * d + q_c = q_o * e, where q1, q2, q3, q4, q12, q34,
/// q_c, q_o are selectors; a, b, c, d are input wires; e is the output
/// wire. Return error if variables are invalid.
pub fn quad_poly_gate(
&mut self,
wires: &[Variable; GATE_WIDTH + 1],
q_lc: &[F; GATE_WIDTH],
q_mul: &[F; N_MUL_SELECTORS],
q_o: F,
q_c: F,
) -> Result<(), PlonkError> {
self.check_vars_bound(wires)?;
self.insert_gate(
wires,
Box::new(QuadPolyGate {
q_lc: *q_lc,
q_mul: *q_mul,
q_o,
q_c,
}),
)?;
Ok(())
}
/// Arithmetic gates
///
/// Quadratic polynomial gate:
/// e = q1 * a + q2 * b + q3 * c + q4 * d + q12 * a *
/// b + q34 * c * d + q_c, where q1, q2, q3, q4, q12, q34,
/// q_c are selectors; a, b, c, d are input wires
///
/// Return the variable for
/// Return error if variables are invalid.
pub fn gen_quad_poly(
&mut self,
wires: &[Variable; GATE_WIDTH],
q_lc: &[F; GATE_WIDTH],
q_mul: &[F; N_MUL_SELECTORS],
q_c: F,
) -> Result<Variable, PlonkError> {
self.check_vars_bound(wires)?;
let output_val = q_lc[0] * self.witness(wires[0])?
+ q_lc[1] * self.witness(wires[1])?
+ q_lc[2] * self.witness(wires[2])?
+ q_lc[3] * self.witness(wires[3])?
+ q_mul[0] * self.witness(wires[0])? * self.witness(wires[1])?
+ q_mul[1] * self.witness(wires[2])? * self.witness(wires[3])?
+ q_c;
let output_var = self.create_variable(output_val)?;
let wires = [wires[0], wires[1], wires[2], wires[3], output_var];
self.insert_gate(
&wires,
Box::new(QuadPolyGate {
q_lc: *q_lc,
q_mul: *q_mul,
q_o: F::one(),
q_c,
}),
)?;
Ok(output_var)
}
/// Constrain a linear combination gate:
/// q1 * a + q2 * b + q3 * c + q4 * d = y
pub fn lc_gate(
&mut self,
wires: &[Variable; GATE_WIDTH + 1],
coeffs: &[F; GATE_WIDTH],
) -> Result<(), PlonkError> {
self.check_vars_bound(wires)?;
let wire_vars = [wires[0], wires[1], wires[2], wires[3], wires[4]];
self.insert_gate(&wire_vars, Box::new(LinCombGate { coeffs: *coeffs }))?;
Ok(())
}
/// Obtain a variable representing a linear combination.
/// Return error if variables are invalid.
pub fn lc(
&mut self,
wires_in: &[Variable; GATE_WIDTH],
coeffs: &[F; GATE_WIDTH],
) -> Result<Variable, PlonkError> {
self.check_vars_bound(wires_in)?;
let vals_in: Vec<F> = wires_in
.iter()
.map(|&var| self.witness(var))
.collect::<Result<Vec<_>, PlonkError>>()?;
// calculate y as the linear combination of coeffs and vals_in
let y_val = vals_in
.iter()
.zip(coeffs.iter())
.map(|(&val, &coeff)| val * coeff)
.sum();
let y = self.create_variable(y_val)?;
let wires = [wires_in[0], wires_in[1], wires_in[2], wires_in[3], y];
self.lc_gate(&wires, coeffs)?;
Ok(y)
}
/// Constrain a mul-addition gate:
/// q_muls\[0\] * wires\[0\] * wires\[1\] + q_muls\[1\] * wires\[2\] *
/// wires\[3\] = wires\[4\]
pub fn mul_add_gate(
&mut self,
wires: &[Variable; GATE_WIDTH + 1],
q_muls: &[F; N_MUL_SELECTORS],
) -> Result<(), PlonkError> {
self.check_vars_bound(wires)?;
let wire_vars = [wires[0], wires[1], wires[2], wires[3], wires[4]];
self.insert_gate(&wire_vars, Box::new(MulAddGate { coeffs: *q_muls }))?;
Ok(())
}
/// Obtain a variable representing `q12 * a * b + q34 * c * d`,
/// where `a, b, c, d` are input wires, and `q12`, `q34` are selectors.
/// Return error if variables are invalid.
pub fn mul_add(
&mut self,
wires_in: &[Variable; GATE_WIDTH],
q_muls: &[F; N_MUL_SELECTORS],
) -> Result<Variable, PlonkError> {
self.check_vars_bound(wires_in)?;
let vals_in: Vec<F> = wires_in
.iter()
.map(|&var| self.witness(var))
.collect::<Result<Vec<_>, PlonkError>>()?;
// calculate y as the mul-addition of coeffs and vals_in
let y_val = q_muls[0] * vals_in[0] * vals_in[1] + q_muls[1] * vals_in[2] * vals_in[3];
let y = self.create_variable(y_val)?;
let wires = [wires_in[0], wires_in[1], wires_in[2], wires_in[3], y];
self.mul_add_gate(&wires, q_muls)?;
Ok(y)
}
/// Obtain a variable representing the sum of a list of variables.
/// Return error if variables are invalid.
pub fn sum(&mut self, elems: &[Variable]) -> Result<Variable, PlonkError> {
if elems.is_empty() {
return Err(CircuitError::ParameterError(
"Sum over an empty slice of variables is undefined".to_string(),
)
.into());
}
self.check_vars_bound(elems)?;
let sum = {
let sum_val: F = elems
.iter()
.map(|&elem| self.witness(elem))
.collect::<Result<Vec<_>, PlonkError>>()?
.iter()
.sum();
self.create_variable(sum_val)?
};
// pad to ("next multiple of 3" + 1) in length
let mut padded: Vec<Variable> = elems.to_owned();
let rate = GATE_WIDTH - 1; // rate at which each lc add
let padded_len = next_multiple(elems.len() - 1, rate)? + 1;
padded.resize(padded_len, self.zero());
// z_0 = = x_0
// z_i = z_i-1 + x_3i-2 + x_3i-1 + x_3i
let coeffs = [F::one(); GATE_WIDTH];
let mut accum = padded[0];
for i in 1..padded_len / rate {
accum = self.lc(
&[
accum,
padded[rate * i - 2],
padded[rate * i - 1],
padded[rate * i],
],
&coeffs,
)?;
}
// final round
let wires = [
accum,
padded[padded_len - 3],
padded[padded_len - 2],
padded[padded_len - 1],
sum,
];
self.lc_gate(&wires, &coeffs)?;
Ok(sum)
}
/// Obtain a variable that equals `x_0` if `b` is zero, or `x_1` if `b` is
/// one. Return error if variables are invalid.
pub fn conditional_select(
&mut self,
b: Variable,
x_0: Variable,
x_1: Variable,
) -> Result<Variable, PlonkError> {
self.check_var_bound(b)?;
self.check_var_bound(x_0)?;
self.check_var_bound(x_1)?;
// y = x_bit
let y = if self.witness(b)? == F::zero() {
self.create_variable(self.witness(x_0)?)?
} else if self.witness(b)? == F::one() {
self.create_variable(self.witness(x_1)?)?
} else {
return Err(CircuitError::ParameterError(
"b in Conditional Selection gate is not a boolean variable".to_string(),
)
.into());
};
let wire_vars = [b, x_0, b, x_1, y];
self.insert_gate(&wire_vars, Box::new(CondSelectGate))?;
Ok(y)
}
/// Constrain variable `y` to the addition of `a` and `c`, where `c` is a
/// constant value Return error if the input variables are invalid.
fn add_constant_gate(&mut self, x: Variable, c: F, y: Variable) -> Result<(), PlonkError> {
self.check_var_bound(x)?;
self.check_var_bound(y)?;
let wire_vars = &[x, self.one(), 0, 0, y];
self.insert_gate(wire_vars, Box::new(ConstantAdditionGate(c)))?;
Ok(())
}
/// Obtains a variable representing an addition with a constant value
/// Return error if the input variable is invalid
pub fn add_constant(&mut self, input_var: Variable, elem: &F) -> Result<Variable, PlonkError> {
self.check_var_bound(input_var)?;
let input_val = self.witness(input_var).unwrap();
let output_val = *elem + input_val;
let output_var = self.create_variable(output_val).unwrap();
self.add_constant_gate(input_var, *elem, output_var)?;
Ok(output_var)
}
/// Constrain variable `y` to the product of `a` and `c`, where `c` is a
/// constant value Return error if the input variables are invalid.
fn mul_constant_gate(&mut self, x: Variable, c: F, y: Variable) -> Result<(), PlonkError> {
self.check_var_bound(x)?;
self.check_var_bound(y)?;
let wire_vars = &[x, 0, 0, 0, y];
self.insert_gate(wire_vars, Box::new(ConstantMultiplicationGate(c)))?;
Ok(())
}
/// Obtains a variable representing a multiplication with a constant value
/// Return error if the input variable is invalid
pub fn mul_constant(&mut self, input_var: Variable, elem: &F) -> Result<Variable, PlonkError> {
self.check_var_bound(input_var)?;
let input_val = self.witness(input_var).unwrap();
let output_val = *elem * input_val;
let output_var = self.create_variable(output_val).unwrap();
self.mul_constant_gate(input_var, *elem, output_var)?;
Ok(output_var)
}
/// Logic gates
/// Constrain that `a` is true or `b` is true.
/// Return error if variables are invalid.
pub fn logic_or_gate(&mut self, a: Variable, b: Variable) -> Result<(), PlonkError> {
self.check_var_bound(a)?;
self.check_var_bound(b)?;
let wire_vars = &[a, b, 0, 0, 0];
self.insert_gate(wire_vars, Box::new(LogicOrGate))?;
Ok(())
}
/// Obtain a bool variable representing whether two input variables are
/// equal. Return error if variables are invalid.
pub fn check_equal(&mut self, a: Variable, b: Variable) -> Result<Variable, PlonkError> {
self.check_var_bound(a)?;
self.check_var_bound(b)?;
let delta = self.sub(a, b)?;
self.check_is_zero(delta)
}
/// Obtain a bool variable representing whether input variable is zero.
/// Return error if the input variable is invalid.
pub fn check_is_zero(&mut self, a: Variable) -> Result<Variable, PlonkError> {
self.check_var_bound(a)?;
// y is the bit indicating if a == zero
// a_inv is the inverse of a when it's not 0
let a_val = self.witness(a)?;
let (y, a_inv) = if a_val.is_zero() {
(F::one(), F::zero())
} else {
(
F::zero(),
a_val.inverse().ok_or_else(|| {
CircuitError::FieldAlgebraError("Unable to find inverse".to_string())
})?,
)
};
let y = self.create_variable(y)?;
let a_inv = self.create_variable(a_inv)?;
// constraint 1: 1 - a * a^(-1) = y, i.e., a * a^(-1) + 1 * y = 1
self.mul_add_gate(
&[a, a_inv, self.one(), y, self.one()],
&[F::one(), F::one()],
)?;
// constraint 2: multiplication y * a = 0
self.mul_gate(y, a, self.zero())?;
Ok(y)
}
/// Constrain a variable to be non-zero.
/// Return error if the variable is invalid.
pub fn non_zero_gate(&mut self, var: Variable) -> Result<(), PlonkError> {
let inverse = self.witness(var)?.inverse().unwrap_or_else(F::zero);
let inv_var = self.create_variable(inverse)?;
let one_var = self.one();
self.mul_gate(var, inv_var, one_var)
}
/// Assuming value represented by `a` is boolean, obtain a
/// variable representing the result of a logic negation gate. Return the
/// index of the variable. Return error if the input variable is invalid.
pub fn logic_neg(&mut self, a: Variable) -> Result<Variable, PlonkError> {
self.check_is_zero(a)
}
/// Assuming values represented by `a` and `b` are boolean, obtain a
/// variable representing the result of a logic AND gate. Return the
/// index of the variable. Return error if the input variables are
/// invalid.
pub fn logic_and(&mut self, a: Variable, b: Variable) -> Result<Variable, PlonkError> {
self.mul(a, b)
}
/// Given a list of boolean variables, obtain a
/// variable representing the result of a logic AND gate. Return the
/// index of the variable. Return error if the input variables are
/// invalid.
pub fn logic_and_all(&mut self, vars: &[Variable]) -> Result<Variable, PlonkError> {
if vars.is_empty() {
return Err(PlonkError::InvalidParameters(
"logic_and_all: empty variable list".to_string(),
));
}
let mut res = vars[0];
for &var in vars.iter().skip(1) {
res = self.logic_and(res, var)?;
}
Ok(res)
}
/// Assuming values represented by `a` and `b` are boolean, obtain a
/// variable representing the result of a logic OR gate. Return the
/// index of the variable. Return error if the input variables are
/// invalid.
pub fn logic_or(&mut self, a: Variable, b: Variable) -> Result<Variable, PlonkError> {
self.check_var_bound(a)?;
self.check_var_bound(b)?;
let a_val = self.witness(a)?;
let b_val = self.witness(b)?;
let c_val = a_val + b_val - a_val * b_val;
let c = self.create_variable(c_val)?;
let wire_vars = &[a, b, 0, 0, c];
self.insert_gate(wire_vars, Box::new(LogicOrValueGate))?;
Ok(c)
}
/// Assuming values represented by `a` is boolean.
/// Constrain `a` is true
pub fn enforce_true(&mut self, a: Variable) -> Result<(), PlonkError> {
self.constant_gate(a, F::one())
}
/// Assuming values represented by `a` is boolean.
/// Constrain `a` is false
pub fn enforce_false(&mut self, a: Variable) -> Result<(), PlonkError> {
self.constant_gate(a, F::zero())
}
/// Return a variable to be the 11th power of the input variable.
/// Cost: 3 constraints.
pub fn power_11_gen(&mut self, x: Variable) -> Result<Variable, PlonkError> {
self.check_var_bound(x)?;
// now we prove that x^11 = x_to_11
let x_val = self.witness(x)?;
let x_to_5_val = x_val.pow(&[5]);
let x_to_5 = self.create_variable(x_to_5_val)?;
let wire_vars = &[x, 0, 0, 0, x_to_5];
self.insert_gate(wire_vars, Box::new(FifthRootGate))?;
let x_to_10 = self.mul(x_to_5, x_to_5)?;
self.mul(x_to_10, x)
}
/// Constraint a variable to be the 11th power of another variable.
/// Cost: 3 constraints.
pub fn power_11_gate(&mut self, x: Variable, x_to_11: Variable) -> Result<(), PlonkError> {
self.check_var_bound(x)?;
self.check_var_bound(x_to_11)?;
// now we prove that x^11 = x_to_11
let x_val = self.witness(x)?;
let x_to_5_val = x_val.pow(&[5]);
let x_to_5 = self.create_variable(x_to_5_val)?;
let wire_vars = &[x, 0, 0, 0, x_to_5];
self.insert_gate(wire_vars, Box::new(FifthRootGate))?;
let x_to_10 = self.mul(x_to_5, x_to_5)?;
self.mul_gate(x_to_10, x, x_to_11)
}
/// Obtain the truncation of the input.
/// Constrain that the input and output values congruent modulo
/// 2^bit_length. Return error if the input is invalid.
pub fn truncate(&mut self, a: Variable, bit_length: usize) -> Result<Variable, PlonkError> {
self.check_var_bound(a)?;
let a_val = self.witness(a)?;
let a_uint: BigUint = a_val.into();
let modulus = F::from(2u8).pow(&[bit_length as u64]);
let modulus_uint: BigUint = modulus.into();
let res = F::from(a_uint % modulus_uint);
let b = self.create_variable(res)?;
self.truncate_gate(a, b, bit_length)?;
Ok(b)
}
/// Truncation gate.
/// Constrain that b == a modulo 2^bit_length.
/// Return error if the inputs are invalid; or b >= 2^bit_length.
pub fn truncate_gate(
&mut self,
a: Variable,
b: Variable,
bit_length: usize,
) -> Result<(), PlonkError> {
if !self.support_lookup() {
return Err(PlonkError::InvalidParameters(
"does not support range table".to_string(),
));
}
self.check_var_bound(a)?;
self.check_var_bound(b)?;
let a_val = self.witness(a)?;
let b_val = self.witness(b)?;
let modulus = F::from(2u8).pow(&[bit_length as u64]);
let modulus_uint: BigUint = modulus.into();
if b_val >= modulus {
return Err(PlonkError::InvalidParameters(
"Truncation error: b is greater than 2^bit_length".to_string(),
));
}
let native_field_bit_length = F::size_in_bits();
if native_field_bit_length <= bit_length {
return Err(PlonkError::InvalidParameters(
"Truncation error: native field is not greater than truncation target".to_string(),
));
}
let bit_length_non_lookup_range = bit_length % self.range_bit_len()?;
let bit_length_lookup_component = bit_length - bit_length_non_lookup_range;
// we need to show that a and b satisfy the following
// relationship:
// (1) b = a mod modulus
// where
// * a is native_field_bit_length bits
// * b is bit_length bits
//
// which is
// (2) a = b + z * modulus
// for some z, where
// * z < 2^(native_field_bit_length - bit_length)
//
// So we set delta_length = native_field_bit_length - bit_length
let delta_length = native_field_bit_length - bit_length;
let delta_length_non_lookup_range = delta_length % self.range_bit_len()?;
let delta_length_lookup_component = delta_length - delta_length_non_lookup_range;
// Now (2) becomes
// (3) a = b1 + b2 * 2^bit_length_lookup_component
// + modulus * (z1 + 2^delta_length_lookup_component * z2)
// with
// b1 < 2^bit_length_lookup_component
// b2 < 2^bit_length_non_lookup_range
// z1 < 2^delta_length_lookup_component
// z2 < 2^delta_length_non_lookup_range
// The concrete statements we need to prove becomes
// (4) b = b1 + b2 * 2^bit_length_lookup_component
// (5) a = b + modulus * z1
// + modulus * 2^delta_length_lookup_component * z2
// (6) b1 < 2^bit_length_lookup_component
// (7) b2 < 2^bit_length_non_lookup_range
// (8) z1 < 2^delta_length_lookup_component
// (9) z2 < 2^delta_length_non_lookup_range
// step 1. setup the constants
let two_to_bit_length_lookup_component =
F::from(2u8).pow(&[bit_length_lookup_component as u64]);
let two_to_bit_length_lookup_component_uint: BigUint =
two_to_bit_length_lookup_component.into();
let two_to_delta_length_lookup_component =
F::from(2u8).pow(&[delta_length_lookup_component as u64]);
let two_to_delta_length_lookup_component_uint: BigUint =
two_to_delta_length_lookup_component.into();
let modulus_mul_two_to_delta_length_lookup_component_uint =
&two_to_delta_length_lookup_component_uint * &modulus_uint;
let modulus_mul_two_to_delta_length_lookup_component =
F::from(modulus_mul_two_to_delta_length_lookup_component_uint);
// step 2. get the intermediate data in the clear
let a_uint: BigUint = a_val.into();
let b_uint: BigUint = b_val.into();
let b1_uint = &b_uint % &two_to_bit_length_lookup_component_uint;
let b2_uint = &b_uint / &two_to_bit_length_lookup_component_uint;
let z_uint = (&a_uint - &b_uint) / &modulus_uint;
let z1_uint = &z_uint % &two_to_delta_length_lookup_component_uint;
let z2_uint = &z_uint / &two_to_delta_length_lookup_component_uint;
// step 3. create intermediate variables
let b1_var = self.create_variable(F::from(b1_uint))?;
let b2_var = self.create_variable(F::from(b2_uint))?;
let z1_var = self.create_variable(F::from(z1_uint))?;
let z2_var = self.create_variable(F::from(z2_uint))?;
// step 4. prove equations (4) - (9)
// (4) b = b1 + b2 * 2^bit_length_lookup_component
let wires = [b1_var, b2_var, self.zero(), self.zero(), b];
let coeffs = [
F::one(),
two_to_bit_length_lookup_component,
F::zero(),
F::zero(),
];
self.lc_gate(&wires, &coeffs)?;
// (5) a = b + modulus * z1
// + modulus * 2^delta_length_lookup_component * z2
let wires = [b, z1_var, z2_var, self.zero(), a];
let coeffs = [
F::one(),
modulus,
modulus_mul_two_to_delta_length_lookup_component,
F::zero(),
];
self.lc_gate(&wires, &coeffs)?;
// (6) b1 < 2^bit_length_lookup_component
// note that bit_length_lookup_component is public information
// so we don't need to add a selection gate here
if bit_length_lookup_component != 0 {
self.range_gate_with_lookup(b1_var, bit_length_lookup_component)?;
}
// (7) b2 < 2^bit_length_non_lookup_range
// note that bit_length_non_lookup_range is public information
// so we don't need to add a selection gate here
if bit_length_non_lookup_range != 0 {
self.range_gate(b2_var, bit_length_non_lookup_range)?;
}
// (8) z1 < 2^delta_length_lookup_component
// note that delta_length_lookup_component is public information
// so we don't need to add a selection gate here
if delta_length_lookup_component != 0 {
self.range_gate_with_lookup(z1_var, delta_length_lookup_component)?;
}
// (9) z2 < 2^delta_length_non_lookup_range
// note that delta_length_non_lookup_range is public information
// so we don't need to add a selection gate here
if delta_length_non_lookup_range != 0 {
self.range_gate(z2_var, delta_length_non_lookup_range)?;
}
Ok(())
}
}
impl<F: PrimeField> PlonkCircuit<F> {
/// Constrain a variable to be within the [0, 2^`bit_len`) range
/// Return error if the variable is invalid.
pub fn range_gate(&mut self, a: Variable, bit_len: usize) -> Result<(), PlonkError> {
if self.support_lookup() && bit_len % self.range_bit_len()? == 0 {
self.range_gate_with_lookup(a, bit_len)?;
} else {
self.range_gate_internal(a, bit_len)?;
}
Ok(())
}
/// Return a boolean variable indicating whether variable `a` is in the
/// range [0, 2^`bit_len`). Return error if the variable is invalid.
/// TODO: optimize the gate for UltraPlonk.
pub fn check_in_range(&mut self, a: Variable, bit_len: usize) -> Result<Variable, PlonkError> {
let a_bit_le = self.unpack(a, F::size_in_bits())?;
// a is in range if and only if the bits in `a_bit_le[bit_len..]` are all
// zeroes.
let higher_bit_sum = self.sum(&a_bit_le[bit_len..])?;
self.check_is_zero(higher_bit_sum)
}
/// Obtain the `bit_len`-long binary representation of variable `a`
/// Return a list of variables [b0, ..., b_`bit_len`] which is the binary
/// representation of `a`.
/// Return error if the `a` is not the range of [0, 2^`bit_len`).
pub fn unpack(&mut self, a: Variable, bit_len: usize) -> Result<Vec<Variable>, PlonkError> {
if bit_len < F::size_in_bits() && self.witness(a)? >= F::from(2u32).pow([bit_len as u64]) {
return Err(CircuitError::ParameterError(
"Failed to unpack variable to a range of smaller than 2^bit_len".to_string(),
)
.into());
}
self.range_gate_internal(a, bit_len)
}
// internal of a range check gate
fn range_gate_internal(
&mut self,
a: Variable,
bit_len: usize,
) -> Result<Vec<Variable>, PlonkError> {
self.check_var_bound(a)?;
if bit_len == 0 {
return Err(CircuitError::ParameterError(
"Only allows positive bit length for range upper bound".to_string(),
)
.into());
}
let a_bits_le: Vec<bool> = self.witness(a)?.into_repr().to_bits_le();
if bit_len > a_bits_le.len() {
return Err(CircuitError::ParameterError(format!(
"Maximum field bit size: {}, requested range upper bound bit len: {}",
a_bits_le.len(),
bit_len
))
.into());
}
// convert to variable in the circuit from the vector of boolean as binary
// representation
let a_bits_le: Vec<Variable> = a_bits_le
.iter()
.take(bit_len) // since little-endian, truncate would remove MSBs
.map(|&b| {
self.create_bool_variable(b)
})
.collect::<Result<Vec<_>, PlonkError>>()?;
self.decompose_vars_gate(a_bits_le.clone(), a, F::from(2u8))?;
Ok(a_bits_le)
}
pub(crate) fn decompose_vars_gate(
&mut self,
mut padded: Vec<Variable>,
a: Variable,
range_size: F,
) -> Result<(), PlonkError> {
// ensure (padded_len - 1) % 3 = 0
let len = padded.len();
let rate = GATE_WIDTH - 1; // rate at which lc add each round
let padded_len = next_multiple(len - 1, rate)? + 1;
padded.resize(padded_len, self.zero());
let range_size_square = range_size.square();
let range_size_cube = range_size * range_size_square;
let coeffs = [range_size_cube, range_size_square, range_size, F::one()];
let mut accum = padded[padded_len - 1];
for i in 1..padded_len / rate {
accum = self.lc(
&[
accum,
padded[padded_len - 1 - rate * i + 2],
padded[padded_len - 1 - rate * i + 1],
padded[padded_len - 1 - rate * i],
],
&coeffs,
)?;
}
// final round
let wires = [accum, padded[2], padded[1], padded[0], a];
self.lc_gate(&wires, &coeffs)?;
Ok(())
}
}
// helper function to find the next multiple of `divisor` for `current` value
pub(crate) fn next_multiple(current: usize, divisor: usize) -> Result<usize, PlonkError> {
if divisor == 0 || divisor == 1 {
return Err(CircuitError::InternalError(
"can only be a multiple of divisor >= 2".to_string(),
)
.into());
}
match current.cmp(&divisor) {
Ordering::Equal => Ok(current),
Ordering::Less => Ok(divisor),
Ordering::Greater => Ok((current / divisor + 1) * divisor),
}
}
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::circuit::{self, Arithmetization, Circuit};
use ark_bls12_377::Fq as Fq377;
use ark_ed_on_bls12_377::Fq as FqEd377;
use ark_ed_on_bls12_381::Fq as FqEd381;
use ark_ed_on_bn254::Fq as FqEd254;
use ark_std::{convert::TryInto, test_rng, vec};
// two circuit with the same statement should have the same extended permutation
// polynomials even with different variable assignment
pub(crate) fn test_variable_independence_for_circuit<F: PrimeField>(
circuit_1: PlonkCircuit<F>,
circuit_2: PlonkCircuit<F>,
) -> Result<(), PlonkError> {
assert_eq!(circuit_1.num_gates(), circuit_2.num_gates());
assert_eq!(circuit_1.num_vars(), circuit_2.num_vars());
// Check extended permutation polynomials
let sigma_polys_1 = circuit_1.compute_extended_permutation_polynomials()?;
let sigma_polys_2 = circuit_2.compute_extended_permutation_polynomials()?;
sigma_polys_1
.iter()
.zip(sigma_polys_2.iter())
.for_each(|(p1, p2)| assert_eq!(p1, p2));
Ok(())
}
#[test]
fn test_helper_next_multiple() -> Result<(), PlonkError> {
assert!(next_multiple(5, 0).is_err());
assert!(next_multiple(5, 1).is_err());
assert_eq!(next_multiple(5, 2)?, 6);
assert_eq!(next_multiple(5, 3)?, 6);
assert_eq!(next_multiple(5, 4)?, 8);
assert_eq!(next_multiple(5, 5)?, 5);
assert_eq!(next_multiple(5, 11)?, 11);
Ok(())
}
#[test]
fn test_logic_or() -> Result<(), PlonkError> {
test_logic_or_helper::<FqEd254>()?;
test_logic_or_helper::<FqEd377>()?;
test_logic_or_helper::<FqEd381>()?;
test_logic_or_helper::<Fq377>()
}
fn test_logic_or_helper<F: PrimeField>() -> Result<(), PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let zero_var = circuit.zero();
let one_var = circuit.one();
// Good path
circuit.logic_or_gate(zero_var, one_var)?;
circuit.logic_or_gate(one_var, zero_var)?;
circuit.logic_or_gate(one_var, one_var)?;
assert!(circuit.check_circuit_satisfiability(&[]).is_ok());
// Error path
circuit.logic_or_gate(zero_var, zero_var)?;
assert!(circuit.check_circuit_satisfiability(&[]).is_err());
let circuit_1 = build_logic_or_circuit(F::one(), F::one())?;
let circuit_2 = build_logic_or_circuit(F::zero(), F::one())?;
test_variable_independence_for_circuit::<F>(circuit_1, circuit_2)?;
Ok(())
}
fn build_logic_or_circuit<F: PrimeField>(a: F, b: F) -> Result<PlonkCircuit<F>, PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let a = circuit.create_variable(a)?;
let b = circuit.create_variable(b)?;
circuit.logic_or_gate(a, b)?;
circuit.finalize_for_arithmetization()?;
Ok(circuit)
}
#[test]
fn test_logic_and() -> Result<(), PlonkError> {
test_logic_and_helper::<FqEd254>()?;
test_logic_and_helper::<FqEd377>()?;
test_logic_and_helper::<FqEd381>()?;
test_logic_and_helper::<Fq377>()
}
fn test_logic_and_helper<F: PrimeField>() -> Result<(), PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let zero_var = circuit.zero();
let one_var = circuit.one();
// Good path
let a = circuit.logic_and(zero_var, one_var)?;
assert_eq!(F::zero(), circuit.witness(a)?);
let b = circuit.logic_and(one_var, zero_var)?;
assert_eq!(F::zero(), circuit.witness(b)?);
let c = circuit.logic_and(one_var, one_var)?;
assert_eq!(F::one(), circuit.witness(c)?);
let d = circuit.logic_and_all(&[zero_var, one_var, one_var])?;
assert_eq!(F::zero(), circuit.witness(d)?);
let e = circuit.logic_and_all(&[one_var, one_var, one_var])?;
assert_eq!(F::one(), circuit.witness(e)?);
assert!(circuit.check_circuit_satisfiability(&[]).is_ok());
// Error path
*circuit.witness_mut(e) = F::zero();
assert!(circuit.check_circuit_satisfiability(&[]).is_err());
*circuit.witness_mut(e) = F::one();
assert!(circuit.logic_and_all(&[]).is_err());
let circuit_1 = build_logic_and_circuit(F::one(), F::one())?;
let circuit_2 = build_logic_and_circuit(F::zero(), F::one())?;
test_variable_independence_for_circuit::<F>(circuit_1, circuit_2)?;
Ok(())
}
fn build_logic_and_circuit<F: PrimeField>(a: F, b: F) -> Result<PlonkCircuit<F>, PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let a = circuit.create_variable(a)?;
let b = circuit.create_variable(b)?;
circuit.logic_and(a, b)?;
circuit.finalize_for_arithmetization()?;
Ok(circuit)
}
#[test]
fn test_is_equal() -> Result<(), PlonkError> {
test_is_equal_helper::<FqEd254>()?;
test_is_equal_helper::<FqEd377>()?;
test_is_equal_helper::<FqEd381>()?;
test_is_equal_helper::<Fq377>()
}
fn test_is_equal_helper<F: PrimeField>() -> Result<(), PlonkError> {
let mut circuit = PlonkCircuit::<F>::new_turbo_plonk();
let val = F::from(31415u32);
let a = circuit.create_variable(val)?;
let b = circuit.create_variable(val)?;
let a_b_eq = circuit.check_equal(a, b)?;
let a_zero_eq = circuit.check_equal(a, circuit.zero())?;
// check circuit
assert_eq!(circuit.witness(a_b_eq)?, F::one());
assert_eq!(circuit.witness(a_zero_eq)?, F::zero());
assert!(circuit.check_circuit_satisfiability(&[]).is_ok());
*circuit.witness_mut(b) = val + F::one();
assert!(circuit.check_circuit_satisfiability(&[]).is_err());
// Check variable out of bound error.
assert!(circuit.check_equal(circuit.num_vars(), a).is_err());
let circuit_1 = build_is_equal_circuit(F::one(), F::one())?;
let circuit_2 = build_is_equal_circuit(F::zero(), F::one())?;
test_variable_independence_for_circuit(circuit_1, circuit_2)?;
Ok(())
}
fn build_is_equal_circuit<F: PrimeField>(a: F, b: F) -> Result<PlonkCircuit<F>, PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let a = circuit.create_variable(a)?;
let b = circuit.create_variable(b)?;
circuit.check_equal(a, b)?;
circuit.finalize_for_arithmetization()?;
Ok(circuit)
}
#[test]
fn test_check_is_zero() -> Result<(), PlonkError> {
test_check_is_zero_helper::<FqEd254>()?;
test_check_is_zero_helper::<FqEd377>()?;
test_check_is_zero_helper::<FqEd381>()?;
test_check_is_zero_helper::<Fq377>()
}
fn test_check_is_zero_helper<F: PrimeField>() -> Result<(), PlonkError> {
let mut circuit = PlonkCircuit::<F>::new_turbo_plonk();
let val = F::from(31415u32);
let a = circuit.create_variable(val)?;
let a_zero_eq = circuit.check_is_zero(a)?;
let zero_zero_eq = circuit.check_is_zero(circuit.zero())?;
// check circuit
assert_eq!(circuit.witness(a_zero_eq)?, F::zero());
assert_eq!(circuit.witness(zero_zero_eq)?, F::one());
assert!(circuit.check_circuit_satisfiability(&[]).is_ok());
*circuit.witness_mut(zero_zero_eq) = F::zero();
assert!(circuit.check_circuit_satisfiability(&[]).is_err());
*circuit.witness_mut(zero_zero_eq) = F::one();
*circuit.witness_mut(a) = F::zero();
assert!(circuit.check_circuit_satisfiability(&[]).is_err());
// Check variable out of bound error.
assert!(circuit.check_is_zero(circuit.num_vars()).is_err());
let circuit_1 = build_check_is_zero_circuit(F::one())?;
let circuit_2 = build_check_is_zero_circuit(F::zero())?;
test_variable_independence_for_circuit(circuit_1, circuit_2)?;
Ok(())
}
fn build_check_is_zero_circuit<F: PrimeField>(a: F) -> Result<PlonkCircuit<F>, PlonkError> {
let mut circuit = PlonkCircuit::new_turbo_plonk();
let a = circuit.create_variable(a)?;
circuit.check_is_zero(a)?;
circuit.finalize_for_arithmetization()?;
Ok(circuit)
}
#[test]
fn test_quad_poly_gate() -> Result<(), PlonkError> {
test_quad_poly_gate_helper::<FqEd254>()?;
test_quad_poly_gate_helper::<FqEd377>()?;
test_quad_poly_gate_helper::<FqEd381>()?;
test_quad_poly_gate_helper::<Fq377>()
}
fn test_quad_poly_gate_helper<F: PrimeField>() -> Result<(), PlonkError> {
let mut circuit: PlonkCircuit<F> = PlonkCircuit::new_turbo_plonk();
let q_lc = [F::from(2u32), F::from(3u32), F::from(5u32), F::from(2u32)];
let q_mul = [F::one(), F::from(2u8)];
let q_o = F::one();
let q_c = F::from(9u8);
let wires_1: Vec<_> = [
F::from(23u32),
F::from(8u32),
F::from(1u32),
-F::from(20u32),
F::from(188u32),
]
.iter()
.map(|val| circuit.create_variable(*val).unwrap())
.collect();
let wires_2: Vec<_> = [
F::zero(),
-F::from(8u32),
F::from(1u32),
F::zero(),
-F::from(10u32),