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