@ocap/mcrypto 1.30.24 → 1.30.26

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 (51) hide show
  1. package/esm/crypter/aes-legacy.d.mts +11 -0
  2. package/esm/crypter/aes-legacy.mjs +67 -15
  3. package/esm/crypter/aes.d.mts +14 -2
  4. package/esm/crypter/aes.mjs +69 -3
  5. package/esm/encode.mjs +1 -1
  6. package/esm/hasher/keccak.mjs +7 -2
  7. package/esm/hasher/sha2.d.mts +1 -1
  8. package/esm/hasher/sha2.mjs +26 -11
  9. package/esm/hasher/sha3.d.mts +1 -1
  10. package/esm/hasher/sha3.mjs +21 -6
  11. package/esm/index.d.mts +1 -1
  12. package/esm/signer/ed25519.d.mts +1 -1
  13. package/esm/signer/ed25519.mjs +143 -16
  14. package/esm/signer/ethereum.mjs +7 -3
  15. package/esm/signer/secp256k1.mjs +3 -2
  16. package/esm/webauthn.d.mts +68 -2
  17. package/esm/webauthn.mjs +64 -16
  18. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  19. package/lib/_vendor/@noble/curves/abstract/curve.cjs +373 -0
  20. package/lib/_vendor/@noble/curves/abstract/modular.cjs +616 -0
  21. package/lib/_vendor/@noble/curves/abstract/weierstrass.cjs +1020 -0
  22. package/lib/_vendor/@noble/curves/nist.cjs +91 -0
  23. package/lib/_vendor/@noble/curves/secp256k1.cjs +73 -0
  24. package/lib/_vendor/@noble/curves/utils.cjs +463 -0
  25. package/lib/_vendor/@noble/ed25519/LICENSE +21 -0
  26. package/lib/_vendor/@noble/ed25519/index.cjs +512 -0
  27. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  28. package/lib/_vendor/@noble/hashes/_md.cjs +230 -0
  29. package/lib/_vendor/@noble/hashes/_u64.cjs +67 -0
  30. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  31. package/lib/_vendor/@noble/hashes/sha2.cjs +477 -0
  32. package/lib/_vendor/@noble/hashes/sha3.cjs +329 -0
  33. package/lib/_vendor/@noble/hashes/utils.cjs +410 -0
  34. package/lib/crypter/aes-legacy.cjs +68 -21
  35. package/lib/crypter/aes-legacy.d.cts +11 -0
  36. package/lib/crypter/aes.cjs +69 -2
  37. package/lib/crypter/aes.d.cts +14 -2
  38. package/lib/encode.cjs +1 -1
  39. package/lib/hasher/keccak.cjs +13 -8
  40. package/lib/hasher/sha2.cjs +32 -17
  41. package/lib/hasher/sha2.d.cts +1 -1
  42. package/lib/hasher/sha3.cjs +27 -12
  43. package/lib/hasher/sha3.d.cts +1 -1
  44. package/lib/index.d.cts +1 -1
  45. package/lib/signer/ed25519.cjs +146 -20
  46. package/lib/signer/ed25519.d.cts +1 -1
  47. package/lib/signer/ethereum.cjs +16 -12
  48. package/lib/signer/secp256k1.cjs +11 -10
  49. package/lib/webauthn.cjs +80 -31
  50. package/lib/webauthn.d.cts +68 -2
  51. package/package.json +6 -7
