From d3c1314b2600091e30bc21b07b8e74cc7667715b Mon Sep 17 00:00:00 2001 From: Andrew Osheroff Date: Mon, 2 Oct 2023 20:56:14 +0200 Subject: [PATCH] Force relaying on holepunch aborted (#151) * Force relaying on holepunch aborted error * Force relaying on several hyperdht error codes --- index.js | 20 ++++++++++++++++---- lib/peer-info.js | 1 + 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 4dca505..a6b4bb6 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 && shouldForceRelaying(err.code)) { + peerInfo.forceRelaying = true + // Reset the attempts in order to fast connect to relay + peerInfo.attempts = 0 + } + }) conn.on('open', () => { opened = true this._connectDone() @@ -499,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') +} 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