@waku/enr 0.0.27 → 0.0.28-b6339f7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/index.js CHANGED
@@ -745,7 +745,7 @@ function encodingLength$1(int) {
745
745
  /**
746
746
  * Creates a multihash digest.
747
747
  */
748
- function create$1(code, digest) {
748
+ function create(code, digest) {
749
749
  const size = digest.byteLength;
750
750
  const sizeOffset = encodingLength$1(code);
751
751
  const digestOffset = sizeOffset + encodingLength$1(size);
@@ -804,7 +804,7 @@ const code = 0x0;
804
804
  const name = 'identity';
805
805
  const encode$2 = coerce;
806
806
  function digest(input) {
807
- return create$1(code, encode$2(input));
807
+ return create(code, encode$2(input));
808
808
  }
809
809
  const identity = { code, name, encode: encode$2, digest };
810
810
 
@@ -828,9 +828,9 @@ class Hasher {
828
828
  if (input instanceof Uint8Array) {
829
829
  const result = this.encode(input);
830
830
  return result instanceof Uint8Array
831
- ? create$1(this.code, result)
831
+ ? create(this.code, result)
832
832
  /* c8 ignore next 1 */
833
- : result.then(digest => create$1(this.code, digest));
833
+ : result.then(digest => create(this.code, digest));
834
834
  }
835
835
  else {
836
836
  throw Error('Unknown type, must be binary type');
@@ -930,7 +930,7 @@ class CID {
930
930
  switch (this.version) {
931
931
  case 0: {
932
932
  const { code, digest } = this.multihash;
933
- const multihash = create$1(code, digest);
933
+ const multihash = create(code, digest);
934
934
  return (CID.createV1(this.code, multihash));
935
935
  }
936
936
  case 1: {
@@ -3072,7 +3072,7 @@ async function sign$1(message, privateKey) {
3072
3072
  function keccak256(input) {
3073
3073
  return new Uint8Array(sha3.keccak256.arrayBuffer(input));
3074
3074
  }
3075
- function compressPublicKey$1(publicKey) {
3075
+ function compressPublicKey(publicKey) {
3076
3076
  if (publicKey.length === 64) {
3077
3077
  publicKey = concat$2([new Uint8Array([4]), publicKey], 65);
3078
3078
  }
@@ -3141,23 +3141,6 @@ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLen
3141
3141
  // The rotate right (circular right shift) operation for uint32
3142
3142
  const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
3143
3143
  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3144
- // There is no setImmediate in browser and setTimeout is slow.
3145
- // call of async fn will return Promise, which will be fullfiled only on
3146
- // next scheduler queue processing step and this is exactly what we need.
3147
- const nextTick = async () => { };
3148
- // Returns control to thread each 'tick' ms to avoid blocking
3149
- async function asyncLoop(iters, tick, cb) {
3150
- let ts = Date.now();
3151
- for (let i = 0; i < iters; i++) {
3152
- cb(i);
3153
- // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
3154
- const diff = Date.now() - ts;
3155
- if (diff >= 0 && diff < tick)
3156
- continue;
3157
- await nextTick();
3158
- ts += diff;
3159
- }
3160
- }
3161
3144
  /**
3162
3145
  * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
3163
3146
  */
@@ -3202,13 +3185,6 @@ class Hash {
3202
3185
  return this._cloneInto();
3203
3186
  }
3204
3187
  }
3205
- const toStr = {}.toString;
3206
- function checkOpts(defaults, opts) {
3207
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
3208
- throw new Error('Options should be object or undefined');
3209
- const merged = Object.assign(defaults, opts);
3210
- return merged;
3211
- }
3212
3188
  function wrapConstructor(hashCons) {
3213
3189
  const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
3214
3190
  const tmp = hashCons();
@@ -3220,7 +3196,7 @@ function wrapConstructor(hashCons) {
3220
3196
  /**
3221
3197
  * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
3222
3198
  */
3223
- function randomBytes$1(bytesLength = 32) {
3199
+ function randomBytes(bytesLength = 32) {
3224
3200
  if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
3225
3201
  return crypto$1.getRandomValues(new Uint8Array(bytesLength));
3226
3202
  }
@@ -5812,31 +5788,30 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
5812
5788
  return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
5813
5789
  }
5814
5790
 
5815
- const peerIdSymbol = Symbol.for('@libp2p/peer-id');
5816
-
5817
5791
  /**
5818
5792
  * When this error is thrown it means an operation was aborted,
5819
5793
  * usually in response to the `abort` event being emitted by an
5820
5794
  * AbortSignal.
5821
5795
  */
5822
- class CodeError extends Error {
5823
- code;
5824
- props;
5825
- constructor(message, code, props) {
5796
+ /**
5797
+ * Thrown when invalid parameters are passed to a function or method call
5798
+ */
5799
+ class InvalidParametersError extends Error {
5800
+ static name = 'InvalidParametersError';
5801
+ constructor(message = 'Invalid parameters') {
5826
5802
  super(message);
5827
- this.code = code;
5828
- this.name = props?.name ?? 'CodeError';
5829
- this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
5803
+ this.name = 'InvalidParametersError';
5830
5804
  }
5831
5805
  }
5832
-
5833
- function isPromise(thing) {
5834
- if (thing == null) {
5835
- return false;
5806
+ /**
5807
+ * Thrown when a public key is invalid
5808
+ */
5809
+ class InvalidPublicKeyError extends Error {
5810
+ static name = 'InvalidPublicKeyError';
5811
+ constructor(message = 'Invalid public key') {
5812
+ super(message);
5813
+ this.name = 'InvalidPublicKeyError';
5836
5814
  }
5837
- return typeof thing.then === 'function' &&
5838
- typeof thing.catch === 'function' &&
5839
- typeof thing.finally === 'function';
5840
5815
  }
5841
5816
 
5842
5817
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
@@ -7510,7 +7485,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7510
7485
  Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
7511
7486
  Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
7512
7487
  hash: sha512,
7513
- randomBytes: randomBytes$1,
7488
+ randomBytes,
7514
7489
  adjustScalarBytes,
7515
7490
  // dom2
7516
7491
  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
@@ -7523,176 +7498,46 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
7523
7498
  const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
7524
7499
 
7525
7500
  const PUBLIC_KEY_BYTE_LENGTH = 32;
7526
- const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
7527
- const KEYS_BYTE_LENGTH = 32;
7528
- function generateKey$2() {
7529
- // the actual private key (32 bytes)
7530
- const privateKeyRaw = ed25519.utils.randomPrivateKey();
7531
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7532
- // concatenated the public key to the private key
7533
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7534
- return {
7535
- privateKey,
7536
- publicKey
7537
- };
7538
- }
7539
- /**
7540
- * Generate keypair from a 32 byte uint8array
7541
- */
7542
- function generateKeyFromSeed(seed) {
7543
- if (seed.length !== KEYS_BYTE_LENGTH) {
7544
- throw new TypeError('"seed" must be 32 bytes in length.');
7545
- }
7546
- else if (!(seed instanceof Uint8Array)) {
7547
- throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
7548
- }
7549
- // based on node forges algorithm, the seed is used directly as private key
7550
- const privateKeyRaw = seed;
7551
- const publicKey = ed25519.getPublicKey(privateKeyRaw);
7552
- const privateKey = concatKeys(privateKeyRaw, publicKey);
7553
- return {
7554
- privateKey,
7555
- publicKey
7556
- };
7557
- }
7558
- function hashAndSign$2(privateKey, msg) {
7559
- const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
7560
- return ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
7561
- }
7562
7501
  function hashAndVerify$2(publicKey, sig, msg) {
7563
7502
  return ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
7564
7503
  }
7565
- function concatKeys(privateKeyRaw, publicKey) {
7566
- const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
7567
- for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
7568
- privateKey[i] = privateKeyRaw[i];
7569
- privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
7570
- }
7571
- return privateKey;
7572
- }
7573
7504
 
7574
- /* eslint-env browser */
7575
- // Check native crypto exists and is enabled (In insecure context `self.crypto`
7576
- // exists but `self.crypto.subtle` does not).
7577
- var webcrypto = {
7578
- get(win = globalThis) {
7579
- const nativeCrypto = win.crypto;
7580
- if (nativeCrypto?.subtle == null) {
7581
- throw Object.assign(new Error('Missing Web Crypto API. ' +
7582
- 'The most likely cause of this error is that this page is being accessed ' +
7583
- 'from an insecure context (i.e. not HTTPS). For more information and ' +
7584
- 'possible resolutions see ' +
7585
- 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });
7586
- }
7587
- return nativeCrypto;
7505
+ class Ed25519PublicKey {
7506
+ type = 'Ed25519';
7507
+ raw;
7508
+ constructor(key) {
7509
+ this.raw = ensureEd25519Key(key, PUBLIC_KEY_BYTE_LENGTH);
7588
7510
  }
7589
- };
7590
-
7591
- // WebKit on Linux does not support deriving a key from an empty PBKDF2 key.
7592
- // So, as a workaround, we provide the generated key as a constant. We test that
7593
- // this generated key is accurate in test/workaround.spec.ts
7594
- // Generated via:
7595
- // await crypto.subtle.exportKey('jwk',
7596
- // await crypto.subtle.deriveKey(
7597
- // { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },
7598
- // await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),
7599
- // { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])
7600
- // )
7601
- const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
7602
- // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
7603
- function create(opts) {
7604
- const algorithm = 'AES-GCM';
7605
- let keyLength = 16;
7606
- const nonceLength = 12;
7607
- const digest = 'SHA-256';
7608
- const saltLength = 16;
7609
- const iterations = 32767;
7610
- const crypto = webcrypto.get();
7611
- keyLength *= 8; // Browser crypto uses bits instead of bytes
7612
- /**
7613
- * Uses the provided password to derive a pbkdf2 key. The key
7614
- * will then be used to encrypt the data.
7615
- */
7616
- async function encrypt(data, password) {
7617
- const salt = crypto.getRandomValues(new Uint8Array(saltLength));
7618
- const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));
7619
- const aesGcm = { name: algorithm, iv: nonce };
7620
- if (typeof password === 'string') {
7621
- password = fromString(password);
7622
- }
7623
- let cryptoKey;
7624
- if (password.length === 0) {
7625
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7626
- try {
7627
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7628
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7629
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);
7630
- }
7631
- catch {
7632
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
7633
- }
7634
- }
7635
- else {
7636
- // Derive a key using PBKDF2.
7637
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7638
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7639
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);
7640
- }
7641
- // Encrypt the string.
7642
- const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);
7643
- return concat$1([salt, aesGcm.iv, new Uint8Array(ciphertext)]);
7644
- }
7645
- /**
7646
- * Uses the provided password to derive a pbkdf2 key. The key
7647
- * will then be used to decrypt the data. The options used to create
7648
- * this decryption cipher must be the same as those used to create
7649
- * the encryption cipher.
7650
- */
7651
- async function decrypt(data, password) {
7652
- const salt = data.subarray(0, saltLength);
7653
- const nonce = data.subarray(saltLength, saltLength + nonceLength);
7654
- const ciphertext = data.subarray(saltLength + nonceLength);
7655
- const aesGcm = { name: algorithm, iv: nonce };
7656
- if (typeof password === 'string') {
7657
- password = fromString(password);
7658
- }
7659
- let cryptoKey;
7660
- if (password.length === 0) {
7661
- try {
7662
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7663
- const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7664
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);
7665
- }
7666
- catch {
7667
- cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);
7668
- }
7511
+ toMultihash() {
7512
+ return identity.digest(publicKeyToProtobuf(this));
7513
+ }
7514
+ toCID() {
7515
+ return CID.createV1(114, this.toMultihash());
7516
+ }
7517
+ toString() {
7518
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
7519
+ }
7520
+ equals(key) {
7521
+ if (key == null || !(key.raw instanceof Uint8Array)) {
7522
+ return false;
7669
7523
  }
7670
- else {
7671
- // Derive the key using PBKDF2.
7672
- const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
7673
- const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
7674
- cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);
7675
- }
7676
- // Decrypt the string.
7677
- const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);
7678
- return new Uint8Array(plaintext);
7679
- }
7680
- const cipher = {
7681
- encrypt,
7682
- decrypt
7683
- };
7684
- return cipher;
7524
+ return equals(this.raw, key.raw);
7525
+ }
7526
+ verify(data, sig) {
7527
+ return hashAndVerify$2(this.raw, sig, data);
7528
+ }
7685
7529
  }
7686
7530
 
7687
- /**
7688
- * Exports the given PrivateKey as a base64 encoded string.
7689
- * The PrivateKey is encrypted via a password derived PBKDF2 key
7690
- * leveraging the aes-gcm cipher algorithm.
7691
- */
7692
- async function exporter(privateKey, password) {
7693
- const cipher = create();
7694
- const encryptedKey = await cipher.encrypt(privateKey, password);
7695
- return base64.encode(encryptedKey);
7531
+ function unmarshalEd25519PublicKey(bytes) {
7532
+ bytes = ensureEd25519Key(bytes, PUBLIC_KEY_BYTE_LENGTH);
7533
+ return new Ed25519PublicKey(bytes);
7534
+ }
7535
+ function ensureEd25519Key(key, length) {
7536
+ key = Uint8Array.from(key ?? []);
7537
+ if (key.length !== length) {
7538
+ throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);
7539
+ }
7540
+ return key;
7696
7541
  }
7697
7542
 
7698
7543
  const f32 = new Float32Array([-0]);
@@ -8901,13 +8746,13 @@ var KeyType;
8901
8746
  (function (KeyType) {
8902
8747
  KeyType["RSA"] = "RSA";
8903
8748
  KeyType["Ed25519"] = "Ed25519";
8904
- KeyType["Secp256k1"] = "Secp256k1";
8749
+ KeyType["secp256k1"] = "secp256k1";
8905
8750
  })(KeyType || (KeyType = {}));
8906
8751
  var __KeyTypeValues;
8907
8752
  (function (__KeyTypeValues) {
8908
8753
  __KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
8909
8754
  __KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
8910
- __KeyTypeValues[__KeyTypeValues["Secp256k1"] = 2] = "Secp256k1";
8755
+ __KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
8911
8756
  })(__KeyTypeValues || (__KeyTypeValues = {}));
8912
8757
  (function (KeyType) {
8913
8758
  KeyType.codec = () => {
@@ -8934,21 +8779,24 @@ var PublicKey;
8934
8779
  if (opts.lengthDelimited !== false) {
8935
8780
  w.ldelim();
8936
8781
  }
8937
- }, (reader, length) => {
8782
+ }, (reader, length, opts = {}) => {
8938
8783
  const obj = {};
8939
8784
  const end = length == null ? reader.len : reader.pos + length;
8940
8785
  while (reader.pos < end) {
8941
8786
  const tag = reader.uint32();
8942
8787
  switch (tag >>> 3) {
8943
- case 1:
8788
+ case 1: {
8944
8789
  obj.Type = KeyType.codec().decode(reader);
8945
8790
  break;
8946
- case 2:
8791
+ }
8792
+ case 2: {
8947
8793
  obj.Data = reader.bytes();
8948
8794
  break;
8949
- default:
8795
+ }
8796
+ default: {
8950
8797
  reader.skipType(tag & 7);
8951
8798
  break;
8799
+ }
8952
8800
  }
8953
8801
  }
8954
8802
  return obj;
@@ -8959,8 +8807,8 @@ var PublicKey;
8959
8807
  PublicKey.encode = (obj) => {
8960
8808
  return encodeMessage(obj, PublicKey.codec());
8961
8809
  };
8962
- PublicKey.decode = (buf) => {
8963
- return decodeMessage(buf, PublicKey.codec());
8810
+ PublicKey.decode = (buf, opts) => {
8811
+ return decodeMessage(buf, PublicKey.codec(), opts);
8964
8812
  };
8965
8813
  })(PublicKey || (PublicKey = {}));
8966
8814
  var PrivateKey;
@@ -8983,21 +8831,24 @@ var PrivateKey;
8983
8831
  if (opts.lengthDelimited !== false) {
8984
8832
  w.ldelim();
8985
8833
  }
8986
- }, (reader, length) => {
8834
+ }, (reader, length, opts = {}) => {
8987
8835
  const obj = {};
8988
8836
  const end = length == null ? reader.len : reader.pos + length;
8989
8837
  while (reader.pos < end) {
8990
8838
  const tag = reader.uint32();
8991
8839
  switch (tag >>> 3) {
8992
- case 1:
8840
+ case 1: {
8993
8841
  obj.Type = KeyType.codec().decode(reader);
8994
8842
  break;
8995
- case 2:
8843
+ }
8844
+ case 2: {
8996
8845
  obj.Data = reader.bytes();
8997
8846
  break;
8998
- default:
8847
+ }
8848
+ default: {
8999
8849
  reader.skipType(tag & 7);
9000
8850
  break;
8851
+ }
9001
8852
  }
9002
8853
  }
9003
8854
  return obj;
@@ -9008,286 +8859,11 @@ var PrivateKey;
9008
8859
  PrivateKey.encode = (obj) => {
9009
8860
  return encodeMessage(obj, PrivateKey.codec());
9010
8861
  };
9011
- PrivateKey.decode = (buf) => {
9012
- return decodeMessage(buf, PrivateKey.codec());
8862
+ PrivateKey.decode = (buf, opts) => {
8863
+ return decodeMessage(buf, PrivateKey.codec(), opts);
9013
8864
  };
9014
8865
  })(PrivateKey || (PrivateKey = {}));
9015
8866
 
9016
- class Ed25519PublicKey {
9017
- _key;
9018
- constructor(key) {
9019
- this._key = ensureKey(key, PUBLIC_KEY_BYTE_LENGTH);
9020
- }
9021
- verify(data, sig) {
9022
- return hashAndVerify$2(this._key, sig, data);
9023
- }
9024
- marshal() {
9025
- return this._key;
9026
- }
9027
- get bytes() {
9028
- return PublicKey.encode({
9029
- Type: KeyType.Ed25519,
9030
- Data: this.marshal()
9031
- }).subarray();
9032
- }
9033
- equals(key) {
9034
- return equals(this.bytes, key.bytes);
9035
- }
9036
- hash() {
9037
- const p = sha256$1.digest(this.bytes);
9038
- if (isPromise(p)) {
9039
- return p.then(({ bytes }) => bytes);
9040
- }
9041
- return p.bytes;
9042
- }
9043
- }
9044
- class Ed25519PrivateKey {
9045
- _key;
9046
- _publicKey;
9047
- // key - 64 byte Uint8Array containing private key
9048
- // publicKey - 32 byte Uint8Array containing public key
9049
- constructor(key, publicKey) {
9050
- this._key = ensureKey(key, PRIVATE_KEY_BYTE_LENGTH);
9051
- this._publicKey = ensureKey(publicKey, PUBLIC_KEY_BYTE_LENGTH);
9052
- }
9053
- sign(message) {
9054
- return hashAndSign$2(this._key, message);
9055
- }
9056
- get public() {
9057
- return new Ed25519PublicKey(this._publicKey);
9058
- }
9059
- marshal() {
9060
- return this._key;
9061
- }
9062
- get bytes() {
9063
- return PrivateKey.encode({
9064
- Type: KeyType.Ed25519,
9065
- Data: this.marshal()
9066
- }).subarray();
9067
- }
9068
- equals(key) {
9069
- return equals(this.bytes, key.bytes);
9070
- }
9071
- async hash() {
9072
- const p = sha256$1.digest(this.bytes);
9073
- let bytes;
9074
- if (isPromise(p)) {
9075
- ({ bytes } = await p);
9076
- }
9077
- else {
9078
- bytes = p.bytes;
9079
- }
9080
- return bytes;
9081
- }
9082
- /**
9083
- * Gets the ID of the key.
9084
- *
9085
- * The key id is the base58 encoding of the identity multihash containing its public key.
9086
- * The public key is a protobuf encoding containing a type and the DER encoding
9087
- * of the PKCS SubjectPublicKeyInfo.
9088
- *
9089
- * @returns {Promise<string>}
9090
- */
9091
- async id() {
9092
- const encoding = identity.digest(this.public.bytes);
9093
- return base58btc.encode(encoding.bytes).substring(1);
9094
- }
9095
- /**
9096
- * Exports the key into a password protected `format`
9097
- */
9098
- async export(password, format = 'libp2p-key') {
9099
- if (format === 'libp2p-key') {
9100
- return exporter(this.bytes, password);
9101
- }
9102
- else {
9103
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
9104
- }
9105
- }
9106
- }
9107
- function unmarshalEd25519PrivateKey(bytes) {
9108
- // Try the old, redundant public key version
9109
- if (bytes.length > PRIVATE_KEY_BYTE_LENGTH) {
9110
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH + PUBLIC_KEY_BYTE_LENGTH);
9111
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9112
- const publicKeyBytes = bytes.subarray(PRIVATE_KEY_BYTE_LENGTH, bytes.length);
9113
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9114
- }
9115
- bytes = ensureKey(bytes, PRIVATE_KEY_BYTE_LENGTH);
9116
- const privateKeyBytes = bytes.subarray(0, PRIVATE_KEY_BYTE_LENGTH);
9117
- const publicKeyBytes = bytes.subarray(PUBLIC_KEY_BYTE_LENGTH);
9118
- return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
9119
- }
9120
- function unmarshalEd25519PublicKey(bytes) {
9121
- bytes = ensureKey(bytes, PUBLIC_KEY_BYTE_LENGTH);
9122
- return new Ed25519PublicKey(bytes);
9123
- }
9124
- async function generateKeyPair$2() {
9125
- const { privateKey, publicKey } = generateKey$2();
9126
- return new Ed25519PrivateKey(privateKey, publicKey);
9127
- }
9128
- async function generateKeyPairFromSeed(seed) {
9129
- const { privateKey, publicKey } = generateKeyFromSeed(seed);
9130
- return new Ed25519PrivateKey(privateKey, publicKey);
9131
- }
9132
- function ensureKey(key, length) {
9133
- key = Uint8Array.from(key ?? []);
9134
- if (key.length !== length) {
9135
- throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
9136
- }
9137
- return key;
9138
- }
9139
-
9140
- var Ed25519 = /*#__PURE__*/Object.freeze({
9141
- __proto__: null,
9142
- Ed25519PrivateKey: Ed25519PrivateKey,
9143
- Ed25519PublicKey: Ed25519PublicKey,
9144
- generateKeyPair: generateKeyPair$2,
9145
- generateKeyPairFromSeed: generateKeyPairFromSeed,
9146
- unmarshalEd25519PrivateKey: unmarshalEd25519PrivateKey,
9147
- unmarshalEd25519PublicKey: unmarshalEd25519PublicKey
9148
- });
9149
-
9150
- /**
9151
- * Generates a Uint8Array with length `number` populated by random bytes
9152
- */
9153
- function randomBytes(length) {
9154
- if (isNaN(length) || length <= 0) {
9155
- throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
9156
- }
9157
- return randomBytes$1(length);
9158
- }
9159
-
9160
- // HMAC (RFC 2104)
9161
- class HMAC extends Hash {
9162
- constructor(hash$1, _key) {
9163
- super();
9164
- this.finished = false;
9165
- this.destroyed = false;
9166
- hash(hash$1);
9167
- const key = toBytes$1(_key);
9168
- this.iHash = hash$1.create();
9169
- if (typeof this.iHash.update !== 'function')
9170
- throw new Error('Expected instance of class which extends utils.Hash');
9171
- this.blockLen = this.iHash.blockLen;
9172
- this.outputLen = this.iHash.outputLen;
9173
- const blockLen = this.blockLen;
9174
- const pad = new Uint8Array(blockLen);
9175
- // blockLen can be bigger than outputLen
9176
- pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
9177
- for (let i = 0; i < pad.length; i++)
9178
- pad[i] ^= 0x36;
9179
- this.iHash.update(pad);
9180
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
9181
- this.oHash = hash$1.create();
9182
- // Undo internal XOR && apply outer XOR
9183
- for (let i = 0; i < pad.length; i++)
9184
- pad[i] ^= 0x36 ^ 0x5c;
9185
- this.oHash.update(pad);
9186
- pad.fill(0);
9187
- }
9188
- update(buf) {
9189
- exists(this);
9190
- this.iHash.update(buf);
9191
- return this;
9192
- }
9193
- digestInto(out) {
9194
- exists(this);
9195
- bytes(out, this.outputLen);
9196
- this.finished = true;
9197
- this.iHash.digestInto(out);
9198
- this.oHash.update(out);
9199
- this.oHash.digestInto(out);
9200
- this.destroy();
9201
- }
9202
- digest() {
9203
- const out = new Uint8Array(this.oHash.outputLen);
9204
- this.digestInto(out);
9205
- return out;
9206
- }
9207
- _cloneInto(to) {
9208
- // Create new instance without calling constructor since key already in state and we don't know it.
9209
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
9210
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
9211
- to = to;
9212
- to.finished = finished;
9213
- to.destroyed = destroyed;
9214
- to.blockLen = blockLen;
9215
- to.outputLen = outputLen;
9216
- to.oHash = oHash._cloneInto(to.oHash);
9217
- to.iHash = iHash._cloneInto(to.iHash);
9218
- return to;
9219
- }
9220
- destroy() {
9221
- this.destroyed = true;
9222
- this.oHash.destroy();
9223
- this.iHash.destroy();
9224
- }
9225
- }
9226
- /**
9227
- * HMAC: RFC2104 message authentication code.
9228
- * @param hash - function that would be used e.g. sha256
9229
- * @param key - message key
9230
- * @param message - message data
9231
- * @example
9232
- * import { hmac } from '@noble/hashes/hmac';
9233
- * import { sha256 } from '@noble/hashes/sha2';
9234
- * const mac1 = hmac(sha256, 'key', 'message');
9235
- */
9236
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
9237
- hmac.create = (hash, key) => new HMAC(hash, key);
9238
-
9239
- // Common prologue and epilogue for sync/async functions
9240
- function pbkdf2Init(hash$1, _password, _salt, _opts) {
9241
- hash(hash$1);
9242
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
9243
- const { c, dkLen, asyncTick } = opts;
9244
- number(c);
9245
- number(dkLen);
9246
- number(asyncTick);
9247
- if (c < 1)
9248
- throw new Error('PBKDF2: iterations (c) should be >= 1');
9249
- const password = toBytes$1(_password);
9250
- const salt = toBytes$1(_salt);
9251
- // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
9252
- const DK = new Uint8Array(dkLen);
9253
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9254
- const PRF = hmac.create(hash$1, password);
9255
- const PRFSalt = PRF._cloneInto().update(salt);
9256
- return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
9257
- }
9258
- function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
9259
- PRF.destroy();
9260
- PRFSalt.destroy();
9261
- if (prfW)
9262
- prfW.destroy();
9263
- u.fill(0);
9264
- return DK;
9265
- }
9266
- async function pbkdf2Async(hash, password, salt, opts) {
9267
- const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
9268
- let prfW; // Working copy
9269
- const arr = new Uint8Array(4);
9270
- const view = createView(arr);
9271
- const u = new Uint8Array(PRF.outputLen);
9272
- // DK = T1 + T2 + ⋯ + Tdklen/hlen
9273
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
9274
- // Ti = F(Password, Salt, c, i)
9275
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
9276
- view.setInt32(0, ti, false);
9277
- // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
9278
- // U1 = PRF(Password, Salt + INT_32_BE(i))
9279
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
9280
- Ti.set(u.subarray(0, Ti.length));
9281
- await asyncLoop(c - 1, asyncTick, () => {
9282
- // Uc = PRF(Password, Uc−1)
9283
- PRF._cloneInto(prfW).update(u).digestInto(u);
9284
- for (let i = 0; i < Ti.length; i++)
9285
- Ti[i] ^= u[i];
9286
- });
9287
- }
9288
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
9289
- }
9290
-
9291
8867
  /*!
9292
8868
  * MIT License
9293
8869
  *
@@ -12539,76 +12115,125 @@ _a = TIME;
12539
12115
  TIME.NAME = "TIME";
12540
12116
 
12541
12117
  /**
12542
- * Convert a PKCS#1 in ASN1 DER format to a JWK key
12118
+ * Signing a message failed
12543
12119
  */
12544
- function pkcs1ToJwk(bytes) {
12545
- const { result } = fromBER(bytes);
12546
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12547
- // safe to have deeply property chains like this
12548
- const values = result.valueBlock.value;
12549
- const key = {
12550
- n: toString$1(bnToBuf(values[1].toBigInt()), 'base64url'),
12551
- e: toString$1(bnToBuf(values[2].toBigInt()), 'base64url'),
12552
- d: toString$1(bnToBuf(values[3].toBigInt()), 'base64url'),
12553
- p: toString$1(bnToBuf(values[4].toBigInt()), 'base64url'),
12554
- q: toString$1(bnToBuf(values[5].toBigInt()), 'base64url'),
12555
- dp: toString$1(bnToBuf(values[6].toBigInt()), 'base64url'),
12556
- dq: toString$1(bnToBuf(values[7].toBigInt()), 'base64url'),
12557
- qi: toString$1(bnToBuf(values[8].toBigInt()), 'base64url'),
12558
- kty: 'RSA',
12559
- alg: 'RS256'
12560
- };
12561
- return key;
12562
- }
12563
12120
  /**
12564
- * Convert a JWK key into PKCS#1 in ASN1 DER format
12121
+ * Verifying a message signature failed
12565
12122
  */
12566
- function jwkToPkcs1(jwk) {
12567
- 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) {
12568
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12123
+ class VerificationError extends Error {
12124
+ constructor(message = 'An error occurred while verifying a message') {
12125
+ super(message);
12126
+ this.name = 'VerificationError';
12569
12127
  }
12570
- const root = new Sequence({
12571
- value: [
12572
- new Integer({ value: 0 }),
12573
- Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
12574
- Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url'))),
12575
- Integer.fromBigInt(bufToBn(fromString(jwk.d, 'base64url'))),
12576
- Integer.fromBigInt(bufToBn(fromString(jwk.p, 'base64url'))),
12577
- Integer.fromBigInt(bufToBn(fromString(jwk.q, 'base64url'))),
12578
- Integer.fromBigInt(bufToBn(fromString(jwk.dp, 'base64url'))),
12579
- Integer.fromBigInt(bufToBn(fromString(jwk.dq, 'base64url'))),
12580
- Integer.fromBigInt(bufToBn(fromString(jwk.qi, 'base64url')))
12581
- ]
12582
- });
12583
- const der = root.toBER();
12584
- return new Uint8Array(der, 0, der.byteLength);
12585
- }
12586
- /**
12587
- * Convert a PKCIX in ASN1 DER format to a JWK key
12588
- */
12589
- function pkixToJwk(bytes) {
12590
- const { result } = fromBER(bytes);
12591
- // @ts-expect-error this looks fragile but DER is a canonical format so we are
12592
- // safe to have deeply property chains like this
12593
- const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12594
- return {
12595
- kty: 'RSA',
12596
- n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
12597
- e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
12598
- };
12599
12128
  }
12600
12129
  /**
12601
- * Convert a JWK key to PKCIX in ASN1 DER format
12130
+ * WebCrypto was not available in the current context
12602
12131
  */
12603
- function jwkToPkix(jwk) {
12604
- if (jwk.n == null || jwk.e == null) {
12605
- throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');
12132
+ class WebCryptoMissingError extends Error {
12133
+ constructor(message = 'Missing Web Crypto API') {
12134
+ super(message);
12135
+ this.name = 'WebCryptoMissingError';
12606
12136
  }
12607
- const root = new Sequence({
12608
- value: [
12609
- new Sequence({
12610
- value: [
12611
- // rsaEncryption
12137
+ }
12138
+
12139
+ /* eslint-env browser */
12140
+ // Check native crypto exists and is enabled (In insecure context `self.crypto`
12141
+ // exists but `self.crypto.subtle` does not).
12142
+ var webcrypto = {
12143
+ get(win = globalThis) {
12144
+ const nativeCrypto = win.crypto;
12145
+ if (nativeCrypto?.subtle == null) {
12146
+ throw new WebCryptoMissingError('Missing Web Crypto API. ' +
12147
+ 'The most likely cause of this error is that this page is being accessed ' +
12148
+ 'from an insecure context (i.e. not HTTPS). For more information and ' +
12149
+ 'possible resolutions see ' +
12150
+ 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');
12151
+ }
12152
+ return nativeCrypto;
12153
+ }
12154
+ };
12155
+
12156
+ async function hashAndVerify$1(key, sig, msg) {
12157
+ const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
12158
+ name: 'RSASSA-PKCS1-v1_5',
12159
+ hash: { name: 'SHA-256' }
12160
+ }, false, ['verify']);
12161
+ return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
12162
+ }
12163
+ function rsaKeySize(jwk) {
12164
+ if (jwk.kty !== 'RSA') {
12165
+ throw new InvalidParametersError('invalid key type');
12166
+ }
12167
+ else if (jwk.n == null) {
12168
+ throw new InvalidParametersError('invalid key modulus');
12169
+ }
12170
+ const bytes = fromString(jwk.n, 'base64url');
12171
+ return bytes.length * 8;
12172
+ }
12173
+
12174
+ class RSAPublicKey {
12175
+ type = 'RSA';
12176
+ _key;
12177
+ _raw;
12178
+ _multihash;
12179
+ constructor(key, digest) {
12180
+ this._key = key;
12181
+ this._multihash = digest;
12182
+ }
12183
+ get raw() {
12184
+ if (this._raw == null) {
12185
+ this._raw = jwkToPkix(this._key);
12186
+ }
12187
+ return this._raw;
12188
+ }
12189
+ toMultihash() {
12190
+ return this._multihash;
12191
+ }
12192
+ toCID() {
12193
+ return CID.createV1(114, this._multihash);
12194
+ }
12195
+ toString() {
12196
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
12197
+ }
12198
+ equals(key) {
12199
+ if (key == null || !(key.raw instanceof Uint8Array)) {
12200
+ return false;
12201
+ }
12202
+ return equals(this.raw, key.raw);
12203
+ }
12204
+ verify(data, sig) {
12205
+ return hashAndVerify$1(this._key, sig, data);
12206
+ }
12207
+ }
12208
+
12209
+ const MAX_RSA_KEY_SIZE = 8192;
12210
+ const SHA2_256_CODE = 0x12;
12211
+ /**
12212
+ * Convert a PKIX in ASN1 DER format to a JWK key
12213
+ */
12214
+ function pkixToJwk(bytes) {
12215
+ const { result } = fromBER(bytes);
12216
+ // @ts-expect-error this looks fragile but DER is a canonical format so we are
12217
+ // safe to have deeply property chains like this
12218
+ const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
12219
+ return {
12220
+ kty: 'RSA',
12221
+ n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
12222
+ e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
12223
+ };
12224
+ }
12225
+ /**
12226
+ * Convert a JWK key to PKIX in ASN1 DER format
12227
+ */
12228
+ function jwkToPkix(jwk) {
12229
+ if (jwk.n == null || jwk.e == null) {
12230
+ throw new InvalidParametersError('JWK was missing components');
12231
+ }
12232
+ const root = new Sequence({
12233
+ value: [
12234
+ new Sequence({
12235
+ value: [
12236
+ // rsaEncryption
12612
12237
  new ObjectIdentifier({
12613
12238
  value: '1.2.840.113549.1.1.1'
12614
12239
  }),
@@ -12657,328 +12282,100 @@ function bufToBn(u8) {
12657
12282
  });
12658
12283
  return BigInt('0x' + hex.join(''));
12659
12284
  }
12660
- const SALT_LENGTH = 16;
12661
- const KEY_SIZE = 32;
12662
- const ITERATIONS = 10000;
12663
- async function exportToPem(privateKey, password) {
12664
- const crypto = webcrypto.get();
12665
- // PrivateKeyInfo
12666
- const keyWrapper = new Sequence({
12667
- value: [
12668
- // version (0)
12669
- new Integer({ value: 0 }),
12670
- // privateKeyAlgorithm
12671
- new Sequence({
12672
- value: [
12673
- // rsaEncryption OID
12674
- new ObjectIdentifier({
12675
- value: '1.2.840.113549.1.1.1'
12676
- }),
12677
- new Null()
12678
- ]
12679
- }),
12680
- // PrivateKey
12681
- new OctetString({
12682
- valueHex: privateKey.marshal()
12683
- })
12684
- ]
12685
- });
12686
- const keyBuf = keyWrapper.toBER();
12687
- const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);
12688
- const salt = randomBytes(SALT_LENGTH);
12689
- const encryptionKey = await pbkdf2Async(sha512, password, salt, {
12690
- c: ITERATIONS,
12691
- dkLen: KEY_SIZE
12692
- });
12693
- const iv = randomBytes(16);
12694
- const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);
12695
- const encrypted = await crypto.subtle.encrypt({
12696
- name: 'AES-CBC',
12697
- iv
12698
- }, cryptoKey, keyArr);
12699
- const pbkdf2Params = new Sequence({
12700
- value: [
12701
- // salt
12702
- new OctetString({ valueHex: salt }),
12703
- // iteration count
12704
- new Integer({ value: ITERATIONS }),
12705
- // key length
12706
- new Integer({ value: KEY_SIZE }),
12707
- // AlgorithmIdentifier
12708
- new Sequence({
12709
- value: [
12710
- // hmacWithSHA512
12711
- new ObjectIdentifier({ value: '1.2.840.113549.2.11' }),
12712
- new Null()
12713
- ]
12714
- })
12715
- ]
12716
- });
12717
- const encryptionAlgorithm = new Sequence({
12718
- value: [
12719
- // pkcs5PBES2
12720
- new ObjectIdentifier({
12721
- value: '1.2.840.113549.1.5.13'
12722
- }),
12723
- new Sequence({
12724
- value: [
12725
- // keyDerivationFunc
12726
- new Sequence({
12727
- value: [
12728
- // pkcs5PBKDF2
12729
- new ObjectIdentifier({
12730
- value: '1.2.840.113549.1.5.12'
12731
- }),
12732
- // PBKDF2-params
12733
- pbkdf2Params
12734
- ]
12735
- }),
12736
- // encryptionScheme
12737
- new Sequence({
12738
- value: [
12739
- // aes256-CBC
12740
- new ObjectIdentifier({
12741
- value: '2.16.840.1.101.3.4.1.42'
12742
- }),
12743
- // iv
12744
- new OctetString({
12745
- valueHex: iv
12746
- })
12747
- ]
12748
- })
12749
- ]
12750
- })
12751
- ]
12752
- });
12753
- const finalWrapper = new Sequence({
12754
- value: [
12755
- encryptionAlgorithm,
12756
- new OctetString({ valueHex: encrypted })
12757
- ]
12758
- });
12759
- const finalWrapperBuf = finalWrapper.toBER();
12760
- const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);
12761
- return [
12762
- '-----BEGIN ENCRYPTED PRIVATE KEY-----',
12763
- ...toString$1(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),
12764
- '-----END ENCRYPTED PRIVATE KEY-----'
12765
- ].join('\n');
12766
- }
12767
-
12768
- async function generateKey$1(bits) {
12769
- const pair = await webcrypto.get().subtle.generateKey({
12770
- name: 'RSASSA-PKCS1-v1_5',
12771
- modulusLength: bits,
12772
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
12773
- hash: { name: 'SHA-256' }
12774
- }, true, ['sign', 'verify']);
12775
- const keys = await exportKey(pair);
12776
- return {
12777
- privateKey: keys[0],
12778
- publicKey: keys[1]
12779
- };
12780
- }
12781
- // Takes a jwk key
12782
- async function unmarshalPrivateKey$1(key) {
12783
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12784
- name: 'RSASSA-PKCS1-v1_5',
12785
- hash: { name: 'SHA-256' }
12786
- }, true, ['sign']);
12787
- const pair = [
12788
- privateKey,
12789
- await derivePublicFromPrivate(key)
12790
- ];
12791
- const keys = await exportKey({
12792
- privateKey: pair[0],
12793
- publicKey: pair[1]
12794
- });
12795
- return {
12796
- privateKey: keys[0],
12797
- publicKey: keys[1]
12798
- };
12799
- }
12800
- async function hashAndSign$1(key, msg) {
12801
- const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
12802
- name: 'RSASSA-PKCS1-v1_5',
12803
- hash: { name: 'SHA-256' }
12804
- }, false, ['sign']);
12805
- const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
12806
- return new Uint8Array(sig, 0, sig.byteLength);
12807
- }
12808
- async function hashAndVerify$1(key, sig, msg) {
12809
- const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
12810
- name: 'RSASSA-PKCS1-v1_5',
12811
- hash: { name: 'SHA-256' }
12812
- }, false, ['verify']);
12813
- return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
12814
- }
12815
- async function exportKey(pair) {
12816
- if (pair.privateKey == null || pair.publicKey == null) {
12817
- throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
12818
- }
12819
- return Promise.all([
12820
- webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
12821
- webcrypto.get().subtle.exportKey('jwk', pair.publicKey)
12822
- ]);
12823
- }
12824
- async function derivePublicFromPrivate(jwKey) {
12825
- return webcrypto.get().subtle.importKey('jwk', {
12826
- kty: jwKey.kty,
12827
- n: jwKey.n,
12828
- e: jwKey.e
12829
- }, {
12830
- name: 'RSASSA-PKCS1-v1_5',
12831
- hash: { name: 'SHA-256' }
12832
- }, true, ['verify']);
12833
- }
12834
- function keySize(jwk) {
12835
- if (jwk.kty !== 'RSA') {
12836
- throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');
12837
- }
12838
- else if (jwk.n == null) {
12839
- throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');
12285
+ /**
12286
+ * Turn PKIX bytes to a PublicKey
12287
+ */
12288
+ function pkixToRSAPublicKey(bytes) {
12289
+ const jwk = pkixToJwk(bytes);
12290
+ if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {
12291
+ throw new InvalidPublicKeyError('Key size is too large');
12840
12292
  }
12841
- const bytes = fromString(jwk.n, 'base64url');
12842
- return bytes.length * 8;
12293
+ const hash = sha256(PublicKey.encode({
12294
+ Type: KeyType.RSA,
12295
+ Data: bytes
12296
+ }));
12297
+ const digest = create(SHA2_256_CODE, hash);
12298
+ return new RSAPublicKey(jwk, digest);
12843
12299
  }
12844
12300
 
12845
- const MAX_RSA_KEY_SIZE = 8192;
12846
- class RsaPublicKey {
12847
- _key;
12848
- constructor(key) {
12849
- this._key = key;
12850
- }
12851
- verify(data, sig) {
12852
- return hashAndVerify$1(this._key, sig, data);
12853
- }
12854
- marshal() {
12855
- return jwkToPkix(this._key);
12856
- }
12857
- get bytes() {
12858
- return PublicKey.encode({
12859
- Type: KeyType.RSA,
12860
- Data: this.marshal()
12861
- }).subarray();
12862
- }
12863
- equals(key) {
12864
- return equals(this.bytes, key.bytes);
12865
- }
12866
- hash() {
12867
- const p = sha256$1.digest(this.bytes);
12868
- if (isPromise(p)) {
12869
- return p.then(({ bytes }) => bytes);
12870
- }
12871
- return p.bytes;
12872
- }
12873
- }
12874
- class RsaPrivateKey {
12875
- _key;
12876
- _publicKey;
12877
- constructor(key, publicKey) {
12878
- this._key = key;
12879
- this._publicKey = publicKey;
12880
- }
12881
- genSecret() {
12882
- return randomBytes(16);
12883
- }
12884
- sign(message) {
12885
- return hashAndSign$1(this._key, message);
12886
- }
12887
- get public() {
12888
- if (this._publicKey == null) {
12889
- throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
12890
- }
12891
- return new RsaPublicKey(this._publicKey);
12892
- }
12893
- marshal() {
12894
- return jwkToPkcs1(this._key);
12895
- }
12896
- get bytes() {
12897
- return PrivateKey.encode({
12898
- Type: KeyType.RSA,
12899
- Data: this.marshal()
12900
- }).subarray();
12901
- }
12902
- equals(key) {
12903
- return equals(this.bytes, key.bytes);
12904
- }
12905
- hash() {
12906
- const p = sha256$1.digest(this.bytes);
12907
- if (isPromise(p)) {
12908
- return p.then(({ bytes }) => bytes);
12909
- }
12910
- return p.bytes;
12911
- }
12912
- /**
12913
- * Gets the ID of the key.
12914
- *
12915
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
12916
- * The public key is a protobuf encoding containing a type and the DER encoding
12917
- * of the PKCS SubjectPublicKeyInfo.
12918
- */
12919
- async id() {
12920
- const hash = await this.public.hash();
12921
- return toString$1(hash, 'base58btc');
12301
+ // HMAC (RFC 2104)
12302
+ class HMAC extends Hash {
12303
+ constructor(hash$1, _key) {
12304
+ super();
12305
+ this.finished = false;
12306
+ this.destroyed = false;
12307
+ hash(hash$1);
12308
+ const key = toBytes$1(_key);
12309
+ this.iHash = hash$1.create();
12310
+ if (typeof this.iHash.update !== 'function')
12311
+ throw new Error('Expected instance of class which extends utils.Hash');
12312
+ this.blockLen = this.iHash.blockLen;
12313
+ this.outputLen = this.iHash.outputLen;
12314
+ const blockLen = this.blockLen;
12315
+ const pad = new Uint8Array(blockLen);
12316
+ // blockLen can be bigger than outputLen
12317
+ pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
12318
+ for (let i = 0; i < pad.length; i++)
12319
+ pad[i] ^= 0x36;
12320
+ this.iHash.update(pad);
12321
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
12322
+ this.oHash = hash$1.create();
12323
+ // Undo internal XOR && apply outer XOR
12324
+ for (let i = 0; i < pad.length; i++)
12325
+ pad[i] ^= 0x36 ^ 0x5c;
12326
+ this.oHash.update(pad);
12327
+ pad.fill(0);
12922
12328
  }
12923
- /**
12924
- * Exports the key as libp2p-key - a aes-gcm encrypted value with the key
12925
- * derived from the password.
12926
- *
12927
- * To export it as a password protected PEM file, please use the `exportPEM`
12928
- * function from `@libp2p/rsa`.
12929
- */
12930
- async export(password, format = 'pkcs-8') {
12931
- if (format === 'pkcs-8') {
12932
- return exportToPem(this, password);
12933
- }
12934
- else if (format === 'libp2p-key') {
12935
- return exporter(this.bytes, password);
12936
- }
12937
- else {
12938
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
12939
- }
12329
+ update(buf) {
12330
+ exists(this);
12331
+ this.iHash.update(buf);
12332
+ return this;
12940
12333
  }
12941
- }
12942
- async function unmarshalRsaPrivateKey(bytes) {
12943
- const jwk = pkcs1ToJwk(bytes);
12944
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12945
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12334
+ digestInto(out) {
12335
+ exists(this);
12336
+ bytes(out, this.outputLen);
12337
+ this.finished = true;
12338
+ this.iHash.digestInto(out);
12339
+ this.oHash.update(out);
12340
+ this.oHash.digestInto(out);
12341
+ this.destroy();
12946
12342
  }
12947
- const keys = await unmarshalPrivateKey$1(jwk);
12948
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12949
- }
12950
- function unmarshalRsaPublicKey(bytes) {
12951
- const jwk = pkixToJwk(bytes);
12952
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12953
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12343
+ digest() {
12344
+ const out = new Uint8Array(this.oHash.outputLen);
12345
+ this.digestInto(out);
12346
+ return out;
12954
12347
  }
12955
- return new RsaPublicKey(jwk);
12956
- }
12957
- async function fromJwk(jwk) {
12958
- if (keySize(jwk) > MAX_RSA_KEY_SIZE) {
12959
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12348
+ _cloneInto(to) {
12349
+ // Create new instance without calling constructor since key already in state and we don't know it.
12350
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
12351
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
12352
+ to = to;
12353
+ to.finished = finished;
12354
+ to.destroyed = destroyed;
12355
+ to.blockLen = blockLen;
12356
+ to.outputLen = outputLen;
12357
+ to.oHash = oHash._cloneInto(to.oHash);
12358
+ to.iHash = iHash._cloneInto(to.iHash);
12359
+ return to;
12960
12360
  }
12961
- const keys = await unmarshalPrivateKey$1(jwk);
12962
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12963
- }
12964
- async function generateKeyPair$1(bits) {
12965
- if (bits > MAX_RSA_KEY_SIZE) {
12966
- throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');
12361
+ destroy() {
12362
+ this.destroyed = true;
12363
+ this.oHash.destroy();
12364
+ this.iHash.destroy();
12967
12365
  }
12968
- const keys = await generateKey$1(bits);
12969
- return new RsaPrivateKey(keys.privateKey, keys.publicKey);
12970
12366
  }
12971
-
12972
- var RSA = /*#__PURE__*/Object.freeze({
12973
- __proto__: null,
12974
- MAX_RSA_KEY_SIZE: MAX_RSA_KEY_SIZE,
12975
- RsaPrivateKey: RsaPrivateKey,
12976
- RsaPublicKey: RsaPublicKey,
12977
- fromJwk: fromJwk,
12978
- generateKeyPair: generateKeyPair$1,
12979
- unmarshalRsaPrivateKey: unmarshalRsaPrivateKey,
12980
- unmarshalRsaPublicKey: unmarshalRsaPublicKey
12981
- });
12367
+ /**
12368
+ * HMAC: RFC2104 message authentication code.
12369
+ * @param hash - function that would be used e.g. sha256
12370
+ * @param key - message key
12371
+ * @param message - message data
12372
+ * @example
12373
+ * import { hmac } from '@noble/hashes/hmac';
12374
+ * import { sha256 } from '@noble/hashes/sha2';
12375
+ * const mac1 = hmac(sha256, 'key', 'message');
12376
+ */
12377
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
12378
+ hmac.create = (hash, key) => new HMAC(hash, key);
12982
12379
 
12983
12380
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12984
12381
  // Short Weierstrass curve. The formula is: y² = x³ + ax + b
@@ -13998,7 +13395,7 @@ function getHash(hash) {
13998
13395
  return {
13999
13396
  hash,
14000
13397
  hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
14001
- randomBytes: randomBytes$1,
13398
+ randomBytes,
14002
13399
  };
14003
13400
  }
14004
13401
  function createCurve(curveDef, defHash) {
@@ -14091,27 +13488,15 @@ const secp256k1 = createCurve({
14091
13488
  BigInt(0);
14092
13489
  secp256k1.ProjectivePoint;
14093
13490
 
14094
- function generateKey() {
14095
- return secp256k1.utils.randomPrivateKey();
14096
- }
14097
- /**
14098
- * Hash and sign message with private key
14099
- */
14100
- function hashAndSign(key, msg) {
14101
- const p = sha256$1.digest(msg instanceof Uint8Array ? msg : msg.subarray());
14102
- if (isPromise(p)) {
14103
- return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
14104
- .catch(err => {
14105
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14106
- });
14107
- }
14108
- try {
14109
- return secp256k1.sign(p.digest, key).toDERRawBytes();
14110
- }
14111
- catch (err) {
14112
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13491
+ function isPromise(thing) {
13492
+ if (thing == null) {
13493
+ return false;
14113
13494
  }
13495
+ return typeof thing.then === 'function' &&
13496
+ typeof thing.catch === 'function' &&
13497
+ typeof thing.finally === 'function';
14114
13498
  }
13499
+
14115
13500
  /**
14116
13501
  * Hash message and verify signature with public key
14117
13502
  */
@@ -14120,207 +13505,114 @@ function hashAndVerify(key, sig, msg) {
14120
13505
  if (isPromise(p)) {
14121
13506
  return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
14122
13507
  .catch(err => {
14123
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
13508
+ throw new VerificationError(String(err));
14124
13509
  });
14125
13510
  }
14126
13511
  try {
14127
13512
  return secp256k1.verify(sig, p.digest, key);
14128
13513
  }
14129
13514
  catch (err) {
14130
- throw new CodeError(String(err), 'ERR_INVALID_INPUT');
14131
- }
14132
- }
14133
- function compressPublicKey(key) {
14134
- const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
14135
- return point;
14136
- }
14137
- function validatePrivateKey(key) {
14138
- try {
14139
- secp256k1.getPublicKey(key, true);
14140
- }
14141
- catch (err) {
14142
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
14143
- }
14144
- }
14145
- function validatePublicKey(key) {
14146
- try {
14147
- secp256k1.ProjectivePoint.fromHex(key);
14148
- }
14149
- catch (err) {
14150
- throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
14151
- }
14152
- }
14153
- function computePublicKey(privateKey) {
14154
- try {
14155
- return secp256k1.getPublicKey(privateKey, true);
14156
- }
14157
- catch (err) {
14158
- throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
13515
+ throw new VerificationError(String(err));
14159
13516
  }
14160
13517
  }
14161
13518
 
14162
13519
  class Secp256k1PublicKey {
13520
+ type = 'secp256k1';
13521
+ raw;
14163
13522
  _key;
14164
13523
  constructor(key) {
14165
- validatePublicKey(key);
14166
- this._key = key;
13524
+ this._key = validateSecp256k1PublicKey(key);
13525
+ this.raw = compressSecp256k1PublicKey(this._key);
14167
13526
  }
14168
- verify(data, sig) {
14169
- return hashAndVerify(this._key, sig, data);
14170
- }
14171
- marshal() {
14172
- return compressPublicKey(this._key);
14173
- }
14174
- get bytes() {
14175
- return PublicKey.encode({
14176
- Type: KeyType.Secp256k1,
14177
- Data: this.marshal()
14178
- }).subarray();
14179
- }
14180
- equals(key) {
14181
- return equals(this.bytes, key.bytes);
14182
- }
14183
- async hash() {
14184
- const p = sha256$1.digest(this.bytes);
14185
- let bytes;
14186
- if (isPromise(p)) {
14187
- ({ bytes } = await p);
14188
- }
14189
- else {
14190
- bytes = p.bytes;
14191
- }
14192
- return bytes;
13527
+ toMultihash() {
13528
+ return identity.digest(publicKeyToProtobuf(this));
14193
13529
  }
14194
- }
14195
- class Secp256k1PrivateKey {
14196
- _key;
14197
- _publicKey;
14198
- constructor(key, publicKey) {
14199
- this._key = key;
14200
- this._publicKey = publicKey ?? computePublicKey(key);
14201
- validatePrivateKey(this._key);
14202
- validatePublicKey(this._publicKey);
14203
- }
14204
- sign(message) {
14205
- return hashAndSign(this._key, message);
14206
- }
14207
- get public() {
14208
- return new Secp256k1PublicKey(this._publicKey);
14209
- }
14210
- marshal() {
14211
- return this._key;
13530
+ toCID() {
13531
+ return CID.createV1(114, this.toMultihash());
14212
13532
  }
14213
- get bytes() {
14214
- return PrivateKey.encode({
14215
- Type: KeyType.Secp256k1,
14216
- Data: this.marshal()
14217
- }).subarray();
13533
+ toString() {
13534
+ return base58btc.encode(this.toMultihash().bytes).substring(1);
14218
13535
  }
14219
13536
  equals(key) {
14220
- return equals(this.bytes, key.bytes);
14221
- }
14222
- hash() {
14223
- const p = sha256$1.digest(this.bytes);
14224
- if (isPromise(p)) {
14225
- return p.then(({ bytes }) => bytes);
13537
+ if (key == null || !(key.raw instanceof Uint8Array)) {
13538
+ return false;
14226
13539
  }
14227
- return p.bytes;
13540
+ return equals(this.raw, key.raw);
14228
13541
  }
14229
- /**
14230
- * Gets the ID of the key.
14231
- *
14232
- * The key id is the base58 encoding of the SHA-256 multihash of its public key.
14233
- * The public key is a protobuf encoding containing a type and the DER encoding
14234
- * of the PKCS SubjectPublicKeyInfo.
14235
- */
14236
- async id() {
14237
- const hash = await this.public.hash();
14238
- return toString$1(hash, 'base58btc');
14239
- }
14240
- /**
14241
- * Exports the key into a password protected `format`
14242
- */
14243
- async export(password, format = 'libp2p-key') {
14244
- if (format === 'libp2p-key') {
14245
- return exporter(this.bytes, password);
14246
- }
14247
- else {
14248
- throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
14249
- }
13542
+ verify(data, sig) {
13543
+ return hashAndVerify(this._key, sig, data);
14250
13544
  }
14251
13545
  }
14252
- function unmarshalSecp256k1PrivateKey(bytes) {
14253
- return new Secp256k1PrivateKey(bytes);
14254
- }
13546
+
14255
13547
  function unmarshalSecp256k1PublicKey(bytes) {
14256
13548
  return new Secp256k1PublicKey(bytes);
14257
13549
  }
14258
- async function generateKeyPair() {
14259
- const privateKeyBytes = generateKey();
14260
- return new Secp256k1PrivateKey(privateKeyBytes);
13550
+ function compressSecp256k1PublicKey(key) {
13551
+ const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
13552
+ return point;
13553
+ }
13554
+ function validateSecp256k1PublicKey(key) {
13555
+ try {
13556
+ secp256k1.ProjectivePoint.fromHex(key);
13557
+ return key;
13558
+ }
13559
+ catch (err) {
13560
+ throw new InvalidPublicKeyError(String(err));
13561
+ }
14261
13562
  }
14262
-
14263
- var Secp256k1 = /*#__PURE__*/Object.freeze({
14264
- __proto__: null,
14265
- Secp256k1PrivateKey: Secp256k1PrivateKey,
14266
- Secp256k1PublicKey: Secp256k1PublicKey,
14267
- generateKeyPair: generateKeyPair,
14268
- unmarshalSecp256k1PrivateKey: unmarshalSecp256k1PrivateKey,
14269
- unmarshalSecp256k1PublicKey: unmarshalSecp256k1PublicKey
14270
- });
14271
13563
 
14272
13564
  /**
14273
13565
  * @packageDocumentation
14274
13566
  *
14275
- * **Supported Key Types**
14276
- *
14277
- * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.
13567
+ * ## Supported Key Types
14278
13568
  *
14279
13569
  * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
14280
13570
  *
14281
13571
  * For encryption / decryption support, RSA keys should be used.
14282
13572
  */
14283
- const supportedKeys = {
14284
- rsa: RSA,
14285
- ed25519: Ed25519,
14286
- secp256k1: Secp256k1
14287
- };
14288
- function unsupportedKey(type) {
14289
- const supported = Object.keys(supportedKeys).join(' / ');
14290
- return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
14291
- }
14292
13573
  /**
14293
- * Converts a protobuf serialized public key into its representative object
13574
+ * Creates a public key from the raw key bytes
14294
13575
  */
14295
- function unmarshalPublicKey(buf) {
14296
- const decoded = PublicKey.decode(buf);
14297
- const data = decoded.Data ?? new Uint8Array();
14298
- switch (decoded.Type) {
14299
- case KeyType.RSA:
14300
- return supportedKeys.rsa.unmarshalRsaPublicKey(data);
14301
- case KeyType.Ed25519:
14302
- return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);
14303
- case KeyType.Secp256k1:
14304
- return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);
14305
- default:
14306
- throw unsupportedKey(decoded.Type ?? 'unknown');
13576
+ function publicKeyFromRaw(buf) {
13577
+ if (buf.byteLength === 32) {
13578
+ return unmarshalEd25519PublicKey(buf);
13579
+ }
13580
+ else if (buf.byteLength === 33) {
13581
+ return unmarshalSecp256k1PublicKey(buf);
13582
+ }
13583
+ else {
13584
+ return pkixToRSAPublicKey(buf);
14307
13585
  }
14308
13586
  }
14309
13587
  /**
14310
- * Converts a protobuf serialized private key into its representative object
13588
+ * Converts a public key object into a protobuf serialized public key
14311
13589
  */
14312
- async function unmarshalPrivateKey(buf) {
14313
- const decoded = PrivateKey.decode(buf);
14314
- const data = decoded.Data ?? new Uint8Array();
14315
- switch (decoded.Type) {
14316
- case KeyType.RSA:
14317
- return supportedKeys.rsa.unmarshalRsaPrivateKey(data);
14318
- case KeyType.Ed25519:
14319
- return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);
14320
- case KeyType.Secp256k1:
14321
- return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);
14322
- default:
14323
- throw unsupportedKey(decoded.Type ?? 'RSA');
13590
+ function publicKeyToProtobuf(key) {
13591
+ return PublicKey.encode({
13592
+ Type: KeyType[key.type],
13593
+ Data: key.raw
13594
+ });
13595
+ }
13596
+
13597
+ /**
13598
+ * All PeerId implementations must use this symbol as the name of a property
13599
+ * with a boolean `true` value
13600
+ */
13601
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
13602
+
13603
+ /**
13604
+ * When this error is thrown it means an operation was aborted,
13605
+ * usually in response to the `abort` event being emitted by an
13606
+ * AbortSignal.
13607
+ */
13608
+ /**
13609
+ * Thrown when and attempt to operate on an unsupported key was made
13610
+ */
13611
+ class UnsupportedKeyTypeError extends Error {
13612
+ static name = 'UnsupportedKeyTypeError';
13613
+ constructor(message = 'Unsupported key type') {
13614
+ super(message);
13615
+ this.name = 'UnsupportedKeyTypeError';
14324
13616
  }
14325
13617
  }
14326
13618
 
@@ -14340,25 +13632,16 @@ async function unmarshalPrivateKey(buf) {
14340
13632
  * ```
14341
13633
  */
14342
13634
  const inspect = Symbol.for('nodejs.util.inspect.custom');
14343
- const baseDecoder = Object
14344
- .values(bases)
14345
- .map(codec => codec.decoder)
14346
- // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
14347
- .reduce((acc, curr) => acc.or(curr), bases.identity.decoder);
14348
13635
  // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14349
13636
  const LIBP2P_KEY_CODE = 0x72;
14350
- const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;
14351
- const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;
14352
13637
  class PeerIdImpl {
14353
13638
  type;
14354
13639
  multihash;
14355
- privateKey;
14356
13640
  publicKey;
14357
13641
  string;
14358
13642
  constructor(init) {
14359
13643
  this.type = init.type;
14360
13644
  this.multihash = init.multihash;
14361
- this.privateKey = init.privateKey;
14362
13645
  // mark string cache as non-enumerable
14363
13646
  Object.defineProperty(this, 'string', {
14364
13647
  enumerable: false,
@@ -14375,17 +13658,14 @@ class PeerIdImpl {
14375
13658
  }
14376
13659
  return this.string;
14377
13660
  }
13661
+ toMultihash() {
13662
+ return this.multihash;
13663
+ }
14378
13664
  // return self-describing String representation
14379
13665
  // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
14380
13666
  toCID() {
14381
13667
  return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
14382
13668
  }
14383
- toBytes() {
14384
- return this.multihash.bytes;
14385
- }
14386
- /**
14387
- * Returns Multiaddr as a JSON string
14388
- */
14389
13669
  toJSON() {
14390
13670
  return this.toString();
14391
13671
  }
@@ -14400,10 +13680,10 @@ class PeerIdImpl {
14400
13680
  return equals(this.multihash.bytes, id);
14401
13681
  }
14402
13682
  else if (typeof id === 'string') {
14403
- return peerIdFromString(id).equals(this);
13683
+ return this.toString() === id;
14404
13684
  }
14405
- else if (id?.multihash?.bytes != null) {
14406
- return equals(this.multihash.bytes, id.multihash.bytes);
13685
+ else if (id?.toMultihash()?.bytes != null) {
13686
+ return equals(this.multihash.bytes, id.toMultihash().bytes);
14407
13687
  }
14408
13688
  else {
14409
13689
  throw new Error('not valid Id');
@@ -14425,7 +13705,7 @@ class PeerIdImpl {
14425
13705
  return `PeerId(${this.toString()})`;
14426
13706
  }
14427
13707
  }
14428
- class RSAPeerIdImpl extends PeerIdImpl {
13708
+ class RSAPeerId extends PeerIdImpl {
14429
13709
  type = 'RSA';
14430
13710
  publicKey;
14431
13711
  constructor(init) {
@@ -14433,153 +13713,67 @@ class RSAPeerIdImpl extends PeerIdImpl {
14433
13713
  this.publicKey = init.publicKey;
14434
13714
  }
14435
13715
  }
14436
- class Ed25519PeerIdImpl extends PeerIdImpl {
13716
+ class Ed25519PeerId extends PeerIdImpl {
14437
13717
  type = 'Ed25519';
14438
13718
  publicKey;
14439
13719
  constructor(init) {
14440
13720
  super({ ...init, type: 'Ed25519' });
14441
- this.publicKey = init.multihash.digest;
13721
+ this.publicKey = init.publicKey;
14442
13722
  }
14443
13723
  }
14444
- class Secp256k1PeerIdImpl extends PeerIdImpl {
13724
+ class Secp256k1PeerId extends PeerIdImpl {
14445
13725
  type = 'secp256k1';
14446
13726
  publicKey;
14447
13727
  constructor(init) {
14448
13728
  super({ ...init, type: 'secp256k1' });
14449
- this.publicKey = init.multihash.digest;
14450
- }
14451
- }
14452
- // these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
14453
- const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
14454
- class URLPeerIdImpl {
14455
- type = 'url';
14456
- multihash;
14457
- privateKey;
14458
- publicKey;
14459
- url;
14460
- constructor(url) {
14461
- this.url = url.toString();
14462
- this.multihash = identity.digest(fromString(this.url));
14463
- }
14464
- [inspect]() {
14465
- return `PeerId(${this.url})`;
14466
- }
14467
- [peerIdSymbol] = true;
14468
- toString() {
14469
- return this.toCID().toString();
14470
- }
14471
- toCID() {
14472
- return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
14473
- }
14474
- toBytes() {
14475
- return this.toCID().bytes;
14476
- }
14477
- equals(other) {
14478
- if (other == null) {
14479
- return false;
14480
- }
14481
- if (other instanceof Uint8Array) {
14482
- other = toString$1(other);
14483
- }
14484
- return other.toString() === this.toString();
14485
- }
14486
- }
14487
- function peerIdFromString(str, decoder) {
14488
- if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
14489
- // identity hash ed25519/secp256k1 key or sha2-256 hash of
14490
- // rsa public key - base58btc encoded either way
14491
- const multihash = decode$2(base58btc.decode(`z${str}`));
14492
- if (str.startsWith('12D')) {
14493
- return new Ed25519PeerIdImpl({ multihash });
14494
- }
14495
- else if (str.startsWith('16U')) {
14496
- return new Secp256k1PeerIdImpl({ multihash });
14497
- }
14498
- else {
14499
- return new RSAPeerIdImpl({ multihash });
14500
- }
14501
- }
14502
- return peerIdFromBytes(baseDecoder.decode(str));
14503
- }
14504
- function peerIdFromBytes(buf) {
14505
- try {
14506
- const multihash = decode$2(buf);
14507
- if (multihash.code === identity.code) {
14508
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14509
- return new Ed25519PeerIdImpl({ multihash });
14510
- }
14511
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14512
- return new Secp256k1PeerIdImpl({ multihash });
14513
- }
14514
- }
14515
- if (multihash.code === sha256$1.code) {
14516
- return new RSAPeerIdImpl({ multihash });
14517
- }
14518
- }
14519
- catch {
14520
- return peerIdFromCID(CID.decode(buf));
14521
- }
14522
- throw new Error('Supplied PeerID CID is invalid');
14523
- }
14524
- function peerIdFromCID(cid) {
14525
- if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
14526
- throw new Error('Supplied PeerID CID is invalid');
14527
- }
14528
- if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
14529
- const url = toString$1(cid.multihash.digest);
14530
- return new URLPeerIdImpl(new URL(url));
14531
- }
14532
- const multihash = cid.multihash;
14533
- if (multihash.code === sha256$1.code) {
14534
- return new RSAPeerIdImpl({ multihash: cid.multihash });
14535
- }
14536
- else if (multihash.code === identity.code) {
14537
- if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14538
- return new Ed25519PeerIdImpl({ multihash: cid.multihash });
14539
- }
14540
- else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14541
- return new Secp256k1PeerIdImpl({ multihash: cid.multihash });
14542
- }
13729
+ this.publicKey = init.publicKey;
14543
13730
  }
14544
- throw new Error('Supplied PeerID CID is invalid');
14545
13731
  }
13732
+
14546
13733
  /**
14547
- * @param publicKey - A marshalled public key
14548
- * @param privateKey - A marshalled private key
13734
+ * @packageDocumentation
13735
+ *
13736
+ * An implementation of a peer id
13737
+ *
13738
+ * @example
13739
+ *
13740
+ * ```TypeScript
13741
+ * import { peerIdFromString } from '@libp2p/peer-id'
13742
+ * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
13743
+ *
13744
+ * console.log(peer.toCID()) // CID(bafzaa...)
13745
+ * console.log(peer.toString()) // "12D3K..."
13746
+ * ```
14549
13747
  */
14550
- async function peerIdFromKeys(publicKey, privateKey) {
14551
- if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
14552
- return new Ed25519PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13748
+ function peerIdFromPublicKey(publicKey) {
13749
+ if (publicKey.type === 'Ed25519') {
13750
+ return new Ed25519PeerId({
13751
+ multihash: publicKey.toCID().multihash,
13752
+ publicKey
13753
+ });
14553
13754
  }
14554
- if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
14555
- return new Secp256k1PeerIdImpl({ multihash: create$1(identity.code, publicKey), privateKey });
13755
+ else if (publicKey.type === 'secp256k1') {
13756
+ return new Secp256k1PeerId({
13757
+ multihash: publicKey.toCID().multihash,
13758
+ publicKey
13759
+ });
14556
13760
  }
14557
- return new RSAPeerIdImpl({ multihash: await sha256$1.digest(publicKey), publicKey, privateKey });
13761
+ else if (publicKey.type === 'RSA') {
13762
+ return new RSAPeerId({
13763
+ multihash: publicKey.toCID().multihash,
13764
+ publicKey
13765
+ });
13766
+ }
13767
+ throw new UnsupportedKeyTypeError();
14558
13768
  }
14559
13769
 
13770
+ const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
14560
13771
  function createPeerIdFromPublicKey(publicKey) {
14561
- const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
14562
- return peerIdFromKeys(_publicKey.bytes, undefined);
14563
- }
14564
- function getPublicKeyFromPeerId(peerId) {
14565
- if (peerId.type !== "secp256k1") {
14566
- throw new Error("Unsupported peer id type");
14567
- }
14568
- if (!peerId.publicKey) {
14569
- throw new Error("Public key not present on peer id");
14570
- }
14571
- return unmarshalPublicKey(peerId.publicKey).marshal();
14572
- }
14573
- // Only used in tests
14574
- async function getPrivateKeyFromPeerId(peerId) {
14575
- if (peerId.type !== "secp256k1") {
14576
- throw new Error("Unsupported peer id type");
14577
- }
14578
- if (!peerId.privateKey) {
14579
- throw new Error("Private key not present on peer id");
13772
+ const pubKey = publicKeyFromRaw(publicKey);
13773
+ if (pubKey.type !== "secp256k1") {
13774
+ throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
14580
13775
  }
14581
- const privateKey = await unmarshalPrivateKey(peerId.privateKey);
14582
- return privateKey.marshal();
13776
+ return peerIdFromPublicKey(pubKey);
14583
13777
  }
14584
13778
 
14585
13779
  function decodeMultiaddrs(bytes) {
@@ -14826,12 +14020,12 @@ var TransportProtocolPerIpVersion;
14826
14020
  class ENR extends RawEnr {
14827
14021
  static RECORD_PREFIX = "enr:";
14828
14022
  peerId;
14829
- static async create(kvs = {}, seq = BigInt(1), signature) {
14023
+ static create(kvs = {}, seq = BigInt(1), signature) {
14830
14024
  const enr = new ENR(kvs, seq, signature);
14831
14025
  try {
14832
14026
  const publicKey = enr.publicKey;
14833
14027
  if (publicKey) {
14834
- enr.peerId = await createPeerIdFromPublicKey(publicKey);
14028
+ enr.peerId = createPeerIdFromPublicKey(publicKey);
14835
14029
  }
14836
14030
  }
14837
14031
  catch (e) {
@@ -14953,7 +14147,7 @@ class EnrCreator {
14953
14147
  static fromPublicKey(publicKey, kvs = {}) {
14954
14148
  // EIP-778 specifies that the key must be in compressed format, 33 bytes
14955
14149
  if (publicKey.length !== 33) {
14956
- publicKey = compressPublicKey$1(publicKey);
14150
+ publicKey = compressPublicKey(publicKey);
14957
14151
  }
14958
14152
  return ENR.create({
14959
14153
  ...kvs,
@@ -14964,7 +14158,7 @@ class EnrCreator {
14964
14158
  static async fromPeerId(peerId, kvs = {}) {
14965
14159
  switch (peerId.type) {
14966
14160
  case "secp256k1":
14967
- return EnrCreator.fromPublicKey(getPublicKeyFromPeerId(peerId), kvs);
14161
+ return EnrCreator.fromPublicKey(peerId.publicKey.raw, kvs);
14968
14162
  default:
14969
14163
  throw new Error();
14970
14164
  }
@@ -15618,7 +14812,7 @@ async function fromValues(values) {
15618
14812
  }
15619
14813
  }
15620
14814
  const _seq = decodeSeq(seq);
15621
- const enr = await ENR.create(obj, _seq, signature);
14815
+ const enr = ENR.create(obj, _seq, signature);
15622
14816
  checkSignature(seq, kvs, enr, signature);
15623
14817
  return enr;
15624
14818
  }
@@ -15651,4 +14845,4 @@ function checkSignature(seq, kvs, enr, signature) {
15651
14845
  }
15652
14846
  }
15653
14847
 
15654
- export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey$1 as compressPublicKey, createPeerIdFromPublicKey, decodeWaku2, encodeWaku2, getPrivateKeyFromPeerId, getPublicKeyFromPeerId, keccak256, sign$1 as sign, verifySignature };
14848
+ export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, ERR_TYPE_NOT_IMPLEMENTED, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey, createPeerIdFromPublicKey, decodeWaku2, encodeWaku2, keccak256, sign$1 as sign, verifySignature };