UNPKG

1.33 kBJavaScriptView Raw
1import EventEmitter from 'events'
2import { pipe } from 'it-pipe'
3import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
4import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
5import PROTOCOL from './protocol.js'
6
7export const emitter = new EventEmitter()
8
9export function handle (libp2p) {
10 // can only register one handler for the protocol
11 libp2p.handle(PROTOCOL, handler).catch(err => {
12 if (err.code !== 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED') {
13 console.error(err) // eslint-disable-line no-console
14 }
15 })
16}
17
18export function unhandle (libp2p) {
19 libp2p.unhandle(PROTOCOL, handler)
20}
21
22function 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 // early
36 }
37
38 if (peerId !== msg.from.toString()) {
39 emitter.emit('warning', 'no peerid match ' + msg.from)
40 continue // early
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}