@decryption/curves 0.2.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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/abstract/bls.d.ts +410 -0
  4. package/abstract/bls.js +433 -0
  5. package/abstract/curve.d.ts +441 -0
  6. package/abstract/curve.js +622 -0
  7. package/abstract/edwards.d.ts +319 -0
  8. package/abstract/edwards.js +697 -0
  9. package/abstract/fft.d.ts +438 -0
  10. package/abstract/fft.js +580 -0
  11. package/abstract/frost.d.ts +292 -0
  12. package/abstract/frost.js +705 -0
  13. package/abstract/hash-to-curve.d.ts +238 -0
  14. package/abstract/hash-to-curve.js +353 -0
  15. package/abstract/modular.d.ts +550 -0
  16. package/abstract/modular.js +872 -0
  17. package/abstract/montgomery.d.ts +95 -0
  18. package/abstract/montgomery.js +180 -0
  19. package/abstract/oprf.d.ts +354 -0
  20. package/abstract/oprf.js +358 -0
  21. package/abstract/poseidon.d.ts +198 -0
  22. package/abstract/poseidon.js +471 -0
  23. package/abstract/tower.d.ts +213 -0
  24. package/abstract/tower.js +963 -0
  25. package/abstract/weierstrass.d.ts +587 -0
  26. package/abstract/weierstrass.js +1421 -0
  27. package/bls12-381.d.ts +23 -0
  28. package/bls12-381.js +680 -0
  29. package/bn254.d.ts +74 -0
  30. package/bn254.js +248 -0
  31. package/ed25519.d.ts +211 -0
  32. package/ed25519.js +626 -0
  33. package/ed448.d.ts +184 -0
  34. package/ed448.js +596 -0
  35. package/esm/abstract/bls.js +429 -0
  36. package/esm/abstract/curve.js +610 -0
  37. package/esm/abstract/edwards.js +691 -0
  38. package/esm/abstract/fft.js +567 -0
  39. package/esm/abstract/frost.js +702 -0
  40. package/esm/abstract/hash-to-curve.js +345 -0
  41. package/esm/abstract/modular.js +849 -0
  42. package/esm/abstract/montgomery.js +177 -0
  43. package/esm/abstract/oprf.js +355 -0
  44. package/esm/abstract/poseidon.js +462 -0
  45. package/esm/abstract/tower.js +925 -0
  46. package/esm/abstract/weierstrass.js +1411 -0
  47. package/esm/bls12-381.js +677 -0
  48. package/esm/bn254.js +244 -0
  49. package/esm/ed25519.js +622 -0
  50. package/esm/ed448.js +593 -0
  51. package/esm/index.js +38 -0
  52. package/esm/misc.js +211 -0
  53. package/esm/nist.js +266 -0
  54. package/esm/secp256k1.js +465 -0
  55. package/esm/utils.js +597 -0
  56. package/esm/webcrypto.js +362 -0
  57. package/index.d.ts +0 -0
  58. package/index.js +38 -0
  59. package/misc.d.ts +113 -0
  60. package/misc.js +216 -0
  61. package/nist.d.ts +136 -0
  62. package/nist.js +269 -0
  63. package/package.json +46 -0
  64. package/secp256k1.d.ts +152 -0
  65. package/secp256k1.js +468 -0
  66. package/utils.d.ts +535 -0
  67. package/utils.js +626 -0
  68. package/webcrypto.d.ts +240 -0
  69. package/webcrypto.js +365 -0
