From 37dadea1d1911b9ad17fb9f56e1d8480961c341c Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Thu, 16 Apr 2020 20:34:59 +0200 Subject: [PATCH] fix peers not getting gced --- index.js | 20 +++++++++++++++----- lib/io.js | 6 ++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index f191009..091cd44 100644 --- a/index.js +++ b/index.js @@ -49,6 +49,10 @@ class DHT extends EventEmitter { this._tickInterval = setInterval(this._ontick.bind(this), 5000) this._initialNodes = false + this.bucket.on('removed', (node) => { + if (this.nodes.has(node)) throw new Error('stop') + }) + process.nextTick(this.bootstrap.bind(this)) } @@ -169,6 +173,10 @@ class DHT extends EventEmitter { } } + onbadid (peer) { + this._removeNode(peer) + } + holepunch (peer, cb) { if (!peer.referrer) throw new Error('peer.referrer is required') this._io.query('_holepunch', null, null, peer, cb) @@ -246,8 +254,9 @@ class DHT extends EventEmitter { node.to = to if (!fresh) this.nodes.remove(node) - this.nodes.add(node) this.bucket.add(node) + if (this.bucket.get(node.id) !== node) return // in a ping + this.nodes.add(node) if (fresh) { this.emit('add-node', node) if (!this._initialNodes && this.nodes.length >= 5) { @@ -258,9 +267,10 @@ class DHT extends EventEmitter { } _removeNode (node) { + if (!this.nodes.has(node)) return this.nodes.remove(node) this.bucket.remove(node.id) - this.emit('remove-node') + this.emit('remove-node', node) } _token (peer, i) { @@ -279,7 +289,7 @@ class DHT extends EventEmitter { const old = oldContacts[i] // check if we recently talked to this peer ... - if (this._tick === old.tick) { + if (this._tick === old.tick && this.nodes.has(oldContacts[i])) { this.bucket.add(oldContacts[i]) continue } @@ -313,12 +323,12 @@ class DHT extends EventEmitter { function afterPing (err, res, node) { if (!err) return ping() self._removeNode(node) - self.bucket.add(newContact) + self._addNode(newContact) } } _pingSome () { - var cnt = this.inflightQueries > 2 ? 1 : 3 + var cnt = this.inflightQueries > 2 ? 2 : 5 var oldest = this.nodes.oldest // tiny dht, ping the bootstrap again if (!oldest) return this.bootstrap() diff --git a/lib/io.js b/lib/io.js index 72ab50d..dffdb6c 100644 --- a/lib/io.js +++ b/lib/io.js @@ -135,6 +135,12 @@ class IO { this.inflight[top.index = req.index] = top this.inflight.pop() + if (val && req.peer.id) { + if (!val.id || val.id.length !== 32 || !val.id.equals(req.peer.id)) { + this._ctx.onbadid(req.peer) + } + } + const type = req.message.type === TYPE.QUERY ? QUERY : UPDATE