-
Notifications
You must be signed in to change notification settings - Fork 11
/
num.go
1935 lines (1760 loc) · 57 KB
/
num.go
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
package saferith
import (
"fmt"
"math/big"
"math/bits"
"strings"
)
// General utilities
// add calculates a + b + carry, returning the sum, and carry
//
// This is a convenient wrapper around bits.Add, and should be optimized
// by the compiler to produce a single ADC instruction.
func add(a, b, carry Word) (sum Word, newCarry Word) {
s, c := bits.Add(uint(a), uint(b), uint(carry))
return Word(s), Word(c)
}
// Constant Time Utilities
// Choice represents a constant-time boolean.
//
// The value of Choice is always either 1 or 0.
//
// We use a separate type instead of bool, in order to be able to make decisions without leaking
// which decision was made.
//
// You can easily convert a Choice into a bool with the operation c == 1.
//
// In general, logical operations on bool become bitwise operations on choice:
// a && b => a & b
// a || b => a | b
// a != b => a ^ b
// !a => 1 ^ a
type Choice Word
// ctEq compares x and y for equality, returning 1 if equal, and 0 otherwise
//
// This doesn't leak any information about either of them
func ctEq(x, y Word) Choice {
// If x == y, then x ^ y should be all zero bits.
q := uint(x ^ y)
// For any q != 0, either the MSB of q, or the MSB of -q is 1.
// We can thus or those together, and check the top bit. When q is zero,
// that means that x and y are equal, so we negate that top bit.
return 1 ^ Choice((q|-q)>>(_W-1))
}
// ctGt checks x > y, returning 1 or 0
//
// This doesn't leak any information about either of them
func ctGt(x, y Word) Choice {
_, b := bits.Sub(uint(y), uint(x), 0)
return Choice(b)
}
// ctIfElse selects x if v = 1, and y otherwise
//
// This doesn't leak the value of any of its inputs
func ctIfElse(v Choice, x, y Word) Word {
// mask should be all 1s if v is 1, otherwise all 0s
mask := -Word(v)
return y ^ (mask & (y ^ x))
}
// ctCondCopy copies y into x, if v == 1, otherwise does nothing
//
// Both slices must have the same length.
//
// LEAK: the length of the slices
//
// Otherwise, which branch was taken isn't leaked
func ctCondCopy(v Choice, x, y []Word) {
if len(x) != len(y) {
panic("ctCondCopy: mismatched arguments")
}
for i := 0; i < len(x); i++ {
x[i] = ctIfElse(v, y[i], x[i])
}
}
// ctCondSwap swaps the contents of a and b, when v == 1, otherwise does nothing
//
// Both slices must have the same length.
//
// LEAK: the length of the slices
//
// Whether or not a swap happened isn't leaked
func ctCondSwap(v Choice, a, b []Word) {
for i := 0; i < len(a) && i < len(b); i++ {
ai := a[i]
a[i] = ctIfElse(v, b[i], ai)
b[i] = ctIfElse(v, ai, b[i])
}
}
// CondAssign sets z <- yes ? x : z.
//
// This function doesn't leak any information about whether the assignment happened.
//
// The announced size of the result will be the largest size between z and x.
func (z *Nat) CondAssign(yes Choice, x *Nat) *Nat {
maxBits := z.maxAnnounced(x)
xLimbs := x.resizedLimbs(maxBits)
z.limbs = z.resizedLimbs(maxBits)
ctCondCopy(yes, z.limbs, xLimbs)
// If the value we're potentially assigning has a different reduction,
// then there's nothing we can conclude about the resulting reduction.
if z.reduced != x.reduced {
z.reduced = nil
}
z.announced = maxBits
return z
}
// "Missing" Functions
// These are routines that could in theory be implemented in assembly,
// but aren't already present in Go's big number routines
// div calculates the quotient and remainder of hi:lo / d
//
// Unlike bits.Div, this doesn't leak anything about the inputs
func div(hi, lo, d Word) (Word, Word) {
var quo Word
hi = ctIfElse(ctEq(hi, d), 0, hi)
for i := _W - 1; i > 0; i-- {
j := _W - i
w := (hi << j) | (lo >> i)
sel := ctEq(w, d) | ctGt(w, d) | Choice(hi>>i)
hi2 := (w - d) >> j
lo2 := lo - (d << i)
hi = ctIfElse(sel, hi2, hi)
lo = ctIfElse(sel, lo2, lo)
quo |= Word(sel)
quo <<= 1
}
sel := ctEq(lo, d) | ctGt(lo, d) | Choice(hi)
quo |= Word(sel)
rem := ctIfElse(sel, lo-d, lo)
return quo, rem
}
// mulSubVVW calculates z -= y * x
//
// This also results in a carry.
func mulSubVVW(z, x []Word, y Word) (c Word) {
for i := 0; i < len(z) && i < len(x); i++ {
hi, lo := mulAddWWW_g(x[i], y, c)
sub, cc := bits.Sub(uint(z[i]), uint(lo), 0)
c, z[i] = Word(cc), Word(sub)
c += hi
}
return
}
// Nat represents an arbitrary sized natural number.
//
// Different methods on Nats will talk about a "capacity". The capacity represents
// the announced size of some number. Operations may vary in time *only* relative
// to this capacity, and not to the actual value of the number.
//
// The capacity of a number is usually inherited through whatever method was used to
// create the number in the first place.
type Nat struct {
// The exact number of bits this number claims to have.
//
// This can differ from the actual number of bits needed to represent this number.
announced int
// If this is set, then the value of this Nat is in the range 0..reduced - 1.
//
// This value should get set based only on statically knowable things, like what
// functions have been called. This means that we will have plenty of false
// negatives, where a value is small enough, but we don't know statically
// that this is the case.
//
// Invariant: If reduced is set, then announced should match the announced size of
// this modulus.
reduced *Modulus
// The limbs representing this number, in little endian order.
//
// Invariant: The bits past announced will not be set. This includes when announced
// isn't a multiple of the limb size.
//
// Invariant: two Nats are not allowed to share the same slice.
// This allows us to use pointer comparison to check that Nats don't alias eachother
limbs []Word
}
// checkInvariants does some internal sanity checks.
//
// This is useful for tests.
func (z *Nat) checkInvariants() bool {
if z.reduced != nil && z.announced != z.reduced.nat.announced {
return false
}
if len(z.limbs) != limbCount(z.announced) {
return false
}
if len(z.limbs) > 0 {
lastLimb := z.limbs[len(z.limbs)-1]
if lastLimb != lastLimb&limbMask(z.announced) {
return false
}
}
return true
}
// maxAnnounced returns the larger announced length of z and y
func (z *Nat) maxAnnounced(y *Nat) int {
maxBits := z.announced
if y.announced > maxBits {
maxBits = y.announced
}
return maxBits
}
// ensureLimbCapacity makes sure that a Nat has capacity for a certain number of limbs
//
// This will modify the slice contained inside the natural, but won't change the size of
// the slice, so it doesn't affect the value of the natural.
//
// LEAK: Probably the current number of limbs, and size
// OK: both of these should be public
func (z *Nat) ensureLimbCapacity(size int) {
if cap(z.limbs) < size {
newLimbs := make([]Word, len(z.limbs), size)
copy(newLimbs, z.limbs)
z.limbs = newLimbs
}
}
// resizedLimbs returns a new slice of limbs accomodating a number of bits.
//
// This will clear out the end of the slice as necessary.
//
// LEAK: the current number of limbs, and bits
// OK: both are public
func (z *Nat) resizedLimbs(bits int) []Word {
size := limbCount(bits)
z.ensureLimbCapacity(size)
res := z.limbs[:size]
// Make sure that the expansion (if any) is cleared
for i := len(z.limbs); i < size; i++ {
res[i] = 0
}
maskEnd(res, bits)
return res
}
// maskEnd applies the correct bit mask to some limbs
func maskEnd(limbs []Word, bits int) {
if len(limbs) <= 0 {
return
}
limbs[len(limbs)-1] &= limbMask(bits)
}
// unaliasedLimbs returns a set of limbs for z, such that they do not alias those of x
//
// This will create a copy of the limbs, if necessary.
//
// LEAK: the size of z, whether or not z and x are the same Nat
func (z *Nat) unaliasedLimbs(x *Nat) []Word {
res := z.limbs
if z == x {
res = make([]Word, len(z.limbs))
copy(res, z.limbs)
}
return res
}
// trueSize calculates the actual size necessary for representing these limbs
//
// This is the size with leading zeros removed. This leaks the number
// of such zeros, but nothing else.
func trueSize(limbs []Word) int {
// Instead of checking == 0 directly, which may leak the value, we instead
// compare with zero in constant time, and check if that succeeded in a leaky way.
var size int
for size = len(limbs); size > 0 && ctEq(limbs[size-1], 0) == 1; size-- {
}
return size
}
// AnnouncedLen returns the number of bits this number is publicly known to have
func (z *Nat) AnnouncedLen() int {
return z.announced
}
// TrueLen calculates the exact number of bits needed to represent z
//
// This function violates the standard contract around Nats and announced length.
// For most purposes, `AnnouncedLen` should be used instead.
//
// That being said, this function does try to limit its leakage, and should
// only leak the number of leading zero bits in the number.
func (z *Nat) TrueLen() int {
limbSize := trueSize(z.limbs)
size := limbSize * _W
if limbSize > 0 {
size -= leadingZeros(z.limbs[limbSize-1])
}
return size
}
// FillBytes writes out the big endian bytes of a natural number.
//
// This will always write out the full capacity of the number, without
// any kind trimming.
func (z *Nat) FillBytes(buf []byte) []byte {
for i := 0; i < len(buf); i++ {
buf[i] = 0
}
i := len(buf)
// LEAK: Number of limbs
// OK: The number of limbs is public
// LEAK: The addresses touched in the out array
// OK: Every member of out is touched
Outer:
for _, x := range z.limbs {
y := x
for j := 0; j < _S; j++ {
i--
if i < 0 {
break Outer
}
buf[i] = byte(y)
y >>= 8
}
}
return buf
}
// SetBytes interprets a number in big-endian format, stores it in z, and returns z.
//
// The exact length of the buffer must be public information! This length also dictates
// the capacity of the number returned, and thus the resulting timings for operations
// involving that number.
func (z *Nat) SetBytes(buf []byte) *Nat {
z.reduced = nil
z.announced = 8 * len(buf)
z.limbs = z.resizedLimbs(z.announced)
bufI := len(buf) - 1
for i := 0; i < len(z.limbs) && bufI >= 0; i++ {
z.limbs[i] = 0
for shift := 0; shift < _W && bufI >= 0; shift += 8 {
z.limbs[i] |= Word(buf[bufI]) << shift
bufI--
}
}
return z
}
// Bytes creates a slice containing the contents of this Nat, in big endian
//
// This will always fill the output byte slice based on the announced length of this Nat.
func (z *Nat) Bytes() []byte {
length := (z.announced + 7) / 8
out := make([]byte, length)
return z.FillBytes(out)
}
// MarshalBinary implements encoding.BinaryMarshaler.
// Returns the same value as Bytes().
func (i *Nat) MarshalBinary() ([]byte, error) {
return i.Bytes(), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler.
// Wraps SetBytes
func (i *Nat) UnmarshalBinary(data []byte) error {
i.SetBytes(data)
return nil
}
// convert a 4 bit value into an ASCII value in constant time
func nibbletoASCII(nibble byte) byte {
w := Word(nibble)
value := ctIfElse(ctGt(w, 9), w-0xA+Word('A'), w+Word('0'))
return byte(value)
}
// convert an ASCII value into a 4 bit value, returning whether or not this value is valid.
func nibbleFromASCII(ascii byte) (byte, Choice) {
w := Word(ascii)
inFirstRange := ctGt(w, Word('0')-1) & (1 ^ ctGt(w, Word('9')))
inSecondRange := ctGt(w, Word('A')-1) & (1 ^ ctGt(w, Word('F')))
valid := inFirstRange | inSecondRange
nibble := ctIfElse(inFirstRange, w-Word('0'), w-Word('A')+0xA)
return byte(nibble), valid
}
// SetHex modifies the value of z to hold a hex string, returning z
//
// The hex string must be in big endian order. If it contains characters
// other than 0..9, A..F, the value of z will be undefined, and an error will
// be returned.
//
// The value of the string shouldn't be leaked, except in the case where the string
// contains invalid characters.
func (z *Nat) SetHex(hex string) (*Nat, error) {
z.reduced = nil
z.announced = 4 * len(hex)
z.limbs = z.resizedLimbs(z.announced)
hexI := len(hex) - 1
for i := 0; i < len(z.limbs) && hexI >= 0; i++ {
z.limbs[i] = 0
for shift := 0; shift < _W && hexI >= 0; shift += 4 {
nibble, valid := nibbleFromASCII(byte(hex[hexI]))
if valid != 1 {
return nil, fmt.Errorf("invalid hex character: %c", hex[hexI])
}
z.limbs[i] |= Word(nibble) << shift
hexI--
}
}
return z, nil
}
// Hex converts this number into a hexadecimal string.
//
// This string will be a multiple of 8 bits.
//
// This shouldn't leak any information about the value of this Nat, only its length.
func (z *Nat) Hex() string {
bytes := z.Bytes()
var builder strings.Builder
for _, b := range bytes {
_ = builder.WriteByte(nibbletoASCII((b >> 4) & 0xF))
_ = builder.WriteByte(nibbletoASCII(b & 0xF))
}
return builder.String()
}
// the number of bytes to print in the string representation before an underscore
const underscoreAfterNBytes = 4
// String will represent this nat as a convenient Hex string
//
// This shouldn't leak any information about the value of this Nat, only its length.
func (z *Nat) String() string {
bytes := z.Bytes()
var builder strings.Builder
_, _ = builder.WriteString("0x")
i := 0
for _, b := range bytes {
if i == underscoreAfterNBytes {
builder.WriteRune('_')
i = 0
}
builder.WriteByte(nibbletoASCII((b >> 4) & 0xF))
builder.WriteByte(nibbletoASCII(b & 0xF))
i += 1
}
return builder.String()
}
// Byte will access the ith byte in this nat, with 0 being the least significant byte.
//
// This will leak the value of i, and panic if i is < 0.
func (z *Nat) Byte(i int) byte {
if i < 0 {
panic("negative byte")
}
limbCount := len(z.limbs)
bytesPerLimb := _W / 8
if i >= bytesPerLimb*limbCount {
return 0
}
return byte(z.limbs[i/bytesPerLimb] >> (8 * (i % bytesPerLimb)))
}
// Big converts a Nat into a big.Int
//
// This will leak information about the true size of z, so caution
// should be exercised when using this method with sensitive values.
func (z *Nat) Big() *big.Int {
res := new(big.Int)
// Unfortunate that there's no good way to handle this
bigLimbs := make([]big.Word, len(z.limbs))
for i := 0; i < len(bigLimbs) && i < len(z.limbs); i++ {
bigLimbs[i] = big.Word(z.limbs[i])
}
res.SetBits(bigLimbs)
return res
}
// SetBig modifies z to contain the value of x
//
// The size parameter is used to pad or truncate z to a certain number of bits.
func (z *Nat) SetBig(x *big.Int, size int) *Nat {
z.announced = size
z.limbs = z.resizedLimbs(size)
bigLimbs := x.Bits()
for i := 0; i < len(z.limbs) && i < len(bigLimbs); i++ {
z.limbs[i] = Word(bigLimbs[i])
}
maskEnd(z.limbs, size)
return z
}
// SetUint64 sets z to x, and returns z
//
// This will have the exact same capacity as a 64 bit number
func (z *Nat) SetUint64(x uint64) *Nat {
z.reduced = nil
z.announced = 64
z.limbs = z.resizedLimbs(z.announced)
for i := 0; i < len(z.limbs); i++ {
z.limbs[i] = Word(x)
x >>= _W
}
return z
}
// Uint64 represents this number as uint64
//
// The behavior of this function is undefined if the announced length of z is > 64.
func (z *Nat) Uint64() uint64 {
var ret uint64
for i := len(z.limbs) - 1; i >= 0; i-- {
ret = (ret << _W) | uint64(z.limbs[i])
}
return ret
}
// SetNat copies the value of x into z
//
// z will have the same announced length as x.
func (z *Nat) SetNat(x *Nat) *Nat {
z.limbs = z.resizedLimbs(x.announced)
copy(z.limbs, x.limbs)
z.reduced = x.reduced
z.announced = x.announced
return z
}
// Clone returns a copy of this value.
//
// This copy can safely be mutated without affecting the original.
func (z *Nat) Clone() *Nat {
return new(Nat).SetNat(z)
}
// Resize resizes z to a certain number of bits, returning z.
func (z *Nat) Resize(cap int) *Nat {
z.limbs = z.resizedLimbs(cap)
z.announced = cap
return z
}
// Modulus represents a natural number used for modular reduction
//
// Unlike with natural numbers, the number of bits need to contain the modulus
// is assumed to be public. Operations are allowed to leak this size, and creating
// a modulus will remove unnecessary zeros.
//
// Operations on a Modulus may leak whether or not a Modulus is even.
type Modulus struct {
nat Nat
// the number of leading zero bits
leading int
// The inverse of the least significant limb, modulo W
m0inv Word
// If true, then this modulus is even
even bool
}
// invertModW calculates x^-1 mod _W
func invertModW(x Word) Word {
y := x
// This is enough for 64 bits, and the extra iteration is not that costly for 32
for i := 0; i < 5; i++ {
y = y * (2 - x*y)
}
return y
}
// precomputeValues calculates the desirable modulus fields in advance
//
// This sets the leading number of bits, leaking the true bit size of m,
// as well as the inverse of the least significant limb (without leaking it).
//
// This will also do integrity checks, namely that the modulus isn't empty or even
func (m *Modulus) precomputeValues() {
announced := m.nat.TrueLen()
m.nat.announced = announced
m.nat.limbs = m.nat.resizedLimbs(announced)
if len(m.nat.limbs) < 1 {
panic("Modulus is empty")
}
m.leading = leadingZeros(m.nat.limbs[len(m.nat.limbs)-1])
// I think checking the bit directly might leak more data than we'd like
m.even = ctEq(m.nat.limbs[0]&1, 0) == 1
// There's no point calculating this if m isn't even, and we can leak evenness
if !m.even {
m.m0inv = invertModW(m.nat.limbs[0])
m.m0inv = -m.m0inv
}
}
// ModulusFromUint64 sets the modulus according to an integer
func ModulusFromUint64(x uint64) *Modulus {
var m Modulus
m.nat.SetUint64(x)
m.precomputeValues()
return &m
}
// ModulusFromBytes creates a new Modulus, converting from big endian bytes
//
// This function will remove leading zeros, thus leaking the true size of the modulus.
// See the documentation for the Modulus type, for more information about this contract.
func ModulusFromBytes(bytes []byte) *Modulus {
var m Modulus
// TODO: You could allocate a smaller buffer to begin with, versus using the Nat method
m.nat.SetBytes(bytes)
m.precomputeValues()
return &m
}
// ModulusFromHex creates a new modulus from a hex string.
//
// The same rules as Nat.SetHex apply.
//
// Additionally, this function will remove leading zeros, leaking the true size of the modulus.
// See the documentation for the Modulus type, for more information about this contract.
func ModulusFromHex(hex string) (*Modulus, error) {
var m Modulus
_, err := m.nat.SetHex(hex)
if err != nil {
return nil, err
}
m.precomputeValues()
return &m, nil
}
// FromNat creates a new Modulus, using the value of a Nat
//
// This will leak the true size of this natural number. Because of this,
// the true size of the number should not be sensitive information. This is
// a stronger requirement than we usually have for Nat.
func ModulusFromNat(nat *Nat) *Modulus {
var m Modulus
m.nat.SetNat(nat)
m.precomputeValues()
return &m
}
// Nat returns the value of this modulus as a Nat.
//
// This will create a copy of this modulus value, so the Nat can be safely
// mutated.
func (m *Modulus) Nat() *Nat {
return new(Nat).SetNat(&m.nat)
}
// Bytes returns the big endian bytes making up the modulus
func (m *Modulus) Bytes() []byte {
return m.nat.Bytes()
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (i *Modulus) MarshalBinary() ([]byte, error) {
return i.nat.Bytes(), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (i *Modulus) UnmarshalBinary(data []byte) error {
i.nat.SetBytes(data)
i.precomputeValues()
return nil
}
// Big returns the value of this Modulus as a big.Int
func (m *Modulus) Big() *big.Int {
return m.nat.Big()
}
// Hex will represent this Modulus as a Hex string.
//
// The hex string will hold a multiple of 8 bits.
//
// This shouldn't leak any information about the value of the modulus, beyond
// the usual leakage around its size.
func (m *Modulus) Hex() string {
return m.nat.Hex()
}
// String will represent this Modulus as a convenient Hex string
//
// This shouldn't leak any information about the value of the modulus, only its length.
func (m *Modulus) String() string {
return m.nat.String()
}
// BitLen returns the exact number of bits used to store this Modulus
//
// Moduli are allowed to leak this value.
func (m *Modulus) BitLen() int {
return m.nat.announced
}
// Cmp compares two moduli, returning results for (>, =, <).
//
// This will not leak information about the value of these relations, or the moduli.
func (m *Modulus) Cmp(n *Modulus) (Choice, Choice, Choice) {
return m.nat.Cmp(&n.nat)
}
// shiftAddInCommon exists to unify behavior between shiftAddIn and shiftAddInGeneric
//
// z, scratch, and m should have the same length.
//
// The two functions differ only in how the calculate a1:a0, and b0.
//
// hi should be what was previously the top limb of z.
//
// a1:a0 and b0 should be the most significant two limbs of z, and single limb of m,
// after shifting to discard leading zeros.
//
// The way these are calculated differs between the two versions of shiftAddIn,
// which is why this function exists.
func shiftAddInCommon(z, scratch, m []Word, hi, a1, a0, b0 Word) (q Word) {
// We want to use a1:a0 / b0 - 1 as our estimate. If rawQ is 0, we should
// use 0 as our estimate. Another edge case when an overflow happens in the quotient.
// It can be shown that this happens when a1 == b0. In this case, we want
// to use the maximum value for q
rawQ, _ := div(a1, a0, b0)
q = ctIfElse(ctEq(a1, b0), ^Word(0), ctIfElse(ctEq(rawQ, 0), 0, rawQ-1))
// This estimate is off by +- 1, so we subtract q * m, and then either add
// or subtract m, based on the result.
c := mulSubVVW(z, m, q)
// If the carry from subtraction is greater than the limb of z we've shifted out,
// then we've underflowed, and need to add in m
under := ctGt(c, hi)
// For us to be too large, we first need to not be too low, as per the previous flag.
// Then, if the lower limbs of z are still larger, or the top limb of z is equal to the carry,
// we can conclude that we're too large, and need to subtract m
stillBigger := cmpGeq(z, m)
over := (1 ^ under) & (stillBigger | (1 ^ ctEq(c, hi)))
addVV(scratch, z, m)
ctCondCopy(under, z, scratch)
q -= Word(under)
subVV(scratch, z, m)
ctCondCopy(over, z, scratch)
q += Word(over)
return
}
// shiftAddIn calculates z = z << _W + x mod m
//
// The length of z and scratch should be len(m)
func shiftAddIn(z, scratch []Word, x Word, m *Modulus) (q Word) {
// Making tests on the exact bit length of m is ok,
// since that's part of the contract for moduli
size := len(m.nat.limbs)
if size == 0 {
return
}
if size == 1 {
// In this case, z:x (/, %) m is exactly what we need to calculate
q, r := div(z[0], x, m.nat.limbs[0])
z[0] = r
return q
}
// The idea is as follows:
//
// We want to shift x into z, and then divide by m. Instead of dividing by
// m, we can get a good estimate, using the top two 2 * _W bits of z, and the
// top _W bits of m. These are stored in a1:a0, and b0 respectively.
// We need to keep around the top word of z, pre-shifting
hi := z[size-1]
a1 := (z[size-1] << m.leading) | (z[size-2] >> (_W - m.leading))
// The actual shift can be performed by moving the limbs of z up, then inserting x
for i := size - 1; i > 0; i-- {
z[i] = z[i-1]
}
z[0] = x
a0 := (z[size-1] << m.leading) | (z[size-2] >> (_W - m.leading))
b0 := (m.nat.limbs[size-1] << m.leading) | (m.nat.limbs[size-2] >> (_W - m.leading))
return shiftAddInCommon(z, scratch, m.nat.limbs, hi, a1, a0, b0)
}
// shiftAddInGeneric is like shiftAddIn, but works with arbitrary m.
//
// See shiftAddIn for what this function is trying to accomplish, and what the
// inputs represent.
//
// The big difference this entails is that z and m may have padding limbs, so
// we have to do a bit more work to recover their significant bits in constant-time.
func shiftAddInGeneric(z, scratch []Word, x Word, m []Word) Word {
size := len(m)
if size == 0 {
return 0
}
if size == 1 {
// In this case, z:x (/, %) m is exactly what we need to calculate
q, r := div(z[0], x, m[0])
z[0] = r
return q
}
// We need to get match the two most significant 2 * _W bits of z with the most significant
// _W bits of m. We also need to eliminate any leading zeros, possibly fetching a
// these bits over multiple limbs. Because of this, we need to scan over both
// arrays, with a window of 3 limbs for z, and 2 limbs for m, until we hit the
// first non-zero limb for either of them. Because z < m, it suffices to check
// for a non-zero limb from m.
var a2, a1, a0, b1, b0 Word
done := Choice(0)
for i := size - 1; i > 1; i-- {
a2 = ctIfElse(done, a2, z[i])
a1 = ctIfElse(done, a1, z[i-1])
a0 = ctIfElse(done, a0, z[i-2])
b1 = ctIfElse(done, b1, m[i])
b0 = ctIfElse(done, b0, m[i-1])
done = 1 ^ ctEq(b1, 0)
}
// We also need to do one more iteration to potentially include x inside of our
// significant bits from z.
a2 = ctIfElse(done, a2, z[1])
a1 = ctIfElse(done, a1, z[0])
a0 = ctIfElse(done, a0, x)
b1 = ctIfElse(done, b1, m[1])
b0 = ctIfElse(done, b0, m[0])
// Now, we need to shift away the leading zeros to get the most significant bits.
// Converting to Word avoids a panic check
l := Word(leadingZeros(b1))
a2 = (a2 << l) | (a1 >> (_W - l))
a1 = (a1 << l) | (a0 >> (_W - l))
b1 = (b1 << l) | (b0 >> (_W - l))
// Another adjustment we need to make before calling the next function is to actually
// insert x inside of z, shifting out hi.
hi := z[len(z)-1]
for i := size - 1; i > 0; i-- {
z[i] = z[i-1]
}
z[0] = x
return shiftAddInCommon(z, scratch, m, hi, a2, a1, b1)
}
// Mod calculates z <- x mod m
//
// The capacity of the resulting number matches the capacity of the modulus.
func (z *Nat) Mod(x *Nat, m *Modulus) *Nat {
if x.reduced == m {
z.SetNat(x)
return z
}
size := len(m.nat.limbs)
xLimbs := x.unaliasedLimbs(z)
z.limbs = z.resizedLimbs(2 * _W * size)
for i := 0; i < len(z.limbs); i++ {
z.limbs[i] = 0
}
// Multiple times in this section:
// LEAK: the length of x
// OK: this is public information
i := len(xLimbs) - 1
// We can inject at least size - 1 limbs while staying under m
// Thus, we start injecting from index size - 2
start := size - 2
// That is, if there are at least that many limbs to choose from
if i < start {
start = i
}
for j := start; j >= 0; j-- {
z.limbs[j] = xLimbs[i]
i--
}
// We shift in the remaining limbs, making sure to reduce modulo M each time
for ; i >= 0; i-- {
shiftAddIn(z.limbs[:size], z.limbs[size:], xLimbs[i], m)
}
z.limbs = z.resizedLimbs(m.nat.announced)
z.announced = m.nat.announced
z.reduced = m
return z
}
// Div calculates z <- x / m, with m a Modulus.
//
// This might seem like an odd signature, but by using a Modulus,
// we can achieve the same speed as the Mod method. This wouldn't be the case for
// an arbitrary Nat.
//
// cap determines the number of bits to keep in the result. If cap < 0, then
// the number of bits will be x.AnnouncedLen() - m.BitLen() + 2
func (z *Nat) Div(x *Nat, m *Modulus, cap int) *Nat {
if cap < 0 {
cap = x.announced - m.nat.announced + 2
}
if len(x.limbs) < len(m.nat.limbs) || x.reduced == m {
z.limbs = z.resizedLimbs(cap)
for i := 0; i < len(z.limbs); i++ {
z.limbs[i] = 0
}
z.announced = cap
z.reduced = nil
return z
}
size := limbCount(m.nat.announced)
xLimbs := x.unaliasedLimbs(z)
// Enough for 2 buffers the size of m, and to store the full quotient
startSize := limbCount(cap)
if startSize < 2*size {
startSize = 2 * size
}
z.limbs = z.resizedLimbs(_W * (startSize + len(xLimbs)))
remainder := z.limbs[:size]
for i := 0; i < len(remainder); i++ {
remainder[i] = 0
}
scratch := z.limbs[size : 2*size]
// Our full quotient, in big endian order.
quotientBE := z.limbs[startSize:]
// We use this to append without actually reallocating. We fill our quotient
// in from 0 upwards.
qI := 0
i := len(xLimbs) - 1
// We can inject at least size - 1 limbs while staying under m
// Thus, we start injecting from index size - 2
start := size - 2
// That is, if there are at least that many limbs to choose from
if i < start {
start = i
}
for j := start; j >= 0; j-- {
remainder[j] = xLimbs[i]
i--
quotientBE[qI] = 0
qI++
}
for ; i >= 0; i-- {
q := shiftAddIn(remainder, scratch, xLimbs[i], m)
quotientBE[qI] = q
qI++
}
z.limbs = z.resizedLimbs(cap)
// First, reverse all the limbs we want, from the last part of the buffer we used.
for i := 0; i < len(z.limbs) && i < len(quotientBE); i++ {
z.limbs[i] = quotientBE[qI-i-1]
}
maskEnd(z.limbs, cap)
z.reduced = nil
z.announced = cap
return z
}
// ModAdd calculates z <- x + y mod m
//
// The capacity of the resulting number matches the capacity of the modulus.
func (z *Nat) ModAdd(x *Nat, y *Nat, m *Modulus) *Nat {
var xModM, yModM Nat
// This is necessary for the correctness of the algorithm, since
// we don't assume that x and y are in range.
// Furthermore, we can now assume that x and y have the same number
// of limbs as m
xModM.Mod(x, m)
yModM.Mod(y, m)
// The only thing we have to resize is z, everything else has m's length
size := limbCount(m.nat.announced)
scratch := z.resizedLimbs(2 * _W * size)
// This might hold some more bits, but masking isn't necessary, since the
// result will be < m.
z.limbs = scratch[:size]
subResult := scratch[size:]
addCarry := addVV(z.limbs, xModM.limbs, yModM.limbs)
subCarry := subVV(subResult, z.limbs, m.nat.limbs)
// Three cases are possible:
//
// addCarry, subCarry = 0 -> subResult
// we didn't overflow our buffer, but our result was big
// enough to subtract m without underflow, so it was larger than m
// addCarry, subCarry = 1 -> subResult
// we overflowed the buffer, and the subtraction of m is correct,