@noble/curves 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +135 -123
  2. package/_shortw_utils.d.ts.map +1 -1
  3. package/abstract/bls.d.ts +37 -34
  4. package/abstract/bls.d.ts.map +1 -1
  5. package/abstract/bls.js +167 -115
  6. package/abstract/bls.js.map +1 -1
  7. package/abstract/curve.d.ts +2 -1
  8. package/abstract/curve.d.ts.map +1 -1
  9. package/abstract/curve.js +22 -7
  10. package/abstract/curve.js.map +1 -1
  11. package/abstract/edwards.d.ts +11 -0
  12. package/abstract/edwards.d.ts.map +1 -1
  13. package/abstract/edwards.js +79 -75
  14. package/abstract/edwards.js.map +1 -1
  15. package/abstract/modular.d.ts +4 -0
  16. package/abstract/modular.d.ts.map +1 -1
  17. package/abstract/modular.js +13 -2
  18. package/abstract/modular.js.map +1 -1
  19. package/abstract/montgomery.d.ts.map +1 -1
  20. package/abstract/montgomery.js +4 -9
  21. package/abstract/montgomery.js.map +1 -1
  22. package/abstract/tower.d.ts +106 -0
  23. package/abstract/tower.d.ts.map +1 -0
  24. package/abstract/tower.js +497 -0
  25. package/abstract/tower.js.map +1 -0
  26. package/abstract/utils.d.ts +17 -0
  27. package/abstract/utils.d.ts.map +1 -1
  28. package/abstract/utils.js +50 -1
  29. package/abstract/utils.js.map +1 -1
  30. package/abstract/weierstrass.d.ts +7 -0
  31. package/abstract/weierstrass.d.ts.map +1 -1
  32. package/abstract/weierstrass.js +88 -72
  33. package/abstract/weierstrass.js.map +1 -1
  34. package/bls12-381.d.ts +1 -65
  35. package/bls12-381.d.ts.map +1 -1
  36. package/bls12-381.js +48 -575
  37. package/bls12-381.js.map +1 -1
  38. package/bn254.d.ts +10 -6
  39. package/bn254.d.ts.map +1 -1
  40. package/bn254.js +207 -10
  41. package/bn254.js.map +1 -1
  42. package/ed25519.d.ts +7 -4
  43. package/ed25519.d.ts.map +1 -1
  44. package/ed25519.js +3 -0
  45. package/ed25519.js.map +1 -1
  46. package/esm/_shortw_utils.d.ts.map +1 -1
  47. package/esm/abstract/bls.d.ts +37 -34
  48. package/esm/abstract/bls.d.ts.map +1 -1
  49. package/esm/abstract/bls.js +168 -116
  50. package/esm/abstract/bls.js.map +1 -1
  51. package/esm/abstract/curve.d.ts +2 -1
  52. package/esm/abstract/curve.d.ts.map +1 -1
  53. package/esm/abstract/curve.js +22 -7
  54. package/esm/abstract/curve.js.map +1 -1
  55. package/esm/abstract/edwards.d.ts +11 -0
  56. package/esm/abstract/edwards.d.ts.map +1 -1
  57. package/esm/abstract/edwards.js +80 -76
  58. package/esm/abstract/edwards.js.map +1 -1
  59. package/esm/abstract/modular.d.ts +4 -0
  60. package/esm/abstract/modular.d.ts.map +1 -1
  61. package/esm/abstract/modular.js +12 -2
  62. package/esm/abstract/modular.js.map +1 -1
  63. package/esm/abstract/montgomery.d.ts.map +1 -1
  64. package/esm/abstract/montgomery.js +5 -10
  65. package/esm/abstract/montgomery.js.map +1 -1
  66. package/esm/abstract/tower.d.ts +106 -0
  67. package/esm/abstract/tower.d.ts.map +1 -0
  68. package/esm/abstract/tower.js +493 -0
  69. package/esm/abstract/tower.js.map +1 -0
  70. package/esm/abstract/utils.d.ts +17 -0
  71. package/esm/abstract/utils.d.ts.map +1 -1
  72. package/esm/abstract/utils.js +44 -0
  73. package/esm/abstract/utils.js.map +1 -1
  74. package/esm/abstract/weierstrass.d.ts +7 -0
  75. package/esm/abstract/weierstrass.d.ts.map +1 -1
  76. package/esm/abstract/weierstrass.js +89 -73
  77. package/esm/abstract/weierstrass.js.map +1 -1
  78. package/esm/bls12-381.d.ts +1 -65
  79. package/esm/bls12-381.d.ts.map +1 -1
  80. package/esm/bls12-381.js +50 -577
  81. package/esm/bls12-381.js.map +1 -1
  82. package/esm/bn254.d.ts +10 -6
  83. package/esm/bn254.d.ts.map +1 -1
  84. package/esm/bn254.js +206 -9
  85. package/esm/bn254.js.map +1 -1
  86. package/esm/ed25519.d.ts +7 -4
  87. package/esm/ed25519.d.ts.map +1 -1
  88. package/esm/ed25519.js +3 -0
  89. package/esm/ed25519.js.map +1 -1
  90. package/esm/p256.d.ts.map +1 -1
  91. package/esm/p384.d.ts.map +1 -1
  92. package/esm/p521.d.ts.map +1 -1
  93. package/esm/secp256k1.d.ts +6 -0
  94. package/esm/secp256k1.d.ts.map +1 -1
  95. package/esm/secp256k1.js +17 -13
  96. package/esm/secp256k1.js.map +1 -1
  97. package/p256.d.ts.map +1 -1
  98. package/p384.d.ts.map +1 -1
  99. package/p521.d.ts.map +1 -1
  100. package/package.json +2 -1
  101. package/secp256k1.d.ts +6 -0
  102. package/secp256k1.d.ts.map +1 -1
  103. package/secp256k1.js +16 -12
  104. package/secp256k1.js.map +1 -1
  105. package/src/abstract/bls.ts +222 -168
  106. package/src/abstract/curve.ts +23 -7
  107. package/src/abstract/edwards.ts +81 -68
  108. package/src/abstract/modular.ts +13 -3
  109. package/src/abstract/montgomery.ts +11 -10
  110. package/src/abstract/tower.ts +604 -0
  111. package/src/abstract/utils.ts +49 -0
  112. package/src/abstract/weierstrass.ts +85 -68
  113. package/src/bls12-381.ts +53 -707
  114. package/src/bn254.ts +224 -9
  115. package/src/ed25519.ts +5 -2
  116. package/src/secp256k1.ts +24 -12
