-
Notifications
You must be signed in to change notification settings - Fork 0
/
dht.js
83 lines (69 loc) · 2.11 KB
/
dht.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
'use strict'
// Dependencies
const DHT = require('bittorrent-dht')
const ed = require('ed25519-supercop')
const _ = require('lodash')
// DHT organizes peers by infohashes
// We just hardcode to the same hash for all nodes
// to find other newschain peer nodes in the DHT
// `echo "newschain" | shasum`
const HASH = '17dde8f2a853f1653a1b6ff948fc5e30e877ebf1'
// Creates a DHT node on dhtPort
// Announces this server as available on the hyperlogPort
// Returns promise that resolves with the dht node
function createDHTNode (dhtPort, hyperlogPort) {
return new Promise((resolve, reject) => {
console.log('Creating DHT node')
const dht = new DHT({ verify: ed.verify })
dht.on('error', (error) => {
console.error(error)
reject(error)
})
// Start listening to the DHT
dht.listen(dhtPort)
dht.once('listening', () => {
console.log('DHT listening on port', dhtPort)
// Anounce ourselves as a peer
const announce = () => dht.announce(HASH, hyperlogPort, (err) => {
if (err) {
console.log('Failed to announce')
console.log(err)
return
}
console.log('Announced to DHT')
})
// Announce immediately and every 5 minutes
announce()
setInterval(announce, 5 * 60 * 1000)
// Return DHT node now that it's ready
resolve(dht)
})
})
}
// Returns a promise resolving with all hyperlog peers
var getPeersPromise = null
function getPeers (dht) {
if (getPeersPromise) return getPeersPromise
getPeersPromise = new Promise((resolve, reject) => {
console.log('Looking up peers')
const peers = []
dht.lookup(HASH, (err, num) => {
if (err) {
getPeersPromise = null
return reject(err)
}
getPeersPromise = null
resolve(_.uniqBy(peers, (p) => p.host + p.port))
})
// When we find a new peer
dht.on('peer', (peer, hash, from) => {
if (hash.toString('hex') !== HASH) {
console.log('wrong hash', hash.toString('hex'))
return
}
peers.push(peer)
})
})
return getPeersPromise
}
module.exports = {createDHTNode, getPeers}