js-libp2p/src/identify.js

96 lines
2.4 KiB
JavaScript
Raw Normal View History

2015-07-08 16:22:59 -07:00
/*
* Identify is one of the protocols swarms speaks in order to broadcast and learn about the ip:port
* pairs a specific peer is available through
*/
var Interactive = require('multistream-select').Interactive
2015-07-09 13:53:03 -07:00
var EventEmmiter = require('events').EventEmitter
var util = require('util')
2015-07-08 16:22:59 -07:00
2015-07-09 13:53:03 -07:00
exports = module.exports = Identify
2015-07-08 16:22:59 -07:00
2015-07-09 13:53:03 -07:00
util.inherits(Identify, EventEmmiter)
2015-07-08 16:22:59 -07:00
2015-07-09 13:53:03 -07:00
function Identify (swarm, peerSelf) {
var self = this
swarm.registerHandle('/ipfs/identify/1.0.0', function (stream) {
var identifyMsg = {}
identifyMsg = {}
identifyMsg.sender = exportPeer(peerSelf)
// TODO (daviddias) populate with the way I see the other peer
// identifyMsg.receiver =
stream.write(JSON.stringify(identifyMsg))
var answer = ''
stream.on('data', function (chunk) {
answer += chunk.toString()
})
stream.on('end', function () {
2015-07-09 15:45:03 -07:00
console.log(JSON.parse(answer))
2015-07-09 13:53:03 -07:00
self.emit('thenews', answer)
2015-07-08 16:22:59 -07:00
})
2015-07-09 13:53:03 -07:00
stream.end()
2015-07-09 13:53:09 -07:00
// receive their info and how they see us
// send back our stuff
2015-07-08 16:22:59 -07:00
})
2015-07-09 13:53:03 -07:00
swarm.on('connection', function (spdyConnection) {
spdyConnection.request({
path: '/',
method: 'GET'
}, function (err, stream) {
if (err) {
return console.log(err)
}
var msi = new Interactive()
msi.handle(stream, function () {
msi.select('/ipfs/identify/1.0.0', function (err, ds) {
if (err) {
return console.log('err')
}
var identifyMsg = {}
identifyMsg = {}
identifyMsg.sender = exportPeer(peerSelf)
// TODO (daviddias) populate with the way I see the other peer
// identifyMsg.receiver =
stream.write(JSON.stringify(identifyMsg))
var answer = ''
stream.on('data', function (chunk) {
answer += chunk.toString()
})
2015-07-08 16:22:59 -07:00
2015-07-09 13:53:03 -07:00
stream.on('end', function () {
console.log(JSON.parse(answer))
// TODO (daviddias), push to the connections list on swarm that we have a new known connection
self.emit('thenews', answer)
})
stream.end()
})
})
})
2015-07-09 13:53:09 -07:00
// open a spdy stream
// do the multistream handshake
// send them our data
2015-07-08 16:22:59 -07:00
})
2015-07-09 13:53:03 -07:00
function exportPeer (peer) {
return {
id: peer.id.toB58String(),
multiaddrs: peer.multiaddrs.map(function (mh) {
return mh.toString()
})
}
}
2015-07-08 16:22:59 -07:00
}