From 695f77ca9be5dddf478e507d9feb2a97eceeb935 Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Thu, 9 Jul 2020 11:11:02 +0200 Subject: [PATCH] fix: not dial all known peers on startup --- src/index.js | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/index.js b/src/index.js index ad7a78281c..99ca1b6e4d 100644 --- a/src/index.js +++ b/src/index.js @@ -467,10 +467,7 @@ class Libp2p extends EventEmitter { }) // Once we start, emit and dial any peers we may have already discovered - for (const peer of this.peerStore.peers.values()) { - this.emit('peer:discovery', peer.id) - this._maybeConnect(peer.id) - } + this._maybeConnectPeerStorePeers() // Peer discovery await this._setupPeerDiscovery() @@ -492,6 +489,33 @@ class Libp2p extends EventEmitter { peer.protocols && this.peerStore.protoBook.set(peer.id, peer.protocols) } + /** + * Will dial a substet of the peers already known + * @private + * @returns {void} + */ + _maybeConnectPeerStorePeers () { + if (!this._config.peerDiscovery.autoDial) { + return + } + + const minPeers = this._options.connectionManager.minPeers || 0 + + // TODO: this should be ordered by score on PeerStoreV2 + this.peerStore.peers.forEach(async (peer) => { + this.emit('peer:discovery', peer.id) + + if (minPeers > this.connectionManager.size && !this.connectionManager.get(peer.id)) { + log('connecting to previously discovered peer %s', peer.id.toB58String()) + try { + await this.dialer.connectToPeer(peer.id) + } catch (err) { + log.error('could not connect to previously discovered peer', err) + } + } + }) + } + /** * Will dial to the given `peerId` if the current number of * connected peers is less than the configured `ConnectionManager`