-
Notifications
You must be signed in to change notification settings - Fork 36
/
ecc.rs
1184 lines (1045 loc) · 38.5 KB
/
ecc.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
//! This module implements various elliptic curve gadgets
#![allow(non_snake_case)]
use crate::{
gadgets::utils::{
alloc_num_equals, alloc_one, alloc_zero, conditionally_select, conditionally_select2,
select_num_or_one, select_num_or_zero, select_num_or_zero2, select_one_or_diff2,
select_one_or_num2, select_zero_or_num2,
},
traits::Group,
};
use bellpepper::gadgets::Assignment;
use bellpepper_core::{
boolean::{AllocatedBit, Boolean},
num::AllocatedNum,
ConstraintSystem, SynthesisError,
};
use ff::{Field, PrimeField};
/// `AllocatedPoint` provides an elliptic curve abstraction inside a circuit.
#[derive(Debug, Clone)]
pub struct AllocatedPoint<G: Group> {
pub(crate) x: AllocatedNum<G::Base>,
pub(crate) y: AllocatedNum<G::Base>,
pub(crate) is_infinity: AllocatedNum<G::Base>,
}
impl<G: Group> AllocatedPoint<G> {
/// Allocates a new point on the curve using coordinates provided by `coords`.
/// If coords = None, it allocates the default infinity point
pub fn alloc<CS: ConstraintSystem<G::Base>>(
mut cs: CS,
coords: Option<(G::Base, G::Base, bool)>,
) -> Result<Self, SynthesisError> {
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
Ok(coords.map_or(G::Base::ZERO, |c| c.0))
})?;
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(coords.map_or(G::Base::ZERO, |c| c.1))
})?;
let is_infinity = AllocatedNum::alloc(cs.namespace(|| "is_infinity"), || {
Ok(if coords.map_or(true, |c| c.2) {
G::Base::ONE
} else {
G::Base::ZERO
})
})?;
cs.enforce(
|| "is_infinity is bit",
|lc| lc + is_infinity.get_variable(),
|lc| lc + CS::one() - is_infinity.get_variable(),
|lc| lc,
);
Ok(Self { x, y, is_infinity })
}
/// checks if `self` is on the curve or if it is infinity
pub fn check_on_curve<CS>(&self, mut cs: CS) -> Result<(), SynthesisError>
where
CS: ConstraintSystem<G::Base>,
{
// check that (x,y) is on the curve if it is not infinity
// we will check that (1- is_infinity) * y^2 = (1-is_infinity) * (x^3 + Ax + B)
// note that is_infinity is already restricted to be in the set {0, 1}
let y_square = self.y.square(cs.namespace(|| "y_square"))?;
let x_square = self.x.square(cs.namespace(|| "x_square"))?;
let x_cube = self.x.mul(cs.namespace(|| "x_cube"), &x_square)?;
let rhs = AllocatedNum::alloc(cs.namespace(|| "rhs"), || {
if *self.is_infinity.get_value().get()? == G::Base::ONE {
Ok(G::Base::ZERO)
} else {
Ok(
*x_cube.get_value().get()?
+ *self.x.get_value().get()? * G::group_params().0
+ G::group_params().1,
)
}
})?;
cs.enforce(
|| "rhs = (1-is_infinity) * (x^3 + Ax + B)",
|lc| {
lc + x_cube.get_variable()
+ (G::group_params().0, self.x.get_variable())
+ (G::group_params().1, CS::one())
},
|lc| lc + CS::one() - self.is_infinity.get_variable(),
|lc| lc + rhs.get_variable(),
);
// check that (1-infinity) * y_square = rhs
cs.enforce(
|| "check that y_square * (1 - is_infinity) = rhs",
|lc| lc + y_square.get_variable(),
|lc| lc + CS::one() - self.is_infinity.get_variable(),
|lc| lc + rhs.get_variable(),
);
Ok(())
}
/// Allocates a default point on the curve, set to the identity point.
pub fn default<CS: ConstraintSystem<G::Base>>(mut cs: CS) -> Result<Self, SynthesisError> {
let zero = alloc_zero(cs.namespace(|| "zero"));
let one = alloc_one(cs.namespace(|| "one"));
Ok(Self {
x: zero.clone(),
y: zero,
is_infinity: one,
})
}
/// Returns coordinates associated with the point.
pub const fn get_coordinates(
&self,
) -> (
&AllocatedNum<G::Base>,
&AllocatedNum<G::Base>,
&AllocatedNum<G::Base>,
) {
(&self.x, &self.y, &self.is_infinity)
}
/// Negates the provided point
pub fn negate<CS: ConstraintSystem<G::Base>>(&self, mut cs: CS) -> Result<Self, SynthesisError> {
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || Ok(-*self.y.get_value().get()?))?;
cs.enforce(
|| "check y = - self.y",
|lc| lc + self.y.get_variable(),
|lc| lc + CS::one(),
|lc| lc - y.get_variable(),
);
Ok(Self {
x: self.x.clone(),
y,
is_infinity: self.is_infinity.clone(),
})
}
/// Add two points (may be equal)
pub fn add<CS: ConstraintSystem<G::Base>>(
&self,
mut cs: CS,
other: &Self,
) -> Result<Self, SynthesisError> {
// Compute boolean equal indicating if self = other
let equal_x = alloc_num_equals(
cs.namespace(|| "check self.x == other.x"),
&self.x,
&other.x,
)?;
let equal_y = alloc_num_equals(
cs.namespace(|| "check self.y == other.y"),
&self.y,
&other.y,
)?;
// Compute the result of the addition and the result of double self
let result_from_add = self.add_internal(cs.namespace(|| "add internal"), other, &equal_x)?;
let result_from_double = self.double(cs.namespace(|| "double"))?;
// Output:
// If (self == other) {
// return double(self)
// }else {
// if (self.x == other.x){
// return infinity [negation]
// } else {
// return add(self, other)
// }
// }
let result_for_equal_x = Self::select_point_or_infinity(
cs.namespace(|| "equal_y ? result_from_double : infinity"),
&result_from_double,
&Boolean::from(equal_y),
)?;
Self::conditionally_select(
cs.namespace(|| "equal ? result_from_double : result_from_add"),
&result_for_equal_x,
&result_from_add,
&Boolean::from(equal_x),
)
}
/// Adds other point to this point and returns the result. Assumes that the two points are
/// different and that both `other.is_infinity` and `this.is_infinity` are bits
pub fn add_internal<CS: ConstraintSystem<G::Base>>(
&self,
mut cs: CS,
other: &Self,
equal_x: &AllocatedBit,
) -> Result<Self, SynthesisError> {
//************************************************************************/
// lambda = (other.y - self.y) * (other.x - self.x).invert().unwrap();
//************************************************************************/
// First compute (other.x - self.x).inverse()
// If either self or other are the infinity point or self.x = other.x then compute bogus values
// Specifically,
// x_diff = self != inf && other != inf && self.x == other.x ? (other.x - self.x) : 1
// Compute self.is_infinity OR other.is_infinity =
// NOT(NOT(self.is_ifninity) AND NOT(other.is_infinity))
let at_least_one_inf = AllocatedNum::alloc(cs.namespace(|| "at least one inf"), || {
Ok(
G::Base::ONE
- (G::Base::ONE - *self.is_infinity.get_value().get()?)
* (G::Base::ONE - *other.is_infinity.get_value().get()?),
)
})?;
cs.enforce(
|| "1 - at least one inf = (1-self.is_infinity) * (1-other.is_infinity)",
|lc| lc + CS::one() - self.is_infinity.get_variable(),
|lc| lc + CS::one() - other.is_infinity.get_variable(),
|lc| lc + CS::one() - at_least_one_inf.get_variable(),
);
// Now compute x_diff_is_actual = at_least_one_inf OR equal_x
let x_diff_is_actual =
AllocatedNum::alloc(cs.namespace(|| "allocate x_diff_is_actual"), || {
Ok(if *equal_x.get_value().get()? {
G::Base::ONE
} else {
*at_least_one_inf.get_value().get()?
})
})?;
cs.enforce(
|| "1 - x_diff_is_actual = (1-equal_x) * (1-at_least_one_inf)",
|lc| lc + CS::one() - at_least_one_inf.get_variable(),
|lc| lc + CS::one() - equal_x.get_variable(),
|lc| lc + CS::one() - x_diff_is_actual.get_variable(),
);
// x_diff = 1 if either self.is_infinity or other.is_infinity or self.x = other.x else self.x -
// other.x
let x_diff = select_one_or_diff2(
cs.namespace(|| "Compute x_diff"),
&other.x,
&self.x,
&x_diff_is_actual,
)?;
let lambda = AllocatedNum::alloc(cs.namespace(|| "lambda"), || {
let x_diff_inv = if *x_diff_is_actual.get_value().get()? == G::Base::ONE {
// Set to default
G::Base::ONE
} else {
// Set to the actual inverse
(*other.x.get_value().get()? - *self.x.get_value().get()?)
.invert()
.unwrap()
};
Ok((*other.y.get_value().get()? - *self.y.get_value().get()?) * x_diff_inv)
})?;
cs.enforce(
|| "Check that lambda is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + x_diff.get_variable(),
|lc| lc + other.y.get_variable() - self.y.get_variable(),
);
//************************************************************************/
// x = lambda * lambda - self.x - other.x;
//************************************************************************/
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
Ok(
*lambda.get_value().get()? * lambda.get_value().get()?
- *self.x.get_value().get()?
- *other.x.get_value().get()?,
)
})?;
cs.enforce(
|| "check that x is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + lambda.get_variable(),
|lc| lc + x.get_variable() + self.x.get_variable() + other.x.get_variable(),
);
//************************************************************************/
// y = lambda * (self.x - x) - self.y;
//************************************************************************/
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(
*lambda.get_value().get()? * (*self.x.get_value().get()? - *x.get_value().get()?)
- *self.y.get_value().get()?,
)
})?;
cs.enforce(
|| "Check that y is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + self.x.get_variable() - x.get_variable(),
|lc| lc + y.get_variable() + self.y.get_variable(),
);
//************************************************************************/
// We only return the computed x, y if neither of the points is infinity and self.x != other.y
// if self.is_infinity return other.clone()
// elif other.is_infinity return self.clone()
// elif self.x == other.x return infinity
// Otherwise return the computed points.
//************************************************************************/
// Now compute the output x
let x1 = conditionally_select2(
cs.namespace(|| "x1 = other.is_infinity ? self.x : x"),
&self.x,
&x,
&other.is_infinity,
)?;
let x = conditionally_select2(
cs.namespace(|| "x = self.is_infinity ? other.x : x1"),
&other.x,
&x1,
&self.is_infinity,
)?;
let y1 = conditionally_select2(
cs.namespace(|| "y1 = other.is_infinity ? self.y : y"),
&self.y,
&y,
&other.is_infinity,
)?;
let y = conditionally_select2(
cs.namespace(|| "y = self.is_infinity ? other.y : y1"),
&other.y,
&y1,
&self.is_infinity,
)?;
let is_infinity1 = select_num_or_zero2(
cs.namespace(|| "is_infinity1 = other.is_infinity ? self.is_infinity : 0"),
&self.is_infinity,
&other.is_infinity,
)?;
let is_infinity = conditionally_select2(
cs.namespace(|| "is_infinity = self.is_infinity ? other.is_infinity : is_infinity1"),
&other.is_infinity,
&is_infinity1,
&self.is_infinity,
)?;
Ok(Self { x, y, is_infinity })
}
/// Doubles the supplied point.
pub fn double<CS: ConstraintSystem<G::Base>>(&self, mut cs: CS) -> Result<Self, SynthesisError> {
//*************************************************************/
// lambda = (G::Base::from(3) * self.x * self.x + G::GG::A())
// * (G::Base::from(2)) * self.y).invert().unwrap();
/*************************************************************/
// Compute tmp = (G::Base::ONE + G::Base::ONE)* self.y ? self != inf : 1
let tmp_actual = AllocatedNum::alloc(cs.namespace(|| "tmp_actual"), || {
Ok(*self.y.get_value().get()? + *self.y.get_value().get()?)
})?;
cs.enforce(
|| "check tmp_actual",
|lc| lc + CS::one() + CS::one(),
|lc| lc + self.y.get_variable(),
|lc| lc + tmp_actual.get_variable(),
);
let tmp = select_one_or_num2(cs.namespace(|| "tmp"), &tmp_actual, &self.is_infinity)?;
// Now compute lambda as (G::Base::from(3) * self.x * self.x + G::GG::A()) * tmp_inv
let prod_1 = AllocatedNum::alloc(cs.namespace(|| "alloc prod 1"), || {
Ok(G::Base::from(3) * self.x.get_value().get()? * self.x.get_value().get()?)
})?;
cs.enforce(
|| "Check prod 1",
|lc| lc + (G::Base::from(3), self.x.get_variable()),
|lc| lc + self.x.get_variable(),
|lc| lc + prod_1.get_variable(),
);
let lambda = AllocatedNum::alloc(cs.namespace(|| "alloc lambda"), || {
let tmp_inv = if *self.is_infinity.get_value().get()? == G::Base::ONE {
// Return default value 1
G::Base::ONE
} else {
// Return the actual inverse
(*tmp.get_value().get()?).invert().unwrap()
};
Ok(tmp_inv * (*prod_1.get_value().get()? + G::group_params().0))
})?;
cs.enforce(
|| "Check lambda",
|lc| lc + tmp.get_variable(),
|lc| lc + lambda.get_variable(),
|lc| lc + prod_1.get_variable() + (G::group_params().0, CS::one()),
);
/*************************************************************/
// x = lambda * lambda - self.x - self.x;
/*************************************************************/
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
Ok(
((*lambda.get_value().get()?) * (*lambda.get_value().get()?))
- *self.x.get_value().get()?
- self.x.get_value().get()?,
)
})?;
cs.enforce(
|| "Check x",
|lc| lc + lambda.get_variable(),
|lc| lc + lambda.get_variable(),
|lc| lc + x.get_variable() + self.x.get_variable() + self.x.get_variable(),
);
/*************************************************************/
// y = lambda * (self.x - x) - self.y;
/*************************************************************/
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(
(*lambda.get_value().get()?) * (*self.x.get_value().get()? - x.get_value().get()?)
- self.y.get_value().get()?,
)
})?;
cs.enforce(
|| "Check y",
|lc| lc + lambda.get_variable(),
|lc| lc + self.x.get_variable() - x.get_variable(),
|lc| lc + y.get_variable() + self.y.get_variable(),
);
/*************************************************************/
// Only return the computed x and y if the point is not infinity
/*************************************************************/
// x
let x = select_zero_or_num2(cs.namespace(|| "final x"), &x, &self.is_infinity)?;
// y
let y = select_zero_or_num2(cs.namespace(|| "final y"), &y, &self.is_infinity)?;
// is_infinity
let is_infinity = self.is_infinity.clone();
Ok(Self { x, y, is_infinity })
}
/// A gadget for scalar multiplication, optimized to use incomplete addition law.
/// The optimization here is analogous to <https://github.com/arkworks-rs/r1cs-std/blob/6d64f379a27011b3629cf4c9cb38b7b7b695d5a0/src/groups/curves/short_weierstrass/mod.rs#L295>,
/// except we use complete addition law over affine coordinates instead of projective coordinates for the tail bits
pub fn scalar_mul<CS: ConstraintSystem<G::Base>>(
&self,
mut cs: CS,
scalar_bits: &[AllocatedBit],
) -> Result<Self, SynthesisError> {
let split_len = core::cmp::min(scalar_bits.len(), (G::Base::NUM_BITS - 2) as usize);
let (incomplete_bits, complete_bits) = scalar_bits.split_at(split_len);
// we convert AllocatedPoint into AllocatedPointNonInfinity; we deal with the case where self.is_infinity = 1 below
let mut p = AllocatedPointNonInfinity::from_allocated_point(self);
// we assume the first bit to be 1, so we must initialize acc to self and double it
// we remove this assumption below
let mut acc = p;
p = acc.double_incomplete(cs.namespace(|| "double"))?;
// perform the double-and-add loop to compute the scalar mul using incomplete addition law
for (i, bit) in incomplete_bits.iter().enumerate().skip(1) {
let temp = acc.add_incomplete(cs.namespace(|| format!("add {i}")), &p)?;
acc = AllocatedPointNonInfinity::conditionally_select(
cs.namespace(|| format!("acc_iteration_{i}")),
&temp,
&acc,
&Boolean::from(bit.clone()),
)?;
p = p.double_incomplete(cs.namespace(|| format!("double {i}")))?;
}
// convert back to AllocatedPoint
let res = {
// we set acc.is_infinity = self.is_infinity
let acc = acc.to_allocated_point(&self.is_infinity)?;
// we remove the initial slack if bits[0] is as not as assumed (i.e., it is not 1)
let acc_minus_initial = {
let neg = self.negate(cs.namespace(|| "negate"))?;
acc.add(cs.namespace(|| "res minus self"), &neg)
}?;
Self::conditionally_select(
cs.namespace(|| "remove slack if necessary"),
&acc,
&acc_minus_initial,
&Boolean::from(scalar_bits[0].clone()),
)?
};
// when self.is_infinity = 1, return the default point, else return res
// we already set res.is_infinity to be self.is_infinity, so we do not need to set it here
let default = Self::default(cs.namespace(|| "default"))?;
let x = conditionally_select2(
cs.namespace(|| "check if self.is_infinity is zero (x)"),
&default.x,
&res.x,
&self.is_infinity,
)?;
let y = conditionally_select2(
cs.namespace(|| "check if self.is_infinity is zero (y)"),
&default.y,
&res.y,
&self.is_infinity,
)?;
// we now perform the remaining scalar mul using complete addition law
let mut acc = Self {
x,
y,
is_infinity: res.is_infinity,
};
let mut p_complete = p.to_allocated_point(&self.is_infinity)?;
for (i, bit) in complete_bits.iter().enumerate() {
let temp = acc.add(cs.namespace(|| format!("add_complete {i}")), &p_complete)?;
acc = Self::conditionally_select(
cs.namespace(|| format!("acc_complete_iteration_{i}")),
&temp,
&acc,
&Boolean::from(bit.clone()),
)?;
p_complete = p_complete.double(cs.namespace(|| format!("double_complete {i}")))?;
}
Ok(acc)
}
/// If condition outputs a otherwise outputs b
pub fn conditionally_select<CS: ConstraintSystem<G::Base>>(
mut cs: CS,
a: &Self,
b: &Self,
condition: &Boolean,
) -> Result<Self, SynthesisError> {
let x = conditionally_select(cs.namespace(|| "select x"), &a.x, &b.x, condition)?;
let y = conditionally_select(cs.namespace(|| "select y"), &a.y, &b.y, condition)?;
let is_infinity = conditionally_select(
cs.namespace(|| "select is_infinity"),
&a.is_infinity,
&b.is_infinity,
condition,
)?;
Ok(Self { x, y, is_infinity })
}
/// If condition outputs a otherwise infinity
pub fn select_point_or_infinity<CS: ConstraintSystem<G::Base>>(
mut cs: CS,
a: &Self,
condition: &Boolean,
) -> Result<Self, SynthesisError> {
let x = select_num_or_zero(cs.namespace(|| "select x"), &a.x, condition)?;
let y = select_num_or_zero(cs.namespace(|| "select y"), &a.y, condition)?;
let is_infinity = select_num_or_one(
cs.namespace(|| "select is_infinity"),
&a.is_infinity,
condition,
)?;
Ok(Self { x, y, is_infinity })
}
}
#[derive(Clone, Debug)]
/// `AllocatedPoint` but one that is guaranteed to be not infinity
pub struct AllocatedPointNonInfinity<G: Group> {
x: AllocatedNum<G::Base>,
y: AllocatedNum<G::Base>,
}
impl<G: Group> AllocatedPointNonInfinity<G> {
/// Creates a new `AllocatedPointNonInfinity` from the specified coordinates
pub const fn new(x: AllocatedNum<G::Base>, y: AllocatedNum<G::Base>) -> Self {
Self { x, y }
}
/// Allocates a new point on the curve using coordinates provided by `coords`.
pub fn alloc<CS: ConstraintSystem<G::Base>>(
mut cs: CS,
coords: Option<(G::Base, G::Base)>,
) -> Result<Self, SynthesisError> {
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
coords.map_or(Err(SynthesisError::AssignmentMissing), |c| Ok(c.0))
})?;
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
coords.map_or(Err(SynthesisError::AssignmentMissing), |c| Ok(c.1))
})?;
Ok(Self { x, y })
}
/// Turns an `AllocatedPoint` into an `AllocatedPointNonInfinity` (assumes it is not infinity)
pub fn from_allocated_point(p: &AllocatedPoint<G>) -> Self {
Self {
x: p.x.clone(),
y: p.y.clone(),
}
}
/// Returns an `AllocatedPoint` from an `AllocatedPointNonInfinity`
pub fn to_allocated_point(
&self,
is_infinity: &AllocatedNum<G::Base>,
) -> Result<AllocatedPoint<G>, SynthesisError> {
Ok(AllocatedPoint {
x: self.x.clone(),
y: self.y.clone(),
is_infinity: is_infinity.clone(),
})
}
/// Returns coordinates associated with the point.
pub const fn get_coordinates(&self) -> (&AllocatedNum<G::Base>, &AllocatedNum<G::Base>) {
(&self.x, &self.y)
}
/// Add two points assuming self != +/- other
pub fn add_incomplete<CS>(&self, mut cs: CS, other: &Self) -> Result<Self, SynthesisError>
where
CS: ConstraintSystem<G::Base>,
{
// allocate a free variable that an honest prover sets to lambda = (y2-y1)/(x2-x1)
let lambda = AllocatedNum::alloc(cs.namespace(|| "lambda"), || {
if *other.x.get_value().get()? == *self.x.get_value().get()? {
Ok(G::Base::ONE)
} else {
Ok(
(*other.y.get_value().get()? - *self.y.get_value().get()?)
* (*other.x.get_value().get()? - *self.x.get_value().get()?)
.invert()
.unwrap(),
)
}
})?;
cs.enforce(
|| "Check that lambda is computed correctly",
|lc| lc + lambda.get_variable(),
|lc| lc + other.x.get_variable() - self.x.get_variable(),
|lc| lc + other.y.get_variable() - self.y.get_variable(),
);
//************************************************************************/
// x = lambda * lambda - self.x - other.x;
//************************************************************************/
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
Ok(
*lambda.get_value().get()? * lambda.get_value().get()?
- *self.x.get_value().get()?
- *other.x.get_value().get()?,
)
})?;
cs.enforce(
|| "check that x is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + lambda.get_variable(),
|lc| lc + x.get_variable() + self.x.get_variable() + other.x.get_variable(),
);
//************************************************************************/
// y = lambda * (self.x - x) - self.y;
//************************************************************************/
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(
*lambda.get_value().get()? * (*self.x.get_value().get()? - *x.get_value().get()?)
- *self.y.get_value().get()?,
)
})?;
cs.enforce(
|| "Check that y is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + self.x.get_variable() - x.get_variable(),
|lc| lc + y.get_variable() + self.y.get_variable(),
);
Ok(Self { x, y })
}
/// doubles the point; since this is called with a point not at infinity, it is guaranteed to be not infinity
pub fn double_incomplete<CS: ConstraintSystem<G::Base>>(
&self,
mut cs: CS,
) -> Result<Self, SynthesisError> {
// lambda = (3 x^2 + a) / 2 * y
let x_sq = self.x.square(cs.namespace(|| "x_sq"))?;
let lambda = AllocatedNum::alloc(cs.namespace(|| "lambda"), || {
let n = G::Base::from(3) * x_sq.get_value().get()? + G::group_params().0;
let d = G::Base::from(2) * *self.y.get_value().get()?;
if d == G::Base::ZERO {
Ok(G::Base::ONE)
} else {
Ok(n * d.invert().unwrap())
}
})?;
cs.enforce(
|| "Check that lambda is computed correctly",
|lc| lc + lambda.get_variable(),
|lc| lc + (G::Base::from(2), self.y.get_variable()),
|lc| lc + (G::Base::from(3), x_sq.get_variable()) + (G::group_params().0, CS::one()),
);
let x = AllocatedNum::alloc(cs.namespace(|| "x"), || {
Ok(
*lambda.get_value().get()? * *lambda.get_value().get()?
- *self.x.get_value().get()?
- *self.x.get_value().get()?,
)
})?;
cs.enforce(
|| "check that x is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + lambda.get_variable(),
|lc| lc + x.get_variable() + (G::Base::from(2), self.x.get_variable()),
);
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(
*lambda.get_value().get()? * (*self.x.get_value().get()? - *x.get_value().get()?)
- *self.y.get_value().get()?,
)
})?;
cs.enforce(
|| "Check that y is correct",
|lc| lc + lambda.get_variable(),
|lc| lc + self.x.get_variable() - x.get_variable(),
|lc| lc + y.get_variable() + self.y.get_variable(),
);
Ok(Self { x, y })
}
/// If condition outputs a otherwise outputs b
pub fn conditionally_select<CS: ConstraintSystem<G::Base>>(
mut cs: CS,
a: &Self,
b: &Self,
condition: &Boolean,
) -> Result<Self, SynthesisError> {
let x = conditionally_select(cs.namespace(|| "select x"), &a.x, &b.x, condition)?;
let y = conditionally_select(cs.namespace(|| "select y"), &a.y, &b.y, condition)?;
Ok(Self { x, y })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
bellpepper::{
r1cs::{NovaShape, NovaWitness},
solver::SatisfyingAssignment,
test_shape_cs::TestShapeCS,
},
provider::{
bn256_grumpkin::{bn256, grumpkin},
secp_secq::{secp256k1, secq256k1},
Bn256Engine, GrumpkinEngine, PallasEngine, Secp256k1Engine, Secq256k1Engine, VestaEngine,
},
traits::{snark::default_ck_hint, Engine},
};
use expect_test::{expect, Expect};
use ff::{Field, PrimeFieldBits};
use pasta_curves::{arithmetic::CurveAffine, group::Curve, pallas, vesta};
use rand::rngs::OsRng;
#[derive(Debug, Clone)]
pub struct Point<G: Group> {
x: G::Base,
y: G::Base,
is_infinity: bool,
}
impl<G: Group> Point<G> {
pub fn new(x: G::Base, y: G::Base, is_infinity: bool) -> Self {
Self { x, y, is_infinity }
}
pub fn random_vartime() -> Self {
loop {
let x = G::Base::random(&mut OsRng);
let y = (x.square() * x + G::group_params().1).sqrt();
if y.is_some().unwrap_u8() == 1 {
return Self {
x,
y: y.unwrap(),
is_infinity: false,
};
}
}
}
/// Add any two points
pub fn add(&self, other: &Self) -> Self {
if self.x == other.x {
// If self == other then call double
if self.y == other.y {
self.double()
} else {
// if self.x == other.x and self.y != other.y then return infinity
Self {
x: G::Base::ZERO,
y: G::Base::ZERO,
is_infinity: true,
}
}
} else {
self.add_internal(other)
}
}
/// Add two different points
pub fn add_internal(&self, other: &Self) -> Self {
if self.is_infinity {
return other.clone();
}
if other.is_infinity {
return self.clone();
}
let lambda = (other.y - self.y) * (other.x - self.x).invert().unwrap();
let x = lambda * lambda - self.x - other.x;
let y = lambda * (self.x - x) - self.y;
Self {
x,
y,
is_infinity: false,
}
}
pub fn double(&self) -> Self {
if self.is_infinity {
return Self {
x: G::Base::ZERO,
y: G::Base::ZERO,
is_infinity: true,
};
}
let lambda = G::Base::from(3)
* self.x
* self.x
* ((G::Base::ONE + G::Base::ONE) * self.y).invert().unwrap();
let x = lambda * lambda - self.x - self.x;
let y = lambda * (self.x - x) - self.y;
Self {
x,
y,
is_infinity: false,
}
}
pub fn scalar_mul(&self, scalar: &G::Scalar) -> Self {
let mut res = Self {
x: G::Base::ZERO,
y: G::Base::ZERO,
is_infinity: true,
};
let bits = scalar.to_le_bits();
for i in (0..bits.len()).rev() {
res = res.double();
if bits[i] {
res = self.add(&res);
}
}
res
}
}
// Allocate a random point. Only used for testing
pub fn alloc_random_point<G: Group, CS: ConstraintSystem<G::Base>>(
mut cs: CS,
) -> Result<AllocatedPoint<G>, SynthesisError> {
// get a random point
let p = Point::<G>::random_vartime();
AllocatedPoint::alloc(cs.namespace(|| "alloc p"), Some((p.x, p.y, p.is_infinity)))
}
/// Make the point io
pub fn inputize_allocated_point<G: Group, CS: ConstraintSystem<G::Base>>(
p: &AllocatedPoint<G>,
mut cs: CS,
) {
let _ = p.x.inputize(cs.namespace(|| "Input point.x"));
let _ = p.y.inputize(cs.namespace(|| "Input point.y"));
let _ = p
.is_infinity
.inputize(cs.namespace(|| "Input point.is_infinity"));
}
#[test]
fn test_ecc_ops() {
test_ecc_ops_with::<pallas::Affine, <PallasEngine as Engine>::GE>();
test_ecc_ops_with::<vesta::Affine, <VestaEngine as Engine>::GE>();
test_ecc_ops_with::<bn256::Affine, <Bn256Engine as Engine>::GE>();
test_ecc_ops_with::<grumpkin::Affine, <GrumpkinEngine as Engine>::GE>();
test_ecc_ops_with::<secp256k1::Affine, <Secp256k1Engine as Engine>::GE>();
test_ecc_ops_with::<secq256k1::Affine, <Secq256k1Engine as Engine>::GE>();
}
fn test_ecc_ops_with<C, G>()
where
G: Group,
C: CurveAffine<Base = G::Base, ScalarExt = G::Scalar>,
{
// perform some curve arithmetic
let a = Point::<G>::random_vartime();
let b = Point::<G>::random_vartime();
let c = a.add(&b);
let d = a.double();
let s = G::Scalar::random(&mut OsRng);
let e = a.scalar_mul(&s);
// perform the same computation by translating to curve types
let a_curve = C::from_xy(
C::Base::from_repr(a.x.to_repr()).unwrap(),
C::Base::from_repr(a.y.to_repr()).unwrap(),
)
.unwrap();
let b_curve = C::from_xy(
C::Base::from_repr(b.x.to_repr()).unwrap(),
C::Base::from_repr(b.y.to_repr()).unwrap(),
)
.unwrap();
let c_curve = (a_curve + b_curve).to_affine();
let d_curve = (a_curve + a_curve).to_affine();
let e_curve = a_curve
.mul(C::Scalar::from_repr(s.to_repr()).unwrap())
.to_affine();
// transform c, d, and e into curve types
let c_curve_2 = C::from_xy(
C::Base::from_repr(c.x.to_repr()).unwrap(),
C::Base::from_repr(c.y.to_repr()).unwrap(),
)
.unwrap();
let d_curve_2 = C::from_xy(
C::Base::from_repr(d.x.to_repr()).unwrap(),
C::Base::from_repr(d.y.to_repr()).unwrap(),
)
.unwrap();
let e_curve_2 = C::from_xy(
C::Base::from_repr(e.x.to_repr()).unwrap(),
C::Base::from_repr(e.y.to_repr()).unwrap(),
)
.unwrap();
// check that we have the same outputs
assert_eq!(c_curve, c_curve_2);
assert_eq!(d_curve, d_curve_2);
assert_eq!(e_curve, e_curve_2);
}
fn synthesize_smul<G, CS>(mut cs: CS) -> (AllocatedPoint<G>, AllocatedPoint<G>, G::Scalar)
where
G: Group,
CS: ConstraintSystem<G::Base>,
{
let a = alloc_random_point(cs.namespace(|| "a")).unwrap();
inputize_allocated_point(&a, cs.namespace(|| "inputize a"));
let s = G::Scalar::random(&mut OsRng);
// Allocate bits for s
let bits: Vec<AllocatedBit> = s
.to_le_bits()
.into_iter()