@@ -0,0 +1,616 @@
1
+ const require_utils = require('../utils.cjs');
2
+
3
+ //#region ../../node_modules/@noble/curves/abstract/modular.js
4
+ /**
5
+ * Utils for modular division and fields.
6
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
7
+ * There is no division: it is replaced by modular multiplicative inverse.
8
+ * @module
9
+ */
10
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);
12
+ const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
13
+ const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
14
+ const _16n = /* @__PURE__ */ BigInt(16);
15
+ /**
16
+ * @param a - Dividend value.
17
+ * @param b - Positive modulus.
18
+ * @returns Reduced value in `[0, b)` only when `b` is positive.
19
+ * @throws If the modulus is not positive. {@link Error}
20
+ * @example
21
+ * Normalize a bigint into one field residue.
22
+ *
23
+ * ```ts
24
+ * mod(-1n, 5n);
25
+ * ```
26
+ */
27
+ function mod(a, b) {
28
+ if (b <= _0n) throw new Error("mod: expected positive modulus, got " + b);
29
+ const result = a % b;
30
+ return result >= _0n ? result : b + result;
31
+ }
32
+ /**
33
+ * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
34
+ * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
35
+ * modulus; the `power===0` fast path intentionally returns the input unchanged.
36
+ * @param x - Base value.
37
+ * @param power - Number of squarings.
38
+ * @param modulo - Reduction modulus.
39
+ * @returns Repeated-squaring result.
40
+ * @throws If the exponent is negative. {@link Error}
41
+ * @example
42
+ * Apply repeated squaring inside one field.
43
+ *
44
+ * ```ts
45
+ * pow2(3n, 2n, 11n);
46
+ * ```
47
+ */
48
+ function pow2(x, power, modulo) {
49
+ if (power < _0n) throw new Error("pow2: expected non-negative exponent, got " + power);
50
+ let res = x;
51
+ while (power-- > _0n) {
52
+ res *= res;
53
+ res %= modulo;
54
+ }
55
+ return res;
56
+ }
57
+ /**
58
+ * Inverses number over modulo.
59
+ * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
60
+ * @param number - Value to invert.
61
+ * @param modulo - Positive modulus.
62
+ * @returns Multiplicative inverse.
63
+ * @throws If the modulus is invalid or the inverse does not exist. {@link Error}
64
+ * @example
65
+ * Compute one modular inverse with the extended Euclidean algorithm.
66
+ *
67
+ * ```ts
68
+ * invert(3n, 11n);
69
+ * ```
70
+ */
71
+ function invert(number, modulo) {
72
+ if (number === _0n) throw new Error("invert: expected non-zero number");
73
+ if (modulo <= _0n) throw new Error("invert: expected positive modulus, got " + modulo);
74
+ let a = mod(number, modulo);
75
+ let b = modulo;
76
+ let x = _0n, y = _1n, u = _1n, v = _0n;
77
+ while (a !== _0n) {
78
+ const q = b / a;
79
+ const r = b - a * q;
80
+ const m = x - u * q;
81
+ const n = y - v * q;
82
+ b = a, a = r, x = u, y = v, u = m, v = n;
83
+ }
84
+ if (b !== _1n) throw new Error("invert: does not exist");
85
+ return mod(x, modulo);
86
+ }
87
+ function assertIsSquare(Fp, root, n) {
88
+ const F = Fp;
89
+ if (!F.eql(F.sqr(root), n)) throw new Error("Cannot find square root");
90
+ }
91
+ function sqrt3mod4(Fp, n) {
92
+ const F = Fp;
93
+ const p1div4 = (F.ORDER + _1n) / _4n;
94
+ const root = F.pow(n, p1div4);
95
+ assertIsSquare(F, root, n);
96
+ return root;
97
+ }
98
+ function sqrt5mod8(Fp, n) {
99
+ const F = Fp;
100
+ const p5div8 = (F.ORDER - _5n) / _8n;
101
+ const n2 = F.mul(n, _2n);
102
+ const v = F.pow(n2, p5div8);
103
+ const nv = F.mul(n, v);
104
+ const i = F.mul(F.mul(nv, _2n), v);
105
+ const root = F.mul(nv, F.sub(i, F.ONE));
106
+ assertIsSquare(F, root, n);
107
+ return root;
108
+ }
109
+ function sqrt9mod16(P) {
110
+ const Fp_ = Field(P);
111
+ const tn = tonelliShanks(P);
112
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
113
+ const c2 = tn(Fp_, c1);
114
+ const c3 = tn(Fp_, Fp_.neg(c1));
115
+ const c4 = (P + _7n) / _16n;
116
+ return ((Fp, n) => {
117
+ const F = Fp;
118
+ let tv1 = F.pow(n, c4);
119
+ let tv2 = F.mul(tv1, c1);
120
+ const tv3 = F.mul(tv1, c2);
121
+ const tv4 = F.mul(tv1, c3);
122
+ const e1 = F.eql(F.sqr(tv2), n);
123
+ const e2 = F.eql(F.sqr(tv3), n);
124
+ tv1 = F.cmov(tv1, tv2, e1);
125
+ tv2 = F.cmov(tv4, tv3, e2);
126
+ const e3 = F.eql(F.sqr(tv2), n);
127
+ const root = F.cmov(tv1, tv2, e3);
128
+ assertIsSquare(F, root, n);
129
+ return root;
130
+ });
131
+ }
132
+ /**
133
+ * Tonelli-Shanks square root search algorithm.
134
+ * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
135
+ * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
136
+ * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
137
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
138
+ * @param P - field order
139
+ * @returns function that takes field Fp (created from P) and number n
140
+ * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
141
+ * @example
142
+ * Construct a square-root helper for primes that need Tonelli-Shanks.
143
+ *
144
+ * ```ts
145
+ * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
146
+ * const Fp = Field(17n);
147
+ * const sqrt = tonelliShanks(17n)(Fp, 4n);
148
+ * ```
149
+ */
150
+ function tonelliShanks(P) {
151
+ if (P < _3n) throw new Error("sqrt is not defined for small field");
152
+ let Q = P - _1n;
153
+ let S = 0;
154
+ while (Q % _2n === _0n) {
155
+ Q /= _2n;
156
+ S++;
157
+ }
158
+ let Z = _2n;
159
+ const _Fp = Field(P);
160
+ while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
161
+ if (S === 1) return sqrt3mod4;
162
+ let cc = _Fp.pow(Z, Q);
163
+ const Q1div2 = (Q + _1n) / _2n;
164
+ return function tonelliSlow(Fp, n) {
165
+ const F = Fp;
166
+ if (F.is0(n)) return n;
167
+ if (FpLegendre(F, n) !== 1) throw new Error("Cannot find square root");
168
+ let M = S;
169
+ let c = F.mul(F.ONE, cc);
170
+ let t = F.pow(n, Q);
171
+ let R = F.pow(n, Q1div2);
172
+ while (!F.eql(t, F.ONE)) {
173
+ if (F.is0(t)) return F.ZERO;
174
+ let i = 1;
175
+ let t_tmp = F.sqr(t);
176
+ while (!F.eql(t_tmp, F.ONE)) {
177
+ i++;
178
+ t_tmp = F.sqr(t_tmp);
179
+ if (i === M) throw new Error("Cannot find square root");
180
+ }
181
+ const exponent = _1n << BigInt(M - i - 1);
182
+ const b = F.pow(c, exponent);
183
+ M = i;
184
+ c = F.sqr(b);
185
+ t = F.mul(t, c);
186
+ R = F.mul(R, b);
187
+ }
188
+ return R;
189
+ };
190
+ }
191
+ /**
192
+ * Square root for a finite field. Will try optimized versions first:
193
+ *
194
+ * 1. P ≡ 3 (mod 4)
195
+ * 2. P ≡ 5 (mod 8)
196
+ * 3. P ≡ 9 (mod 16)
197
+ * 4. Tonelli-Shanks algorithm
198
+ *
199
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
200
+ * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
201
+ * (used for hash-to-curve).
202
+ * @param P - Field order.
203
+ * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
204
+ * behavior and this selector assumes prime-field-style integer moduli.
205
+ * @throws If the field is unsupported or the square root does not exist. {@link Error}
206
+ * @example
207
+ * Choose the square-root helper appropriate for one field modulus.
208
+ *
209
+ * ```ts
210
+ * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
211
+ * const Fp = Field(17n);
212
+ * const sqrt = FpSqrt(17n)(Fp, 4n);
213
+ * ```
214
+ */
215
+ function FpSqrt(P) {
216
+ if (P % _4n === _3n) return sqrt3mod4;
217
+ if (P % _8n === _5n) return sqrt5mod8;
218
+ if (P % _16n === _9n) return sqrt9mod16(P);
219
+ return tonelliShanks(P);
220
+ }
221
+ const FIELD_FIELDS = [
222
+ "create",
223
+ "isValid",
224
+ "is0",
225
+ "neg",
226
+ "inv",
227
+ "sqrt",
228
+ "sqr",
229
+ "eql",
230
+ "add",
231
+ "sub",
232
+ "mul",
233
+ "pow",
234
+ "div",
235
+ "addN",
236
+ "subN",
237
+ "mulN",
238
+ "sqrN"
239
+ ];
240
+ /**
241
+ * @param field - Field implementation.
242
+ * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
243
+ * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
244
+ * field-specific extras beyond positive `BYTES` / `BITS`.
245
+ * @throws If the field shape or numeric metadata are invalid. {@link Error}
246
+ * @example
247
+ * Check that a field implementation exposes the operations curve code expects.
248
+ *
249
+ * ```ts
250
+ * import { Field, validateField } from '@noble/curves/abstract/modular.js';
251
+ * const Fp = validateField(Field(17n));
252
+ * ```
253
+ */
254
+ function validateField(field) {
255
+ require_utils.validateObject(field, FIELD_FIELDS.reduce((map, val) => {
256
+ map[val] = "function";
257
+ return map;
258
+ }, {
259
+ ORDER: "bigint",
260
+ BYTES: "number",
261
+ BITS: "number"
262
+ }));
263
+ require_utils.asafenumber(field.BYTES, "BYTES");
264
+ require_utils.asafenumber(field.BITS, "BITS");
265
+ if (field.BYTES < 1 || field.BITS < 1) throw new Error("invalid field: expected BYTES/BITS > 0");
266
+ if (field.ORDER <= _1n) throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
267
+ return field;
268
+ }
269
+ /**
270
+ * Same as `pow` but for Fp: non-constant-time.
271
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
272
+ * @param Fp - Field implementation.
273
+ * @param num - Base value.
274
+ * @param power - Exponent value.
275
+ * @returns Powered field element.
276
+ * @throws If the exponent is negative. {@link Error}
277
+ * @example
278
+ * Raise one field element to a public exponent.
279
+ *
280
+ * ```ts
281
+ * import { Field, FpPow } from '@noble/curves/abstract/modular.js';
282
+ * const Fp = Field(17n);
283
+ * const x = FpPow(Fp, 3n, 5n);
284
+ * ```
285
+ */
286
+ function FpPow(Fp, num, power) {
287
+ const F = Fp;
288
+ if (power < _0n) throw new Error("invalid exponent, negatives unsupported");
289
+ if (power === _0n) return F.ONE;
290
+ if (power === _1n) return num;
291
+ let p = F.ONE;
292
+ let d = num;
293
+ while (power > _0n) {
294
+ if (power & _1n) p = F.mul(p, d);
295
+ d = F.sqr(d);
296
+ power >>= _1n;
297
+ }
298
+ return p;
299
+ }
300
+ /**
301
+ * Efficiently invert an array of Field elements.
302
+ * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
303
+ * @param Fp - Field implementation.
304
+ * @param nums - Values to invert.
305
+ * @param passZero - map 0 to 0 (instead of undefined)
306
+ * @returns Inverted values.
307
+ * @example
308
+ * Invert several field elements with one shared inversion.
309
+ *
310
+ * ```ts
311
+ * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
312
+ * const Fp = Field(17n);
313
+ * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
314
+ * ```
315
+ */
316
+ function FpInvertBatch(Fp, nums, passZero = false) {
317
+ const F = Fp;
318
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
319
+ const multipliedAcc = nums.reduce((acc, num, i) => {
320
+ if (F.is0(num)) return acc;
321
+ inverted[i] = acc;
322
+ return F.mul(acc, num);
323
+ }, F.ONE);
324
+ const invertedAcc = F.inv(multipliedAcc);
325
+ nums.reduceRight((acc, num, i) => {
326
+ if (F.is0(num)) return acc;
327
+ inverted[i] = F.mul(acc, inverted[i]);
328
+ return F.mul(acc, num);
329
+ }, invertedAcc);
330
+ return inverted;
331
+ }
332
+ /**
333
+ * Legendre symbol.
334
+ * Legendre constant is used to calculate Legendre symbol (a | p)
335
+ * which denotes the value of a^((p-1)/2) (mod p).
336
+ *
337
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
338
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
339
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
340
+ * @param Fp - Field implementation.
341
+ * @param n - Value to inspect.
342
+ * @returns Legendre symbol.
343
+ * @throws If the field returns an invalid Legendre symbol value. {@link Error}
344
+ * @example
345
+ * Compute the Legendre symbol of one field element.
346
+ *
347
+ * ```ts
348
+ * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
349
+ * const Fp = Field(17n);
350
+ * const symbol = FpLegendre(Fp, 4n);
351
+ * ```
352
+ */
353
+ function FpLegendre(Fp, n) {
354
+ const F = Fp;
355
+ const p1mod2 = (F.ORDER - _1n) / _2n;
356
+ const powered = F.pow(n, p1mod2);
357
+ const yes = F.eql(powered, F.ONE);
358
+ const zero = F.eql(powered, F.ZERO);
359
+ const no = F.eql(powered, F.neg(F.ONE));
360
+ if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
361
+ return yes ? 1 : zero ? 0 : -1;
362
+ }
363
+ /**
364
+ * @param n - Curve order. Callers are expected to pass a positive order.
365
+ * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
366
+ * value when overriding the derived bit length.
367
+ * @returns Byte and bit lengths.
368
+ * @throws If the order or cached bit length is invalid. {@link Error}
369
+ * @example
370
+ * Measure the encoding sizes needed for one modulus.
371
+ *
372
+ * ```ts
373
+ * nLength(255n);
374
+ * ```
375
+ */
376
+ function nLength(n, nBitLength) {
377
+ if (nBitLength !== void 0) require_utils.anumber(nBitLength);
378
+ if (n <= _0n) throw new Error("invalid n length: expected positive n, got " + n);
379
+ if (nBitLength !== void 0 && nBitLength < 1) throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
380
+ const bits = require_utils.bitLen(n);
381
+ if (nBitLength !== void 0 && nBitLength < bits) throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
382
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
383
+ return {
384
+ nBitLength: _nBitLength,
385
+ nByteLength: Math.ceil(_nBitLength / 8)
386
+ };
387
+ }
388
+ const FIELD_SQRT = /* @__PURE__ */ new WeakMap();
389
+ var _Field = class {
390
+ ORDER;
391
+ BITS;
392
+ BYTES;
393
+ isLE;
394
+ ZERO = _0n;
395
+ ONE = _1n;
396
+ _lengths;
397
+ _mod;
398
+ constructor(ORDER, opts = {}) {
399
+ if (ORDER <= _1n) throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
400
+ let _nbitLength = void 0;
401
+ this.isLE = false;
402
+ if (opts != null && typeof opts === "object") {
403
+ if (typeof opts.BITS === "number") _nbitLength = opts.BITS;
404
+ if (typeof opts.sqrt === "function") Object.defineProperty(this, "sqrt", {
405
+ value: opts.sqrt,
406
+ enumerable: true
407
+ });
408
+ if (typeof opts.isLE === "boolean") this.isLE = opts.isLE;
409
+ if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());
410
+ if (typeof opts.modFromBytes === "boolean") this._mod = opts.modFromBytes;
411
+ }
412
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
413
+ if (nByteLength > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
414
+ this.ORDER = ORDER;
415
+ this.BITS = nBitLength;
416
+ this.BYTES = nByteLength;
417
+ Object.freeze(this);
418
+ }
419
+ create(num) {
420
+ return mod(num, this.ORDER);
421
+ }
422
+ isValid(num) {
423
+ if (typeof num !== "bigint") throw new TypeError("invalid field element: expected bigint, got " + typeof num);
424
+ return _0n <= num && num < this.ORDER;
425
+ }
426
+ is0(num) {
427
+ return num === _0n;
428
+ }
429
+ isValidNot0(num) {
430
+ return !this.is0(num) && this.isValid(num);
431
+ }
432
+ isOdd(num) {
433
+ return (num & _1n) === _1n;
434
+ }
435
+ neg(num) {
436
+ return mod(-num, this.ORDER);
437
+ }
438
+ eql(lhs, rhs) {
439
+ return lhs === rhs;
440
+ }
441
+ sqr(num) {
442
+ return mod(num * num, this.ORDER);
443
+ }
444
+ add(lhs, rhs) {
445
+ return mod(lhs + rhs, this.ORDER);
446
+ }
447
+ sub(lhs, rhs) {
448
+ return mod(lhs - rhs, this.ORDER);
449
+ }
450
+ mul(lhs, rhs) {
451
+ return mod(lhs * rhs, this.ORDER);
452
+ }
453
+ pow(num, power) {
454
+ return FpPow(this, num, power);
455
+ }
456
+ div(lhs, rhs) {
457
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
458
+ }
459
+ sqrN(num) {
460
+ return num * num;
461
+ }
462
+ addN(lhs, rhs) {
463
+ return lhs + rhs;
464
+ }
465
+ subN(lhs, rhs) {
466
+ return lhs - rhs;
467
+ }
468
+ mulN(lhs, rhs) {
469
+ return lhs * rhs;
470
+ }
471
+ inv(num) {
472
+ return invert(num, this.ORDER);
473
+ }
474
+ sqrt(num) {
475
+ let sqrt = FIELD_SQRT.get(this);
476
+ if (!sqrt) FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
477
+ return sqrt(this, num);
478
+ }
479
+ toBytes(num) {
480
+ return this.isLE ? require_utils.numberToBytesLE(num, this.BYTES) : require_utils.numberToBytesBE(num, this.BYTES);
481
+ }
482
+ fromBytes(bytes, skipValidation = false) {
483
+ require_utils.abytes(bytes);
484
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
485
+ if (allowedLengths) {
486
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
487
+ const padded = new Uint8Array(BYTES);
488
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
489
+ bytes = padded;
490
+ }
491
+ if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
492
+ let scalar = isLE ? require_utils.bytesToNumberLE(bytes) : require_utils.bytesToNumberBE(bytes);
493
+ if (modFromBytes) scalar = mod(scalar, ORDER);
494
+ if (!skipValidation) {
495
+ if (!this.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
496
+ }
497
+ return scalar;
498
+ }
499
+ invertBatch(lst) {
500
+ return FpInvertBatch(this, lst);
501
+ }
502
+ cmov(a, b, condition) {
503
+ require_utils.abool(condition, "condition");
504
+ return condition ? b : a;
505
+ }
506
+ };
507
+ Object.freeze(_Field.prototype);
508
+ /**
509
+ * Creates a finite field. Major performance optimizations:
510
+ * * 1. Denormalized operations like mulN instead of mul.
511
+ * * 2. Identical object shape: never add or remove keys.
512
+ * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
513
+ * Fragile: always run a benchmark on a change.
514
+ * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
515
+ * all elements for performance and protocol-flexibility reasons; callers are responsible for
516
+ * supplying valid elements when they need canonical field behavior.
517
+ * This is low-level code, please make sure you know what you're doing.
518
+ *
519
+ * Note about field properties:
520
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
521
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
522
+ *
523
+ * @param ORDER - field order, probably prime, or could be composite
524
+ * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
525
+ * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
526
+ * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
527
+ * @example
528
+ * Construct one prime field with optional overrides.
529
+ *
530
+ * ```ts
531
+ * Field(11n);
532
+ * ```
533
+ */
534
+ function Field(ORDER, opts = {}) {
535
+ return new _Field(ORDER, opts);
536
+ }
537
+ /**
538
+ * Returns total number of bytes consumed by the field element.
539
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
540
+ * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
541
+ * order greater than 1.
542
+ * @returns byte length of field
543
+ * @throws If the field order is not a bigint. {@link Error}
544
+ * @example
545
+ * Read the fixed-width byte length of one field.
546
+ *
547
+ * ```ts
548
+ * getFieldBytesLength(255n);
549
+ * ```
550
+ */
551
+ function getFieldBytesLength(fieldOrder) {
552
+ if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
553
+ if (fieldOrder <= _1n) throw new Error("field order must be greater than 1");
554
+ const bitLength = require_utils.bitLen(fieldOrder - _1n);
555
+ return Math.ceil(bitLength / 8);
556
+ }
557
+ /**
558
+ * Returns minimal amount of bytes that can be safely reduced
559
+ * by field order.
560
+ * Should be 2^-128 for 128-bit curve such as P256.
561
+ * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
562
+ * absolute floor for policy reasons.
563
+ * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
564
+ * @returns byte length of target hash
565
+ * @throws If the field order is invalid. {@link Error}
566
+ * @example
567
+ * Compute the minimum hash length needed for field reduction.
568
+ *
569
+ * ```ts
570
+ * getMinHashLength(255n);
571
+ * ```
572
+ */
573
+ function getMinHashLength(fieldOrder) {
574
+ const length = getFieldBytesLength(fieldOrder);
575
+ return length + Math.ceil(length / 2);
576
+ }
577
+ /**
578
+ * "Constant-time" private key generation utility.
579
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
580
+ * and convert them into private scalar, with the modulo bias being negligible.
581
+ * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
582
+ * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
583
+ * accidentally acceptable for real scalar derivation.
584
+ * 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},
585
+ * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
586
+ * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
587
+ * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
588
+ * @param key - Uniform input bytes.
589
+ * @param fieldOrder - Size of subgroup.
590
+ * @param isLE - interpret hash bytes as LE num
591
+ * @returns valid private scalar
592
+ * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
593
+ * @example
594
+ * Map hash output into a private scalar range.
595
+ *
596
+ * ```ts
597
+ * mapHashToField(new Uint8Array(48).fill(1), 255n);
598
+ * ```
599
+ */
600
+ function mapHashToField(key, fieldOrder, isLE = false) {
601
+ require_utils.abytes(key);
602
+ const len = key.length;
603
+ const fieldLen = getFieldBytesLength(fieldOrder);
604
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
605
+ if (len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
606
+ const reduced = mod(isLE ? require_utils.bytesToNumberLE(key) : require_utils.bytesToNumberBE(key), fieldOrder - _1n) + _1n;
607
+ return isLE ? require_utils.numberToBytesLE(reduced, fieldLen) : require_utils.numberToBytesBE(reduced, fieldLen);
608
+ }
609
+
610
+ //#endregion
611
+ exports.Field = Field;
612
+ exports.FpInvertBatch = FpInvertBatch;
613
+ exports.getMinHashLength = getMinHashLength;
614
+ exports.mapHashToField = mapHashToField;
615
+ exports.pow2 = pow2;
616
+ exports.validateField = validateField;