Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent duplicate connections to multiaddr #2734

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion packages/libp2p/src/connection-manager/dial-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,12 @@
*/
async dial (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {
const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)
const { force } = options

// make sure we don't have an existing connection to any of the addresses we
// are about to dial
const existingConnection = Array.from(this.connections.values()).flat().find(conn => {
if (options.force === true) {
if (force === true) {
return false
}

Expand Down Expand Up @@ -267,6 +268,30 @@
this.log.error('could not update last dial failure key for %p', peerId, err)
}

const { remotePeer } = conn

// make sure we don't have an existing connection to the address we dialed
const existingConnection = Array.from(this.connections.values()).flat().find(_conn => {
if (force === true) {
return false
}

Check warning on line 277 in packages/libp2p/src/connection-manager/dial-queue.ts

View check run for this annotation

Codecov / codecov/patch

packages/libp2p/src/connection-manager/dial-queue.ts#L276-L277

Added lines #L276 - L277 were not covered by tests

if (_conn.remotePeer.equals(remotePeer) && _conn !== conn) {
return true
}

return false

Check warning on line 283 in packages/libp2p/src/connection-manager/dial-queue.ts

View check run for this annotation

Codecov / codecov/patch

packages/libp2p/src/connection-manager/dial-queue.ts#L282-L283

Added lines #L282 - L283 were not covered by tests
})

// return existing, open connection to peer if equal or better limits
if (existingConnection?.status === 'open' && (existingConnection?.limits == null || conn?.limits != null)) {
this.log('already connected to %a', existingConnection.remoteAddr)
options?.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
this.log('closing duplicate connection to %p', remotePeer)
await conn.close()
return existingConnection
}

return conn
} catch (err: any) {
this.log.error('dial failed to %a', address.multiaddr, err)
Expand Down
71 changes: 71 additions & 0 deletions packages/libp2p/test/connection-manager/dial-queue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { generateKeyPair } from '@libp2p/crypto/keys'
import { NotFoundError } from '@libp2p/interface'
import { peerLogger } from '@libp2p/logger'
import { PeerMap } from '@libp2p/peer-collections'
import { peerIdFromPrivateKey } from '@libp2p/peer-id'
import { multiaddr, resolvers } from '@multiformats/multiaddr'
import { WebRTC } from '@multiformats/multiaddr-matcher'
Expand Down Expand Up @@ -327,6 +328,76 @@ describe('dial queue', () => {
await expect(dialer.dial(remotePeer)).to.eventually.equal(connection)
})

it('should return existing connection when dialing a multiaddr without a peer id', async () => {
const remotePeer = peerIdFromPrivateKey(await generateKeyPair('Ed25519'))
const ip = multiaddr('/ip4/123.123.123.123')
const addr1 = ip.encapsulate('/tcp/123')
const addr2 = ip.encapsulate('/tcp/321')

const existingConnection = stubInterface<Connection>({
limits: {
bytes: 100n
},
remotePeer,
remoteAddr: addr1.encapsulate(`/p2p/${remotePeer}`),
status: 'open'
})

const newConnection = stubInterface<Connection>({
limits: {
bytes: 100n
},
remotePeer,
remoteAddr: addr2.encapsulate(`/p2p/${remotePeer}`),
status: 'open'
})

const connections = new PeerMap<Connection[]>()
connections.set(remotePeer, [existingConnection])

components.transportManager.dialTransportForMultiaddr.callsFake(ma => {
return stubInterface<Transport>()
})
components.transportManager.dial.callsFake(async (ma, opts = {}) => newConnection)
dialer = new DialQueue(components, { connections })

await expect(dialer.dial(addr2)).to.eventually.equal(existingConnection)
})

it('should return new connection when existing connection to same peer is worse', async () => {
const remotePeer = peerIdFromPrivateKey(await generateKeyPair('Ed25519'))
const ip = multiaddr('/ip4/123.123.123.123')
const addr1 = ip.encapsulate('/tcp/123')
const addr2 = ip.encapsulate('/tcp/321')

const existingConnection = stubInterface<Connection>({
limits: {
bytes: 100n
},
remotePeer,
remoteAddr: addr1.encapsulate(`/p2p/${remotePeer}`),
status: 'open'
})

const newConnection = stubInterface<Connection>({
limits: undefined,
remotePeer,
remoteAddr: addr2.encapsulate(`/p2p/${remotePeer}`),
status: 'open'
})

const connections = new PeerMap<Connection[]>()
connections.set(remotePeer, [existingConnection])

components.transportManager.dialTransportForMultiaddr.callsFake(ma => {
return stubInterface<Transport>()
})
components.transportManager.dial.callsFake(async (ma, opts = {}) => newConnection)
dialer = new DialQueue(components, { connections })

await expect(dialer.dial(addr2)).to.eventually.equal(newConnection)
})

it('should respect user dial signal over default timeout if it is passed', async () => {
const dialTimeout = 10
const userTimeout = 500
Expand Down
Loading