1 | import EventEmitter from 'events'
|
2 | import { pipe } from 'it-pipe'
|
3 | import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
|
4 | import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
|
5 | import PROTOCOL from './protocol.js'
|
6 |
|
7 | export const emitter = new EventEmitter()
|
8 |
|
9 | export function handle (libp2p) {
|
10 |
|
11 | libp2p.handle(PROTOCOL, handler).catch(err => {
|
12 | if (err.code !== 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED') {
|
13 | console.error(err)
|
14 | }
|
15 | })
|
16 | }
|
17 |
|
18 | export function unhandle (libp2p) {
|
19 | libp2p.unhandle(PROTOCOL, handler)
|
20 | }
|
21 |
|
22 | function handler ({ connection, stream }) {
|
23 | const peerId = connection.remotePeer.toString()
|
24 |
|
25 | pipe(
|
26 | stream,
|
27 | async function (source) {
|
28 | for await (const message of source) {
|
29 | let msg
|
30 |
|
31 | try {
|
32 | msg = JSON.parse(uint8ArrayToString(message))
|
33 | } catch (err) {
|
34 | emitter.emit('warning', err.message)
|
35 | continue
|
36 | }
|
37 |
|
38 | if (peerId !== msg.from.toString()) {
|
39 | emitter.emit('warning', 'no peerid match ' + msg.from)
|
40 | continue
|
41 | }
|
42 |
|
43 | msg.data = uint8ArrayFromString(msg.data, 'hex')
|
44 | msg.seqno = BigInt(msg.seqno)
|
45 |
|
46 | emitter.emit(msg.topic, msg)
|
47 | }
|
48 | }
|
49 | )
|
50 | }
|