2020-05-06 13:23:45 +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.
|
|
|
|
|
|
|
|
import
|
|
|
|
# Standard library
|
2020-09-16 11:30:03 +00:00
|
|
|
std/[os, tables, sequtils, osproc, streams],
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
# Nimble packages
|
2020-06-29 17:30:19 +00:00
|
|
|
stew/[objects], stew/shims/macros,
|
2020-05-09 12:43:15 +00:00
|
|
|
chronos, metrics, json_rpc/[rpcserver, jsonmarshal],
|
|
|
|
chronicles,
|
2020-05-06 13:23:45 +00:00
|
|
|
json_serialization/std/[options, sets, net], serialization/errors,
|
2020-05-14 11:19:10 +00:00
|
|
|
eth/db/kvstore,
|
2020-05-09 12:43:15 +00:00
|
|
|
eth/[keys, async_utils], eth/p2p/discoveryv5/[protocol, enr],
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
# Local modules
|
2020-09-16 11:30:03 +00:00
|
|
|
spec/[datatypes, digest, crypto, helpers, validator, network, signatures],
|
2020-06-23 13:54:24 +00:00
|
|
|
spec/state_transition,
|
|
|
|
conf, time, validator_pool,
|
2020-10-07 16:57:21 +00:00
|
|
|
attestation_pool, exit_pool, block_pools/[spec_cache, chain_dag, clearance],
|
2020-07-30 19:18:17 +00:00
|
|
|
eth2_network, keystore_management, beacon_node_common, beacon_node_types,
|
2020-06-23 10:38:59 +00:00
|
|
|
nimbus_binary_common, mainchain_monitor, version, ssz/merkleization, interop,
|
2020-09-16 11:30:03 +00:00
|
|
|
attestation_aggregation, sync_manager, sszdump,
|
|
|
|
validator_slashing_protection
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
# Metrics for tracking attestation and beacon block loss
|
|
|
|
declareCounter beacon_attestations_sent,
|
|
|
|
"Number of beacon chain attestations sent by this peer"
|
|
|
|
declareCounter beacon_blocks_proposed,
|
|
|
|
"Number of beacon chain blocks sent by this peer"
|
|
|
|
|
|
|
|
logScope: topics = "beacval"
|
|
|
|
|
2020-08-27 18:23:41 +00:00
|
|
|
# TODO: This procedure follows insecure scheme of creating directory without
|
|
|
|
# any permissions and writing file without any permissions.
|
2020-05-06 13:23:45 +00:00
|
|
|
proc saveValidatorKey*(keyName, key: string, conf: BeaconNodeConf) =
|
2020-06-03 11:52:36 +00:00
|
|
|
let validatorsDir = conf.validatorsDir
|
2020-05-06 13:23:45 +00:00
|
|
|
let outputFile = validatorsDir / keyName
|
|
|
|
createDir validatorsDir
|
|
|
|
writeFile(outputFile, key)
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Imported validator key", file = outputFile
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
proc checkValidatorInRegistry(state: BeaconState,
|
|
|
|
pubKey: ValidatorPubKey) =
|
2020-05-18 17:49:22 +00:00
|
|
|
let idx = state.validators.asSeq.findIt(it.pubKey == pubKey)
|
2020-05-06 13:23:45 +00:00
|
|
|
if idx == -1:
|
|
|
|
# We allow adding a validator even if its key is not in the state registry:
|
|
|
|
# it might be that the deposit for this validator has not yet been processed
|
|
|
|
warn "Validator not in registry (yet?)", pubKey
|
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
proc addLocalValidator*(node: BeaconNode,
|
|
|
|
state: BeaconState,
|
|
|
|
privKey: ValidatorPrivKey) =
|
|
|
|
let pubKey = privKey.toPubKey()
|
|
|
|
state.checkValidatorInRegistry(pubKey)
|
2020-05-06 13:23:45 +00:00
|
|
|
node.attachedValidators.addLocalValidator(pubKey, privKey)
|
|
|
|
|
2020-07-30 15:48:25 +00:00
|
|
|
proc addLocalValidators*(node: BeaconNode) =
|
|
|
|
for validatorKey in node.config.validatorKeys:
|
2020-07-30 19:18:17 +00:00
|
|
|
node.addLocalValidator node.chainDag.headState.data.data, validatorKey
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Local validators attached ", count = node.attachedValidators.count
|
2020-06-11 12:13:12 +00:00
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
proc addRemoteValidators*(node: BeaconNode) =
|
|
|
|
# load all the validators from the child process - loop until `end`
|
|
|
|
var line = newStringOfCap(120).TaintedString
|
|
|
|
while line != "end" and running(node.vcProcess):
|
|
|
|
if node.vcProcess.outputStream.readLine(line) and line != "end":
|
|
|
|
let key = ValidatorPubKey.fromHex(line).get().initPubKey()
|
|
|
|
node.chainDag.headState.data.data.checkValidatorInRegistry(key)
|
|
|
|
|
|
|
|
let v = AttachedValidator(pubKey: key,
|
|
|
|
kind: ValidatorKind.remote,
|
|
|
|
connection: ValidatorConnection(
|
|
|
|
inStream: node.vcProcess.inputStream,
|
|
|
|
outStream: node.vcProcess.outputStream,
|
|
|
|
pubKeyStr: $key))
|
|
|
|
node.attachedValidators.addRemoteValidator(key, v)
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Remote validators attached ", count = node.attachedValidators.count
|
2020-09-01 13:44:40 +00:00
|
|
|
|
2020-08-10 13:21:31 +00:00
|
|
|
proc getAttachedValidator*(node: BeaconNode,
|
|
|
|
pubkey: ValidatorPubKey): AttachedValidator =
|
|
|
|
node.attachedValidators.getValidator(pubkey)
|
|
|
|
|
2020-07-23 18:24:38 +00:00
|
|
|
proc getAttachedValidator*(node: BeaconNode,
|
2020-06-11 12:13:12 +00:00
|
|
|
state: BeaconState,
|
|
|
|
idx: ValidatorIndex): AttachedValidator =
|
2020-08-10 13:21:31 +00:00
|
|
|
if idx < state.validators.len.ValidatorIndex:
|
|
|
|
node.getAttachedValidator(state.validators[idx].pubkey)
|
|
|
|
else:
|
|
|
|
warn "Validator index out of bounds",
|
|
|
|
idx, stateSlot = state.slot, validators = state.validators.len
|
|
|
|
nil
|
|
|
|
|
|
|
|
proc getAttachedValidator*(node: BeaconNode,
|
|
|
|
epochRef: EpochRef,
|
|
|
|
idx: ValidatorIndex): AttachedValidator =
|
|
|
|
if idx < epochRef.validator_keys.len.ValidatorIndex:
|
|
|
|
node.getAttachedValidator(epochRef.validator_keys[idx])
|
|
|
|
else:
|
|
|
|
warn "Validator index out of bounds",
|
|
|
|
idx, epoch = epochRef.epoch, validators = epochRef.validator_keys.len
|
|
|
|
nil
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-07-08 10:11:22 +00:00
|
|
|
proc isSynced*(node: BeaconNode, head: BlockRef): bool =
|
2020-05-06 13:23:45 +00:00
|
|
|
## TODO This function is here as a placeholder for some better heurestics to
|
|
|
|
## determine if we're in sync and should be producing blocks and
|
|
|
|
## attestations. Generally, the problem is that slot time keeps advancing
|
|
|
|
## even when there are no blocks being produced, so there's no way to
|
|
|
|
## distinguish validators geniunely going missing from the node not being
|
|
|
|
## well connected (during a network split or an internet outage for
|
|
|
|
## example). It would generally be correct to simply keep running as if
|
|
|
|
## we were the only legit node left alive, but then we run into issues:
|
|
|
|
## with enough many empty slots, the validator pool is emptied leading
|
|
|
|
## to empty committees and lots of empty slot processing that will be
|
|
|
|
## thrown away as soon as we're synced again.
|
|
|
|
|
|
|
|
let
|
|
|
|
# The slot we should be at, according to the clock
|
|
|
|
beaconTime = node.beaconClock.now()
|
|
|
|
wallSlot = beaconTime.toSlot()
|
|
|
|
|
2020-09-16 11:30:03 +00:00
|
|
|
# TODO: MaxEmptySlotCount should likely involve the weak subjectivity period.
|
|
|
|
|
2020-05-06 13:23:45 +00:00
|
|
|
# TODO if everyone follows this logic, the network will not recover from a
|
|
|
|
# halt: nobody will be producing blocks because everone expects someone
|
|
|
|
# else to do it
|
|
|
|
if wallSlot.afterGenesis and head.slot + MaxEmptySlotCount < wallSlot.slot:
|
|
|
|
false
|
|
|
|
else:
|
|
|
|
true
|
|
|
|
|
2020-06-23 10:38:59 +00:00
|
|
|
proc sendAttestation*(
|
2020-09-14 14:50:03 +00:00
|
|
|
node: BeaconNode, attestation: Attestation, num_active_validators: uint64) =
|
2020-06-29 18:08:58 +00:00
|
|
|
node.network.broadcast(
|
|
|
|
getAttestationTopic(node.forkDigest, attestation, num_active_validators),
|
|
|
|
attestation)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
beacon_attestations_sent.inc()
|
|
|
|
|
2020-06-23 10:38:59 +00:00
|
|
|
proc sendAttestation*(node: BeaconNode, attestation: Attestation) =
|
|
|
|
# For the validator API, which doesn't supply num_active_validators.
|
|
|
|
let attestationBlck =
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.getRef(attestation.data.beacon_block_root)
|
2020-06-23 10:38:59 +00:00
|
|
|
if attestationBlck.isNil:
|
|
|
|
debug "Attempt to send attestation without corresponding block"
|
|
|
|
return
|
|
|
|
|
2020-07-30 15:48:25 +00:00
|
|
|
node.sendAttestation(
|
|
|
|
attestation,
|
|
|
|
count_active_validators(
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.getEpochRef(attestationBlck, attestation.data.target.epoch)))
|
2020-06-23 10:38:59 +00:00
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
proc createAndSendAttestation(node: BeaconNode,
|
|
|
|
fork: Fork,
|
|
|
|
genesis_validators_root: Eth2Digest,
|
|
|
|
validator: AttachedValidator,
|
|
|
|
attestationData: AttestationData,
|
|
|
|
committeeLen: int,
|
2020-06-23 10:38:59 +00:00
|
|
|
indexInCommittee: int,
|
|
|
|
num_active_validators: uint64) {.async.} =
|
2020-07-25 19:41:12 +00:00
|
|
|
var attestation = await validator.produceAndSignAttestation(
|
|
|
|
attestationData, committeeLen, indexInCommittee, fork,
|
|
|
|
genesis_validators_root)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-06-23 10:38:59 +00:00
|
|
|
node.sendAttestation(attestation, num_active_validators)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
2020-05-06 13:23:45 +00:00
|
|
|
if node.config.dumpEnabled:
|
2020-06-16 08:49:32 +00:00
|
|
|
dump(node.config.dumpDirOutgoing, attestation.data, validator.pubKey)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-08-31 14:34:04 +00:00
|
|
|
notice "Attestation sent",
|
2020-05-06 13:23:45 +00:00
|
|
|
attestation = shortLog(attestation),
|
|
|
|
validator = shortLog(validator),
|
2020-07-16 13:16:51 +00:00
|
|
|
indexInCommittee = indexInCommittee
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
type
|
2020-05-27 17:06:28 +00:00
|
|
|
ValidatorInfoForMakeBeaconBlockKind* = enum
|
2020-05-22 17:04:52 +00:00
|
|
|
viValidator
|
|
|
|
viRandao_reveal
|
|
|
|
ValidatorInfoForMakeBeaconBlock* = object
|
2020-05-27 17:06:28 +00:00
|
|
|
case kind*: ValidatorInfoForMakeBeaconBlockKind
|
2020-05-22 17:04:52 +00:00
|
|
|
of viValidator: validator*: AttachedValidator
|
2020-05-27 17:06:28 +00:00
|
|
|
of viRandao_reveal: randao_reveal*: ValidatorSig
|
2020-05-22 17:04:52 +00:00
|
|
|
|
|
|
|
proc makeBeaconBlockForHeadAndSlot*(node: BeaconNode,
|
|
|
|
val_info: ValidatorInfoForMakeBeaconBlock,
|
|
|
|
validator_index: ValidatorIndex,
|
2020-06-29 17:30:19 +00:00
|
|
|
graffiti: GraffitiBytes,
|
2020-05-22 17:04:52 +00:00
|
|
|
head: BlockRef,
|
|
|
|
slot: Slot):
|
2020-09-01 13:44:40 +00:00
|
|
|
Future[tuple[message: Option[BeaconBlock], fork: Fork,
|
|
|
|
genesis_validators_root: Eth2Digest]] {.async.} =
|
2020-05-06 13:23:45 +00:00
|
|
|
# Advance state to the slot that we're proposing for - this is the equivalent
|
|
|
|
# of running `process_slots` up to the slot of the new block.
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.withState(
|
|
|
|
node.chainDag.tmpState, head.atSlot(slot)):
|
2020-05-06 13:23:45 +00:00
|
|
|
let (eth1data, deposits) =
|
|
|
|
if node.mainchainMonitor.isNil:
|
|
|
|
(get_eth1data_stub(state.eth1_deposit_index, slot.compute_epoch_at_slot()),
|
|
|
|
newSeq[Deposit]())
|
|
|
|
else:
|
|
|
|
node.mainchainMonitor.getBlockProposalData(state)
|
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
# TODO perhaps just making the enclosing function accept 2 different types at the
|
|
|
|
# same time and doing some compile-time branching logic is cleaner (without the
|
|
|
|
# need for the discriminated union)... but we need the `state` from `withState`
|
|
|
|
# in order to get the fork/root for the specific head/slot for the randao_reveal
|
|
|
|
# and it's causing problems when the function becomes a generic for 2 types...
|
2020-09-01 13:44:40 +00:00
|
|
|
proc getRandaoReveal(val_info: ValidatorInfoForMakeBeaconBlock):
|
|
|
|
Future[ValidatorSig] {.async.} =
|
2020-05-22 17:04:52 +00:00
|
|
|
if val_info.kind == viValidator:
|
2020-09-01 13:44:40 +00:00
|
|
|
return await val_info.validator.genRandaoReveal(
|
|
|
|
state.fork, state.genesis_validators_root, slot)
|
2020-05-27 17:06:28 +00:00
|
|
|
elif val_info.kind == viRandao_reveal:
|
|
|
|
return val_info.randao_reveal
|
2020-05-22 17:04:52 +00:00
|
|
|
|
2020-05-22 14:21:22 +00:00
|
|
|
let
|
2020-07-30 19:18:17 +00:00
|
|
|
poolPtr = unsafeAddr node.chainDag # safe because restore is short-lived
|
2020-05-22 14:21:22 +00:00
|
|
|
|
|
|
|
func restore(v: var HashedBeaconState) =
|
|
|
|
# TODO address this ugly workaround - there should probably be a
|
|
|
|
# `state_transition` that takes a `StateData` instead and updates
|
|
|
|
# the block as well
|
|
|
|
doAssert v.addr == addr poolPtr.tmpState.data
|
avoid genericAssign for beacon node types (#1166)
* avoid genericAssign for beacon node types
ok, I got fed up of this function messing up cpu measurements - it's so
ridiculously slow, it's sad.
before, while syncing:
```
40,65% beacon_node_shared_witti_0 [.]
genericAssignAux__U5DxFPRpHCCZDKWQzM9adaw
9,02% libc-2.31.so [.] __memmove_avx_unaligned_erms
7,07% beacon_node_shared_witti_0 [.] BIG_384_58_monty
5,19% beacon_node_shared_witti_0 [.] BIG_384_58_mul
2,72% beacon_node_shared_witti_0 [.] memcpy@plt
1,18% [kernel] [k] rb_next
1,17% beacon_node_shared_witti_0 [.] genericReset
1,06% [kernel] [k] map_private_extent_buffer
```
after:
```
24,88% beacon_node_shared_witti_0 [.] BIG_384_58_monty
20,29% beacon_node_shared_witti_0 [.] BIG_384_58_mul
3,15% beacon_node_shared_witti_0 [.] BIG_384_58_norm
2,93% beacon_node_shared_witti_0 [.] BIG_384_58_add
2,55% beacon_node_shared_witti_0 [.] BIG_384_58_sqr
1,64% beacon_node_shared_witti_0 [.] BIG_384_58_mod
1,63% beacon_node_shared_witti_0 [.]
sha256Transform__BJNBQtWr9bJwzqbyfKXd38Q
1,48% beacon_node_shared_witti_0 [.] FP_BLS381_add
1,39% beacon_node_shared_witti_0 [.] BIG_384_58_sub
1,33% beacon_node_shared_witti_0 [.] BIG_384_58_dnorm
1,14% beacon_node_shared_witti_0 [.] FP2_BLS381_mul
1,05% beacon_node_shared_witti_0 [.] BIG_384_58_cmove
1,05% beacon_node_shared_witti_0 [.]
get_shuffled_seq__4uncAHNsSG3Pndo5H11U9aQ
```
* better field iteration
2020-06-12 19:10:22 +00:00
|
|
|
assign(poolPtr.tmpState, poolPtr.headState)
|
2020-05-22 14:21:22 +00:00
|
|
|
|
2020-05-06 13:23:45 +00:00
|
|
|
let message = makeBeaconBlock(
|
2020-07-07 23:02:14 +00:00
|
|
|
node.config.runtimePreset,
|
2020-05-22 14:21:22 +00:00
|
|
|
hashedState,
|
|
|
|
validator_index,
|
2020-05-06 13:23:45 +00:00
|
|
|
head.root,
|
2020-09-01 13:44:40 +00:00
|
|
|
await getRandaoReveal(val_info),
|
2020-05-06 13:23:45 +00:00
|
|
|
eth1data,
|
2020-05-22 17:04:52 +00:00
|
|
|
graffiti,
|
2020-09-14 14:50:03 +00:00
|
|
|
node.attestationPool[].getAttestationsForBlock(state, cache),
|
2020-05-22 14:21:22 +00:00
|
|
|
deposits,
|
2020-10-07 16:57:21 +00:00
|
|
|
node.exitPool[].getProposerSlashingsForBlock(),
|
|
|
|
node.exitPool[].getAttesterSlashingsForBlock(),
|
|
|
|
node.exitPool[].getVoluntaryExitsForBlock(),
|
2020-06-04 12:03:16 +00:00
|
|
|
restore,
|
|
|
|
cache)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
if message.isSome():
|
|
|
|
# TODO this restore is needed because otherwise tmpState will be internally
|
|
|
|
# inconsistent - it's blck will not be pointing to the block that
|
|
|
|
# created this state - we have to reset it here before `await` to avoid
|
|
|
|
# races.
|
|
|
|
restore(poolPtr.tmpState.data)
|
|
|
|
|
|
|
|
return (message, state.fork, state.genesis_validators_root)
|
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
proc proposeSignedBlock*(node: BeaconNode,
|
|
|
|
head: BlockRef,
|
|
|
|
validator: AttachedValidator,
|
2020-07-16 13:16:51 +00:00
|
|
|
newBlock: SignedBeaconBlock): Future[BlockRef] {.async.} =
|
2020-07-09 09:29:32 +00:00
|
|
|
|
2020-09-14 14:50:03 +00:00
|
|
|
let newBlockRef = node.chainDag.addRawBlock(node.quarantine,
|
|
|
|
newBlock) do (
|
|
|
|
blckRef: BlockRef, signedBlock: SignedBeaconBlock,
|
|
|
|
epochRef: EpochRef, state: HashedBeaconState):
|
|
|
|
# Callback add to fork choice if valid
|
|
|
|
node.attestationPool[].addForkChoice(
|
|
|
|
epochRef, blckRef, signedBlock.message,
|
|
|
|
node.beaconClock.now().slotOrZero())
|
2020-07-09 09:29:32 +00:00
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
if newBlockRef.isErr:
|
|
|
|
warn "Unable to add proposed block to block pool",
|
|
|
|
newBlock = shortLog(newBlock.message),
|
2020-07-16 13:16:51 +00:00
|
|
|
blockRoot = shortLog(newBlock.root)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
|
|
|
return head
|
|
|
|
|
2020-08-31 14:34:04 +00:00
|
|
|
notice "Block proposed",
|
2020-06-05 09:57:40 +00:00
|
|
|
blck = shortLog(newBlock.message),
|
|
|
|
blockRoot = shortLog(newBlockRef[].root),
|
2020-07-16 13:16:51 +00:00
|
|
|
validator = shortLog(validator)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
|
|
|
if node.config.dumpEnabled:
|
2020-07-16 13:16:51 +00:00
|
|
|
dump(node.config.dumpDirOutgoing, newBlock)
|
2020-06-05 09:57:40 +00:00
|
|
|
|
|
|
|
node.network.broadcast(node.topicBeaconBlocks, newBlock)
|
|
|
|
|
|
|
|
beacon_blocks_proposed.inc()
|
|
|
|
|
|
|
|
return newBlockRef[]
|
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
proc proposeBlock(node: BeaconNode,
|
|
|
|
validator: AttachedValidator,
|
|
|
|
validator_index: ValidatorIndex,
|
|
|
|
head: BlockRef,
|
|
|
|
slot: Slot): Future[BlockRef] {.async.} =
|
|
|
|
if head.slot >= slot:
|
|
|
|
# We should normally not have a head newer than the slot we're proposing for
|
|
|
|
# but this can happen if block proposal is delayed
|
|
|
|
warn "Skipping proposal, have newer head already",
|
|
|
|
headSlot = shortLog(head.slot),
|
|
|
|
headBlockRoot = shortLog(head.root),
|
2020-07-16 13:16:51 +00:00
|
|
|
slot = shortLog(slot)
|
2020-05-22 17:04:52 +00:00
|
|
|
return head
|
2020-05-22 14:21:22 +00:00
|
|
|
|
2020-09-16 11:30:03 +00:00
|
|
|
let notSlashable = node.attachedValidators
|
|
|
|
.slashingProtection
|
|
|
|
.checkSlashableBlockProposal(validator.pubkey, slot)
|
|
|
|
if notSlashable.isErr:
|
|
|
|
warn "Slashing protection activated",
|
|
|
|
validator = validator.pubkey,
|
|
|
|
slot = slot,
|
|
|
|
existingProposal = notSlashable.error
|
|
|
|
return head
|
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
let valInfo = ValidatorInfoForMakeBeaconBlock(kind: viValidator, validator: validator)
|
2020-09-01 13:44:40 +00:00
|
|
|
let beaconBlockTuple = await makeBeaconBlockForHeadAndSlot(
|
|
|
|
node, valInfo, validator_index, node.graffitiBytes, head, slot)
|
2020-05-22 17:04:52 +00:00
|
|
|
if not beaconBlockTuple.message.isSome():
|
|
|
|
return head # already logged elsewhere!
|
|
|
|
var
|
|
|
|
newBlock = SignedBeaconBlock(
|
|
|
|
message: beaconBlockTuple.message.get()
|
|
|
|
)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-07-16 13:16:51 +00:00
|
|
|
newBlock.root = hash_tree_root(newBlock.message)
|
2020-09-16 11:30:03 +00:00
|
|
|
|
|
|
|
# TODO: recomputed in block proposal
|
|
|
|
let signing_root = compute_block_root(
|
|
|
|
beaconBlockTuple.fork, beaconBlockTuple.genesis_validators_root, slot, newBlock.root)
|
|
|
|
node.attachedValidators
|
|
|
|
.slashingProtection
|
|
|
|
.registerBlock(validator.pubkey, slot, signing_root)
|
|
|
|
|
2020-05-22 17:04:52 +00:00
|
|
|
newBlock.signature = await validator.signBlockProposal(
|
2020-07-16 13:16:51 +00:00
|
|
|
beaconBlockTuple.fork, beaconBlockTuple.genesis_validators_root, slot, newBlock.root)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-07-16 13:16:51 +00:00
|
|
|
return await node.proposeSignedBlock(head, validator, newBlock)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
proc handleAttestations(node: BeaconNode, head: BlockRef, slot: Slot) =
|
|
|
|
## Perform all attestations that the validators attached to this node should
|
|
|
|
## perform during the given slot
|
|
|
|
if slot + SLOTS_PER_EPOCH < head.slot:
|
|
|
|
# The latest block we know about is a lot newer than the slot we're being
|
|
|
|
# asked to attest to - this makes it unlikely that it will be included
|
|
|
|
# at all.
|
|
|
|
# TODO the oldest attestations allowed are those that are older than the
|
|
|
|
# finalized epoch.. also, it seems that posting very old attestations
|
|
|
|
# is risky from a slashing perspective. More work is needed here.
|
2020-10-01 18:56:42 +00:00
|
|
|
warn "Skipping attestation, head is too recent",
|
2020-05-06 13:23:45 +00:00
|
|
|
headSlot = shortLog(head.slot),
|
|
|
|
slot = shortLog(slot)
|
|
|
|
return
|
|
|
|
|
|
|
|
let attestationHead = head.atSlot(slot)
|
|
|
|
if head != attestationHead.blck:
|
|
|
|
# In rare cases, such as when we're busy syncing or just slow, we'll be
|
|
|
|
# attesting to a past state - we must then recreate the world as it looked
|
|
|
|
# like back then
|
|
|
|
notice "Attesting to a state in the past, falling behind?",
|
|
|
|
headSlot = shortLog(head.slot),
|
|
|
|
attestationHeadSlot = shortLog(attestationHead.slot),
|
|
|
|
attestationSlot = shortLog(slot)
|
|
|
|
|
|
|
|
trace "Checking attestations",
|
|
|
|
attestationHeadRoot = shortLog(attestationHead.blck.root),
|
2020-07-16 13:16:51 +00:00
|
|
|
attestationSlot = shortLog(slot)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
# Collect data to send before node.stateCache grows stale
|
|
|
|
var attestations: seq[tuple[
|
|
|
|
data: AttestationData, committeeLen, indexInCommittee: int,
|
|
|
|
validator: AttachedValidator]]
|
|
|
|
|
|
|
|
# We need to run attestations exactly for the slot that we're attesting to.
|
|
|
|
# In case blocks went missing, this means advancing past the latest block
|
|
|
|
# using empty slots as fillers.
|
2020-09-24 17:04:10 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.12.3/specs/phase0/validator.md#validator-assignments
|
2020-08-10 13:21:31 +00:00
|
|
|
let
|
|
|
|
epochRef = node.chainDag.getEpochRef(
|
|
|
|
attestationHead.blck, slot.compute_epoch_at_slot())
|
|
|
|
committees_per_slot =
|
|
|
|
get_committee_count_per_slot(epochRef)
|
|
|
|
num_active_validators = count_active_validators(epochRef)
|
|
|
|
fork = node.chainDag.headState.data.data.fork
|
|
|
|
genesis_validators_root =
|
|
|
|
node.chainDag.headState.data.data.genesis_validators_root
|
|
|
|
|
|
|
|
for committee_index in 0'u64..<committees_per_slot:
|
|
|
|
let committee = get_beacon_committee(
|
|
|
|
epochRef, slot, committee_index.CommitteeIndex)
|
|
|
|
|
|
|
|
for index_in_committee, validatorIdx in committee:
|
|
|
|
let validator = node.getAttachedValidator(epochRef, validatorIdx)
|
|
|
|
if validator != nil:
|
|
|
|
let ad = makeAttestationData(epochRef, attestationHead, committee_index)
|
|
|
|
attestations.add((ad, committee.len, index_in_committee, validator))
|
|
|
|
|
|
|
|
for a in attestations:
|
2020-09-16 11:30:03 +00:00
|
|
|
let notSlashable = node.attachedValidators
|
|
|
|
.slashingProtection
|
|
|
|
.checkSlashableAttestation(
|
|
|
|
a.validator.pubkey,
|
|
|
|
a.data.source.epoch,
|
|
|
|
a.data.target.epoch)
|
|
|
|
|
|
|
|
if notSlashable.isOk():
|
2020-10-06 08:51:33 +00:00
|
|
|
# TODO signing_root is recomputed in produceAndSignAttestation/signAttestation just after
|
|
|
|
let signing_root = compute_attestation_root(
|
|
|
|
fork, genesis_validators_root, a.data)
|
|
|
|
node.attachedValidators
|
|
|
|
.slashingProtection
|
|
|
|
.registerAttestation(
|
|
|
|
a.validator.pubkey,
|
|
|
|
a.data.source.epoch,
|
|
|
|
a.data.target.epoch,
|
|
|
|
signing_root
|
|
|
|
)
|
|
|
|
|
2020-09-16 11:30:03 +00:00
|
|
|
traceAsyncErrors createAndSendAttestation(
|
|
|
|
node, fork, genesis_validators_root, a.validator, a.data,
|
|
|
|
a.committeeLen, a.indexInCommittee, num_active_validators)
|
|
|
|
else:
|
|
|
|
warn "Slashing protection activated for attestation",
|
|
|
|
validator = a.validator.pubkey,
|
|
|
|
badVoteDetails = $notSlashable.error
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
proc handleProposal(node: BeaconNode, head: BlockRef, slot: Slot):
|
|
|
|
Future[BlockRef] {.async.} =
|
|
|
|
## Perform the proposal for the given slot, iff we have a validator attached
|
|
|
|
## that is supposed to do so, given the shuffling in head
|
|
|
|
|
|
|
|
# TODO here we advance the state to the new slot, but later we'll be
|
|
|
|
# proposing for it - basically, we're selecting proposer based on an
|
|
|
|
# empty slot
|
|
|
|
|
2020-07-30 19:18:17 +00:00
|
|
|
let proposer = node.chainDag.getProposer(head, slot)
|
2020-05-22 14:21:22 +00:00
|
|
|
if proposer.isNone():
|
2020-05-06 13:23:45 +00:00
|
|
|
return head
|
|
|
|
|
2020-08-06 19:48:47 +00:00
|
|
|
let validator =
|
2020-08-10 13:21:31 +00:00
|
|
|
node.attachedValidators.getValidator(proposer.get()[1])
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
if validator != nil:
|
2020-05-22 14:21:22 +00:00
|
|
|
return await proposeBlock(node, validator, proposer.get()[0], head, slot)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
debug "Expecting block proposal",
|
|
|
|
headRoot = shortLog(head.root),
|
|
|
|
slot = shortLog(slot),
|
2020-05-22 14:21:22 +00:00
|
|
|
proposer_index = proposer.get()[0],
|
2020-09-14 14:50:03 +00:00
|
|
|
proposer = shortLog(proposer.get()[1].initPubKey())
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
return head
|
|
|
|
|
|
|
|
proc broadcastAggregatedAttestations(
|
2020-09-01 13:44:40 +00:00
|
|
|
node: BeaconNode, aggregationHead: BlockRef, aggregationSlot: Slot) {.async.} =
|
2020-05-06 13:23:45 +00:00
|
|
|
# The index is via a
|
|
|
|
# locally attested validator. Unlike in handleAttestations(...) there's a
|
|
|
|
# single one at most per slot (because that's how aggregation attestation
|
|
|
|
# works), so the machinery that has to handle looping across, basically a
|
|
|
|
# set of locally attached validators is in principle not necessary, but a
|
|
|
|
# way to organize this. Then the private key for that validator should be
|
|
|
|
# the corresponding one -- whatver they are, they match.
|
|
|
|
|
|
|
|
let bs = BlockSlot(blck: aggregationHead, slot: aggregationSlot)
|
2020-07-30 19:18:17 +00:00
|
|
|
node.chainDag.withState(node.chainDag.tmpState, bs):
|
2020-05-06 13:23:45 +00:00
|
|
|
let
|
2020-07-23 17:01:07 +00:00
|
|
|
committees_per_slot =
|
2020-07-27 10:59:57 +00:00
|
|
|
get_committee_count_per_slot(state, aggregationSlot.epoch, cache)
|
2020-09-14 14:50:03 +00:00
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
var
|
|
|
|
slotSigs: seq[Future[ValidatorSig]] = @[]
|
|
|
|
slotSigsData: seq[tuple[committee_index: uint64,
|
|
|
|
validator_idx: ValidatorIndex,
|
|
|
|
v: AttachedValidator]] = @[]
|
2020-09-14 14:50:03 +00:00
|
|
|
|
2020-05-06 13:23:45 +00:00
|
|
|
for committee_index in 0'u64..<committees_per_slot:
|
|
|
|
let committee = get_beacon_committee(
|
|
|
|
state, aggregationSlot, committee_index.CommitteeIndex, cache)
|
|
|
|
|
|
|
|
for index_in_committee, validatorIdx in committee:
|
|
|
|
let validator = node.getAttachedValidator(state, validatorIdx)
|
|
|
|
if validator != nil:
|
2020-09-01 13:44:40 +00:00
|
|
|
# the validator index and private key pair.
|
|
|
|
slotSigs.add getSlotSig(validator, state.fork,
|
|
|
|
state.genesis_validators_root, state.slot)
|
|
|
|
slotSigsData.add (committee_index, validatorIdx, validator)
|
|
|
|
|
|
|
|
await allFutures(slotSigs)
|
|
|
|
|
|
|
|
for curr in zip(slotSigsData, slotSigs):
|
|
|
|
let aggregateAndProof =
|
|
|
|
aggregate_attestations(node.attestationPool[], state,
|
|
|
|
curr[0].committee_index.CommitteeIndex,
|
|
|
|
curr[0].validator_idx,
|
|
|
|
curr[1].read, cache)
|
|
|
|
|
|
|
|
# Don't broadcast when, e.g., this node isn't aggregator
|
|
|
|
# TODO verify there is only one isSome() with test.
|
|
|
|
if aggregateAndProof.isSome:
|
2020-09-14 14:50:03 +00:00
|
|
|
let sig = await signAggregateAndProof(curr[0].v,
|
2020-09-01 13:44:40 +00:00
|
|
|
aggregateAndProof.get, state.fork,
|
|
|
|
state.genesis_validators_root)
|
|
|
|
var signedAP = SignedAggregateAndProof(
|
|
|
|
message: aggregateAndProof.get,
|
|
|
|
signature: sig)
|
|
|
|
node.network.broadcast(node.topicAggregateAndProofs, signedAP)
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Aggregated attestation sent",
|
2020-09-01 13:44:40 +00:00
|
|
|
attestation = shortLog(signedAP.message.aggregate),
|
|
|
|
validator = shortLog(curr[0].v)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
proc handleValidatorDuties*(
|
2020-06-10 06:58:12 +00:00
|
|
|
node: BeaconNode, lastSlot, slot: Slot) {.async.} =
|
2020-07-22 08:04:21 +00:00
|
|
|
## Perform validator duties - create blocks, vote and aggregate existing votes
|
2020-08-26 15:23:34 +00:00
|
|
|
let maybeHead = node.updateHead(slot)
|
|
|
|
if maybeHead.isNil():
|
|
|
|
error "Couldn't update head - cannot proceed with validator duties"
|
|
|
|
return
|
|
|
|
var head = maybeHead
|
2020-05-06 13:23:45 +00:00
|
|
|
if node.attachedValidators.count == 0:
|
|
|
|
# Nothing to do because we have no validator attached
|
2020-06-10 06:58:12 +00:00
|
|
|
return
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
if not node.isSynced(head):
|
|
|
|
notice "Node out of sync, skipping validator duties",
|
|
|
|
slot, headSlot = head.slot
|
2020-06-10 06:58:12 +00:00
|
|
|
return
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
var curSlot = lastSlot + 1
|
|
|
|
|
|
|
|
# Start by checking if there's work we should have done in the past that we
|
|
|
|
# can still meaningfully do
|
|
|
|
while curSlot < slot:
|
|
|
|
# TODO maybe even collect all work synchronously to avoid unnecessary
|
|
|
|
# state rewinds while waiting for async operations like validator
|
|
|
|
# signature..
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Catching up on validator duties",
|
2020-05-06 13:23:45 +00:00
|
|
|
curSlot = shortLog(curSlot),
|
|
|
|
lastSlot = shortLog(lastSlot),
|
2020-07-16 13:16:51 +00:00
|
|
|
slot = shortLog(slot)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
|
|
|
# For every slot we're catching up, we'll propose then send
|
|
|
|
# attestations - head should normally be advancing along the same branch
|
|
|
|
# in this case
|
|
|
|
# TODO what if we receive blocks / attestations while doing this work?
|
|
|
|
head = await handleProposal(node, head, curSlot)
|
|
|
|
|
|
|
|
# For each slot we missed, we need to send out attestations - if we were
|
|
|
|
# proposing during this time, we'll use the newly proposed head, else just
|
|
|
|
# keep reusing the same - the attestation that goes out will actually
|
|
|
|
# rewind the state to what it looked like at the time of that slot
|
|
|
|
# TODO smells like there's an optimization opportunity here
|
|
|
|
handleAttestations(node, head, curSlot)
|
|
|
|
|
|
|
|
curSlot += 1
|
|
|
|
|
|
|
|
head = await handleProposal(node, head, slot)
|
|
|
|
|
|
|
|
# We've been doing lots of work up until now which took time. Normally, we
|
|
|
|
# send out attestations at the slot thirds-point, so we go back to the clock
|
|
|
|
# to see how much time we need to wait.
|
|
|
|
# TODO the beacon clock might jump here also. It's probably easier to complete
|
|
|
|
# the work for the whole slot using a monotonic clock instead, then deal
|
|
|
|
# with any clock discrepancies once only, at the start of slot timer
|
|
|
|
# processing..
|
|
|
|
|
2020-09-24 17:04:10 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.12.3/specs/phase0/validator.md#attesting
|
2020-05-06 13:23:45 +00:00
|
|
|
# A validator should create and broadcast the attestation to the associated
|
|
|
|
# attestation subnet when either (a) the validator has received a valid
|
|
|
|
# block from the expected block proposer for the assigned slot or
|
|
|
|
# (b) one-third of the slot has transpired (`SECONDS_PER_SLOT / 3` seconds
|
|
|
|
# after the start of slot) -- whichever comes first.
|
2020-06-05 09:57:40 +00:00
|
|
|
template sleepToSlotOffsetWithHeadUpdate(extra: chronos.Duration, msg: static string) =
|
|
|
|
if await node.beaconClock.sleepToSlotOffset(extra, slot, msg):
|
2020-05-06 13:23:45 +00:00
|
|
|
# Time passed - we might need to select a new head in that case
|
2020-08-26 15:23:34 +00:00
|
|
|
let maybeHead = node.updateHead(slot)
|
|
|
|
if not maybeHead.isNil():
|
|
|
|
head = maybeHead
|
|
|
|
else:
|
|
|
|
error "Couldn't update head"
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-06-05 09:57:40 +00:00
|
|
|
sleepToSlotOffsetWithHeadUpdate(
|
2020-05-06 13:23:45 +00:00
|
|
|
seconds(int64(SECONDS_PER_SLOT)) div 3, "Waiting to send attestations")
|
|
|
|
|
|
|
|
handleAttestations(node, head, slot)
|
|
|
|
|
2020-09-24 17:04:10 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.12.3/specs/phase0/validator.md#broadcast-aggregate
|
2020-05-06 13:23:45 +00:00
|
|
|
# If the validator is selected to aggregate (is_aggregator), then they
|
|
|
|
# broadcast their best aggregate as a SignedAggregateAndProof to the global
|
|
|
|
# aggregate channel (beacon_aggregate_and_proof) two-thirds of the way
|
|
|
|
# through the slot-that is, SECONDS_PER_SLOT * 2 / 3 seconds after the start
|
|
|
|
# of slot.
|
|
|
|
if slot > 2:
|
2020-06-05 09:57:40 +00:00
|
|
|
sleepToSlotOffsetWithHeadUpdate(
|
2020-05-06 13:23:45 +00:00
|
|
|
seconds(int64(SECONDS_PER_SLOT * 2) div 3),
|
|
|
|
"Waiting to aggregate attestations")
|
|
|
|
|
|
|
|
const TRAILING_DISTANCE = 1
|
2020-09-25 11:52:50 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.12.3/specs/phase0/p2p-interface.md#configuration
|
2020-08-21 01:22:26 +00:00
|
|
|
static:
|
|
|
|
doAssert TRAILING_DISTANCE <= ATTESTATION_PROPAGATION_SLOT_RANGE
|
|
|
|
|
2020-05-06 13:23:45 +00:00
|
|
|
let
|
|
|
|
aggregationSlot = slot - TRAILING_DISTANCE
|
2020-08-03 19:47:42 +00:00
|
|
|
aggregationHead = get_ancestor(head, aggregationSlot)
|
2020-05-06 13:23:45 +00:00
|
|
|
|
2020-09-01 13:44:40 +00:00
|
|
|
await broadcastAggregatedAttestations(node, aggregationHead, aggregationSlot)
|