forked from holepunchto/hyperdht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
569 lines (468 loc) · 14.7 KB
/
index.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const { decode } = require('hypercore-id-encoding')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')
class HyperDHT extends DHT {
constructor (opts, sig, dht_keys, keychain = {}) {
const port = opts.port || 49737
const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
const nodes = opts.nodes || KNOWN_NODES
super({ ...opts, port, bootstrap, nodes, filterNode })
const { router, persistent } = defaultCacheOpts(opts)
this.checkedSigs = [sig]
this.sig = sig
this.keychain = keychain
this.dht_keys = dht_keys
this.defaultKeyPair = dht_keys || createKeyPair(opts.seed)
this.listening = new Set()
this.connectionKeepAlive = opts.connectionKeepAlive === false
? 0
: opts.connectionKeepAlive || 5000
// stats is inherited from dht-rpc so fwd the ones from there
this.stats = { punches: { consistent: 0, random: 0, open: 0 }, ...this.stats }
this._router = new Router(this, router)
this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
this._rawStreams = new RawStreamSet(this)
this._persistent = null
this._validatedLocalAddresses = new Map()
this._lastRandomPunch = 0
this._randomPunchInterval = 20000 // min 20s between random punches...
this._randomPunches = 0
this._randomPunchLimit = 1 // set to one for extra safety for now
this.once('persistent', () => {
this._persistent = new Persistent(this, persistent)
})
this.on('network-change', () => {
for (const server of this.listening) server.refresh()
})
this.on('network-update', () => {
if (!this.online) return
for (const server of this.listening) server.notifyOnline()
})
}
connect (remotePublicKey, opts) {
return connect(this, decode(remotePublicKey), opts)
}
createServer (opts, onconnection) {
if (typeof opts === 'function') return this.createServer({}, opts)
if (opts && opts.onconnection) onconnection = opts.onconnection
const s = new Server(this, opts)
if (onconnection) s.on('connection', onconnection)
return s
}
pool () {
return new ConnectionPool(this)
}
async resume () {
await super.resume()
const resuming = []
for (const server of this.listening) resuming.push(server.resume())
await Promise.allSettled(resuming)
}
async suspend () {
const suspending = []
for (const server of this.listening) suspending.push(server.suspend())
await Promise.allSettled(suspending)
await super.suspend()
await this._rawStreams.clear()
}
async destroy ({ force = false } = {}) {
if (!force) {
const closing = []
for (const server of this.listening) closing.push(server.close())
await Promise.allSettled(closing)
}
this._router.destroy()
if (this._persistent) this._persistent.destroy()
await this._rawStreams.clear()
await this._socketPool.destroy()
await super.destroy()
}
async validateLocalAddresses (addresses) {
const list = []
const socks = []
const waiting = []
for (const addr of addresses) {
const { host } = addr
if (this._validatedLocalAddresses.has(host)) {
if (await this._validatedLocalAddresses.get(host)) {
list.push(addr)
}
continue
}
const sock = this.udx.createSocket()
try {
sock.bind(0, host)
} catch {
this._validatedLocalAddresses.set(host, Promise.resolve(false))
continue
}
socks.push(sock)
// semi terrible heuristic until we proper fix local connections by racing them to the remote...
const promise = new Promise(resolve => {
sock.on('message', () => resolve(true))
setTimeout(() => resolve(false), 500)
sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
})
this._validatedLocalAddresses.set(host, promise)
waiting.push(addr)
}
for (const addr of waiting) {
const { host } = addr
if (this._validatedLocalAddresses.has(host)) {
if (await this._validatedLocalAddresses.get(host)) {
list.push(addr)
}
continue
}
}
for (const sock of socks) await sock.close()
return list
}
findPeer (publicKey, opts = {}) {
const target = opts.hash === false ? publicKey : hash(publicKey)
opts = { ...opts, map: mapFindPeer }
return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
}
lookup (target, opts = {}) {
opts = { ...opts, map: mapLookup }
return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
}
lookupAndUnannounce (target, keyPair, opts = {}) {
const unannounces = []
const dht = this
const userCommit = opts.commit || noop
const signUnannounce = opts.signUnannounce || Persistent.signUnannounce
if (this._persistent !== null) { // unlink self
this._persistent.unannounce(target, keyPair.publicKey)
}
opts = { ...opts, map, commit }
return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
async function commit (reply, dht, query) {
await Promise.all(unannounces) // can never fail, caught below
return userCommit(reply, dht, query)
}
function map (reply) {
const data = mapLookup(reply)
if (!data || !data.token) return data
let found = data.peers.length >= 20
for (let i = 0; !found && i < data.peers.length; i++) {
found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
}
if (!found) return data
if (!data.from.id) return data
unannounces.push(
dht._requestUnannounce(
keyPair,
dht,
target,
data.token,
data.from,
signUnannounce
).catch(safetyCatch)
)
return data
}
}
unannounce (target, keyPair, opts = {}) {
return this.lookupAndUnannounce(target, keyPair, opts).finished()
}
announce (target, keyPair, relayAddresses, opts = {}) {
const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
opts = { ...opts, commit }
return opts.clear
? this.lookupAndUnannounce(target, keyPair, opts)
: this.lookup(target, opts)
function commit (reply, dht) {
return dht._requestAnnounce(
keyPair,
dht,
target,
reply.token,
reply.from,
relayAddresses,
signAnnounce
)
}
}
async immutableGet (target, opts = {}) {
opts = { ...opts, map: mapImmutable }
const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
const check = b4a.allocUnsafe(32)
for await (const node of query) {
const { value } = node
sodium.crypto_generichash(check, value)
if (b4a.equals(check, target)) return node
}
return null
}
async immutablePut (value, opts = {}) {
const target = b4a.allocUnsafe(32)
sodium.crypto_generichash(target, value)
opts = {
...opts,
map: mapImmutable,
commit (reply, dht) {
return dht.request({ token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value }, reply.from)
}
}
const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
await query.finished()
return { hash: target, closestNodes: query.closestNodes }
}
async mutableGet (publicKey, opts = {}) {
let refresh = opts.refresh || null
let signed = null
let result = null
opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }
const target = b4a.allocUnsafe(32)
sodium.crypto_generichash(target, publicKey)
const userSeq = opts.seq || 0
const query = this.query({ target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) }, opts)
const latest = opts.latest !== false
for await (const node of query) {
if (result && node.seq <= result.seq) continue
if (node.seq < userSeq || !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)) continue
if (!latest) return node
if (!result || node.seq > result.seq) result = node
}
return result
function commit (reply, dht) {
if (!signed && result && refresh) {
if (refresh(result)) {
signed = c.encode(m.mutablePutRequest, {
publicKey,
seq: result.seq,
value: result.value,
signature: result.signature
})
} else {
refresh = null
}
}
return signed ? dht.request({ token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed }, reply.from) : Promise.resolve(null)
}
}
async mutablePut (keyPair, value, opts = {}) {
const signMutable = opts.signMutable || Persistent.signMutable
const target = b4a.allocUnsafe(32)
sodium.crypto_generichash(target, keyPair.publicKey)
const seq = opts.seq || 0
const signature = await signMutable(seq, value, keyPair)
const signed = c.encode(m.mutablePutRequest, {
publicKey: keyPair.publicKey,
seq,
value,
signature
})
opts = {
...opts,
map: mapMutable,
commit (reply, dht) {
return dht.request({ token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed }, reply.from)
}
}
// use seq = 0, for the query part here, as we don't care about the actual values
const query = this.query({ target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) }, opts)
await query.finished()
return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
}
onrequest (req) {
switch (req.command) {
case COMMANDS.PEER_HANDSHAKE: {
this._router.onpeerhandshake(req)
return true
}
case COMMANDS.PEER_HOLEPUNCH: {
this._router.onpeerholepunch(req)
return true
}
}
if (this._persistent === null) return false
switch (req.command) {
case COMMANDS.FIND_PEER: {
this._persistent.onfindpeer(req)
return true
}
case COMMANDS.LOOKUP: {
this._persistent.onlookup(req)
return true
}
case COMMANDS.ANNOUNCE: {
this._persistent.onannounce(req)
return true
}
case COMMANDS.UNANNOUNCE: {
this._persistent.onunannounce(req)
return true
}
case COMMANDS.MUTABLE_PUT: {
this._persistent.onmutableput(req)
return true
}
case COMMANDS.MUTABLE_GET: {
this._persistent.onmutableget(req)
return true
}
case COMMANDS.IMMUTABLE_PUT: {
this._persistent.onimmutableput(req)
return true
}
case COMMANDS.IMMUTABLE_GET: {
this._persistent.onimmutableget(req)
return true
}
}
return false
}
static keyPair (seed) {
return createKeyPair(seed)
}
static hash (data) {
return hash(data)
}
static connectRawStream (encryptedStream, rawStream, remoteId) {
const stream = encryptedStream.rawStream
if (!stream.connected) throw STREAM_NOT_CONNECTED()
rawStream.connect(
stream.socket,
remoteId,
stream.remotePort,
stream.remoteHost
)
}
createRawStream (opts) {
return this._rawStreams.add(opts)
}
async _requestAnnounce (keyPair, dht, target, token, from, relayAddresses, sign) {
const ann = {
peer: {
publicKey: keyPair.publicKey,
relayAddresses: relayAddresses || []
},
refresh: null,
signature: null
}
ann.signature = await sign(target, token, from.id, ann, keyPair)
const value = c.encode(m.announce, ann)
return dht.request({
token,
target,
command: COMMANDS.ANNOUNCE,
value
}, from)
}
async _requestUnannounce (keyPair, dht, target, token, from, sign) {
const unann = {
peer: {
publicKey: keyPair.publicKey,
relayAddresses: []
},
signature: null
}
unann.signature = await sign(target, token, from.id, unann, keyPair)
const value = c.encode(m.announce, unann)
return dht.request({
token,
target,
command: COMMANDS.UNANNOUNCE,
value
}, from)
}
}
HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL
module.exports = HyperDHT
function mapLookup (node) {
if (!node.value) return null
try {
return {
token: node.token,
from: node.from,
to: node.to,
peers: c.decode(m.peers, node.value)
}
} catch {
return null
}
}
function mapFindPeer (node) {
if (!node.value) return null
try {
return {
token: node.token,
from: node.from,
to: node.to,
peer: c.decode(m.peer, node.value)
}
} catch {
return null
}
}
function mapImmutable (node) {
if (!node.value) return null
return {
token: node.token,
from: node.from,
to: node.to,
value: node.value
}
}
function mapMutable (node) {
if (!node.value) return null
try {
const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)
return {
token: node.token,
from: node.from,
to: node.to,
seq,
value,
signature
}
} catch {
return null
}
}
function noop () {}
function filterNode (node) {
// always skip these testnet nodes that got mixed in by accident, until they get updated
return !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
!(node.port === 9400 && node.host === '35.233.47.252') && !(node.host === '150.136.142.116')
}
const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes
function defaultCacheOpts (opts) {
const maxSize = opts.maxSize || defaultMaxSize
const maxAge = opts.maxAge || defaultMaxAge
return {
router: {
forwards: { maxSize, maxAge }
},
persistent: {
records: { maxSize, maxAge },
refreshes: { maxSize, maxAge },
mutables: {
maxSize: maxSize / 2 | 0,
maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
},
immutables: {
maxSize: maxSize / 2 | 0,
maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
}
}
}
}