@waku/discovery 0.0.9-16328a3.0 → 0.0.9-383e0b2.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.
package/bundle/index.js CHANGED
@@ -249,31 +249,22 @@ function isDefined(value) {
249
249
  return Boolean(value);
250
250
  }
251
251
 
252
- const crypto$2 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
253
-
254
252
  /**
255
- * Utilities for hex, bytes, CSPRNG.
253
+ * Internal assertion helpers.
256
254
  * @module
257
255
  */
258
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
259
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
260
- // node.js versions earlier than v19 don't declare it in global scope.
261
- // For node.js, package.json#exports field mapping rewrites import
262
- // from `crypto` to `cryptoNode`, which imports native module.
263
- // Makes the utils un-importable in browsers without a bundler.
264
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
265
- /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
266
- function isBytes$3(a) {
267
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
268
- }
269
256
  /** Asserts something is positive integer. */
270
257
  function anumber(n) {
271
258
  if (!Number.isSafeInteger(n) || n < 0)
272
259
  throw new Error('positive integer expected, got ' + n);
273
260
  }
261
+ /** Is number an Uint8Array? Copied from utils for perf. */
262
+ function isBytes$2(a) {
263
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
264
+ }
274
265
  /** Asserts something is Uint8Array. */
275
- function abytes$2(b, ...lengths) {
276
- if (!isBytes$3(b))
266
+ function abytes$1(b, ...lengths) {
267
+ if (!isBytes$2(b))
277
268
  throw new Error('Uint8Array expected');
278
269
  if (lengths.length > 0 && !lengths.includes(b.length))
279
270
  throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
@@ -281,7 +272,7 @@ function abytes$2(b, ...lengths) {
281
272
  /** Asserts something is hash */
282
273
  function ahash(h) {
283
274
  if (typeof h !== 'function' || typeof h.create !== 'function')
284
- throw new Error('Hash should be wrapped by utils.createHasher');
275
+ throw new Error('Hash should be wrapped by utils.wrapConstructor');
285
276
  anumber(h.outputLen);
286
277
  anumber(h.blockLen);
287
278
  }
@@ -294,19 +285,27 @@ function aexists(instance, checkFinished = true) {
294
285
  }
295
286
  /** Asserts output is properly-sized byte array */
296
287
  function aoutput(out, instance) {
297
- abytes$2(out);
288
+ abytes$1(out);
298
289
  const min = instance.outputLen;
299
290
  if (out.length < min) {
300
291
  throw new Error('digestInto() expects output buffer of length at least ' + min);
301
292
  }
302
293
  }
303
- /** Zeroize a byte array. Warning: JS provides no guarantees. */
304
- function clean(...arrays) {
305
- for (let i = 0; i < arrays.length; i++) {
306
- arrays[i].fill(0);
307
- }
308
- }
309
- /** Create DataView of an array for easy byte-level manipulation. */
294
+
295
+ const crypto$2 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
296
+
297
+ /**
298
+ * Utilities for hex, bytes, CSPRNG.
299
+ * @module
300
+ */
301
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
302
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
303
+ // node.js versions earlier than v19 don't declare it in global scope.
304
+ // For node.js, package.json#exports field mapping rewrites import
305
+ // from `crypto` to `cryptoNode`, which imports native module.
306
+ // Makes the utils un-importable in browsers without a bundler.
307
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
308
+ // Cast array to view
310
309
  function createView(arr) {
311
310
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
312
311
  }
@@ -315,12 +314,12 @@ function rotr(word, shift) {
315
314
  return (word << (32 - shift)) | (word >>> shift);
316
315
  }
317
316
  /**
318
- * Converts string to bytes using UTF8 encoding.
319
- * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
317
+ * Convert JS string to byte array.
318
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
320
319
  */
321
- function utf8ToBytes$1(str) {
320
+ function utf8ToBytes$2(str) {
322
321
  if (typeof str !== 'string')
323
- throw new Error('string expected');
322
+ throw new Error('utf8ToBytes expected string, got ' + typeof str);
324
323
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
325
324
  }
326
325
  /**
@@ -330,16 +329,18 @@ function utf8ToBytes$1(str) {
330
329
  */
331
330
  function toBytes$1(data) {
332
331
  if (typeof data === 'string')
333
- data = utf8ToBytes$1(data);
334
- abytes$2(data);
332
+ data = utf8ToBytes$2(data);
333
+ abytes$1(data);
335
334
  return data;
336
335
  }
337
- /** Copies several Uint8Arrays into one. */
336
+ /**
337
+ * Copies several Uint8Arrays into one.
338
+ */
338
339
  function concatBytes$2(...arrays) {
339
340
  let sum = 0;
340
341
  for (let i = 0; i < arrays.length; i++) {
341
342
  const a = arrays[i];
342
- abytes$2(a);
343
+ abytes$1(a);
343
344
  sum += a.length;
344
345
  }
345
346
  const res = new Uint8Array(sum);
@@ -352,9 +353,13 @@ function concatBytes$2(...arrays) {
352
353
  }
353
354
  /** For runtime check if class implements interface */
354
355
  class Hash {
356
+ // Safe version that clones internal state
357
+ clone() {
358
+ return this._cloneInto();
359
+ }
355
360
  }
356
361
  /** Wraps hash function, creating an interface on top of it */
357
- function createHasher(hashCons) {
362
+ function wrapConstructor(hashCons) {
358
363
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
359
364
  const tmp = hashCons();
360
365
  hashC.outputLen = tmp.outputLen;
@@ -369,7 +374,7 @@ function randomBytes(bytesLength = 32) {
369
374
  }
370
375
  // Legacy Node.js compatibility
371
376
  if (crypto$2 && typeof crypto$2.randomBytes === 'function') {
372
- return Uint8Array.from(crypto$2.randomBytes(bytesLength));
377
+ return crypto$2.randomBytes(bytesLength);
373
378
  }
374
379
  throw new Error('crypto.getRandomValues must be defined');
375
380
  }
@@ -406,22 +411,21 @@ function Maj(a, b, c) {
406
411
  class HashMD extends Hash {
407
412
  constructor(blockLen, outputLen, padOffset, isLE) {
408
413
  super();
409
- this.finished = false;
410
- this.length = 0;
411
- this.pos = 0;
412
- this.destroyed = false;
413
414
  this.blockLen = blockLen;
414
415
  this.outputLen = outputLen;
415
416
  this.padOffset = padOffset;
416
417
  this.isLE = isLE;
418
+ this.finished = false;
419
+ this.length = 0;
420
+ this.pos = 0;
421
+ this.destroyed = false;
417
422
  this.buffer = new Uint8Array(blockLen);
418
423
  this.view = createView(this.buffer);
419
424
  }
420
425
  update(data) {
421
426
  aexists(this);
422
- data = toBytes$1(data);
423
- abytes$2(data);
424
427
  const { view, buffer, blockLen } = this;
428
+ data = toBytes$1(data);
425
429
  const len = data.length;
426
430
  for (let pos = 0; pos < len;) {
427
431
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -455,7 +459,7 @@ class HashMD extends Hash {
455
459
  let { pos } = this;
456
460
  // append the bit '1' to the message
457
461
  buffer[pos++] = 0b10000000;
458
- clean(this.buffer.subarray(pos));
462
+ this.buffer.subarray(pos).fill(0);
459
463
  // we have less than padOffset left in buffer, so we cannot put length in
460
464
  // current block, need process it and pad again
461
465
  if (this.padOffset > blockLen - pos) {
@@ -493,90 +497,28 @@ class HashMD extends Hash {
493
497
  to || (to = new this.constructor());
494
498
  to.set(...this.get());
495
499
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
496
- to.destroyed = destroyed;
497
- to.finished = finished;
498
500
  to.length = length;
499
501
  to.pos = pos;
502
+ to.finished = finished;
503
+ to.destroyed = destroyed;
500
504
  if (length % blockLen)
501
505
  to.buffer.set(buffer);
502
506
  return to;
503
507
  }
504
- clone() {
505
- return this._cloneInto();
506
- }
507
508
  }
508
- /**
509
- * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
510
- * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
511
- */
512
- /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
513
- const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
514
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
515
- ]);
516
- /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
517
- const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
518
- 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
519
- 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
520
- ]);
521
509
 
522
510
  /**
523
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
524
- * @todo re-check https://issues.chromium.org/issues/42212588
525
- * @module
526
- */
527
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
528
- const _32n = /* @__PURE__ */ BigInt(32);
529
- function fromBig(n, le = false) {
530
- if (le)
531
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
532
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
533
- }
534
- function split(lst, le = false) {
535
- const len = lst.length;
536
- let Ah = new Uint32Array(len);
537
- let Al = new Uint32Array(len);
538
- for (let i = 0; i < len; i++) {
539
- const { h, l } = fromBig(lst[i], le);
540
- [Ah[i], Al[i]] = [h, l];
541
- }
542
- return [Ah, Al];
543
- }
544
- // for Shift in [0, 32)
545
- const shrSH = (h, _l, s) => h >>> s;
546
- const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
547
- // Right rotate for Shift in [1, 32)
548
- const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
549
- const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
550
- // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
551
- const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
552
- const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
553
- // JS uses 32-bit signed integers for bitwise operations which means we cannot
554
- // simple take carry out of low bit sum by shift, we need to use division.
555
- function add(Ah, Al, Bh, Bl) {
556
- const l = (Al >>> 0) + (Bl >>> 0);
557
- return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
558
- }
559
- // Addition with more than 2 elements
560
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
561
- const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
562
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
563
- const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
564
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
565
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
566
-
567
- /**
568
- * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
569
- * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
570
- * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
571
- * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
511
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
512
+ *
513
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
514
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
515
+ *
516
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
572
517
  * @module
573
518
  */
574
- /**
575
- * Round constants:
576
- * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
577
- */
519
+ /** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */
578
520
  // prettier-ignore
579
- const SHA256_K = /* @__PURE__ */ Uint32Array.from([
521
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
580
522
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
581
523
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
582
524
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -586,11 +528,19 @@ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
586
528
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
587
529
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
588
530
  ]);
589
- /** Reusable temporary buffer. "W" comes straight from spec. */
531
+ /** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */
532
+ // prettier-ignore
533
+ const SHA256_IV = /* @__PURE__ */ new Uint32Array([
534
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
535
+ ]);
536
+ /**
537
+ * Temporary buffer, not used to store anything between runs.
538
+ * Named this way because it matches specification.
539
+ */
590
540
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
591
541
  class SHA256 extends HashMD {
592
- constructor(outputLen = 32) {
593
- super(64, outputLen, 8, false);
542
+ constructor() {
543
+ super(64, 32, 8, false);
594
544
  // We cannot use array here since array allows indexing by variable
595
545
  // which means optimizer/compiler cannot use registers.
596
546
  this.A = SHA256_IV[0] | 0;
@@ -656,192 +606,15 @@ class SHA256 extends HashMD {
656
606
  this.set(A, B, C, D, E, F, G, H);
657
607
  }
658
608
  roundClean() {
659
- clean(SHA256_W);
609
+ SHA256_W.fill(0);
660
610
  }
661
611
  destroy() {
662
612
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
663
- clean(this.buffer);
664
- }
665
- }
666
- // SHA2-512 is slower than sha256 in js because u64 operations are slow.
667
- // Round contants
668
- // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
669
- // prettier-ignore
670
- const K512 = /* @__PURE__ */ (() => split([
671
- '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
672
- '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
673
- '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
674
- '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
675
- '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
676
- '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
677
- '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
678
- '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
679
- '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
680
- '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
681
- '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
682
- '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
683
- '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
684
- '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
685
- '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
686
- '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
687
- '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
688
- '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
689
- '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
690
- '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
691
- ].map(n => BigInt(n))))();
692
- const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
693
- const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
694
- // Reusable temporary buffers
695
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
696
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
697
- class SHA512 extends HashMD {
698
- constructor(outputLen = 64) {
699
- super(128, outputLen, 16, false);
700
- // We cannot use array here since array allows indexing by variable
701
- // which means optimizer/compiler cannot use registers.
702
- // h -- high 32 bits, l -- low 32 bits
703
- this.Ah = SHA512_IV[0] | 0;
704
- this.Al = SHA512_IV[1] | 0;
705
- this.Bh = SHA512_IV[2] | 0;
706
- this.Bl = SHA512_IV[3] | 0;
707
- this.Ch = SHA512_IV[4] | 0;
708
- this.Cl = SHA512_IV[5] | 0;
709
- this.Dh = SHA512_IV[6] | 0;
710
- this.Dl = SHA512_IV[7] | 0;
711
- this.Eh = SHA512_IV[8] | 0;
712
- this.El = SHA512_IV[9] | 0;
713
- this.Fh = SHA512_IV[10] | 0;
714
- this.Fl = SHA512_IV[11] | 0;
715
- this.Gh = SHA512_IV[12] | 0;
716
- this.Gl = SHA512_IV[13] | 0;
717
- this.Hh = SHA512_IV[14] | 0;
718
- this.Hl = SHA512_IV[15] | 0;
719
- }
720
- // prettier-ignore
721
- get() {
722
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
723
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
724
- }
725
- // prettier-ignore
726
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
727
- this.Ah = Ah | 0;
728
- this.Al = Al | 0;
729
- this.Bh = Bh | 0;
730
- this.Bl = Bl | 0;
731
- this.Ch = Ch | 0;
732
- this.Cl = Cl | 0;
733
- this.Dh = Dh | 0;
734
- this.Dl = Dl | 0;
735
- this.Eh = Eh | 0;
736
- this.El = El | 0;
737
- this.Fh = Fh | 0;
738
- this.Fl = Fl | 0;
739
- this.Gh = Gh | 0;
740
- this.Gl = Gl | 0;
741
- this.Hh = Hh | 0;
742
- this.Hl = Hl | 0;
743
- }
744
- process(view, offset) {
745
- // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
746
- for (let i = 0; i < 16; i++, offset += 4) {
747
- SHA512_W_H[i] = view.getUint32(offset);
748
- SHA512_W_L[i] = view.getUint32((offset += 4));
749
- }
750
- for (let i = 16; i < 80; i++) {
751
- // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
752
- const W15h = SHA512_W_H[i - 15] | 0;
753
- const W15l = SHA512_W_L[i - 15] | 0;
754
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
755
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
756
- // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
757
- const W2h = SHA512_W_H[i - 2] | 0;
758
- const W2l = SHA512_W_L[i - 2] | 0;
759
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
760
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
761
- // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
762
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
763
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
764
- SHA512_W_H[i] = SUMh | 0;
765
- SHA512_W_L[i] = SUMl | 0;
766
- }
767
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
768
- // Compression function main loop, 80 rounds
769
- for (let i = 0; i < 80; i++) {
770
- // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
771
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
772
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
773
- //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
774
- const CHIh = (Eh & Fh) ^ (~Eh & Gh);
775
- const CHIl = (El & Fl) ^ (~El & Gl);
776
- // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
777
- // prettier-ignore
778
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
779
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
780
- const T1l = T1ll | 0;
781
- // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
782
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
783
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
784
- const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
785
- const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
786
- Hh = Gh | 0;
787
- Hl = Gl | 0;
788
- Gh = Fh | 0;
789
- Gl = Fl | 0;
790
- Fh = Eh | 0;
791
- Fl = El | 0;
792
- ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
793
- Dh = Ch | 0;
794
- Dl = Cl | 0;
795
- Ch = Bh | 0;
796
- Cl = Bl | 0;
797
- Bh = Ah | 0;
798
- Bl = Al | 0;
799
- const All = add3L(T1l, sigma0l, MAJl);
800
- Ah = add3H(All, T1h, sigma0h, MAJh);
801
- Al = All | 0;
802
- }
803
- // Add the compressed chunk to the current hash value
804
- ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
805
- ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
806
- ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
807
- ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
808
- ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
809
- ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
810
- ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
811
- ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
812
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
813
- }
814
- roundClean() {
815
- clean(SHA512_W_H, SHA512_W_L);
816
- }
817
- destroy() {
818
- clean(this.buffer);
819
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
613
+ this.buffer.fill(0);
820
614
  }
821
615
  }
822
- /**
823
- * SHA2-256 hash function from RFC 4634.
824
- *
825
- * It is the fastest JS hash, even faster than Blake3.
826
- * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
827
- * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
828
- */
829
- const sha256$2 = /* @__PURE__ */ createHasher(() => new SHA256());
830
- /** SHA2-512 hash function from RFC 4634. */
831
- const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
832
-
833
- /**
834
- * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
835
- *
836
- * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
837
- * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
838
- *
839
- * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
840
- * @module
841
- * @deprecated
842
- */
843
- /** @deprecated Use import from `noble/hashes/sha2` module */
844
- const sha256$1 = sha256$2;
616
+ /** SHA2-256 hash function */
617
+ const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
845
618
 
846
619
  function equals$2(aa, bb) {
847
620
  if (aa === bb)
@@ -2167,7 +1940,7 @@ const bytesToUtf8 = (b) => toString$1(b, "utf8");
2167
1940
  /**
2168
1941
  * Encode utf-8 string to byte array.
2169
1942
  */
2170
- const utf8ToBytes = (s) => fromString(s, "utf8");
1943
+ const utf8ToBytes$1 = (s) => fromString(s, "utf8");
2171
1944
 
2172
1945
  const decodeRelayShard = (bytes) => {
2173
1946
  // explicitly converting to Uint8Array to avoid Buffer
@@ -3041,7 +2814,7 @@ var nodeCrypto = /*#__PURE__*/Object.freeze({
3041
2814
  /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
3042
2815
  const _0n$5 = BigInt(0);
3043
2816
  const _1n$7 = BigInt(1);
3044
- const _2n$4 = BigInt(2);
2817
+ const _2n$5 = BigInt(2);
3045
2818
  const _3n$2 = BigInt(3);
3046
2819
  const _8n$3 = BigInt(8);
3047
2820
  const CURVE = Object.freeze({
@@ -3054,7 +2827,7 @@ const CURVE = Object.freeze({
3054
2827
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
3055
2828
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
3056
2829
  });
3057
- const divNearest$1 = (a, b) => (a + b / _2n$4) / b;
2830
+ const divNearest$1 = (a, b) => (a + b / _2n$5) / b;
3058
2831
  const endo = {
3059
2832
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
3060
2833
  splitScalar(k) {
@@ -3143,12 +2916,12 @@ class JacobianPoint {
3143
2916
  const B = mod$1(Y1 * Y1);
3144
2917
  const C = mod$1(B * B);
3145
2918
  const x1b = X1 + B;
3146
- const D = mod$1(_2n$4 * (mod$1(x1b * x1b) - A - C));
2919
+ const D = mod$1(_2n$5 * (mod$1(x1b * x1b) - A - C));
3147
2920
  const E = mod$1(_3n$2 * A);
3148
2921
  const F = mod$1(E * E);
3149
- const X3 = mod$1(F - _2n$4 * D);
2922
+ const X3 = mod$1(F - _2n$5 * D);
3150
2923
  const Y3 = mod$1(E * (D - X3) - _8n$3 * C);
3151
- const Z3 = mod$1(_2n$4 * Y1 * Z1);
2924
+ const Z3 = mod$1(_2n$5 * Y1 * Z1);
3152
2925
  return new JacobianPoint(X3, Y3, Z3);
3153
2926
  }
3154
2927
  add(other) {
@@ -3178,7 +2951,7 @@ class JacobianPoint {
3178
2951
  const HH = mod$1(H * H);
3179
2952
  const HHH = mod$1(H * HH);
3180
2953
  const V = mod$1(U1 * HH);
3181
- const X3 = mod$1(r * r - HHH - _2n$4 * V);
2954
+ const X3 = mod$1(r * r - HHH - _2n$5 * V);
3182
2955
  const Y3 = mod$1(r * (V - X3) - S1 * HHH);
3183
2956
  const Z3 = mod$1(Z1 * Z2 * H);
3184
2957
  return new JacobianPoint(X3, Y3, Z3);
@@ -3339,7 +3112,7 @@ class Point {
3339
3112
  pointPrecomputes$1.delete(this);
3340
3113
  }
3341
3114
  hasEvenY() {
3342
- return this.y % _2n$4 === _0n$5;
3115
+ return this.y % _2n$5 === _0n$5;
3343
3116
  }
3344
3117
  static fromCompressedHex(bytes) {
3345
3118
  const isShort = bytes.length === 32;
@@ -3498,7 +3271,7 @@ class Signature {
3498
3271
  this.assertValidity();
3499
3272
  }
3500
3273
  static fromCompact(hex) {
3501
- const arr = isBytes$2(hex);
3274
+ const arr = hex instanceof Uint8Array;
3502
3275
  const name = 'Signature.fromCompact';
3503
3276
  if (typeof hex !== 'string' && !arr)
3504
3277
  throw new TypeError(`${name}: Expected string or Uint8Array`);
@@ -3508,7 +3281,7 @@ class Signature {
3508
3281
  return new Signature(hexToNumber$1(str.slice(0, 64)), hexToNumber$1(str.slice(64, 128)));
3509
3282
  }
3510
3283
  static fromDER(hex) {
3511
- const arr = isBytes$2(hex);
3284
+ const arr = hex instanceof Uint8Array;
3512
3285
  if (typeof hex !== 'string' && !arr)
3513
3286
  throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
3514
3287
  const { r, s } = parseDERSignature(arr ? hex : hexToBytes$1(hex));
@@ -3557,15 +3330,9 @@ class Signature {
3557
3330
  return numTo32bStr(this.r) + numTo32bStr(this.s);
3558
3331
  }
3559
3332
  }
3560
- function isBytes$2(a) {
3561
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3562
- }
3563
- function abytes$1(item) {
3564
- if (!isBytes$2(item))
3565
- throw new Error('Uint8Array expected');
3566
- }
3567
3333
  function concatBytes$1(...arrays) {
3568
- arrays.every(abytes$1);
3334
+ if (!arrays.every((b) => b instanceof Uint8Array))
3335
+ throw new Error('Uint8Array list expected');
3569
3336
  if (arrays.length === 1)
3570
3337
  return arrays[0];
3571
3338
  const length = arrays.reduce((a, arr) => a + arr.length, 0);
@@ -3577,44 +3344,16 @@ function concatBytes$1(...arrays) {
3577
3344
  }
3578
3345
  return result;
3579
3346
  }
3580
- const hexes$1 = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
3581
- function bytesToHex$1(bytes) {
3582
- abytes$1(bytes);
3347
+ const hexes$1 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
3348
+ function bytesToHex$1(uint8a) {
3349
+ if (!(uint8a instanceof Uint8Array))
3350
+ throw new Error('Expected Uint8Array');
3583
3351
  let hex = '';
3584
- for (let i = 0; i < bytes.length; i++) {
3585
- hex += hexes$1[bytes[i]];
3352
+ for (let i = 0; i < uint8a.length; i++) {
3353
+ hex += hexes$1[uint8a[i]];
3586
3354
  }
3587
3355
  return hex;
3588
3356
  }
3589
- const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
3590
- function asciiToBase16$1(ch) {
3591
- if (ch >= asciis$1._0 && ch <= asciis$1._9)
3592
- return ch - asciis$1._0;
3593
- if (ch >= asciis$1.A && ch <= asciis$1.F)
3594
- return ch - (asciis$1.A - 10);
3595
- if (ch >= asciis$1.a && ch <= asciis$1.f)
3596
- return ch - (asciis$1.a - 10);
3597
- return;
3598
- }
3599
- function hexToBytes$1(hex) {
3600
- if (typeof hex !== 'string')
3601
- throw new Error('hex string expected, got ' + typeof hex);
3602
- const hl = hex.length;
3603
- const al = hl / 2;
3604
- if (hl % 2)
3605
- throw new Error('hex string expected, got unpadded hex of length ' + hl);
3606
- const array = new Uint8Array(al);
3607
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
3608
- const n1 = asciiToBase16$1(hex.charCodeAt(hi));
3609
- const n2 = asciiToBase16$1(hex.charCodeAt(hi + 1));
3610
- if (n1 === undefined || n2 === undefined) {
3611
- const char = hex[hi] + hex[hi + 1];
3612
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
3613
- }
3614
- array[ai] = n1 * 16 + n2;
3615
- }
3616
- return array;
3617
- }
3618
3357
  const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
3619
3358
  function numTo32bStr(num) {
3620
3359
  if (typeof num !== 'bigint')
@@ -3639,11 +3378,28 @@ function hexToNumber$1(hex) {
3639
3378
  }
3640
3379
  return BigInt(`0x${hex}`);
3641
3380
  }
3381
+ function hexToBytes$1(hex) {
3382
+ if (typeof hex !== 'string') {
3383
+ throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
3384
+ }
3385
+ if (hex.length % 2)
3386
+ throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);
3387
+ const array = new Uint8Array(hex.length / 2);
3388
+ for (let i = 0; i < array.length; i++) {
3389
+ const j = i * 2;
3390
+ const hexByte = hex.slice(j, j + 2);
3391
+ const byte = Number.parseInt(hexByte, 16);
3392
+ if (Number.isNaN(byte) || byte < 0)
3393
+ throw new Error('Invalid byte sequence');
3394
+ array[i] = byte;
3395
+ }
3396
+ return array;
3397
+ }
3642
3398
  function bytesToNumber(bytes) {
3643
3399
  return hexToNumber$1(bytesToHex$1(bytes));
3644
3400
  }
3645
3401
  function ensureBytes$1(hex) {
3646
- return isBytes$2(hex) ? Uint8Array.from(hex) : hexToBytes$1(hex);
3402
+ return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex);
3647
3403
  }
3648
3404
  function normalizeScalar(num) {
3649
3405
  if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)
@@ -3677,7 +3433,7 @@ function sqrtMod$1(x) {
3677
3433
  const b3 = (b2 * b2 * x) % P;
3678
3434
  const b6 = (pow2$1(b3, _3n$2) * b3) % P;
3679
3435
  const b9 = (pow2$1(b6, _3n$2) * b3) % P;
3680
- const b11 = (pow2$1(b9, _2n$4) * b2) % P;
3436
+ const b11 = (pow2$1(b9, _2n$5) * b2) % P;
3681
3437
  const b22 = (pow2$1(b11, _11n) * b11) % P;
3682
3438
  const b44 = (pow2$1(b22, _22n) * b22) % P;
3683
3439
  const b88 = (pow2$1(b44, _44n) * b44) % P;
@@ -3686,7 +3442,7 @@ function sqrtMod$1(x) {
3686
3442
  const b223 = (pow2$1(b220, _3n$2) * b3) % P;
3687
3443
  const t1 = (pow2$1(b223, _23n) * b22) % P;
3688
3444
  const t2 = (pow2$1(t1, _6n) * b2) % P;
3689
- const rt = pow2$1(t2, _2n$4);
3445
+ const rt = pow2$1(t2, _2n$5);
3690
3446
  const xc = (rt * rt) % P;
3691
3447
  if (xc !== x)
3692
3448
  throw new Error('Cannot find square root');
@@ -3851,7 +3607,7 @@ function normalizePrivateKey(key) {
3851
3607
  throw new Error('Expected 32 bytes of private key');
3852
3608
  num = hexToNumber$1(key);
3853
3609
  }
3854
- else if (isBytes$2(key)) {
3610
+ else if (key instanceof Uint8Array) {
3855
3611
  if (key.length !== groupLen)
3856
3612
  throw new Error('Expected 32 bytes of private key');
3857
3613
  num = bytesToNumber(key);
@@ -7077,38 +6833,265 @@ function getOID(curve) {
7077
6833
  throw new InvalidParametersError(`Invalid curve ${curve}`);
7078
6834
  }
7079
6835
 
7080
- class ECDSAPublicKey {
7081
- type = 'ECDSA';
7082
- jwk;
7083
- _raw;
7084
- constructor(jwk) {
7085
- this.jwk = jwk;
7086
- }
7087
- get raw() {
7088
- if (this._raw == null) {
7089
- this._raw = publicKeyToPKIMessage(this.jwk);
7090
- }
7091
- return this._raw;
7092
- }
7093
- toMultihash() {
7094
- return identity.digest(publicKeyToProtobuf(this));
6836
+ class ECDSAPublicKey {
6837
+ type = 'ECDSA';
6838
+ jwk;
6839
+ _raw;
6840
+ constructor(jwk) {
6841
+ this.jwk = jwk;
6842
+ }
6843
+ get raw() {
6844
+ if (this._raw == null) {
6845
+ this._raw = publicKeyToPKIMessage(this.jwk);
6846
+ }
6847
+ return this._raw;
6848
+ }
6849
+ toMultihash() {
6850
+ return identity.digest(publicKeyToProtobuf(this));
6851
+ }
6852
+ toCID() {
6853
+ return CID.createV1(114, this.toMultihash());
6854
+ }
6855
+ toString() {
6856
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
6857
+ }
6858
+ equals(key) {
6859
+ if (key == null || !(key.raw instanceof Uint8Array)) {
6860
+ return false;
6861
+ }
6862
+ return equals(this.raw, key.raw);
6863
+ }
6864
+ async verify(data, sig) {
6865
+ return hashAndVerify$3(this.jwk, sig, data);
6866
+ }
6867
+ }
6868
+
6869
+ /**
6870
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
6871
+ * @todo re-check https://issues.chromium.org/issues/42212588
6872
+ * @module
6873
+ */
6874
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
6875
+ const _32n = /* @__PURE__ */ BigInt(32);
6876
+ function fromBig(n, le = false) {
6877
+ if (le)
6878
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
6879
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
6880
+ }
6881
+ function split(lst, le = false) {
6882
+ let Ah = new Uint32Array(lst.length);
6883
+ let Al = new Uint32Array(lst.length);
6884
+ for (let i = 0; i < lst.length; i++) {
6885
+ const { h, l } = fromBig(lst[i], le);
6886
+ [Ah[i], Al[i]] = [h, l];
6887
+ }
6888
+ return [Ah, Al];
6889
+ }
6890
+ const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
6891
+ // for Shift in [0, 32)
6892
+ const shrSH = (h, _l, s) => h >>> s;
6893
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
6894
+ // Right rotate for Shift in [1, 32)
6895
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
6896
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
6897
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
6898
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
6899
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
6900
+ // Right rotate for shift===32 (just swaps l&h)
6901
+ const rotr32H = (_h, l) => l;
6902
+ const rotr32L = (h, _l) => h;
6903
+ // Left rotate for Shift in [1, 32)
6904
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
6905
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
6906
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
6907
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
6908
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
6909
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
6910
+ // simple take carry out of low bit sum by shift, we need to use division.
6911
+ function add(Ah, Al, Bh, Bl) {
6912
+ const l = (Al >>> 0) + (Bl >>> 0);
6913
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
6914
+ }
6915
+ // Addition with more than 2 elements
6916
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
6917
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
6918
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
6919
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
6920
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
6921
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
6922
+ // prettier-ignore
6923
+ const u64 = {
6924
+ fromBig, split, toBig,
6925
+ shrSH, shrSL,
6926
+ rotrSH, rotrSL, rotrBH, rotrBL,
6927
+ rotr32H, rotr32L,
6928
+ rotlSH, rotlSL, rotlBH, rotlBL,
6929
+ add, add3L, add3H, add4L, add4H, add5H, add5L,
6930
+ };
6931
+
6932
+ /**
6933
+ * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
6934
+ *
6935
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
6936
+ * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
6937
+ * @module
6938
+ */
6939
+ // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
6940
+ // prettier-ignore
6941
+ const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
6942
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
6943
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
6944
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
6945
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
6946
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
6947
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
6948
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
6949
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
6950
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
6951
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
6952
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
6953
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
6954
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
6955
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
6956
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
6957
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
6958
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
6959
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
6960
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
6961
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
6962
+ ].map(n => BigInt(n))))();
6963
+ // Temporary buffer, not used to store anything between runs
6964
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
6965
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
6966
+ class SHA512 extends HashMD {
6967
+ constructor() {
6968
+ super(128, 64, 16, false);
6969
+ // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
6970
+ // Also looks cleaner and easier to verify with spec.
6971
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
6972
+ // h -- high 32 bits, l -- low 32 bits
6973
+ this.Ah = 0x6a09e667 | 0;
6974
+ this.Al = 0xf3bcc908 | 0;
6975
+ this.Bh = 0xbb67ae85 | 0;
6976
+ this.Bl = 0x84caa73b | 0;
6977
+ this.Ch = 0x3c6ef372 | 0;
6978
+ this.Cl = 0xfe94f82b | 0;
6979
+ this.Dh = 0xa54ff53a | 0;
6980
+ this.Dl = 0x5f1d36f1 | 0;
6981
+ this.Eh = 0x510e527f | 0;
6982
+ this.El = 0xade682d1 | 0;
6983
+ this.Fh = 0x9b05688c | 0;
6984
+ this.Fl = 0x2b3e6c1f | 0;
6985
+ this.Gh = 0x1f83d9ab | 0;
6986
+ this.Gl = 0xfb41bd6b | 0;
6987
+ this.Hh = 0x5be0cd19 | 0;
6988
+ this.Hl = 0x137e2179 | 0;
7095
6989
  }
7096
- toCID() {
7097
- return CID.createV1(114, this.toMultihash());
6990
+ // prettier-ignore
6991
+ get() {
6992
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
6993
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
7098
6994
  }
7099
- toString() {
7100
- return base58btc.encode(this.toMultihash().bytes).substring(1);
6995
+ // prettier-ignore
6996
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
6997
+ this.Ah = Ah | 0;
6998
+ this.Al = Al | 0;
6999
+ this.Bh = Bh | 0;
7000
+ this.Bl = Bl | 0;
7001
+ this.Ch = Ch | 0;
7002
+ this.Cl = Cl | 0;
7003
+ this.Dh = Dh | 0;
7004
+ this.Dl = Dl | 0;
7005
+ this.Eh = Eh | 0;
7006
+ this.El = El | 0;
7007
+ this.Fh = Fh | 0;
7008
+ this.Fl = Fl | 0;
7009
+ this.Gh = Gh | 0;
7010
+ this.Gl = Gl | 0;
7011
+ this.Hh = Hh | 0;
7012
+ this.Hl = Hl | 0;
7101
7013
  }
7102
- equals(key) {
7103
- if (key == null || !(key.raw instanceof Uint8Array)) {
7104
- return false;
7014
+ process(view, offset) {
7015
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
7016
+ for (let i = 0; i < 16; i++, offset += 4) {
7017
+ SHA512_W_H[i] = view.getUint32(offset);
7018
+ SHA512_W_L[i] = view.getUint32((offset += 4));
7105
7019
  }
7106
- return equals(this.raw, key.raw);
7020
+ for (let i = 16; i < 80; i++) {
7021
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
7022
+ const W15h = SHA512_W_H[i - 15] | 0;
7023
+ const W15l = SHA512_W_L[i - 15] | 0;
7024
+ const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
7025
+ const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
7026
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
7027
+ const W2h = SHA512_W_H[i - 2] | 0;
7028
+ const W2l = SHA512_W_L[i - 2] | 0;
7029
+ const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
7030
+ const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
7031
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
7032
+ const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
7033
+ const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
7034
+ SHA512_W_H[i] = SUMh | 0;
7035
+ SHA512_W_L[i] = SUMl | 0;
7036
+ }
7037
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
7038
+ // Compression function main loop, 80 rounds
7039
+ for (let i = 0; i < 80; i++) {
7040
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
7041
+ const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
7042
+ const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
7043
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
7044
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
7045
+ const CHIl = (El & Fl) ^ (~El & Gl);
7046
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
7047
+ // prettier-ignore
7048
+ const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
7049
+ const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
7050
+ const T1l = T1ll | 0;
7051
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
7052
+ const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
7053
+ const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
7054
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
7055
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
7056
+ Hh = Gh | 0;
7057
+ Hl = Gl | 0;
7058
+ Gh = Fh | 0;
7059
+ Gl = Fl | 0;
7060
+ Fh = Eh | 0;
7061
+ Fl = El | 0;
7062
+ ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
7063
+ Dh = Ch | 0;
7064
+ Dl = Cl | 0;
7065
+ Ch = Bh | 0;
7066
+ Cl = Bl | 0;
7067
+ Bh = Ah | 0;
7068
+ Bl = Al | 0;
7069
+ const All = u64.add3L(T1l, sigma0l, MAJl);
7070
+ Ah = u64.add3H(All, T1h, sigma0h, MAJh);
7071
+ Al = All | 0;
7072
+ }
7073
+ // Add the compressed chunk to the current hash value
7074
+ ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
7075
+ ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
7076
+ ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
7077
+ ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
7078
+ ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
7079
+ ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
7080
+ ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
7081
+ ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
7082
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
7107
7083
  }
7108
- async verify(data, sig) {
7109
- return hashAndVerify$3(this.jwk, sig, data);
7084
+ roundClean() {
7085
+ SHA512_W_H.fill(0);
7086
+ SHA512_W_L.fill(0);
7087
+ }
7088
+ destroy() {
7089
+ this.buffer.fill(0);
7090
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
7110
7091
  }
7111
7092
  }
7093
+ /** SHA2-512 hash function. */
7094
+ const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
7112
7095
 
7113
7096
  /**
7114
7097
  * Hex, bytes and number utilities.
@@ -7121,6 +7104,7 @@ class ECDSAPublicKey {
7121
7104
  // won't be included into their bundle.
7122
7105
  const _0n$4 = /* @__PURE__ */ BigInt(0);
7123
7106
  const _1n$6 = /* @__PURE__ */ BigInt(1);
7107
+ const _2n$4 = /* @__PURE__ */ BigInt(2);
7124
7108
  function isBytes$1(a) {
7125
7109
  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
7126
7110
  }
@@ -7132,31 +7116,13 @@ function abool(title, value) {
7132
7116
  if (typeof value !== 'boolean')
7133
7117
  throw new Error(title + ' boolean expected, got ' + value);
7134
7118
  }
7135
- // Used in weierstrass, der
7136
- function numberToHexUnpadded(num) {
7137
- const hex = num.toString(16);
7138
- return hex.length & 1 ? '0' + hex : hex;
7139
- }
7140
- function hexToNumber(hex) {
7141
- if (typeof hex !== 'string')
7142
- throw new Error('hex string expected, got ' + typeof hex);
7143
- return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
7144
- }
7145
- // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
7146
- const hasHexBuiltin =
7147
- // @ts-ignore
7148
- typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
7149
7119
  // Array where index 0xf0 (240) is mapped to string 'f0'
7150
7120
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
7151
7121
  /**
7152
- * Convert byte array to hex string. Uses built-in function, when available.
7153
7122
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
7154
7123
  */
7155
7124
  function bytesToHex(bytes) {
7156
7125
  abytes(bytes);
7157
- // @ts-ignore
7158
- if (hasHexBuiltin)
7159
- return bytes.toHex();
7160
7126
  // pre-caching improves the speed 6x
7161
7127
  let hex = '';
7162
7128
  for (let i = 0; i < bytes.length; i++) {
@@ -7164,6 +7130,15 @@ function bytesToHex(bytes) {
7164
7130
  }
7165
7131
  return hex;
7166
7132
  }
7133
+ function numberToHexUnpadded(num) {
7134
+ const hex = num.toString(16);
7135
+ return hex.length & 1 ? '0' + hex : hex;
7136
+ }
7137
+ function hexToNumber(hex) {
7138
+ if (typeof hex !== 'string')
7139
+ throw new Error('hex string expected, got ' + typeof hex);
7140
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
7141
+ }
7167
7142
  // We use optimized technique to convert hex string to byte array
7168
7143
  const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
7169
7144
  function asciiToBase16(ch) {
@@ -7176,15 +7151,11 @@ function asciiToBase16(ch) {
7176
7151
  return;
7177
7152
  }
7178
7153
  /**
7179
- * Convert hex string to byte array. Uses built-in function, when available.
7180
7154
  * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
7181
7155
  */
7182
7156
  function hexToBytes(hex) {
7183
7157
  if (typeof hex !== 'string')
7184
7158
  throw new Error('hex string expected, got ' + typeof hex);
7185
- // @ts-ignore
7186
- if (hasHexBuiltin)
7187
- return Uint8Array.fromHex(hex);
7188
7159
  const hl = hex.length;
7189
7160
  const al = hl / 2;
7190
7161
  if (hl % 2)
@@ -7215,6 +7186,10 @@ function numberToBytesBE(n, len) {
7215
7186
  function numberToBytesLE(n, len) {
7216
7187
  return numberToBytesBE(n, len).reverse();
7217
7188
  }
7189
+ // Unpadded, rarely used
7190
+ function numberToVarBytesBE(n) {
7191
+ return hexToBytes(numberToHexUnpadded(n));
7192
+ }
7218
7193
  /**
7219
7194
  * Takes hex string or Uint8Array, converts to Uint8Array.
7220
7195
  * Validates output length.
@@ -7265,6 +7240,23 @@ function concatBytes(...arrays) {
7265
7240
  }
7266
7241
  return res;
7267
7242
  }
7243
+ // Compares 2 u8a-s in kinda constant time
7244
+ function equalBytes(a, b) {
7245
+ if (a.length !== b.length)
7246
+ return false;
7247
+ let diff = 0;
7248
+ for (let i = 0; i < a.length; i++)
7249
+ diff |= a[i] ^ b[i];
7250
+ return diff === 0;
7251
+ }
7252
+ /**
7253
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
7254
+ */
7255
+ function utf8ToBytes(str) {
7256
+ if (typeof str !== 'string')
7257
+ throw new Error('string expected');
7258
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
7259
+ }
7268
7260
  // Is positive bigint
7269
7261
  const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
7270
7262
  function inRange(n, min, max) {
@@ -7288,7 +7280,6 @@ function aInRange(title, n, min, max) {
7288
7280
  /**
7289
7281
  * Calculates amount of bits in a bigint.
7290
7282
  * Same as `n.toString(2).length`
7291
- * TODO: merge with nLength in modular
7292
7283
  */
7293
7284
  function bitLen(n) {
7294
7285
  let len;
@@ -7296,13 +7287,27 @@ function bitLen(n) {
7296
7287
  ;
7297
7288
  return len;
7298
7289
  }
7290
+ /**
7291
+ * Gets single bit at position.
7292
+ * NOTE: first bit position is 0 (same as arrays)
7293
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
7294
+ */
7295
+ function bitGet(n, pos) {
7296
+ return (n >> BigInt(pos)) & _1n$6;
7297
+ }
7298
+ /**
7299
+ * Sets single bit at position.
7300
+ */
7301
+ function bitSet(n, pos, value) {
7302
+ return n | ((value ? _1n$6 : _0n$4) << BigInt(pos));
7303
+ }
7299
7304
  /**
7300
7305
  * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
7301
7306
  * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
7302
7307
  */
7303
- const bitMask = (n) => (_1n$6 << BigInt(n)) - _1n$6;
7308
+ const bitMask = (n) => (_2n$4 << BigInt(n - 1)) - _1n$6;
7304
7309
  // DRBG
7305
- const u8n = (len) => new Uint8Array(len); // creates Uint8Array
7310
+ const u8n = (data) => new Uint8Array(data); // creates Uint8Array
7306
7311
  const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
7307
7312
  /**
7308
7313
  * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
@@ -7328,7 +7333,7 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
7328
7333
  i = 0;
7329
7334
  };
7330
7335
  const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
7331
- const reseed = (seed = u8n(0)) => {
7336
+ const reseed = (seed = u8n()) => {
7332
7337
  // HMAC-DRBG reseed() function. Steps D-G
7333
7338
  k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
7334
7339
  v = h(); // v = hmac(k || v)
@@ -7393,6 +7398,20 @@ function validateObject(object, validators, optValidators = {}) {
7393
7398
  checkField(fieldName, type, true);
7394
7399
  return object;
7395
7400
  }
7401
+ // validate type tests
7402
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
7403
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
7404
+ // // Should fail type-check
7405
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
7406
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
7407
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
7408
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
7409
+ /**
7410
+ * throws not implemented error
7411
+ */
7412
+ const notImplemented = () => {
7413
+ throw new Error('not implemented');
7414
+ };
7396
7415
  /**
7397
7416
  * Memoizes (caches) computation result.
7398
7417
  * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
@@ -7409,6 +7428,36 @@ function memoized(fn) {
7409
7428
  };
7410
7429
  }
7411
7430
 
7431
+ var ut = /*#__PURE__*/Object.freeze({
7432
+ __proto__: null,
7433
+ aInRange: aInRange,
7434
+ abool: abool,
7435
+ abytes: abytes,
7436
+ bitGet: bitGet,
7437
+ bitLen: bitLen,
7438
+ bitMask: bitMask,
7439
+ bitSet: bitSet,
7440
+ bytesToHex: bytesToHex,
7441
+ bytesToNumberBE: bytesToNumberBE,
7442
+ bytesToNumberLE: bytesToNumberLE,
7443
+ concatBytes: concatBytes,
7444
+ createHmacDrbg: createHmacDrbg,
7445
+ ensureBytes: ensureBytes,
7446
+ equalBytes: equalBytes,
7447
+ hexToBytes: hexToBytes,
7448
+ hexToNumber: hexToNumber,
7449
+ inRange: inRange,
7450
+ isBytes: isBytes$1,
7451
+ memoized: memoized,
7452
+ notImplemented: notImplemented,
7453
+ numberToBytesBE: numberToBytesBE,
7454
+ numberToBytesLE: numberToBytesLE,
7455
+ numberToHexUnpadded: numberToHexUnpadded,
7456
+ numberToVarBytesBE: numberToVarBytesBE,
7457
+ utf8ToBytes: utf8ToBytes,
7458
+ validateObject: validateObject
7459
+ });
7460
+
7412
7461
  /**
7413
7462
  * Utils for modular division and finite fields.
7414
7463
  * A finite field over 11 is integer number operations `mod 11`.
@@ -7425,6 +7474,29 @@ function mod(a, b) {
7425
7474
  const result = a % b;
7426
7475
  return result >= _0n$3 ? result : b + result;
7427
7476
  }
7477
+ /**
7478
+ * Efficiently raise num to power and do modular division.
7479
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
7480
+ * @todo use field version && remove
7481
+ * @example
7482
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
7483
+ */
7484
+ function pow(num, power, modulo) {
7485
+ if (power < _0n$3)
7486
+ throw new Error('invalid exponent, negatives unsupported');
7487
+ if (modulo <= _0n$3)
7488
+ throw new Error('invalid modulus');
7489
+ if (modulo === _1n$5)
7490
+ return _0n$3;
7491
+ let res = _1n$5;
7492
+ while (power > _0n$3) {
7493
+ if (power & _1n$5)
7494
+ res = (res * num) % modulo;
7495
+ num = (num * num) % modulo;
7496
+ power >>= _1n$5;
7497
+ }
7498
+ return res;
7499
+ }
7428
7500
  /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
7429
7501
  function pow2(x, power, modulo) {
7430
7502
  let res = x;
@@ -7465,25 +7537,27 @@ function invert(number, modulo) {
7465
7537
  * Tonelli-Shanks square root search algorithm.
7466
7538
  * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
7467
7539
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
7540
+ * Will start an infinite loop if field order P is not prime.
7468
7541
  * @param P field order
7469
7542
  * @returns function that takes field Fp (created from P) and number n
7470
7543
  */
7471
7544
  function tonelliShanks(P) {
7472
- // Do expensive precomputation step
7545
+ // Legendre constant: used to calculate Legendre symbol (a | p),
7546
+ // which denotes the value of a^((p-1)/2) (mod p).
7547
+ // (a | p) ≡ 1 if a is a square (mod p)
7548
+ // (a | p) ≡ -1 if a is not a square (mod p)
7549
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
7550
+ const legendreC = (P - _1n$5) / _2n$3;
7551
+ let Q, S, Z;
7473
7552
  // Step 1: By factoring out powers of 2 from p - 1,
7474
- // find q and s such that p-1 == q*(2^s) with q odd
7475
- let Q = P - _1n$5;
7476
- let S = 0;
7477
- while (Q % _2n$3 === _0n$3) {
7478
- Q /= _2n$3;
7479
- S++;
7480
- }
7553
+ // find q and s such that p - 1 = q*(2^s) with q odd
7554
+ for (Q = P - _1n$5, S = 0; Q % _2n$3 === _0n$3; Q /= _2n$3, S++)
7555
+ ;
7481
7556
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
7482
- let Z = _2n$3;
7483
- const _Fp = Field(P);
7484
- while (Z < P && FpIsSquare(_Fp, Z)) {
7485
- if (Z++ > 1000)
7486
- throw new Error('Cannot find square root: probably non-prime P');
7557
+ for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++) {
7558
+ // Crash instead of infinity loop, we cannot reasonable count until P.
7559
+ if (Z > 1000)
7560
+ throw new Error('Cannot find square root: likely non-prime P');
7487
7561
  }
7488
7562
  // Fast-path
7489
7563
  if (S === 1) {
@@ -7499,18 +7573,16 @@ function tonelliShanks(P) {
7499
7573
  const Q1div2 = (Q + _1n$5) / _2n$3;
7500
7574
  return function tonelliSlow(Fp, n) {
7501
7575
  // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
7502
- if (!FpIsSquare(Fp, n))
7576
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
7503
7577
  throw new Error('Cannot find square root');
7504
7578
  let r = S;
7505
- // TODO: test on Fp2 and others
7579
+ // TODO: will fail at Fp2/etc
7506
7580
  let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
7507
7581
  let x = Fp.pow(n, Q1div2); // first guess at the square root
7508
7582
  let b = Fp.pow(n, Q); // first guess at the fudge factor
7509
7583
  while (!Fp.eql(b, Fp.ONE)) {
7510
- // (4. If t = 0, return r = 0)
7511
- // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
7512
7584
  if (Fp.eql(b, Fp.ZERO))
7513
- return Fp.ZERO;
7585
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
7514
7586
  // Find m such b^(2^m)==1
7515
7587
  let m = 1;
7516
7588
  for (let t2 = Fp.sqr(b); m < r; m++) {
@@ -7518,8 +7590,7 @@ function tonelliShanks(P) {
7518
7590
  break;
7519
7591
  t2 = Fp.sqr(t2); // t2 *= t2
7520
7592
  }
7521
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
7522
- // otherwise there will be overflow.
7593
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
7523
7594
  const ge = Fp.pow(g, _1n$5 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
7524
7595
  g = Fp.sqr(ge); // g = ge * ge
7525
7596
  x = Fp.mul(x, ge); // x *= ge
@@ -7548,8 +7619,8 @@ function FpSqrt(P) {
7548
7619
  // const ORDER =
7549
7620
  // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
7550
7621
  // const NUM = 72057594037927816n;
7622
+ const p1div4 = (P + _1n$5) / _4n;
7551
7623
  return function sqrt3mod4(Fp, n) {
7552
- const p1div4 = (P + _1n$5) / _4n;
7553
7624
  const root = Fp.pow(n, p1div4);
7554
7625
  // Throw if root**2 != n
7555
7626
  if (!Fp.eql(Fp.sqr(root), n))
@@ -7559,9 +7630,9 @@ function FpSqrt(P) {
7559
7630
  }
7560
7631
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
7561
7632
  if (P % _8n$2 === _5n$1) {
7633
+ const c1 = (P - _5n$1) / _8n$2;
7562
7634
  return function sqrt5mod8(Fp, n) {
7563
7635
  const n2 = Fp.mul(n, _2n$3);
7564
- const c1 = (P - _5n$1) / _8n$2;
7565
7636
  const v = Fp.pow(n2, c1);
7566
7637
  const nv = Fp.mul(n, v);
7567
7638
  const i = Fp.mul(Fp.mul(nv, _2n$3), v);
@@ -7600,78 +7671,52 @@ function validateField(field) {
7600
7671
  * Same as `pow` but for Fp: non-constant-time.
7601
7672
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
7602
7673
  */
7603
- function FpPow(Fp, num, power) {
7674
+ function FpPow(f, num, power) {
7675
+ // Should have same speed as pow for bigints
7676
+ // TODO: benchmark!
7604
7677
  if (power < _0n$3)
7605
7678
  throw new Error('invalid exponent, negatives unsupported');
7606
7679
  if (power === _0n$3)
7607
- return Fp.ONE;
7680
+ return f.ONE;
7608
7681
  if (power === _1n$5)
7609
7682
  return num;
7610
- // @ts-ignore
7611
- let p = Fp.ONE;
7683
+ let p = f.ONE;
7612
7684
  let d = num;
7613
7685
  while (power > _0n$3) {
7614
7686
  if (power & _1n$5)
7615
- p = Fp.mul(p, d);
7616
- d = Fp.sqr(d);
7687
+ p = f.mul(p, d);
7688
+ d = f.sqr(d);
7617
7689
  power >>= _1n$5;
7618
7690
  }
7619
7691
  return p;
7620
7692
  }
7621
7693
  /**
7622
7694
  * Efficiently invert an array of Field elements.
7623
- * Exception-free. Will return `undefined` for 0 elements.
7624
- * @param passZero map 0 to 0 (instead of undefined)
7695
+ * `inv(0)` will return `undefined` here: make sure to throw an error.
7625
7696
  */
7626
- function FpInvertBatch(Fp, nums, passZero = false) {
7627
- const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
7697
+ function FpInvertBatch(f, nums) {
7698
+ const tmp = new Array(nums.length);
7628
7699
  // Walk from first to last, multiply them by each other MOD p
7629
- const multipliedAcc = nums.reduce((acc, num, i) => {
7630
- if (Fp.is0(num))
7700
+ const lastMultiplied = nums.reduce((acc, num, i) => {
7701
+ if (f.is0(num))
7631
7702
  return acc;
7632
- inverted[i] = acc;
7633
- return Fp.mul(acc, num);
7634
- }, Fp.ONE);
7703
+ tmp[i] = acc;
7704
+ return f.mul(acc, num);
7705
+ }, f.ONE);
7635
7706
  // Invert last element
7636
- const invertedAcc = Fp.inv(multipliedAcc);
7707
+ const inverted = f.inv(lastMultiplied);
7637
7708
  // Walk from last to first, multiply them by inverted each other MOD p
7638
7709
  nums.reduceRight((acc, num, i) => {
7639
- if (Fp.is0(num))
7710
+ if (f.is0(num))
7640
7711
  return acc;
7641
- inverted[i] = Fp.mul(acc, inverted[i]);
7642
- return Fp.mul(acc, num);
7643
- }, invertedAcc);
7644
- return inverted;
7645
- }
7646
- /**
7647
- * Legendre symbol.
7648
- * Legendre constant is used to calculate Legendre symbol (a | p)
7649
- * which denotes the value of a^((p-1)/2) (mod p)..
7650
- *
7651
- * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
7652
- * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
7653
- * * (a | p) ≡ 0 if a ≡ 0 (mod p)
7654
- */
7655
- function FpLegendre(Fp, n) {
7656
- const legc = (Fp.ORDER - _1n$5) / _2n$3;
7657
- const powered = Fp.pow(n, legc);
7658
- const yes = Fp.eql(powered, Fp.ONE);
7659
- const zero = Fp.eql(powered, Fp.ZERO);
7660
- const no = Fp.eql(powered, Fp.neg(Fp.ONE));
7661
- if (!yes && !zero && !no)
7662
- throw new Error('Cannot find square root: probably non-prime P');
7663
- return yes ? 1 : zero ? 0 : -1;
7664
- }
7665
- // This function returns True whenever the value x is a square in the field F.
7666
- function FpIsSquare(Fp, n) {
7667
- const l = FpLegendre(Fp, n);
7668
- return l === 0 || l === 1;
7712
+ tmp[i] = f.mul(acc, tmp[i]);
7713
+ return f.mul(acc, num);
7714
+ }, inverted);
7715
+ return tmp;
7669
7716
  }
7670
7717
  // CURVE.n lengths
7671
7718
  function nLength(n, nBitLength) {
7672
7719
  // Bit size, byte size of CURVE.n
7673
- if (nBitLength !== undefined)
7674
- anumber(nBitLength);
7675
7720
  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
7676
7721
  const nByteLength = Math.ceil(_nBitLength / 8);
7677
7722
  return { nBitLength: _nBitLength, nByteLength };
@@ -7734,17 +7779,16 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
7734
7779
  sqrtP = FpSqrt(ORDER);
7735
7780
  return sqrtP(f, n);
7736
7781
  }),
7782
+ invertBatch: (lst) => FpInvertBatch(f, lst),
7783
+ // TODO: do we really need constant cmov?
7784
+ // We don't have const-time bigints anyway, so probably will be not very useful
7785
+ cmov: (a, b, c) => (c ? b : a),
7737
7786
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
7738
7787
  fromBytes: (bytes) => {
7739
7788
  if (bytes.length !== BYTES)
7740
7789
  throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
7741
7790
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
7742
7791
  },
7743
- // TODO: we don't need it here, move out to separate fn
7744
- invertBatch: (lst) => FpInvertBatch(f, lst),
7745
- // We can't move this out because Fp6, Fp12 implement it
7746
- // and it's unclear what to return in there.
7747
- cmov: (a, b, c) => (c ? b : a),
7748
7792
  });
7749
7793
  return Object.freeze(f);
7750
7794
  }
@@ -7813,36 +7857,11 @@ function validateW(W, bits) {
7813
7857
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
7814
7858
  throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
7815
7859
  }
7816
- function calcWOpts(W, scalarBits) {
7817
- validateW(W, scalarBits);
7818
- const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
7819
- const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
7820
- const maxNumber = 2 ** W; // W=8 256
7821
- const mask = bitMask(W); // W=8 255 == mask 0b11111111
7822
- const shiftBy = BigInt(W); // W=8 8
7823
- return { windows, windowSize, mask, maxNumber, shiftBy };
7824
- }
7825
- function calcOffsets(n, window, wOpts) {
7826
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
7827
- let wbits = Number(n & mask); // extract W bits.
7828
- let nextN = n >> shiftBy; // shift number by W bits.
7829
- // What actually happens here:
7830
- // const highestBit = Number(mask ^ (mask >> 1n));
7831
- // let wbits2 = wbits - 1; // skip zero
7832
- // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
7833
- // split if bits > max: +224 => 256-32
7834
- if (wbits > windowSize) {
7835
- // we skip zero, which means instead of `>= size-1`, we do `> size`
7836
- wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
7837
- nextN += _1n$4; // +256 (carry)
7838
- }
7839
- const offsetStart = window * windowSize;
7840
- const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
7841
- const isZero = wbits === 0; // is current window slice a 0?
7842
- const isNeg = wbits < 0; // is current window slice negative?
7843
- const isNegF = window % 2 !== 0; // fake random statement for noise
7844
- const offsetF = offsetStart; // fake offset for noise
7845
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
7860
+ function calcWOpts(W, bits) {
7861
+ validateW(W, bits);
7862
+ const windows = Math.ceil(bits / W) + 1; // +1, because
7863
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
7864
+ return { windows, windowSize };
7846
7865
  }
7847
7866
  function validateMSMPoints(points, c) {
7848
7867
  if (!Array.isArray(points))
@@ -7861,10 +7880,9 @@ function validateMSMScalars(scalars, field) {
7861
7880
  });
7862
7881
  }
7863
7882
  // Since points in different groups cannot be equal (different object constructor),
7864
- // we can have single place to store precomputes.
7865
- // Allows to make points frozen / immutable.
7883
+ // we can have single place to store precomputes
7866
7884
  const pointPrecomputes = new WeakMap();
7867
- const pointWindowSizes = new WeakMap();
7885
+ const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
7868
7886
  function getW(P) {
7869
7887
  return pointWindowSizes.get(P) || 1;
7870
7888
  }
@@ -7919,7 +7937,7 @@ function wNAF(c, bits) {
7919
7937
  for (let window = 0; window < windows; window++) {
7920
7938
  base = p;
7921
7939
  points.push(base);
7922
- // i=1, bc we skip 0
7940
+ // =1, because we skip zero
7923
7941
  for (let i = 1; i < windowSize; i++) {
7924
7942
  base = base.add(p);
7925
7943
  points.push(base);
@@ -7936,35 +7954,48 @@ function wNAF(c, bits) {
7936
7954
  * @returns real and fake (for const-time) points
7937
7955
  */
7938
7956
  wNAF(W, precomputes, n) {
7939
- // Smaller version:
7940
- // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
7941
- // TODO: check the scalar is less than group order?
7942
- // wNAF behavior is undefined otherwise. But have to carefully remove
7943
- // other checks before wNAF. ORDER == bits here.
7944
- // Accumulators
7957
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
7958
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
7959
+ const { windows, windowSize } = calcWOpts(W, bits);
7945
7960
  let p = c.ZERO;
7946
7961
  let f = c.BASE;
7947
- // This code was first written with assumption that 'f' and 'p' will never be infinity point:
7948
- // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
7949
- // there is negate now: it is possible that negated element from low value
7950
- // would be the same as high element, which will create carry into next window.
7951
- // It's not obvious how this can fail, but still worth investigating later.
7952
- const wo = calcWOpts(W, bits);
7953
- for (let window = 0; window < wo.windows; window++) {
7954
- // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
7955
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
7956
- n = nextN;
7957
- if (isZero) {
7958
- // bits are 0: add garbage to fake point
7959
- // Important part for const-time getPublicKey: add random "noise" point to f.
7960
- f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
7962
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
7963
+ const maxNumber = 2 ** W;
7964
+ const shiftBy = BigInt(W);
7965
+ for (let window = 0; window < windows; window++) {
7966
+ const offset = window * windowSize;
7967
+ // Extract W bits.
7968
+ let wbits = Number(n & mask);
7969
+ // Shift number by W bits.
7970
+ n >>= shiftBy;
7971
+ // If the bits are bigger than max size, we'll split those.
7972
+ // +224 => 256 - 32
7973
+ if (wbits > windowSize) {
7974
+ wbits -= maxNumber;
7975
+ n += _1n$4;
7976
+ }
7977
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
7978
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
7979
+ // there is negate now: it is possible that negated element from low value
7980
+ // would be the same as high element, which will create carry into next window.
7981
+ // It's not obvious how this can fail, but still worth investigating later.
7982
+ // Check if we're onto Zero point.
7983
+ // Add random point inside current window to f.
7984
+ const offset1 = offset;
7985
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
7986
+ const cond1 = window % 2 !== 0;
7987
+ const cond2 = wbits < 0;
7988
+ if (wbits === 0) {
7989
+ // The most important part for const-time getPublicKey
7990
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
7961
7991
  }
7962
7992
  else {
7963
- // bits are 1: add to result point
7964
- p = p.add(constTimeNegate(isNeg, precomputes[offset]));
7993
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
7965
7994
  }
7966
7995
  }
7967
- // Return both real and fake points: JIT won't eliminate f.
7996
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
7997
+ // Even if the variable is still unused, there are some checks which will
7998
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
7968
7999
  // At this point there is a way to F be infinity-point even if p is not,
7969
8000
  // which makes it less const-time: around 1 bigint multiply.
7970
8001
  return { p, f };
@@ -7978,21 +8009,31 @@ function wNAF(c, bits) {
7978
8009
  * @returns point
7979
8010
  */
7980
8011
  wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
7981
- const wo = calcWOpts(W, bits);
7982
- for (let window = 0; window < wo.windows; window++) {
8012
+ const { windows, windowSize } = calcWOpts(W, bits);
8013
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
8014
+ const maxNumber = 2 ** W;
8015
+ const shiftBy = BigInt(W);
8016
+ for (let window = 0; window < windows; window++) {
8017
+ const offset = window * windowSize;
7983
8018
  if (n === _0n$2)
7984
- break; // Early-exit, skip 0 value
7985
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
7986
- n = nextN;
7987
- if (isZero) {
7988
- // Window bits are 0: skip processing.
7989
- // Move to next window.
8019
+ break; // No need to go over empty scalar
8020
+ // Extract W bits.
8021
+ let wbits = Number(n & mask);
8022
+ // Shift number by W bits.
8023
+ n >>= shiftBy;
8024
+ // If the bits are bigger than max size, we'll split those.
8025
+ // +224 => 256 - 32
8026
+ if (wbits > windowSize) {
8027
+ wbits -= maxNumber;
8028
+ n += _1n$4;
8029
+ }
8030
+ if (wbits === 0)
7990
8031
  continue;
7991
- }
7992
- else {
7993
- const item = precomputes[offset];
7994
- acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
7995
- }
8032
+ let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero
8033
+ if (wbits < 0)
8034
+ curr = curr.negate();
8035
+ // NOTE: by re-using acc, we can save a lot of additions in case of MSM
8036
+ acc = acc.add(curr);
7996
8037
  }
7997
8038
  return acc;
7998
8039
  },
@@ -8028,7 +8069,7 @@ function wNAF(c, bits) {
8028
8069
  }
8029
8070
  /**
8030
8071
  * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
8031
- * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
8072
+ * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
8032
8073
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
8033
8074
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
8034
8075
  * @param c Curve Point constructor
@@ -8050,15 +8091,15 @@ function pippenger(c, fieldN, points, scalars) {
8050
8091
  const zero = c.ZERO;
8051
8092
  const wbits = bitLen(BigInt(points.length));
8052
8093
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
8053
- const MASK = bitMask(windowSize);
8054
- const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
8094
+ const MASK = (1 << windowSize) - 1;
8095
+ const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array
8055
8096
  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
8056
8097
  let sum = zero;
8057
8098
  for (let i = lastBits; i >= 0; i -= windowSize) {
8058
8099
  buckets.fill(zero);
8059
8100
  for (let j = 0; j < scalars.length; j++) {
8060
8101
  const scalar = scalars[j];
8061
- const wbits = Number((scalar >> BigInt(i)) & MASK);
8102
+ const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
8062
8103
  buckets[wbits] = buckets[wbits].add(points[j]);
8063
8104
  }
8064
8105
  let resI = zero; // not using this will do small speed-up, but will lose ct
@@ -8099,7 +8140,6 @@ function validateBasic(curve) {
8099
8140
  * @module
8100
8141
  */
8101
8142
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8102
- // prettier-ignore
8103
8143
  // Be friendly to bad ECMAScript parsers by not using bigint literals
8104
8144
  // prettier-ignore
8105
8145
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -8158,11 +8198,10 @@ function twistedEdwards(curveDef) {
8158
8198
  }); // NOOP
8159
8199
  // 0 <= n < MASK
8160
8200
  // Coordinates larger than Fp.ORDER are allowed for zip215
8161
- function aCoordinate(title, n, banZero = false) {
8162
- const min = banZero ? _1n$3 : _0n$1;
8163
- aInRange('coordinate ' + title, n, min, MASK);
8201
+ function aCoordinate(title, n) {
8202
+ aInRange('coordinate ' + title, n, _0n$1, MASK);
8164
8203
  }
8165
- function aextpoint(other) {
8204
+ function assertPoint(other) {
8166
8205
  if (!(other instanceof Point))
8167
8206
  throw new Error('ExtendedPoint expected');
8168
8207
  }
@@ -8209,14 +8248,14 @@ function twistedEdwards(curveDef) {
8209
8248
  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
8210
8249
  class Point {
8211
8250
  constructor(ex, ey, ez, et) {
8212
- aCoordinate('x', ex);
8213
- aCoordinate('y', ey);
8214
- aCoordinate('z', ez, true);
8215
- aCoordinate('t', et);
8216
8251
  this.ex = ex;
8217
8252
  this.ey = ey;
8218
8253
  this.ez = ez;
8219
8254
  this.et = et;
8255
+ aCoordinate('x', ex);
8256
+ aCoordinate('y', ey);
8257
+ aCoordinate('z', ez);
8258
+ aCoordinate('t', et);
8220
8259
  Object.freeze(this);
8221
8260
  }
8222
8261
  get x() {
@@ -8234,7 +8273,7 @@ function twistedEdwards(curveDef) {
8234
8273
  return new Point(x, y, _1n$3, modP(x * y));
8235
8274
  }
8236
8275
  static normalizeZ(points) {
8237
- const toInv = FpInvertBatch(Fp, points.map((p) => p.ez));
8276
+ const toInv = Fp.invertBatch(points.map((p) => p.ez));
8238
8277
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
8239
8278
  }
8240
8279
  // Multiscalar Multiplication
@@ -8252,7 +8291,7 @@ function twistedEdwards(curveDef) {
8252
8291
  }
8253
8292
  // Compare one point to another.
8254
8293
  equals(other) {
8255
- aextpoint(other);
8294
+ assertPoint(other);
8256
8295
  const { ex: X1, ey: Y1, ez: Z1 } = this;
8257
8296
  const { ex: X2, ey: Y2, ez: Z2 } = other;
8258
8297
  const X1Z2 = modP(X1 * Z2);
@@ -8293,10 +8332,31 @@ function twistedEdwards(curveDef) {
8293
8332
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
8294
8333
  // Cost: 9M + 1*a + 1*d + 7add.
8295
8334
  add(other) {
8296
- aextpoint(other);
8335
+ assertPoint(other);
8297
8336
  const { a, d } = CURVE;
8298
8337
  const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
8299
8338
  const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
8339
+ // Faster algo for adding 2 Extended Points when curve's a=-1.
8340
+ // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
8341
+ // Cost: 8M + 8add + 2*2.
8342
+ // Note: It does not check whether the `other` point is valid.
8343
+ if (a === BigInt(-1)) {
8344
+ const A = modP((Y1 - X1) * (Y2 + X2));
8345
+ const B = modP((Y1 + X1) * (Y2 - X2));
8346
+ const F = modP(B - A);
8347
+ if (F === _0n$1)
8348
+ return this.double(); // Same point. Tests say it doesn't affect timing
8349
+ const C = modP(Z1 * _2n$2 * T2);
8350
+ const D = modP(T1 * _2n$2 * Z2);
8351
+ const E = D + C;
8352
+ const G = B + A;
8353
+ const H = D - C;
8354
+ const X3 = modP(E * F);
8355
+ const Y3 = modP(G * H);
8356
+ const T3 = modP(E * H);
8357
+ const Z3 = modP(F * G);
8358
+ return new Point(X3, Y3, Z3, T3);
8359
+ }
8300
8360
  const A = modP(X1 * X2); // A = X1*X2
8301
8361
  const B = modP(Y1 * Y2); // B = Y1*Y2
8302
8362
  const C = modP(T1 * d * T2); // C = T1*d*T2
@@ -8396,8 +8456,7 @@ function twistedEdwards(curveDef) {
8396
8456
  return Point.fromAffine({ x, y });
8397
8457
  }
8398
8458
  static fromPrivateKey(privKey) {
8399
- const { scalar } = getPrivateScalar(privKey);
8400
- return G.multiply(scalar); // reduced one call of `toRawBytes`
8459
+ return getExtendedPublicKey(privKey).point;
8401
8460
  }
8402
8461
  toRawBytes() {
8403
8462
  const { x, y } = this.toAffine();
@@ -8420,8 +8479,8 @@ function twistedEdwards(curveDef) {
8420
8479
  function modN_LE(hash) {
8421
8480
  return modN(bytesToNumberLE(hash));
8422
8481
  }
8423
- // Get the hashed private scalar per RFC8032 5.1.5
8424
- function getPrivateScalar(key) {
8482
+ /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
8483
+ function getExtendedPublicKey(key) {
8425
8484
  const len = Fp.BYTES;
8426
8485
  key = ensureBytes('private key', key, len);
8427
8486
  // Hash private key with curve's hash function to produce uniformingly random input
@@ -8430,11 +8489,6 @@ function twistedEdwards(curveDef) {
8430
8489
  const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
8431
8490
  const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
8432
8491
  const scalar = modN_LE(head); // The actual private scalar
8433
- return { head, prefix, scalar };
8434
- }
8435
- // Convenience method that creates public key from scalar. RFC8032 5.1.5
8436
- function getExtendedPublicKey(key) {
8437
- const { head, prefix, scalar } = getPrivateScalar(key);
8438
8492
  const point = G.multiply(scalar); // Point on Edwards curve aka public key
8439
8493
  const pointBytes = point.toRawBytes(); // Uint8Array representation
8440
8494
  return { head, prefix, scalar, point, pointBytes };
@@ -8444,7 +8498,7 @@ function twistedEdwards(curveDef) {
8444
8498
  return getExtendedPublicKey(privKey).pointBytes;
8445
8499
  }
8446
8500
  // int('LE', SHA512(dom2(F, C) || msgs)) mod N
8447
- function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
8501
+ function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
8448
8502
  const msg = concatBytes(...msgs);
8449
8503
  return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
8450
8504
  }
@@ -8501,7 +8555,7 @@ function twistedEdwards(curveDef) {
8501
8555
  G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
8502
8556
  const utils = {
8503
8557
  getExtendedPublicKey,
8504
- /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */
8558
+ // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
8505
8559
  randomPrivateKey: () => randomBytes(Fp.BYTES),
8506
8560
  /**
8507
8561
  * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
@@ -8533,10 +8587,8 @@ function twistedEdwards(curveDef) {
8533
8587
  * @module
8534
8588
  */
8535
8589
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8536
- // 2n**255n - 19n
8537
8590
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
8538
8591
  // √(-1) aka √(a) aka 2^((p-1)/4)
8539
- // Fp.sqrt(Fp.neg(1))
8540
8592
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
8541
8593
  // prettier-ignore
8542
8594
  BigInt(0); const _1n$2 = BigInt(1), _2n$1 = BigInt(2); BigInt(3);
@@ -8595,15 +8647,19 @@ function uvRatio(u, v) {
8595
8647
  }
8596
8648
  const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
8597
8649
  const ed25519Defaults = /* @__PURE__ */ (() => ({
8598
- // Removing Fp.create() will still work, and is 10% faster on sign
8599
- a: Fp.create(BigInt(-1)),
8600
- // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
8650
+ // Param: a
8651
+ a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
8652
+ // d is equal to -121665/121666 over finite field.
8653
+ // Negative number is P - number, and division is invert(number, P)
8601
8654
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
8602
- // Finite field 2n**255n - 19n
8655
+ // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
8603
8656
  Fp,
8604
- // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;
8657
+ // Subgroup order: how many points curve has
8658
+ // 2n**252n + 27742317777372353535851937790883648493n;
8605
8659
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
8660
+ // Cofactor
8606
8661
  h: _8n,
8662
+ // Base point (x, y) aka generator point
8607
8663
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
8608
8664
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
8609
8665
  hash: sha512,
@@ -10176,7 +10232,7 @@ class HMAC extends Hash {
10176
10232
  for (let i = 0; i < pad.length; i++)
10177
10233
  pad[i] ^= 0x36 ^ 0x5c;
10178
10234
  this.oHash.update(pad);
10179
- clean(pad);
10235
+ pad.fill(0);
10180
10236
  }
10181
10237
  update(buf) {
10182
10238
  aexists(this);
@@ -10185,7 +10241,7 @@ class HMAC extends Hash {
10185
10241
  }
10186
10242
  digestInto(out) {
10187
10243
  aexists(this);
10188
- abytes$2(out, this.outputLen);
10244
+ abytes$1(out, this.outputLen);
10189
10245
  this.finished = true;
10190
10246
  this.iHash.digestInto(out);
10191
10247
  this.oHash.update(out);
@@ -10210,9 +10266,6 @@ class HMAC extends Hash {
10210
10266
  to.iHash = iHash._cloneInto(to.iHash);
10211
10267
  return to;
10212
10268
  }
10213
- clone() {
10214
- return this._cloneInto();
10215
- }
10216
10269
  destroy() {
10217
10270
  this.destroyed = true;
10218
10271
  this.oHash.destroy();
@@ -10235,19 +10288,6 @@ hmac.create = (hash, key) => new HMAC(hash, key);
10235
10288
  /**
10236
10289
  * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
10237
10290
  *
10238
- * ### Parameters
10239
- *
10240
- * To initialize a weierstrass curve, one needs to pass following params:
10241
- *
10242
- * * a: formula param
10243
- * * b: formula param
10244
- * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
10245
- * * n: Curve prime subgroup order, total count of valid points in the field
10246
- * * Gx: Base point (x, y) aka generator point x coordinate
10247
- * * Gy: ...y coordinate
10248
- * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
10249
- * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
10250
- *
10251
10291
  * ### Design rationale for types
10252
10292
  *
10253
10293
  * * Interaction between classes from different curves should fail:
@@ -10272,7 +10312,6 @@ hmac.create = (hash, key) => new HMAC(hash, key);
10272
10312
  * @module
10273
10313
  */
10274
10314
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
10275
- // prettier-ignore
10276
10315
  function validateSigVerOpts(opts) {
10277
10316
  if (opts.lowS !== undefined)
10278
10317
  abool('lowS', opts.lowS);
@@ -10306,6 +10345,7 @@ function validatePointOpts(curve) {
10306
10345
  }
10307
10346
  return Object.freeze({ ...opts });
10308
10347
  }
10348
+ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
10309
10349
  class DERErr extends Error {
10310
10350
  constructor(m = '') {
10311
10351
  super(m);
@@ -10398,13 +10438,14 @@ const DER = {
10398
10438
  throw new E('invalid signature integer: negative');
10399
10439
  if (data[0] === 0x00 && !(data[1] & 128))
10400
10440
  throw new E('invalid signature integer: unnecessary leading zero');
10401
- return bytesToNumberBE(data);
10441
+ return b2n(data);
10402
10442
  },
10403
10443
  },
10404
10444
  toSig(hex) {
10405
10445
  // parse DER signature
10406
10446
  const { Err: E, _int: int, _tlv: tlv } = DER;
10407
- const data = ensureBytes('signature', hex);
10447
+ const data = typeof hex === 'string' ? h2b(hex) : hex;
10448
+ abytes(data);
10408
10449
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
10409
10450
  if (seqLeftBytes.length)
10410
10451
  throw new E('invalid signature: left bytes after parsing');
@@ -10444,7 +10485,7 @@ function weierstrassPoints(opts) {
10444
10485
  return { x, y };
10445
10486
  });
10446
10487
  /**
10447
- * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
10488
+ * y² = x³ + ax + b: Short weierstrass curve formula
10448
10489
  * @returns y²
10449
10490
  */
10450
10491
  function weierstrassEquation(x) {
@@ -10490,7 +10531,7 @@ function weierstrassPoints(opts) {
10490
10531
  aInRange('private key', num, _1n$1, N); // num in range [1..N-1]
10491
10532
  return num;
10492
10533
  }
10493
- function aprjpoint(other) {
10534
+ function assertPrjPoint(other) {
10494
10535
  if (!(other instanceof Point))
10495
10536
  throw new Error('ProjectivePoint expected');
10496
10537
  }
@@ -10548,15 +10589,15 @@ function weierstrassPoints(opts) {
10548
10589
  */
10549
10590
  class Point {
10550
10591
  constructor(px, py, pz) {
10592
+ this.px = px;
10593
+ this.py = py;
10594
+ this.pz = pz;
10551
10595
  if (px == null || !Fp.isValid(px))
10552
10596
  throw new Error('x required');
10553
- if (py == null || !Fp.isValid(py) || Fp.is0(py))
10597
+ if (py == null || !Fp.isValid(py))
10554
10598
  throw new Error('y required');
10555
10599
  if (pz == null || !Fp.isValid(pz))
10556
10600
  throw new Error('z required');
10557
- this.px = px;
10558
- this.py = py;
10559
- this.pz = pz;
10560
10601
  Object.freeze(this);
10561
10602
  }
10562
10603
  // Does not validate if the point is on-curve.
@@ -10586,7 +10627,7 @@ function weierstrassPoints(opts) {
10586
10627
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
10587
10628
  */
10588
10629
  static normalizeZ(points) {
10589
- const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
10630
+ const toInv = Fp.invertBatch(points.map((p) => p.pz));
10590
10631
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
10591
10632
  }
10592
10633
  /**
@@ -10624,7 +10665,7 @@ function weierstrassPoints(opts) {
10624
10665
  * Compare one point to another.
10625
10666
  */
10626
10667
  equals(other) {
10627
- aprjpoint(other);
10668
+ assertPrjPoint(other);
10628
10669
  const { px: X1, py: Y1, pz: Z1 } = this;
10629
10670
  const { px: X2, py: Y2, pz: Z2 } = other;
10630
10671
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
@@ -10684,7 +10725,7 @@ function weierstrassPoints(opts) {
10684
10725
  // https://eprint.iacr.org/2015/1060, algorithm 1
10685
10726
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10686
10727
  add(other) {
10687
- aprjpoint(other);
10728
+ assertPrjPoint(other);
10688
10729
  const { px: X1, py: Y1, pz: Z1 } = this;
10689
10730
  const { px: X2, py: Y2, pz: Z2 } = other;
10690
10731
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
@@ -10855,9 +10896,10 @@ function weierstrassPoints(opts) {
10855
10896
  }
10856
10897
  }
10857
10898
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10858
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
10899
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10859
10900
  const _bits = CURVE.nBitLength;
10860
10901
  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
10902
+ // Validate if generator point is on curve
10861
10903
  return {
10862
10904
  CURVE,
10863
10905
  ProjectivePoint: Point,
@@ -10948,7 +10990,7 @@ function weierstrass(curveDef) {
10948
10990
  }
10949
10991
  },
10950
10992
  });
10951
- const numToNByteHex = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
10993
+ const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
10952
10994
  function isBiggerThanHalfOrder(number) {
10953
10995
  const HALF = CURVE_ORDER >> _1n$1;
10954
10996
  return number > HALF;
@@ -10963,13 +11005,10 @@ function weierstrass(curveDef) {
10963
11005
  */
10964
11006
  class Signature {
10965
11007
  constructor(r, s, recovery) {
10966
- aInRange('r', r, _1n$1, CURVE_ORDER); // r in [1..N]
10967
- aInRange('s', s, _1n$1, CURVE_ORDER); // s in [1..N]
10968
11008
  this.r = r;
10969
11009
  this.s = s;
10970
- if (recovery != null)
10971
- this.recovery = recovery;
10972
- Object.freeze(this);
11010
+ this.recovery = recovery;
11011
+ this.assertValidity();
10973
11012
  }
10974
11013
  // pair (bytes of r, bytes of s)
10975
11014
  static fromCompact(hex) {
@@ -10983,11 +11022,10 @@ function weierstrass(curveDef) {
10983
11022
  const { r, s } = DER.toSig(ensureBytes('DER', hex));
10984
11023
  return new Signature(r, s);
10985
11024
  }
10986
- /**
10987
- * @todo remove
10988
- * @deprecated
10989
- */
10990
- assertValidity() { }
11025
+ assertValidity() {
11026
+ aInRange('r', this.r, _1n$1, CURVE_ORDER); // r in [1..N]
11027
+ aInRange('s', this.s, _1n$1, CURVE_ORDER); // s in [1..N]
11028
+ }
10991
11029
  addRecoveryBit(recovery) {
10992
11030
  return new Signature(this.r, this.s, recovery);
10993
11031
  }
@@ -11000,7 +11038,7 @@ function weierstrass(curveDef) {
11000
11038
  if (radj >= Fp.ORDER)
11001
11039
  throw new Error('recovery id 2 or 3 invalid');
11002
11040
  const prefix = (rec & 1) === 0 ? '02' : '03';
11003
- const R = Point.fromHex(prefix + numToNByteHex(radj));
11041
+ const R = Point.fromHex(prefix + numToNByteStr(radj));
11004
11042
  const ir = invN(radj); // r^-1
11005
11043
  const u1 = modN(-h * ir); // -hr^-1
11006
11044
  const u2 = modN(s * ir); // sr^-1
@@ -11022,14 +11060,14 @@ function weierstrass(curveDef) {
11022
11060
  return hexToBytes(this.toDERHex());
11023
11061
  }
11024
11062
  toDERHex() {
11025
- return DER.hexFromSig(this);
11063
+ return DER.hexFromSig({ r: this.r, s: this.s });
11026
11064
  }
11027
11065
  // padded bytes of r, then padded bytes of s
11028
11066
  toCompactRawBytes() {
11029
11067
  return hexToBytes(this.toCompactHex());
11030
11068
  }
11031
11069
  toCompactHex() {
11032
- return numToNByteHex(this.r) + numToNByteHex(this.s);
11070
+ return numToNByteStr(this.r) + numToNByteStr(this.s);
11033
11071
  }
11034
11072
  }
11035
11073
  const utils = {
@@ -11369,28 +11407,26 @@ function sqrtMod(y) {
11369
11407
  }
11370
11408
  const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
11371
11409
  /**
11372
- * secp256k1 curve, ECDSA and ECDH methods.
11373
- *
11374
- * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
11410
+ * secp256k1 short weierstrass curve and ECDSA signatures over it.
11375
11411
  *
11376
11412
  * @example
11377
- * ```js
11378
11413
  * import { secp256k1 } from '@noble/curves/secp256k1';
11414
+ *
11379
11415
  * const priv = secp256k1.utils.randomPrivateKey();
11380
11416
  * const pub = secp256k1.getPublicKey(priv);
11381
11417
  * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
11382
11418
  * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
11383
11419
  * const isValid = secp256k1.verify(sig, msg, pub) === true;
11384
- * ```
11385
11420
  */
11386
11421
  const secp256k1 = createCurve({
11387
- a: BigInt(0),
11422
+ a: BigInt(0), // equation params: a, b
11388
11423
  b: BigInt(7),
11389
- Fp: Fpk1,
11390
- n: secp256k1N,
11424
+ Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
11425
+ n: secp256k1N, // Curve order, total count of valid points in the field
11426
+ // Base point (x, y) aka generator point
11391
11427
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
11392
11428
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
11393
- h: BigInt(1),
11429
+ h: BigInt(1), // Cofactor
11394
11430
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
11395
11431
  endo: {
11396
11432
  // Endomorphism, see above
@@ -11418,7 +11454,7 @@ const secp256k1 = createCurve({
11418
11454
  return { k1neg, k1, k2neg, k2 };
11419
11455
  },
11420
11456
  },
11421
- }, sha256$2);
11457
+ }, sha256$1);
11422
11458
  // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
11423
11459
  // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
11424
11460
  BigInt(0);
@@ -13055,15 +13091,7 @@ class QuickLRU extends Map {
13055
13091
  }
13056
13092
 
13057
13093
  get [Symbol.toStringTag]() {
13058
- return 'QuickLRU';
13059
- }
13060
-
13061
- toString() {
13062
- return `QuickLRU(${this.size}/${this.maxSize})`;
13063
- }
13064
-
13065
- [Symbol.for('nodejs.util.inspect.custom')]() {
13066
- return this.toString();
13094
+ return JSON.stringify([...this.entriesAscending()]);
13067
13095
  }
13068
13096
  }
13069
13097
 
@@ -14436,7 +14464,7 @@ class ENRTree {
14436
14464
  // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string
14437
14465
  // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)
14438
14466
  const signedComponent = root.split(" sig")[0];
14439
- const signedComponentBuffer = utf8ToBytes(signedComponent);
14467
+ const signedComponentBuffer = utf8ToBytes$1(signedComponent);
14440
14468
  const signatureBuffer = fromString(rootValues.signature, "base64url").slice(0, 64);
14441
14469
  const isVerified = verifySignature(signatureBuffer, keccak256(signedComponentBuffer), new Uint8Array(decodedPublicKey));
14442
14470
  if (!isVerified)