From f28dffb2684abbd4ca84c5502c2f6f8deb2d0713 Mon Sep 17 00:00:00 2001 From: Jacob Heun Date: Tue, 16 Apr 2019 12:05:22 +0200 Subject: [PATCH] fix: bail when discovering self (#357) --- src/errors.js | 4 +++- src/index.js | 7 ++++++- test/peer-discovery.node.js | 27 +++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/errors.js b/src/errors.js index 64054bbd..19fb8530 100644 --- a/src/errors.js +++ b/src/errors.js @@ -7,5 +7,7 @@ exports.messages = { exports.codes = { DHT_DISABLED: 'ERR_DHT_DISABLED', - PUBSUB_NOT_STARTED: 'ERR_PUBSUB_NOT_STARTED' + PUBSUB_NOT_STARTED: 'ERR_PUBSUB_NOT_STARTED', + ERR_NODE_NOT_STARTED: 'ERR_NODE_NOT_STARTED', + ERR_DISCOVERED_SELF: 'ERR_DISCOVERED_SELF' } diff --git a/src/index.js b/src/index.js index 67fb84aa..90fd0337 100644 --- a/src/index.js +++ b/src/index.js @@ -24,11 +24,12 @@ const dht = require('./dht') const pubsub = require('./pubsub') const getPeerInfo = require('./get-peer-info') const validateConfig = require('./config').validate +const { codes } = require('./errors') const notStarted = (action, state) => { return errCode( new Error(`libp2p cannot ${action} when not started; state is ${state}`), - 'ERR_NODE_NOT_STARTED' + codes.ERR_NODE_NOT_STARTED ) } @@ -476,6 +477,10 @@ class Node extends EventEmitter { * @param {PeerInfo} peerInfo */ _peerDiscovered (peerInfo) { + if (peerInfo.id.toB58String() === this.peerInfo.id.toB58String()) { + log.error(new Error(codes.ERR_DISCOVERED_SELF)) + return + } peerInfo = this.peerBook.put(peerInfo) if (!this.isStarted()) return diff --git a/test/peer-discovery.node.js b/test/peer-discovery.node.js index de7106df..b9d44783 100644 --- a/test/peer-discovery.node.js +++ b/test/peer-discovery.node.js @@ -259,6 +259,33 @@ describe('peer discovery', () => { }) }) + describe('discovery scenarios', () => { + setup({ + config: { + dht: { + enabled: false + }, + peerDiscovery: { + autoDial: false, + bootstrap: { + enabled: true, + list: [] + } + } + } + }) + + it('should ignore self on discovery', function () { + const discoverySpy = sinon.spy() + nodeA.on('peer:discovery', discoverySpy) + nodeA._discovery[0].emit('peer', nodeA.peerInfo) + + expect(discoverySpy.called).to.eql(false) + expect(nodeA.peerBook.getAllArray()).to.have.length(0) + expect() + }) + }) + describe('MulticastDNS', () => { setup({ config: {