@waku/enr 0.0.28-c43cec2.0 → 0.0.28-caeafce.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')
@@ -5830,9 +5874,13 @@ class UnsupportedKeyTypeError extends Error {
5830
5874
  }
5831
5875
  }
5832
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
+ */
5833
5882
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
5834
5883
  const _32n = /* @__PURE__ */ BigInt(32);
5835
- // We are not using BigUint64Array, because they are extremely slow as per 2022
5836
5884
  function fromBig(n, le = false) {
5837
5885
  if (le)
5838
5886
  return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
@@ -5889,6 +5937,13 @@ const u64 = {
5889
5937
  add, add3L, add3H, add4L, add4H, add5H, add5L,
5890
5938
  };
5891
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
+ */
5892
5947
  // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
5893
5948
  // prettier-ignore
5894
5949
  const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
@@ -6043,8 +6098,13 @@ class SHA512 extends HashMD {
6043
6098
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
6044
6099
  }
6045
6100
  }
6101
+ /** SHA2-512 hash function. */
6046
6102
  const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
6047
6103
 
6104
+ /**
6105
+ * Hex, bytes and number utilities.
6106
+ * @module
6107
+ */
6048
6108
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6049
6109
  // 100 lines of code in the file are duplicated from noble-hashes (utils).
6050
6110
  // This is OK: `abstract` directory does not use noble-hashes.
@@ -6054,8 +6114,7 @@ const _0n$4 = /* @__PURE__ */ BigInt(0);
6054
6114
  const _1n$6 = /* @__PURE__ */ BigInt(1);
6055
6115
  const _2n$4 = /* @__PURE__ */ BigInt(2);
6056
6116
  function isBytes$1(a) {
6057
- return (a instanceof Uint8Array ||
6058
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
6117
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
6059
6118
  }
6060
6119
  function abytes(item) {
6061
6120
  if (!isBytes$1(item))
@@ -6063,7 +6122,7 @@ function abytes(item) {
6063
6122
  }
6064
6123
  function abool(title, value) {
6065
6124
  if (typeof value !== 'boolean')
6066
- throw new Error(`${title} must be valid boolean, got "${value}".`);
6125
+ throw new Error(title + ' boolean expected, got ' + value);
6067
6126
  }
6068
6127
  // Array where index 0xf0 (240) is mapped to string 'f0'
6069
6128
  const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
@@ -6081,23 +6140,22 @@ function bytesToHex(bytes) {
6081
6140
  }
6082
6141
  function numberToHexUnpadded(num) {
6083
6142
  const hex = num.toString(16);
6084
- return hex.length & 1 ? `0${hex}` : hex;
6143
+ return hex.length & 1 ? '0' + hex : hex;
6085
6144
  }
6086
6145
  function hexToNumber(hex) {
6087
6146
  if (typeof hex !== 'string')
6088
6147
  throw new Error('hex string expected, got ' + typeof hex);
6089
- // Big Endian
6090
- return BigInt(hex === '' ? '0' : `0x${hex}`);
6148
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
6091
6149
  }
6092
6150
  // We use optimized technique to convert hex string to byte array
6093
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
6094
- function asciiToBase16(char) {
6095
- if (char >= asciis._0 && char <= asciis._9)
6096
- return char - asciis._0;
6097
- if (char >= asciis._A && char <= asciis._F)
6098
- return char - (asciis._A - 10);
6099
- if (char >= asciis._a && char <= asciis._f)
6100
- 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)
6101
6159
  return;
6102
6160
  }
6103
6161
  /**
@@ -6109,7 +6167,7 @@ function hexToBytes(hex) {
6109
6167
  const hl = hex.length;
6110
6168
  const al = hl / 2;
6111
6169
  if (hl % 2)
6112
- 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);
6113
6171
  const array = new Uint8Array(al);
6114
6172
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
6115
6173
  const n1 = asciiToBase16(hex.charCodeAt(hi));
@@ -6118,7 +6176,7 @@ function hexToBytes(hex) {
6118
6176
  const char = hex[hi] + hex[hi + 1];
6119
6177
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
6120
6178
  }
6121
- array[ai] = n1 * 16 + n2;
6179
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
6122
6180
  }
6123
6181
  return array;
6124
6182
  }
@@ -6156,7 +6214,7 @@ function ensureBytes(title, hex, expectedLength) {
6156
6214
  res = hexToBytes(hex);
6157
6215
  }
6158
6216
  catch (e) {
6159
- 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);
6160
6218
  }
6161
6219
  }
6162
6220
  else if (isBytes$1(hex)) {
@@ -6165,11 +6223,11 @@ function ensureBytes(title, hex, expectedLength) {
6165
6223
  res = Uint8Array.from(hex);
6166
6224
  }
6167
6225
  else {
6168
- throw new Error(`${title} must be hex string or Uint8Array`);
6226
+ throw new Error(title + ' must be hex string or Uint8Array');
6169
6227
  }
6170
6228
  const len = res.length;
6171
6229
  if (typeof expectedLength === 'number' && len !== expectedLength)
6172
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
6230
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
6173
6231
  return res;
6174
6232
  }
6175
6233
  /**
@@ -6204,7 +6262,7 @@ function equalBytes(a, b) {
6204
6262
  */
6205
6263
  function utf8ToBytes(str) {
6206
6264
  if (typeof str !== 'string')
6207
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6265
+ throw new Error('string expected');
6208
6266
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6209
6267
  }
6210
6268
  // Is positive bigint
@@ -6224,7 +6282,7 @@ function aInRange(title, n, min, max) {
6224
6282
  // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
6225
6283
  // - our way is the cleanest: `inRange('x', x, 0n, P)
6226
6284
  if (!inRange(n, min, max))
6227
- 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);
6228
6286
  }
