2020-04-24 07:16:11 +00:00
|
|
|
# beacon_chain
|
|
|
|
# Copyright (c) 2018-2020 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
import
|
2019-10-02 12:38:14 +00:00
|
|
|
# Standard library
|
2020-11-27 19:48:33 +00:00
|
|
|
std/[os, tables, strutils, strformat, sequtils, times, math,
|
|
|
|
terminal, osproc, random],
|
2019-10-02 12:38:14 +00:00
|
|
|
|
|
|
|
# Nimble packages
|
2020-08-19 13:12:10 +00:00
|
|
|
stew/[objects, byteutils, endians2, io2], stew/shims/macros,
|
2020-11-27 19:48:33 +00:00
|
|
|
chronos, confutils, metrics, json_rpc/[rpcclient, rpcserver, jsonmarshal],
|
2020-08-24 12:56:45 +00:00
|
|
|
chronicles, bearssl, blscurve,
|
2020-03-16 22:28:54 +00:00
|
|
|
json_serialization/std/[options, sets, net], serialization/errors,
|
2020-07-09 22:08:54 +00:00
|
|
|
|
|
|
|
eth/[keys, async_utils],
|
|
|
|
eth/db/[kvstore, kvstore_sqlite3],
|
|
|
|
eth/p2p/enode, eth/p2p/discoveryv5/[protocol, enr],
|
2019-10-02 12:38:14 +00:00
|
|
|
|
|
|
|
# Local modules
|
2020-10-27 09:00:57 +00:00
|
|
|
./rpc/[beacon_api, config_api, debug_api, event_api, nimbus_api, node_api,
|
|
|
|
validator_api],
|
2020-07-07 23:02:14 +00:00
|
|
|
spec/[datatypes, digest, crypto, beaconstate, helpers, network, presets],
|
2020-11-27 19:48:33 +00:00
|
|
|
spec/[weak_subjectivity, signatures],
|
|
|
|
spec/eth2_apis/beacon_rpc_client,
|
2020-04-05 09:50:31 +00:00
|
|
|
conf, time, beacon_chain_db, validator_pool, extras,
|
2020-09-14 14:26:31 +00:00
|
|
|
attestation_pool, exit_pool, eth2_network, eth2_discovery,
|
2020-09-28 15:19:57 +00:00
|
|
|
beacon_node_common, beacon_node_types, beacon_node_status,
|
2020-10-27 09:00:57 +00:00
|
|
|
block_pools/[chain_dag, quarantine, clearance, block_pools_types],
|
2020-07-02 15:14:11 +00:00
|
|
|
nimbus_binary_common, network_metadata,
|
2020-11-27 19:48:33 +00:00
|
|
|
eth1_monitor, version, ssz/merkleization,
|
2020-06-08 14:56:56 +00:00
|
|
|
sync_protocol, request_manager, keystore_management, interop, statusbar,
|
2020-10-27 11:04:17 +00:00
|
|
|
sync_manager, validator_duties, filepath,
|
|
|
|
validator_slashing_protection, ./eth2_processor
|
2018-11-23 23:58:49 +00:00
|
|
|
|
|
|
|
const
|
2019-10-02 12:38:14 +00:00
|
|
|
hasPrompt = not defined(withoutPrompt)
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
type
|
2020-05-06 13:23:45 +00:00
|
|
|
RpcServer* = RpcHttpServer
|
2020-03-16 22:28:54 +00:00
|
|
|
|
2020-06-05 15:08:50 +00:00
|
|
|
template init(T: type RpcHttpServer, ip: ValidIpAddress, port: Port): T =
|
2020-03-16 22:28:54 +00:00
|
|
|
newRpcHttpServer([initTAddress(ip, port)])
|
2020-02-19 08:58:10 +00:00
|
|
|
|
2019-10-24 06:51:27 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-metrics/blob/master/metrics.md#interop-metrics
|
2020-11-27 22:16:13 +00:00
|
|
|
declareGauge beacon_slot, "Latest slot of the beacon chain state"
|
|
|
|
declareGauge beacon_current_epoch, "Current epoch"
|
2019-09-07 17:48:05 +00:00
|
|
|
|
2020-07-30 14:27:34 +00:00
|
|
|
# Finalization tracking
|
|
|
|
declareGauge finalization_delay,
|
|
|
|
"Epoch delay between scheduled epoch and finalized epoch"
|
|
|
|
|
2020-08-10 18:49:45 +00:00
|
|
|
declareGauge ticks_delay,
|
|
|
|
"How long does to take to run the onSecond loop"
|
|
|
|
|
2019-09-12 01:45:04 +00:00
|
|
|
logScope: topics = "beacnde"
|
|
|
|
|
2020-06-30 13:53:57 +00:00
|
|
|
func enrForkIdFromState(state: BeaconState): ENRForkID =
|
2020-04-15 02:41:22 +00:00
|
|
|
let
|
|
|
|
forkVer = state.fork.current_version
|
|
|
|
forkDigest = compute_fork_digest(forkVer, state.genesis_validators_root)
|
|
|
|
|
|
|
|
ENRForkID(
|
|
|
|
fork_digest: forkDigest,
|
|
|
|
next_fork_version: forkVer,
|
|
|
|
next_fork_epoch: FAR_FUTURE_EPOCH)
|
|
|
|
|
2020-06-29 17:30:19 +00:00
|
|
|
proc init*(T: type BeaconNode,
|
|
|
|
rng: ref BrHmacDrbgContext,
|
2020-08-04 10:35:20 +00:00
|
|
|
conf: BeaconNodeConf,
|
2020-11-24 21:21:47 +00:00
|
|
|
eth1Network: Option[Eth1Network],
|
2020-11-06 21:45:56 +00:00
|
|
|
genesisStateContents: ref string,
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisDepositsSnapshotContents: ref string): Future[BeaconNode] {.async.} =
|
2020-01-17 13:44:01 +00:00
|
|
|
let
|
2020-10-15 11:49:02 +00:00
|
|
|
db = BeaconChainDB.init(conf.runtimePreset, conf.databaseDir)
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
var
|
|
|
|
genesisState, checkpointState: ref BeaconState
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisDepositsSnapshot: DepositContractSnapshot
|
2020-09-22 20:42:42 +00:00
|
|
|
checkpointBlock: SignedBeaconBlock
|
|
|
|
|
|
|
|
if conf.finalizedCheckpointState.isSome:
|
|
|
|
let checkpointStatePath = conf.finalizedCheckpointState.get.string
|
|
|
|
checkpointState = try:
|
|
|
|
newClone(SSZ.loadFile(checkpointStatePath, BeaconState))
|
|
|
|
except SerializationError as err:
|
|
|
|
fatal "Checkpoint state deserialization failed",
|
|
|
|
err = formatMsg(err, checkpointStatePath)
|
|
|
|
quit 1
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to read checkpoint state file", err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
if conf.finalizedCheckpointBlock.isNone:
|
|
|
|
if checkpointState.slot > 0:
|
|
|
|
fatal "Specifying a non-genesis --finalized-checkpoint-state requires specifying --finalized-checkpoint-block as well"
|
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
let checkpointBlockPath = conf.finalizedCheckpointBlock.get.string
|
|
|
|
try:
|
|
|
|
checkpointBlock = SSZ.loadFile(checkpointBlockPath, SignedBeaconBlock)
|
|
|
|
except SerializationError as err:
|
|
|
|
fatal "Invalid checkpoint block", err = err.formatMsg(checkpointBlockPath)
|
|
|
|
quit 1
|
|
|
|
except IOError as err:
|
|
|
|
fatal "Failed to load the checkpoint block", err = err.msg
|
|
|
|
quit 1
|
|
|
|
elif conf.finalizedCheckpointBlock.isSome:
|
|
|
|
# TODO We can download the state from somewhere in the future relying
|
|
|
|
# on the trusted `state_root` appearing in the checkpoint block.
|
|
|
|
fatal "--finalized-checkpoint-block cannot be specified without --finalized-checkpoint-state"
|
|
|
|
quit 1
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-11-16 19:15:43 +00:00
|
|
|
var eth1Monitor: Eth1Monitor
|
2020-07-31 14:49:06 +00:00
|
|
|
if not ChainDAGRef.isInitialized(db):
|
2020-09-22 20:42:42 +00:00
|
|
|
var
|
|
|
|
tailState: ref BeaconState
|
|
|
|
tailBlock: SignedBeaconBlock
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
if genesisStateContents == nil and checkpointState == nil:
|
2020-11-24 21:21:47 +00:00
|
|
|
when hasGenesisDetection:
|
|
|
|
if genesisDepositsSnapshotContents != nil:
|
|
|
|
fatal "A deposits snapshot cannot be provided without also providing a matching beacon state snapshot"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
# This is a fresh start without a known genesis state
|
|
|
|
# (most likely, it hasn't arrived yet). We'll try to
|
|
|
|
# obtain a genesis through the Eth1 deposits monitor:
|
|
|
|
if conf.web3Url.len == 0:
|
|
|
|
fatal "Web3 URL not specified"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
if conf.depositContractAddress.isNone:
|
|
|
|
fatal "Deposit contract address not specified"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
if conf.depositContractDeployedAt.isNone:
|
|
|
|
# When we don't have a known genesis state, the network metadata
|
|
|
|
# must specify the deployment block of the contract.
|
|
|
|
fatal "Deposit contract deployment block not specified"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
# TODO Could move this to a separate "GenesisMonitor" process or task
|
|
|
|
# that would do only this - see Paul's proposal for this.
|
|
|
|
let eth1MonitorRes = await Eth1Monitor.init(
|
|
|
|
db,
|
|
|
|
conf.runtimePreset,
|
|
|
|
conf.web3Url,
|
|
|
|
conf.depositContractAddress.get,
|
|
|
|
conf.depositContractDeployedAt.get,
|
|
|
|
eth1Network)
|
|
|
|
|
|
|
|
if eth1MonitorRes.isErr:
|
|
|
|
fatal "Failed to start Eth1 monitor",
|
|
|
|
reason = eth1MonitorRes.error,
|
|
|
|
web3Url = conf.web3Url,
|
|
|
|
depositContractAddress = conf.depositContractAddress.get,
|
|
|
|
depositContractDeployedAt = conf.depositContractDeployedAt.get
|
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
eth1Monitor = eth1MonitorRes.get
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisState = await eth1Monitor.waitGenesis()
|
|
|
|
if bnStatus == BeaconNodeStatus.Stopping:
|
|
|
|
return nil
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-24 21:21:47 +00:00
|
|
|
tailState = genesisState
|
|
|
|
tailBlock = get_initial_beacon_block(genesisState[])
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-24 21:21:47 +00:00
|
|
|
notice "Eth2 genesis state detected",
|
|
|
|
genesisTime = genesisState.genesisTime,
|
|
|
|
eth1Block = genesisState.eth1_data.block_hash,
|
|
|
|
totalDeposits = genesisState.eth1_data.deposit_count
|
2020-11-12 16:21:04 +00:00
|
|
|
else:
|
2020-11-24 21:21:47 +00:00
|
|
|
fatal "The beacon node must be compiled with -d:has_genesis_detection " &
|
|
|
|
"in order to support monitoring for genesis events"
|
|
|
|
quit 1
|
2019-10-25 14:53:31 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
elif genesisStateContents == nil:
|
|
|
|
if checkpointState.slot == GENESIS_SLOT:
|
|
|
|
genesisState = checkpointState
|
|
|
|
tailState = checkpointState
|
|
|
|
tailBlock = get_initial_beacon_block(genesisState[])
|
|
|
|
else:
|
|
|
|
fatal "State checkpoints cannot be provided for a network without a known genesis state"
|
2020-04-22 23:35:55 +00:00
|
|
|
quit 1
|
2020-09-22 20:42:42 +00:00
|
|
|
else:
|
2020-04-22 23:35:55 +00:00
|
|
|
try:
|
2020-09-22 20:42:42 +00:00
|
|
|
genesisState = newClone(SSZ.decode(genesisStateContents[], BeaconState))
|
|
|
|
except CatchableError as err:
|
2020-11-16 19:15:43 +00:00
|
|
|
raiseAssert "Invalid baked-in state: " & err.msg
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
if checkpointState != nil:
|
|
|
|
tailState = checkpointState
|
|
|
|
tailBlock = checkpointBlock
|
|
|
|
else:
|
|
|
|
tailState = genesisState
|
|
|
|
tailBlock = get_initial_beacon_block(genesisState[])
|
|
|
|
|
|
|
|
try:
|
|
|
|
ChainDAGRef.preInit(db, genesisState[], tailState[], tailBlock)
|
|
|
|
doAssert ChainDAGRef.isInitialized(db), "preInit should have initialized db"
|
|
|
|
except CatchableError as e:
|
|
|
|
error "Failed to initialize database", err = e.msg
|
|
|
|
quit 1
|
2020-07-02 15:52:48 +00:00
|
|
|
|
2020-11-16 19:15:43 +00:00
|
|
|
info "Loading block dag from database", path = conf.databaseDir
|
|
|
|
|
2020-07-07 23:02:14 +00:00
|
|
|
let
|
2020-07-30 19:18:17 +00:00
|
|
|
chainDagFlags = if conf.verifyFinalization: {verifyFinalization}
|
2020-07-07 23:02:14 +00:00
|
|
|
else: {}
|
2020-11-16 19:15:43 +00:00
|
|
|
chainDag = ChainDAGRef.init(conf.runtimePreset, db, chainDagFlags)
|
2020-09-22 20:42:42 +00:00
|
|
|
beaconClock = BeaconClock.init(chainDag.headState.data.data)
|
2020-07-31 14:49:06 +00:00
|
|
|
quarantine = QuarantineRef()
|
2020-11-25 01:09:31 +00:00
|
|
|
databaseGenesisValidatorsRoot =
|
|
|
|
chainDag.headState.data.data.genesis_validators_root
|
|
|
|
|
|
|
|
if genesisStateContents != nil:
|
|
|
|
let
|
|
|
|
networkGenesisValidatorsRoot =
|
2020-11-27 19:48:33 +00:00
|
|
|
extractGenesisValidatorRootFromSnapshop(genesisStateContents[])
|
2020-11-25 01:09:31 +00:00
|
|
|
|
|
|
|
if networkGenesisValidatorsRoot != databaseGenesisValidatorsRoot:
|
|
|
|
fatal "The specified --data-dir contains data for a different network",
|
|
|
|
networkGenesisValidatorsRoot, databaseGenesisValidatorsRoot,
|
|
|
|
dataDir = conf.dataDir
|
|
|
|
quit 1
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
if conf.weakSubjectivityCheckpoint.isSome:
|
|
|
|
let
|
|
|
|
currentSlot = beaconClock.now.slotOrZero
|
|
|
|
isCheckpointStale = not is_within_weak_subjectivity_period(
|
|
|
|
currentSlot,
|
|
|
|
chainDag.headState.data.data,
|
|
|
|
conf.weakSubjectivityCheckpoint.get)
|
|
|
|
|
|
|
|
if isCheckpointStale:
|
|
|
|
error "Weak subjectivity checkpoint is stale",
|
|
|
|
currentSlot,
|
|
|
|
checkpoint = conf.weakSubjectivityCheckpoint.get,
|
|
|
|
headStateSlot = chainDag.headState.data.data.slot
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
if checkpointState != nil:
|
2020-11-25 01:09:31 +00:00
|
|
|
let checkpointGenesisValidatorsRoot = checkpointState[].genesis_validators_root
|
|
|
|
if checkpointGenesisValidatorsRoot != databaseGenesisValidatorsRoot:
|
|
|
|
fatal "The specified checkpoint state is intended for a different network",
|
|
|
|
checkpointGenesisValidatorsRoot, databaseGenesisValidatorsRoot,
|
|
|
|
dataDir = conf.dataDir
|
|
|
|
quit 1
|
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
chainDag.setTailState(checkpointState[], checkpointBlock)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
if eth1Monitor.isNil and
|
2020-03-24 11:13:07 +00:00
|
|
|
conf.web3Url.len > 0 and
|
2020-10-14 14:04:08 +00:00
|
|
|
conf.depositContractAddress.isSome and
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisDepositsSnapshotContents != nil:
|
|
|
|
let genesisDepositsSnapshot = SSZ.decode(genesisDepositsSnapshotContents[],
|
|
|
|
DepositContractSnapshot)
|
2020-11-10 18:41:04 +00:00
|
|
|
# TODO(zah) if we don't have any validators attached,
|
|
|
|
# we don't need a mainchain monitor
|
2020-11-12 16:21:04 +00:00
|
|
|
let eth1MonitorRes = await Eth1Monitor.init(
|
|
|
|
db,
|
|
|
|
conf.runtimePreset,
|
|
|
|
conf.web3Url,
|
|
|
|
conf.depositContractAddress.get,
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisDepositsSnapshot,
|
2020-11-12 16:21:04 +00:00
|
|
|
eth1Network)
|
|
|
|
|
|
|
|
if eth1MonitorRes.isErr:
|
|
|
|
error "Failed to start Eth1 monitor",
|
|
|
|
reason = eth1MonitorRes.error,
|
|
|
|
web3Url = conf.web3Url,
|
|
|
|
depositContractAddress = conf.depositContractAddress.get,
|
|
|
|
depositContractDeployedAt = conf.depositContractDeployedAt.get
|
|
|
|
else:
|
|
|
|
eth1Monitor = eth1MonitorRes.get
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-03-16 22:28:54 +00:00
|
|
|
let rpcServer = if conf.rpcEnabled:
|
|
|
|
RpcServer.init(conf.rpcAddress, conf.rpcPort)
|
|
|
|
else:
|
|
|
|
nil
|
|
|
|
|
2020-04-15 02:41:22 +00:00
|
|
|
let
|
2020-11-16 19:15:43 +00:00
|
|
|
netKeys = getPersistentNetKeys(rng[], conf)
|
|
|
|
nickname = if conf.nodeName == "auto": shortForm(netKeys)
|
|
|
|
else: conf.nodeName
|
2020-07-30 19:18:17 +00:00
|
|
|
enrForkId = enrForkIdFromState(chainDag.headState.data.data)
|
2020-04-15 02:41:22 +00:00
|
|
|
topicBeaconBlocks = getBeaconBlocksTopic(enrForkId.forkDigest)
|
|
|
|
topicAggregateAndProofs = getAggregateAndProofsTopic(enrForkId.forkDigest)
|
2020-08-19 13:12:10 +00:00
|
|
|
network = createEth2Node(rng, conf, netKeys, enrForkId)
|
2020-08-20 16:30:47 +00:00
|
|
|
attestationPool = newClone(AttestationPool.init(chainDag, quarantine))
|
2020-09-14 14:26:31 +00:00
|
|
|
exitPool = newClone(ExitPool.init(chainDag, quarantine))
|
2020-01-17 13:44:01 +00:00
|
|
|
var res = BeaconNode(
|
|
|
|
nickname: nickname,
|
2020-06-29 17:30:19 +00:00
|
|
|
graffitiBytes: if conf.graffiti.isSome: conf.graffiti.get.GraffitiBytes
|
|
|
|
else: defaultGraffitiBytes(),
|
2020-01-17 13:44:01 +00:00
|
|
|
network: network,
|
2020-02-05 20:40:14 +00:00
|
|
|
netKeys: netKeys,
|
2020-01-17 13:44:01 +00:00
|
|
|
db: db,
|
|
|
|
config: conf,
|
2020-07-30 19:18:17 +00:00
|
|
|
chainDag: chainDag,
|
|
|
|
quarantine: quarantine,
|
2020-08-20 16:30:47 +00:00
|
|
|
attestationPool: attestationPool,
|
2020-09-14 14:26:31 +00:00
|
|
|
exitPool: exitPool,
|
2020-11-03 01:21:07 +00:00
|
|
|
eth1Monitor: eth1Monitor,
|
2020-09-22 20:42:42 +00:00
|
|
|
beaconClock: beaconClock,
|
2020-03-16 22:28:54 +00:00
|
|
|
rpcServer: rpcServer,
|
2020-04-15 02:41:22 +00:00
|
|
|
forkDigest: enrForkId.forkDigest,
|
|
|
|
topicBeaconBlocks: topicBeaconBlocks,
|
|
|
|
topicAggregateAndProofs: topicAggregateAndProofs,
|
2020-01-17 13:44:01 +00:00
|
|
|
)
|
2020-08-20 16:30:47 +00:00
|
|
|
|
2020-11-16 19:15:43 +00:00
|
|
|
info "Loading slashing protection database", path = conf.validatorsDir()
|
2020-09-16 11:30:03 +00:00
|
|
|
res.attachedValidators = ValidatorPool.init(
|
|
|
|
SlashingProtectionDB.init(
|
|
|
|
chainDag.headState.data.data.genesis_validators_root,
|
2020-10-06 08:51:33 +00:00
|
|
|
kvStore SqStoreRef.init(conf.validatorsDir(), "slashing_protection").tryGet()
|
2020-09-16 11:30:03 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2020-08-20 16:30:47 +00:00
|
|
|
proc getWallTime(): BeaconTime = res.beaconClock.now()
|
|
|
|
|
|
|
|
res.processor = Eth2Processor.new(
|
2020-09-14 14:26:31 +00:00
|
|
|
conf, chainDag, attestationPool, exitPool, quarantine, getWallTime)
|
2020-08-20 16:30:47 +00:00
|
|
|
|
|
|
|
res.requestManager = RequestManager.init(
|
|
|
|
network, res.processor.blocksQueue)
|
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
if res.config.inProcessValidators:
|
|
|
|
res.addLocalValidators()
|
|
|
|
else:
|
2020-11-07 18:00:31 +00:00
|
|
|
let cmd = getAppDir() / "nimbus_signing_process".addFileExt(ExeExt)
|
2020-09-22 08:27:46 +00:00
|
|
|
let args = [$res.config.validatorsDir, $res.config.secretsDir]
|
|
|
|
let workdir = io2.getCurrentDir().tryGet()
|
|
|
|
res.vcProcess = startProcess(cmd, workdir, args)
|
2020-09-01 13:44:40 +00:00
|
|
|
res.addRemoteValidators()
|
2020-06-11 12:13:12 +00:00
|
|
|
|
|
|
|
# This merely configures the BeaconSync
|
|
|
|
# The traffic will be started when we join the network.
|
2020-07-30 19:18:17 +00:00
|
|
|
network.initBeaconSync(chainDag, enrForkId.forkDigest)
|
2020-01-17 13:44:01 +00:00
|
|
|
return res
|
2019-09-07 17:48:05 +00:00
|
|
|
|
2020-05-13 08:36:33 +00:00
|
|
|
func verifyFinalization(node: BeaconNode, slot: Slot) =
|
|
|
|
# Epoch must be >= 4 to check finalization
|
|
|
|
const SETTLING_TIME_OFFSET = 1'u64
|
|
|
|
let epoch = slot.compute_epoch_at_slot()
|
|
|
|
|
|
|
|
# Don't static-assert this -- if this isn't called, don't require it
|
|
|
|
doAssert SLOTS_PER_EPOCH > SETTLING_TIME_OFFSET
|
|
|
|
|
|
|
|
# Intentionally, loudly assert. Point is to fail visibly and unignorably
|
|
|
|
# during testing.
|
|
|
|
if epoch >= 4 and slot mod SLOTS_PER_EPOCH > SETTLING_TIME_OFFSET:
|
|
|
|
let finalizedEpoch =
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.finalizedHead.slot.compute_epoch_at_slot()
|
2020-05-13 08:36:33 +00:00
|
|
|
# Finalization rule 234, that has the most lag slots among the cases, sets
|
|
|
|
# state.finalized_checkpoint = old_previous_justified_checkpoint.epoch + 3
|
|
|
|
# and then state.slot gets incremented, to increase the maximum offset, if
|
|
|
|
# finalization occurs every slot, to 4 slots vs scheduledSlot.
|
|
|
|
doAssert finalizedEpoch + 4 >= epoch
|
|
|
|
|
2020-08-12 17:48:31 +00:00
|
|
|
proc installAttestationSubnetHandlers(node: BeaconNode, subnets: set[uint8]) =
|
|
|
|
var attestationSubscriptions: seq[Future[void]] = @[]
|
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/p2p-interface.md#attestations-and-aggregation
|
2020-08-12 17:48:31 +00:00
|
|
|
for subnet in subnets:
|
|
|
|
attestationSubscriptions.add(node.network.subscribe(
|
2020-08-20 16:30:47 +00:00
|
|
|
getAttestationTopic(node.forkDigest, subnet)))
|
2020-08-12 17:48:31 +00:00
|
|
|
|
|
|
|
waitFor allFutures(attestationSubscriptions)
|
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/p2p-interface.md#metadata
|
2020-08-12 17:48:31 +00:00
|
|
|
node.network.metadata.seq_number += 1
|
|
|
|
for subnet in subnets:
|
|
|
|
node.network.metadata.attnets[subnet] = true
|
|
|
|
|
|
|
|
proc cycleAttestationSubnets(node: BeaconNode, slot: Slot) =
|
2020-09-15 12:40:43 +00:00
|
|
|
static: doAssert RANDOM_SUBNETS_PER_VALIDATOR == 1
|
|
|
|
|
2020-08-12 17:48:31 +00:00
|
|
|
let epochParity = slot.epoch mod 2
|
|
|
|
var attachedValidators: seq[ValidatorIndex]
|
|
|
|
for validatorIndex in 0 ..< node.chainDag.headState.data.data.validators.len:
|
|
|
|
if node.getAttachedValidator(
|
|
|
|
node.chainDag.headState.data.data, validatorIndex.ValidatorIndex) != nil:
|
|
|
|
attachedValidators.add validatorIndex.ValidatorIndex
|
|
|
|
|
2020-09-15 12:40:43 +00:00
|
|
|
if attachedValidators.len == 0:
|
|
|
|
return
|
|
|
|
|
2020-08-12 17:48:31 +00:00
|
|
|
let (newAttestationSubnets, expiringSubnets, newSubnets) =
|
|
|
|
get_attestation_subnet_changes(
|
|
|
|
node.chainDag.headState.data.data, attachedValidators,
|
|
|
|
node.attestationSubnets, slot.epoch)
|
|
|
|
|
|
|
|
node.attestationSubnets = newAttestationSubnets
|
|
|
|
debug "Attestation subnets",
|
|
|
|
expiring_subnets = expiringSubnets,
|
|
|
|
current_epoch_subnets =
|
|
|
|
node.attestationSubnets.subscribedSubnets[1 - epochParity],
|
|
|
|
upcoming_subnets = node.attestationSubnets.subscribedSubnets[epochParity],
|
|
|
|
new_subnets = newSubnets,
|
|
|
|
stability_subnet = node.attestationSubnets.stabilitySubnet,
|
|
|
|
stability_subnet_expiration_epoch =
|
|
|
|
node.attestationSubnets.stabilitySubnetExpirationEpoch
|
|
|
|
|
|
|
|
block:
|
|
|
|
var unsubscriptions: seq[Future[void]] = @[]
|
|
|
|
for expiringSubnet in expiringSubnets:
|
|
|
|
unsubscriptions.add(node.network.unsubscribe(
|
|
|
|
getAttestationTopic(node.forkDigest, expiringSubnet)))
|
|
|
|
|
|
|
|
waitFor allFutures(unsubscriptions)
|
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/p2p-interface.md#metadata
|
2020-08-12 17:48:31 +00:00
|
|
|
# The race condition window is smaller by placing the fast, local, and
|
|
|
|
# synchronous operation after a variable-latency, asynchronous action.
|
|
|
|
node.network.metadata.seq_number += 1
|
|
|
|
for expiringSubnet in expiringSubnets:
|
|
|
|
node.network.metadata.attnets[expiringSubnet] = false
|
|
|
|
|
|
|
|
node.installAttestationSubnetHandlers(newSubnets)
|
|
|
|
|
|
|
|
block:
|
|
|
|
let subscribed_subnets =
|
|
|
|
node.attestationSubnets.subscribedSubnets[0] +
|
|
|
|
node.attestationSubnets.subscribedSubnets[1] +
|
|
|
|
{node.attestationSubnets.stabilitySubnet.uint8}
|
|
|
|
for subnet in 0'u8 ..< ATTESTATION_SUBNET_COUNT:
|
2020-11-27 14:54:13 +00:00
|
|
|
node.network.metadata.attnets[subnet] = subnet in subscribed_subnets
|
2020-08-12 17:48:31 +00:00
|
|
|
|
2020-08-19 12:42:10 +00:00
|
|
|
proc getAttestationHandlers(node: BeaconNode): Future[void] =
|
|
|
|
var initialSubnets: set[uint8]
|
|
|
|
for i in 0'u8 ..< ATTESTATION_SUBNET_COUNT:
|
|
|
|
initialSubnets.incl i
|
|
|
|
node.installAttestationSubnetHandlers(initialSubnets)
|
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#phase-0-attestation-subnet-stability
|
2020-08-19 12:42:10 +00:00
|
|
|
let wallEpoch = node.beaconClock.now().slotOrZero().epoch
|
|
|
|
node.attestationSubnets.stabilitySubnet = rand(ATTESTATION_SUBNET_COUNT - 1).uint64
|
|
|
|
node.attestationSubnets.stabilitySubnetExpirationEpoch =
|
|
|
|
wallEpoch + getStabilitySubnetLength()
|
|
|
|
|
|
|
|
# Sets the "current" and "future" attestation subnets. One of these gets
|
|
|
|
# replaced by get_attestation_subnet_changes() immediately.
|
|
|
|
node.attestationSubnets.subscribedSubnets[0] = initialSubnets
|
|
|
|
node.attestationSubnets.subscribedSubnets[1] = initialSubnets
|
|
|
|
|
|
|
|
node.network.subscribe(getAggregateAndProofsTopic(node.forkDigest))
|
|
|
|
|
|
|
|
proc addMessageHandlers(node: BeaconNode): Future[void] =
|
|
|
|
allFutures(
|
|
|
|
# As a side-effect, this gets the attestation subnets too.
|
|
|
|
node.network.subscribe(node.topicBeaconBlocks),
|
2020-09-14 14:26:31 +00:00
|
|
|
node.network.subscribe(getAttesterSlashingsTopic(node.forkDigest)),
|
2020-09-24 17:05:49 +00:00
|
|
|
node.network.subscribe(getProposerSlashingsTopic(node.forkDigest)),
|
|
|
|
node.network.subscribe(getVoluntaryExitsTopic(node.forkDigest)),
|
2020-08-19 12:42:10 +00:00
|
|
|
|
|
|
|
node.getAttestationHandlers()
|
|
|
|
)
|
|
|
|
|
2020-09-15 12:40:43 +00:00
|
|
|
func getTopicSubscriptionEnabled(node: BeaconNode): bool =
|
|
|
|
node.attestationSubnets.subscribedSubnets[0].len +
|
|
|
|
node.attestationSubnets.subscribedSubnets[1].len > 0
|
|
|
|
|
|
|
|
proc removeMessageHandlers(node: BeaconNode): Future[void] =
|
|
|
|
node.attestationSubnets.subscribedSubnets[0] = {}
|
|
|
|
node.attestationSubnets.subscribedSubnets[1] = {}
|
|
|
|
doAssert not node.getTopicSubscriptionEnabled()
|
|
|
|
|
|
|
|
var unsubscriptions = mapIt(
|
|
|
|
[getBeaconBlocksTopic(node.forkDigest),
|
|
|
|
getVoluntaryExitsTopic(node.forkDigest),
|
|
|
|
getProposerSlashingsTopic(node.forkDigest),
|
|
|
|
getAttesterSlashingsTopic(node.forkDigest),
|
|
|
|
getAggregateAndProofsTopic(node.forkDigest)],
|
|
|
|
node.network.unsubscribe(it))
|
|
|
|
|
|
|
|
for subnet in 0'u64 ..< ATTESTATION_SUBNET_COUNT:
|
|
|
|
unsubscriptions.add node.network.unsubscribe(
|
|
|
|
getAttestationTopic(node.forkDigest, subnet))
|
|
|
|
|
|
|
|
allFutures(unsubscriptions)
|
|
|
|
|
2020-12-01 10:43:02 +00:00
|
|
|
proc updateGossipStatus(node: BeaconNode, slot: Slot) {.async.} =
|
|
|
|
# Syncing tends to be ~1 block/s, and allow for an epoch of time for libp2p
|
|
|
|
# subscribing to spin up. The faster the sync, the more wallSlot - headSlot
|
|
|
|
# lead time is required
|
|
|
|
const
|
|
|
|
TOPIC_SUBSCRIBE_THRESHOLD_SLOTS = 64
|
|
|
|
HYSTERESIS_BUFFER = 16
|
|
|
|
|
|
|
|
let
|
|
|
|
syncQueueLen = node.syncManager.syncQueueLen
|
|
|
|
topicSubscriptionEnabled = node.getTopicSubscriptionEnabled()
|
|
|
|
if
|
|
|
|
# Don't enable if already enabled; to avoid race conditions requires care,
|
|
|
|
# but isn't crucial, as this condition spuriously fail, but the next time,
|
|
|
|
# should properly succeed.
|
|
|
|
not topicSubscriptionEnabled and
|
|
|
|
# SyncManager forward sync by default runs until maxHeadAge slots, or one
|
|
|
|
# epoch range is achieved. This particular condition has a couple caveats
|
|
|
|
# including that under certain conditions, debtsCount appears to push len
|
|
|
|
# (here, syncQueueLen) to underflow-like values; and even when exactly at
|
|
|
|
# the expected walltime slot the queue isn't necessarily empty. Therefore
|
|
|
|
# TOPIC_SUBSCRIBE_THRESHOLD_SLOTS is not exactly the number of slots that
|
|
|
|
# are left. Furthermore, even when 0 peers are being used, this won't get
|
|
|
|
# to 0 slots in syncQueueLen, but that's a vacuous condition given that a
|
|
|
|
# networking interaction cannot happen under such circumstances.
|
|
|
|
syncQueueLen < TOPIC_SUBSCRIBE_THRESHOLD_SLOTS:
|
|
|
|
# When node.cycleAttestationSubnets() is enabled more properly, integrate
|
|
|
|
# this into the node.cycleAttestationSubnets() call.
|
|
|
|
debug "Enabling topic subscriptions",
|
|
|
|
wallSlot = slot,
|
|
|
|
headSlot = node.chainDag.head.slot,
|
|
|
|
syncQueueLen
|
|
|
|
|
|
|
|
await node.addMessageHandlers()
|
|
|
|
doAssert node.getTopicSubscriptionEnabled()
|
|
|
|
elif
|
|
|
|
topicSubscriptionEnabled and
|
|
|
|
syncQueueLen > TOPIC_SUBSCRIBE_THRESHOLD_SLOTS + HYSTERESIS_BUFFER and
|
|
|
|
# Filter out underflow from debtsCount; plausible queue lengths can't
|
|
|
|
# exceed wallslot, with safety margin.
|
|
|
|
syncQueueLen < 2 * slot.uint64:
|
|
|
|
debug "Disabling topic subscriptions",
|
|
|
|
wallSlot = slot,
|
|
|
|
headSlot = node.chainDag.head.slot,
|
|
|
|
syncQueueLen
|
|
|
|
await node.removeMessageHandlers()
|
|
|
|
|
|
|
|
# Subscription or unsubscription might have occurred; recheck
|
|
|
|
if slot.isEpoch and node.getTopicSubscriptionEnabled:
|
|
|
|
node.cycleAttestationSubnets(slot)
|
|
|
|
|
2020-09-14 14:50:03 +00:00
|
|
|
proc onSlotStart(node: BeaconNode, lastSlot, scheduledSlot: Slot) {.async.} =
|
2019-03-22 15:49:37 +00:00
|
|
|
## Called at the beginning of a slot - usually every slot, but sometimes might
|
|
|
|
## skip a few in case we're running late.
|
2020-06-26 13:51:20 +00:00
|
|
|
## lastSlot: the last slot that we successfully processed, so we know where to
|
2019-03-22 15:49:37 +00:00
|
|
|
## start work from
|
|
|
|
## scheduledSlot: the slot that we were aiming for, in terms of timing
|
|
|
|
let
|
|
|
|
# The slot we should be at, according to the clock
|
2019-08-16 11:16:56 +00:00
|
|
|
beaconTime = node.beaconClock.now()
|
|
|
|
wallSlot = beaconTime.toSlot()
|
2020-07-30 14:27:34 +00:00
|
|
|
finalizedEpoch =
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.finalizedHead.blck.slot.compute_epoch_at_slot()
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2020-11-16 09:44:18 +00:00
|
|
|
if not node.processor[].blockReceivedDuringSlot.finished:
|
|
|
|
node.processor[].blockReceivedDuringSlot.complete()
|
|
|
|
node.processor[].blockReceivedDuringSlot = newFuture[void]()
|
|
|
|
|
2019-12-23 15:34:09 +00:00
|
|
|
info "Slot start",
|
2019-08-15 16:01:55 +00:00
|
|
|
lastSlot = shortLog(lastSlot),
|
|
|
|
scheduledSlot = shortLog(scheduledSlot),
|
2019-09-12 01:45:04 +00:00
|
|
|
beaconTime = shortLog(beaconTime),
|
2020-09-21 16:02:27 +00:00
|
|
|
peers = len(node.network.peerPool),
|
2020-07-30 19:18:17 +00:00
|
|
|
head = shortLog(node.chainDag.head),
|
|
|
|
headEpoch = shortLog(node.chainDag.head.slot.compute_epoch_at_slot()),
|
|
|
|
finalized = shortLog(node.chainDag.finalizedHead.blck),
|
2020-07-30 14:27:34 +00:00
|
|
|
finalizedEpoch = shortLog(finalizedEpoch)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2020-02-17 18:24:14 +00:00
|
|
|
# Check before any re-scheduling of onSlotStart()
|
2020-09-01 13:38:34 +00:00
|
|
|
checkIfShouldStopAtEpoch(scheduledSlot, node.config.stopAtEpoch)
|
2020-02-17 18:24:14 +00:00
|
|
|
|
2019-08-16 11:16:56 +00:00
|
|
|
if not wallSlot.afterGenesis or (wallSlot.slot < lastSlot):
|
2019-12-23 15:34:09 +00:00
|
|
|
let
|
|
|
|
slot =
|
|
|
|
if wallSlot.afterGenesis: wallSlot.slot
|
|
|
|
else: GENESIS_SLOT
|
|
|
|
nextSlot = slot + 1 # At least GENESIS_SLOT + 1!
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
# This can happen if the system clock changes time for example, and it's
|
|
|
|
# pretty bad
|
|
|
|
# TODO shut down? time either was or is bad, and PoS relies on accuracy..
|
|
|
|
warn "Beacon clock time moved back, rescheduling slot actions",
|
2019-08-16 11:16:56 +00:00
|
|
|
beaconTime = shortLog(beaconTime),
|
|
|
|
lastSlot = shortLog(lastSlot),
|
2019-09-12 01:45:04 +00:00
|
|
|
scheduledSlot = shortLog(scheduledSlot),
|
2020-07-16 13:16:51 +00:00
|
|
|
nextSlot = shortLog(nextSlot)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
|
|
|
addTimer(saturate(node.beaconClock.fromNow(nextSlot))) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(slot, nextSlot)
|
|
|
|
|
|
|
|
return
|
|
|
|
|
2019-08-16 11:16:56 +00:00
|
|
|
let
|
|
|
|
slot = wallSlot.slot # afterGenesis == true!
|
|
|
|
nextSlot = slot + 1
|
|
|
|
|
2019-09-07 17:48:05 +00:00
|
|
|
beacon_slot.set slot.int64
|
2020-11-27 22:16:13 +00:00
|
|
|
beacon_current_epoch.set slot.epoch.int64
|
|
|
|
|
2020-07-30 14:27:34 +00:00
|
|
|
finalization_delay.set scheduledSlot.epoch.int64 - finalizedEpoch.int64
|
2019-09-07 17:48:05 +00:00
|
|
|
|
2020-05-13 08:36:33 +00:00
|
|
|
if node.config.verifyFinalization:
|
|
|
|
verifyFinalization(node, scheduledSlot)
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
if slot > lastSlot + SLOTS_PER_EPOCH:
|
|
|
|
# We've fallen behind more than an epoch - there's nothing clever we can
|
|
|
|
# do here really, except skip all the work and try again later.
|
|
|
|
# TODO how long should the period be? Using an epoch because that's roughly
|
|
|
|
# how long attestations remain interesting
|
|
|
|
# TODO should we shut down instead? clearly we're unable to keep up
|
2019-12-23 15:34:09 +00:00
|
|
|
warn "Unable to keep up, skipping ahead",
|
2019-08-15 16:01:55 +00:00
|
|
|
lastSlot = shortLog(lastSlot),
|
|
|
|
slot = shortLog(slot),
|
2019-12-23 15:34:09 +00:00
|
|
|
nextSlot = shortLog(nextSlot),
|
2020-07-16 13:16:51 +00:00
|
|
|
scheduledSlot = shortLog(scheduledSlot)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
|
|
|
addTimer(saturate(node.beaconClock.fromNow(nextSlot))) do (p: pointer):
|
|
|
|
# We pass the current slot here to indicate that work should be skipped!
|
|
|
|
asyncCheck node.onSlotStart(slot, nextSlot)
|
|
|
|
return
|
|
|
|
|
|
|
|
# Whatever we do during the slot, we need to know the head, because this will
|
|
|
|
# give us a state to work with and thus a shuffling.
|
|
|
|
# TODO if the head is very old, that is indicative of something being very
|
|
|
|
# wrong - us being out of sync or disconnected from the network - need
|
|
|
|
# to consider what to do in that case:
|
|
|
|
# * nothing - the other parts of the application will reconnect and
|
|
|
|
# start listening to broadcasts, learn a new head etc..
|
|
|
|
# risky, because the network might stall if everyone does
|
|
|
|
# this, because no blocks will be produced
|
|
|
|
# * shut down - this allows the user to notice and take action, but is
|
|
|
|
# kind of harsh
|
|
|
|
# * keep going - we create blocks and attestations as usual and send them
|
|
|
|
# out - if network conditions improve, fork choice should
|
|
|
|
# eventually select the correct head and the rest will
|
|
|
|
# disappear naturally - risky because user is not aware,
|
|
|
|
# and might lose stake on canonical chain but "just works"
|
|
|
|
# when reconnected..
|
2020-10-28 07:55:36 +00:00
|
|
|
node.processor[].updateHead(slot)
|
2020-04-20 17:28:12 +00:00
|
|
|
|
|
|
|
# Time passes in here..
|
2020-09-11 09:50:00 +00:00
|
|
|
await node.handleValidatorDuties(lastSlot, slot)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
nextSlotStart = saturate(node.beaconClock.fromNow(nextSlot))
|
|
|
|
|
2019-12-23 15:34:09 +00:00
|
|
|
info "Slot end",
|
|
|
|
slot = shortLog(slot),
|
|
|
|
nextSlot = shortLog(nextSlot),
|
2020-07-30 19:18:17 +00:00
|
|
|
head = shortLog(node.chainDag.head),
|
|
|
|
headEpoch = shortLog(node.chainDag.head.slot.compute_epoch_at_slot()),
|
|
|
|
finalizedHead = shortLog(node.chainDag.finalizedHead.blck),
|
|
|
|
finalizedEpoch = shortLog(node.chainDag.finalizedHead.blck.slot.compute_epoch_at_slot())
|
2019-12-23 15:34:09 +00:00
|
|
|
|
2020-12-01 10:43:02 +00:00
|
|
|
await node.updateGossipStatus(slot)
|
2020-08-19 12:42:10 +00:00
|
|
|
|
2020-05-06 10:01:19 +00:00
|
|
|
when declared(GC_fullCollect):
|
|
|
|
# The slots in the beacon node work as frames in a game: we want to make
|
|
|
|
# sure that we're ready for the next one and don't get stuck in lengthy
|
|
|
|
# garbage collection tasks when time is of essence in the middle of a slot -
|
|
|
|
# while this does not guarantee that we'll never collect during a slot, it
|
|
|
|
# makes sure that all the scratch space we used during slot tasks (logging,
|
|
|
|
# temporary buffers etc) gets recycled for the next slot that is likely to
|
|
|
|
# need similar amounts of memory.
|
|
|
|
GC_fullCollect()
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
addTimer(nextSlotStart) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(slot, nextSlot)
|
|
|
|
|
2019-12-02 14:42:57 +00:00
|
|
|
proc handleMissingBlocks(node: BeaconNode) =
|
2020-07-30 19:18:17 +00:00
|
|
|
let missingBlocks = node.quarantine.checkMissing()
|
2019-03-28 14:03:19 +00:00
|
|
|
if missingBlocks.len > 0:
|
2020-10-01 18:56:42 +00:00
|
|
|
debug "Requesting detected missing blocks", blocks = shortLog(missingBlocks)
|
2020-06-18 10:03:36 +00:00
|
|
|
node.requestManager.fetchAncestorBlocks(missingBlocks)
|
2019-12-02 14:42:57 +00:00
|
|
|
|
2020-08-10 18:49:45 +00:00
|
|
|
proc onSecond(node: BeaconNode) =
|
2020-06-03 08:46:29 +00:00
|
|
|
## This procedure will be called once per second.
|
|
|
|
if not(node.syncManager.inProgress):
|
|
|
|
node.handleMissingBlocks()
|
|
|
|
|
|
|
|
proc runOnSecondLoop(node: BeaconNode) {.async.} =
|
2020-08-10 18:49:45 +00:00
|
|
|
let sleepTime = chronos.seconds(1)
|
|
|
|
const nanosecondsIn1s = float(chronos.seconds(1).nanoseconds)
|
2020-06-03 08:46:29 +00:00
|
|
|
while true:
|
|
|
|
let start = chronos.now(chronos.Moment)
|
2020-08-10 18:49:45 +00:00
|
|
|
await chronos.sleepAsync(sleepTime)
|
|
|
|
let afterSleep = chronos.now(chronos.Moment)
|
|
|
|
let sleepTime = afterSleep - start
|
|
|
|
node.onSecond()
|
|
|
|
let finished = chronos.now(chronos.Moment)
|
|
|
|
let processingTime = finished - afterSleep
|
|
|
|
ticks_delay.set(sleepTime.nanoseconds.float / nanosecondsIn1s)
|
2020-10-01 18:56:42 +00:00
|
|
|
trace "onSecond task completed", sleepTime, processingTime
|
2019-03-27 20:17:01 +00:00
|
|
|
|
2020-08-12 09:29:11 +00:00
|
|
|
proc startSyncManager(node: BeaconNode) =
|
2020-06-30 13:53:57 +00:00
|
|
|
func getLocalHeadSlot(): Slot =
|
2020-08-12 09:29:11 +00:00
|
|
|
node.chainDag.head.slot
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-09-14 14:50:03 +00:00
|
|
|
proc getLocalWallSlot(): Slot =
|
2020-10-30 12:33:52 +00:00
|
|
|
node.beaconClock.now().slotOrZero
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-09-14 14:50:03 +00:00
|
|
|
func getFirstSlotAtFinalizedEpoch(): Slot =
|
2020-09-22 20:42:42 +00:00
|
|
|
node.chainDag.finalizedHead.slot
|
2020-06-11 14:20:53 +00:00
|
|
|
|
2020-04-23 15:31:00 +00:00
|
|
|
proc scoreCheck(peer: Peer): bool =
|
2020-05-28 05:02:28 +00:00
|
|
|
if peer.score < PeerScoreLowLimit:
|
2020-08-12 09:29:11 +00:00
|
|
|
false
|
2020-04-23 15:31:00 +00:00
|
|
|
else:
|
2020-08-12 09:29:11 +00:00
|
|
|
true
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-10-27 09:25:28 +00:00
|
|
|
proc onDeletePeer(peer: Peer) =
|
|
|
|
if peer.connectionState notin {Disconnecting, Disconnected}:
|
|
|
|
if peer.score < PeerScoreLowLimit:
|
|
|
|
debug "Peer was removed from PeerPool due to low score", peer = peer,
|
|
|
|
peer_score = peer.score, score_low_limit = PeerScoreLowLimit,
|
|
|
|
score_high_limit = PeerScoreHighLimit
|
|
|
|
asyncSpawn peer.disconnect(PeerScoreLow)
|
|
|
|
else:
|
|
|
|
debug "Peer was removed from PeerPool", peer = peer,
|
|
|
|
peer_score = peer.score, score_low_limit = PeerScoreLowLimit,
|
|
|
|
score_high_limit = PeerScoreHighLimit
|
|
|
|
asyncSpawn peer.disconnect(FaultOrError)
|
|
|
|
|
2020-04-23 15:31:00 +00:00
|
|
|
node.network.peerPool.setScoreCheck(scoreCheck)
|
2020-10-27 09:25:28 +00:00
|
|
|
node.network.peerPool.setOnDeletePeer(onDeletePeer)
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
node.syncManager = newSyncManager[Peer, PeerID](
|
2020-04-20 14:59:18 +00:00
|
|
|
node.network.peerPool, getLocalHeadSlot, getLocalWallSlot,
|
2020-08-20 16:30:47 +00:00
|
|
|
getFirstSlotAtFinalizedEpoch, node.processor.blocksQueue, chunkSize = 32
|
2020-04-20 14:59:18 +00:00
|
|
|
)
|
2020-08-10 07:15:50 +00:00
|
|
|
node.syncManager.start()
|
|
|
|
|
2020-03-16 22:28:54 +00:00
|
|
|
proc connectedPeersCount(node: BeaconNode): int =
|
2020-09-14 14:50:03 +00:00
|
|
|
len(node.network.peerPool)
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
proc installRpcHandlers(rpcServer: RpcServer, node: BeaconNode) =
|
|
|
|
rpcServer.installBeaconApiHandlers(node)
|
2020-10-27 09:00:57 +00:00
|
|
|
rpcServer.installConfigApiHandlers(node)
|
2020-03-16 22:28:54 +00:00
|
|
|
rpcServer.installDebugApiHandlers(node)
|
2020-10-27 09:00:57 +00:00
|
|
|
rpcServer.installEventApiHandlers(node)
|
|
|
|
rpcServer.installNimbusApiHandlers(node)
|
|
|
|
rpcServer.installNodeApiHandlers(node)
|
|
|
|
rpcServer.installValidatorApiHandlers(node)
|
2020-03-16 22:28:54 +00:00
|
|
|
|
2020-08-17 12:07:29 +00:00
|
|
|
proc installMessageValidators(node: BeaconNode) =
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/p2p-interface.md#attestations-and-aggregation
|
2020-08-12 17:48:31 +00:00
|
|
|
# These validators stay around the whole time, regardless of which specific
|
|
|
|
# subnets are subscribed to during any given epoch.
|
2020-03-31 18:39:02 +00:00
|
|
|
for it in 0'u64 ..< ATTESTATION_SUBNET_COUNT.uint64:
|
|
|
|
closureScope:
|
|
|
|
let ci = it
|
2020-08-12 17:48:31 +00:00
|
|
|
node.network.addValidator(
|
2020-08-04 22:43:54 +00:00
|
|
|
getAttestationTopic(node.forkDigest, ci),
|
2020-06-29 18:08:58 +00:00
|
|
|
# This proc needs to be within closureScope; don't lift out of loop.
|
2020-09-18 11:53:09 +00:00
|
|
|
proc(attestation: Attestation): ValidationResult =
|
2020-08-20 16:30:47 +00:00
|
|
|
node.processor[].attestationValidator(attestation, ci))
|
2020-08-12 17:48:31 +00:00
|
|
|
|
2020-08-17 12:07:29 +00:00
|
|
|
node.network.addValidator(
|
|
|
|
getAggregateAndProofsTopic(node.forkDigest),
|
2020-09-18 11:53:09 +00:00
|
|
|
proc(signedAggregateAndProof: SignedAggregateAndProof): ValidationResult =
|
2020-08-20 16:30:47 +00:00
|
|
|
node.processor[].aggregateValidator(signedAggregateAndProof))
|
2020-08-17 12:07:29 +00:00
|
|
|
|
2020-08-20 16:30:47 +00:00
|
|
|
node.network.addValidator(
|
|
|
|
node.topicBeaconBlocks,
|
2020-09-18 11:53:09 +00:00
|
|
|
proc (signedBlock: SignedBeaconBlock): ValidationResult =
|
2020-08-20 16:30:47 +00:00
|
|
|
node.processor[].blockValidator(signedBlock))
|
2020-08-17 12:07:29 +00:00
|
|
|
|
2020-09-14 14:26:31 +00:00
|
|
|
node.network.addValidator(
|
|
|
|
getAttesterSlashingsTopic(node.forkDigest),
|
2020-09-18 11:53:09 +00:00
|
|
|
proc (attesterSlashing: AttesterSlashing): ValidationResult =
|
2020-09-14 14:26:31 +00:00
|
|
|
node.processor[].attesterSlashingValidator(attesterSlashing))
|
|
|
|
|
|
|
|
node.network.addValidator(
|
|
|
|
getProposerSlashingsTopic(node.forkDigest),
|
2020-09-18 11:53:09 +00:00
|
|
|
proc (proposerSlashing: ProposerSlashing): ValidationResult =
|
2020-09-14 14:26:31 +00:00
|
|
|
node.processor[].proposerSlashingValidator(proposerSlashing))
|
|
|
|
|
|
|
|
node.network.addValidator(
|
|
|
|
getVoluntaryExitsTopic(node.forkDigest),
|
2020-09-24 17:05:49 +00:00
|
|
|
proc (signedVoluntaryExit: SignedVoluntaryExit): ValidationResult =
|
|
|
|
node.processor[].voluntaryExitValidator(signedVoluntaryExit))
|
2020-09-14 14:26:31 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
proc stop*(node: BeaconNode) =
|
2020-09-28 15:19:57 +00:00
|
|
|
bnStatus = BeaconNodeStatus.Stopping
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Graceful shutdown"
|
2020-09-01 13:44:40 +00:00
|
|
|
if not node.config.inProcessValidators:
|
|
|
|
node.vcProcess.close()
|
2020-05-19 18:57:35 +00:00
|
|
|
waitFor node.network.stop()
|
2020-11-20 13:23:55 +00:00
|
|
|
node.attachedValidators.slashingProtection.close()
|
2020-09-12 05:35:58 +00:00
|
|
|
node.db.close()
|
2020-11-20 13:23:55 +00:00
|
|
|
notice "Databases closed"
|
2020-05-19 18:57:35 +00:00
|
|
|
|
2020-05-14 11:19:10 +00:00
|
|
|
proc run*(node: BeaconNode) =
|
2020-09-28 15:19:57 +00:00
|
|
|
if bnStatus == BeaconNodeStatus.Starting:
|
2020-05-19 18:57:35 +00:00
|
|
|
# it might have been set to "Stopping" with Ctrl+C
|
2020-09-28 15:19:57 +00:00
|
|
|
bnStatus = BeaconNodeStatus.Running
|
2020-05-19 18:57:35 +00:00
|
|
|
|
|
|
|
if node.rpcServer != nil:
|
|
|
|
node.rpcServer.installRpcHandlers(node)
|
|
|
|
node.rpcServer.start()
|
|
|
|
|
2020-08-17 12:07:29 +00:00
|
|
|
node.installMessageValidators()
|
2020-05-14 11:19:10 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
let
|
2020-05-22 17:04:52 +00:00
|
|
|
curSlot = node.beaconClock.now().slotOrZero()
|
2020-05-19 18:57:35 +00:00
|
|
|
nextSlot = curSlot + 1 # No earlier than GENESIS_SLOT + 1
|
|
|
|
fromNow = saturate(node.beaconClock.fromNow(nextSlot))
|
|
|
|
|
|
|
|
info "Scheduling first slot action",
|
|
|
|
beaconTime = shortLog(node.beaconClock.now()),
|
|
|
|
nextSlot = shortLog(nextSlot),
|
2020-07-16 13:16:51 +00:00
|
|
|
fromNow = shortLog(fromNow)
|
2020-05-14 11:19:10 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
addTimer(fromNow) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(curSlot, nextSlot)
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
node.onSecondLoop = runOnSecondLoop(node)
|
2020-08-20 16:30:47 +00:00
|
|
|
node.blockProcessingLoop = node.processor.runQueueProcessingLoop()
|
2019-03-27 20:17:01 +00:00
|
|
|
|
2020-06-18 10:03:36 +00:00
|
|
|
node.requestManager.start()
|
2020-08-12 09:29:11 +00:00
|
|
|
node.startSyncManager()
|
2020-06-18 10:03:36 +00:00
|
|
|
|
2020-12-01 10:43:02 +00:00
|
|
|
waitFor node.addMessageHandlers()
|
|
|
|
doAssert node.getTopicSubscriptionEnabled()
|
|
|
|
|
2020-11-02 18:02:27 +00:00
|
|
|
## Ctrl+C handling
|
|
|
|
proc controlCHandler() {.noconv.} =
|
|
|
|
when defined(windows):
|
|
|
|
# workaround for https://github.com/nim-lang/Nim/issues/4057
|
|
|
|
setupForeignThreadGc()
|
|
|
|
notice "Shutting down after having received SIGINT"
|
|
|
|
bnStatus = BeaconNodeStatus.Stopping
|
|
|
|
setControlCHook(controlCHandler)
|
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
# main event loop
|
2020-09-28 15:19:57 +00:00
|
|
|
while bnStatus == BeaconNodeStatus.Running:
|
2020-05-19 18:57:35 +00:00
|
|
|
try:
|
|
|
|
poll()
|
|
|
|
except CatchableError as e:
|
|
|
|
debug "Exception in poll()", exc = e.name, err = e.msg
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
# time to say goodbye
|
|
|
|
node.stop()
|
2018-11-23 23:58:49 +00:00
|
|
|
|
2018-12-19 12:58:53 +00:00
|
|
|
var gPidFile: string
|
|
|
|
proc createPidFile(filename: string) =
|
2019-07-07 09:53:58 +00:00
|
|
|
writeFile filename, $os.getCurrentProcessId()
|
2018-12-19 12:58:53 +00:00
|
|
|
gPidFile = filename
|
2020-08-19 13:12:10 +00:00
|
|
|
addQuitProc proc {.noconv.} = discard io2.removeFile(gPidFile)
|
|
|
|
|
2020-06-11 12:13:12 +00:00
|
|
|
proc initializeNetworking(node: BeaconNode) {.async.} =
|
2020-11-16 19:15:43 +00:00
|
|
|
info "Listening to incoming network requests"
|
2020-08-03 17:35:27 +00:00
|
|
|
await node.network.startListening()
|
2020-06-11 12:13:12 +00:00
|
|
|
|
2020-06-19 17:42:28 +00:00
|
|
|
let addressFile = node.config.dataDir / "beacon_node.enr"
|
2020-06-11 12:13:12 +00:00
|
|
|
writeFile(addressFile, node.network.announcedENR.toURI)
|
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
await node.network.start()
|
2020-06-11 12:13:12 +00:00
|
|
|
|
2019-11-25 12:47:29 +00:00
|
|
|
proc start(node: BeaconNode) =
|
|
|
|
let
|
2020-07-30 19:18:17 +00:00
|
|
|
head = node.chainDag.head
|
|
|
|
finalizedHead = node.chainDag.finalizedHead
|
2020-06-29 05:34:48 +00:00
|
|
|
genesisTime = node.beaconClock.fromNow(toBeaconTime(Slot 0))
|
2020-06-11 12:13:12 +00:00
|
|
|
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Starting beacon node",
|
2019-11-12 00:05:35 +00:00
|
|
|
version = fullVersionStr,
|
2020-11-16 19:15:43 +00:00
|
|
|
enr = node.network.announcedENR.toURI,
|
|
|
|
peerId = $node.network.switch.peerInfo.peerId,
|
2019-08-16 11:16:56 +00:00
|
|
|
timeSinceFinalization =
|
2020-11-16 19:15:43 +00:00
|
|
|
node.beaconClock.now() - finalizedHead.slot.toBeaconTime(),
|
2020-07-28 13:54:32 +00:00
|
|
|
head = shortLog(head),
|
2020-07-16 13:16:51 +00:00
|
|
|
finalizedHead = shortLog(finalizedHead),
|
2019-03-20 11:52:30 +00:00
|
|
|
SLOTS_PER_EPOCH,
|
|
|
|
SECONDS_PER_SLOT,
|
2019-09-12 01:45:04 +00:00
|
|
|
SPEC_VERSION,
|
2020-11-16 19:15:43 +00:00
|
|
|
dataDir = node.config.dataDir.string,
|
|
|
|
validators = node.attachedValidators.count
|
2019-03-20 11:52:30 +00:00
|
|
|
|
2020-06-29 05:34:48 +00:00
|
|
|
if genesisTime.inFuture:
|
|
|
|
notice "Waiting for genesis", genesisIn = genesisTime.offset
|
|
|
|
|
2020-06-11 12:13:12 +00:00
|
|
|
waitFor node.initializeNetworking()
|
2020-11-12 16:21:04 +00:00
|
|
|
|
2020-11-24 21:21:47 +00:00
|
|
|
if node.eth1Monitor != nil and node.attachedValidators.count > 0:
|
2020-11-12 16:21:04 +00:00
|
|
|
node.eth1Monitor.start()
|
|
|
|
|
2019-03-20 11:52:30 +00:00
|
|
|
node.run()
|
|
|
|
|
2019-10-03 01:51:44 +00:00
|
|
|
func formatGwei(amount: uint64): string =
|
|
|
|
# TODO This is implemented in a quite a silly way.
|
|
|
|
# Better routines for formatting decimal numbers
|
|
|
|
# should exists somewhere else.
|
|
|
|
let
|
|
|
|
eth = amount div 1000000000
|
|
|
|
remainder = amount mod 1000000000
|
|
|
|
|
|
|
|
result = $eth
|
|
|
|
if remainder != 0:
|
|
|
|
result.add '.'
|
2020-12-01 18:08:55 +00:00
|
|
|
let remainderStr = $remainder
|
|
|
|
for i in remainderStr.len ..< 9:
|
|
|
|
result.add '0'
|
|
|
|
result.add remainderStr
|
2019-10-03 01:51:44 +00:00
|
|
|
while result[^1] == '0':
|
|
|
|
result.setLen(result.len - 1)
|
|
|
|
|
2019-10-02 12:38:14 +00:00
|
|
|
when hasPrompt:
|
|
|
|
from unicode import Rune
|
2020-06-23 19:11:07 +00:00
|
|
|
import prompt
|
2019-10-02 12:38:14 +00:00
|
|
|
|
2020-06-30 13:53:57 +00:00
|
|
|
func providePromptCompletions*(line: seq[Rune], cursorPos: int): seq[string] =
|
2019-10-02 12:38:14 +00:00
|
|
|
# TODO
|
|
|
|
# The completions should be generated with the general-purpose command-line
|
|
|
|
# parsing API of Confutils
|
|
|
|
result = @[]
|
|
|
|
|
2019-10-03 01:51:44 +00:00
|
|
|
proc processPromptCommands(p: ptr Prompt) {.thread.} =
|
|
|
|
while true:
|
|
|
|
var cmd = p[].readLine()
|
|
|
|
case cmd
|
|
|
|
of "quit":
|
|
|
|
quit 0
|
|
|
|
else:
|
|
|
|
p[].writeLine("Unknown command: " & cmd)
|
2019-10-02 12:38:14 +00:00
|
|
|
|
2019-10-03 01:51:44 +00:00
|
|
|
proc initPrompt(node: BeaconNode) =
|
2019-10-28 23:04:52 +00:00
|
|
|
if isatty(stdout) and node.config.statusBarEnabled:
|
2019-10-03 01:51:44 +00:00
|
|
|
enableTrueColors()
|
|
|
|
|
|
|
|
# TODO: nim-prompt seems to have threading issues at the moment
|
|
|
|
# which result in sporadic crashes. We should introduce a
|
|
|
|
# lock that guards the access to the internal prompt line
|
|
|
|
# variable.
|
|
|
|
#
|
|
|
|
# var p = Prompt.init("nimbus > ", providePromptCompletions)
|
|
|
|
# p.useHistoryFile()
|
|
|
|
|
|
|
|
proc dataResolver(expr: string): string =
|
2020-07-30 19:18:17 +00:00
|
|
|
template justified: untyped = node.chainDag.head.atEpochStart(
|
|
|
|
node.chainDag.headState.data.data.current_justified_checkpoint.epoch)
|
2019-10-03 01:51:44 +00:00
|
|
|
# TODO:
|
|
|
|
# We should introduce a general API for resolving dot expressions
|
|
|
|
# such as `db.latest_block.slot` or `metrics.connected_peers`.
|
|
|
|
# Such an API can be shared between the RPC back-end, CLI tools
|
|
|
|
# such as ncli, a potential GraphQL back-end and so on.
|
|
|
|
# The status bar feature would allow the user to specify an
|
|
|
|
# arbitrary expression that is resolvable through this API.
|
|
|
|
case expr.toLowerAscii
|
|
|
|
of "connected_peers":
|
2020-03-16 22:28:54 +00:00
|
|
|
$(node.connectedPeersCount)
|
2019-10-03 01:51:44 +00:00
|
|
|
|
2020-06-08 16:04:11 +00:00
|
|
|
of "head_root":
|
2020-07-30 19:18:17 +00:00
|
|
|
shortLog(node.chainDag.head.root)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "head_epoch":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.head.slot.epoch)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "head_epoch_slot":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.head.slot mod SLOTS_PER_EPOCH)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "head_slot":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.head.slot)
|
2020-06-08 16:04:11 +00:00
|
|
|
|
|
|
|
of "justifed_root":
|
2020-07-28 13:54:32 +00:00
|
|
|
shortLog(justified.blck.root)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "justifed_epoch":
|
2020-07-28 13:54:32 +00:00
|
|
|
$(justified.slot.epoch)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "justifed_epoch_slot":
|
2020-07-28 13:54:32 +00:00
|
|
|
$(justified.slot mod SLOTS_PER_EPOCH)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "justifed_slot":
|
2020-07-28 13:54:32 +00:00
|
|
|
$(justified.slot)
|
2020-06-08 16:04:11 +00:00
|
|
|
|
|
|
|
of "finalized_root":
|
2020-07-30 19:18:17 +00:00
|
|
|
shortLog(node.chainDag.finalizedHead.blck.root)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "finalized_epoch":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.finalizedHead.slot.epoch)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "finalized_epoch_slot":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.finalizedHead.slot mod SLOTS_PER_EPOCH)
|
2020-06-08 16:04:11 +00:00
|
|
|
of "finalized_slot":
|
2020-07-30 19:18:17 +00:00
|
|
|
$(node.chainDag.finalizedHead.slot)
|
2019-10-07 08:29:39 +00:00
|
|
|
|
|
|
|
of "epoch":
|
2020-06-08 16:04:11 +00:00
|
|
|
$node.currentSlot.epoch
|
2019-10-07 08:29:39 +00:00
|
|
|
|
|
|
|
of "epoch_slot":
|
2020-06-08 16:04:11 +00:00
|
|
|
$(node.currentSlot mod SLOTS_PER_EPOCH)
|
2019-10-07 08:29:39 +00:00
|
|
|
|
2019-10-29 19:48:32 +00:00
|
|
|
of "slot":
|
2020-03-16 22:28:54 +00:00
|
|
|
$node.currentSlot
|
2019-10-29 19:48:32 +00:00
|
|
|
|
2020-06-08 16:04:11 +00:00
|
|
|
of "slots_per_epoch":
|
|
|
|
$SLOTS_PER_EPOCH
|
|
|
|
|
2019-10-07 08:29:39 +00:00
|
|
|
of "slot_trailing_digits":
|
2020-06-08 16:04:11 +00:00
|
|
|
var slotStr = $node.currentSlot
|
2019-10-07 08:29:39 +00:00
|
|
|
if slotStr.len > 3: slotStr = slotStr[^3..^1]
|
|
|
|
slotStr
|
2019-10-03 01:51:44 +00:00
|
|
|
|
|
|
|
of "attached_validators_balance":
|
2020-11-29 21:35:39 +00:00
|
|
|
formatGwei(node.attachedValidatorBalanceTotal)
|
2019-10-03 01:51:44 +00:00
|
|
|
|
2020-09-11 12:46:01 +00:00
|
|
|
of "sync_status":
|
|
|
|
if isNil(node.syncManager):
|
|
|
|
"pending"
|
|
|
|
else:
|
|
|
|
if node.syncManager.inProgress:
|
|
|
|
node.syncManager.syncStatus
|
|
|
|
else:
|
|
|
|
"synced"
|
2019-10-03 01:51:44 +00:00
|
|
|
else:
|
|
|
|
# We ignore typos for now and just render the expression
|
|
|
|
# as it was written. TODO: come up with a good way to show
|
|
|
|
# an error message to the user.
|
|
|
|
"$" & expr
|
|
|
|
|
|
|
|
var statusBar = StatusBarView.init(
|
2019-10-28 23:04:52 +00:00
|
|
|
node.config.statusBarContents,
|
2019-10-03 01:51:44 +00:00
|
|
|
dataResolver)
|
2019-10-02 12:38:14 +00:00
|
|
|
|
2019-10-29 01:22:06 +00:00
|
|
|
when compiles(defaultChroniclesStream.output.writer):
|
|
|
|
defaultChroniclesStream.output.writer =
|
2020-09-14 14:50:03 +00:00
|
|
|
proc (logLevel: LogLevel, msg: LogOutputStr) {.raises: [Defect].} =
|
2020-04-22 05:53:02 +00:00
|
|
|
try:
|
|
|
|
# p.hidePrompt
|
|
|
|
erase statusBar
|
|
|
|
# p.writeLine msg
|
|
|
|
stdout.write msg
|
|
|
|
render statusBar
|
|
|
|
# p.showPrompt
|
|
|
|
except Exception as e: # render raises Exception
|
2020-03-24 11:13:07 +00:00
|
|
|
logLoggingFailure(cstring(msg), e)
|
2019-10-03 01:51:44 +00:00
|
|
|
|
|
|
|
proc statusBarUpdatesPollingLoop() {.async.} =
|
|
|
|
while true:
|
|
|
|
update statusBar
|
2020-11-25 21:56:52 +00:00
|
|
|
erase statusBar
|
|
|
|
render statusBar
|
2019-11-25 12:47:29 +00:00
|
|
|
await sleepAsync(chronos.seconds(1))
|
2019-10-03 01:51:44 +00:00
|
|
|
|
|
|
|
traceAsyncErrors statusBarUpdatesPollingLoop()
|
|
|
|
|
|
|
|
# var t: Thread[ptr Prompt]
|
|
|
|
# createThread(t, processPromptCommands, addr p)
|
2019-10-02 12:38:14 +00:00
|
|
|
|
2020-11-27 19:48:33 +00:00
|
|
|
proc handleValidatorExitCommand(config: BeaconNodeConf) {.async.} =
|
|
|
|
let port = try:
|
|
|
|
let value = parseInt(config.rpcUrlForExit.port)
|
|
|
|
if value < Port.low.int or value > Port.high.int:
|
|
|
|
raise newException(ValueError,
|
|
|
|
"The port number must be between " & $Port.low & " and " & $Port.high)
|
|
|
|
Port value
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Invalid port number", err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let rpcClient = newRpcHttpClient()
|
|
|
|
|
|
|
|
try:
|
|
|
|
await connect(rpcClient, config.rpcUrlForExit.hostname, port)
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to connect to the beacon node RPC service", err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let (validator, validatorIdx, status, balance) = try:
|
|
|
|
await rpcClient.get_v1_beacon_states_stateId_validators_validatorId(
|
|
|
|
"head", config.exitedValidator)
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to obtain information for validator", err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let exitAtEpoch = if config.exitAtEpoch.isSome:
|
|
|
|
Epoch config.exitAtEpoch.get
|
|
|
|
else:
|
|
|
|
let headSlot = try:
|
|
|
|
await rpcClient.getBeaconHead()
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to obtain the current head slot", err = err.msg
|
|
|
|
quit 1
|
|
|
|
headSlot.epoch
|
|
|
|
|
|
|
|
let
|
|
|
|
validatorsDir = config.validatorsDir
|
|
|
|
validatorKeyAsStr = "0x" & $validator.pubkey
|
|
|
|
keystoreDir = validatorsDir / validatorKeyAsStr
|
|
|
|
|
|
|
|
if not dirExists(keystoreDir):
|
|
|
|
echo "The validator keystores directory '" & config.validatorsDir.string &
|
|
|
|
"' does not contain a keystore for the selected validator with public " &
|
|
|
|
"key '" & validatorKeyAsStr & "'."
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let signingKey = loadKeystore(
|
|
|
|
validatorsDir,
|
|
|
|
config.secretsDir,
|
|
|
|
validatorKeyAsStr,
|
|
|
|
config.nonInteractive)
|
|
|
|
|
|
|
|
if signingKey.isNone:
|
|
|
|
fatal "Unable to continue without decrypted signing key"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let fork = try:
|
|
|
|
await rpcClient.get_v1_beacon_states_fork("head")
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to obtain the fork id of the head state", err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
let genesisValidatorsRoot = try:
|
|
|
|
(await rpcClient.get_v1_beacon_genesis()).genesis_validators_root
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to obtain the genesis validators root of the network",
|
|
|
|
err = err.msg
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
var signedExit = SignedVoluntaryExit(
|
|
|
|
message: VoluntaryExit(
|
|
|
|
epoch: exitAtEpoch,
|
|
|
|
validator_index: validatorIdx))
|
|
|
|
|
|
|
|
signedExit.signature = get_voluntary_exit_signature(
|
|
|
|
fork, genesisValidatorsRoot, signedExit.message, signingKey.get)
|
|
|
|
|
|
|
|
template ask(prompt: string): string =
|
|
|
|
try:
|
|
|
|
stdout.write prompt, ": "
|
|
|
|
stdin.readLine()
|
|
|
|
except IOError as err:
|
|
|
|
fatal "Failed to read user input from stdin"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
try:
|
|
|
|
echoP "PLEASE BEWARE!"
|
|
|
|
|
|
|
|
echoP "Publishing a voluntary exit is an irreversible operation! " &
|
|
|
|
"You won't be able to restart again with the same validator."
|
|
|
|
|
|
|
|
echoP "By requesting an exit now, you'll be exempt from penalties " &
|
|
|
|
"stemming from not performing your validator duties, but you " &
|
2020-11-29 21:07:33 +00:00
|
|
|
"won't be able to withdraw your deposited funds for the time " &
|
2020-11-27 19:48:33 +00:00
|
|
|
"being. This means that your funds will be effectively frozen " &
|
2020-11-29 21:07:33 +00:00
|
|
|
"until withdrawals are enabled in a future phase of Eth2."
|
2020-12-01 08:44:30 +00:00
|
|
|
|
2020-11-27 19:48:33 +00:00
|
|
|
|
|
|
|
echoP "To understand more about the Eth2 roadmap, we recommend you " &
|
|
|
|
"have a look at\n" &
|
|
|
|
"https://ethereum.org/en/eth2/#roadmap"
|
|
|
|
|
2020-11-29 21:07:33 +00:00
|
|
|
echoP "You must keep your validator running for at least 5 epochs " &
|
2020-11-27 19:48:33 +00:00
|
|
|
"(32 minutes) after requesting a validator exit, as you will " &
|
|
|
|
"still be required to perform validator duties until your exit " &
|
|
|
|
"has been processed. The number of epochs could be significantly " &
|
|
|
|
"higher depending on how many other validators are queued to exit."
|
|
|
|
|
|
|
|
echoP "As such, we recommend you keep track of your validator's status " &
|
|
|
|
"using an Eth2 block explorer before shutting down your beacon node."
|
|
|
|
|
|
|
|
const
|
|
|
|
confirmation = "I understand the implications of submitting a voluntary exit"
|
|
|
|
|
|
|
|
while true:
|
|
|
|
echoP "To proceed to submitting your voluntary exit, please type '" &
|
|
|
|
confirmation & "' (without the quotes) in the prompt below and " &
|
|
|
|
"press ENTER or type 'q' to quit."
|
|
|
|
echo ""
|
|
|
|
|
|
|
|
let choice = ask "Your choice"
|
|
|
|
if choice == "q":
|
|
|
|
quit 0
|
|
|
|
elif choice == confirmation:
|
|
|
|
let success = await rpcClient.post_v1_beacon_pool_voluntary_exits(signedExit)
|
|
|
|
if success:
|
|
|
|
echo "Successfully published voluntary exit for validator " &
|
|
|
|
$validatorIdx & "(" & validatorKeyAsStr[0..9] & ")."
|
|
|
|
quit 0
|
|
|
|
else:
|
|
|
|
echo "The voluntary exit was not submitted successfully. Please try again."
|
|
|
|
quit 1
|
|
|
|
except CatchableError as err:
|
|
|
|
fatal "Failed to send the signed exit message to the beacon node RPC"
|
|
|
|
quit 1
|
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
programMain:
|
2020-08-04 10:35:20 +00:00
|
|
|
var
|
|
|
|
config = makeBannerAndConfig(clientId, BeaconNodeConf)
|
|
|
|
# This is ref so we can mutate it (to erase it) after the initial loading.
|
2020-09-22 20:42:42 +00:00
|
|
|
genesisStateContents: ref string
|
2020-11-24 21:21:47 +00:00
|
|
|
genesisDepositsSnapshotContents: ref string
|
2020-11-06 21:45:56 +00:00
|
|
|
eth1Network: Option[Eth1Network]
|
2020-02-18 00:32:12 +00:00
|
|
|
|
2020-08-27 13:24:30 +00:00
|
|
|
setupStdoutLogging(config.logLevel)
|
|
|
|
|
2020-08-26 08:13:08 +00:00
|
|
|
if not(checkAndCreateDataDir(string(config.dataDir))):
|
2020-08-26 06:42:26 +00:00
|
|
|
# We are unable to access/create data folder or data folder's
|
|
|
|
# permissions are insecure.
|
|
|
|
quit QuitFailure
|
2020-08-25 10:16:31 +00:00
|
|
|
|
2020-07-15 13:15:55 +00:00
|
|
|
setupLogging(config.logLevel, config.logFile)
|
2019-01-16 23:01:15 +00:00
|
|
|
|
2020-10-09 13:57:45 +00:00
|
|
|
## This Ctrl+C handler exits the program in non-graceful way.
|
|
|
|
## It's responsible for handling Ctrl+C in sub-commands such
|
|
|
|
## as `wallets *` and `deposits *`. In a regular beacon node
|
|
|
|
## run, it will be overwritten later with a different handler
|
|
|
|
## performing a graceful exit.
|
|
|
|
proc exitImmediatelyOnCtrlC() {.noconv.} =
|
|
|
|
when defined(windows):
|
|
|
|
# workaround for https://github.com/nim-lang/Nim/issues/4057
|
|
|
|
setupForeignThreadGc()
|
|
|
|
echo "" # If we interrupt during an interactive prompt, this
|
|
|
|
# will move the cursor to the next line
|
|
|
|
notice "Shutting down after having received SIGINT"
|
|
|
|
quit 0
|
|
|
|
setControlCHook(exitImmediatelyOnCtrlC)
|
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
if config.eth2Network.isSome:
|
2020-09-01 09:01:57 +00:00
|
|
|
let metadata = getMetadataForNetwork(config.eth2Network.get)
|
2020-07-07 23:02:14 +00:00
|
|
|
config.runtimePreset = metadata.runtimePreset
|
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
if config.cmd == noCommand:
|
2020-12-01 11:35:55 +00:00
|
|
|
for node in mainnetMetadata.bootstrapNodes:
|
|
|
|
config.bootstrapNodes.add node
|
2020-07-02 15:14:11 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
if metadata.genesisData.len > 0:
|
|
|
|
genesisStateContents = newClone metadata.genesisData
|
2020-07-02 15:52:48 +00:00
|
|
|
|
2020-11-24 21:21:47 +00:00
|
|
|
if metadata.genesisDepositsSnapshot.len > 0:
|
|
|
|
genesisDepositsSnapshotContents = newClone metadata.genesisDepositsSnapshot
|
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
template checkForIncompatibleOption(flagName, fieldName) =
|
|
|
|
# TODO: This will have to be reworked slightly when we introduce config files.
|
|
|
|
# We'll need to keep track of the "origin" of the config value, so we can
|
|
|
|
# discriminate between values from config files that can be overridden and
|
|
|
|
# regular command-line options (that may conflict).
|
|
|
|
if config.fieldName.isSome:
|
|
|
|
fatal "Invalid CLI arguments specified. You must not specify '--network' and '" & flagName & "' at the same time",
|
2020-09-01 09:01:57 +00:00
|
|
|
networkParam = config.eth2Network.get, `flagName` = config.fieldName.get
|
2020-07-02 15:14:11 +00:00
|
|
|
quit 1
|
|
|
|
|
|
|
|
checkForIncompatibleOption "deposit-contract", depositContractAddress
|
|
|
|
checkForIncompatibleOption "deposit-contract-block", depositContractDeployedAt
|
|
|
|
config.depositContractAddress = some metadata.depositContractAddress
|
|
|
|
config.depositContractDeployedAt = some metadata.depositContractDeployedAt
|
2020-11-06 21:45:56 +00:00
|
|
|
eth1Network = metadata.eth1Network
|
2020-07-07 23:02:14 +00:00
|
|
|
else:
|
|
|
|
config.runtimePreset = defaultRuntimePreset
|
2020-11-05 22:33:31 +00:00
|
|
|
when const_preset == "mainnet":
|
2020-12-01 11:35:55 +00:00
|
|
|
if config.cmd == noCommand:
|
|
|
|
# TODO Remove the ability to override the depositContractAddress
|
|
|
|
# on the command line in favour of always requiring a custom
|
|
|
|
# nework file. We have to do this, because any user setting
|
|
|
|
# would conflict with the default choice of 'mainnet' as a
|
|
|
|
# --network value.
|
|
|
|
config.depositContractAddress =
|
|
|
|
some mainnetMetadata.depositContractAddress
|
|
|
|
config.depositContractDeployedAt =
|
|
|
|
some mainnetMetadata.depositContractDeployedAt
|
|
|
|
|
|
|
|
for node in mainnetMetadata.bootstrapNodes:
|
|
|
|
config.bootstrapNodes.add node
|
|
|
|
|
|
|
|
genesisStateContents = newClone mainnetMetadata.genesisData
|
|
|
|
genesisDepositsSnapshotContents = newClone mainnetMetadata.genesisDepositsSnapshot
|
|
|
|
eth1Network = some mainnet
|
2020-07-02 15:14:11 +00:00
|
|
|
|
2020-07-07 15:51:02 +00:00
|
|
|
# Single RNG instance for the application - will be seeded on construction
|
|
|
|
# and avoid using system resources (such as urandom) after that
|
|
|
|
let rng = keys.newRng()
|
|
|
|
|
2020-10-02 13:38:32 +00:00
|
|
|
template findWalletWithoutErrors(name: WalletName): auto =
|
|
|
|
let res = keystore_management.findWallet(config, name)
|
|
|
|
if res.isErr:
|
|
|
|
fatal "Failed to locate wallet", error = res.error
|
|
|
|
quit 1
|
|
|
|
res.get
|
|
|
|
|
2018-12-19 12:58:53 +00:00
|
|
|
case config.cmd
|
2019-03-19 17:22:17 +00:00
|
|
|
of createTestnet:
|
2020-07-17 20:59:50 +00:00
|
|
|
let launchPadDeposits = try:
|
|
|
|
Json.loadFile(config.testnetDepositsFile.string, seq[LaunchPadDeposit])
|
|
|
|
except SerializationError as err:
|
|
|
|
error "Invalid LaunchPad deposits file",
|
|
|
|
err = formatMsg(err, config.testnetDepositsFile.string)
|
|
|
|
quit 1
|
2020-06-02 19:59:51 +00:00
|
|
|
|
2020-11-14 21:43:27 +00:00
|
|
|
var deposits: seq[DepositData]
|
2020-07-17 20:59:50 +00:00
|
|
|
for i in config.firstValidator.int ..< launchPadDeposits.len:
|
2020-11-14 21:43:27 +00:00
|
|
|
deposits.add(launchPadDeposits[i] as DepositData)
|
2019-03-19 17:22:17 +00:00
|
|
|
|
2019-10-29 16:46:41 +00:00
|
|
|
let
|
2019-09-02 10:31:14 +00:00
|
|
|
startTime = uint64(times.toUnix(times.getTime()) + config.genesisOffset)
|
2019-10-29 16:46:41 +00:00
|
|
|
outGenesis = config.outputGenesis.string
|
2020-03-24 11:13:07 +00:00
|
|
|
eth1Hash = if config.web3Url.len == 0: eth1BlockHash
|
2020-07-28 13:36:11 +00:00
|
|
|
else: (waitFor getEth1BlockHash(config.web3Url, blockId("latest"))).asEth2Digest
|
2019-10-29 16:46:41 +00:00
|
|
|
var
|
2019-09-02 10:31:14 +00:00
|
|
|
initialState = initialize_beacon_state_from_eth1(
|
2020-09-01 09:01:57 +00:00
|
|
|
config.runtimePreset, eth1Hash, startTime, deposits, {skipBlsValidation})
|
2019-09-02 10:31:14 +00:00
|
|
|
|
|
|
|
# https://github.com/ethereum/eth2.0-pm/tree/6e41fcf383ebeb5125938850d8e9b4e9888389b4/interop/mocked_start#create-genesis-state
|
|
|
|
initialState.genesis_time = startTime
|
2019-07-01 13:20:55 +00:00
|
|
|
|
|
|
|
doAssert initialState.validators.len > 0
|
2019-03-19 17:22:17 +00:00
|
|
|
|
2019-10-29 16:46:41 +00:00
|
|
|
let outGenesisExt = splitFile(outGenesis).ext
|
|
|
|
if cmpIgnoreCase(outGenesisExt, ".json") == 0:
|
|
|
|
Json.saveFile(outGenesis, initialState, pretty = true)
|
|
|
|
echo "Wrote ", outGenesis
|
2019-03-19 17:22:17 +00:00
|
|
|
|
2019-10-29 16:46:41 +00:00
|
|
|
let outSszGenesis = outGenesis.changeFileExt "ssz"
|
2020-04-29 20:12:07 +00:00
|
|
|
SSZ.saveFile(outSszGenesis, initialState[])
|
2019-10-29 16:46:41 +00:00
|
|
|
echo "Wrote ", outSszGenesis
|
2019-09-08 15:32:38 +00:00
|
|
|
|
2019-10-28 23:04:52 +00:00
|
|
|
let bootstrapFile = config.outputBootstrapFile.string
|
2019-09-27 16:05:17 +00:00
|
|
|
if bootstrapFile.len > 0:
|
2020-02-11 16:58:29 +00:00
|
|
|
let
|
2020-07-07 15:51:02 +00:00
|
|
|
networkKeys = getPersistentNetKeys(rng[], config)
|
2020-09-01 09:01:57 +00:00
|
|
|
netMetadata = getPersistentNetMetadata(config)
|
2020-02-19 08:58:10 +00:00
|
|
|
bootstrapEnr = enr.Record.init(
|
|
|
|
1, # sequence number
|
|
|
|
networkKeys.seckey.asEthKey,
|
2020-03-31 10:02:13 +00:00
|
|
|
some(config.bootstrapAddress),
|
|
|
|
config.bootstrapPort,
|
2020-04-15 02:41:22 +00:00
|
|
|
config.bootstrapPort,
|
2020-04-23 18:58:54 +00:00
|
|
|
[toFieldPair("eth2", SSZ.encode(enrForkIdFromState initialState[])),
|
2020-09-01 09:01:57 +00:00
|
|
|
toFieldPair("attnets", SSZ.encode(netMetadata.attnets))])
|
2020-02-19 08:58:10 +00:00
|
|
|
|
2020-05-09 14:47:14 +00:00
|
|
|
writeFile(bootstrapFile, bootstrapEnr.tryGet().toURI)
|
2019-09-27 16:05:17 +00:00
|
|
|
echo "Wrote ", bootstrapFile
|
|
|
|
|
2018-12-19 12:58:53 +00:00
|
|
|
of noCommand:
|
2020-10-22 11:08:46 +00:00
|
|
|
info "Launching beacon node",
|
2020-04-07 16:04:22 +00:00
|
|
|
version = fullVersionStr,
|
2020-08-24 12:56:45 +00:00
|
|
|
bls_backend = $BLS_BACKEND,
|
2020-04-07 16:04:22 +00:00
|
|
|
cmdParams = commandLineParams(),
|
|
|
|
config
|
|
|
|
|
2018-12-28 16:51:40 +00:00
|
|
|
createPidFile(config.dataDir.string / "beacon_node.pid")
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-06-16 08:49:32 +00:00
|
|
|
config.createDumpDirs()
|
2020-05-20 08:58:48 +00:00
|
|
|
|
2020-01-17 13:44:01 +00:00
|
|
|
when useInsecureFeatures:
|
2020-03-16 22:28:54 +00:00
|
|
|
if config.metricsEnabled:
|
|
|
|
let metricsAddress = config.metricsAddress
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Starting metrics HTTP server",
|
2020-11-16 19:15:43 +00:00
|
|
|
url = "http://" & $metricsAddress & ":" & $config.metricsPort & "/metrics"
|
2020-03-16 22:28:54 +00:00
|
|
|
metrics.startHttpServer($metricsAddress, config.metricsPort)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-11-02 18:02:27 +00:00
|
|
|
# There are no managed event loops in here, to do a graceful shutdown, but
|
|
|
|
# letting the default Ctrl+C handler exit is safe, since we only read from
|
|
|
|
# the db.
|
2020-11-06 21:45:56 +00:00
|
|
|
var node = waitFor BeaconNode.init(
|
2020-11-24 21:21:47 +00:00
|
|
|
rng, config, eth1Network,
|
|
|
|
genesisStateContents,
|
|
|
|
genesisDepositsSnapshotContents)
|
2020-11-02 18:02:27 +00:00
|
|
|
|
2020-09-28 15:19:57 +00:00
|
|
|
if bnStatus == BeaconNodeStatus.Stopping:
|
|
|
|
return
|
2020-11-24 21:21:47 +00:00
|
|
|
|
2020-09-22 20:42:42 +00:00
|
|
|
# The memory for the initial snapshot won't be needed anymore
|
2020-11-24 21:21:47 +00:00
|
|
|
if genesisStateContents != nil:
|
|
|
|
genesisStateContents[] = ""
|
|
|
|
if genesisDepositsSnapshotContents != nil:
|
|
|
|
genesisDepositsSnapshotContents[] = ""
|
2020-09-14 06:24:31 +00:00
|
|
|
|
|
|
|
when hasPrompt:
|
|
|
|
initPrompt(node)
|
|
|
|
|
2019-03-22 14:35:20 +00:00
|
|
|
if node.nickname != "":
|
2019-11-25 12:47:29 +00:00
|
|
|
dynamicLogScope(node = node.nickname): node.start()
|
2019-03-20 11:52:30 +00:00
|
|
|
else:
|
2019-11-25 12:47:29 +00:00
|
|
|
node.start()
|
2019-09-01 15:02:49 +00:00
|
|
|
|
2020-06-15 22:20:31 +00:00
|
|
|
of deposits:
|
|
|
|
case config.depositsCmd
|
2020-11-27 19:48:33 +00:00
|
|
|
#[
|
2020-06-15 22:20:31 +00:00
|
|
|
of DepositsCmd.create:
|
2020-10-19 19:02:48 +00:00
|
|
|
var seed: KeySeed
|
|
|
|
defer: burnMem(seed)
|
2020-08-21 19:36:42 +00:00
|
|
|
var walletPath: WalletPathPair
|
|
|
|
|
|
|
|
if config.existingWalletId.isSome:
|
2020-10-02 13:38:32 +00:00
|
|
|
let
|
|
|
|
id = config.existingWalletId.get
|
|
|
|
found = findWalletWithoutErrors(id)
|
|
|
|
|
|
|
|
if found.isSome:
|
2020-08-21 19:36:42 +00:00
|
|
|
walletPath = found.get
|
|
|
|
else:
|
2020-10-02 13:38:32 +00:00
|
|
|
fatal "Unable to find wallet with the specified name/uuid", id
|
2020-07-17 20:59:50 +00:00
|
|
|
quit 1
|
2020-10-02 13:38:32 +00:00
|
|
|
|
2020-08-21 19:36:42 +00:00
|
|
|
var unlocked = unlockWalletInteractively(walletPath.wallet)
|
2020-07-17 20:59:50 +00:00
|
|
|
if unlocked.isOk:
|
2020-10-19 19:02:48 +00:00
|
|
|
swap(seed, unlocked.get)
|
2020-07-17 20:59:50 +00:00
|
|
|
else:
|
2020-08-21 19:36:42 +00:00
|
|
|
# The failure will be reported in `unlockWalletInteractively`.
|
2020-07-17 20:59:50 +00:00
|
|
|
quit 1
|
|
|
|
else:
|
2020-08-21 19:36:42 +00:00
|
|
|
var walletRes = createWalletInteractively(rng[], config)
|
|
|
|
if walletRes.isErr:
|
|
|
|
fatal "Unable to create wallet", err = walletRes.error
|
2020-07-17 20:59:50 +00:00
|
|
|
quit 1
|
2020-08-21 19:36:42 +00:00
|
|
|
else:
|
2020-10-19 19:02:48 +00:00
|
|
|
swap(seed, walletRes.get.seed)
|
2020-08-21 19:36:42 +00:00
|
|
|
walletPath = walletRes.get.walletPath
|
2020-07-10 15:18:14 +00:00
|
|
|
|
2020-10-27 11:04:17 +00:00
|
|
|
let vres = secureCreatePath(config.outValidatorsDir)
|
2020-08-27 18:23:41 +00:00
|
|
|
if vres.isErr():
|
|
|
|
fatal "Could not create directory", path = config.outValidatorsDir
|
|
|
|
quit QuitFailure
|
|
|
|
|
2020-10-27 11:04:17 +00:00
|
|
|
let sres = secureCreatePath(config.outSecretsDir)
|
2020-08-27 18:23:41 +00:00
|
|
|
if sres.isErr():
|
|
|
|
fatal "Could not create directory", path = config.outSecretsDir
|
|
|
|
quit QuitFailure
|
2019-11-05 18:16:10 +00:00
|
|
|
|
2020-06-24 13:57:09 +00:00
|
|
|
let deposits = generateDeposits(
|
2020-07-07 23:02:14 +00:00
|
|
|
config.runtimePreset,
|
2020-07-07 15:51:02 +00:00
|
|
|
rng[],
|
2020-10-19 19:02:48 +00:00
|
|
|
seed,
|
2020-08-21 19:36:42 +00:00
|
|
|
walletPath.wallet.nextAccount,
|
2020-06-01 19:48:20 +00:00
|
|
|
config.totalDeposits,
|
|
|
|
config.outValidatorsDir,
|
2020-06-15 22:20:31 +00:00
|
|
|
config.outSecretsDir)
|
2019-09-01 15:02:49 +00:00
|
|
|
|
2020-06-24 13:57:09 +00:00
|
|
|
if deposits.isErr:
|
|
|
|
fatal "Failed to generate deposits", err = deposits.error
|
|
|
|
quit 1
|
|
|
|
|
2020-07-17 20:59:50 +00:00
|
|
|
try:
|
|
|
|
let depositDataPath = if config.outDepositsFile.isSome:
|
|
|
|
config.outDepositsFile.get.string
|
|
|
|
else:
|
2020-08-02 18:47:15 +00:00
|
|
|
config.outValidatorsDir / "deposit_data-" & $epochTime() & ".json"
|
2020-06-24 13:57:09 +00:00
|
|
|
|
2020-07-17 20:59:50 +00:00
|
|
|
let launchPadDeposits =
|
|
|
|
mapIt(deposits.value, LaunchPadDeposit.init(config.runtimePreset, it))
|
2020-07-01 09:13:56 +00:00
|
|
|
|
2020-07-17 20:59:50 +00:00
|
|
|
Json.saveFile(depositDataPath, launchPadDeposits)
|
2020-10-02 13:38:32 +00:00
|
|
|
echo "Deposit data written to \"", depositDataPath, "\""
|
2020-08-21 19:36:42 +00:00
|
|
|
|
|
|
|
walletPath.wallet.nextAccount += deposits.value.len
|
|
|
|
let status = saveWallet(walletPath)
|
|
|
|
if status.isErr:
|
2020-10-02 13:38:32 +00:00
|
|
|
fatal "Failed to update wallet file after generating deposits",
|
2020-08-21 19:36:42 +00:00
|
|
|
wallet = walletPath.path,
|
|
|
|
error = status.error
|
|
|
|
quit 1
|
2020-07-17 20:59:50 +00:00
|
|
|
except CatchableError as err:
|
2020-10-02 13:38:32 +00:00
|
|
|
fatal "Failed to create launchpad deposit data file", err = err.msg
|
2020-03-24 11:13:07 +00:00
|
|
|
quit 1
|
|
|
|
|
2020-11-27 19:48:33 +00:00
|
|
|
of DepositsCmd.status:
|
|
|
|
echo "The status command is not implemented yet"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
#]#
|
2020-08-02 17:26:57 +00:00
|
|
|
of DepositsCmd.`import`:
|
2020-11-30 22:59:45 +00:00
|
|
|
let validatorKeysDir = if config.importedDepositsDir.isSome:
|
|
|
|
config.importedDepositsDir.get
|
|
|
|
else:
|
2020-11-28 18:50:09 +00:00
|
|
|
let cwd = os.getCurrentDir()
|
|
|
|
if dirExists(cwd / "validator_keys"):
|
|
|
|
InputDir(cwd / "validator_keys")
|
|
|
|
else:
|
|
|
|
echo "The default search path for validator keys is a sub-directory " &
|
|
|
|
"named 'validator_keys' in the current working directory. Since " &
|
|
|
|
"no such directory exists, please either provide the correct path" &
|
|
|
|
"as an argument or copy the imported keys in the expected location."
|
|
|
|
quit 1
|
|
|
|
|
2020-08-02 17:26:57 +00:00
|
|
|
importKeystoresFromDir(
|
|
|
|
rng[],
|
2020-11-28 18:50:09 +00:00
|
|
|
validatorKeysDir.string,
|
2020-08-02 17:26:57 +00:00
|
|
|
config.validatorsDir, config.secretsDir)
|
|
|
|
|
2020-11-27 19:48:33 +00:00
|
|
|
of DepositsCmd.exit:
|
|
|
|
waitFor handleValidatorExitCommand(config)
|
2020-06-23 19:11:07 +00:00
|
|
|
|
|
|
|
of wallets:
|
|
|
|
case config.walletsCmd:
|
|
|
|
of WalletsCmd.create:
|
2020-10-02 13:38:32 +00:00
|
|
|
if config.createdWalletNameFlag.isSome:
|
|
|
|
let
|
|
|
|
name = config.createdWalletNameFlag.get
|
|
|
|
existingWallet = findWalletWithoutErrors(name)
|
|
|
|
if existingWallet.isSome:
|
|
|
|
echo "The Wallet '" & name.string & "' already exists."
|
|
|
|
quit 1
|
|
|
|
|
2020-08-21 19:36:42 +00:00
|
|
|
var walletRes = createWalletInteractively(rng[], config)
|
|
|
|
if walletRes.isErr:
|
|
|
|
fatal "Unable to create wallet", err = walletRes.error
|
2020-07-14 19:00:35 +00:00
|
|
|
quit 1
|
2020-10-19 19:02:48 +00:00
|
|
|
burnMem(walletRes.get.seed)
|
2020-07-14 19:00:35 +00:00
|
|
|
|
2020-06-23 19:11:07 +00:00
|
|
|
of WalletsCmd.list:
|
2020-08-21 19:36:42 +00:00
|
|
|
for kind, walletFile in walkDir(config.walletsDir):
|
|
|
|
if kind != pcFile: continue
|
2020-09-30 11:47:42 +00:00
|
|
|
if checkSensitiveFilePermissions(walletFile):
|
2020-08-27 13:24:30 +00:00
|
|
|
let walletRes = loadWallet(walletFile)
|
|
|
|
if walletRes.isOk:
|
|
|
|
echo walletRes.get.longName
|
|
|
|
else:
|
|
|
|
warn "Found corrupt wallet file",
|
|
|
|
wallet = walletFile, error = walletRes.error
|
2020-08-21 19:36:42 +00:00
|
|
|
else:
|
2020-08-27 13:24:30 +00:00
|
|
|
warn "Found wallet file with insecure permissions",
|
|
|
|
wallet = walletFile
|
2020-07-14 19:00:35 +00:00
|
|
|
|
2020-06-23 19:11:07 +00:00
|
|
|
of WalletsCmd.restore:
|
2020-08-21 19:36:42 +00:00
|
|
|
restoreWalletInteractively(rng[], config)
|
2020-11-24 23:23:28 +00:00
|
|
|
|
|
|
|
of record:
|
|
|
|
case config.recordCmd:
|
|
|
|
of RecordCmd.create:
|
|
|
|
let netKeys = getPersistentNetKeys(rng[], config)
|
|
|
|
|
|
|
|
var fieldPairs: seq[FieldPair]
|
|
|
|
for field in config.fields:
|
|
|
|
let fieldPair = field.split(":")
|
|
|
|
if fieldPair.len > 1:
|
|
|
|
fieldPairs.add(toFieldPair(fieldPair[0], hexToSeqByte(fieldPair[1])))
|
|
|
|
else:
|
|
|
|
fatal "Invalid field pair"
|
|
|
|
quit QuitFailure
|
|
|
|
|
|
|
|
let record = enr.Record.init(
|
|
|
|
config.seqNumber,
|
|
|
|
netKeys.seckey.asEthKey,
|
|
|
|
some(config.ipExt),
|
|
|
|
config.tcpPortExt,
|
|
|
|
config.udpPortExt,
|
|
|
|
fieldPairs).expect("Record within size limits")
|
|
|
|
|
|
|
|
echo record.toURI()
|
|
|
|
|
|
|
|
of RecordCmd.print:
|
|
|
|
echo $config.recordPrint
|
2020-12-01 11:35:55 +00:00
|
|
|
|