@@ -0,0 +1,604 @@
1
+ import * as mod from './modular.js';
2
+ import { bitLen, bitMask, concatBytes, notImplemented } from './utils.js';
3
+ import type { ProjConstructor, ProjPointType } from './weierstrass.js';
4
+
5
+ /*
6
+ Towered extension fields
7
+
8
+ Rather than implementing a massive 12th-degree extension directly, it is more efficient
9
+ to build it up from smaller extensions: a tower of extensions.
10
+
11
+ For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension,
12
+ on top of a cubic (degree three) extension, on top of a quadratic extension of Fp.
13
+
14
+ For more info: "Pairings for beginners" by Costello, section 7.3.
15
+ */
16
+
17
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
18
+ // prettier-ignore
19
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
20
+
21
+ // Fp₂ over complex plane
22
+ export type BigintTuple = [bigint, bigint];
23
+ export type Fp = bigint;
24
+ // Finite extension field over irreducible polynominal.
25
+ // Fp(u) / (u² - β) where β = -1
26
+ export type Fp2 = { c0: bigint; c1: bigint };
27
+ export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];
28
+ export type Fp6 = { c0: Fp2; c1: Fp2; c2: Fp2 };
29
+ export type Fp12 = { c0: Fp6; c1: Fp6 }; // Fp₁₂ = Fp₆² => Fp₂³, Fp₆(w) / (w² - γ) where γ = v
30
+ // prettier-ignore
31
+ export type BigintTwelve = [
32
+ bigint, bigint, bigint, bigint, bigint, bigint,
33
+ bigint, bigint, bigint, bigint, bigint, bigint
34
+ ];
35
+
36
+ export type Fp2Bls = mod.IField<Fp2> & {
37
+ reim: (num: Fp2) => { re: Fp; im: Fp };
38
+ mulByB: (num: Fp2) => Fp2;
39
+ frobeniusMap(num: Fp2, power: number): Fp2;
40
+ fromBigTuple(num: [bigint, bigint]): Fp2;
41
+ };
42
+
43
+ export type Fp12Bls = mod.IField<Fp12> & {
44
+ frobeniusMap(num: Fp12, power: number): Fp12;
45
+ mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;
46
+ mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;
47
+ conjugate(num: Fp12): Fp12;
48
+ finalExponentiate(num: Fp12): Fp12;
49
+ };
50
+
51
+ function calcFrobeniusCoefficients<T>(
52
+ Fp: mod.IField<T>,
53
+ nonResidue: T,
54
+ modulus: bigint,
55
+ degree: number,
56
+ num: number = 1,
57
+ divisor?: number
58
+ ) {
59
+ const _divisor = BigInt(divisor === undefined ? degree : divisor);
60
+ const towerModulus: any = modulus ** BigInt(degree);
61
+ const res: T[][] = [];
62
+ for (let i = 0; i < num; i++) {
63
+ const a = BigInt(i + 1);
64
+ const powers: T[] = [];
65
+ for (let j = 0, qPower = _1n; j < degree; j++) {
66
+ const power = ((a * qPower - a) / _divisor) % towerModulus;
67
+ powers.push(Fp.pow(nonResidue, power));
68
+ qPower *= modulus;
69
+ }
70
+ res.push(powers);
71
+ }
72
+ return res;
73
+ }
74
+
75
+ // This works same at least for bls12-381, bn254 and bls12-377
76
+ export function psiFrobenius(Fp: mod.IField<Fp>, Fp2: Fp2Bls, base: Fp2) {
77
+ // Ψ endomorphism
78
+ const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3)
79
+ const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2)
80
+ function psi(x: Fp2, y: Fp2): [Fp2, Fp2] {
81
+ // This x10 faster than previous version in bls12-381
82
+ const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);
83
+ const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);
84
+ return [x2, y2];
85
+ }
86
+ // Ψ²(P) endomorphism (psi2(x) = psi(psi(x)))
87
+ const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3)
88
+ // This equals -1, which causes y to be Fp2.neg(y).
89
+ // But not sure if there are case when this is not true?
90
+ const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/3)
91
+ if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) throw new Error('psiFrobenius: PSI2_Y!==-1');
92
+ function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] {
93
+ return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];
94
+ }
95
+ // Map points
96
+ const mapAffine =
97
+ <T>(fn: (x: T, y: T) => [T, T]) =>
98
+ (c: ProjConstructor<T>, P: ProjPointType<T>) => {
99
+ const affine = P.toAffine();
100
+ const p = fn(affine.x, affine.y);
101
+ return c.fromAffine({ x: p[0], y: p[1] });
102
+ };
103
+ const G2psi = mapAffine(psi);
104
+ const G2psi2 = mapAffine(psi2);
105
+ return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y };
106
+ }
107
+
108
+ export type Tower12Opts = {
109
+ ORDER: bigint;
110
+ NONRESIDUE?: Fp;
111
+ // Fp2
112
+ FP2_NONRESIDUE: BigintTuple;
113
+ Fp2sqrt?: (num: Fp2) => Fp2;
114
+ Fp2mulByB: (num: Fp2) => Fp2;
115
+ // Fp12
116
+ Fp12cyclotomicSquare: (num: Fp12) => Fp12;
117
+ Fp12cyclotomicExp: (num: Fp12, n: bigint) => Fp12;
118
+ Fp12finalExponentiate: (num: Fp12) => Fp12;
119
+ };
120
+
121
+ export function tower12(opts: Tower12Opts) {
122
+ const { ORDER } = opts;
123
+ // Fp
124
+ const Fp = mod.Field(ORDER);
125
+ const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1));
126
+ const FpLegendre = mod.FpLegendre(ORDER);
127
+ const Fpdiv2 = Fp.div(Fp.ONE, _2n); // 1/2
128
+
129
+ // Fp2
130
+ const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0];
131
+ const Fp2Add = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({
132
+ c0: Fp.add(c0, r0),
133
+ c1: Fp.add(c1, r1),
134
+ });
135
+ const Fp2Subtract = ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => ({
136
+ c0: Fp.sub(c0, r0),
137
+ c1: Fp.sub(c1, r1),
138
+ });
139
+ const Fp2Multiply = ({ c0, c1 }: Fp2, rhs: Fp2) => {
140
+ if (typeof rhs === 'bigint') return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) };
141
+ // (a+bi)(c+di) = (ac−bd) + (ad+bc)i
142
+ const { c0: r0, c1: r1 } = rhs;
143
+ let t1 = Fp.mul(c0, r0); // c0 * o0
144
+ let t2 = Fp.mul(c1, r1); // c1 * o1
145
+ // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i
146
+ const o0 = Fp.sub(t1, t2);
147
+ const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));
148
+ return { c0: o0, c1: o1 };
149
+ };
150
+ const Fp2Square = ({ c0, c1 }: Fp2) => {
151
+ const a = Fp.add(c0, c1);
152
+ const b = Fp.sub(c0, c1);
153
+ const c = Fp.add(c0, c0);
154
+ return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) };
155
+ };
156
+ type Fp2Utils = {
157
+ NONRESIDUE: Fp2;
158
+ fromBigTuple: (tuple: BigintTuple | bigint[]) => Fp2;
159
+ reim: (num: Fp2) => { re: bigint; im: bigint };
160
+ mulByNonresidue: (num: Fp2) => Fp2;
161
+ mulByB: (num: Fp2) => Fp2;
162
+ frobeniusMap(num: Fp2, power: number): Fp2;
163
+ };
164
+ const Fp2fromBigTuple = (tuple: BigintTuple | bigint[]) => {
165
+ if (tuple.length !== 2) throw new Error('Invalid tuple');
166
+ const fps = tuple.map((n) => Fp.create(n)) as [Fp, Fp];
167
+ return { c0: fps[0], c1: fps[1] };
168
+ };
169
+
170
+ const FP2_ORDER = ORDER * ORDER;
171
+ const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE);
172
+ const Fp2: mod.IField<Fp2> & Fp2Utils = {
173
+ ORDER: FP2_ORDER,
174
+ NONRESIDUE: Fp2Nonresidue,
175
+ BITS: bitLen(FP2_ORDER),
176
+ BYTES: Math.ceil(bitLen(FP2_ORDER) / 8),
177
+ MASK: bitMask(bitLen(FP2_ORDER)),
178
+ ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },
179
+ ONE: { c0: Fp.ONE, c1: Fp.ZERO },
180
+ create: (num) => num,
181
+ isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint',
182
+ is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1),
183
+ eql: ({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) => Fp.eql(c0, r0) && Fp.eql(c1, r1),
184
+ neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }),
185
+ pow: (num, power) => mod.FpPow(Fp2, num, power),
186
+ invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums),
187
+ // Normalized
188
+ add: Fp2Add,
189
+ sub: Fp2Subtract,
190
+ mul: Fp2Multiply,
191
+ sqr: Fp2Square,
192
+ // NonNormalized stuff
193
+ addN: Fp2Add,
194
+ subN: Fp2Subtract,
195
+ mulN: Fp2Multiply,
196
+ sqrN: Fp2Square,
197
+ // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?
198
+ div: (lhs, rhs) =>
199
+ Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)),
200
+ inv: ({ c0: a, c1: b }) => {
201
+ // We wish to find the multiplicative inverse of a nonzero
202
+ // element a + bu in Fp2. We leverage an identity
203
+ //
204
+ // (a + bu)(a - bu) = a² + b²
205
+ //
206
+ // which holds because u² = -1. This can be rewritten as
207
+ //
208
+ // (a + bu)(a - bu)/(a² + b²) = 1
209
+ //
210
+ // because a² + b² = 0 has no nonzero solutions for (a, b).
211
+ // This gives that (a - bu)/(a² + b²) is the inverse
212
+ // of (a + bu). Importantly, this can be computing using
213
+ // only a single inversion in Fp.
214
+ const factor = Fp.inv(Fp.create(a * a + b * b));
215
+ return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) };
216
+ },
217
+ sqrt: (num) => {
218
+ if (opts.Fp2sqrt) return opts.Fp2sqrt(num);
219
+ // This is generic for all quadratic extensions (Fp2)
220
+ const { c0, c1 } = num;
221
+ if (Fp.is0(c1)) {
222
+ // if c0 is quadratic residue
223
+ if (Fp.eql(FpLegendre(Fp, c0), Fp.ONE)) return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO });
224
+ else return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) });
225
+ }
226
+ const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE)));
227
+ let d = Fp.mul(Fp.add(a, c0), Fpdiv2);
228
+ const legendre = FpLegendre(Fp, d);
229
+ // -1, Quadratic non residue
230
+ if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE)) d = Fp.sub(d, a);
231
+ const a0 = Fp.sqrt(d);
232
+ const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) });
233
+ if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) throw new Error('Cannot find square root');
234
+ // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num
235
+ const x1 = candidateSqrt;
236
+ const x2 = Fp2.neg(x1);
237
+ const { re: re1, im: im1 } = Fp2.reim(x1);
238
+ const { re: re2, im: im2 } = Fp2.reim(x2);
239
+ if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1;
240
+ return x2;
241
+ },
242
+ // Same as sgn0_m_eq_2 in RFC 9380
243
+ isOdd: (x: Fp2) => {
244
+ const { re: x0, im: x1 } = Fp2.reim(x);
245
+ const sign_0 = x0 % _2n;
246
+ const zero_0 = x0 === _0n;
247
+ const sign_1 = x1 % _2n;
248
+ return BigInt(sign_0 || (zero_0 && sign_1)) == _1n;
249
+ },
250
+ // Bytes util
251
+ fromBytes(b: Uint8Array): Fp2 {
252
+ if (b.length !== Fp2.BYTES) throw new Error(`fromBytes wrong length=${b.length}`);
253
+ return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) };
254
+ },
255
+ toBytes: ({ c0, c1 }) => concatBytes(Fp.toBytes(c0), Fp.toBytes(c1)),
256
+ cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
257
+ c0: Fp.cmov(c0, r0, c),
258
+ c1: Fp.cmov(c1, r1, c),
259
+ }),
260
+ reim: ({ c0, c1 }) => ({ re: c0, im: c1 }),
261
+ // multiply by u + 1
262
+ mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue),
263
+ mulByB: opts.Fp2mulByB,
264
+ fromBigTuple: Fp2fromBigTuple,
265
+ frobeniusMap: ({ c0, c1 }, power: number): Fp2 => ({
266
+ c0,
267
+ c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]),
268
+ }),
269
+ };
270
+ // Fp6
271
+ const Fp6Add = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({
272
+ c0: Fp2.add(c0, r0),
273
+ c1: Fp2.add(c1, r1),
274
+ c2: Fp2.add(c2, r2),
275
+ });
276
+ const Fp6Subtract = ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) => ({
277
+ c0: Fp2.sub(c0, r0),
278
+ c1: Fp2.sub(c1, r1),
279
+ c2: Fp2.sub(c2, r2),
280
+ });
281
+ const Fp6Multiply = ({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) => {
282
+ if (typeof rhs === 'bigint') {
283
+ return {
284
+ c0: Fp2.mul(c0, rhs),
285
+ c1: Fp2.mul(c1, rhs),
286
+ c2: Fp2.mul(c2, rhs),
287
+ };
288
+ }
289
+ const { c0: r0, c1: r1, c2: r2 } = rhs;
290
+ const t0 = Fp2.mul(c0, r0); // c0 * o0
291
+ const t1 = Fp2.mul(c1, r1); // c1 * o1
292
+ const t2 = Fp2.mul(c2, r2); // c2 * o2
293
+ return {
294
+ // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
295
+ c0: Fp2.add(
296
+ t0,
297
+ Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))
298
+ ),
299
+ // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
300
+ c1: Fp2.add(
301
+ Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)),
302
+ Fp2.mulByNonresidue(t2)
303
+ ),
304
+ // T1 + (c0 + c2) * (r0 + r2) - T0 + T2
305
+ c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)),
306
+ };
307
+ };
308
+ const Fp6Square = ({ c0, c1, c2 }: Fp6) => {
309
+ let t0 = Fp2.sqr(c0); // c0²
310
+ let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1
311
+ let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2
312
+ let t4 = Fp2.sqr(c2); // c2²
313
+ return {
314
+ c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0
315
+ c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1
316
+ // T1 + (c0 - c1 + c2)² + T3 - T0 - T4
317
+ c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4),
318
+ };
319
+ };
320
+ type Fp6Utils = {
321
+ fromBigSix: (tuple: BigintSix) => Fp6;
322
+ mulByNonresidue: (num: Fp6) => Fp6;
323
+ frobeniusMap(num: Fp6, power: number): Fp6;
324
+ mul1(num: Fp6, b1: Fp2): Fp6;
325
+ mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6;
326
+ mulByFp2(lhs: Fp6, rhs: Fp2): Fp6;
327
+ };
328
+
329
+ const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients(
330
+ Fp2,
331
+ Fp2Nonresidue,
332
+ Fp.ORDER,
333
+ 6,
334
+ 2,
335
+ 3
336
+ );
337
+
338
+ const Fp6: mod.IField<Fp6> & Fp6Utils = {
339
+ ORDER: Fp2.ORDER, // TODO: unused, but need to verify
340
+ BITS: 3 * Fp2.BITS,
341
+ BYTES: 3 * Fp2.BYTES,
342
+ MASK: bitMask(3 * Fp2.BITS),
343
+ ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },
344
+ ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },
345
+ create: (num) => num,
346
+ isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2),
347
+ is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2),
348
+ neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }),
349
+ eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) =>
350
+ Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2),
351
+ sqrt: notImplemented,
352
+ // Do we need division by bigint at all? Should be done via order:
353
+ div: (lhs, rhs) =>
354
+ Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)),
355
+ pow: (num, power) => mod.FpPow(Fp6, num, power),
356
+ invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums),
357
+ // Normalized
358
+ add: Fp6Add,
359
+ sub: Fp6Subtract,
360
+ mul: Fp6Multiply,
361
+ sqr: Fp6Square,
362
+ // NonNormalized stuff
363
+ addN: Fp6Add,
364
+ subN: Fp6Subtract,
365
+ mulN: Fp6Multiply,
366
+ sqrN: Fp6Square,
367
+
368
+ inv: ({ c0, c1, c2 }) => {
369
+ let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1)
370
+ let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1
371
+ let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2
372
+ // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)
373
+ let t4 = Fp2.inv(
374
+ Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))
375
+ );
376
+ return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) };
377
+ },
378
+ // Bytes utils
379
+ fromBytes: (b: Uint8Array): Fp6 => {
380
+ if (b.length !== Fp6.BYTES) throw new Error(`fromBytes wrong length=${b.length}`);
381
+ return {
382
+ c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)),
383
+ c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)),
384
+ c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)),
385
+ };
386
+ },
387
+ toBytes: ({ c0, c1, c2 }): Uint8Array =>
388
+ concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
389
+ cmov: ({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c) => ({
390
+ c0: Fp2.cmov(c0, r0, c),
391
+ c1: Fp2.cmov(c1, r1, c),
392
+ c2: Fp2.cmov(c2, r2, c),
393
+ }),
394
+ fromBigSix: (t: BigintSix): Fp6 => {
395
+ if (!Array.isArray(t) || t.length !== 6) throw new Error('Invalid Fp6 usage');
396
+ return {
397
+ c0: Fp2.fromBigTuple(t.slice(0, 2)),
398
+ c1: Fp2.fromBigTuple(t.slice(2, 4)),
399
+ c2: Fp2.fromBigTuple(t.slice(4, 6)),
400
+ };
401
+ },
402
+ frobeniusMap: ({ c0, c1, c2 }, power: number) => ({
403
+ c0: Fp2.frobeniusMap(c0, power),
404
+ c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),
405
+ c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]),
406
+ }),
407
+ mulByFp2: ({ c0, c1, c2 }, rhs: Fp2): Fp6 => ({
408
+ c0: Fp2.mul(c0, rhs),
409
+ c1: Fp2.mul(c1, rhs),
410
+ c2: Fp2.mul(c2, rhs),
411
+ }),
412
+ mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }),
413
+ // Sparse multiplication
414
+ mul1: ({ c0, c1, c2 }, b1: Fp2): Fp6 => ({
415
+ c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),
416
+ c1: Fp2.mul(c0, b1),
417
+ c2: Fp2.mul(c1, b1),
418
+ }),
419
+ // Sparse multiplication
420
+ mul01({ c0, c1, c2 }, b0: Fp2, b1: Fp2): Fp6 {
421
+ let t0 = Fp2.mul(c0, b0); // c0 * b0
422
+ let t1 = Fp2.mul(c1, b1); // c1 * b1
423
+ return {
424
+ // ((c1 + c2) * b1 - T1) * (u + 1) + T0
425
+ c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),
426
+ // (b0 + b1) * (c0 + c1) - T0 - T1
427
+ c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),
428
+ // (c0 + c2) * b0 - T0 + T1
429
+ c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1),
430
+ };
431
+ },
432
+ };
433
+
434
+ // Fp12
435
+ const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(
436
+ Fp2,
437
+ Fp2Nonresidue,
438
+ Fp.ORDER,
439
+ 12,
440
+ 1,
441
+ 6
442
+ )[0];
443
+
444
+ const Fp12Add = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({
445
+ c0: Fp6.add(c0, r0),
446
+ c1: Fp6.add(c1, r1),
447
+ });
448
+ const Fp12Subtract = ({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) => ({
449
+ c0: Fp6.sub(c0, r0),
450
+ c1: Fp6.sub(c1, r1),
451
+ });
452
+ const Fp12Multiply = ({ c0, c1 }: Fp12, rhs: Fp12 | bigint) => {
453
+ if (typeof rhs === 'bigint') return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) };
454
+ let { c0: r0, c1: r1 } = rhs;
455
+ let t1 = Fp6.mul(c0, r0); // c0 * r0
456
+ let t2 = Fp6.mul(c1, r1); // c1 * r1
457
+ return {
458
+ c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v
459
+ // (c0 + c1) * (r0 + r1) - (T1 + T2)
460
+ c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)),
461
+ };
462
+ };
463
+ const Fp12Square = ({ c0, c1 }: Fp12) => {
464
+ let ab = Fp6.mul(c0, c1); // c0 * c1
465
+ return {
466
+ // (c1 * v + c0) * (c0 + c1) - AB - AB * v
467
+ c0: Fp6.sub(
468
+ Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab),
469
+ Fp6.mulByNonresidue(ab)
470
+ ),
471
+ c1: Fp6.add(ab, ab),
472
+ }; // AB + AB
473
+ };
474
+ function Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } {
475
+ const a2 = Fp2.sqr(a);
476
+ const b2 = Fp2.sqr(b);
477
+ return {
478
+ first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a²
479
+ second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b²
480
+ };
481
+ }
482
+ type Fp12Utils = {
483
+ fromBigTwelve: (t: BigintTwelve) => Fp12;
484
+ frobeniusMap(num: Fp12, power: number): Fp12;
485
+ mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;
486
+ mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;
487
+ mulByFp2(lhs: Fp12, rhs: Fp2): Fp12;
488
+ conjugate(num: Fp12): Fp12;
489
+ finalExponentiate(num: Fp12): Fp12;
490
+ _cyclotomicSquare(num: Fp12): Fp12;
491
+ _cyclotomicExp(num: Fp12, n: bigint): Fp12;
492
+ };
493
+
494
+ const Fp12: mod.IField<Fp12> & Fp12Utils = {
495
+ ORDER: Fp2.ORDER, // TODO: unused, but need to verify
496
+ BITS: 2 * Fp2.BITS,
497
+ BYTES: 2 * Fp2.BYTES,
498
+ MASK: bitMask(2 * Fp2.BITS),
499
+ ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },
500
+ ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },
501
+ create: (num) => num,
502
+ isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1),
503
+ is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1),
504
+ neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }),
505
+ eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1),
506
+ sqrt: notImplemented,
507
+ inv: ({ c0, c1 }) => {
508
+ let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v)
509
+ return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w
510
+ },
511
+ div: (lhs, rhs) =>
512
+ Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)),
513
+ pow: (num, power) => mod.FpPow(Fp12, num, power),
514
+ invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums),
515
+ // Normalized
516
+ add: Fp12Add,
517
+ sub: Fp12Subtract,
518
+ mul: Fp12Multiply,
519
+ sqr: Fp12Square,
520
+ // NonNormalized stuff
521
+ addN: Fp12Add,
522
+ subN: Fp12Subtract,
523
+ mulN: Fp12Multiply,
524
+ sqrN: Fp12Square,
525
+
526
+ // Bytes utils
527
+ fromBytes: (b: Uint8Array): Fp12 => {
528
+ if (b.length !== Fp12.BYTES) throw new Error(`fromBytes wrong length=${b.length}`);
529
+ return {
530
+ c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),
531
+ c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)),
532
+ };
533
+ },
534
+ toBytes: ({ c0, c1 }): Uint8Array => concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1)),
535
+ cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
536
+ c0: Fp6.cmov(c0, r0, c),
537
+ c1: Fp6.cmov(c1, r1, c),
538
+ }),
539
+ // Utils
540
+ // toString() {
541
+ // return `Fp12(${this.c0} + ${this.c1} * w)`;
542
+ // },
543
+ // fromTuple(c: [Fp6, Fp6]) {
544
+ // return new Fp12(...c);
545
+ // }
546
+ fromBigTwelve: (t: BigintTwelve): Fp12 => ({
547
+ c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix),
548
+ c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix),
549
+ }),
550
+ // Raises to q**i -th power
551
+ frobeniusMap(lhs, power: number) {
552
+ const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);
553
+ const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];
554
+ return {
555
+ c0: Fp6.frobeniusMap(lhs.c0, power),
556
+ c1: Fp6.create({
557
+ c0: Fp2.mul(c0, coeff),
558
+ c1: Fp2.mul(c1, coeff),
559
+ c2: Fp2.mul(c2, coeff),
560
+ }),
561
+ };
562
+ },
563
+ mulByFp2: ({ c0, c1 }, rhs: Fp2): Fp12 => ({
564
+ c0: Fp6.mulByFp2(c0, rhs),
565
+ c1: Fp6.mulByFp2(c1, rhs),
566
+ }),
567
+ conjugate: ({ c0, c1 }): Fp12 => ({ c0, c1: Fp6.neg(c1) }),
568
+ // Sparse multiplication
569
+ mul014: ({ c0, c1 }, o0: Fp2, o1: Fp2, o4: Fp2) => {
570
+ let t0 = Fp6.mul01(c0, o0, o1);
571
+ let t1 = Fp6.mul1(c1, o4);
572
+ return {
573
+ c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0
574
+ // (c1 + c0) * [o0, o1+o4] - T0 - T1
575
+ c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1),
576
+ };
577
+ },
578
+ mul034: ({ c0, c1 }, o0: Fp2, o3: Fp2, o4: Fp2) => {
579
+ const a = Fp6.create({
580
+ c0: Fp2.mul(c0.c0, o0),
581
+ c1: Fp2.mul(c0.c1, o0),
582
+ c2: Fp2.mul(c0.c2, o0),
583
+ });
584
+ const b = Fp6.mul01(c1, o3, o4);
585
+ const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4);
586
+ return {
587
+ c0: Fp6.add(Fp6.mulByNonresidue(b), a),
588
+ c1: Fp6.sub(e, Fp6.add(a, b)),
589
+ };
590
+ },
591
+
592
+ // A cyclotomic group is a subgroup of Fp^n defined by
593
+ // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
594
+ // The result of any pairing is in a cyclotomic subgroup
595
+ // https://eprint.iacr.org/2009/565.pdf
596
+ _cyclotomicSquare: opts.Fp12cyclotomicSquare,
597
+ _cyclotomicExp: opts.Fp12cyclotomicExp,
598
+ // https://eprint.iacr.org/2010/354.pdf
599
+ // https://eprint.iacr.org/2009/565.pdf
600
+ finalExponentiate: opts.Fp12finalExponentiate,
601
+ };
602
+
603
+ return { Fp, Fp2, Fp6, Fp4Square, Fp12 };
604
+ }
@@ -27,6 +27,11 @@ export function abytes(item: unknown): void {
27
27
  if (!isBytes(item)) throw new Error('Uint8Array expected');
28
28
  }
