forked from libp2p/js-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.js
77 lines (70 loc) · 2.05 KB
/
3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* eslint-disable no-console */
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { bootstrap } from '@libp2p/bootstrap'
import { floodsub } from '@libp2p/floodsub'
import { mplex } from '@libp2p/mplex'
import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'
import { tcp } from '@libp2p/tcp'
import { createLibp2p } from 'libp2p'
import { circuitRelayTransport, circuitRelayServer } from 'libp2p/circuit-relay'
import { identifyService } from 'libp2p/identify'
const createNode = async (bootstrappers) => {
const node = await createLibp2p({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
transports: [tcp()],
streamMuxers: [yamux(), mplex()],
connectionEncryption: [noise()],
peerDiscovery: [
bootstrap({
list: bootstrappers
}),
pubsubPeerDiscovery({
interval: 1000
})
],
services: {
pubsub: floodsub(),
identify: identifyService()
}
})
return node
}
;(async () => {
const relay = await createLibp2p({
addresses: {
listen: [
'/ip4/0.0.0.0/tcp/0'
]
},
transports: [tcp(), circuitRelayTransport()],
streamMuxers: [yamux(), mplex()],
connectionEncryption: [noise()],
peerDiscovery: [
pubsubPeerDiscovery({
interval: 1000
})
],
services: {
relay: circuitRelayServer(),
identify: identifyService(),
pubsub: floodsub()
}
})
console.log(`libp2p relay started with id: ${relay.peerId.toString()}`)
const relayMultiaddrs = relay.getMultiaddrs().map((m) => m.toString())
const [node1, node2] = await Promise.all([
createNode(relayMultiaddrs),
createNode(relayMultiaddrs)
])
node1.addEventListener('peer:discovery', (evt) => {
const peer = evt.detail
console.log(`Peer ${node1.peerId.toString()} discovered: ${peer.id.toString()}`)
})
node2.addEventListener('peer:discovery', (evt) => {
const peer = evt.detail
console.log(`Peer ${node2.peerId.toString()} discovered: ${peer.id.toString()}`)
})
})()