diff --git a/src/index.ts b/src/index.ts index a9fee946..92cfe77f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -635,14 +635,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', () => {