diff --git a/package.json b/package.json index f4f4b21e..b82e2b58 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "dependencies": { "async": "^2.6.1", "base32.js": "~0.1.0", + "chai-checkmark": "^1.0.1", "cids": "~0.5.7", "debug": "^4.1.1", "err-code": "^1.1.2", diff --git a/src/index.js b/src/index.js index 02232092..dc334b28 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,6 @@ 'use strict' +const { EventEmitter } = require('events') const libp2pRecord = require('libp2p-record') const MemoryStore = require('interface-datastore').MemoryDatastore const waterfall = require('async/waterfall') @@ -27,7 +28,7 @@ const assert = require('assert') * * Original implementation in go: https://github.com/libp2p/go-libp2p-kad-dht. */ -class KadDHT { +class KadDHT extends EventEmitter { /** * Create a new KadDHT. * @@ -40,6 +41,7 @@ class KadDHT { * @param {object} options.selectors selectors object with namespace as keys and function(key, records) */ constructor (sw, options) { + super() assert(sw, 'libp2p-kad-dht requires a instance of Switch') options = options || {} options.validators = options.validators || {} @@ -608,6 +610,10 @@ class KadDHT { ], callback) }) } + + _peerDiscovered (peerInfo) { + this.emit('peer', peerInfo) + } } module.exports = KadDHT diff --git a/src/network.js b/src/network.js index edf7f234..29781ec8 100644 --- a/src/network.js +++ b/src/network.js @@ -122,6 +122,8 @@ class Network { return this._log.error('Failed to add to the routing table', err) } + this.dht._peerDiscovered(peer) + this._log('added to the routing table: %s', peer.id.toB58String()) }) }) diff --git a/src/query.js b/src/query.js index 411d1847..a11cab40 100644 --- a/src/query.js +++ b/src/query.js @@ -206,6 +206,7 @@ function execQuery (next, query, path, callback) { return cb() } closer = query.dht.peerBook.put(closer) + query.dht._peerDiscovered(closer) addPeerToQuery(closer.id, query.dht, path, cb) }, callback) } else { diff --git a/test/kad-dht.spec.js b/test/kad-dht.spec.js index c2fef90a..dfb6949f 100644 --- a/test/kad-dht.spec.js +++ b/test/kad-dht.spec.js @@ -3,6 +3,7 @@ const chai = require('chai') chai.use(require('dirty-chai')) +chai.use(require('chai-checkmark')) const expect = chai.expect const sinon = require('sinon') const series = require('async/series') @@ -256,6 +257,31 @@ describe('KadDHT', () => { }) }) + it('should emit a peer event when a peer is connected', function (done) { + this.timeout(10 * 1000) + const tdht = new TestDHT() + + tdht.spawn(2, (err, dhts) => { + expect(err).to.not.exist() + const dhtA = dhts[0] + const dhtB = dhts[1] + + dhtA.on('peer', (peerInfo) => { + expect(peerInfo).to.exist().mark() + }) + + dhtB.on('peer', (peerInfo) => { + expect(peerInfo).to.exist().mark() + }) + + connect(dhtA, dhtB, (err) => { + expect(err).to.not.exist() + }) + }) + + expect(2).checks(done) + }) + it('put - get', function (done) { this.timeout(10 * 1000) const tdht = new TestDHT()