2020-05-22 17:04:52 +00:00
|
|
|
# beacon_chain
|
2021-02-15 16:40:00 +00:00
|
|
|
# Copyright (c) 2018-2021 Status Research & Development GmbH
|
2020-05-22 17:04:52 +00:00
|
|
|
# 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.
|
2022-07-29 08:36:20 +00:00
|
|
|
import metrics, metrics/chronos_httpserver
|
2021-07-13 11:15:07 +00:00
|
|
|
import validator_client/[common, fallback_service, duties_service,
|
2022-07-14 21:11:25 +00:00
|
|
|
attestation_service, fork_service,
|
2022-07-21 16:54:07 +00:00
|
|
|
sync_committee_service, doppelganger_service]
|
2020-05-22 17:04:52 +00:00
|
|
|
|
2022-07-29 08:36:20 +00:00
|
|
|
type
|
|
|
|
ValidatorClientError* = object of CatchableError
|
|
|
|
|
2021-12-21 14:24:23 +00:00
|
|
|
proc initGenesis(vc: ValidatorClientRef): Future[RestGenesis] {.async.} =
|
2021-07-13 11:15:07 +00:00
|
|
|
info "Initializing genesis", nodes_count = len(vc.beaconNodes)
|
|
|
|
var nodes = vc.beaconNodes
|
2020-06-19 09:21:17 +00:00
|
|
|
while true:
|
2022-07-21 16:54:07 +00:00
|
|
|
var pendingRequests: seq[Future[RestResponse[GetGenesisResponse]]]
|
2021-07-13 11:15:07 +00:00
|
|
|
for node in nodes:
|
|
|
|
debug "Requesting genesis information", endpoint = node
|
2022-07-21 16:54:07 +00:00
|
|
|
pendingRequests.add(node.client.getGenesis())
|
2020-07-08 10:11:22 +00:00
|
|
|
|
2021-07-13 11:15:07 +00:00
|
|
|
try:
|
2022-07-21 16:54:07 +00:00
|
|
|
await allFutures(pendingRequests)
|
2021-07-13 11:15:07 +00:00
|
|
|
except CancelledError as exc:
|
2022-07-21 16:54:07 +00:00
|
|
|
var pending: seq[Future[void]]
|
2022-07-13 14:43:57 +00:00
|
|
|
debug "Genesis information request was interrupted"
|
2022-07-21 16:54:07 +00:00
|
|
|
for future in pendingRequests:
|
|
|
|
if not(future.finished()):
|
|
|
|
pending.add(future.cancelAndWait())
|
|
|
|
await allFutures(pending)
|
2021-07-13 11:15:07 +00:00
|
|
|
raise exc
|
|
|
|
|
|
|
|
let (errorNodes, genesisList) =
|
|
|
|
block:
|
2021-08-03 15:17:11 +00:00
|
|
|
var gres: seq[RestGenesis]
|
2021-07-13 11:15:07 +00:00
|
|
|
var bres: seq[BeaconNodeServerRef]
|
2022-07-21 16:54:07 +00:00
|
|
|
for i in 0 ..< len(pendingRequests):
|
|
|
|
let fut = pendingRequests[i]
|
2021-07-13 11:15:07 +00:00
|
|
|
if fut.done():
|
|
|
|
let resp = fut.read()
|
|
|
|
if resp.status == 200:
|
|
|
|
debug "Received genesis information", endpoint = nodes[i],
|
|
|
|
genesis_time = resp.data.data.genesis_time,
|
|
|
|
genesis_fork_version = resp.data.data.genesis_fork_version,
|
|
|
|
genesis_root = resp.data.data.genesis_validators_root
|
|
|
|
gres.add(resp.data.data)
|
|
|
|
else:
|
2021-09-01 16:08:24 +00:00
|
|
|
debug "Received unsuccessful response code", endpoint = nodes[i],
|
2021-07-13 11:15:07 +00:00
|
|
|
response_code = resp.status
|
|
|
|
bres.add(nodes[i])
|
|
|
|
elif fut.failed():
|
|
|
|
let error = fut.readError()
|
|
|
|
debug "Could not obtain genesis information from beacon node",
|
|
|
|
endpoint = nodes[i], error_name = error.name,
|
|
|
|
error_msg = error.msg
|
|
|
|
bres.add(nodes[i])
|
|
|
|
else:
|
|
|
|
debug "Interrupted while requesting information from beacon node",
|
|
|
|
endpoint = nodes[i]
|
|
|
|
bres.add(nodes[i])
|
|
|
|
(bres, gres)
|
|
|
|
|
|
|
|
if len(genesisList) == 0:
|
|
|
|
let sleepDuration = 2.seconds
|
|
|
|
info "Could not obtain network genesis information from nodes, repeating",
|
|
|
|
sleep_time = sleepDuration
|
|
|
|
await sleepAsync(sleepDuration)
|
|
|
|
nodes = errorNodes
|
|
|
|
else:
|
|
|
|
# Boyer-Moore majority vote algorithm
|
2021-08-03 15:17:11 +00:00
|
|
|
var melem: RestGenesis
|
2021-07-13 11:15:07 +00:00
|
|
|
var counter = 0
|
|
|
|
for item in genesisList:
|
|
|
|
if counter == 0:
|
|
|
|
melem = item
|
|
|
|
inc(counter)
|
|
|
|
else:
|
|
|
|
if melem == item:
|
|
|
|
inc(counter)
|
|
|
|
else:
|
|
|
|
dec(counter)
|
|
|
|
return melem
|
|
|
|
|
2021-12-21 14:24:23 +00:00
|
|
|
proc initValidators(vc: ValidatorClientRef): Future[bool] {.async.} =
|
2021-07-13 11:15:07 +00:00
|
|
|
info "Initializaing validators", path = vc.config.validatorsDir()
|
|
|
|
var duplicates: seq[ValidatorPubKey]
|
2021-12-22 12:37:31 +00:00
|
|
|
for keystore in listLoadableKeystores(vc.config):
|
|
|
|
let pubkey = keystore.pubkey
|
2021-07-13 11:15:07 +00:00
|
|
|
if pubkey in duplicates:
|
|
|
|
error "Duplicate validator's key found", validator_pubkey = pubkey
|
|
|
|
return false
|
2022-05-10 00:32:12 +00:00
|
|
|
elif keystore.kind == KeystoreKind.Remote:
|
|
|
|
info "Remote validator client was skipped", validator_pubkey = pubkey
|
|
|
|
continue
|
2021-07-13 11:15:07 +00:00
|
|
|
else:
|
|
|
|
duplicates.add(pubkey)
|
2022-07-21 16:54:07 +00:00
|
|
|
vc.addValidator(keystore)
|
2021-07-13 11:15:07 +00:00
|
|
|
return true
|
|
|
|
|
2021-12-21 14:24:23 +00:00
|
|
|
proc initClock(vc: ValidatorClientRef): Future[BeaconClock] {.async.} =
|
2021-07-13 11:15:07 +00:00
|
|
|
# This procedure performs initialization of BeaconClock using current genesis
|
|
|
|
# information. It also performs waiting for genesis.
|
|
|
|
let res = BeaconClock.init(vc.beaconGenesis.genesis_time)
|
|
|
|
let currentSlot = res.now().slotOrZero()
|
|
|
|
let currentEpoch = currentSlot.epoch()
|
|
|
|
info "Initializing beacon clock",
|
|
|
|
genesis_time = vc.beaconGenesis.genesis_time,
|
|
|
|
current_slot = currentSlot, current_epoch = currentEpoch
|
2022-01-11 10:01:54 +00:00
|
|
|
let genesisTime = res.fromNow(start_beacon_time(Slot(0)))
|
2021-07-13 11:15:07 +00:00
|
|
|
if genesisTime.inFuture:
|
|
|
|
notice "Waiting for genesis", genesisIn = genesisTime.offset
|
|
|
|
await sleepAsync(genesisTime.offset)
|
|
|
|
return res
|
|
|
|
|
2022-07-29 08:36:20 +00:00
|
|
|
proc initMetrics(vc: ValidatorClientRef): Future[bool] {.async.} =
|
|
|
|
if vc.config.metricsEnabled:
|
|
|
|
let
|
|
|
|
metricsAddress = vc.config.metricsAddress
|
|
|
|
metricsPort = vc.config.metricsPort
|
|
|
|
url = "http://" & $metricsAddress & ":" & $metricsPort & "/metrics"
|
|
|
|
info "Starting metrics HTTP server", url = url
|
|
|
|
let server =
|
|
|
|
block:
|
|
|
|
let res = MetricsHttpServerRef.new($metricsAddress, metricsPort)
|
|
|
|
if res.isErr():
|
|
|
|
error "Could not start metrics HTTP server", url = url,
|
|
|
|
error_msg = res.error()
|
|
|
|
return false
|
|
|
|
res.get()
|
|
|
|
vc.metricsServer = some(server)
|
|
|
|
try:
|
|
|
|
await server.start()
|
|
|
|
except MetricsError as exc:
|
|
|
|
error "Could not start metrics HTTP server", url = url,
|
|
|
|
error_msg = exc.msg, error_name = exc.name
|
|
|
|
return false
|
|
|
|
return true
|
|
|
|
|
|
|
|
proc shutdownMetrics(vc: ValidatorClientRef) {.async.} =
|
|
|
|
if vc.config.metricsEnabled:
|
|
|
|
if vc.metricsServer.isSome():
|
|
|
|
info "Shutting down metrics HTTP server"
|
|
|
|
await vc.metricsServer.get().close()
|
|
|
|
|
|
|
|
proc shutdownSlashingProtection(vc: ValidatorClientRef) =
|
|
|
|
info "Closing slashing protection", path = vc.config.validatorsDir()
|
|
|
|
vc.attachedValidators.slashingProtection.close()
|
|
|
|
|
2021-07-13 11:15:07 +00:00
|
|
|
proc onSlotStart(vc: ValidatorClientRef, wallTime: BeaconTime,
|
2022-07-13 14:43:57 +00:00
|
|
|
lastSlot: Slot): Future[bool] {.async.} =
|
2021-07-13 11:15:07 +00:00
|
|
|
## Called at the beginning of a slot - usually every slot, but sometimes might
|
|
|
|
## skip a few in case we're running late.
|
|
|
|
## wallTime: current system time - we will strive to perform all duties up
|
|
|
|
## to this point in time
|
|
|
|
## lastSlot: the last slot that we successfully processed, so we know where to
|
|
|
|
## start work from - there might be jumps if processing is delayed
|
2020-05-22 17:04:52 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
# The slot we should be at, according to the clock
|
2021-07-13 11:15:07 +00:00
|
|
|
beaconTime = wallTime
|
|
|
|
wallSlot = wallTime.toSlot()
|
2020-05-22 17:04:52 +00:00
|
|
|
|
|
|
|
let
|
2021-07-13 11:15:07 +00:00
|
|
|
# If everything was working perfectly, the slot that we should be processing
|
|
|
|
expectedSlot = lastSlot + 1
|
2022-01-11 10:01:54 +00:00
|
|
|
delay = wallTime - expectedSlot.start_beacon_time()
|
2021-07-13 11:15:07 +00:00
|
|
|
|
2022-07-13 14:43:57 +00:00
|
|
|
if checkIfShouldStopAtEpoch(wallSlot.slot, vc.config.stopAtEpoch):
|
|
|
|
return true
|
2020-05-22 17:04:52 +00:00
|
|
|
|
2020-06-10 10:30:57 +00:00
|
|
|
info "Slot start",
|
2021-11-02 17:06:36 +00:00
|
|
|
slot = shortLog(wallSlot.slot),
|
2021-07-13 11:15:07 +00:00
|
|
|
attestationIn = vc.getDurationToNextAttestation(wallSlot.slot),
|
2021-11-02 17:06:36 +00:00
|
|
|
blockIn = vc.getDurationToNextBlock(wallSlot.slot),
|
|
|
|
delay = shortLog(delay)
|
2020-05-27 17:06:28 +00:00
|
|
|
|
2022-07-13 14:43:57 +00:00
|
|
|
return false
|
|
|
|
|
|
|
|
proc asyncInit(vc: ValidatorClientRef) {.async.} =
|
|
|
|
vc.beaconGenesis = await vc.initGenesis()
|
|
|
|
info "Genesis information", genesis_time = vc.beaconGenesis.genesis_time,
|
|
|
|
genesis_fork_version = vc.beaconGenesis.genesis_fork_version,
|
|
|
|
genesis_root = vc.beaconGenesis.genesis_validators_root
|
|
|
|
|
|
|
|
vc.beaconClock = await vc.initClock()
|
|
|
|
|
2022-07-29 08:36:20 +00:00
|
|
|
if not(await initMetrics(vc)):
|
|
|
|
raise newException(ValidatorClientError,
|
|
|
|
"Could not initialize metrics server")
|
|
|
|
|
|
|
|
try:
|
|
|
|
if not(await initValidators(vc)):
|
|
|
|
await vc.shutdownMetrics()
|
|
|
|
raise newException(ValidatorClientError,
|
|
|
|
"Could not initialize local validators")
|
|
|
|
except CancelledError:
|
|
|
|
debug "Initialization process interrupted"
|
|
|
|
await vc.shutdownMetrics()
|
|
|
|
return
|
2022-07-13 14:43:57 +00:00
|
|
|
|
|
|
|
info "Initializing slashing protection", path = vc.config.validatorsDir()
|
|
|
|
vc.attachedValidators.slashingProtection =
|
|
|
|
SlashingProtectionDB.init(
|
|
|
|
vc.beaconGenesis.genesis_validators_root,
|
|
|
|
vc.config.validatorsDir(), "slashing_protection"
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
vc.fallbackService = await FallbackServiceRef.init(vc)
|
|
|
|
vc.forkService = await ForkServiceRef.init(vc)
|
|
|
|
vc.dutiesService = await DutiesServiceRef.init(vc)
|
2022-07-21 16:54:07 +00:00
|
|
|
vc.doppelgangerService = await DoppelgangerServiceRef.init(vc)
|
2022-07-13 14:43:57 +00:00
|
|
|
vc.attestationService = await AttestationServiceRef.init(vc)
|
|
|
|
vc.syncCommitteeService = await SyncCommitteeServiceRef.init(vc)
|
2022-07-29 08:36:20 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
warn "Unexpected error encountered while initializing",
|
|
|
|
error_name = exc.name, error_msg = exc.msg
|
|
|
|
await vc.shutdownMetrics()
|
|
|
|
vc.shutdownSlashingProtection()
|
2022-07-13 14:43:57 +00:00
|
|
|
except CancelledError:
|
|
|
|
debug "Initialization process interrupted"
|
2022-07-29 08:36:20 +00:00
|
|
|
await vc.shutdownMetrics()
|
|
|
|
vc.shutdownSlashingProtection()
|
|
|
|
return
|
2022-07-13 14:43:57 +00:00
|
|
|
|
2021-12-21 14:24:23 +00:00
|
|
|
proc asyncRun(vc: ValidatorClientRef) {.async.} =
|
2021-07-13 11:15:07 +00:00
|
|
|
vc.fallbackService.start()
|
|
|
|
vc.forkService.start()
|
|
|
|
vc.dutiesService.start()
|
2022-07-21 16:54:07 +00:00
|
|
|
vc.doppelgangerService.start()
|
2021-07-13 11:15:07 +00:00
|
|
|
vc.attestationService.start()
|
2022-05-10 10:03:40 +00:00
|
|
|
vc.syncCommitteeService.start()
|
2020-05-27 17:06:28 +00:00
|
|
|
|
2022-07-14 21:11:25 +00:00
|
|
|
var exitEventFut = vc.gracefulExit.wait()
|
2022-07-13 14:43:57 +00:00
|
|
|
try:
|
|
|
|
vc.runSlotLoopFut = runSlotLoop(vc, vc.beaconClock.now(), onSlotStart)
|
2022-07-14 21:11:25 +00:00
|
|
|
discard await race(vc.runSlotLoopFut, exitEventFut)
|
|
|
|
if not(vc.runSlotLoopFut.finished()):
|
|
|
|
notice "Received shutdown event, exiting"
|
2022-07-13 14:43:57 +00:00
|
|
|
except CancelledError:
|
|
|
|
debug "Main loop interrupted"
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Main loop failed with an error", err_name = $exc.name,
|
|
|
|
err_msg = $exc.msg
|
|
|
|
|
2022-07-29 08:36:20 +00:00
|
|
|
await vc.shutdownMetrics()
|
|
|
|
vc.shutdownSlashingProtection()
|
2022-07-13 14:43:57 +00:00
|
|
|
debug "Stopping main processing loop"
|
|
|
|
var pending: seq[Future[void]]
|
|
|
|
if not(vc.runSlotLoopFut.finished()):
|
|
|
|
pending.add(vc.runSlotLoopFut.cancelAndWait())
|
2022-07-14 21:11:25 +00:00
|
|
|
if not(exitEventFut.finished()):
|
|
|
|
pending.add(exitEventFut.cancelAndWait())
|
2022-07-13 14:43:57 +00:00
|
|
|
debug "Stopping running services"
|
|
|
|
pending.add(vc.fallbackService.stop())
|
|
|
|
pending.add(vc.forkService.stop())
|
|
|
|
pending.add(vc.dutiesService.stop())
|
2022-07-21 16:54:07 +00:00
|
|
|
pending.add(vc.doppelgangerService.stop())
|
2022-07-13 14:43:57 +00:00
|
|
|
pending.add(vc.attestationService.stop())
|
|
|
|
pending.add(vc.syncCommitteeService.stop())
|
|
|
|
await allFutures(pending)
|
|
|
|
|
|
|
|
template runWithSignals(vc: ValidatorClientRef, body: untyped): bool =
|
|
|
|
let future = body
|
|
|
|
discard await race(future, vc.sigintHandleFut, vc.sigtermHandleFut)
|
|
|
|
if future.finished():
|
|
|
|
if future.failed() or future.cancelled():
|
|
|
|
let exc = future.readError()
|
|
|
|
debug "Validator client initialization failed", err_name = $exc.name,
|
|
|
|
err_msg = $exc.msg
|
|
|
|
var pending: seq[Future[void]]
|
|
|
|
if not(vc.sigintHandleFut.finished()):
|
|
|
|
pending.add(cancelAndWait(vc.sigintHandleFut))
|
|
|
|
if not(vc.sigtermHandleFut.finished()):
|
|
|
|
pending.add(cancelAndWait(vc.sigtermHandleFut))
|
|
|
|
await allFutures(pending)
|
|
|
|
false
|
|
|
|
else:
|
|
|
|
true
|
|
|
|
else:
|
|
|
|
let signal = if vc.sigintHandleFut.finished(): "SIGINT" else: "SIGTERM"
|
|
|
|
info "Got interrupt, trying to shutdown gracefully", signal = signal
|
|
|
|
var pending = @[cancelAndWait(future)]
|
|
|
|
if not(vc.sigintHandleFut.finished()):
|
|
|
|
pending.add(cancelAndWait(vc.sigintHandleFut))
|
|
|
|
if not(vc.sigtermHandleFut.finished()):
|
|
|
|
pending.add(cancelAndWait(vc.sigtermHandleFut))
|
|
|
|
await allFutures(pending)
|
|
|
|
false
|
|
|
|
|
|
|
|
proc asyncLoop*(vc: ValidatorClientRef) {.async.} =
|
|
|
|
if not(vc.runWithSignals(asyncInit(vc))):
|
|
|
|
return
|
|
|
|
if not(vc.runWithSignals(asyncRun(vc))):
|
|
|
|
return
|
2021-03-26 06:52:01 +00:00
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
programMain:
|
2021-07-13 11:15:07 +00:00
|
|
|
let config = makeBannerAndConfig("Nimbus validator client " & fullVersionStr,
|
|
|
|
ValidatorClientConf)
|
2020-05-22 17:04:52 +00:00
|
|
|
|
2021-11-02 17:06:36 +00:00
|
|
|
setupLogging(config.logLevel, config.logStdout, config.logFile)
|
2020-05-22 17:04:52 +00:00
|
|
|
|
2022-02-27 11:02:45 +00:00
|
|
|
let beaconNodes =
|
|
|
|
block:
|
|
|
|
var servers: seq[BeaconNodeServerRef]
|
|
|
|
let flags = {RestClientFlag.CommaSeparatedArray}
|
|
|
|
for url in config.beaconNodes:
|
|
|
|
let res = RestClientRef.new(url, flags = flags)
|
|
|
|
if res.isErr():
|
|
|
|
warn "Unable to resolve remote beacon node server's hostname",
|
|
|
|
url = url
|
|
|
|
else:
|
|
|
|
servers.add(BeaconNodeServerRef(client: res.get(), endpoint: url))
|
|
|
|
servers
|
|
|
|
|
|
|
|
if len(beaconNodes) == 0:
|
2022-06-01 10:47:52 +00:00
|
|
|
# This should not happen, thanks to defaults in `conf.nim`
|
2022-02-27 11:02:45 +00:00
|
|
|
fatal "Not enough beacon nodes in command line"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
notice "Launching validator client", version = fullVersionStr,
|
|
|
|
cmdParams = commandLineParams(),
|
|
|
|
config,
|
|
|
|
beacon_nodes_count = len(beaconNodes)
|
|
|
|
|
2022-07-13 14:43:57 +00:00
|
|
|
var vc =
|
|
|
|
when declared(waitSignal):
|
|
|
|
ValidatorClientRef(
|
|
|
|
config: config,
|
|
|
|
beaconNodes: beaconNodes,
|
|
|
|
graffitiBytes: config.graffiti.get(defaultGraffitiBytes()),
|
|
|
|
nodesAvailable: newAsyncEvent(),
|
|
|
|
forksAvailable: newAsyncEvent(),
|
2022-07-14 21:11:25 +00:00
|
|
|
gracefulExit: newAsyncEvent(),
|
2022-07-13 14:43:57 +00:00
|
|
|
sigintHandleFut: waitSignal(SIGINT),
|
|
|
|
sigtermHandleFut: waitSignal(SIGTERM)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
ValidatorClientRef(
|
|
|
|
config: config,
|
|
|
|
beaconNodes: beaconNodes,
|
|
|
|
graffitiBytes: config.graffiti.get(defaultGraffitiBytes()),
|
|
|
|
nodesAvailable: newAsyncEvent(),
|
|
|
|
forksAvailable: newAsyncEvent(),
|
2022-07-14 21:11:25 +00:00
|
|
|
gracefulExit: newAsyncEvent(),
|
2022-07-13 14:43:57 +00:00
|
|
|
sigintHandleFut: newFuture[void]("sigint_placeholder"),
|
|
|
|
sigtermHandleFut: newFuture[void]("sigterm_placeholder")
|
|
|
|
)
|
2022-02-27 11:02:45 +00:00
|
|
|
|
2022-07-13 14:43:57 +00:00
|
|
|
waitFor asyncLoop(vc)
|
|
|
|
info "Validator client stopped"
|