-
Notifications
You must be signed in to change notification settings - Fork 46
/
lib.rs
1935 lines (1679 loc) · 57.4 KB
/
lib.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 crate provides an implementation of the **Jubjub** elliptic curve and its associated
//! field arithmetic. See [`README.md`](https://github.com/zkcrypto/jubjub/blob/master/README.md) for more details about Jubjub.
//!
//! # API
//!
//! * `AffinePoint` / `ExtendedPoint` which are implementations of Jubjub group arithmetic
//! * `AffineNielsPoint` / `ExtendedNielsPoint` which are pre-processed Jubjub points
//! * `Fq`, which is the base field of Jubjub
//! * `Fr`, which is the scalar field of Jubjub
//! * `batch_normalize` for converting many `ExtendedPoint`s into `AffinePoint`s efficiently.
//!
//! # Constant Time
//!
//! All operations are constant time unless explicitly noted; these functions will contain
//! "vartime" in their name and they will be documented as variable time.
//!
//! This crate uses the `subtle` crate to perform constant-time operations.
#![no_std]
// Catch documentation errors caused by code changes.
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(unsafe_code)]
// This lint is described at
// https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_arithmetic_impl
// In our library, some of the arithmetic will necessarily involve various binary
// operators, and so this lint is triggered unnecessarily.
#![allow(clippy::suspicious_arithmetic_impl)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(test)]
#[macro_use]
extern crate std;
use bitvec::{order::Lsb0, view::AsBits};
use core::borrow::Borrow;
use core::fmt;
use core::iter::Sum;
use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use ff::{BatchInverter, Field};
use group::{
cofactor::{CofactorCurve, CofactorCurveAffine, CofactorGroup},
prime::PrimeGroup,
Curve, Group, GroupEncoding,
};
use rand_core::RngCore;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
use group::WnafGroup;
#[macro_use]
mod util;
mod fr;
pub use bls12_381::Scalar as Fq;
pub use fr::Fr;
/// Represents an element of the base field $\mathbb{F}_q$ of the Jubjub elliptic curve
/// construction.
pub type Base = Fq;
/// Represents an element of the scalar field $\mathbb{F}_r$ of the Jubjub elliptic curve
/// construction.
pub type Scalar = Fr;
const FR_MODULUS_BYTES: [u8; 32] = [
183, 44, 247, 214, 94, 14, 151, 208, 130, 16, 200, 204, 147, 32, 104, 166, 0, 59, 52, 1, 1, 59,
103, 6, 169, 175, 51, 101, 234, 180, 125, 14,
];
/// This represents a Jubjub point in the affine `(u, v)`
/// coordinates.
#[derive(Clone, Copy, Debug, Eq)]
pub struct AffinePoint {
u: Fq,
v: Fq,
}
impl fmt::Display for AffinePoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Neg for AffinePoint {
type Output = AffinePoint;
/// This computes the negation of a point `P = (u, v)`
/// as `-P = (-u, v)`.
#[inline]
fn neg(self) -> AffinePoint {
AffinePoint {
u: -self.u,
v: self.v,
}
}
}
impl ConstantTimeEq for AffinePoint {
fn ct_eq(&self, other: &Self) -> Choice {
self.u.ct_eq(&other.u) & self.v.ct_eq(&other.v)
}
}
impl PartialEq for AffinePoint {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl ConditionallySelectable for AffinePoint {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
AffinePoint {
u: Fq::conditional_select(&a.u, &b.u, choice),
v: Fq::conditional_select(&a.v, &b.v, choice),
}
}
}
/// This represents an extended point `(U, V, Z, T1, T2)`
/// with `Z` nonzero, corresponding to the affine point
/// `(U/Z, V/Z)`. We always have `T1 * T2 = UV/Z`.
///
/// You can do the following things with a point in this
/// form:
///
/// * Convert it into a point in the affine form.
/// * Add it to an `ExtendedPoint`, `AffineNielsPoint` or `ExtendedNielsPoint`.
/// * Double it using `double()`.
/// * Compare it with another extended point using `PartialEq` or `ct_eq()`.
#[derive(Clone, Copy, Debug, Eq)]
pub struct ExtendedPoint {
u: Fq,
v: Fq,
z: Fq,
t1: Fq,
t2: Fq,
}
impl fmt::Display for ExtendedPoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl ConstantTimeEq for ExtendedPoint {
fn ct_eq(&self, other: &Self) -> Choice {
// (u/z, v/z) = (u'/z', v'/z') is implied by
// (uz'z = u'z'z) and
// (vz'z = v'z'z)
// as z and z' are always nonzero.
(self.u * other.z).ct_eq(&(other.u * self.z))
& (self.v * other.z).ct_eq(&(other.v * self.z))
}
}
impl ConditionallySelectable for ExtendedPoint {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
ExtendedPoint {
u: Fq::conditional_select(&a.u, &b.u, choice),
v: Fq::conditional_select(&a.v, &b.v, choice),
z: Fq::conditional_select(&a.z, &b.z, choice),
t1: Fq::conditional_select(&a.t1, &b.t1, choice),
t2: Fq::conditional_select(&a.t2, &b.t2, choice),
}
}
}
impl PartialEq for ExtendedPoint {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl<T> Sum<T> for ExtendedPoint
where
T: Borrow<ExtendedPoint>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>,
{
iter.fold(Self::identity(), |acc, item| acc + item.borrow())
}
}
impl Neg for ExtendedPoint {
type Output = ExtendedPoint;
/// Computes the negation of a point `P = (U, V, Z, T)`
/// as `-P = (-U, V, Z, -T1, T2)`. The choice of `T1`
/// is made without loss of generality.
#[inline]
fn neg(self) -> ExtendedPoint {
ExtendedPoint {
u: -self.u,
v: self.v,
z: self.z,
t1: -self.t1,
t2: self.t2,
}
}
}
impl From<AffinePoint> for ExtendedPoint {
/// Constructs an extended point (with `Z = 1`) from
/// an affine point using the map `(u, v) => (u, v, 1, u, v)`.
fn from(affine: AffinePoint) -> ExtendedPoint {
ExtendedPoint {
u: affine.u,
v: affine.v,
z: Fq::one(),
t1: affine.u,
t2: affine.v,
}
}
}
impl<'a> From<&'a ExtendedPoint> for AffinePoint {
/// Constructs an affine point from an extended point
/// using the map `(U, V, Z, T1, T2) => (U/Z, V/Z)`
/// as Z is always nonzero. **This requires a field inversion
/// and so it is recommended to perform these in a batch
/// using [`batch_normalize`](crate::batch_normalize) instead.**
fn from(extended: &'a ExtendedPoint) -> AffinePoint {
// Z coordinate is always nonzero, so this is
// its inverse.
let zinv = extended.z.invert().unwrap();
AffinePoint {
u: extended.u * zinv,
v: extended.v * zinv,
}
}
}
impl From<ExtendedPoint> for AffinePoint {
fn from(extended: ExtendedPoint) -> AffinePoint {
AffinePoint::from(&extended)
}
}
/// This is a pre-processed version of an affine point `(u, v)`
/// in the form `(v + u, v - u, u * v * 2d)`. This can be added to an
/// [`ExtendedPoint`](crate::ExtendedPoint).
#[derive(Clone, Copy, Debug)]
pub struct AffineNielsPoint {
v_plus_u: Fq,
v_minus_u: Fq,
t2d: Fq,
}
impl AffineNielsPoint {
/// Constructs this point from the neutral element `(0, 1)`.
pub const fn identity() -> Self {
AffineNielsPoint {
v_plus_u: Fq::one(),
v_minus_u: Fq::one(),
t2d: Fq::zero(),
}
}
#[inline]
fn multiply(&self, by: &[u8; 32]) -> ExtendedPoint {
let zero = AffineNielsPoint::identity();
let mut acc = ExtendedPoint::identity();
// This is a simple double-and-add implementation of point
// multiplication, moving from most significant to least
// significant bit of the scalar.
//
// We skip the leading four bits because they're always
// unset for Fr.
for bit in by
.as_bits::<Lsb0>()
.iter()
.rev()
.skip(4)
.map(|bit| Choice::from(if *bit { 1 } else { 0 }))
{
acc = acc.double();
acc += AffineNielsPoint::conditional_select(&zero, &self, bit);
}
acc
}
/// Multiplies this point by the specific little-endian bit pattern in the
/// given byte array, ignoring the highest four bits.
pub fn multiply_bits(&self, by: &[u8; 32]) -> ExtendedPoint {
self.multiply(by)
}
}
impl<'a, 'b> Mul<&'b Fr> for &'a AffineNielsPoint {
type Output = ExtendedPoint;
fn mul(self, other: &'b Fr) -> ExtendedPoint {
self.multiply(&other.to_bytes())
}
}
impl_binops_multiplicative_mixed!(AffineNielsPoint, Fr, ExtendedPoint);
impl ConditionallySelectable for AffineNielsPoint {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
AffineNielsPoint {
v_plus_u: Fq::conditional_select(&a.v_plus_u, &b.v_plus_u, choice),
v_minus_u: Fq::conditional_select(&a.v_minus_u, &b.v_minus_u, choice),
t2d: Fq::conditional_select(&a.t2d, &b.t2d, choice),
}
}
}
/// This is a pre-processed version of an extended point `(U, V, Z, T1, T2)`
/// in the form `(V + U, V - U, Z, T1 * T2 * 2d)`.
#[derive(Clone, Copy, Debug)]
pub struct ExtendedNielsPoint {
v_plus_u: Fq,
v_minus_u: Fq,
z: Fq,
t2d: Fq,
}
impl ConditionallySelectable for ExtendedNielsPoint {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
ExtendedNielsPoint {
v_plus_u: Fq::conditional_select(&a.v_plus_u, &b.v_plus_u, choice),
v_minus_u: Fq::conditional_select(&a.v_minus_u, &b.v_minus_u, choice),
z: Fq::conditional_select(&a.z, &b.z, choice),
t2d: Fq::conditional_select(&a.t2d, &b.t2d, choice),
}
}
}
impl ExtendedNielsPoint {
/// Constructs this point from the neutral element `(0, 1)`.
pub const fn identity() -> Self {
ExtendedNielsPoint {
v_plus_u: Fq::one(),
v_minus_u: Fq::one(),
z: Fq::one(),
t2d: Fq::zero(),
}
}
#[inline]
fn multiply(&self, by: &[u8; 32]) -> ExtendedPoint {
let zero = ExtendedNielsPoint::identity();
let mut acc = ExtendedPoint::identity();
// This is a simple double-and-add implementation of point
// multiplication, moving from most significant to least
// significant bit of the scalar.
//
// We skip the leading four bits because they're always
// unset for Fr.
for bit in by
.iter()
.rev()
.flat_map(|byte| (0..8).rev().map(move |i| Choice::from((byte >> i) & 1u8)))
.skip(4)
{
acc = acc.double();
acc += ExtendedNielsPoint::conditional_select(&zero, &self, bit);
}
acc
}
/// Multiplies this point by the specific little-endian bit pattern in the
/// given byte array, ignoring the highest four bits.
pub fn multiply_bits(&self, by: &[u8; 32]) -> ExtendedPoint {
self.multiply(by)
}
}
impl<'a, 'b> Mul<&'b Fr> for &'a ExtendedNielsPoint {
type Output = ExtendedPoint;
fn mul(self, other: &'b Fr) -> ExtendedPoint {
self.multiply(&other.to_bytes())
}
}
impl_binops_multiplicative_mixed!(ExtendedNielsPoint, Fr, ExtendedPoint);
// `d = -(10240/10241)`
const EDWARDS_D: Fq = Fq::from_raw([
0x0106_5fd6_d634_3eb1,
0x292d_7f6d_3757_9d26,
0xf5fd_9207_e6bd_7fd4,
0x2a93_18e7_4bfa_2b48,
]);
// `2*d`
const EDWARDS_D2: Fq = Fq::from_raw([
0x020c_bfad_ac68_7d62,
0x525a_feda_6eaf_3a4c,
0xebfb_240f_cd7a_ffa8,
0x5526_31ce_97f4_5691,
]);
impl AffinePoint {
/// Constructs the neutral element `(0, 1)`.
pub const fn identity() -> Self {
AffinePoint {
u: Fq::zero(),
v: Fq::one(),
}
}
/// Determines if this point is the identity.
pub fn is_identity(&self) -> Choice {
ExtendedPoint::from(*self).is_identity()
}
/// Multiplies this point by the cofactor, producing an
/// `ExtendedPoint`
pub fn mul_by_cofactor(&self) -> ExtendedPoint {
ExtendedPoint::from(*self).mul_by_cofactor()
}
/// Determines if this point is of small order.
pub fn is_small_order(&self) -> Choice {
ExtendedPoint::from(*self).is_small_order()
}
/// Determines if this point is torsion free and so is
/// in the prime order subgroup.
pub fn is_torsion_free(&self) -> Choice {
ExtendedPoint::from(*self).is_torsion_free()
}
/// Determines if this point is prime order, or in other words that
/// the smallest scalar multiplied by this point that produces the
/// identity is `r`. This is equivalent to checking that the point
/// is both torsion free and not the identity.
pub fn is_prime_order(&self) -> Choice {
let extended = ExtendedPoint::from(*self);
extended.is_torsion_free() & (!extended.is_identity())
}
/// Converts this element into its byte representation.
pub fn to_bytes(&self) -> [u8; 32] {
let mut tmp = self.v.to_bytes();
let u = self.u.to_bytes();
// Encode the sign of the u-coordinate in the most
// significant bit.
tmp[31] |= u[0] << 7;
tmp
}
/// Attempts to interpret a byte representation of an
/// affine point, failing if the element is not on
/// the curve or non-canonical.
pub fn from_bytes(b: [u8; 32]) -> CtOption<Self> {
Self::from_bytes_inner(b, 1.into())
}
/// Attempts to interpret a byte representation of an affine point, failing if the
/// element is not on the curve.
///
/// Most non-canonical encodings will also cause a failure. However, this API
/// preserves (for use in consensus-critical protocols) a bug in the parsing code that
/// caused two non-canonical encodings to be **silently** accepted:
///
/// - (0, 1), which is the identity;
/// - (0, -1), which is a point of order two.
///
/// Each of these has a single non-canonical encoding in which the value of the sign
/// bit is 1.
///
/// See [ZIP 216](https://zips.z.cash/zip-0216) for a more detailed description of the
/// bug, as well as its fix.
pub fn from_bytes_pre_zip216_compatibility(b: [u8; 32]) -> CtOption<Self> {
Self::from_bytes_inner(b, 0.into())
}
fn from_bytes_inner(mut b: [u8; 32], zip_216_enabled: Choice) -> CtOption<Self> {
// Grab the sign bit from the representation
let sign = b[31] >> 7;
// Mask away the sign bit
b[31] &= 0b0111_1111;
// Interpret what remains as the v-coordinate
Fq::from_bytes(&b).and_then(|v| {
// -u^2 + v^2 = 1 + d.u^2.v^2
// -u^2 = 1 + d.u^2.v^2 - v^2 (rearrange)
// -u^2 - d.u^2.v^2 = 1 - v^2 (rearrange)
// u^2 + d.u^2.v^2 = v^2 - 1 (flip signs)
// u^2 (1 + d.v^2) = v^2 - 1 (factor)
// u^2 = (v^2 - 1) / (1 + d.v^2) (isolate u^2)
// We know that (1 + d.v^2) is nonzero for all v:
// (1 + d.v^2) = 0
// d.v^2 = -1
// v^2 = -(1 / d) No solutions, as -(1 / d) is not a square
let v2 = v.square();
((v2 - Fq::one()) * ((Fq::one() + EDWARDS_D * v2).invert().unwrap_or(Fq::zero())))
.sqrt()
.and_then(|u| {
// Fix the sign of `u` if necessary
let flip_sign = Choice::from((u.to_bytes()[0] ^ sign) & 1);
let u_negated = -u;
let final_u = Fq::conditional_select(&u, &u_negated, flip_sign);
// If u == 0, flip_sign == sign_bit. We therefore want to reject the
// encoding as non-canonical if all of the following occur:
// - ZIP 216 is enabled
// - u == 0
// - flip_sign == true
let u_is_zero = u.ct_eq(&Fq::zero());
CtOption::new(
AffinePoint { u: final_u, v },
!(zip_216_enabled & u_is_zero & flip_sign),
)
})
})
}
/// Attempts to interpret a batch of byte representations of affine points.
///
/// Returns None for each element if it is not on the curve, or is non-canonical
/// according to ZIP 216.
#[cfg(feature = "alloc")]
pub fn batch_from_bytes(items: impl Iterator<Item = [u8; 32]>) -> Vec<CtOption<Self>> {
use ff::BatchInvert;
#[derive(Clone, Copy, Default)]
struct Item {
sign: u8,
v: Fq,
numerator: Fq,
denominator: Fq,
}
impl ConditionallySelectable for Item {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
Item {
sign: u8::conditional_select(&a.sign, &b.sign, choice),
v: Fq::conditional_select(&a.v, &b.v, choice),
numerator: Fq::conditional_select(&a.numerator, &b.numerator, choice),
denominator: Fq::conditional_select(&a.denominator, &b.denominator, choice),
}
}
}
let items: Vec<_> = items
.map(|mut b| {
// Grab the sign bit from the representation
let sign = b[31] >> 7;
// Mask away the sign bit
b[31] &= 0b0111_1111;
// Interpret what remains as the v-coordinate
Fq::from_bytes(&b).map(|v| {
// -u^2 + v^2 = 1 + d.u^2.v^2
// -u^2 = 1 + d.u^2.v^2 - v^2 (rearrange)
// -u^2 - d.u^2.v^2 = 1 - v^2 (rearrange)
// u^2 + d.u^2.v^2 = v^2 - 1 (flip signs)
// u^2 (1 + d.v^2) = v^2 - 1 (factor)
// u^2 = (v^2 - 1) / (1 + d.v^2) (isolate u^2)
// We know that (1 + d.v^2) is nonzero for all v:
// (1 + d.v^2) = 0
// d.v^2 = -1
// v^2 = -(1 / d) No solutions, as -(1 / d) is not a square
let v2 = v.square();
Item {
v,
sign,
numerator: (v2 - Fq::one()),
denominator: Fq::one() + EDWARDS_D * v2,
}
})
})
.collect();
let mut denominators: Vec<_> = items
.iter()
.map(|item| item.map(|item| item.denominator).unwrap_or(Fq::zero()))
.collect();
denominators.iter_mut().batch_invert();
items
.into_iter()
.zip(denominators.into_iter())
.map(|(item, inv_denominator)| {
item.and_then(
|Item {
v, sign, numerator, ..
}| {
(numerator * inv_denominator).sqrt().and_then(|u| {
// Fix the sign of `u` if necessary
let flip_sign = Choice::from((u.to_bytes()[0] ^ sign) & 1);
let u_negated = -u;
let final_u = Fq::conditional_select(&u, &u_negated, flip_sign);
// If u == 0, flip_sign == sign_bit. We therefore want to reject the
// encoding as non-canonical if all of the following occur:
// - u == 0
// - flip_sign == true
let u_is_zero = u.ct_eq(&Fq::zero());
CtOption::new(AffinePoint { u: final_u, v }, !(u_is_zero & flip_sign))
})
},
)
})
.collect()
}
/// Returns the `u`-coordinate of this point.
pub fn get_u(&self) -> Fq {
self.u
}
/// Returns the `v`-coordinate of this point.
pub fn get_v(&self) -> Fq {
self.v
}
/// Returns an `ExtendedPoint` for use in arithmetic operations.
pub const fn to_extended(&self) -> ExtendedPoint {
ExtendedPoint {
u: self.u,
v: self.v,
z: Fq::one(),
t1: self.u,
t2: self.v,
}
}
/// Performs a pre-processing step that produces an `AffineNielsPoint`
/// for use in multiple additions.
pub const fn to_niels(&self) -> AffineNielsPoint {
AffineNielsPoint {
v_plus_u: Fq::add(&self.v, &self.u),
v_minus_u: Fq::sub(&self.v, &self.u),
t2d: Fq::mul(&Fq::mul(&self.u, &self.v), &EDWARDS_D2),
}
}
/// Constructs an AffinePoint given `u` and `v` without checking
/// that the point is on the curve.
pub const fn from_raw_unchecked(u: Fq, v: Fq) -> AffinePoint {
AffinePoint { u, v }
}
/// This is only for debugging purposes and not
/// exposed in the public API. Checks that this
/// point is on the curve.
#[cfg(test)]
fn is_on_curve_vartime(&self) -> bool {
let u2 = self.u.square();
let v2 = self.v.square();
v2 - u2 == Fq::one() + EDWARDS_D * u2 * v2
}
}
impl ExtendedPoint {
/// Constructs an extended point from the neutral element `(0, 1)`.
pub const fn identity() -> Self {
ExtendedPoint {
u: Fq::zero(),
v: Fq::one(),
z: Fq::one(),
t1: Fq::zero(),
t2: Fq::zero(),
}
}
/// Determines if this point is the identity.
pub fn is_identity(&self) -> Choice {
// If this point is the identity, then
// u = 0 * z = 0
// and v = 1 * z = z
self.u.ct_eq(&Fq::zero()) & self.v.ct_eq(&self.z)
}
/// Determines if this point is of small order.
pub fn is_small_order(&self) -> Choice {
// We only need to perform two doublings, since the 2-torsion
// points are (0, 1) and (0, -1), and so we only need to check
// that the u-coordinate of the result is zero to see if the
// point is small order.
self.double().double().u.ct_eq(&Fq::zero())
}
/// Determines if this point is torsion free and so is contained
/// in the prime order subgroup.
pub fn is_torsion_free(&self) -> Choice {
self.multiply(&FR_MODULUS_BYTES).is_identity()
}
/// Determines if this point is prime order, or in other words that
/// the smallest scalar multiplied by this point that produces the
/// identity is `r`. This is equivalent to checking that the point
/// is both torsion free and not the identity.
pub fn is_prime_order(&self) -> Choice {
self.is_torsion_free() & (!self.is_identity())
}
/// Multiplies this element by the cofactor `8`.
pub fn mul_by_cofactor(&self) -> ExtendedPoint {
self.double().double().double()
}
/// Performs a pre-processing step that produces an `ExtendedNielsPoint`
/// for use in multiple additions.
pub fn to_niels(&self) -> ExtendedNielsPoint {
ExtendedNielsPoint {
v_plus_u: self.v + self.u,
v_minus_u: self.v - self.u,
z: self.z,
t2d: self.t1 * self.t2 * EDWARDS_D2,
}
}
/// Computes the doubling of a point more efficiently than a point can
/// be added to itself.
pub fn double(&self) -> ExtendedPoint {
// Doubling is more efficient (three multiplications, four squarings)
// when we work within the projective coordinate space (U:Z, V:Z). We
// rely on the most efficient formula, "dbl-2008-bbjlp", as described
// in Section 6 of "Twisted Edwards Curves" by Bernstein et al.
//
// See <https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp>
// for more information.
//
// We differ from the literature in that we use (u, v) rather than
// (x, y) coordinates. We also have the constant `a = -1` implied. Let
// us rewrite the procedure of doubling (u, v, z) to produce (U, V, Z)
// as follows:
//
// B = (u + v)^2
// C = u^2
// D = v^2
// F = D - C
// H = 2 * z^2
// J = F - H
// U = (B - C - D) * J
// V = F * (- C - D)
// Z = F * J
//
// If we compute K = D + C, we can rewrite this:
//
// B = (u + v)^2
// C = u^2
// D = v^2
// F = D - C
// K = D + C
// H = 2 * z^2
// J = F - H
// U = (B - K) * J
// V = F * (-K)
// Z = F * J
//
// In order to avoid the unnecessary negation of K,
// we will negate J, transforming the result into
// an equivalent point with a negated z-coordinate.
//
// B = (u + v)^2
// C = u^2
// D = v^2
// F = D - C
// K = D + C
// H = 2 * z^2
// J = H - F
// U = (B - K) * J
// V = F * K
// Z = F * J
//
// Let us rename some variables to simplify:
//
// UV2 = (u + v)^2
// UU = u^2
// VV = v^2
// VVmUU = VV - UU
// VVpUU = VV + UU
// ZZ2 = 2 * z^2
// J = ZZ2 - VVmUU
// U = (UV2 - VVpUU) * J
// V = VVmUU * VVpUU
// Z = VVmUU * J
//
// We wish to obtain two factors of T = UV/Z.
//
// UV/Z = (UV2 - VVpUU) * (ZZ2 - VVmUU) * VVmUU * VVpUU / VVmUU / (ZZ2 - VVmUU)
// = (UV2 - VVpUU) * VVmUU * VVpUU / VVmUU
// = (UV2 - VVpUU) * VVpUU
//
// and so we have that T1 = (UV2 - VVpUU) and T2 = VVpUU.
let uu = self.u.square();
let vv = self.v.square();
let zz2 = self.z.square().double();
let uv2 = (self.u + self.v).square();
let vv_plus_uu = vv + uu;
let vv_minus_uu = vv - uu;
// The remaining arithmetic is exactly the process of converting
// from a completed point to an extended point.
CompletedPoint {
u: uv2 - vv_plus_uu,
v: vv_plus_uu,
z: vv_minus_uu,
t: zz2 - vv_minus_uu,
}
.into_extended()
}
#[inline]
fn multiply(self, by: &[u8; 32]) -> Self {
self.to_niels().multiply(by)
}
/// Converts a batch of projective elements into affine elements.
///
/// This function will panic if `p.len() != q.len()`.
///
/// This costs 5 multiplications per element, and a field inversion.
fn batch_normalize(p: &[Self], q: &mut [AffinePoint]) {
assert_eq!(p.len(), q.len());
for (p, q) in p.iter().zip(q.iter_mut()) {
// We use the `u` field of `AffinePoint` to store the z-coordinate being
// inverted, and the `v` field for scratch space.
q.u = p.z;
}
BatchInverter::invert_with_internal_scratch(q, |q| &mut q.u, |q| &mut q.v);
for (p, q) in p.iter().zip(q.iter_mut()).rev() {
let tmp = q.u;
// Set the coordinates to the correct value
q.u = p.u * &tmp; // Multiply by 1/z
q.v = p.v * &tmp; // Multiply by 1/z
}
}
/// This is only for debugging purposes and not
/// exposed in the public API. Checks that this
/// point is on the curve.
#[cfg(test)]
fn is_on_curve_vartime(&self) -> bool {
let affine = AffinePoint::from(*self);
self.z != Fq::zero()
&& affine.is_on_curve_vartime()
&& (affine.u * affine.v * self.z == self.t1 * self.t2)
}
}
impl<'a, 'b> Mul<&'b Fr> for &'a ExtendedPoint {
type Output = ExtendedPoint;
fn mul(self, other: &'b Fr) -> ExtendedPoint {
self.multiply(&other.to_bytes())
}
}
impl_binops_multiplicative!(ExtendedPoint, Fr);
impl<'a, 'b> Add<&'b ExtendedNielsPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint;
#[allow(clippy::suspicious_arithmetic_impl)]
fn add(self, other: &'b ExtendedNielsPoint) -> ExtendedPoint {
// We perform addition in the extended coordinates. Here we use
// a formula presented by Hisil, Wong, Carter and Dawson in
// "Twisted Edward Curves Revisited" which only requires 8M.
//
// A = (V1 - U1) * (V2 - U2)
// B = (V1 + U1) * (V2 + U2)
// C = 2d * T1 * T2
// D = 2 * Z1 * Z2
// E = B - A
// F = D - C
// G = D + C
// H = B + A
// U3 = E * F
// Y3 = G * H
// Z3 = F * G
// T3 = E * H
let a = (self.v - self.u) * other.v_minus_u;
let b = (self.v + self.u) * other.v_plus_u;
let c = self.t1 * self.t2 * other.t2d;
let d = (self.z * other.z).double();
// The remaining arithmetic is exactly the process of converting
// from a completed point to an extended point.
CompletedPoint {
u: b - a,
v: b + a,
z: d + c,
t: d - c,
}
.into_extended()
}
}
impl<'a, 'b> Sub<&'b ExtendedNielsPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint;
#[allow(clippy::suspicious_arithmetic_impl)]
fn sub(self, other: &'b ExtendedNielsPoint) -> ExtendedPoint {
let a = (self.v - self.u) * other.v_plus_u;
let b = (self.v + self.u) * other.v_minus_u;
let c = self.t1 * self.t2 * other.t2d;
let d = (self.z * other.z).double();
CompletedPoint {
u: b - a,
v: b + a,
z: d - c,
t: d + c,
}
.into_extended()
}
}
impl_binops_additive!(ExtendedPoint, ExtendedNielsPoint);
impl<'a, 'b> Add<&'b AffineNielsPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint;
#[allow(clippy::suspicious_arithmetic_impl)]
fn add(self, other: &'b AffineNielsPoint) -> ExtendedPoint {
// This is identical to the addition formula for `ExtendedNielsPoint`,
// except we can assume that `other.z` is one, so that we perform
// 7 multiplications.
let a = (self.v - self.u) * other.v_minus_u;
let b = (self.v + self.u) * other.v_plus_u;
let c = self.t1 * self.t2 * other.t2d;
let d = self.z.double();
// The remaining arithmetic is exactly the process of converting
// from a completed point to an extended point.
CompletedPoint {
u: b - a,
v: b + a,
z: d + c,
t: d - c,
}
.into_extended()
}
}
impl<'a, 'b> Sub<&'b AffineNielsPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint;
#[allow(clippy::suspicious_arithmetic_impl)]
fn sub(self, other: &'b AffineNielsPoint) -> ExtendedPoint {
let a = (self.v - self.u) * other.v_plus_u;
let b = (self.v + self.u) * other.v_minus_u;
let c = self.t1 * self.t2 * other.t2d;
let d = self.z.double();
CompletedPoint {
u: b - a,
v: b + a,
z: d - c,
t: d + c,
}
.into_extended()
}
}
impl_binops_additive!(ExtendedPoint, AffineNielsPoint);
impl<'a, 'b> Add<&'b ExtendedPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint;
#[inline]
fn add(self, other: &'b ExtendedPoint) -> ExtendedPoint {
self + other.to_niels()
}
}