From a5658c6344b97888db73ba48be6d235a5b6a623d Mon Sep 17 00:00:00 2001 From: Nabarun Gogoi Date: Fri, 27 Jan 2023 11:49:53 +0530 Subject: [PATCH] Fix for multiple connections between two peers (#305) * Close existing connection * Fix closing existing connections * Close new connections from only peer * Refresh in intervals to update UI stats --- packages/peer/src/index.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/peer/src/index.ts b/packages/peer/src/index.ts index ecd7ae83..377c3e23 100644 --- a/packages/peer/src/index.ts +++ b/packages/peer/src/index.ts @@ -263,11 +263,27 @@ export class Peer { } async _handleConnect (connection: Connection): Promise { + assert(this._node); const remotePeerId = connection.remotePeer; + const remoteConnections = this._node.getConnections(remotePeerId); // Log connected peer console.log(`Connected to ${remotePeerId.toString()} using multiaddr ${connection.remoteAddr.toString()}`); - console.log(`Current number of peers connected: ${this._node?.getPeers().length}`); + + // Keep only one connection with a peer. + if (remoteConnections.length > 1) { + // Close new connection from peer having the smaller peer id. + if (this._node.peerId.toString() < remotePeerId.toString()) { + console.log('Closing new connection for already connected peer'); + // Close new connection as protocol stream is opened in the first connection that is established. + await connection.close(); + console.log('Closed'); + } + + return; + } + + console.log(`Current number of peers connected: ${this._node.getPeers().length}`); // Start heartbeat check peer await this._startHeartbeatChecks(