diff --git a/packages/peer-id/src/index.ts b/packages/peer-id/src/index.ts index b098c9a696..15c22a1dad 100644 --- a/packages/peer-id/src/index.ts +++ b/packages/peer-id/src/index.ts @@ -17,7 +17,7 @@ import { publicKeyFromMultihash } from '@libp2p/crypto/keys' import { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface' import { base58btc } from 'multiformats/bases/base58' -import { type CID, type MultibaseDecoder } from 'multiformats/cid' +import { CID, type MultibaseDecoder } from 'multiformats/cid' import * as Digest from 'multiformats/hashes/digest' import { identity } from 'multiformats/hashes/identity' import { sha256 } from 'multiformats/hashes/sha2' @@ -37,6 +37,9 @@ export function peerIdFromString (str: string, decoder?: MultibaseDecoder): // identity hash ed25519/secp256k1 key or sha2-256 hash of // rsa public key - base58btc encoded either way multihash = Digest.decode(base58btc.decode(`z${str}`)) + } else if (str.startsWith('k51qzi5uqu5') || str.startsWith('kzwfwjn5ji4') || str.startsWith('k2k4r8') || str.startsWith('bafz')) { + // base36 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) or base32 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) + return peerIdFromCID(CID.parse(str)) } else { if (decoder == null) { throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with "1" or "Q"') diff --git a/packages/peer-id/test/index.spec.ts b/packages/peer-id/test/index.spec.ts index b94506fbfd..343363aba9 100644 --- a/packages/peer-id/test/index.spec.ts +++ b/packages/peer-id/test/index.spec.ts @@ -1,6 +1,8 @@ /* eslint-env mocha */ import { generateKeyPair } from '@libp2p/crypto/keys' import { expect } from 'aegir/chai' +import { base32 } from 'multiformats/bases/base32' +import { base36 } from 'multiformats/bases/base36' import { base58btc } from 'multiformats/bases/base58' import { CID } from 'multiformats/cid' import { identity } from 'multiformats/hashes/identity' @@ -56,6 +58,20 @@ describe('PeerId', () => { expect(id.toCID().toString()).to.equal(peerId.toCID().toString()) }) + it('should return the correct peer id from cid encoded peer id in base36', async () => { + const id = peerIdFromString(peerId.toCID().toString(base36)) + expect(id.type).to.equal(type) + expect(id.toString()).to.equal(peerId.toString()) + expect(id.toCID().toString()).to.equal(peerId.toCID().toString()) + }) + + it('should return the correct peer id from cid encoded peer id in base32', async () => { + const id = peerIdFromString(peerId.toCID().toString(base32)) + expect(id.type).to.equal(type) + expect(id.toString()).to.equal(peerId.toString()) + expect(id.toCID().toString()).to.equal(peerId.toCID().toString()) + }) + it('should default to base58btc when stringifying', async () => { expect(base58btc.decode(`z${peerId.toString()}`)).to.be.ok() })