@waku/discovery 0.0.8 → 0.0.9-b7e9b08.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
@@ -123,14 +123,14 @@ class TypedEventEmitter extends EventTarget {
123
123
  }
124
124
  }
125
125
 
126
- var Protocols;
126
+ var Protocols$1;
127
127
  (function (Protocols) {
128
128
  Protocols["Relay"] = "relay";
129
129
  Protocols["Store"] = "store";
130
130
  Protocols["LightPush"] = "lightpush";
131
131
  Protocols["Filter"] = "filter";
132
- })(Protocols || (Protocols = {}));
133
- var ProtocolError;
132
+ })(Protocols$1 || (Protocols$1 = {}));
133
+ var ProtocolError$1;
134
134
  (function (ProtocolError) {
135
135
  //
136
136
  // GENERAL ERRORS SECTION
@@ -212,59 +212,68 @@ var ProtocolError;
212
212
  * Ensure that all the pubsub topics used in the decoders are valid and match each other.
213
213
  */
214
214
  ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
215
- })(ProtocolError || (ProtocolError = {}));
215
+ })(ProtocolError$1 || (ProtocolError$1 = {}));
216
216
 
217
- var Tags;
217
+ var Tags$1;
218
218
  (function (Tags) {
219
219
  Tags["BOOTSTRAP"] = "bootstrap";
220
220
  Tags["PEER_EXCHANGE"] = "peer-exchange";
221
221
  Tags["LOCAL"] = "local-peer-cache";
222
- })(Tags || (Tags = {}));
223
- var EPeersByDiscoveryEvents;
222
+ })(Tags$1 || (Tags$1 = {}));
223
+ var EPeersByDiscoveryEvents$1;
224
224
  (function (EPeersByDiscoveryEvents) {
225
225
  EPeersByDiscoveryEvents["PEER_DISCOVERY_BOOTSTRAP"] = "peer:discovery:bootstrap";
226
226
  EPeersByDiscoveryEvents["PEER_DISCOVERY_PEER_EXCHANGE"] = "peer:discovery:peer-exchange";
227
227
  EPeersByDiscoveryEvents["PEER_CONNECT_BOOTSTRAP"] = "peer:connected:bootstrap";
228
228
  EPeersByDiscoveryEvents["PEER_CONNECT_PEER_EXCHANGE"] = "peer:connected:peer-exchange";
229
- })(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));
230
- var EConnectionStateEvents;
229
+ })(EPeersByDiscoveryEvents$1 || (EPeersByDiscoveryEvents$1 = {}));
230
+ var EConnectionStateEvents$1;
231
231
  (function (EConnectionStateEvents) {
232
232
  EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
233
- })(EConnectionStateEvents || (EConnectionStateEvents = {}));
233
+ })(EConnectionStateEvents$1 || (EConnectionStateEvents$1 = {}));
234
234
 
235
235
  const DNS_DISCOVERY_TAG = "@waku/bootstrap";
236
236
 
237
- var HealthStatusChangeEvents;
237
+ var HealthStatusChangeEvents$1;
238
238
  (function (HealthStatusChangeEvents) {
239
239
  HealthStatusChangeEvents["StatusChange"] = "health:change";
240
- })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
241
- var HealthStatus;
240
+ })(HealthStatusChangeEvents$1 || (HealthStatusChangeEvents$1 = {}));
241
+ var HealthStatus$1;
242
242
  (function (HealthStatus) {
243
243
  HealthStatus["Unhealthy"] = "Unhealthy";
244
244
  HealthStatus["MinimallyHealthy"] = "MinimallyHealthy";
245
245
  HealthStatus["SufficientlyHealthy"] = "SufficientlyHealthy";
246
- })(HealthStatus || (HealthStatus = {}));
246
+ })(HealthStatus$1 || (HealthStatus$1 = {}));
247
247
 
248
248
  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
+
252
254
  /**
253
- * Internal assertion helpers.
255
+ * Utilities for hex, bytes, CSPRNG.
254
256
  * @module
255
257
  */
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
+ }
256
269
  /** Asserts something is positive integer. */
257
270
  function anumber(n) {
258
271
  if (!Number.isSafeInteger(n) || n < 0)
259
272
  throw new Error('positive integer expected, got ' + n);
260
273
  }
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
- }
265
274
  /** Asserts something is Uint8Array. */
