-
Notifications
You must be signed in to change notification settings - Fork 37
/
Connection.js
172 lines (139 loc) · 4.79 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
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
const EventEmitter = require('events').EventEmitter
const Libp2pBundle = require('./Libp2pBundle')
const {
callbackToPromise,
getAddress
} = require('../util')
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const pull = require('pull-stream')
const debug = require('debug')('streamr:connection')
const encoder = require('../helpers/MessageEncoder')
const HANDLER = '/streamr/v1/'
module.exports = class Connection extends EventEmitter {
constructor(host, port, privateKey = '', isNode = false) {
super()
this.host = host
this.port = port
this.privateKey = privateKey
this.status = null
this.isStarted = false
this.createNode(isNode)
this.once('node:ready', () => this.nodeReady())
}
async createNode(isNode) {
let peerInfo
if (this.privateKey) {
const idPeer = await callbackToPromise(PeerId.createFromPrivKey, this.privateKey)
peerInfo = new PeerInfo(idPeer)
} else {
peerInfo = await callbackToPromise(PeerInfo.create)
}
peerInfo.multiaddrs.add(`/ip4/${this.host}/tcp/${this.port}`)
this.node = new Libp2pBundle(peerInfo, isNode)
this.node.handle(HANDLER, (protocol, conn) =>
this.recieve(protocol, conn)
)
this.node.start((err) => {
if (err) {
throw err
}
debug('node has started: %s', this.node.isStarted())
this.isStarted = this.node.isStarted()
this.emit('node:ready')
})
}
isReady() {
return this.node && this.node.isStarted()
}
nodeReady() {
if (!this.isStarted) {
throw new Error('libP2P node is not ready')
}
this.node.peerInfo.multiaddrs.forEach(ma =>
debug('listening on: %s', ma.toString())
)
this.bindEvents()
}
bindEvents() {
debug('binding events')
this.node.on('peer:discovery', (peer) => this.emit('streamr:peer:discovery', peer))
this.node.on('peer:connect', (peer) => {
debug('new connection')
this.emit('streamr:peer:connect', peer)
})
this.node.on('peer:disconnect', (peer) => this.emit('streamr:peer:disconnect', peer))
this.on('streamr:send-message', ({
recipient,
messages
}) => this.send(recipient, message))
}
send(recipient, message) {
const messageDecoded = encoder.decode(message)
debug('sending to the %s, message %s with data "%s"', getAddress(recipient), encoder.getMsgPrefix(messageDecoded.code), JSON.stringify(messageDecoded.data))
this.node.dialProtocol(recipient, HANDLER, (err, conn) => {
if (err) {
throw err
}
pull(pull.values([message]), conn)
this.emit('streamr:message-sent', {
recipient,
message
})
})
}
async recieve(protocol, conn) {
try {
const sender = await this.getPeerInfo(conn)
pull(
conn,
pull.map(message => message.toString('utf8')),
pull.drain(message => {
const messageDecoded = encoder.decode(message)
debug('recieved from %s, message %s with data "%s"', getAddress(sender), encoder.getMsgPrefix(messageDecoded.code), JSON.stringify(messageDecoded.data))
this.emit('streamr:message-recieved', {
sender,
message
})
})
)
} catch (err) {
console.log(err)
}
}
async getPeerInfo(conn) {
return new Promise((resolve, reject) => {
return conn.getPeerInfo((err, peerInfo) => {
return err ? reject(err) : resolve(peerInfo)
})
})
}
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) => {
return this.node.dial(address, (err, peerInfo) => {
return err ? reject(err) : resolve(peerInfo)
})
})
}
isConnected(peerInfo) {
return this.node.peerBook.has(peerInfo)
}
getPeers() {
return this.node.peerBook.getAllArray()
}
}