forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer-communication-les.ts
238 lines (204 loc) · 6.53 KB
/
peer-communication-les.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
import { bytesToInt, intToBytes, randomBytes, bytesToHex, hexToBytes } from '@ethereumjs/util'
import { Block, BlockHeader } from '@ethereumjs/block'
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import chalk from 'chalk'
import ms from 'ms'
import * as devp2p from '@ethereumjs/devp2p'
import { ETH, Peer } from '@ethereumjs/devp2p'
const PRIVATE_KEY = randomBytes(32)
const GENESIS_TD = 1
const GENESIS_HASH = hexToBytes(
'0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177'
)
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London })
const bootstrapNodes = common.bootstrapNodes()
const BOOTNODES = bootstrapNodes.map((node: any) => {
return {
address: node.ip,
udpPort: node.port,
tcpPort: node.port,
}
})
const REMOTE_CLIENTID_FILTER = [
'go1.5',
'go1.6',
'go1.7',
'Geth/v1.7',
'quorum',
'pirl',
'ubiq',
'gmc',
'gwhale',
'prichain',
]
// @ts-ignore
const getPeerAddr = (peer: Peer) => `${peer._socket.remoteAddress}:${peer._socket.remotePort}`
// DPT
const dpt = new devp2p.DPT(PRIVATE_KEY, {
refreshInterval: 30000,
endpoint: {
address: '0.0.0.0',
udpPort: null,
tcpPort: null,
},
})
/* eslint-disable no-console */
dpt.events.on('error', (err) => console.error(chalk.red(`DPT error: ${err}`)))
/* eslint-disable @typescript-eslint/no-use-before-define */
// RLPx
const rlpx = new devp2p.RLPx(PRIVATE_KEY, {
dpt,
maxPeers: 25,
capabilities: [devp2p.LES.les4],
common,
remoteClientIdFilter: REMOTE_CLIENTID_FILTER,
})
rlpx.events.on('error', (err) => console.error(chalk.red(`RLPx error: ${err.stack ?? err}`)))
rlpx.events.on('peer:added', (peer) => {
const addr = getPeerAddr(peer)
const les = peer.getProtocols()[0]
const requests: { headers: BlockHeader[]; bodies: any[] } = { headers: [], bodies: [] }
const clientId = peer.getHelloMessage().clientId
console.log(
chalk.green(
`Add peer: ${addr} ${clientId} (les${les.getVersion()}) (total: ${rlpx.getPeers().length})`
)
)
les.sendStatus({
headTd: intToBytes(GENESIS_TD),
headHash: GENESIS_HASH,
headNum: Uint8Array.from([]),
genesisHash: GENESIS_HASH,
announceType: intToBytes(0),
recentTxLookup: intToBytes(1),
forkID: [hexToBytes('0x3b8e0691'), intToBytes(1)],
})
les.events.once('status', (status: LES.Status) => {
const msg = [
Uint8Array.from([]),
[
bytesToInt(status['headNum']),
Uint8Array.from([1]),
Uint8Array.from([]),
Uint8Array.from([1]),
],
]
les.sendMessage(devp2p.LES.MESSAGE_CODES.GET_BLOCK_HEADERS, msg)
})
les.events.on('message', async (code: LES.MESSAGE_CODES, payload: any) => {
switch (code) {
case devp2p.LES.MESSAGE_CODES.BLOCK_HEADERS: {
if (payload[2].length > 1) {
console.log(
`${addr} not more than one block header expected (received: ${payload[2].length})`
)
break
}
const header = BlockHeader.fromValuesArray(payload[2][0], { common })
setTimeout(() => {
les.sendMessage(devp2p.LES.MESSAGE_CODES.GET_BLOCK_BODIES, [
Uint8Array.from([1]),
[header.hash()],
])
requests.bodies.push(header)
}, ms('0.1s'))
break
}
case devp2p.LES.MESSAGE_CODES.BLOCK_BODIES: {
if (payload[2].length !== 1) {
console.log(
`${addr} not more than one block body expected (received: ${payload[2].length})`
)
break
}
const header2 = requests.bodies.shift()
const txs = payload[2][0][0]
const uncleHeaders = payload[2][0][1]
const block = Block.fromValuesArray([header2.raw(), txs, uncleHeaders], { common })
const isValid = await isValidBlock(block)
let isValidPayload = false
if (isValid) {
isValidPayload = true
onNewBlock(block, peer)
break
}
if (!isValidPayload) {
console.log(`${addr} received wrong block body`)
}
break
}
}
})
})
rlpx.events.on('peer:removed', (peer, reasonCode, disconnectWe) => {
const who = disconnectWe === true ? 'we disconnect' : 'peer disconnect'
const total = rlpx.getPeers().length
console.log(
chalk.yellow(
`Remove peer: ${getPeerAddr(peer)} - ${who}, reason: ${peer.getDisconnectPrefix(
reasonCode
)} (${String(reasonCode)}) (total: ${total})`
)
)
})
rlpx.events.on('peer:error', (peer, err) => {
if (err.code === 'ECONNRESET') return
if (err instanceof Error) {
const peerId = peer.getId()
if (peerId !== null) dpt.banPeer(peerId, ms('5m'))
console.error(chalk.red(`Peer error (${getPeerAddr(peer)}): ${err.message}`))
return
}
console.error(chalk.red(`Peer error (${getPeerAddr(peer)}): ${err.stack ?? err}`))
})
// uncomment, if you want accept incoming connections
// rlpx.listen(30303, '0.0.0.0')
// dpt.bind(30303, '0.0.0.0')
for (const bootnode of BOOTNODES) {
dpt.bootstrap(bootnode).catch((err) => {
console.error(chalk.bold.red(`DPT bootstrap error: ${err.stack ?? err}`))
})
}
// connect to local ethereum node (debug)
/*
dpt.addPeer({ address: '127.0.0.1', udpPort: 30303, tcpPort: 30303 })
.then((peer) => {
return rlpx.connect({
id: peer.id,
address: peer.address,
tcpPort: peer.tcpPort,
udpPort: peer.tcpPort
})
})
.catch((err) => console.log(`error on connection to local node: ${err.stack ?? err}`)) */
function onNewBlock(block: Block, peer: Peer) {
const blockHashHex = bytesToHex(block.hash())
const blockNumber = block.header.number
console.log(
`----------------------------------------------------------------------------------------------------------`
)
console.log(`block ${blockNumber} received: ${blockHashHex} (from ${getPeerAddr(peer)})`)
console.log(
`----------------------------------------------------------------------------------------------------------`
)
}
async function isValidBlock(block: Block) {
return (
block.uncleHashIsValid() &&
block.transactions.every(({ isValid }) => isValid()) &&
block.transactionsTrieIsValid()
)
}
setInterval(() => {
const peersCount = dpt.getPeers().length
const openSlots = rlpx._getOpenSlots()
// @ts-ignore
const queueLength = rlpx._peersQueue.length
// @ts-ignore
const queueLength2 = rlpx._peersQueue.filter((o) => o.ts <= Date.now()).length
console.log(
chalk.yellow(
`Total nodes in DPT: ${peersCount}, open slots: ${openSlots}, queue: ${queueLength} / ${queueLength2}`
)
)
}, ms('30s'))