This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
field.rs
1607 lines (1389 loc) · 56.1 KB
/
field.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
//! Field arithmetic modulo `2^252 + 27742317777372353535851937790883648493`
//! which makes use of 64-bit limbs with 128-bit products.
//! In the 64-bit backend implementation, the `FieldElement` is
//! represented in radix `2^52`.
//!
//! The basic modular operations have been taken from the
//! [Curve25519-dalek repository](https://github.com/dalek-cryptography/curve25519-dalek) and refactored to work
//! for the Doppio finite field.
use core::fmt::Debug;
use core::convert::From;
use std::default::Default;
use std::cmp::{PartialOrd, Ordering, Ord};
use core::ops::{Index, IndexMut};
use core::ops::{Add, Sub, Mul, Div, Neg};
use subtle::{Choice, ConstantTimeEq, ConditionallySelectable, ConditionallyNegatable};
use num::Integer;
use rand::{thread_rng, Rng};
use crate::backend::u64::constants as constants;
use crate::scalar::Ristretto255Scalar;
use crate::traits::Identity;
use crate::traits::ops::*;
/// A `FieldElement` represents an element of the field
/// which has order of `2^252 + 27742317777372353535851937790883648493`
///
/// In the 64-bit backend implementation, the `FieldElement` is
/// represented in radix `2^52`
#[derive(Copy, Clone, Eq)]
pub struct FieldElement(pub [u64;5] );
impl Debug for FieldElement {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "FieldElement({:?})", &self.0[..])
}
}
impl Index<usize> for FieldElement {
type Output = u64;
fn index(&self, _index: usize) -> &u64 {
&(self.0[_index])
}
}
impl IndexMut<usize> for FieldElement {
fn index_mut(&mut self, _index: usize) -> &mut u64 {
&mut (self.0[_index])
}
}
impl PartialOrd for FieldElement {
fn partial_cmp(&self, other: &FieldElement) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for FieldElement {
fn cmp(&self, other: &Self) -> Ordering {
for i in (0..5).rev() {
if self[i] > other[i] {
return Ordering::Greater;
}else if self[i] < other[i] {
return Ordering::Less;
}
}
Ordering::Equal
}
}
impl Identity for FieldElement {
/// Returns the Identity element over the finite field
/// modulo `2^252 + 27742317777372353535851937790883648493`.
///
/// It is defined as 1 on `FieldElement` format, and is therefore written as:
/// `[1, 0, 0, 0, 0]`.
fn identity() -> FieldElement {
FieldElement([1, 0, 0, 0 ,0])
}
}
impl Default for FieldElement {
///Returns the default value for a FieldElement = Zero.
fn default() -> FieldElement {
FieldElement::zero()
}
}
//-------------- From Implementations -----------------//
impl<'a> From<&'a u8> for FieldElement {
/// Performs the conversion.
fn from(_inp: &'a u8) -> FieldElement {
let mut res = FieldElement::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u16> for FieldElement {
/// Performs the conversion.
fn from(_inp: &'a u16) -> FieldElement {
let mut res = FieldElement::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u32> for FieldElement {
/// Performs the conversion.
fn from(_inp: &'a u32) -> FieldElement {
let mut res = FieldElement::zero();
res[0] = *_inp as u64;
res
}
}
impl<'a> From<&'a u64> for FieldElement {
/// Performs the conversion.
fn from(_inp: &'a u64) -> FieldElement {
let mut res = FieldElement::zero();
let mask = (1u64 << 52) - 1;
res[0] = _inp & mask;
res[1] = _inp >> 52;
res
}
}
impl<'a> From<&'a u128> for FieldElement {
/// Performs the conversion.
fn from(_inp: &'a u128) -> FieldElement {
let mut res = FieldElement::zero();
let mask = (1u128 << 52) - 1;
// Since 128 / 52 < 4 , we only need to be attentive to
// the first three limbs.
res[0] = (_inp & mask) as u64;
res[1] = ((_inp >> 52) & mask) as u64;
res[2] = (_inp >> 104) as u64;
res
}
}
impl<'a> From<&'a Ristretto255Scalar> for FieldElement {
/// Given a Ristretto255Scalar on canonical bytes representation
/// get it's FieldElement equivalent value as 5 limbs and
/// radix-52.
fn from(origin: &'a Ristretto255Scalar) -> FieldElement {
let origin_bytes = origin.to_bytes();
FieldElement::from_bytes(&origin_bytes)
}
}
impl Into<Ristretto255Scalar> for FieldElement {
/// Given a FieldElement reference get it's
/// Ristretto255Scalar Equivalent on it's
/// canonical bytes representation.
fn into(self) -> Ristretto255Scalar {
Ristretto255Scalar::from_canonical_bytes(self.to_bytes()).unwrap()
}
}
impl<'a> Neg for &'a FieldElement {
type Output = FieldElement;
/// Computes `-self (mod l)`.
/// Compute the negated value that corresponds to the
/// complement of the two, of the input FieldElement.
#[inline]
fn neg(self) -> FieldElement {
&FieldElement::zero() - self
}
}
impl Neg for FieldElement {
type Output = FieldElement;
/// Computes `-self (mod l)`.
///
/// Compute the negated value that correspond's to the
/// two's complement of the input FieldElement.
#[inline]
fn neg(self) -> FieldElement {
-&self
}
}
impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
/// Compute `a + b (mod l)`.
#[inline]
fn add(self, b: &'b FieldElement) -> FieldElement {
let mut sum = FieldElement::zero();
let mask = (1u64 << 52) - 1;
// a + b
let mut carry: u64 = 0;
for i in 0..5 {
carry = self.0[i] + b[i] + (carry >> 52);
sum[i] = carry & mask;
}
// subtract l if the sum is >= l
&sum - &constants::FIELD_L
}
}
impl Add<FieldElement> for FieldElement {
type Output = FieldElement;
/// Compute `a + b (mod l)`.
#[inline]
fn add(self, b: FieldElement) -> FieldElement {
&self + &b
}
}
impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
/// Compute `a - b (mod l)`
#[inline]
fn sub(self, b: &'b FieldElement) -> FieldElement {
let mut sub = 0u64;
let mut difference: FieldElement = FieldElement::zero();
let mask = (1u64 << 52) - 1;
// Save wrapping_sub result. Store as a reminder on the next limb.
for i in 0..5 {
sub = self.0[i].wrapping_sub(b[i] + (sub >> 63));
difference[i] = sub & mask;
}
// Conditionaly add l, if difference is negative.
// Be aware that here `sub` tells us the most significant bit of the last limb
// so then we know whether or not the value is greater than `l`.
let underflow_mask = ((sub >> 63) ^ 1).wrapping_sub(1);
let mut carry = 0u64;
for i in 0..5 {
carry = (carry >> 52) + difference[i] + (constants::FIELD_L[i] & underflow_mask);
difference[i] = carry & mask;
}
difference
}
}
impl Sub<FieldElement> for FieldElement {
type Output = FieldElement;
/// Compute `a + b (mod l)`.
#[inline]
fn sub(self, b: FieldElement) -> FieldElement {
&self - &b
}
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
/// This Mul implementation returns a double precision result.
///
/// The result of the standard mul is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `FieldElement` format: [u64; 5].
#[inline]
fn mul(self, _rhs: &'b FieldElement) -> FieldElement {
let prod = FieldElement::montgomery_reduce(&FieldElement::mul_internal(self, _rhs));
FieldElement::montgomery_reduce(&FieldElement::mul_internal(&prod, &constants::RR_FIELD))
}
}
impl Mul<FieldElement> for FieldElement {
type Output = FieldElement;
/// This Mul implementation returns a double precision result.
///
/// The result of the standard mul is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `FieldElement` format: [u64; 5].
#[inline]
fn mul(self, _rhs: FieldElement) -> FieldElement {
&self * &_rhs
}
}
impl<'a,'b> Div<&'a FieldElement> for &'b FieldElement {
type Output = FieldElement;
/// Performs the op: `x / y (mod l)`.
///
/// Since on modular fields we don't divide, the equivanelnt op
/// is: `x * (y^-1 (mod l))`, which is equivalent to the naive
/// division but for Finite Fields.
#[inline]
fn div(self, _rhs: &'a FieldElement) -> FieldElement {
assert!(_rhs != &FieldElement::zero(), "Cannot divide by zero.");
self * &_rhs.inverse()
}
}
impl Div<FieldElement> for FieldElement {
type Output = FieldElement;
/// Performs the op: `x / y (mod l)`.
///
/// Since on modular fields we don't divide, the equivanelnt op
/// is: `x * (y^-1 (mod l))`, which is equivalent to the naive
/// division but for Finite Fields.
#[inline]
fn div(self, _rhs: FieldElement) -> FieldElement {
&self * &_rhs.inverse()
}
}
impl<'a> Square for &'a FieldElement {
type Output = FieldElement;
/// Compute `a^2 (mod l)`.
///
/// This `Square` implementation returns a double precision result.
/// The result of the standard square is stored on a [u128; 9].
///
/// Then, we apply the Montgomery Reduction function to perform
/// the modulo and the reduction to the `FieldElement` format: [u64; 5].
#[inline]
fn square(self) -> FieldElement {
let aa = FieldElement::montgomery_reduce(&FieldElement::square_internal(self));
FieldElement::montgomery_reduce(&FieldElement::mul_internal(&aa, &constants::RR_FIELD))
}
}
impl<'a> Half for &'a FieldElement {
type Output = FieldElement;
/// Give the half of the FieldElement value (mod l).
///
/// This function SHOULD ONLY be used with even
/// `FieldElements` otherways, can produce erroneus
/// results.
#[inline]
fn half(self) -> FieldElement {
assert!(self.is_even(), "The FieldElement has to be even.");
let mut res = self.clone();
let mut remainder = 0u64;
for i in (0..5).rev() {
res[i] = res[i] + remainder;
match(res[i] == 1, res[i].is_even()){
(true, _) => {
remainder = 4503599627370496u64;
}
(_, false) => {
res[i] = res[i] - 1u64;
remainder = 4503599627370496u64;
}
(_, true) => {
remainder = 0;
}
}
res[i] = res[i] >> 1;
};
res
}
}
impl<'a, 'b> Pow<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
/// Performs the op: `a^b (mod l)`.
///
/// Exponentiation by squaring classical algorithm
/// implementation for `FieldElement`.
///
/// Schneier, Bruce (1996). Applied Cryptography: Protocols,
/// Algorithms, and Source Code in C, Second Edition (2nd ed.).
fn pow(self, exp: &'b FieldElement) -> FieldElement {
let mut base = self.clone();
let mut res = FieldElement::one();
let mut expon = exp.clone();
while expon > FieldElement::zero() {
if expon.is_even() {
expon = expon.half();
base = &base * &base;
} else {
expon = expon - FieldElement::one();
res = res * base;
expon = expon.half();
base = &base * &base;
}
}
res
}
}
impl<'a> ModSqrt for &'a FieldElement {
type Output = Option<FieldElement>;
/// Performs the op: `sqrt(a) (mod l)`.
///
/// Tonelli-Shanks prime modular square root
/// algorithm implementation for `FieldElement`.
///
/// Conditionally selects and returns the positive or the
/// negative result of the `mod_sqrt` by analyzing the
/// `Choice` sent as input:
///
/// For `Choice(0)` -> Negative result.
/// For `Choice(1)` -> Positive result.
///
/// Daniel Shanks. Five Number Theoretic Algorithms.
/// Proceedings of the Second Manitoba Conference on
/// Numerical Mathematics. Pp. 51–70. 1973.
///
/// This algorithm was translated from the python impl
/// found in:
/// https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root
fn mod_sqrt(self, sign: Choice) -> Option<FieldElement> {
// If the input is `0` the sqrt is directly 0.
if self.ct_eq(&FieldElement::zero()).unwrap_u8() == 1u8
{return Some(FieldElement::zero());}
// Check if exists a solution insine the finite
// field generated by `FIELD_L`.
if self.legendre_symbol().unwrap_u8() == 0u8 {return None;}
// Factor p-1 on the form q * 2^s (with Q odd).
let mut q = FieldElement::minus_one();
let mut s = FieldElement::zero();
while q.is_even() {
s = s + FieldElement::one();
q = q.half();
}
// Select a z which is a quadratic non resudue modulo p.
// We pre-computed it so we know that 6 isn't QR.
let z = FieldElement::from(&6u8);
let mut c = z.pow(&q);
// Search for a solution.
let mut x = self.pow(&(q + FieldElement::one()).inner_half());
let mut t = self.pow(&q);
let mut m = s.clone();
let one = FieldElement::one();
let two = FieldElement::from(&2u8);
while t != FieldElement::one() {
// Find the lowest i such that t^(2^i) = 1.
let mut i = FieldElement::zero();
let mut e = FieldElement::from(&2u8);
let b;
while i < m {
i = i + one;
if t.pow(&e).ct_eq(&one).unwrap_u8() == 1u8 {break;}
e = e * two;
}
// Update values for next iter
b = c.pow(&two.pow(&(m - i - one)));
x = x * b;
t = t * b.square();
c = b.square();
m = i;
};
Some(FieldElement::conditional_select(&x, &(constants::FIELD_L - x), sign))
}
}
impl InvSqrt for &FieldElement {
type Output = (Choice, FieldElement);
/// This is a convenience wrapper function over the `SqrtRatioI` trait
/// implementation when `self = 1`:
/// Computes `sqrt(1/self)`.
///
/// This function always returns the non-negative result of the sqrt.
///
/// # Returns:
///
/// - `(Choice(1), +sqrt(1/self)) ` if `self` is a nonzero square;
/// - `(Choice(0), zero) ` if `self` is zero;
/// - `(Choice(0), +sqrt(i/self)) ` if `self` is a nonzero nonsquare;
fn inv_sqrt(self) -> (Choice, FieldElement) {
FieldElement::one().sqrt_ratio_i(self)
}
}
impl SqrtRatioI<&FieldElement> for FieldElement {
type Output = (Choice, FieldElement);
/// The first part of the return value signals whether u/v was square,
/// and the second part contains a square root.
/// Specifically, it returns:
///
///- (true, +sqrt(u/v)) if v is nonzero and u/v is square;
///- (true, zero) if u is zero;
///- (false, zero) if v is zero and u is nonzero;
///- (false, +sqrt(i*u/v)) if u/v is nonsquare (so iu/v is square).
fn sqrt_ratio_i(&self, v: &FieldElement) -> (Choice, FieldElement) {
let SQRT_MINUS_ONE: FieldElement = FieldElement([3075585030474777, 2451921961843096, 1194333869305507, 2218299809671669, 7376823328646]);
let zero = &FieldElement::zero();
match(self == zero, v == zero) {
(true, _) => return (Choice::from(1u8), FieldElement::zero()),
(false, true) => return (Choice::from(0u8), FieldElement::zero()),
(false, false) => (),
};
// (false, false) case. We check "QRness".
match (self / v).legendre_symbol().unwrap_u8() == 1u8 {
// (u/v) is not QR, so we multiply by `i` and
// return `(false, +sqrt(i*u/v))`.
false => {
let mut res = (&SQRT_MINUS_ONE * &(self / v)).mod_sqrt(Choice::from(1u8)).unwrap();
res.conditional_negate(!res.is_positive());
(Choice::from(0u8), res)
},
// (u/v) is QR, so we don't need to do anything and
// we return `(true, +sqrt(u/v))`.
true => {
let mut res = (self / v).mod_sqrt(Choice::from(1u8)).unwrap();
res.conditional_negate(!res.is_positive());
(Choice::from(1u8), res)
},
}
}
}
/// u64 * u64 = u128 inline func multiply helper
#[inline]
fn m(x: u64, y: u64) -> u128 {
(x as u128) * (y as u128)
}
impl FieldElement {
/// Construct zero.
pub fn zero() -> FieldElement {
FieldElement([ 0, 0, 0, 0, 0 ])
}
/// Construct one.
pub fn one() -> FieldElement {
FieldElement([ 1, 0, 0, 0, 0 ])
}
/// Construct -1 (mod l).
pub fn minus_one() -> FieldElement {
FieldElement([671914833335276, 3916664325105025, 1367801, 0, 17592186044416])
}
/// Evaluate if a `FieldElement` is even or not.
pub fn is_even(self) -> bool {
// Compare the last bit of the first limb to check evenness.
// 0b0 -> true
// 0b1 -> false
self.0[0] & 0b01 == 0u64
}
/// Performs the operation `((a + constants::FIELD_L) >> 2) % l)`.
/// This function SHOULD only be used on the Kalinski's modular
/// inverse algorithm, since it's the only way we have to add `l`
/// to a `FieldElement` without obtaining the same number.
///
/// On Kalinski's `PhaseII`, this function allows us to trick the
/// addition and be able to divide odd numbers by `2`.
#[inline]
pub(self) fn plus_p_and_half(&self) -> FieldElement {
let mut res = self.clone();
for i in 0..5 {
res[i] += constants::FIELD_L[i];
};
res.inner_half()
}
/// Checks if a ´FieldElement` is considered negative following
/// the Decaf paper criteria.
///
/// The criteria says: Non-negative field elements.
/// Let p > 2 be prime. Define a residue x ∈ F =Z/pZ to be
/// “non-negative” if the least absolute residue for x is in
/// `[0,(p−1)/2]`, and “negative” otherwise.
///
/// # Returns:
/// - `Choice(1)` if pos.
/// - `Choice(0)` if neg.
pub fn is_positive(&self) -> Choice {
if self >= &FieldElement::zero() && self <= &constants::POS_RANGE {
return Choice::from(1)
}
Choice::from(0)
}
/// Load a `FieldElement` from the low 253b bits of a 256-bit
/// input. So Little Endian representation in bytes of a FieldElement.
// @TODO: Macro for Inline load8 function as it has variadic arguments.
#[warn(dead_code)]
pub fn from_bytes(bytes: &[u8;32]) -> FieldElement {
let load8 = |input: &[u8]| -> u64 {
(input[0] as u64)
| ((input[1] as u64) << 8)
| ((input[2] as u64) << 16)
| ((input[3] as u64) << 24)
| ((input[4] as u64) << 32)
| ((input[5] as u64) << 40)
| ((input[6] as u64) << 48)
| ((input[7] as u64) << 56)
};
let low_52_bit_mask = (1u64 << 52) - 1;
FieldElement(
// load bits [ 0, 64), no shift
[ load8(&bytes[ 0..]) & low_52_bit_mask
// load bits [ 48,112), shift to [ 52,112)
, (load8(&bytes[ 6..]) >> 4) & low_52_bit_mask
// load bits [ 96,160), shift to [104,160)
, (load8(&bytes[12..]) >> 8) & low_52_bit_mask
// load bits [152,216), shift to [156,216)
, (load8(&bytes[19..]) >> 4) & low_52_bit_mask
// load bits [192,256), shift to [208,256)
, (load8(&bytes[24..]) >> 16) & low_52_bit_mask
])
}
/// Serialize this `FieldElement` to a 32-byte array. The
/// encoding is canonical.
pub fn to_bytes(self) -> [u8; 32] {
let mut res = [0u8; 32];
res[0] = (self.0[0] >> 0) as u8;
res[1] = (self.0[0] >> 8) as u8;
res[2] = (self.0[0] >> 16) as u8;
res[3] = (self.0[0] >> 24) as u8;
res[4] = (self.0[0] >> 32) as u8;
res[5] = (self.0[0] >> 40) as u8;
// Satisfy radix 52 with the next limb value shifted according the needs
res[6] = ((self.0[0] >> 48) | (self.0[1] << 4)) as u8;
res[7] = (self.0[1] >> 4) as u8;
res[8] = (self.0[1] >> 12) as u8;
res[9] = (self.0[ 1] >> 20) as u8;
res[10] = (self.0[ 1] >> 28) as u8;
res[11] = (self.0[ 1] >> 36) as u8;
res[12] = (self.0[ 1] >> 44) as u8;
res[13] = (self.0[ 2] >> 0) as u8;
res[14] = (self.0[ 2] >> 8) as u8;
res[15] = (self.0[ 2] >> 16) as u8;
res[16] = (self.0[ 2] >> 24) as u8;
res[17] = (self.0[ 2] >> 32) as u8;
res[18] = (self.0[ 2] >> 40) as u8;
res[19] = ((self.0[ 2] >> 48) | (self.0[ 3] << 4)) as u8;
res[20] = (self.0[ 3] >> 4) as u8;
res[21] = (self.0[ 3] >> 12) as u8;
res[22] = (self.0[ 3] >> 20) as u8;
res[23] = (self.0[ 3] >> 28) as u8;
res[24] = (self.0[ 3] >> 36) as u8;
res[25] = (self.0[ 3] >> 44) as u8;
res[26] = (self.0[ 4] >> 0) as u8;
res[27] = (self.0[ 4] >> 8) as u8;
res[28] = (self.0[ 4] >> 16) as u8;
res[29] = (self.0[ 4] >> 24) as u8;
res[30] = (self.0[ 4] >> 32) as u8;
res[31] = (self.0[ 4] >> 40) as u8;
// High bit should be zero.
//debug_assert!((res[31] & 0b1000_0000u8) == 0u8);
res
}
/// Given a `k`: u64, compute `2^k` giving the resulting result
/// as a `FieldElement`.
///
/// See that the input must be between the range => 0..253.
///
/// NOTE: This function implements an `assert!` statement that
/// checks the correctness of the exponent provided as param.
#[inline]
pub fn two_pow_k(exp: &u64) -> FieldElement {
// Check that exp has to be less than 260.
// Note that a FieldElement can be as much
// `2^252 + 27742317777372353535851937790883648493` so we pick
// 253 knowing that 252 will be less than `FIELD_L`.
assert!(exp < &253u64, "Exponent can't be greater than 260");
let mut res = FieldElement::zero();
match exp {
0...51 => {
res[0] = 1u64 << exp;
},
52...103 => {
res[1] = 1u64 << (exp - 52);
},
104...155 => {
res[2] = 1u64 << (exp - 104);
},
156...207 => {
res[3] = 1u64 << (exp - 156);
},
_ => {
res[4] = 1u64 << (exp - 208);
}
}
res
}
/// Given a FieldElement, this function evaluates if it is a quadratic
/// residue (mod l).
///
/// See: [https://en.wikipedia.org/wiki/Legendre_symbol](https://en.wikipedia.org/wiki/Legendre_symbol).
///
/// Returns:
///
/// `-1` -> Non-quadratic residue (mod l) == Choice(0).
///
/// `1` -> Quadratic residue (mod l) == Choice(1).
///
/// `0` -> `Input (mod l) == 0`. Not implemented since you can't pass
/// an input which is multiple of `FIELD_L`.
#[inline]
pub fn legendre_symbol(&self) -> Choice {
let res = self.pow(&FieldElement::minus_one().half());
res.ct_eq(&FieldElement::minus_one()) ^ Choice::from(1u8)
}
#[inline]
#[doc(hidden)]
/// This half implementation has no restriction for odd values
/// and is used in some parts of algorithms which impl require
/// to divide by 2 odd numbers at some parts.
pub(self) fn inner_half(self) -> FieldElement {
let mut res = self.clone();
let mut remainder = 0u64;
for i in (0..5).rev() {
res[i] = res[i] + remainder;
match(res[i] == 1, res[i].is_even()){
(true, _) => {
remainder = 4503599627370496u64;
}
(_, false) => {
res[i] = res[i] - 1u64;
remainder = 4503599627370496u64;
}
(_, true) => {
remainder = 0;
}
}
res[i] = res[i] >> 1;
};
res
}
/// Given a `k`: u64, compute `2^k` giving the resulting result
/// as a `FieldElement`.
/// Note that the input must be between the range => 0..260.
///
/// NOTE: Usually, we will say 253, but since on some operations as
/// inversion we need to exponenciate to greater values, we set the
/// max on the Montgomery modulo so `260`.
#[doc(hidden)]
pub(self) fn inner_two_pow_k(exp: &u64) -> FieldElement {
// Check that exp has to be less than 260.
// Note that a FieldElement can be as much
// `2^252 + 27742317777372353535851937790883648493` so we pick
// 253 knowing that 252 will be less than `FIELD_L`.
debug_assert!(exp < &260u64, "Exponent can't be greater than 260");
let mut res = FieldElement::zero();
match exp {
0...51 => {
res[0] = 1u64 << exp;
},
52...103 => {
res[1] = 1u64 << (exp - 52);
},
104...155 => {
res[2] = 1u64 << (exp - 104);
},
156...207 => {
res[3] = 1u64 << (exp - 156);
},
_ => {
res[4] = 1u64 << (exp - 208);
}
}
res
}
/// Compute `a * b` with the function multiplying helper
#[inline]
pub(self) fn mul_internal(a: &FieldElement, b: &FieldElement) -> [u128; 9] {
let mut res = [0u128; 9];
// Note that this is just the normal way of performing a product.
// We need to store the results on u128 as otherwise we'll end
// up having overflowings.
res[0] = m(a[0],b[0]);
res[1] = m(a[0],b[1]) + m(a[1],b[0]);
res[2] = m(a[0],b[2]) + m(a[1],b[1]) + m(a[2],b[0]);
res[3] = m(a[0],b[3]) + m(a[1],b[2]) + m(a[2],b[1]) + m(a[3],b[0]);
res[4] = m(a[0],b[4]) + m(a[1],b[3]) + m(a[2],b[2]) + m(a[3],b[1]) + m(a[4],b[0]);
res[5] = m(a[1],b[4]) + m(a[2],b[3]) + m(a[3],b[2]) + m(a[4],b[1]);
res[6] = m(a[2],b[4]) + m(a[3],b[3]) + m(a[4],b[2]);
res[7] = m(a[3],b[4]) + m(a[4],b[3]);
res[8] = m(a[4],b[4]);
res
}
/// Compute `a^2`.
///
/// This operation is multo-precision. So it gives back
/// an `[u128; 9]` with the result of the squaring.
#[inline]
pub(self) fn square_internal(a: &FieldElement) -> [u128; 9] {
let a_sqrt = [
a[0]*2,
a[1]*2,
a[2]*2,
a[3]*2,
];
[
m(a[0],a[0]),
m(a_sqrt[0],a[1]),
m(a_sqrt[0],a[2]) + m(a[1],a[1]),
m(a_sqrt[0],a[3]) + m(a_sqrt[1],a[2]),
m(a_sqrt[0],a[4]) + m(a_sqrt[1],a[3]) + m(a[2],a[2]),
m(a_sqrt[1],a[4]) + m(a_sqrt[2],a[3]),
m(a_sqrt[2],a[4]) + m(a[3],a[3]),
m(a_sqrt[3],a[4]),
m(a[4],a[4])
]
}
/// Compute `limbs/R` (mod l), where R is the Montgomery modulus 2^260
#[inline]
pub(self) fn montgomery_reduce(limbs: &[u128; 9]) -> FieldElement {
#[inline]
fn adjustment_fact(sum: u128) -> (u128, u64) {
let p = (sum as u64).wrapping_mul(constants::LFACTOR_FIELD) & ((1u64 << 52) - 1);
((sum + m(p,constants::FIELD_L[0])) >> 52, p)
}
#[inline]
fn montg_red_res(sum: u128) -> (u128, u64) {
let w = (sum as u64) & ((1u64 << 52) - 1);
(sum >> 52, w)
}
// FIELD_L[3] = 0 so we can skip these products.
let l = &constants::FIELD_L;
// the first half computes the Montgomery adjustment factor n, and begins adding n*l to make limbs divisible by R
let (carry, n0) = adjustment_fact( limbs[0]);
let (carry, n1) = adjustment_fact(carry + limbs[1] + m(n0,l[1]));
let (carry, n2) = adjustment_fact(carry + limbs[2] + m(n0,l[2]) + m(n1,l[1]));
let (carry, n3) = adjustment_fact(carry + limbs[3] + m(n1,l[2]) + m(n2,l[1]));
let (carry, n4) = adjustment_fact(carry + limbs[4] + m(n0,l[4]) + m(n2,l[2]) + m(n3,l[1]));
// limbs is divisible by R now, so we can divide by R by simply storing the upper half as the result
let (carry, r0) = montg_red_res(carry + limbs[5] + m(n1,l[4]) + m(n3,l[2]) + m(n4,l[1]));
let (carry, r1) = montg_red_res(carry + limbs[6] + m(n2,l[4]) + m(n4,l[2]));
let (carry, r2) = montg_red_res(carry + limbs[7] + m(n3,l[4]) );
let (carry, r3) = montg_red_res(carry + limbs[8] + m(n4,l[4]));
let r4 = carry as u64;
// result may be >= r, so attempt to subtract l
&FieldElement([r0,r1,r2,r3,r4]) - l
}
//--------------------InverseModMontgomery tools-----------------------//
/// Compute `(a * b) / R` (mod l), where R is the Montgomery modulus 2^253
#[inline]
pub(self) fn montgomery_mul(a: &FieldElement, b: &FieldElement) -> FieldElement {
FieldElement::montgomery_reduce(&FieldElement::mul_internal(a, b))
}
/// Puts a FieldElement into Montgomery form, i.e. computes `a*R (mod l)`
#[inline]
#[allow(dead_code)]
pub(self) fn to_montgomery(&self) -> FieldElement {
FieldElement::montgomery_mul(self, &constants::RR_FIELD)
}
/// Takes a FieldElement out of Montgomery form, i.e. computes `a/R (mod l)`
#[inline]
pub(self) fn from_montgomery(&self) -> FieldElement {
let mut limbs = [0u128; 9];
for i in 0..5 {
limbs[i] = self[i] as u128;
}
FieldElement::montgomery_reduce(&limbs)
}
/// Compute `a^-1 (mod l)` using the the Kalinski implementation
/// of the Montgomery Modular Inverse algorithm.
/// B. S. Kaliski Jr. - The Montgomery inverse and its applica-tions.
/// IEEE Transactions on Computers, 44(8):1064–1065, August-1995
#[inline]
#[allow(dead_code)]
pub(self) fn kalinski_inverse(&self) -> FieldElement {
/// This Phase I indeed is the Binary GCD algorithm, a version of Steins algorithm
/// which tries to remove the expensive division operation away from the Classical
/// Euclidean GDC algorithm by replacing it with Bit-shifting, subtraction and comparison.
///
/// Output = `a^(-1) * 2^k (mod l)` where `k = log2(FIELD_L) == 253`.
///
/// Stein, J.: Computational problems associated with Racah algebra.J. Comput. Phys.1, 397–405 (1967)
///
///
/// Mentioned on: SPECIAL ISSUE ON MONTGOMERY ARITHMETIC.
/// Montgomery inversion - Erkay Sava ̧s & Çetin Kaya Koç
/// J Cryptogr Eng (2018) 8:201–210
/// https://doi.org/10.1007/s13389-017-0161-x
#[inline]
fn phase1(a: &FieldElement) -> (FieldElement, u64) {
// Declare L = 2^252 + 27742317777372353535851937790883648493
let p = FieldElement([671914833335277, 3916664325105025, 1367801, 0, 17592186044416]);
let mut u = p.clone();
let mut v = a.clone();
let mut r = FieldElement::zero();
let mut s = FieldElement::one();
let two = FieldElement([2, 0, 0, 0, 0]);
let mut k = 0u64;
while v > FieldElement::zero() {
match(u.is_even(), v.is_even(), u > v, v >= u) {
// u is even
(true, _, _, _) => {
u = u.inner_half();
s = &s * &two;
},
// u isn't even but v is even
(false, true, _, _) => {
v = v.inner_half();
r = &r * &two;
},
// u and v aren't even and u > v
(false, false, true, _) => {
u = &u - &v;
u = u.inner_half();
r = &r + &s;
s = &s * &two;
},
// u and v aren't even and v > u
(false, false, false, true) => {
v = &v - &u;
v = v.inner_half();
s = &r + &s;
r = &r * &two;
},
(false, false, false, false) => panic!("Unexpected error has ocurred."),
}
k += 1;
}
if r > p {
r = &r - &p;
}
(&p - &r, k)
}
/// Phase II performs some adjustments to obtain
/// the Montgomery inverse.
///
/// Output: `a^(-1) * 2^n (mod l)` where `n = 253 = log2(p) = log2(FIELD_L)`
#[inline]
fn phase2(r: &FieldElement, k: &u64) -> FieldElement {
let mut rr = r.clone();
let _p = &constants::FIELD_L;
for _i in 0..(k-253) {
match rr.is_even() {
true => {
rr = rr.inner_half();
},
false => {
rr = rr.plus_p_and_half();
}
}
}
rr
}
let (mut r, z) = phase1(&self.clone());
r = phase2(&r, &z);
// Since the output of the Phase II is multiplied by `2^n`
// We can multiply it by the two power needed to achive the
// Montgomery modulus value and then convert it back to the
// normal FieldElement domain.