-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathnimbus_execution_client.nim
306 lines (258 loc) · 9.54 KB
/
nimbus_execution_client.nim
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
# Nimbus
# Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
import
../nimbus/compile_info
import
std/[os, osproc, strutils, net],
chronicles,
eth/net/nat,
metrics,
metrics/chronicles_support,
kzg4844/kzg,
stew/byteutils,
./rpc,
./version,
./constants,
./nimbus_desc,
./nimbus_import,
./core/block_import,
./core/eip4844,
./db/core_db/persistent,
./db/storage_types,
./sync/handlers,
./common/chain_config_hash
from beacon_chain/nimbus_binary_common import setupFileLimits
when defined(evmc_enabled):
import transaction/evmc_dynamic_loader
## TODO:
## * No IPv6 support
## * No multiple bind addresses support
## * No database support
proc basicServices(nimbus: NimbusNode,
conf: NimbusConf,
com: CommonRef) =
nimbus.chainRef = ForkedChainRef.init(com)
# txPool must be informed of active head
# so it can know the latest account state
# e.g. sender nonce, etc
nimbus.txPool = TxPoolRef.new(nimbus.chainRef)
nimbus.beaconEngine = BeaconEngineRef.new(nimbus.txPool)
proc manageAccounts(nimbus: NimbusNode, conf: NimbusConf) =
if string(conf.keyStore).len > 0:
let res = nimbus.ctx.am.loadKeystores(string conf.keyStore)
if res.isErr:
fatal "Load keystore error", msg = res.error()
quit(QuitFailure)
if string(conf.importKey).len > 0:
let res = nimbus.ctx.am.importPrivateKey(string conf.importKey)
if res.isErr:
fatal "Import private key error", msg = res.error()
quit(QuitFailure)
proc setupP2P(nimbus: NimbusNode, conf: NimbusConf,
com: CommonRef) =
## Creating P2P Server
let kpres = nimbus.ctx.getNetKeys(conf.netKey, conf.dataDir.string)
if kpres.isErr:
fatal "Get network keys error", msg = kpres.error
quit(QuitFailure)
let keypair = kpres.get()
var address = enode.Address(
ip: conf.listenAddress,
tcpPort: conf.tcpPort,
udpPort: conf.udpPort
)
if conf.nat.hasExtIp:
# any required port redirection is assumed to be done by hand
address.ip = conf.nat.extIp
else:
# automated NAT traversal
let extIP = getExternalIP(conf.nat.nat)
# This external IP only appears in the logs, so don't worry about dynamic
# IPs. Don't remove it either, because the above call does initialisation
# and discovery for NAT-related objects.
if extIP.isSome:
address.ip = extIP.get()
let extPorts = redirectPorts(tcpPort = address.tcpPort,
udpPort = address.udpPort,
description = NimbusName & " " & NimbusVersion)
if extPorts.isSome:
(address.tcpPort, address.udpPort) = extPorts.get()
let bootstrapNodes = conf.getBootNodes()
nimbus.ethNode = newEthereumNode(
keypair, address, conf.networkId, conf.agentString,
addAllCapabilities = false, minPeers = conf.maxPeers,
bootstrapNodes = bootstrapNodes,
bindUdpPort = conf.udpPort, bindTcpPort = conf.tcpPort,
bindIp = conf.listenAddress,
rng = nimbus.ctx.rng)
# Add protocol capabilities
nimbus.ethNode.addEthHandlerCapability(
nimbus.ethNode.peerPool, nimbus.chainRef, nimbus.txPool)
# Always initialise beacon syncer
nimbus.beaconSyncRef = BeaconSyncRef.init(
nimbus.ethNode, nimbus.chainRef, conf.maxPeers, conf.beaconChunkSize)
# Connect directly to the static nodes
let staticPeers = conf.getStaticPeers()
if staticPeers.len > 0:
nimbus.peerManager = PeerManagerRef.new(
nimbus.ethNode.peerPool,
conf.reconnectInterval,
conf.reconnectMaxRetry,
staticPeers
)
nimbus.peerManager.start()
# Start Eth node
if conf.maxPeers > 0:
nimbus.networkLoop = nimbus.ethNode.connectToNetwork(
enableDiscovery = conf.discovery != DiscoveryType.None,
waitForPeers = true)
proc setupMetrics(nimbus: NimbusNode, conf: NimbusConf) =
# metrics logging
if conf.logMetricsEnabled:
# https://github.com/nim-lang/Nim/issues/17369
var logMetrics: proc(udata: pointer) {.gcsafe, raises: [].}
logMetrics = proc(udata: pointer) =
{.gcsafe.}:
let registry = defaultRegistry
info "metrics", registry
discard setTimer(Moment.fromNow(conf.logMetricsInterval.seconds), logMetrics)
discard setTimer(Moment.fromNow(conf.logMetricsInterval.seconds), logMetrics)
# metrics server
if conf.metricsEnabled:
info "Starting metrics HTTP server", address = conf.metricsAddress, port = conf.metricsPort
let res = MetricsHttpServerRef.new($conf.metricsAddress, conf.metricsPort)
if res.isErr:
fatal "Failed to create metrics server", msg=res.error
quit(QuitFailure)
nimbus.metricsServer = res.get
waitFor nimbus.metricsServer.start()
proc preventLoadingDataDirForTheWrongNetwork(db: CoreDbRef; conf: NimbusConf) =
let
kvt = db.ctx.getKvt()
calculatedId = calcHash(conf.networkId, conf.networkParams)
dataDirIdBytes = kvt.get(dataDirIdKey().toOpenArray).valueOr:
# an empty database
info "Writing data dir ID", ID=calculatedId
kvt.put(dataDirIdKey().toOpenArray, calculatedId.data).isOkOr:
fatal "Cannot write data dir ID", ID=calculatedId
quit(QuitFailure)
return
if calculatedId.data != dataDirIdBytes:
fatal "Data dir already initialized with other network configuration",
get=dataDirIdBytes.toHex,
expected=calculatedId
quit(QuitFailure)
proc run*(nimbus: NimbusNode, conf: NimbusConf) =
# ## logging
# setLogLevel(conf.logLevel)
# if conf.logFile.isSome:
# let logFile = string conf.logFile.get()
# defaultChroniclesStream.output.outFile = nil # to avoid closing stdout
# discard defaultChroniclesStream.output.open(logFile, fmAppend)
# setupFileLimits()
# info "Launching execution client", version = FullVersionStr, conf
when defined(evmc_enabled):
evmcSetLibraryPath(conf.evm)
# Trusted setup is needed for processing Cancun+ blocks
# if conf.trustedSetupFile.isSome:
# let fileName = conf.trustedSetupFile.get()
# let res = loadTrustedSetup(fileName, 0)
# if res.isErr:
# fatal "Cannot load Kzg trusted setup from file", msg=res.error
# quit(QuitFailure)
# else:
# let res = loadKzgTrustedSetup()
# if res.isErr:
# fatal "Cannot load baked in Kzg trusted setup", msg=res.error
# quit(QuitFailure)
createDir(string conf.dataDir)
let coreDB =
# Resolve statically for database type
case conf.chainDbMode:
of Aristo,AriPrune:
AristoDbRocks.newCoreDbRef(
string conf.dataDir,
conf.dbOptions(noKeyCache = conf.cmd == NimbusCmd.`import`))
preventLoadingDataDirForTheWrongNetwork(coreDB, conf)
setupMetrics(nimbus, conf)
let taskpool =
try:
if conf.numThreads < 0:
fatal "The number of threads --num-threads cannot be negative."
quit QuitFailure
elif conf.numThreads == 0:
Taskpool.new(numThreads = min(countProcessors(), 16))
else:
Taskpool.new(numThreads = conf.numThreads)
except CatchableError as e:
fatal "Cannot start taskpool", err = e.msg
quit QuitFailure
info "Threadpool started", numThreads = taskpool.numThreads
let com = CommonRef.new(
db = coreDB,
taskpool = taskpool,
pruneHistory = (conf.chainDbMode == AriPrune),
networkId = conf.networkId,
params = conf.networkParams)
if conf.extraData.len > 32:
warn "ExtraData exceeds 32 bytes limit, truncate",
extraData=conf.extraData,
len=conf.extraData.len
if conf.gasLimit > GAS_LIMIT_MAXIMUM or
conf.gasLimit < GAS_LIMIT_MINIMUM:
warn "GasLimit not in expected range, truncate",
min=GAS_LIMIT_MINIMUM,
max=GAS_LIMIT_MAXIMUM,
get=conf.gasLimit
com.extraData = conf.extraData
com.gasLimit = conf.gasLimit
defer:
com.db.finish()
case conf.cmd
of NimbusCmd.`import`:
importBlocks(conf, com)
of NimbusCmd.`import-rlp`:
importRlpBlocks(conf, com)
else:
basicServices(nimbus, conf, com)
manageAccounts(nimbus, conf)
setupP2P(nimbus, conf, com)
setupRpc(nimbus, conf, com)
if conf.maxPeers > 0 and conf.engineApiServerEnabled():
# Not starting syncer if there is definitely no way to run it. This
# avoids polling (i.e. waiting for instructions) and some logging.
if not nimbus.beaconSyncRef.start():
nimbus.beaconSyncRef = BeaconSyncRef(nil)
if nimbus.state == NimbusState.Starting:
# it might have been set to "Stopping" with Ctrl+C
nimbus.state = NimbusState.Running
# Main event loop
while nimbus.state == NimbusState.Running:
try:
poll()
except CatchableError as e:
debug "Exception in poll()", exc = e.name, err = e.msg
discard e # silence warning when chronicles not activated
# Stop loop
waitFor nimbus.stop(conf)
when isMainModule:
var nimbus = NimbusNode(state: NimbusState.Starting, ctx: newEthContext())
## Ctrl+C handling
proc controlCHandler() {.noconv.} =
when defined(windows):
# workaround for https://github.com/nim-lang/Nim/issues/4057
setupForeignThreadGc()
nimbus.state = NimbusState.Stopping
echo "\nCtrl+C pressed. Waiting for a graceful shutdown."
setControlCHook(controlCHandler)
## Show logs on stdout until we get the user's logging choice
discard defaultChroniclesStream.output.open(stdout)
## Processing command line arguments
let conf = makeConfig()
nimbus.run(conf)