Skip to content

Commit c8a86db

Browse files
alanshawjacobheun
authored andcommitted
fix: callback with error for invalid or non-peer multiaddr (#232)
License: MIT Signed-off-by: Alan Shaw <alan@tableflip.io>
1 parent ce29902 commit c8a86db

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/get-peer-info.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
const PeerId = require('peer-id')
44
const PeerInfo = require('peer-info')
55
const multiaddr = require('multiaddr')
6+
const setImmediate = require('async/setImmediate')
67

78
module.exports = (node) => {
89
/*
@@ -16,12 +17,19 @@ module.exports = (node) => {
1617
// Multiaddr instance or Multiaddr String
1718
} else if (multiaddr.isMultiaddr(peer) || typeof peer === 'string') {
1819
if (typeof peer === 'string') {
19-
peer = multiaddr(peer)
20+
try {
21+
peer = multiaddr(peer)
22+
} catch (err) {
23+
return setImmediate(() => callback(err))
24+
}
2025
}
2126

2227
const peerIdB58Str = peer.getPeerId()
28+
2329
if (!peerIdB58Str) {
24-
throw new Error(`peer multiaddr instance or string must include peerId`)
30+
return setImmediate(() => {
31+
callback(new Error('peer multiaddr instance or string must include peerId'))
32+
})
2533
}
2634

2735
try {

test/get-peer-info.spec.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/* eslint-env mocha */
2+
'use strict'
3+
4+
const chai = require('chai')
5+
chai.use(require('dirty-chai'))
6+
const expect = chai.expect
7+
8+
const getPeerInfo = require('../src/get-peer-info')
9+
10+
describe('getPeerInfo', () => {
11+
it('should callback with error for invalid string multiaddr', (done) => {
12+
getPeerInfo(null)('INVALID MULTIADDR', (err) => {
13+
expect(err).to.exist()
14+
expect(err.message).to.contain('must start with a "/"')
15+
done()
16+
})
17+
})
18+
19+
it('should callback with error for invalid non-peer multiaddr', (done) => {
20+
getPeerInfo(null)('/ip4/8.8.8.8/tcp/1080', (err) => {
21+
expect(err).to.exist()
22+
expect(err.message).to.equal('peer multiaddr instance or string must include peerId')
23+
done()
24+
})
25+
})
26+
})

0 commit comments

Comments
 (0)