This repository has been archived by the owner on Oct 12, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
math.ts
1790 lines (1668 loc) · 59.5 KB
/
math.ts
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
// To verify curve parameters, see pairing-friendly-curves spec:
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09
// Basic math is done over finite fields over p.
// More complicated math is done over polynominal extension fields.
// To simplify calculations in Fp12, we construct extension tower:
// Fp₁₂ = Fp₆² => Fp₂³
// Fp(u) / (u² - β) where β = -1
// Fp₂(v) / (v³ - ξ) where ξ = u + 1
// Fp₆(w) / (w² - γ) where γ = v
export const CURVE = {
// G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where
// characteristic; z + (z⁴ - z² + 1)(z - 1)²/3
P: 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn,
// order; z⁴ − z² + 1
r: 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001n,
// cofactor; (z - 1)²/3
h: 0x396c8c005555e1568c00aaab0000aaabn,
// generator's coordinates
// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507
// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569
Gx: 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bbn,
Gy: 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1n,
b: 4n,
// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1),
// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where
// G² - 1
// h2q
P2:
0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn **
2n -
1n,
// cofactor
h2: 0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5n,
G2x: [
0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8n,
0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7en,
],
// y =
// 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582,
// 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905
G2y: [
0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801n,
0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79ben,
],
b2: [4n, 4n],
// The BLS parameter x for BLS12-381
x: 0xd201000000010000n,
h2Eff:
0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551n,
};
const BLS_X_LEN = bitLen(CURVE.x);
type BigintTuple = [bigint, bigint];
type FpTuple = [Fp, Fp];
type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];
// prettier-ignore
type BigintTwelve = [
bigint, bigint, bigint, bigint, bigint, bigint,
bigint, bigint, bigint, bigint, bigint, bigint
];
// Finite field
interface Field<T> {
isZero(): boolean;
equals(rhs: T): boolean;
negate(): T;
add(rhs: T): T;
subtract(rhs: T): T;
invert(): T;
multiply(rhs: T | bigint): T;
square(): T;
pow(n: bigint): T;
div(rhs: T | bigint): T;
}
type FieldStatic<T extends Field<T>> = { ZERO: T; ONE: T };
export function mod(a: bigint, b: bigint) {
const res = a % b;
return res >= 0n ? res : b + res;
}
/**
* Efficiently exponentiate num to power and do modular division.
* @example
* powMod(2n, 6n, 11n) // 64n % 11n == 9n
*/
export function powMod(num: bigint, power: bigint, modulo: bigint) {
if (modulo <= 0n || power < 0n) throw new Error('Expected power/modulo > 0');
if (modulo === 1n) return 0n;
let res = 1n;
while (power > 0n) {
if (power & 1n) res = (res * num) % modulo;
num = (num * num) % modulo;
power >>= 1n;
}
return res;
}
function genInvertBatch<T extends Field<T>>(cls: FieldStatic<T>, nums: T[]): T[] {
const tmp = new Array(nums.length);
// Walk from first to last, multiply them by each other MOD p
const lastMultiplied = nums.reduce((acc, num, i) => {
if (num.isZero()) return acc;
tmp[i] = acc;
return acc.multiply(num);
}, cls.ONE);
// Invert last element
const inverted = lastMultiplied.invert();
// Walk from last to first, multiply them by inverted each other MOD p
nums.reduceRight((acc, num, i) => {
if (num.isZero()) return acc;
tmp[i] = acc.multiply(tmp[i]);
return acc.multiply(num);
}, inverted);
return tmp;
}
// Amount of bits inside bigint
function bitLen(n: bigint) {
let len;
for (len = 0; n > 0n; n >>= 1n, len += 1);
return len;
}
// Get single bit from bigint at pos
function bitGet(n: bigint, pos: number) {
return (n >> BigInt(pos)) & 1n;
}
// Inverses number over modulo
function invert(number: bigint, modulo: bigint = CURVE.P): bigint {
const _0n = 0n;
const _1n = 1n;
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
// Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
let a = mod(number, modulo);
let b = modulo;
// prettier-ignore
let x = _0n, y = _1n, u = _1n, v = _0n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
// prettier-ignore
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n) throw new Error('invert: does not exist');
return mod(x, modulo);
}
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex.slice(j, j + 2);
if (hexByte.length !== 2) throw new Error('Invalid byte sequence');
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
function numberToHex(num: number | bigint, byteLength: number): string {
if (!byteLength) throw new Error('byteLength target must be specified');
const hex = num.toString(16);
const p1 = hex.length & 1 ? `0${hex}` : hex;
return p1.padStart(byteLength * 2, '0');
}
export function numberToBytesBE(num: bigint, byteLength: number): Uint8Array {
const res = hexToBytes(numberToHex(num, byteLength));
if (res.length !== byteLength) throw new Error('numberToBytesBE: wrong byteLength');
return res;
}
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
export function bytesToHex(uint8a: Uint8Array): string {
// pre-caching chars could speed this up 6x.
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
export function bytesToNumberBE(bytes: Uint8Array): bigint {
return BigInt('0x' + bytesToHex(bytes));
}
export function concatBytes(...arrays: Uint8Array[]): Uint8Array {
if (arrays.length === 1) return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
// Finite field over p.
export class Fp implements Field<Fp> {
static readonly ORDER = CURVE.P;
static readonly MAX_BITS = bitLen(CURVE.P);
static readonly BYTES_LEN = Math.ceil(this.MAX_BITS / 8);
static readonly ZERO = new Fp(0n);
static readonly ONE = new Fp(1n);
readonly value: bigint;
constructor(value: bigint) {
this.value = mod(value, Fp.ORDER);
}
isZero(): boolean {
return this.value === 0n;
}
equals(rhs: Fp): boolean {
return this.value === rhs.value;
}
negate(): Fp {
return new Fp(-this.value);
}
invert(): Fp {
return new Fp(invert(this.value, Fp.ORDER));
}
add(rhs: Fp): Fp {
return new Fp(this.value + rhs.value);
}
square(): Fp {
return new Fp(this.value * this.value);
}
pow(n: bigint): Fp {
return new Fp(powMod(this.value, n, Fp.ORDER));
}
// square root computation for p ≡ 3 (mod 4)
// a^((p-3)/4)) ≡ 1/√a (mod p)
// √a ≡ a * 1/√a ≡ a^((p+1)/4) (mod p)
// It's possible to unwrap the exponentiation, but (P+1)/4 has 228 1's out of 379 bits.
// https://eprint.iacr.org/2012/685.pdf
sqrt(): Fp | undefined {
const root = this.pow((Fp.ORDER + 1n) / 4n);
if (!root.square().equals(this)) return;
return root;
}
subtract(rhs: Fp): Fp {
return new Fp(this.value - rhs.value);
}
multiply(rhs: Fp | bigint): Fp {
if (rhs instanceof Fp) rhs = rhs.value;
return new Fp(this.value * rhs);
}
div(rhs: Fp | bigint): Fp {
if (typeof rhs === 'bigint') rhs = new Fp(rhs);
return this.multiply(rhs.invert());
}
toString() {
const str = this.value.toString(16).padStart(96, '0');
return str.slice(0, 2) + '.' + str.slice(-2);
}
static fromBytes(b: Uint8Array): Fp {
if (b.length !== Fp.BYTES_LEN) throw new Error(`fromBytes wrong length=${b.length}`);
return new Fp(bytesToNumberBE(b));
}
toBytes(): Uint8Array {
return numberToBytesBE(this.value, Fp.BYTES_LEN);
}
}
// Finite field over r.
// This particular field is not used anywhere in bls12-381, but it is still useful.
export class Fr implements Field<Fr> {
static readonly ORDER = CURVE.r;
static readonly ZERO = new Fr(0n);
static readonly ONE = new Fr(1n);
readonly value: bigint;
constructor(value: bigint) {
this.value = mod(value, Fr.ORDER);
}
static isValid(b: bigint) {
return b <= Fr.ORDER;
}
isZero(): boolean {
return this.value === 0n;
}
equals(rhs: Fr): boolean {
return this.value === rhs.value;
}
negate(): Fr {
return new Fr(-this.value);
}
invert(): Fr {
return new Fr(invert(this.value, Fr.ORDER));
}
add(rhs: Fr): Fr {
return new Fr(this.value + rhs.value);
}
square(): Fr {
return new Fr(this.value * this.value);
}
pow(n: bigint): Fr {
return new Fr(powMod(this.value, n, Fr.ORDER));
}
subtract(rhs: Fr): Fr {
return new Fr(this.value - rhs.value);
}
multiply(rhs: Fr | bigint): Fr {
if (rhs instanceof Fr) rhs = rhs.value;
return new Fr(this.value * rhs);
}
div(rhs: Fr | bigint): Fr {
if (typeof rhs === 'bigint') rhs = new Fr(rhs);
return this.multiply(rhs.invert());
}
legendre(): Fr {
return this.pow((Fr.ORDER - 1n) / 2n);
}
// Tonelli-Shanks algorithm
sqrt(): Fr | undefined {
if (!this.legendre().equals(Fr.ONE)) return;
const P = Fr.ORDER;
let q, s, z;
for (q = P - 1n, s = 0; q % 2n === 0n; q /= 2n, s++);
if (s === 1) return this.pow((P + 1n) / 4n);
for (z = 2n; z < P && new Fr(z).legendre().value !== P - 1n; z++);
let c = powMod(z, q, P);
let r = powMod(this.value, (q + 1n) / 2n, P);
let t = powMod(this.value, q, P);
let t2 = 0n;
while (mod(t - 1n, P) !== 0n) {
t2 = mod(t * t, P);
let i;
for (i = 1; i < s; i++) {
if (mod(t2 - 1n, P) === 0n) break;
t2 = mod(t2 * t2, P);
}
let b = powMod(c, BigInt(1 << (s - i - 1)), P);
r = mod(r * b, P);
c = mod(b * b, P);
t = mod(t * c, P);
s = i;
}
return new Fr(r);
}
toString() {
return '0x' + this.value.toString(16).padStart(64, '0');
}
}
function powMod_FQP(fqp: any, fqpOne: any, n: bigint) {
const elm = fqp;
if (n === 0n) return fqpOne;
if (n === 1n) return elm;
let p = fqpOne;
let d = elm;
while (n > 0n) {
if (n & 1n) p = p.multiply(d);
n >>= 1n;
d = d.square();
}
return p;
}
// Fp₂ over complex plane
export class Fp2 implements Field<Fp2> {
static readonly ORDER = CURVE.P2;
static readonly MAX_BITS = bitLen(CURVE.P2);
static readonly BYTES_LEN = Math.ceil(this.MAX_BITS / 8);
static readonly ZERO = new Fp2(Fp.ZERO, Fp.ZERO);
static readonly ONE = new Fp2(Fp.ONE, Fp.ZERO);
constructor(readonly c0: Fp, readonly c1: Fp) {
if (typeof c0 === 'bigint') throw new Error('c0: Expected Fp');
if (typeof c1 === 'bigint') throw new Error('c1: Expected Fp');
}
static fromBigTuple(tuple: BigintTuple | bigint[]): Fp2 {
const fps = tuple.map((n) => new Fp(n)) as [Fp, Fp];
return new Fp2(...fps);
}
one() {
return Fp2.ONE;
}
isZero(): boolean {
return this.c0.isZero() && this.c1.isZero();
}
toString() {
return `Fp2(${this.c0} + ${this.c1}×i)`;
}
// real, imaginary
reim() {
return { re: this.c0.value, im: this.c1.value };
}
negate(): Fp2 {
const { c0, c1 } = this;
return new Fp2(c0.negate(), c1.negate());
}
equals(rhs: Fp2): boolean {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return c0.equals(r0) && c1.equals(r1);
}
add(rhs: Fp2): Fp2 {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return new Fp2(c0.add(r0), c1.add(r1));
}
subtract(rhs: Fp2): Fp2 {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return new Fp2(c0.subtract(r0), c1.subtract(r1));
}
multiply(rhs: Fp2 | bigint): Fp2 {
const { c0, c1 } = this;
if (typeof rhs === 'bigint') {
return new Fp2(c0.multiply(rhs), c1.multiply(rhs));
}
// (a+bi)(c+di) = (ac−bd) + (ad+bc)i
const { c0: r0, c1: r1 } = rhs;
let t1 = c0.multiply(r0); // c0 * o0
let t2 = c1.multiply(r1); // c1 * o1
// (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i
return new Fp2(t1.subtract(t2), c0.add(c1).multiply(r0.add(r1)).subtract(t1.add(t2)));
}
pow(n: bigint): Fp2 {
return powMod_FQP(this, Fp2.ONE, n);
}
div(rhs: Fp2 | bigint): Fp2 {
const inv = typeof rhs === 'bigint' ? new Fp(rhs).invert().value : rhs.invert();
return this.multiply(inv);
}
// multiply by u + 1
mulByNonresidue() {
const c0 = this.c0;
const c1 = this.c1;
return new Fp2(c0.subtract(c1), c0.add(c1));
}
square() {
const c0 = this.c0;
const c1 = this.c1;
const a = c0.add(c1);
const b = c0.subtract(c1);
const c = c0.add(c0);
return new Fp2(a.multiply(b), c.multiply(c1));
}
sqrt(): Fp2 | undefined {
// TODO: Optimize this line. It's extremely slow.
// Speeding this up would boost aggregateSignatures.
// https://eprint.iacr.org/2012/685.pdf applicable?
// https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250
// https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1
// Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99
const candidateSqrt = this.pow((Fp2.ORDER + 8n) / 16n);
const check = candidateSqrt.square().div(this);
const R = FP2_ROOTS_OF_UNITY;
const divisor = [R[0], R[2], R[4], R[6]].find((r) => r.equals(check));
if (!divisor) return;
const index = R.indexOf(divisor);
const root = R[index / 2];
if (!root) throw new Error('Invalid root');
const x1 = candidateSqrt.div(root);
const x2 = x1.negate();
const { re: re1, im: im1 } = x1.reim();
const { re: re2, im: im2 } = x2.reim();
if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1;
return x2;
}
// We wish to find the multiplicative inverse of a nonzero
// element a + bu in Fp2. We leverage an identity
//
// (a + bu)(a - bu) = a² + b²
//
// which holds because u² = -1. This can be rewritten as
//
// (a + bu)(a - bu)/(a² + b²) = 1
//
// because a² + b² = 0 has no nonzero solutions for (a, b).
// This gives that (a - bu)/(a² + b²) is the inverse
// of (a + bu). Importantly, this can be computing using
// only a single inversion in Fp.
invert() {
const { re: a, im: b } = this.reim();
const factor = new Fp(a * a + b * b).invert();
return new Fp2(factor.multiply(new Fp(a)), factor.multiply(new Fp(-b)));
}
// Raises to q**i -th power
frobeniusMap(power: number): Fp2 {
return new Fp2(this.c0, this.c1.multiply(FP2_FROBENIUS_COEFFICIENTS[power % 2]));
}
multiplyByB() {
let c0 = this.c0;
let c1 = this.c1;
let t0 = c0.multiply(4n); // 4 * c0
let t1 = c1.multiply(4n); // 4 * c1
// (T0-T1) + (T0+T1)*i
return new Fp2(t0.subtract(t1), t0.add(t1));
}
static fromBytes(b: Uint8Array): Fp2 {
if (b.length !== Fp2.BYTES_LEN) throw new Error(`fromBytes wrong length=${b.length}`);
return new Fp2(
Fp.fromBytes(b.subarray(0, Fp.BYTES_LEN)),
Fp.fromBytes(b.subarray(Fp.BYTES_LEN))
);
}
toBytes(): Uint8Array {
return concatBytes(this.c0.toBytes(), this.c1.toBytes());
}
}
// Finite extension field over irreducible polynominal.
// Fp2(v) / (v³ - ξ) where ξ = u + 1
export class Fp6 implements Field<Fp6> {
static readonly ZERO = new Fp6(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO);
static readonly ONE = new Fp6(Fp2.ONE, Fp2.ZERO, Fp2.ZERO);
static readonly BYTES_LEN = 3 * Fp2.BYTES_LEN;
static fromBigSix(t: BigintSix): Fp6 {
if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage');
const c = [t.slice(0, 2), t.slice(2, 4), t.slice(4, 6)].map((t) => Fp2.fromBigTuple(t)) as [
Fp2,
Fp2,
Fp2
];
return new Fp6(...c);
}
constructor(readonly c0: Fp2, readonly c1: Fp2, readonly c2: Fp2) {}
fromTriple(triple: [Fp2, Fp2, Fp2]) {
return new Fp6(...triple);
}
one() {
return Fp6.ONE;
}
isZero(): boolean {
return this.c0.isZero() && this.c1.isZero() && this.c2.isZero();
}
negate(): Fp6 {
const { c0, c1, c2 } = this;
return new Fp6(c0.negate(), c1.negate(), c2.negate());
}
toString() {
return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`;
}
equals(rhs: Fp6): boolean {
const { c0, c1, c2 } = this;
const { c0: r0, c1: r1, c2: r2 } = rhs;
return c0.equals(r0) && c1.equals(r1) && c2.equals(r2);
}
add(rhs: Fp6): Fp6 {
const { c0, c1, c2 } = this;
const { c0: r0, c1: r1, c2: r2 } = rhs;
return new Fp6(c0.add(r0), c1.add(r1), c2.add(r2));
}
subtract(rhs: Fp6): Fp6 {
const { c0, c1, c2 } = this;
const { c0: r0, c1: r1, c2: r2 } = rhs;
return new Fp6(c0.subtract(r0), c1.subtract(r1), c2.subtract(r2));
}
multiply(rhs: Fp6 | bigint) {
if (typeof rhs === 'bigint') {
return new Fp6(this.c0.multiply(rhs), this.c1.multiply(rhs), this.c2.multiply(rhs));
}
let { c0, c1, c2 } = this;
let { c0: r0, c1: r1, c2: r2 } = rhs;
let t0 = c0.multiply(r0); // c0 * o0
let t1 = c1.multiply(r1); // c1 * o1
let t2 = c2.multiply(r2); // c2 * o2
return new Fp6(
// t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
t0.add(c1.add(c2).multiply(r1.add(r2)).subtract(t1.add(t2)).mulByNonresidue()),
// (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
c0.add(c1).multiply(r0.add(r1)).subtract(t0.add(t1)).add(t2.mulByNonresidue()),
// T1 + (c0 + c2) * (r0 + r2) - T0 + T2
t1.add(c0.add(c2).multiply(r0.add(r2)).subtract(t0.add(t2)))
);
}
pow(n: bigint): Fp6 {
return powMod_FQP(this, Fp6.ONE, n);
}
div(rhs: Fp6 | bigint): Fp6 {
const inv = typeof rhs === 'bigint' ? new Fp(rhs).invert().value : rhs.invert();
return this.multiply(inv);
}
// Multiply by quadratic nonresidue v.
mulByNonresidue() {
return new Fp6(this.c2.mulByNonresidue(), this.c0, this.c1);
}
// Sparse multiplication
multiplyBy1(b1: Fp2): Fp6 {
return new Fp6(
this.c2.multiply(b1).mulByNonresidue(),
this.c0.multiply(b1),
this.c1.multiply(b1)
);
}
// Sparse multiplication
multiplyBy01(b0: Fp2, b1: Fp2): Fp6 {
let { c0, c1, c2 } = this;
let t0 = c0.multiply(b0); // c0 * b0
let t1 = c1.multiply(b1); // c1 * b1
return new Fp6(
// ((c1 + c2) * b1 - T1) * (u + 1) + T0
c1.add(c2).multiply(b1).subtract(t1).mulByNonresidue().add(t0),
// (b0 + b1) * (c0 + c1) - T0 - T1
b0.add(b1).multiply(c0.add(c1)).subtract(t0).subtract(t1),
// (c0 + c2) * b0 - T0 + T1
c0.add(c2).multiply(b0).subtract(t0).add(t1)
);
}
multiplyByFp2(rhs: Fp2): Fp6 {
let { c0, c1, c2 } = this;
return new Fp6(c0.multiply(rhs), c1.multiply(rhs), c2.multiply(rhs));
}
square() {
let { c0, c1, c2 } = this;
let t0 = c0.square(); // c0²
let t1 = c0.multiply(c1).multiply(2n); // 2 * c0 * c1
let t3 = c1.multiply(c2).multiply(2n); // 2 * c1 * c2
let t4 = c2.square(); // c2²
return new Fp6(
t3.mulByNonresidue().add(t0), // T3 * (u + 1) + T0
t4.mulByNonresidue().add(t1), // T4 * (u + 1) + T1
// T1 + (c0 - c1 + c2)² + T3 - T0 - T4
t1.add(c0.subtract(c1).add(c2).square()).add(t3).subtract(t0).subtract(t4)
);
}
invert() {
let { c0, c1, c2 } = this;
let t0 = c0.square().subtract(c2.multiply(c1).mulByNonresidue()); // c0² - c2 * c1 * (u + 1)
let t1 = c2.square().mulByNonresidue().subtract(c0.multiply(c1)); // c2² * (u + 1) - c0 * c1
let t2 = c1.square().subtract(c0.multiply(c2)); // c1² - c0 * c2
// 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)
let t4 = c2.multiply(t1).add(c1.multiply(t2)).mulByNonresidue().add(c0.multiply(t0)).invert();
return new Fp6(t4.multiply(t0), t4.multiply(t1), t4.multiply(t2));
}
// Raises to q**i -th power
frobeniusMap(power: number) {
return new Fp6(
this.c0.frobeniusMap(power),
this.c1.frobeniusMap(power).multiply(FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),
this.c2.frobeniusMap(power).multiply(FP6_FROBENIUS_COEFFICIENTS_2[power % 6])
);
}
static fromBytes(b: Uint8Array): Fp6 {
if (b.length !== Fp6.BYTES_LEN) throw new Error(`fromBytes wrong length=${b.length}`);
return new Fp6(
Fp2.fromBytes(b.subarray(0, Fp2.BYTES_LEN)),
Fp2.fromBytes(b.subarray(Fp2.BYTES_LEN, 2 * Fp2.BYTES_LEN)),
Fp2.fromBytes(b.subarray(2 * Fp2.BYTES_LEN))
);
}
toBytes(): Uint8Array {
return concatBytes(this.c0.toBytes(), this.c1.toBytes(), this.c2.toBytes());
}
}
// Finite extension field over irreducible polynominal.
// Fp₁₂ = Fp₆² => Fp₂³
// Fp₆(w) / (w² - γ) where γ = v
export class Fp12 implements Field<Fp12> {
static readonly ZERO = new Fp12(Fp6.ZERO, Fp6.ZERO);
static readonly ONE = new Fp12(Fp6.ONE, Fp6.ZERO);
static readonly BYTES_LEN = 2 * Fp6.BYTES_LEN;
static fromBigTwelve(t: BigintTwelve): Fp12 {
return new Fp12(
Fp6.fromBigSix(t.slice(0, 6) as BigintSix),
Fp6.fromBigSix(t.slice(6, 12) as BigintSix)
);
}
constructor(readonly c0: Fp6, readonly c1: Fp6) {}
fromTuple(c: [Fp6, Fp6]) {
return new Fp12(...c);
}
one() {
return Fp12.ONE;
}
isZero(): boolean {
return this.c0.isZero() && this.c1.isZero();
}
toString() {
return `Fp12(${this.c0} + ${this.c1} * w)`;
}
negate(): Fp12 {
const { c0, c1 } = this;
return new Fp12(c0.negate(), c1.negate());
}
equals(rhs: Fp12): boolean {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return c0.equals(r0) && c1.equals(r1);
}
add(rhs: Fp12): Fp12 {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return new Fp12(c0.add(r0), c1.add(r1));
}
subtract(rhs: Fp12): Fp12 {
const { c0, c1 } = this;
const { c0: r0, c1: r1 } = rhs;
return new Fp12(c0.subtract(r0), c1.subtract(r1));
}
multiply(rhs: Fp12 | bigint) {
if (typeof rhs === 'bigint') return new Fp12(this.c0.multiply(rhs), this.c1.multiply(rhs));
let { c0, c1 } = this;
let { c0: r0, c1: r1 } = rhs;
let t1 = c0.multiply(r0); // c0 * r0
let t2 = c1.multiply(r1); // c1 * r1
return new Fp12(
t1.add(t2.mulByNonresidue()), // T1 + T2 * v
// (c0 + c1) * (r0 + r1) - (T1 + T2)
c0.add(c1).multiply(r0.add(r1)).subtract(t1.add(t2))
);
}
pow(n: bigint): Fp12 {
return powMod_FQP(this, Fp12.ONE, n);
}
div(rhs: Fp12 | bigint): Fp12 {
const inv = typeof rhs === 'bigint' ? new Fp(rhs).invert().value : rhs.invert();
return this.multiply(inv);
}
// Sparse multiplication
multiplyBy014(o0: Fp2, o1: Fp2, o4: Fp2) {
let { c0, c1 } = this;
let t0 = c0.multiplyBy01(o0, o1);
let t1 = c1.multiplyBy1(o4);
return new Fp12(
t1.mulByNonresidue().add(t0), // T1 * v + T0
// (c1 + c0) * [o0, o1+o4] - T0 - T1
c1.add(c0).multiplyBy01(o0, o1.add(o4)).subtract(t0).subtract(t1)
);
}
multiplyByFp2(rhs: Fp2): Fp12 {
return new Fp12(this.c0.multiplyByFp2(rhs), this.c1.multiplyByFp2(rhs));
}
square() {
let { c0, c1 } = this;
let ab = c0.multiply(c1); // c0 * c1
return new Fp12(
// (c1 * v + c0) * (c0 + c1) - AB - AB * v
c1.mulByNonresidue().add(c0).multiply(c0.add(c1)).subtract(ab).subtract(ab.mulByNonresidue()),
ab.add(ab)
); // AB + AB
}
invert() {
let { c0, c1 } = this;
let t = c0.square().subtract(c1.square().mulByNonresidue()).invert(); // 1 / (c0² - c1² * v)
return new Fp12(c0.multiply(t), c1.multiply(t).negate()); // ((C0 * T) * T) + (-C1 * T) * w
}
conjugate(): Fp12 {
return new Fp12(this.c0, this.c1.negate());
}
// Raises to q**i -th power
frobeniusMap(power: number) {
const r0 = this.c0.frobeniusMap(power);
const { c0, c1, c2 } = this.c1.frobeniusMap(power);
const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];
return new Fp12(r0, new Fp6(c0.multiply(coeff), c1.multiply(coeff), c2.multiply(coeff)));
}
private Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } {
const a2 = a.square();
const b2 = b.square();
return {
first: b2.mulByNonresidue().add(a2), // b² * Nonresidue + a²
second: a.add(b).square().subtract(a2).subtract(b2), // (a + b)² - a² - b²
};
}
// A cyclotomic group is a subgroup of Fp^n defined by
// GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
// The result of any pairing is in a cyclotomic subgroup
// https://eprint.iacr.org/2009/565.pdf
private cyclotomicSquare(): Fp12 {
const { c0: c0c0, c1: c0c1, c2: c0c2 } = this.c0;
const { c0: c1c0, c1: c1c1, c2: c1c2 } = this.c1;
const { first: t3, second: t4 } = this.Fp4Square(c0c0, c1c1);
const { first: t5, second: t6 } = this.Fp4Square(c1c0, c0c2);
const { first: t7, second: t8 } = this.Fp4Square(c0c1, c1c2);
let t9 = t8.mulByNonresidue(); // T8 * (u + 1)
return new Fp12(
new Fp6(
t3.subtract(c0c0).multiply(2n).add(t3), // 2 * (T3 - c0c0) + T3
t5.subtract(c0c1).multiply(2n).add(t5), // 2 * (T5 - c0c1) + T5
t7.subtract(c0c2).multiply(2n).add(t7)
), // 2 * (T7 - c0c2) + T7
new Fp6(
t9.add(c1c0).multiply(2n).add(t9), // 2 * (T9 + c1c0) + T9
t4.add(c1c1).multiply(2n).add(t4), // 2 * (T4 + c1c1) + T4
t6.add(c1c2).multiply(2n).add(t6)
)
); // 2 * (T6 + c1c2) + T6
}
private cyclotomicExp(n: bigint) {
let z = Fp12.ONE;
for (let i = BLS_X_LEN - 1; i >= 0; i--) {
z = z.cyclotomicSquare();
if (bitGet(n, i)) z = z.multiply(this);
}
return z;
}
// https://eprint.iacr.org/2010/354.pdf
// https://eprint.iacr.org/2009/565.pdf
finalExponentiate() {
const { x } = CURVE;
// this^(q⁶) / this
const t0 = this.frobeniusMap(6).div(this);
// t0^(q²) * t0
const t1 = t0.frobeniusMap(2).multiply(t0);
const t2 = t1.cyclotomicExp(x).conjugate();
const t3 = t1.cyclotomicSquare().conjugate().multiply(t2);
const t4 = t3.cyclotomicExp(x).conjugate();
const t5 = t4.cyclotomicExp(x).conjugate();
const t6 = t5.cyclotomicExp(x).conjugate().multiply(t2.cyclotomicSquare());
const t7 = t6.cyclotomicExp(x).conjugate();
const t2_t5_pow_q2 = t2.multiply(t5).frobeniusMap(2);
const t4_t1_pow_q3 = t4.multiply(t1).frobeniusMap(3);
const t6_t1c_pow_q1 = t6.multiply(t1.conjugate()).frobeniusMap(1);
const t7_t3c_t1 = t7.multiply(t3.conjugate()).multiply(t1);
// (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1
return t2_t5_pow_q2.multiply(t4_t1_pow_q3).multiply(t6_t1c_pow_q1).multiply(t7_t3c_t1);
}
static fromBytes(b: Uint8Array): Fp12 {
if (b.length !== Fp12.BYTES_LEN) throw new Error(`fromBytes wrong length=${b.length}`);
return new Fp12(
Fp6.fromBytes(b.subarray(0, Fp6.BYTES_LEN)),
Fp6.fromBytes(b.subarray(Fp6.BYTES_LEN))
);
}
toBytes(): Uint8Array {
return concatBytes(this.c0.toBytes(), this.c1.toBytes());
}
}
type Constructor<T extends Field<T>> = { new (...args: any[]): T } & FieldStatic<T> & {
MAX_BITS: number;
};
//type PointConstructor<TT extends Field<T>, T extends ProjectivePoint<TT>> = { new(...args: any[]): T };
// x=X/Z, y=Y/Z
export abstract class ProjectivePoint<T extends Field<T>> {
private _MPRECOMPUTES: undefined | [number, this[]];
constructor(
public readonly x: T,
public readonly y: T,
public readonly z: T,
private readonly C: Constructor<T>
) {}
isZero() {
return this.z.isZero();
}
createPoint<TT extends this>(x: T, y: T, z: T): TT {
return new (<any>this.constructor)(x, y, z);
}
getZero(): this {
return this.createPoint(this.C.ONE, this.C.ONE, this.C.ZERO);
}
// Compare one point to another.
equals(rhs: ProjectivePoint<T>) {
if (this.constructor !== rhs.constructor)
throw new Error(
`ProjectivePoint#equals: this is ${this.constructor}, but rhs is ${rhs.constructor}`
);
const a = this;
const b = rhs;
// Ax * Bz == Bx * Az
const xe = a.x.multiply(b.z).equals(b.x.multiply(a.z));
// Ay * Bz == By * Az
const ye = a.y.multiply(b.z).equals(b.y.multiply(a.z));
return xe && ye;
}
negate(): this {
return this.createPoint(this.x, this.y.negate(), this.z);
}
toString(isAffine = true) {
if (this.isZero()) {
return `Point<Zero>`;
}
if (!isAffine) {
return `Point<x=${this.x}, y=${this.y}, z=${this.z}>`;
}
const [x, y] = this.toAffine();
return `Point<x=${x}, y=${y}>`;
}
fromAffineTuple(xy: [T, T]): this {
return this.createPoint(xy[0], xy[1], this.C.ONE);
}
// Converts Projective point to default (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
toAffine(invZ?: T): [T, T] {
const { x, y, z } = this;
const is0 = this.isZero();
if (invZ == null) invZ = is0 ? x : z.invert(); // x was chosen arbitrarily
const ax = x.multiply(invZ);
const ay = y.multiply(invZ);
if (is0) return [this.C.ZERO, this.C.ZERO];
if (invZ.isZero()) throw new Error('Invalid inverted z');
return [ax, ay];
}
toAffineBatch(points: ProjectivePoint<T>[]): [T, T][] {
const toInv = genInvertBatch(
this.C,
points.map((p) => p.z)
);
return points.map((p, i) => p.toAffine(toInv[i]));
}
normalizeZ(points: this[]): this[] {
return this.toAffineBatch(points).map((t) => this.fromAffineTuple(t));
}
// http://hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#doubling-dbl-1998-cmo-2
// Cost: 6M + 5S + 1*a + 4add + 1*2 + 1*3 + 1*4 + 3*8.
double(): this {
const { x, y, z } = this;
const W = x.multiply(x).multiply(3n);
const S = y.multiply(z);
const SS = S.multiply(S);
const SSS = SS.multiply(S);
const B = x.multiply(y).multiply(S);
const H = W.multiply(W).subtract(B.multiply(8n));
const X3 = H.multiply(S).multiply(2n);
// W * (4 * B - H) - 8 * y * y * S_squared
const Y3 = W.multiply(B.multiply(4n).subtract(H)).subtract(
y.multiply(y).multiply(8n).multiply(SS)
);
const Z3 = SSS.multiply(8n);
return this.createPoint(X3, Y3, Z3);
}
// http://hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#addition-add-1998-cmo-2
// Cost: 12M + 2S + 6add + 1*2.
add(rhs: this): this {
if (this.constructor !== rhs.constructor)
throw new Error(
`ProjectivePoint#add: this is ${this.constructor}, but rhs is ${rhs.constructor}`
);
const p1 = this;
const p2 = rhs;
if (p1.isZero()) return p2;