-
Notifications
You must be signed in to change notification settings - Fork 48
/
testnet.js
80 lines (61 loc) · 1.67 KB
/
testnet.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
const DHT = require('.')
module.exports = async function createTestnet (size = 10, opts = {}) {
const swarm = []
const teardown = typeof opts === 'function' ? opts : (opts.teardown ? opts.teardown.bind(opts) : noop)
const host = opts.host || '127.0.0.1'
const port = opts.port || 0
const bootstrap = opts.bootstrap ? [...opts.bootstrap] : []
const bindHost = host === '127.0.0.1' ? '127.0.0.1' : '0.0.0.0'
if (size === 0) return new Testnet(swarm)
const first = new DHT({
ephemeral: false,
firewalled: false,
bootstrap,
port,
host: bindHost
})
await first.fullyBootstrapped()
if (bootstrap.length === 0) bootstrap.push({ host, port: first.address().port })
swarm.push(first)
while (swarm.length < size) {
const node = new DHT({
ephemeral: false,
firewalled: false,
bootstrap,
host: bindHost
})
await node.fullyBootstrapped()
swarm.push(node)
}
const testnet = new Testnet(swarm, bootstrap)
teardown(() => testnet.destroy(), { order: Infinity })
return testnet
}
class Testnet {
constructor (nodes, bootstrap = []) {
this.nodes = nodes
this.bootstrap = bootstrap
}
createNode (opts = {}) {
const node = new DHT({
ephemeral: true,
bootstrap: this.bootstrap,
host: '127.0.0.1',
...opts
})
this.nodes.push(node)
return node
}
async destroy () {
for (const node of this.nodes) {
for (const server of node.listening) await server.close()
}
for (let i = this.nodes.length - 1; i >= 0; i--) {
await this.nodes[i].destroy()
}
}
[Symbol.iterator] () {
return this.nodes[Symbol.iterator]()
}
}
function noop () {}