@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,417 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ // Utilities for modular arithmetics and finite fields
3
+ import {
4
+ bitMask,
5
+ numberToBytesBE,
6
+ numberToBytesLE,
7
+ bytesToNumberBE,
8
+ bytesToNumberLE,
9
+ ensureBytes,
10
+ validateObject,
11
+ } from './utils.js';
12
+ // prettier-ignore
13
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
14
+ // prettier-ignore
15
+ const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
16
+ // prettier-ignore
17
+ const _9n = BigInt(9), _16n = BigInt(16);
18
+
19
+ // Calculates a modulo b
20
+ export function mod(a: bigint, b: bigint): bigint {
21
+ const result = a % b;
22
+ return result >= _0n ? result : b + result;
23
+ }
24
+ /**
25
+ * Efficiently exponentiate num to power and do modular division.
26
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
27
+ * @example
28
+ * powMod(2n, 6n, 11n) // 64n % 11n == 9n
29
+ */
30
+ // TODO: use field version && remove
31
+ export function pow(num: bigint, power: bigint, modulo: bigint): bigint {
32
+ if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');
33
+ if (modulo === _1n) return _0n;
34
+ let res = _1n;
35
+ while (power > _0n) {
36
+ if (power & _1n) res = (res * num) % modulo;
37
+ num = (num * num) % modulo;
38
+ power >>= _1n;
39
+ }
40
+ return res;
41
+ }
42
+
43
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
44
+ export function pow2(x: bigint, power: bigint, modulo: bigint): bigint {
45
+ let res = x;
46
+ while (power-- > _0n) {
47
+ res *= res;
48
+ res %= modulo;
49
+ }
50
+ return res;
51
+ }
52
+
53
+ // Inverses number over modulo
54
+ export function invert(number: bigint, modulo: bigint): bigint {
55
+ if (number === _0n || modulo <= _0n) {
56
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
57
+ }
58
+ // Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
59
+ let a = mod(number, modulo);
60
+ let b = modulo;
61
+ // prettier-ignore
62
+ let x = _0n, y = _1n, u = _1n, v = _0n;
63
+ while (a !== _0n) {
64
+ // JIT applies optimization if those two lines follow each other
65
+ const q = b / a;
66
+ const r = b % a;
67
+ const m = x - u * q;
68
+ const n = y - v * q;
69
+ // prettier-ignore
70
+ b = a, a = r, x = u, y = v, u = m, v = n;
71
+ }
72
+ const gcd = b;
73
+ if (gcd !== _1n) throw new Error('invert: does not exist');
74
+ return mod(x, modulo);
75
+ }
76
+
77
+ // Tonelli-Shanks algorithm
78
+ // Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12)
79
+ // Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks
80
+ export function tonelliShanks(P: bigint) {
81
+ // Legendre constant: used to calculate Legendre symbol (a | p),
82
+ // which denotes the value of a^((p-1)/2) (mod p).
83
+ // (a | p) ≡ 1 if a is a square (mod p)
84
+ // (a | p) ≡ -1 if a is not a square (mod p)
85
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
86
+ const legendreC = (P - _1n) / _2n;
87
+
88
+ let Q: bigint, S: number, Z: bigint;
89
+ // Step 1: By factoring out powers of 2 from p - 1,
90
+ // find q and s such that p - 1 = q*(2^s) with q odd
91
+ for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);
92
+
93
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
94
+ for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);
95
+
96
+ // Fast-path
97
+ if (S === 1) {
98
+ const p1div4 = (P + _1n) / _4n;
99
+ return function tonelliFast<T>(Fp: Field<T>, n: T) {
100
+ const root = Fp.pow(n, p1div4);
101
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');
102
+ return root;
103
+ };
104
+ }
105
+
106
+ // Slow-path
107
+ const Q1div2 = (Q + _1n) / _2n;
108
+ return function tonelliSlow<T>(Fp: Field<T>, n: T): T {
109
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
110
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');
111
+ let r = S;
112
+ // TODO: will fail at Fp2/etc
113
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
114
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
115
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
116
+
117
+ while (!Fp.eql(b, Fp.ONE)) {
118
+ if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
119
+ // Find m such b^(2^m)==1
120
+ let m = 1;
121
+ for (let t2 = Fp.sqr(b); m < r; m++) {
122
+ if (Fp.eql(t2, Fp.ONE)) break;
123
+ t2 = Fp.sqr(t2); // t2 *= t2
124
+ }
125
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
126
+ const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
127
+ g = Fp.sqr(ge); // g = ge * ge
128
+ x = Fp.mul(x, ge); // x *= ge
129
+ b = Fp.mul(b, g); // b *= g
130
+ r = m;
131
+ }
132
+ return x;
133
+ };
134
+ }
135
+
136
+ export function FpSqrt(P: bigint) {
137
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
138
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
139
+
140
+ // P ≡ 3 (mod 4)
141
+ // √n = n^((P+1)/4)
142
+ if (P % _4n === _3n) {
143
+ // Not all roots possible!
144
+ // const ORDER =
145
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
146
+ // const NUM = 72057594037927816n;
147
+ const p1div4 = (P + _1n) / _4n;
148
+ return function sqrt3mod4<T>(Fp: Field<T>, n: T) {
149
+ const root = Fp.pow(n, p1div4);
150
+ // Throw if root**2 != n
151
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');
152
+ return root;
153
+ };
154
+ }
155
+
156
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
157
+ if (P % _8n === _5n) {
158
+ const c1 = (P - _5n) / _8n;
159
+ return function sqrt5mod8<T>(Fp: Field<T>, n: T) {
160
+ const n2 = Fp.mul(n, _2n);
161
+ const v = Fp.pow(n2, c1);
162
+ const nv = Fp.mul(n, v);
163
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
164
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
165
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');
166
+ return root;
167
+ };
168
+ }
169
+
170
+ // P ≡ 9 (mod 16)
171
+ if (P % _16n === _9n) {
172
+ // NOTE: tonelli is too slow for bls-Fp2 calculations even on start
173
+ // Means we cannot use sqrt for constants at all!
174
+ //
175
+ // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
176
+ // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
177
+ // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
178
+ // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
179
+ // sqrt = (x) => {
180
+ // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
181
+ // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
182
+ // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
183
+ // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
184
+ // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
185
+ // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
186
+ // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
187
+ // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
188
+ // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
189
+ // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
190
+ // }
191
+ }
192
+
193
+ // Other cases: Tonelli-Shanks algorithm
194
+ return tonelliShanks(P);
195
+ }
196
+
197
+ // Little-endian check for first LE bit (last BE bit);
198
+ export const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;
199
+
200
+ // Currently completly inconsistent naming:
201
+ // - readable: add, mul, sqr, sqrt, inv, div, pow, eq, sub
202
+ // - unreadable mess: addition, multiply, square, squareRoot, inversion, divide, power, equals, subtract
203
+
204
+ // Field is not always over prime, Fp2 for example has ORDER(q)=p^m
205
+ export interface Field<T> {
206
+ ORDER: bigint;
207
+ BYTES: number;
208
+ BITS: number;
209
+ MASK: bigint;
210
+ ZERO: T;
211
+ ONE: T;
212
+ // 1-arg
213
+ create: (num: T) => T;
214
+ isValid: (num: T) => boolean;
215
+ is0: (num: T) => boolean;
216
+ neg(num: T): T;
217
+ inv(num: T): T;
218
+ sqrt(num: T): T;
219
+ sqr(num: T): T;
220
+ // 2-args
221
+ eql(lhs: T, rhs: T): boolean;
222
+ add(lhs: T, rhs: T): T;
223
+ sub(lhs: T, rhs: T): T;
224
+ mul(lhs: T, rhs: T | bigint): T;
225
+ pow(lhs: T, power: bigint): T;
226
+ div(lhs: T, rhs: T | bigint): T;
227
+ // N for NonNormalized (for now)
228
+ addN(lhs: T, rhs: T): T;
229
+ subN(lhs: T, rhs: T): T;
230
+ mulN(lhs: T, rhs: T | bigint): T;
231
+ sqrN(num: T): T;
232
+
233
+ // Optional
234
+ // Should be same as sgn0 function in https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/
235
+ // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.
236
+ isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2
237
+ // legendre?(num: T): T;
238
+ pow(lhs: T, power: bigint): T;
239
+ invertBatch: (lst: T[]) => T[];
240
+ toBytes(num: T): Uint8Array;
241
+ fromBytes(bytes: Uint8Array): T;
242
+ // If c is False, CMOV returns a, otherwise it returns b.
243
+ cmov(a: T, b: T, c: boolean): T;
244
+ }
245
+ // prettier-ignore
246
+ const FIELD_FIELDS = [
247
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
248
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
249
+ 'addN', 'subN', 'mulN', 'sqrN'
250
+ ] as const;
251
+ export function validateField<T>(field: Field<T>) {
252
+ const initial = {
253
+ ORDER: 'bigint',
254
+ MASK: 'bigint',
255
+ BYTES: 'isSafeInteger',
256
+ BITS: 'isSafeInteger',
257
+ } as Record<string, string>;
258
+ const opts = FIELD_FIELDS.reduce((map, val: string) => {
259
+ map[val] = 'function';
260
+ return map;
261
+ }, initial);
262
+ return validateObject(field, opts);
263
+ }
264
+
265
+ // Generic field functions
266
+ export function FpPow<T>(f: Field<T>, num: T, power: bigint): T {
267
+ // Should have same speed as pow for bigints
268
+ // TODO: benchmark!
269
+ if (power < _0n) throw new Error('Expected power > 0');
270
+ if (power === _0n) return f.ONE;
271
+ if (power === _1n) return num;
272
+ let p = f.ONE;
273
+ let d = num;
274
+ while (power > _0n) {
275
+ if (power & _1n) p = f.mul(p, d);
276
+ d = f.sqr(d);
277
+ power >>= 1n;
278
+ }
279
+ return p;
280
+ }
281
+
282
+ export function FpInvertBatch<T>(f: Field<T>, nums: T[]): T[] {
283
+ const tmp = new Array(nums.length);
284
+ // Walk from first to last, multiply them by each other MOD p
285
+ const lastMultiplied = nums.reduce((acc, num, i) => {
286
+ if (f.is0(num)) return acc;
287
+ tmp[i] = acc;
288
+ return f.mul(acc, num);
289
+ }, f.ONE);
290
+ // Invert last element
291
+ const inverted = f.inv(lastMultiplied);
292
+ // Walk from last to first, multiply them by inverted each other MOD p
293
+ nums.reduceRight((acc, num, i) => {
294
+ if (f.is0(num)) return acc;
295
+ tmp[i] = f.mul(acc, tmp[i]);
296
+ return f.mul(acc, num);
297
+ }, inverted);
298
+ return tmp;
299
+ }
300
+
301
+ export function FpDiv<T>(f: Field<T>, lhs: T, rhs: T | bigint): T {
302
+ return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
303
+ }
304
+
305
+ // This function returns True whenever the value x is a square in the field F.
306
+ export function FpIsSquare<T>(f: Field<T>) {
307
+ const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
308
+ return (x: T): boolean => {
309
+ const p = f.pow(x, legendreConst);
310
+ return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
311
+ };
312
+ }
313
+
314
+ // CURVE.n lengths
315
+ export function nLength(n: bigint, nBitLength?: number) {
316
+ // Bit size, byte size of CURVE.n
317
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
318
+ const nByteLength = Math.ceil(_nBitLength / 8);
319
+ return { nBitLength: _nBitLength, nByteLength };
320
+ }
321
+
322
+ // NOTE: very fragile, always bench. Major performance points:
323
+ // - NonNormalized ops
324
+ // - Object.freeze
325
+ // - same shape of object (don't add/remove keys)
326
+ type FpField = Field<bigint> & Required<Pick<Field<bigint>, 'isOdd'>>;
327
+ export function Fp(
328
+ ORDER: bigint,
329
+ bitLen?: number,
330
+ isLE = false,
331
+ redef: Partial<Field<bigint>> = {}
332
+ ): Readonly<FpField> {
333
+ if (ORDER <= _0n) throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
334
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
335
+ if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');
336
+ const sqrtP = FpSqrt(ORDER);
337
+ const f: Readonly<FpField> = Object.freeze({
338
+ ORDER,
339
+ BITS,
340
+ BYTES,
341
+ MASK: bitMask(BITS),
342
+ ZERO: _0n,
343
+ ONE: _1n,
344
+ create: (num) => mod(num, ORDER),
345
+ isValid: (num) => {
346
+ if (typeof num !== 'bigint')
347
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
348
+ return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
349
+ },
350
+ is0: (num) => num === _0n,
351
+ isOdd: (num) => (num & _1n) === _1n,
352
+ neg: (num) => mod(-num, ORDER),
353
+ eql: (lhs, rhs) => lhs === rhs,
354
+
355
+ sqr: (num) => mod(num * num, ORDER),
356
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
357
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
358
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
359
+ pow: (num, power) => FpPow(f, num, power),
360
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
361
+
362
+ // Same as above, but doesn't normalize
363
+ sqrN: (num) => num * num,
364
+ addN: (lhs, rhs) => lhs + rhs,
365
+ subN: (lhs, rhs) => lhs - rhs,
366
+ mulN: (lhs, rhs) => lhs * rhs,
367
+
368
+ inv: (num) => invert(num, ORDER),
369
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
370
+ invertBatch: (lst) => FpInvertBatch(f, lst),
371
+ // TODO: do we really need constant cmov?
372
+ // We don't have const-time bigints anyway, so probably will be not very useful
373
+ cmov: (a, b, c) => (c ? b : a),
374
+ toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
375
+ fromBytes: (bytes) => {
376
+ if (bytes.length !== BYTES)
377
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
378
+ return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
379
+ },
380
+ } as FpField);
381
+ return Object.freeze(f);
382
+ }
383
+
384
+ export function FpSqrtOdd<T>(Fp: Field<T>, elm: T) {
385
+ if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);
386
+ const root = Fp.sqrt(elm);
387
+ return Fp.isOdd(root) ? root : Fp.neg(root);
388
+ }
389
+
390
+ export function FpSqrtEven<T>(Fp: Field<T>, elm: T) {
391
+ if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);
392
+ const root = Fp.sqrt(elm);
393
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
394
+ }
395
+
396
+ /**
397
+ * FIPS 186 B.4.1-compliant "constant-time" private key generation utility.
398
+ * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF
399
+ * and convert them into private scalar, with the modulo bias being neglible.
400
+ * Needs at least 40 bytes of input for 32-byte private key.
401
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
402
+ * @param hash hash output from SHA3 or a similar function
403
+ * @returns valid private scalar
404
+ */
405
+ export function hashToPrivateScalar(
406
+ hash: string | Uint8Array,
407
+ groupOrder: bigint,
408
+ isLE = false
409
+ ): bigint {
410
+ hash = ensureBytes('privateHash', hash);
411
+ const hashLen = hash.length;
412
+ const minLen = nLength(groupOrder).nByteLength + 8;
413
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024)
414
+ throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
415
+ const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
416
+ return mod(num, groupOrder - _1n) + _1n;
417
+ }
@@ -0,0 +1,186 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ import { mod, pow } from './modular.js';
3
+ import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';
4
+
5
+ const _0n = BigInt(0);
6
+ const _1n = BigInt(1);
7
+ type Hex = string | Uint8Array;
8
+
9
+ export type CurveType = {
10
+ P: bigint; // finite field prime
11
+ nByteLength: number;
12
+ adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;
13
+ domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
14
+ a: bigint;
15
+ montgomeryBits: number;
16
+ powPminus2?: (x: bigint) => bigint;
17
+ xyToU?: (x: bigint, y: bigint) => bigint;
18
+ Gu: bigint;
19
+ };
20
+ export type CurveFn = {
21
+ scalarMult: (scalar: Hex, u: Hex) => Uint8Array;
22
+ scalarMultBase: (scalar: Hex) => Uint8Array;
23
+ getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;
24
+ getPublicKey: (privateKey: Hex) => Uint8Array;
25
+ GuBytes: Uint8Array;
26
+ };
27
+
28
+ function validateOpts(curve: CurveType) {
29
+ validateObject(
30
+ curve,
31
+ {
32
+ a: 'bigint',
33
+ },
34
+ {
35
+ montgomeryBits: 'isSafeInteger',
36
+ nByteLength: 'isSafeInteger',
37
+ adjustScalarBytes: 'function',
38
+ domain: 'function',
39
+ powPminus2: 'function',
40
+ Gu: 'bigint',
41
+ }
42
+ );
43
+ // Set defaults
44
+ return Object.freeze({ ...curve } as const);
45
+ }
46
+
47
+ // NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)
48
+ // Uses only one coordinate instead of two
49
+ export function montgomery(curveDef: CurveType): CurveFn {
50
+ const CURVE = validateOpts(curveDef);
51
+ const { P } = CURVE;
52
+ const modP = (n: bigint) => mod(n, P);
53
+ const montgomeryBits = CURVE.montgomeryBits;
54
+ const montgomeryBytes = Math.ceil(montgomeryBits / 8);
55
+ const fieldLen = CURVE.nByteLength;
56
+ const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);
57
+ const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));
58
+
59
+ // cswap from RFC7748. But it is not from RFC7748!
60
+ /*
61
+ cswap(swap, x_2, x_3):
62
+ dummy = mask(swap) AND (x_2 XOR x_3)
63
+ x_2 = x_2 XOR dummy
64
+ x_3 = x_3 XOR dummy
65
+ Return (x_2, x_3)
66
+ Where mask(swap) is the all-1 or all-0 word of the same length as x_2
67
+ and x_3, computed, e.g., as mask(swap) = 0 - swap.
68
+ */
69
+ function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {
70
+ const dummy = modP(swap * (x_2 - x_3));
71
+ x_2 = modP(x_2 - dummy);
72
+ x_3 = modP(x_3 + dummy);
73
+ return [x_2, x_3];
74
+ }
75
+
76
+ // Accepts 0 as well
77
+ function assertFieldElement(n: bigint): bigint {
78
+ if (typeof n === 'bigint' && _0n <= n && n < P) return n;
79
+ throw new Error('Expected valid scalar 0 < scalar < CURVE.P');
80
+ }
81
+
82
+ // x25519 from 4
83
+ // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
84
+ const a24 = (CURVE.a - BigInt(2)) / BigInt(4);
85
+ /**
86
+ *
87
+ * @param pointU u coordinate (x) on Montgomery Curve 25519
88
+ * @param scalar by which the point would be multiplied
89
+ * @returns new Point on Montgomery curve
90
+ */
91
+ function montgomeryLadder(pointU: bigint, scalar: bigint): bigint {
92
+ const u = assertFieldElement(pointU);
93
+ // Section 5: Implementations MUST accept non-canonical values and process them as
94
+ // if they had been reduced modulo the field prime.
95
+ const k = assertFieldElement(scalar);
96
+ const x_1 = u;
97
+ let x_2 = _1n;
98
+ let z_2 = _0n;
99
+ let x_3 = u;
100
+ let z_3 = _1n;
101
+ let swap = _0n;
102
+ let sw: [bigint, bigint];
103
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
104
+ const k_t = (k >> t) & _1n;
105
+ swap ^= k_t;
106
+ sw = cswap(swap, x_2, x_3);
107
+ x_2 = sw[0];
108
+ x_3 = sw[1];
109
+ sw = cswap(swap, z_2, z_3);
110
+ z_2 = sw[0];
111
+ z_3 = sw[1];
112
+ swap = k_t;
113
+
114
+ const A = x_2 + z_2;
115
+ const AA = modP(A * A);
116
+ const B = x_2 - z_2;
117
+ const BB = modP(B * B);
118
+ const E = AA - BB;
119
+ const C = x_3 + z_3;
120
+ const D = x_3 - z_3;
121
+ const DA = modP(D * A);
122
+ const CB = modP(C * B);
123
+ const dacb = DA + CB;
124
+ const da_cb = DA - CB;
125
+ x_3 = modP(dacb * dacb);
126
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
127
+ x_2 = modP(AA * BB);
128
+ z_2 = modP(E * (AA + modP(a24 * E)));
129
+ }
130
+ // (x_2, x_3) = cswap(swap, x_2, x_3)
131
+ sw = cswap(swap, x_2, x_3);
132
+ x_2 = sw[0];
133
+ x_3 = sw[1];
134
+ // (z_2, z_3) = cswap(swap, z_2, z_3)
135
+ sw = cswap(swap, z_2, z_3);
136
+ z_2 = sw[0];
137
+ z_3 = sw[1];
138
+ // z_2^(p - 2)
139
+ const z2 = powPminus2(z_2);
140
+ // Return x_2 * (z_2^(p - 2))
141
+ return modP(x_2 * z2);
142
+ }
143
+
144
+ function encodeUCoordinate(u: bigint): Uint8Array {
145
+ return numberToBytesLE(modP(u), montgomeryBytes);
146
+ }
147
+
148
+ function decodeUCoordinate(uEnc: Hex): bigint {
149
+ // Section 5: When receiving such an array, implementations of X25519
150
+ // MUST mask the most significant bit in the final byte.
151
+ // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP
152
+ // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519
153
+ const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);
154
+ // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index)
155
+ if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; // 0b0111_1111
156
+ return bytesToNumberLE(u);
157
+ }
158
+ function decodeScalar(n: Hex): bigint {
159
+ const bytes = ensureBytes('scalar', n);
160
+ if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen)
161
+ throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`);
162
+ return bytesToNumberLE(adjustScalarBytes(bytes));
163
+ }
164
+ function scalarMult(scalar: Hex, u: Hex): Uint8Array {
165
+ const pointU = decodeUCoordinate(u);
166
+ const _scalar = decodeScalar(scalar);
167
+ const pu = montgomeryLadder(pointU, _scalar);
168
+ // The result was not contributory
169
+ // https://cr.yp.to/ecdh.html#validate
170
+ if (pu === _0n) throw new Error('Invalid private or public key received');
171
+ return encodeUCoordinate(pu);
172
+ }
173
+ // Computes public key from private. By doing scalar multiplication of base point.
174
+ const GuBytes = encodeUCoordinate(CURVE.Gu);
175
+ function scalarMultBase(scalar: Hex): Uint8Array {
176
+ return scalarMult(scalar, GuBytes);
177
+ }
178
+
179
+ return {
180
+ scalarMult,
181
+ scalarMultBase,
182
+ getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),
183
+ getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),
184
+ GuBytes: GuBytes,
185
+ };
186
+ }