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-07-17 20:59:50 +00:00
|
|
|
algorithm, os, tables, strutils, sequtils, times, math, terminal,
|
2019-10-02 12:38:14 +00:00
|
|
|
|
|
|
|
# Nimble packages
|
2020-07-07 23:02:14 +00:00
|
|
|
stew/[objects, byteutils, endians2], stew/shims/macros,
|
2020-04-27 22:39:04 +00:00
|
|
|
chronos, confutils, metrics, json_rpc/[rpcserver, jsonmarshal],
|
2020-07-17 20:59:50 +00:00
|
|
|
chronicles, bearssl,
|
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/common/eth_types_json_serialization,
|
|
|
|
eth/db/[kvstore, kvstore_sqlite3],
|
|
|
|
eth/p2p/enode, eth/p2p/discoveryv5/[protocol, enr],
|
2019-10-02 12:38:14 +00:00
|
|
|
|
|
|
|
# Local modules
|
2020-07-07 23:02:14 +00:00
|
|
|
spec/[datatypes, digest, crypto, beaconstate, helpers, network, presets],
|
|
|
|
spec/state_transition,
|
2020-04-05 09:50:31 +00:00
|
|
|
conf, time, beacon_chain_db, validator_pool, extras,
|
2020-07-30 19:18:17 +00:00
|
|
|
attestation_pool, eth2_network, eth2_discovery,
|
2020-07-30 15:48:25 +00:00
|
|
|
beacon_node_common, beacon_node_types,
|
2020-07-30 19:18:17 +00:00
|
|
|
block_pools/[spec_cache, candidate_chains, quarantine, clearance, block_pools_types],
|
2020-07-02 15:14:11 +00:00
|
|
|
nimbus_binary_common, network_metadata,
|
2020-07-17 20:59:50 +00:00
|
|
|
mainchain_monitor, version, ssz/[merkleization], sszdump, merkle_minimal,
|
2020-06-08 14:56:56 +00:00
|
|
|
sync_protocol, request_manager, keystore_management, interop, statusbar,
|
2020-06-23 13:54:24 +00:00
|
|
|
sync_manager, validator_duties, validator_api, attestation_aggregation
|
2018-11-23 23:58:49 +00:00
|
|
|
|
|
|
|
const
|
2020-05-27 17:06:28 +00:00
|
|
|
genesisFile* = "genesis.ssz"
|
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-02-19 08:58:10 +00:00
|
|
|
KeyPair = eth2_network.KeyPair
|
2020-03-16 22:28:54 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
# "state" is already taken by BeaconState
|
|
|
|
BeaconNodeStatus* = enum
|
|
|
|
Starting, Running, Stopping
|
|
|
|
|
|
|
|
# this needs to be global, so it can be set in the Ctrl+C signal handler
|
|
|
|
var status = BeaconNodeStatus.Starting
|
|
|
|
|
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
|
2019-10-25 17:15:12 +00:00
|
|
|
declareGauge beacon_slot,
|
|
|
|
"Latest slot of the beacon chain state"
|
|
|
|
declareGauge beacon_head_slot,
|
|
|
|
"Slot of the head block of the beacon chain"
|
2019-09-07 17:48:05 +00:00
|
|
|
|
2019-10-24 06:51:27 +00:00
|
|
|
# Metrics for tracking attestation and beacon block loss
|
2019-10-25 17:15:12 +00:00
|
|
|
declareCounter beacon_attestations_received,
|
|
|
|
"Number of beacon chain attestations received by this peer"
|
2020-06-05 09:57:40 +00:00
|
|
|
declareCounter beacon_blocks_received,
|
|
|
|
"Number of beacon chain blocks received by this peer"
|
2019-10-24 06:51:27 +00:00
|
|
|
|
2020-07-30 14:27:34 +00:00
|
|
|
# Finalization tracking
|
|
|
|
declareGauge finalization_delay,
|
|
|
|
"Epoch delay between scheduled epoch and finalized epoch"
|
|
|
|
|
2020-05-11 06:25:49 +00:00
|
|
|
declareHistogram beacon_attestation_received_seconds_from_slot_start,
|
|
|
|
"Interval between slot start and attestation receival", buckets = [2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, Inf]
|
|
|
|
|
2019-09-12 01:45:04 +00:00
|
|
|
logScope: topics = "beacnde"
|
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
proc onBeaconBlock(node: BeaconNode, signedBlock: SignedBeaconBlock) {.gcsafe.}
|
|
|
|
|
2020-05-27 17:06:28 +00:00
|
|
|
proc getStateFromSnapshot(conf: BeaconNodeConf): NilableBeaconStateRef =
|
|
|
|
var
|
|
|
|
genesisPath = conf.dataDir/genesisFile
|
|
|
|
snapshotContents: TaintedString
|
|
|
|
writeGenesisFile = false
|
|
|
|
|
|
|
|
if conf.stateSnapshot.isSome:
|
|
|
|
let
|
|
|
|
snapshotPath = conf.stateSnapshot.get.string
|
|
|
|
snapshotExt = splitFile(snapshotPath).ext
|
|
|
|
|
|
|
|
if cmpIgnoreCase(snapshotExt, ".ssz") != 0:
|
|
|
|
error "The supplied state snapshot must be a SSZ file",
|
|
|
|
suppliedPath = snapshotPath
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
snapshotContents = readFile(snapshotPath)
|
|
|
|
if fileExists(genesisPath):
|
|
|
|
let genesisContents = readFile(genesisPath)
|
|
|
|
if snapshotContents != genesisContents:
|
|
|
|
error "Data directory not empty. Existing genesis state differs from supplied snapshot",
|
|
|
|
dataDir = conf.dataDir.string, snapshot = snapshotPath
|
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
debug "No previous genesis state. Importing snapshot",
|
|
|
|
genesisPath, dataDir = conf.dataDir.string
|
|
|
|
writeGenesisFile = true
|
|
|
|
genesisPath = snapshotPath
|
2020-06-16 18:38:51 +00:00
|
|
|
elif fileExists(genesisPath):
|
|
|
|
try: snapshotContents = readFile(genesisPath)
|
2020-05-27 17:06:28 +00:00
|
|
|
except CatchableError as err:
|
|
|
|
error "Failed to read genesis file", err = err.msg
|
|
|
|
quit 1
|
2020-07-02 15:52:48 +00:00
|
|
|
elif conf.stateSnapshotContents != nil:
|
|
|
|
swap(snapshotContents, TaintedString conf.stateSnapshotContents[])
|
2020-06-16 18:38:51 +00:00
|
|
|
else:
|
|
|
|
# No snapshot was provided. We should wait for genesis.
|
|
|
|
return nil
|
2020-05-27 17:06:28 +00:00
|
|
|
|
|
|
|
result = try:
|
|
|
|
newClone(SSZ.decode(snapshotContents, BeaconState))
|
|
|
|
except SerializationError:
|
|
|
|
error "Failed to import genesis file", path = genesisPath
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
info "Loaded genesis state", path = genesisPath
|
|
|
|
|
|
|
|
if writeGenesisFile:
|
|
|
|
try:
|
|
|
|
notice "Writing genesis to data directory", path = conf.dataDir/genesisFile
|
|
|
|
writeFile(conf.dataDir/genesisFile, snapshotContents.string)
|
|
|
|
except CatchableError as err:
|
|
|
|
error "Failed to persist genesis file to data dir",
|
|
|
|
err = err.msg, genesisFile = conf.dataDir/genesisFile
|
|
|
|
quit 1
|
|
|
|
|
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,
|
|
|
|
conf: BeaconNodeConf): Future[BeaconNode] {.async.} =
|
2020-01-17 13:44:01 +00:00
|
|
|
let
|
2020-07-07 15:51:02 +00:00
|
|
|
netKeys = getPersistentNetKeys(rng[], conf)
|
2020-02-05 20:40:14 +00:00
|
|
|
nickname = if conf.nodeName == "auto": shortForm(netKeys)
|
2020-01-17 13:44:01 +00:00
|
|
|
else: conf.nodeName
|
2020-04-23 06:27:35 +00:00
|
|
|
db = BeaconChainDB.init(kvStore SqStoreRef.init(conf.databaseDir, "nbc").tryGet())
|
2020-01-17 13:44:01 +00:00
|
|
|
|
|
|
|
var mainchainMonitor: MainchainMonitor
|
|
|
|
|
2020-07-30 19:18:17 +00:00
|
|
|
if not CandidateChains.isInitialized(db):
|
2020-01-17 13:44:01 +00:00
|
|
|
# Fresh start - need to load a genesis state from somewhere
|
2020-04-22 23:35:55 +00:00
|
|
|
var genesisState = conf.getStateFromSnapshot()
|
2020-01-17 13:44:01 +00:00
|
|
|
|
|
|
|
# Try file from command line first
|
2020-04-22 23:35:55 +00:00
|
|
|
if genesisState.isNil:
|
2020-06-27 12:01:19 +00:00
|
|
|
if conf.web3Url.len == 0:
|
|
|
|
fatal "Web3 URL not specified"
|
|
|
|
quit 1
|
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
if conf.depositContractAddress.isNone:
|
2020-06-27 12:01:19 +00:00
|
|
|
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
|
|
|
|
|
2020-07-28 13:36:11 +00:00
|
|
|
let web3 = web3Provider(conf.web3Url)
|
|
|
|
let deployedAtAsHash =
|
|
|
|
if conf.depositContractDeployedAt.get.startsWith "0x":
|
|
|
|
try: BlockHash.fromHex conf.depositContractDeployedAt.get
|
|
|
|
except ValueError:
|
|
|
|
fatal "Invalid hex value specified for deposit-contract-block"
|
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
let blockNum = try: parseBiggestUInt conf.depositContractDeployedAt.get
|
|
|
|
except ValueError:
|
|
|
|
fatal "Invalid nummeric value for deposit-contract-block"
|
|
|
|
quit 1
|
|
|
|
await getEth1BlockHash(conf.web3Url, blockId blockNum)
|
|
|
|
|
2020-01-17 13:44:01 +00:00
|
|
|
# TODO Could move this to a separate "GenesisMonitor" process or task
|
2020-06-11 12:13:12 +00:00
|
|
|
# that would do only this - see Paul's proposal for this.
|
2020-06-27 12:01:19 +00:00
|
|
|
mainchainMonitor = MainchainMonitor.init(
|
2020-07-07 23:02:14 +00:00
|
|
|
conf.runtimePreset,
|
2020-07-28 13:36:11 +00:00
|
|
|
web3,
|
2020-07-02 15:14:11 +00:00
|
|
|
conf.depositContractAddress.get,
|
2020-07-28 13:36:11 +00:00
|
|
|
Eth1Data(block_hash: deployedAtAsHash.asEth2Digest, deposit_count: 0))
|
|
|
|
|
2020-06-27 12:01:19 +00:00
|
|
|
mainchainMonitor.start()
|
2019-10-25 14:53:31 +00:00
|
|
|
|
2020-06-28 20:17:47 +00:00
|
|
|
genesisState = await mainchainMonitor.waitGenesis()
|
2020-06-28 21:06:43 +00:00
|
|
|
|
2020-06-28 20:17:47 +00:00
|
|
|
info "Eth2 genesis state detected",
|
|
|
|
genesisTime = genesisState.genesisTime,
|
|
|
|
eth1Block = genesisState.eth1_data.block_hash,
|
|
|
|
totalDeposits = genesisState.eth1_data.deposit_count
|
2019-10-25 14:53:31 +00:00
|
|
|
|
2020-04-22 23:35:55 +00:00
|
|
|
# This is needed to prove the not nil property from here on
|
|
|
|
if genesisState == nil:
|
|
|
|
doAssert false
|
|
|
|
else:
|
|
|
|
if genesisState.slot != GENESIS_SLOT:
|
|
|
|
# TODO how to get a block from a non-genesis state?
|
|
|
|
error "Starting from non-genesis state not supported",
|
|
|
|
stateSlot = genesisState.slot,
|
2020-04-29 20:12:07 +00:00
|
|
|
stateRoot = hash_tree_root(genesisState[])
|
2020-04-22 23:35:55 +00:00
|
|
|
quit 1
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2020-04-23 18:58:54 +00:00
|
|
|
let tailBlock = get_initial_beacon_block(genesisState[])
|
2019-01-25 14:17:35 +00:00
|
|
|
|
2020-04-22 23:35:55 +00:00
|
|
|
try:
|
2020-07-30 19:18:17 +00:00
|
|
|
CandidateChains.preInit(db, genesisState[], tailBlock)
|
|
|
|
doAssert CandidateChains.isInitialized(db), "preInit should have initialized db"
|
2020-04-22 23:35:55 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "Failed to initialize database", err = e.msg
|
|
|
|
quit 1
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-07-02 15:52:48 +00:00
|
|
|
if conf.stateSnapshotContents != nil:
|
|
|
|
# The memory for the initial snapshot won't be needed anymore
|
|
|
|
conf.stateSnapshotContents[] = ""
|
|
|
|
|
2020-01-17 13:44:01 +00:00
|
|
|
# TODO check that genesis given on command line (if any) matches database
|
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-07-30 19:18:17 +00:00
|
|
|
chainDag = init(CandidateChains, conf.runtimePreset, db, chainDagFlags)
|
|
|
|
quarantine = Quarantine()
|
2020-01-17 13:44:01 +00:00
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
if mainchainMonitor.isNil and
|
|
|
|
conf.web3Url.len > 0 and
|
2020-07-02 15:14:11 +00:00
|
|
|
conf.depositContractAddress.isSome:
|
2020-01-17 13:44:01 +00:00
|
|
|
mainchainMonitor = MainchainMonitor.init(
|
2020-07-07 23:02:14 +00:00
|
|
|
conf.runtimePreset,
|
2020-03-24 11:13:07 +00:00
|
|
|
web3Provider(conf.web3Url),
|
2020-07-02 15:14:11 +00:00
|
|
|
conf.depositContractAddress.get,
|
2020-07-30 19:18:17 +00:00
|
|
|
chainDag.headState.data.data.eth1_data)
|
2020-02-07 07:13:38 +00:00
|
|
|
# TODO if we don't have any validators attached, we don't need a mainchain
|
|
|
|
# monitor
|
2020-01-17 13:44:01 +00:00
|
|
|
mainchainMonitor.start()
|
|
|
|
|
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-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-07-30 15:48:25 +00:00
|
|
|
network = createEth2Node(rng, conf, enrForkId)
|
2020-04-15 02:41:22 +00:00
|
|
|
|
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,
|
|
|
|
attachedValidators: ValidatorPool.init(),
|
2020-07-30 19:18:17 +00:00
|
|
|
chainDag: chainDag,
|
|
|
|
quarantine: quarantine,
|
|
|
|
attestationPool: AttestationPool.init(chainDag, quarantine),
|
2020-01-17 13:44:01 +00:00
|
|
|
mainchainMonitor: mainchainMonitor,
|
2020-07-30 19:18:17 +00:00
|
|
|
beaconClock: BeaconClock.init(chainDag.headState.data.data),
|
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
|
|
|
)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-06-18 10:03:36 +00:00
|
|
|
res.requestManager = RequestManager.init(network,
|
|
|
|
proc(signedBlock: SignedBeaconBlock) =
|
|
|
|
onBeaconBlock(res, signedBlock)
|
|
|
|
)
|
|
|
|
|
2020-07-30 15:48:25 +00:00
|
|
|
res.addLocalValidators()
|
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-06-05 09:57:40 +00:00
|
|
|
proc onAttestation(node: BeaconNode, attestation: Attestation) =
|
|
|
|
# We received an attestation from the network but don't know much about it
|
|
|
|
# yet - in particular, we haven't verified that it belongs to particular chain
|
|
|
|
# we're on, or that it follows the rules of the protocol
|
2020-07-16 13:16:51 +00:00
|
|
|
logScope:
|
|
|
|
attestation = shortLog(attestation)
|
2020-07-30 19:18:17 +00:00
|
|
|
head = shortLog(node.chainDag.head)
|
2020-07-16 13:16:51 +00:00
|
|
|
pcs = "on_attestation"
|
2020-06-05 09:57:40 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
wallSlot = node.beaconClock.now().toSlot()
|
2020-07-30 19:18:17 +00:00
|
|
|
head = node.chainDag.head
|
2020-06-05 09:57:40 +00:00
|
|
|
|
|
|
|
debug "Attestation received",
|
2020-07-16 13:16:51 +00:00
|
|
|
wallSlot = shortLog(wallSlot.slot)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-07-28 13:54:32 +00:00
|
|
|
if not wallSlot.afterGenesis or wallSlot.slot < head.slot:
|
2020-06-05 09:57:40 +00:00
|
|
|
warn "Received attestation before genesis or head - clock is wrong?",
|
|
|
|
afterGenesis = wallSlot.afterGenesis,
|
2020-07-28 13:54:32 +00:00
|
|
|
wallSlot = shortLog(wallSlot.slot)
|
2020-06-05 09:57:40 +00:00
|
|
|
return
|
|
|
|
|
2020-07-28 13:54:32 +00:00
|
|
|
if attestation.data.slot > head.slot and
|
|
|
|
(attestation.data.slot - head.slot) > MaxEmptySlotCount:
|
|
|
|
warn "Ignoring attestation, head block too old (out of sync?)"
|
2020-06-05 09:57:40 +00:00
|
|
|
return
|
|
|
|
|
2020-07-28 13:54:32 +00:00
|
|
|
node.attestationPool.addAttestation(attestation, wallSlot.slot)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-06-16 08:49:32 +00:00
|
|
|
proc dumpBlock[T](
|
|
|
|
node: BeaconNode, signedBlock: SignedBeaconBlock,
|
|
|
|
res: Result[T, BlockError]) =
|
|
|
|
if node.config.dumpEnabled and res.isErr:
|
|
|
|
case res.error
|
|
|
|
of Invalid:
|
|
|
|
dump(
|
2020-07-16 13:16:51 +00:00
|
|
|
node.config.dumpDirInvalid, signedBlock)
|
2020-06-16 08:49:32 +00:00
|
|
|
of MissingParent:
|
|
|
|
dump(
|
2020-07-16 13:16:51 +00:00
|
|
|
node.config.dumpDirIncoming, signedBlock)
|
2020-06-16 08:49:32 +00:00
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
proc storeBlock(
|
|
|
|
node: BeaconNode, signedBlock: SignedBeaconBlock): Result[void, BlockError] =
|
|
|
|
debug "Block received",
|
|
|
|
signedBlock = shortLog(signedBlock.message),
|
2020-07-16 13:16:51 +00:00
|
|
|
blockRoot = shortLog(signedBlock.root),
|
2020-06-05 09:57:40 +00:00
|
|
|
pcs = "receive_block"
|
|
|
|
|
|
|
|
beacon_blocks_received.inc()
|
2020-07-09 09:29:32 +00:00
|
|
|
|
2020-07-30 19:18:17 +00:00
|
|
|
{.gcsafe.}: # TODO: fork choice and quarantine should sync via messages instead of callbacks
|
|
|
|
let blck = node.chainDag.addRawBlock(node.quarantine, signedBlock) do (
|
2020-07-22 09:42:55 +00:00
|
|
|
blckRef: BlockRef, signedBlock: SignedBeaconBlock,
|
|
|
|
state: HashedBeaconState):
|
2020-07-09 09:29:32 +00:00
|
|
|
# Callback add to fork choice if valid
|
2020-07-25 19:41:12 +00:00
|
|
|
node.attestationPool.addForkChoice(
|
|
|
|
state.data, blckRef, signedBlock.message,
|
|
|
|
node.beaconClock.now().slotOrZero())
|
2020-06-12 16:43:20 +00:00
|
|
|
|
2020-06-16 08:49:32 +00:00
|
|
|
node.dumpBlock(signedBlock, blck)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-07-09 09:29:32 +00:00
|
|
|
# There can be a scenario where we receive a block we already received.
|
|
|
|
# However this block was before the last finalized epoch and so its parent
|
|
|
|
# was pruned from the ForkChoice.
|
2020-06-16 08:49:32 +00:00
|
|
|
if blck.isErr:
|
2020-06-05 09:57:40 +00:00
|
|
|
return err(blck.error)
|
|
|
|
|
|
|
|
ok()
|
|
|
|
|
|
|
|
proc onBeaconBlock(node: BeaconNode, signedBlock: SignedBeaconBlock) =
|
|
|
|
# We received a block but don't know much about it yet - in particular, we
|
|
|
|
# don't know if it's part of the chain we're currently building.
|
|
|
|
discard node.storeBlock(signedBlock)
|
|
|
|
|
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
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
proc onSlotStart(node: BeaconNode, lastSlot, scheduledSlot: Slot) {.gcsafe, async.} =
|
|
|
|
## 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
|
|
|
|
|
2019-09-12 01:45:04 +00:00
|
|
|
logScope: pcs = "slot_start"
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
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
|
|
|
|
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),
|
|
|
|
peers = node.network.peersCount,
|
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-05-13 08:36:33 +00:00
|
|
|
# Offset backwards slightly to allow this epoch's finalization check to occur
|
|
|
|
if scheduledSlot > 3 and node.config.stopAtEpoch > 0'u64 and
|
|
|
|
(scheduledSlot - 3).compute_epoch_at_slot() >= node.config.stopAtEpoch:
|
2020-02-17 18:24:14 +00:00
|
|
|
info "Stopping at pre-chosen epoch",
|
2020-02-17 21:22:50 +00:00
|
|
|
chosenEpoch = node.config.stopAtEpoch,
|
2020-02-17 18:24:14 +00:00
|
|
|
epoch = scheduledSlot.compute_epoch_at_slot(),
|
|
|
|
slot = scheduledSlot
|
|
|
|
|
2020-07-10 09:24:04 +00:00
|
|
|
# Brute-force, but ensure it's reliable enough to run in CI.
|
2020-02-17 18:24:14 +00:00
|
|
|
quit(0)
|
|
|
|
|
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-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 typically, what consitutes correct actions stays constant between slot
|
|
|
|
# updates and is stable across some epoch transitions as well - see how
|
|
|
|
# we can avoid recalculating everything here
|
|
|
|
# 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-07-28 13:54:32 +00:00
|
|
|
var head = node.updateHead(slot)
|
2020-04-20 17:28:12 +00:00
|
|
|
|
|
|
|
# TODO is the slot of the clock or the head block more interesting? provide
|
|
|
|
# rationale in comment
|
|
|
|
beacon_head_slot.set slot.int64
|
|
|
|
|
|
|
|
# Time passes in here..
|
2020-06-10 06:58:12 +00:00
|
|
|
asyncCheck 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-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:
|
2019-12-02 14:42:57 +00:00
|
|
|
var left = missingBlocks.len
|
2020-06-18 10:03:36 +00:00
|
|
|
info "Requesting detected missing blocks", blocks = shortLog(missingBlocks)
|
|
|
|
node.requestManager.fetchAncestorBlocks(missingBlocks)
|
2019-12-02 14:42:57 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
proc onSecond(node: BeaconNode) {.async.} =
|
|
|
|
## This procedure will be called once per second.
|
|
|
|
if not(node.syncManager.inProgress):
|
|
|
|
node.handleMissingBlocks()
|
|
|
|
|
|
|
|
proc runOnSecondLoop(node: BeaconNode) {.async.} =
|
|
|
|
var sleepTime = chronos.seconds(1)
|
|
|
|
while true:
|
|
|
|
await chronos.sleepAsync(sleepTime)
|
|
|
|
let start = chronos.now(chronos.Moment)
|
|
|
|
await node.onSecond()
|
|
|
|
let finish = chronos.now(chronos.Moment)
|
|
|
|
debug "onSecond task completed", elapsed = $(finish - start)
|
|
|
|
if finish - start > chronos.seconds(1):
|
|
|
|
sleepTime = chronos.seconds(0)
|
|
|
|
else:
|
|
|
|
sleepTime = chronos.seconds(1) - (finish - start)
|
2019-03-27 20:17:01 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
proc runForwardSyncLoop(node: BeaconNode) {.async.} =
|
2020-06-30 13:53:57 +00:00
|
|
|
func getLocalHeadSlot(): Slot =
|
2020-07-30 19:18:17 +00:00
|
|
|
result = node.chainDag.head.slot
|
2020-04-20 14:59:18 +00:00
|
|
|
|
|
|
|
proc getLocalWallSlot(): Slot {.gcsafe.} =
|
2020-06-10 19:36:54 +00:00
|
|
|
let epoch = node.beaconClock.now().slotOrZero.compute_epoch_at_slot() +
|
2020-06-03 08:46:29 +00:00
|
|
|
1'u64
|
2020-04-20 14:59:18 +00:00
|
|
|
result = epoch.compute_start_slot_at_epoch()
|
|
|
|
|
2020-06-30 13:53:57 +00:00
|
|
|
func getFirstSlotAtFinalizedEpoch(): Slot {.gcsafe.} =
|
2020-07-30 19:18:17 +00:00
|
|
|
let fepoch = node.chainDag.headState.data.data.finalized_checkpoint.epoch
|
2020-06-11 14:20:53 +00:00
|
|
|
compute_start_slot_at_epoch(fepoch)
|
|
|
|
|
2020-07-28 13:54:32 +00:00
|
|
|
proc updateLocalBlocks(list: openArray[SignedBeaconBlock]): Result[void, BlockError] =
|
2020-04-20 14:59:18 +00:00
|
|
|
debug "Forward sync imported blocks", count = len(list),
|
2020-04-23 15:31:00 +00:00
|
|
|
local_head_slot = getLocalHeadSlot()
|
2020-05-19 12:08:50 +00:00
|
|
|
let sm = now(chronos.Moment)
|
2020-04-20 14:59:18 +00:00
|
|
|
for blk in list:
|
2020-05-28 05:02:28 +00:00
|
|
|
let res = node.storeBlock(blk)
|
2020-07-01 15:21:21 +00:00
|
|
|
# We going to ignore `BlockError.Unviable` errors because we have working
|
2020-05-28 05:02:28 +00:00
|
|
|
# backward sync and it can happens that we can perform overlapping
|
|
|
|
# requests.
|
2020-07-09 09:29:32 +00:00
|
|
|
# For the same reason we ignore Duplicate blocks as if they are duplicate
|
|
|
|
# from before the current finalized epoch, we can drop them
|
|
|
|
# (and they may have no parents anymore in the fork choice if it was pruned)
|
|
|
|
if res.isErr and res.error notin {BlockError.Unviable, BlockError.Old, BLockError.Duplicate}:
|
2020-05-28 05:02:28 +00:00
|
|
|
return res
|
2020-07-28 13:54:32 +00:00
|
|
|
discard node.updateHead(node.beaconClock.now().slotOrZero)
|
2020-05-19 12:08:50 +00:00
|
|
|
|
|
|
|
let dur = now(chronos.Moment) - sm
|
|
|
|
let secs = float(chronos.seconds(1).nanoseconds)
|
|
|
|
var storeSpeed = 0.0
|
|
|
|
if not(dur.isZero()):
|
|
|
|
let v = float(len(list)) * (secs / float(dur.nanoseconds))
|
|
|
|
# We doing round manually because stdlib.round is deprecated
|
|
|
|
storeSpeed = round(v * 10000) / 10000
|
|
|
|
|
2020-06-26 13:51:20 +00:00
|
|
|
info "Forward sync blocks got imported successfully", count = len(list),
|
2020-05-19 12:08:50 +00:00
|
|
|
local_head_slot = getLocalHeadSlot(), store_speed = storeSpeed
|
2020-05-28 05:02:28 +00:00
|
|
|
ok()
|
2020-04-20 14:59:18 +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-04-23 15:31:00 +00:00
|
|
|
try:
|
|
|
|
debug "Peer score is too low, removing it from PeerPool", peer = peer,
|
2020-05-28 05:02:28 +00:00
|
|
|
peer_score = peer.score, score_low_limit = PeerScoreLowLimit,
|
|
|
|
score_high_limit = PeerScoreHighLimit
|
2020-04-23 15:31:00 +00:00
|
|
|
except:
|
|
|
|
discard
|
|
|
|
result = false
|
|
|
|
else:
|
|
|
|
result = true
|
|
|
|
|
|
|
|
node.network.peerPool.setScoreCheck(scoreCheck)
|
|
|
|
|
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-06-11 14:20:53 +00:00
|
|
|
getFirstSlotAtFinalizedEpoch, updateLocalBlocks,
|
2020-05-19 12:08:50 +00:00
|
|
|
# 4 blocks per chunk is the optimal value right now, because our current
|
|
|
|
# syncing speed is around 4 blocks per second. So there no need to request
|
|
|
|
# more then 4 blocks right now. As soon as `store_speed` value become
|
|
|
|
# significantly more then 4 blocks per second you can increase this
|
|
|
|
# value appropriately.
|
|
|
|
chunkSize = 4
|
2020-04-20 14:59:18 +00:00
|
|
|
)
|
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
await node.syncManager.sync()
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-03-22 16:20:46 +00:00
|
|
|
proc currentSlot(node: BeaconNode): Slot =
|
2020-03-16 22:28:54 +00:00
|
|
|
node.beaconClock.now.slotOrZero
|
|
|
|
|
|
|
|
proc connectedPeersCount(node: BeaconNode): int =
|
2020-06-17 11:04:24 +00:00
|
|
|
nbc_peers.value.int
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
proc installBeaconApiHandlers(rpcServer: RpcServer, node: BeaconNode) =
|
|
|
|
rpcServer.rpc("getBeaconHead") do () -> Slot:
|
2020-07-30 19:18:17 +00:00
|
|
|
return node.chainDag.head.slot
|
2020-05-14 09:18:08 +00:00
|
|
|
|
|
|
|
rpcServer.rpc("getChainHead") do () -> JsonNode:
|
|
|
|
let
|
2020-07-30 19:18:17 +00:00
|
|
|
head = node.chainDag.head
|
|
|
|
finalized = node.chainDag.headState.data.data.finalized_checkpoint
|
|
|
|
justified = node.chainDag.headState.data.data.current_justified_checkpoint
|
2020-05-14 09:18:08 +00:00
|
|
|
return %* {
|
2020-07-28 13:54:32 +00:00
|
|
|
"head_slot": head.slot,
|
|
|
|
"head_block_root": head.root.data.toHex(),
|
2020-05-14 09:18:08 +00:00
|
|
|
"finalized_slot": finalized.epoch * SLOTS_PER_EPOCH,
|
|
|
|
"finalized_block_root": finalized.root.data.toHex(),
|
|
|
|
"justified_slot": justified.epoch * SLOTS_PER_EPOCH,
|
|
|
|
"justified_block_root": justified.root.data.toHex(),
|
|
|
|
}
|
|
|
|
|
|
|
|
rpcServer.rpc("getSyncing") do () -> bool:
|
|
|
|
let
|
|
|
|
beaconTime = node.beaconClock.now()
|
|
|
|
wallSlot = currentSlot(node)
|
2020-07-30 19:18:17 +00:00
|
|
|
headSlot = node.chainDag.head.slot
|
2020-05-14 09:18:08 +00:00
|
|
|
# FIXME: temporary hack: If more than 1 block away from expected head, then we are "syncing"
|
|
|
|
return (headSlot + 1) < wallSlot
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
template requireOneOf(x, y: distinct Option) =
|
|
|
|
if x.isNone xor y.isNone:
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"Please specify one of " & astToStr(x) & " or " & astToStr(y))
|
|
|
|
|
|
|
|
template jsonResult(x: auto): auto =
|
2020-03-17 20:06:26 +00:00
|
|
|
StringOfJson(Json.encode(x))
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
rpcServer.rpc("getBeaconBlock") do (slot: Option[Slot],
|
2020-03-17 20:06:26 +00:00
|
|
|
root: Option[Eth2Digest]) -> StringOfJson:
|
2020-03-16 22:28:54 +00:00
|
|
|
requireOneOf(slot, root)
|
|
|
|
var blockHash: Eth2Digest
|
|
|
|
if root.isSome:
|
|
|
|
blockHash = root.get
|
|
|
|
else:
|
2020-07-30 19:18:17 +00:00
|
|
|
let foundRef = node.chainDag.getBlockByPreciseSlot(slot.get)
|
2020-03-18 19:38:34 +00:00
|
|
|
if foundRef != nil:
|
|
|
|
blockHash = foundRef.root
|
2020-03-16 22:28:54 +00:00
|
|
|
else:
|
2020-03-17 20:06:26 +00:00
|
|
|
return StringOfJson("null")
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
let dbBlock = node.db.getBlock(blockHash)
|
|
|
|
if dbBlock.isSome:
|
|
|
|
return jsonResult(dbBlock.get)
|
|
|
|
else:
|
2020-03-17 20:06:26 +00:00
|
|
|
return StringOfJson("null")
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
rpcServer.rpc("getBeaconState") do (slot: Option[Slot],
|
2020-03-17 20:06:26 +00:00
|
|
|
root: Option[Eth2Digest]) -> StringOfJson:
|
2020-03-16 22:28:54 +00:00
|
|
|
requireOneOf(slot, root)
|
|
|
|
if slot.isSome:
|
2020-07-13 14:58:38 +00:00
|
|
|
# TODO sanity check slot so that it doesn't cause excessive rewinding
|
2020-07-30 19:18:17 +00:00
|
|
|
let blk = node.chainDag.head.atSlot(slot.get)
|
|
|
|
node.chainDag.withState(node.chainDag.tmpState, blk):
|
2020-03-16 22:28:54 +00:00
|
|
|
return jsonResult(state)
|
|
|
|
else:
|
2020-04-28 08:08:32 +00:00
|
|
|
let tmp = BeaconStateRef() # TODO use tmpState - but load the entire StateData!
|
|
|
|
let state = node.db.getState(root.get, tmp[], noRollback)
|
|
|
|
if state:
|
|
|
|
return jsonResult(tmp[])
|
2020-03-16 22:28:54 +00:00
|
|
|
else:
|
2020-03-17 20:06:26 +00:00
|
|
|
return StringOfJson("null")
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
rpcServer.rpc("getNetworkPeerId") do () -> string:
|
2020-03-22 20:54:47 +00:00
|
|
|
return $publicKey(node.network)
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
rpcServer.rpc("getNetworkPeers") do () -> seq[string]:
|
|
|
|
for peerId, peer in node.network.peerPool:
|
|
|
|
result.add $peerId
|
|
|
|
|
|
|
|
rpcServer.rpc("getNetworkEnr") do () -> string:
|
2020-04-08 21:09:52 +00:00
|
|
|
return $node.network.discovery.localNode.record
|
2020-03-16 22:28:54 +00:00
|
|
|
|
|
|
|
proc installDebugApiHandlers(rpcServer: RpcServer, node: BeaconNode) =
|
2020-05-14 09:18:08 +00:00
|
|
|
rpcServer.rpc("getNodeVersion") do () -> string:
|
|
|
|
return "Nimbus/" & fullVersionStr
|
|
|
|
|
2020-03-16 23:49:53 +00:00
|
|
|
rpcServer.rpc("getSpecPreset") do () -> JsonNode:
|
|
|
|
var res = newJObject()
|
2020-07-07 23:02:14 +00:00
|
|
|
genStmtList:
|
|
|
|
for presetValue in PresetValue:
|
|
|
|
if presetValue notin ignoredValues + runtimeValues:
|
|
|
|
let
|
|
|
|
settingSym = ident($presetValue)
|
|
|
|
settingKey = newLit(toLowerAscii($presetValue))
|
|
|
|
let f = quote do:
|
2020-07-13 14:44:58 +00:00
|
|
|
res[`settingKey`] = %(presets.`settingSym`)
|
2020-07-07 23:02:14 +00:00
|
|
|
yield f
|
|
|
|
|
|
|
|
for field, value in fieldPairs(node.config.runtimePreset):
|
|
|
|
res[field] = when value isnot Version: %value
|
|
|
|
else: %value.toUInt64
|
2020-03-16 23:49:53 +00:00
|
|
|
|
|
|
|
return res
|
2020-03-16 22:28:54 +00:00
|
|
|
|
2020-06-17 14:27:07 +00:00
|
|
|
rpcServer.rpc("peers") do () -> JsonNode:
|
|
|
|
var res = newJObject()
|
|
|
|
var peers = newJArray()
|
|
|
|
for id, peer in node.network.peerPool:
|
|
|
|
peers.add(
|
|
|
|
%(
|
|
|
|
info: shortLog(peer.info),
|
|
|
|
wasDialed: peer.wasDialed,
|
|
|
|
connectionState: $peer.connectionState,
|
|
|
|
score: peer.score,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
res.add("peers", peers)
|
|
|
|
|
|
|
|
return res
|
|
|
|
|
2020-03-16 22:28:54 +00:00
|
|
|
proc installRpcHandlers(rpcServer: RpcServer, node: BeaconNode) =
|
2020-06-05 09:57:40 +00:00
|
|
|
rpcServer.installValidatorApiHandlers(node)
|
2020-03-16 22:28:54 +00:00
|
|
|
rpcServer.installBeaconApiHandlers(node)
|
|
|
|
rpcServer.installDebugApiHandlers(node)
|
|
|
|
|
2020-05-14 11:19:10 +00:00
|
|
|
proc installAttestationHandlers(node: BeaconNode) =
|
2020-03-31 18:39:02 +00:00
|
|
|
proc attestationHandler(attestation: Attestation) =
|
|
|
|
# Avoid double-counting attestation-topic attestations on shared codepath
|
|
|
|
# when they're reflected through beacon blocks
|
|
|
|
beacon_attestations_received.inc()
|
2020-05-14 11:19:10 +00:00
|
|
|
beacon_attestation_received_seconds_from_slot_start.observe(
|
|
|
|
node.beaconClock.now.int64 -
|
|
|
|
(attestation.data.slot.int64 * SECONDS_PER_SLOT.int64))
|
2020-05-11 06:25:49 +00:00
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
node.onAttestation(attestation)
|
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
proc attestationValidator(attestation: Attestation,
|
|
|
|
committeeIndex: uint64): bool =
|
|
|
|
let (afterGenesis, slot) = node.beaconClock.now().toSlot()
|
|
|
|
if not afterGenesis:
|
|
|
|
return false
|
2020-06-10 08:30:21 +00:00
|
|
|
node.attestationPool.isValidAttestation(attestation, slot, committeeIndex)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-07-02 16:15:27 +00:00
|
|
|
proc aggregatedAttestationValidator(
|
|
|
|
signedAggregateAndProof: SignedAggregateAndProof): bool =
|
|
|
|
let (afterGenesis, slot) = node.beaconClock.now().toSlot()
|
|
|
|
if not afterGenesis:
|
|
|
|
return false
|
|
|
|
node.attestationPool.isValidAggregatedAttestation(signedAggregateAndProof, slot)
|
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
var attestationSubscriptions: seq[Future[void]] = @[]
|
2020-05-14 11:19:10 +00:00
|
|
|
|
2020-07-31 09:59:14 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.12.2/specs/phase0/p2p-interface.md#attestations-and-aggregation
|
2020-03-31 18:39:02 +00:00
|
|
|
for it in 0'u64 ..< ATTESTATION_SUBNET_COUNT.uint64:
|
|
|
|
closureScope:
|
|
|
|
let ci = it
|
2020-06-29 18:08:58 +00:00
|
|
|
attestationSubscriptions.add(node.network.subscribe(
|
|
|
|
getAttestationTopic(node.forkDigest, ci), attestationHandler,
|
|
|
|
# This proc needs to be within closureScope; don't lift out of loop.
|
|
|
|
proc(attestation: Attestation): bool =
|
|
|
|
attestationValidator(attestation, ci)
|
|
|
|
))
|
2020-06-09 16:48:51 +00:00
|
|
|
|
2020-07-02 16:15:27 +00:00
|
|
|
attestationSubscriptions.add(node.network.subscribe(
|
|
|
|
getAggregateAndProofsTopic(node.forkDigest),
|
|
|
|
proc(signedAggregateAndProof: SignedAggregateAndProof) =
|
|
|
|
attestationHandler(signedAggregateAndProof.message.aggregate),
|
|
|
|
proc(signedAggregateAndProof: SignedAggregateAndProof): bool =
|
|
|
|
aggregatedAttestationValidator(signedAggregateAndProof)
|
|
|
|
))
|
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
waitFor allFutures(attestationSubscriptions)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
proc stop*(node: BeaconNode) =
|
|
|
|
status = BeaconNodeStatus.Stopping
|
|
|
|
info "Graceful shutdown"
|
|
|
|
waitFor node.network.stop()
|
|
|
|
|
2020-05-14 11:19:10 +00:00
|
|
|
proc run*(node: BeaconNode) =
|
2020-05-19 18:57:35 +00:00
|
|
|
if status == BeaconNodeStatus.Starting:
|
|
|
|
# it might have been set to "Stopping" with Ctrl+C
|
|
|
|
status = BeaconNodeStatus.Running
|
|
|
|
|
|
|
|
if node.rpcServer != nil:
|
|
|
|
node.rpcServer.installRpcHandlers(node)
|
|
|
|
node.rpcServer.start()
|
|
|
|
|
|
|
|
waitFor node.network.subscribe(node.topicBeaconBlocks) do (signedBlock: SignedBeaconBlock):
|
|
|
|
onBeaconBlock(node, signedBlock)
|
|
|
|
do (signedBlock: SignedBeaconBlock) -> bool:
|
|
|
|
let (afterGenesis, slot) = node.beaconClock.now.toSlot()
|
|
|
|
if not afterGenesis:
|
|
|
|
return false
|
2020-06-16 08:49:32 +00:00
|
|
|
|
2020-07-30 19:18:17 +00:00
|
|
|
let blck = node.chainDag.isValidBeaconBlock(node.quarantine,
|
|
|
|
signedBlock, slot, {})
|
2020-06-16 08:49:32 +00:00
|
|
|
node.dumpBlock(signedBlock, blck)
|
|
|
|
|
|
|
|
blck.isOk
|
2020-05-14 11:19:10 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
installAttestationHandlers(node)
|
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)
|
|
|
|
node.forwardSyncLoop = runForwardSyncLoop(node)
|
2019-03-27 20:17:01 +00:00
|
|
|
|
2020-06-18 10:03:36 +00:00
|
|
|
node.requestManager.start()
|
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
# main event loop
|
|
|
|
while status == BeaconNodeStatus.Running:
|
|
|
|
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) =
|
|
|
|
createDir splitFile(filename).dir
|
2019-07-07 09:53:58 +00:00
|
|
|
writeFile filename, $os.getCurrentProcessId()
|
2018-12-19 12:58:53 +00:00
|
|
|
gPidFile = filename
|
|
|
|
addQuitProc proc {.noconv.} = removeFile gPidFile
|
|
|
|
|
2020-06-11 12:13:12 +00:00
|
|
|
proc initializeNetworking(node: BeaconNode) {.async.} =
|
|
|
|
node.network.startListening()
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
await node.network.startLookingForPeers()
|
|
|
|
|
2020-06-29 12:00:59 +00:00
|
|
|
info "Networking initialized",
|
|
|
|
enr = node.network.announcedENR.toURI,
|
|
|
|
libp2p = shortLog(node.network.switch.peerInfo)
|
|
|
|
|
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
|
|
|
|
2019-03-20 11:52:30 +00:00
|
|
|
info "Starting beacon node",
|
2019-11-12 00:05:35 +00:00
|
|
|
version = fullVersionStr,
|
2020-06-30 12:23:52 +00:00
|
|
|
nim = shortNimBanner(),
|
2019-08-16 11:16:56 +00:00
|
|
|
timeSinceFinalization =
|
2019-11-25 12:47:29 +00:00
|
|
|
int64(finalizedHead.slot.toBeaconTime()) -
|
2019-03-22 15:49:37 +00:00
|
|
|
int64(node.beaconClock.now()),
|
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,
|
2019-10-22 21:18:45 +00:00
|
|
|
dataDir = node.config.dataDir.string,
|
2019-09-12 01:45:04 +00:00
|
|
|
pcs = "start_beacon_node"
|
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()
|
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 '.'
|
|
|
|
result.add $remainder
|
|
|
|
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":
|
|
|
|
var balance = uint64(0)
|
2019-11-25 12:47:29 +00:00
|
|
|
# TODO slow linear scan!
|
2020-07-30 19:18:17 +00:00
|
|
|
for idx, b in node.chainDag.headState.data.data.balances:
|
2019-11-25 12:47:29 +00:00
|
|
|
if node.getAttachedValidator(
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.headState.data.data, ValidatorIndex(idx)) != nil:
|
2019-11-25 12:47:29 +00:00
|
|
|
balance += b
|
2019-10-03 01:51:44 +00:00
|
|
|
formatGwei(balance)
|
|
|
|
|
|
|
|
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-04-22 05:53:02 +00:00
|
|
|
proc (logLevel: LogLevel, msg: LogOutputStr) {.gcsafe, raises: [Defect].} =
|
|
|
|
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
|
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-03-24 11:13:07 +00:00
|
|
|
programMain:
|
2020-07-02 15:14:11 +00:00
|
|
|
var config = makeBannerAndConfig(clientId, BeaconNodeConf)
|
2020-02-18 00:32:12 +00:00
|
|
|
|
2020-07-15 13:15:55 +00:00
|
|
|
setupLogging(config.logLevel, config.logFile)
|
2019-01-16 23:01:15 +00:00
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
if config.eth2Network.isSome:
|
|
|
|
let
|
|
|
|
networkName = config.eth2Network.get
|
|
|
|
metadata = case toLowerAscii(networkName)
|
2020-07-03 19:29:23 +00:00
|
|
|
of "mainnet":
|
|
|
|
mainnetMetadata
|
2020-07-02 15:14:11 +00:00
|
|
|
of "altona":
|
|
|
|
altonaMetadata
|
2020-07-28 15:14:13 +00:00
|
|
|
of "medalla":
|
|
|
|
medallaMetadata
|
2020-07-10 14:31:24 +00:00
|
|
|
of "testnet0":
|
|
|
|
testnet0Metadata
|
|
|
|
of "testnet1":
|
|
|
|
testnet1Metadata
|
2020-07-02 15:14:11 +00:00
|
|
|
else:
|
|
|
|
if fileExists(networkName):
|
2020-07-09 22:08:54 +00:00
|
|
|
try:
|
|
|
|
Json.loadFile(networkName, Eth2NetworkMetadata)
|
|
|
|
except SerializationError as err:
|
|
|
|
echo err.formatMsg(networkName)
|
|
|
|
quit 1
|
2020-07-02 15:14:11 +00:00
|
|
|
else:
|
|
|
|
fatal "Unrecognized network name", networkName
|
|
|
|
quit 1
|
|
|
|
|
2020-07-09 22:08:54 +00:00
|
|
|
if metadata.incompatible:
|
|
|
|
fatal "The selected network is not compatible with the current build",
|
|
|
|
reason = metadata.incompatibilityDesc
|
|
|
|
quit 1
|
|
|
|
|
2020-07-07 23:02:14 +00:00
|
|
|
config.runtimePreset = metadata.runtimePreset
|
|
|
|
|
2020-07-02 15:14:11 +00:00
|
|
|
if config.cmd == noCommand:
|
|
|
|
for node in metadata.bootstrapNodes:
|
|
|
|
config.bootstrapNodes.add node
|
|
|
|
|
2020-07-02 15:52:48 +00:00
|
|
|
if config.stateSnapshot.isNone:
|
|
|
|
config.stateSnapshotContents = newClone metadata.genesisData
|
|
|
|
|
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",
|
|
|
|
networkParam = networkName, `flagName` = config.fieldName.get
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
checkForIncompatibleOption "deposit-contract", depositContractAddress
|
|
|
|
checkForIncompatibleOption "deposit-contract-block", depositContractDeployedAt
|
|
|
|
|
|
|
|
config.depositContractAddress = some metadata.depositContractAddress
|
|
|
|
config.depositContractDeployedAt = some metadata.depositContractDeployedAt
|
2020-07-07 23:02:14 +00:00
|
|
|
else:
|
|
|
|
config.runtimePreset = defaultRuntimePreset
|
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()
|
|
|
|
|
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-07-17 20:59:50 +00:00
|
|
|
var deposits: seq[Deposit]
|
|
|
|
for i in config.firstValidator.int ..< launchPadDeposits.len:
|
|
|
|
deposits.add Deposit(data: launchPadDeposits[i] as DepositData)
|
2020-06-18 05:56:47 +00:00
|
|
|
|
2020-07-17 20:59:50 +00:00
|
|
|
attachMerkleProofs(deposits)
|
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-07-07 23:02:14 +00:00
|
|
|
defaultRuntimePreset, 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-04-22 13:12:18 +00:00
|
|
|
metadata = 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-04-22 13:12:18 +00:00
|
|
|
toFieldPair("attnets", SSZ.encode(metadata.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-04-07 16:04:22 +00:00
|
|
|
debug "Launching beacon node",
|
|
|
|
version = fullVersionStr,
|
|
|
|
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-07-07 15:51:02 +00:00
|
|
|
var node = waitFor BeaconNode.init(rng, config)
|
2020-05-19 18:57:35 +00:00
|
|
|
|
2020-07-08 10:11:22 +00:00
|
|
|
## Ctrl+C handling
|
|
|
|
proc controlCHandler() {.noconv.} =
|
|
|
|
when defined(windows):
|
|
|
|
# workaround for https://github.com/nim-lang/Nim/issues/4057
|
|
|
|
setupForeignThreadGc()
|
|
|
|
info "Shutting down after having received SIGINT"
|
|
|
|
status = BeaconNodeStatus.Stopping
|
|
|
|
setControlCHook(controlCHandler)
|
2020-05-19 18:57:35 +00:00
|
|
|
|
2020-01-17 13:44:01 +00:00
|
|
|
when hasPrompt:
|
|
|
|
initPrompt(node)
|
|
|
|
|
|
|
|
when useInsecureFeatures:
|
2020-03-16 22:28:54 +00:00
|
|
|
if config.metricsEnabled:
|
|
|
|
let metricsAddress = config.metricsAddress
|
2020-01-17 13:44:01 +00:00
|
|
|
info "Starting metrics HTTP server",
|
2020-03-16 22:28:54 +00:00
|
|
|
address = metricsAddress, port = config.metricsPort
|
|
|
|
metrics.startHttpServer($metricsAddress, config.metricsPort)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
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
|
|
|
|
of DepositsCmd.create:
|
2020-07-17 20:59:50 +00:00
|
|
|
var walletData = if config.existingWalletId.isSome:
|
|
|
|
let id = config.existingWalletId.get
|
|
|
|
let found = keystore_management.findWallet(config, id)
|
|
|
|
if found.isErr:
|
|
|
|
fatal "Unable to find wallet with the specified name/uuid",
|
|
|
|
id, err = found.error
|
|
|
|
quit 1
|
|
|
|
let unlocked = unlockWalletInteractively(found.get)
|
|
|
|
if unlocked.isOk:
|
|
|
|
unlocked.get
|
|
|
|
else:
|
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
let walletData = createWalletInteractively(rng[], config)
|
|
|
|
if walletData.isErr:
|
|
|
|
fatal "Unable to create wallet", err = walletData.error
|
|
|
|
quit 1
|
|
|
|
walletData.get
|
2020-07-10 15:18:14 +00:00
|
|
|
|
2020-07-17 20:59:50 +00:00
|
|
|
defer: burnMem(walletData.mnemonic)
|
2020-07-10 15:18:14 +00:00
|
|
|
|
2020-06-15 22:20:31 +00:00
|
|
|
createDir(config.outValidatorsDir)
|
|
|
|
createDir(config.outSecretsDir)
|
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-07-17 20:59:50 +00:00
|
|
|
walletData,
|
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:
|
|
|
|
config.outValidatorsDir / "deposit_data-" & $epochTime()
|
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)
|
|
|
|
info "Deposit data written", filename = depositDataPath
|
|
|
|
except CatchableError as err:
|
|
|
|
error "Failed to create launchpad deposit data file", err = err.msg
|
2020-03-24 11:13:07 +00:00
|
|
|
quit 1
|
|
|
|
|
2020-06-23 19:11:07 +00:00
|
|
|
of DepositsCmd.status:
|
|
|
|
echo "The status command is not implemented yet"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
of wallets:
|
|
|
|
case config.walletsCmd:
|
|
|
|
of WalletsCmd.create:
|
2020-07-14 19:00:35 +00:00
|
|
|
let status = createWalletInteractively(rng[], config)
|
|
|
|
if status.isErr:
|
2020-07-17 20:59:50 +00:00
|
|
|
fatal "Unable to create wallet", err = status.error
|
2020-07-14 19:00:35 +00:00
|
|
|
quit 1
|
|
|
|
|
2020-06-23 19:11:07 +00:00
|
|
|
of WalletsCmd.list:
|
|
|
|
# TODO
|
|
|
|
discard
|
2020-07-14 19:00:35 +00:00
|
|
|
|
2020-06-23 19:11:07 +00:00
|
|
|
of WalletsCmd.restore:
|
|
|
|
# TODO
|
|
|
|
discard
|