@@ -0,0 +1,872 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNegativeLE = void 0;
4
+ exports.mod = mod;
5
+ exports.pow = pow;
6
+ exports.pow2 = pow2;
7
+ exports.invert = invert;
8
+ exports.tonelliShanks = tonelliShanks;
9
+ exports.FpSqrt = FpSqrt;
10
+ exports.validateField = validateField;
11
+ exports.FpPow = FpPow;
12
+ exports.FpInvertBatch = FpInvertBatch;
13
+ exports.FpDiv = FpDiv;
14
+ exports.FpLegendre = FpLegendre;
15
+ exports.FpIsSquare = FpIsSquare;
16
+ exports.nLength = nLength;
17
+ exports.Field = Field;
18
+ exports.FpSqrtOdd = FpSqrtOdd;
19
+ exports.FpSqrtEven = FpSqrtEven;
20
+ exports.getFieldBytesLength = getFieldBytesLength;
21
+ exports.getMinHashLength = getMinHashLength;
22
+ exports.mapHashToField = mapHashToField;
23
+ /**
24
+ * Utils for modular division and fields.
25
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
26
+ * There is no division: it is replaced by modular multiplicative inverse.
27
+ * @module
28
+ */
29
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
30
+ const utils_1 = require("../utils");
31
+ // Numbers aren't used in x25519 / x448 builds
32
+ // prettier-ignore
33
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);
34
+ // prettier-ignore
35
+ const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
36
+ // prettier-ignore
37
+ const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
38
+ const _16n = /* @__PURE__ */ BigInt(16);
39
+ /**
40
+ * @param a - Dividend value.
41
+ * @param b - Positive modulus.
42
+ * @returns Reduced value in `[0, b)` only when `b` is positive.
43
+ * @throws If the modulus is not positive. {@link Error}
44
+ * @example
45
+ * Normalize a bigint into one field residue.
46
+ *
47
+ * ```ts
48
+ * mod(-1n, 5n);
49
+ * ```
50
+ */
51
+ function mod(a, b) {
52
+ if (b <= _0n)
53
+ throw new Error('mod: expected positive modulus, got ' + b);
54
+ const result = a % b;
55
+ return result >= _0n ? result : b + result;
56
+ }
57
+ /**
58
+ * Efficiently raise num to a power with modular reduction.
59
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
60
+ * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
61
+ * modulus instead of relying on the `power===0/1` fast paths to normalize it.
62
+ * @param num - Base value.
63
+ * @param power - Exponent value.
64
+ * @param modulo - Reduction modulus.
65
+ * @returns Modular exponentiation result.
66
+ * @throws If the modulus or exponent is invalid. {@link Error}
67
+ * @example
68
+ * Raise one bigint to a modular power.
69
+ *
70
+ * ```ts
71
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
72
+ * ```
73
+ */
74
+ function pow(num, power, modulo) {
75
+ return FpPow(Field(modulo), num, power);
76
+ }
77
+ /**
78
+ * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
79
+ * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
80
+ * modulus; the `power===0` fast path intentionally returns the input unchanged.
81
+ * @param x - Base value.
82
+ * @param power - Number of squarings.
83
+ * @param modulo - Reduction modulus.
84
+ * @returns Repeated-squaring result.
85
+ * @throws If the exponent is negative. {@link Error}
86
+ * @example
87
+ * Apply repeated squaring inside one field.
88
+ *
89
+ * ```ts
90
+ * pow2(3n, 2n, 11n);
91
+ * ```
92
+ */
93
+ function pow2(x, power, modulo) {
94
+ if (power < _0n)
95
+ throw new Error('pow2: expected non-negative exponent, got ' + power);
96
+ let res = x;
97
+ while (power-- > _0n) {
98
+ res *= res;
99
+ res %= modulo;
100
+ }
101
+ return res;
102
+ }
103
+ /**
104
+ * Inverses number over modulo.
105
+ * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
106
+ * @param number - Value to invert.
107
+ * @param modulo - Positive modulus.
108
+ * @returns Multiplicative inverse.
109
+ * @throws If the modulus is invalid or the inverse does not exist. {@link Error}
110
+ * @example
111
+ * Compute one modular inverse with the extended Euclidean algorithm.
112
+ *
113
+ * ```ts
114
+ * invert(3n, 11n);
115
+ * ```
116
+ */
117
+ function invert(number, modulo) {
118
+ if (number === _0n)
119
+ throw new Error('invert: expected non-zero number');
120
+ if (modulo <= _0n)
121
+ throw new Error('invert: expected positive modulus, got ' + modulo);
122
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
123
+ let a = mod(number, modulo);
124
+ let b = modulo;
125
+ // prettier-ignore
126
+ let x = _0n, y = _1n, u = _1n, v = _0n;
127
+ while (a !== _0n) {
128
+ const q = b / a;
129
+ const r = b - a * q;
130
+ const m = x - u * q;
131
+ const n = y - v * q;
132
+ // prettier-ignore
133
+ b = a, a = r, x = u, y = v, u = m, v = n;
134
+ }
135
+ const gcd = b;
136
+ if (gcd !== _1n)
137
+ throw new Error('invert: does not exist');
138
+ return mod(x, modulo);
139
+ }
140
+ function assertIsSquare(Fp, root, n) {
141
+ const F = Fp;
142
+ if (!F.eql(F.sqr(root), n))
143
+ throw new Error('Cannot find square root');
144
+ }
145
+ // Not all roots are possible! Example which will throw:
146
+ // const NUM =
147
+ // n = 72057594037927816n;
148
+ // Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
149
+ function sqrt3mod4(Fp, n) {
150
+ const F = Fp;
151
+ const p1div4 = (F.ORDER + _1n) / _4n;
152
+ const root = F.pow(n, p1div4);
153
+ assertIsSquare(F, root, n);
154
+ return root;
155
+ }
156
+ // Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV
157
+ // pseudocode verbatim.
158
+ function sqrt5mod8(Fp, n) {
159
+ const F = Fp;
160
+ const p5div8 = (F.ORDER - _5n) / _8n;
161
+ const n2 = F.mul(n, _2n);
162
+ const v = F.pow(n2, p5div8);
163
+ const nv = F.mul(n, v);
164
+ const i = F.mul(F.mul(nv, _2n), v);
165
+ const root = F.mul(nv, F.sub(i, F.ONE));
166
+ assertIsSquare(F, root, n);
167
+ return root;
168
+ }
169
+ // Based on RFC9380, Kong algorithm
170
+ // prettier-ignore
171
+ function sqrt9mod16(P) {
172
+ const Fp_ = Field(P);
173
+ const tn = tonelliShanks(P);
174
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
175
+ const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
176
+ const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
177
+ const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
178
+ return ((Fp, n) => {
179
+ const F = Fp;
180
+ let tv1 = F.pow(n, c4); // 1. tv1 = x^c4
181
+ let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1
182
+ const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1
183
+ const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1
184
+ const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x
185
+ const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x
186
+ tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
187
+ tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
188
+ const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x
189
+ const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
190
+ assertIsSquare(F, root, n);
191
+ return root;
192
+ });
193
+ }
194
+ /**
195
+ * Tonelli-Shanks square root search algorithm.
196
+ * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
197
+ * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
198
+ * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
199
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
200
+ * @param P - field order
201
+ * @returns function that takes field Fp (created from P) and number n
202
+ * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
203
+ * @example
204
+ * Construct a square-root helper for primes that need Tonelli-Shanks.
205
+ *
206
+ * ```ts
207
+ * import { Field, tonelliShanks } from './modular';
208
+ * const Fp = Field(17n);
209
+ * const sqrt = tonelliShanks(17n)(Fp, 4n);
210
+ * ```
211
+ */
212
+ function tonelliShanks(P) {
213
+ // Initialization (precomputation).
214
+ // Caching initialization could boost perf by 7%.
215
+ if (P < _3n)
216
+ throw new Error('sqrt is not defined for small field');
217
+ // Factor P - 1 = Q * 2^S, where Q is odd
218
+ let Q = P - _1n;
219
+ let S = 0;
220
+ while (Q % _2n === _0n) {
221
+ Q /= _2n;
222
+ S++;
223
+ }
224
+ // Find the first quadratic non-residue Z >= 2
225
+ let Z = _2n;
226
+ const _Fp = Field(P);
227
+ while (FpLegendre(_Fp, Z) === 1) {
228
+ // Basic primality test for P. After x iterations, chance of
229
+ // not finding quadratic non-residue is 2^x, so 2^1000.
230
+ if (Z++ > 1000)
231
+ throw new Error('Cannot find square root: probably non-prime P');
232
+ }
233
+ // Fast-path; usually done before Z, but we do "primality test".
234
+ if (S === 1)
235
+ return sqrt3mod4;
236
+ // Slow-path
237
+ // TODO: test on Fp2 and others
238
+ let cc = _Fp.pow(Z, Q); // c = z^Q
239
+ const Q1div2 = (Q + _1n) / _2n;
240
+ return function tonelliSlow(Fp, n) {
241
+ const F = Fp;
242
+ if (F.is0(n))
243
+ return n;
244
+ // Check if n is a quadratic residue using Legendre symbol
245
+ if (FpLegendre(F, n) !== 1)
246
+ throw new Error('Cannot find square root');
247
+ // Initialize variables for the main loop
248
+ let M = S;
249
+ let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
250
+ let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor
251
+ let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
252
+ // Main loop
253
+ // while t != 1
254
+ while (!F.eql(t, F.ONE)) {
255
+ if (F.is0(t))
256
+ return F.ZERO; // if t=0 return R=0
257
+ let i = 1;
258
+ // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
259
+ let t_tmp = F.sqr(t); // t^(2^1)
260
+ while (!F.eql(t_tmp, F.ONE)) {
261
+ i++;
262
+ t_tmp = F.sqr(t_tmp); // t^(2^2)...
263
+ if (i === M)
264
+ throw new Error('Cannot find square root');
265
+ }
266
+ // Calculate the exponent for b: 2^(M - i - 1)
267
+ const exponent = _1n << BigInt(M - i - 1); // bigint is important
268
+ const b = F.pow(c, exponent); // b = 2^(M - i - 1)
269
+ // Update variables
270
+ M = i;
271
+ c = F.sqr(b); // c = b^2
272
+ t = F.mul(t, c); // t = (t * b^2)
273
+ R = F.mul(R, b); // R = R*b
274
+ }
275
+ return R;
276
+ };
277
+ }
278
+ /**
279
+ * Square root for a finite field. Will try optimized versions first:
280
+ *
281
+ * 1. P ≡ 3 (mod 4)
282
+ * 2. P ≡ 5 (mod 8)
283
+ * 3. P ≡ 9 (mod 16)
284
+ * 4. Tonelli-Shanks algorithm
285
+ *
286
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
287
+ * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
288
+ * (used for hash-to-curve).
289
+ * @param P - Field order.
290
+ * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
291
+ * behavior and this selector assumes prime-field-style integer moduli.
292
+ * @throws If the field is unsupported or the square root does not exist. {@link Error}
293
+ * @example
294
+ * Choose the square-root helper appropriate for one field modulus.
295
+ *
296
+ * ```ts
297
+ * import { Field, FpSqrt } from './modular';
298
+ * const Fp = Field(17n);
299
+ * const sqrt = FpSqrt(17n)(Fp, 4n);
300
+ * ```
301
+ */
302
+ function FpSqrt(P) {
303
+ // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
304
+ if (P % _4n === _3n)
305
+ return sqrt3mod4;
306
+ // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
307
+ if (P % _8n === _5n)
308
+ return sqrt5mod8;
309
+ // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
310
+ if (P % _16n === _9n)
311
+ return sqrt9mod16(P);
312
+ // Tonelli-Shanks algorithm
313
+ return tonelliShanks(P);
314
+ }
315
+ /**
316
+ * @param num - Value to inspect.
317
+ * @param modulo - Field modulus.
318
+ * @returns `true` when the least-significant little-endian bit is set.
319
+ * @throws If the modulus is invalid for `mod(...)`. {@link Error}
320
+ * @example
321
+ * Inspect the low bit used by little-endian sign conventions.
322
+ *
323
+ * ```ts
324
+ * isNegativeLE(3n, 11n);
325
+ * ```
326
+ */
327
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
328
+ exports.isNegativeLE = isNegativeLE;
329
+ // prettier-ignore
330
+ // Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime
331
+ // IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and
332
+ // field-specific extras like `isOdd` are left to the callers that actually need them.
333
+ const FIELD_FIELDS = [
334
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
335
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
336
+ 'addN', 'subN', 'mulN', 'sqrN'
337
+ ];
338
+ /**
339
+ * @param field - Field implementation.
340
+ * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
341
+ * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
342
+ * field-specific extras beyond positive `BYTES` / `BITS`.
343
+ * @throws If the field shape or numeric metadata are invalid. {@link Error}
344
+ * @example
345
+ * Check that a field implementation exposes the operations curve code expects.
346
+ *
347
+ * ```ts
348
+ * import { Field, validateField } from './modular';
349
+ * const Fp = validateField(Field(17n));
350
+ * ```
351
+ */
352
+ function validateField(field) {
353
+ const initial = {
354
+ ORDER: 'bigint',
355
+ BYTES: 'number',
356
+ BITS: 'number',
357
+ };
358
+ const opts = FIELD_FIELDS.reduce((map, val) => {
359
+ map[val] = 'function';
360
+ return map;
361
+ }, initial);
362
+ (0, utils_1.validateObject)(field, opts);
363
+ // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /
364
+ // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.
365
+ (0, utils_1.asafenumber)(field.BYTES, 'BYTES');
366
+ (0, utils_1.asafenumber)(field.BITS, 'BITS');
367
+ // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the
368
+ // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.
369
+ if (field.BYTES < 1 || field.BITS < 1)
370
+ throw new Error('invalid field: expected BYTES/BITS > 0');
371
+ if (field.ORDER <= _1n)
372
+ throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);
373
+ return field;
374
+ }
375
+ // Generic field functions
376
+ /**
377
+ * Same as `pow` but for Fp: non-constant-time.
378
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
379
+ * @param Fp - Field implementation.
380
+ * @param num - Base value.
381
+ * @param power - Exponent value.
382
+ * @returns Powered field element.
383
+ * @throws If the exponent is negative. {@link Error}
384
+ * @example
385
+ * Raise one field element to a public exponent.
386
+ *
387
+ * ```ts
388
+ * import { Field, FpPow } from './modular';
389
+ * const Fp = Field(17n);
390
+ * const x = FpPow(Fp, 3n, 5n);
391
+ * ```
392
+ */
393
+ function FpPow(Fp, num, power) {
394
+ const F = Fp;
395
+ if (power < _0n)
396
+ throw new Error('invalid exponent, negatives unsupported');
397
+ if (power === _0n)
398
+ return F.ONE;
399
+ if (power === _1n)
400
+ return num;
401
+ let p = F.ONE;
402
+ let d = num;
403
+ while (power > _0n) {
404
+ if (power & _1n)
405
+ p = F.mul(p, d);
406
+ d = F.sqr(d);
407
+ power >>= _1n;
408
+ }
409
+ return p;
410
+ }
411
+ /**
412
+ * Efficiently invert an array of Field elements.
413
+ * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
414
+ * @param Fp - Field implementation.
415
+ * @param nums - Values to invert.
416
+ * @param passZero - map 0 to 0 (instead of undefined)
417
+ * @returns Inverted values.
418
+ * @example
419
+ * Invert several field elements with one shared inversion.
420
+ *
421
+ * ```ts
422
+ * import { Field, FpInvertBatch } from './modular';
423
+ * const Fp = Field(17n);
424
+ * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
425
+ * ```
426
+ */
427
+ function FpInvertBatch(Fp, nums, passZero = false) {
428
+ const F = Fp;
429
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);
430
+ // Walk from first to last, multiply them by each other MOD p
431
+ const multipliedAcc = nums.reduce((acc, num, i) => {
432
+ if (F.is0(num))
433
+ return acc;
434
+ inverted[i] = acc;
435
+ return F.mul(acc, num);
436
+ }, F.ONE);
437
+ // Invert last element
438
+ const invertedAcc = F.inv(multipliedAcc);
439
+ // Walk from last to first, multiply them by inverted each other MOD p
440
+ nums.reduceRight((acc, num, i) => {
441
+ if (F.is0(num))
442
+ return acc;
443
+ inverted[i] = F.mul(acc, inverted[i]);
444
+ return F.mul(acc, num);
445
+ }, invertedAcc);
446
+ return inverted;
447
+ }
448
+ /**
449
+ * @param Fp - Field implementation.
450
+ * @param lhs - Dividend value.
451
+ * @param rhs - Divisor value.
452
+ * @returns Division result.
453
+ * @throws If the divisor is non-invertible. {@link Error}
454
+ * @example
455
+ * Divide one field element by another.
456
+ *
457
+ * ```ts
458
+ * import { Field, FpDiv } from './modular';
459
+ * const Fp = Field(17n);
460
+ * const x = FpDiv(Fp, 6n, 3n);
461
+ * ```
462
+ */
463
+ function FpDiv(Fp, lhs, rhs) {
464
+ const F = Fp;
465
+ return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));
466
+ }
467
+ /**
468
+ * Legendre symbol.
469
+ * Legendre constant is used to calculate Legendre symbol (a | p)
470
+ * which denotes the value of a^((p-1)/2) (mod p).
471
+ *
472
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
473
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
474
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
475
+ * @param Fp - Field implementation.
476
+ * @param n - Value to inspect.
477
+ * @returns Legendre symbol.
478
+ * @throws If the field returns an invalid Legendre symbol value. {@link Error}
479
+ * @example
480
+ * Compute the Legendre symbol of one field element.
481
+ *
482
+ * ```ts
483
+ * import { Field, FpLegendre } from './modular';
484
+ * const Fp = Field(17n);
485
+ * const symbol = FpLegendre(Fp, 4n);
486
+ * ```
487
+ */
488
+ function FpLegendre(Fp, n) {
489
+ const F = Fp;
490
+ // We can use 3rd argument as optional cache of this value
491
+ // but seems unneeded for now. The operation is very fast.
492
+ const p1mod2 = (F.ORDER - _1n) / _2n;
493
+ const powered = F.pow(n, p1mod2);
494
+ const yes = F.eql(powered, F.ONE);
495
+ const zero = F.eql(powered, F.ZERO);
496
+ const no = F.eql(powered, F.neg(F.ONE));
497
+ if (!yes && !zero && !no)
498
+ throw new Error('invalid Legendre symbol result');
499
+ return yes ? 1 : zero ? 0 : -1;
500
+ }
501
+ /**
502
+ * @param Fp - Field implementation.
503
+ * @param n - Value to inspect.
504
+ * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic
505
+ * residue" terminology often reserves that name for the non-zero square class.
506
+ * @throws If the field returns an invalid Legendre symbol value. {@link Error}
507
+ * @example
508
+ * Check whether one field element has a square root in the field.
509
+ *
510
+ * ```ts
511
+ * import { Field, FpIsSquare } from './modular';
512
+ * const Fp = Field(17n);
513
+ * const isSquare = FpIsSquare(Fp, 4n);
514
+ * ```
515
+ */
516
+ function FpIsSquare(Fp, n) {
517
+ const l = FpLegendre(Fp, n);
518
+ // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.
519
+ return l !== -1;
520
+ }
521
+ /**
522
+ * @param n - Curve order. Callers are expected to pass a positive order.
523
+ * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
524
+ * value when overriding the derived bit length.
525
+ * @returns Byte and bit lengths.
526
+ * @throws If the order or cached bit length is invalid. {@link Error}
527
+ * @example
528
+ * Measure the encoding sizes needed for one modulus.
529
+ *
530
+ * ```ts
531
+ * nLength(255n);
532
+ * ```
533
+ */
534
+ function nLength(n, nBitLength) {
535
+ // Bit size, byte size of CURVE.n
536
+ if (nBitLength !== undefined)
537
+ (0, utils_1.anumber)(nBitLength);
538
+ if (n <= _0n)
539
+ throw new Error('invalid n length: expected positive n, got ' + n);
540
+ if (nBitLength !== undefined && nBitLength < 1)
541
+ throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);
542
+ const bits = (0, utils_1.bitLen)(n);
543
+ // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison
544
+ // any math that relies on the derived field metadata.
545
+ if (nBitLength !== undefined && nBitLength < bits)
546
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
547
+ const _nBitLength = nBitLength !== undefined ? nBitLength : bits;
548
+ const nByteLength = Math.ceil(_nBitLength / 8);
549
+ return { nBitLength: _nBitLength, nByteLength };
550
+ }
551
+ // Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the
552
+ // cached helper write would keep the field surface externally mutable.
553
+ const FIELD_SQRT = new WeakMap();
554
+ class _Field {
555
+ ORDER;
556
+ BITS;
557
+ BYTES;
558
+ isLE;
559
+ ZERO = _0n;
560
+ ONE = _1n;
561
+ _lengths;
562
+ _mod;
563
+ constructor(ORDER, opts = {}) {
564
+ // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv
565
+ // would stop modeling field arithmetic.
566
+ if (ORDER <= _1n)
567
+ throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);
568
+ let _nbitLength = undefined;
569
+ this.isLE = false;
570
+ if (opts != null && typeof opts === 'object') {
571
+ // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.
572
+ if (typeof opts.BITS === 'number')
573
+ _nbitLength = opts.BITS;
574
+ if (typeof opts.sqrt === 'function')
575
+ // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties
576
+ // explicitly instead of relying on writable prototype shadowing via assignment.
577
+ Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });
578
+ if (typeof opts.isLE === 'boolean')
579
+ this.isLE = opts.isLE;
580
+ if (opts.allowedLengths)
581
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
582
+ if (typeof opts.modFromBytes === 'boolean')
583
+ this._mod = opts.modFromBytes;
584
+ }
585
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
586
+ if (nByteLength > 2048)
587
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
588
+ this.ORDER = ORDER;
589
+ this.BITS = nBitLength;
590
+ this.BYTES = nByteLength;
591
+ Object.freeze(this);
592
+ }
593
+ create(num) {
594
+ return mod(num, this.ORDER);
595
+ }
596
+ isValid(num) {
597
+ if (typeof num !== 'bigint')
598
+ throw new TypeError('invalid field element: expected bigint, got ' + typeof num);
599
+ return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible
600
+ }
601
+ is0(num) {
602
+ return num === _0n;
603
+ }
604
+ // is valid and invertible
605
+ isValidNot0(num) {
606
+ return !this.is0(num) && this.isValid(num);
607
+ }
608
+ isOdd(num) {
609
+ return (num & _1n) === _1n;
610
+ }
611
+ neg(num) {
612
+ return mod(-num, this.ORDER);
613
+ }
614
+ eql(lhs, rhs) {
615
+ return lhs === rhs;
616
+ }
617
+ sqr(num) {
618
+ return mod(num * num, this.ORDER);
619
+ }
620
+ add(lhs, rhs) {
621
+ return mod(lhs + rhs, this.ORDER);
622
+ }
623
+ sub(lhs, rhs) {
624
+ return mod(lhs - rhs, this.ORDER);
625
+ }
626
+ mul(lhs, rhs) {
627
+ return mod(lhs * rhs, this.ORDER);
628
+ }
629
+ pow(num, power) {
630
+ return FpPow(this, num, power);
631
+ }
632
+ div(lhs, rhs) {
633
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
634
+ }
635
+ // Same as above, but doesn't normalize
636
+ sqrN(num) {
637
+ return num * num;
638
+ }
639
+ addN(lhs, rhs) {
640
+ return lhs + rhs;
641
+ }
642
+ subN(lhs, rhs) {
643
+ return lhs - rhs;
644
+ }
645
+ mulN(lhs, rhs) {
646
+ return lhs * rhs;
647
+ }
648
+ inv(num) {
649
+ return invert(num, this.ORDER);
650
+ }
651
+ sqrt(num) {
652
+ // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping
653
+ // the field instance itself mutable.
654
+ let sqrt = FIELD_SQRT.get(this);
655
+ if (!sqrt)
656
+ FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));
657
+ return sqrt(this, num);
658
+ }
659
+ toBytes(num) {
660
+ // Serialize fixed-width limbs without re-validating the field range. Callers that need a
661
+ // canonical encoding must pass a valid element; some protocols intentionally serialize raw
662
+ // residues here and reduce or validate them elsewhere.
663
+ return this.isLE ? (0, utils_1.numberToBytesLE)(num, this.BYTES) : (0, utils_1.numberToBytesBE)(num, this.BYTES);
664
+ }
665
+ fromBytes(bytes, skipValidation = false) {
666
+ (0, utils_1.abytes)(bytes);
667
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
668
+ if (allowedLengths) {
669
+ // `allowedLengths` must list real positive byte lengths; otherwise empty input would get
670
+ // padded into zero and silently decode as a field element.
671
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
672
+ throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
673
+ }
674
+ const padded = new Uint8Array(BYTES);
675
+ // isLE add 0 to right, !isLE to the left.
676
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
677
+ bytes = padded;
678
+ }
679
+ if (bytes.length !== BYTES)
680
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
681
+ let scalar = isLE ? (0, utils_1.bytesToNumberLE)(bytes) : (0, utils_1.bytesToNumberBE)(bytes);
682
+ if (modFromBytes)
683
+ scalar = mod(scalar, ORDER);
684
+ if (!skipValidation)
685
+ if (!this.isValid(scalar))
686
+ throw new Error('invalid field element: outside of range 0..ORDER');
687
+ // Range validation is optional here because some protocols intentionally decode raw residues
688
+ // and reduce or validate them elsewhere.
689
+ return scalar;
690
+ }
691
+ // TODO: we don't need it here, move out to separate fn
692
+ invertBatch(lst) {
693
+ return FpInvertBatch(this, lst);
694
+ }
695
+ // We can't move this out because Fp6, Fp12 implement it
696
+ // and it's unclear what to return in there.
697
+ cmov(a, b, condition) {
698
+ // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject
699
+ // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.
700
+ (0, utils_1.abool)(condition, 'condition');
701
+ return condition ? b : a;
702
+ }
703
+ }
704
+ // Freeze the shared method surface too; otherwise callers can still poison every Field instance by
705
+ // monkey-patching `_Field.prototype` even if each instance is frozen.
706
+ Object.freeze(_Field.prototype);
707
+ /**
708
+ * Creates a finite field. Major performance optimizations:
709
+ * * 1. Denormalized operations like mulN instead of mul.
710
+ * * 2. Identical object shape: never add or remove keys.
711
+ * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
712
+ * Fragile: always run a benchmark on a change.
713
+ * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
714
+ * all elements for performance and protocol-flexibility reasons; callers are responsible for
715
+ * supplying valid elements when they need canonical field behavior.
716
+ * This is low-level code, please make sure you know what you're doing.
717
+ *
718
+ * Note about field properties:
719
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
720
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
721
+ *
722
+ * @param ORDER - field order, probably prime, or could be composite
723
+ * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
724
+ * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
725
+ * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
726
+ * @example
727
+ * Construct one prime field with optional overrides.
728
+ *
729
+ * ```ts
730
+ * Field(11n);
731
+ * ```
732
+ */
733
+ function Field(ORDER, opts = {}) {
734
+ return new _Field(ORDER, opts);
735
+ }
736
+ // Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
737
+ // This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
738
+ // which mean we cannot force this via opts.
739
+ // Not sure what to do with randomBytes, we can accept it inside opts if wanted.
740
+ // Probably need to export getMinHashLength somewhere?
741
+ // random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
742
+ // const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
743
+ // if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
744
+ // const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
745
+ // // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
746
+ // const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
747
+ // return reduced;
748
+ // },
749
+ /**
750
+ * @param Fp - Field implementation.
751
+ * @param elm - Value to square-root.
752
+ * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,
753
+ * which is the only square root but is not odd.
754
+ * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
755
+ * @example
756
+ * Select the odd square root when two roots exist.
757
+ *
758
+ * ```ts
759
+ * import { Field, FpSqrtOdd } from './modular';
760
+ * const Fp = Field(17n);
761
+ * const root = FpSqrtOdd(Fp, 4n);
762
+ * ```
763
+ */
764
+ function FpSqrtOdd(Fp, elm) {
765
+ const F = Fp;
766
+ if (!F.isOdd)
767
+ throw new Error("Field doesn't have isOdd");
768
+ const root = F.sqrt(elm);
769
+ return F.isOdd(root) ? root : F.neg(root);
770
+ }
771
+ /**
772
+ * @param Fp - Field implementation.
773
+ * @param elm - Value to square-root.
774
+ * @returns Even square root.
775
+ * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
776
+ * @example
777
+ * Select the even square root when two roots exist.
778
+ *
779
+ * ```ts
780
+ * import { Field, FpSqrtEven } from './modular';
781
+ * const Fp = Field(17n);
782
+ * const root = FpSqrtEven(Fp, 4n);
783
+ * ```
784
+ */
785
+ function FpSqrtEven(Fp, elm) {
786
+ const F = Fp;
787
+ if (!F.isOdd)
788
+ throw new Error("Field doesn't have isOdd");
789
+ const root = F.sqrt(elm);
790
+ return F.isOdd(root) ? F.neg(root) : root;
791
+ }
792
+ /**
793
+ * Returns total number of bytes consumed by the field element.
794
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
795
+ * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
796
+ * order greater than 1.
797
+ * @returns byte length of field
798
+ * @throws If the field order is not a bigint. {@link Error}
799
+ * @example
800
+ * Read the fixed-width byte length of one field.
801
+ *
802
+ * ```ts
803
+ * getFieldBytesLength(255n);
804
+ * ```
805
+ */
806
+ function getFieldBytesLength(fieldOrder) {
807
+ if (typeof fieldOrder !== 'bigint')
808
+ throw new Error('field order must be bigint');
809
+ // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.
810
+ if (fieldOrder <= _1n)
811
+ throw new Error('field order must be greater than 1');
812
+ // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.
813
+ const bitLength = (0, utils_1.bitLen)(fieldOrder - _1n);
814
+ return Math.ceil(bitLength / 8);
815
+ }
816
+ /**
817
+ * Returns minimal amount of bytes that can be safely reduced
818
+ * by field order.
819
+ * Should be 2^-128 for 128-bit curve such as P256.
820
+ * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
821
+ * absolute floor for policy reasons.
822
+ * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
823
+ * @returns byte length of target hash
824
+ * @throws If the field order is invalid. {@link Error}
825
+ * @example
826
+ * Compute the minimum hash length needed for field reduction.
827
+ *
828
+ * ```ts
829
+ * getMinHashLength(255n);
830
+ * ```
831
+ */
832
+ function getMinHashLength(fieldOrder) {
833
+ const length = getFieldBytesLength(fieldOrder);
834
+ return length + Math.ceil(length / 2);
835
+ }
836
+ /**
837
+ * "Constant-time" private key generation utility.
838
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
839
+ * and convert them into private scalar, with the modulo bias being negligible.
840
+ * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
841
+ * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
842
+ * accidentally acceptable for real scalar derivation.
843
+ * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},
844
+ * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
845
+ * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
846
+ * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
847
+ * @param key - Uniform input bytes.
848
+ * @param fieldOrder - Size of subgroup.
849
+ * @param isLE - interpret hash bytes as LE num
850
+ * @returns valid private scalar
851
+ * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
852
+ * @example
853
+ * Map hash output into a private scalar range.
854
+ *
855
+ * ```ts
856
+ * mapHashToField(new Uint8Array(48).fill(1), 255n);
857
+ * ```
858
+ */
859
+ function mapHashToField(key, fieldOrder, isLE = false) {
860
+ (0, utils_1.abytes)(key);
861
+ const len = key.length;
862
+ const fieldLen = getFieldBytesLength(fieldOrder);
863
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
864
+ // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge
865
+ // inputs: easier to reason about JS timing / allocation behavior.
866
+ if (len < minLen || len > 1024)
867
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
868
+ const num = isLE ? (0, utils_1.bytesToNumberLE)(key) : (0, utils_1.bytesToNumberBE)(key);
869
+ // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
870
+ const reduced = mod(num, fieldOrder - _1n) + _1n;
871
+ return isLE ? (0, utils_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_1.numberToBytesBE)(reduced, fieldLen);
872
+ }