forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpt.ts
276 lines (235 loc) · 7.31 KB
/
dpt.ts
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
import ms from 'ms'
import { EventEmitter } from 'events'
import { publicKeyCreate } from 'secp256k1'
import { randomBytes } from 'crypto'
import { debug as createDebugLogger } from 'debug'
import { buffer2int, pk2id } from '../util'
import { KBucket } from './kbucket'
import { BanList } from './ban-list'
import { Server as DPTServer } from './server'
import { DNS } from '../dns'
const debug = createDebugLogger('devp2p:dpt')
export interface PeerInfo {
id?: Uint8Array | Buffer
address?: string
udpPort?: number | null
tcpPort?: number | null
}
export interface DPTOptions {
/**
* Timeout for peer requests
*
* Default: 10s
*/
timeout?: number
/**
* Network info to send a long a request
*
* Default: 0.0.0.0, no UDP or TCP port provided
*/
endpoint?: PeerInfo
/**
* Function for socket creation
*
* Default: dgram-created socket
*/
createSocket?: Function
/**
* Interval for peer table refresh
*
* Default: 60s
*/
refreshInterval?: number
/**
* Toggles whether or not peers should be queried with 'findNeighbours'
* to discover more peers
*
* Default: true
*/
shouldFindNeighbours?: boolean
/**
* Toggles whether or not peers should be discovered by querying EIP-1459 DNS lists
*
* Default: false
*/
shouldGetDnsPeers?: boolean
/**
* Max number of candidate peers to retrieve from DNS records when
* attempting to discover new nodes
*
* Default: 25
*/
dnsRefreshQuantity?: number
/**
* EIP-1459 ENR tree urls to query for peer discovery
*
* Default: (network dependent)
*/
dnsNetworks?: string[]
/**
* DNS server to query DNS TXT records from for peer discovery
*/
dnsAddr?: string
}
export class DPT extends EventEmitter {
privateKey: Buffer
banlist: BanList
dns: DNS
private _id: Buffer | undefined
private _kbucket: KBucket
private _server: DPTServer
private _refreshIntervalId: NodeJS.Timeout
private _refreshIntervalSelectionCounter: number = 0
private _shouldFindNeighbours: boolean
private _shouldGetDnsPeers: boolean
private _dnsRefreshQuantity: number
private _dnsNetworks: string[]
private _dnsAddr: string
constructor(privateKey: Buffer, options: DPTOptions) {
super()
this.privateKey = Buffer.from(privateKey)
this._id = pk2id(Buffer.from(publicKeyCreate(this.privateKey, false)))
this._shouldFindNeighbours = options.shouldFindNeighbours === false ? false : true
this._shouldGetDnsPeers = options.shouldGetDnsPeers ?? false
// By default, tries to connect to 12 new peers every 3s
this._dnsRefreshQuantity = Math.floor((options.dnsRefreshQuantity ?? 25) / 2)
this._dnsNetworks = options.dnsNetworks ?? []
this._dnsAddr = options.dnsAddr ?? '8.8.8.8'
this.dns = new DNS({ dnsServerAddress: this._dnsAddr })
this.banlist = new BanList()
this._kbucket = new KBucket(this._id)
this._kbucket.on('added', (peer: PeerInfo) => this.emit('peer:added', peer))
this._kbucket.on('removed', (peer: PeerInfo) => this.emit('peer:removed', peer))
this._kbucket.on('ping', this._onKBucketPing.bind(this))
this._server = new DPTServer(this, this.privateKey, {
timeout: options.timeout,
endpoint: options.endpoint,
createSocket: options.createSocket,
})
this._server.once('listening', () => this.emit('listening'))
this._server.once('close', () => this.emit('close'))
this._server.on('error', (err) => this.emit('error', err))
// When not using peer neighbour discovery we don't add peers here
// because it results in duplicate calls for the same targets
this._server.on('peers', (peers) => {
if (!this._shouldFindNeighbours) return
this._addPeerBatch(peers)
})
// By default calls refresh every 3s
const refreshIntervalSubdivided = Math.floor((options.refreshInterval ?? ms('60s')) / 10)
this._refreshIntervalId = setInterval(() => this.refresh(), refreshIntervalSubdivided)
}
bind(...args: any[]): void {
this._server.bind(...args)
}
destroy(...args: any[]): void {
clearInterval(this._refreshIntervalId)
this._server.destroy(...args)
}
_onKBucketPing(oldPeers: PeerInfo[], newPeer: PeerInfo): void {
if (this.banlist.has(newPeer)) return
let count = 0
let err: Error | null = null
for (const peer of oldPeers) {
this._server
.ping(peer)
.catch((_err: Error) => {
this.banlist.add(peer, ms('5m'))
this._kbucket.remove(peer)
err = err || _err
})
.then(() => {
if (++count < oldPeers.length) return
if (err === null) this.banlist.add(newPeer, ms('5m'))
else this._kbucket.add(newPeer)
})
}
}
_addPeerBatch(peers: PeerInfo[]): void {
const DIFF_TIME_MS = 200
let ms = 0
for (const peer of peers) {
setTimeout(() => {
this.addPeer(peer).catch((error) => {
this.emit('error', error)
})
}, ms)
ms += DIFF_TIME_MS
}
}
async bootstrap(peer: PeerInfo): Promise<void> {
try {
peer = await this.addPeer(peer)
} catch (error) {
this.emit('error', error)
return
}
if (!this._id) return
if (this._shouldFindNeighbours) {
this._server.findneighbours(peer, this._id)
}
}
async addPeer(obj: PeerInfo): Promise<any> {
if (this.banlist.has(obj)) throw new Error('Peer is banned')
debug(`attempt adding peer ${obj.address}:${obj.udpPort}`)
// check k-bucket first
const peer = this._kbucket.get(obj)
if (peer !== null) return peer
// check that peer is alive
try {
const peer = await this._server.ping(obj)
this.emit('peer:new', peer)
this._kbucket.add(peer)
return peer
} catch (err) {
this.banlist.add(obj, ms('5m'))
throw err
}
}
getPeer(obj: string | Buffer | PeerInfo) {
return this._kbucket.get(obj)
}
getPeers() {
return this._kbucket.getAll()
}
getClosestPeers(id: string) {
return this._kbucket.closest(id)
}
removePeer(obj: any) {
this._kbucket.remove(obj)
}
banPeer(obj: string | Buffer | PeerInfo, maxAge?: number) {
this.banlist.add(obj, maxAge)
this._kbucket.remove(obj)
}
async getDnsPeers(): Promise<PeerInfo[]> {
return this.dns.getPeers(this._dnsRefreshQuantity, this._dnsNetworks)
}
async refresh(): Promise<void> {
if (this._shouldFindNeighbours) {
// Rotating selection counter going in loop from 0..9
this._refreshIntervalSelectionCounter = (this._refreshIntervalSelectionCounter + 1) % 10
const peers = this.getPeers()
debug(
`call .refresh() (selector ${this._refreshIntervalSelectionCounter}) (${peers.length} peers in table)`
)
for (const peer of peers) {
// Randomly distributed selector based on peer ID
// to decide on subdivided execution
const selector = buffer2int((peer.id! as Buffer).slice(0, 1)) % 10
if (selector === this._refreshIntervalSelectionCounter) {
this._server.findneighbours(peer, randomBytes(64))
}
}
}
if (this._shouldGetDnsPeers) {
const dnsPeers = await this.getDnsPeers()
debug(
`.refresh() Adding ${dnsPeers.length} from DNS tree, (${
this.getPeers().length
} current peers in table)`
)
this._addPeerBatch(dnsPeers)
}
}
}