@waku/enr 0.0.27-f599932.0 โ†’ 0.0.28-b6339f7.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
@@ -241,11 +241,12 @@ class Decoder {
241
241
  constructor(name, prefix, baseDecode) {
242
242
  this.name = name;
243
243
  this.prefix = prefix;
244
+ const prefixCodePoint = prefix.codePointAt(0);
244
245
  /* c8 ignore next 3 */
245
- if (prefix.codePointAt(0) === undefined) {
246
+ if (prefixCodePoint === undefined) {
246
247
  throw new Error('Invalid prefix character');
247
248
  }
248
- this.prefixCodePoint = prefix.codePointAt(0);
249
+ this.prefixCodePoint = prefixCodePoint;
249
250
  this.baseDecode = baseDecode;
250
251
  }
251
252
  decode(text) {
@@ -449,7 +450,14 @@ var base2$1 = /*#__PURE__*/Object.freeze({
449
450
 
450
451
  const alphabet = Array.from('๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚');
451
452
  const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
452
- const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));
453
+ const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
454
+ const codePoint = c.codePointAt(0);
455
+ if (codePoint == null) {
456
+ throw new Error(`Invalid character: ${c}`);
457
+ }
458
+ p[codePoint] = i;
459
+ return p;
460
+ }, ([])));
453
461
  function encode$4(data) {
454
462
  return data.reduce((p, c) => {
455
463
  p += alphabetBytesToChars[c];
@@ -459,8 +467,12 @@ function encode$4(data) {
459
467
  function decode$5(str) {
460
468
  const byts = [];
461
469
  for (const char of str) {
462
- const byt = alphabetCharsToBytes[char.codePointAt(0)];
463
- if (byt === undefined) {
470
+ const codePoint = char.codePointAt(0);
471
+ if (codePoint == null) {
472
+ throw new Error(`Invalid character: ${char}`);
473
+ }
474
+ const byt = alphabetCharsToBytes[codePoint];
475
+ if (byt == null) {
464
476
  throw new Error(`Non-base256emoji character: ${char}`);
465
477
  }
466
478
  byts.push(byt);
@@ -733,7 +745,7 @@ function encodingLength$1(int) {
733
745
  /**
734
746
  * Creates a multihash digest.
735
747
  */
736
- function create$1(code, digest) {
748
+ function create(code, digest) {
737
749
  const size = digest.byteLength;
738
750
  const sizeOffset = encodingLength$1(code);
739
751
  const digestOffset = sizeOffset + encodingLength$1(size);
@@ -792,7 +804,7 @@ const code = 0x0;
792
804
  const name = 'identity';
793
805
  const encode$2 = coerce;
794
806
  function digest(input) {
795
- return create$1(code, encode$2(input));
807
+ return create(code, encode$2(input));
796
808
  }
797
809
  const identity = { code, name, encode: encode$2, digest };
798
810
 
@@ -816,9 +828,9 @@ class Hasher {
816
828
  if (input instanceof Uint8Array) {
817
829
  const result = this.encode(input);
818
830
  return result instanceof Uint8Array
819
- ? create$1(this.code, result)
831
+ ? create(this.code, result)
820
832
  /* c8 ignore next 1 */
821
- : result.then(digest => create$1(this.code, digest));
833
+ : result.then(digest => create(this.code, digest));
822
834
  }
823
835
  else {
824
836
  throw Error('Unknown type, must be binary type');
@@ -918,7 +930,7 @@ class CID {
918
930
  switch (this.version) {
919
931
  case 0: {
920
932
  const { code, digest } = this.multihash;
921
- const multihash = create$1(code, digest);
933
+ const multihash = create(code, digest);
922
934
  return (CID.createV1(this.code, multihash));
923
935
  }
924
936
  case 1: {
@@ -1148,9 +1160,13 @@ function parseCIDtoBytes(source, base) {
1148
1160
  const decoder = base ?? base32;
1149
1161
  return [base32.prefix, decoder.decode(source)];
1150
1162
  }
1163
+ case base36.prefix: {
1164
+ const decoder = base ?? base36;
1165
+ return [base36.prefix, decoder.decode(source)];
1166
+ }
1151
1167
  default: {
1152
1168
  if (base == null) {
1153
- throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');
1169
+ throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
1154
1170
  }
1155
1171
  return [source[0], base.decode(source)];
1156
1172
  }
@@ -3056,7 +3072,7 @@ async function sign$1(message, privateKey) {
3056
3072
  function keccak256(input) {
3057
3073
  return new Uint8Array(sha3.keccak256.arrayBuffer(input));
3058
3074
  }
3059
- function compressPublicKey$1(publicKey) {
3075
+ function compressPublicKey(publicKey) {
3060
3076
  if (publicKey.length === 64) {
3061
3077
  publicKey = concat$2([new Uint8Array([4]), publicKey], 65);
3062
3078
  }
@@ -3125,23 +3141,6 @@ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLen
3125
3141
  // The rotate right (circular right shift) operation for uint32
3126
3142
  const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
3127
3143
  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3128
- // There is no setImmediate in browser and setTimeout is slow.
3129
- // call of async fn will return Promise, which will be fullfiled only on
3130
- // next scheduler queue processing step and this is exactly what we need.
3131
- const nextTick = async () => { };
3132
- // Returns control to thread each 'tick' ms to avoid blocking
3133
- async function asyncLoop(iters, tick, cb) {
3134
- let ts = Date.now();
3135
- for (let i = 0; i < iters; i++) {
3136
- cb(i);
3137
- // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
3138
- const diff = Date.now() - ts;
3139
- if (diff >= 0 && diff < tick)
3140
- continue;
3141
- await nextTick();
3142
- ts += diff;
3143
- }
3144
- }
3145
3144
  /**
3146
3145
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
3147
3146
  */
@@ -3186,13 +3185,6 @@ class Hash {
3186
3185
  return this._cloneInto();
3187
3186
  }
3188
3187
  }
3189
- const toStr = {}.toString;
3190
- function checkOpts(defaults, opts) {
3191
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
3192
- throw new Error('Options should be object or undefined');
3193
- const merged = Object.assign(defaults, opts);
3194
- return merged;
3195
- }
3196
3188
  function wrapConstructor(hashCons) {
3197
3189
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
3198
3190
  const tmp = hashCons();
@@ -3204,14 +3196,20 @@ function wrapConstructor(hashCons) {
3204
3196
  /**
3205
3197
  * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
3206
3198
  */
3207
- function randomBytes$1(bytesLength = 32) {
3199
+ function randomBytes(bytesLength = 32) {
3208
3200
  if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
3209
3201
  return crypto$1.getRandomValues(new Uint8Array(bytesLength));
3210
3202
  }
3203
+ // Legacy Node.js compatibility
3204
+ if (crypto$1 && typeof crypto$1.randomBytes === 'function') {
3205
+ return crypto$1.randomBytes(bytesLength);
3206
+ }
3211
3207
  throw new Error('crypto.getRandomValues must be defined');
3212
3208
  }
3213
3209
 
3214
- // Polyfill for Safari 14
3210
+ /**
3211
+ * Polyfill for Safari 14
3212
+ */
3215
3213
  function setBigUint64(view, byteOffset, value, isLE) {
3216
3214
  if (typeof view.setBigUint64 === 'function')
3217
3215
  return view.setBigUint64(byteOffset, value, isLE);
@@ -3224,9 +3222,13 @@ function setBigUint64(view, byteOffset, value, isLE) {
3224
3222
  view.setUint32(byteOffset + h, wh, isLE);
3225
3223
  view.setUint32(byteOffset + l, wl, isLE);
3226
3224
  }
3227
- // Choice: a ? b : c
3225
+ /**
3226
+ * Choice: a ? b : c
3227
+ */
3228
3228
  const Chi = (a, b, c) => (a & b) ^ (~a & c);
3229
- // Majority function, true if any two inpust is true
3229
+ /**
3230
+ * Majority function, true if any two inputs is true
3231
+ */
3230
3232
  const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
3231
3233
  /**
3232
3234
  * Merkle-Damgard hash construction base class.
@@ -3621,7 +3623,7 @@ function requireMs () {
3621
3623
  * @api public
3622
3624
  */
3623
3625
 
3624
- ms = function(val, options) {
3626
+ ms = function (val, options) {
3625
3627
  options = options || {};
3626
3628
  var type = typeof val;
3627
3629
  if (type === 'string' && val.length > 0) {
@@ -4314,7 +4316,6 @@ var debug = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
4314
4316
 
4315
4317
  const APP_NAME = "waku";
4316
4318
  let Logger$1 = class Logger {
4317
- _debug;
4318
4319
  _info;
4319
4320
  _warn;
4320
4321
  _error;
@@ -4322,14 +4323,10 @@ let Logger$1 = class Logger {
4322
4323
  return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;
4323
4324
  }
4324
4325
  constructor(prefix) {
4325
- this._debug = debug(Logger.createDebugNamespace("debug", prefix));
4326
4326
  this._info = debug(Logger.createDebugNamespace("info", prefix));
4327
4327
  this._warn = debug(Logger.createDebugNamespace("warn", prefix));
4328
4328
  this._error = debug(Logger.createDebugNamespace("error", prefix));
4329
4329
  }
4330
- get debug() {
4331
- return this._debug;
4332
- }
4333
4330
  get info() {
4334
4331
  return this._info;
4335
4332
  }
@@ -4345,34 +4342,6 @@ let Logger$1 = class Logger {
4345
4342
  }
4346
4343
  };
4347
4344
 
4348
- const peerIdSymbol = Symbol.for('@libp2p/peer-id');
4349
-
4350
- /**
4351
- * When this error is thrown it means an operation was aborted,
4352
- * usually in response to the `abort` event being emitted by an
4353
- * AbortSignal.
4354
- */
4355
- class CodeError extends Error {
4356
- code;
4357
- props;
4358
- constructor(message, code, props) {
4359
- super(message);
4360
- this.code = code;
4361
- this.name = props?.name ?? 'CodeError';
4362
- this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
4363
- }
4364
- }
4365
- class AggregateCodeError extends AggregateError {
4366
- code;
4367
- props;
4368
- constructor(errors, message, code, props) {
4369
- super(errors, message);
4370
- this.code = code;
4371
- this.name = props?.name ?? 'AggregateCodeError';
4372
- this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
4373
- }
4374
- }
4375
-
4376
4345
  /**
4377
4346
  * Returns true if the two passed Uint8Arrays have the same content
4378
4347
  */
@@ -5430,6 +5399,12 @@ const DNS_CODES = [
5430
5399
  getProtocol('dns6').code,
5431
5400
  getProtocol('dnsaddr').code
5432
5401
  ];
5402
+ class NoAvailableResolverError extends Error {
5403
+ constructor(message = 'No available resolver') {
5404
+ super(message);
5405
+ this.name = 'NoAvailableResolverError';
5406
+ }
5407
+ }
5433
5408
  /**
5434
5409
  * Creates a {@link Multiaddr} from a {@link MultiaddrInput}
5435
5410
  */
@@ -5599,7 +5574,7 @@ class Multiaddr {
5599
5574
  }
5600
5575
  const resolver = resolvers.get(resolvableProto.name);
5601
5576
  if (resolver == null) {
5602
- throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');
5577
+ throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);
5603
5578
  }
5604
5579
  const result = await resolver(this, options);
5605
5580
  return result.map(str => multiaddr(str));
@@ -5813,13 +5788,30 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
5813
5788
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
5814
5789
  }
5815
5790
 
5816
- function isPromise(thing) {
5817
- if (thing == null) {
5818
- return false;
5791
+ /**
5792
+ * When this error is thrown it means an operation was aborted,
5793
+ * usually in response to the `abort` event being emitted by an
5794
+ * AbortSignal.
5795
+ */
5796
+ /**
5797
+ * Thrown when invalid parameters are passed to a function or method call
5798
+ */
5799
+ class InvalidParametersError extends Error {
5800
+ static name = 'InvalidParametersError';
5801
+ constructor(message = 'Invalid parameters') {
5802
+ super(message);
5803
+ this.name = 'InvalidParametersError';
5804
+ }
5805
+ }
5806
+ /**
5807
+ * Thrown when a public key is invalid
5808
+ */
5809
+ class InvalidPublicKeyError extends Error {
5810
+ static name = 'InvalidPublicKeyError';
5811
+ constructor(message = 'Invalid public key') {
5812
+ super(message);
5813
+ this.name = 'InvalidPublicKeyError';
5819
5814
  }
5820
- return typeof thing.then === 'function' &&
5821
- typeof thing.catch === 'function' &&
5822
- typeof thing.finally === 'function';
5823
5815
  }
5824
5816
 
5825
5817
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
@@ -6907,6 +6899,60 @@ function wNAF(c, bits) {
6907
6899
  },
6908
6900
  };
6909
6901
  }
6902
+ /**
6903
+ * Pippenger algorithm for multi-scalar multiplication (MSM).
6904
+ * MSM is basically (Pa + Qb + Rc + ...).
6905
+ * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
6906
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
6907
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
6908
+ * @param c Curve Point constructor
6909
+ * @param field field over CURVE.N - important that it's not over CURVE.P
6910
+ * @param points array of L curve points
6911
+ * @param scalars array of L scalars (aka private keys / bigints)
6912
+ */
6913
+ function pippenger(c, field, points, scalars) {
6914
+ // If we split scalars by some window (let's say 8 bits), every chunk will only
6915
+ // take 256 buckets even if there are 4096 scalars, also re-uses double.
6916
+ // TODO:
6917
+ // - https://eprint.iacr.org/2024/750.pdf
6918
+ // - https://tches.iacr.org/index.php/TCHES/article/view/10287
6919
+ // 0 is accepted in scalars
6920
+ if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
6921
+ throw new Error('arrays of points and scalars must have equal length');
6922
+ scalars.forEach((s, i) => {
6923
+ if (!field.isValid(s))
6924
+ throw new Error(`wrong scalar at index ${i}`);
6925
+ });
6926
+ points.forEach((p, i) => {
6927
+ if (!(p instanceof c))
6928
+ throw new Error(`wrong point at index ${i}`);
6929
+ });
6930
+ const wbits = bitLen(BigInt(points.length));
6931
+ const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
6932
+ const MASK = (1 << windowSize) - 1;
6933
+ const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
6934
+ const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
6935
+ let sum = c.ZERO;
6936
+ for (let i = lastBits; i >= 0; i -= windowSize) {
6937
+ buckets.fill(c.ZERO);
6938
+ for (let j = 0; j < scalars.length; j++) {
6939
+ const scalar = scalars[j];
6940
+ const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
6941
+ buckets[wbits] = buckets[wbits].add(points[j]);
6942
+ }
6943
+ let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
6944
+ // Skip first bucket, because it is zero
6945
+ for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
6946
+ sumI = sumI.add(buckets[j]);
6947
+ resI = resI.add(sumI);
6948
+ }
6949
+ sum = sum.add(resI);
6950
+ if (i !== 0)
6951
+ for (let j = 0; j < windowSize; j++)
6952
+ sum = sum.double();
6953
+ }
6954
+ return sum;
6955
+ }
6910
6956
  function validateBasic(curve) {
6911
6957
  validateField(curve.Fp);
6912
6958
  validateObject(curve, {
@@ -6961,6 +7007,7 @@ function twistedEdwards(curveDef) {
6961
7007
  const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
6962
7008
  const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
6963
7009
  const modP = Fp.create; // Function overrides
7010
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
6964
7011
  // sqrt(u/v)
6965
7012
  const uvRatio = CURVE.uvRatio ||
6966
7013
  ((u, v) => {
@@ -7059,6 +7106,10 @@ function twistedEdwards(curveDef) {
7059
7106
  const toInv = Fp.invertBatch(points.map((p) => p.ez));
7060
7107
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
7061
7108
  }
7109
+ // Multiscalar Multiplication
7110
+ static msm(points, scalars) {
7111
+ return pippenger(Point, Fn, points, scalars);
7112
+ }
7062
7113
  // "Private method", don't use it directly
7063
7114
  _setWindowSize(windowSize) {
7064
7115
  wnaf.setWindowSize(this, windowSize);
@@ -7434,7 +7485,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7434
7485
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
7435
7486
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
7436
7487
  hash: sha512,
7437
- randomBytes: randomBytes$1,
7488
+ randomBytes,
7438
7489
  adjustScalarBytes,
7439
7490
  // dom2
7440
7491
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
@@ -7447,176 +7498,46 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7447
7498
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7448
7499
 
7449
7500
  const PUBLIC_KEY_BYTE_LENGTH = 32;
7450
- const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
7451
- const KEYS_BYTE_LENGTH = 32;
7452
- function generateKey$2() {
7453
- // the actual private key (32 bytes)
7454
- const privateKeyRaw = ed25519.utils.randomPrivateKey();
7455
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7456
- // concatenated the public key to the private key
7457
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7458
- return {
7459
- privateKey,
7460
- publicKey
7461
- };
7462
- }
7463
- /**
7464
- * Generate keypair from a 32 byte uint8array
7465
- */
7466
- function generateKeyFromSeed(seed) {
7467
- if (seed.length !== KEYS_BYTE_LENGTH) {
7468
- throw new TypeError('"seed" must be 32 bytes in length.');
7469
- }
7470
- else if (!(seed instanceof Uint8Array)) {
7471
- throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
7472
- }
7473
- // based on node forges algorithm, the seed is used directly as private key
7474
- const privateKeyRaw = seed;
7475
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7476
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7477
- return {
7478
- privateKey,
7479
- publicKey
7480
- };
7481
- }
7482
- function hashAndSign$2(privateKey, msg) {
7483
- const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
7484
- return ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
7485
- }
7486
7501
  function hashAndVerify$2(publicKey, sig, msg) {
7487
7502
  return ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
7488
7503
  }
7489
- function concatKeys(privateKeyRaw, publicKey) {
7490
- const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
7491
- for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
7492
- privateKey[i] = privateKeyRaw[i];
7493
- privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
7494
- }
7495
- return privateKey;
7496
- }
7497
7504
 
7498
- /* eslint-env browser */
7499
- // Check native crypto exists and is enabled (In insecure context `self.crypto`
7500
- // exists but `self.crypto.subtle` does not).
7501
- var webcrypto = {
7502
- get(win = globalThis) {
7503
- const nativeCrypto = win.crypto;
7504
- if (nativeCrypto?.subtle == null) {
7505
- throw Object.assign(new Error('Missing Web Crypto API. ' +
7506
- 'The most likely cause of this error is that this page is being accessed ' +
7507
- 'from an insecure context (i.e. not HTTPS). For more information and ' +
7508
- 'possible resolutions see ' +
7509
- 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });
7510
- }
7511
- return nativeCrypto;
7505
+ class Ed25519PublicKey {
7506
+ type = 'Ed25519';
7507
+ raw;
7508
+ constructor(key) {
7509
+ this.raw = ensureEd25519Key(key, PUBLIC_KEY_BYTE_LENGTH);
7512
7510
  }
7513
- };
7514
-
7515
- // WebKit on Linux does not support deriving a key from an empty PBKDF2 key.
7516
- // So, as a workaround, we provide the generated key as a constant. We test that
7517
- // this generated key is accurate in test/workaround.spec.ts
7518
- // Generated via:
7519
- // await crypto.subtle.exportKey('jwk',
7520
- // await crypto.subtle.deriveKey(
7521
- // { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },
7522
- // await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),
7523
- // { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])
7524
- // )
7525
- const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
7526
- // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
7527
- function create(opts) {
7528
- const algorithm = 'AES-GCM';
7529
- let keyLength = 16;
7530
- const nonceLength = 12;
7531
- const digest = 'SHA-256';
7532
- const saltLength = 16;
7533
- const iterations = 32767;
7534
- const crypto = webcrypto.get();
7535
- keyLength *= 8; // Browser crypto uses bits instead of bytes
7536
- /**
7537
- * Uses the provided password to derive a pbkdf2 key. The key
7538
- * will then be used to encrypt the data.
7539
- */
7540
- async function encrypt(data, password) {
7541
- const salt = crypto.getRandomValues(new Uint8Array(saltLength));
7542
- const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));
7543
- const aesGcm = { name: algorithm, iv: nonce };
7544
- if (typeof password === 'string') {
7545
- password = fromString(password);
7546
- }
7547
- let cryptoKey;
7548
- if (password.length === 0) {
7549
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7550
- try {
7551
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7552
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7553
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);
7554
- }
7555
- catch {
7556
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7557
- }
7558
- }
7559
- else {
7560
- // Derive a key using PBKDF2.
7561
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7562
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7563
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);
7564
- }
7565
- // Encrypt the string.
7566
- const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);
7567
- return concat$1([salt, aesGcm.iv, new Uint8Array(ciphertext)]);
7568
- }
7569
- /**
7570
- * Uses the provided password to derive a pbkdf2 key. The key
7571
- * will then be used to decrypt the data. The options used to create
7572
- * this decryption cipher must be the same as those used to create
7573
- * the encryption cipher.
7574
- */
7575
- async function decrypt(data, password) {
7576
- const salt = data.subarray(0, saltLength);
7577
- const nonce = data.subarray(saltLength, saltLength + nonceLength);
7578
- const ciphertext = data.subarray(saltLength + nonceLength);
7579
- const aesGcm = { name: algorithm, iv: nonce };
7580
- if (typeof password === 'string') {
7581
- password = fromString(password);
7582
- }
7583
- let cryptoKey;
7584
- if (password.length === 0) {
7585
- try {
7586
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7587
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7588
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);
7589
- }
7590
- catch {
7591
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);
7592
- }
7511
+ toMultihash() {
7512
+ return identity.digest(publicKeyToProtobuf(this));
7513
+ }
7514
+ toCID() {
7515
+ return CID.createV1(114, this.toMultihash());
7516
+ }
7517
+ toString() {
7518
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
7519
+ }
7520
+ equals(key) {
7521
+ if (key == null || !(key.raw instanceof Uint8Array)) {
7522
+ return false;
7593
7523
  }
7594
- else {
7595
- // Derive the key using PBKDF2.
7596
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7597
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7598
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);
7599
- }
7600
- // Decrypt the string.
7601
- const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);
7602
- return new Uint8Array(plaintext);
7603
- }
7604
- const cipher = {
7605
- encrypt,
7606
- decrypt
7607
- };
7608
- return cipher;
7524
+ return equals(this.raw, key.raw);
7525
+ }
7526
+ verify(data, sig) {
7527
+ return hashAndVerify$2(this.raw, sig, data);
7528
+ }
7609
7529
  }
7610
7530
 
7611
- /**
7612
- * Exports the given PrivateKey as a base64 encoded string.
7613
- * The PrivateKey is encrypted via a password derived PBKDF2 key
7614
- * leveraging the aes-gcm cipher algorithm.
7615
- */
7616
- async function exporter(privateKey, password) {
7617
- const cipher = create();
7618
- const encryptedKey = await cipher.encrypt(privateKey, password);
7619
- return base64.encode(encryptedKey);
7531
+ function unmarshalEd25519PublicKey(bytes) {
7532
+ bytes = ensureEd25519Key(bytes, PUBLIC_KEY_BYTE_LENGTH);
7533
+ return new Ed25519PublicKey(bytes);
7534
+ }
7535
+ function ensureEd25519Key(key, length) {
7536
+ key = Uint8Array.from(key ?? []);
7537
+ if (key.length !== length) {
7538
+ throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);
7539
+ }
7540
+ return key;
7620
7541
  }
7621
7542
 
7622
7543
  const f32 = new Float32Array([-0]);
@@ -8825,13 +8746,13 @@ var KeyType;
8825
8746
  (function (KeyType) {
8826
8747
  KeyType["RSA"] = "RSA";
8827
8748
  KeyType["Ed25519"] = "Ed25519";
8828
- KeyType["Secp256k1"] = "Secp256k1";
8749
+ KeyType["secp256k1"] = "secp256k1";
8829
8750
  })(KeyType || (KeyType = {}));
8830
8751
  var __KeyTypeValues;
8831
8752
  (function (__KeyTypeValues) {
8832
8753
  __KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
8833
8754
  __KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
8834
- __KeyTypeValues[__KeyTypeValues["Secp256k1"] = 2] = "Secp256k1";
8755
+ __KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
8835
8756
  })(__KeyTypeValues || (__KeyTypeValues = {}));
8836
8757
  (function (KeyType) {
8837
8758
  KeyType.codec = () => {
@@ -8858,21 +8779,24 @@ var PublicKey;
8858
8779
  if (opts.lengthDelimited !== false) {
8859
8780
  w.ldelim();
8860
8781
  }
8861
- }, (reader, length) => {
8782
+ }, (reader, length, opts = {}) => {
8862
8783
  const obj = {};
8863
8784
  const end = length == null ? reader.len : reader.pos + length;
8864
8785
  while (reader.pos < end) {
8865
8786
  const tag = reader.uint32();
8866
8787
  switch (tag >>> 3) {
8867
- case 1:
8788
+ case 1: {
8868
8789
  obj.Type = KeyType.codec().decode(reader);
8869
8790
  break;
8870
- case 2:
8791
+ }
8792
+ case 2: {
8871
8793
  obj.Data = reader.bytes();
8872
8794
  break;
8873
- default:
8795
+ }
8796
+ default: {
8874
8797
  reader.skipType(tag & 7);
8875
8798
  break;
8799
+ }
8876
8800
  }
8877
8801
  }
8878
8802
  return obj;
@@ -8883,8 +8807,8 @@ var PublicKey;
8883
8807
  PublicKey.encode = (obj) => {
8884
8808
  return encodeMessage(obj, PublicKey.codec());
8885
8809
  };
8886
- PublicKey.decode = (buf) => {
8887
- return decodeMessage(buf, PublicKey.codec());
8810
+ PublicKey.decode = (buf, opts) => {
8811
+ return decodeMessage(buf, PublicKey.codec(), opts);
8888
8812
  };
8889
8813
  })(PublicKey || (PublicKey = {}));
8890
8814
  var PrivateKey;
@@ -8907,21 +8831,24 @@ var PrivateKey;
8907
8831
  if (opts.lengthDelimited !== false) {
8908
8832
  w.ldelim();
8909
8833
  }
8910
- }, (reader, length) => {
8834
+ }, (reader, length, opts = {}) => {
8911
8835
  const obj = {};
8912
8836
  const end = length == null ? reader.len : reader.pos + length;
8913
8837
  while (reader.pos < end) {
8914
8838
  const tag = reader.uint32();
8915
8839
  switch (tag >>> 3) {
8916
- case 1:
8840
+ case 1: {
8917
8841
  obj.Type = KeyType.codec().decode(reader);
8918
8842
  break;
8919
- case 2:
8843
+ }
8844
+ case 2: {
8920
8845
  obj.Data = reader.bytes();
8921
8846
  break;
8922
- default:
8847
+ }
8848
+ default: {
8923
8849
  reader.skipType(tag & 7);
8924
8850
  break;
8851
+ }
8925
8852
  }
8926
8853
  }
8927
8854
  return obj;
@@ -8932,393 +8859,122 @@ var PrivateKey;
8932
8859
  PrivateKey.encode = (obj) => {
8933
8860
  return encodeMessage(obj, PrivateKey.codec());
8934
8861
  };
8935
- PrivateKey.decode = (buf) => {
8936
- return decodeMessage(buf, PrivateKey.codec());
8862
+ PrivateKey.decode = (buf, opts) => {
8863
+ return decodeMessage(buf, PrivateKey.codec(), opts);
8937
8864
  };
8938
8865
  })(PrivateKey || (PrivateKey = {}));
8939
8866
 
8940
- class Ed25519PublicKey {
8941
- _key;
8942
- constructor(key) {
8943
- this._key = ensureKey(key, PUBLIC_KEY_BYTE_LENGTH);
8944
- }
8945
- verify(data, sig) {
8946
- return hashAndVerify$2(this._key, sig, data);
8947
- }
8948
- marshal() {
8949
- return this._key;
8950
- }
8951
- get bytes() {
8952
- return PublicKey.encode({
8953
- Type: KeyType.Ed25519,
8954
- Data: this.marshal()
8955
- }).subarray();
8956
- }
8957
- equals(key) {
8958
- return equals(this.bytes, key.bytes);
8867
+ /*!
8868
+ * MIT License
8869
+ *
8870
+ * Copyright (c) 2017-2022 Peculiar Ventures, LLC
8871
+ *
8872
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8873
+ * of this software and associated documentation files (the "Software"), to deal
8874
+ * in the Software without restriction, including without limitation the rights
8875
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8876
+ * copies of the Software, and to permit persons to whom the Software is
8877
+ * furnished to do so, subject to the following conditions:
8878
+ *
8879
+ * The above copyright notice and this permission notice shall be included in all
8880
+ * copies or substantial portions of the Software.
8881
+ *
8882
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8883
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8884
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8885
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8886
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
8887
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
8888
+ * SOFTWARE.
8889
+ *
8890
+ */
8891
+
8892
+ const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
8893
+ class BufferSourceConverter {
8894
+ static isArrayBuffer(data) {
8895
+ return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
8959
8896
  }
8960
- hash() {
8961
- const p = sha256$1.digest(this.bytes);
8962
- if (isPromise(p)) {
8963
- return p.then(({ bytes }) => bytes);
8897
+ static toArrayBuffer(data) {
8898
+ if (this.isArrayBuffer(data)) {
8899
+ return data;
8964
8900
  }
8965
- return p.bytes;
8966
- }
8967
- }
8968
- class Ed25519PrivateKey {
8969
- _key;
8970
- _publicKey;
8971
- // key - 64 byte Uint8Array containing private key
8972
- // publicKey - 32 byte Uint8Array containing public key
8973
- constructor(key, publicKey) {
8974
- this._key = ensureKey(key, PRIVATE_KEY_BYTE_LENGTH);
8975
- this._publicKey = ensureKey(publicKey, PUBLIC_KEY_BYTE_LENGTH);
8976
- }
8977
- sign(message) {
8978
- return hashAndSign$2(this._key, message);
8901
+ if (data.byteLength === data.buffer.byteLength) {
8902
+ return data.buffer;
8903
+ }
8904
+ if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
8905
+ return data.buffer;
8906
+ }
8907
+ return this.toUint8Array(data.buffer)
8908
+ .slice(data.byteOffset, data.byteOffset + data.byteLength)
8909
+ .buffer;
8979
8910
  }
8980
- get public() {
8981
- return new Ed25519PublicKey(this._publicKey);
8911
+ static toUint8Array(data) {
8912
+ return this.toView(data, Uint8Array);
8982
8913
  }
8983
- marshal() {
8984
- return this._key;
8914
+ static toView(data, type) {
8915
+ if (data.constructor === type) {
8916
+ return data;
8917
+ }
8918
+ if (this.isArrayBuffer(data)) {
8919
+ return new type(data);
8920
+ }
8921
+ if (this.isArrayBufferView(data)) {
8922
+ return new type(data.buffer, data.byteOffset, data.byteLength);
8923
+ }
8924
+ throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
8985
8925
  }
8986
- get bytes() {
8987
- return PrivateKey.encode({
8988
- Type: KeyType.Ed25519,
8989
- Data: this.marshal()
8990
- }).subarray();
8926
+ static isBufferSource(data) {
8927
+ return this.isArrayBufferView(data)
8928
+ || this.isArrayBuffer(data);
8991
8929
  }
8992
- equals(key) {
8993
- return equals(this.bytes, key.bytes);
8930
+ static isArrayBufferView(data) {
8931
+ return ArrayBuffer.isView(data)
8932
+ || (data && this.isArrayBuffer(data.buffer));
8994
8933
  }
8995
- async hash() {
8996
- const p = sha256$1.digest(this.bytes);
8997
- let bytes;
8998
- if (isPromise(p)) {
8999
- ({ bytes } = await p);
8934
+ static isEqual(a, b) {
8935
+ const aView = BufferSourceConverter.toUint8Array(a);
8936
+ const bView = BufferSourceConverter.toUint8Array(b);
8937
+ if (aView.length !== bView.byteLength) {
8938
+ return false;
9000
8939
  }
9001
- else {
9002
- bytes = p.bytes;
8940
+ for (let i = 0; i < aView.length; i++) {
8941
+ if (aView[i] !== bView[i]) {
8942
+ return false;
8943
+ }
9003
8944
  }
9004
- return bytes;
9005
- }
9006
- /**
9007
- * Gets the ID of the key.
9008
- *
9009
- * The key id is the base58 encoding of the identity multihash containing its public key.
9010
- * The public key is a protobuf encoding containing a type and the DER encoding
9011
- * of the PKCS SubjectPublicKeyInfo.
9012
- *
9013
- * @returns {Promise<string>}
9014
- */
9015
- async id() {
9016
- const encoding = identity.digest(this.public.bytes);
9017
- return base58btc.encode(encoding.bytes).substring(1);
8945
+ return true;
9018
8946
  }
9019
- /**
9020
- * Exports the key into a password protected `format`
9021
- */
9022
- async export(password, format = 'libp2p-key') {
9023
- if (format === 'libp2p-key') {
9024
- return exporter(this.bytes, password);
8947
+ static concat(...args) {
8948
+ let buffers;
8949
+ if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
8950
+ buffers = args[0];
8951
+ }
8952
+ else if (Array.isArray(args[0]) && args[1] instanceof Function) {
8953
+ buffers = args[0];
9025
8954
  }
9026
8955
  else {
9027
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
8956
+ if (args[args.length - 1] instanceof Function) {
8957
+ buffers = args.slice(0, args.length - 1);
8958
+ }
8959
+ else {
8960
+ buffers = args;
8961
+ }
9028
8962
  }
9029
- }
9030
- }
9031
- function unmarshalEd25519PrivateKey(bytes) {
9032
- // Try the old, redundant public key version
9033
- if (bytes.length > PRIVATE_KEY_BYTE_LENGTH) {
9034
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH + PUBLIC_KEY_BYTE_LENGTH);
9035
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9036
- const publicKeyBytes = bytes.subarray(PRIVATE_KEY_BYTE_LENGTH, bytes.length);
9037
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9038
- }
9039
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH);
9040
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9041
- const publicKeyBytes = bytes.subarray(PUBLIC_KEY_BYTE_LENGTH);
9042
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9043
- }
9044
- function unmarshalEd25519PublicKey(bytes) {
9045
- bytes = ensureKey(bytes, PUBLIC_KEY_BYTE_LENGTH);
9046
- return new Ed25519PublicKey(bytes);
9047
- }
9048
- async function generateKeyPair$2() {
9049
- const { privateKey, publicKey } = generateKey$2();
9050
- return new Ed25519PrivateKey(privateKey, publicKey);
9051
- }
9052
- async function generateKeyPairFromSeed(seed) {
9053
- const { privateKey, publicKey } = generateKeyFromSeed(seed);
9054
- return new Ed25519PrivateKey(privateKey, publicKey);
9055
- }
9056
- function ensureKey(key, length) {
9057
- key = Uint8Array.from(key ?? []);
9058
- if (key.length !== length) {
9059
- throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
9060
- }
9061
- return key;
9062
- }
9063
-
9064
- var Ed25519 = /*#__PURE__*/Object.freeze({
9065
- __proto__: null,
9066
- Ed25519PrivateKey: Ed25519PrivateKey,
9067
- Ed25519PublicKey: Ed25519PublicKey,
9068
- generateKeyPair: generateKeyPair$2,
9069
- generateKeyPairFromSeed: generateKeyPairFromSeed,
9070
- unmarshalEd25519PrivateKey: unmarshalEd25519PrivateKey,
9071
- unmarshalEd25519PublicKey: unmarshalEd25519PublicKey
9072
- });
9073
-
9074
- /**
9075
- * Generates a Uint8Array with length `number` populated by random bytes
9076
- */
9077
- function randomBytes(length) {
9078
- if (isNaN(length) || length <= 0) {
9079
- throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
9080
- }
9081
- return randomBytes$1(length);
9082
- }
9083
-
9084
- // HMAC (RFC 2104)
9085
- class HMAC extends Hash {
9086
- constructor(hash$1, _key) {
9087
- super();
9088
- this.finished = false;
9089
- this.destroyed = false;
9090
- hash(hash$1);
9091
- const key = toBytes$1(_key);
9092
- this.iHash = hash$1.create();
9093
- if (typeof this.iHash.update !== 'function')
9094
- throw new Error('Expected instance of class which extends utils.Hash');
9095
- this.blockLen = this.iHash.blockLen;
9096
- this.outputLen = this.iHash.outputLen;
9097
- const blockLen = this.blockLen;
9098
- const pad = new Uint8Array(blockLen);
9099
- // blockLen can be bigger than outputLen
9100
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
9101
- for (let i = 0; i < pad.length; i++)
9102
- pad[i] ^= 0x36;
9103
- this.iHash.update(pad);
9104
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
9105
- this.oHash = hash$1.create();
9106
- // Undo internal XOR && apply outer XOR
9107
- for (let i = 0; i < pad.length; i++)
9108
- pad[i] ^= 0x36 ^ 0x5c;
9109
- this.oHash.update(pad);
9110
- pad.fill(0);
9111
- }
9112
- update(buf) {
9113
- exists(this);
9114
- this.iHash.update(buf);
9115
- return this;
9116
- }
9117
- digestInto(out) {
9118
- exists(this);
9119
- bytes(out, this.outputLen);
9120
- this.finished = true;
9121
- this.iHash.digestInto(out);
9122
- this.oHash.update(out);
9123
- this.oHash.digestInto(out);
9124
- this.destroy();
9125
- }
9126
- digest() {
9127
- const out = new Uint8Array(this.oHash.outputLen);
9128
- this.digestInto(out);
9129
- return out;
9130
- }
9131
- _cloneInto(to) {
9132
- // Create new instance without calling constructor since key already in state and we don't know it.
9133
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
9134
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
9135
- to = to;
9136
- to.finished = finished;
9137
- to.destroyed = destroyed;
9138
- to.blockLen = blockLen;
9139
- to.outputLen = outputLen;
9140
- to.oHash = oHash._cloneInto(to.oHash);
9141
- to.iHash = iHash._cloneInto(to.iHash);
9142
- return to;
9143
- }
9144
- destroy() {
9145
- this.destroyed = true;
9146
- this.oHash.destroy();
9147
- this.iHash.destroy();
9148
- }
9149
- }
9150
- /**
9151
- * HMAC: RFC2104 message authentication code.
9152
- * @param hash - function that would be used e.g. sha256
9153
- * @param key - message key
9154
- * @param message - message data
9155
- */
9156
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
9157
- hmac.create = (hash, key) => new HMAC(hash, key);
9158
-
9159
- // Common prologue and epilogue for sync/async functions
9160
- function pbkdf2Init(hash$1, _password, _salt, _opts) {
9161
- hash(hash$1);
9162
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
9163
- const { c, dkLen, asyncTick } = opts;
9164
- number(c);
9165
- number(dkLen);
9166
- number(asyncTick);
9167
- if (c < 1)
9168
- throw new Error('PBKDF2: iterations (c) should be >= 1');
9169
- const password = toBytes$1(_password);
9170
- const salt = toBytes$1(_salt);
9171
- // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
9172
- const DK = new Uint8Array(dkLen);
9173
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9174
- const PRF = hmac.create(hash$1, password);
9175
- const PRFSalt = PRF._cloneInto().update(salt);
9176
- return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
9177
- }
9178
- function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
9179
- PRF.destroy();
9180
- PRFSalt.destroy();
9181
- if (prfW)
9182
- prfW.destroy();
9183
- u.fill(0);
9184
- return DK;
9185
- }
9186
- async function pbkdf2Async(hash, password, salt, opts) {
9187
- const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
9188
- let prfW; // Working copy
9189
- const arr = new Uint8Array(4);
9190
- const view = createView(arr);
9191
- const u = new Uint8Array(PRF.outputLen);
9192
- // DK = T1 + T2 + โ‹ฏ + Tdklen/hlen
9193
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
9194
- // Ti = F(Password, Salt, c, i)
9195
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
9196
- view.setInt32(0, ti, false);
9197
- // F(Password, Salt, c, i) = U1 ^ U2 ^ โ‹ฏ ^ Uc
9198
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9199
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
9200
- Ti.set(u.subarray(0, Ti.length));
9201
- await asyncLoop(c - 1, asyncTick, () => {
9202
- // Uc = PRF(Password, Ucโˆ’1)
9203
- PRF._cloneInto(prfW).update(u).digestInto(u);
9204
- for (let i = 0; i < Ti.length; i++)
9205
- Ti[i] ^= u[i];
9206
- });
9207
- }
9208
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
9209
- }
9210
-
9211
- /*!
9212
- * MIT License
9213
- *
9214
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9215
- *
9216
- * Permission is hereby granted, free of charge, to any person obtaining a copy
9217
- * of this software and associated documentation files (the "Software"), to deal
9218
- * in the Software without restriction, including without limitation the rights
9219
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9220
- * copies of the Software, and to permit persons to whom the Software is
9221
- * furnished to do so, subject to the following conditions:
9222
- *
9223
- * The above copyright notice and this permission notice shall be included in all
9224
- * copies or substantial portions of the Software.
9225
- *
9226
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9227
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9228
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9229
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9230
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9231
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
9232
- * SOFTWARE.
9233
- *
9234
- */
9235
-
9236
- const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
9237
- class BufferSourceConverter {
9238
- static isArrayBuffer(data) {
9239
- return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
9240
- }
9241
- static toArrayBuffer(data) {
9242
- if (this.isArrayBuffer(data)) {
9243
- return data;
9244
- }
9245
- if (data.byteLength === data.buffer.byteLength) {
9246
- return data.buffer;
9247
- }
9248
- if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
9249
- return data.buffer;
9250
- }
9251
- return this.toUint8Array(data.buffer)
9252
- .slice(data.byteOffset, data.byteOffset + data.byteLength)
9253
- .buffer;
9254
- }
9255
- static toUint8Array(data) {
9256
- return this.toView(data, Uint8Array);
9257
- }
9258
- static toView(data, type) {
9259
- if (data.constructor === type) {
9260
- return data;
9261
- }
9262
- if (this.isArrayBuffer(data)) {
9263
- return new type(data);
9264
- }
9265
- if (this.isArrayBufferView(data)) {
9266
- return new type(data.buffer, data.byteOffset, data.byteLength);
9267
- }
9268
- throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
9269
- }
9270
- static isBufferSource(data) {
9271
- return this.isArrayBufferView(data)
9272
- || this.isArrayBuffer(data);
9273
- }
9274
- static isArrayBufferView(data) {
9275
- return ArrayBuffer.isView(data)
9276
- || (data && this.isArrayBuffer(data.buffer));
9277
- }
9278
- static isEqual(a, b) {
9279
- const aView = BufferSourceConverter.toUint8Array(a);
9280
- const bView = BufferSourceConverter.toUint8Array(b);
9281
- if (aView.length !== bView.byteLength) {
9282
- return false;
9283
- }
9284
- for (let i = 0; i < aView.length; i++) {
9285
- if (aView[i] !== bView[i]) {
9286
- return false;
9287
- }
9288
- }
9289
- return true;
9290
- }
9291
- static concat(...args) {
9292
- let buffers;
9293
- if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
9294
- buffers = args[0];
9295
- }
9296
- else if (Array.isArray(args[0]) && args[1] instanceof Function) {
9297
- buffers = args[0];
9298
- }
9299
- else {
9300
- if (args[args.length - 1] instanceof Function) {
9301
- buffers = args.slice(0, args.length - 1);
9302
- }
9303
- else {
9304
- buffers = args;
9305
- }
9306
- }
9307
- let size = 0;
9308
- for (const buffer of buffers) {
9309
- size += buffer.byteLength;
9310
- }
9311
- const res = new Uint8Array(size);
9312
- let offset = 0;
9313
- for (const buffer of buffers) {
9314
- const view = this.toUint8Array(buffer);
9315
- res.set(view, offset);
9316
- offset += view.length;
9317
- }
9318
- if (args[args.length - 1] instanceof Function) {
9319
- return this.toView(res, args[args.length - 1]);
9320
- }
9321
- return res.buffer;
8963
+ let size = 0;
8964
+ for (const buffer of buffers) {
8965
+ size += buffer.byteLength;
8966
+ }
8967
+ const res = new Uint8Array(size);
8968
+ let offset = 0;
8969
+ for (const buffer of buffers) {
8970
+ const view = this.toUint8Array(buffer);
8971
+ res.set(view, offset);
8972
+ offset += view.length;
8973
+ }
8974
+ if (args[args.length - 1] instanceof Function) {
8975
+ return this.toView(res, args[args.length - 1]);
8976
+ }
8977
+ return res.buffer;
9322
8978
  }
9323
8979
  }
9324
8980
 
@@ -12459,272 +12115,44 @@ _a = TIME;
12459
12115
  TIME.NAME = "TIME";
12460
12116
 
12461
12117
  /**
12462
- * Convert a PKCS#1 in ASN1 DER format to a JWK key
12118
+ * Signing a message failed
12463
12119
  */
12464
- function pkcs1ToJwk(bytes) {
12465
- const { result } = fromBER(bytes);
12466
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12467
- // safe to have deeply property chains like this
12468
- const values = result.valueBlock.value;
12469
- const key = {
12470
- n: toString$1(bnToBuf(values[1].toBigInt()), 'base64url'),
12471
- e: toString$1(bnToBuf(values[2].toBigInt()), 'base64url'),
12472
- d: toString$1(bnToBuf(values[3].toBigInt()), 'base64url'),
12473
- p: toString$1(bnToBuf(values[4].toBigInt()), 'base64url'),
12474
- q: toString$1(bnToBuf(values[5].toBigInt()), 'base64url'),
12475
- dp: toString$1(bnToBuf(values[6].toBigInt()), 'base64url'),
12476
- dq: toString$1(bnToBuf(values[7].toBigInt()), 'base64url'),
12477
- qi: toString$1(bnToBuf(values[8].toBigInt()), 'base64url'),
12478
- kty: 'RSA',
12479
- alg: 'RS256'
12480
- };
12481
- return key;
12482
- }
12483
12120
  /**
12484
- * Convert a JWK key into PKCS#1 in ASN1 DER format
12121
+ * Verifying a message signature failed
12485
12122
  */
12486
- function jwkToPkcs1(jwk) {
12487
- if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {
12488
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12123
+ class VerificationError extends Error {
12124
+ constructor(message = 'An error occurred while verifying a message') {
12125
+ super(message);
12126
+ this.name = 'VerificationError';
12489
12127
  }
12490
- const root = new Sequence({
12491
- value: [
12492
- new Integer({ value: 0 }),
12493
- Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
12494
- Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url'))),
12495
- Integer.fromBigInt(bufToBn(fromString(jwk.d, 'base64url'))),
12496
- Integer.fromBigInt(bufToBn(fromString(jwk.p, 'base64url'))),
12497
- Integer.fromBigInt(bufToBn(fromString(jwk.q, 'base64url'))),
12498
- Integer.fromBigInt(bufToBn(fromString(jwk.dp, 'base64url'))),
12499
- Integer.fromBigInt(bufToBn(fromString(jwk.dq, 'base64url'))),
12500
- Integer.fromBigInt(bufToBn(fromString(jwk.qi, 'base64url')))
12501
- ]
12502
- });
12503
- const der = root.toBER();
12504
- return new Uint8Array(der, 0, der.byteLength);
12505
- }
12506
- /**
12507
- * Convert a PKCIX in ASN1 DER format to a JWK key
12508
- */
12509
- function pkixToJwk(bytes) {
12510
- const { result } = fromBER(bytes);
12511
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12512
- // safe to have deeply property chains like this
12513
- const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12514
- return {
12515
- kty: 'RSA',
12516
- n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
12517
- e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
12518
- };
12519
12128
  }
12520
12129
  /**
12521
- * Convert a JWK key to PKCIX in ASN1 DER format
12130
+ * WebCrypto was not available in the current context
12522
12131
  */
12523
- function jwkToPkix(jwk) {
12524
- if (jwk.n == null || jwk.e == null) {
12525
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12132
+ class WebCryptoMissingError extends Error {
12133
+ constructor(message = 'Missing Web Crypto API') {
12134
+ super(message);
12135
+ this.name = 'WebCryptoMissingError';
12526
12136
  }
12527
- const root = new Sequence({
12528
- value: [
12529
- new Sequence({
12530
- value: [
12531
- // rsaEncryption
12532
- new ObjectIdentifier({
12533
- value: '1.2.840.113549.1.1.1'
12534
- }),
12535
- new Null()
12536
- ]
12537
- }),
12538
- // this appears to be a bug in asn1js.js - this should really be a Sequence
12539
- // and not a BitString but it generates the same bytes as node-forge so ๐Ÿคทโ€โ™‚๏ธ
12540
- new BitString({
12541
- valueHex: new Sequence({
12542
- value: [
12543
- Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
12544
- Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url')))
12545
- ]
12546
- }).toBER()
12547
- })
12548
- ]
12549
- });
12550
- const der = root.toBER();
12551
- return new Uint8Array(der, 0, der.byteLength);
12552
12137
  }
12553
- function bnToBuf(bn) {
12554
- let hex = bn.toString(16);
12555
- if (hex.length % 2 > 0) {
12556
- hex = `0${hex}`;
12557
- }
12558
- const len = hex.length / 2;
12559
- const u8 = new Uint8Array(len);
12560
- let i = 0;
12561
- let j = 0;
12562
- while (i < len) {
12563
- u8[i] = parseInt(hex.slice(j, j + 2), 16);
12564
- i += 1;
12565
- j += 2;
12566
- }
12567
- return u8;
12568
- }
12569
- function bufToBn(u8) {
12570
- const hex = [];
12571
- u8.forEach(function (i) {
12572
- let h = i.toString(16);
12573
- if (h.length % 2 > 0) {
12574
- h = `0${h}`;
12138
+
12139
+ /* eslint-env browser */
12140
+ // Check native crypto exists and is enabled (In insecure context `self.crypto`
12141
+ // exists but `self.crypto.subtle` does not).
12142
+ var webcrypto = {
12143
+ get(win = globalThis) {
12144
+ const nativeCrypto = win.crypto;
12145
+ if (nativeCrypto?.subtle == null) {
12146
+ throw new WebCryptoMissingError('Missing Web Crypto API. ' +
12147
+ 'The most likely cause of this error is that this page is being accessed ' +
12148
+ 'from an insecure context (i.e. not HTTPS). For more information and ' +
12149
+ 'possible resolutions see ' +
12150
+ 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');
12575
12151
  }
12576
- hex.push(h);
12577
- });
12578
- return BigInt('0x' + hex.join(''));
12579
- }
12580
- const SALT_LENGTH = 16;
12581
- const KEY_SIZE = 32;
12582
- const ITERATIONS = 10000;
12583
- async function exportToPem(privateKey, password) {
12584
- const crypto = webcrypto.get();
12585
- // PrivateKeyInfo
12586
- const keyWrapper = new Sequence({
12587
- value: [
12588
- // version (0)
12589
- new Integer({ value: 0 }),
12590
- // privateKeyAlgorithm
12591
- new Sequence({
12592
- value: [
12593
- // rsaEncryption OID
12594
- new ObjectIdentifier({
12595
- value: '1.2.840.113549.1.1.1'
12596
- }),
12597
- new Null()
12598
- ]
12599
- }),
12600
- // PrivateKey
12601
- new OctetString({
12602
- valueHex: privateKey.marshal()
12603
- })
12604
- ]
12605
- });
12606
- const keyBuf = keyWrapper.toBER();
12607
- const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);
12608
- const salt = randomBytes(SALT_LENGTH);
12609
- const encryptionKey = await pbkdf2Async(sha512, password, salt, {
12610
- c: ITERATIONS,
12611
- dkLen: KEY_SIZE
12612
- });
12613
- const iv = randomBytes(16);
12614
- const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);
12615
- const encrypted = await crypto.subtle.encrypt({
12616
- name: 'AES-CBC',
12617
- iv
12618
- }, cryptoKey, keyArr);
12619
- const pbkdf2Params = new Sequence({
12620
- value: [
12621
- // salt
12622
- new OctetString({ valueHex: salt }),
12623
- // iteration count
12624
- new Integer({ value: ITERATIONS }),
12625
- // key length
12626
- new Integer({ value: KEY_SIZE }),
12627
- // AlgorithmIdentifier
12628
- new Sequence({
12629
- value: [
12630
- // hmacWithSHA512
12631
- new ObjectIdentifier({ value: '1.2.840.113549.2.11' }),
12632
- new Null()
12633
- ]
12634
- })
12635
- ]
12636
- });
12637
- const encryptionAlgorithm = new Sequence({
12638
- value: [
12639
- // pkcs5PBES2
12640
- new ObjectIdentifier({
12641
- value: '1.2.840.113549.1.5.13'
12642
- }),
12643
- new Sequence({
12644
- value: [
12645
- // keyDerivationFunc
12646
- new Sequence({
12647
- value: [
12648
- // pkcs5PBKDF2
12649
- new ObjectIdentifier({
12650
- value: '1.2.840.113549.1.5.12'
12651
- }),
12652
- // PBKDF2-params
12653
- pbkdf2Params
12654
- ]
12655
- }),
12656
- // encryptionScheme
12657
- new Sequence({
12658
- value: [
12659
- // aes256-CBC
12660
- new ObjectIdentifier({
12661
- value: '2.16.840.1.101.3.4.1.42'
12662
- }),
12663
- // iv
12664
- new OctetString({
12665
- valueHex: iv
12666
- })
12667
- ]
12668
- })
12669
- ]
12670
- })
12671
- ]
12672
- });
12673
- const finalWrapper = new Sequence({
12674
- value: [
12675
- encryptionAlgorithm,
12676
- new OctetString({ valueHex: encrypted })
12677
- ]
12678
- });
12679
- const finalWrapperBuf = finalWrapper.toBER();
12680
- const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);
12681
- return [
12682
- '-----BEGIN ENCRYPTED PRIVATE KEY-----',
12683
- ...toString$1(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),
12684
- '-----END ENCRYPTED PRIVATE KEY-----'
12685
- ].join('\n');
12686
- }
12152
+ return nativeCrypto;
12153
+ }
12154
+ };
12687
12155
 
12688
- async function generateKey$1(bits) {
12689
- const pair = await webcrypto.get().subtle.generateKey({
12690
- name: 'RSASSA-PKCS1-v1_5',
12691
- modulusLength: bits,
12692
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
12693
- hash: { name: 'SHA-256' }
12694
- }, true, ['sign', 'verify']);
12695
- const keys = await exportKey(pair);
12696
- return {
12697
- privateKey: keys[0],
12698
- publicKey: keys[1]
12699
- };
12700
- }
12701
- // Takes a jwk key
12702
- async function unmarshalPrivateKey$1(key) {
12703
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12704
- name: 'RSASSA-PKCS1-v1_5',
12705
- hash: { name: 'SHA-256' }
12706
- }, true, ['sign']);
12707
- const pair = [
12708
- privateKey,
12709
- await derivePublicFromPrivate(key)
12710
- ];
12711
- const keys = await exportKey({
12712
- privateKey: pair[0],
12713
- publicKey: pair[1]
12714
- });
12715
- return {
12716
- privateKey: keys[0],
12717
- publicKey: keys[1]
12718
- };
12719
- }
12720
- async function hashAndSign$1(key, msg) {
12721
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12722
- name: 'RSASSA-PKCS1-v1_5',
12723
- hash: { name: 'SHA-256' }
12724
- }, false, ['sign']);
12725
- const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
12726
- return new Uint8Array(sig, 0, sig.byteLength);
12727
- }
12728
12156
  async function hashAndVerify$1(key, sig, msg) {
12729
12157
  const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
12730
12158
  name: 'RSASSA-PKCS1-v1_5',
@@ -12732,173 +12160,222 @@ async function hashAndVerify$1(key, sig, msg) {
12732
12160
  }, false, ['verify']);
12733
12161
  return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
12734
12162
  }
12735
- async function exportKey(pair) {
12736
- if (pair.privateKey == null || pair.publicKey == null) {
12737
- throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
12738
- }
12739
- return Promise.all([
12740
- webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
12741
- webcrypto.get().subtle.exportKey('jwk', pair.publicKey)
12742
- ]);
12743
- }
12744
- async function derivePublicFromPrivate(jwKey) {
12745
- return webcrypto.get().subtle.importKey('jwk', {
12746
- kty: jwKey.kty,
12747
- n: jwKey.n,
12748
- e: jwKey.e
12749
- }, {
12750
- name: 'RSASSA-PKCS1-v1_5',
12751
- hash: { name: 'SHA-256' }
12752
- }, true, ['verify']);
12753
- }
12754
- function keySize(jwk) {
12163
+ function rsaKeySize(jwk) {
12755
12164
  if (jwk.kty !== 'RSA') {
12756
- throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');
12165
+ throw new InvalidParametersError('invalid key type');
12757
12166
  }
12758
12167
  else if (jwk.n == null) {
12759
- throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');
12168
+ throw new InvalidParametersError('invalid key modulus');
12760
12169
  }
12761
12170
  const bytes = fromString(jwk.n, 'base64url');
12762
12171
  return bytes.length * 8;
12763
12172
  }
12764
12173
 
12765
- const MAX_RSA_KEY_SIZE = 8192;
12766
- class RsaPublicKey {
12174
+ class RSAPublicKey {
12175
+ type = 'RSA';
12767
12176
  _key;
12768
- constructor(key) {
12177
+ _raw;
12178
+ _multihash;
12179
+ constructor(key, digest) {
12769
12180
  this._key = key;
12181
+ this._multihash = digest;
12770
12182
  }
12771
- verify(data, sig) {
12772
- return hashAndVerify$1(this._key, sig, data);
12773
- }
12774
- marshal() {
12775
- return jwkToPkix(this._key);
12776
- }
12777
- get bytes() {
12778
- return PublicKey.encode({
12779
- Type: KeyType.RSA,
12780
- Data: this.marshal()
12781
- }).subarray();
12782
- }
12783
- equals(key) {
12784
- return equals(this.bytes, key.bytes);
12785
- }
12786
- hash() {
12787
- const p = sha256$1.digest(this.bytes);
12788
- if (isPromise(p)) {
12789
- return p.then(({ bytes }) => bytes);
12183
+ get raw() {
12184
+ if (this._raw == null) {
12185
+ this._raw = jwkToPkix(this._key);
12790
12186
  }
12791
- return p.bytes;
12187
+ return this._raw;
12792
12188
  }
12793
- }
12794
- class RsaPrivateKey {
12795
- _key;
12796
- _publicKey;
12797
- constructor(key, publicKey) {
12798
- this._key = key;
12799
- this._publicKey = publicKey;
12800
- }
12801
- genSecret() {
12802
- return randomBytes(16);
12803
- }
12804
- sign(message) {
12805
- return hashAndSign$1(this._key, message);
12189
+ toMultihash() {
12190
+ return this._multihash;
12806
12191
  }
12807
- get public() {
12808
- if (this._publicKey == null) {
12809
- throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
12810
- }
12811
- return new RsaPublicKey(this._publicKey);
12812
- }
12813
- marshal() {
12814
- return jwkToPkcs1(this._key);
12192
+ toCID() {
12193
+ return CID.createV1(114, this._multihash);
12815
12194
  }
12816
- get bytes() {
12817
- return PrivateKey.encode({
12818
- Type: KeyType.RSA,
12819
- Data: this.marshal()
12820
- }).subarray();
12195
+ toString() {
12196
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
12821
12197
  }
12822
12198
  equals(key) {
12823
- return equals(this.bytes, key.bytes);
12824
- }
12825
- hash() {
12826
- const p = sha256$1.digest(this.bytes);
12827
- if (isPromise(p)) {
12828
- return p.then(({ bytes }) => bytes);
12199
+ if (key == null || !(key.raw instanceof Uint8Array)) {
12200
+ return false;
12829
12201
  }
12830
- return p.bytes;
12202
+ return equals(this.raw, key.raw);
12831
12203
  }
12832
- /**
12833
- * Gets the ID of the key.
12834
- *
12835
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
12836
- * The public key is a protobuf encoding containing a type and the DER encoding
12837
- * of the PKCS SubjectPublicKeyInfo.
12838
- */
12839
- async id() {
12840
- const hash = await this.public.hash();
12841
- return toString$1(hash, 'base58btc');
12204
+ verify(data, sig) {
12205
+ return hashAndVerify$1(this._key, sig, data);
12842
12206
  }
12843
- /**
12844
- * Exports the key as libp2p-key - a aes-gcm encrypted value with the key
12845
- * derived from the password.
12846
- *
12847
- * To export it as a password protected PEM file, please use the `exportPEM`
12848
- * function from `@libp2p/rsa`.
12849
- */
12850
- async export(password, format = 'pkcs-8') {
12851
- if (format === 'pkcs-8') {
12852
- return exportToPem(this, password);
12853
- }
12854
- else if (format === 'libp2p-key') {
12855
- return exporter(this.bytes, password);
12856
- }
12857
- else {
12858
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
12859
- }
12207
+ }
12208
+
12209
+ const MAX_RSA_KEY_SIZE = 8192;
12210
+ const SHA2_256_CODE = 0x12;
12211
+ /**
12212
+ * Convert a PKIX in ASN1 DER format to a JWK key
12213
+ */
12214
+ function pkixToJwk(bytes) {
12215
+ const { result } = fromBER(bytes);
12216
+ // @ts-expect-error this looks fragile but DER is a canonical format so we are
12217
+ // safe to have deeply property chains like this
12218
+ const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12219
+ return {
12220
+ kty: 'RSA',
12221
+ n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
12222
+ e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
12223
+ };
12224
+ }
12225
+ /**
12226
+ * Convert a JWK key to PKIX in ASN1 DER format
12227
+ */
12228
+ function jwkToPkix(jwk) {
12229
+ if (jwk.n == null || jwk.e == null) {
12230
+ throw new InvalidParametersError('JWK was missing components');
12860
12231
  }
12232
+ const root = new Sequence({
12233
+ value: [
12234
+ new Sequence({
12235
+ value: [
12236
+ // rsaEncryption
12237
+ new ObjectIdentifier({
12238
+ value: '1.2.840.113549.1.1.1'
12239
+ }),
12240
+ new Null()
12241
+ ]
12242
+ }),
12243
+ // this appears to be a bug in asn1js.js - this should really be a Sequence
12244
+ // and not a BitString but it generates the same bytes as node-forge so ๐Ÿคทโ€โ™‚๏ธ
12245
+ new BitString({
12246
+ valueHex: new Sequence({
12247
+ value: [
12248
+ Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
12249
+ Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url')))
12250
+ ]
12251
+ }).toBER()
12252
+ })
12253
+ ]
12254
+ });
12255
+ const der = root.toBER();
12256
+ return new Uint8Array(der, 0, der.byteLength);
12861
12257
  }
12862
- async function unmarshalRsaPrivateKey(bytes) {
12863
- const jwk = pkcs1ToJwk(bytes);
12864
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12865
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12258
+ function bnToBuf(bn) {
12259
+ let hex = bn.toString(16);
12260
+ if (hex.length % 2 > 0) {
12261
+ hex = `0${hex}`;
12262
+ }
12263
+ const len = hex.length / 2;
12264
+ const u8 = new Uint8Array(len);
12265
+ let i = 0;
12266
+ let j = 0;
12267
+ while (i < len) {
12268
+ u8[i] = parseInt(hex.slice(j, j + 2), 16);
12269
+ i += 1;
12270
+ j += 2;
12866
12271
  }
12867
- const keys = await unmarshalPrivateKey$1(jwk);
12868
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12272
+ return u8;
12869
12273
  }
12870
- function unmarshalRsaPublicKey(bytes) {
12274
+ function bufToBn(u8) {
12275
+ const hex = [];
12276
+ u8.forEach(function (i) {
12277
+ let h = i.toString(16);
12278
+ if (h.length % 2 > 0) {
12279
+ h = `0${h}`;
12280
+ }
12281
+ hex.push(h);
12282
+ });
12283
+ return BigInt('0x' + hex.join(''));
12284
+ }
12285
+ /**
12286
+ * Turn PKIX bytes to a PublicKey
12287
+ */
12288
+ function pkixToRSAPublicKey(bytes) {
12871
12289
  const jwk = pkixToJwk(bytes);
12872
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12873
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12290
+ if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {
12291
+ throw new InvalidPublicKeyError('Key size is too large');
12874
12292
  }
12875
- return new RsaPublicKey(jwk);
12293
+ const hash = sha256(PublicKey.encode({
12294
+ Type: KeyType.RSA,
12295
+ Data: bytes
12296
+ }));
12297
+ const digest = create(SHA2_256_CODE, hash);
12298
+ return new RSAPublicKey(jwk, digest);
12876
12299
  }
12877
- async function fromJwk(jwk) {
12878
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12879
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12300
+
12301
+ // HMAC (RFC 2104)
12302
+ class HMAC extends Hash {
12303
+ constructor(hash$1, _key) {
12304
+ super();
12305
+ this.finished = false;
12306
+ this.destroyed = false;
12307
+ hash(hash$1);
12308
+ const key = toBytes$1(_key);
12309
+ this.iHash = hash$1.create();
12310
+ if (typeof this.iHash.update !== 'function')
12311
+ throw new Error('Expected instance of class which extends utils.Hash');
12312
+ this.blockLen = this.iHash.blockLen;
12313
+ this.outputLen = this.iHash.outputLen;
12314
+ const blockLen = this.blockLen;
12315
+ const pad = new Uint8Array(blockLen);
12316
+ // blockLen can be bigger than outputLen
12317
+ pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12318
+ for (let i = 0; i < pad.length; i++)
12319
+ pad[i] ^= 0x36;
12320
+ this.iHash.update(pad);
12321
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12322
+ this.oHash = hash$1.create();
12323
+ // Undo internal XOR && apply outer XOR
12324
+ for (let i = 0; i < pad.length; i++)
12325
+ pad[i] ^= 0x36 ^ 0x5c;
12326
+ this.oHash.update(pad);
12327
+ pad.fill(0);
12880
12328
  }
12881
- const keys = await unmarshalPrivateKey$1(jwk);
12882
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12883
- }
12884
- async function generateKeyPair$1(bits) {
12885
- if (bits > MAX_RSA_KEY_SIZE) {
12886
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12329
+ update(buf) {
12330
+ exists(this);
12331
+ this.iHash.update(buf);
12332
+ return this;
12333
+ }
12334
+ digestInto(out) {
12335
+ exists(this);
12336
+ bytes(out, this.outputLen);
12337
+ this.finished = true;
12338
+ this.iHash.digestInto(out);
12339
+ this.oHash.update(out);
12340
+ this.oHash.digestInto(out);
12341
+ this.destroy();
12342
+ }
12343
+ digest() {
12344
+ const out = new Uint8Array(this.oHash.outputLen);
12345
+ this.digestInto(out);
12346
+ return out;
12347
+ }
12348
+ _cloneInto(to) {
12349
+ // Create new instance without calling constructor since key already in state and we don't know it.
12350
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
12351
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
12352
+ to = to;
12353
+ to.finished = finished;
12354
+ to.destroyed = destroyed;
12355
+ to.blockLen = blockLen;
12356
+ to.outputLen = outputLen;
12357
+ to.oHash = oHash._cloneInto(to.oHash);
12358
+ to.iHash = iHash._cloneInto(to.iHash);
12359
+ return to;
12360
+ }
12361
+ destroy() {
12362
+ this.destroyed = true;
12363
+ this.oHash.destroy();
12364
+ this.iHash.destroy();
12887
12365
  }
12888
- const keys = await generateKey$1(bits);
12889
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12890
12366
  }
12891
-
12892
- var RSA = /*#__PURE__*/Object.freeze({
12893
- __proto__: null,
12894
- MAX_RSA_KEY_SIZE: MAX_RSA_KEY_SIZE,
12895
- RsaPrivateKey: RsaPrivateKey,
12896
- RsaPublicKey: RsaPublicKey,
12897
- fromJwk: fromJwk,
12898
- generateKeyPair: generateKeyPair$1,
12899
- unmarshalRsaPrivateKey: unmarshalRsaPrivateKey,
12900
- unmarshalRsaPublicKey: unmarshalRsaPublicKey
12901
- });
12367
+ /**
12368
+ * HMAC: RFC2104 message authentication code.
12369
+ * @param hash - function that would be used e.g. sha256
12370
+ * @param key - message key
12371
+ * @param message - message data
12372
+ * @example
12373
+ * import { hmac } from '@noble/hashes/hmac';
12374
+ * import { sha256 } from '@noble/hashes/sha2';
12375
+ * const mac1 = hmac(sha256, 'key', 'message');
12376
+ */
12377
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12378
+ hmac.create = (hash, key) => new HMAC(hash, key);
12902
12379
 
12903
12380
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12904
12381
  // Short Weierstrass curve. The formula is: yยฒ = xยณ + ax + b
@@ -12935,8 +12412,14 @@ function validatePointOpts(curve) {
12935
12412
  }
12936
12413
  return Object.freeze({ ...opts });
12937
12414
  }
12938
- // ASN.1 DER encoding utilities
12939
12415
  const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
12416
+ /**
12417
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
12418
+ *
12419
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
12420
+ *
12421
+ * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
12422
+ */
12940
12423
  const DER = {
12941
12424
  // asn.1 DER encoding utils
12942
12425
  Err: class DERErr extends Error {
@@ -12944,54 +12427,103 @@ const DER = {
12944
12427
  super(m);
12945
12428
  }
12946
12429
  },
12947
- _parseInt(data) {
12948
- const { Err: E } = DER;
12949
- if (data.length < 2 || data[0] !== 0x02)
12950
- throw new E('Invalid signature integer tag');
12951
- const len = data[1];
12952
- const res = data.subarray(2, len + 2);
12953
- if (!len || res.length !== len)
12954
- throw new E('Invalid signature integer: wrong length');
12955
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
12956
- // since we always use positive integers here. It must always be empty:
12957
- // - add zero byte if exists
12958
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
12959
- if (res[0] & 0b10000000)
12960
- throw new E('Invalid signature integer: negative');
12961
- if (res[0] === 0x00 && !(res[1] & 0b10000000))
12962
- throw new E('Invalid signature integer: unnecessary leading zero');
12963
- return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
12430
+ // Basic building block is TLV (Tag-Length-Value)
12431
+ _tlv: {
12432
+ encode: (tag, data) => {
12433
+ const { Err: E } = DER;
12434
+ if (tag < 0 || tag > 256)
12435
+ throw new E('tlv.encode: wrong tag');
12436
+ if (data.length & 1)
12437
+ throw new E('tlv.encode: unpadded data');
12438
+ const dataLen = data.length / 2;
12439
+ const len = numberToHexUnpadded(dataLen);
12440
+ if ((len.length / 2) & 128)
12441
+ throw new E('tlv.encode: long form length too big');
12442
+ // length of length with long form flag
12443
+ const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
12444
+ return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
12445
+ },
12446
+ // v - value, l - left bytes (unparsed)
12447
+ decode(tag, data) {
12448
+ const { Err: E } = DER;
12449
+ let pos = 0;
12450
+ if (tag < 0 || tag > 256)
12451
+ throw new E('tlv.encode: wrong tag');
12452
+ if (data.length < 2 || data[pos++] !== tag)
12453
+ throw new E('tlv.decode: wrong tlv');
12454
+ const first = data[pos++];
12455
+ const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
12456
+ let length = 0;
12457
+ if (!isLong)
12458
+ length = first;
12459
+ else {
12460
+ // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
12461
+ const lenLen = first & 127;
12462
+ if (!lenLen)
12463
+ throw new E('tlv.decode(long): indefinite length not supported');
12464
+ if (lenLen > 4)
12465
+ throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
12466
+ const lengthBytes = data.subarray(pos, pos + lenLen);
12467
+ if (lengthBytes.length !== lenLen)
12468
+ throw new E('tlv.decode: length bytes not complete');
12469
+ if (lengthBytes[0] === 0)
12470
+ throw new E('tlv.decode(long): zero leftmost byte');
12471
+ for (const b of lengthBytes)
12472
+ length = (length << 8) | b;
12473
+ pos += lenLen;
12474
+ if (length < 128)
12475
+ throw new E('tlv.decode(long): not minimal encoding');
12476
+ }
12477
+ const v = data.subarray(pos, pos + length);
12478
+ if (v.length !== length)
12479
+ throw new E('tlv.decode: wrong value length');
12480
+ return { v, l: data.subarray(pos + length) };
12481
+ },
12482
+ },
12483
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
12484
+ // since we always use positive integers here. It must always be empty:
12485
+ // - add zero byte if exists
12486
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
12487
+ _int: {
12488
+ encode(num) {
12489
+ const { Err: E } = DER;
12490
+ if (num < _0n)
12491
+ throw new E('integer: negative integers are not allowed');
12492
+ let hex = numberToHexUnpadded(num);
12493
+ // Pad with zero byte if negative flag is present
12494
+ if (Number.parseInt(hex[0], 16) & 0b1000)
12495
+ hex = '00' + hex;
12496
+ if (hex.length & 1)
12497
+ throw new E('unexpected assertion');
12498
+ return hex;
12499
+ },
12500
+ decode(data) {
12501
+ const { Err: E } = DER;
12502
+ if (data[0] & 128)
12503
+ throw new E('Invalid signature integer: negative');
12504
+ if (data[0] === 0x00 && !(data[1] & 128))
12505
+ throw new E('Invalid signature integer: unnecessary leading zero');
12506
+ return b2n(data);
12507
+ },
12964
12508
  },
12965
12509
  toSig(hex) {
12966
12510
  // parse DER signature
12967
- const { Err: E } = DER;
12511
+ const { Err: E, _int: int, _tlv: tlv } = DER;
12968
12512
  const data = typeof hex === 'string' ? h2b(hex) : hex;
12969
12513
  abytes(data);
12970
- let l = data.length;
12971
- if (l < 2 || data[0] != 0x30)
12972
- throw new E('Invalid signature tag');
12973
- if (data[1] !== l - 2)
12974
- throw new E('Invalid signature: incorrect length');
12975
- const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
12976
- const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
12977
- if (rBytesLeft.length)
12514
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
12515
+ if (seqLeftBytes.length)
12978
12516
  throw new E('Invalid signature: left bytes after parsing');
12979
- return { r, s };
12517
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
12518
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
12519
+ if (sLeftBytes.length)
12520
+ throw new E('Invalid signature: left bytes after parsing');
12521
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
12980
12522
  },
12981
12523
  hexFromSig(sig) {
12982
- // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
12983
- const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
12984
- const h = (num) => {
12985
- const hex = num.toString(16);
12986
- return hex.length & 1 ? `0${hex}` : hex;
12987
- };
12988
- const s = slice(h(sig.s));
12989
- const r = slice(h(sig.r));
12990
- const shl = s.length / 2;
12991
- const rhl = r.length / 2;
12992
- const sl = h(shl);
12993
- const rl = h(rhl);
12994
- return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
12524
+ const { _tlv: tlv, _int: int } = DER;
12525
+ const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
12526
+ return tlv.encode(0x30, seq);
12995
12527
  },
12996
12528
  };
12997
12529
  // Be friendly to bad ECMAScript parsers by not using bigint literals
@@ -13000,6 +12532,7 @@ const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigI
13000
12532
  function weierstrassPoints(opts) {
13001
12533
  const CURVE = validatePointOpts(opts);
13002
12534
  const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
12535
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
13003
12536
  const toBytes = CURVE.toBytes ||
13004
12537
  ((_c, point, _isCompressed) => {
13005
12538
  const a = point.toAffine();
@@ -13173,6 +12706,10 @@ function weierstrassPoints(opts) {
13173
12706
  static fromPrivateKey(privateKey) {
13174
12707
  return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
13175
12708
  }
12709
+ // Multiscalar Multiplication
12710
+ static msm(points, scalars) {
12711
+ return pippenger(Point, Fn, points, scalars);
12712
+ }
13176
12713
  // "Private method", don't use it directly
13177
12714
  _setWindowSize(windowSize) {
13178
12715
  wnaf.setWindowSize(this, windowSize);
@@ -13858,7 +13395,7 @@ function getHash(hash) {
13858
13395
  return {
13859
13396
  hash,
13860
13397
  hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
13861
- randomBytes: randomBytes$1,
13398
+ randomBytes,
13862
13399
  };
13863
13400
  }
13864
13401
  function createCurve(curveDef, defHash) {
@@ -13951,27 +13488,15 @@ const secp256k1 = createCurve({
13951
13488
  BigInt(0);
13952
13489
  secp256k1.ProjectivePoint;
13953
13490
 
13954
- function generateKey() {
13955
- return secp256k1.utils.randomPrivateKey();
13956
- }
13957
- /**
13958
- * Hash and sign message with private key
13959
- */
13960
- function hashAndSign(key, msg) {
13961
- const p = sha256$1.digest(msg instanceof Uint8Array ? msg : msg.subarray());
13962
- if (isPromise(p)) {
13963
- return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
13964
- .catch(err => {
13965
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13966
- });
13967
- }
13968
- try {
13969
- return secp256k1.sign(p.digest, key).toDERRawBytes();
13970
- }
13971
- catch (err) {
13972
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13491
+ function isPromise(thing) {
13492
+ if (thing == null) {
13493
+ return false;
13973
13494
  }
13495
+ return typeof thing.then === 'function' &&
13496
+ typeof thing.catch === 'function' &&
13497
+ typeof thing.finally === 'function';
13974
13498
  }
13499
+
13975
13500
  /**
13976
13501
  * Hash message and verify signature with public key
13977
13502
  */
@@ -13980,207 +13505,114 @@ function hashAndVerify(key, sig, msg) {
13980
13505
  if (isPromise(p)) {
13981
13506
  return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
13982
13507
  .catch(err => {
13983
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13508
+ throw new VerificationError(String(err));
13984
13509
  });
13985
13510
  }
13986
13511
  try {
13987
13512
  return secp256k1.verify(sig, p.digest, key);
13988
13513
  }
13989
13514
  catch (err) {
13990
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13991
- }
13992
- }
13993
- function compressPublicKey(key) {
13994
- const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
13995
- return point;
13996
- }
13997
- function validatePrivateKey(key) {
13998
- try {
13999
- secp256k1.getPublicKey(key, true);
14000
- }
14001
- catch (err) {
14002
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
14003
- }
14004
- }
14005
- function validatePublicKey(key) {
14006
- try {
14007
- secp256k1.ProjectivePoint.fromHex(key);
14008
- }
14009
- catch (err) {
14010
- throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
14011
- }
14012
- }
14013
- function computePublicKey(privateKey) {
14014
- try {
14015
- return secp256k1.getPublicKey(privateKey, true);
14016
- }
14017
- catch (err) {
14018
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
13515
+ throw new VerificationError(String(err));
14019
13516
  }
14020
13517
  }
14021
13518
 
14022
13519
  class Secp256k1PublicKey {
13520
+ type = 'secp256k1';
13521
+ raw;
14023
13522
  _key;
14024
13523
  constructor(key) {
14025
- validatePublicKey(key);
14026
- this._key = key;
13524
+ this._key = validateSecp256k1PublicKey(key);
13525
+ this.raw = compressSecp256k1PublicKey(this._key);
14027
13526
  }
14028
- verify(data, sig) {
14029
- return hashAndVerify(this._key, sig, data);
14030
- }
14031
- marshal() {
14032
- return compressPublicKey(this._key);
14033
- }
14034
- get bytes() {
14035
- return PublicKey.encode({
14036
- Type: KeyType.Secp256k1,
14037
- Data: this.marshal()
14038
- }).subarray();
13527
+ toMultihash() {
13528
+ return identity.digest(publicKeyToProtobuf(this));
14039
13529
  }
14040
- equals(key) {
14041
- return equals(this.bytes, key.bytes);
14042
- }
14043
- async hash() {
14044
- const p = sha256$1.digest(this.bytes);
14045
- let bytes;
14046
- if (isPromise(p)) {
14047
- ({ bytes } = await p);
14048
- }
14049
- else {
14050
- bytes = p.bytes;
14051
- }
14052
- return bytes;
14053
- }
14054
- }
14055
- class Secp256k1PrivateKey {
14056
- _key;
14057
- _publicKey;
14058
- constructor(key, publicKey) {
14059
- this._key = key;
14060
- this._publicKey = publicKey ?? computePublicKey(key);
14061
- validatePrivateKey(this._key);
14062
- validatePublicKey(this._publicKey);
14063
- }
14064
- sign(message) {
14065
- return hashAndSign(this._key, message);
14066
- }
14067
- get public() {
14068
- return new Secp256k1PublicKey(this._publicKey);
14069
- }
14070
- marshal() {
14071
- return this._key;
13530
+ toCID() {
13531
+ return CID.createV1(114, this.toMultihash());
14072
13532
  }
14073
- get bytes() {
14074
- return PrivateKey.encode({
14075
- Type: KeyType.Secp256k1,
14076
- Data: this.marshal()
14077
- }).subarray();
13533
+ toString() {
13534
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
14078
13535
  }
14079
13536
  equals(key) {
14080
- return equals(this.bytes, key.bytes);
14081
- }
14082
- hash() {
14083
- const p = sha256$1.digest(this.bytes);
14084
- if (isPromise(p)) {
14085
- return p.then(({ bytes }) => bytes);
13537
+ if (key == null || !(key.raw instanceof Uint8Array)) {
13538
+ return false;
14086
13539
  }
14087
- return p.bytes;
13540
+ return equals(this.raw, key.raw);
14088
13541
  }
14089
- /**
14090
- * Gets the ID of the key.
14091
- *
14092
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
14093
- * The public key is a protobuf encoding containing a type and the DER encoding
14094
- * of the PKCS SubjectPublicKeyInfo.
14095
- */
14096
- async id() {
14097
- const hash = await this.public.hash();
14098
- return toString$1(hash, 'base58btc');
14099
- }
14100
- /**
14101
- * Exports the key into a password protected `format`
14102
- */
14103
- async export(password, format = 'libp2p-key') {
14104
- if (format === 'libp2p-key') {
14105
- return exporter(this.bytes, password);
14106
- }
14107
- else {
14108
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
14109
- }
13542
+ verify(data, sig) {
13543
+ return hashAndVerify(this._key, sig, data);
14110
13544
  }
14111
13545
  }
14112
- function unmarshalSecp256k1PrivateKey(bytes) {
14113
- return new Secp256k1PrivateKey(bytes);
14114
- }
13546
+
14115
13547
  function unmarshalSecp256k1PublicKey(bytes) {
14116
13548
  return new Secp256k1PublicKey(bytes);
14117
13549
  }
14118
- async function generateKeyPair() {
14119
- const privateKeyBytes = generateKey();
14120
- return new Secp256k1PrivateKey(privateKeyBytes);
13550
+ function compressSecp256k1PublicKey(key) {
13551
+ const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
13552
+ return point;
13553
+ }
13554
+ function validateSecp256k1PublicKey(key) {
13555
+ try {
13556
+ secp256k1.ProjectivePoint.fromHex(key);
13557
+ return key;
13558
+ }
13559
+ catch (err) {
13560
+ throw new InvalidPublicKeyError(String(err));
13561
+ }
14121
13562
  }
14122
-
14123
- var Secp256k1 = /*#__PURE__*/Object.freeze({
14124
- __proto__: null,
14125
- Secp256k1PrivateKey: Secp256k1PrivateKey,
14126
- Secp256k1PublicKey: Secp256k1PublicKey,
14127
- generateKeyPair: generateKeyPair,
14128
- unmarshalSecp256k1PrivateKey: unmarshalSecp256k1PrivateKey,
14129
- unmarshalSecp256k1PublicKey: unmarshalSecp256k1PublicKey
14130
- });
14131
13563
 
14132
13564
  /**
14133
13565
  * @packageDocumentation
14134
13566
  *
14135
- * **Supported Key Types**
14136
- *
14137
- * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.
13567
+ * ## Supported Key Types
14138
13568
  *
14139
13569
  * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
14140
13570
  *
14141
13571
  * For encryption / decryption support, RSA keys should be used.
14142
13572
  */
14143
- const supportedKeys = {
14144
- rsa: RSA,
14145
- ed25519: Ed25519,
14146
- secp256k1: Secp256k1
14147
- };
14148
- function unsupportedKey(type) {
14149
- const supported = Object.keys(supportedKeys).join(' / ');
14150
- return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
14151
- }
14152
13573
  /**
14153
- * Converts a protobuf serialized public key into its representative object
13574
+ * Creates a public key from the raw key bytes
14154
13575
  */
14155
- function unmarshalPublicKey(buf) {
14156
- const decoded = PublicKey.decode(buf);
14157
- const data = decoded.Data ?? new Uint8Array();
14158
- switch (decoded.Type) {
14159
- case KeyType.RSA:
14160
- return supportedKeys.rsa.unmarshalRsaPublicKey(data);
14161
- case KeyType.Ed25519:
14162
- return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);
14163
- case KeyType.Secp256k1:
14164
- return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);
14165
- default:
14166
- throw unsupportedKey(decoded.Type ?? 'unknown');
13576
+ function publicKeyFromRaw(buf) {
13577
+ if (buf.byteLength === 32) {
13578
+ return unmarshalEd25519PublicKey(buf);
13579
+ }
13580
+ else if (buf.byteLength === 33) {
13581
+ return unmarshalSecp256k1PublicKey(buf);
13582
+ }
13583
+ else {
13584
+ return pkixToRSAPublicKey(buf);
14167
13585
  }
14168
13586
  }
14169
13587
  /**
14170
- * Converts a protobuf serialized private key into its representative object
13588
+ * Converts a public key object into a protobuf serialized public key
14171
13589
  */
14172
- async function unmarshalPrivateKey(buf) {
14173
- const decoded = PrivateKey.decode(buf);
14174
- const data = decoded.Data ?? new Uint8Array();
14175
- switch (decoded.Type) {
14176
- case KeyType.RSA:
14177
- return supportedKeys.rsa.unmarshalRsaPrivateKey(data);
14178
- case KeyType.Ed25519:
14179
- return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);
14180
- case KeyType.Secp256k1:
14181
- return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);
14182
- default:
14183
- throw unsupportedKey(decoded.Type ?? 'RSA');
13590
+ function publicKeyToProtobuf(key) {
13591
+ return PublicKey.encode({
13592
+ Type: KeyType[key.type],
13593
+ Data: key.raw
13594
+ });
13595
+ }
13596
+
13597
+ /**
13598
+ * All PeerId implementations must use this symbol as the name of a property
13599
+ * with a boolean `true` value
13600
+ */
13601
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
13602
+
13603
+ /**
13604
+ * When this error is thrown it means an operation was aborted,
13605
+ * usually in response to the `abort` event being emitted by an
13606
+ * AbortSignal.
13607
+ */
13608
+ /**
13609
+ * Thrown when and attempt to operate on an unsupported key was made
13610
+ */
13611
+ class UnsupportedKeyTypeError extends Error {
13612
+ static name = 'UnsupportedKeyTypeError';
13613
+ constructor(message = 'Unsupported key type') {
13614
+ super(message);
13615
+ this.name = 'UnsupportedKeyTypeError';
14184
13616
  }
14185
13617
  }
14186
13618
 
@@ -14200,25 +13632,16 @@ async function unmarshalPrivateKey(buf) {
14200
13632
  * ```
14201
13633
  */
14202
13634
  const inspect = Symbol.for('nodejs.util.inspect.custom');
14203
- const baseDecoder = Object
14204
- .values(bases)
14205
- .map(codec => codec.decoder)
14206
- // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
14207
- .reduce((acc, curr) => acc.or(curr), bases.identity.decoder);
14208
13635
  // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14209
13636
  const LIBP2P_KEY_CODE = 0x72;
14210
- const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;
14211
- const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;
14212
13637
  class PeerIdImpl {
14213
13638
  type;
14214
13639
  multihash;
14215
- privateKey;
14216
13640
  publicKey;
14217
13641
  string;
14218
13642
  constructor(init) {
14219
13643
  this.type = init.type;
14220
13644
  this.multihash = init.multihash;
14221
- this.privateKey = init.privateKey;
14222
13645
  // mark string cache as non-enumerable
14223
13646
  Object.defineProperty(this, 'string', {
14224
13647
  enumerable: false,
@@ -14235,17 +13658,14 @@ class PeerIdImpl {
14235
13658
  }
14236
13659
  return this.string;
14237
13660
  }
13661
+ toMultihash() {
13662
+ return this.multihash;
13663
+ }
14238
13664
  // return self-describing String representation
14239
13665
  // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
14240
13666
  toCID() {
14241
13667
  return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
14242
13668
  }
14243
- toBytes() {
14244
- return this.multihash.bytes;
14245
- }
14246
- /**
14247
- * Returns Multiaddr as a JSON string
14248
- */
14249
13669
  toJSON() {
14250
13670
  return this.toString();
14251
13671
  }
@@ -14260,10 +13680,10 @@ class PeerIdImpl {
14260
13680
  return equals(this.multihash.bytes, id);
14261
13681
  }
14262
13682
  else if (typeof id === 'string') {
14263
- return peerIdFromString(id).equals(this);
13683
+ return this.toString() === id;
14264
13684
  }
14265
- else if (id?.multihash?.bytes != null) {
14266
- return equals(this.multihash.bytes, id.multihash.bytes);
13685
+ else if (id?.toMultihash()?.bytes != null) {
13686
+ return equals(this.multihash.bytes, id.toMultihash().bytes);
14267
13687
  }
14268
13688
  else {
14269
13689
  throw new Error('not valid Id');
@@ -14285,7 +13705,7 @@ class PeerIdImpl {
14285
13705
  return `PeerId(${this.toString()})`;
14286
13706
  }
14287
13707
  }
14288
- class RSAPeerIdImpl extends PeerIdImpl {
13708
+ class RSAPeerId extends PeerIdImpl {
14289
13709
  type = 'RSA';
14290
13710
  publicKey;
14291
13711
  constructor(init) {
@@ -14293,153 +13713,67 @@ class RSAPeerIdImpl extends PeerIdImpl {
14293
13713
  this.publicKey = init.publicKey;
14294
13714
  }
14295
13715
  }
14296
- class Ed25519PeerIdImpl extends PeerIdImpl {
13716
+ class Ed25519PeerId extends PeerIdImpl {
14297
13717
  type = 'Ed25519';
14298
13718
  publicKey;
14299
13719
  constructor(init) {
14300
13720
  super({ ...init, type: 'Ed25519' });
14301
- this.publicKey = init.multihash.digest;
13721
+ this.publicKey = init.publicKey;
14302
13722
  }
14303
13723
  }
14304
- class Secp256k1PeerIdImpl extends PeerIdImpl {
13724
+ class Secp256k1PeerId extends PeerIdImpl {
14305
13725
  type = 'secp256k1';
14306
13726
  publicKey;
14307
13727
  constructor(init) {
14308
13728
  super({ ...init, type: 'secp256k1' });
14309
- this.publicKey = init.multihash.digest;
14310
- }
14311
- }
14312
- // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14313
- const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
14314
- class URLPeerIdImpl {
14315
- type = 'url';
14316
- multihash;
14317
- privateKey;
14318
- publicKey;
14319
- url;
14320
- constructor(url) {
14321
- this.url = url.toString();
14322
- this.multihash = identity.digest(fromString(this.url));
14323
- }
14324
- [inspect]() {
14325
- return `PeerId(${this.url})`;
14326
- }
14327
- [peerIdSymbol] = true;
14328
- toString() {
14329
- return this.toCID().toString();
14330
- }
14331
- toCID() {
14332
- return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
14333
- }
14334
- toBytes() {
14335
- return this.toCID().bytes;
14336
- }
14337
- equals(other) {
14338
- if (other == null) {
14339
- return false;
14340
- }
14341
- if (other instanceof Uint8Array) {
14342
- other = toString$1(other);
14343
- }
14344
- return other.toString() === this.toString();
14345
- }
14346
- }
14347
- function peerIdFromString(str, decoder) {
14348
- if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
14349
- // identity hash ed25519/secp256k1 key or sha2-256 hash of
14350
- // rsa public key - base58btc encoded either way
14351
- const multihash = decode$2(base58btc.decode(`z${str}`));
14352
- if (str.startsWith('12D')) {
14353
- return new Ed25519PeerIdImpl({ multihash });
14354
- }
14355
- else if (str.startsWith('16U')) {
14356
- return new Secp256k1PeerIdImpl({ multihash });
14357
- }
14358
- else {
14359
- return new RSAPeerIdImpl({ multihash });
14360
- }
14361
- }
14362
- return peerIdFromBytes(baseDecoder.decode(str));
14363
- }
14364
- function peerIdFromBytes(buf) {
14365
- try {
14366
- const multihash = decode$2(buf);
14367
- if (multihash.code === identity.code) {
14368
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14369
- return new Ed25519PeerIdImpl({ multihash });
14370
- }
14371
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14372
- return new Secp256k1PeerIdImpl({ multihash });
14373
- }
14374
- }
14375
- if (multihash.code === sha256$1.code) {
14376
- return new RSAPeerIdImpl({ multihash });
14377
- }
14378
- }
14379
- catch {
14380
- return peerIdFromCID(CID.decode(buf));
14381
- }
14382
- throw new Error('Supplied PeerID CID is invalid');
14383
- }
14384
- function peerIdFromCID(cid) {
14385
- if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
14386
- throw new Error('Supplied PeerID CID is invalid');
14387
- }
14388
- if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
14389
- const url = toString$1(cid.multihash.digest);
14390
- return new URLPeerIdImpl(new URL(url));
14391
- }
14392
- const multihash = cid.multihash;
14393
- if (multihash.code === sha256$1.code) {
14394
- return new RSAPeerIdImpl({ multihash: cid.multihash });
14395
- }
14396
- else if (multihash.code === identity.code) {
14397
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14398
- return new Ed25519PeerIdImpl({ multihash: cid.multihash });
14399
- }
14400
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14401
- return new Secp256k1PeerIdImpl({ multihash: cid.multihash });
14402
- }
13729
+ this.publicKey = init.publicKey;
14403
13730
  }
14404
- throw new Error('Supplied PeerID CID is invalid');
14405
13731
  }
13732
+
14406
13733
  /**
14407
- * @param publicKey - A marshalled public key
14408
- * @param privateKey - A marshalled private key
13734
+ * @packageDocumentation
13735
+ *
13736
+ * An implementation of a peer id
13737
+ *
13738
+ * @example
13739
+ *
13740
+ * ```TypeScript
13741
+ * import { peerIdFromString } from '@libp2p/peer-id'
13742
+ * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
13743
+ *
13744
+ * console.log(peer.toCID()) // CID(bafzaa...)
13745
+ * console.log(peer.toString()) // "12D3K..."
13746
+ * ```
14409
13747
  */
14410
- async function peerIdFromKeys(publicKey, privateKey) {
14411
- if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14412
- return new Ed25519PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13748
+ function peerIdFromPublicKey(publicKey) {
13749
+ if (publicKey.type === 'Ed25519') {
13750
+ return new Ed25519PeerId({
13751
+ multihash: publicKey.toCID().multihash,
13752
+ publicKey
13753
+ });
13754
+ }
13755
+ else if (publicKey.type === 'secp256k1') {
13756
+ return new Secp256k1PeerId({
13757
+ multihash: publicKey.toCID().multihash,
13758
+ publicKey
13759
+ });
14413
13760
  }
14414
- if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14415
- return new Secp256k1PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13761
+ else if (publicKey.type === 'RSA') {
13762
+ return new RSAPeerId({
13763
+ multihash: publicKey.toCID().multihash,
13764
+ publicKey
13765
+ });
14416
13766
  }
14417
- return new RSAPeerIdImpl({ multihash: await sha256$1.digest(publicKey), publicKey, privateKey });
13767
+ throw new UnsupportedKeyTypeError();
14418
13768
  }
14419
13769
 
13770
+ const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
14420
13771
  function createPeerIdFromPublicKey(publicKey) {
14421
- const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
14422
- return peerIdFromKeys(_publicKey.bytes, undefined);
14423
- }
14424
- function getPublicKeyFromPeerId(peerId) {
14425
- if (peerId.type !== "secp256k1") {
14426
- throw new Error("Unsupported peer id type");
14427
- }
14428
- if (!peerId.publicKey) {
14429
- throw new Error("Public key not present on peer id");
14430
- }
14431
- return unmarshalPublicKey(peerId.publicKey).marshal();
14432
- }
14433
- // Only used in tests
14434
- async function getPrivateKeyFromPeerId(peerId) {
14435
- if (peerId.type !== "secp256k1") {
14436
- throw new Error("Unsupported peer id type");
14437
- }
14438
- if (!peerId.privateKey) {
14439
- throw new Error("Private key not present on peer id");
13772
+ const pubKey = publicKeyFromRaw(publicKey);
13773
+ if (pubKey.type !== "secp256k1") {
13774
+ throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
14440
13775
  }
14441
- const privateKey = await unmarshalPrivateKey(peerId.privateKey);
14442
- return privateKey.marshal();
13776
+ return peerIdFromPublicKey(pubKey);
14443
13777
  }
14444
13778
 
14445
13779
  function decodeMultiaddrs(bytes) {
@@ -14686,12 +14020,12 @@ var TransportProtocolPerIpVersion;
14686
14020
  class ENR extends RawEnr {
14687
14021
  static RECORD_PREFIX = "enr:";
14688
14022
  peerId;
14689
- static async create(kvs = {}, seq = BigInt(1), signature) {
14023
+ static create(kvs = {}, seq = BigInt(1), signature) {
14690
14024
  const enr = new ENR(kvs, seq, signature);
14691
14025
  try {
14692
14026
  const publicKey = enr.publicKey;
14693
14027
  if (publicKey) {
14694
- enr.peerId = await createPeerIdFromPublicKey(publicKey);
14028
+ enr.peerId = createPeerIdFromPublicKey(publicKey);
14695
14029
  }
14696
14030
  }
14697
14031
  catch (e) {
@@ -14813,7 +14147,7 @@ class EnrCreator {
14813
14147
  static fromPublicKey(publicKey, kvs = {}) {
14814
14148
  // EIP-778 specifies that the key must be in compressed format, 33 bytes
14815
14149
  if (publicKey.length !== 33) {
14816
- publicKey = compressPublicKey$1(publicKey);
14150
+ publicKey = compressPublicKey(publicKey);
14817
14151
  }
14818
14152
  return ENR.create({
14819
14153
  ...kvs,
@@ -14824,7 +14158,7 @@ class EnrCreator {
14824
14158
  static async fromPeerId(peerId, kvs = {}) {
14825
14159
  switch (peerId.type) {
14826
14160
  case "secp256k1":
14827
- return EnrCreator.fromPublicKey(getPublicKeyFromPeerId(peerId), kvs);
14161
+ return EnrCreator.fromPublicKey(peerId.publicKey.raw, kvs);
14828
14162
  default:
14829
14163
  throw new Error();
14830
14164
  }
@@ -15478,7 +14812,7 @@ async function fromValues(values) {
15478
14812
  }
15479
14813
  }
15480
14814
  const _seq = decodeSeq(seq);
15481
- const enr = await ENR.create(obj, _seq, signature);
14815
+ const enr = ENR.create(obj, _seq, signature);
15482
14816
  checkSignature(seq, kvs, enr, signature);
15483
14817
  return enr;
15484
14818
  }
@@ -15511,4 +14845,4 @@ function checkSignature(seq, kvs, enr, signature) {
15511
14845
  }
15512
14846
  }
15513
14847
 
15514
- export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey$1 as compressPublicKey, createPeerIdFromPublicKey, decodeWaku2, encodeWaku2, getPrivateKeyFromPeerId, getPublicKeyFromPeerId, keccak256, sign$1 as sign, verifySignature };
14848
+ export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, ERR_TYPE_NOT_IMPLEMENTED, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey, createPeerIdFromPublicKey, decodeWaku2, encodeWaku2, keccak256, sign$1 as sign, verifySignature };