generated from libp2p/js-libp2p-example-fork-go-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
172 lines (152 loc) · 4.57 KB
/
index.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
import { identify, identifyPush } from '@libp2p/identify'
import { ping } from '@libp2p/ping'
import { webRTC } from '@libp2p/webrtc'
import { webSockets } from '@libp2p/websockets'
import * as filters from '@libp2p/websockets/filters'
import { multiaddr, protocols } from '@multiformats/multiaddr'
import { byteStream } from 'it-byte-stream'
import { createLibp2p } from 'libp2p'
import { fromString, toString } from 'uint8arrays'
const WEBRTC_CODE = protocols('webrtc').code
const output = document.getElementById('output')
const sendSection = document.getElementById('send-section')
const appendOutput = (line) => {
const div = document.createElement('div')
div.appendChild(document.createTextNode(line))
output.append(div)
}
const CHAT_PROTOCOL = '/libp2p/examples/chat/1.0.0'
let ma
let chatStream
const node = await createLibp2p({
addresses: {
listen: [
'/p2p-circuit',
'/webrtc'
]
},
transports: [
webSockets({
filter: filters.all
}),
webRTC(),
circuitRelayTransport()
],
connectionEncrypters: [noise()],
streamMuxers: [yamux()],
connectionGater: {
denyDialMultiaddr: () => {
// by default we refuse to dial local addresses from the browser since they
// are usually sent by remote peers broadcasting undialable multiaddrs but
// here we are explicitly connecting to a local node so do not deny dialing
// any discovered address
return false
}
},
services: {
identify: identify(),
identifyPush: identifyPush(),
ping: ping()
}
})
await node.start()
function updateConnList () {
// Update connections list
const connListEls = node.getConnections()
.map((connection) => {
if (connection.remoteAddr.protoCodes().includes(WEBRTC_CODE)) {
ma = connection.remoteAddr
sendSection.style.display = 'block'
}
const el = document.createElement('li')
el.textContent = connection.remoteAddr.toString()
return el
})
document.getElementById('connections').replaceChildren(...connListEls)
}
node.addEventListener('connection:open', (event) => {
updateConnList()
})
node.addEventListener('connection:close', (event) => {
updateConnList()
})
node.addEventListener('self:peer:update', (event) => {
// Update multiaddrs list, only show WebRTC addresses
const multiaddrs = node.getMultiaddrs()
.filter(ma => isWebrtc(ma))
.map((ma) => {
const el = document.createElement('li')
el.textContent = ma.toString()
return el
})
document.getElementById('multiaddrs').replaceChildren(...multiaddrs)
})
node.handle(CHAT_PROTOCOL, async ({ stream }) => {
chatStream = byteStream(stream)
while (true) {
const buf = await chatStream.read()
appendOutput(`Received message '${toString(buf.subarray())}'`)
}
})
const isWebrtc = (ma) => {
return ma.protoCodes().includes(WEBRTC_CODE)
}
window.connect.onclick = async () => {
ma = multiaddr(window.peer.value)
appendOutput(`Dialing '${ma}'`)
const signal = AbortSignal.timeout(5000)
try {
if (isWebrtc(ma)) {
const rtt = await node.services.ping.ping(ma, {
signal
})
appendOutput(`Connected to '${ma}'`)
appendOutput(`RTT to ${ma.getPeerId()} was ${rtt}ms`)
} else {
await node.dial(ma, {
signal
})
appendOutput('Connected to relay')
}
} catch (err) {
if (signal.aborted) {
appendOutput(`Timed out connecting to '${ma}'`)
} else {
appendOutput(`Connecting to '${ma}' failed - ${err.message}`)
}
}
}
window.send.onclick = async () => {
if (chatStream == null) {
appendOutput('Opening chat stream')
const signal = AbortSignal.timeout(5000)
try {
const stream = await node.dialProtocol(ma, CHAT_PROTOCOL, {
signal
})
chatStream = byteStream(stream)
Promise.resolve().then(async () => {
while (true) {
const buf = await chatStream.read()
appendOutput(`Received message '${toString(buf.subarray())}'`)
}
})
} catch (err) {
if (signal.aborted) {
appendOutput('Timed out opening chat stream')
} else {
appendOutput(`Opening chat stream failed - ${err.message}`)
}
return
}
}
const message = window.message.value.toString().trim()
appendOutput(`Sending message '${message}'`)
chatStream.write(fromString(message))
.catch(err => {
appendOutput(`Error sending message - ${err.message}`)
})
}