6229
6287
  // Bit operations
6230
6288
  /**
@@ -6334,12 +6392,12 @@ function validateObject(object, validators, optValidators = {}) {
6334
6392
  const checkField = (fieldName, type, isOptional) => {
6335
6393
  const checkVal = validatorFns[type];
6336
6394
  if (typeof checkVal !== 'function')
6337
- throw new Error(`Invalid validator "${type}", expected function`);
6395
+ throw new Error('invalid validator function');
6338
6396
  const val = object[fieldName];
6339
6397
  if (isOptional && val === undefined)
6340
6398
  return;
6341
6399
  if (!checkVal(val, object)) {
6342
- 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);
6343
6401
  }
6344
6402
  };
6345
6403
  for (const [fieldName, type] of Object.entries(validators))
@@ -6408,14 +6466,17 @@ var ut = /*#__PURE__*/Object.freeze({
6408
6466
  validateObject: validateObject
6409
6467
  });
6410
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
+ */
6411
6475
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6412
- // Utilities for modular arithmetics and finite fields
6413
6476
  // prettier-ignore
6414
- 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);
6415
6478
  // prettier-ignore
6416
- const _4n = BigInt(4), _5n$1 = BigInt(5), _8n$2 = BigInt(8);
6417
- // prettier-ignore
6418
- BigInt(9); BigInt(16);
6479
+ const _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _8n$2 = /* @__PURE__ */ BigInt(8);
6419
6480
  // Calculates a modulo b
