-
Notifications
You must be signed in to change notification settings - Fork 296
/
Copy pathcurve.go
1291 lines (1208 loc) · 51.4 KB
/
curve.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
// Copyright (c) 2015-2024 The Decred developers
// Copyright 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package secp256k1
import (
"encoding/hex"
"math/bits"
)
// References:
// [SECG]: Recommended Elliptic Curve Domain Parameters
// https://www.secg.org/sec2-v2.pdf
//
// [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone)
//
// [BRID]: On Binary Representations of Integers with Digits -1, 0, 1
// (Prodinger, Helmut)
//
// [STWS]: Secure-TWS: Authenticating Node to Multi-user Communication in
// Shared Sensor Networks (Oliveira, Leonardo B. et al)
// All group operations are performed using Jacobian coordinates. For a given
// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1)
// where x = x1/z1^2 and y = y1/z1^3.
// hexToFieldVal converts the passed hex string into a FieldVal and will panic
// if there is an error. This is only provided for the hard-coded constants so
// errors in the source code can be detected. It will only (and must only) be
// called with hard-coded values.
func hexToFieldVal(s string) *FieldVal {
b, err := hex.DecodeString(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
var f FieldVal
if overflow := f.SetByteSlice(b); overflow {
panic("hex in source file overflows mod P: " + s)
}
return &f
}
// hexToModNScalar converts the passed hex string into a ModNScalar and will
// panic if there is an error. This is only provided for the hard-coded
// constants so errors in the source code can be detected. It will only (and
// must only) be called with hard-coded values.
func hexToModNScalar(s string) *ModNScalar {
var isNegative bool
if len(s) > 0 && s[0] == '-' {
isNegative = true
s = s[1:]
}
if len(s)%2 != 0 {
s = "0" + s
}
b, err := hex.DecodeString(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
var scalar ModNScalar
if overflow := scalar.SetByteSlice(b); overflow {
panic("hex in source file overflows mod N scalar: " + s)
}
if isNegative {
scalar.Negate()
}
return &scalar
}
var (
// The following constants are used to accelerate scalar point
// multiplication through the use of the endomorphism:
//
// φ(Q) ⟼ λ*Q = (β*Q.x mod p, Q.y)
//
// See the code in the deriveEndomorphismParams function in genprecomps.go
// for details on their derivation.
//
// Additionally, see the scalar multiplication function in this file for
// details on how they are used.
endoNegLambda = hexToModNScalar("-5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72")
endoBeta = hexToFieldVal("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")
endoNegB1 = hexToModNScalar("e4437ed6010e88286f547fa90abfe4c3")
endoNegB2 = hexToModNScalar("-3086d221a7d46bcde86c90e49284eb15")
endoZ1 = hexToModNScalar("3086d221a7d46bcde86c90e49284eb153daa8a1471e8ca7f")
endoZ2 = hexToModNScalar("e4437ed6010e88286f547fa90abfe4c4221208ac9df506c6")
// Alternatively, the following parameters are valid as well, however,
// benchmarks show them to be about 2% slower in practice.
// endoNegLambda = hexToModNScalar("-ac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283ce")
// endoBeta = hexToFieldVal("851695d49a83f8ef919bb86153cbcb16630fb68aed0a766a3ec693d68e6afa40")
// endoNegB1 = hexToModNScalar("3086d221a7d46bcde86c90e49284eb15")
// endoNegB2 = hexToModNScalar("-114ca50f7a8e2f3f657c1108d9d44cfd8")
// endoZ1 = hexToModNScalar("114ca50f7a8e2f3f657c1108d9d44cfd95fbc92c10fddd145")
// endoZ2 = hexToModNScalar("3086d221a7d46bcde86c90e49284eb153daa8a1471e8ca7f")
)
// JacobianPoint is an element of the group formed by the secp256k1 curve in
// Jacobian projective coordinates and thus represents a point on the curve.
type JacobianPoint struct {
// The X coordinate in Jacobian projective coordinates. The affine point is
// X/z^2.
X FieldVal
// The Y coordinate in Jacobian projective coordinates. The affine point is
// Y/z^3.
Y FieldVal
// The Z coordinate in Jacobian projective coordinates.
Z FieldVal
}
// MakeJacobianPoint returns a Jacobian point with the provided X, Y, and Z
// coordinates.
func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {
var p JacobianPoint
p.X.Set(x)
p.Y.Set(y)
p.Z.Set(z)
return p
}
// Set sets the Jacobian point to the provided point.
func (p *JacobianPoint) Set(other *JacobianPoint) {
p.X.Set(&other.X)
p.Y.Set(&other.Y)
p.Z.Set(&other.Z)
}
// ToAffine reduces the Z value of the existing point to 1 effectively
// making it an affine coordinate in constant time. The point will be
// normalized.
func (p *JacobianPoint) ToAffine() {
// Inversions are expensive and both point addition and point doubling
// are faster when working with points that have a z value of one. So,
// if the point needs to be converted to affine, go ahead and normalize
// the point itself at the same time as the calculation is the same.
var zInv, tempZ FieldVal
zInv.Set(&p.Z).Inverse() // zInv = Z^-1
tempZ.SquareVal(&zInv) // tempZ = Z^-2
p.X.Mul(&tempZ) // X = X/Z^2 (mag: 1)
p.Y.Mul(tempZ.Mul(&zInv)) // Y = Y/Z^3 (mag: 1)
p.Z.SetInt(1) // Z = 1 (mag: 1)
// Normalize the x and y values.
p.X.Normalize()
p.Y.Normalize()
}
// addZ1AndZ2EqualsOne adds two Jacobian points that are already known to have
// z values of 1 and stores the result in the provided result param. That is to
// say result = p1 + p2. It performs faster addition than the generic add
// routine since less arithmetic is needed due to the ability to avoid the z
// value multiplications.
//
// NOTE: The points must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func addZ1AndZ2EqualsOne(p1, p2, result *JacobianPoint) {
// To compute the point addition efficiently, this implementation splits
// the equation into intermediate elements which are used to minimize
// the number of field multiplications using the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-mmadd-2007-bl
//
// In particular it performs the calculations using the following:
// H = X2-X1, HH = H^2, I = 4*HH, J = H*I, r = 2*(Y2-Y1), V = X1*I
// X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*Y1*J, Z3 = 2*H
//
// This results in a cost of 4 field multiplications, 2 field squarings,
// 6 field additions, and 5 integer multiplications.
x1, y1 := &p1.X, &p1.Y
x2, y2 := &p2.X, &p2.Y
x3, y3, z3 := &result.X, &result.Y, &result.Z
// When the x coordinates are the same for two points on the curve, the
// y coordinates either must be the same, in which case it is point
// doubling, or they are opposite and the result is the point at
// infinity per the group law for elliptic curve cryptography.
if x1.Equals(x2) {
if y1.Equals(y2) {
// Since x1 == x2 and y1 == y2, point doubling must be
// done, otherwise the addition would end up dividing
// by zero.
DoubleNonConst(p1, result)
return
}
// Since x1 == x2 and y1 == -y2, the sum is the point at
// infinity per the group law.
x3.SetInt(0)
y3.SetInt(0)
z3.SetInt(0)
return
}
// Calculate X3, Y3, and Z3 according to the intermediate elements
// breakdown above.
var h, i, j, r, v FieldVal
var negJ, neg2V, negX3 FieldVal
h.Set(x1).Negate(1).Add(x2) // H = X2-X1 (mag: 3)
i.SquareVal(&h).MulInt(4) // I = 4*H^2 (mag: 4)
j.Mul2(&h, &i) // J = H*I (mag: 1)
r.Set(y1).Negate(1).Add(y2).MulInt(2) // r = 2*(Y2-Y1) (mag: 6)
v.Mul2(x1, &i) // V = X1*I (mag: 1)
negJ.Set(&j).Negate(1) // negJ = -J (mag: 2)
neg2V.Set(&v).MulInt(2).Negate(2) // neg2V = -(2*V) (mag: 3)
x3.Set(&r).Square().Add(&negJ).Add(&neg2V) // X3 = r^2-J-2*V (mag: 6)
negX3.Set(x3).Negate(6) // negX3 = -X3 (mag: 7)
j.Mul(y1).MulInt(2).Negate(2) // J = -(2*Y1*J) (mag: 3)
y3.Set(&v).Add(&negX3).Mul(&r).Add(&j) // Y3 = r*(V-X3)-2*Y1*J (mag: 4)
z3.Set(&h).MulInt(2) // Z3 = 2*H (mag: 6)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// addZ1EqualsZ2 adds two Jacobian points that are already known to have the
// same z value and stores the result in the provided result param. That is to
// say result = p1 + p2. It performs faster addition than the generic add
// routine since less arithmetic is needed due to the known equivalence.
//
// NOTE: The points must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func addZ1EqualsZ2(p1, p2, result *JacobianPoint) {
// To compute the point addition efficiently, this implementation splits
// the equation into intermediate elements which are used to minimize
// the number of field multiplications using a slightly modified version
// of the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-zadd-2007-m
//
// In particular it performs the calculations using the following:
// A = X2-X1, B = A^2, C=Y2-Y1, D = C^2, E = X1*B, F = X2*B
// X3 = D-E-F, Y3 = C*(E-X3)-Y1*(F-E), Z3 = Z1*A
//
// This results in a cost of 5 field multiplications, 2 field squarings,
// 9 field additions, and 0 integer multiplications.
x1, y1, z1 := &p1.X, &p1.Y, &p1.Z
x2, y2 := &p2.X, &p2.Y
x3, y3, z3 := &result.X, &result.Y, &result.Z
// When the x coordinates are the same for two points on the curve, the
// y coordinates either must be the same, in which case it is point
// doubling, or they are opposite and the result is the point at
// infinity per the group law for elliptic curve cryptography.
if x1.Equals(x2) {
if y1.Equals(y2) {
// Since x1 == x2 and y1 == y2, point doubling must be
// done, otherwise the addition would end up dividing
// by zero.
DoubleNonConst(p1, result)
return
}
// Since x1 == x2 and y1 == -y2, the sum is the point at
// infinity per the group law.
x3.SetInt(0)
y3.SetInt(0)
z3.SetInt(0)
return
}
// Calculate X3, Y3, and Z3 according to the intermediate elements
// breakdown above.
var a, b, c, d, e, f FieldVal
var negX1, negY1, negE, negX3 FieldVal
negX1.Set(x1).Negate(1) // negX1 = -X1 (mag: 2)
negY1.Set(y1).Negate(1) // negY1 = -Y1 (mag: 2)
a.Set(&negX1).Add(x2) // A = X2-X1 (mag: 3)
b.SquareVal(&a) // B = A^2 (mag: 1)
c.Set(&negY1).Add(y2) // C = Y2-Y1 (mag: 3)
d.SquareVal(&c) // D = C^2 (mag: 1)
e.Mul2(x1, &b) // E = X1*B (mag: 1)
negE.Set(&e).Negate(1) // negE = -E (mag: 2)
f.Mul2(x2, &b) // F = X2*B (mag: 1)
x3.Add2(&e, &f).Negate(2).Add(&d) // X3 = D-E-F (mag: 4)
negX3.Set(x3).Negate(4) // negX3 = -X3 (mag: 5)
y3.Set(y1).Mul(f.Add(&negE)).Negate(1) // Y3 = -(Y1*(F-E)) (mag: 2)
y3.Add(e.Add(&negX3).Mul(&c)) // Y3 = C*(E-X3)+Y3 (mag: 3)
z3.Mul2(z1, &a) // Z3 = Z1*A (mag: 1)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// addZ2EqualsOne adds two Jacobian points when the second point is already
// known to have a z value of 1 (and the z value for the first point is not 1)
// and stores the result in the provided result param. That is to say result =
// p1 + p2. It performs faster addition than the generic add routine since
// less arithmetic is needed due to the ability to avoid multiplications by the
// second point's z value.
//
// NOTE: The points must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func addZ2EqualsOne(p1, p2, result *JacobianPoint) {
// To compute the point addition efficiently, this implementation splits
// the equation into intermediate elements which are used to minimize
// the number of field multiplications using the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl
//
// In particular it performs the calculations using the following:
// Z1Z1 = Z1^2, U2 = X2*Z1Z1, S2 = Y2*Z1*Z1Z1, H = U2-X1, HH = H^2,
// I = 4*HH, J = H*I, r = 2*(S2-Y1), V = X1*I
// X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*Y1*J, Z3 = (Z1+H)^2-Z1Z1-HH
//
// This results in a cost of 7 field multiplications, 4 field squarings,
// 9 field additions, and 4 integer multiplications.
x1, y1, z1 := &p1.X, &p1.Y, &p1.Z
x2, y2 := &p2.X, &p2.Y
x3, y3, z3 := &result.X, &result.Y, &result.Z
// When the x coordinates are the same for two points on the curve, the
// y coordinates either must be the same, in which case it is point
// doubling, or they are opposite and the result is the point at
// infinity per the group law for elliptic curve cryptography. Since
// any number of Jacobian coordinates can represent the same affine
// point, the x and y values need to be converted to like terms. Due to
// the assumption made for this function that the second point has a z
// value of 1 (z2=1), the first point is already "converted".
var z1z1, u2, s2 FieldVal
z1z1.SquareVal(z1) // Z1Z1 = Z1^2 (mag: 1)
u2.Set(x2).Mul(&z1z1).Normalize() // U2 = X2*Z1Z1 (mag: 1)
s2.Set(y2).Mul(&z1z1).Mul(z1).Normalize() // S2 = Y2*Z1*Z1Z1 (mag: 1)
if x1.Equals(&u2) {
if y1.Equals(&s2) {
// Since x1 == x2 and y1 == y2, point doubling must be
// done, otherwise the addition would end up dividing
// by zero.
DoubleNonConst(p1, result)
return
}
// Since x1 == x2 and y1 == -y2, the sum is the point at
// infinity per the group law.
x3.SetInt(0)
y3.SetInt(0)
z3.SetInt(0)
return
}
// Calculate X3, Y3, and Z3 according to the intermediate elements
// breakdown above.
var h, hh, i, j, r, rr, v FieldVal
var negX1, negY1, negX3 FieldVal
negX1.Set(x1).Negate(1) // negX1 = -X1 (mag: 2)
h.Add2(&u2, &negX1) // H = U2-X1 (mag: 3)
hh.SquareVal(&h) // HH = H^2 (mag: 1)
i.Set(&hh).MulInt(4) // I = 4 * HH (mag: 4)
j.Mul2(&h, &i) // J = H*I (mag: 1)
negY1.Set(y1).Negate(1) // negY1 = -Y1 (mag: 2)
r.Set(&s2).Add(&negY1).MulInt(2) // r = 2*(S2-Y1) (mag: 6)
rr.SquareVal(&r) // rr = r^2 (mag: 1)
v.Mul2(x1, &i) // V = X1*I (mag: 1)
x3.Set(&v).MulInt(2).Add(&j).Negate(3) // X3 = -(J+2*V) (mag: 4)
x3.Add(&rr) // X3 = r^2+X3 (mag: 5)
negX3.Set(x3).Negate(5) // negX3 = -X3 (mag: 6)
y3.Set(y1).Mul(&j).MulInt(2).Negate(2) // Y3 = -(2*Y1*J) (mag: 3)
y3.Add(v.Add(&negX3).Mul(&r)) // Y3 = r*(V-X3)+Y3 (mag: 4)
z3.Add2(z1, &h).Square() // Z3 = (Z1+H)^2 (mag: 1)
z3.Add(z1z1.Add(&hh).Negate(2)) // Z3 = Z3-(Z1Z1+HH) (mag: 4)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// addGeneric adds two Jacobian points without any assumptions about the z
// values of the two points and stores the result in the provided result param.
// That is to say result = p1 + p2. It is the slowest of the add routines due
// to requiring the most arithmetic.
//
// NOTE: The points must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func addGeneric(p1, p2, result *JacobianPoint) {
// To compute the point addition efficiently, this implementation splits
// the equation into intermediate elements which are used to minimize
// the number of field multiplications using the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
//
// In particular it performs the calculations using the following:
// Z1Z1 = Z1^2, Z2Z2 = Z2^2, U1 = X1*Z2Z2, U2 = X2*Z1Z1, S1 = Y1*Z2*Z2Z2
// S2 = Y2*Z1*Z1Z1, H = U2-U1, I = (2*H)^2, J = H*I, r = 2*(S2-S1)
// V = U1*I
// X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*S1*J, Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2)*H
//
// This results in a cost of 11 field multiplications, 5 field squarings,
// 9 field additions, and 4 integer multiplications.
x1, y1, z1 := &p1.X, &p1.Y, &p1.Z
x2, y2, z2 := &p2.X, &p2.Y, &p2.Z
x3, y3, z3 := &result.X, &result.Y, &result.Z
// When the x coordinates are the same for two points on the curve, the
// y coordinates either must be the same, in which case it is point
// doubling, or they are opposite and the result is the point at
// infinity. Since any number of Jacobian coordinates can represent the
// same affine point, the x and y values need to be converted to like
// terms.
var z1z1, z2z2, u1, u2, s1, s2 FieldVal
z1z1.SquareVal(z1) // Z1Z1 = Z1^2 (mag: 1)
z2z2.SquareVal(z2) // Z2Z2 = Z2^2 (mag: 1)
u1.Set(x1).Mul(&z2z2).Normalize() // U1 = X1*Z2Z2 (mag: 1)
u2.Set(x2).Mul(&z1z1).Normalize() // U2 = X2*Z1Z1 (mag: 1)
s1.Set(y1).Mul(&z2z2).Mul(z2).Normalize() // S1 = Y1*Z2*Z2Z2 (mag: 1)
s2.Set(y2).Mul(&z1z1).Mul(z1).Normalize() // S2 = Y2*Z1*Z1Z1 (mag: 1)
if u1.Equals(&u2) {
if s1.Equals(&s2) {
// Since x1 == x2 and y1 == y2, point doubling must be
// done, otherwise the addition would end up dividing
// by zero.
DoubleNonConst(p1, result)
return
}
// Since x1 == x2 and y1 == -y2, the sum is the point at
// infinity per the group law.
x3.SetInt(0)
y3.SetInt(0)
z3.SetInt(0)
return
}
// Calculate X3, Y3, and Z3 according to the intermediate elements
// breakdown above.
var h, i, j, r, rr, v FieldVal
var negU1, negS1, negX3 FieldVal
negU1.Set(&u1).Negate(1) // negU1 = -U1 (mag: 2)
h.Add2(&u2, &negU1) // H = U2-U1 (mag: 3)
i.Set(&h).MulInt(2).Square() // I = (2*H)^2 (mag: 1)
j.Mul2(&h, &i) // J = H*I (mag: 1)
negS1.Set(&s1).Negate(1) // negS1 = -S1 (mag: 2)
r.Set(&s2).Add(&negS1).MulInt(2) // r = 2*(S2-S1) (mag: 6)
rr.SquareVal(&r) // rr = r^2 (mag: 1)
v.Mul2(&u1, &i) // V = U1*I (mag: 1)
x3.Set(&v).MulInt(2).Add(&j).Negate(3) // X3 = -(J+2*V) (mag: 4)
x3.Add(&rr) // X3 = r^2+X3 (mag: 5)
negX3.Set(x3).Negate(5) // negX3 = -X3 (mag: 6)
y3.Mul2(&s1, &j).MulInt(2).Negate(2) // Y3 = -(2*S1*J) (mag: 3)
y3.Add(v.Add(&negX3).Mul(&r)) // Y3 = r*(V-X3)+Y3 (mag: 4)
z3.Add2(z1, z2).Square() // Z3 = (Z1+Z2)^2 (mag: 1)
z3.Add(z1z1.Add(&z2z2).Negate(2)) // Z3 = Z3-(Z1Z1+Z2Z2) (mag: 4)
z3.Mul(&h) // Z3 = Z3*H (mag: 1)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// AddNonConst adds the passed Jacobian points together and stores the result in
// the provided result param in *non-constant* time.
//
// NOTE: The points must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func AddNonConst(p1, p2, result *JacobianPoint) {
// The point at infinity is the identity according to the group law for
// elliptic curve cryptography. Thus, ∞ + P = P and P + ∞ = P.
if (p1.X.IsZero() && p1.Y.IsZero()) || p1.Z.IsZero() {
result.Set(p2)
return
}
if (p2.X.IsZero() && p2.Y.IsZero()) || p2.Z.IsZero() {
result.Set(p1)
return
}
// Faster point addition can be achieved when certain assumptions are
// met. For example, when both points have the same z value, arithmetic
// on the z values can be avoided. This section thus checks for these
// conditions and calls an appropriate add function which is accelerated
// by using those assumptions.
isZ1One := p1.Z.IsOne()
isZ2One := p2.Z.IsOne()
switch {
case isZ1One && isZ2One:
addZ1AndZ2EqualsOne(p1, p2, result)
return
case p1.Z.Equals(&p2.Z):
addZ1EqualsZ2(p1, p2, result)
return
case isZ2One:
addZ2EqualsOne(p1, p2, result)
return
}
// None of the above assumptions are true, so fall back to generic
// point addition.
addGeneric(p1, p2, result)
}
// doubleZ1EqualsOne performs point doubling on the passed Jacobian point when
// the point is already known to have a z value of 1 and stores the result in
// the provided result param. That is to say result = 2*p. It performs faster
// point doubling than the generic routine since less arithmetic is needed due
// to the ability to avoid multiplication by the z value.
//
// NOTE: The resulting point will be normalized.
func doubleZ1EqualsOne(p, result *JacobianPoint) {
// This function uses the assumptions that z1 is 1, thus the point
// doubling formulas reduce to:
//
// X3 = (3*X1^2)^2 - 8*X1*Y1^2
// Y3 = (3*X1^2)*(4*X1*Y1^2 - X3) - 8*Y1^4
// Z3 = 2*Y1
//
// To compute the above efficiently, this implementation splits the
// equation into intermediate elements which are used to minimize the
// number of field multiplications in favor of field squarings which
// are roughly 35% faster than field multiplications with the current
// implementation at the time this was written.
//
// This uses a slightly modified version of the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl
//
// In particular it performs the calculations using the following:
// A = X1^2, B = Y1^2, C = B^2, D = 2*((X1+B)^2-A-C)
// E = 3*A, F = E^2, X3 = F-2*D, Y3 = E*(D-X3)-8*C
// Z3 = 2*Y1
//
// This results in a cost of 1 field multiplication, 5 field squarings,
// 6 field additions, and 5 integer multiplications.
x1, y1 := &p.X, &p.Y
x3, y3, z3 := &result.X, &result.Y, &result.Z
var a, b, c, d, e, f FieldVal
z3.Set(y1).MulInt(2) // Z3 = 2*Y1 (mag: 2)
a.SquareVal(x1) // A = X1^2 (mag: 1)
b.SquareVal(y1) // B = Y1^2 (mag: 1)
c.SquareVal(&b) // C = B^2 (mag: 1)
b.Add(x1).Square() // B = (X1+B)^2 (mag: 1)
d.Set(&a).Add(&c).Negate(2) // D = -(A+C) (mag: 3)
d.Add(&b).MulInt(2) // D = 2*(B+D)(mag: 8)
e.Set(&a).MulInt(3) // E = 3*A (mag: 3)
f.SquareVal(&e) // F = E^2 (mag: 1)
x3.Set(&d).MulInt(2).Negate(16) // X3 = -(2*D) (mag: 17)
x3.Add(&f) // X3 = F+X3 (mag: 18)
f.Set(x3).Negate(18).Add(&d).Normalize() // F = D-X3 (mag: 1)
y3.Set(&c).MulInt(8).Negate(8) // Y3 = -(8*C) (mag: 9)
y3.Add(f.Mul(&e)) // Y3 = E*F+Y3 (mag: 10)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// doubleGeneric performs point doubling on the passed Jacobian point without
// any assumptions about the z value and stores the result in the provided
// result param. That is to say result = 2*p. It is the slowest of the point
// doubling routines due to requiring the most arithmetic.
//
// NOTE: The resulting point will be normalized.
func doubleGeneric(p, result *JacobianPoint) {
// Point doubling formula for Jacobian coordinates for the secp256k1
// curve:
//
// X3 = (3*X1^2)^2 - 8*X1*Y1^2
// Y3 = (3*X1^2)*(4*X1*Y1^2 - X3) - 8*Y1^4
// Z3 = 2*Y1*Z1
//
// To compute the above efficiently, this implementation splits the
// equation into intermediate elements which are used to minimize the
// number of field multiplications in favor of field squarings which
// are roughly 35% faster than field multiplications with the current
// implementation at the time this was written.
//
// This uses a slightly modified version of the method shown at:
// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
//
// In particular it performs the calculations using the following:
// A = X1^2, B = Y1^2, C = B^2, D = 2*((X1+B)^2-A-C)
// E = 3*A, F = E^2, X3 = F-2*D, Y3 = E*(D-X3)-8*C
// Z3 = 2*Y1*Z1
//
// This results in a cost of 1 field multiplication, 5 field squarings,
// 6 field additions, and 5 integer multiplications.
x1, y1, z1 := &p.X, &p.Y, &p.Z
x3, y3, z3 := &result.X, &result.Y, &result.Z
var a, b, c, d, e, f FieldVal
z3.Mul2(y1, z1).MulInt(2) // Z3 = 2*Y1*Z1 (mag: 2)
a.SquareVal(x1) // A = X1^2 (mag: 1)
b.SquareVal(y1) // B = Y1^2 (mag: 1)
c.SquareVal(&b) // C = B^2 (mag: 1)
b.Add(x1).Square() // B = (X1+B)^2 (mag: 1)
d.Set(&a).Add(&c).Negate(2) // D = -(A+C) (mag: 3)
d.Add(&b).MulInt(2) // D = 2*(B+D)(mag: 8)
e.Set(&a).MulInt(3) // E = 3*A (mag: 3)
f.SquareVal(&e) // F = E^2 (mag: 1)
x3.Set(&d).MulInt(2).Negate(16) // X3 = -(2*D) (mag: 17)
x3.Add(&f) // X3 = F+X3 (mag: 18)
f.Set(x3).Negate(18).Add(&d).Normalize() // F = D-X3 (mag: 1)
y3.Set(&c).MulInt(8).Negate(8) // Y3 = -(8*C) (mag: 9)
y3.Add(f.Mul(&e)) // Y3 = E*F+Y3 (mag: 10)
// Normalize the resulting field values as needed.
x3.Normalize()
y3.Normalize()
z3.Normalize()
}
// DoubleNonConst doubles the passed Jacobian point and stores the result in the
// provided result parameter in *non-constant* time.
//
// NOTE: The point must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func DoubleNonConst(p, result *JacobianPoint) {
// Doubling the point at infinity is still infinity.
if p.Y.IsZero() || p.Z.IsZero() {
result.X.SetInt(0)
result.Y.SetInt(0)
result.Z.SetInt(0)
return
}
// Slightly faster point doubling can be achieved when the z value is 1
// by avoiding the multiplication on the z value. This section calls
// a point doubling function which is accelerated by using that
// assumption when possible.
if p.Z.IsOne() {
doubleZ1EqualsOne(p, result)
return
}
// Fall back to generic point doubling which works with arbitrary z
// values.
doubleGeneric(p, result)
}
// mulAdd64 multiplies the two passed base 2^64 digits together, adds the given
// value to the result, and returns the 128-bit result via a (hi, lo) tuple
// where the upper half of the bits are returned in hi and the lower half in lo.
func mulAdd64(digit1, digit2, m uint64) (hi, lo uint64) {
// Note the carry on the final add is safe to discard because the maximum
// possible value is:
// (2^64 - 1)(2^64 - 1) + (2^64 - 1) = 2^128 - 2^64
// and:
// 2^128 - 2^64 < 2^128.
var c uint64
hi, lo = bits.Mul64(digit1, digit2)
lo, c = bits.Add64(lo, m, 0)
hi, _ = bits.Add64(hi, 0, c)
return hi, lo
}
// mulAdd64Carry multiplies the two passed base 2^64 digits together, adds both
// the given value and carry to the result, and returns the 128-bit result via a
// (hi, lo) tuple where the upper half of the bits are returned in hi and the
// lower half in lo.
func mulAdd64Carry(digit1, digit2, m, c uint64) (hi, lo uint64) {
// Note the carry on the high order add is safe to discard because the
// maximum possible value is:
// (2^64 - 1)(2^64 - 1) + 2*(2^64 - 1) = 2^128 - 1
// and:
// 2^128 - 1 < 2^128.
var c2 uint64
hi, lo = mulAdd64(digit1, digit2, m)
lo, c2 = bits.Add64(lo, c, 0)
hi, _ = bits.Add64(hi, 0, c2)
return hi, lo
}
// mul512Rsh320Round computes the full 512-bit product of the two given scalars,
// right shifts the result by 320 bits, rounds to the nearest integer, and
// returns the result in constant time.
//
// Note that despite the inputs and output being mod n scalars, the 512-bit
// product is NOT reduced mod N prior to the right shift. This is intentional
// because it is used for replacing division with multiplication and thus the
// intermediate results must be done via a field extension to a larger field.
func mul512Rsh320Round(n1, n2 *ModNScalar) ModNScalar {
// Convert n1 and n2 to base 2^64 digits.
n1Digit0 := uint64(n1.n[0]) | uint64(n1.n[1])<<32
n1Digit1 := uint64(n1.n[2]) | uint64(n1.n[3])<<32
n1Digit2 := uint64(n1.n[4]) | uint64(n1.n[5])<<32
n1Digit3 := uint64(n1.n[6]) | uint64(n1.n[7])<<32
n2Digit0 := uint64(n2.n[0]) | uint64(n2.n[1])<<32
n2Digit1 := uint64(n2.n[2]) | uint64(n2.n[3])<<32
n2Digit2 := uint64(n2.n[4]) | uint64(n2.n[5])<<32
n2Digit3 := uint64(n2.n[6]) | uint64(n2.n[7])<<32
// Compute the full 512-bit product n1*n2.
var r0, r1, r2, r3, r4, r5, r6, r7, c uint64
// Terms resulting from the product of the first digit of the second number
// by all digits of the first number.
//
// Note that r0 is ignored because it is not needed to compute the higher
// terms and it is shifted out below anyway.
c, _ = bits.Mul64(n2Digit0, n1Digit0)
c, r1 = mulAdd64(n2Digit0, n1Digit1, c)
c, r2 = mulAdd64(n2Digit0, n1Digit2, c)
r4, r3 = mulAdd64(n2Digit0, n1Digit3, c)
// Terms resulting from the product of the second digit of the second number
// by all digits of the first number.
//
// Note that r1 is ignored because it is no longer needed to compute the
// higher terms and it is shifted out below anyway.
c, _ = mulAdd64(n2Digit1, n1Digit0, r1)
c, r2 = mulAdd64Carry(n2Digit1, n1Digit1, r2, c)
c, r3 = mulAdd64Carry(n2Digit1, n1Digit2, r3, c)
r5, r4 = mulAdd64Carry(n2Digit1, n1Digit3, r4, c)
// Terms resulting from the product of the third digit of the second number
// by all digits of the first number.
//
// Note that r2 is ignored because it is no longer needed to compute the
// higher terms and it is shifted out below anyway.
c, _ = mulAdd64(n2Digit2, n1Digit0, r2)
c, r3 = mulAdd64Carry(n2Digit2, n1Digit1, r3, c)
c, r4 = mulAdd64Carry(n2Digit2, n1Digit2, r4, c)
r6, r5 = mulAdd64Carry(n2Digit2, n1Digit3, r5, c)
// Terms resulting from the product of the fourth digit of the second number
// by all digits of the first number.
//
// Note that r3 is ignored because it is no longer needed to compute the
// higher terms and it is shifted out below anyway.
c, _ = mulAdd64(n2Digit3, n1Digit0, r3)
c, r4 = mulAdd64Carry(n2Digit3, n1Digit1, r4, c)
c, r5 = mulAdd64Carry(n2Digit3, n1Digit2, r5, c)
r7, r6 = mulAdd64Carry(n2Digit3, n1Digit3, r6, c)
// At this point the upper 256 bits of the full 512-bit product n1*n2 are in
// r4..r7 (recall the low order results were discarded as noted above).
//
// Right shift the result 320 bits. Note that the MSB of r4 determines
// whether or not to round because it is the final bit that is shifted out.
//
// Also, notice that r3..r7 would also ordinarily be set to 0 as well for
// the full shift, but that is skipped since they are no longer used as
// their values are known to be zero.
roundBit := r4 >> 63
r2, r1, r0 = r7, r6, r5
// Conditionally add 1 depending on the round bit in constant time.
r0, c = bits.Add64(r0, roundBit, 0)
r1, c = bits.Add64(r1, 0, c)
r2, r3 = bits.Add64(r2, 0, c)
// Finally, convert the result to a mod n scalar.
//
// No modular reduction is needed because the result is guaranteed to be
// less than the group order given the group order is > 2^255 and the
// maximum possible value of the result is 2^192.
var result ModNScalar
result.n[0] = uint32(r0)
result.n[1] = uint32(r0 >> 32)
result.n[2] = uint32(r1)
result.n[3] = uint32(r1 >> 32)
result.n[4] = uint32(r2)
result.n[5] = uint32(r2 >> 32)
result.n[6] = uint32(r3)
result.n[7] = uint32(r3 >> 32)
return result
}
// splitK returns two scalars (k1 and k2) that are a balanced length-two
// representation of the provided scalar such that k ≡ k1 + k2*λ (mod N), where
// N is the secp256k1 group order.
func splitK(k *ModNScalar) (ModNScalar, ModNScalar) {
// The ultimate goal is to decompose k into two scalars that are around
// half the bit length of k such that the following equation is satisfied:
//
// k1 + k2*λ ≡ k (mod n)
//
// The strategy used here is based on algorithm 3.74 from [GECC] with a few
// modifications to make use of the more efficient mod n scalar type, avoid
// some costly long divisions, and minimize the number of calculations.
//
// Start by defining a function that takes a vector v = <a,b> ∈ ℤ⨯ℤ:
//
// f(v) = a + bλ (mod n)
//
// Then, find two vectors, v1 = <a1,b1>, and v2 = <a2,b2> in ℤ⨯ℤ such that:
// 1) v1 and v2 are linearly independent
// 2) f(v1) = f(v2) = 0
// 3) v1 and v2 have small Euclidean norm
//
// The vectors that satisfy these properties are found via the Euclidean
// algorithm and are precomputed since both n and λ are fixed values for the
// secp256k1 curve. See genprecomps.go for derivation details.
//
// Next, consider k as a vector <k, 0> in ℚ⨯ℚ and by linear algebra write:
//
// <k, 0> = g1*v1 + g2*v2, where g1, g2 ∈ ℚ
//
// Note that, per above, the components of vector v1 are a1 and b1 while the
// components of vector v2 are a2 and b2. Given the vectors v1 and v2 were
// generated such that a1*b2 - a2*b1 = n, solving the equation for g1 and g2
// yields:
//
// g1 = b2*k / n
// g2 = -b1*k / n
//
// Observe:
// <k, 0> = g1*v1 + g2*v2
// = (b2*k/n)*<a1,b1> + (-b1*k/n)*<a2,b2> | substitute
// = <a1*b2*k/n, b1*b2*k/n> + <-a2*b1*k/n, -b2*b1*k/n> | scalar mul
// = <a1*b2*k/n - a2*b1*k/n, b1*b2*k/n - b2*b1*k/n> | vector add
// = <[a1*b2*k - a2*b1*k]/n, 0> | simplify
// = <k*[a1*b2 - a2*b1]/n, 0> | factor out k
// = <k*n/n, 0> | substitute
// = <k, 0> | simplify
//
// Now, consider an integer-valued vector v:
//
// v = c1*v1 + c2*v2, where c1, c2 ∈ ℤ (mod n)
//
// Since vectors v1 and v2 are linearly independent and were generated such
// that f(v1) = f(v2) = 0, all possible scalars c1 and c2 also produce a
// vector v such that f(v) = 0.
//
// In other words, c1 and c2 can be any integers and the resulting
// decomposition will still satisfy the required equation. However, since
// the goal is to produce a balanced decomposition that provides a
// performance advantage by minimizing max(k1, k2), c1 and c2 need to be
// integers close to g1 and g2, respectively, so the resulting vector v is
// an integer-valued vector that is close to <k, 0>.
//
// Finally, consider the vector u:
//
// u = <k, 0> - v
//
// It follows that f(u) = k and thus the two components of vector u satisfy
// the required equation:
//
// k1 + k2*λ ≡ k (mod n)
//
// Choosing c1 and c2:
// -------------------
//
// As mentioned above, c1 and c2 need to be integers close to g1 and g2,
// respectively. The algorithm in [GECC] chooses the following values:
//
// c1 = round(g1) = round(b2*k / n)
// c2 = round(g2) = round(-b1*k / n)
//
// However, as section 3.4.2 of [STWS] notes, the aforementioned approach
// requires costly long divisions that can be avoided by precomputing
// rounded estimates as follows:
//
// t = bitlen(n) + 1
// z1 = round(2^t * b2 / n)
// z2 = round(2^t * -b1 / n)
//
// Then, use those precomputed estimates to perform a multiplication by k
// along with a floored division by 2^t, which is a simple right shift by t:
//
// c1 = floor(k * z1 / 2^t) = (k * z1) >> t
// c2 = floor(k * z2 / 2^t) = (k * z2) >> t
//
// Finally, round up if last bit discarded in the right shift by t is set by
// adding 1.
//
// As a further optimization, rather than setting t = bitlen(n) + 1 = 257 as
// stated by [STWS], this implementation uses a higher precision estimate of
// t = bitlen(n) + 64 = 320 because it allows simplification of the shifts
// in the internal calculations that are done via uint64s and also allows
// the use of floor in the precomputations.
//
// Thus, the calculations this implementation uses are:
//
// z1 = floor(b2<<320 / n) | precomputed
// z2 = floor((-b1)<<320) / n) | precomputed
// c1 = ((k * z1) >> 320) + (((k * z1) >> 319) & 1)
// c2 = ((k * z2) >> 320) + (((k * z2) >> 319) & 1)
//
// Putting it all together:
// ------------------------
//
// Calculate the following vectors using the values discussed above:
//
// v = c1*v1 + c2*v2
// u = <k, 0> - v
//
// The two components of the resulting vector v are:
// va = c1*a1 + c2*a2
// vb = c1*b1 + c2*b2
//
// Thus, the two components of the resulting vector u are:
// k1 = k - va
// k2 = 0 - vb = -vb
//
// As some final optimizations:
//
// 1) Note that k1 + k2*λ ≡ k (mod n) means that k1 ≡ k - k2*λ (mod n).
// Therefore, the computation of va can be avoided to save two
// field multiplications and a field addition.
//
// 2) Since k1 ≡ k - k2*λ ≡ k + k2*(-λ), an additional field negation is
// saved by storing and using the negative version of λ.
//
// 3) Since k2 ≡ -vb ≡ -(c1*b1 + c2*b2) ≡ c1*(-b1) + c2*(-b2), one more
// field negation is saved by storing and using the negative versions of
// b1 and b2.
//
// k2 = c1*(-b1) + c2*(-b2)
// k1 = k + k2*(-λ)
var k1, k2 ModNScalar
c1 := mul512Rsh320Round(k, endoZ1)
c2 := mul512Rsh320Round(k, endoZ2)
k2.Add2(c1.Mul(endoNegB1), c2.Mul(endoNegB2))
k1.Mul2(&k2, endoNegLambda).Add(k)
return k1, k2
}
// nafScalar represents a positive integer up to a maximum value of 2^256 - 1
// encoded in non-adjacent form.
//
// NAF is a signed-digit representation where each digit can be +1, 0, or -1.
//
// In order to efficiently encode that information, this type uses two arrays, a
// "positive" array where set bits represent the +1 signed digits and a
// "negative" array where set bits represent the -1 signed digits. 0 is
// represented by neither array having a bit set in that position.
//
// The Pos and Neg methods return the aforementioned positive and negative
// arrays, respectively.
type nafScalar struct {
// pos houses the positive portion of the representation. An additional
// byte is required for the positive portion because the NAF encoding can be
// up to 1 bit longer than the normal binary encoding of the value.
//
// neg houses the negative portion of the representation. Even though the
// additional byte is not required for the negative portion, since it can
// never exceed the length of the normal binary encoding of the value,
// keeping the same length for positive and negative portions simplifies
// working with the representation and allows extra conditional branches to
// be avoided.
//
// start and end specify the starting and ending index to use within the pos
// and neg arrays, respectively. This allows fixed size arrays to be used
// versus needing to dynamically allocate space on the heap.
//
// NOTE: The fields are defined in the order that they are to minimize the
// padding on 32-bit and 64-bit platforms.
pos [33]byte
start, end uint8
neg [33]byte
}
// Pos returns the bytes of the encoded value with bits set in the positions
// that represent a signed digit of +1.
func (s *nafScalar) Pos() []byte {
return s.pos[s.start:s.end]
}
// Neg returns the bytes of the encoded value with bits set in the positions
// that represent a signed digit of -1.
func (s *nafScalar) Neg() []byte {
return s.neg[s.start:s.end]
}
// naf takes a positive integer up to a maximum value of 2^256 - 1 and returns
// its non-adjacent form (NAF), which is a unique signed-digit representation
// such that no two consecutive digits are nonzero. See the documentation for
// the returned type for details on how the representation is encoded
// efficiently and how to interpret it
//
// NAF is useful in that it has the fewest nonzero digits of any signed digit
// representation, only 1/3rd of its digits are nonzero on average, and at least
// half of the digits will be 0.
//
// The aforementioned properties are particularly beneficial for optimizing
// elliptic curve point multiplication because they effectively minimize the
// number of required point additions in exchange for needing to perform a mix
// of fewer point additions and subtractions and possibly one additional point
// doubling. This is an excellent tradeoff because subtraction of points has
// the same computational complexity as addition of points and point doubling is
// faster than both.
func naf(k []byte) nafScalar {
// Strip leading zero bytes.
for len(k) > 0 && k[0] == 0x00 {
k = k[1:]
}
// The non-adjacent form (NAF) of a positive integer k is an expression
// k = ∑_(i=0, l-1) k_i * 2^i where k_i ∈ {0,±1}, k_(l-1) != 0, and no two
// consecutive digits k_i are nonzero.
//
// The traditional method of computing the NAF of a positive integer is
// given by algorithm 3.30 in [GECC]. It consists of repeatedly dividing k
// by 2 and choosing the remainder so that the quotient (k−r)/2 is even
// which ensures the next NAF digit is 0. This requires log_2(k) steps.
//
// However, in [BRID], Prodinger notes that a closed form expression for the
// NAF representation is the bitwise difference 3k/2 - k/2. This is more
// efficient as it can be computed in O(1) versus the O(log(n)) of the
// traditional approach.
//
// The following code makes use of that formula to compute the NAF more
// efficiently.
//
// To understand the logic here, observe that the only way the NAF has a
// nonzero digit at a given bit is when either 3k/2 or k/2 has a bit set in
// that position, but not both. In other words, the result of a bitwise