@noble/curves 0.6.4 → 0.7.1

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 (172) hide show
  1. package/README.md +486 -298
  2. package/{lib/_shortw_utils.d.ts → _shortw_utils.d.ts} +1 -1
  3. package/_shortw_utils.d.ts.map +1 -0
  4. package/{lib/_shortw_utils.js → _shortw_utils.js} +2 -0
  5. package/_shortw_utils.js.map +1 -0
  6. package/{lib/abstract → abstract}/bls.d.ts +4 -9
  7. package/abstract/bls.d.ts.map +1 -0
  8. package/{lib/abstract → abstract}/bls.js +13 -26
  9. package/abstract/bls.js.map +1 -0
  10. package/{lib/abstract → abstract}/curve.d.ts +1 -0
  11. package/abstract/curve.d.ts.map +1 -0
  12. package/{lib/abstract → abstract}/curve.js +1 -0
  13. package/abstract/curve.js.map +1 -0
  14. package/{lib/abstract → abstract}/edwards.d.ts +1 -0
  15. package/abstract/edwards.d.ts.map +1 -0
  16. package/{lib/abstract → abstract}/edwards.js +9 -15
  17. package/abstract/edwards.js.map +1 -0
  18. package/{lib/abstract → abstract}/hash-to-curve.d.ts +5 -5
  19. package/abstract/hash-to-curve.d.ts.map +1 -0
  20. package/{lib/abstract → abstract}/hash-to-curve.js +41 -38
  21. package/abstract/hash-to-curve.js.map +1 -0
  22. package/{lib/abstract → abstract}/modular.d.ts +1 -0
  23. package/abstract/modular.d.ts.map +1 -0
  24. package/{lib/abstract → abstract}/modular.js +2 -1
  25. package/abstract/modular.js.map +1 -0
  26. package/{lib/abstract → abstract}/montgomery.d.ts +4 -3
  27. package/abstract/montgomery.d.ts.map +1 -0
  28. package/{lib/abstract → abstract}/montgomery.js +12 -9
  29. package/abstract/montgomery.js.map +1 -0
  30. package/{lib/abstract → abstract}/poseidon.d.ts +1 -0
  31. package/abstract/poseidon.d.ts.map +1 -0
  32. package/{lib/abstract → abstract}/poseidon.js +1 -0
  33. package/abstract/poseidon.js.map +1 -0
  34. package/{lib/abstract → abstract}/utils.d.ts +12 -1
  35. package/abstract/utils.d.ts.map +1 -0
  36. package/{lib/abstract → abstract}/utils.js +96 -10
  37. package/abstract/utils.js.map +1 -0
  38. package/{lib/abstract → abstract}/weierstrass.d.ts +6 -6
  39. package/abstract/weierstrass.d.ts.map +1 -0
  40. package/{lib/abstract → abstract}/weierstrass.js +74 -115
  41. package/abstract/weierstrass.js.map +1 -0
  42. package/{lib/bls12-381.d.ts → bls12-381.d.ts} +1 -0
  43. package/bls12-381.d.ts.map +1 -0
  44. package/{lib/bls12-381.js → bls12-381.js} +41 -7
  45. package/bls12-381.js.map +1 -0
  46. package/{lib/bn.d.ts → bn.d.ts} +1 -0
  47. package/bn.d.ts.map +1 -0
  48. package/{lib/bn.js → bn.js} +1 -0
  49. package/bn.js.map +1 -0
  50. package/{lib/ed25519.d.ts → ed25519.d.ts} +2 -1
  51. package/ed25519.d.ts.map +1 -0
  52. package/{lib/ed25519.js → ed25519.js} +6 -5
  53. package/ed25519.js.map +1 -0
  54. package/{lib/ed448.d.ts → ed448.d.ts} +2 -1
  55. package/ed448.d.ts.map +1 -0
  56. package/{lib/ed448.js → ed448.js} +4 -3
  57. package/ed448.js.map +1 -0
  58. package/{lib/esm → esm}/_shortw_utils.js +2 -0
  59. package/esm/_shortw_utils.js.map +1 -0
  60. package/{lib/esm → esm}/abstract/bls.js +14 -27
  61. package/esm/abstract/bls.js.map +1 -0
  62. package/{lib/esm → esm}/abstract/curve.js +1 -0
  63. package/esm/abstract/curve.js.map +1 -0
  64. package/{lib/esm → esm}/abstract/edwards.js +9 -15
  65. package/esm/abstract/edwards.js.map +1 -0
  66. package/{lib/esm → esm}/abstract/hash-to-curve.js +40 -36
  67. package/esm/abstract/hash-to-curve.js.map +1 -0
  68. package/{lib/esm → esm}/abstract/modular.js +2 -1
  69. package/esm/abstract/modular.js.map +1 -0
  70. package/{lib/esm → esm}/abstract/montgomery.js +12 -9
  71. package/esm/abstract/montgomery.js.map +1 -0
  72. package/{lib/esm → esm}/abstract/poseidon.js +1 -0
  73. package/esm/abstract/poseidon.js.map +1 -0
  74. package/{lib/esm → esm}/abstract/utils.js +93 -9
  75. package/esm/abstract/utils.js.map +1 -0
  76. package/{lib/esm → esm}/abstract/weierstrass.js +74 -115
  77. package/esm/abstract/weierstrass.js.map +1 -0
  78. package/{lib/esm → esm}/bls12-381.js +41 -7
  79. package/esm/bls12-381.js.map +1 -0
  80. package/{lib/esm → esm}/bn.js +1 -0
  81. package/esm/bn.js.map +1 -0
  82. package/{lib/esm → esm}/ed25519.js +7 -6
  83. package/esm/ed25519.js.map +1 -0
  84. package/{lib/esm → esm}/ed448.js +4 -3
  85. package/esm/ed448.js.map +1 -0
  86. package/{lib → esm}/index.js +1 -0
  87. package/esm/index.js.map +1 -0
  88. package/{lib/esm → esm}/jubjub.js +1 -0
  89. package/esm/jubjub.js.map +1 -0
  90. package/{lib/esm → esm}/p192.js +1 -0
  91. package/esm/p192.js.map +1 -0
  92. package/{lib/esm → esm}/p224.js +1 -0
  93. package/esm/p224.js.map +1 -0
  94. package/{lib/esm → esm}/p256.js +2 -1
  95. package/esm/p256.js.map +1 -0
  96. package/{lib/esm → esm}/p384.js +2 -1
  97. package/esm/p384.js.map +1 -0
  98. package/{lib/esm → esm}/p521.js +2 -1
  99. package/esm/p521.js.map +1 -0
  100. package/{lib/esm → esm}/package.json +0 -0
  101. package/{lib/esm → esm}/pasta.js +1 -0
  102. package/esm/pasta.js.map +1 -0
  103. package/{lib/esm → esm}/secp256k1.js +51 -50
  104. package/esm/secp256k1.js.map +1 -0
  105. package/{lib/esm → esm}/stark.js +5 -4
  106. package/esm/stark.js.map +1 -0
  107. package/index.d.ts +1 -0
  108. package/index.d.ts.map +1 -0
  109. package/index.js +3 -0
  110. package/index.js.map +1 -0
  111. package/{lib/jubjub.d.ts → jubjub.d.ts} +1 -0
  112. package/jubjub.d.ts.map +1 -0
  113. package/{lib/jubjub.js → jubjub.js} +1 -0
  114. package/jubjub.js.map +1 -0
  115. package/{lib/p192.d.ts → p192.d.ts} +1 -2
  116. package/p192.d.ts.map +1 -0
  117. package/{lib/p192.js → p192.js} +1 -0
  118. package/p192.js.map +1 -0
  119. package/{lib/p224.d.ts → p224.d.ts} +1 -2
  120. package/p224.d.ts.map +1 -0
  121. package/{lib/p224.js → p224.js} +1 -0
  122. package/p224.js.map +1 -0
  123. package/{lib/p256.d.ts → p256.d.ts} +2 -3
  124. package/p256.d.ts.map +1 -0
  125. package/{lib/p256.js → p256.js} +2 -1
  126. package/p256.js.map +1 -0
  127. package/{lib/p384.d.ts → p384.d.ts} +2 -3
  128. package/p384.d.ts.map +1 -0
  129. package/{lib/p384.js → p384.js} +2 -1
  130. package/p384.js.map +1 -0
  131. package/{lib/p521.d.ts → p521.d.ts} +2 -3
  132. package/p521.d.ts.map +1 -0
  133. package/{lib/p521.js → p521.js} +2 -1
  134. package/p521.js.map +1 -0
  135. package/package.json +84 -79
  136. package/{lib/pasta.d.ts → pasta.d.ts} +1 -0
  137. package/pasta.d.ts.map +1 -0
  138. package/{lib/pasta.js → pasta.js} +1 -0
  139. package/pasta.js.map +1 -0
  140. package/{lib/secp256k1.d.ts → secp256k1.d.ts} +20 -6
  141. package/secp256k1.d.ts.map +1 -0
  142. package/{lib/secp256k1.js → secp256k1.js} +48 -47
  143. package/secp256k1.js.map +1 -0
  144. package/src/_shortw_utils.ts +20 -0
  145. package/src/abstract/bls.ts +376 -0
  146. package/src/abstract/curve.ts +199 -0
  147. package/src/abstract/edwards.ts +479 -0
  148. package/src/abstract/hash-to-curve.ts +220 -0
  149. package/src/abstract/modular.ts +417 -0
  150. package/src/abstract/montgomery.ts +186 -0
  151. package/src/abstract/poseidon.ts +119 -0
  152. package/src/abstract/utils.ts +246 -0
  153. package/src/abstract/weierstrass.ts +1177 -0
  154. package/src/bls12-381.ts +1274 -0
  155. package/src/bn.ts +21 -0
  156. package/src/ed25519.ts +428 -0
  157. package/src/ed448.ts +241 -0
  158. package/{lib/esm/index.js → src/index.ts} +0 -1
  159. package/src/jubjub.ts +58 -0
  160. package/src/p192.ts +25 -0
  161. package/src/p224.ts +25 -0
  162. package/src/p256.ts +53 -0
  163. package/src/p384.ts +57 -0
  164. package/src/p521.ts +57 -0
  165. package/src/pasta.ts +31 -0
  166. package/src/secp256k1.ts +270 -0
  167. package/src/stark.ts +356 -0
  168. package/{lib/stark.d.ts → stark.d.ts} +1 -1
  169. package/stark.d.ts.map +1 -0
  170. package/{lib/stark.js → stark.js} +5 -4
  171. package/stark.js.map +1 -0
  172. package/lib/index.d.ts +0 -0
