-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpex.js
210 lines (174 loc) · 6.76 KB
/
pex.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const { PexBatch } = require('./messages')
const EventEmitter = require('events')
const MAX_AGE = 600
const MAX_PEERS = 50
class PeerExchange extends EventEmitter {
/**
* @param {import('./')} pubsub
*/
constructor(pubsub, maxSize, anytopic = false) {
super()
this.pubsub = pubsub
this.peers = new PeerDict(maxSize || 1000)
/** @type {Array<Buffer>} */
this.topics = []
this.anytopic = !!anytopic
if (this.anytopic) pubsub.sub('pex', (msg, app, peer) => this._onMessage(msg, peer), false)
pubsub.on('subscriber-add', (topic, peer) => this._sendPeers(topic, peer))
pubsub.on('subscriber-remove', (topic, peer) => this.peers.peerUnsubscribed(peer))
}
announce(discoveryKey) {
this.pubsub.pub(toTopic(discoveryKey), encode({ discoveryKey }))
this.pubsub.pub('pex', encode({ discoveryKey }))
}
lookup(discoveryKey) {
this.pubsub.sub(toTopic(discoveryKey), (msg, app, peer) => this._onMessage(msg, peer), false)
this.topics.push(discoveryKey)
}
unannounce(discoveryKey) {
this.pubsub.unsub(toTopic(discoveryKey))
this.topics = this.topics.filter(t => !t.equals(discoveryKey))
}
close() {
this.topics.forEach(t => this.pubsub.unsub(toTopic(discoveryKey)))
this.topics = null
this.peers = null
this.pubsub.peerExchange = null
}
_onMessage(msg, peer) {
try{
const messages = decode(msg)
if(messages.length > MAX_PEERS + 10) {
// likely trying to DoS us
return this.emit('error', new Error('peer sent ' + messages.length + 'messages, dropping that'))
}
for (const pex of messages) {
// sanity checks (TODO: more)
if(! Buffer.isBuffer(pex.discoveryKey) || pex.discoveryKey.length !== 32) {
console.warn('received PEX peer didn`t pass sanity check (discovery key of length ' + pex.discoveryKey.length + ')')
continue
}
const directConnection = !pex.address
if (directConnection) {
pex.address = peer.remoteAddress
pex.publicKey = peer.remotePublicKey
}
this.peers.add(pex, directConnection)
this.emit('peer-received', pex.discoveryKey, {remoteAddress: pex.address, remotePublicKey: pex.publicKey})
if(this.anytopic) {
const recvTopic = toTopic(pex.discoveryKey)
const mytopics = [...this.pubsub.topics.keys()].filter(t => t.startsWith('pex'))
if(!mytopics.includes(recvTopic)) {
this.pubsub.sub(recvTopic, (msg, app, peer) => this._onMessage(msg, peer), false)
}
}
}
} catch (err) {
this.emit('error', err)
}
}
_sendPeers(topic, peer) {
if(topic === 'pex') {
const myTopics = this.topics.map(discoveryKey => {return {discoveryKey}})
this.pubsub.pub('pex', encode(myTopics), peer)
} else {
const discoveryKey = toDiscoveryKey(topic)
const peers = this.peers.get(discoveryKey)
if(this.topics.findIndex(t => t.equals(discoveryKey)) >= 0) {
peers.push({discoveryKey})
}
if (peers.length > 0) {
const msg = encode(peers)
this.pubsub.pub(topic, msg, peer)
}
}
}
}
class Peer {
constructor(peer, directConnection = false) {
this.remoteAddress = peer.remoteAddress
this.remotePublicKey = peer.remotePublicKey
this.lastSeen = directConnection ? (peer.lastSeen || Date.now()) : null
this.topics = new Set()
this.topics.add(toTopic(peer.discoveryKey))
}
seen(discoveryKey) {
if (Buffer.isBuffer(discoveryKey)) discoveryKey = toTopic(discoveryKey)
this.topics.add(discoveryKey)
if (this.lastSeen !== null) this.lastSeen = Date.now()
}
toMessage(discoveryKey) {
return {
discoveryKey,
address: this.remoteAddress,
publicKey: this.remotePublicKey,
lastSeen: this.time()
}
}
unsubscribed() {
this.lastSeen = Date.now()
}
time() {
return (this.lastSeen || Date.now()) / 1000
}
}
class PeerDict {
constructor(maxSize) {
/** @type {Array<Peer>} */
this.peers = []
this.maxSize = maxSize
}
add(peerMsg, directConnection = false) {
const peer = this.peers.find(p => p.remoteAddress === peerMsg.remoteAddress)
if (peer) peer.seen(peerMsg.discoveryKey)
else this.peers.push(new Peer(peerMsg, directConnection))
if (this.peers.length > this.maxSize) this.prune()
}
get(discoveryKey) {
this.prune()
const peers = this.peers.filter(p => p.topics.has(discoveryKey))
if (peers.length > MAX_PEERS) peers.splice(MAX_PEERS)
return peers.map(p => p.toMessage(discoveryKey))
}
prune() {
const now = Date.now() / 1000
this.peers = this.peers.filter(p => now - p.time() < MAX_AGE)
if (this.peers.length > this.maxSize) {
console.log(`peer dict pruning insufficient, randomly remove not directly connected peers (${this.peers.length}/${this.maxSize})`)
for (let i = 0; i < this.peers.length - this.peers.maxSize; i++) {
// randomly delete peers that are not directly connected
const rand = Math.floor(Math.random() * this.peers.length)
if (this.peers[rand].lastSeen !== null) this.peers.splice(rand, 1)
}
}
// in case that didn't help just cut the rest away
if (this.peers.length > this.maxSize) {
console.warn(`random peer dict pruning insufficient, dropping the rest (${this.peers.length}/${this.maxSize})`)
this.peers.splice(this.maxSize)
}
}
peerUnsubscribed(peer) {
const p = this.peers.find(p => p.remoteAddress === peer.remoteAddress)
if (p) p.unsubscribed()
}
}
function toTopic(discoveryKey) {
return 'pex.' + (Buffer.isBuffer(discoveryKey) ? discoveryKey.toString('hex') : discoveryKey)
}
function toDiscoveryKey(topic) {
const hex = topic.substr(4)
return Buffer.from(hex, 'hex')
}
function encode(messages) {
if (!Array.isArray(messages)) messages = [messages]
return PexBatch.encode({ messages })
}
/**
* @param {Buffer} binary
* @returns {Array<{discoveryKey: Buffer, address?: string, publicKey?: Buffer}>}
*/
function decode(binary) {
const batch = PexBatch.decode(binary)
return batch.messages
}
module.exports = PeerExchange