diff --git a/package.json b/package.json index 42c6c2ae..b1ae4c5e 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "it-protocol-buffers": "^0.2.0", "libp2p-crypto": "^0.18.0", "libp2p-interfaces": "^0.5.1", - "libp2p-utils": "^0.2.0", + "libp2p-utils": "^0.2.1", "mafmt": "^8.0.0", "merge-options": "^2.0.0", "moving-average": "^1.0.0", diff --git a/src/circuit/auto-relay.js b/src/circuit/auto-relay.js index c0475dba..768d17eb 100644 --- a/src/circuit/auto-relay.js +++ b/src/circuit/auto-relay.js @@ -4,6 +4,8 @@ const debug = require('debug') const log = debug('libp2p:auto-relay') log.error = debug('libp2p:auto-relay:error') +const isPrivate = require('libp2p-utils/src/multiaddr/is-private') + const uint8ArrayFromString = require('uint8arrays/from-string') const uint8ArrayToString = require('uint8arrays/to-string') const multiaddr = require('multiaddr') @@ -131,9 +133,13 @@ class AutoRelay { let listenAddr, remoteMultiaddr, remoteAddrs try { + // Get peer known addresses and sort them per public addresses first remoteAddrs = this._peerStore.addressBook.get(connection.remotePeer) - // TODO: HOP Relays should avoid advertising private addresses! + // TODO: This sort should be customizable in the config (dialer addr sort) + remoteAddrs.sort(multiaddrsCompareFunction) + remoteMultiaddr = remoteAddrs.find(a => a.isCertified).multiaddr // Get first announced address certified + // TODO: HOP Relays should avoid advertising private addresses! } catch (_) { log.error(`${id} does not have announced certified multiaddrs`) @@ -267,4 +273,24 @@ class AutoRelay { } } +/** + * Compare function for array.sort(). + * This sort aims to move the private adresses to the end of the array. + * + * @param {Address} a + * @param {Address} b + * @returns {number} + */ +function multiaddrsCompareFunction (a, b) { + const isAPrivate = isPrivate(a.multiaddr) + const isBPrivate = isPrivate(b.multiaddr) + + if (isAPrivate && !isBPrivate) { + return 1 + } else if (!isAPrivate && isBPrivate) { + return -1 + } + return 0 +} + module.exports = AutoRelay