@@ -0,0 +1,376 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ /**
3
+ * BLS (Barreto-Lynn-Scott) family of pairing-friendly curves.
4
+ * Implements BLS (Boneh-Lynn-Shacham) signatures.
5
+ * Consists of two curves: G1 and G2:
6
+ * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
7
+ * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
8
+ * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
9
+ * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
10
+ * Pairing is used to aggregate and verify signatures.
11
+ * We are using Fp for private keys (shorter) and Fp₂ for signatures (longer).
12
+ * Some projects may prefer to swap this relation, it is not supported for now.
13
+ */
14
+ import { AffinePoint } from './curve.js';
15
+ import { Field, hashToPrivateScalar } from './modular.js';
16
+ import { Hex, PrivKey, CHash, bitLen, bitGet, ensureBytes } from './utils.js';
17
+ import * as htf from './hash-to-curve.js';
18
+ import {
19
+ CurvePointsType,
20
+ ProjPointType as ProjPointType,
21
+ CurvePointsRes,
22
+ weierstrassPoints,
23
+ } from './weierstrass.js';
24
+
25
+ type Fp = bigint; // Can be different field?
26
+
27
+ export type SignatureCoder<Fp2> = {
28
+ decode(hex: Hex): ProjPointType<Fp2>;
29
+ encode(point: ProjPointType<Fp2>): Uint8Array;
30
+ };
31
+
32
+ export type CurveType<Fp, Fp2, Fp6, Fp12> = {
33
+ r: bigint;
34
+ G1: Omit<CurvePointsType<Fp>, 'n'> & {
35
+ mapToCurve: htf.MapToCurve<Fp>;
36
+ htfDefaults: htf.Opts;
37
+ };
38
+ G2: Omit<CurvePointsType<Fp2>, 'n'> & {
39
+ Signature: SignatureCoder<Fp2>;
40
+ mapToCurve: htf.MapToCurve<Fp2>;
41
+ htfDefaults: htf.Opts;
42
+ };
43
+ x: bigint;
44
+ Fp: Field<Fp>;
45
+ Fr: Field<bigint>;
46
+ Fp2: Field<Fp2> & {
47
+ reim: (num: Fp2) => { re: bigint; im: bigint };
48
+ multiplyByB: (num: Fp2) => Fp2;
49
+ frobeniusMap(num: Fp2, power: number): Fp2;
50
+ };
51
+ Fp6: Field<Fp6>;
52
+ Fp12: Field<Fp12> & {
53
+ frobeniusMap(num: Fp12, power: number): Fp12;
54
+ multiplyBy014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;
55
+ conjugate(num: Fp12): Fp12;
56
+ finalExponentiate(num: Fp12): Fp12;
57
+ };
58
+ htfDefaults: htf.Opts;
59
+ hash: CHash; // Because we need outputLen for DRBG
60
+ randomBytes: (bytesLength?: number) => Uint8Array;
61
+ };
62
+
63
+ export type CurveFn<Fp, Fp2, Fp6, Fp12> = {
64
+ CURVE: CurveType<Fp, Fp2, Fp6, Fp12>;
65
+ Fr: Field<bigint>;
66
+ Fp: Field<Fp>;
67
+ Fp2: Field<Fp2>;
68
+ Fp6: Field<Fp6>;
69
+ Fp12: Field<Fp12>;
70
+ G1: CurvePointsRes<Fp> & ReturnType<typeof htf.createHasher<Fp>>;
71
+ G2: CurvePointsRes<Fp2> & ReturnType<typeof htf.createHasher<Fp2>>;
72
+ Signature: SignatureCoder<Fp2>;
73
+ millerLoop: (ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]) => Fp12;
74
+ calcPairingPrecomputes: (p: AffinePoint<Fp2>) => [Fp2, Fp2, Fp2][];
75
+ pairing: (P: ProjPointType<Fp>, Q: ProjPointType<Fp2>, withFinalExponent?: boolean) => Fp12;
76
+ getPublicKey: (privateKey: PrivKey) => Uint8Array;
77
+ sign: {
78
+ (message: Hex, privateKey: PrivKey): Uint8Array;
79
+ (message: ProjPointType<Fp2>, privateKey: PrivKey): ProjPointType<Fp2>;
80
+ };
81
+ verify: (
82
+ signature: Hex | ProjPointType<Fp2>,
83
+ message: Hex | ProjPointType<Fp2>,
84
+ publicKey: Hex | ProjPointType<Fp>
85
+ ) => boolean;
86
+ aggregatePublicKeys: {
87
+ (publicKeys: Hex[]): Uint8Array;
88
+ (publicKeys: ProjPointType<Fp>[]): ProjPointType<Fp>;
89
+ };
90
+ aggregateSignatures: {
91
+ (signatures: Hex[]): Uint8Array;
92
+ (signatures: ProjPointType<Fp2>[]): ProjPointType<Fp2>;
93
+ };
94
+ verifyBatch: (
95
+ signature: Hex | ProjPointType<Fp2>,
96
+ messages: (Hex | ProjPointType<Fp2>)[],
97
+ publicKeys: (Hex | ProjPointType<Fp>)[]
98
+ ) => boolean;
99
+ utils: {
100
+ randomPrivateKey: () => Uint8Array;
101
+ };
102
+ };
103
+
104
+ export function bls<Fp2, Fp6, Fp12>(
105
+ CURVE: CurveType<Fp, Fp2, Fp6, Fp12>
106
+ ): CurveFn<Fp, Fp2, Fp6, Fp12> {
107
+ // Fields looks pretty specific for curve, so for now we need to pass them with opts
108
+ const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE;
109
+ const BLS_X_LEN = bitLen(CURVE.x);
110
+ const groupLen = 32; // TODO: calculate; hardcoded for now
111
+
112
+ // Pre-compute coefficients for sparse multiplication
113
+ // Point addition and point double calculations is reused for coefficients
114
+ function calcPairingPrecomputes(p: AffinePoint<Fp2>) {
115
+ const { x, y } = p;
116
+ // prettier-ignore
117
+ const Qx = x, Qy = y, Qz = Fp2.ONE;
118
+ // prettier-ignore
119
+ let Rx = Qx, Ry = Qy, Rz = Qz;
120
+ let ell_coeff: [Fp2, Fp2, Fp2][] = [];
121
+ for (let i = BLS_X_LEN - 2; i >= 0; i--) {
122
+ // Double
123
+ let t0 = Fp2.sqr(Ry); // Ry²
124
+ let t1 = Fp2.sqr(Rz); // Rz²
125
+ let t2 = Fp2.multiplyByB(Fp2.mul(t1, 3n)); // 3 * T1 * B
126
+ let t3 = Fp2.mul(t2, 3n); // 3 * T2
127
+ let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0
128
+ ell_coeff.push([
129
+ Fp2.sub(t2, t0), // T2 - T0
130
+ Fp2.mul(Fp2.sqr(Rx), 3n), // 3 * Rx²
131
+ Fp2.neg(t4), // -T4
132
+ ]);
133
+ Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), 2n); // ((T0 - T3) * Rx * Ry) / 2
134
+ Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), 2n)), Fp2.mul(Fp2.sqr(t2), 3n)); // ((T0 + T3) / 2)² - 3 * T2²
135
+ Rz = Fp2.mul(t0, t4); // T0 * T4
136
+ if (bitGet(CURVE.x, i)) {
137
+ // Addition
138
+ let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz
139
+ let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz
140
+ ell_coeff.push([
141
+ Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy
142
+ Fp2.neg(t0), // -T0
143
+ t1, // T1
144
+ ]);
145
+ let t2 = Fp2.sqr(t1); // T1²
146
+ let t3 = Fp2.mul(t2, t1); // T2 * T1
147
+ let t4 = Fp2.mul(t2, Rx); // T2 * Rx
148
+ let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, 2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz
149
+ Rx = Fp2.mul(t1, t5); // T1 * T5
150
+ Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry
151
+ Rz = Fp2.mul(Rz, t3); // Rz * T3
152
+ }
153
+ }
154
+ return ell_coeff;
155
+ }
156
+
157
+ function millerLoop(ell: [Fp2, Fp2, Fp2][], g1: [Fp, Fp]): Fp12 {
158
+ const { x } = CURVE;
159
+ const Px = g1[0];
160
+ const Py = g1[1];
161
+ let f12 = Fp12.ONE;
162
+ for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) {
163
+ const E = ell[j];
164
+ f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py));
165
+ if (bitGet(x, i)) {
166
+ j += 1;
167
+ const F = ell[j];
168
+ f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py));
169
+ }
170
+ if (i !== 0) f12 = Fp12.sqr(f12);
171
+ }
172
+ return Fp12.conjugate(f12);
173
+ }
174
+
175
+ const utils = {
176
+ randomPrivateKey: (): Uint8Array => {
177
+ return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.r));
178
+ },
179
+ };
180
+
181
+ // Point on G1 curve: (x, y)
182
+ const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 });
183
+ const G1 = Object.assign(
184
+ G1_,
185
+ htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
186
+ ...CURVE.htfDefaults,
187
+ ...CURVE.G1.htfDefaults,
188
+ })
189
+ );
190
+
191
+ // Sparse multiplication against precomputed coefficients
192
+ // TODO: replace with weakmap?
193
+ type withPairingPrecomputes = { _PPRECOMPUTES: [Fp2, Fp2, Fp2][] | undefined };
194
+ function pairingPrecomputes(point: G2): [Fp2, Fp2, Fp2][] {
195
+ const p = point as G2 & withPairingPrecomputes;
196
+ if (p._PPRECOMPUTES) return p._PPRECOMPUTES;
197
+ p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine());
198
+ return p._PPRECOMPUTES;
199
+ }
200
+
201
+ // TODO: export
202
+ // function clearPairingPrecomputes(point: G2) {
203
+ // const p = point as G2 & withPairingPrecomputes;
204
+ // p._PPRECOMPUTES = undefined;
205
+ // }
206
+
207
+ // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
208
+ const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 });
209
+ const G2 = Object.assign(
210
+ G2_,
211
+ htf.createHasher(G2_.ProjectivePoint as htf.H2CPointConstructor<Fp2>, CURVE.G2.mapToCurve, {
212
+ ...CURVE.htfDefaults,
213
+ ...CURVE.G2.htfDefaults,
214
+ })
215
+ );
216
+
217
+ const { Signature } = CURVE.G2;
218
+
219
+ // Calculates bilinear pairing
220
+ function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 {
221
+ if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO))
222
+ throw new Error('pairing is not available for ZERO point');
223
+ Q.assertValidity();
224
+ P.assertValidity();
225
+ // Performance: 9ms for millerLoop and ~14ms for exp.
226
+ const Qa = Q.toAffine();
227
+ const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]);
228
+ return withFinalExponent ? Fp12.finalExponentiate(looped) : looped;
229
+ }
230
+ type G1 = typeof G1.ProjectivePoint.BASE;
231
+ type G2 = typeof G2.ProjectivePoint.BASE;
232
+
233
+ type G1Hex = Hex | G1;
234
+ type G2Hex = Hex | G2;
235
+ function normP1(point: G1Hex): G1 {
236
+ return point instanceof G1.ProjectivePoint ? (point as G1) : G1.ProjectivePoint.fromHex(point);
237
+ }
238
+ function normP2(point: G2Hex): G2 {
239
+ return point instanceof G2.ProjectivePoint ? point : Signature.decode(point);
240
+ }
241
+ function normP2Hash(point: G2Hex, htfOpts?: htf.htfBasicOpts): G2 {
242
+ return point instanceof G2.ProjectivePoint
243
+ ? point
244
+ : (G2.hashToCurve(ensureBytes('point', point), htfOpts) as G2);
245
+ }
246
+
247
+ // Multiplies generator by private key.
248
+ // P = pk x G
249
+ function getPublicKey(privateKey: PrivKey): Uint8Array {
250
+ return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
251
+ }
252
+
253
+ // Executes `hashToCurve` on the message and then multiplies the result by private key.
254
+ // S = pk x H(m)
255
+ function sign(message: Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array;
256
+ function sign(message: G2, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): G2;
257
+ function sign(message: G2Hex, privateKey: PrivKey, htfOpts?: htf.htfBasicOpts): Uint8Array | G2 {
258
+ const msgPoint = normP2Hash(message, htfOpts);
259
+ msgPoint.assertValidity();
260
+ const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
261
+ if (message instanceof G2.ProjectivePoint) return sigPoint;
262
+ return Signature.encode(sigPoint);
263
+ }
264
+
265
+ // Checks if pairing of public key & hash is equal to pairing of generator & signature.
266
+ // e(P, H(m)) == e(G, S)
267
+ function verify(
268
+ signature: G2Hex,
269
+ message: G2Hex,
270
+ publicKey: G1Hex,
271
+ htfOpts?: htf.htfBasicOpts
272
+ ): boolean {
273
+ const P = normP1(publicKey);
274
+ const Hm = normP2Hash(message, htfOpts);
275
+ const G = G1.ProjectivePoint.BASE;
276
+ const S = normP2(signature);
277
+ // Instead of doing 2 exponentiations, we use property of billinear maps
278
+ // and do one exp after multiplying 2 points.
279
+ const ePHm = pairing(P.negate(), Hm, false);
280
+ const eGS = pairing(G, S, false);
281
+ const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm));
282
+ return Fp12.eql(exp, Fp12.ONE);
283
+ }
284
+
285
+ // Adds a bunch of public key points together.
286
+ // pk1 + pk2 + pk3 = pkA
287
+ function aggregatePublicKeys(publicKeys: Hex[]): Uint8Array;
288
+ function aggregatePublicKeys(publicKeys: G1[]): G1;
289
+ function aggregatePublicKeys(publicKeys: G1Hex[]): Uint8Array | G1 {
290
+ if (!publicKeys.length) throw new Error('Expected non-empty array');
291
+ const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
292
+ const aggAffine = agg; //.toAffine();
293
+ if (publicKeys[0] instanceof G1.ProjectivePoint) {
294
+ aggAffine.assertValidity();
295
+ return aggAffine;
296
+ }
297
+ // toRawBytes ensures point validity
298
+ return aggAffine.toRawBytes(true);
299
+ }
300
+
301
+ // Adds a bunch of signature points together.
302
+ function aggregateSignatures(signatures: Hex[]): Uint8Array;
303
+ function aggregateSignatures(signatures: G2[]): G2;
304
+ function aggregateSignatures(signatures: G2Hex[]): Uint8Array | G2 {
305
+ if (!signatures.length) throw new Error('Expected non-empty array');
306
+ const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO);
307
+ const aggAffine = agg; //.toAffine();
308
+ if (signatures[0] instanceof G2.ProjectivePoint) {
309
+ aggAffine.assertValidity();
310
+ return aggAffine;
311
+ }
312
+ return Signature.encode(aggAffine);
313
+ }
314
+
315
+ // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
316
+ // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
317
+ function verifyBatch(
318
+ signature: G2Hex,
319
+ messages: G2Hex[],
320
+ publicKeys: G1Hex[],
321
+ htfOpts?: htf.htfBasicOpts
322
+ ): boolean {
323
+ // @ts-ignore
324
+ // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex));
325
+
326
+ if (!messages.length) throw new Error('Expected non-empty messages array');
327
+ if (publicKeys.length !== messages.length)
328
+ throw new Error('Pubkey count should equal msg count');
329
+ const sig = normP2(signature);
330
+ const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
331
+ const nPublicKeys = publicKeys.map(normP1);
332
+ try {
333
+ const paired = [];
334
+ for (const message of new Set(nMessages)) {
335
+ const groupPublicKey = nMessages.reduce(
336
+ (groupPublicKey, subMessage, i) =>
337
+ subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey,
338
+ G1.ProjectivePoint.ZERO
339
+ );
340
+ // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message);
341
+ // Possible to batch pairing for same msg with different groupPublicKey here
342
+ paired.push(pairing(groupPublicKey, message, false));
343
+ }
344
+ paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false));
345
+ const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE);
346
+ const exp = Fp12.finalExponentiate(product);
347
+ return Fp12.eql(exp, Fp12.ONE);
348
+ } catch {
349
+ return false;
350
+ }
351
+ }
352
+
353
+ G1.ProjectivePoint.BASE._setWindowSize(4);
354
+
355
+ return {
356
+ CURVE,
357
+ Fr,
358
+ Fp,
359
+ Fp2,
360
+ Fp6,
361
+ Fp12,
362
+ G1,
363
+ G2,
364
+ Signature,
365
+ millerLoop,
366
+ calcPairingPrecomputes,
367
+ pairing,
368
+ getPublicKey,
369
+ sign,
370
+ verify,
371
+ aggregatePublicKeys,
372
+ aggregateSignatures,
373
+ verifyBatch,
374
+ utils,
375
+ };
376
+ }
@@ -0,0 +1,199 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ // Abelian group utilities
3
+ import { Field, validateField, nLength } from './modular.js';
4
+ import { validateObject } from './utils.js';
5
+ const _0n = BigInt(0);
6
+ const _1n = BigInt(1);
7
+
8
+ export type AffinePoint<T> = {
9
+ x: T;
10
+ y: T;
11
+ } & { z?: never; t?: never };
12
+
13
+ export interface Group<T extends Group<T>> {
14
+ double(): T;
15
+ negate(): T;
16
+ add(other: T): T;
17
+ subtract(other: T): T;
18
+ equals(other: T): boolean;
19
+ multiply(scalar: bigint): T;
20
+ }
21
+
22
+ export type GroupConstructor<T> = {
23
+ BASE: T;
24
+ ZERO: T;
25
+ };
26
+ export type Mapper<T> = (i: T[]) => T[];
27
+
28
+ // Elliptic curve multiplication of Point by scalar. Fragile.
29
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
30
+ // Creates precomputation tables for fast multiplication:
31
+ // - private scalar is split by fixed size windows of W bits
32
+ // - every window point is collected from window's table & added to accumulator
33
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
34
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
35
+ // - +1 window is neccessary for wNAF
36
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
37
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
38
+ // windows to be in different memory locations
39
+ export function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {
40
+ const constTimeNegate = (condition: boolean, item: T): T => {
41
+ const neg = item.negate();
42
+ return condition ? neg : item;
43
+ };
44
+ const opts = (W: number) => {
45
+ const windows = Math.ceil(bits / W) + 1; // +1, because
46
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
47
+ return { windows, windowSize };
48
+ };
49
+ return {
50
+ constTimeNegate,
51
+ // non-const time multiplication ladder
52
+ unsafeLadder(elm: T, n: bigint) {
53
+ let p = c.ZERO;
54
+ let d: T = elm;
55
+ while (n > _0n) {
56
+ if (n & _1n) p = p.add(d);
57
+ d = d.double();
58
+ n >>= _1n;
59
+ }
60
+ return p;
61
+ },
62
+
63
+ /**
64
+ * Creates a wNAF precomputation window. Used for caching.
65
+ * Default window size is set by `utils.precompute()` and is equal to 8.
66
+ * Number of precomputed points depends on the curve size:
67
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
68
+ * - 𝑊 is the window size
69
+ * - 𝑛 is the bitlength of the curve order.
70
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
71
+ * @returns precomputed point tables flattened to a single array
72
+ */
73
+ precomputeWindow(elm: T, W: number): Group<T>[] {
74
+ const { windows, windowSize } = opts(W);
75
+ const points: T[] = [];
76
+ let p: T = elm;
77
+ let base = p;
78
+ for (let window = 0; window < windows; window++) {
79
+ base = p;
80
+ points.push(base);
81
+ // =1, because we skip zero
82
+ for (let i = 1; i < windowSize; i++) {
83
+ base = base.add(p);
84
+ points.push(base);
85
+ }
86
+ p = base.double();
87
+ }
88
+ return points;
89
+ },
90
+
91
+ /**
92
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
93
+ * @param W window size
94
+ * @param precomputes precomputed tables
95
+ * @param n scalar (we don't check here, but should be less than curve order)
96
+ * @returns real and fake (for const-time) points
97
+ */
98
+ wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {
99
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
100
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
101
+ const { windows, windowSize } = opts(W);
102
+
103
+ let p = c.ZERO;
104
+ let f = c.BASE;
105
+
106
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
107
+ const maxNumber = 2 ** W;
108
+ const shiftBy = BigInt(W);
109
+
110
+ for (let window = 0; window < windows; window++) {
111
+ const offset = window * windowSize;
112
+ // Extract W bits.
113
+ let wbits = Number(n & mask);
114
+
115
+ // Shift number by W bits.
116
+ n >>= shiftBy;
117
+
118
+ // If the bits are bigger than max size, we'll split those.
119
+ // +224 => 256 - 32
120
+ if (wbits > windowSize) {
121
+ wbits -= maxNumber;
122
+ n += _1n;
123
+ }
124
+
125
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
126
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
127
+ // there is negate now: it is possible that negated element from low value
128
+ // would be the same as high element, which will create carry into next window.
129
+ // It's not obvious how this can fail, but still worth investigating later.
130
+
131
+ // Check if we're onto Zero point.
132
+ // Add random point inside current window to f.
133
+ const offset1 = offset;
134
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
135
+ const cond1 = window % 2 !== 0;
136
+ const cond2 = wbits < 0;
137
+ if (wbits === 0) {
138
+ // The most important part for const-time getPublicKey
139
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
140
+ } else {
141
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
142
+ }
143
+ }
144
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
145
+ // Even if the variable is still unused, there are some checks which will
146
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
147
+ // At this point there is a way to F be infinity-point even if p is not,
148
+ // which makes it less const-time: around 1 bigint multiply.
149
+ return { p, f };
150
+ },
151
+
152
+ wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {
153
+ // @ts-ignore
154
+ const W: number = P._WINDOW_SIZE || 1;
155
+ // Calculate precomputes on a first run, reuse them after
156
+ let comp = precomputesMap.get(P);
157
+ if (!comp) {
158
+ comp = this.precomputeWindow(P, W) as T[];
159
+ if (W !== 1) {
160
+ precomputesMap.set(P, transform(comp));
161
+ }
162
+ }
163
+ return this.wNAF(W, comp, n);
164
+ },
165
+ };
166
+ }
167
+
168
+ // Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.
169
+ // Though generator can be different (Fp2 / Fp6 for BLS).
170
+ export type BasicCurve<T> = {
171
+ Fp: Field<T>; // Field over which we'll do calculations (Fp)
172
+ n: bigint; // Curve order, total count of valid points in the field
173
+ nBitLength?: number; // bit length of curve order
174
+ nByteLength?: number; // byte length of curve order
175
+ h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation
176
+ hEff?: bigint; // Number to multiply to clear cofactor
177
+ Gx: T; // base point X coordinate
178
+ Gy: T; // base point Y coordinate
179
+ allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey
180
+ };
181
+
182
+ export function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {
183
+ validateField(curve.Fp);
184
+ validateObject(
185
+ curve,
186
+ {
187
+ n: 'bigint',
188
+ h: 'bigint',
189
+ Gx: 'field',
190
+ Gy: 'field',
191
+ },
192
+ {
193
+ nBitLength: 'isSafeInteger',
194
+ nByteLength: 'isSafeInteger',
195
+ }
196
+ );
197
+ // Set defaults
198
+ return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve } as const);
199
+ }