Skip to content

Commit ec02351

Browse files
authored
fix: when creating dial targets, encapsulate PeerIds last (#1389)
It turns out because `Multiaddr.encapsulate` stringifies the `Multiaddr` it's a [suprisingly expensive operation](multiformats/js-multiaddr#275 (comment)) so here we switch the order of our `Multiaddr` pipeline around so we filter undialable addresses (e.g. unsupported transports etc) before encapsulating the `PeerId` onto a `Multiaddr` we'd then just ignore.
1 parent 3f57eda commit ec02351

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

src/connection-manager/dialer/index.ts

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -232,15 +232,23 @@ export class DefaultDialer implements Startable, Dialer {
232232
* Multiaddrs not supported by the available transports will be filtered out.
233233
*/
234234
async _createDialTarget (peer: PeerId, options: AbortOptions): Promise<DialTarget> {
235-
const knownAddrs = await pipe(
235+
const _resolve = this._resolve.bind(this)
236+
237+
const addrs = await pipe(
236238
await this.components.getPeerStore().addressBook.get(peer),
237239
(source) => filter(source, async (address) => {
238240
return !(await this.components.getConnectionGater().denyDialMultiaddr(peer, address.multiaddr))
239241
}),
242+
// Sort addresses so, for example, we try certified public address first
240243
(source) => sort(source, this.addressSorter),
241-
(source) => map(source, (address) => {
242-
const ma = address.multiaddr
243-
244+
async function * resolve (source) {
245+
for await (const a of source) {
246+
yield * await _resolve(a.multiaddr, options)
247+
}
248+
},
249+
// Multiaddrs not supported by the available transports will be filtered out.
250+
(source) => filter(source, (ma) => Boolean(this.components.getTransportManager().transportForMultiaddr(ma))),
251+
(source) => map(source, (ma) => {
244252
if (peer.toString() === ma.getPeerId()) {
245253
return ma
246254
}
@@ -250,23 +258,14 @@ export class DefaultDialer implements Startable, Dialer {
250258
async (source) => await all(source)
251259
)
252260

253-
const addrs: Multiaddr[] = []
254-
for (const a of knownAddrs) {
255-
const resolvedAddrs = await this._resolve(a, options)
256-
resolvedAddrs.forEach(ra => addrs.push(ra))
257-
}
258-
259-
// Multiaddrs not supported by the available transports will be filtered out.
260-
const supportedAddrs = addrs.filter(a => this.components.getTransportManager().transportForMultiaddr(a))
261-
262-
if (supportedAddrs.length > this.maxAddrsToDial) {
261+
if (addrs.length > this.maxAddrsToDial) {
263262
await this.components.getPeerStore().delete(peer)
264263
throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)
265264
}
266265

267266
return {
268267
id: peer.toString(),
269-
addrs: supportedAddrs
268+
addrs
270269
}
271270
}
272271

0 commit comments

Comments
 (0)