Here’s the code:
/* eslint-disable no-console */
‘use strict’
const libp2p = require(‘libp2p’)
//const TCP = require(‘libp2p-tcp’)
//const WS = require(‘libp2p-websockets’)
const Mplex = require(‘libp2p-mplex’)
const SECIO = require(‘libp2p-secio’)
const PeerInfo = require(‘peer-info’)
const KadDHT = require(‘libp2p-kad-dht’)
const defaultsDeep = require(’@nodeutils/defaults-deep’)
const waterfall = require(‘async/waterfall’)
const parallel = require(‘async/parallel’)
const WebRTCDirect = require(‘libp2p-webrtc-direct’)
//let currentPort = 9090
const mockUpgrader = {
upgradeInbound: maConn => maConn,
upgradeOutbound: maConn => maConn
}
let wS = new WebRTCDirect({ upgrader: mockUpgrader })
class MyBundle extends libp2p {
constructor (_options) {
const defaults = {
modules: {
transport: [ wS ],
streamMuxer: [ Mplex ],
connEncryption: [ SECIO ],
// we add the DHT module that will enable Peer and Content Routing
dht: KadDHT
},
config: {
dht: {
enabled: true,
kBucketSize: 20
}
}
}
super(defaultsDeep(_options, defaults))
}
}
function createNode (callback) {
let node
waterfall([
(cb) => PeerInfo.create(cb),
(peerInfo, cb) => {
//peerInfo.multiaddrs.add(’/ip4/0.0.0.0/tcp/0/ws’)
peerInfo.multiaddrs.add(’/ip4/127.0.0.1/tcp/12345/http/p2p-webrtc-direct’)
//peerInfo.multiaddrs.add(’/ip4/0.0.0.0/tcp/0’)
//urrentPort++
node = new MyBundle({
peerInfo
})
node.start(cb)
}
], (err) => callback(err, node))
}
parallel([
(cb) => createNode(cb),
(cb) => createNode(cb),
(cb) => createNode(cb)
], (err, nodes) => {
if (err) { throw err }
const node1 = nodes[0]
const node2 = nodes[1]
const node3 = nodes[2]
console.log(“NODE 1”);
node1.peerInfo.multiaddrs.forEach((ma) => console.log(ma.toString()))
console.log(“NODE 2”);
node2.peerInfo.multiaddrs.forEach((ma) => console.log(ma.toString()))
console.log(“NODE 3”);
node3.peerInfo.multiaddrs.forEach((ma) => console.log(ma.toString()))
parallel([
(cb) => node1.dial(node2.peerInfo, cb),
(cb) => node2.dial(node3.peerInfo, cb),
// Set up of the cons might take time
(cb) => setTimeout(cb, 300)
], (err) => {
if (err) { throw err }
node1.peerRouting.findPeer(node3.peerInfo.id, (err, peer) => {
if (err) { throw err }
console.log(‘Found it, multiaddrs are:’)
peer.multiaddrs.forEach((ma) => console.log(ma.toString()))
})
})
})