@waku/enr 0.0.28-5674b0e.0 → 0.0.28-5c50ed7.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
@@ -655,7 +655,7 @@ new TextDecoder();
655
655
 
656
656
  /* eslint-disable */
657
657
  var encode_1 = encode$3;
658
- var MSB$1 = 0x80, REST$1 = 0x7F, MSBALL = ~REST$1, INT = Math.pow(2, 31);
658
+ var MSB$1 = 0x80, MSBALL = -128, INT = Math.pow(2, 31);
659
659
  /**
660
660
  * @param {number} num
661
661
  * @param {number[]} out
@@ -679,7 +679,7 @@ function encode$3(num, out, offset) {
679
679
  return out;
680
680
  }
681
681
  var decode$4 = read$1;
682
- var MSB$1$1 = 0x80, REST$1$1 = 0x7F;
682
+ var MSB$1$1 = 0x80, REST$1 = 0x7F;
683
683
  /**
684
684
  * @param {string | any[]} buf
685
685
  * @param {number} offset
@@ -694,8 +694,8 @@ function read$1(buf, offset) {
694
694
  }
695
695
  b = buf[counter++];
696
696
  res += shift < 28
697
- ? (b & REST$1$1) << shift
698
- : (b & REST$1$1) * Math.pow(2, shift);
697
+ ? (b & REST$1) << shift
698
+ : (b & REST$1) * Math.pow(2, shift);
699
699
  shift += 7;
700
700
  } while (b >= MSB$1$1);
701
701
  // @ts-ignore
@@ -1586,10 +1586,10 @@ class JacobianPoint {
1586
1586
  const cond1 = window % 2 !== 0;
1587
1587
  const cond2 = wbits < 0;
1588
1588
  if (wbits === 0) {
1589
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1589
+ f = f.add(constTimeNegate$1(cond1, precomputes[offset1]));
1590
1590
  }
1591
1591
  else {
1592
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1592
+ p = p.add(constTimeNegate$1(cond2, precomputes[offset2]));
1593
1593
  }
1594
1594
  }
1595
1595
  return { p, f };
@@ -1602,8 +1602,8 @@ class JacobianPoint {
1602
1602
  const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1603
1603
  let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
1604
1604
  let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
1605
- k1p = constTimeNegate(k1neg, k1p);
1606
- k2p = constTimeNegate(k2neg, k2p);
1605
+ k1p = constTimeNegate$1(k1neg, k1p);
1606
+ k2p = constTimeNegate$1(k2neg, k2p);
1607
1607
  k2p = new JacobianPoint(mod$1(k2p.x * endo.beta), k2p.y, k2p.z);
1608
1608
  point = k1p.add(k2p);
1609
1609
  fake = f1p.add(f2p);
@@ -1635,7 +1635,7 @@ class JacobianPoint {
1635
1635
  }
1636
1636
  JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n$7);
1637
1637
  JacobianPoint.ZERO = new JacobianPoint(_0n$5, _1n$7, _0n$5);
1638
- function constTimeNegate(condition, item) {
1638
+ function constTimeNegate$1(condition, item) {
1639
1639
  const neg = item.negate();
1640
1640
  return condition ? neg : item;
1641
1641
  }
@@ -3092,43 +3092,55 @@ function verifySignature(signature, message, publicKey) {
3092
3092
  }
3093
3093
  }
3094
3094
 
3095
- function number(n) {
3095
+ /**
3096
+ * Internal assertion helpers.
3097
+ * @module
3098
+ */
3099
+ /** Asserts something is positive integer. */
3100
+ function anumber(n) {
3096
3101
  if (!Number.isSafeInteger(n) || n < 0)
3097
- throw new Error(`positive integer expected, not ${n}`);
3102
+ throw new Error('positive integer expected, got ' + n);
3098
3103
  }
