@qntx/wallet-chains 0.4.0 → 0.6.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.
@@ -1,2865 +0,0 @@
1
- //#region ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
2
- const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
3
- const _32n = /* @__PURE__ */ BigInt(32);
4
- function fromBig(n, le = false) {
5
- if (le) return {
6
- h: Number(n & U32_MASK64),
7
- l: Number(n >> _32n & U32_MASK64)
8
- };
9
- return {
10
- h: Number(n >> _32n & U32_MASK64) | 0,
11
- l: Number(n & U32_MASK64) | 0
12
- };
13
- }
14
- function split(lst, le = false) {
15
- const len = lst.length;
16
- let Ah = new Uint32Array(len);
17
- let Al = new Uint32Array(len);
18
- for (let i = 0; i < len; i++) {
19
- const { h, l } = fromBig(lst[i], le);
20
- [Ah[i], Al[i]] = [h, l];
21
- }
22
- return [Ah, Al];
23
- }
24
- const fromNumH = (n) => n / 2 ** 32 | 0;
25
- const fromNumL = (n) => n >>> 0;
26
- function setU64FromNum(view, byteOffset, n, isLE) {
27
- const h = fromNumH(n);
28
- const l = fromNumL(n);
29
- view.setUint32(byteOffset, isLE ? l : h, isLE);
30
- view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
31
- }
32
- const shrSH = (h, _l, s) => h >>> s;
33
- const shrSL = (h, l, s) => h << 32 - s | l >>> s;
34
- const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
35
- const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
36
- const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
37
- const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
38
- function add(Ah, Al, Bh, Bl) {
39
- const l = (Al >>> 0) + (Bl >>> 0);
40
- return {
41
- h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
42
- l: l | 0
43
- };
44
- }
45
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
46
- const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
47
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
48
- const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
49
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
50
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
51
- //#endregion
52
- //#region ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
53
- /**
54
- * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
55
- * @param a - value to test
56
- * @returns `true` when the value is a Uint8Array-compatible view.
57
- * @example
58
- * Check whether a value is a Uint8Array-compatible view.
59
- * ```ts
60
- * isBytes(new Uint8Array([1, 2, 3]));
61
- * ```
62
- */
63
- function isBytes$1(a) {
64
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
65
- }
66
- const atitle$1 = (title) => title ? `"${title}" ` : "";
67
- /**
68
- * Asserts something is a non-negative integer.
69
- * @param n - number to validate
70
- * @param title - label included in thrown errors
71
- * @returns The validated number.
72
- * @throws On wrong argument types. {@link TypeError}
73
- * @throws On wrong argument ranges or values. {@link RangeError}
74
- * @example
75
- * Validate a non-negative integer option.
76
- * ```ts
77
- * anumber(32, 'length');
78
- * ```
79
- */
80
- function anumber$1(n, title = "") {
81
- if (typeof n !== "number") throw new TypeError(atitle$1(title) + "expected number, got " + typeof n);
82
- if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle$1(title) + "expected integer >= 0, got " + n);
83
- return n;
84
- }
85
- /**
86
- * Asserts something is a boolean.
87
- * @param value - value to validate
88
- * @param title - label included in thrown errors
89
- * @returns The validated boolean.
90
- * @throws On wrong argument types. {@link TypeError}
91
- * @example
92
- * Validate a boolean option.
93
- * ```ts
94
- * abool(true, 'enableXOF');
95
- * ```
96
- */
97
- function abool$1(value, title = "") {
98
- if (typeof value !== "boolean") throw new TypeError(atitle$1(title) + "expected boolean, got type=" + typeof value);
99
- return value;
100
- }
101
- /**
102
- * Asserts something is Uint8Array.
103
- * @param value - value to validate
104
- * @param length - optional exact length constraint
105
- * @param title - label included in thrown errors
106
- * @returns The validated byte array.
107
- * @throws On wrong argument types. {@link TypeError}
108
- * @throws On wrong argument ranges or values. {@link RangeError}
109
- * @example
110
- * Validate that a value is a byte array.
111
- * ```ts
112
- * abytes(new Uint8Array([1, 2, 3]));
113
- * ```
114
- */
115
- function abytes$1(value, length, title = "") {
116
- if (isBytes$1(value) && (length === void 0 || value.length === length)) return value;
117
- if (length !== void 0) anumber$1(length, "length");
118
- const bytes = isBytes$1(value);
119
- const ofLen = length !== void 0 ? ` of length ${length}` : "";
120
- const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
121
- const message = atitle$1(title) + "expected Uint8Array" + ofLen + ", got " + got;
122
- if (!bytes) throw new TypeError(message);
123
- throw new RangeError(message);
124
- }
125
- /**
126
- * Asserts something is a wrapped hash constructor.
127
- * @param h - hash constructor to validate
128
- * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
129
- * @throws On invalid hash metadata ranges or values. {@link RangeError}
130
- * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
131
- * @example
132
- * Validate a callable hash wrapper.
133
- * ```ts
134
- * import { ahash } from '@noble/hashes/utils.js';
135
- * import { sha256 } from '@noble/hashes/sha2.js';
136
- * ahash(sha256);
137
- * ```
138
- */
139
- function ahash(h) {
140
- if (typeof h !== "function" || typeof h.create !== "function") throw new TypeError("expected hash wrapped by utils.createHasher");
141
- anumber$1(h.outputLen);
142
- anumber$1(h.blockLen);
143
- if (h.outputLen < 1 || h.blockLen < 1) throw new Error("hash blockLen / outputLen must be >= 1");
144
- }
145
- const aobject$1 = (value, label) => {
146
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
147
- };
148
- const aopts = (value, label) => {
149
- aobject$1(value, label);
150
- const proto = Object.getPrototypeOf(value);
151
- if (proto !== Object.prototype && proto !== null) throw new TypeError(`"${label}" expected plain object`);
152
- if (Object.hasOwn(value, "__proto__")) throw new TypeError(`"${label}.__proto__" is not allowed`);
153
- };
154
- /**
155
- * Asserts a hash instance has not been destroyed or finished.
156
- * @param instance - hash instance to validate
157
- * @param checkFinished - whether to reject finalized instances
158
- * @throws If the hash instance has already been destroyed or finalized. {@link Error}
159
- * @example
160
- * Validate that a hash instance is still usable.
161
- * ```ts
162
- * import { aexists } from '@noble/hashes/utils.js';
163
- * import { sha256 } from '@noble/hashes/sha2.js';
164
- * const hash = sha256.create();
165
- * aexists(hash);
166
- * ```
167
- */
168
- function aexists(instance, checkFinished = true) {
169
- if (instance.destroyed) throw new Error("hash was destroyed");
170
- if (checkFinished && instance.finished) throw new Error("digest() was already called");
171
- }
172
- /**
173
- * Asserts output is a sufficiently-sized byte array.
174
- * @param out - destination buffer
175
- * @param instance - hash instance providing output length
176
- * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
177
- * @throws On wrong argument types. {@link TypeError}
178
- * @throws On wrong argument ranges or values. {@link RangeError}
179
- * @example
180
- * Validate a caller-provided digest buffer.
181
- * ```ts
182
- * import { aoutput } from '@noble/hashes/utils.js';
183
- * import { sha256 } from '@noble/hashes/sha2.js';
184
- * const hash = sha256.create();
185
- * aoutput(new Uint8Array(hash.outputLen), hash);
186
- * ```
187
- */
188
- function aoutput(out, instance) {
189
- abytes$1(out, void 0, "output");
190
- const min = instance.outputLen;
191
- if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
192
- }
193
- /**
194
- * Casts a typed array view to Uint32Array.
195
- * `arr.byteOffset` must already be 4-byte aligned or the platform
196
- * Uint32Array constructor will throw.
197
- * @param arr - source typed array
198
- * @returns Uint32Array view over the same buffer.
199
- * @example
200
- * Reinterpret a byte array as 32-bit words.
201
- * ```ts
202
- * u32(new Uint8Array(8));
203
- * ```
204
- */
205
- function u32(arr) {
206
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
207
- }
208
- /**
209
- * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
210
- * @param arrays - arrays to overwrite with zeros
211
- * @example
212
- * Zeroize sensitive buffers in place.
213
- * ```ts
214
- * clean(new Uint8Array([1, 2, 3]));
215
- * ```
216
- */
217
- function clean(...arrays) {
218
- for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
219
- }
220
- /**
221
- * Creates a DataView for byte-level manipulation.
222
- * @param arr - source typed array
223
- * @returns DataView over the same buffer region.
224
- * @example
225
- * Create a DataView over an existing buffer.
226
- * ```ts
227
- * createView(new Uint8Array(4));
228
- * ```
229
- */
230
- function createView(arr) {
231
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
232
- }
233
- /**
234
- * Rotate-right operation for uint32 values.
235
- * @param word - source word
236
- * @param shift - shift amount in bits
237
- * @returns Rotated word.
238
- * @example
239
- * Rotate a 32-bit word to the right.
240
- * ```ts
241
- * rotr(0x12345678, 8);
242
- * ```
243
- */
244
- function rotr(word, shift) {
245
- return word << 32 - shift | word >>> shift;
246
- }
247
- /** Whether the current platform is little-endian. */
248
- const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
249
- /**
250
- * Byte-swap operation for uint32 values.
251
- * @param word - source word
252
- * @returns Word with reversed byte order.
253
- * @example
254
- * Reverse the byte order of a 32-bit word.
255
- * ```ts
256
- * byteSwap(0x11223344);
257
- * ```
258
- */
259
- function byteSwap(word) {
260
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
261
- }
262
- /**
263
- * Byte-swaps every word of a Uint32Array in place.
264
- * @param arr - array to mutate
265
- * @returns The same array after mutation; callers pass live state arrays here.
266
- * @example
267
- * Reverse the byte order of every word in place.
268
- * ```ts
269
- * byteSwap32(new Uint32Array([0x11223344]));
270
- * ```
271
- */
272
- function byteSwap32(arr) {
273
- for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);
274
- return arr;
275
- }
276
- /**
277
- * Conditionally byte-swaps a Uint32Array on big-endian platforms.
278
- * @param u - array to normalize for host endianness
279
- * @returns Original or byte-swapped array depending on platform endianness.
280
- * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
281
- * @example
282
- * Normalize a word array for host endianness.
283
- * ```ts
284
- * swap32IfBE(new Uint32Array([0x11223344]));
285
- * ```
286
- */
287
- const swap32IfBE = isLE ? (u) => u : byteSwap32;
288
- const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
289
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
290
- /**
291
- * Convert byte array to hex string.
292
- * Uses the built-in function when available and assumes it matches the tested
293
- * fallback semantics.
294
- * @param bytes - bytes to encode
295
- * @returns Lowercase hexadecimal string.
296
- * @throws On wrong argument types. {@link TypeError}
297
- * @example
298
- * Convert bytes to lowercase hexadecimal.
299
- * ```ts
300
- * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
301
- * ```
302
- */
303
- function bytesToHex$1(bytes) {
304
- abytes$1(bytes);
305
- if (hasHexBuiltin) return bytes.toHex();
306
- let hex = "";
307
- for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
308
- return hex;
309
- }
310
- function asciiToBase16(ch) {
311
- return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - 55 : ch >= 97 && ch <= 102 ? ch - 87 : void 0;
312
- }
313
- /**
314
- * Convert hex string to byte array. Uses built-in function, when available.
315
- * @param hex - hexadecimal string to decode
316
- * @returns Decoded bytes.
317
- * @throws On wrong argument types. {@link TypeError}
318
- * @throws On wrong argument ranges or values. {@link RangeError}
319
- * @example
320
- * Decode lowercase hexadecimal into bytes.
321
- * ```ts
322
- * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
323
- * ```
324
- */
325
- function hexToBytes$1(hex) {
326
- if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
327
- if (hasHexBuiltin) try {
328
- return Uint8Array.fromHex(hex);
329
- } catch (error) {
330
- if (error instanceof SyntaxError) throw new RangeError(error.message);
331
- throw error;
332
- }
333
- const hl = hex.length;
334
- const al = hl / 2;
335
- if (hl % 2) throw new RangeError("hex string expected, got unpadded hex of length " + hl);
336
- const array = new Uint8Array(al);
337
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
338
- const n1 = asciiToBase16(hex.charCodeAt(hi));
339
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
340
- if (n1 === void 0 || n2 === void 0) {
341
- const char = hex[hi] + hex[hi + 1];
342
- throw new RangeError("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
343
- }
344
- array[ai] = n1 * 16 + n2;
345
- }
346
- return array;
347
- }
348
- /**
349
- * Copies several Uint8Arrays into one.
350
- * @param arrays - arrays to concatenate
351
- * @returns Concatenated byte array.
352
- * @throws On wrong argument types. {@link TypeError}
353
- * @example
354
- * Concatenate multiple byte arrays.
355
- * ```ts
356
- * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
357
- * ```
358
- */
359
- function concatBytes$1(...arrays) {
360
- let sum = 0;
361
- for (let i = 0; i < arrays.length; i++) {
362
- const a = arrays[i];
363
- abytes$1(a);
364
- sum += a.length;
365
- }
366
- const res = new Uint8Array(sum);
367
- for (let i = 0, pad = 0; i < arrays.length; i++) {
368
- const a = arrays[i];
369
- res.set(a, pad);
370
- pad += a.length;
371
- }
372
- return res;
373
- }
374
- /**
375
- * Merges default options and passed options.
376
- * @param defaults - base option object
377
- * @param opts - user overrides
378
- * @param title - label included in thrown override errors
379
- * @returns Fresh merged option object with a null prototype.
380
- * @throws On wrong argument types. {@link TypeError}
381
- * @example
382
- * Merge user overrides onto default options.
383
- * ```ts
384
- * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
385
- * ```
386
- */
387
- function checkOpts(defaults, opts, title = "opts") {
388
- aopts(defaults, "defaults");
389
- if (opts !== void 0) aopts(opts, title);
390
- return Object.assign(Object.create(null), defaults, opts);
391
- }
392
- /**
393
- * Creates a callable hash function from a stateful class constructor.
394
- * @param hashCons - hash constructor or factory
395
- * @param info - optional metadata such as DER OID
396
- * @returns Frozen callable hash wrapper with `.create()`.
397
- * Wrapper construction eagerly calls `hashCons(undefined)` once to read
398
- * `outputLen` / `blockLen`, so constructor side effects happen at module
399
- * init time.
400
- * @throws On wrong argument types. {@link TypeError}
401
- * @example
402
- * Wrap a stateful hash constructor into a callable helper.
403
- * ```ts
404
- * import { createHasher } from '@noble/hashes/utils.js';
405
- * import { sha256 } from '@noble/hashes/sha2.js';
406
- * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
407
- * wrapped(new Uint8Array([1]));
408
- * ```
409
- */
410
- function createHasher(hashCons, info = {}) {
411
- if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
412
- info = checkOpts({}, info, "info");
413
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
414
- const tmp = hashCons(void 0);
415
- hashC.outputLen = tmp.outputLen;
416
- hashC.blockLen = tmp.blockLen;
417
- hashC.canXOF = tmp.canXOF;
418
- hashC.create = (opts) => hashCons(opts);
419
- Object.assign(hashC, info);
420
- return Object.freeze(hashC);
421
- }
422
- /**
423
- * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
424
- * @param bytesLength - number of random bytes to generate
425
- * @returns Random bytes.
426
- * The platform `getRandomValues()` implementation still defines any
427
- * single-call length cap, and this helper rejects oversize requests
428
- * with a stable library `RangeError` instead of host-specific errors.
429
- * @throws On wrong argument types. {@link TypeError}
430
- * @throws On wrong argument ranges or values. {@link RangeError}
431
- * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
432
- * @example
433
- * Generate a fresh random key or nonce.
434
- * ```ts
435
- * const key = randomBytes(16);
436
- * ```
437
- */
438
- function randomBytes$1(bytesLength = 32) {
439
- anumber$1(bytesLength, "bytesLength");
440
- const cr = typeof globalThis === "object" ? globalThis.crypto : null;
441
- if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
442
- if (bytesLength > 65536) throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
443
- return cr.getRandomValues(new Uint8Array(bytesLength));
444
- }
445
- /**
446
- * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
447
- * @param suffix - final OID byte for the selected hash.
448
- * The helper accepts any byte even though only the documented NIST hash
449
- * suffixes are meaningful downstream.
450
- * @returns Object containing the DER-encoded OID.
451
- * @example
452
- * Build OID metadata for a NIST hash.
453
- * ```ts
454
- * oidNist(0x01);
455
- * ```
456
- */
457
- const oidNist = (suffix) => ({ oid: Uint8Array.from([
458
- 6,
459
- 9,
460
- 96,
461
- 134,
462
- 72,
463
- 1,
464
- 101,
465
- 3,
466
- 4,
467
- 2,
468
- suffix
469
- ]) });
470
- //#endregion
471
- //#region ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
472
- /**
473
- * Internal Merkle-Damgard hash utils.
474
- * @module
475
- */
476
- /**
477
- * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
478
- * Returns bits from `b` when `a` is set, otherwise from `c`.
479
- * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
480
- * set the same bit.
481
- * @param a - selector word
482
- * @param b - word chosen when selector bit is set
483
- * @param c - word chosen when selector bit is clear
484
- * @returns Mixed 32-bit word.
485
- * @example
486
- * Combine three words with the shared 32-bit choice primitive.
487
- * ```ts
488
- * Chi(0xffffffff, 0x12345678, 0x87654321);
489
- * ```
490
- */
491
- function Chi(a, b, c) {
492
- return a & b ^ ~a & c;
493
- }
494
- /**
495
- * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
496
- * Returns bits shared by at least two inputs.
497
- * @param a - first input word
498
- * @param b - second input word
499
- * @param c - third input word
500
- * @returns Mixed 32-bit word.
501
- * @example
502
- * Combine three words with the shared 32-bit majority primitive.
503
- * ```ts
504
- * Maj(0xffffffff, 0x12345678, 0x87654321);
505
- * ```
506
- */
507
- function Maj(a, b, c) {
508
- return a & b ^ a & c ^ b & c;
509
- }
510
- /**
511
- * Merkle-Damgard hash construction base class.
512
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
513
- * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
514
- * strings with partial-byte tails.
515
- * @param blockLen - internal block size in bytes
516
- * @param outputLen - digest size in bytes
517
- * @param padOffset - trailing length field size in bytes
518
- * @param isLE - whether length and state words are encoded in little-endian
519
- * @example
520
- * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
521
- * ```ts
522
- * import { _SHA1 } from '@noble/hashes/legacy.js';
523
- * const hash = new _SHA1();
524
- * hash.update(new Uint8Array([97, 98, 99]));
525
- * hash.digest();
526
- * ```
527
- */
528
- var HashMD = class {
529
- blockLen;
530
- outputLen;
531
- canXOF = false;
532
- padOffset;
533
- isLE;
534
- buffer;
535
- view;
536
- finished = false;
537
- length = 0;
538
- pos = 0;
539
- destroyed = false;
540
- constructor(blockLen, outputLen, padOffset, isLE) {
541
- this.blockLen = blockLen;
542
- this.outputLen = outputLen;
543
- this.padOffset = padOffset;
544
- this.isLE = isLE;
545
- this.buffer = new Uint8Array(blockLen);
546
- this.view = createView(this.buffer);
547
- }
548
- update(data) {
549
- aexists(this);
550
- abytes$1(data);
551
- const { view, buffer, blockLen } = this;
552
- const len = data.length;
553
- let processed = false;
554
- for (let pos = 0; pos < len;) {
555
- const take = Math.min(blockLen - this.pos, len - pos);
556
- if (take === blockLen) {
557
- const dataView = createView(data);
558
- for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
559
- processed = true;
560
- continue;
561
- }
562
- buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
563
- this.pos += take;
564
- pos += take;
565
- if (this.pos === blockLen) {
566
- this.process(view, 0);
567
- this.pos = 0;
568
- processed = true;
569
- }
570
- }
571
- this.length += data.length;
572
- if (processed) this.roundClean();
573
- return this;
574
- }
575
- digestInto(out) {
576
- aexists(this);
577
- aoutput(out, this);
578
- this.finished = true;
579
- const { buffer, view, blockLen, isLE } = this;
580
- let { pos } = this;
581
- buffer[pos++] = 128;
582
- buffer.fill(0, pos);
583
- if (this.padOffset > blockLen - pos) {
584
- this.process(view, 0);
585
- buffer.fill(0);
586
- }
587
- setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
588
- this.process(view, 0);
589
- this.roundClean();
590
- const oview = out === buffer ? view : createView(out);
591
- const len = this.outputLen;
592
- const outLen = len / 4;
593
- const state = this.get();
594
- if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
595
- for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
596
- }
597
- digest() {
598
- const { buffer, outputLen } = this;
599
- this.digestInto(buffer);
600
- const res = buffer.slice(0, outputLen);
601
- this.destroy();
602
- return res;
603
- }
604
- _cloneIntoMeta(to) {
605
- const { buffer, length, finished, destroyed, pos } = this;
606
- to.destroyed = destroyed;
607
- to.finished = finished;
608
- to.length = length;
609
- to.pos = pos;
610
- if (pos) to.buffer.set(buffer);
611
- return to;
612
- }
613
- clone() {
614
- return this._cloneInto();
615
- }
616
- };
617
- /**
618
- * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
619
- * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
620
- */
621
- /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
622
- * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
623
- * it as read-only because constructors copy words from it by index. */
624
- const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
625
- 1779033703,
626
- 3144134277,
627
- 1013904242,
628
- 2773480762,
629
- 1359893119,
630
- 2600822924,
631
- 528734635,
632
- 1541459225
633
- ]);
634
- /** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
635
- * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
636
- * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
637
- * constructors copy halves from it by index. */
638
- const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
639
- 1779033703,
640
- 4089235720,
641
- 3144134277,
642
- 2227873595,
643
- 1013904242,
644
- 4271175723,
645
- 2773480762,
646
- 1595750129,
647
- 1359893119,
648
- 2917565137,
649
- 2600822924,
650
- 725511199,
651
- 528734635,
652
- 4215389547,
653
- 1541459225,
654
- 327033209
655
- ]);
656
- //#endregion
657
- //#region ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js
658
- /**
659
- * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
660
- * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
661
- * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
662
- * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
663
- * @module
664
- */
665
- /**
666
- * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
667
- * of the cube roots of the first 64 primes (2..311).
668
- */
669
- const SHA256_K = /* @__PURE__ */ Uint32Array.from([
670
- 1116352408,
671
- 1899447441,
672
- 3049323471,
673
- 3921009573,
674
- 961987163,
675
- 1508970993,
676
- 2453635748,
677
- 2870763221,
678
- 3624381080,
679
- 310598401,
680
- 607225278,
681
- 1426881987,
682
- 1925078388,
683
- 2162078206,
684
- 2614888103,
685
- 3248222580,
686
- 3835390401,
687
- 4022224774,
688
- 264347078,
689
- 604807628,
690
- 770255983,
691
- 1249150122,
692
- 1555081692,
693
- 1996064986,
694
- 2554220882,
695
- 2821834349,
696
- 2952996808,
697
- 3210313671,
698
- 3336571891,
699
- 3584528711,
700
- 113926993,
701
- 338241895,
702
- 666307205,
703
- 773529912,
704
- 1294757372,
705
- 1396182291,
706
- 1695183700,
707
- 1986661051,
708
- 2177026350,
709
- 2456956037,
710
- 2730485921,
711
- 2820302411,
712
- 3259730800,
713
- 3345764771,
714
- 3516065817,
715
- 3600352804,
716
- 4094571909,
717
- 275423344,
718
- 430227734,
719
- 506948616,
720
- 659060556,
721
- 883997877,
722
- 958139571,
723
- 1322822218,
724
- 1537002063,
725
- 1747873779,
726
- 1955562222,
727
- 2024104815,
728
- 2227730452,
729
- 2361852424,
730
- 2428436474,
731
- 2756734187,
732
- 3204031479,
733
- 3329325298
734
- ]);
735
- /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
736
- const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
737
- /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
738
- var SHA2_32B = class extends HashMD {
739
- A = 0;
740
- B = 0;
741
- C = 0;
742
- D = 0;
743
- E = 0;
744
- F = 0;
745
- G = 0;
746
- H = 0;
747
- constructor(outputLen, IV) {
748
- super(64, outputLen, 8, false);
749
- this.A = IV[0] | 0;
750
- this.B = IV[1] | 0;
751
- this.C = IV[2] | 0;
752
- this.D = IV[3] | 0;
753
- this.E = IV[4] | 0;
754
- this.F = IV[5] | 0;
755
- this.G = IV[6] | 0;
756
- this.H = IV[7] | 0;
757
- }
758
- get() {
759
- const { A, B, C, D, E, F, G, H } = this;
760
- return [
761
- A,
762
- B,
763
- C,
764
- D,
765
- E,
766
- F,
767
- G,
768
- H
769
- ];
770
- }
771
- set(A, B, C, D, E, F, G, H) {
772
- this.A = A | 0;
773
- this.B = B | 0;
774
- this.C = C | 0;
775
- this.D = D | 0;
776
- this.E = E | 0;
777
- this.F = F | 0;
778
- this.G = G | 0;
779
- this.H = H | 0;
780
- }
781
- _cloneInto(to) {
782
- (to ||= new this.constructor()).set(...this.get());
783
- return this._cloneIntoMeta(to);
784
- }
785
- process(view, offset) {
786
- for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
787
- for (let i = 16; i < 64; i++) {
788
- const W15 = SHA256_W[i - 15];
789
- const W2 = SHA256_W[i - 2];
790
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
791
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
792
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
793
- }
794
- let { A, B, C, D, E, F, G, H } = this;
795
- for (let i = 0; i < 64; i++) {
796
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
797
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
798
- const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
799
- H = G;
800
- G = F;
801
- F = E;
802
- E = D + T1 | 0;
803
- D = C;
804
- C = B;
805
- B = A;
806
- A = T1 + T2 | 0;
807
- }
808
- A = A + this.A | 0;
809
- B = B + this.B | 0;
810
- C = C + this.C | 0;
811
- D = D + this.D | 0;
812
- E = E + this.E | 0;
813
- F = F + this.F | 0;
814
- G = G + this.G | 0;
815
- H = H + this.H | 0;
816
- this.set(A, B, C, D, E, F, G, H);
817
- }
818
- roundClean() {
819
- clean(SHA256_W);
820
- }
821
- destroy() {
822
- this.destroyed = true;
823
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
824
- clean(this.buffer);
825
- }
826
- };
827
- /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
828
- var _SHA256 = class extends SHA2_32B {
829
- constructor() {
830
- super(32, SHA256_IV);
831
- }
832
- };
833
- const K512 = /* @__PURE__ */ (() => split([
834
- "0x428a2f98d728ae22",
835
- "0x7137449123ef65cd",
836
- "0xb5c0fbcfec4d3b2f",
837
- "0xe9b5dba58189dbbc",
838
- "0x3956c25bf348b538",
839
- "0x59f111f1b605d019",
840
- "0x923f82a4af194f9b",
841
- "0xab1c5ed5da6d8118",
842
- "0xd807aa98a3030242",
843
- "0x12835b0145706fbe",
844
- "0x243185be4ee4b28c",
845
- "0x550c7dc3d5ffb4e2",
846
- "0x72be5d74f27b896f",
847
- "0x80deb1fe3b1696b1",
848
- "0x9bdc06a725c71235",
849
- "0xc19bf174cf692694",
850
- "0xe49b69c19ef14ad2",
851
- "0xefbe4786384f25e3",
852
- "0x0fc19dc68b8cd5b5",
853
- "0x240ca1cc77ac9c65",
854
- "0x2de92c6f592b0275",
855
- "0x4a7484aa6ea6e483",
856
- "0x5cb0a9dcbd41fbd4",
857
- "0x76f988da831153b5",
858
- "0x983e5152ee66dfab",
859
- "0xa831c66d2db43210",
860
- "0xb00327c898fb213f",
861
- "0xbf597fc7beef0ee4",
862
- "0xc6e00bf33da88fc2",
863
- "0xd5a79147930aa725",
864
- "0x06ca6351e003826f",
865
- "0x142929670a0e6e70",
866
- "0x27b70a8546d22ffc",
867
- "0x2e1b21385c26c926",
868
- "0x4d2c6dfc5ac42aed",
869
- "0x53380d139d95b3df",
870
- "0x650a73548baf63de",
871
- "0x766a0abb3c77b2a8",
872
- "0x81c2c92e47edaee6",
873
- "0x92722c851482353b",
874
- "0xa2bfe8a14cf10364",
875
- "0xa81a664bbc423001",
876
- "0xc24b8b70d0f89791",
877
- "0xc76c51a30654be30",
878
- "0xd192e819d6ef5218",
879
- "0xd69906245565a910",
880
- "0xf40e35855771202a",
881
- "0x106aa07032bbd1b8",
882
- "0x19a4c116b8d2d0c8",
883
- "0x1e376c085141ab53",
884
- "0x2748774cdf8eeb99",
885
- "0x34b0bcb5e19b48a8",
886
- "0x391c0cb3c5c95a63",
887
- "0x4ed8aa4ae3418acb",
888
- "0x5b9cca4f7763e373",
889
- "0x682e6ff3d6b2b8a3",
890
- "0x748f82ee5defb2fc",
891
- "0x78a5636f43172f60",
892
- "0x84c87814a1f0ab72",
893
- "0x8cc702081a6439ec",
894
- "0x90befffa23631e28",
895
- "0xa4506cebde82bde9",
896
- "0xbef9a3f7b2c67915",
897
- "0xc67178f2e372532b",
898
- "0xca273eceea26619c",
899
- "0xd186b8c721c0c207",
900
- "0xeada7dd6cde0eb1e",
901
- "0xf57d4f7fee6ed178",
902
- "0x06f067aa72176fba",
903
- "0x0a637dc5a2c898a6",
904
- "0x113f9804bef90dae",
905
- "0x1b710b35131c471b",
906
- "0x28db77f523047d84",
907
- "0x32caab7b40c72493",
908
- "0x3c9ebe0a15c9bebc",
909
- "0x431d67c49c100d4c",
910
- "0x4cc5d4becb3e42b6",
911
- "0x597f299cfc657e2a",
912
- "0x5fcb6fab3ad6faec",
913
- "0x6c44198c4a475817"
914
- ].map((n) => BigInt(n))))();
915
- const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
916
- const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
917
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
918
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
919
- /** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
920
- var SHA2_64B = class extends HashMD {
921
- Ah = 0;
922
- Al = 0;
923
- Bh = 0;
924
- Bl = 0;
925
- Ch = 0;
926
- Cl = 0;
927
- Dh = 0;
928
- Dl = 0;
929
- Eh = 0;
930
- El = 0;
931
- Fh = 0;
932
- Fl = 0;
933
- Gh = 0;
934
- Gl = 0;
935
- Hh = 0;
936
- Hl = 0;
937
- constructor(outputLen, IV) {
938
- super(128, outputLen, 16, false);
939
- this.Ah = IV[0] | 0;
940
- this.Al = IV[1] | 0;
941
- this.Bh = IV[2] | 0;
942
- this.Bl = IV[3] | 0;
943
- this.Ch = IV[4] | 0;
944
- this.Cl = IV[5] | 0;
945
- this.Dh = IV[6] | 0;
946
- this.Dl = IV[7] | 0;
947
- this.Eh = IV[8] | 0;
948
- this.El = IV[9] | 0;
949
- this.Fh = IV[10] | 0;
950
- this.Fl = IV[11] | 0;
951
- this.Gh = IV[12] | 0;
952
- this.Gl = IV[13] | 0;
953
- this.Hh = IV[14] | 0;
954
- this.Hl = IV[15] | 0;
955
- }
956
- get() {
957
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
958
- return [
959
- Ah,
960
- Al,
961
- Bh,
962
- Bl,
963
- Ch,
964
- Cl,
965
- Dh,
966
- Dl,
967
- Eh,
968
- El,
969
- Fh,
970
- Fl,
971
- Gh,
972
- Gl,
973
- Hh,
974
- Hl
975
- ];
976
- }
977
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
978
- this.Ah = Ah | 0;
979
- this.Al = Al | 0;
980
- this.Bh = Bh | 0;
981
- this.Bl = Bl | 0;
982
- this.Ch = Ch | 0;
983
- this.Cl = Cl | 0;
984
- this.Dh = Dh | 0;
985
- this.Dl = Dl | 0;
986
- this.Eh = Eh | 0;
987
- this.El = El | 0;
988
- this.Fh = Fh | 0;
989
- this.Fl = Fl | 0;
990
- this.Gh = Gh | 0;
991
- this.Gl = Gl | 0;
992
- this.Hh = Hh | 0;
993
- this.Hl = Hl | 0;
994
- }
995
- _cloneInto(to) {
996
- (to ||= new this.constructor()).set(...this.get());
997
- return this._cloneIntoMeta(to);
998
- }
999
- process(view, offset) {
1000
- for (let i = 0; i < 16; i++, offset += 4) {
1001
- SHA512_W_H[i] = view.getUint32(offset);
1002
- SHA512_W_L[i] = view.getUint32(offset += 4);
1003
- }
1004
- for (let i = 16; i < 80; i++) {
1005
- const W15h = SHA512_W_H[i - 15] | 0;
1006
- const W15l = SHA512_W_L[i - 15] | 0;
1007
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1008
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1009
- const W2h = SHA512_W_H[i - 2] | 0;
1010
- const W2l = SHA512_W_L[i - 2] | 0;
1011
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1012
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1013
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1014
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1015
- SHA512_W_H[i] = SUMh | 0;
1016
- SHA512_W_L[i] = SUMl | 0;
1017
- }
1018
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1019
- for (let i = 0; i < 80; i++) {
1020
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1021
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1022
- const CHIh = Eh & Fh ^ ~Eh & Gh;
1023
- const CHIl = El & Fl ^ ~El & Gl;
1024
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1025
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1026
- const T1l = T1ll | 0;
1027
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1028
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1029
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1030
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1031
- Hh = Gh | 0;
1032
- Hl = Gl | 0;
1033
- Gh = Fh | 0;
1034
- Gl = Fl | 0;
1035
- Fh = Eh | 0;
1036
- Fl = El | 0;
1037
- ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1038
- Dh = Ch | 0;
1039
- Dl = Cl | 0;
1040
- Ch = Bh | 0;
1041
- Cl = Bl | 0;
1042
- Bh = Ah | 0;
1043
- Bl = Al | 0;
1044
- const All = add3L(T1l, sigma0l, MAJl);
1045
- Ah = add3H(All, T1h, sigma0h, MAJh);
1046
- Al = All | 0;
1047
- }
1048
- ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1049
- ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1050
- ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1051
- ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1052
- ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1053
- ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1054
- ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1055
- ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1056
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1057
- }
1058
- roundClean() {
1059
- clean(SHA512_W_H, SHA512_W_L);
1060
- }
1061
- destroy() {
1062
- this.destroyed = true;
1063
- clean(this.buffer);
1064
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1065
- }
1066
- };
1067
- /** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
1068
- var _SHA512 = class extends SHA2_64B {
1069
- constructor() {
1070
- super(64, SHA512_IV);
1071
- }
1072
- };
1073
- /**
1074
- * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
1075
- *
1076
- * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
1077
- * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1078
- * - Each sha256 hash is executing 2^18 bit operations.
1079
- * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
1080
- * @param msg - message bytes to hash
1081
- * @param opts - Reserved hash options.
1082
- * @returns Digest bytes.
1083
- * @example
1084
- * Hash a message with SHA2-256.
1085
- * ```ts
1086
- * sha256(new Uint8Array([97, 98, 99]));
1087
- * ```
1088
- */
1089
- const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
1090
- /**
1091
- * SHA2-512 hash function from RFC 4634.
1092
- * @param msg - message bytes to hash
1093
- * @param opts - Reserved hash options.
1094
- * @returns Digest bytes.
1095
- * @example
1096
- * Hash a message with SHA2-512.
1097
- * ```ts
1098
- * sha512(new Uint8Array([97, 98, 99]));
1099
- * ```
1100
- */
1101
- const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
1102
- //#endregion
1103
- //#region ../../node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js
1104
- /**
1105
- * Hex, bytes and number utilities.
1106
- * @module
1107
- */
1108
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1109
- /**
1110
- * Validates that a value is an array, optionally validating each element.
1111
- * @param item - Value to validate.
1112
- * @param title - Label included in thrown errors.
1113
- * @param inner - Optional per-element validator, called with the element and its label.
1114
- * @returns The validated array.
1115
- * @example
1116
- * Validate an array of points before batch processing.
1117
- *
1118
- * ```ts
1119
- * aarray([1n, 2n], 'scalars');
1120
- * ```
1121
- */
1122
- function aarray(item, title, inner = () => {}) {
1123
- if (!Array.isArray(item)) throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
1124
- for (let i = 0; i < item.length; i++) inner(item[i], `${title}[${i}]`);
1125
- return item;
1126
- }
1127
- /**
1128
- * Validates that a value is a byte array.
1129
- * @param value - Value to validate.
1130
- * @param length - Optional exact byte length.
1131
- * @param title - Optional field name.
1132
- * @returns Original byte array.
1133
- * @example
1134
- * Reject non-byte input before passing data into curve code.
1135
- *
1136
- * ```ts
1137
- * abytes(new Uint8Array(1));
1138
- * ```
1139
- */
1140
- const abytes = (value, length, title) => abytes$1(value, length, title);
1141
- /**
1142
- * Validates that a value is a non-negative safe integer.
1143
- * @param n - Value to validate.
1144
- * @param title - Optional field name.
1145
- * @returns The validated number.
1146
- * @example
1147
- * Validate a numeric length before allocating buffers.
1148
- *
1149
- * ```ts
1150
- * anumber(1);
1151
- * ```
1152
- */
1153
- const anumber = anumber$1;
1154
- /**
1155
- * Asserts something is a string.
1156
- * @param value - Value to validate.
1157
- * @param title - Label included in thrown errors.
1158
- * @returns The validated string.
1159
- * @throws On wrong argument types. {@link TypeError}
1160
- * @example
1161
- * Validate a label string.
1162
- *
1163
- * ```ts
1164
- * astring('example', 'label');
1165
- * ```
1166
- */
1167
- function astring(value, title = "") {
1168
- if (typeof value !== "string") {
1169
- const prefix = title && `"${title}" `;
1170
- throw new TypeError(prefix + "expected string, got type=" + typeof value);
1171
- }
1172
- return value;
1173
- }
1174
- /**
1175
- * Asserts something is a plain object-ish value, not null or array.
1176
- * @param value - Value to validate.
1177
- * @param title - Label included in thrown errors.
1178
- * @returns The validated object.
1179
- * @throws On wrong argument types. {@link TypeError}
1180
- * @example
1181
- * Validate an options object before checking fields.
1182
- *
1183
- * ```ts
1184
- * aobject({ flag: true });
1185
- * ```
1186
- */
1187
- function aobject(value, title = "object") {
1188
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
1189
- return value;
1190
- }
1191
- /**
1192
- * Asserts something is a function.
1193
- * @param value - Value to validate.
1194
- * @param title - Label included in thrown errors.
1195
- * @returns The validated function.
1196
- * @throws On wrong argument types. {@link TypeError}
1197
- * @example
1198
- * Validate a required method before calling it.
1199
- *
1200
- * ```ts
1201
- * afunction(() => true, 'predicate');
1202
- * ```
1203
- */
1204
- function afunction(value, title) {
1205
- if (typeof value !== "function") throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
1206
- return value;
1207
- }
1208
- /**
1209
- * Encodes bytes as lowercase hex.
1210
- * @param bytes - Bytes to encode.
1211
- * @returns Lowercase hex string.
1212
- * @example
1213
- * Serialize bytes as hex for logging or fixtures.
1214
- *
1215
- * ```ts
1216
- * bytesToHex(Uint8Array.of(1, 2, 3));
1217
- * ```
1218
- */
1219
- const bytesToHex = bytesToHex$1;
1220
- /**
1221
- * Concatenates byte arrays.
1222
- * @param arrays - Byte arrays to join.
1223
- * @returns Concatenated bytes.
1224
- * @example
1225
- * Join domain-separated chunks into one buffer.
1226
- *
1227
- * ```ts
1228
- * concatBytes(Uint8Array.of(1), Uint8Array.of(2));
1229
- * ```
1230
- */
1231
- const concatBytes = (...arrays) => concatBytes$1(...arrays);
1232
- /**
1233
- * Decodes lowercase or uppercase hex into bytes.
1234
- * @param hex - Hex string to decode.
1235
- * @returns Decoded bytes.
1236
- * @example
1237
- * Parse fixture hex into bytes before hashing.
1238
- *
1239
- * ```ts
1240
- * hexToBytes('0102');
1241
- * ```
1242
- */
1243
- const hexToBytes = (hex) => hexToBytes$1(hex);
1244
- /**
1245
- * Checks whether a value is a Uint8Array.
1246
- * @param a - Value to inspect.
1247
- * @returns `true` when `a` is a Uint8Array.
1248
- * @example
1249
- * Branch on byte input before decoding it.
1250
- *
1251
- * ```ts
1252
- * isBytes(new Uint8Array(1));
1253
- * ```
1254
- */
1255
- const isBytes = isBytes$1;
1256
- /**
1257
- * Reads random bytes from the platform CSPRNG.
1258
- * @param bytesLength - Number of random bytes to read.
1259
- * @returns Fresh random bytes.
1260
- * @example
1261
- * Generate a random seed for a keypair.
1262
- *
1263
- * ```ts
1264
- * randomBytes(2);
1265
- * ```
1266
- */
1267
- const randomBytes = (bytesLength) => randomBytes$1(bytesLength);
1268
- const _0n$2 = /* @__PURE__ */ BigInt(0);
1269
- const _1n$2 = /* @__PURE__ */ BigInt(1);
1270
- const atitle = (title) => title ? `"${title}" ` : "";
1271
- /**
1272
- * Validates that a flag is boolean.
1273
- * @param value - Value to validate.
1274
- * @param title - Optional field name.
1275
- * @returns Original value.
1276
- * @throws On wrong argument types. {@link TypeError}
1277
- * @example
1278
- * Reject non-boolean option flags early.
1279
- *
1280
- * ```ts
1281
- * abool(true);
1282
- * ```
1283
- */
1284
- function abool(value, title = "") {
1285
- if (typeof value !== "boolean") throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
1286
- return value;
1287
- }
1288
- /**
1289
- * Validates that a value is a non-negative bigint or safe integer.
1290
- * @param n - Value to validate.
1291
- * @returns The same validated value.
1292
- * @throws On wrong argument ranges or values. {@link RangeError}
1293
- * @example
1294
- * Validate one integer-like value before serializing it.
1295
- *
1296
- * ```ts
1297
- * abignumber(1n);
1298
- * ```
1299
- */
1300
- function abignumber(n) {
1301
- if (typeof n === "bigint") {
1302
- if (!isPosBig(n)) throw new RangeError("positive bigint expected, got " + n);
1303
- } else anumber(n);
1304
- return n;
1305
- }
1306
- /**
1307
- * Validates that a value is a safe integer.
1308
- * @param value - Integer to validate.
1309
- * @param title - Optional field name.
1310
- * @throws On wrong argument types. {@link TypeError}
1311
- * @throws On wrong argument ranges or values. {@link RangeError}
1312
- * @example
1313
- * Validate a window size before scalar arithmetic uses it.
1314
- *
1315
- * ```ts
1316
- * asafenumber(1);
1317
- * ```
1318
- */
1319
- function asafenumber(value, title = "") {
1320
- if (typeof value !== "number") {
1321
- const prefix = title && `"${title}" `;
1322
- throw new TypeError(prefix + "expected number, got type=" + typeof value);
1323
- }
1324
- if (!Number.isSafeInteger(value)) {
1325
- const prefix = title && `"${title}" `;
1326
- throw new RangeError(prefix + "expected safe integer, got " + value);
1327
- }
1328
- }
1329
- /**
1330
- * Encodes a bigint into even-length big-endian hex.
1331
- * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
1332
- * gets one leading zero nibble so the result always represents whole bytes.
1333
- * @param num - Number to encode.
1334
- * @returns Big-endian hex string.
1335
- * @throws On wrong argument ranges or values. {@link RangeError}
1336
- * @example
1337
- * Encode a scalar into hex without a `0x` prefix.
1338
- *
1339
- * ```ts
1340
- * numberToHexUnpadded(255n);
1341
- * ```
1342
- */
1343
- function numberToHexUnpadded(num) {
1344
- const hex = abignumber(num).toString(16);
1345
- return hex.length & 1 ? "0" + hex : hex;
1346
- }
1347
- /**
1348
- * Parses a big-endian hex string into bigint.
1349
- * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
1350
- * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
1351
- * @param hex - Hex string without `0x`.
1352
- * @returns Parsed bigint value.
1353
- * @throws On wrong argument types. {@link TypeError}
1354
- * @example
1355
- * Parse a scalar from fixture hex.
1356
- *
1357
- * ```ts
1358
- * hexToNumber('ff');
1359
- * ```
1360
- */
1361
- function hexToNumber(hex) {
1362
- if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
1363
- return hex === "" ? _0n$2 : BigInt("0x" + hex);
1364
- }
1365
- /**
1366
- * Parses big-endian bytes into bigint.
1367
- * @param bytes - Bytes in big-endian order.
1368
- * @returns Parsed bigint value.
1369
- * @throws On wrong argument types. {@link TypeError}
1370
- * @example
1371
- * Read a scalar encoded in network byte order.
1372
- *
1373
- * ```ts
1374
- * bytesToNumberBE(Uint8Array.of(1, 0));
1375
- * ```
1376
- */
1377
- function bytesToNumberBE(bytes) {
1378
- return hexToNumber(bytesToHex$1(bytes));
1379
- }
1380
- /**
1381
- * Parses little-endian bytes into bigint.
1382
- * @param bytes - Bytes in little-endian order.
1383
- * @returns Parsed bigint value.
1384
- * @throws On wrong argument types. {@link TypeError}
1385
- * @example
1386
- * Read a scalar encoded in little-endian form.
1387
- *
1388
- * ```ts
1389
- * bytesToNumberLE(Uint8Array.of(1, 0));
1390
- * ```
1391
- */
1392
- function bytesToNumberLE(bytes) {
1393
- return hexToNumber(bytesToHex$1(copyBytes(abytes$1(bytes)).reverse()));
1394
- }
1395
- /**
1396
- * Encodes a bigint into fixed-length big-endian bytes.
1397
- * @param n - Number to encode.
1398
- * @param len - Output length in bytes. Must be greater than zero.
1399
- * @returns Big-endian byte array.
1400
- * @throws On wrong argument ranges or values. {@link RangeError}
1401
- * @throws If a documented runtime validation or state check fails. {@link Error}
1402
- * @example
1403
- * Serialize a scalar into a 32-byte field element.
1404
- *
1405
- * ```ts
1406
- * numberToBytesBE(255n, 2);
1407
- * ```
1408
- */
1409
- function numberToBytesBE(n, len) {
1410
- anumber$1(len);
1411
- if (len === 0) throw new Error("zero output length is invalid");
1412
- n = abignumber(n);
1413
- const expectedLen = len * 2;
1414
- const hex = n.toString(16);
1415
- if (hex.length > expectedLen) throw new RangeError("number is too large");
1416
- return hexToBytes$1(hex.padStart(expectedLen, "0"));
1417
- }
1418
- /**
1419
- * Encodes a bigint into fixed-length little-endian bytes.
1420
- * @param n - Number to encode.
1421
- * @param len - Output length in bytes.
1422
- * @returns Little-endian byte array.
1423
- * @throws On wrong argument ranges or values. {@link RangeError}
1424
- * @throws If a documented runtime validation or state check fails. {@link Error}
1425
- * @example
1426
- * Serialize a scalar for little-endian protocols.
1427
- *
1428
- * ```ts
1429
- * numberToBytesLE(255n, 2);
1430
- * ```
1431
- */
1432
- function numberToBytesLE(n, len) {
1433
- return numberToBytesBE(n, len).reverse();
1434
- }
1435
- /**
1436
- * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
1437
- * and Buffer#slice creates mutable copy. Never use Buffers!
1438
- * @param bytes - Bytes to copy.
1439
- * @returns Detached copy.
1440
- * @example
1441
- * Make an isolated copy before mutating serialized bytes.
1442
- *
1443
- * ```ts
1444
- * copyBytes(Uint8Array.of(1, 2, 3));
1445
- * ```
1446
- */
1447
- function copyBytes(bytes) {
1448
- return Uint8Array.from(abytes(bytes));
1449
- }
1450
- /**
1451
- * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
1452
- * Should be safe to use for things expected to be ASCII.
1453
- * Returns exact same result as `TextEncoder` for ASCII or throws.
1454
- * @param ascii - ASCII input text.
1455
- * @returns Encoded bytes.
1456
- * @throws On wrong argument types. {@link TypeError}
1457
- * @example
1458
- * Encode an ASCII domain-separation tag.
1459
- *
1460
- * ```ts
1461
- * asciiToBytes('ABC');
1462
- * ```
1463
- */
1464
- function asciiToBytes(ascii) {
1465
- if (typeof ascii !== "string") throw new TypeError("ascii string expected, got " + typeof ascii);
1466
- return Uint8Array.from(ascii, (c, i) => {
1467
- const charCode = c.charCodeAt(0);
1468
- if (c.length !== 1 || charCode > 127) throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
1469
- return charCode;
1470
- });
1471
- }
1472
- /**
1473
- * Checks whether n is non-negative bigint. Historical name.
1474
- * @param n - candidate value
1475
- * @returns `true` when the value is bigint and 0 or larger
1476
- * @example
1477
- * Check a candidate scalar before range validation.
1478
- *
1479
- * ```ts
1480
- * isPosBig(2n);
1481
- * ```
1482
- */
1483
- function isPosBig(n) {
1484
- return typeof n === "bigint" && _0n$2 <= n;
1485
- }
1486
- /**
1487
- * Checks whether a bigint lies inside a half-open range.
1488
- * @param n - Candidate value.
1489
- * @param min - Inclusive lower bound.
1490
- * @param max - Exclusive upper bound.
1491
- * @returns `true` when the value is inside the range.
1492
- * @example
1493
- * Check whether a candidate scalar fits the field order.
1494
- *
1495
- * ```ts
1496
- * inRange(2n, 1n, 3n);
1497
- * ```
1498
- */
1499
- function inRange(n, min, max) {
1500
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1501
- }
1502
- /**
1503
- * Asserts `min <= n < max`. NOTE: upper bound is exclusive.
1504
- * @param title - Value label for error messages.
1505
- * @param n - Candidate value.
1506
- * @param min - Inclusive lower bound.
1507
- * @param max - Exclusive upper bound.
1508
- * Wrong-type inputs are not separated from out-of-range values here: they still flow through the
1509
- * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
1510
- * @throws On wrong argument ranges or values. {@link RangeError}
1511
- * @example
1512
- * Assert that a bigint stays within one half-open range.
1513
- *
1514
- * ```ts
1515
- * aInRange('x', 2n, 1n, 256n);
1516
- * ```
1517
- */
1518
- function aInRange(title, n, min, max) {
1519
- if (!inRange(n, min, max)) throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1520
- }
1521
- /**
1522
- * Calculates amount of bits in a bigint.
1523
- * Same as `n.toString(2).length`
1524
- * TODO: merge with nLength in modular
1525
- * @param n - Value to inspect.
1526
- * @returns Bit length.
1527
- * @throws If the value is negative. {@link Error}
1528
- * @example
1529
- * Measure the bit length of a scalar before serialization.
1530
- *
1531
- * ```ts
1532
- * bitLen(8n);
1533
- * ```
1534
- */
1535
- function bitLen(n) {
1536
- if (n < _0n$2) throw new Error("expected non-negative bigint, got " + n);
1537
- return n === _0n$2 ? 0 : n.toString(2).length;
1538
- }
1539
- /**
1540
- * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1541
- * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1542
- * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
1543
- * semantics and therefore produce `-1n`.
1544
- * @returns Bitmask value.
1545
- * @example
1546
- * Calculate mask for N bits.
1547
- *
1548
- * ```ts
1549
- * bitMask(4);
1550
- * ```
1551
- */
1552
- const bitMask = (n) => {
1553
- asafenumber(n, "n");
1554
- return (_1n$2 << BigInt(n)) - _1n$2;
1555
- };
1556
- /**
1557
- * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1558
- * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
1559
- * is not rejected here and would make the internal generate loop non-progressing.
1560
- * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
1561
- * @param hmacFn - HMAC implementation.
1562
- * @returns Function that will call DRBG until the predicate returns anything
1563
- * other than `undefined`.
1564
- * @throws On wrong argument types. {@link TypeError}
1565
- * @example
1566
- * Build a deterministic nonce generator for RFC6979-style signing.
1567
- *
1568
- * ```ts
1569
- * import { createHmacDrbg } from '@noble/curves/utils.js';
1570
- * import { hmac } from '@noble/hashes/hmac.js';
1571
- * import { sha256 } from '@noble/hashes/sha2.js';
1572
- * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);
1573
- * const drbg = createHmacDrbg(32, 32, hmacFn);
1574
- * const seed = new Uint8Array(32);
1575
- * drbg(seed, (bytes) => bytes);
1576
- * ```
1577
- */
1578
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1579
- anumber$1(hashLen, "hashLen");
1580
- anumber$1(qByteLen, "qByteLen");
1581
- if (typeof hmacFn !== "function") throw new TypeError("hmacFn must be a function");
1582
- const u8n = (len) => new Uint8Array(len);
1583
- const NULL = Uint8Array.of();
1584
- const byte0 = Uint8Array.of(0);
1585
- const byte1 = Uint8Array.of(1);
1586
- const _maxDrbgIters = 1e3;
1587
- let v = u8n(hashLen);
1588
- let k = u8n(hashLen);
1589
- let i = 0;
1590
- const reset = () => {
1591
- v.fill(1);
1592
- k.fill(0);
1593
- i = 0;
1594
- };
1595
- const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
1596
- const reseed = (seed = NULL) => {
1597
- k = h(byte0, seed);
1598
- v = h();
1599
- if (seed.length === 0) return;
1600
- k = h(byte1, seed);
1601
- v = h();
1602
- };
1603
- const gen = () => {
1604
- if (i++ >= _maxDrbgIters) throw new Error("drbg: tried max amount of iterations");
1605
- let len = 0;
1606
- const out = [];
1607
- while (len < qByteLen) {
1608
- v = h();
1609
- const sl = v.slice();
1610
- out.push(sl);
1611
- len += v.length;
1612
- }
1613
- return concatBytes(...out);
1614
- };
1615
- const genUntil = (seed, pred) => {
1616
- reset();
1617
- reseed(seed);
1618
- let res = void 0;
1619
- while ((res = pred(gen())) === void 0) reseed();
1620
- reset();
1621
- return res;
1622
- };
1623
- return genUntil;
1624
- }
1625
- /**
1626
- * Validates declared required and optional field types on a plain object.
1627
- * Extra keys are intentionally ignored because many callers validate only the subset they use from
1628
- * richer option bags or runtime objects.
1629
- * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
1630
- * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.
1631
- * @param object - Object to validate.
1632
- * @param fields - Required field types.
1633
- * @param optFields - Optional field types.
1634
- * @param title - Object label included in thrown errors.
1635
- * @throws On wrong argument types. {@link TypeError}
1636
- * @example
1637
- * Check user options before building a curve helper.
1638
- *
1639
- * ```ts
1640
- * validateObject({ flag: true }, { flag: 'boolean' });
1641
- * ```
1642
- */
1643
- function validateObject(object, fields = {}, optFields = {}, title = "object") {
1644
- aobject(object, title);
1645
- aobject(fields, "fields");
1646
- aobject(optFields, "optFields");
1647
- function checkField(fieldName, expectedType, isOpt) {
1648
- const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
1649
- const val = object[fieldName];
1650
- if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) throw new TypeError(`${label} is invalid: expected own property`);
1651
- if (isOpt && val === void 0) return;
1652
- const current = typeof val;
1653
- if (current !== expectedType || val === null) throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
1654
- }
1655
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1656
- iter(fields, false);
1657
- iter(optFields, true);
1658
- }
1659
- //#endregion
1660
- //#region ../../node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js
1661
- /**
1662
- * Utils for modular division and fields.
1663
- * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
1664
- * There is no division: it is replaced by modular multiplicative inverse.
1665
- * @module
1666
- */
1667
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1668
- const _0n$1 = /* @__PURE__ */ BigInt(0);
1669
- const _1n$1 = /* @__PURE__ */ BigInt(1);
1670
- const _2n = /* @__PURE__ */ BigInt(2);
1671
- const _3n = /* @__PURE__ */ BigInt(3);
1672
- const _4n$1 = /* @__PURE__ */ BigInt(4);
1673
- const _5n = /* @__PURE__ */ BigInt(5);
1674
- const _7n = /* @__PURE__ */ BigInt(7);
1675
- const _8n = /* @__PURE__ */ BigInt(8);
1676
- const _9n = /* @__PURE__ */ BigInt(9);
1677
- const _15n = /* @__PURE__ */ BigInt(15);
1678
- const _16n = /* @__PURE__ */ BigInt(16);
1679
- const POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
1680
- /**
1681
- * @param a - Dividend value.
1682
- * @param b - Positive modulus.
1683
- * @returns Reduced value in `[0, b)` only when `b` is positive.
1684
- * @throws If the modulus is not positive. {@link Error}
1685
- * @example
1686
- * Normalize a bigint into one field residue.
1687
- *
1688
- * ```ts
1689
- * mod(-1n, 5n);
1690
- * ```
1691
- */
1692
- function mod(a, b) {
1693
- if (b <= _0n$1) throw new Error("mod: expected positive modulus, got " + b);
1694
- const result = a % b;
1695
- return result >= _0n$1 ? result : b + result;
1696
- }
1697
- /**
1698
- * Efficiently raise num to a power with modular reduction.
1699
- * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1700
- * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
1701
- * modulus instead of relying on the `power===0/1` fast paths to normalize it.
1702
- * @param num - Base value.
1703
- * @param power - Exponent value.
1704
- * @param modulo - Reduction modulus.
1705
- * @returns Modular exponentiation result.
1706
- * @throws If the modulus or exponent is invalid. {@link Error}
1707
- * @example
1708
- * Raise one bigint to a modular power.
1709
- *
1710
- * ```ts
1711
- * pow(2n, 6n, 11n) // 64n % 11n == 9n
1712
- * ```
1713
- */
1714
- function pow(num, power, modulo) {
1715
- if (modulo <= _1n$1) throw new Error("pow: expected modulus > 1, got " + modulo);
1716
- if (typeof power !== "bigint") throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
1717
- if (power < _0n$1) throw new Error("invalid exponent, negatives unsupported");
1718
- if (power === _0n$1) return _1n$1;
1719
- if (power === _1n$1) return num;
1720
- let d = num % modulo;
1721
- if (d < _0n$1) d += modulo;
1722
- if (power < POW_WINDOWED_MIN) {
1723
- let p = _1n$1;
1724
- while (power > _0n$1) {
1725
- if (power & _1n$1) p = p * d % modulo;
1726
- d = d * d % modulo;
1727
- power >>= _1n$1;
1728
- }
1729
- return p;
1730
- }
1731
- const digits = [];
1732
- while (power > _0n$1) {
1733
- digits.push(Number(power & _15n));
1734
- power >>= _4n$1;
1735
- }
1736
- const table = new Array(16);
1737
- table[0] = _1n$1;
1738
- table[1] = d;
1739
- for (let i = 2; i < 16; i++) table[i] = table[i - 1] * d % modulo;
1740
- let p = table[digits[digits.length - 1]];
1741
- for (let w = digits.length - 2; w >= 0; w--) {
1742
- p = p * p % modulo;
1743
- p = p * p % modulo;
1744
- p = p * p % modulo;
1745
- p = p * p % modulo;
1746
- const digit = digits[w];
1747
- if (digit !== 0) p = p * table[digit] % modulo;
1748
- }
1749
- return p;
1750
- }
1751
- /**
1752
- * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
1753
- * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
1754
- * modulus; the `power===0` fast path intentionally returns the input unchanged.
1755
- * @param x - Base value.
1756
- * @param power - Number of squarings.
1757
- * @param modulo - Reduction modulus.
1758
- * @returns Repeated-squaring result.
1759
- * @throws If the exponent is negative. {@link Error}
1760
- * @example
1761
- * Apply repeated squaring inside one field.
1762
- *
1763
- * ```ts
1764
- * pow2(3n, 2n, 11n);
1765
- * ```
1766
- */
1767
- function pow2(x, power, modulo) {
1768
- if (modulo <= _1n$1) throw new Error("pow2: expected modulus > 1, got " + modulo);
1769
- if (power < _0n$1) throw new Error("pow2: expected non-negative exponent, got " + power);
1770
- let res = x;
1771
- while (power-- > _0n$1) {
1772
- res *= res;
1773
- res %= modulo;
1774
- }
1775
- return res;
1776
- }
1777
- /**
1778
- * Inverses number over modulo.
1779
- * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
1780
- * @param number - Value to invert.
1781
- * @param modulo - Modulus greater than 1.
1782
- * @returns Multiplicative inverse.
1783
- * @throws If the modulus is invalid or the inverse does not exist. {@link Error}
1784
- * @example
1785
- * Compute one modular inverse with the extended Euclidean algorithm.
1786
- *
1787
- * ```ts
1788
- * invert(3n, 11n);
1789
- * ```
1790
- */
1791
- function invert(number, modulo) {
1792
- if (number === _0n$1) throw new Error("invert: expected non-zero number");
1793
- if (modulo <= _1n$1) throw new Error("invert: expected modulus > 1, got " + modulo);
1794
- let a = mod(number, modulo);
1795
- let b = modulo;
1796
- let x = _0n$1, u = _1n$1;
1797
- while (a !== _0n$1) {
1798
- const q = b / a;
1799
- const r = b - a * q;
1800
- const m = x - u * q;
1801
- b = a, a = r, x = u, u = m;
1802
- }
1803
- if (b !== _1n$1) throw new Error("invert: does not exist");
1804
- return mod(x, modulo);
1805
- }
1806
- /**
1807
- * Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.
1808
- *
1809
- * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the
1810
- * underlying square-and-multiply has the same control flow for every secret `a`: there is no
1811
- * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style
1812
- * ECDSA nonce-inversion attacks). This is only "algorithmically" constant-time — JS bigint
1813
- * multiplication/reduction is still value-dependent — and it is roughly 4x slower than
1814
- * {@link invert}.
1815
- *
1816
- * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be
1817
- * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error
1818
- * instead of returning a wrong value.
1819
- * @param a - Value to invert.
1820
- * @param prime - Prime modulus.
1821
- * @returns Multiplicative inverse in `[1, prime)`.
1822
- * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.
1823
- * {@link Error}
1824
- * @example
1825
- * Compute one modular inverse without secret-dependent branching.
1826
- *
1827
- * ```ts
1828
- * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)
1829
- * ```
1830
- */
1831
- function invertCt(a, prime) {
1832
- if (prime <= _1n$1) throw new Error("invertCt: expected prime modulus > 1, got " + prime);
1833
- const an = mod(a, prime);
1834
- if (an === _0n$1) throw new Error("invertCt: expected non-zero number");
1835
- const inverse = pow(an, prime - _2n, prime);
1836
- if (mod(an * inverse, prime) !== _1n$1) throw new Error("invertCt: does not exist");
1837
- return inverse;
1838
- }
1839
- function assertIsSquare(Fp, root, n) {
1840
- const F = Fp;
1841
- if (!F.eql(F.sqr(root), n)) throw new Error("Cannot find square root");
1842
- }
1843
- function aoddModulus(order, fnName) {
1844
- if ((order & _1n$1) === _0n$1) throw new Error(fnName + ": expected odd modulus, got " + order);
1845
- }
1846
- function sqrt3mod4(Fp, n) {
1847
- const F = Fp;
1848
- const p1div4 = (F.ORDER + _1n$1) / _4n$1;
1849
- const root = F.pow(n, p1div4);
1850
- assertIsSquare(F, root, n);
1851
- return root;
1852
- }
1853
- function sqrt5mod8(Fp, n) {
1854
- const F = Fp;
1855
- const p5div8 = (F.ORDER - _5n) / _8n;
1856
- const n2 = F.mul(n, _2n);
1857
- const v = F.pow(n2, p5div8);
1858
- const nv = F.mul(n, v);
1859
- const i = F.mul(F.mul(nv, _2n), v);
1860
- const root = F.mul(nv, F.sub(i, F.ONE));
1861
- assertIsSquare(F, root, n);
1862
- return root;
1863
- }
1864
- function sqrt9mod16(P) {
1865
- const Fp_ = Field(P);
1866
- const tn = tonelliShanks(P);
1867
- const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1868
- const c2 = tn(Fp_, c1);
1869
- const c3 = tn(Fp_, Fp_.neg(c1));
1870
- const c4 = (P + _7n) / _16n;
1871
- return ((Fp, n) => {
1872
- const F = Fp;
1873
- let tv1 = F.pow(n, c4);
1874
- let tv2 = F.mul(tv1, c1);
1875
- const tv3 = F.mul(tv1, c2);
1876
- const tv4 = F.mul(tv1, c3);
1877
- const e1 = F.eql(F.sqr(tv2), n);
1878
- const e2 = F.eql(F.sqr(tv3), n);
1879
- tv1 = F.cmov(tv1, tv2, e1);
1880
- tv2 = F.cmov(tv4, tv3, e2);
1881
- const e3 = F.eql(F.sqr(tv2), n);
1882
- const root = F.cmov(tv1, tv2, e3);
1883
- assertIsSquare(F, root, n);
1884
- return root;
1885
- });
1886
- }
1887
- /**
1888
- * Tonelli-Shanks square root search algorithm.
1889
- * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
1890
- * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
1891
- * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
1892
- * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
1893
- * @param P - field order
1894
- * @returns function that takes field Fp (created from P) and number n
1895
- * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
1896
- * @example
1897
- * Construct a square-root helper for primes that need Tonelli-Shanks.
1898
- *
1899
- * ```ts
1900
- * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
1901
- * const Fp = Field(17n);
1902
- * const sqrt = tonelliShanks(17n)(Fp, 4n);
1903
- * ```
1904
- */
1905
- function tonelliShanks(P) {
1906
- if (P < _3n) throw new Error("sqrt is not defined for small field");
1907
- aoddModulus(P, "tonelliShanks");
1908
- let Q = P - _1n$1;
1909
- let S = 0;
1910
- while (Q % _2n === _0n$1) {
1911
- Q /= _2n;
1912
- S++;
1913
- }
1914
- let Z = _2n;
1915
- const _Fp = Field(P);
1916
- while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
1917
- if (S === 1) return sqrt3mod4;
1918
- let cc = _Fp.pow(Z, Q);
1919
- const Q1div2 = (Q + _1n$1) / _2n;
1920
- return function tonelliSlow(Fp, n) {
1921
- const F = Fp;
1922
- if (F.is0(n)) return n;
1923
- if (FpLegendre(F, n) !== 1) throw new Error("Cannot find square root");
1924
- let M = S;
1925
- let c = F.mul(F.ONE, cc);
1926
- let t = F.pow(n, Q);
1927
- let R = F.pow(n, Q1div2);
1928
- while (!F.eql(t, F.ONE)) {
1929
- if (F.is0(t)) throw new Error("Cannot find square root: probably non-prime P");
1930
- let i = 1;
1931
- let t_tmp = F.sqr(t);
1932
- while (!F.eql(t_tmp, F.ONE)) {
1933
- i++;
1934
- t_tmp = F.sqr(t_tmp);
1935
- if (i === M) throw new Error("Cannot find square root");
1936
- }
1937
- const exponent = _1n$1 << BigInt(M - i - 1);
1938
- const b = F.pow(c, exponent);
1939
- M = i;
1940
- c = F.sqr(b);
1941
- t = F.mul(t, c);
1942
- R = F.mul(R, b);
1943
- }
1944
- return R;
1945
- };
1946
- }
1947
- /**
1948
- * Square root for a finite field. Will try optimized versions first:
1949
- *
1950
- * 1. P ≡ 3 (mod 4)
1951
- * 2. P ≡ 5 (mod 8)
1952
- * 3. P ≡ 9 (mod 16)
1953
- * 4. Tonelli-Shanks algorithm
1954
- *
1955
- * Different algorithms can give different roots, it is up to user to decide which one they want.
1956
- * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
1957
- * (used for hash-to-curve).
1958
- * @param P - Field order.
1959
- * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
1960
- * behavior and this selector assumes prime-field-style integer moduli.
1961
- * @throws If the field is unsupported or the square root does not exist. {@link Error}
1962
- * @example
1963
- * Choose the square-root helper appropriate for one field modulus.
1964
- *
1965
- * ```ts
1966
- * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
1967
- * const Fp = Field(17n);
1968
- * const sqrt = FpSqrt(17n)(Fp, 4n);
1969
- * ```
1970
- */
1971
- function FpSqrt(P) {
1972
- aoddModulus(P, "Fp.sqrt");
1973
- if (P % _4n$1 === _3n) return sqrt3mod4;
1974
- if (P % _8n === _5n) return sqrt5mod8;
1975
- if (P % _16n === _9n) return sqrt9mod16(P);
1976
- return tonelliShanks(P);
1977
- }
1978
- /**
1979
- * @param num - Value to inspect.
1980
- * @param modulo - Field modulus.
1981
- * @returns `true` when the least-significant little-endian bit is set.
1982
- * @throws If the modulus is invalid for `mod(...)`. {@link Error}
1983
- * @example
1984
- * Inspect the low bit used by little-endian sign conventions.
1985
- *
1986
- * ```ts
1987
- * isNegativeLE(3n, 11n);
1988
- * ```
1989
- */
1990
- const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$1) === _1n$1;
1991
- const FIELD_FIELDS = [
1992
- "create",
1993
- "isValid",
1994
- "is0",
1995
- "neg",
1996
- "inv",
1997
- "sqrt",
1998
- "sqr",
1999
- "eql",
2000
- "add",
2001
- "sub",
2002
- "mul",
2003
- "pow",
2004
- "div",
2005
- "addN",
2006
- "subN",
2007
- "mulN",
2008
- "sqrN"
2009
- ];
2010
- /**
2011
- * @param field - Field implementation.
2012
- * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
2013
- * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
2014
- * field-specific extras beyond positive `BYTES` / `BITS`.
2015
- * @throws If the field shape or numeric metadata are invalid. {@link Error}
2016
- * @example
2017
- * Check that a field implementation exposes the operations curve code expects.
2018
- *
2019
- * ```ts
2020
- * import { Field, validateField } from '@noble/curves/abstract/modular.js';
2021
- * const Fp = validateField(Field(17n));
2022
- * ```
2023
- */
2024
- function validateField(field) {
2025
- aobject(field, "field");
2026
- if (typeof field.ORDER !== "bigint") throw new TypeError("param \"ORDER\" is invalid: expected bigint, got " + typeof field.ORDER);
2027
- asafenumber(field.BYTES, "BYTES");
2028
- asafenumber(field.BITS, "BITS");
2029
- for (const name of FIELD_FIELDS) afunction(field[name], "field." + name);
2030
- if (field.BYTES < 1 || field.BITS < 1) throw new Error("invalid field: expected BYTES/BITS > 0");
2031
- if (field.ORDER <= _1n$1) throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
2032
- return field;
2033
- }
2034
- function FpInvertBatch(Fp, nums, passZero = false) {
2035
- validateField(Fp);
2036
- aarray(nums, "nums");
2037
- abool(passZero, "passZero");
2038
- const F = Fp;
2039
- const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
2040
- const multipliedAcc = nums.reduce((acc, num, i) => {
2041
- if (F.is0(num)) return acc;
2042
- inverted[i] = acc;
2043
- return F.mul(acc, num);
2044
- }, F.ONE);
2045
- const invertedAcc = F.inv(multipliedAcc);
2046
- nums.reduceRight((acc, num, i) => {
2047
- if (F.is0(num)) return acc;
2048
- inverted[i] = F.mul(acc, inverted[i]);
2049
- return F.mul(acc, num);
2050
- }, invertedAcc);
2051
- return inverted;
2052
- }
2053
- /**
2054
- * Legendre symbol.
2055
- * Legendre constant is used to calculate Legendre symbol (a | p)
2056
- * which denotes the value of a^((p-1)/2) (mod p).
2057
- *
2058
- * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
2059
- * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
2060
- * * (a | p) ≡ 0 if a ≡ 0 (mod p)
2061
- * @param Fp - Field implementation.
2062
- * @param n - Value to inspect.
2063
- * @returns Legendre symbol.
2064
- * @throws If the powered value does not match a valid Legendre symbol. {@link Error}
2065
- * @example
2066
- * Compute the Legendre symbol of one field element.
2067
- *
2068
- * ```ts
2069
- * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
2070
- * const Fp = Field(17n);
2071
- * const symbol = FpLegendre(Fp, 4n);
2072
- * ```
2073
- */
2074
- function FpLegendre(Fp, n) {
2075
- validateField(Fp);
2076
- const F = Fp;
2077
- aoddModulus(F.ORDER, "FpLegendre");
2078
- const p1mod2 = (F.ORDER - _1n$1) / _2n;
2079
- const powered = F.pow(n, p1mod2);
2080
- const yes = F.eql(powered, F.ONE);
2081
- const zero = F.eql(powered, F.ZERO);
2082
- const no = F.eql(powered, F.neg(F.ONE));
2083
- if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
2084
- return yes ? 1 : zero ? 0 : -1;
2085
- }
2086
- /**
2087
- * @param n - Curve order. Callers are expected to pass a positive order.
2088
- * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
2089
- * value when overriding the derived bit length.
2090
- * @returns Byte and bit lengths.
2091
- * @throws If the order or cached bit length is invalid. {@link Error}
2092
- * @example
2093
- * Measure the encoding sizes needed for one modulus.
2094
- *
2095
- * ```ts
2096
- * nLength(255n);
2097
- * ```
2098
- */
2099
- function nLength(n, nBitLength) {
2100
- if (nBitLength !== void 0) anumber(nBitLength);
2101
- if (n <= _0n$1) throw new Error("invalid n length: expected positive n, got " + n);
2102
- if (nBitLength !== void 0 && nBitLength < 1) throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
2103
- const bits = bitLen(n);
2104
- if (nBitLength !== void 0 && nBitLength < bits) throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
2105
- const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
2106
- return {
2107
- nBitLength: _nBitLength,
2108
- nByteLength: Math.ceil(_nBitLength / 8)
2109
- };
2110
- }
2111
- const FIELD_SQRT = /* @__PURE__ */ new WeakMap();
2112
- var _Field = class {
2113
- ORDER;
2114
- BITS;
2115
- BYTES;
2116
- isLE;
2117
- ZERO = _0n$1;
2118
- ONE = _1n$1;
2119
- _lengths;
2120
- _mod;
2121
- constructor(ORDER, opts = {}) {
2122
- if (ORDER <= _1n$1) throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
2123
- let _nbitLength = void 0;
2124
- this.isLE = false;
2125
- if (opts != null && typeof opts === "object") {
2126
- if (typeof opts.BITS === "number") _nbitLength = opts.BITS;
2127
- if (typeof opts.sqrt === "function") Object.defineProperty(this, "sqrt", {
2128
- value: opts.sqrt,
2129
- enumerable: true
2130
- });
2131
- if (typeof opts.isLE === "boolean") this.isLE = opts.isLE;
2132
- if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());
2133
- if (typeof opts.modFromBytes === "boolean") this._mod = opts.modFromBytes;
2134
- }
2135
- const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
2136
- if (nByteLength > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
2137
- this.ORDER = ORDER;
2138
- this.BITS = nBitLength;
2139
- this.BYTES = nByteLength;
2140
- Object.freeze(this);
2141
- }
2142
- create(num) {
2143
- return mod(num, this.ORDER);
2144
- }
2145
- isValid(num) {
2146
- if (typeof num !== "bigint") throw new TypeError("invalid field element: expected bigint, got " + typeof num);
2147
- return _0n$1 <= num && num < this.ORDER;
2148
- }
2149
- is0(num) {
2150
- return num === _0n$1;
2151
- }
2152
- isValidNot0(num) {
2153
- return !this.is0(num) && this.isValid(num);
2154
- }
2155
- isOdd(num) {
2156
- return (num & _1n$1) === _1n$1;
2157
- }
2158
- neg(num) {
2159
- return mod(-num, this.ORDER);
2160
- }
2161
- eql(lhs, rhs) {
2162
- return lhs === rhs;
2163
- }
2164
- sqr(num) {
2165
- return mod(num * num, this.ORDER);
2166
- }
2167
- add(lhs, rhs) {
2168
- return mod(lhs + rhs, this.ORDER);
2169
- }
2170
- sub(lhs, rhs) {
2171
- return mod(lhs - rhs, this.ORDER);
2172
- }
2173
- mul(lhs, rhs) {
2174
- return mod(lhs * rhs, this.ORDER);
2175
- }
2176
- pow(num, power) {
2177
- return pow(num, power, this.ORDER);
2178
- }
2179
- div(lhs, rhs) {
2180
- return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
2181
- }
2182
- sqrN(num) {
2183
- return num * num;
2184
- }
2185
- addN(lhs, rhs) {
2186
- return lhs + rhs;
2187
- }
2188
- subN(lhs, rhs) {
2189
- return lhs - rhs;
2190
- }
2191
- mulN(lhs, rhs) {
2192
- return lhs * rhs;
2193
- }
2194
- inv(num) {
2195
- return invert(num, this.ORDER);
2196
- }
2197
- sqrt(num) {
2198
- let sqrt = FIELD_SQRT.get(this);
2199
- if (!sqrt) FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
2200
- return sqrt(this, num);
2201
- }
2202
- toBytes(num) {
2203
- return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
2204
- }
2205
- fromBytes(bytes, skipValidation = false) {
2206
- abytes(bytes);
2207
- const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
2208
- if (allowedLengths) {
2209
- if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
2210
- const padded = new Uint8Array(BYTES);
2211
- padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
2212
- bytes = padded;
2213
- }
2214
- if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
2215
- let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
2216
- if (modFromBytes) scalar = mod(scalar, ORDER);
2217
- if (!skipValidation) {
2218
- if (!this.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
2219
- }
2220
- return scalar;
2221
- }
2222
- invertBatch(lst) {
2223
- return FpInvertBatch(this, lst, true);
2224
- }
2225
- cmov(a, b, condition) {
2226
- abool(condition, "condition");
2227
- return condition ? b : a;
2228
- }
2229
- };
2230
- /**
2231
- * Creates a finite field. Major performance optimizations:
2232
- * * 1. Denormalized operations like mulN instead of mul.
2233
- * * 2. Identical object shape: never add or remove keys.
2234
- * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
2235
- * Fragile: always run a benchmark on a change.
2236
- * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
2237
- * all elements for performance and protocol-flexibility reasons; callers are responsible for
2238
- * supplying valid elements when they need canonical field behavior.
2239
- * This is low-level code, please make sure you know what you're doing.
2240
- *
2241
- * Note about field properties:
2242
- * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
2243
- * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
2244
- *
2245
- * @param ORDER - field order, probably prime, or could be composite
2246
- * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
2247
- * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
2248
- * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
2249
- * @example
2250
- * Construct one prime field with optional overrides.
2251
- *
2252
- * ```ts
2253
- * Field(11n);
2254
- * ```
2255
- */
2256
- function Field(ORDER, opts = {}) {
2257
- Object.freeze(_Field.prototype);
2258
- return new _Field(ORDER, opts);
2259
- }
2260
- /**
2261
- * Returns total number of bytes consumed by the field element.
2262
- * For example, 32 bytes for usual 256-bit weierstrass curve.
2263
- * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
2264
- * order greater than 1.
2265
- * @returns byte length of field
2266
- * @throws If the field order is not a bigint. {@link Error}
2267
- * @example
2268
- * Read the fixed-width byte length of one field.
2269
- *
2270
- * ```ts
2271
- * getFieldBytesLength(255n);
2272
- * ```
2273
- */
2274
- function getFieldBytesLength(fieldOrder) {
2275
- if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
2276
- if (fieldOrder <= _1n$1) throw new Error("field order must be greater than 1");
2277
- const bitLength = bitLen(fieldOrder - _1n$1);
2278
- return Math.ceil(bitLength / 8);
2279
- }
2280
- /**
2281
- * Returns minimal amount of bytes that can be safely reduced
2282
- * by field order.
2283
- * Should be 2^-128 for 128-bit curve such as P256.
2284
- * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
2285
- * absolute floor for policy reasons.
2286
- * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
2287
- * @returns byte length of target hash
2288
- * @throws If the field order is invalid. {@link Error}
2289
- * @example
2290
- * Compute the minimum hash length needed for field reduction.
2291
- *
2292
- * ```ts
2293
- * getMinHashLength(255n);
2294
- * ```
2295
- */
2296
- function getMinHashLength(fieldOrder) {
2297
- const length = getFieldBytesLength(fieldOrder);
2298
- return length + Math.ceil(length / 2);
2299
- }
2300
- /**
2301
- * "Constant-time" private key generation utility.
2302
- * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
2303
- * and convert them into private scalar, with the modulo bias being negligible.
2304
- * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
2305
- * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
2306
- * accidentally acceptable for real scalar derivation.
2307
- * 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},
2308
- * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
2309
- * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
2310
- * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
2311
- * @param key - Uniform input bytes.
2312
- * @param fieldOrder - Size of subgroup.
2313
- * @param isLE - interpret hash bytes as LE num
2314
- * @returns valid private scalar
2315
- * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
2316
- * @example
2317
- * Map hash output into a private scalar range.
2318
- *
2319
- * ```ts
2320
- * mapHashToField(new Uint8Array(48).fill(1), 255n);
2321
- * ```
2322
- */
2323
- function mapHashToField(key, fieldOrder, isLE = false) {
2324
- abytes(key);
2325
- const len = key.length;
2326
- const fieldLen = getFieldBytesLength(fieldOrder);
2327
- const minLen = Math.max(getMinHashLength(fieldOrder), 16);
2328
- if (len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
2329
- const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$1) + _1n$1;
2330
- return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
2331
- }
2332
- //#endregion
2333
- //#region ../../node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js
2334
- /**
2335
- * Methods for elliptic curve multiplication by scalars.
2336
- * Contains wNAF-based ScalarMultiplier, pippenger.
2337
- * @module
2338
- */
2339
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2340
- const _0n = /* @__PURE__ */ BigInt(0);
2341
- const _1n = /* @__PURE__ */ BigInt(1);
2342
- const _4n = /* @__PURE__ */ BigInt(4);
2343
- const BLIND_BYTES = 16;
2344
- const BLIND_BITS = 128;
2345
- const FW_WINDOW = 5;
2346
- const TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
2347
- /**
2348
- * Validates the static surface of a point constructor.
2349
- * This is only a cheap sanity check for the constructor hooks and fields consumed by generic
2350
- * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
2351
- * @param Point - Runtime point constructor.
2352
- * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
2353
- * @example
2354
- * Check that one point constructor exposes the static hooks generic helpers need.
2355
- *
2356
- * ```ts
2357
- * import { ed25519 } from '@noble/curves/ed25519.js';
2358
- * import { validatePointCons } from '@noble/curves/abstract/curve.js';
2359
- * validatePointCons(ed25519.Point);
2360
- * ```
2361
- */
2362
- function validatePointCons(Point) {
2363
- const pc = Point;
2364
- if (typeof pc !== "function") throw new TypeError("\"Point\" expected constructor, got type=" + typeof Point);
2365
- afunction(pc.fromAffine, "Point.fromAffine");
2366
- afunction(pc.fromBytes, "Point.fromBytes");
2367
- afunction(pc.fromHex, "Point.fromHex");
2368
- aobject(pc.BASE, "Point.BASE");
2369
- aobject(pc.ZERO, "Point.ZERO");
2370
- validateField(pc.Fp);
2371
- validateField(pc.Fn);
2372
- }
2373
- /**
2374
- * Takes a bunch of Projective Points but executes only one
2375
- * inversion on all of them. Inversion is very slow operation,
2376
- * so this improves performance massively.
2377
- * Optimization: converts a list of projective points to a list of identical points with Z=1.
2378
- * Input points are left unchanged; the normalized points are returned as fresh instances.
2379
- * @param c - Point constructor.
2380
- * @param points - Projective points.
2381
- * @returns Fresh projective points reconstructed from normalized affine coordinates.
2382
- * @example
2383
- * Batch-normalize projective points with a single shared inversion.
2384
- *
2385
- * ```ts
2386
- * import { normalizeZ } from '@noble/curves/abstract/curve.js';
2387
- * import { p256 } from '@noble/curves/nist.js';
2388
- * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
2389
- * ```
2390
- */
2391
- function normalizeZ(c, points) {
2392
- validatePointCons(c);
2393
- validateMSMPoints(points, c);
2394
- const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
2395
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
2396
- }
2397
- function validateW(W, bits, min = 1) {
2398
- if (!Number.isSafeInteger(W) || W < min || W > bits) throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
2399
- }
2400
- function validateTableBytes(numPoints, fpBytes) {
2401
- const bytes = numPoints * (4 * fpBytes + 128);
2402
- if (bytes > TABLE_BYTES_MAX) throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
2403
- }
2404
- /**
2405
- * Probes an RNG once, at construction time: returns `undefined` when it is unavailable —
2406
- * throws or returns malformed bytes — so callers can downgrade to their unblinded /
2407
- * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template
2408
- * hardening), not a correctness or key-secrecy requirement, so availability-based
2409
- * downgrade is acceptable.
2410
- *
2411
- * The downgrade decision is deliberately static. After a successful probe the RNG becomes
2412
- * part of the trusted contract: later misbehavior must fail closed in per-call validation
2413
- * (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip
2414
- * blinding on demand. A probe can only ever classify broken environments, not adversarial
2415
- * RNGs: a stateful RNG can always behave while probed and misbehave later.
2416
- * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.
2417
- * @param length - Byte length requested from the probe call.
2418
- * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.
2419
- * @example
2420
- * Probe an RNG once before enabling scalar blinding.
2421
- *
2422
- * ```ts
2423
- * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';
2424
- * import { randomBytes } from '@noble/hashes/utils.js';
2425
- * const rng = probeRandomBytes(randomBytes, 16);
2426
- * ```
2427
- */
2428
- function probeRandomBytes(randomBytes, length) {
2429
- if (randomBytes === void 0) return void 0;
2430
- afunction(randomBytes, "randomBytes");
2431
- try {
2432
- const probe = randomBytes(length);
2433
- if (!isBytes(probe) || probe.length !== length) return void 0;
2434
- } catch {
2435
- return;
2436
- }
2437
- return randomBytes;
2438
- }
2439
- function validateMSMPoints(points, c) {
2440
- aarray(points, "points");
2441
- points.forEach((p, i) => {
2442
- if (!(p instanceof c)) throw new Error("invalid point at index " + i);
2443
- });
2444
- }
2445
- function validateMSMScalars(scalars, field, maxScalar) {
2446
- if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
2447
- scalars.forEach((s, i) => {
2448
- if (!(maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar)) throw new Error("invalid scalar at index " + i);
2449
- });
2450
- }
2451
- const pointWindowSizes = /* @__PURE__ */ new WeakMap();
2452
- function getWindowSize(P) {
2453
- return pointWindowSizes.get(P) || 1;
2454
- }
2455
- /** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */
2456
- function oddMultiples(p, size) {
2457
- const dbl = p.double();
2458
- const t = [p];
2459
- for (let j = 1; j < size; j++) t.push(t[j - 1].add(dbl));
2460
- return t;
2461
- }
2462
- /**
2463
- * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with
2464
- * |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).
2465
- */
2466
- function wnafDigits(n, W) {
2467
- const size = 2 ** W;
2468
- const half = size / 2;
2469
- const mask = BigInt(size - 1);
2470
- const d = [];
2471
- while (n > _0n) {
2472
- let w = 0;
2473
- if (n & _1n) {
2474
- w = Number(n & mask);
2475
- if (w >= half) w -= size;
2476
- n -= BigInt(w);
2477
- }
2478
- d.push(w);
2479
- n >>= _1n;
2480
- }
2481
- return d;
2482
- }
2483
- /**
2484
- * Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with
2485
- * digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one
2486
- * extra window for the final carry), so recoding length does not depend on the scalar.
2487
- */
2488
- function signedWindowDigits(n, W, windows) {
2489
- const size = 2 ** W;
2490
- const half = size / 2;
2491
- const mask = BigInt(size - 1);
2492
- const shiftBy = BigInt(W);
2493
- const d = [];
2494
- for (let w = 0; w < windows; w++) {
2495
- let v = Number(n & mask);
2496
- n >>= shiftBy;
2497
- if (v > half) {
2498
- v -= size;
2499
- n += _1n;
2500
- }
2501
- d.push(v);
2502
- }
2503
- if (n !== _0n) throw new Error("invalid wnaf");
2504
- return d;
2505
- }
2506
- /**
2507
- * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared
2508
- * accumulator per bit position of the longest recoding, one signed table addition per
2509
- * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.
2510
- */
2511
- function wnafWalk(zero, tables, digits) {
2512
- let max = 0;
2513
- for (const d of digits) max = Math.max(max, d.length);
2514
- let acc = zero;
2515
- for (let bit = max - 1; bit >= 0; bit--) {
2516
- if (bit !== max - 1) acc = acc.double();
2517
- for (let i = 0; i < digits.length; i++) {
2518
- const w = digits[i][bit];
2519
- if (w) {
2520
- const item = tables[i][Math.abs(w) - 1 >> 1];
2521
- acc = acc.add(w < 0 ? item.negate() : item);
2522
- }
2523
- }
2524
- }
2525
- return acc;
2526
- }
2527
- /**
2528
- * Elliptic curve multiplication of Point by scalar.
2529
- * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate
2530
- * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the
2531
- * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).
2532
- * Table generation is expensive and happens on first call of `multiply()`
2533
- * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.
2534
- *
2535
- * Cached algorithm is signed fixed-window wNAF:
2536
- * - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings
2537
- * are baked in, so a multiplication is exactly one table addition per window
2538
- * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent
2539
- * (basis of the constant-time path)
2540
- * - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply
2541
- * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which
2542
- * widens tables by 128 bits
2543
- * @param Point - Point constructor.
2544
- * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.
2545
- * @example
2546
- * Elliptic curve multiplication of Point by scalar.
2547
- *
2548
- * ```ts
2549
- * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';
2550
- * import { p256 } from '@noble/curves/nist.js';
2551
- * const mul = new ScalarMultiplier(p256.Point);
2552
- * ```
2553
- */
2554
- var ScalarMultiplier = class {
2555
- Point;
2556
- BASE;
2557
- ZERO;
2558
- randomBytes;
2559
- wnafPrecomputes = /* @__PURE__ */ new WeakMap();
2560
- baseCanBeBlinded;
2561
- bits;
2562
- constructor(Point, randomBytes) {
2563
- validatePointCons(Point);
2564
- this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);
2565
- this.Point = Point;
2566
- this.BASE = Point.BASE;
2567
- this.ZERO = Point.ZERO;
2568
- this.bits = Point.Fn.BITS;
2569
- }
2570
- /**
2571
- * Creates a signed fixed-window wNAF precomputation table: for every window w, the
2572
- * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
2573
- * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
2574
- * window absorbs the final carry of signed-digit recoding.
2575
- * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
2576
- * @param point - Point instance
2577
- * @param W - window size
2578
- * @param bits - scalar bitlength the table must cover
2579
- */
2580
- buildWnafTable(point, W, bits) {
2581
- const windows = Math.ceil(bits / W) + 1;
2582
- const half = 2 ** (W - 1);
2583
- const comp = [];
2584
- let base = point;
2585
- for (let w = 0; w < windows; w++) {
2586
- let acc = base;
2587
- for (let i = 0; i < half; i++) {
2588
- comp.push(acc);
2589
- acc = acc.add(base);
2590
- }
2591
- base = comp[comp.length - 1].double();
2592
- }
2593
- return {
2594
- W,
2595
- bits,
2596
- windows,
2597
- comp
2598
- };
2599
- }
2600
- /**
2601
- * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
2602
- * Constant-time: fixed window count with one table addition per window — zero digits feed
2603
- * the fake accumulator — and no doublings; the lookup scans the whole window slice.
2604
- * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
2605
- * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
2606
- * signedWindowDigits throws if `n` exceeds the table.
2607
- * @returns real and fake (for const-time) points
2608
- */
2609
- wnafCachedCT(precomputes, n) {
2610
- const { W, windows, comp } = precomputes;
2611
- const half = 2 ** (W - 1);
2612
- const digits = signedWindowDigits(n, W, windows);
2613
- let p = this.ZERO;
2614
- let f = this.BASE;
2615
- for (let w = 0; w < windows; w++) {
2616
- const digit = digits[w];
2617
- const start = w * half;
2618
- const idx = Math.abs(digit) - 1;
2619
- let sel = comp[start];
2620
- for (let i = 1; i < half; i++) sel = i === idx ? comp[start + i] : sel;
2621
- const neg = sel.negate();
2622
- if (digit === 0) f = f.add(comp[start]);
2623
- else p = p.add(digit < 0 ? neg : sel);
2624
- }
2625
- return {
2626
- p,
2627
- f
2628
- };
2629
- }
2630
- getWnafPrecomputes(W, point, bits, transform) {
2631
- let entries = this.wnafPrecomputes.get(point);
2632
- let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
2633
- if (!comp) {
2634
- comp = this.buildWnafTable(point, W, bits);
2635
- if (typeof transform === "function") comp = {
2636
- ...comp,
2637
- comp: transform(comp.comp)
2638
- };
2639
- if (!entries) {
2640
- entries = [];
2641
- this.wnafPrecomputes.set(point, entries);
2642
- }
2643
- entries.push(comp);
2644
- }
2645
- return comp;
2646
- }
2647
- assertPoint(point) {
2648
- if (!(point instanceof this.Point)) throw new TypeError("\"point\" expected Point instance, got type=" + typeof point);
2649
- }
2650
- validateMulInput(point, scalar) {
2651
- this.assertPoint(point);
2652
- if (!inRange(scalar, _1n, this.Point.Fn.ORDER)) throw new Error("invalid scalar");
2653
- }
2654
- runCT(point, n, bits, transform) {
2655
- const W = getWindowSize(point);
2656
- if (W === 1) return this.fixedWindowCT(point, n, bits);
2657
- return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
2658
- }
2659
- mulCT(point, scalar, transform) {
2660
- this.validateMulInput(point, scalar);
2661
- return this.runCT(point, scalar, this.bits, transform);
2662
- }
2663
- mulCTBlinded(point, scalar, transform) {
2664
- this.validateMulInput(point, scalar);
2665
- if (this.randomBytes === void 0) throw new Error("randomBytes is required for scalar blinding");
2666
- const bits = this.Point.Fn.BITS + BLIND_BITS;
2667
- const blind = this.randomBytes(BLIND_BYTES);
2668
- if (!isBytes(blind) || blind.length !== BLIND_BYTES) throw new Error("randomBytes returned invalid byte array");
2669
- blind[0] = blind[0] & 63 | 128;
2670
- const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
2671
- return this.runCT(point, n, bits, transform);
2672
- }
2673
- /**
2674
- * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
2675
- * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
2676
- * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
2677
- * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
2678
- * every table entry, and one addition (adds the identity when the window digit is 0 — never
2679
- * skipped).
2680
- *
2681
- * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
2682
- * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
2683
- * projective form (no normalizeZ): normalizing this small a table costs more than the
2684
- * mixed-add savings it would buy for a single multiply.
2685
- * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
2686
- * (this path needs no fake accumulator — its op-count is already scalar-independent).
2687
- */
2688
- fixedWindowCT(point, n, bits) {
2689
- const W = FW_WINDOW;
2690
- const size = 32;
2691
- const mask = bitMask(W);
2692
- const table = new Array(size);
2693
- table[0] = this.ZERO;
2694
- for (let i = 1; i < size; i++) table[i] = table[i - 1].add(point);
2695
- const windows = Math.ceil(bits / W);
2696
- let acc = this.ZERO;
2697
- for (let window = windows - 1; window >= 0; window--) {
2698
- if (window !== windows - 1) for (let d = 0; d < W; d++) acc = acc.double();
2699
- const digit = Number(n >> BigInt(window * W) & mask);
2700
- let sel = table[0];
2701
- for (let i = 1; i < size; i++) sel = i === digit ? table[i] : sel;
2702
- acc = acc.add(sel);
2703
- }
2704
- return {
2705
- p: acc,
2706
- f: acc
2707
- };
2708
- }
2709
- shouldBlind(point, cofactor) {
2710
- if (this.randomBytes === void 0) return false;
2711
- if (cofactor === _1n) return true;
2712
- if (point !== this.BASE) return false;
2713
- if (this.baseCanBeBlinded === void 0) this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
2714
- return this.baseCanBeBlinded;
2715
- }
2716
- mulSecret(point, scalar, cofactor, transform) {
2717
- return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
2718
- }
2719
- mulUnsafe(point, scalar, transform) {
2720
- this.assertPoint(point);
2721
- if (!isPosBig(scalar)) throw new Error("invalid scalar");
2722
- const W = getWindowSize(point);
2723
- if (W === 1 || scalar >= this.Point.Fn.ORDER) return mulAddUnsafe(this.Point, [point], [scalar], true);
2724
- const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
2725
- return this.wnafCachedCT(precomputes, scalar).p;
2726
- }
2727
- setWindowSize(point, W) {
2728
- this.assertPoint(point);
2729
- validateW(W, this.bits);
2730
- validateTableBytes((Math.ceil((this.bits + BLIND_BITS) / W) + 1) * 2 ** (W - 1), this.Point.Fp.BYTES);
2731
- pointWindowSizes.set(point, W);
2732
- this.wnafPrecomputes.delete(point);
2733
- }
2734
- hasWindowSize(point) {
2735
- return getWindowSize(point) !== 1;
2736
- }
2737
- };
2738
- /**
2739
- * Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF
2740
- * (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and
2741
- * signed-digit recoding, but all walks share one doubling chain, so total cost is
2742
- * `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate
2743
- * multiplications. Intended for the 2-4 point shapes of signature verification
2744
- * (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.
2745
- *
2746
- * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;
2747
- * fold negative signs into the points before calling.
2748
- * @param c - Point constructor.
2749
- * @param points - Array of curve points.
2750
- * @param scalars - Array of non-negative scalars, same length as points.
2751
- * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.
2752
- * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks
2753
- * (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.
2754
- * @returns Combined multiplication result; identity for empty input.
2755
- * @throws If the point set or scalar set is invalid. {@link Error}
2756
- * @example
2757
- * Combined multi-scalar multiplication via Strauss–Shamir.
2758
- *
2759
- * ```ts
2760
- * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';
2761
- * import { p256 } from '@noble/curves/nist.js';
2762
- * const G = p256.Point.BASE;
2763
- * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)
2764
- * ```
2765
- */
2766
- function mulAddUnsafe(c, points, scalars, allowOversized = false) {
2767
- validatePointCons(c);
2768
- validateMSMPoints(points, c);
2769
- abool(allowOversized, "allowOversized");
2770
- validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : void 0);
2771
- if (points.length !== scalars.length) throw new Error("arrays of points and scalars must have equal length");
2772
- const tables = points.map((p) => oddMultiples(p, 4));
2773
- const digits = scalars.map((n) => wnafDigits(n, 4));
2774
- return wnafWalk(c.ZERO, tables, digits);
2775
- }
2776
- function createField(order, field, isLE) {
2777
- if (field) {
2778
- if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
2779
- validateField(field);
2780
- return field;
2781
- } else return Field(order, { isLE });
2782
- }
2783
- /**
2784
- * Validates basic CURVE shape and field membership, then creates fields.
2785
- * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
2786
- * that the curve equation itself is otherwise sane.
2787
- * @param type - Curve family.
2788
- * @param CURVE - Curve parameters.
2789
- * @param curveOpts - Optional field overrides. See {@link FpFn}:
2790
- * - `Fp` (optional): Optional base-field override.
2791
- * - `Fn` (optional): Optional scalar-field override.
2792
- * @param FpFnLE - Whether field encoding is little-endian.
2793
- * @returns Frozen curve parameters and fields.
2794
- * @throws If the curve parameters or field overrides are invalid. {@link Error}
2795
- * @example
2796
- * Build curve fields from raw constants before constructing a curve instance.
2797
- *
2798
- * ```ts
2799
- * const curve = createCurveFields('weierstrass', {
2800
- * p: 17n,
2801
- * n: 19n,
2802
- * h: 1n,
2803
- * a: 2n,
2804
- * b: 2n,
2805
- * Gx: 5n,
2806
- * Gy: 1n,
2807
- * });
2808
- * ```
2809
- */
2810
- function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
2811
- if (type !== "weierstrass" && type !== "edwards") throw new Error("expected curve type \"weierstrass\" or \"edwards\"");
2812
- if (FpFnLE === void 0) FpFnLE = type === "edwards";
2813
- if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
2814
- validateObject(curveOpts);
2815
- for (const p of [
2816
- "p",
2817
- "n",
2818
- "h"
2819
- ]) {
2820
- const val = CURVE[p];
2821
- if (!(isPosBig(val) && val !== _0n)) throw new Error(`CURVE.${p} must be positive bigint`);
2822
- }
2823
- const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
2824
- const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
2825
- const params = [
2826
- "Gx",
2827
- "Gy",
2828
- "a",
2829
- type === "weierstrass" ? "b" : "d"
2830
- ];
2831
- for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
2832
- CURVE = Object.freeze(Object.assign({}, CURVE));
2833
- return {
2834
- CURVE,
2835
- Fp,
2836
- Fn
2837
- };
2838
- }
2839
- /**
2840
- * @param randomSecretKey - Secret-key generator.
2841
- * @param getPublicKey - Public-key derivation helper.
2842
- * @returns Keypair generator.
2843
- * @example
2844
- * Build a `keygen()` helper from existing secret-key and public-key primitives.
2845
- *
2846
- * ```ts
2847
- * import { createKeygen } from '@noble/curves/abstract/curve.js';
2848
- * import { p256 } from '@noble/curves/nist.js';
2849
- * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
2850
- * const pair = keygen();
2851
- * ```
2852
- */
2853
- function createKeygen(randomSecretKey, getPublicKey) {
2854
- return function keygen(seed) {
2855
- const secretKey = randomSecretKey(seed);
2856
- return {
2857
- secretKey,
2858
- publicKey: getPublicKey(secretKey)
2859
- };
2860
- };
2861
- }
2862
- //#endregion
2863
- export { createHmacDrbg as A, aexists as B, bitLen as C, bytesToNumberLE as D, bytesToNumberBE as E, validateObject as F, clean as G, anumber$1 as H, sha256 as I, swap32IfBE as J, createHasher as K, sha512 as L, isBytes as M, numberToHexUnpadded as N, concatBytes as O, randomBytes as P, abool$1 as R, astring as S, bytesToHex as T, aoutput as U, ahash as V, bytesToHex$1 as W, split as X, u32 as Y, abignumber as _, normalizeZ as a, asafenumber as b, Field as c, invertCt as d, isNegativeLE as f, aInRange as g, pow2 as h, mulAddUnsafe as i, hexToBytes as j, copyBytes as k, FpLegendre as l, mod as m, createCurveFields as n, probeRandomBytes as o, mapHashToField as p, randomBytes$1 as q, createKeygen as r, validatePointCons as s, ScalarMultiplier as t, getMinHashLength as u, abool as v, bitMask as w, asciiToBytes as x, abytes as y, abytes$1 as z };
2864
-
2865
- //# sourceMappingURL=curve-BeDNVVGm.mjs.map