266
- function abytes$1(b, ...lengths) {
267
- if (!isBytes$2(b))
275
+ function abytes$2(b, ...lengths) {
276
+ if (!isBytes$3(b))
268
277
  throw new Error('Uint8Array expected');
269
278
  if (lengths.length > 0 && !lengths.includes(b.length))
270
279
  throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
@@ -272,7 +281,7 @@ function abytes$1(b, ...lengths) {
272
281
  /** Asserts something is hash */
273
282
  function ahash(h) {
274
283
  if (typeof h !== 'function' || typeof h.create !== 'function')
275
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
284
+ throw new Error('Hash should be wrapped by utils.createHasher');
276
285
  anumber(h.outputLen);
277
286
  anumber(h.blockLen);
278
287
  }
@@ -285,27 +294,19 @@ function aexists(instance, checkFinished = true) {
285
294
  }
286
295
  /** Asserts output is properly-sized byte array */
287
296
  function aoutput(out, instance) {
288
- abytes$1(out);
297
+ abytes$2(out);
289
298
  const min = instance.outputLen;
290
299
  if (out.length < min) {
291
300
  throw new Error('digestInto() expects output buffer of length at least ' + min);
292
301
  }
293
302
  }
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
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. */
309
310
  function createView(arr) {
310
311
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
311
312
  }
@@ -314,12 +315,12 @@ function rotr(word, shift) {
314
315
  return (word << (32 - shift)) | (word >>> shift);
315
316
  }
316
317
  /**
317
- * Convert JS string to byte array.
318
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
318
+ * Converts string to bytes using UTF8 encoding.
319
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
319
320
  */
320
- function utf8ToBytes$2(str) {
321
+ function utf8ToBytes$1(str) {
321
322
  if (typeof str !== 'string')
322
- throw new Error('utf8ToBytes expected string, got ' + typeof str);
323
+ throw new Error('string expected');
323
324
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
324
325
  }
325
326
  /**
@@ -329,18 +330,16 @@ function utf8ToBytes$2(str) {
329
330
  */
330
331
  function toBytes$1(data) {
331
332
  if (typeof data === 'string')
332
- data = utf8ToBytes$2(data);
333
- abytes$1(data);
333
+ data = utf8ToBytes$1(data);
334
+ abytes$2(data);
334
335
  return data;
335
336
  }
336
- /**
337
- * Copies several Uint8Arrays into one.
338
- */
337
+ /** Copies several Uint8Arrays into one. */
339
338
  function concatBytes$2(...arrays) {
340
339
  let sum = 0;
341
340
  for (let i = 0; i < arrays.length; i++) {
342
341
  const a = arrays[i];
343
- abytes$1(a);
342
+ abytes$2(a);
344
343
  sum += a.length;
345
344
  }
346
345
  const res = new Uint8Array(sum);
@@ -353,13 +352,9 @@ function concatBytes$2(...arrays) {
353
352
  }
354
353
  /** For runtime check if class implements interface */
355
354
  class Hash {
356
- // Safe version that clones internal state
357
- clone() {
358
- return this._cloneInto();
359
- }
360
355
  }
361
356
  /** Wraps hash function, creating an interface on top of it */
362
- function wrapConstructor(hashCons) {
357
+ function createHasher(hashCons) {
363
358
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
364
359
  const tmp = hashCons();
365
360
  hashC.outputLen = tmp.outputLen;
@@ -374,7 +369,7 @@ function randomBytes(bytesLength = 32) {
374
369
  }
375
370
  // Legacy Node.js compatibility
376
371
  if (crypto$2 && typeof crypto$2.randomBytes === 'function') {
377
- return crypto$2.randomBytes(bytesLength);
372
+ return Uint8Array.from(crypto$2.randomBytes(bytesLength));
378
373
  }
379
374
  throw new Error('crypto.getRandomValues must be defined');
380
375
  }
@@ -411,21 +406,22 @@ function Maj(a, b, c) {
411
406
  class HashMD extends Hash {
412
407
  constructor(blockLen, outputLen, padOffset, isLE) {
413
408
  super();
414
- this.blockLen = blockLen;
415
- this.outputLen = outputLen;
416
- this.padOffset = padOffset;
417
- this.isLE = isLE;
418
409
  this.finished = false;
419
410
  this.length = 0;
420
411
  this.pos = 0;
421
412
  this.destroyed = false;
413
+ this.blockLen = blockLen;
414
+ this.outputLen = outputLen;
415
+ this.padOffset = padOffset;
416
+ this.isLE = isLE;
422
417
  this.buffer = new Uint8Array(blockLen);
423
418
  this.view = createView(this.buffer);
424
419
  }
425
420
  update(data) {
426
421
  aexists(this);
427
- const { view, buffer, blockLen } = this;
428
422
  data = toBytes$1(data);
423
+ abytes$2(data);
424
+ const { view, buffer, blockLen } = this;
429
425
  const len = data.length;
430
426
  for (let pos = 0; pos < len;) {
431
427
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -459,7 +455,7 @@ class HashMD extends Hash {
459
455
  let { pos } = this;
460
456
  // append the bit '1' to the message
461
457
  buffer[pos++] = 0b10000000;
462
- this.buffer.subarray(pos).fill(0);
458
+ clean(this.buffer.subarray(pos));
463
459
  // we have less than padOffset left in buffer, so we cannot put length in
464
460
  // current block, need process it and pad again
465
461
  if (this.padOffset > blockLen - pos) {
@@ -497,28 +493,90 @@ class HashMD extends Hash {
497
493
  to || (to = new this.constructor());
498
494
  to.set(...this.get());
499
495
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
496
+ to.destroyed = destroyed;
497
+ to.finished = finished;
500
498
  to.length = length;
501
499
  to.pos = pos;
502
- to.finished = finished;
503
- to.destroyed = destroyed;
504
500
  if (length % blockLen)
505
501
  to.buffer.set(buffer);
506
502
  return to;
507
503
  }
504
+ clone() {
505
+ return this._cloneInto();
506
+ }
508
507
  }
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
+ ]);
509
521
 
510
522
  /**
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).
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).
517
572
  * @module
518
573
  */
519
- /** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */
574
+ /**
575
+ * Round constants:
576
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
577
+ */
520
578
  // prettier-ignore
521
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
579
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
522
580
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
523
581
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
524
582
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -528,19 +586,11 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
528
586
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
529
587
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
530
588
  ]);
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
- */
589
+ /** Reusable temporary buffer. "W" comes straight from spec. */
540
590
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
541
591
  class SHA256 extends HashMD {
542
- constructor() {
543
- super(64, 32, 8, false);
592
+ constructor(outputLen = 32) {
593
+ super(64, outputLen, 8, false);
544
594
  // We cannot use array here since array allows indexing by variable
545
595
  // which means optimizer/compiler cannot use registers.
546
596
  this.A = SHA256_IV[0] | 0;
@@ -606,15 +656,312 @@ class SHA256 extends HashMD {
606
656
  this.set(A, B, C, D, E, F, G, H);
607
657
  }
608
658
  roundClean() {
609
- SHA256_W.fill(0);
659
+ clean(SHA256_W);
610
660
  }
611
661
  destroy() {
612
662
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
613
- this.buffer.fill(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);
614
820
  }
615
821
  }
616
- /** SHA2-256 hash function */
617
- const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
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;
845
+
846
+ var Protocols;
847
+ (function (Protocols) {
848
+ Protocols["Relay"] = "relay";
849
+ Protocols["Store"] = "store";
850
+ Protocols["LightPush"] = "lightpush";
851
+ Protocols["Filter"] = "filter";
852
+ })(Protocols || (Protocols = {}));
853
+ var ProtocolError;
854
+ (function (ProtocolError) {
855
+ //
856
+ // GENERAL ERRORS SECTION
857
+ //
858
+ /**
859
+ * Could not determine the origin of the fault. Best to check connectivity and try again
860
+ * */
861
+ ProtocolError["GENERIC_FAIL"] = "Generic error";
862
+ /**
863
+ * The remote peer rejected the message. Information provided by the remote peer
864
+ * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
865
+ * or `DECODE_FAILED` can be used.
866
+ */
867
+ ProtocolError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
868
+ /**
869
+ * Failure to protobuf decode the message. May be due to a remote peer issue,
870
+ * ensuring that messages are sent via several peer enable mitigation of this error.
871
+ */
872
+ ProtocolError["DECODE_FAILED"] = "Failed to decode";
873
+ /**
874
+ * Failure to find a peer with suitable protocols. This may due to a connection issue.
875
+ * Mitigation can be: retrying after a given time period, display connectivity issue
876
+ * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`
877
+ * on the connection manager before retrying.
878
+ */
879
+ ProtocolError["NO_PEER_AVAILABLE"] = "No peer available";
880
+ /**
881
+ * Failure to find a stream to the peer. This may be because the connection with the peer is not still alive.
882
+ * Mitigation can be: retrying after a given time period, or mitigation for `NO_PEER_AVAILABLE` can be used.
883
+ */
884
+ ProtocolError["NO_STREAM_AVAILABLE"] = "No stream available";
885
+ /**
886
+ * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`
887
+ * or `DECODE_FAILED` can be used.
888
+ */
889
+ ProtocolError["NO_RESPONSE"] = "No response received";
890
+ //
891
+ // SEND ERRORS SECTION
892
+ //
893
+ /**
894
+ * Failure to protobuf encode the message. This is not recoverable and needs
895
+ * further investigation.
896
+ */
897
+ ProtocolError["ENCODE_FAILED"] = "Failed to encode";
898
+ /**
899
+ * The message payload is empty, making the message invalid. Ensure that a non-empty
900
+ * payload is set on the outgoing message.
901
+ */
902
+ ProtocolError["EMPTY_PAYLOAD"] = "Payload is empty";
903
+ /**
904
+ * The message size is above the maximum message size allowed on the Waku Network.
905
+ * Compressing the message or using an alternative strategy for large messages is recommended.
906
+ */
907
+ ProtocolError["SIZE_TOO_BIG"] = "Size is too big";
908
+ /**
909
+ * The PubsubTopic passed to the send function is not configured on the Waku node.
910
+ * Please ensure that the PubsubTopic is used when initializing the Waku node.
911
+ */
912
+ ProtocolError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
913
+ /**
914
+ * Fails when
915
+ */
916
+ ProtocolError["STREAM_ABORTED"] = "Stream aborted";
917
+ /**
918
+ * General proof generation error message.
919
+ * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42
920
+ */
921
+ ProtocolError["RLN_PROOF_GENERATION"] = "Proof generation failed";
922
+ //
923
+ // RECEIVE ERRORS SECTION
924
+ //
925
+ /**
926
+ * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.
927
+ * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
928
+ */
929
+ ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
930
+ /**
931
+ * The topics passed in the decoders do not match each other, or don't exist at all.
932
+ * Ensure that all the pubsub topics used in the decoders are valid and match each other.
933
+ */
934
+ ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
935
+ })(ProtocolError || (ProtocolError = {}));
936
+
937
+ var Tags;
938
+ (function (Tags) {
939
+ Tags["BOOTSTRAP"] = "bootstrap";
940
+ Tags["PEER_EXCHANGE"] = "peer-exchange";
941
+ Tags["LOCAL"] = "local-peer-cache";
942
+ })(Tags || (Tags = {}));
943
+ var EPeersByDiscoveryEvents;
944
+ (function (EPeersByDiscoveryEvents) {
945
+ EPeersByDiscoveryEvents["PEER_DISCOVERY_BOOTSTRAP"] = "peer:discovery:bootstrap";
946
+ EPeersByDiscoveryEvents["PEER_DISCOVERY_PEER_EXCHANGE"] = "peer:discovery:peer-exchange";
947
+ EPeersByDiscoveryEvents["PEER_CONNECT_BOOTSTRAP"] = "peer:connected:bootstrap";
948
+ EPeersByDiscoveryEvents["PEER_CONNECT_PEER_EXCHANGE"] = "peer:connected:peer-exchange";
949
+ })(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));
950
+ var EConnectionStateEvents;
951
+ (function (EConnectionStateEvents) {
952
+ EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
953
+ })(EConnectionStateEvents || (EConnectionStateEvents = {}));
954
+
955
+ var HealthStatusChangeEvents;
956
+ (function (HealthStatusChangeEvents) {
957
+ HealthStatusChangeEvents["StatusChange"] = "health:change";
958
+ })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
959
+ var HealthStatus;
960
+ (function (HealthStatus) {
961
+ HealthStatus["Unhealthy"] = "Unhealthy";
962
+ HealthStatus["MinimallyHealthy"] = "MinimallyHealthy";
963
+ HealthStatus["SufficientlyHealthy"] = "SufficientlyHealthy";
964
+ })(HealthStatus || (HealthStatus = {}));
618
965
 
619
966
  function equals$2(aa, bb) {
620
967
  if (aa === bb)
@@ -1940,7 +2287,7 @@ const bytesToUtf8 = (b) => toString$1(b, "utf8");
1940
2287
  /**
1941
2288
  * Encode utf-8 string to byte array.
1942
2289
  */
1943
- const utf8ToBytes$1 = (s) => fromString(s, "utf8");
2290
+ const utf8ToBytes = (s) => fromString(s, "utf8");
1944
2291
 
1945
2292
  const decodeRelayShard = (bytes) => {
1946
2293
  // explicitly converting to Uint8Array to avoid Buffer
@@ -2814,7 +3161,7 @@ var nodeCrypto = /*#__PURE__*/Object.freeze({
2814
3161
  /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
2815
3162
  const _0n$5 = BigInt(0);
2816
3163
  const _1n$7 = BigInt(1);
2817
- const _2n$5 = BigInt(2);
3164
+ const _2n$4 = BigInt(2);
2818
3165
  const _3n$2 = BigInt(3);
2819
3166
  const _8n$3 = BigInt(8);
2820
3167
  const CURVE = Object.freeze({
@@ -2827,7 +3174,7 @@ const CURVE = Object.freeze({
2827
3174
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
2828
3175
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2829
3176
  });
2830
- const divNearest$1 = (a, b) => (a + b / _2n$5) / b;
3177
+ const divNearest$1 = (a, b) => (a + b / _2n$4) / b;
2831
3178
  const endo = {
2832
3179
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2833
3180
  splitScalar(k) {
@@ -2916,12 +3263,12 @@ class JacobianPoint {
2916
3263
  const B = mod$1(Y1 * Y1);
2917
3264
  const C = mod$1(B * B);
2918
3265
  const x1b = X1 + B;
2919
- const D = mod$1(_2n$5 * (mod$1(x1b * x1b) - A - C));
3266
+ const D = mod$1(_2n$4 * (mod$1(x1b * x1b) - A - C));
2920
3267
  const E = mod$1(_3n$2 * A);
2921
3268
  const F = mod$1(E * E);
2922
- const X3 = mod$1(F - _2n$5 * D);
3269
+ const X3 = mod$1(F - _2n$4 * D);
2923
3270
  const Y3 = mod$1(E * (D - X3) - _8n$3 * C);
2924
- const Z3 = mod$1(_2n$5 * Y1 * Z1);
3271
+ const Z3 = mod$1(_2n$4 * Y1 * Z1);
2925
3272
  return new JacobianPoint(X3, Y3, Z3);
2926
3273
  }
2927
3274
  add(other) {
@@ -2951,7 +3298,7 @@ class JacobianPoint {
2951
3298
  const HH = mod$1(H * H);
2952
3299
  const HHH = mod$1(H * HH);
2953
3300
  const V = mod$1(U1 * HH);
2954
- const X3 = mod$1(r * r - HHH - _2n$5 * V);
3301
+ const X3 = mod$1(r * r - HHH - _2n$4 * V);
2955
3302
  const Y3 = mod$1(r * (V - X3) - S1 * HHH);
2956
3303
  const Z3 = mod$1(Z1 * Z2 * H);
2957
3304
  return new JacobianPoint(X3, Y3, Z3);
@@ -3112,7 +3459,7 @@ class Point {
3112
3459
  pointPrecomputes$1.delete(this);
3113
3460
  }
3114
3461
  hasEvenY() {
3115
- return this.y % _2n$5 === _0n$5;
3462
+ return this.y % _2n$4 === _0n$5;
3116
3463
  }
3117
3464
  static fromCompressedHex(bytes) {
3118
3465
  const isShort = bytes.length === 32;
@@ -3271,7 +3618,7 @@ class Signature {
3271
3618
  this.assertValidity();
3272
3619
  }
3273
3620
  static fromCompact(hex) {
3274
- const arr = hex instanceof Uint8Array;
3621
+ const arr = isBytes$2(hex);
3275
3622
  const name = 'Signature.fromCompact';
3276
3623
  if (typeof hex !== 'string' && !arr)
3277
3624
  throw new TypeError(`${name}: Expected string or Uint8Array`);
@@ -3281,7 +3628,7 @@ class Signature {
3281
3628
  return new Signature(hexToNumber$1(str.slice(0, 64)), hexToNumber$1(str.slice(64, 128)));
3282
3629
  }
3283
3630
  static fromDER(hex) {
3284
- const arr = hex instanceof Uint8Array;
3631
+ const arr = isBytes$2(hex);
3285
3632
  if (typeof hex !== 'string' && !arr)
3286
3633
  throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
3287
3634
  const { r, s } = parseDERSignature(arr ? hex : hexToBytes$1(hex));
@@ -3330,9 +3677,15 @@ class Signature {
3330
3677
  return numTo32bStr(this.r) + numTo32bStr(this.s);
3331
3678
  }
3332
3679
  }
3680
+ function isBytes$2(a) {
3681
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3682
+ }
3683
+ function abytes$1(item) {
3684
+ if (!isBytes$2(item))
3685
+ throw new Error('Uint8Array expected');
3686
+ }
3333
3687
  function concatBytes$1(...arrays) {
3334
- if (!arrays.every((b) => b instanceof Uint8Array))
3335
- throw new Error('Uint8Array list expected');
3688
+ arrays.every(abytes$1);
3336
3689
  if (arrays.length === 1)
3337
3690
  return arrays[0];
3338
3691
  const length = arrays.reduce((a, arr) => a + arr.length, 0);
@@ -3344,16 +3697,44 @@ function concatBytes$1(...arrays) {
3344
3697
  }
3345
3698
  return result;
3346
3699
  }
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');
3700
+ const hexes$1 = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
3701
+ function bytesToHex$1(bytes) {
3702
+ abytes$1(bytes);
3351
3703
  let hex = '';
3352
- for (let i = 0; i < uint8a.length; i++) {
3353
- hex += hexes$1[uint8a[i]];
3704
+ for (let i = 0; i < bytes.length; i++) {
3705
+ hex += hexes$1[bytes[i]];
3354
3706
  }
3355
3707
  return hex;
3356
3708
  }
3709
+ const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
3710
+ function asciiToBase16$1(ch) {
3711
+ if (ch >= asciis$1._0 && ch <= asciis$1._9)
3712
+ return ch - asciis$1._0;
3713
+ if (ch >= asciis$1.A && ch <= asciis$1.F)
3714
+ return ch - (asciis$1.A - 10);
3715
+ if (ch >= asciis$1.a && ch <= asciis$1.f)
3716
+ return ch - (asciis$1.a - 10);
3717
+ return;
3718
+ }
3719
+ function hexToBytes$1(hex) {
3720
+ if (typeof hex !== 'string')
3721
+ throw new Error('hex string expected, got ' + typeof hex);
3722
+ const hl = hex.length;
3723
+ const al = hl / 2;
3724
+ if (hl % 2)
3725
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
3726
+ const array = new Uint8Array(al);
3727
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
3728
+ const n1 = asciiToBase16$1(hex.charCodeAt(hi));
3729
+ const n2 = asciiToBase16$1(hex.charCodeAt(hi + 1));
3730
+ if (n1 === undefined || n2 === undefined) {
3731
+ const char = hex[hi] + hex[hi + 1];
3732
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
3733
+ }
3734
+ array[ai] = n1 * 16 + n2;
3735
+ }
3736
+ return array;
3737
+ }
3357
3738
  const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
3358
3739
  function numTo32bStr(num) {
3359
3740
  if (typeof num !== 'bigint')
@@ -3378,28 +3759,11 @@ function hexToNumber$1(hex) {
3378
3759
  }
3379
3760
  return BigInt(`0x${hex}`);
3380
3761
  }
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
- }
3398
3762
  function bytesToNumber(bytes) {
3399
3763
  return hexToNumber$1(bytesToHex$1(bytes));
3400
3764
  }
3401
3765
  function ensureBytes$1(hex) {
3402
- return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex);
3766
+ return isBytes$2(hex) ? Uint8Array.from(hex) : hexToBytes$1(hex);
3403
3767
  }
3404
3768
  function normalizeScalar(num) {
3405
3769
  if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)
@@ -3433,7 +3797,7 @@ function sqrtMod$1(x) {
3433
3797
  const b3 = (b2 * b2 * x) % P;
3434
3798
  const b6 = (pow2$1(b3, _3n$2) * b3) % P;
3435
3799
  const b9 = (pow2$1(b6, _3n$2) * b3) % P;
3436
- const b11 = (pow2$1(b9, _2n$5) * b2) % P;
3800
+ const b11 = (pow2$1(b9, _2n$4) * b2) % P;
3437
3801
  const b22 = (pow2$1(b11, _11n) * b11) % P;
3438
3802
  const b44 = (pow2$1(b22, _22n) * b22) % P;
3439
3803
  const b88 = (pow2$1(b44, _44n) * b44) % P;
@@ -3442,7 +3806,7 @@ function sqrtMod$1(x) {
3442
3806
  const b223 = (pow2$1(b220, _3n$2) * b3) % P;
3443
3807
  const t1 = (pow2$1(b223, _23n) * b22) % P;
3444
3808
  const t2 = (pow2$1(t1, _6n) * b2) % P;
3445
- const rt = pow2$1(t2, _2n$5);
3809
+ const rt = pow2$1(t2, _2n$4);
3446
3810
  const xc = (rt * rt) % P;
3447
3811
  if (xc !== x)
3448
3812
  throw new Error('Cannot find square root');
@@ -3607,7 +3971,7 @@ function normalizePrivateKey(key) {
3607
3971
  throw new Error('Expected 32 bytes of private key');
3608
3972
  num = hexToNumber$1(key);
3609
3973
  }
3610
- else if (key instanceof Uint8Array) {
3974
+ else if (isBytes$2(key)) {
3611
3975
  if (key.length !== groupLen)
3612
3976
  throw new Error('Expected 32 bytes of private key');
3613
3977
  num = bytesToNumber(key);
@@ -6825,273 +7189,46 @@ function getOID(curve) {
6825
7189
  return OID_256;
6826
7190
  }
6827
7191
  if (curve === 'P-384') {
6828
- return OID_384;
6829
- }
6830
- if (curve === 'P-521') {
6831
- return OID_521;
6832
- }
6833
- throw new InvalidParametersError(`Invalid curve ${curve}`);
6834
- }
6835
-
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 };
7192
+ return OID_384;
7193
+ }
7194
+ if (curve === 'P-521') {
7195
+ return OID_521;
7196
+ }
7197
+ throw new InvalidParametersError(`Invalid curve ${curve}`);
6914
7198
  }
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
7199
 
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;
7200
+ class ECDSAPublicKey {
7201
+ type = 'ECDSA';
7202
+ jwk;
7203
+ _raw;
7204
+ constructor(jwk) {
7205
+ this.jwk = jwk;
6989
7206
  }
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];
7207
+ get raw() {
7208
+ if (this._raw == null) {
7209
+ this._raw = publicKeyToPKIMessage(this.jwk);
7210
+ }
7211
+ return this._raw;
6994
7212
  }
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;
7213
+ toMultihash() {
7214
+ return identity.digest(publicKeyToProtobuf(this));
7013
7215
  }
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));
7019
- }
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);
7216
+ toCID() {
7217
+ return CID.createV1(114, this.toMultihash());
7083
7218
  }
7084
- roundClean() {
7085
- SHA512_W_H.fill(0);
7086
- SHA512_W_L.fill(0);
7219
+ toString() {
7220
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
7087
7221
  }
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);
7222
+ equals(key) {
7223
+ if (key == null || !(key.raw instanceof Uint8Array)) {
7224
+ return false;
7225
+ }
7226
+ return equals(this.raw, key.raw);
7227
+ }
7228
+ async verify(data, sig) {
7229
+ return hashAndVerify$3(this.jwk, sig, data);
7091
7230
  }
7092
7231
  }
7093
- /** SHA2-512 hash function. */
7094
- const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
7095
7232
 
7096
7233
  /**
7097
7234
  * Hex, bytes and number utilities.
@@ -7104,7 +7241,6 @@ const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
7104
7241
  // won't be included into their bundle.
7105
7242
  const _0n$4 = /* @__PURE__ */ BigInt(0);
7106
7243
  const _1n$6 = /* @__PURE__ */ BigInt(1);
7107
- const _2n$4 = /* @__PURE__ */ BigInt(2);
7108
7244
  function isBytes$1(a) {
7109
7245
  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
7110
7246
  }
@@ -7116,13 +7252,31 @@ function abool(title, value) {
7116
7252
  if (typeof value !== 'boolean')
7117
7253
  throw new Error(title + ' boolean expected, got ' + value);
7118
7254
  }
7255
+ // Used in weierstrass, der
7256
+ function numberToHexUnpadded(num) {
7257
+ const hex = num.toString(16);
7258
+ return hex.length & 1 ? '0' + hex : hex;
7259
+ }
7260
+ function hexToNumber(hex) {
7261
+ if (typeof hex !== 'string')
7262
+ throw new Error('hex string expected, got ' + typeof hex);
7263
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
7264
+ }
7265
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
7266
+ const hasHexBuiltin =
7267
+ // @ts-ignore
7268
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
7119
7269
  // Array where index 0xf0 (240) is mapped to string 'f0'
7120
7270
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
7121
7271
  /**
7272
+ * Convert byte array to hex string. Uses built-in function, when available.
7122
7273
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
7123
7274
  */
7124
7275
  function bytesToHex(bytes) {
7125
7276
  abytes(bytes);
7277
+ // @ts-ignore
7278
+ if (hasHexBuiltin)
7279
+ return bytes.toHex();
7126
7280
  // pre-caching improves the speed 6x
7127
7281
  let hex = '';
7128
7282
  for (let i = 0; i < bytes.length; i++) {
@@ -7130,15 +7284,6 @@ function bytesToHex(bytes) {
7130
7284
  }
7131
7285
  return hex;
7132
7286
  }
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
- }
7142
7287
  // We use optimized technique to convert hex string to byte array
7143
7288
  const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
7144
7289
  function asciiToBase16(ch) {
@@ -7151,11 +7296,15 @@ function asciiToBase16(ch) {
7151
7296
  return;
7152
7297
  }
7153
7298
  /**
7299
+ * Convert hex string to byte array. Uses built-in function, when available.
7154
7300
  * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
7155
7301
  */
7156
7302
  function hexToBytes(hex) {
7157
7303
  if (typeof hex !== 'string')
7158
7304
  throw new Error('hex string expected, got ' + typeof hex);
7305
+ // @ts-ignore
7306
+ if (hasHexBuiltin)
7307
+ return Uint8Array.fromHex(hex);
7159
7308
  const hl = hex.length;
7160
7309
  const al = hl / 2;
7161
7310
  if (hl % 2)
@@ -7186,10 +7335,6 @@ function numberToBytesBE(n, len) {
7186
7335
  function numberToBytesLE(n, len) {
7187
7336
  return numberToBytesBE(n, len).reverse();
7188
7337
  }
7189
- // Unpadded, rarely used
7190
- function numberToVarBytesBE(n) {
7191
- return hexToBytes(numberToHexUnpadded(n));
7192
- }
7193
7338
  /**
7194
7339
  * Takes hex string or Uint8Array, converts to Uint8Array.
7195
7340
  * Validates output length.
@@ -7240,23 +7385,6 @@ function concatBytes(...arrays) {
7240
7385
  }
7241
7386
  return res;
7242
7387
  }
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
- }
7260
7388
  // Is positive bigint
7261
7389
  const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
7262
7390
  function inRange(n, min, max) {
@@ -7280,6 +7408,7 @@ function aInRange(title, n, min, max) {
7280
7408
  /**
7281
7409
  * Calculates amount of bits in a bigint.
7282
7410
  * Same as `n.toString(2).length`
7411
+ * TODO: merge with nLength in modular
7283
7412
  */
7284
7413
  function bitLen(n) {
7285
7414
  let len;
@@ -7287,27 +7416,13 @@ function bitLen(n) {
7287
7416
  ;
7288
7417
  return len;
7289
7418
  }
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
- }
7304
7419
  /**
7305
7420
  * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
7306
7421
  * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
7307
7422
  */
7308
- const bitMask = (n) => (_2n$4 << BigInt(n - 1)) - _1n$6;
7423
+ const bitMask = (n) => (_1n$6 << BigInt(n)) - _1n$6;
7309
7424
  // DRBG
7310
- const u8n = (data) => new Uint8Array(data); // creates Uint8Array
7425
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
7311
7426
  const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
7312
7427
  /**
7313
7428
  * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
@@ -7333,7 +7448,7 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
7333
7448
  i = 0;
7334
7449
  };
7335
7450
  const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
7336
- const reseed = (seed = u8n()) => {
7451
+ const reseed = (seed = u8n(0)) => {
7337
7452
  // HMAC-DRBG reseed() function. Steps D-G
7338
7453
  k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
7339
7454
  v = h(); // v = hmac(k || v)
@@ -7398,20 +7513,6 @@ function validateObject(object, validators, optValidators = {}) {
7398
7513
  checkField(fieldName, type, true);
7399
7514
  return object;
7400
7515
  }
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
- };
7415
7516
  /**
7416
7517
  * Memoizes (caches) computation result.
7417
7518
  * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
@@ -7428,36 +7529,6 @@ function memoized(fn) {
7428
7529
  };
7429
7530
  }
7430
7531
 
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
-
7461
7532
  /**
7462
7533
  * Utils for modular division and finite fields.
7463
7534
  * A finite field over 11 is integer number operations `mod 11`.
@@ -7474,29 +7545,6 @@ function mod(a, b) {
7474
7545
  const result = a % b;
7475
7546
  return result >= _0n$3 ? result : b + result;
7476
7547
  }
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
- }
7500
7548
  /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
7501
7549
  function pow2(x, power, modulo) {
7502
7550
  let res = x;
@@ -7537,27 +7585,25 @@ function invert(number, modulo) {
7537
7585
  * Tonelli-Shanks square root search algorithm.
7538
7586
  * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
7539
7587
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
7540
- * Will start an infinite loop if field order P is not prime.
7541
7588
  * @param P field order
7542
7589
  * @returns function that takes field Fp (created from P) and number n
7543
7590
  */
7544
7591
  function tonelliShanks(P) {
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;
7592
+ // Do expensive precomputation step
7552
7593
  // Step 1: By factoring out powers of 2 from p - 1,
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
- ;
7594
+ // find q and s such that p-1 == q*(2^s) with q odd
7595
+ let Q = P - _1n$5;
7596
+ let S = 0;
7597
+ while (Q % _2n$3 === _0n$3) {
7598
+ Q /= _2n$3;
7599
+ S++;
7600
+ }
7556
7601
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
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');
7602
+ let Z = _2n$3;
7603
+ const _Fp = Field(P);
7604
+ while (Z < P && FpIsSquare(_Fp, Z)) {
7605
+ if (Z++ > 1000)
7606
+ throw new Error('Cannot find square root: probably non-prime P');
7561
7607
  }
7562
7608
  // Fast-path
7563
7609
  if (S === 1) {
@@ -7573,16 +7619,18 @@ function tonelliShanks(P) {
7573
7619
  const Q1div2 = (Q + _1n$5) / _2n$3;
7574
7620
  return function tonelliSlow(Fp, n) {
7575
7621
  // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
7576
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
7622
+ if (!FpIsSquare(Fp, n))
7577
7623
  throw new Error('Cannot find square root');
7578
7624
  let r = S;
7579
- // TODO: will fail at Fp2/etc
7625
+ // TODO: test on Fp2 and others
7580
7626
  let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
7581
7627
  let x = Fp.pow(n, Q1div2); // first guess at the square root
7582
7628
  let b = Fp.pow(n, Q); // first guess at the fudge factor
7583
7629
  while (!Fp.eql(b, Fp.ONE)) {
7630
+ // (4. If t = 0, return r = 0)
7631
+ // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
7584
7632
  if (Fp.eql(b, Fp.ZERO))
7585
- return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
7633
+ return Fp.ZERO;
7586
7634
  // Find m such b^(2^m)==1
7587
7635
  let m = 1;
7588
7636
  for (let t2 = Fp.sqr(b); m < r; m++) {
@@ -7590,7 +7638,8 @@ function tonelliShanks(P) {
7590
7638
  break;
7591
7639
  t2 = Fp.sqr(t2); // t2 *= t2
7592
7640
  }
7593
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
7641
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
7642
+ // otherwise there will be overflow.
7594
7643
  const ge = Fp.pow(g, _1n$5 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
7595
7644
  g = Fp.sqr(ge); // g = ge * ge
7596
7645
  x = Fp.mul(x, ge); // x *= ge
@@ -7619,8 +7668,8 @@ function FpSqrt(P) {
7619
7668
  // const ORDER =
7620
7669
  // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
7621
7670
  // const NUM = 72057594037927816n;
7622
- const p1div4 = (P + _1n$5) / _4n;
7623
7671
  return function sqrt3mod4(Fp, n) {
7672
+ const p1div4 = (P + _1n$5) / _4n;
7624
7673
  const root = Fp.pow(n, p1div4);
7625
7674
  // Throw if root**2 != n
7626
7675
  if (!Fp.eql(Fp.sqr(root), n))
@@ -7630,9 +7679,9 @@ function FpSqrt(P) {
7630
7679
  }
7631
7680
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
7632
7681
  if (P % _8n$2 === _5n$1) {
7633
- const c1 = (P - _5n$1) / _8n$2;
7634
7682
  return function sqrt5mod8(Fp, n) {
7635
7683
  const n2 = Fp.mul(n, _2n$3);
7684
+ const c1 = (P - _5n$1) / _8n$2;
7636
7685
  const v = Fp.pow(n2, c1);
7637
7686
  const nv = Fp.mul(n, v);
7638
7687
  const i = Fp.mul(Fp.mul(nv, _2n$3), v);
@@ -7671,52 +7720,78 @@ function validateField(field) {
7671
7720
  * Same as `pow` but for Fp: non-constant-time.
7672
7721
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
7673
7722
  */
7674
- function FpPow(f, num, power) {
7675
- // Should have same speed as pow for bigints
7676
- // TODO: benchmark!
7723
+ function FpPow(Fp, num, power) {
7677
7724
  if (power < _0n$3)
7678
7725
  throw new Error('invalid exponent, negatives unsupported');
7679
7726
  if (power === _0n$3)
7680
- return f.ONE;
7727
+ return Fp.ONE;
7681
7728
  if (power === _1n$5)
7682
7729
  return num;
7683
- let p = f.ONE;
7730
+ // @ts-ignore
7731
+ let p = Fp.ONE;
7684
7732
  let d = num;
7685
7733
  while (power > _0n$3) {
7686
7734
  if (power & _1n$5)
7687
- p = f.mul(p, d);
7688
- d = f.sqr(d);
7735
+ p = Fp.mul(p, d);
7736
+ d = Fp.sqr(d);
7689
7737
  power >>= _1n$5;
7690
7738
  }
7691
7739
  return p;
7692
7740
  }
7693
7741
  /**
7694
7742
  * Efficiently invert an array of Field elements.
7695
- * `inv(0)` will return `undefined` here: make sure to throw an error.
7743
+ * Exception-free. Will return `undefined` for 0 elements.
7744
+ * @param passZero map 0 to 0 (instead of undefined)
7696
7745
  */
7697
- function FpInvertBatch(f, nums) {
7698
- const tmp = new Array(nums.length);
7746
+ function FpInvertBatch(Fp, nums, passZero = false) {
7747
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
7699
7748
  // Walk from first to last, multiply them by each other MOD p
7700
- const lastMultiplied = nums.reduce((acc, num, i) => {
7701
- if (f.is0(num))
7749
+ const multipliedAcc = nums.reduce((acc, num, i) => {
7750
+ if (Fp.is0(num))
7702
7751
  return acc;
7703
- tmp[i] = acc;
7704
- return f.mul(acc, num);
7705
- }, f.ONE);
7752
+ inverted[i] = acc;
7753
+ return Fp.mul(acc, num);
7754
+ }, Fp.ONE);
7706
7755
  // Invert last element
7707
- const inverted = f.inv(lastMultiplied);
7756
+ const invertedAcc = Fp.inv(multipliedAcc);
7708
7757
  // Walk from last to first, multiply them by inverted each other MOD p
7709
7758
  nums.reduceRight((acc, num, i) => {
7710
- if (f.is0(num))
7759
+ if (Fp.is0(num))
7711
7760
  return acc;
7712
- tmp[i] = f.mul(acc, tmp[i]);
7713
- return f.mul(acc, num);
7714
- }, inverted);
7715
- return tmp;
7761
+ inverted[i] = Fp.mul(acc, inverted[i]);
7762
+ return Fp.mul(acc, num);
7763
+ }, invertedAcc);
7764
+ return inverted;
7765
+ }
7766
+ /**
7767
+ * Legendre symbol.
7768
+ * Legendre constant is used to calculate Legendre symbol (a | p)
7769
+ * which denotes the value of a^((p-1)/2) (mod p)..
7770
+ *
7771
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
7772
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
7773
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
7774
+ */
7775
+ function FpLegendre(Fp, n) {
7776
+ const legc = (Fp.ORDER - _1n$5) / _2n$3;
7777
+ const powered = Fp.pow(n, legc);
7778
+ const yes = Fp.eql(powered, Fp.ONE);
7779
+ const zero = Fp.eql(powered, Fp.ZERO);
7780
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
7781
+ if (!yes && !zero && !no)
7782
+ throw new Error('Cannot find square root: probably non-prime P');
7783
+ return yes ? 1 : zero ? 0 : -1;
7784
+ }
7785
+ // This function returns True whenever the value x is a square in the field F.
7786
+ function FpIsSquare(Fp, n) {
7787
+ const l = FpLegendre(Fp, n);
7788
+ return l === 0 || l === 1;
7716
7789
  }
7717
7790
  // CURVE.n lengths
7718
7791
  function nLength(n, nBitLength) {
7719
7792
  // Bit size, byte size of CURVE.n
7793
+ if (nBitLength !== undefined)
7794
+ anumber(nBitLength);
7720
7795
  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
7721
7796
  const nByteLength = Math.ceil(_nBitLength / 8);
7722
7797
  return { nBitLength: _nBitLength, nByteLength };
@@ -7779,16 +7854,17 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
7779
7854
  sqrtP = FpSqrt(ORDER);
7780
7855
  return sqrtP(f, n);
7781
7856
  }),
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),
7786
7857
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
7787
7858
  fromBytes: (bytes) => {
7788
7859
  if (bytes.length !== BYTES)
7789
7860
  throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
7790
7861
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
7791
7862
  },
7863
+ // TODO: we don't need it here, move out to separate fn
7864
+ invertBatch: (lst) => FpInvertBatch(f, lst),
7865
+ // We can't move this out because Fp6, Fp12 implement it
7866
+ // and it's unclear what to return in there.
7867
+ cmov: (a, b, c) => (c ? b : a),
7792
7868
  });
7793
7869
  return Object.freeze(f);
7794
7870
  }
@@ -7857,11 +7933,36 @@ function validateW(W, bits) {
7857
7933
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
7858
7934
  throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
7859
7935
  }
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 };
7936
+ function calcWOpts(W, scalarBits) {
7937
+ validateW(W, scalarBits);
7938
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
7939
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
7940
+ const maxNumber = 2 ** W; // W=8 256
7941
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
7942
+ const shiftBy = BigInt(W); // W=8 8
7943
+ return { windows, windowSize, mask, maxNumber, shiftBy };
7944
+ }
7945
+ function calcOffsets(n, window, wOpts) {
7946
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
7947
+ let wbits = Number(n & mask); // extract W bits.
7948
+ let nextN = n >> shiftBy; // shift number by W bits.
7949
+ // What actually happens here:
7950
+ // const highestBit = Number(mask ^ (mask >> 1n));
7951
+ // let wbits2 = wbits - 1; // skip zero
7952
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
7953
+ // split if bits > max: +224 => 256-32
7954
+ if (wbits > windowSize) {
7955
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
7956
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
7957
+ nextN += _1n$4; // +256 (carry)
7958
+ }
7959
+ const offsetStart = window * windowSize;
7960
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
7961
+ const isZero = wbits === 0; // is current window slice a 0?
7962
+ const isNeg = wbits < 0; // is current window slice negative?
7963
+ const isNegF = window % 2 !== 0; // fake random statement for noise
7964
+ const offsetF = offsetStart; // fake offset for noise
7965
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
7865
7966
  }
7866
7967
  function validateMSMPoints(points, c) {
7867
7968
  if (!Array.isArray(points))
@@ -7880,9 +7981,10 @@ function validateMSMScalars(scalars, field) {
7880
7981
  });
7881
7982
  }
7882
7983
  // Since points in different groups cannot be equal (different object constructor),
7883
- // we can have single place to store precomputes
7984
+ // we can have single place to store precomputes.
7985
+ // Allows to make points frozen / immutable.
7884
7986
  const pointPrecomputes = new WeakMap();
7885
- const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
7987
+ const pointWindowSizes = new WeakMap();
7886
7988
  function getW(P) {
7887
7989
  return pointWindowSizes.get(P) || 1;
7888
7990
  }
@@ -7937,7 +8039,7 @@ function wNAF(c, bits) {
7937
8039
  for (let window = 0; window < windows; window++) {
7938
8040
  base = p;
7939
8041
  points.push(base);
7940
- // =1, because we skip zero
8042
+ // i=1, bc we skip 0
7941
8043
  for (let i = 1; i < windowSize; i++) {
7942
8044
  base = base.add(p);
7943
8045
  points.push(base);
@@ -7954,48 +8056,35 @@ function wNAF(c, bits) {
7954
8056
  * @returns real and fake (for const-time) points
7955
8057
  */
7956
8058
  wNAF(W, precomputes, n) {
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);
8059
+ // Smaller version:
8060
+ // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
8061
+ // TODO: check the scalar is less than group order?
8062
+ // wNAF behavior is undefined otherwise. But have to carefully remove
8063
+ // other checks before wNAF. ORDER == bits here.
8064
+ // Accumulators
7960
8065
  let p = c.ZERO;
7961
8066
  let f = c.BASE;
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]));
8067
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
8068
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
8069
+ // there is negate now: it is possible that negated element from low value
8070
+ // would be the same as high element, which will create carry into next window.
8071
+ // It's not obvious how this can fail, but still worth investigating later.
8072
+ const wo = calcWOpts(W, bits);
8073
+ for (let window = 0; window < wo.windows; window++) {
8074
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
8075
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
8076
+ n = nextN;
8077
+ if (isZero) {
8078
+ // bits are 0: add garbage to fake point
8079
+ // Important part for const-time getPublicKey: add random "noise" point to f.
8080
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
7991
8081
  }
7992
8082
  else {
7993
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
8083
+ // bits are 1: add to result point
8084
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
7994
8085
  }
7995
8086
  }
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.
8087
+ // Return both real and fake points: JIT won't eliminate f.
7999
8088
  // At this point there is a way to F be infinity-point even if p is not,
8000
8089
  // which makes it less const-time: around 1 bigint multiply.
8001
8090
  return { p, f };
@@ -8009,31 +8098,21 @@ function wNAF(c, bits) {
8009
8098
  * @returns point
8010
8099
  */
8011
8100
  wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
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;
8101
+ const wo = calcWOpts(W, bits);
8102
+ for (let window = 0; window < wo.windows; window++) {
8018
8103
  if (n === _0n$2)
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)
8104
+ break; // Early-exit, skip 0 value
8105
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
8106
+ n = nextN;
8107
+ if (isZero) {
8108
+ // Window bits are 0: skip processing.
8109
+ // Move to next window.
8031
8110
  continue;
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);
8111
+ }
8112
+ else {
8113
+ const item = precomputes[offset];
8114
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
8115
+ }
8037
8116
  }
8038
8117
  return acc;
8039
8118
  },
@@ -8069,7 +8148,7 @@ function wNAF(c, bits) {
8069
8148
  }
8070
8149
  /**
8071
8150
  * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
8072
- * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
8151
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
8073
8152
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
8074
8153
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
8075
8154
  * @param c Curve Point constructor
@@ -8091,15 +8170,15 @@ function pippenger(c, fieldN, points, scalars) {
8091
8170
  const zero = c.ZERO;
8092
8171
  const wbits = bitLen(BigInt(points.length));
8093
8172
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
8094
- const MASK = (1 << windowSize) - 1;
8095
- const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array
8173
+ const MASK = bitMask(windowSize);
8174
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
8096
8175
  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
8097
8176
  let sum = zero;
8098
8177
  for (let i = lastBits; i >= 0; i -= windowSize) {
8099
8178
  buckets.fill(zero);
8100
8179
  for (let j = 0; j < scalars.length; j++) {
8101
8180
  const scalar = scalars[j];
8102
- const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
8181
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
8103
8182
  buckets[wbits] = buckets[wbits].add(points[j]);
8104
8183
  }
8105
8184
  let resI = zero; // not using this will do small speed-up, but will lose ct
@@ -8140,6 +8219,7 @@ function validateBasic(curve) {
8140
8219
  * @module
8141
8220
  */
8142
8221
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8222
+ // prettier-ignore
8143
8223
  // Be friendly to bad ECMAScript parsers by not using bigint literals
8144
8224
  // prettier-ignore
8145
8225
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -8198,10 +8278,11 @@ function twistedEdwards(curveDef) {
8198
8278
  }); // NOOP
8199
8279
  // 0 <= n < MASK
8200
8280
  // Coordinates larger than Fp.ORDER are allowed for zip215
8201
- function aCoordinate(title, n) {
8202
- aInRange('coordinate ' + title, n, _0n$1, MASK);
8281
+ function aCoordinate(title, n, banZero = false) {
8282
+ const min = banZero ? _1n$3 : _0n$1;
8283
+ aInRange('coordinate ' + title, n, min, MASK);
8203
8284
  }
8204
- function assertPoint(other) {
8285
+ function aextpoint(other) {
8205
8286
  if (!(other instanceof Point))
8206
8287
  throw new Error('ExtendedPoint expected');
8207
8288
  }
@@ -8248,14 +8329,14 @@ function twistedEdwards(curveDef) {
8248
8329
  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
8249
8330
  class Point {
8250
8331
  constructor(ex, ey, ez, et) {
8332
+ aCoordinate('x', ex);
8333
+ aCoordinate('y', ey);
8334
+ aCoordinate('z', ez, true);
8335
+ aCoordinate('t', et);
8251
8336
  this.ex = ex;
8252
8337
  this.ey = ey;
8253
8338
  this.ez = ez;
8254
8339
  this.et = et;
8255
- aCoordinate('x', ex);
8256
- aCoordinate('y', ey);
8257
- aCoordinate('z', ez);
8258
- aCoordinate('t', et);
8259
8340
  Object.freeze(this);
8260
8341
  }
8261
8342
  get x() {
@@ -8273,7 +8354,7 @@ function twistedEdwards(curveDef) {
8273
8354
  return new Point(x, y, _1n$3, modP(x * y));
8274
8355
  }
8275
8356
  static normalizeZ(points) {
8276
- const toInv = Fp.invertBatch(points.map((p) => p.ez));
8357
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.ez));
8277
8358
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
8278
8359
  }
8279
8360
  // Multiscalar Multiplication
@@ -8291,7 +8372,7 @@ function twistedEdwards(curveDef) {
8291
8372
  }
8292
8373
  // Compare one point to another.
8293
8374
  equals(other) {
8294
- assertPoint(other);
8375
+ aextpoint(other);
8295
8376
  const { ex: X1, ey: Y1, ez: Z1 } = this;
8296
8377
  const { ex: X2, ey: Y2, ez: Z2 } = other;
8297
8378
  const X1Z2 = modP(X1 * Z2);
@@ -8332,31 +8413,10 @@ function twistedEdwards(curveDef) {
8332
8413
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
8333
8414
  // Cost: 9M + 1*a + 1*d + 7add.
8334
8415
  add(other) {
8335
- assertPoint(other);
8416
+ aextpoint(other);
8336
8417
  const { a, d } = CURVE;
8337
8418
  const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
8338
8419
  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
- }
8360
8420
  const A = modP(X1 * X2); // A = X1*X2
8361
8421
  const B = modP(Y1 * Y2); // B = Y1*Y2
8362
8422
  const C = modP(T1 * d * T2); // C = T1*d*T2
@@ -8456,7 +8516,8 @@ function twistedEdwards(curveDef) {
8456
8516
  return Point.fromAffine({ x, y });
8457
8517
  }
8458
8518
  static fromPrivateKey(privKey) {
8459
- return getExtendedPublicKey(privKey).point;
8519
+ const { scalar } = getPrivateScalar(privKey);
8520
+ return G.multiply(scalar); // reduced one call of `toRawBytes`
8460
8521
  }
8461
8522
  toRawBytes() {
8462
8523
  const { x, y } = this.toAffine();
@@ -8479,8 +8540,8 @@ function twistedEdwards(curveDef) {
8479
8540
  function modN_LE(hash) {
8480
8541
  return modN(bytesToNumberLE(hash));
8481
8542
  }
8482
- /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
8483
- function getExtendedPublicKey(key) {
8543
+ // Get the hashed private scalar per RFC8032 5.1.5
8544
+ function getPrivateScalar(key) {
8484
8545
  const len = Fp.BYTES;
8485
8546
  key = ensureBytes('private key', key, len);
8486
8547
  // Hash private key with curve's hash function to produce uniformingly random input
@@ -8489,6 +8550,11 @@ function twistedEdwards(curveDef) {
8489
8550
  const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
8490
8551
  const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
8491
8552
  const scalar = modN_LE(head); // The actual private scalar
8553
+ return { head, prefix, scalar };
8554
+ }
8555
+ // Convenience method that creates public key from scalar. RFC8032 5.1.5
8556
+ function getExtendedPublicKey(key) {
8557
+ const { head, prefix, scalar } = getPrivateScalar(key);
8492
8558
  const point = G.multiply(scalar); // Point on Edwards curve aka public key
8493
8559
  const pointBytes = point.toRawBytes(); // Uint8Array representation
8494
8560
  return { head, prefix, scalar, point, pointBytes };
@@ -8498,7 +8564,7 @@ function twistedEdwards(curveDef) {
8498
8564
  return getExtendedPublicKey(privKey).pointBytes;
8499
8565
  }
8500
8566
  // int('LE', SHA512(dom2(F, C) || msgs)) mod N
8501
- function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
8567
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
8502
8568
  const msg = concatBytes(...msgs);
8503
8569
  return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
8504
8570
  }
@@ -8555,7 +8621,7 @@ function twistedEdwards(curveDef) {
8555
8621
  G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
8556
8622
  const utils = {
8557
8623
  getExtendedPublicKey,
8558
- // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
8624
+ /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */
8559
8625
  randomPrivateKey: () => randomBytes(Fp.BYTES),
8560
8626
  /**
8561
8627
  * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
@@ -8587,8 +8653,10 @@ function twistedEdwards(curveDef) {
8587
8653
  * @module
8588
8654
  */
8589
8655
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8656
+ // 2n**255n - 19n
8590
8657
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
8591
8658
  // √(-1) aka √(a) aka 2^((p-1)/4)
8659
+ // Fp.sqrt(Fp.neg(1))
8592
8660
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
8593
8661
  // prettier-ignore
8594
8662
  BigInt(0); const _1n$2 = BigInt(1), _2n$1 = BigInt(2); BigInt(3);
@@ -8647,19 +8715,15 @@ function uvRatio(u, v) {
8647
8715
  }
8648
8716
  const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
8649
8717
  const ed25519Defaults = /* @__PURE__ */ (() => ({
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)
8718
+ // Removing Fp.create() will still work, and is 10% faster on sign
8719
+ a: Fp.create(BigInt(-1)),
8720
+ // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
8654
8721
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
8655
- // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
8722
+ // Finite field 2n**255n - 19n
8656
8723
  Fp,
8657
- // Subgroup order: how many points curve has
8658
- // 2n**252n + 27742317777372353535851937790883648493n;
8724
+ // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;
8659
8725
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
8660
- // Cofactor
8661
8726
  h: _8n,
8662
- // Base point (x, y) aka generator point
8663
8727
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
8664
8728
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
8665
8729
  hash: sha512,
@@ -10232,7 +10296,7 @@ class HMAC extends Hash {
10232
10296
  for (let i = 0; i < pad.length; i++)
10233
10297
  pad[i] ^= 0x36 ^ 0x5c;
10234
10298
  this.oHash.update(pad);
10235
- pad.fill(0);
10299
+ clean(pad);
10236
10300
  }
10237
10301
  update(buf) {
10238
10302
  aexists(this);
@@ -10241,7 +10305,7 @@ class HMAC extends Hash {
10241
10305
  }
10242
10306
  digestInto(out) {
10243
10307
  aexists(this);
10244
- abytes$1(out, this.outputLen);
10308
+ abytes$2(out, this.outputLen);
10245
10309
  this.finished = true;
10246
10310
  this.iHash.digestInto(out);
10247
10311
  this.oHash.update(out);
@@ -10266,6 +10330,9 @@ class HMAC extends Hash {
10266
10330
  to.iHash = iHash._cloneInto(to.iHash);
10267
10331
  return to;
10268
10332
  }
10333
+ clone() {
10334
+ return this._cloneInto();
10335
+ }
10269
10336
  destroy() {
10270
10337
  this.destroyed = true;
10271
10338
  this.oHash.destroy();
@@ -10288,6 +10355,19 @@ hmac.create = (hash, key) => new HMAC(hash, key);
10288
10355
  /**
10289
10356
  * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
10290
10357
  *
10358
+ * ### Parameters
10359
+ *
10360
+ * To initialize a weierstrass curve, one needs to pass following params:
10361
+ *
10362
+ * * a: formula param
10363
+ * * b: formula param
10364
+ * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
10365
+ * * n: Curve prime subgroup order, total count of valid points in the field
10366
+ * * Gx: Base point (x, y) aka generator point x coordinate
10367
+ * * Gy: ...y coordinate
10368
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
10369
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
10370
+ *
10291
10371
  * ### Design rationale for types
10292
10372
  *
10293
10373
  * * Interaction between classes from different curves should fail:
@@ -10312,6 +10392,7 @@ hmac.create = (hash, key) => new HMAC(hash, key);
10312
10392
  * @module
10313
10393
  */
10314
10394
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
10395
+ // prettier-ignore
10315
10396
  function validateSigVerOpts(opts) {
10316
10397
  if (opts.lowS !== undefined)
10317
10398
  abool('lowS', opts.lowS);
@@ -10345,7 +10426,6 @@ function validatePointOpts(curve) {
10345
10426
  }
10346
10427
  return Object.freeze({ ...opts });
10347
10428
  }
10348
- const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
10349
10429
  class DERErr extends Error {
10350
10430
  constructor(m = '') {
10351
10431
  super(m);
@@ -10438,14 +10518,13 @@ const DER = {
10438
10518
  throw new E('invalid signature integer: negative');
10439
10519
  if (data[0] === 0x00 && !(data[1] & 128))
10440
10520
  throw new E('invalid signature integer: unnecessary leading zero');
10441
- return b2n(data);
10521
+ return bytesToNumberBE(data);
10442
10522
  },
10443
10523
  },
10444
10524
  toSig(hex) {
10445
10525
  // parse DER signature
10446
10526
  const { Err: E, _int: int, _tlv: tlv } = DER;
10447
- const data = typeof hex === 'string' ? h2b(hex) : hex;
10448
- abytes(data);
10527
+ const data = ensureBytes('signature', hex);
10449
10528
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
10450
10529
  if (seqLeftBytes.length)
10451
10530
  throw new E('invalid signature: left bytes after parsing');
@@ -10485,7 +10564,7 @@ function weierstrassPoints(opts) {
10485
10564
  return { x, y };
10486
10565
  });
10487
10566
  /**
10488
- * y² = x³ + ax + b: Short weierstrass curve formula
10567
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
10489
10568
  * @returns y²
10490
10569
  */
10491
10570
  function weierstrassEquation(x) {
@@ -10531,7 +10610,7 @@ function weierstrassPoints(opts) {
10531
10610
  aInRange('private key', num, _1n$1, N); // num in range [1..N-1]
10532
10611
  return num;
10533
10612
  }
10534
- function assertPrjPoint(other) {
10613
+ function aprjpoint(other) {
10535
10614
  if (!(other instanceof Point))
10536
10615
  throw new Error('ProjectivePoint expected');
10537
10616
  }
@@ -10589,15 +10668,15 @@ function weierstrassPoints(opts) {
10589
10668
  */
10590
10669
  class Point {
10591
10670
  constructor(px, py, pz) {
10592
- this.px = px;
10593
- this.py = py;
10594
- this.pz = pz;
10595
10671
  if (px == null || !Fp.isValid(px))
10596
10672
  throw new Error('x required');
10597
- if (py == null || !Fp.isValid(py))
10673
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
10598
10674
  throw new Error('y required');
10599
10675
  if (pz == null || !Fp.isValid(pz))
10600
10676
  throw new Error('z required');
10677
+ this.px = px;
10678
+ this.py = py;
10679
+ this.pz = pz;
10601
10680
  Object.freeze(this);
10602
10681
  }
10603
10682
  // Does not validate if the point is on-curve.
@@ -10627,7 +10706,7 @@ function weierstrassPoints(opts) {
10627
10706
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
10628
10707
  */
10629
10708
  static normalizeZ(points) {
10630
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
10709
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
10631
10710
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
10632
10711
  }
10633
10712
  /**
@@ -10665,7 +10744,7 @@ function weierstrassPoints(opts) {
10665
10744
  * Compare one point to another.
10666
10745
  */
10667
10746
  equals(other) {
10668
- assertPrjPoint(other);
10747
+ aprjpoint(other);
10669
10748
  const { px: X1, py: Y1, pz: Z1 } = this;
10670
10749
  const { px: X2, py: Y2, pz: Z2 } = other;
10671
10750
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
@@ -10725,7 +10804,7 @@ function weierstrassPoints(opts) {
10725
10804
  // https://eprint.iacr.org/2015/1060, algorithm 1
10726
10805
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10727
10806
  add(other) {
10728
- assertPrjPoint(other);
10807
+ aprjpoint(other);
10729
10808
  const { px: X1, py: Y1, pz: Z1 } = this;
10730
10809
  const { px: X2, py: Y2, pz: Z2 } = other;
10731
10810
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
@@ -10896,10 +10975,9 @@ function weierstrassPoints(opts) {
10896
10975
  }
10897
10976
  }
10898
10977
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10899
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10978
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
10900
10979
  const _bits = CURVE.nBitLength;
10901
10980
  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
10902
- // Validate if generator point is on curve
10903
10981
  return {
10904
10982
  CURVE,
10905
10983
  ProjectivePoint: Point,
@@ -10990,7 +11068,7 @@ function weierstrass(curveDef) {
10990
11068
  }
10991
11069
  },
10992
11070
  });
10993
- const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
11071
+ const numToNByteHex = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
10994
11072
  function isBiggerThanHalfOrder(number) {
10995
11073
  const HALF = CURVE_ORDER >> _1n$1;
10996
11074
  return number > HALF;
@@ -11005,10 +11083,13 @@ function weierstrass(curveDef) {
11005
11083
  */
11006
11084
  class Signature {
11007
11085
  constructor(r, s, recovery) {
11086
+ aInRange('r', r, _1n$1, CURVE_ORDER); // r in [1..N]
11087
+ aInRange('s', s, _1n$1, CURVE_ORDER); // s in [1..N]
11008
11088
  this.r = r;
11009
11089
  this.s = s;
11010
- this.recovery = recovery;
11011
- this.assertValidity();
11090
+ if (recovery != null)
11091
+ this.recovery = recovery;
11092
+ Object.freeze(this);
11012
11093
  }
11013
11094
  // pair (bytes of r, bytes of s)
11014
11095
  static fromCompact(hex) {
@@ -11022,10 +11103,11 @@ function weierstrass(curveDef) {
11022
11103
  const { r, s } = DER.toSig(ensureBytes('DER', hex));
11023
11104
  return new Signature(r, s);
11024
11105
  }
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
- }
11106
+ /**
11107
+ * @todo remove
11108
+ * @deprecated
11109
+ */
11110
+ assertValidity() { }
11029
11111
  addRecoveryBit(recovery) {
11030
11112
  return new Signature(this.r, this.s, recovery);
11031
11113
  }
@@ -11038,7 +11120,7 @@ function weierstrass(curveDef) {
11038
11120
  if (radj >= Fp.ORDER)
11039
11121
  throw new Error('recovery id 2 or 3 invalid');
11040
11122
  const prefix = (rec & 1) === 0 ? '02' : '03';
11041
- const R = Point.fromHex(prefix + numToNByteStr(radj));
11123
+ const R = Point.fromHex(prefix + numToNByteHex(radj));
11042
11124
  const ir = invN(radj); // r^-1
11043
11125
  const u1 = modN(-h * ir); // -hr^-1
11044
11126
  const u2 = modN(s * ir); // sr^-1
@@ -11060,14 +11142,14 @@ function weierstrass(curveDef) {
11060
11142
  return hexToBytes(this.toDERHex());
11061
11143
  }
11062
11144
  toDERHex() {
11063
- return DER.hexFromSig({ r: this.r, s: this.s });
11145
+ return DER.hexFromSig(this);
11064
11146
  }
11065
11147
  // padded bytes of r, then padded bytes of s
11066
11148
  toCompactRawBytes() {
11067
11149
  return hexToBytes(this.toCompactHex());
11068
11150
  }
11069
11151
  toCompactHex() {
11070
- return numToNByteStr(this.r) + numToNByteStr(this.s);
11152
+ return numToNByteHex(this.r) + numToNByteHex(this.s);
11071
11153
  }
11072
11154
  }
11073
11155
  const utils = {
@@ -11407,26 +11489,28 @@ function sqrtMod(y) {
11407
11489
  }
11408
11490
  const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
11409
11491
  /**
11410
- * secp256k1 short weierstrass curve and ECDSA signatures over it.
11492
+ * secp256k1 curve, ECDSA and ECDH methods.
11493
+ *
11494
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
11411
11495
  *
11412
11496
  * @example
11497
+ * ```js
11413
11498
  * import { secp256k1 } from '@noble/curves/secp256k1';
11414
- *
11415
11499
  * const priv = secp256k1.utils.randomPrivateKey();
11416
11500
  * const pub = secp256k1.getPublicKey(priv);
11417
11501
  * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
11418
11502
  * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
11419
11503
  * const isValid = secp256k1.verify(sig, msg, pub) === true;
11504
+ * ```
11420
11505
  */
11421
11506
  const secp256k1 = createCurve({
11422
- a: BigInt(0), // equation params: a, b
11507
+ a: BigInt(0),
11423
11508
  b: BigInt(7),
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
11509
+ Fp: Fpk1,
11510
+ n: secp256k1N,
11427
11511
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
11428
11512
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
11429
- h: BigInt(1), // Cofactor
11513
+ h: BigInt(1),
11430
11514
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
11431
11515
  endo: {
11432
11516
  // Endomorphism, see above
@@ -11454,7 +11538,7 @@ const secp256k1 = createCurve({
11454
11538
  return { k1neg, k1, k2neg, k2 };
11455
11539
  },
11456
11540
  },
11457
- }, sha256$1);
11541
+ }, sha256$2);
11458
11542
  // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
11459
11543
  // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
11460
11544
  BigInt(0);
@@ -13091,7 +13175,15 @@ class QuickLRU extends Map {
13091
13175
  }
13092
13176
 
13093
13177
  get [Symbol.toStringTag]() {
13094
- return JSON.stringify([...this.entriesAscending()]);
13178
+ return 'QuickLRU';
13179
+ }
13180
+
13181
+ toString() {
13182
+ return `QuickLRU(${this.size}/${this.maxSize})`;
13183
+ }
13184
+
13185
+ [Symbol.for('nodejs.util.inspect.custom')]() {
13186
+ return this.toString();
13095
13187
  }
13096
13188
  }
13097
13189
 
@@ -14464,7 +14556,7 @@ class ENRTree {
14464
14556
  // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string
14465
14557
  // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)
14466
14558
  const signedComponent = root.split(" sig")[0];
14467
- const signedComponentBuffer = utf8ToBytes$1(signedComponent);
14559
+ const signedComponentBuffer = utf8ToBytes(signedComponent);
14468
14560
  const signatureBuffer = fromString(rootValues.signature, "base64url").slice(0, 64);
14469
14561
  const isVerified = verifySignature(signatureBuffer, keccak256(signedComponentBuffer), new Uint8Array(decodedPublicKey));
14470
14562
  if (!isVerified)
@@ -18491,7 +18583,7 @@ class WakuPeerExchange extends BaseProtocol {
18491
18583
  if (!peer) {
18492
18584
  return {
18493
18585
  peerInfos: null,
18494
- error: ProtocolError.NO_PEER_AVAILABLE
18586
+ error: ProtocolError$1.NO_PEER_AVAILABLE
18495
18587
  };
18496
18588
  }
18497
18589
  let stream;
@@ -18502,7 +18594,7 @@ class WakuPeerExchange extends BaseProtocol {
18502
18594
  log$2.error("Failed to get stream", err);
18503
18595
  return {
18504
18596
  peerInfos: null,
18505
- error: ProtocolError.NO_STREAM_AVAILABLE
18597
+ error: ProtocolError$1.NO_STREAM_AVAILABLE
18506
18598
  };
18507
18599
  }
18508
18600
  const res = await pipe([rpcQuery.encode()], encode, stream, decode, async (source) => await all(source));
@@ -18516,7 +18608,7 @@ class WakuPeerExchange extends BaseProtocol {
18516
18608
  log$2.error("PeerExchangeRPC message did not contains a `response` field");
18517
18609
  return {
18518
18610
  peerInfos: null,
18519
- error: ProtocolError.EMPTY_PAYLOAD
18611
+ error: ProtocolError$1.EMPTY_PAYLOAD
18520
18612
  };
18521
18613
  }
18522
18614
  const peerInfos = await Promise.all(response.peerInfos
@@ -18534,7 +18626,7 @@ class WakuPeerExchange extends BaseProtocol {
18534
18626
  log$2.error("Failed to decode push reply", err);
18535
18627
  return {
18536
18628
  peerInfos: null,
18537
- error: ProtocolError.DECODE_FAILED
18629
+ error: ProtocolError$1.DECODE_FAILED
18538
18630
  };
18539
18631
  }
18540
18632
  }
@@ -18551,7 +18643,7 @@ const log$1 = new Logger$1("peer-exchange-discovery");
18551
18643
  const DEFAULT_PEER_EXCHANGE_REQUEST_NODES = 10;
18552
18644
  const DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS = 10 * 1000;
18553
18645
  const DEFAULT_MAX_RETRIES = 3;
18554
- const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags.PEER_EXCHANGE;
18646
+ const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags$1.PEER_EXCHANGE;
18555
18647
  const DEFAULT_PEER_EXCHANGE_TAG_VALUE = 50;
18556
18648
  const DEFAULT_PEER_EXCHANGE_TAG_TTL = 100_000_000;
18557
18649
  class PeerExchangeDiscovery extends TypedEventEmitter {
@@ -18934,7 +19026,7 @@ function isSha256Multihash(multihash) {
18934
19026
  }
18935
19027
 
18936
19028
  const log = new Logger$1("peer-exchange-discovery");
18937
- const DEFAULT_LOCAL_TAG_NAME = Tags.LOCAL;
19029
+ const DEFAULT_LOCAL_TAG_NAME = Tags$1.LOCAL;
18938
19030
  const DEFAULT_LOCAL_TAG_VALUE = 50;
18939
19031
  const DEFAULT_LOCAL_TAG_TTL = 100_000_000;
18940
19032
  class LocalPeerCacheDiscovery extends TypedEventEmitter {