mirror of
https://github.com/status-im/nimbus-eth1.git
synced 2025-03-01 04:10:45 +00:00
* aristo: fork support via layers/txframes This change reorganises how the database is accessed: instead holding a "current frame" in the database object, a dag of frames is created based on the "base frame" held in `AristoDbRef` and all database access happens through this frame, which can be thought of as a consistent point-in-time snapshot of the database based on a particular fork of the chain. In the code, "frame", "transaction" and "layer" is used to denote more or less the same thing: a dag of stacked changes backed by the on-disk database. Although this is not a requirement, in practice each frame holds the change set of a single block - as such, the frame and its ancestors leading up to the on-disk state represents the state of the database after that block has been applied. "committing" means merging the changes to its parent frame so that the difference between them is lost and only the cumulative changes remain - this facility enables frames to be combined arbitrarily wherever they are in the dag. In particular, it becomes possible to consolidate a set of changes near the base of the dag and commit those to disk without having to re-do the in-memory frames built on top of them - this is useful for "flattening" a set of changes during a base update and sending those to storage without having to perform a block replay on top. Looking at abstractions, a side effect of this change is that the KVT and Aristo are brought closer together by considering them to be part of the "same" atomic transaction set - the way the code gets organised, applying a block and saving it to the kvt happens in the same "logical" frame - therefore, discarding the frame discards both the aristo and kvt changes at the same time - likewise, they are persisted to disk together - this makes reasoning about the database somewhat easier but has the downside of increased memory usage, something that perhaps will need addressing in the future. Because the code reasons more strictly about frames and the state of the persisted database, it also makes it more visible where ForkedChain should be used and where it is still missing - in particular, frames represent a single branch of history while forkedchain manages multiple parallel forks - user-facing services such as the RPC should use the latter, ie until it has been finalized, a getBlock request should consider all forks and not just the blocks in the canonical head branch. Another advantage of this approach is that `AristoDbRef` conceptually becomes more simple - removing its tracking of the "current" transaction stack simplifies reasoning about what can go wrong since this state now has to be passed around in the form of `AristoTxRef` - as such, many of the tests and facilities in the code that were dealing with "stack inconsistency" are now structurally prevented from happening. The test suite will need significant refactoring after this change. Once this change has been merged, there are several follow-ups to do: * there's no mechanism for keeping frames up to date as they get committed or rolled back - TODO * naming is confused - many names for the same thing for legacy reason * forkedchain support is still missing in lots of code * clean up redundant logic based on previous designs - in particular the debug and introspection code no longer makes sense * the way change sets are stored will probably need revisiting - because it's a stack of changes where each frame must be interrogated to find an on-disk value, with a base distance of 128 we'll at minimum have to perform 128 frame lookups for *every* database interaction - regardless, the "dag-like" nature will stay * dispose and commit are poorly defined and perhaps redundant - in theory, one could simply let the GC collect abandoned frames etc, though it's likely an explicit mechanism will remain useful, so they stay for now More about the changes: * `AristoDbRef` gains a `txRef` field (todo: rename) that "more or less" corresponds to the old `balancer` field * `AristoDbRef.stack` is gone - instead, there's a chain of `AristoTxRef` objects that hold their respective "layer" which has the actual changes * No more reasoning about "top" and "stack" - instead, each `AristoTxRef` can be a "head" that "more or less" corresponds to the old single-history `top` notion and its stack * `level` still represents "distance to base" - it's computed from the parent chain instead of being stored * one has to be careful not to use frames where forkedchain was intended - layers are only for a single branch of history! * fix layer vtop after rollback * engine fix * Fix test_txpool * Fix test_rpc * Fix copyright year * fix simulator * Fix copyright year * Fix copyright year * Fix tracer * Fix infinite recursion bug * Remove aristo and kvt empty files * Fic copyright year * Fix fc chain_kvt * ForkedChain refactoring * Fix merge master conflict * Fix copyright year * Reparent txFrame * Fix test * Fix txFrame reparent again * Cleanup and fix test * UpdateBase bugfix and fix test * Fixe newPayload bug discovered by hive * Fix engine api fcu * Clean up call template, chain_kvt, andn txguid * Fix copyright year * work around base block loading issue * Add test * Fix updateHead bug * Fix updateBase bug * Change func commitBase to proc commitBase * Touch up and fix debug mode crash --------- Co-authored-by: jangko <jangko128@gmail.com>
307 lines
9.3 KiB
Nim
307 lines
9.3 KiB
Nim
# Nimbus
|
|
# Copyright (c) 2018-2025 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) =
|
|
proc writeDataDirId(kvt: CoreDbTxRef, calculatedId: Hash32) =
|
|
info "Writing data dir ID", ID=calculatedId
|
|
kvt.put(dataDirIdKey().toOpenArray, calculatedId.data).isOkOr:
|
|
fatal "Cannot write data dir ID", ID=calculatedId
|
|
quit(QuitFailure)
|
|
|
|
let
|
|
kvt = db.baseTxFrame()
|
|
calculatedId = calcHash(conf.networkId, conf.networkParams)
|
|
dataDirIdBytes = kvt.get(dataDirIdKey().toOpenArray).valueOr:
|
|
# an empty database
|
|
writeDataDirId(kvt, calculatedId)
|
|
return
|
|
|
|
if conf.rewriteDatadirId:
|
|
writeDataDirId(kvt, calculatedId)
|
|
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) =
|
|
|
|
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())
|
|
|
|
## Processing command line arguments
|
|
let conf = makeConfig()
|
|
|
|
setupFileLimits()
|
|
|
|
## Ctrl+C handling
|
|
proc controlCHandler() {.noconv.} =
|
|
when defined(windows):
|
|
# workaround for https://github.com/nim-lang/Nim/issues/4057
|
|
setupForeignThreadGc()
|
|
nimbus.state = NimbusState.Stopping
|
|
notice "\nCtrl+C pressed. Waiting for a graceful shutdown."
|
|
setControlCHook(controlCHandler)
|
|
|
|
nimbus.run(conf)
|