2018-10-19 17:37:34 +02:00
|
|
|
/* eslint-disable no-console */
|
2017-07-20 19:42:32 -07:00
|
|
|
'use strict'
|
|
|
|
|
2018-06-28 10:06:25 +02:00
|
|
|
const libp2p = require('../../')
|
2017-07-20 19:42:32 -07:00
|
|
|
const TCP = require('libp2p-tcp')
|
2018-02-19 09:46:11 +00:00
|
|
|
const Mplex = require('libp2p-mplex')
|
2017-07-20 19:42:32 -07:00
|
|
|
const SECIO = require('libp2p-secio')
|
|
|
|
const PeerInfo = require('peer-info')
|
|
|
|
const MulticastDNS = require('libp2p-mdns')
|
2018-06-28 10:06:25 +02:00
|
|
|
const defaultsDeep = require('@nodeutils/defaults-deep')
|
2017-07-20 19:42:32 -07:00
|
|
|
const waterfall = require('async/waterfall')
|
|
|
|
const parallel = require('async/parallel')
|
|
|
|
const series = require('async/series')
|
|
|
|
|
|
|
|
class MyBundle extends libp2p {
|
2018-06-28 10:06:25 +02:00
|
|
|
constructor (_options) {
|
|
|
|
const defaults = {
|
|
|
|
modules: {
|
|
|
|
transport: [ TCP ],
|
|
|
|
streamMuxer: [ Mplex ],
|
|
|
|
connEncryption: [ SECIO ],
|
|
|
|
peerDiscovery: [ MulticastDNS ]
|
2017-07-20 19:42:32 -07:00
|
|
|
},
|
2018-06-28 10:06:25 +02:00
|
|
|
config: {
|
|
|
|
peerDiscovery: {
|
|
|
|
mdns: {
|
|
|
|
interval: 2000,
|
|
|
|
enabled: true
|
|
|
|
}
|
|
|
|
},
|
|
|
|
EXPERIMENTAL: {
|
|
|
|
pubsub: true
|
|
|
|
}
|
|
|
|
}
|
2017-07-20 19:42:32 -07:00
|
|
|
}
|
2018-06-28 10:06:25 +02:00
|
|
|
|
|
|
|
super(defaultsDeep(_options, defaults))
|
2017-07-20 19:42:32 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function createNode (callback) {
|
|
|
|
let node
|
|
|
|
|
|
|
|
waterfall([
|
|
|
|
(cb) => PeerInfo.create(cb),
|
|
|
|
(peerInfo, cb) => {
|
|
|
|
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
2018-06-28 10:06:25 +02:00
|
|
|
node = new MyBundle({
|
|
|
|
peerInfo
|
|
|
|
})
|
2017-07-20 19:42:32 -07:00
|
|
|
node.start(cb)
|
|
|
|
}
|
|
|
|
], (err) => callback(err, node))
|
|
|
|
}
|
|
|
|
|
|
|
|
parallel([
|
|
|
|
(cb) => createNode(cb),
|
|
|
|
(cb) => createNode(cb)
|
|
|
|
], (err, nodes) => {
|
|
|
|
if (err) { throw err }
|
|
|
|
|
|
|
|
const node1 = nodes[0]
|
|
|
|
const node2 = nodes[1]
|
|
|
|
|
2019-04-11 15:52:04 +02:00
|
|
|
node1.once('peer:connect', (peer) => {
|
|
|
|
console.log('connected to %s', peer.id.toB58String())
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2018-02-22 07:06:21 +00:00
|
|
|
// Subscribe to the topic 'news'
|
2018-02-15 20:15:18 +01:00
|
|
|
node1.pubsub.subscribe('news',
|
2018-02-16 18:04:10 +00:00
|
|
|
(msg) => console.log(msg.from, msg.data.toString()),
|
2018-02-15 20:15:18 +01:00
|
|
|
() => {
|
|
|
|
setInterval(() => {
|
2018-02-22 07:06:21 +00:00
|
|
|
// Publish the message on topic 'news'
|
|
|
|
node2.pubsub.publish(
|
|
|
|
'news',
|
|
|
|
Buffer.from('Bird bird bird, bird is the word!'),
|
|
|
|
() => {}
|
|
|
|
)
|
2018-02-15 20:15:18 +01:00
|
|
|
}, 1000)
|
2018-02-16 18:04:10 +00:00
|
|
|
}
|
2018-02-15 20:15:18 +01:00
|
|
|
)
|
2017-07-20 19:42:32 -07:00
|
|
|
})
|
|
|
|
})
|