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