Skip to content

Commit 9156383

Browse files
committed
fix: prevent duplicate connections to multiaddr
After opening a new connection, check if there is an existing connection to the same peer. If the existing connection is not limited or the new connection is also limit, return the existing connection. This will prevent multiple connections to the same peer in cases where the multiaddr being dialed does not contain a peer id.
1 parent d7312ae commit 9156383

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

packages/libp2p/src/connection-manager/dial-queue.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,12 @@ export class DialQueue {
135135
*/
136136
async dial (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {
137137
const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)
138+
const { force } = options
138139

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

@@ -260,6 +261,30 @@ export class DialQueue {
260261
this.log.error('could not update last dial failure key for %p', peerId, err)
261262
}
262263

264+
const { remotePeer } = conn
265+
266+
// make sure we don't have an existing connection to the address we dialed
267+
const existingConnection = Array.from(this.connections.values()).flat().find(_conn => {
268+
if (force === true) {
269+
return false
270+
}
271+
272+
if (_conn.remotePeer.equals(remotePeer) && _conn !== conn) {
273+
return true
274+
}
275+
276+
return false
277+
})
278+
279+
// return existing, open connection to peer if equal or better limits
280+
if (existingConnection?.status === 'open' && (existingConnection?.limits == null || conn?.limits != null)) {
281+
this.log('already connected to %a', existingConnection.remoteAddr)
282+
options?.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
283+
this.log('closing duplicate connection to %p', remotePeer)
284+
await conn.close()
285+
return existingConnection
286+
}
287+
263288
return conn
264289
} catch (err: any) {
265290
this.log.error('dial failed to %a', address.multiaddr, err)

0 commit comments

Comments
 (0)