3099
- // copied from utils
3104
+ /** Is number an Uint8Array? Copied from utils for perf. */
3100
3105
  function isBytes$2(a) {
3101
- return (a instanceof Uint8Array ||
3102
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
3106
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3103
3107
  }
3104
- function bytes(b, ...lengths) {
3108
+ /** Asserts something is Uint8Array. */
3109
+ function abytes$1(b, ...lengths) {
3105
3110
  if (!isBytes$2(b))
3106
3111
  throw new Error('Uint8Array expected');
3107
3112
  if (lengths.length > 0 && !lengths.includes(b.length))
3108
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
3113
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3109
3114
  }
3110
- function hash(h) {
3115
+ /** Asserts something is hash */
3116
+ function ahash(h) {
3111
3117
  if (typeof h !== 'function' || typeof h.create !== 'function')
3112
3118
  throw new Error('Hash should be wrapped by utils.wrapConstructor');
3113
- number(h.outputLen);
3114
- number(h.blockLen);
3119
+ anumber(h.outputLen);
3120
+ anumber(h.blockLen);
3115
3121
  }
3116
- function exists(instance, checkFinished = true) {
3122
+ /** Asserts a hash instance has not been destroyed / finished */
3123
+ function aexists(instance, checkFinished = true) {
3117
3124
  if (instance.destroyed)
3118
3125
  throw new Error('Hash instance has been destroyed');
3119
3126
  if (checkFinished && instance.finished)
3120
3127
  throw new Error('Hash#digest() has already been called');
3121
3128
  }
3122
- function output(out, instance) {
3123
- bytes(out);
3129
+ /** Asserts output is properly-sized byte array */
3130
+ function aoutput(out, instance) {
3131
+ abytes$1(out);
3124
3132
  const min = instance.outputLen;
3125
3133
  if (out.length < min) {
3126
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
3134
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
3127
3135
  }
3128
3136
  }
3129
3137
 
3130
3138
  const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
3131
3139
 
3140
+ /**
3141
+ * Utilities for hex, bytes, CSPRNG.
3142
+ * @module
3143
+ */
3132
3144
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3133
3145
  // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
3134
3146
  // node.js versions earlier than v19 don't declare it in global scope.
@@ -3137,16 +3149,20 @@ const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? glob
3137
3149
  // Makes the utils un-importable in browsers without a bundler.
3138
3150
  // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
3139
3151
  // Cast array to view
3140
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3141
- // The rotate right (circular right shift) operation for uint32
3142
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
3143
- new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3152
+ function createView(arr) {
3153
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3154
+ }
3155
+ /** The rotate right (circular right shift) operation for uint32 */
3156
+ function rotr(word, shift) {
3157
+ return (word << (32 - shift)) | (word >>> shift);
3158
+ }
3144
3159
  /**
3160
+ * Convert JS string to byte array.
3145
3161
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
3146
3162
  */
3147
3163
  function utf8ToBytes$1(str) {
3148
3164
  if (typeof str !== 'string')
3149
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
3165
+ throw new Error('utf8ToBytes expected string, got ' + typeof str);
3150
3166
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
3151
3167
  }
3152
3168
  /**
@@ -3157,7 +3173,7 @@ function utf8ToBytes$1(str) {
3157
3173
  function toBytes$1(data) {
3158
3174
  if (typeof data === 'string')
3159
3175
  data = utf8ToBytes$1(data);
3160
- bytes(data);
3176
+ abytes$1(data);
3161
3177
  return data;
3162
3178
  }
3163
3179
  /**
@@ -3167,7 +3183,7 @@ function concatBytes$1(...arrays) {
3167
3183
  let sum = 0;
3168
3184
  for (let i = 0; i < arrays.length; i++) {
3169
3185
  const a = arrays[i];
3170
- bytes(a);
3186
+ abytes$1(a);
3171
3187
  sum += a.length;
3172
3188
  }
3173
3189
  const res = new Uint8Array(sum);
@@ -3178,13 +3194,14 @@ function concatBytes$1(...arrays) {
3178
3194
  }
3179
3195
  return res;
3180
3196
  }
3181
- // For runtime check if class implements interface
3197
+ /** For runtime check if class implements interface */
3182
3198
  class Hash {
3183
3199
  // Safe version that clones internal state
3184
3200
  clone() {
3185
3201
  return this._cloneInto();
3186
3202
  }
3187
3203
  }
3204
+ /** Wraps hash function, creating an interface on top of it */
3188
3205
  function wrapConstructor(hashCons) {
3189
3206
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
3190
3207
  const tmp = hashCons();
@@ -3193,9 +3210,7 @@ function wrapConstructor(hashCons) {
3193
3210
  hashC.create = () => hashCons();
3194
3211
  return hashC;
3195
3212
  }
3196
- /**
3197
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
3198
- */
3213
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
3199
3214
  function randomBytes(bytesLength = 32) {
3200
3215
  if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
3201
3216
  return crypto$1.getRandomValues(new Uint8Array(bytesLength));
@@ -3208,8 +3223,10 @@ function randomBytes(bytesLength = 32) {
3208
3223
  }
3209
3224
 
3210
3225
  /**
3211
- * Polyfill for Safari 14
3226
+ * Internal Merkle-Damgard hash utils.
3227
+ * @module
3212
3228
  */
3229
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
3213
3230
  function setBigUint64(view, byteOffset, value, isLE) {
3214
3231
  if (typeof view.setBigUint64 === 'function')
3215
3232
  return view.setBigUint64(byteOffset, value, isLE);
@@ -3222,14 +3239,14 @@ function setBigUint64(view, byteOffset, value, isLE) {
3222
3239
  view.setUint32(byteOffset + h, wh, isLE);
3223
3240
  view.setUint32(byteOffset + l, wl, isLE);
3224
3241
  }
3225
- /**
3226
- * Choice: a ? b : c
3227
- */
3228
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
3229
- /**
3230
- * Majority function, true if any two inputs is true
3231
- */
3232
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
3242
+ /** Choice: a ? b : c */
3243
+ function Chi(a, b, c) {
3244
+ return (a & b) ^ (~a & c);
3245
+ }
3246
+ /** Majority function, true if any two inputs is true. */
3247
+ function Maj(a, b, c) {
3248
+ return (a & b) ^ (a & c) ^ (b & c);
3249
+ }
3233
3250
  /**
3234
3251
  * Merkle-Damgard hash construction base class.
3235
3252
  * Could be used to create MD5, RIPEMD, SHA1, SHA2.
@@ -3249,7 +3266,7 @@ class HashMD extends Hash {
3249
3266
  this.view = createView(this.buffer);
3250
3267
  }
3251
3268
  update(data) {
3252
- exists(this);
3269
+ aexists(this);
3253
3270
  const { view, buffer, blockLen } = this;
3254
3271
  data = toBytes$1(data);
3255
3272
  const len = data.length;
@@ -3275,8 +3292,8 @@ class HashMD extends Hash {
3275
3292
  return this;
3276
3293
  }
3277
3294
  digestInto(out) {
3278
- exists(this);
3279
- output(out, this);
3295
+ aexists(this);
3296
+ aoutput(out, this);
3280
3297
  this.finished = true;
3281
3298
  // Padding
3282
3299
  // We can avoid allocation of buffer for padding completely if it
@@ -3333,10 +3350,16 @@ class HashMD extends Hash {
3333
3350
  }
3334
3351
  }
3335
3352
 
3336
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
3337
- // BTC network is doing 2^67 hashes/sec as per early 2023.
3338
- // Round constants:
3339
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
3353
+ /**
3354
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
3355
+ *
3356
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
3357
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3358
+ *
3359
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
3360
+ * @module
3361
+ */
3362
+ /** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */
3340
3363
  // prettier-ignore
3341
3364
  const SHA256_K = /* @__PURE__ */ new Uint32Array([
3342
3365
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
@@ -3348,14 +3371,15 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
3348
3371
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3349
3372
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3350
3373
  ]);
3351
- // Initial state:
3352
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
3374
+ /** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */
3353
3375
  // prettier-ignore
3354
3376
  const SHA256_IV = /* @__PURE__ */ new Uint32Array([
3355
3377
  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
3356
3378
  ]);
3357
- // Temporary buffer, not used to store anything between runs
3358
- // Named this way because it matches specification.
3379
+ /**
3380
+ * Temporary buffer, not used to store anything between runs.
3381
+ * Named this way because it matches specification.
3382
+ */
3359
3383
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3360
3384
  class SHA256 extends HashMD {
3361
3385
  constructor() {
@@ -3432,10 +3456,7 @@ class SHA256 extends HashMD {
3432
3456
  this.buffer.fill(0);
3433
3457
  }
3434
3458
  }
3435
- /**
3436
- * SHA2-256 hash function
3437
- * @param message - data that would be hashed
3438
- */
3459
+ /** SHA2-256 hash function */
3439
3460
  const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
3440
3461
 
3441
3462
  var Protocols;
@@ -3447,43 +3468,24 @@ var Protocols;
3447
3468
  })(Protocols || (Protocols = {}));
3448
3469
  var ProtocolError;
3449
3470
  (function (ProtocolError) {
3450
- /** Could not determine the origin of the fault. Best to check connectivity and try again */
3471
+ //
3472
+ // GENERAL ERRORS SECTION
3473
+ //
3474
+ /**
3475
+ * Could not determine the origin of the fault. Best to check connectivity and try again
3476
+ * */
3451
3477
  ProtocolError["GENERIC_FAIL"] = "Generic error";
3452
3478
  /**
3453
- * Failure to protobuf encode the message. This is not recoverable and needs
3454
- * further investigation.
3479
+ * The remote peer rejected the message. Information provided by the remote peer
3480
+ * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
3481
+ * or `DECODE_FAILED` can be used.
3455
3482
  */
3456
- ProtocolError["ENCODE_FAILED"] = "Failed to encode";
3483
+ ProtocolError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
3457
3484
  /**
3458
3485
  * Failure to protobuf decode the message. May be due to a remote peer issue,
3459
3486
  * ensuring that messages are sent via several peer enable mitigation of this error.
3460
3487
  */
3461
3488
  ProtocolError["DECODE_FAILED"] = "Failed to decode";
3462
- /**
3463
- * The message payload is empty, making the message invalid. Ensure that a non-empty
3464
- * payload is set on the outgoing message.
3465
- */
3466
- ProtocolError["EMPTY_PAYLOAD"] = "Payload is empty";
3467
- /**
3468
- * The message size is above the maximum message size allowed on the Waku Network.
3469
- * Compressing the message or using an alternative strategy for large messages is recommended.
3470
- */
3471
- ProtocolError["SIZE_TOO_BIG"] = "Size is too big";
3472
- /**
3473
- * The PubsubTopic passed to the send function is not configured on the Waku node.
3474
- * Please ensure that the PubsubTopic is used when initializing the Waku node.
3475
- */
3476
- ProtocolError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
3477
- /**
3478
- * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.
3479
- * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
3480
- */
3481
- ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
3482
- /**
3483
- * The topics passed in the decoders do not match each other, or don't exist at all.
3484
- * Ensure that all the pubsub topics used in the decoders are valid and match each other.
3485
- */
3486
- ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
3487
3489
  /**
3488
3490
  * Failure to find a peer with suitable protocols. This may due to a connection issue.
3489
3491
  * Mitigation can be: retrying after a given time period, display connectivity issue
@@ -3501,37 +3503,51 @@ var ProtocolError;
3501
3503
  * or `DECODE_FAILED` can be used.
3502
3504
  */
3503
3505
  ProtocolError["NO_RESPONSE"] = "No response received";
3506
+ //
3507
+ // SEND ERRORS SECTION
3508
+ //
3504
3509
  /**
3505
- * The remote peer rejected the message. Information provided by the remote peer
3506
- * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
3507
- * or `DECODE_FAILED` can be used.
3510
+ * Failure to protobuf encode the message. This is not recoverable and needs
3511
+ * further investigation.
3508
3512
  */
3509
- ProtocolError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
3513
+ ProtocolError["ENCODE_FAILED"] = "Failed to encode";
3510
3514
  /**
3511
- * The protocol request timed out without a response. This may be due to a connection issue.
3512
- * Mitigation can be: retrying after a given time period
3515
+ * The message payload is empty, making the message invalid. Ensure that a non-empty
3516
+ * payload is set on the outgoing message.
3513
3517
  */
3514
- ProtocolError["REQUEST_TIMEOUT"] = "Request timeout";
3518
+ ProtocolError["EMPTY_PAYLOAD"] = "Payload is empty";
3515
3519
  /**
3516
- * Missing credentials info message.
3517
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L186
3520
+ * The message size is above the maximum message size allowed on the Waku Network.
3521
+ * Compressing the message or using an alternative strategy for large messages is recommended.
3518
3522
  */
3519
- ProtocolError["RLN_IDENTITY_MISSING"] = "Identity credentials are not set";
3523
+ ProtocolError["SIZE_TOO_BIG"] = "Size is too big";
3520
3524
  /**
3521
- * Membership index missing info message.
3522
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L188
3525
+ * The PubsubTopic passed to the send function is not configured on the Waku node.
3526
+ * Please ensure that the PubsubTopic is used when initializing the Waku node.
3523
3527
  */
3524
- ProtocolError["RLN_MEMBERSHIP_INDEX"] = "Membership index is not set";
3528
+ ProtocolError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
3525
3529
  /**
3526
- * Message limit is missing.
3527
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L190
3530
+ * Fails when
3528
3531
  */
3529
- ProtocolError["RLN_LIMIT_MISSING"] = "User message limit is not set";
3532
+ ProtocolError["STREAM_ABORTED"] = "Stream aborted";
3530
3533
  /**
3531
3534
  * General proof generation error message.
3532
3535
  * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42
3533
3536
  */
3534
3537
  ProtocolError["RLN_PROOF_GENERATION"] = "Proof generation failed";
3538
+ //
3539
+ // RECEIVE ERRORS SECTION
3540
+ //
3541
+ /**
3542
+ * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.
3543
+ * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
3544
+ */
3545
+ ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
3546
+ /**
3547
+ * The topics passed in the decoders do not match each other, or don't exist at all.
3548
+ * Ensure that all the pubsub topics used in the decoders are valid and match each other.
3549
+ */
3550
+ ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
3535
3551
  })(ProtocolError || (ProtocolError = {}));
3536
3552
 
3537
3553
  var Tags;
@@ -3552,6 +3568,10 @@ var EConnectionStateEvents;
3552
3568
  EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
3553
3569
  })(EConnectionStateEvents || (EConnectionStateEvents = {}));
3554
3570
 
3571
+ var HealthStatusChangeEvents;
3572
+ (function (HealthStatusChangeEvents) {
3573
+ HealthStatusChangeEvents["StatusChange"] = "health:change";
3574
+ })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
3555
3575
  var HealthStatus;
3556
3576
  (function (HealthStatus) {
3557
3577
  HealthStatus["Unhealthy"] = "Unhealthy";
@@ -3930,24 +3950,62 @@ function setup(env) {
3930
3950
  createDebug.names = [];
3931
3951
  createDebug.skips = [];
3932
3952
 
3933
- let i;
3934
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
3935
- const len = split.length;
3953
+ const split = (typeof namespaces === 'string' ? namespaces : '')
3954
+ .trim()
3955
+ .replace(' ', ',')
3956
+ .split(',')
3957
+ .filter(Boolean);
3936
3958
 
3937
- for (i = 0; i < len; i++) {
3938
- if (!split[i]) {
3939
- // ignore empty strings
3940
- continue;
3959
+ for (const ns of split) {
3960
+ if (ns[0] === '-') {
3961
+ createDebug.skips.push(ns.slice(1));
3962
+ } else {
3963
+ createDebug.names.push(ns);
3941
3964
  }
3965
+ }
3966
+ }
3942
3967
 
3943
- namespaces = split[i].replace(/\*/g, '.*?');
3944
-
3945
- if (namespaces[0] === '-') {
3946
- createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
3968
+ /**
3969
+ * Checks if the given string matches a namespace template, honoring
3970
+ * asterisks as wildcards.
3971
+ *
3972
+ * @param {String} search
3973
+ * @param {String} template
3974
+ * @return {Boolean}
3975
+ */
3976
+ function matchesTemplate(search, template) {
3977
+ let searchIndex = 0;
3978
+ let templateIndex = 0;
3979
+ let starIndex = -1;
3980
+ let matchIndex = 0;
3981
+
3982
+ while (searchIndex < search.length) {
3983
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
3984
+ // Match character or proceed with wildcard
3985
+ if (template[templateIndex] === '*') {
3986
+ starIndex = templateIndex;
3987
+ matchIndex = searchIndex;
3988
+ templateIndex++; // Skip the '*'
3989
+ } else {
3990
+ searchIndex++;
3991
+ templateIndex++;
3992
+ }
3993
+ } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
3994
+ // Backtrack to the last '*' and try to match more characters
3995
+ templateIndex = starIndex + 1;
3996
+ matchIndex++;
3997
+ searchIndex = matchIndex;
3947
3998
  } else {
3948
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
3999
+ return false; // No match
3949
4000
  }
3950
4001
  }
4002
+
4003
+ // Handle trailing '*' in template
4004
+ while (templateIndex < template.length && template[templateIndex] === '*') {
4005
+ templateIndex++;
4006
+ }
4007
+
4008
+ return templateIndex === template.length;
3951
4009
  }
3952
4010
 
3953
4011
  /**
@@ -3958,8 +4016,8 @@ function setup(env) {
3958
4016
  */
3959
4017
  function disable() {
3960
4018
  const namespaces = [
3961
- ...createDebug.names.map(toNamespace),
3962
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
4019
+ ...createDebug.names,
4020
+ ...createDebug.skips.map(namespace => '-' + namespace)
3963
4021
  ].join(',');
3964
4022
  createDebug.enable('');
3965
4023
  return namespaces;
@@ -3973,21 +4031,14 @@ function setup(env) {
3973
4031
  * @api public
3974
4032
  */
3975
4033
  function enabled(name) {
3976
- if (name[name.length - 1] === '*') {
3977
- return true;
3978
- }
3979
-
3980
- let i;
3981
- let len;
3982
-
3983
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
3984
- if (createDebug.skips[i].test(name)) {
4034
+ for (const skip of createDebug.skips) {
4035
+ if (matchesTemplate(name, skip)) {
3985
4036
  return false;
3986
4037
  }
3987
4038
  }
3988
4039
 
3989
- for (i = 0, len = createDebug.names.length; i < len; i++) {
3990
- if (createDebug.names[i].test(name)) {
4040
+ for (const ns of createDebug.names) {
4041
+ if (matchesTemplate(name, ns)) {
3991
4042
  return true;
3992
4043
  }
3993
4044
  }
@@ -3995,19 +4046,6 @@ function setup(env) {
3995
4046
  return false;
3996
4047
  }
3997
4048
 
3998
- /**
3999
- * Convert regexp to namespace
4000
- *
4001
- * @param {RegExp} regxep
4002
- * @return {String} namespace
4003
- * @api private
4004
- */
4005
- function toNamespace(regexp) {
4006
- return regexp.toString()
4007
- .substring(2, regexp.toString().length - 2)
4008
- .replace(/\.\*\?$/, '*');
4009
- }
4010
-
4011
4049
  /**
4012
4050
  * Coerce `val`.
4013
4051
  *
@@ -4169,6 +4207,7 @@ var common = setup;
4169
4207
 
4170
4208
  // Is webkit? http://stackoverflow.com/a/16459606/376773
4171
4209
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
4210
+ // eslint-disable-next-line no-return-assign
4172
4211
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
4173
4212
  // Is firebug? http://stackoverflow.com/a/398120/376773
4174
4213
  (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
@@ -4833,7 +4872,7 @@ function parseIPv6(input) {
4833
4872
  return parser.new(input).parseWith(() => parser.readIPv6Addr());
4834
4873
  }
4835
4874
  /** Parse `input` into IPv4 or IPv6 bytes. */
4836
- function parseIP(input) {
4875
+ function parseIP(input, mapIPv4ToIPv6 = false) {
4837
4876
  // strip zone index if it is present
4838
4877
  if (input.includes("%")) {
4839
4878
  input = input.split("%")[0];
@@ -4841,7 +4880,14 @@ function parseIP(input) {
4841
4880
  if (input.length > MAX_IPV6_LENGTH) {
4842
4881
  return undefined;
4843
4882
  }
4844
- return parser.new(input).parseWith(() => parser.readIPAddr());
4883
+ const addr = parser.new(input).parseWith(() => parser.readIPAddr());
4884
+ if (!addr) {
4885
+ return undefined;
4886
+ }
4887
+ if (mapIPv4ToIPv6 && addr.length === 4) {
4888
+ return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);
4889
+ }
4890
+ return addr;
4845
4891
  }
4846
4892
 
4847
4893
  /** Check if `input` is IPv4. */
@@ -5029,17 +5075,13 @@ function getProtocol(proto) {
5029
5075
  throw new Error(`invalid protocol id type: ${typeof proto}`);
5030
5076
  }
5031
5077
 
5032
- /**
5033
- * @packageDocumentation
5034
- *
5035
- * Provides methods for converting
5036
- */
5037
5078
  getProtocol('ip4');
5038
5079
  getProtocol('ip6');
5039
5080
  getProtocol('ipcidr');
5040
5081
  /**
5041
5082
  * Convert [code,Uint8Array] to string
5042
5083
  */
5084
+ // eslint-disable-next-line complexity
5043
5085
  function convertToString(proto, buf) {
5044
5086
  const protocol = getProtocol(proto);
5045
5087
  switch (protocol.code) {
@@ -5048,6 +5090,8 @@ function convertToString(proto, buf) {
5048
5090
  return bytes2ip(buf);
5049
5091
  case 42: // ipv6zone
5050
5092
  return bytes2str(buf);
5093
+ case 43: // ipcidr
5094
+ return toString$1(buf, 'base10');
5051
5095
  case 6: // tcp
5052
5096
  case 273: // udp
5053
5097
  case 33: // dccp
@@ -5075,6 +5119,7 @@ function convertToString(proto, buf) {
5075
5119
  return toString$1(buf, 'base16'); // no clue. convert to hex
5076
5120
  }
5077
5121
  }
5122
+ // eslint-disable-next-line complexity
5078
5123
  function convertToBytes(proto, str) {
5079
5124
  const protocol = getProtocol(proto);
5080
5125
  switch (protocol.code) {
@@ -5084,6 +5129,8 @@ function convertToBytes(proto, str) {
5084
5129
  return ip2bytes(str);
5085
5130
  case 42: // ipv6zone
5086
5131
  return str2bytes(str);
5132
+ case 43: // ipcidr
5133
+ return fromString(str, 'base10');
5087
5134
  case 6: // tcp
5088
5135
  case 273: // udp
5089
5136
  case 33: // dccp
@@ -5378,19 +5425,6 @@ function ParseError(str) {
5378
5425
  return new Error('Error parsing address: ' + str);
5379
5426
  }
5380
5427
 
5381
- /**
5382
- * @packageDocumentation
5383
- *
5384
- * An implementation of a Multiaddr in JavaScript
5385
- *
5386
- * @example
5387
- *
5388
- * ```js
5389
- * import { multiaddr } from '@multiformats/multiaddr'
5390
- *
5391
- * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')
5392
- * ```
5393
- */
5394
5428
  const inspect$1 = Symbol.for('nodejs.util.inspect.custom');
5395
5429
  const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');
5396
5430
  const DNS_CODES = [
@@ -5502,10 +5536,20 @@ class Multiaddr {
5502
5536
  return this.#tuples.map(([code]) => getProtocol(code).name);
5503
5537
  }
5504
5538
  tuples() {
5505
- return this.#tuples;
5539
+ return this.#tuples.map(([code, value]) => {
5540
+ if (value == null) {
5541
+ return [code];
5542
+ }
5543
+ return [code, value];
5544
+ });
5506
5545
  }
5507
5546
  stringTuples() {
5508
- return this.#stringTuples;
5547
+ return this.#stringTuples.map(([code, value]) => {
5548
+ if (value == null) {
5549
+ return [code];
5550
+ }
5551
+ return [code, value];
5552
+ });
5509
5553
  }
5510
5554
  encapsulate(addr) {
5511
5555
  addr = new Multiaddr(addr);
@@ -5635,10 +5679,8 @@ class Multiaddr {
5635
5679
  *
5636
5680
  * ```TypeScript
5637
5681
  * import { multiaddr } from '@multiformats/multiaddr'
5638
- * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5639
- * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5640
5682
  *
5641
- * const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
5683
+ * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')
5642
5684
  * // Multiaddr(/ip4/127.0.0.1/udp/1234)
5643
5685
  *
5644
5686
  * addr.bytes
@@ -5677,9 +5719,9 @@ class Multiaddr {
5677
5719
  *
5678
5720
  * ```TypeScript
5679
5721
  * import { multiaddr, resolvers } from '@multiformats/multiaddr'
5680
- * import { dnsaddr } from '@multiformats/multiaddr/resolvers'
5722
+ * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
5681
5723
  *
5682
- * resolvers.set('dnsaddr', dnsaddr)
5724
+ * resolvers.set('dnsaddr', dnsaddrResolver)
5683
5725
  *
5684
5726
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
5685
5727
  *
@@ -5688,7 +5730,7 @@ class Multiaddr {
5688
5730
  * signal: AbortSignal.timeout(5000)
5689
5731
  * })
5690
5732
  *
5691
- * console.info(await ma.resolve(resolved)
5733
+ * console.info(resolved)
5692
5734
  * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]
5693
5735
  * ```
5694
5736
  *
@@ -5702,7 +5744,9 @@ class Multiaddr {
5702
5744
  * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'
5703
5745
  *
5704
5746
  * const resolver = dns({
5705
- * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5747
+ * resolvers: {
5748
+ * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
5749
+ * }
5706
5750
  * })
5707
5751
  *
5708
5752
  * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
@@ -5788,6 +5832,12 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
5788
5832
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
5789
5833
  }
5790
5834
 
5835
+ /**
5836
+ * All PeerId implementations must use this symbol as the name of a property
5837
+ * with a boolean `true` value
5838
+ */
5839
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
5840
+
5791
5841
  /**
5792
5842
  * When this error is thrown it means an operation was aborted,
5793
5843
  * usually in response to the `abort` event being emitted by an
@@ -5813,10 +5863,24 @@ class InvalidPublicKeyError extends Error {
5813
5863
  this.name = 'InvalidPublicKeyError';
5814
5864
  }
5815
5865
  }
5866
+ /**
5867
+ * Thrown when and attempt to operate on an unsupported key was made
5868
+ */
5869
+ class UnsupportedKeyTypeError extends Error {
5870
+ static name = 'UnsupportedKeyTypeError';
5871
+ constructor(message = 'Unsupported key type') {
5872
+ super(message);
5873
+ this.name = 'UnsupportedKeyTypeError';
5874
+ }
5875
+ }
5816
5876
 
5877
+ /**
5878
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
5879
+ * @todo re-check https://issues.chromium.org/issues/42212588
5880
+ * @module
5881
+ */
5817
5882
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
5818
5883
  const _32n = /* @__PURE__ */ BigInt(32);
5819
- // We are not using BigUint64Array, because they are extremely slow as per 2022
5820
5884
  function fromBig(n, le = false) {
5821
5885
  if (le)
5822
5886
  return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
@@ -5873,6 +5937,13 @@ const u64 = {
5873
5937
  add, add3L, add3H, add4L, add4H, add5H, add5L,
5874
5938
  };
5875
5939
 
5940
+ /**
5941
+ * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
5942
+ *
5943
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
5944
+ * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
5945
+ * @module
5946
+ */
5876
5947
  // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
5877
5948
  // prettier-ignore
5878
5949
  const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
@@ -6027,8 +6098,13 @@ class SHA512 extends HashMD {
6027
6098
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
6028
6099
  }
6029
6100
  }
6101
+ /** SHA2-512 hash function. */
6030
6102
  const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
6031
6103
 
6104
+ /**
6105
+ * Hex, bytes and number utilities.
6106
+ * @module
6107
+ */
6032
6108
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6033
6109
  // 100 lines of code in the file are duplicated from noble-hashes (utils).
6034
6110
  // This is OK: `abstract` directory does not use noble-hashes.
@@ -6038,8 +6114,7 @@ const _0n$4 = /* @__PURE__ */ BigInt(0);
6038
6114
  const _1n$6 = /* @__PURE__ */ BigInt(1);
6039
6115
  const _2n$4 = /* @__PURE__ */ BigInt(2);
6040
6116
  function isBytes$1(a) {
6041
- return (a instanceof Uint8Array ||
6042
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
6117
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
6043
6118
  }
6044
6119
  function abytes(item) {
6045
6120
  if (!isBytes$1(item))
@@ -6047,7 +6122,7 @@ function abytes(item) {
6047
6122
  }
6048
6123
  function abool(title, value) {
6049
6124
  if (typeof value !== 'boolean')
6050
- throw new Error(`${title} must be valid boolean, got "${value}".`);
6125
+ throw new Error(title + ' boolean expected, got ' + value);
6051
6126
  }
6052
6127
  // Array where index 0xf0 (240) is mapped to string 'f0'
6053
6128
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
@@ -6065,23 +6140,22 @@ function bytesToHex(bytes) {
6065
6140
  }
6066
6141
  function numberToHexUnpadded(num) {
6067
6142
  const hex = num.toString(16);
6068
- return hex.length & 1 ? `0${hex}` : hex;
6143
+ return hex.length & 1 ? '0' + hex : hex;
6069
6144
  }
6070
6145
  function hexToNumber(hex) {
6071
6146
  if (typeof hex !== 'string')
6072
6147
  throw new Error('hex string expected, got ' + typeof hex);
6073
- // Big Endian
6074
- return BigInt(hex === '' ? '0' : `0x${hex}`);
6148
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
6075
6149
  }
6076
6150
  // We use optimized technique to convert hex string to byte array
6077
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
6078
- function asciiToBase16(char) {
6079
- if (char >= asciis._0 && char <= asciis._9)
6080
- return char - asciis._0;
6081
- if (char >= asciis._A && char <= asciis._F)
6082
- return char - (asciis._A - 10);
6083
- if (char >= asciis._a && char <= asciis._f)
6084
- return char - (asciis._a - 10);
6151
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
6152
+ function asciiToBase16(ch) {
6153
+ if (ch >= asciis._0 && ch <= asciis._9)
6154
+ return ch - asciis._0; // '2' => 50-48
6155
+ if (ch >= asciis.A && ch <= asciis.F)
6156
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
6157
+ if (ch >= asciis.a && ch <= asciis.f)
6158
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
6085
6159
  return;
6086
6160
  }
6087
6161
  /**
@@ -6093,7 +6167,7 @@ function hexToBytes(hex) {
6093
6167
  const hl = hex.length;
6094
6168
  const al = hl / 2;
6095
6169
  if (hl % 2)
6096
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
6170
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
6097
6171
  const array = new Uint8Array(al);
6098
6172
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
6099
6173
  const n1 = asciiToBase16(hex.charCodeAt(hi));
@@ -6102,7 +6176,7 @@ function hexToBytes(hex) {
6102
6176
  const char = hex[hi] + hex[hi + 1];
6103
6177
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
6104
6178
  }
6105
- array[ai] = n1 * 16 + n2;
6179
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
6106
6180
  }
6107
6181
  return array;
6108
6182
  }
@@ -6140,7 +6214,7 @@ function ensureBytes(title, hex, expectedLength) {
6140
6214
  res = hexToBytes(hex);
6141
6215
  }
6142
6216
  catch (e) {
6143
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
6217
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
6144
6218
  }
6145
6219
  }
6146
6220
  else if (isBytes$1(hex)) {
@@ -6149,11 +6223,11 @@ function ensureBytes(title, hex, expectedLength) {
6149
6223
  res = Uint8Array.from(hex);
6150
6224
  }
6151
6225
  else {
6152
- throw new Error(`${title} must be hex string or Uint8Array`);
6226
+ throw new Error(title + ' must be hex string or Uint8Array');
6153
6227
  }
6154
6228
  const len = res.length;
6155
6229
  if (typeof expectedLength === 'number' && len !== expectedLength)
6156
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
6230
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
6157
6231
  return res;
6158
6232
  }
6159
6233
  /**
@@ -6188,7 +6262,7 @@ function equalBytes(a, b) {
6188
6262
  */
6189
6263
  function utf8ToBytes(str) {
6190
6264
  if (typeof str !== 'string')
6191
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6265
+ throw new Error('string expected');
6192
6266
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6193
6267
  }
6194
6268
  // Is positive bigint
@@ -6208,7 +6282,7 @@ function aInRange(title, n, min, max) {
6208
6282
  // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
6209
6283
  // - our way is the cleanest: `inRange('x', x, 0n, P)
6210
6284
  if (!inRange(n, min, max))
6211
- throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
6285
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
6212
6286
  }
6213
6287
  // Bit operations
6214
6288
  /**
@@ -6318,12 +6392,12 @@ function validateObject(object, validators, optValidators = {}) {
6318
6392
  const checkField = (fieldName, type, isOptional) => {
6319
6393
  const checkVal = validatorFns[type];
6320
6394
  if (typeof checkVal !== 'function')
6321
- throw new Error(`Invalid validator "${type}", expected function`);
6395
+ throw new Error('invalid validator function');
6322
6396
  const val = object[fieldName];
6323
6397
  if (isOptional && val === undefined)
6324
6398
  return;
6325
6399
  if (!checkVal(val, object)) {
6326
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
6400
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
6327
6401
  }
6328
6402
  };
6329
6403
  for (const [fieldName, type] of Object.entries(validators))
@@ -6392,14 +6466,17 @@ var ut = /*#__PURE__*/Object.freeze({
6392
6466
  validateObject: validateObject
6393
6467
  });
6394
6468
 
6469
+ /**
6470
+ * Utils for modular division and finite fields.
6471
+ * A finite field over 11 is integer number operations `mod 11`.
6472
+ * There is no division: it is replaced by modular multiplicative inverse.
6473
+ * @module
6474
+ */
6395
6475
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6396
- // Utilities for modular arithmetics and finite fields
6397
6476
  // prettier-ignore
6398
- const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = BigInt(2), _3n$1 = BigInt(3);
6477
+ const _0n$3 = BigInt(0), _1n$5 = BigInt(1), _2n$3 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
6399
6478
  // prettier-ignore
6400
- const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$2 = BigInt(8);
6401
- // prettier-ignore
6402
- BigInt(9); BigInt(16);
6479
+ const _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _8n$2 = /* @__PURE__ */ BigInt(8);
6403
6480
  // Calculates a modulo b
6404
6481
  function mod(a, b) {
6405
6482
  const result = a % b;
@@ -6408,13 +6485,15 @@ function mod(a, b) {
6408
6485
  /**
6409
6486
  * Efficiently raise num to power and do modular division.
6410
6487
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
6488
+ * @todo use field version && remove
6411
6489
  * @example
6412
6490
  * pow(2n, 6n, 11n) // 64n % 11n == 9n
6413
6491
  */
6414
- // TODO: use field version && remove
6415
6492
  function pow(num, power, modulo) {
6416
- if (modulo <= _0n$3 || power < _0n$3)
6417
- throw new Error('Expected power/modulo > 0');
6493
+ if (power < _0n$3)
6494
+ throw new Error('invalid exponent, negatives unsupported');
6495
+ if (modulo <= _0n$3)
6496
+ throw new Error('invalid modulus');
6418
6497
  if (modulo === _1n$5)
6419
6498
  return _0n$3;
6420
6499
  let res = _1n$5;
@@ -6426,7 +6505,7 @@ function pow(num, power, modulo) {
6426
6505
  }
6427
6506
  return res;
6428
6507
  }
6429
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
6508
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
6430
6509
  function pow2(x, power, modulo) {
6431
6510
  let res = x;
6432
6511
  while (power-- > _0n$3) {
@@ -6435,12 +6514,15 @@ function pow2(x, power, modulo) {
6435
6514
  }
6436
6515
  return res;
6437
6516
  }
6438
- // Inverses number over modulo
6517
+ /**
6518
+ * Inverses number over modulo.
6519
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
6520
+ */
6439
6521
  function invert(number, modulo) {
6440
- if (number === _0n$3 || modulo <= _0n$3) {
6441
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
6442
- }
6443
- // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
6522
+ if (number === _0n$3)
6523
+ throw new Error('invert: expected non-zero number');
6524
+ if (modulo <= _0n$3)
6525
+ throw new Error('invert: expected positive modulus, got ' + modulo);
6444
6526
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
6445
6527
  let a = mod(number, modulo);
6446
6528
  let b = modulo;
@@ -6480,8 +6562,11 @@ function tonelliShanks(P) {
6480
6562
  for (Q = P - _1n$5, S = 0; Q % _2n$3 === _0n$3; Q /= _2n$3, S++)
6481
6563
  ;
6482
6564
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
6483
- for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++)
6484
- ;
6565
+ for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++) {
6566
+ // Crash instead of infinity loop, we cannot reasonable count until P.
6567
+ if (Z > 1000)
6568
+ throw new Error('Cannot find square root: likely non-prime P');
6569
+ }
6485
6570
  // Fast-path
6486
6571
  if (S === 1) {
6487
6572
  const p1div4 = (P + _1n$5) / _4n;
@@ -6523,9 +6608,18 @@ function tonelliShanks(P) {
6523
6608
  return x;
6524
6609
  };
6525
6610
  }
6611
+ /**
6612
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
6613
+ *
6614
+ * 1. P ≡ 3 (mod 4)
6615
+ * 2. P ≡ 5 (mod 8)
6616
+ * 3. P ≡ 9 (mod 16)
6617
+ * 4. Tonelli-Shanks algorithm
6618
+ *
6619
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
6620
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6621
+ */
6526
6622
  function FpSqrt(P) {
6527
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
6528
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6529
6623
  // P ≡ 3 (mod 4)
6530
6624
  // √n = n^((P+1)/4)
6531
6625
  if (P % _4n === _3n$1) {
@@ -6589,7 +6683,7 @@ function FpPow(f, num, power) {
6589
6683
  // Should have same speed as pow for bigints
6590
6684
  // TODO: benchmark!
6591
6685
  if (power < _0n$3)
6592
- throw new Error('Expected power > 0');
6686
+ throw new Error('invalid exponent, negatives unsupported');
6593
6687
  if (power === _0n$3)
6594
6688
  return f.ONE;
6595
6689
  if (power === _1n$5)
@@ -6636,15 +6730,15 @@ function nLength(n, nBitLength) {
6636
6730
  return { nBitLength: _nBitLength, nByteLength };
6637
6731
  }
6638
6732
  /**
6639
- * Initializes a finite field over prime. **Non-primes are not supported.**
6640
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
6733
+ * Initializes a finite field over prime.
6641
6734
  * Major performance optimizations:
6642
6735
  * * a) denormalized operations like mulN instead of mul
6643
6736
  * * b) same object shape: never add or remove keys
6644
6737
  * * c) Object.freeze
6645
- * NOTE: operations don't check 'isValid' for all elements for performance reasons,
6738
+ * Fragile: always run a benchmark on a change.
6739
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
6646
6740
  * it is caller responsibility to check this.
6647
- * This is low-level code, please make sure you know what you doing.
6741
+ * This is low-level code, please make sure you know what you're doing.
6648
6742
  * @param ORDER prime positive bigint
6649
6743
  * @param bitLen how many bits the field consumes
6650
6744
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -6652,13 +6746,14 @@ function nLength(n, nBitLength) {
6652
6746
  */
6653
6747
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
6654
6748
  if (ORDER <= _0n$3)
6655
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
6749
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
6656
6750
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
6657
6751
  if (BYTES > 2048)
6658
- throw new Error('Field lengths over 2048 bytes are not supported');
6659
- const sqrtP = FpSqrt(ORDER);
6752
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
6753
+ let sqrtP; // cached sqrtP
6660
6754
  const f = Object.freeze({
6661
6755
  ORDER,
6756
+ isLE,
6662
6757
  BITS,
6663
6758
  BYTES,
6664
6759
  MASK: bitMask(BITS),
@@ -6667,7 +6762,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6667
6762
  create: (num) => mod(num, ORDER),
6668
6763
  isValid: (num) => {
6669
6764
  if (typeof num !== 'bigint')
6670
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
6765
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
6671
6766
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
6672
6767
  },
6673
6768
  is0: (num) => num === _0n$3,
@@ -6686,7 +6781,12 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6686
6781
  subN: (lhs, rhs) => lhs - rhs,
6687
6782
  mulN: (lhs, rhs) => lhs * rhs,
6688
6783
  inv: (num) => invert(num, ORDER),
6689
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
6784
+ sqrt: redef.sqrt ||
6785
+ ((n) => {
6786
+ if (!sqrtP)
6787
+ sqrtP = FpSqrt(ORDER);
6788
+ return sqrtP(f, n);
6789
+ }),
6690
6790
  invertBatch: (lst) => FpInvertBatch(f, lst),
6691
6791
  // TODO: do we really need constant cmov?
6692
6792
  // We don't have const-time bigints anyway, so probably will be not very useful
@@ -6694,7 +6794,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6694
6794
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
6695
6795
  fromBytes: (bytes) => {
6696
6796
  if (bytes.length !== BYTES)
6697
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
6797
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
6698
6798
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
6699
6799
  },
6700
6800
  });
@@ -6742,52 +6842,80 @@ function mapHashToField(key, fieldOrder, isLE = false) {
6742
6842
  const minLen = getMinHashLength(fieldOrder);
6743
6843
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
6744
6844
  if (len < 16 || len < minLen || len > 1024)
6745
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
6746
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
6845
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
6846
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
6747
6847
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
6748
6848
  const reduced = mod(num, fieldOrder - _1n$5) + _1n$5;
6749
6849
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
6750
6850
  }
6751
6851
 
6852
+ /**
6853
+ * Methods for elliptic curve multiplication by scalars.
6854
+ * Contains wNAF, pippenger
6855
+ * @module
6856
+ */
6752
6857
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6753
- // Abelian group utilities
6754
6858
  const _0n$2 = BigInt(0);
6755
6859
  const _1n$4 = BigInt(1);
6860
+ function constTimeNegate(condition, item) {
6861
+ const neg = item.negate();
6862
+ return condition ? neg : item;
6863
+ }
6864
+ function validateW(W, bits) {
6865
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6866
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
6867
+ }
6868
+ function calcWOpts(W, bits) {
6869
+ validateW(W, bits);
6870
+ const windows = Math.ceil(bits / W) + 1; // +1, because
6871
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
6872
+ return { windows, windowSize };
6873
+ }
6874
+ function validateMSMPoints(points, c) {
6875
+ if (!Array.isArray(points))
6876
+ throw new Error('array expected');
6877
+ points.forEach((p, i) => {
6878
+ if (!(p instanceof c))
6879
+ throw new Error('invalid point at index ' + i);
6880
+ });
6881
+ }
6882
+ function validateMSMScalars(scalars, field) {
6883
+ if (!Array.isArray(scalars))
6884
+ throw new Error('array of scalars expected');
6885
+ scalars.forEach((s, i) => {
6886
+ if (!field.isValid(s))
6887
+ throw new Error('invalid scalar at index ' + i);
6888
+ });
6889
+ }
6756
6890
  // Since points in different groups cannot be equal (different object constructor),
6757
6891
  // we can have single place to store precomputes
6758
6892
  const pointPrecomputes = new WeakMap();
6759
6893
  const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
6760
- // Elliptic curve multiplication of Point by scalar. Fragile.
6761
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
6762
- // Creates precomputation tables for fast multiplication:
6763
- // - private scalar is split by fixed size windows of W bits
6764
- // - every window point is collected from window's table & added to accumulator
6765
- // - since windows are different, same point inside tables won't be accessed more than once per calc
6766
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6767
- // - +1 window is neccessary for wNAF
6768
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6769
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
6770
- // windows to be in different memory locations
6894
+ function getW(P) {
6895
+ return pointWindowSizes.get(P) || 1;
6896
+ }
6897
+ /**
6898
+ * Elliptic curve multiplication of Point by scalar. Fragile.
6899
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
6900
+ * Creates precomputation tables for fast multiplication:
6901
+ * - private scalar is split by fixed size windows of W bits
6902
+ * - every window point is collected from window's table & added to accumulator
6903
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
6904
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6905
+ * - +1 window is neccessary for wNAF
6906
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6907
+ *
6908
+ * @todo Research returning 2d JS array of windows, instead of a single window.
6909
+ * This would allow windows to be in different memory locations
6910
+ */
6771
6911
  function wNAF(c, bits) {
6772
- const constTimeNegate = (condition, item) => {
6773
- const neg = item.negate();
6774
- return condition ? neg : item;
6775
- };
6776
- const validateW = (W) => {
6777
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6778
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
6779
- };
6780
- const opts = (W) => {
6781
- validateW(W);
6782
- const windows = Math.ceil(bits / W) + 1; // +1, because
6783
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
6784
- return { windows, windowSize };
6785
- };
6786
6912
  return {
6787
6913
  constTimeNegate,
6914
+ hasPrecomputes(elm) {
6915
+ return getW(elm) !== 1;
6916
+ },
6788
6917
  // non-const time multiplication ladder
6789
- unsafeLadder(elm, n) {
6790
- let p = c.ZERO;
6918
+ unsafeLadder(elm, n, p = c.ZERO) {
6791
6919
  let d = elm;
6792
6920
  while (n > _0n$2) {
6793
6921
  if (n & _1n$4)
@@ -6805,10 +6933,12 @@ function wNAF(c, bits) {
6805
6933
  * - 𝑊 is the window size
6806
6934
  * - 𝑛 is the bitlength of the curve order.
6807
6935
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
6936
+ * @param elm Point instance
6937
+ * @param W window size
6808
6938
  * @returns precomputed point tables flattened to a single array
6809
6939
  */
6810
6940
  precomputeWindow(elm, W) {
6811
- const { windows, windowSize } = opts(W);
6941
+ const { windows, windowSize } = calcWOpts(W, bits);
6812
6942
  const points = [];
6813
6943
  let p = elm;
6814
6944
  let base = p;
@@ -6834,7 +6964,7 @@ function wNAF(c, bits) {
6834
6964
  wNAF(W, precomputes, n) {
6835
6965
  // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
6836
6966
  // But need to carefully remove other checks before wNAF. ORDER == bits here
6837
- const { windows, windowSize } = opts(W);
6967
+ const { windows, windowSize } = calcWOpts(W, bits);
6838
6968
  let p = c.ZERO;
6839
6969
  let f = c.BASE;
6840
6970
  const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
@@ -6878,8 +7008,44 @@ function wNAF(c, bits) {
6878
7008
  // which makes it less const-time: around 1 bigint multiply.
6879
7009
  return { p, f };
6880
7010
  },
6881
- wNAFCached(P, n, transform) {
6882
- const W = pointWindowSizes.get(P) || 1;
7011
+ /**
7012
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
7013
+ * @param W window size
7014
+ * @param precomputes precomputed tables
7015
+ * @param n scalar (we don't check here, but should be less than curve order)
7016
+ * @param acc accumulator point to add result of multiplication
7017
+ * @returns point
7018
+ */
7019
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
7020
+ const { windows, windowSize } = calcWOpts(W, bits);
7021
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
7022
+ const maxNumber = 2 ** W;
7023
+ const shiftBy = BigInt(W);
7024
+ for (let window = 0; window < windows; window++) {
7025
+ const offset = window * windowSize;
7026
+ if (n === _0n$2)
7027
+ break; // No need to go over empty scalar
7028
+ // Extract W bits.
7029
+ let wbits = Number(n & mask);
7030
+ // Shift number by W bits.
7031
+ n >>= shiftBy;
7032
+ // If the bits are bigger than max size, we'll split those.
7033
+ // +224 => 256 - 32
7034
+ if (wbits > windowSize) {
7035
+ wbits -= maxNumber;
7036
+ n += _1n$4;
7037
+ }
7038
+ if (wbits === 0)
7039
+ continue;
7040
+ let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero
7041
+ if (wbits < 0)
7042
+ curr = curr.negate();
7043
+ // NOTE: by re-using acc, we can save a lot of additions in case of MSM
7044
+ acc = acc.add(curr);
7045
+ }
7046
+ return acc;
7047
+ },
7048
+ getPrecomputes(W, P, transform) {
6883
7049
  // Calculate precomputes on a first run, reuse them after
6884
7050
  let comp = pointPrecomputes.get(P);
6885
7051
  if (!comp) {
@@ -6887,62 +7053,66 @@ function wNAF(c, bits) {
6887
7053
  if (W !== 1)
6888
7054
  pointPrecomputes.set(P, transform(comp));
6889
7055
  }
6890
- return this.wNAF(W, comp, n);
7056
+ return comp;
7057
+ },
7058
+ wNAFCached(P, n, transform) {
7059
+ const W = getW(P);
7060
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
7061
+ },
7062
+ wNAFCachedUnsafe(P, n, transform, prev) {
7063
+ const W = getW(P);
7064
+ if (W === 1)
7065
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
7066
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
6891
7067
  },
6892
7068
  // We calculate precomputes for elliptic curve point multiplication
6893
7069
  // using windowed method. This specifies window size and
6894
7070
  // stores precomputed values. Usually only base point would be precomputed.
6895
7071
  setWindowSize(P, W) {
6896
- validateW(W);
7072
+ validateW(W, bits);
6897
7073
  pointWindowSizes.set(P, W);
6898
7074
  pointPrecomputes.delete(P);
6899
7075
  },
6900
7076
  };
6901
7077
  }
6902
7078
  /**
6903
- * Pippenger algorithm for multi-scalar multiplication (MSM).
6904
- * MSM is basically (Pa + Qb + Rc + ...).
7079
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
6905
7080
  * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
6906
7081
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
6907
7082
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
6908
7083
  * @param c Curve Point constructor
6909
- * @param field field over CURVE.N - important that it's not over CURVE.P
7084
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
6910
7085
  * @param points array of L curve points
6911
7086
  * @param scalars array of L scalars (aka private keys / bigints)
6912
7087
  */
6913
- function pippenger(c, field, points, scalars) {
7088
+ function pippenger(c, fieldN, points, scalars) {
6914
7089
  // If we split scalars by some window (let's say 8 bits), every chunk will only
6915
7090
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
6916
7091
  // TODO:
6917
7092
  // - https://eprint.iacr.org/2024/750.pdf
6918
7093
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
6919
7094
  // 0 is accepted in scalars
6920
- if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
7095
+ validateMSMPoints(points, c);
7096
+ validateMSMScalars(scalars, fieldN);
7097
+ if (points.length !== scalars.length)
6921
7098
  throw new Error('arrays of points and scalars must have equal length');
6922
- scalars.forEach((s, i) => {
6923
- if (!field.isValid(s))
6924
- throw new Error(`wrong scalar at index ${i}`);
6925
- });
6926
- points.forEach((p, i) => {
6927
- if (!(p instanceof c))
6928
- throw new Error(`wrong point at index ${i}`);
6929
- });
7099
+ const zero = c.ZERO;
6930
7100
  const wbits = bitLen(BigInt(points.length));
6931
7101
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
6932
7102
  const MASK = (1 << windowSize) - 1;
6933
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
6934
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
6935
- let sum = c.ZERO;
7103
+ const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array
7104
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
7105
+ let sum = zero;
6936
7106
  for (let i = lastBits; i >= 0; i -= windowSize) {
6937
- buckets.fill(c.ZERO);
7107
+ buckets.fill(zero);
6938
7108
  for (let j = 0; j < scalars.length; j++) {
6939
7109
  const scalar = scalars[j];
6940
7110
  const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
6941
7111
  buckets[wbits] = buckets[wbits].add(points[j]);
6942
7112
  }
6943
- let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
7113
+ let resI = zero; // not using this will do small speed-up, but will lose ct
6944
7114
  // Skip first bucket, because it is zero
6945
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
7115
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
6946
7116
  sumI = sumI.add(buckets[j]);
6947
7117
  resI = resI.add(sumI);
6948
7118
  }
@@ -6972,8 +7142,12 @@ function validateBasic(curve) {
6972
7142
  });
6973
7143
  }
6974
7144
 
7145
+ /**
7146
+ * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
7147
+ * For design rationale of types / exports, see weierstrass module documentation.
7148
+ * @module
7149
+ */
6975
7150
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6976
- // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
6977
7151
  // Be friendly to bad ECMAScript parsers by not using bigint literals
6978
7152
  // prettier-ignore
6979
7153
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -7005,6 +7179,10 @@ function validateOpts$1(curve) {
7005
7179
  function twistedEdwards(curveDef) {
7006
7180
  const CURVE = validateOpts$1(curveDef);
7007
7181
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
7182
+ // Important:
7183
+ // There are some places where Fp.BYTES is used instead of nByteLength.
7184
+ // So far, everything has been tested with curves of Fp.BYTES == nByteLength.
7185
+ // TODO: test and find curves which behave otherwise.
7008
7186
  const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
7009
7187
  const modP = Fp.create; // Function overrides
7010
7188
  const Fn = Field(CURVE.n, CURVE.nBitLength);
@@ -7218,16 +7396,15 @@ function twistedEdwards(curveDef) {
7218
7396
  // It's faster, but should only be used when you don't care about
7219
7397
  // an exposed private key e.g. sig verification.
7220
7398
  // Does NOT allow scalars higher than CURVE.n.
7221
- multiplyUnsafe(scalar) {
7399
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
7400
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
7222
7401
  const n = scalar;
7223
7402
  aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L
7224
7403
  if (n === _0n$1)
7225
7404
  return I;
7226
- if (this.equals(I) || n === _1n$3)
7405
+ if (this.is0() || n === _1n$3)
7227
7406
  return this;
7228
- if (this.equals(G))
7229
- return this.wNAF(n).p;
7230
- return wnaf.unsafeLadder(this, n);
7407
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
7231
7408
  }
7232
7409
  // Checks if point is of small order.
7233
7410
  // If you add something to small order point, you will have "dirty"
@@ -7261,8 +7438,9 @@ function twistedEdwards(curveDef) {
7261
7438
  abool('zip215', zip215);
7262
7439
  const normed = hex.slice(); // copy again, we'll manipulate it
7263
7440
  const lastByte = hex[len - 1]; // select last byte
7264
- normed[len - 1] = lastByte & ~0x80; // clear last bit
7441
+ normed[len - 1] = lastByte & -129; // clear last bit
7265
7442
  const y = bytesToNumberLE(normed);
7443
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7266
7444
  // RFC8032 prohibits >= p, but ZIP215 doesn't
7267
7445
  // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7268
7446
  // zip215=false: 0 <= y < P (2^255-19 for ed25519)
@@ -7311,7 +7489,7 @@ function twistedEdwards(curveDef) {
7311
7489
  }
7312
7490
  /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
7313
7491
  function getExtendedPublicKey(key) {
7314
- const len = nByteLength;
7492
+ const len = Fp.BYTES;
7315
7493
  key = ensureBytes('private key', key, len);
7316
7494
  // Hash private key with curve's hash function to produce uniformingly random input
7317
7495
  // Check byte lengths: ensure(64, h(ensure(32, key)))
@@ -7344,23 +7522,29 @@ function twistedEdwards(curveDef) {
7344
7522
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
7345
7523
  aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l
7346
7524
  const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));
7347
- return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
7525
+ return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature
7348
7526
  }
7349
7527
  const verifyOpts = VERIFY_DEFAULT;
7528
+ /**
7529
+ * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7530
+ * An extended group equation is checked.
7531
+ */
7350
7532
  function verify(sig, msg, publicKey, options = verifyOpts) {
7351
7533
  const { context, zip215 } = options;
7352
7534
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7353
7535
  sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
7354
7536
  msg = ensureBytes('message', msg);
7537
+ publicKey = ensureBytes('publicKey', publicKey, len);
7355
7538
  if (zip215 !== undefined)
7356
7539
  abool('zip215', zip215);
7357
7540
  if (prehash)
7358
7541
  msg = prehash(msg); // for ed25519ph, etc
7359
7542
  const s = bytesToNumberLE(sig.slice(len, 2 * len));
7360
- // zip215: true is good for consensus-critical apps and allows points < 2^256
7361
- // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
7362
7543
  let A, R, SB;
7363
7544
  try {
7545
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7546
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7547
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
7364
7548
  A = Point.fromHex(publicKey, zip215);
7365
7549
  R = Point.fromHex(sig.slice(0, len), zip215);
7366
7550
  SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
@@ -7372,6 +7556,7 @@ function twistedEdwards(curveDef) {
7372
7556
  return false;
7373
7557
  const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
7374
7558
  const RkA = R.add(A.multiplyUnsafe(k));
7559
+ // Extended group equation
7375
7560
  // [8][S]B = [8]R + [8][k]A'
7376
7561
  return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
7377
7562
  }
@@ -7402,13 +7587,14 @@ function twistedEdwards(curveDef) {
7402
7587
  };
7403
7588
  }
7404
7589
 
7405
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7406
7590
  /**
7407
7591
  * ed25519 Twisted Edwards curve with following addons:
7408
7592
  * - X25519 ECDH
7409
7593
  * - Ristretto cofactor elimination
7410
7594
  * - Elligator hash-to-group / point indistinguishability
7595
+ * @module
7411
7596
  */
7597
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7412
7598
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
7413
7599
  // √(-1) aka √(a) aka 2^((p-1)/4)
7414
7600
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
@@ -7467,7 +7653,7 @@ function uvRatio(u, v) {
7467
7653
  x = mod(-x, P);
7468
7654
  return { isValid: useRoot1 || useRoot2, value: x };
7469
7655
  }
7470
- const Fp$1 = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7656
+ const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7471
7657
  const ed25519Defaults = /* @__PURE__ */ (() => ({
7472
7658
  // Param: a
7473
7659
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
@@ -7475,7 +7661,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7475
7661
  // Negative number is P - number, and division is invert(number, P)
7476
7662
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
7477
7663
  // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
7478
- Fp: Fp$1,
7664
+ Fp,
7479
7665
  // Subgroup order: how many points curve has
7480
7666
  // 2n**252n + 27742317777372353535851937790883648493n;
7481
7667
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
@@ -7494,6 +7680,14 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7494
7680
  }))();
7495
7681
  /**
7496
7682
  * ed25519 curve with EdDSA signatures.
7683
+ * @example
7684
+ * import { ed25519 } from '@noble/curves/ed25519';
7685
+ * const priv = ed25519.utils.randomPrivateKey();
7686
+ * const pub = ed25519.getPublicKey(priv);
7687
+ * const msg = new TextEncoder().encode('hello');
7688
+ * const sig = ed25519.sign(msg, priv);
7689
+ * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
7690
+ * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5
7497
7691
  */
7498
7692
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7499
7693
 
@@ -8867,7 +9061,7 @@ var PrivateKey;
8867
9061
  /*!
8868
9062
  * MIT License
8869
9063
  *
8870
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9064
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
8871
9065
  *
8872
9066
  * Permission is hereby granted, free of charge, to any person obtaining a copy
8873
9067
  * of this software and associated documentation files (the "Software"), to deal
@@ -8979,7 +9173,7 @@ class BufferSourceConverter {
8979
9173
  }
8980
9174
 
8981
9175
  const STRING_TYPE = "string";
8982
- const HEX_REGEX = /^[0-9a-f]+$/i;
9176
+ const HEX_REGEX = /^[0-9a-f\s]+$/i;
8983
9177
  const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
8984
9178
  const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
8985
9179
  class Utf8Converter {
@@ -9213,7 +9407,7 @@ class Convert {
9213
9407
  return base64;
9214
9408
  }
9215
9409
  static formatString(data) {
9216
- return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
9410
+ return (data === null || data === undefined ? undefined : data.replace(/[\n\r\t ]/g, "")) || "";
9217
9411
  }
9218
9412
  }
9219
9413
  Convert.DEFAULT_UTF8_ENCODING = "utf8";
@@ -9469,7 +9663,7 @@ function HexBlock(BaseClass) {
9469
9663
  var _a;
9470
9664
  super(...args);
9471
9665
  const params = args[0] || {};
9472
- this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
9666
+ this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== undefined ? _a : false;
9473
9667
  this.valueHexView = params.valueHex ? BufferSourceConverter_1.toUint8Array(params.valueHex) : EMPTY_VIEW;
9474
9668
  }
9475
9669
  get valueHex() {
@@ -9559,11 +9753,11 @@ class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
9559
9753
  var _a, _b, _c, _d;
9560
9754
  super();
9561
9755
  if (idBlock) {
9562
- this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
9756
+ this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== undefined ? _a : false;
9563
9757
  this.valueHexView = idBlock.valueHex ? BufferSourceConverter_1.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
9564
- this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
9565
- this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
9566
- this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
9758
+ this.tagClass = (_b = idBlock.tagClass) !== null && _b !== undefined ? _b : -1;
9759
+ this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== undefined ? _c : -1;
9760
+ this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== undefined ? _d : false;
9567
9761
  }
9568
9762
  else {
9569
9763
  this.tagClass = -1;
@@ -9730,9 +9924,9 @@ class LocalLengthBlock extends LocalBaseBlock {
9730
9924
  constructor({ lenBlock = {}, } = {}) {
9731
9925
  var _a, _b, _c;
9732
9926
  super();
9733
- this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
9734
- this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
9735
- this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
9927
+ this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== undefined ? _a : false;
9928
+ this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== undefined ? _b : false;
9929
+ this.length = (_c = lenBlock.length) !== null && _c !== undefined ? _c : 0;
9736
9930
  }
9737
9931
  fromBER(inputBuffer, inputOffset, inputLength) {
9738
9932
  const view = BufferSourceConverter_1.toUint8Array(inputBuffer);
@@ -10504,7 +10698,7 @@ var _a$r;
10504
10698
  class OctetString extends BaseBlock {
10505
10699
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10506
10700
  var _b, _c;
10507
- (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
10701
+ (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10508
10702
  super({
10509
10703
  idBlock: {
10510
10704
  isConstructed: parameters.isConstructed,
@@ -10665,7 +10859,7 @@ var _a$q;
10665
10859
  class BitString extends BaseBlock {
10666
10860
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10667
10861
  var _b, _c;
10668
- (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
10862
+ (_b = parameters.isConstructed) !== null && _b !== undefined ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === undefined ? undefined : _c.length));
10669
10863
  super({
10670
10864
  idBlock: {
10671
10865
  isConstructed: parameters.isConstructed,
@@ -11867,7 +12061,7 @@ class GeneralizedTime extends UTCTime {
11867
12061
  constructor(parameters = {}) {
11868
12062
  var _b;
11869
12063
  super(parameters);
11870
- (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
12064
+ (_b = this.millisecond) !== null && _b !== undefined ? _b : (this.millisecond = 0);
11871
12065
  this.idBlock.tagClass = 1;
11872
12066
  this.idBlock.tagNumber = 24;
11873
12067
  }
@@ -12290,15 +12484,18 @@ function pkixToRSAPublicKey(bytes) {
12290
12484
  return new RSAPublicKey(jwk, digest);
12291
12485
  }
12292
12486
 
12293
- // HMAC (RFC 2104)
12487
+ /**
12488
+ * HMAC: RFC2104 message authentication code.
12489
+ * @module
12490
+ */
12294
12491
  class HMAC extends Hash {
12295
- constructor(hash$1, _key) {
12492
+ constructor(hash, _key) {
12296
12493
  super();
12297
12494
  this.finished = false;
12298
12495
  this.destroyed = false;
12299
- hash(hash$1);
12496
+ ahash(hash);
12300
12497
  const key = toBytes$1(_key);
12301
- this.iHash = hash$1.create();
12498
+ this.iHash = hash.create();
12302
12499
  if (typeof this.iHash.update !== 'function')
12303
12500
  throw new Error('Expected instance of class which extends utils.Hash');
12304
12501
  this.blockLen = this.iHash.blockLen;
@@ -12306,12 +12503,12 @@ class HMAC extends Hash {
12306
12503
  const blockLen = this.blockLen;
12307
12504
  const pad = new Uint8Array(blockLen);
12308
12505
  // blockLen can be bigger than outputLen
12309
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12506
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
12310
12507
  for (let i = 0; i < pad.length; i++)
12311
12508
  pad[i] ^= 0x36;
12312
12509
  this.iHash.update(pad);
12313
12510
  // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12314
- this.oHash = hash$1.create();
12511
+ this.oHash = hash.create();
12315
12512
  // Undo internal XOR && apply outer XOR
12316
12513
  for (let i = 0; i < pad.length; i++)
12317
12514
  pad[i] ^= 0x36 ^ 0x5c;
@@ -12319,13 +12516,13 @@ class HMAC extends Hash {
12319
12516
  pad.fill(0);
12320
12517
  }
12321
12518
  update(buf) {
12322
- exists(this);
12519
+ aexists(this);
12323
12520
  this.iHash.update(buf);
12324
12521
  return this;
12325
12522
  }
12326
12523
  digestInto(out) {
12327
- exists(this);
12328
- bytes(out, this.outputLen);
12524
+ aexists(this);
12525
+ abytes$1(out, this.outputLen);
12329
12526
  this.finished = true;
12330
12527
  this.iHash.digestInto(out);
12331
12528
  this.oHash.update(out);
@@ -12369,8 +12566,33 @@ class HMAC extends Hash {
12369
12566
  const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12370
12567
  hmac.create = (hash, key) => new HMAC(hash, key);
12371
12568
 
12569
+ /**
12570
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
12571
+ *
12572
+ * ### Design rationale for types
12573
+ *
12574
+ * * Interaction between classes from different curves should fail:
12575
+ * `k256.Point.BASE.add(p256.Point.BASE)`
12576
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
12577
+ * * Different calls of `curve()` would return different classes -
12578
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
12579
+ * it won't affect others
12580
+ *
12581
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
12582
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
12583
+ * unique type for every function call.
12584
+ *
12585
+ * We can use generic types via some param, like curve opts, but that would:
12586
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
12587
+ * which is hard to debug.
12588
+ * 2. Params can be generic and we can't enforce them to be constant value:
12589
+ * if somebody creates curve from non-constant params,
12590
+ * it would be allowed to interact with other curves with non-constant params
12591
+ *
12592
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
12593
+ * @module
12594
+ */
12372
12595
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12373
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
12374
12596
  function validateSigVerOpts(opts) {
12375
12597
  if (opts.lowS !== undefined)
12376
12598
  abool('lowS', opts.lowS);
@@ -12394,17 +12616,22 @@ function validatePointOpts(curve) {
12394
12616
  const { endo, Fp, a } = opts;
12395
12617
  if (endo) {
12396
12618
  if (!Fp.eql(a, Fp.ZERO)) {
12397
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
12619
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
12398
12620
  }
12399
12621
  if (typeof endo !== 'object' ||
12400
12622
  typeof endo.beta !== 'bigint' ||
12401
12623
  typeof endo.splitScalar !== 'function') {
12402
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
12624
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
12403
12625
  }
12404
12626
  }
12405
12627
  return Object.freeze({ ...opts });
12406
12628
  }
12407
12629
  const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12630
+ class DERErr extends Error {
12631
+ constructor(m = '') {
12632
+ super(m);
12633
+ }
12634
+ }
12408
12635
  /**
12409
12636
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
12410
12637
  *
@@ -12414,11 +12641,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12414
12641
  */
12415
12642
  const DER = {
12416
12643
  // asn.1 DER encoding utils
12417
- Err: class DERErr extends Error {
12418
- constructor(m = '') {
12419
- super(m);
12420
- }
12421
- },
12644
+ Err: DERErr,
12422
12645
  // Basic building block is TLV (Tag-Length-Value)
12423
12646
  _tlv: {
12424
12647
  encode: (tag, data) => {
@@ -12433,7 +12656,8 @@ const DER = {
12433
12656
  throw new E('tlv.encode: long form length too big');
12434
12657
  // length of length with long form flag
12435
12658
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
12436
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
12659
+ const t = numberToHexUnpadded(tag);
12660
+ return t + lenLen + len + data;
12437
12661
  },
12438
12662
  // v - value, l - left bytes (unparsed)
12439
12663
  decode(tag, data) {
@@ -12486,15 +12710,15 @@ const DER = {
12486
12710
  if (Number.parseInt(hex[0], 16) & 0b1000)
12487
12711
  hex = '00' + hex;
12488
12712
  if (hex.length & 1)
12489
- throw new E('unexpected assertion');
12713
+ throw new E('unexpected DER parsing assertion: unpadded hex');
12490
12714
  return hex;
12491
12715
  },
12492
12716
  decode(data) {
12493
12717
  const { Err: E } = DER;
12494
12718
  if (data[0] & 128)
12495
- throw new E('Invalid signature integer: negative');
12719
+ throw new E('invalid signature integer: negative');
12496
12720
  if (data[0] === 0x00 && !(data[1] & 128))
12497
- throw new E('Invalid signature integer: unnecessary leading zero');
12721
+ throw new E('invalid signature integer: unnecessary leading zero');
12498
12722
  return b2n(data);
12499
12723
  },
12500
12724
  },
@@ -12505,16 +12729,18 @@ const DER = {
12505
12729
  abytes(data);
12506
12730
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
12507
12731
  if (seqLeftBytes.length)
12508
- throw new E('Invalid signature: left bytes after parsing');
12732
+ throw new E('invalid signature: left bytes after parsing');
12509
12733
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
12510
12734
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
12511
12735
  if (sLeftBytes.length)
12512
- throw new E('Invalid signature: left bytes after parsing');
12736
+ throw new E('invalid signature: left bytes after parsing');
12513
12737
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
12514
12738
  },
12515
12739
  hexFromSig(sig) {
12516
12740
  const { _tlv: tlv, _int: int } = DER;
12517
- const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
12741
+ const rs = tlv.encode(0x02, int.encode(sig.r));
12742
+ const ss = tlv.encode(0x02, int.encode(sig.s));
12743
+ const seq = rs + ss;
12518
12744
  return tlv.encode(0x30, seq);
12519
12745
  },
12520
12746
  };
@@ -12568,7 +12794,7 @@ function weierstrassPoints(opts) {
12568
12794
  key = bytesToHex(key);
12569
12795
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
12570
12796
  if (typeof key !== 'string' || !lengths.includes(key.length))
12571
- throw new Error('Invalid key');
12797
+ throw new Error('invalid private key');
12572
12798
  key = key.padStart(nByteLength * 2, '0');
12573
12799
  }
12574
12800
  let num;
@@ -12579,7 +12805,7 @@ function weierstrassPoints(opts) {
12579
12805
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
12580
12806
  }
12581
12807
  catch (error) {
12582
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
12808
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
12583
12809
  }
12584
12810
  if (wrapPrivateKey)
12585
12811
  num = mod(num, N); // disabled by default, enabled for BLS
@@ -12619,7 +12845,7 @@ function weierstrassPoints(opts) {
12619
12845
  if (p.is0()) {
12620
12846
  // (0, 1, 0) aka ZERO is invalid in most contexts.
12621
12847
  // In BLS, ZERO can be serialized, so we allow it.
12622
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
12848
+ // (0, 0, 0) is invalid representation of ZERO.
12623
12849
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
12624
12850
  return;
12625
12851
  throw new Error('bad point: ZERO');
@@ -12843,16 +13069,17 @@ function weierstrassPoints(opts) {
12843
13069
  * an exposed private key e.g. sig verification, which works over *public* keys.
12844
13070
  */
12845
13071
  multiplyUnsafe(sc) {
12846
- aInRange('scalar', sc, _0n, CURVE.n);
13072
+ const { endo, n: N } = CURVE;
13073
+ aInRange('scalar', sc, _0n, N);
12847
13074
  const I = Point.ZERO;
12848
13075
  if (sc === _0n)
12849
13076
  return I;
12850
- if (sc === _1n$1)
13077
+ if (this.is0() || sc === _1n$1)
12851
13078
  return this;
12852
- const { endo } = CURVE;
12853
- if (!endo)
12854
- return wnaf.unsafeLadder(this, sc);
12855
- // Apply endomorphism
13079
+ // Case a: no endomorphism. Case b: has precomputes.
13080
+ if (!endo || wnaf.hasPrecomputes(this))
13081
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
13082
+ // Case c: endomorphism
12856
13083
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
12857
13084
  let k1p = I;
12858
13085
  let k2p = I;
@@ -13038,7 +13265,9 @@ function weierstrass(curveDef) {
13038
13265
  return { x, y };
13039
13266
  }
13040
13267
  else {
13041
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
13268
+ const cl = compressedLen;
13269
+ const ul = uncompressedLen;
13270
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
13042
13271
  }
13043
13272
  },
13044
13273
  });
@@ -13203,6 +13432,9 @@ function weierstrass(curveDef) {
13203
13432
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
13204
13433
  const bits2int = CURVE.bits2int ||
13205
13434
  function (bytes) {
13435
+ // Our custom check "just in case"
13436
+ if (bytes.length > 8192)
13437
+ throw new Error('input is too large');
13206
13438
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
13207
13439
  // for some cases, since bytes.length * 8 is not actual bitLength.
13208
13440
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -13219,15 +13451,15 @@ function weierstrass(curveDef) {
13219
13451
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
13220
13452
  */
13221
13453
  function int2octets(num) {
13222
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
13454
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
13223
13455
  // works with order, can have different size than numToField!
13224
13456
  return numberToBytesBE(num, CURVE.nByteLength);
13225
13457
  }
13226
13458
  // Steps A, D of RFC6979 3.2
13227
13459
  // Creates RFC6979 seed; converts msg/privKey to numbers.
13228
13460
  // Used only in sign, not in verify.
13229
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
13230
- // Also it can be bigger for P224 + SHA256
13461
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
13462
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
13231
13463
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
13232
13464
  if (['recovered', 'canonical'].some((k) => k in opts))
13233
13465
  throw new Error('sign() legacy options not supported');
@@ -13321,39 +13553,48 @@ function weierstrass(curveDef) {
13321
13553
  const sg = signature;
13322
13554
  msgHash = ensureBytes('msgHash', msgHash);
13323
13555
  publicKey = ensureBytes('publicKey', publicKey);
13556
+ const { lowS, prehash, format } = opts;
13557
+ // Verify opts, deduce signature format
13558
+ validateSigVerOpts(opts);
13324
13559
  if ('strict' in opts)
13325
13560
  throw new Error('options.strict was renamed to lowS');
13326
- validateSigVerOpts(opts);
13327
- const { lowS, prehash } = opts;
13561
+ if (format !== undefined && format !== 'compact' && format !== 'der')
13562
+ throw new Error('format must be compact or der');
13563
+ const isHex = typeof sg === 'string' || isBytes$1(sg);
13564
+ const isObj = !isHex &&
13565
+ !format &&
13566
+ typeof sg === 'object' &&
13567
+ sg !== null &&
13568
+ typeof sg.r === 'bigint' &&
13569
+ typeof sg.s === 'bigint';
13570
+ if (!isHex && !isObj)
13571
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
13328
13572
  let _sig = undefined;
13329
13573
  let P;
13330
13574
  try {
13331
- if (typeof sg === 'string' || isBytes$1(sg)) {
13575
+ if (isObj)
13576
+ _sig = new Signature(sg.r, sg.s);
13577
+ if (isHex) {
13332
13578
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
13333
13579
  // Since DER can also be 2*nByteLength bytes, we check for it first.
13334
13580
  try {
13335
- _sig = Signature.fromDER(sg);
13581
+ if (format !== 'compact')
13582
+ _sig = Signature.fromDER(sg);
13336
13583
  }
13337
13584
  catch (derError) {
13338
13585
  if (!(derError instanceof DER.Err))
13339
13586
  throw derError;
13340
- _sig = Signature.fromCompact(sg);
13341
13587
  }
13342
- }
13343
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
13344
- const { r, s } = sg;
13345
- _sig = new Signature(r, s);
13346
- }
13347
- else {
13348
- throw new Error('PARSE');
13588
+ if (!_sig && format !== 'der')
13589
+ _sig = Signature.fromCompact(sg);
13349
13590
  }
13350
13591
  P = Point.fromHex(publicKey);
13351
13592
  }
13352
13593
  catch (error) {
13353
- if (error.message === 'PARSE')
13354
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
13355
13594
  return false;
13356
13595
  }
13596
+ if (!_sig)
13597
+ return false;
13357
13598
  if (lowS && _sig.hasHighS())
13358
13599
  return false;
13359
13600
  if (prehash)
@@ -13381,8 +13622,12 @@ function weierstrass(curveDef) {
13381
13622
  };
13382
13623
  }
13383
13624
 
13625
+ /**
13626
+ * Utilities for short weierstrass curves, combined with noble-hashes.
13627
+ * @module
13628
+ */
13384
13629
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13385
- // connects noble-curves to noble-hashes
13630
+ /** connects noble-curves to noble-hashes */
13386
13631
  function getHash(hash) {
13387
13632
  return {
13388
13633
  hash,
@@ -13392,9 +13637,21 @@ function getHash(hash) {
13392
13637
  }
13393
13638
  function createCurve(curveDef, defHash) {
13394
13639
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
13395
- return Object.freeze({ ...create(defHash), create });
13640
+ return { ...create(defHash), create };
13396
13641
  }
13397
13642
 
13643
+ /**
13644
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
13645
+ *
13646
+ * Seems to be rigid (not backdoored)
13647
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
13648
+ *
13649
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13650
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13651
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13652
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
13653
+ * @module
13654
+ */
13398
13655
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13399
13656
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
13400
13657
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -13425,31 +13682,35 @@ function sqrtMod(y) {
13425
13682
  const t1 = (pow2(b223, _23n, P) * b22) % P;
13426
13683
  const t2 = (pow2(t1, _6n, P) * b2) % P;
13427
13684
  const root = pow2(t2, _2n, P);
13428
- if (!Fp.eql(Fp.sqr(root), y))
13685
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
13429
13686
  throw new Error('Cannot find square root');
13430
13687
  return root;
13431
13688
  }
13432
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13689
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13433
13690
  /**
13434
13691
  * secp256k1 short weierstrass curve and ECDSA signatures over it.
13692
+ *
13693
+ * @example
13694
+ * import { secp256k1 } from '@noble/curves/secp256k1';
13695
+ *
13696
+ * const priv = secp256k1.utils.randomPrivateKey();
13697
+ * const pub = secp256k1.getPublicKey(priv);
13698
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
13699
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
13700
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
13435
13701
  */
13436
13702
  const secp256k1 = createCurve({
13437
13703
  a: BigInt(0), // equation params: a, b
13438
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
13439
- Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13704
+ b: BigInt(7),
13705
+ Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
13440
13706
  n: secp256k1N, // Curve order, total count of valid points in the field
13441
13707
  // Base point (x, y) aka generator point
13442
13708
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
13443
13709
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
13444
13710
  h: BigInt(1), // Cofactor
13445
13711
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
13446
- /**
13447
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13448
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13449
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13450
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
13451
- */
13452
13712
  endo: {
13713
+ // Endomorphism, see above
13453
13714
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
13454
13715
  splitScalar: (k) => {
13455
13716
  const n = secp256k1N;
@@ -13586,28 +13847,6 @@ function publicKeyToProtobuf(key) {
13586
13847
  });
13587
13848
  }
13588
13849
 
13589
- /**
13590
- * All PeerId implementations must use this symbol as the name of a property
13591
- * with a boolean `true` value
13592
- */
13593
- const peerIdSymbol = Symbol.for('@libp2p/peer-id');
13594
-
13595
- /**
13596
- * When this error is thrown it means an operation was aborted,
13597
- * usually in response to the `abort` event being emitted by an
13598
- * AbortSignal.
13599
- */
13600
- /**
13601
- * Thrown when and attempt to operate on an unsupported key was made
13602
- */
13603
- class UnsupportedKeyTypeError extends Error {
13604
- static name = 'UnsupportedKeyTypeError';
13605
- constructor(message = 'Unsupported key type') {
13606
- super(message);
13607
- this.name = 'UnsupportedKeyTypeError';
13608
- }
13609
- }
13610
-
13611
13850
  /**
13612
13851
  * @packageDocumentation
13613
13852
  *