Skip to content

Commit 72831c1

Browse files
committed
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
1 parent 8a84847 commit 72831c1

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/index.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -655,14 +655,21 @@ class DefaultMultiaddr implements Multiaddr {
655655

656656
getPeerId (): string | null {
657657
try {
658-
const tuples = this.stringTuples().filter((tuple) => {
659-
if (tuple[0] === names.ipfs.code) {
660-
return true
658+
let tuples: Array<[number, string | undefined]> = []
659+
660+
this.stringTuples().forEach(([code, name]) => {
661+
if (code === names.p2p.code) {
662+
tuples.push([code, name])
663+
}
664+
665+
// if this is a p2p-circuit address, return the target peer id if present
666+
// not the peer id of the relay
667+
if (code === names['p2p-circuit'].code) {
668+
tuples = []
661669
}
662-
return false
663670
})
664671

665-
// Get the last ipfs tuple ['ipfs', 'peerid string']
672+
// Get the last ipfs tuple ['p2p', 'peerid string']
666673
const tuple = tuples.pop()
667674
if (tuple?.[1] != null) {
668675
const peerIdStr = tuple[1]

test/index.spec.ts

+5
Original file line numberDiff line numberDiff line change
@@ -997,6 +997,11 @@ describe('helpers', () => {
997997
multiaddr('/p2p-circuit/p2p/12D3KooWNvSZnPi3RrhrTwEY4LuuBeB6K6facKUCJcyWG1aoDd2p').getPeerId()
998998
).to.equal('12D3KooWNvSZnPi3RrhrTwEY4LuuBeB6K6facKUCJcyWG1aoDd2p')
999999
})
1000+
it('does not extract a peer Id from a circuit relay multiaddr where only the relay peer id is present', () => {
1001+
expect(
1002+
multiaddr('/ip4/127.0.0.1/tcp/123/p2p/bafzbeigweq4zr4x4ky2dvv7nanbkw6egutvrrvzw6g3h2rftp7gidyhtt4/p2p-circuit').getPeerId()
1003+
).to.be.null()
1004+
})
10001005
})
10011006

10021007
describe('.getPeerId should return null on missing peer id in multiaddr', () => {

0 commit comments

Comments
 (0)