@waku/discovery 0.0.6-535a20f.0 → 0.0.6-98208d5.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
@@ -19,21 +19,35 @@
19
19
  */
20
20
  const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');
21
21
 
22
- const peerIdSymbol = Symbol.for('@libp2p/peer-id');
22
+ /**
23
+ * All PeerId implementations must use this symbol as the name of a property
24
+ * with a boolean `true` value
25
+ */
26
+ const peerIdSymbol$1 = Symbol.for('@libp2p/peer-id');
23
27
 
24
28
  /**
25
29
  * When this error is thrown it means an operation was aborted,
26
30
  * usually in response to the `abort` event being emitted by an
27
31
  * AbortSignal.
28
32
  */
29
- class CodeError extends Error {
30
- code;
31
- props;
32
- constructor(message, code, props) {
33
+ /**
34
+ * Thrown when invalid parameters are passed to a function or method call
35
+ */
36
+ let InvalidParametersError$1 = class InvalidParametersError extends Error {
37
+ static name = 'InvalidParametersError';
38
+ constructor(message = 'Invalid parameters') {
33
39
  super(message);
34
- this.code = code;
35
- this.name = props?.name ?? 'CodeError';
36
- this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
40
+ this.name = 'InvalidParametersError';
41
+ }
42
+ };
43
+ /**
44
+ * Thrown when an invalid multihash is encountered
45
+ */
46
+ class InvalidMultihashError extends Error {
47
+ static name = 'InvalidMultihashError';
48
+ constructor(message = 'Invalid Multihash') {
49
+ super(message);
50
+ this.name = 'InvalidMultihashError';
37
51
  }
38
52
  }
39
53
 
@@ -104,7 +118,6 @@ class TypedEventEmitter extends EventTarget {
104
118
  return this.dispatchEvent(new CustomEvent(type, detail));
105
119
  }
106
120
  }
107
- const CustomEvent = globalThis.CustomEvent;
108
121
 
109
122
  var Protocols;
110
123
  (function (Protocols) {
@@ -282,23 +295,6 @@ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLen
282
295
  // The rotate right (circular right shift) operation for uint32
283
296
  const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
284
297
  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
285
- // There is no setImmediate in browser and setTimeout is slow.
286
- // call of async fn will return Promise, which will be fullfiled only on
287
- // next scheduler queue processing step and this is exactly what we need.
288
- const nextTick = async () => { };
289
- // Returns control to thread each 'tick' ms to avoid blocking
290
- async function asyncLoop(iters, tick, cb) {
291
- let ts = Date.now();
292
- for (let i = 0; i < iters; i++) {
293
- cb(i);
294
- // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
295
- const diff = Date.now() - ts;
296
- if (diff >= 0 && diff < tick)
297
- continue;
298
- await nextTick();
299
- ts += diff;
300
- }
301
- }
302
298
  /**
303
299
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
304
300
  */
@@ -343,13 +339,6 @@ class Hash {
343
339
  return this._cloneInto();
344
340
  }
345
341
  }
346
- const toStr = {}.toString;
347
- function checkOpts(defaults, opts) {
348
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
349
- throw new Error('Options should be object or undefined');
350
- const merged = Object.assign(defaults, opts);
351
- return merged;
352
- }
353
342
  function wrapConstructor(hashCons) {
354
343
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
355
344
  const tmp = hashCons();
@@ -361,7 +350,7 @@ function wrapConstructor(hashCons) {
361
350
  /**
362
351
  * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
363
352
  */
364
- function randomBytes$1(bytesLength = 32) {
353
+ function randomBytes(bytesLength = 32) {
365
354
  if (crypto$2 && typeof crypto$2.getRandomValues === 'function') {
366
355
  return crypto$2.getRandomValues(new Uint8Array(bytesLength));
367
356
  }
@@ -1342,7 +1331,7 @@ function encodingLength$3(int) {
1342
1331
  /**
1343
1332
  * Creates a multihash digest.
1344
1333
  */
1345
- function create$1(code, digest) {
1334
+ function create(code, digest) {
1346
1335
  const size = digest.byteLength;
1347
1336
  const sizeOffset = encodingLength$3(code);
1348
1337
  const digestOffset = sizeOffset + encodingLength$3(size);
@@ -1401,7 +1390,7 @@ const code = 0x0;
1401
1390
  const name$1 = 'identity';
1402
1391
  const encode$6 = coerce;
1403
1392
  function digest(input) {
1404
- return create$1(code, encode$6(input));
1393
+ return create(code, encode$6(input));
1405
1394
  }
1406
1395
  const identity = { code, name: name$1, encode: encode$6, digest };
1407
1396
 
@@ -1425,9 +1414,9 @@ class Hasher {
1425
1414
  if (input instanceof Uint8Array) {
1426
1415
  const result = this.encode(input);
1427
1416
  return result instanceof Uint8Array
1428
- ? create$1(this.code, result)
1417
+ ? create(this.code, result)
1429
1418
  /* c8 ignore next 1 */
1430
- : result.then(digest => create$1(this.code, digest));
1419
+ : result.then(digest => create(this.code, digest));
1431
1420
  }
1432
1421
  else {
1433
1422
  throw Error('Unknown type, must be binary type');
@@ -1527,7 +1516,7 @@ class CID {
1527
1516
  switch (this.version) {
1528
1517
  case 0: {
1529
1518
  const { code, digest } = this.multihash;
1530
- const multihash = create$1(code, digest);
1519
+ const multihash = create(code, digest);
1531
1520
  return (CID.createV1(this.code, multihash));
1532
1521
  }
1533
1522
  case 1: {
@@ -2723,7 +2712,6 @@ var debug = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
2723
2712
 
2724
2713
  const APP_NAME = "waku";
2725
2714
  let Logger$1 = class Logger {
2726
- _debug;
2727
2715
  _info;
2728
2716
  _warn;
2729
2717
  _error;
@@ -2731,14 +2719,10 @@ let Logger$1 = class Logger {
2731
2719
  return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;
2732
2720
  }
2733
2721
  constructor(prefix) {
2734
- this._debug = debug(Logger.createDebugNamespace("debug", prefix));
2735
2722
  this._info = debug(Logger.createDebugNamespace("info", prefix));
2736
2723
  this._warn = debug(Logger.createDebugNamespace("warn", prefix));
2737
2724
  this._error = debug(Logger.createDebugNamespace("error", prefix));
2738
2725
  }
2739
- get debug() {
2740
- return this._debug;
2741
- }
2742
2726
  get info() {
2743
2727
  return this._info;
2744
2728
  }
@@ -5548,7 +5532,7 @@ function ParseError(str) {
5548
5532
  * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')
5549
5533
  * ```
5550
5534
  */
5551
- const inspect$1 = Symbol.for('nodejs.util.inspect.custom');
5535
+ const inspect$2 = Symbol.for('nodejs.util.inspect.custom');
5552
5536
  const symbol$1 = Symbol.for('@multiformats/js-multiaddr/multiaddr');
5553
5537
  const DNS_CODES = [
5554
5538
  getProtocol('dns').code,
@@ -5772,7 +5756,7 @@ class Multiaddr {
5772
5756
  * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'
5773
5757
  * ```
5774
5758
  */
5775
- [inspect$1]() {
5759
+ [inspect$2]() {
5776
5760
  return `Multiaddr(${this.#string})`;
5777
5761
  }
5778
5762
  }
@@ -5945,14 +5929,41 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
5945
5929
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
5946
5930
  }
5947
5931
 
5948
- function isPromise$1(thing) {
5949
- if (thing == null) {
5950
- return false;
5932
+ /**
5933
+ * When this error is thrown it means an operation was aborted,
5934
+ * usually in response to the `abort` event being emitted by an
5935
+ * AbortSignal.
5936
+ */
5937
+ /**
5938
+ * Thrown when invalid parameters are passed to a function or method call
5939
+ */
5940
+ class InvalidParametersError extends Error {
5941
+ static name = 'InvalidParametersError';
5942
+ constructor(message = 'Invalid parameters') {
5943
+ super(message);
5944
+ this.name = 'InvalidParametersError';
5945
+ }
5946
+ }
5947
+ /**
5948
+ * Thrown when a public key is invalid
5949
+ */
5950
+ class InvalidPublicKeyError extends Error {
5951
+ static name = 'InvalidPublicKeyError';
5952
+ constructor(message = 'Invalid public key') {
5953
+ super(message);
5954
+ this.name = 'InvalidPublicKeyError';
5951
5955
  }
5952
- return typeof thing.then === 'function' &&
5953
- typeof thing.catch === 'function' &&
5954
- typeof thing.finally === 'function';
5955
5956
  }
5957
+ /**
5958
+ * Thrown when and attempt to operate on an unsupported key was made
5959
+ */
5960
+ let UnsupportedKeyTypeError$1 = class UnsupportedKeyTypeError extends Error {
5961
+ static name = 'UnsupportedKeyTypeError';
5962
+ constructor(message = 'Unsupported key type') {
5963
+ super(message);
5964
+ this.name = 'UnsupportedKeyTypeError';
5965
+ }
5966
+ };
5956
5967
 
5957
5968
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
5958
5969
  const _32n = /* @__PURE__ */ BigInt(32);
@@ -7625,7 +7636,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7625
7636
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
7626
7637
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
7627
7638
  hash: sha512,
7628
- randomBytes: randomBytes$1,
7639
+ randomBytes,
7629
7640
  adjustScalarBytes,
7630
7641
  // dom2
7631
7642
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
@@ -7638,176 +7649,46 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7638
7649
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7639
7650
 
7640
7651
  const PUBLIC_KEY_BYTE_LENGTH = 32;
7641
- const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
7642
- const KEYS_BYTE_LENGTH = 32;
7643
- function generateKey$2() {
7644
- // the actual private key (32 bytes)
7645
- const privateKeyRaw = ed25519.utils.randomPrivateKey();
7646
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7647
- // concatenated the public key to the private key
7648
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7649
- return {
7650
- privateKey,
7651
- publicKey
7652
- };
7653
- }
7654
- /**
7655
- * Generate keypair from a 32 byte uint8array
7656
- */
7657
- function generateKeyFromSeed(seed) {
7658
- if (seed.length !== KEYS_BYTE_LENGTH) {
7659
- throw new TypeError('"seed" must be 32 bytes in length.');
7660
- }
7661
- else if (!(seed instanceof Uint8Array)) {
7662
- throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
7663
- }
7664
- // based on node forges algorithm, the seed is used directly as private key
7665
- const privateKeyRaw = seed;
7666
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7667
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7668
- return {
7669
- privateKey,
7670
- publicKey
7671
- };
7672
- }
7673
- function hashAndSign$2(privateKey, msg) {
7674
- const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
7675
- return ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
7676
- }
7677
7652
  function hashAndVerify$2(publicKey, sig, msg) {
7678
7653
  return ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
7679
7654
  }
7680
- function concatKeys(privateKeyRaw, publicKey) {
7681
- const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
7682
- for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
7683
- privateKey[i] = privateKeyRaw[i];
7684
- privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
7685
- }
7686
- return privateKey;
7687
- }
7688
7655
 
7689
- /* eslint-env browser */
7690
- // Check native crypto exists and is enabled (In insecure context `self.crypto`
7691
- // exists but `self.crypto.subtle` does not).
7692
- var webcrypto = {
7693
- get(win = globalThis) {
7694
- const nativeCrypto = win.crypto;
7695
- if (nativeCrypto?.subtle == null) {
7696
- throw Object.assign(new Error('Missing Web Crypto API. ' +
7697
- 'The most likely cause of this error is that this page is being accessed ' +
7698
- 'from an insecure context (i.e. not HTTPS). For more information and ' +
7699
- 'possible resolutions see ' +
7700
- 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });
7701
- }
7702
- return nativeCrypto;
7656
+ class Ed25519PublicKey {
7657
+ type = 'Ed25519';
7658
+ raw;
7659
+ constructor(key) {
7660
+ this.raw = ensureEd25519Key(key, PUBLIC_KEY_BYTE_LENGTH);
7703
7661
  }
7704
- };
7705
-
7706
- // WebKit on Linux does not support deriving a key from an empty PBKDF2 key.
7707
- // So, as a workaround, we provide the generated key as a constant. We test that
7708
- // this generated key is accurate in test/workaround.spec.ts
7709
- // Generated via:
7710
- // await crypto.subtle.exportKey('jwk',
7711
- // await crypto.subtle.deriveKey(
7712
- // { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },
7713
- // await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),
7714
- // { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])
7715
- // )
7716
- const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
7717
- // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
7718
- function create(opts) {
7719
- const algorithm = 'AES-GCM';
7720
- let keyLength = 16;
7721
- const nonceLength = 12;
7722
- const digest = 'SHA-256';
7723
- const saltLength = 16;
7724
- const iterations = 32767;
7725
- const crypto = webcrypto.get();
7726
- keyLength *= 8; // Browser crypto uses bits instead of bytes
7727
- /**
7728
- * Uses the provided password to derive a pbkdf2 key. The key
7729
- * will then be used to encrypt the data.
7730
- */
7731
- async function encrypt(data, password) {
7732
- const salt = crypto.getRandomValues(new Uint8Array(saltLength));
7733
- const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));
7734
- const aesGcm = { name: algorithm, iv: nonce };
7735
- if (typeof password === 'string') {
7736
- password = fromString(password);
7737
- }
7738
- let cryptoKey;
7739
- if (password.length === 0) {
7740
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7741
- try {
7742
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7743
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7744
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);
7745
- }
7746
- catch {
7747
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7748
- }
7749
- }
7750
- else {
7751
- // Derive a key using PBKDF2.
7752
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7753
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7754
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);
7755
- }
7756
- // Encrypt the string.
7757
- const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);
7758
- return concat$1([salt, aesGcm.iv, new Uint8Array(ciphertext)]);
7662
+ toMultihash() {
7663
+ return identity.digest(publicKeyToProtobuf(this));
7759
7664
  }
7760
- /**
7761
- * Uses the provided password to derive a pbkdf2 key. The key
7762
- * will then be used to decrypt the data. The options used to create
7763
- * this decryption cipher must be the same as those used to create
7764
- * the encryption cipher.
7765
- */
7766
- async function decrypt(data, password) {
7767
- const salt = data.subarray(0, saltLength);
7768
- const nonce = data.subarray(saltLength, saltLength + nonceLength);
7769
- const ciphertext = data.subarray(saltLength + nonceLength);
7770
- const aesGcm = { name: algorithm, iv: nonce };
7771
- if (typeof password === 'string') {
7772
- password = fromString(password);
7773
- }
7774
- let cryptoKey;
7775
- if (password.length === 0) {
7776
- try {
7777
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7778
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7779
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);
7780
- }
7781
- catch {
7782
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);
7783
- }
7665
+ toCID() {
7666
+ return CID.createV1(114, this.toMultihash());
7667
+ }
7668
+ toString() {
7669
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
7670
+ }
7671
+ equals(key) {
7672
+ if (key == null || !(key.raw instanceof Uint8Array)) {
7673
+ return false;
7784
7674
  }
7785
- else {
7786
- // Derive the key using PBKDF2.
7787
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7788
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7789
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);
7790
- }
7791
- // Decrypt the string.
7792
- const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);
7793
- return new Uint8Array(plaintext);
7794
- }
7795
- const cipher = {
7796
- encrypt,
7797
- decrypt
7798
- };
7799
- return cipher;
7675
+ return equals(this.raw, key.raw);
7676
+ }
7677
+ verify(data, sig) {
7678
+ return hashAndVerify$2(this.raw, sig, data);
7679
+ }
7800
7680
  }
7801
7681
 
7802
- /**
7803
- * Exports the given PrivateKey as a base64 encoded string.
7804
- * The PrivateKey is encrypted via a password derived PBKDF2 key
7805
- * leveraging the aes-gcm cipher algorithm.
7806
- */
7807
- async function exporter(privateKey, password) {
7808
- const cipher = create();
7809
- const encryptedKey = await cipher.encrypt(privateKey, password);
7810
- return base64.encode(encryptedKey);
7682
+ function unmarshalEd25519PublicKey(bytes) {
7683
+ bytes = ensureEd25519Key(bytes, PUBLIC_KEY_BYTE_LENGTH);
7684
+ return new Ed25519PublicKey(bytes);
7685
+ }
7686
+ function ensureEd25519Key(key, length) {
7687
+ key = Uint8Array.from(key ?? []);
7688
+ if (key.length !== length) {
7689
+ throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);
7690
+ }
7691
+ return key;
7811
7692
  }
7812
7693
 
7813
7694
  const f32 = new Float32Array([-0]);
@@ -9040,13 +8921,13 @@ var KeyType;
9040
8921
  (function (KeyType) {
9041
8922
  KeyType["RSA"] = "RSA";
9042
8923
  KeyType["Ed25519"] = "Ed25519";
9043
- KeyType["Secp256k1"] = "Secp256k1";
8924
+ KeyType["secp256k1"] = "secp256k1";
9044
8925
  })(KeyType || (KeyType = {}));
9045
8926
  var __KeyTypeValues;
9046
8927
  (function (__KeyTypeValues) {
9047
8928
  __KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
9048
8929
  __KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
9049
- __KeyTypeValues[__KeyTypeValues["Secp256k1"] = 2] = "Secp256k1";
8930
+ __KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
9050
8931
  })(__KeyTypeValues || (__KeyTypeValues = {}));
9051
8932
  (function (KeyType) {
9052
8933
  KeyType.codec = () => {
@@ -9073,21 +8954,24 @@ var PublicKey;
9073
8954
  if (opts.lengthDelimited !== false) {
9074
8955
  w.ldelim();
9075
8956
  }
9076
- }, (reader, length) => {
8957
+ }, (reader, length, opts = {}) => {
9077
8958
  const obj = {};
9078
8959
  const end = length == null ? reader.len : reader.pos + length;
9079
8960
  while (reader.pos < end) {
9080
8961
  const tag = reader.uint32();
9081
8962
  switch (tag >>> 3) {
9082
- case 1:
8963
+ case 1: {
9083
8964
  obj.Type = KeyType.codec().decode(reader);
9084
8965
  break;
9085
- case 2:
8966
+ }
8967
+ case 2: {
9086
8968
  obj.Data = reader.bytes();
9087
8969
  break;
9088
- default:
8970
+ }
8971
+ default: {
9089
8972
  reader.skipType(tag & 7);
9090
8973
  break;
8974
+ }
9091
8975
  }
9092
8976
  }
9093
8977
  return obj;
@@ -9098,8 +8982,8 @@ var PublicKey;
9098
8982
  PublicKey.encode = (obj) => {
9099
8983
  return encodeMessage(obj, PublicKey.codec());
9100
8984
  };
9101
- PublicKey.decode = (buf) => {
9102
- return decodeMessage(buf, PublicKey.codec());
8985
+ PublicKey.decode = (buf, opts) => {
8986
+ return decodeMessage(buf, PublicKey.codec(), opts);
9103
8987
  };
9104
8988
  })(PublicKey || (PublicKey = {}));
9105
8989
  var PrivateKey;
@@ -9122,21 +9006,24 @@ var PrivateKey;
9122
9006
  if (opts.lengthDelimited !== false) {
9123
9007
  w.ldelim();
9124
9008
  }
9125
- }, (reader, length) => {
9009
+ }, (reader, length, opts = {}) => {
9126
9010
  const obj = {};
9127
9011
  const end = length == null ? reader.len : reader.pos + length;
9128
9012
  while (reader.pos < end) {
9129
9013
  const tag = reader.uint32();
9130
9014
  switch (tag >>> 3) {
9131
- case 1:
9015
+ case 1: {
9132
9016
  obj.Type = KeyType.codec().decode(reader);
9133
9017
  break;
9134
- case 2:
9018
+ }
9019
+ case 2: {
9135
9020
  obj.Data = reader.bytes();
9136
9021
  break;
9137
- default:
9022
+ }
9023
+ default: {
9138
9024
  reader.skipType(tag & 7);
9139
9025
  break;
9026
+ }
9140
9027
  }
9141
9028
  }
9142
9029
  return obj;
@@ -9147,397 +9034,122 @@ var PrivateKey;
9147
9034
  PrivateKey.encode = (obj) => {
9148
9035
  return encodeMessage(obj, PrivateKey.codec());
9149
9036
  };
9150
- PrivateKey.decode = (buf) => {
9151
- return decodeMessage(buf, PrivateKey.codec());
9037
+ PrivateKey.decode = (buf, opts) => {
9038
+ return decodeMessage(buf, PrivateKey.codec(), opts);
9152
9039
  };
9153
9040
  })(PrivateKey || (PrivateKey = {}));
9154
9041
 
9155
- class Ed25519PublicKey {
9156
- _key;
9157
- constructor(key) {
9158
- this._key = ensureKey(key, PUBLIC_KEY_BYTE_LENGTH);
9159
- }
9160
- verify(data, sig) {
9161
- return hashAndVerify$2(this._key, sig, data);
9162
- }
9163
- marshal() {
9164
- return this._key;
9165
- }
9166
- get bytes() {
9167
- return PublicKey.encode({
9168
- Type: KeyType.Ed25519,
9169
- Data: this.marshal()
9170
- }).subarray();
9171
- }
9172
- equals(key) {
9173
- return equals(this.bytes, key.bytes);
9042
+ /*!
9043
+ * MIT License
9044
+ *
9045
+ * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9046
+ *
9047
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9048
+ * of this software and associated documentation files (the "Software"), to deal
9049
+ * in the Software without restriction, including without limitation the rights
9050
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9051
+ * copies of the Software, and to permit persons to whom the Software is
9052
+ * furnished to do so, subject to the following conditions:
9053
+ *
9054
+ * The above copyright notice and this permission notice shall be included in all
9055
+ * copies or substantial portions of the Software.
9056
+ *
9057
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9058
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9059
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9060
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9061
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9062
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
9063
+ * SOFTWARE.
9064
+ *
9065
+ */
9066
+
9067
+ const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
9068
+ class BufferSourceConverter {
9069
+ static isArrayBuffer(data) {
9070
+ return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
9174
9071
  }
9175
- hash() {
9176
- const p = sha256.digest(this.bytes);
9177
- if (isPromise$1(p)) {
9178
- return p.then(({ bytes }) => bytes);
9072
+ static toArrayBuffer(data) {
9073
+ if (this.isArrayBuffer(data)) {
9074
+ return data;
9179
9075
  }
9180
- return p.bytes;
9181
- }
9182
- }
9183
- class Ed25519PrivateKey {
9184
- _key;
9185
- _publicKey;
9186
- // key - 64 byte Uint8Array containing private key
9187
- // publicKey - 32 byte Uint8Array containing public key
9188
- constructor(key, publicKey) {
9189
- this._key = ensureKey(key, PRIVATE_KEY_BYTE_LENGTH);
9190
- this._publicKey = ensureKey(publicKey, PUBLIC_KEY_BYTE_LENGTH);
9191
- }
9192
- sign(message) {
9193
- return hashAndSign$2(this._key, message);
9076
+ if (data.byteLength === data.buffer.byteLength) {
9077
+ return data.buffer;
9078
+ }
9079
+ if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
9080
+ return data.buffer;
9081
+ }
9082
+ return this.toUint8Array(data.buffer)
9083
+ .slice(data.byteOffset, data.byteOffset + data.byteLength)
9084
+ .buffer;
9194
9085
  }
9195
- get public() {
9196
- return new Ed25519PublicKey(this._publicKey);
9086
+ static toUint8Array(data) {
9087
+ return this.toView(data, Uint8Array);
9197
9088
  }
9198
- marshal() {
9199
- return this._key;
9089
+ static toView(data, type) {
9090
+ if (data.constructor === type) {
9091
+ return data;
9092
+ }
9093
+ if (this.isArrayBuffer(data)) {
9094
+ return new type(data);
9095
+ }
9096
+ if (this.isArrayBufferView(data)) {
9097
+ return new type(data.buffer, data.byteOffset, data.byteLength);
9098
+ }
9099
+ throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
9200
9100
  }
9201
- get bytes() {
9202
- return PrivateKey.encode({
9203
- Type: KeyType.Ed25519,
9204
- Data: this.marshal()
9205
- }).subarray();
9101
+ static isBufferSource(data) {
9102
+ return this.isArrayBufferView(data)
9103
+ || this.isArrayBuffer(data);
9206
9104
  }
9207
- equals(key) {
9208
- return equals(this.bytes, key.bytes);
9105
+ static isArrayBufferView(data) {
9106
+ return ArrayBuffer.isView(data)
9107
+ || (data && this.isArrayBuffer(data.buffer));
9209
9108
  }
9210
- async hash() {
9211
- const p = sha256.digest(this.bytes);
9212
- let bytes;
9213
- if (isPromise$1(p)) {
9214
- ({ bytes } = await p);
9109
+ static isEqual(a, b) {
9110
+ const aView = BufferSourceConverter.toUint8Array(a);
9111
+ const bView = BufferSourceConverter.toUint8Array(b);
9112
+ if (aView.length !== bView.byteLength) {
9113
+ return false;
9215
9114
  }
9216
- else {
9217
- bytes = p.bytes;
9115
+ for (let i = 0; i < aView.length; i++) {
9116
+ if (aView[i] !== bView[i]) {
9117
+ return false;
9118
+ }
9218
9119
  }
9219
- return bytes;
9220
- }
9221
- /**
9222
- * Gets the ID of the key.
9223
- *
9224
- * The key id is the base58 encoding of the identity multihash containing its public key.
9225
- * The public key is a protobuf encoding containing a type and the DER encoding
9226
- * of the PKCS SubjectPublicKeyInfo.
9227
- *
9228
- * @returns {Promise<string>}
9229
- */
9230
- async id() {
9231
- const encoding = identity.digest(this.public.bytes);
9232
- return base58btc.encode(encoding.bytes).substring(1);
9120
+ return true;
9233
9121
  }
9234
- /**
9235
- * Exports the key into a password protected `format`
9236
- */
9237
- async export(password, format = 'libp2p-key') {
9238
- if (format === 'libp2p-key') {
9239
- return exporter(this.bytes, password);
9122
+ static concat(...args) {
9123
+ let buffers;
9124
+ if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
9125
+ buffers = args[0];
9126
+ }
9127
+ else if (Array.isArray(args[0]) && args[1] instanceof Function) {
9128
+ buffers = args[0];
9240
9129
  }
9241
9130
  else {
9242
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
9131
+ if (args[args.length - 1] instanceof Function) {
9132
+ buffers = args.slice(0, args.length - 1);
9133
+ }
9134
+ else {
9135
+ buffers = args;
9136
+ }
9243
9137
  }
9244
- }
9245
- }
9246
- function unmarshalEd25519PrivateKey(bytes) {
9247
- // Try the old, redundant public key version
9248
- if (bytes.length > PRIVATE_KEY_BYTE_LENGTH) {
9249
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH + PUBLIC_KEY_BYTE_LENGTH);
9250
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9251
- const publicKeyBytes = bytes.subarray(PRIVATE_KEY_BYTE_LENGTH, bytes.length);
9252
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9253
- }
9254
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH);
9255
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9256
- const publicKeyBytes = bytes.subarray(PUBLIC_KEY_BYTE_LENGTH);
9257
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9258
- }
9259
- function unmarshalEd25519PublicKey(bytes) {
9260
- bytes = ensureKey(bytes, PUBLIC_KEY_BYTE_LENGTH);
9261
- return new Ed25519PublicKey(bytes);
9262
- }
9263
- async function generateKeyPair$2() {
9264
- const { privateKey, publicKey } = generateKey$2();
9265
- return new Ed25519PrivateKey(privateKey, publicKey);
9266
- }
9267
- async function generateKeyPairFromSeed(seed) {
9268
- const { privateKey, publicKey } = generateKeyFromSeed(seed);
9269
- return new Ed25519PrivateKey(privateKey, publicKey);
9270
- }
9271
- function ensureKey(key, length) {
9272
- key = Uint8Array.from(key ?? []);
9273
- if (key.length !== length) {
9274
- throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
9275
- }
9276
- return key;
9277
- }
9278
-
9279
- var Ed25519 = /*#__PURE__*/Object.freeze({
9280
- __proto__: null,
9281
- Ed25519PrivateKey: Ed25519PrivateKey,
9282
- Ed25519PublicKey: Ed25519PublicKey,
9283
- generateKeyPair: generateKeyPair$2,
9284
- generateKeyPairFromSeed: generateKeyPairFromSeed,
9285
- unmarshalEd25519PrivateKey: unmarshalEd25519PrivateKey,
9286
- unmarshalEd25519PublicKey: unmarshalEd25519PublicKey
9287
- });
9288
-
9289
- /**
9290
- * Generates a Uint8Array with length `number` populated by random bytes
9291
- */
9292
- function randomBytes(length) {
9293
- if (isNaN(length) || length <= 0) {
9294
- throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
9295
- }
9296
- return randomBytes$1(length);
9297
- }
9298
-
9299
- // HMAC (RFC 2104)
9300
- class HMAC extends Hash {
9301
- constructor(hash$1, _key) {
9302
- super();
9303
- this.finished = false;
9304
- this.destroyed = false;
9305
- hash(hash$1);
9306
- const key = toBytes$1(_key);
9307
- this.iHash = hash$1.create();
9308
- if (typeof this.iHash.update !== 'function')
9309
- throw new Error('Expected instance of class which extends utils.Hash');
9310
- this.blockLen = this.iHash.blockLen;
9311
- this.outputLen = this.iHash.outputLen;
9312
- const blockLen = this.blockLen;
9313
- const pad = new Uint8Array(blockLen);
9314
- // blockLen can be bigger than outputLen
9315
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
9316
- for (let i = 0; i < pad.length; i++)
9317
- pad[i] ^= 0x36;
9318
- this.iHash.update(pad);
9319
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
9320
- this.oHash = hash$1.create();
9321
- // Undo internal XOR && apply outer XOR
9322
- for (let i = 0; i < pad.length; i++)
9323
- pad[i] ^= 0x36 ^ 0x5c;
9324
- this.oHash.update(pad);
9325
- pad.fill(0);
9326
- }
9327
- update(buf) {
9328
- exists(this);
9329
- this.iHash.update(buf);
9330
- return this;
9331
- }
9332
- digestInto(out) {
9333
- exists(this);
9334
- bytes(out, this.outputLen);
9335
- this.finished = true;
9336
- this.iHash.digestInto(out);
9337
- this.oHash.update(out);
9338
- this.oHash.digestInto(out);
9339
- this.destroy();
9340
- }
9341
- digest() {
9342
- const out = new Uint8Array(this.oHash.outputLen);
9343
- this.digestInto(out);
9344
- return out;
9345
- }
9346
- _cloneInto(to) {
9347
- // Create new instance without calling constructor since key already in state and we don't know it.
9348
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
9349
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
9350
- to = to;
9351
- to.finished = finished;
9352
- to.destroyed = destroyed;
9353
- to.blockLen = blockLen;
9354
- to.outputLen = outputLen;
9355
- to.oHash = oHash._cloneInto(to.oHash);
9356
- to.iHash = iHash._cloneInto(to.iHash);
9357
- return to;
9358
- }
9359
- destroy() {
9360
- this.destroyed = true;
9361
- this.oHash.destroy();
9362
- this.iHash.destroy();
9363
- }
9364
- }
9365
- /**
9366
- * HMAC: RFC2104 message authentication code.
9367
- * @param hash - function that would be used e.g. sha256
9368
- * @param key - message key
9369
- * @param message - message data
9370
- * @example
9371
- * import { hmac } from '@noble/hashes/hmac';
9372
- * import { sha256 } from '@noble/hashes/sha2';
9373
- * const mac1 = hmac(sha256, 'key', 'message');
9374
- */
9375
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
9376
- hmac.create = (hash, key) => new HMAC(hash, key);
9377
-
9378
- // Common prologue and epilogue for sync/async functions
9379
- function pbkdf2Init(hash$1, _password, _salt, _opts) {
9380
- hash(hash$1);
9381
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
9382
- const { c, dkLen, asyncTick } = opts;
9383
- number(c);
9384
- number(dkLen);
9385
- number(asyncTick);
9386
- if (c < 1)
9387
- throw new Error('PBKDF2: iterations (c) should be >= 1');
9388
- const password = toBytes$1(_password);
9389
- const salt = toBytes$1(_salt);
9390
- // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
9391
- const DK = new Uint8Array(dkLen);
9392
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9393
- const PRF = hmac.create(hash$1, password);
9394
- const PRFSalt = PRF._cloneInto().update(salt);
9395
- return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
9396
- }
9397
- function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
9398
- PRF.destroy();
9399
- PRFSalt.destroy();
9400
- if (prfW)
9401
- prfW.destroy();
9402
- u.fill(0);
9403
- return DK;
9404
- }
9405
- async function pbkdf2Async(hash, password, salt, opts) {
9406
- const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
9407
- let prfW; // Working copy
9408
- const arr = new Uint8Array(4);
9409
- const view = createView(arr);
9410
- const u = new Uint8Array(PRF.outputLen);
9411
- // DK = T1 + T2 + ⋯ + Tdklen/hlen
9412
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
9413
- // Ti = F(Password, Salt, c, i)
9414
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
9415
- view.setInt32(0, ti, false);
9416
- // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
9417
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9418
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
9419
- Ti.set(u.subarray(0, Ti.length));
9420
- await asyncLoop(c - 1, asyncTick, () => {
9421
- // Uc = PRF(Password, Uc−1)
9422
- PRF._cloneInto(prfW).update(u).digestInto(u);
9423
- for (let i = 0; i < Ti.length; i++)
9424
- Ti[i] ^= u[i];
9425
- });
9426
- }
9427
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
9428
- }
9429
-
9430
- /*!
9431
- * MIT License
9432
- *
9433
- * Copyright (c) 2017-2022 Peculiar Ventures, LLC
9434
- *
9435
- * Permission is hereby granted, free of charge, to any person obtaining a copy
9436
- * of this software and associated documentation files (the "Software"), to deal
9437
- * in the Software without restriction, including without limitation the rights
9438
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9439
- * copies of the Software, and to permit persons to whom the Software is
9440
- * furnished to do so, subject to the following conditions:
9441
- *
9442
- * The above copyright notice and this permission notice shall be included in all
9443
- * copies or substantial portions of the Software.
9444
- *
9445
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9446
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9447
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9448
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9449
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9450
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
9451
- * SOFTWARE.
9452
- *
9453
- */
9454
-
9455
- const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
9456
- class BufferSourceConverter {
9457
- static isArrayBuffer(data) {
9458
- return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
9459
- }
9460
- static toArrayBuffer(data) {
9461
- if (this.isArrayBuffer(data)) {
9462
- return data;
9463
- }
9464
- if (data.byteLength === data.buffer.byteLength) {
9465
- return data.buffer;
9466
- }
9467
- if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
9468
- return data.buffer;
9469
- }
9470
- return this.toUint8Array(data.buffer)
9471
- .slice(data.byteOffset, data.byteOffset + data.byteLength)
9472
- .buffer;
9473
- }
9474
- static toUint8Array(data) {
9475
- return this.toView(data, Uint8Array);
9476
- }
9477
- static toView(data, type) {
9478
- if (data.constructor === type) {
9479
- return data;
9480
- }
9481
- if (this.isArrayBuffer(data)) {
9482
- return new type(data);
9483
- }
9484
- if (this.isArrayBufferView(data)) {
9485
- return new type(data.buffer, data.byteOffset, data.byteLength);
9486
- }
9487
- throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
9488
- }
9489
- static isBufferSource(data) {
9490
- return this.isArrayBufferView(data)
9491
- || this.isArrayBuffer(data);
9492
- }
9493
- static isArrayBufferView(data) {
9494
- return ArrayBuffer.isView(data)
9495
- || (data && this.isArrayBuffer(data.buffer));
9496
- }
9497
- static isEqual(a, b) {
9498
- const aView = BufferSourceConverter.toUint8Array(a);
9499
- const bView = BufferSourceConverter.toUint8Array(b);
9500
- if (aView.length !== bView.byteLength) {
9501
- return false;
9502
- }
9503
- for (let i = 0; i < aView.length; i++) {
9504
- if (aView[i] !== bView[i]) {
9505
- return false;
9506
- }
9507
- }
9508
- return true;
9509
- }
9510
- static concat(...args) {
9511
- let buffers;
9512
- if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
9513
- buffers = args[0];
9514
- }
9515
- else if (Array.isArray(args[0]) && args[1] instanceof Function) {
9516
- buffers = args[0];
9517
- }
9518
- else {
9519
- if (args[args.length - 1] instanceof Function) {
9520
- buffers = args.slice(0, args.length - 1);
9521
- }
9522
- else {
9523
- buffers = args;
9524
- }
9525
- }
9526
- let size = 0;
9527
- for (const buffer of buffers) {
9528
- size += buffer.byteLength;
9529
- }
9530
- const res = new Uint8Array(size);
9531
- let offset = 0;
9532
- for (const buffer of buffers) {
9533
- const view = this.toUint8Array(buffer);
9534
- res.set(view, offset);
9535
- offset += view.length;
9536
- }
9537
- if (args[args.length - 1] instanceof Function) {
9538
- return this.toView(res, args[args.length - 1]);
9539
- }
9540
- return res.buffer;
9138
+ let size = 0;
9139
+ for (const buffer of buffers) {
9140
+ size += buffer.byteLength;
9141
+ }
9142
+ const res = new Uint8Array(size);
9143
+ let offset = 0;
9144
+ for (const buffer of buffers) {
9145
+ const view = this.toUint8Array(buffer);
9146
+ res.set(view, offset);
9147
+ offset += view.length;
9148
+ }
9149
+ if (args[args.length - 1] instanceof Function) {
9150
+ return this.toView(res, args[args.length - 1]);
9151
+ }
9152
+ return res.buffer;
9541
9153
  }
9542
9154
  }
9543
9155
 
@@ -12678,82 +12290,131 @@ _a = TIME;
12678
12290
  TIME.NAME = "TIME";
12679
12291
 
12680
12292
  /**
12681
- * Convert a PKCS#1 in ASN1 DER format to a JWK key
12293
+ * Signing a message failed
12682
12294
  */
12683
- function pkcs1ToJwk(bytes) {
12684
- const { result } = fromBER(bytes);
12685
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12686
- // safe to have deeply property chains like this
12687
- const values = result.valueBlock.value;
12688
- const key = {
12689
- n: toString$6(bnToBuf(values[1].toBigInt()), 'base64url'),
12690
- e: toString$6(bnToBuf(values[2].toBigInt()), 'base64url'),
12691
- d: toString$6(bnToBuf(values[3].toBigInt()), 'base64url'),
12692
- p: toString$6(bnToBuf(values[4].toBigInt()), 'base64url'),
12693
- q: toString$6(bnToBuf(values[5].toBigInt()), 'base64url'),
12694
- dp: toString$6(bnToBuf(values[6].toBigInt()), 'base64url'),
12695
- dq: toString$6(bnToBuf(values[7].toBigInt()), 'base64url'),
12696
- qi: toString$6(bnToBuf(values[8].toBigInt()), 'base64url'),
12697
- kty: 'RSA',
12698
- alg: 'RS256'
12699
- };
12700
- return key;
12701
- }
12702
12295
  /**
12703
- * Convert a JWK key into PKCS#1 in ASN1 DER format
12296
+ * Verifying a message signature failed
12704
12297
  */
12705
- function jwkToPkcs1(jwk) {
12706
- 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) {
12707
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12298
+ class VerificationError extends Error {
12299
+ constructor(message = 'An error occurred while verifying a message') {
12300
+ super(message);
12301
+ this.name = 'VerificationError';
12708
12302
  }
12709
- const root = new Sequence({
12710
- value: [
12711
- new Integer({ value: 0 }),
12712
- Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
12713
- Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url'))),
12714
- Integer.fromBigInt(bufToBn(fromString(jwk.d, 'base64url'))),
12715
- Integer.fromBigInt(bufToBn(fromString(jwk.p, 'base64url'))),
12716
- Integer.fromBigInt(bufToBn(fromString(jwk.q, 'base64url'))),
12717
- Integer.fromBigInt(bufToBn(fromString(jwk.dp, 'base64url'))),
12718
- Integer.fromBigInt(bufToBn(fromString(jwk.dq, 'base64url'))),
12719
- Integer.fromBigInt(bufToBn(fromString(jwk.qi, 'base64url')))
12720
- ]
12721
- });
12722
- const der = root.toBER();
12723
- return new Uint8Array(der, 0, der.byteLength);
12724
12303
  }
12725
12304
  /**
12726
- * Convert a PKCIX in ASN1 DER format to a JWK key
12305
+ * WebCrypto was not available in the current context
12727
12306
  */
12728
- function pkixToJwk(bytes) {
12729
- const { result } = fromBER(bytes);
12730
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12731
- // safe to have deeply property chains like this
12732
- const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12733
- return {
12734
- kty: 'RSA',
12735
- n: toString$6(bnToBuf(values[0].toBigInt()), 'base64url'),
12736
- e: toString$6(bnToBuf(values[1].toBigInt()), 'base64url')
12737
- };
12307
+ class WebCryptoMissingError extends Error {
12308
+ constructor(message = 'Missing Web Crypto API') {
12309
+ super(message);
12310
+ this.name = 'WebCryptoMissingError';
12311
+ }
12738
12312
  }
12739
- /**
12740
- * Convert a JWK key to PKCIX in ASN1 DER format
12741
- */
12742
- function jwkToPkix(jwk) {
12743
- if (jwk.n == null || jwk.e == null) {
12744
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12313
+
12314
+ /* eslint-env browser */
12315
+ // Check native crypto exists and is enabled (In insecure context `self.crypto`
12316
+ // exists but `self.crypto.subtle` does not).
12317
+ var webcrypto = {
12318
+ get(win = globalThis) {
12319
+ const nativeCrypto = win.crypto;
12320
+ if (nativeCrypto?.subtle == null) {
12321
+ throw new WebCryptoMissingError('Missing Web Crypto API. ' +
12322
+ 'The most likely cause of this error is that this page is being accessed ' +
12323
+ 'from an insecure context (i.e. not HTTPS). For more information and ' +
12324
+ 'possible resolutions see ' +
12325
+ 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');
12326
+ }
12327
+ return nativeCrypto;
12745
12328
  }
12746
- const root = new Sequence({
12747
- value: [
12748
- new Sequence({
12749
- value: [
12750
- // rsaEncryption
12751
- new ObjectIdentifier({
12752
- value: '1.2.840.113549.1.1.1'
12753
- }),
12754
- new Null()
12755
- ]
12756
- }),
12329
+ };
12330
+
12331
+ async function hashAndVerify$1(key, sig, msg) {
12332
+ const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
12333
+ name: 'RSASSA-PKCS1-v1_5',
12334
+ hash: { name: 'SHA-256' }
12335
+ }, false, ['verify']);
12336
+ return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
12337
+ }
12338
+ function rsaKeySize(jwk) {
12339
+ if (jwk.kty !== 'RSA') {
12340
+ throw new InvalidParametersError('invalid key type');
12341
+ }
12342
+ else if (jwk.n == null) {
12343
+ throw new InvalidParametersError('invalid key modulus');
12344
+ }
12345
+ const bytes = fromString(jwk.n, 'base64url');
12346
+ return bytes.length * 8;
12347
+ }
12348
+
12349
+ class RSAPublicKey {
12350
+ type = 'RSA';
12351
+ _key;
12352
+ _raw;
12353
+ _multihash;
12354
+ constructor(key, digest) {
12355
+ this._key = key;
12356
+ this._multihash = digest;
12357
+ }
12358
+ get raw() {
12359
+ if (this._raw == null) {
12360
+ this._raw = jwkToPkix(this._key);
12361
+ }
12362
+ return this._raw;
12363
+ }
12364
+ toMultihash() {
12365
+ return this._multihash;
12366
+ }
12367
+ toCID() {
12368
+ return CID.createV1(114, this._multihash);
12369
+ }
12370
+ toString() {
12371
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
12372
+ }
12373
+ equals(key) {
12374
+ if (key == null || !(key.raw instanceof Uint8Array)) {
12375
+ return false;
12376
+ }
12377
+ return equals(this.raw, key.raw);
12378
+ }
12379
+ verify(data, sig) {
12380
+ return hashAndVerify$1(this._key, sig, data);
12381
+ }
12382
+ }
12383
+
12384
+ const MAX_RSA_KEY_SIZE = 8192;
12385
+ const SHA2_256_CODE = 0x12;
12386
+ /**
12387
+ * Convert a PKIX in ASN1 DER format to a JWK key
12388
+ */
12389
+ function pkixToJwk(bytes) {
12390
+ const { result } = fromBER(bytes);
12391
+ // @ts-expect-error this looks fragile but DER is a canonical format so we are
12392
+ // safe to have deeply property chains like this
12393
+ const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12394
+ return {
12395
+ kty: 'RSA',
12396
+ n: toString$6(bnToBuf(values[0].toBigInt()), 'base64url'),
12397
+ e: toString$6(bnToBuf(values[1].toBigInt()), 'base64url')
12398
+ };
12399
+ }
12400
+ /**
12401
+ * Convert a JWK key to PKIX in ASN1 DER format
12402
+ */
12403
+ function jwkToPkix(jwk) {
12404
+ if (jwk.n == null || jwk.e == null) {
12405
+ throw new InvalidParametersError('JWK was missing components');
12406
+ }
12407
+ const root = new Sequence({
12408
+ value: [
12409
+ new Sequence({
12410
+ value: [
12411
+ // rsaEncryption
12412
+ new ObjectIdentifier({
12413
+ value: '1.2.840.113549.1.1.1'
12414
+ }),
12415
+ new Null()
12416
+ ]
12417
+ }),
12757
12418
  // this appears to be a bug in asn1js.js - this should really be a Sequence
12758
12419
  // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️
12759
12420
  new BitString({
@@ -12796,328 +12457,100 @@ function bufToBn(u8) {
12796
12457
  });
12797
12458
  return BigInt('0x' + hex.join(''));
12798
12459
  }
12799
- const SALT_LENGTH = 16;
12800
- const KEY_SIZE = 32;
12801
- const ITERATIONS = 10000;
12802
- async function exportToPem(privateKey, password) {
12803
- const crypto = webcrypto.get();
12804
- // PrivateKeyInfo
12805
- const keyWrapper = new Sequence({
12806
- value: [
12807
- // version (0)
12808
- new Integer({ value: 0 }),
12809
- // privateKeyAlgorithm
12810
- new Sequence({
12811
- value: [
12812
- // rsaEncryption OID
12813
- new ObjectIdentifier({
12814
- value: '1.2.840.113549.1.1.1'
12815
- }),
12816
- new Null()
12817
- ]
12818
- }),
12819
- // PrivateKey
12820
- new OctetString({
12821
- valueHex: privateKey.marshal()
12822
- })
12823
- ]
12824
- });
12825
- const keyBuf = keyWrapper.toBER();
12826
- const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);
12827
- const salt = randomBytes(SALT_LENGTH);
12828
- const encryptionKey = await pbkdf2Async(sha512, password, salt, {
12829
- c: ITERATIONS,
12830
- dkLen: KEY_SIZE
12831
- });
12832
- const iv = randomBytes(16);
12833
- const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);
12834
- const encrypted = await crypto.subtle.encrypt({
12835
- name: 'AES-CBC',
12836
- iv
12837
- }, cryptoKey, keyArr);
12838
- const pbkdf2Params = new Sequence({
12839
- value: [
12840
- // salt
12841
- new OctetString({ valueHex: salt }),
12842
- // iteration count
12843
- new Integer({ value: ITERATIONS }),
12844
- // key length
12845
- new Integer({ value: KEY_SIZE }),
12846
- // AlgorithmIdentifier
12847
- new Sequence({
12848
- value: [
12849
- // hmacWithSHA512
12850
- new ObjectIdentifier({ value: '1.2.840.113549.2.11' }),
12851
- new Null()
12852
- ]
12853
- })
12854
- ]
12855
- });
12856
- const encryptionAlgorithm = new Sequence({
12857
- value: [
12858
- // pkcs5PBES2
12859
- new ObjectIdentifier({
12860
- value: '1.2.840.113549.1.5.13'
12861
- }),
12862
- new Sequence({
12863
- value: [
12864
- // keyDerivationFunc
12865
- new Sequence({
12866
- value: [
12867
- // pkcs5PBKDF2
12868
- new ObjectIdentifier({
12869
- value: '1.2.840.113549.1.5.12'
12870
- }),
12871
- // PBKDF2-params
12872
- pbkdf2Params
12873
- ]
12874
- }),
12875
- // encryptionScheme
12876
- new Sequence({
12877
- value: [
12878
- // aes256-CBC
12879
- new ObjectIdentifier({
12880
- value: '2.16.840.1.101.3.4.1.42'
12881
- }),
12882
- // iv
12883
- new OctetString({
12884
- valueHex: iv
12885
- })
12886
- ]
12887
- })
12888
- ]
12889
- })
12890
- ]
12891
- });
12892
- const finalWrapper = new Sequence({
12893
- value: [
12894
- encryptionAlgorithm,
12895
- new OctetString({ valueHex: encrypted })
12896
- ]
12897
- });
12898
- const finalWrapperBuf = finalWrapper.toBER();
12899
- const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);
12900
- return [
12901
- '-----BEGIN ENCRYPTED PRIVATE KEY-----',
12902
- ...toString$6(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),
12903
- '-----END ENCRYPTED PRIVATE KEY-----'
12904
- ].join('\n');
12905
- }
12906
-
12907
- async function generateKey$1(bits) {
12908
- const pair = await webcrypto.get().subtle.generateKey({
12909
- name: 'RSASSA-PKCS1-v1_5',
12910
- modulusLength: bits,
12911
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
12912
- hash: { name: 'SHA-256' }
12913
- }, true, ['sign', 'verify']);
12914
- const keys = await exportKey(pair);
12915
- return {
12916
- privateKey: keys[0],
12917
- publicKey: keys[1]
12918
- };
12919
- }
12920
- // Takes a jwk key
12921
- async function unmarshalPrivateKey$1(key) {
12922
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12923
- name: 'RSASSA-PKCS1-v1_5',
12924
- hash: { name: 'SHA-256' }
12925
- }, true, ['sign']);
12926
- const pair = [
12927
- privateKey,
12928
- await derivePublicFromPrivate(key)
12929
- ];
12930
- const keys = await exportKey({
12931
- privateKey: pair[0],
12932
- publicKey: pair[1]
12933
- });
12934
- return {
12935
- privateKey: keys[0],
12936
- publicKey: keys[1]
12937
- };
12938
- }
12939
- async function hashAndSign$1(key, msg) {
12940
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12941
- name: 'RSASSA-PKCS1-v1_5',
12942
- hash: { name: 'SHA-256' }
12943
- }, false, ['sign']);
12944
- const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
12945
- return new Uint8Array(sig, 0, sig.byteLength);
12946
- }
12947
- async function hashAndVerify$1(key, sig, msg) {
12948
- const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
12949
- name: 'RSASSA-PKCS1-v1_5',
12950
- hash: { name: 'SHA-256' }
12951
- }, false, ['verify']);
12952
- return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
12953
- }
12954
- async function exportKey(pair) {
12955
- if (pair.privateKey == null || pair.publicKey == null) {
12956
- throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
12957
- }
12958
- return Promise.all([
12959
- webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
12960
- webcrypto.get().subtle.exportKey('jwk', pair.publicKey)
12961
- ]);
12962
- }
12963
- async function derivePublicFromPrivate(jwKey) {
12964
- return webcrypto.get().subtle.importKey('jwk', {
12965
- kty: jwKey.kty,
12966
- n: jwKey.n,
12967
- e: jwKey.e
12968
- }, {
12969
- name: 'RSASSA-PKCS1-v1_5',
12970
- hash: { name: 'SHA-256' }
12971
- }, true, ['verify']);
12972
- }
12973
- function keySize(jwk) {
12974
- if (jwk.kty !== 'RSA') {
12975
- throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');
12976
- }
12977
- else if (jwk.n == null) {
12978
- throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');
12460
+ /**
12461
+ * Turn PKIX bytes to a PublicKey
12462
+ */
12463
+ function pkixToRSAPublicKey(bytes) {
12464
+ const jwk = pkixToJwk(bytes);
12465
+ if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {
12466
+ throw new InvalidPublicKeyError('Key size is too large');
12979
12467
  }
12980
- const bytes = fromString(jwk.n, 'base64url');
12981
- return bytes.length * 8;
12468
+ const hash = sha256$1(PublicKey.encode({
12469
+ Type: KeyType.RSA,
12470
+ Data: bytes
12471
+ }));
12472
+ const digest = create(SHA2_256_CODE, hash);
12473
+ return new RSAPublicKey(jwk, digest);
12982
12474
  }
12983
12475
 
12984
- const MAX_RSA_KEY_SIZE = 8192;
12985
- class RsaPublicKey {
12986
- _key;
12987
- constructor(key) {
12988
- this._key = key;
12989
- }
12990
- verify(data, sig) {
12991
- return hashAndVerify$1(this._key, sig, data);
12992
- }
12993
- marshal() {
12994
- return jwkToPkix(this._key);
12995
- }
12996
- get bytes() {
12997
- return PublicKey.encode({
12998
- Type: KeyType.RSA,
12999
- Data: this.marshal()
13000
- }).subarray();
13001
- }
13002
- equals(key) {
13003
- return equals(this.bytes, key.bytes);
13004
- }
13005
- hash() {
13006
- const p = sha256.digest(this.bytes);
13007
- if (isPromise$1(p)) {
13008
- return p.then(({ bytes }) => bytes);
13009
- }
13010
- return p.bytes;
13011
- }
13012
- }
13013
- class RsaPrivateKey {
13014
- _key;
13015
- _publicKey;
13016
- constructor(key, publicKey) {
13017
- this._key = key;
13018
- this._publicKey = publicKey;
13019
- }
13020
- genSecret() {
13021
- return randomBytes(16);
13022
- }
13023
- sign(message) {
13024
- return hashAndSign$1(this._key, message);
13025
- }
13026
- get public() {
13027
- if (this._publicKey == null) {
13028
- throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
13029
- }
13030
- return new RsaPublicKey(this._publicKey);
13031
- }
13032
- marshal() {
13033
- return jwkToPkcs1(this._key);
13034
- }
13035
- get bytes() {
13036
- return PrivateKey.encode({
13037
- Type: KeyType.RSA,
13038
- Data: this.marshal()
13039
- }).subarray();
13040
- }
13041
- equals(key) {
13042
- return equals(this.bytes, key.bytes);
13043
- }
13044
- hash() {
13045
- const p = sha256.digest(this.bytes);
13046
- if (isPromise$1(p)) {
13047
- return p.then(({ bytes }) => bytes);
13048
- }
13049
- return p.bytes;
13050
- }
13051
- /**
13052
- * Gets the ID of the key.
13053
- *
13054
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
13055
- * The public key is a protobuf encoding containing a type and the DER encoding
13056
- * of the PKCS SubjectPublicKeyInfo.
13057
- */
13058
- async id() {
13059
- const hash = await this.public.hash();
13060
- return toString$6(hash, 'base58btc');
12476
+ // HMAC (RFC 2104)
12477
+ class HMAC extends Hash {
12478
+ constructor(hash$1, _key) {
12479
+ super();
12480
+ this.finished = false;
12481
+ this.destroyed = false;
12482
+ hash(hash$1);
12483
+ const key = toBytes$1(_key);
12484
+ this.iHash = hash$1.create();
12485
+ if (typeof this.iHash.update !== 'function')
12486
+ throw new Error('Expected instance of class which extends utils.Hash');
12487
+ this.blockLen = this.iHash.blockLen;
12488
+ this.outputLen = this.iHash.outputLen;
12489
+ const blockLen = this.blockLen;
12490
+ const pad = new Uint8Array(blockLen);
12491
+ // blockLen can be bigger than outputLen
12492
+ pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12493
+ for (let i = 0; i < pad.length; i++)
12494
+ pad[i] ^= 0x36;
12495
+ this.iHash.update(pad);
12496
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12497
+ this.oHash = hash$1.create();
12498
+ // Undo internal XOR && apply outer XOR
12499
+ for (let i = 0; i < pad.length; i++)
12500
+ pad[i] ^= 0x36 ^ 0x5c;
12501
+ this.oHash.update(pad);
12502
+ pad.fill(0);
13061
12503
  }
13062
- /**
13063
- * Exports the key as libp2p-key - a aes-gcm encrypted value with the key
13064
- * derived from the password.
13065
- *
13066
- * To export it as a password protected PEM file, please use the `exportPEM`
13067
- * function from `@libp2p/rsa`.
13068
- */
13069
- async export(password, format = 'pkcs-8') {
13070
- if (format === 'pkcs-8') {
13071
- return exportToPem(this, password);
13072
- }
13073
- else if (format === 'libp2p-key') {
13074
- return exporter(this.bytes, password);
13075
- }
13076
- else {
13077
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
13078
- }
12504
+ update(buf) {
12505
+ exists(this);
12506
+ this.iHash.update(buf);
12507
+ return this;
13079
12508
  }
13080
- }
13081
- async function unmarshalRsaPrivateKey(bytes) {
13082
- const jwk = pkcs1ToJwk(bytes);
13083
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13084
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12509
+ digestInto(out) {
12510
+ exists(this);
12511
+ bytes(out, this.outputLen);
12512
+ this.finished = true;
12513
+ this.iHash.digestInto(out);
12514
+ this.oHash.update(out);
12515
+ this.oHash.digestInto(out);
12516
+ this.destroy();
13085
12517
  }
13086
- const keys = await unmarshalPrivateKey$1(jwk);
13087
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
13088
- }
13089
- function unmarshalRsaPublicKey(bytes) {
13090
- const jwk = pkixToJwk(bytes);
13091
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13092
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12518
+ digest() {
12519
+ const out = new Uint8Array(this.oHash.outputLen);
12520
+ this.digestInto(out);
12521
+ return out;
13093
12522
  }
13094
- return new RsaPublicKey(jwk);
13095
- }
13096
- async function fromJwk(jwk) {
13097
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
13098
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12523
+ _cloneInto(to) {
12524
+ // Create new instance without calling constructor since key already in state and we don't know it.
12525
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
12526
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
12527
+ to = to;
12528
+ to.finished = finished;
12529
+ to.destroyed = destroyed;
12530
+ to.blockLen = blockLen;
12531
+ to.outputLen = outputLen;
12532
+ to.oHash = oHash._cloneInto(to.oHash);
12533
+ to.iHash = iHash._cloneInto(to.iHash);
12534
+ return to;
13099
12535
  }
13100
- const keys = await unmarshalPrivateKey$1(jwk);
13101
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
13102
- }
13103
- async function generateKeyPair$1(bits) {
13104
- if (bits > MAX_RSA_KEY_SIZE) {
13105
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12536
+ destroy() {
12537
+ this.destroyed = true;
12538
+ this.oHash.destroy();
12539
+ this.iHash.destroy();
13106
12540
  }
13107
- const keys = await generateKey$1(bits);
13108
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
13109
12541
  }
13110
-
13111
- var RSA = /*#__PURE__*/Object.freeze({
13112
- __proto__: null,
13113
- MAX_RSA_KEY_SIZE: MAX_RSA_KEY_SIZE,
13114
- RsaPrivateKey: RsaPrivateKey,
13115
- RsaPublicKey: RsaPublicKey,
13116
- fromJwk: fromJwk,
13117
- generateKeyPair: generateKeyPair$1,
13118
- unmarshalRsaPrivateKey: unmarshalRsaPrivateKey,
13119
- unmarshalRsaPublicKey: unmarshalRsaPublicKey
13120
- });
12542
+ /**
12543
+ * HMAC: RFC2104 message authentication code.
12544
+ * @param hash - function that would be used e.g. sha256
12545
+ * @param key - message key
12546
+ * @param message - message data
12547
+ * @example
12548
+ * import { hmac } from '@noble/hashes/hmac';
12549
+ * import { sha256 } from '@noble/hashes/sha2';
12550
+ * const mac1 = hmac(sha256, 'key', 'message');
12551
+ */
12552
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12553
+ hmac.create = (hash, key) => new HMAC(hash, key);
13121
12554
 
13122
12555
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13123
12556
  // Short Weierstrass curve. The formula is: y² = x³ + ax + b
@@ -14137,7 +13570,7 @@ function getHash(hash) {
14137
13570
  return {
14138
13571
  hash,
14139
13572
  hmac: (key, ...msgs) => hmac(hash, key, concatBytes$2(...msgs)),
14140
- randomBytes: randomBytes$1,
13573
+ randomBytes,
14141
13574
  };
14142
13575
  }
14143
13576
  function createCurve(curveDef, defHash) {
@@ -14230,27 +13663,15 @@ const secp256k1 = createCurve({
14230
13663
  BigInt(0);
14231
13664
  secp256k1.ProjectivePoint;
14232
13665
 
14233
- function generateKey() {
14234
- return secp256k1.utils.randomPrivateKey();
14235
- }
14236
- /**
14237
- * Hash and sign message with private key
14238
- */
14239
- function hashAndSign(key, msg) {
14240
- const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());
14241
- if (isPromise$1(p)) {
14242
- return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
14243
- .catch(err => {
14244
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14245
- });
14246
- }
14247
- try {
14248
- return secp256k1.sign(p.digest, key).toDERRawBytes();
14249
- }
14250
- catch (err) {
14251
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13666
+ function isPromise$1(thing) {
13667
+ if (thing == null) {
13668
+ return false;
14252
13669
  }
13670
+ return typeof thing.then === 'function' &&
13671
+ typeof thing.catch === 'function' &&
13672
+ typeof thing.finally === 'function';
14253
13673
  }
13674
+
14254
13675
  /**
14255
13676
  * Hash message and verify signature with public key
14256
13677
  */
@@ -14259,231 +13680,134 @@ function hashAndVerify(key, sig, msg) {
14259
13680
  if (isPromise$1(p)) {
14260
13681
  return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
14261
13682
  .catch(err => {
14262
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13683
+ throw new VerificationError(String(err));
14263
13684
  });
14264
13685
  }
14265
13686
  try {
14266
13687
  return secp256k1.verify(sig, p.digest, key);
14267
13688
  }
14268
13689
  catch (err) {
14269
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14270
- }
14271
- }
14272
- function compressPublicKey(key) {
14273
- const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
14274
- return point;
14275
- }
14276
- function validatePrivateKey(key) {
14277
- try {
14278
- secp256k1.getPublicKey(key, true);
14279
- }
14280
- catch (err) {
14281
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
14282
- }
14283
- }
14284
- function validatePublicKey(key) {
14285
- try {
14286
- secp256k1.ProjectivePoint.fromHex(key);
14287
- }
14288
- catch (err) {
14289
- throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
14290
- }
14291
- }
14292
- function computePublicKey(privateKey) {
14293
- try {
14294
- return secp256k1.getPublicKey(privateKey, true);
14295
- }
14296
- catch (err) {
14297
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
13690
+ throw new VerificationError(String(err));
14298
13691
  }
14299
13692
  }
14300
13693
 
14301
13694
  class Secp256k1PublicKey {
13695
+ type = 'secp256k1';
13696
+ raw;
14302
13697
  _key;
14303
13698
  constructor(key) {
14304
- validatePublicKey(key);
14305
- this._key = key;
14306
- }
14307
- verify(data, sig) {
14308
- return hashAndVerify(this._key, sig, data);
14309
- }
14310
- marshal() {
14311
- return compressPublicKey(this._key);
14312
- }
14313
- get bytes() {
14314
- return PublicKey.encode({
14315
- Type: KeyType.Secp256k1,
14316
- Data: this.marshal()
14317
- }).subarray();
14318
- }
14319
- equals(key) {
14320
- return equals(this.bytes, key.bytes);
13699
+ this._key = validateSecp256k1PublicKey(key);
13700
+ this.raw = compressSecp256k1PublicKey(this._key);
14321
13701
  }
14322
- async hash() {
14323
- const p = sha256.digest(this.bytes);
14324
- let bytes;
14325
- if (isPromise$1(p)) {
14326
- ({ bytes } = await p);
14327
- }
14328
- else {
14329
- bytes = p.bytes;
14330
- }
14331
- return bytes;
13702
+ toMultihash() {
13703
+ return identity.digest(publicKeyToProtobuf(this));
14332
13704
  }
14333
- }
14334
- class Secp256k1PrivateKey {
14335
- _key;
14336
- _publicKey;
14337
- constructor(key, publicKey) {
14338
- this._key = key;
14339
- this._publicKey = publicKey ?? computePublicKey(key);
14340
- validatePrivateKey(this._key);
14341
- validatePublicKey(this._publicKey);
14342
- }
14343
- sign(message) {
14344
- return hashAndSign(this._key, message);
14345
- }
14346
- get public() {
14347
- return new Secp256k1PublicKey(this._publicKey);
14348
- }
14349
- marshal() {
14350
- return this._key;
13705
+ toCID() {
13706
+ return CID.createV1(114, this.toMultihash());
14351
13707
  }
14352
- get bytes() {
14353
- return PrivateKey.encode({
14354
- Type: KeyType.Secp256k1,
14355
- Data: this.marshal()
14356
- }).subarray();
13708
+ toString() {
13709
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
14357
13710
  }
14358
13711
  equals(key) {
14359
- return equals(this.bytes, key.bytes);
14360
- }
14361
- hash() {
14362
- const p = sha256.digest(this.bytes);
14363
- if (isPromise$1(p)) {
14364
- return p.then(({ bytes }) => bytes);
13712
+ if (key == null || !(key.raw instanceof Uint8Array)) {
13713
+ return false;
14365
13714
  }
14366
- return p.bytes;
13715
+ return equals(this.raw, key.raw);
14367
13716
  }
14368
- /**
14369
- * Gets the ID of the key.
14370
- *
14371
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
14372
- * The public key is a protobuf encoding containing a type and the DER encoding
14373
- * of the PKCS SubjectPublicKeyInfo.
14374
- */
14375
- async id() {
14376
- const hash = await this.public.hash();
14377
- return toString$6(hash, 'base58btc');
14378
- }
14379
- /**
14380
- * Exports the key into a password protected `format`
14381
- */
14382
- async export(password, format = 'libp2p-key') {
14383
- if (format === 'libp2p-key') {
14384
- return exporter(this.bytes, password);
14385
- }
14386
- else {
14387
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
14388
- }
13717
+ verify(data, sig) {
13718
+ return hashAndVerify(this._key, sig, data);
14389
13719
  }
14390
13720
  }
14391
- function unmarshalSecp256k1PrivateKey(bytes) {
14392
- return new Secp256k1PrivateKey(bytes);
14393
- }
13721
+
14394
13722
  function unmarshalSecp256k1PublicKey(bytes) {
14395
13723
  return new Secp256k1PublicKey(bytes);
14396
13724
  }
14397
- async function generateKeyPair() {
14398
- const privateKeyBytes = generateKey();
14399
- return new Secp256k1PrivateKey(privateKeyBytes);
13725
+ function compressSecp256k1PublicKey(key) {
13726
+ const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
13727
+ return point;
13728
+ }
13729
+ function validateSecp256k1PublicKey(key) {
13730
+ try {
13731
+ secp256k1.ProjectivePoint.fromHex(key);
13732
+ return key;
13733
+ }
13734
+ catch (err) {
13735
+ throw new InvalidPublicKeyError(String(err));
13736
+ }
14400
13737
  }
14401
-
14402
- var Secp256k1 = /*#__PURE__*/Object.freeze({
14403
- __proto__: null,
14404
- Secp256k1PrivateKey: Secp256k1PrivateKey,
14405
- Secp256k1PublicKey: Secp256k1PublicKey,
14406
- generateKeyPair: generateKeyPair,
14407
- unmarshalSecp256k1PrivateKey: unmarshalSecp256k1PrivateKey,
14408
- unmarshalSecp256k1PublicKey: unmarshalSecp256k1PublicKey
14409
- });
14410
13738
 
14411
13739
  /**
14412
13740
  * @packageDocumentation
14413
13741
  *
14414
- * **Supported Key Types**
14415
- *
14416
- * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.
13742
+ * ## Supported Key Types
14417
13743
  *
14418
13744
  * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
14419
13745
  *
14420
13746
  * For encryption / decryption support, RSA keys should be used.
14421
13747
  */
14422
- const supportedKeys = {
14423
- rsa: RSA,
14424
- ed25519: Ed25519,
14425
- secp256k1: Secp256k1
14426
- };
14427
- function unsupportedKey(type) {
14428
- const supported = Object.keys(supportedKeys).join(' / ');
14429
- return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
14430
- }
14431
- function typeToKey(type) {
14432
- type = type.toLowerCase();
14433
- if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {
14434
- return supportedKeys[type];
13748
+ /**
13749
+ * Creates a public key from the raw key bytes
13750
+ */
13751
+ function publicKeyFromRaw(buf) {
13752
+ if (buf.byteLength === 32) {
13753
+ return unmarshalEd25519PublicKey(buf);
13754
+ }
13755
+ else if (buf.byteLength === 33) {
13756
+ return unmarshalSecp256k1PublicKey(buf);
13757
+ }
13758
+ else {
13759
+ return pkixToRSAPublicKey(buf);
14435
13760
  }
14436
- throw unsupportedKey(type);
14437
13761
  }
14438
13762
  /**
14439
- * Converts a protobuf serialized public key into its representative object
13763
+ * Creates a public key from an identity multihash which contains a protobuf
13764
+ * encoded Ed25519 or secp256k1 public key.
13765
+ *
13766
+ * RSA keys are not supported as in practice we they are not stored in identity
13767
+ * multihashes since the hash would be very large.
14440
13768
  */
14441
- function unmarshalPublicKey(buf) {
14442
- const decoded = PublicKey.decode(buf);
14443
- const data = decoded.Data ?? new Uint8Array();
14444
- switch (decoded.Type) {
14445
- case KeyType.RSA:
14446
- return supportedKeys.rsa.unmarshalRsaPublicKey(data);
13769
+ function publicKeyFromMultihash(digest) {
13770
+ const { Type, Data } = PublicKey.decode(digest.digest);
13771
+ const data = Data ?? new Uint8Array();
13772
+ switch (Type) {
14447
13773
  case KeyType.Ed25519:
14448
- return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);
14449
- case KeyType.Secp256k1:
14450
- return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);
13774
+ return unmarshalEd25519PublicKey(data);
13775
+ case KeyType.secp256k1:
13776
+ return unmarshalSecp256k1PublicKey(data);
14451
13777
  default:
14452
- throw unsupportedKey(decoded.Type ?? 'unknown');
13778
+ throw new UnsupportedKeyTypeError$1();
14453
13779
  }
14454
13780
  }
14455
13781
  /**
14456
13782
  * Converts a public key object into a protobuf serialized public key
14457
13783
  */
14458
- function marshalPublicKey(key, type) {
14459
- type = (type ?? 'rsa').toLowerCase();
14460
- typeToKey(type); // check type
14461
- return key.bytes;
13784
+ function publicKeyToProtobuf(key) {
13785
+ return PublicKey.encode({
13786
+ Type: KeyType[key.type],
13787
+ Data: key.raw
13788
+ });
14462
13789
  }
13790
+
14463
13791
  /**
14464
- * Converts a protobuf serialized private key into its representative object
13792
+ * All PeerId implementations must use this symbol as the name of a property
13793
+ * with a boolean `true` value
14465
13794
  */
14466
- async function unmarshalPrivateKey(buf) {
14467
- const decoded = PrivateKey.decode(buf);
14468
- const data = decoded.Data ?? new Uint8Array();
14469
- switch (decoded.Type) {
14470
- case KeyType.RSA:
14471
- return supportedKeys.rsa.unmarshalRsaPrivateKey(data);
14472
- case KeyType.Ed25519:
14473
- return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);
14474
- case KeyType.Secp256k1:
14475
- return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);
14476
- default:
14477
- throw unsupportedKey(decoded.Type ?? 'RSA');
14478
- }
14479
- }
13795
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
13796
+
14480
13797
  /**
14481
- * Converts a private key object into a protobuf serialized private key
13798
+ * When this error is thrown it means an operation was aborted,
13799
+ * usually in response to the `abort` event being emitted by an
13800
+ * AbortSignal.
13801
+ */
13802
+ /**
13803
+ * Thrown when and attempt to operate on an unsupported key was made
14482
13804
  */
14483
- function marshalPrivateKey(key, type) {
14484
- type = (type ?? 'rsa').toLowerCase();
14485
- typeToKey(type); // check type
14486
- return key.bytes;
13805
+ class UnsupportedKeyTypeError extends Error {
13806
+ static name = 'UnsupportedKeyTypeError';
13807
+ constructor(message = 'Unsupported key type') {
13808
+ super(message);
13809
+ this.name = 'UnsupportedKeyTypeError';
13810
+ }
14487
13811
  }
14488
13812
 
14489
13813
  /**
@@ -14501,26 +13825,17 @@ function marshalPrivateKey(key, type) {
14501
13825
  * console.log(peer.toString()) // "12D3K..."
14502
13826
  * ```
14503
13827
  */
14504
- const inspect = Symbol.for('nodejs.util.inspect.custom');
14505
- const baseDecoder = Object
14506
- .values(bases)
14507
- .map(codec => codec.decoder)
14508
- // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
14509
- .reduce((acc, curr) => acc.or(curr), bases.identity.decoder);
13828
+ const inspect$1 = Symbol.for('nodejs.util.inspect.custom');
14510
13829
  // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14511
- const LIBP2P_KEY_CODE = 0x72;
14512
- const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;
14513
- const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;
14514
- class PeerIdImpl {
13830
+ const LIBP2P_KEY_CODE$1 = 0x72;
13831
+ let PeerIdImpl$1 = class PeerIdImpl {
14515
13832
  type;
14516
13833
  multihash;
14517
- privateKey;
14518
13834
  publicKey;
14519
13835
  string;
14520
13836
  constructor(init) {
14521
13837
  this.type = init.type;
14522
13838
  this.multihash = init.multihash;
14523
- this.privateKey = init.privateKey;
14524
13839
  // mark string cache as non-enumerable
14525
13840
  Object.defineProperty(this, 'string', {
14526
13841
  enumerable: false,
@@ -14537,17 +13852,14 @@ class PeerIdImpl {
14537
13852
  }
14538
13853
  return this.string;
14539
13854
  }
13855
+ toMultihash() {
13856
+ return this.multihash;
13857
+ }
14540
13858
  // return self-describing String representation
14541
13859
  // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
14542
13860
  toCID() {
14543
- return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
13861
+ return CID.createV1(LIBP2P_KEY_CODE$1, this.multihash);
14544
13862
  }
14545
- toBytes() {
14546
- return this.multihash.bytes;
14547
- }
14548
- /**
14549
- * Returns Multiaddr as a JSON string
14550
- */
14551
13863
  toJSON() {
14552
13864
  return this.toString();
14553
13865
  }
@@ -14562,10 +13874,10 @@ class PeerIdImpl {
14562
13874
  return equals(this.multihash.bytes, id);
14563
13875
  }
14564
13876
  else if (typeof id === 'string') {
14565
- return peerIdFromString(id).equals(this);
13877
+ return this.toString() === id;
14566
13878
  }
14567
- else if (id?.multihash?.bytes != null) {
14568
- return equals(this.multihash.bytes, id.multihash.bytes);
13879
+ else if (id?.toMultihash()?.bytes != null) {
13880
+ return equals(this.multihash.bytes, id.toMultihash().bytes);
14569
13881
  }
14570
13882
  else {
14571
13883
  throw new Error('not valid Id');
@@ -14583,145 +13895,79 @@ class PeerIdImpl {
14583
13895
  * // 'PeerId(QmFoo)'
14584
13896
  * ```
14585
13897
  */
14586
- [inspect]() {
13898
+ [inspect$1]() {
14587
13899
  return `PeerId(${this.toString()})`;
14588
13900
  }
14589
- }
14590
- class RSAPeerIdImpl extends PeerIdImpl {
13901
+ };
13902
+ let RSAPeerId$1 = class RSAPeerId extends PeerIdImpl$1 {
14591
13903
  type = 'RSA';
14592
13904
  publicKey;
14593
13905
  constructor(init) {
14594
13906
  super({ ...init, type: 'RSA' });
14595
13907
  this.publicKey = init.publicKey;
14596
13908
  }
14597
- }
14598
- class Ed25519PeerIdImpl extends PeerIdImpl {
13909
+ };
13910
+ let Ed25519PeerId$1 = class Ed25519PeerId extends PeerIdImpl$1 {
14599
13911
  type = 'Ed25519';
14600
13912
  publicKey;
14601
13913
  constructor(init) {
14602
13914
  super({ ...init, type: 'Ed25519' });
14603
- this.publicKey = init.multihash.digest;
13915
+ this.publicKey = init.publicKey;
14604
13916
  }
14605
- }
14606
- class Secp256k1PeerIdImpl extends PeerIdImpl {
13917
+ };
13918
+ let Secp256k1PeerId$1 = class Secp256k1PeerId extends PeerIdImpl$1 {
14607
13919
  type = 'secp256k1';
14608
13920
  publicKey;
14609
13921
  constructor(init) {
14610
13922
  super({ ...init, type: 'secp256k1' });
14611
- this.publicKey = init.multihash.digest;
14612
- }
14613
- }
14614
- // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14615
- const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
14616
- class URLPeerIdImpl {
14617
- type = 'url';
14618
- multihash;
14619
- privateKey;
14620
- publicKey;
14621
- url;
14622
- constructor(url) {
14623
- this.url = url.toString();
14624
- this.multihash = identity.digest(fromString(this.url));
14625
- }
14626
- [inspect]() {
14627
- return `PeerId(${this.url})`;
14628
- }
14629
- [peerIdSymbol] = true;
14630
- toString() {
14631
- return this.toCID().toString();
14632
- }
14633
- toCID() {
14634
- return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
14635
- }
14636
- toBytes() {
14637
- return this.toCID().bytes;
14638
- }
14639
- equals(other) {
14640
- if (other == null) {
14641
- return false;
14642
- }
14643
- if (other instanceof Uint8Array) {
14644
- other = toString$6(other);
14645
- }
14646
- return other.toString() === this.toString();
14647
- }
14648
- }
14649
- function peerIdFromString(str, decoder) {
14650
- if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
14651
- // identity hash ed25519/secp256k1 key or sha2-256 hash of
14652
- // rsa public key - base58btc encoded either way
14653
- const multihash = decode$6(base58btc.decode(`z${str}`));
14654
- if (str.startsWith('12D')) {
14655
- return new Ed25519PeerIdImpl({ multihash });
14656
- }
14657
- else if (str.startsWith('16U')) {
14658
- return new Secp256k1PeerIdImpl({ multihash });
14659
- }
14660
- else {
14661
- return new RSAPeerIdImpl({ multihash });
14662
- }
14663
- }
14664
- return peerIdFromBytes(baseDecoder.decode(str));
14665
- }
14666
- function peerIdFromBytes(buf) {
14667
- try {
14668
- const multihash = decode$6(buf);
14669
- if (multihash.code === identity.code) {
14670
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14671
- return new Ed25519PeerIdImpl({ multihash });
14672
- }
14673
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14674
- return new Secp256k1PeerIdImpl({ multihash });
14675
- }
14676
- }
14677
- if (multihash.code === sha256.code) {
14678
- return new RSAPeerIdImpl({ multihash });
14679
- }
14680
- }
14681
- catch {
14682
- return peerIdFromCID(CID.decode(buf));
14683
- }
14684
- throw new Error('Supplied PeerID CID is invalid');
14685
- }
14686
- function peerIdFromCID(cid) {
14687
- if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
14688
- throw new Error('Supplied PeerID CID is invalid');
14689
- }
14690
- if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
14691
- const url = toString$6(cid.multihash.digest);
14692
- return new URLPeerIdImpl(new URL(url));
14693
- }
14694
- const multihash = cid.multihash;
14695
- if (multihash.code === sha256.code) {
14696
- return new RSAPeerIdImpl({ multihash: cid.multihash });
14697
- }
14698
- else if (multihash.code === identity.code) {
14699
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14700
- return new Ed25519PeerIdImpl({ multihash: cid.multihash });
14701
- }
14702
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14703
- return new Secp256k1PeerIdImpl({ multihash: cid.multihash });
14704
- }
13923
+ this.publicKey = init.publicKey;
14705
13924
  }
14706
- throw new Error('Supplied PeerID CID is invalid');
14707
- }
13925
+ };
13926
+
14708
13927
  /**
14709
- * @param publicKey - A marshalled public key
14710
- * @param privateKey - A marshalled private key
13928
+ * @packageDocumentation
13929
+ *
13930
+ * An implementation of a peer id
13931
+ *
13932
+ * @example
13933
+ *
13934
+ * ```TypeScript
13935
+ * import { peerIdFromString } from '@libp2p/peer-id'
13936
+ * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
13937
+ *
13938
+ * console.log(peer.toCID()) // CID(bafzaa...)
13939
+ * console.log(peer.toString()) // "12D3K..."
13940
+ * ```
14711
13941
  */
14712
- async function peerIdFromKeys(publicKey, privateKey) {
14713
- if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14714
- return new Ed25519PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13942
+ function peerIdFromPublicKey(publicKey) {
13943
+ if (publicKey.type === 'Ed25519') {
13944
+ return new Ed25519PeerId$1({
13945
+ multihash: publicKey.toCID().multihash,
13946
+ publicKey
13947
+ });
14715
13948
  }
14716
- if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14717
- return new Secp256k1PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13949
+ else if (publicKey.type === 'secp256k1') {
13950
+ return new Secp256k1PeerId$1({
13951
+ multihash: publicKey.toCID().multihash,
13952
+ publicKey
13953
+ });
13954
+ }
13955
+ else if (publicKey.type === 'RSA') {
13956
+ return new RSAPeerId$1({
13957
+ multihash: publicKey.toCID().multihash,
13958
+ publicKey
13959
+ });
14718
13960
  }
14719
- return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey });
13961
+ throw new UnsupportedKeyTypeError();
14720
13962
  }
14721
13963
 
13964
+ const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
14722
13965
  function createPeerIdFromPublicKey(publicKey) {
14723
- const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
14724
- return peerIdFromKeys(_publicKey.bytes, undefined);
13966
+ const pubKey = publicKeyFromRaw(publicKey);
13967
+ if (pubKey.type !== "secp256k1") {
13968
+ throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
13969
+ }
13970
+ return peerIdFromPublicKey(pubKey);
14725
13971
  }
14726
13972
 
14727
13973
  function decodeMultiaddrs(bytes) {
@@ -14968,12 +14214,12 @@ var TransportProtocolPerIpVersion;
14968
14214
  class ENR extends RawEnr {
14969
14215
  static RECORD_PREFIX = "enr:";
14970
14216
  peerId;
14971
- static async create(kvs = {}, seq = BigInt(1), signature) {
14217
+ static create(kvs = {}, seq = BigInt(1), signature) {
14972
14218
  const enr = new ENR(kvs, seq, signature);
14973
14219
  try {
14974
14220
  const publicKey = enr.publicKey;
14975
14221
  if (publicKey) {
14976
- enr.peerId = await createPeerIdFromPublicKey(publicKey);
14222
+ enr.peerId = createPeerIdFromPublicKey(publicKey);
14977
14223
  }
14978
14224
  }
14979
14225
  catch (e) {
@@ -15738,7 +14984,7 @@ async function fromValues(values) {
15738
14984
  }
15739
14985
  }
15740
14986
  const _seq = decodeSeq(seq);
15741
- const enr = await ENR.create(obj, _seq, signature);
14987
+ const enr = ENR.create(obj, _seq, signature);
15742
14988
  checkSignature(seq, kvs, enr, signature);
15743
14989
  return enr;
15744
14990
  }
@@ -25004,50 +24250,210 @@ function wakuPeerExchangeDiscovery(pubsubTopics) {
25004
24250
  /**
25005
24251
  * @packageDocumentation
25006
24252
  *
25007
- * Generate, import, and export PeerIDs.
25008
- *
25009
- * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.
25010
- *
25011
- * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.
24253
+ * An implementation of a peer id
25012
24254
  *
25013
24255
  * @example
25014
24256
  *
25015
24257
  * ```TypeScript
25016
- * import { createEd25519PeerId } from '@libp2p/peer-id-factory'
25017
- *
25018
- * const peerId = await createEd25519PeerId()
25019
- * console.log(peerId.toString())
25020
- * ```
24258
+ * import { peerIdFromString } from '@libp2p/peer-id'
24259
+ * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
25021
24260
  *
25022
- * ```bash
25023
- * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD
24261
+ * console.log(peer.toCID()) // CID(bafzaa...)
24262
+ * console.log(peer.toString()) // "12D3K..."
25024
24263
  * ```
25025
24264
  */
25026
- async function createFromPubKey(publicKey) {
25027
- return peerIdFromKeys(marshalPublicKey(publicKey));
24265
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
24266
+ // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
24267
+ const LIBP2P_KEY_CODE = 0x72;
24268
+ class PeerIdImpl {
24269
+ type;
24270
+ multihash;
24271
+ publicKey;
24272
+ string;
24273
+ constructor(init) {
24274
+ this.type = init.type;
24275
+ this.multihash = init.multihash;
24276
+ // mark string cache as non-enumerable
24277
+ Object.defineProperty(this, 'string', {
24278
+ enumerable: false,
24279
+ writable: true
24280
+ });
24281
+ }
24282
+ get [Symbol.toStringTag]() {
24283
+ return `PeerId(${this.toString()})`;
24284
+ }
24285
+ [peerIdSymbol$1] = true;
24286
+ toString() {
24287
+ if (this.string == null) {
24288
+ this.string = base58btc.encode(this.multihash.bytes).slice(1);
24289
+ }
24290
+ return this.string;
24291
+ }
24292
+ toMultihash() {
24293
+ return this.multihash;
24294
+ }
24295
+ // return self-describing String representation
24296
+ // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
24297
+ toCID() {
24298
+ return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
24299
+ }
24300
+ toJSON() {
24301
+ return this.toString();
24302
+ }
24303
+ /**
24304
+ * Checks the equality of `this` peer against a given PeerId
24305
+ */
24306
+ equals(id) {
24307
+ if (id == null) {
24308
+ return false;
24309
+ }
24310
+ if (id instanceof Uint8Array) {
24311
+ return equals(this.multihash.bytes, id);
24312
+ }
24313
+ else if (typeof id === 'string') {
24314
+ return this.toString() === id;
24315
+ }
24316
+ else if (id?.toMultihash()?.bytes != null) {
24317
+ return equals(this.multihash.bytes, id.toMultihash().bytes);
24318
+ }
24319
+ else {
24320
+ throw new Error('not valid Id');
24321
+ }
24322
+ }
24323
+ /**
24324
+ * Returns PeerId as a human-readable string
24325
+ * https://nodejs.org/api/util.html#utilinspectcustom
24326
+ *
24327
+ * @example
24328
+ * ```TypeScript
24329
+ * import { peerIdFromString } from '@libp2p/peer-id'
24330
+ *
24331
+ * console.info(peerIdFromString('QmFoo'))
24332
+ * // 'PeerId(QmFoo)'
24333
+ * ```
24334
+ */
24335
+ [inspect]() {
24336
+ return `PeerId(${this.toString()})`;
24337
+ }
24338
+ }
24339
+ class RSAPeerId extends PeerIdImpl {
24340
+ type = 'RSA';
24341
+ publicKey;
24342
+ constructor(init) {
24343
+ super({ ...init, type: 'RSA' });
24344
+ this.publicKey = init.publicKey;
24345
+ }
24346
+ }
24347
+ class Ed25519PeerId extends PeerIdImpl {
24348
+ type = 'Ed25519';
24349
+ publicKey;
24350
+ constructor(init) {
24351
+ super({ ...init, type: 'Ed25519' });
24352
+ this.publicKey = init.publicKey;
24353
+ }
25028
24354
  }
25029
- async function createFromPrivKey(privateKey) {
25030
- return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey));
24355
+ class Secp256k1PeerId extends PeerIdImpl {
24356
+ type = 'secp256k1';
24357
+ publicKey;
24358
+ constructor(init) {
24359
+ super({ ...init, type: 'secp256k1' });
24360
+ this.publicKey = init.publicKey;
24361
+ }
25031
24362
  }
25032
- async function createFromJSON(obj) {
25033
- return createFromParts(fromString(obj.id, 'base58btc'), obj.privKey != null ? fromString(obj.privKey, 'base64pad') : undefined, obj.pubKey != null ? fromString(obj.pubKey, 'base64pad') : undefined);
24363
+ // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
24364
+ const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
24365
+ class URLPeerId {
24366
+ type = 'url';
24367
+ multihash;
24368
+ publicKey;
24369
+ url;
24370
+ constructor(url) {
24371
+ this.url = url.toString();
24372
+ this.multihash = identity.digest(fromString(this.url));
24373
+ }
24374
+ [inspect]() {
24375
+ return `PeerId(${this.url})`;
24376
+ }
24377
+ [peerIdSymbol$1] = true;
24378
+ toString() {
24379
+ return this.toCID().toString();
24380
+ }
24381
+ toMultihash() {
24382
+ return this.multihash;
24383
+ }
24384
+ toCID() {
24385
+ return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash());
24386
+ }
24387
+ toJSON() {
24388
+ return this.toString();
24389
+ }
24390
+ equals(other) {
24391
+ if (other == null) {
24392
+ return false;
24393
+ }
24394
+ if (other instanceof Uint8Array) {
24395
+ other = toString$6(other);
24396
+ }
24397
+ return other.toString() === this.toString();
24398
+ }
25034
24399
  }
25035
- async function createFromParts(multihash, privKey, pubKey) {
25036
- if (privKey != null) {
25037
- const key = await unmarshalPrivateKey(privKey);
25038
- return createFromPrivKey(key);
24400
+
24401
+ /**
24402
+ * @packageDocumentation
24403
+ *
24404
+ * An implementation of a peer id
24405
+ *
24406
+ * @example
24407
+ *
24408
+ * ```TypeScript
24409
+ * import { peerIdFromString } from '@libp2p/peer-id'
24410
+ * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
24411
+ *
24412
+ * console.log(peer.toCID()) // CID(bafzaa...)
24413
+ * console.log(peer.toString()) // "12D3K..."
24414
+ * ```
24415
+ */
24416
+ function peerIdFromString(str, decoder) {
24417
+ let multihash;
24418
+ if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
24419
+ // identity hash ed25519/secp256k1 key or sha2-256 hash of
24420
+ // rsa public key - base58btc encoded either way
24421
+ multihash = decode$6(base58btc.decode(`z${str}`));
24422
+ }
24423
+ else {
24424
+ {
24425
+ throw new InvalidParametersError$1('Please pass a multibase decoder for strings that do not start with "1" or "Q"');
24426
+ }
25039
24427
  }
25040
- else if (pubKey != null) {
25041
- const key = unmarshalPublicKey(pubKey);
25042
- return createFromPubKey(key);
24428
+ return peerIdFromMultihash(multihash);
24429
+ }
24430
+ function peerIdFromMultihash(multihash) {
24431
+ if (isSha256Multihash(multihash)) {
24432
+ return new RSAPeerId({ multihash });
25043
24433
  }
25044
- const peerId = peerIdFromBytes(multihash);
25045
- if (peerId.type !== 'Ed25519' && peerId.type !== 'secp256k1' && peerId.type !== 'RSA') {
25046
- // should not be possible since `multihash` is derived from keys and these
25047
- // are the cryptographic peer id types
25048
- throw new Error('Supplied PeerID is invalid');
24434
+ else if (isIdentityMultihash(multihash)) {
24435
+ try {
24436
+ const publicKey = publicKeyFromMultihash(multihash);
24437
+ if (publicKey.type === 'Ed25519') {
24438
+ return new Ed25519PeerId({ multihash, publicKey });
24439
+ }
24440
+ else if (publicKey.type === 'secp256k1') {
24441
+ return new Secp256k1PeerId({ multihash, publicKey });
24442
+ }
24443
+ }
24444
+ catch (err) {
24445
+ // was not Ed or secp key, try URL
24446
+ const url = toString$6(multihash.digest);
24447
+ return new URLPeerId(new URL(url));
24448
+ }
25049
24449
  }
25050
- return peerId;
24450
+ throw new InvalidMultihashError('Supplied PeerID Multihash is invalid');
24451
+ }
24452
+ function isIdentityMultihash(multihash) {
24453
+ return multihash.code === identity.code;
24454
+ }
24455
+ function isSha256Multihash(multihash) {
24456
+ return multihash.code === sha256.code;
25051
24457
  }
25052
24458
 
25053
24459
  const log = new Logger$1("peer-exchange-discovery");
@@ -25075,7 +24481,7 @@ class LocalPeerCacheDiscovery extends TypedEventEmitter {
25075
24481
  log.info("Starting Local Storage Discovery");
25076
24482
  this.components.events.addEventListener("peer:identify", this.handleNewPeers);
25077
24483
  for (const { id: idStr, address } of this.peers) {
25078
- const peerId = await createFromJSON({ id: idStr });
24484
+ const peerId = peerIdFromString(idStr);
25079
24485
  if (await this.components.peerStore.has(peerId))
25080
24486
  continue;
25081
24487
  await this.components.peerStore.save(peerId, {