Skip to content

Commit

Permalink
fix: callback with error for invalid or non-peer multiaddr (#232)
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Alan Shaw <alan@tableflip.io>
  • Loading branch information
alanshaw authored and jacobheun committed Aug 13, 2018
1 parent ce29902 commit c8a86db
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/get-peer-info.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const setImmediate = require('async/setImmediate')

module.exports = (node) => {
/*
Expand All @@ -16,12 +17,19 @@ module.exports = (node) => {
// Multiaddr instance or Multiaddr String
} else if (multiaddr.isMultiaddr(peer) || typeof peer === 'string') {
if (typeof peer === 'string') {
peer = multiaddr(peer)
try {
peer = multiaddr(peer)
} catch (err) {
return setImmediate(() => callback(err))
}
}

const peerIdB58Str = peer.getPeerId()

if (!peerIdB58Str) {
throw new Error(`peer multiaddr instance or string must include peerId`)
return setImmediate(() => {
callback(new Error('peer multiaddr instance or string must include peerId'))
})
}

try {
Expand Down
26 changes: 26 additions & 0 deletions test/get-peer-info.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* eslint-env mocha */
'use strict'

const chai = require('chai')
chai.use(require('dirty-chai'))
const expect = chai.expect

const getPeerInfo = require('../src/get-peer-info')

describe('getPeerInfo', () => {
it('should callback with error for invalid string multiaddr', (done) => {
getPeerInfo(null)('INVALID MULTIADDR', (err) => {
expect(err).to.exist()
expect(err.message).to.contain('must start with a "/"')
done()
})
})

it('should callback with error for invalid non-peer multiaddr', (done) => {
getPeerInfo(null)('/ip4/8.8.8.8/tcp/1080', (err) => {
expect(err).to.exist()
expect(err.message).to.equal('peer multiaddr instance or string must include peerId')
done()
})
})
})

0 comments on commit c8a86db

Please sign in to comment.