6420
6481
  function mod(a, b) {
6421
6482
  const result = a % b;
@@ -6424,13 +6485,15 @@ function mod(a, b) {
6424
6485
  /**
6425
6486
  * Efficiently raise num to power and do modular division.
6426
6487
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
6488
+ * @todo use field version && remove
6427
6489
  * @example
6428
6490
  * pow(2n, 6n, 11n) // 64n % 11n == 9n
6429
6491
  */
6430
- // TODO: use field version && remove
6431
6492
  function pow(num, power, modulo) {
6432
- if (modulo <= _0n$3 || power < _0n$3)
6433
- 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');
6434
6497
  if (modulo === _1n$5)
6435
6498
  return _0n$3;
6436
6499
  let res = _1n$5;
@@ -6442,7 +6505,7 @@ function pow(num, power, modulo) {
6442
6505
  }
6443
6506
  return res;
6444
6507
  }
6445
- // 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)` */
6446
6509
  function pow2(x, power, modulo) {
6447
6510
  let res = x;
6448
6511
  while (power-- > _0n$3) {
@@ -6451,12 +6514,15 @@ function pow2(x, power, modulo) {
6451
6514
  }
6452
6515
  return res;
6453
6516
  }
6454
- // Inverses number over modulo
6517
+ /**
6518
+ * Inverses number over modulo.
6519
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
6520
+ */
6455
6521
  function invert(number, modulo) {
6456
- if (number === _0n$3 || modulo <= _0n$3) {
6457
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
6458
- }
6459
- // 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);
6460
6526
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
6461
6527
  let a = mod(number, modulo);
6462
6528
  let b = modulo;
@@ -6496,8 +6562,11 @@ function tonelliShanks(P) {
6496
6562
  for (Q = P - _1n$5, S = 0; Q % _2n$3 === _0n$3; Q /= _2n$3, S++)
6497
6563
  ;
6498
6564
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
6499
- for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$5; Z++)
6500
- ;
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
+ }
6501
6570
  // Fast-path
6502
6571
  if (S === 1) {
6503
6572
  const p1div4 = (P + _1n$5) / _4n;
@@ -6539,9 +6608,18 @@ function tonelliShanks(P) {
6539
6608
  return x;
6540
6609
  };
6541
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
+ */
6542
6622
  function FpSqrt(P) {
6543
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
6544
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
6545
6623
  // P ≡ 3 (mod 4)
6546
6624
  // √n = n^((P+1)/4)
6547
6625
  if (P % _4n === _3n$1) {
@@ -6605,7 +6683,7 @@ function FpPow(f, num, power) {
6605
6683
  // Should have same speed as pow for bigints
6606
6684
  // TODO: benchmark!
6607
6685
  if (power < _0n$3)
6608
- throw new Error('Expected power > 0');
6686
+ throw new Error('invalid exponent, negatives unsupported');
6609
6687
  if (power === _0n$3)
6610
6688
  return f.ONE;
6611
6689
  if (power === _1n$5)
@@ -6652,15 +6730,15 @@ function nLength(n, nBitLength) {
6652
6730
  return { nBitLength: _nBitLength, nByteLength };
6653
6731
  }
6654
6732
  /**
6655
- * Initializes a finite field over prime. **Non-primes are not supported.**
6656
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
6733
+ * Initializes a finite field over prime.
6657
6734
  * Major performance optimizations:
6658
6735
  * * a) denormalized operations like mulN instead of mul
6659
6736
  * * b) same object shape: never add or remove keys
6660
6737
  * * c) Object.freeze
6661
- * 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,
6662
6740
  * it is caller responsibility to check this.
6663
- * 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.
6664
6742
  * @param ORDER prime positive bigint
6665
6743
  * @param bitLen how many bits the field consumes
6666
6744
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -6668,13 +6746,14 @@ function nLength(n, nBitLength) {
6668
6746
  */
6669
6747
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
6670
6748
  if (ORDER <= _0n$3)
6671
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
6749
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
6672
6750
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
6673
6751
  if (BYTES > 2048)
6674
- throw new Error('Field lengths over 2048 bytes are not supported');
6675
- const sqrtP = FpSqrt(ORDER);
6752
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
6753
+ let sqrtP; // cached sqrtP
6676
6754
  const f = Object.freeze({
6677
6755
  ORDER,
6756
+ isLE,
6678
6757
  BITS,
6679
6758
  BYTES,
6680
6759
  MASK: bitMask(BITS),
@@ -6683,7 +6762,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6683
6762
  create: (num) => mod(num, ORDER),
6684
6763
  isValid: (num) => {
6685
6764
  if (typeof num !== 'bigint')
6686
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
6765
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
6687
6766
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
6688
6767
  },
6689
6768
  is0: (num) => num === _0n$3,
@@ -6702,7 +6781,12 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6702
6781
  subN: (lhs, rhs) => lhs - rhs,
6703
6782
  mulN: (lhs, rhs) => lhs * rhs,
6704
6783
  inv: (num) => invert(num, ORDER),
6705
- 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
+ }),
6706
6790
  invertBatch: (lst) => FpInvertBatch(f, lst),
6707
6791
  // TODO: do we really need constant cmov?
6708
6792
  // We don't have const-time bigints anyway, so probably will be not very useful
@@ -6710,7 +6794,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
6710
6794
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
6711
6795
  fromBytes: (bytes) => {
6712
6796
  if (bytes.length !== BYTES)
6713
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
6797
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
6714
6798
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
6715
6799
  },
6716
6800
  });
@@ -6758,52 +6842,80 @@ function mapHashToField(key, fieldOrder, isLE = false) {
6758
6842
  const minLen = getMinHashLength(fieldOrder);
6759
6843
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
6760
6844
  if (len < 16 || len < minLen || len > 1024)
6761
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
6762
- 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);
6763
6847
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
6764
6848
  const reduced = mod(num, fieldOrder - _1n$5) + _1n$5;
6765
6849
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
6766
6850
  }
6767
6851
 
6852
+ /**
6853
+ * Methods for elliptic curve multiplication by scalars.
6854
+ * Contains wNAF, pippenger
6855
+ * @module
6856
+ */
6768
6857
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6769
- // Abelian group utilities
6770
6858
  const _0n$2 = BigInt(0);
6771
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
+ }
6772
6890
  // Since points in different groups cannot be equal (different object constructor),
6773
6891
  // we can have single place to store precomputes
6774
6892
  const pointPrecomputes = new WeakMap();
6775
6893
  const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
6776
- // Elliptic curve multiplication of Point by scalar. Fragile.
6777
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
6778
- // Creates precomputation tables for fast multiplication:
6779
- // - private scalar is split by fixed size windows of W bits
6780
- // - every window point is collected from window's table & added to accumulator
6781
- // - since windows are different, same point inside tables won't be accessed more than once per calc
6782
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
6783
- // - +1 window is neccessary for wNAF
6784
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
6785
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
6786
- // 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
+ */
6787
6911
  function wNAF(c, bits) {
6788
- const constTimeNegate = (condition, item) => {
6789
- const neg = item.negate();
6790
- return condition ? neg : item;
6791
- };
6792
- const validateW = (W) => {
6793
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
6794
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
6795
- };
6796
- const opts = (W) => {
6797
- validateW(W);
6798
- const windows = Math.ceil(bits / W) + 1; // +1, because
6799
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
6800
- return { windows, windowSize };
6801
- };
6802
6912
  return {
6803
6913
  constTimeNegate,
6914
+ hasPrecomputes(elm) {
6915
+ return getW(elm) !== 1;
6916
+ },
6804
6917
  // non-const time multiplication ladder
6805
- unsafeLadder(elm, n) {
6806
- let p = c.ZERO;
6918
+ unsafeLadder(elm, n, p = c.ZERO) {
6807
6919
  let d = elm;
6808
6920
  while (n > _0n$2) {
6809
6921
  if (n & _1n$4)
@@ -6821,10 +6933,12 @@ function wNAF(c, bits) {
6821
6933
  * - 𝑊 is the window size
6822
6934
  * - 𝑛 is the bitlength of the curve order.
6823
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
6824
6938
  * @returns precomputed point tables flattened to a single array
6825
6939
  */
6826
6940
  precomputeWindow(elm, W) {
6827
- const { windows, windowSize } = opts(W);
6941
+ const { windows, windowSize } = calcWOpts(W, bits);
6828
6942
  const points = [];
6829
6943
  let p = elm;
6830
6944
  let base = p;
@@ -6850,7 +6964,7 @@ function wNAF(c, bits) {
6850
6964
  wNAF(W, precomputes, n) {
6851
6965
  // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
6852
6966
  // But need to carefully remove other checks before wNAF. ORDER == bits here
6853
- const { windows, windowSize } = opts(W);
6967
+ const { windows, windowSize } = calcWOpts(W, bits);
6854
6968
  let p = c.ZERO;
6855
6969
  let f = c.BASE;
6856
6970
  const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
@@ -6894,8 +7008,44 @@ function wNAF(c, bits) {
6894
7008
  // which makes it less const-time: around 1 bigint multiply.
6895
7009
  return { p, f };
6896
7010
  },
6897
- wNAFCached(P, n, transform) {
6898
- 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) {
6899
7049
  // Calculate precomputes on a first run, reuse them after
6900
7050
  let comp = pointPrecomputes.get(P);
6901
7051
  if (!comp) {
@@ -6903,62 +7053,66 @@ function wNAF(c, bits) {
6903
7053
  if (W !== 1)
6904
7054
  pointPrecomputes.set(P, transform(comp));
6905
7055
  }
6906
- 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);
6907
7067
  },
6908
7068
  // We calculate precomputes for elliptic curve point multiplication
6909
7069
  // using windowed method. This specifies window size and
6910
7070
  // stores precomputed values. Usually only base point would be precomputed.
6911
7071
  setWindowSize(P, W) {
6912
- validateW(W);
7072
+ validateW(W, bits);
6913
7073
  pointWindowSizes.set(P, W);
6914
7074
  pointPrecomputes.delete(P);
6915
7075
  },
6916
7076
  };
6917
7077
  }
6918
7078
  /**
6919
- * Pippenger algorithm for multi-scalar multiplication (MSM).
6920
- * MSM is basically (Pa + Qb + Rc + ...).
7079
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
6921
7080
  * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
6922
7081
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
6923
7082
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
6924
7083
  * @param c Curve Point constructor
6925
- * @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
6926
7085
  * @param points array of L curve points
6927
7086
  * @param scalars array of L scalars (aka private keys / bigints)
6928
7087
  */
6929
- function pippenger(c, field, points, scalars) {
7088
+ function pippenger(c, fieldN, points, scalars) {
6930
7089
  // If we split scalars by some window (let's say 8 bits), every chunk will only
6931
7090
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
6932
7091
  // TODO:
6933
7092
  // - https://eprint.iacr.org/2024/750.pdf
6934
7093
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
6935
7094
  // 0 is accepted in scalars
6936
- 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)
6937
7098
  throw new Error('arrays of points and scalars must have equal length');
6938
- scalars.forEach((s, i) => {
6939
- if (!field.isValid(s))
6940
- throw new Error(`wrong scalar at index ${i}`);
6941
- });
6942
- points.forEach((p, i) => {
6943
- if (!(p instanceof c))
6944
- throw new Error(`wrong point at index ${i}`);
6945
- });
7099
+ const zero = c.ZERO;
6946
7100
  const wbits = bitLen(BigInt(points.length));
6947
7101
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
6948
7102
  const MASK = (1 << windowSize) - 1;
6949
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
6950
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
6951
- 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;
6952
7106
  for (let i = lastBits; i >= 0; i -= windowSize) {
6953
- buckets.fill(c.ZERO);
7107
+ buckets.fill(zero);
6954
7108
  for (let j = 0; j < scalars.length; j++) {
6955
7109
  const scalar = scalars[j];
6956
7110
  const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
6957
7111
  buckets[wbits] = buckets[wbits].add(points[j]);
6958
7112
  }
6959
- 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
6960
7114
  // Skip first bucket, because it is zero
6961
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
7115
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
6962
7116
  sumI = sumI.add(buckets[j]);
6963
7117
  resI = resI.add(sumI);
6964
7118
  }
@@ -6988,8 +7142,12 @@ function validateBasic(curve) {
6988
7142
  });
6989
7143
  }
6990
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
+ */
6991
7150
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6992
- // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
6993
7151
  // Be friendly to bad ECMAScript parsers by not using bigint literals
6994
7152
  // prettier-ignore
6995
7153
  const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
@@ -7021,6 +7179,10 @@ function validateOpts$1(curve) {
7021
7179
  function twistedEdwards(curveDef) {
7022
7180
  const CURVE = validateOpts$1(curveDef);
7023
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.
7024
7186
  const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
7025
7187
  const modP = Fp.create; // Function overrides
7026
7188
  const Fn = Field(CURVE.n, CURVE.nBitLength);
@@ -7234,16 +7396,15 @@ function twistedEdwards(curveDef) {
7234
7396
  // It's faster, but should only be used when you don't care about
7235
7397
  // an exposed private key e.g. sig verification.
7236
7398
  // Does NOT allow scalars higher than CURVE.n.
7237
- multiplyUnsafe(scalar) {
7399
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
7400
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
7238
7401
  const n = scalar;
7239
7402
  aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L
7240
7403
  if (n === _0n$1)
7241
7404
  return I;
7242
- if (this.equals(I) || n === _1n$3)
7405
+ if (this.is0() || n === _1n$3)
7243
7406
  return this;
7244
- if (this.equals(G))
7245
- return this.wNAF(n).p;
7246
- return wnaf.unsafeLadder(this, n);
7407
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
7247
7408
  }
7248
7409
  // Checks if point is of small order.
7249
7410
  // If you add something to small order point, you will have "dirty"
@@ -7277,8 +7438,9 @@ function twistedEdwards(curveDef) {
7277
7438
  abool('zip215', zip215);
7278
7439
  const normed = hex.slice(); // copy again, we'll manipulate it
7279
7440
  const lastByte = hex[len - 1]; // select last byte
7280
- normed[len - 1] = lastByte & ~0x80; // clear last bit
7441
+ normed[len - 1] = lastByte & -129; // clear last bit
7281
7442
  const y = bytesToNumberLE(normed);
7443
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
7282
7444
  // RFC8032 prohibits >= p, but ZIP215 doesn't
7283
7445
  // zip215=true: 0 <= y < MASK (2^256 for ed25519)
7284
7446
  // zip215=false: 0 <= y < P (2^255-19 for ed25519)
@@ -7327,7 +7489,7 @@ function twistedEdwards(curveDef) {
7327
7489
  }
7328
7490
  /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
7329
7491
  function getExtendedPublicKey(key) {
7330
- const len = nByteLength;
7492
+ const len = Fp.BYTES;
7331
7493
  key = ensureBytes('private key', key, len);
7332
7494
  // Hash private key with curve's hash function to produce uniformingly random input
7333
7495
  // Check byte lengths: ensure(64, h(ensure(32, key)))
@@ -7360,23 +7522,29 @@ function twistedEdwards(curveDef) {
7360
7522
  const s = modN(r + k * scalar); // S = (r + k * s) mod L
7361
7523
  aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l
7362
7524
  const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));
7363
- return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
7525
+ return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature
7364
7526
  }
7365
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
+ */
7366
7532
  function verify(sig, msg, publicKey, options = verifyOpts) {
7367
7533
  const { context, zip215 } = options;
7368
7534
  const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
7369
7535
  sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
7370
7536
  msg = ensureBytes('message', msg);
7537
+ publicKey = ensureBytes('publicKey', publicKey, len);
7371
7538
  if (zip215 !== undefined)
7372
7539
  abool('zip215', zip215);
7373
7540
  if (prehash)
7374
7541
  msg = prehash(msg); // for ed25519ph, etc
7375
7542
  const s = bytesToNumberLE(sig.slice(len, 2 * len));
7376
- // zip215: true is good for consensus-critical apps and allows points < 2^256
7377
- // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
7378
7543
  let A, R, SB;
7379
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)
7380
7548
  A = Point.fromHex(publicKey, zip215);
7381
7549
  R = Point.fromHex(sig.slice(0, len), zip215);
7382
7550
  SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
@@ -7388,6 +7556,7 @@ function twistedEdwards(curveDef) {
7388
7556
  return false;
7389
7557
  const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
7390
7558
  const RkA = R.add(A.multiplyUnsafe(k));
7559
+ // Extended group equation
7391
7560
  // [8][S]B = [8]R + [8][k]A'
7392
7561
  return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
7393
7562
  }
@@ -7418,13 +7587,14 @@ function twistedEdwards(curveDef) {
7418
7587
  };
7419
7588
  }
7420
7589
 
7421
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7422
7590
  /**
7423
7591
  * ed25519 Twisted Edwards curve with following addons:
7424
7592
  * - X25519 ECDH
7425
7593
  * - Ristretto cofactor elimination
7426
7594
  * - Elligator hash-to-group / point indistinguishability
7595
+ * @module
7427
7596
  */
7597
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7428
7598
  const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
7429
7599
  // √(-1) aka √(a) aka 2^((p-1)/4)
7430
7600
  const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
@@ -7483,7 +7653,7 @@ function uvRatio(u, v) {
7483
7653
  x = mod(-x, P);
7484
7654
  return { isValid: useRoot1 || useRoot2, value: x };
7485
7655
  }
7486
- const Fp$1 = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7656
+ const Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();
7487
7657
  const ed25519Defaults = /* @__PURE__ */ (() => ({
7488
7658
  // Param: a
7489
7659
  a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
@@ -7491,7 +7661,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7491
7661
  // Negative number is P - number, and division is invert(number, P)
7492
7662
  d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
7493
7663
  // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
7494
- Fp: Fp$1,
7664
+ Fp,
7495
7665
  // Subgroup order: how many points curve has
7496
7666
  // 2n**252n + 27742317777372353535851937790883648493n;
7497
7667
  n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
@@ -7510,6 +7680,14 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7510
7680
  }))();
7511
7681
  /**
7512
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
7513
7691
  */
7514
7692
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7515
7693
 
@@ -8883,7 +9061,7 @@ var PrivateKey;
8883
9061
  /*!
8884
9062
  * MIT License
8885
9063
  *
8886
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9064
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
8887
9065
  *
8888
9066
  * Permission is hereby granted, free of charge, to any person obtaining a copy
8889
9067
  * of this software and associated documentation files (the "Software"), to deal
@@ -8995,7 +9173,7 @@ class BufferSourceConverter {
8995
9173
  }
8996
9174
 
8997
9175
  const STRING_TYPE = "string";
8998
- const HEX_REGEX = /^[0-9a-f]+$/i;
9176
+ const HEX_REGEX = /^[0-9a-f\s]+$/i;
8999
9177
  const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
9000
9178
  const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
9001
9179
  class Utf8Converter {
@@ -9229,7 +9407,7 @@ class Convert {
9229
9407
  return base64;
9230
9408
  }
9231
9409
  static formatString(data) {
9232
- 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, "")) || "";
9233
9411
  }
9234
9412
  }
9235
9413
  Convert.DEFAULT_UTF8_ENCODING = "utf8";
@@ -9485,7 +9663,7 @@ function HexBlock(BaseClass) {
9485
9663
  var _a;
9486
9664
  super(...args);
9487
9665
  const params = args[0] || {};
9488
- this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
9666
+ this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== undefined ? _a : false;
9489
9667
  this.valueHexView = params.valueHex ? BufferSourceConverter_1.toUint8Array(params.valueHex) : EMPTY_VIEW;
9490
9668
  }
9491
9669
  get valueHex() {
@@ -9575,11 +9753,11 @@ class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
9575
9753
  var _a, _b, _c, _d;
9576
9754
  super();
9577
9755
  if (idBlock) {
9578
- this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
9756
+ this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== undefined ? _a : false;
9579
9757
  this.valueHexView = idBlock.valueHex ? BufferSourceConverter_1.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
9580
- this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
9581
- this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
9582
- 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;
9583
9761
  }
9584
9762
  else {
9585
9763
  this.tagClass = -1;
@@ -9746,9 +9924,9 @@ class LocalLengthBlock extends LocalBaseBlock {
9746
9924
  constructor({ lenBlock = {}, } = {}) {
9747
9925
  var _a, _b, _c;
9748
9926
  super();
9749
- this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
9750
- this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
9751
- 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;
9752
9930
  }
9753
9931
  fromBER(inputBuffer, inputOffset, inputLength) {
9754
9932
  const view = BufferSourceConverter_1.toUint8Array(inputBuffer);
@@ -10520,7 +10698,7 @@ var _a$r;
10520
10698
  class OctetString extends BaseBlock {
10521
10699
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10522
10700
  var _b, _c;
10523
- (_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));
10524
10702
  super({
10525
10703
  idBlock: {
10526
10704
  isConstructed: parameters.isConstructed,
@@ -10681,7 +10859,7 @@ var _a$q;
10681
10859
  class BitString extends BaseBlock {
10682
10860
  constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
10683
10861
  var _b, _c;
10684
- (_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));
10685
10863
  super({
10686
10864
  idBlock: {
10687
10865
  isConstructed: parameters.isConstructed,
@@ -11883,7 +12061,7 @@ class GeneralizedTime extends UTCTime {
11883
12061
  constructor(parameters = {}) {
11884
12062
  var _b;
11885
12063
  super(parameters);
11886
- (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
12064
+ (_b = this.millisecond) !== null && _b !== undefined ? _b : (this.millisecond = 0);
11887
12065
  this.idBlock.tagClass = 1;
11888
12066
  this.idBlock.tagNumber = 24;
11889
12067
  }
@@ -12234,8 +12412,8 @@ function pkixToJwk(bytes) {
12234
12412
  const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12235
12413
  return {
12236
12414
  kty: 'RSA',
12237
- n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
12238
- e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
12415
+ n: asn1jsIntegerToBase64(values[0]),
12416
+ e: asn1jsIntegerToBase64(values[1])
12239
12417
  };
12240
12418
  }
12241
12419
  /**
@@ -12271,21 +12449,13 @@ function jwkToPkix(jwk) {
12271
12449
  const der = root.toBER();
12272
12450
  return new Uint8Array(der, 0, der.byteLength);
12273
12451
  }
12274
- function bnToBuf(bn) {
12275
- let hex = bn.toString(16);
12276
- if (hex.length % 2 > 0) {
12277
- hex = `0${hex}`;
12278
- }
12279
- const len = hex.length / 2;
12280
- const u8 = new Uint8Array(len);
12281
- let i = 0;
12282
- let j = 0;
12283
- while (i < len) {
12284
- u8[i] = parseInt(hex.slice(j, j + 2), 16);
12285
- i += 1;
12286
- j += 2;
12452
+ function asn1jsIntegerToBase64(int) {
12453
+ let buf = int.valueBlock.valueHexView;
12454
+ // chrome rejects values with leading 0s
12455
+ while (buf[0] === 0) {
12456
+ buf = buf.subarray(1);
12287
12457
  }
12288
- return u8;
12458
+ return toString$1(buf, 'base64url');
12289
12459
  }
12290
12460
  function bufToBn(u8) {
12291
12461
  const hex = [];
@@ -12314,15 +12484,18 @@ function pkixToRSAPublicKey(bytes) {
12314
12484
  return new RSAPublicKey(jwk, digest);
12315
12485
  }
12316
12486
 
12317
- // HMAC (RFC 2104)
12487
+ /**
12488
+ * HMAC: RFC2104 message authentication code.
12489
+ * @module
12490
+ */
12318
12491
  class HMAC extends Hash {
12319
- constructor(hash$1, _key) {
12492
+ constructor(hash, _key) {
12320
12493
  super();
12321
12494
  this.finished = false;
12322
12495
  this.destroyed = false;
12323
- hash(hash$1);
12496
+ ahash(hash);
12324
12497
  const key = toBytes$1(_key);
12325
- this.iHash = hash$1.create();
12498
+ this.iHash = hash.create();
12326
12499
  if (typeof this.iHash.update !== 'function')
12327
12500
  throw new Error('Expected instance of class which extends utils.Hash');
12328
12501
  this.blockLen = this.iHash.blockLen;
@@ -12330,12 +12503,12 @@ class HMAC extends Hash {
12330
12503
  const blockLen = this.blockLen;
12331
12504
  const pad = new Uint8Array(blockLen);
12332
12505
  // blockLen can be bigger than outputLen
12333
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12506
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
12334
12507
  for (let i = 0; i < pad.length; i++)
12335
12508
  pad[i] ^= 0x36;
12336
12509
  this.iHash.update(pad);
12337
12510
  // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12338
- this.oHash = hash$1.create();
12511
+ this.oHash = hash.create();
12339
12512
  // Undo internal XOR && apply outer XOR
12340
12513
  for (let i = 0; i < pad.length; i++)
12341
12514
  pad[i] ^= 0x36 ^ 0x5c;
@@ -12343,13 +12516,13 @@ class HMAC extends Hash {
12343
12516
  pad.fill(0);
12344
12517
  }
12345
12518
  update(buf) {
12346
- exists(this);
12519
+ aexists(this);
12347
12520
  this.iHash.update(buf);
12348
12521
  return this;
12349
12522
  }
12350
12523
  digestInto(out) {
12351
- exists(this);
12352
- bytes(out, this.outputLen);
12524
+ aexists(this);
12525
+ abytes$1(out, this.outputLen);
12353
12526
  this.finished = true;
12354
12527
  this.iHash.digestInto(out);
12355
12528
  this.oHash.update(out);
@@ -12393,8 +12566,33 @@ class HMAC extends Hash {
12393
12566
  const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12394
12567
  hmac.create = (hash, key) => new HMAC(hash, key);
12395
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
+ */
12396
12595
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12397
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
12398
12596
  function validateSigVerOpts(opts) {
12399
12597
  if (opts.lowS !== undefined)
12400
12598
  abool('lowS', opts.lowS);
@@ -12418,17 +12616,22 @@ function validatePointOpts(curve) {
12418
12616
  const { endo, Fp, a } = opts;
12419
12617
  if (endo) {
12420
12618
  if (!Fp.eql(a, Fp.ZERO)) {
12421
- 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');
12422
12620
  }
12423
12621
  if (typeof endo !== 'object' ||
12424
12622
  typeof endo.beta !== 'bigint' ||
12425
12623
  typeof endo.splitScalar !== 'function') {
12426
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
12624
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
12427
12625
  }
12428
12626
  }
12429
12627
  return Object.freeze({ ...opts });
12430
12628
  }
12431
12629
  const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12630
+ class DERErr extends Error {
12631
+ constructor(m = '') {
12632
+ super(m);
12633
+ }
12634
+ }
12432
12635
  /**
12433
12636
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
12434
12637
  *
@@ -12438,11 +12641,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12438
12641
  */
12439
12642
  const DER = {
12440
12643
  // asn.1 DER encoding utils
12441
- Err: class DERErr extends Error {
12442
- constructor(m = '') {
12443
- super(m);
12444
- }
12445
- },
12644
+ Err: DERErr,
12446
12645
  // Basic building block is TLV (Tag-Length-Value)
12447
12646
  _tlv: {
12448
12647
  encode: (tag, data) => {
@@ -12457,7 +12656,8 @@ const DER = {
12457
12656
  throw new E('tlv.encode: long form length too big');
12458
12657
  // length of length with long form flag
12459
12658
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
12460
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
12659
+ const t = numberToHexUnpadded(tag);
12660
+ return t + lenLen + len + data;
12461
12661
  },
12462
12662
  // v - value, l - left bytes (unparsed)
12463
12663
  decode(tag, data) {
@@ -12510,15 +12710,15 @@ const DER = {
12510
12710
  if (Number.parseInt(hex[0], 16) & 0b1000)
12511
12711
  hex = '00' + hex;
12512
12712
  if (hex.length & 1)
12513
- throw new E('unexpected assertion');
12713
+ throw new E('unexpected DER parsing assertion: unpadded hex');
12514
12714
  return hex;
12515
12715
  },
12516
12716
  decode(data) {
12517
12717
  const { Err: E } = DER;
12518
12718
  if (data[0] & 128)
12519
- throw new E('Invalid signature integer: negative');
12719
+ throw new E('invalid signature integer: negative');
12520
12720
  if (data[0] === 0x00 && !(data[1] & 128))
12521
- throw new E('Invalid signature integer: unnecessary leading zero');
12721
+ throw new E('invalid signature integer: unnecessary leading zero');
12522
12722
  return b2n(data);
12523
12723
  },
12524
12724
  },
@@ -12529,16 +12729,18 @@ const DER = {
12529
12729
  abytes(data);
12530
12730
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
12531
12731
  if (seqLeftBytes.length)
12532
- throw new E('Invalid signature: left bytes after parsing');
12732
+ throw new E('invalid signature: left bytes after parsing');
12533
12733
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
12534
12734
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
12535
12735
  if (sLeftBytes.length)
12536
- throw new E('Invalid signature: left bytes after parsing');
12736
+ throw new E('invalid signature: left bytes after parsing');
12537
12737
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
12538
12738
  },
12539
12739
  hexFromSig(sig) {
12540
12740
  const { _tlv: tlv, _int: int } = DER;
12541
- 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;
12542
12744
  return tlv.encode(0x30, seq);
12543
12745
  },
12544
12746
  };
@@ -12592,7 +12794,7 @@ function weierstrassPoints(opts) {
12592
12794
  key = bytesToHex(key);
12593
12795
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
12594
12796
  if (typeof key !== 'string' || !lengths.includes(key.length))
12595
- throw new Error('Invalid key');
12797
+ throw new Error('invalid private key');
12596
12798
  key = key.padStart(nByteLength * 2, '0');
12597
12799
  }
12598
12800
  let num;
@@ -12603,7 +12805,7 @@ function weierstrassPoints(opts) {
12603
12805
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
12604
12806
  }
12605
12807
  catch (error) {
12606
- 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);
12607
12809
  }
12608
12810
  if (wrapPrivateKey)
12609
12811
  num = mod(num, N); // disabled by default, enabled for BLS
@@ -12643,7 +12845,7 @@ function weierstrassPoints(opts) {
12643
12845
  if (p.is0()) {
12644
12846
  // (0, 1, 0) aka ZERO is invalid in most contexts.
12645
12847
  // In BLS, ZERO can be serialized, so we allow it.
12646
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
12848
+ // (0, 0, 0) is invalid representation of ZERO.
12647
12849
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
12648
12850
  return;
12649
12851
  throw new Error('bad point: ZERO');
@@ -12867,16 +13069,17 @@ function weierstrassPoints(opts) {
12867
13069
  * an exposed private key e.g. sig verification, which works over *public* keys.
12868
13070
  */
12869
13071
  multiplyUnsafe(sc) {
12870
- aInRange('scalar', sc, _0n, CURVE.n);
13072
+ const { endo, n: N } = CURVE;
13073
+ aInRange('scalar', sc, _0n, N);
12871
13074
  const I = Point.ZERO;
12872
13075
  if (sc === _0n)
12873
13076
  return I;
12874
- if (sc === _1n$1)
13077
+ if (this.is0() || sc === _1n$1)
12875
13078
  return this;
12876
- const { endo } = CURVE;
12877
- if (!endo)
12878
- return wnaf.unsafeLadder(this, sc);
12879
- // 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
12880
13083
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
12881
13084
  let k1p = I;
12882
13085
  let k2p = I;
@@ -13062,7 +13265,9 @@ function weierstrass(curveDef) {
13062
13265
  return { x, y };
13063
13266
  }
13064
13267
  else {
13065
- 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);
13066
13271
  }
13067
13272
  },
13068
13273
  });
@@ -13227,6 +13432,9 @@ function weierstrass(curveDef) {
13227
13432
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
13228
13433
  const bits2int = CURVE.bits2int ||
13229
13434
  function (bytes) {
13435
+ // Our custom check "just in case"
13436
+ if (bytes.length > 8192)
13437
+ throw new Error('input is too large');
13230
13438
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
13231
13439
  // for some cases, since bytes.length * 8 is not actual bitLength.
13232
13440
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -13243,15 +13451,15 @@ function weierstrass(curveDef) {
13243
13451
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
13244
13452
  */
13245
13453
  function int2octets(num) {
13246
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
13454
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
13247
13455
  // works with order, can have different size than numToField!
13248
13456
  return numberToBytesBE(num, CURVE.nByteLength);
13249
13457
  }
13250
13458
  // Steps A, D of RFC6979 3.2
13251
13459
  // Creates RFC6979 seed; converts msg/privKey to numbers.
13252
13460
  // Used only in sign, not in verify.
13253
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
13254
- // 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
13255
13463
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
13256
13464
  if (['recovered', 'canonical'].some((k) => k in opts))
13257
13465
  throw new Error('sign() legacy options not supported');
@@ -13345,39 +13553,48 @@ function weierstrass(curveDef) {
13345
13553
  const sg = signature;
13346
13554
  msgHash = ensureBytes('msgHash', msgHash);
13347
13555
  publicKey = ensureBytes('publicKey', publicKey);
13556
+ const { lowS, prehash, format } = opts;
13557
+ // Verify opts, deduce signature format
13558
+ validateSigVerOpts(opts);
13348
13559
  if ('strict' in opts)
13349
13560
  throw new Error('options.strict was renamed to lowS');
13350
- validateSigVerOpts(opts);
13351
- 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');
13352
13572
  let _sig = undefined;
13353
13573
  let P;
13354
13574
  try {
13355
- if (typeof sg === 'string' || isBytes$1(sg)) {
13575
+ if (isObj)
13576
+ _sig = new Signature(sg.r, sg.s);
13577
+ if (isHex) {
13356
13578
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
13357
13579
  // Since DER can also be 2*nByteLength bytes, we check for it first.
13358
13580
  try {
13359
- _sig = Signature.fromDER(sg);
13581
+ if (format !== 'compact')
13582
+ _sig = Signature.fromDER(sg);
13360
13583
  }
13361
13584
  catch (derError) {
13362
13585
  if (!(derError instanceof DER.Err))
13363
13586
  throw derError;
13364
- _sig = Signature.fromCompact(sg);
13365
13587
  }
13366
- }
13367
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
13368
- const { r, s } = sg;
13369
- _sig = new Signature(r, s);
13370
- }
13371
- else {
13372
- throw new Error('PARSE');
13588
+ if (!_sig && format !== 'der')
13589
+ _sig = Signature.fromCompact(sg);
13373
13590
  }
13374
13591
  P = Point.fromHex(publicKey);
13375
13592
  }
13376
13593
  catch (error) {
13377
- if (error.message === 'PARSE')
13378
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
13379
13594
  return false;
13380
13595
  }
13596
+ if (!_sig)
13597
+ return false;
13381
13598
  if (lowS && _sig.hasHighS())
13382
13599
  return false;
13383
13600
  if (prehash)
@@ -13405,8 +13622,12 @@ function weierstrass(curveDef) {
13405
13622
  };
13406
13623
  }
13407
13624
 
13625
+ /**
13626
+ * Utilities for short weierstrass curves, combined with noble-hashes.
13627
+ * @module
13628
+ */
13408
13629
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13409
- // connects noble-curves to noble-hashes
13630
+ /** connects noble-curves to noble-hashes */
13410
13631
  function getHash(hash) {
13411
13632
  return {
13412
13633
  hash,
@@ -13416,9 +13637,21 @@ function getHash(hash) {
13416
13637
  }
13417
13638
  function createCurve(curveDef, defHash) {
13418
13639
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
13419
- return Object.freeze({ ...create(defHash), create });
13640
+ return { ...create(defHash), create };
13420
13641
  }
13421
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
+ */
13422
13655
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13423
13656
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
13424
13657
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -13449,31 +13682,35 @@ function sqrtMod(y) {
13449
13682
  const t1 = (pow2(b223, _23n, P) * b22) % P;
13450
13683
  const t2 = (pow2(t1, _6n, P) * b2) % P;
13451
13684
  const root = pow2(t2, _2n, P);
13452
- if (!Fp.eql(Fp.sqr(root), y))
13685
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
13453
13686
  throw new Error('Cannot find square root');
13454
13687
  return root;
13455
13688
  }
13456
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13689
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
13457
13690
  /**
13458
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;
13459
13701
  */
13460
13702
  const secp256k1 = createCurve({
13461
13703
  a: BigInt(0), // equation params: a, b
13462
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
13463
- 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
13464
13706
  n: secp256k1N, // Curve order, total count of valid points in the field
13465
13707
  // Base point (x, y) aka generator point
13466
13708
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
13467
13709
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
13468
13710
  h: BigInt(1), // Cofactor
13469
13711
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
13470
- /**
13471
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
13472
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
13473
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
13474
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
13475
- */
13476
13712
  endo: {
13713
+ // Endomorphism, see above
13477
13714
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
13478
13715
  splitScalar: (k) => {
13479
13716
  const n = secp256k1N;