From 72831c187e9d88fa287be11879e1d42325b22bff Mon Sep 17 00:00:00 2001 From: achingbrain Date: Thu, 11 May 2023 08:43:32 +0100 Subject: [PATCH] fix: make getPeerId return the target peer id from relay addresses If a p2p-circuit address doesn't contain the `/p2p/QmFoo` tuple for the target peer, `getPeerId` returns the peer id of the relay which is not what you'd expect. The fix here is for relay addresses, to return the peer id of the target and never the relay. Fixes #319 --- src/index.ts | 17 ++++++++++++----- test/index.spec.ts | 5 +++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index e65323b9..69e9d922 100644 --- a/src/index.ts +++ b/src/index.ts @@ -655,14 +655,21 @@ class DefaultMultiaddr implements Multiaddr { getPeerId (): string | null { try { - const tuples = this.stringTuples().filter((tuple) => { - if (tuple[0] === names.ipfs.code) { - return true + let tuples: Array<[number, string | undefined]> = [] + + this.stringTuples().forEach(([code, name]) => { + if (code === names.p2p.code) { + tuples.push([code, name]) + } + + // if this is a p2p-circuit address, return the target peer id if present + // not the peer id of the relay + if (code === names['p2p-circuit'].code) { + tuples = [] } - return false }) - // Get the last ipfs tuple ['ipfs', 'peerid string'] + // Get the last ipfs tuple ['p2p', 'peerid string'] const tuple = tuples.pop() if (tuple?.[1] != null) { const peerIdStr = tuple[1] diff --git a/test/index.spec.ts b/test/index.spec.ts index 73da3303..db81f1c9 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -997,6 +997,11 @@ describe('helpers', () => { multiaddr('/p2p-circuit/p2p/12D3KooWNvSZnPi3RrhrTwEY4LuuBeB6K6facKUCJcyWG1aoDd2p').getPeerId() ).to.equal('12D3KooWNvSZnPi3RrhrTwEY4LuuBeB6K6facKUCJcyWG1aoDd2p') }) + it('does not extract a peer Id from a circuit relay multiaddr where only the relay peer id is present', () => { + expect( + multiaddr('/ip4/127.0.0.1/tcp/123/p2p/bafzbeigweq4zr4x4ky2dvv7nanbkw6egutvrrvzw6g3h2rftp7gidyhtt4/p2p-circuit').getPeerId() + ).to.be.null() + }) }) describe('.getPeerId should return null on missing peer id in multiaddr', () => {