-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo5.js
149 lines (138 loc) · 4.83 KB
/
demo5.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { createLibp2p } from 'libp2p'
import { peerIdFromString } from '@libp2p/peer-id'
import { multiaddr } from '@multiformats/multiaddr'
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
import { webTransport } from '@libp2p/webtransport'
import { mplex } from '@libp2p/mplex'
import { yamux } from '@chainsafe/libp2p-yamux'
import { noise } from '@chainsafe/libp2p-noise'
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
import { bootstrap } from '@libp2p/bootstrap'
import { identifyService } from 'libp2p/identify'
import { kadDHT } from '@libp2p/kad-dht'
import { webRTCDirect } from '@libp2p/webrtc'
// import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
const log = (...args) => {
console.log(...args)
const logHtml = (...args) => {
const p = document.createElement('p')
let textContent = ''
for (const [i, arg] of args.entries()) {
if (textContent !== '') {
textContent += ' '
}
if (typeof arg === 'object') {
textContent += JSON.stringify(arg, null, 2)
if (args.length - 1 !== i) {
textContent += '\n'
}
}
else {
textContent += arg
}
}
p.textContent = textContent
p.style.whiteSpace = 'pre'
document.body.prepend(p)
}
try {
if (document.readyState !== 'complete') {
window.addEventListener('load', () => logHtml(...args))
}
else {
logHtml(...args)
}
}
catch (e) {}
}
const logEvents = (nodeName, node) => {
const events = [
'connection:close',
'connection:open',
'connection:prune',
'peer:connect',
'peer:disconnect',
'peer:discovery',
'peer:identify',
'peer:update',
'self:peer:update',
'start',
'stop',
'transport:close',
'transport:listening',
]
const logEvent = (event) => log(nodeName, event.type, event.detail)
events.forEach(event => node.addEventListener(event, logEvent))
}
let peerId, peerMultiAddress
try {
// example: /demo4.html?/ip4/0.0.0.0/udp/36338/quic-v1/webtransport/certhash/uEiAKYNN-nS53kXTQTzM0__ksuMI9mEczZA9YbNyyth-NLw/certhash/uEiD9Ja-UEHkuLjtaVKX7D1wZVri6GKkrmxFOue8-9YMAzg/p2p/Qmbi4zsa9H8WDZk8akwSiBqEe8U1Gedh8Mh4R4aCfR3Twx
peerMultiAddress = location.search.replace(/^\?/, '')
peerId = peerMultiAddress.split('/p2p/')[1]
}
catch (e) {
log(e)
}
if (!peerId || !peerMultiAddress) {
log('failed to get peer to connect to from query string, example: /demo4.html?/ip4/0.0.0.0/udp/36338/quic-v1/webtransport/certhash/uEiAKYNN-nS53kXTQTzM0__ksuMI9mEczZA9YbNyyth-NLw/certhash/uEiD9Ja-UEHkuLjtaVKX7D1wZVri6GKkrmxFOue8-9YMAzg/p2p/Qmbi4zsa9H8WDZk8akwSiBqEe8U1Gedh8Mh4R4aCfR3Twx')
}
;(async () => {
try {
// bootstrap node is created in go because listening on webTransport is not implemented in libp2p js
const bootstrapNode = {
peerId: peerIdFromString(peerId),
getMultiaddrs: () => [multiaddr(peerMultiAddress)]
}
const createNode2 = async () => {
const node = await createLibp2p({
// can't listen using webtransport in libp2p js
// addresses: {listen: []},
peerDiscovery: [
bootstrap({list: bootstrapNode.getMultiaddrs()})
],
transports: [
webTransport(),
webRTCDirect(),
// circuitRelayTransport({discoverRelays: 1}) // TODO: test this later, probably need to upgrade libp2p
],
streamMuxers: [yamux(), mplex()],
connectionEncryption: [noise()],
connectionGater: {
// not sure why needed, doesn't connect without it
denyDialMultiaddr: async () => false,
},
connectionManager: {
maxConnections: 10,
minConnections: 5
},
services: {
identify: identifyService(), // required for peer discovery of pubsub
dht: kadDHT(), // p2p peer discovery
pubsub: gossipsub({
allowPublishToZeroPeers: true,
})
}
})
logEvents('node2', node)
return node
}
const node2 = await createNode2()
// log addresses
log('bootstrapNode', bootstrapNode.getMultiaddrs(), 'node2', node2.getMultiaddrs())
const topic = 'demo'
// sub
node2.services.pubsub.addEventListener('message', (evt) => {
log(`node2: ${evt.detail.from}: ${uint8ArrayToString(evt.detail.data)} on topic ${evt.detail.topic}`)
})
await node2.services.pubsub.subscribe(topic)
// pub
setInterval(() => {
node2.services.pubsub.publish(topic, uint8ArrayFromString(`demo message from node 2 ${node2.peerId}`)).catch(err => {
console.error(err)
})
}, 1000)
} catch (e) {
log(e.stack)
}
})()