29
29
 
30
+ export function abool(title: string, value: boolean): void {
31
+ if (typeof value !== 'boolean')
32
+ throw new Error(`${title} must be valid boolean, got "${value}".`);
33
+ }
34
+
30
35
  // Array where index 0xf0 (240) is mapped to string 'f0'
31
36
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>
32
37
  i.toString(16).padStart(2, '0')
@@ -174,6 +179,28 @@ export function utf8ToBytes(str: string): Uint8Array {
174
179
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
175
180
  }
176
181
 
182
+ // Is positive bigint
183
+ const isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;
184
+
185
+ export function inRange(n: bigint, min: bigint, max: bigint) {
186
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
187
+ }
188
+
189
+ /**
190
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
191
+ * @example
192
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
193
+ */
194
+ export function aInRange(title: string, n: bigint, min: bigint, max: bigint) {
195
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
196
+ // consider P=256n, min=0n, max=P
197
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
198
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
199
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
200
+ if (!inRange(n, min, max))
201
+ throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
202
+ }
203
+
177
204
  // Bit operations
178
205
 
179
206
  /**
@@ -317,3 +344,25 @@ export function validateObject<T extends Record<string, any>>(
317
344
  // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
318
345
  // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
319
346
  // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
347
+
348
+ /**
349
+ * throws not implemented error
350
+ */
351
+ export const notImplemented = () => {
352
+ throw new Error('not implemented');
353
+ };
354
+
355
+ /**
356
+ * Memoizes (caches) computation result.
357
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
358
+ */
359
+ export function memoized<T extends object, R, O extends any[]>(fn: (arg: T, ...args: O) => R) {
360
+ const map = new WeakMap<T, R>();
361
+ return (arg: T, ...args: O): R => {
362
+ const val = map.get(arg);
363
+ if (val !== undefined) return val;
364
+ const computed = fn(arg, ...args);
365
+ map.set(arg, computed);
366
+ return computed;
367
+ };
368
+ }