From dd09e00dc45f20b534ab3518ecd8b9802fb4a2b0 Mon Sep 17 00:00:00 2001 From: Marcin Rataj Date: Fri, 25 Oct 2019 23:39:26 +0200 Subject: [PATCH] feat: support Peer ID represented as CID This change adds support for Peer ID represented as CID. Implements `Stage 1` from https://github.com/libp2p/specs/issues/216 License: MIT Signed-off-by: Marcin Rataj --- package.json | 5 +++-- src/index.js | 5 +++-- test/index.spec.js | 5 +++++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index accda8de..c1f13f22 100644 --- a/package.json +++ b/package.json @@ -31,11 +31,12 @@ "homepage": "https://github.com/multiformats/js-multiaddr", "dependencies": { "bs58": "^4.0.1", + "cids": "~0.7.1", "class-is": "^1.1.0", + "hi-base32": "~0.5.0", "ip": "^1.1.5", "is-ip": "^3.1.0", - "varint": "^5.0.0", - "hi-base32": "~0.5.0" + "varint": "^5.0.0" }, "devDependencies": { "aegir": "^20.0.0", diff --git a/src/index.js b/src/index.js index edfc8065..d72db826 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,7 @@ const codec = require('./codec') const protocols = require('./protocols-table') const varint = require('varint') const bs58 = require('bs58') +const CID = require('cids') const withIs = require('class-is') /** @@ -287,8 +288,8 @@ Multiaddr.prototype.getPeerId = function getPeerId () { // Get the last id b58str = tuples.pop()[1] - - bs58.decode(b58str) + // Get multihash, unwrap from CID if needed + b58str = bs58.encode(new CID(b58str).multihash) } catch (e) { b58str = null } diff --git a/test/index.spec.js b/test/index.spec.js index d6e4f0fb..32b18a9e 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -776,6 +776,11 @@ describe('helpers', () => { multiaddr('/p2p-circuit/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC').getPeerId() ).to.equal('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC') }) + it('parses extracts the peer Id from a multiaddr, p2p and CIDv1 Base32', () => { + expect( + multiaddr('/p2p-circuit/p2p/bafzbeigweq4zr4x4ky2dvv7nanbkw6egutvrrvzw6g3h2rftp7gidyhtt4').getPeerId() + ).to.equal('QmckZzdVd72h9QUFuJJpQqhsZqGLwjhh81qSvZ9BhB2FQi') + }) }) describe('.getPeerId should return null on missing peer id in multiaddr', () => {