Skip to content

Commit

Permalink
fix: make getPeerId return the target peer id from relay addrs (#325)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
achingbrain committed Jul 28, 2023
1 parent a04c7f1 commit 2b0e353
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
5 changes: 5 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 2b0e353

Please sign in to comment.