Skip to content

Commit acbbc0f

Browse files
dirkmcjacobheun
authored andcommitted
fix: replace peerInfo addresses with listen addresses (#485)
* feat: replace peer info addresses with listen addresses * test: add listening test * chore: fix linting
1 parent 995640e commit acbbc0f

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,10 +301,18 @@ class Libp2p extends EventEmitter {
301301
}
302302

303303
async _onStarting () {
304+
// Listen on the addresses supplied in the peerInfo
304305
const multiaddrs = this.peerInfo.multiaddrs.toArray()
305306

306307
await this.transportManager.listen(multiaddrs)
307308

309+
// The addresses may change once the listener starts
310+
// eg /ip4/0.0.0.0/tcp/0 => /ip4/192.168.1.0/tcp/58751
311+
this.peerInfo.multiaddrs.clear()
312+
for (const ma of this.transportManager.getAddrs()) {
313+
this.peerInfo.multiaddrs.add(ma)
314+
}
315+
308316
if (this._config.pubsub.enabled) {
309317
this.pubsub && this.pubsub.start()
310318
}

test/core/listening.node.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
'use strict'
2+
/* eslint-env mocha */
3+
4+
const chai = require('chai')
5+
chai.use(require('dirty-chai'))
6+
const { expect } = chai
7+
8+
const multiaddr = require('multiaddr')
9+
const Transport = require('libp2p-tcp')
10+
11+
const { create } = require('../../src')
12+
const peerUtils = require('../utils/creators/peer')
13+
14+
const listenAddr = multiaddr('/ip4/0.0.0.0/tcp/0')
15+
16+
describe('Listening', () => {
17+
let peerInfo
18+
let libp2p
19+
20+
before(async () => {
21+
[peerInfo] = await peerUtils.createPeerInfoFromFixture(1)
22+
peerInfo.multiaddrs.add(listenAddr)
23+
})
24+
25+
after(async () => {
26+
await libp2p.stop()
27+
})
28+
29+
it('should replace wildcard host and port with actual host and port on startup', async () => {
30+
libp2p = await create({
31+
peerInfo,
32+
modules: {
33+
transport: [Transport]
34+
}
35+
})
36+
37+
await libp2p.start()
38+
39+
const addrs = libp2p.peerInfo.multiaddrs.toArray()
40+
41+
// Should get something like:
42+
// /ip4/127.0.0.1/tcp/50866
43+
// /ip4/192.168.1.2/tcp/50866
44+
expect(addrs.length).to.equal(2)
45+
46+
const opts = [addrs[0].toOptions(), addrs[1].toOptions()]
47+
expect(opts[0].family).to.equal('ipv4')
48+
expect(opts[1].family).to.equal('ipv4')
49+
expect(opts[0].transport).to.equal('tcp')
50+
expect(opts[1].transport).to.equal('tcp')
51+
expect(opts[0].host).to.match(/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)
52+
expect(opts[1].host).to.match(/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)
53+
expect(opts[0].port).to.be.gt(0)
54+
expect(opts[1].port).to.be.gt(0)
55+
})
56+
})

0 commit comments

Comments
 (0)