-
Notifications
You must be signed in to change notification settings - Fork 37
/
Connection.js
146 lines (122 loc) · 4.4 KB
/
Connection.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
const { EventEmitter } = require('events')
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const pull = require('pull-stream')
const debug = require('debug')('streamr:connection:connection')
const { callbackToPromise, getAddress } = require('../util')
const Libp2pBundle = require('./Libp2pBundle')
const HANDLER = '/streamr/v1/'
const events = Object.freeze({
READY: 'node:ready',
PEER_DISCOVERED: 'streamr:peer:discovery',
PEER_CONNECTED: 'streamr:peer:connect',
PEER_DISCONNECTED: 'streamr:peer:disconnect',
MESSAGE_SENT: 'streamr:message-sent',
MESSAGE_RECEIVED: 'streamr:message-received'
})
class Connection extends EventEmitter {
constructor(node) {
super()
this.node = node
node.peerInfo.multiaddrs.forEach((ma) => debug('listening on: %s', ma.toString()))
node.handle(HANDLER, (protocol, conn) => this.onReceive(protocol, conn))
node.on('peer:discovery', (peer) => this.emit(events.PEER_DISCOVERED, peer))
node.on('peer:connect', (peer) => {
debug('new connection')
this.emit(events.PEER_CONNECTED, peer)
})
node.on('peer:disconnect', (peer) => this.emit(events.PEER_DISCONNECTED, peer))
}
send(recipient, message) {
debug('sending to the %s, message with data "%s"', recipient instanceof PeerInfo ? getAddress(recipient) : '', message)
this.node.dialProtocol(recipient, HANDLER, (err, conn) => {
if (err) {
throw err
}
pull(pull.values([message]), conn)
this.emit(events.MESSAGE_SENT, {
recipient,
message
})
})
}
async onReceive(protocol, conn) {
try {
const sender = await Connection.getPeerInfo(conn)
pull(
conn,
pull.map((message) => message.toString('utf8')),
pull.drain((message) => {
debug('received from %s, message with data "%s"', sender instanceof PeerInfo ? getAddress(sender) : '', message)
this.emit(events.MESSAGE_RECEIVED, {
sender,
message
})
})
)
} catch (err) {
console.log(err)
}
}
async connect(peerInfo) {
let address = ''
if (typeof peerInfo === 'string') {
address = peerInfo
} else if (PeerInfo.isPeerInfo(peerInfo)) {
// peer.id.toB58String()
address = getAddress(peerInfo)
} else {
throw new Error('not valid PeerId or PeerInfo, or B58Str')
}
if (!this.isConnected(address)) {
await this._dial(address)
debug('connected to %s', address)
}
}
async _dial(address) {
return new Promise((resolve, reject) => this.node.dial(address, (err, peerInfo) => (err ? reject(err) : resolve(peerInfo))))
}
async stop(callback = true) {
return new Promise((resolve, reject) => this.node.stop((err) => (err ? reject(err) : resolve(callback))))
}
isConnected(peerInfo) {
return this.node.peerBook.has(peerInfo)
}
getPeers() {
return this.node.peerBook.getAllArray()
}
static async getPeerInfo(connection) {
return new Promise((resolve, reject) => {
return connection.getPeerInfo((err, peerInfo) => (err ? reject(err) : resolve(peerInfo)))
})
}
}
async function createPeerInfo(host, port, privateKey) {
let peerInfo
if (privateKey) {
const idPeer = await callbackToPromise(PeerId.createFromPrivKey, privateKey)
peerInfo = new PeerInfo(idPeer)
} else {
peerInfo = await callbackToPromise(PeerInfo.create)
}
peerInfo.multiaddrs.add(`/ip4/${host}/tcp/${port}`)
return peerInfo
}
async function startLibp2pNode(host, port, privateKey, isNode) {
const peerInfo = await createPeerInfo(host, port, privateKey)
const node = new Libp2pBundle(peerInfo, isNode)
return new Promise((resolve, reject) => {
node.start((err) => {
if (err) {
reject(err)
}
resolve(node)
})
})
}
module.exports = {
events,
async createConnection(host, port, privateKey, isNode = false) {
return startLibp2pNode(host, port, privateKey, isNode).then((n) => new Connection(n))
}
}