From 4ba2c84509d930e1ef1cf46fdf3f3d8d25038b6b Mon Sep 17 00:00:00 2001 From: Andrew Osheroff Date: Mon, 2 Oct 2023 20:40:35 +0200 Subject: [PATCH 1/2] Force relaying on holepunch aborted error --- index.js | 14 ++++++++++---- lib/peer-info.js | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 4dca505..ba80e56 100644 --- a/index.js +++ b/index.js @@ -74,9 +74,9 @@ module.exports = class Hyperswarm extends EventEmitter { this.dht.on('network-change', this._handleNetworkChange.bind(this)) } - _maybeRelayConnection () { + _maybeRelayConnection (force) { if (!this.relayThrough) return null - return this.relayThrough() + return this.relayThrough(force) } _enqueue (peerInfo) { @@ -157,7 +157,7 @@ module.exports = class Hyperswarm extends EventEmitter { return } - const relayThrough = this._maybeRelayConnection() + const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying) const conn = this.dht.connect(peerInfo.publicKey, { relayAddresses: peerInfo.relayAddresses, keyPair: this.keyPair, @@ -185,7 +185,13 @@ module.exports = class Hyperswarm extends EventEmitter { this.emit('update') }) - conn.on('error', noop) + conn.on('error', err => { + if (this.relayThrough && (err.code === 'HOLEPUNCH_ABORTED')) { + peerInfo.forceRelaying = true + // Reset the attempts in order to fast connect to relay + peerInfo.attempts = 0 + } + }) conn.on('open', () => { opened = true this._connectDone() diff --git a/lib/peer-info.js b/lib/peer-info.js index 74ee535..2afa735 100644 --- a/lib/peer-info.js +++ b/lib/peer-info.js @@ -20,6 +20,7 @@ module.exports = class PeerInfo extends EventEmitter { this.tried = false this.explicit = false this.waiting = false + this.forceRelaying = false // Set by the Swarm this.queued = false From 1f535b5804f309427dd450fcfd8bf567f352cb66 Mon Sep 17 00:00:00 2001 From: Andrew Osheroff Date: Mon, 2 Oct 2023 20:50:47 +0200 Subject: [PATCH 2/2] Force relaying on several hyperdht error codes --- index.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index ba80e56..a6b4bb6 100644 --- a/index.js +++ b/index.js @@ -186,7 +186,7 @@ module.exports = class Hyperswarm extends EventEmitter { this.emit('update') }) conn.on('error', err => { - if (this.relayThrough && (err.code === 'HOLEPUNCH_ABORTED')) { + if (this.relayThrough && shouldForceRelaying(err.code)) { peerInfo.forceRelaying = true // Reset the attempts in order to fast connect to relay peerInfo.attempts = 0 @@ -505,3 +505,9 @@ function noop () { } function allowAll () { return false } + +function shouldForceRelaying (code) { + return (code === 'HOLEPUNCH_ABORTED') || + (code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS') || + (code === 'REMOTE_NOT_HOLEPUNCHABLE') +}