2018-11-23 23:58:49 +00:00
|
|
|
import
|
2019-04-08 12:46:12 +00:00
|
|
|
net, sequtils, options, tables, osproc, random, strutils, times, strformat,
|
2019-07-07 09:53:58 +00:00
|
|
|
stew/shims/os, stew/objects,
|
2019-03-20 00:05:10 +00:00
|
|
|
chronos, chronicles, confutils, serialization/errors,
|
2019-03-28 11:01:28 +00:00
|
|
|
eth/trie/db, eth/trie/backends/rocksdb_backend, eth/async_utils,
|
2019-03-20 20:01:48 +00:00
|
|
|
spec/[bitfield, datatypes, digest, crypto, beaconstate, helpers, validator],
|
2019-06-17 11:08:05 +00:00
|
|
|
conf, time, state_transition, fork_choice, ssz, beacon_chain_db,
|
|
|
|
validator_pool, extras, attestation_pool, block_pool, eth2_network,
|
|
|
|
beacon_node_types, mainchain_monitor, trusted_state_snapshots, version,
|
2019-07-12 14:24:11 +00:00
|
|
|
sync_protocol, request_manager, genesis
|
2018-11-23 23:58:49 +00:00
|
|
|
|
|
|
|
const
|
2018-11-26 13:33:06 +00:00
|
|
|
topicBeaconBlocks = "ethereum/2.1/beacon_chain/blocks"
|
|
|
|
topicAttestations = "ethereum/2.1/beacon_chain/attestations"
|
2019-02-07 21:14:08 +00:00
|
|
|
|
2019-03-18 03:54:08 +00:00
|
|
|
dataDirValidators = "validators"
|
|
|
|
networkMetadataFile = "network.json"
|
|
|
|
genesisFile = "genesis.json"
|
2019-03-19 17:22:17 +00:00
|
|
|
testnetsBaseUrl = "https://serenity-testnets.status.im"
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-02-18 10:34:39 +00:00
|
|
|
proc onBeaconBlock*(node: BeaconNode, blck: BeaconBlock) {.gcsafe.}
|
|
|
|
|
2019-03-18 03:54:08 +00:00
|
|
|
func localValidatorsDir(conf: BeaconNodeConf): string =
|
|
|
|
conf.dataDir / "validators"
|
|
|
|
|
|
|
|
func databaseDir(conf: BeaconNodeConf): string =
|
|
|
|
conf.dataDir / "db"
|
|
|
|
|
|
|
|
template `//`(url, fragment: string): string =
|
|
|
|
url & "/" & fragment
|
|
|
|
|
|
|
|
proc downloadFile(url: string): Future[string] {.async.} =
|
2019-04-01 18:41:35 +00:00
|
|
|
let cmd = "curl --fail " & url
|
|
|
|
let (fileContents, errorCode) = execCmdEx(cmd, options = {poUsePath})
|
2019-03-18 03:54:08 +00:00
|
|
|
if errorCode != 0:
|
2019-04-01 18:41:35 +00:00
|
|
|
raise newException(IOError, "Failed external command: '" & cmd & "', exit code: " & $errorCode & ", output: '" & fileContents & "'")
|
2019-03-18 03:54:08 +00:00
|
|
|
return fileContents
|
|
|
|
|
2019-03-19 17:22:17 +00:00
|
|
|
proc updateTestnetMetadata(conf: BeaconNodeConf): Future[NetworkMetadata] {.async.} =
|
2019-06-24 12:57:22 +00:00
|
|
|
let metadataUrl = testnetsBaseUrl // $conf.network // networkMetadataFile
|
2019-04-08 12:46:12 +00:00
|
|
|
let latestMetadata = await downloadFile(metadataUrl)
|
|
|
|
|
|
|
|
try:
|
|
|
|
result = Json.decode(latestMetadata, NetworkMetadata)
|
|
|
|
except SerializationError as err:
|
|
|
|
stderr.write "Error while loading the testnet metadata. Your client my be out of date.\n"
|
|
|
|
stderr.write err.formatMsg(metadataUrl), "\n"
|
|
|
|
stderr.write "Please follow the instructions at https://github.com/status-im/nim-beacon-chain " &
|
|
|
|
"in order to produce an up-to-date build.\n"
|
|
|
|
quit 1
|
2019-03-20 00:05:10 +00:00
|
|
|
|
2019-03-18 03:54:08 +00:00
|
|
|
let localMetadataFile = conf.dataDir / networkMetadataFile
|
|
|
|
if fileExists(localMetadataFile) and readFile(localMetadataFile).string == latestMetadata:
|
|
|
|
return
|
|
|
|
|
2019-03-19 17:22:17 +00:00
|
|
|
info "New testnet genesis data received. Starting with a fresh database."
|
2019-03-27 16:29:02 +00:00
|
|
|
|
|
|
|
createDir conf.dataDir.string
|
2019-03-18 03:54:08 +00:00
|
|
|
removeDir conf.databaseDir
|
|
|
|
writeFile localMetadataFile, latestMetadata
|
|
|
|
|
|
|
|
let newGenesis = await downloadFile(testnetsBaseUrl // $conf.network // genesisFile)
|
|
|
|
writeFile conf.dataDir / genesisFile, newGenesis
|
|
|
|
|
2019-03-25 23:26:11 +00:00
|
|
|
proc obtainTestnetKey(conf: BeaconNodeConf): Future[(string, string)] {.async.} =
|
2019-03-18 03:54:08 +00:00
|
|
|
let
|
2019-03-19 17:22:17 +00:00
|
|
|
metadata = await updateTestnetMetadata(conf)
|
2019-03-18 03:54:08 +00:00
|
|
|
privKeyName = validatorFileBaseName(rand(metadata.userValidatorsRange)) & ".privkey"
|
2019-03-27 16:29:02 +00:00
|
|
|
privKeyUrl = testnetsBaseUrl // $conf.network // privKeyName
|
|
|
|
privKeyContent = strip await downloadFile(privKeyUrl)
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-03-25 23:26:11 +00:00
|
|
|
let key = ValidatorPrivKey.init(privKeyContent)
|
|
|
|
return (privKeyName, privKeyContent)
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-03-25 23:26:11 +00:00
|
|
|
proc saveValidatorKey(keyName, key: string, conf: BeaconNodeConf) =
|
2019-03-19 21:04:22 +00:00
|
|
|
let validatorsDir = conf.dataDir / dataDirValidators
|
2019-03-25 23:26:11 +00:00
|
|
|
let outputFile = validatorsDir / keyName
|
2019-03-19 21:04:22 +00:00
|
|
|
createDir validatorsDir
|
2019-03-25 23:26:11 +00:00
|
|
|
writeFile(outputFile, key)
|
|
|
|
info "Imported validator key", file = outputFile
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
proc init*(T: type BeaconNode, conf: BeaconNodeConf): Future[BeaconNode] {.async.} =
|
2018-11-23 23:58:49 +00:00
|
|
|
new result
|
2019-06-17 11:08:05 +00:00
|
|
|
result.onBeaconBlock = onBeaconBlock
|
2018-11-23 23:58:49 +00:00
|
|
|
result.config = conf
|
2019-05-22 07:13:15 +00:00
|
|
|
result.networkIdentity = getPersistentNetIdentity(conf)
|
|
|
|
result.nickname = if conf.nodename == "auto": shortForm(result.networkIdentity)
|
2019-03-22 14:35:20 +00:00
|
|
|
else: conf.nodename
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-03-19 17:22:17 +00:00
|
|
|
template fail(args: varargs[untyped]) =
|
|
|
|
stderr.write args, "\n"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
case conf.network
|
|
|
|
of "mainnet":
|
|
|
|
fail "The Serenity mainnet hasn't been launched yet"
|
|
|
|
of "testnet0", "testnet1":
|
|
|
|
result.networkMetadata = await updateTestnetMetadata(conf)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
result.networkMetadata = Json.loadFile(conf.network, NetworkMetadata)
|
2019-06-24 15:13:48 +00:00
|
|
|
except SerializationError as err:
|
|
|
|
fail "Failed to load network metadata: \n", err.formatMsg(conf.network)
|
2019-03-19 17:22:17 +00:00
|
|
|
|
|
|
|
var metadataErrorMsg = ""
|
|
|
|
|
|
|
|
template checkCompatibility(metadataField, LOCAL_CONSTANT) =
|
|
|
|
let metadataValue = metadataField
|
|
|
|
if metadataValue != LOCAL_CONSTANT:
|
2019-03-23 10:57:18 +00:00
|
|
|
if metadataErrorMsg.len > 0: metadataErrorMsg.add " and"
|
|
|
|
metadataErrorMsg.add " -d:" & astToStr(LOCAL_CONSTANT) & "=" & $metadataValue &
|
|
|
|
" (instead of " & $LOCAL_CONSTANT & ")"
|
2019-03-19 17:22:17 +00:00
|
|
|
|
2019-04-08 12:46:12 +00:00
|
|
|
if result.networkMetadata.networkGeneration != semanticVersion:
|
|
|
|
let newerVersionRequired = result.networkMetadata.networkGeneration.int > semanticVersion
|
|
|
|
let newerOrOlder = if newerVersionRequired: "a newer" else: "an older"
|
|
|
|
stderr.write &"Connecting to '{conf.network}' requires {newerOrOlder} version of Nimbus. "
|
|
|
|
if newerVersionRequired:
|
|
|
|
stderr.write "Please follow the instructions at https://github.com/status-im/nim-beacon-chain " &
|
|
|
|
"in order to produce an up-to-date build.\n"
|
|
|
|
quit 1
|
|
|
|
|
2019-03-19 17:22:17 +00:00
|
|
|
checkCompatibility result.networkMetadata.numShards , SHARD_COUNT
|
|
|
|
checkCompatibility result.networkMetadata.slotDuration , SECONDS_PER_SLOT
|
|
|
|
checkCompatibility result.networkMetadata.slotsPerEpoch , SLOTS_PER_EPOCH
|
|
|
|
|
|
|
|
if metadataErrorMsg.len > 0:
|
2019-03-20 00:05:10 +00:00
|
|
|
fail "To connect to the ", conf.network, " network, please compile with", metadataErrorMsg
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2018-12-28 16:51:40 +00:00
|
|
|
result.attachedValidators = ValidatorPool.init
|
|
|
|
init result.mainchainMonitor, "", Port(0) # TODO: specify geth address and port
|
|
|
|
|
2019-03-18 03:54:08 +00:00
|
|
|
let trieDB = trieDB newChainDb(string conf.databaseDir)
|
2019-01-14 12:19:44 +00:00
|
|
|
result.db = BeaconChainDB.init(trieDB)
|
2019-01-25 14:17:35 +00:00
|
|
|
|
2019-02-28 21:21:29 +00:00
|
|
|
# TODO this is problably not the right place to ensure that db is sane..
|
2019-02-21 04:42:17 +00:00
|
|
|
# TODO does it really make sense to load from DB if a state snapshot has been
|
|
|
|
# specified on command line? potentially, this should be the other way
|
|
|
|
# around...
|
|
|
|
|
2019-02-28 21:21:29 +00:00
|
|
|
let headBlock = result.db.getHeadBlock()
|
|
|
|
if headBlock.isNone():
|
2019-03-18 03:54:08 +00:00
|
|
|
var snapshotFile = conf.dataDir / genesisFile
|
|
|
|
if conf.stateSnapshot.isSome:
|
|
|
|
snapshotFile = conf.stateSnapshot.get.string
|
|
|
|
elif not fileExists(snapshotFile):
|
|
|
|
error "Nimbus database not initialized. Please specify the initial state snapshot file."
|
|
|
|
quit 1
|
|
|
|
|
2019-03-20 00:05:10 +00:00
|
|
|
try:
|
|
|
|
info "Importing snapshot file", path = snapshotFile
|
2019-07-12 14:24:11 +00:00
|
|
|
info "Waiting for genesis state from eth1"
|
2019-03-20 00:05:10 +00:00
|
|
|
|
|
|
|
let
|
2019-07-12 14:24:11 +00:00
|
|
|
tailState = await getGenesisFromEth1(conf)
|
|
|
|
# tailState = Json.loadFile(snapshotFile, BeaconState)
|
2019-03-20 00:05:10 +00:00
|
|
|
tailBlock = get_initial_beacon_block(tailState)
|
|
|
|
|
2019-07-12 14:24:11 +00:00
|
|
|
info "Got genesis state", hash = hash_tree_root(tailState)
|
2019-03-28 06:10:48 +00:00
|
|
|
BlockPool.preInit(result.db, tailState, tailBlock)
|
2019-03-20 00:05:10 +00:00
|
|
|
|
|
|
|
except SerializationError as err:
|
|
|
|
stderr.write "Failed to import ", snapshotFile, "\n"
|
|
|
|
stderr.write err.formatMsg(snapshotFile), "\n"
|
|
|
|
quit 1
|
|
|
|
except:
|
|
|
|
stderr.write "Failed to initialize database\n"
|
|
|
|
stderr.write getCurrentExceptionMsg(), "\n"
|
|
|
|
quit 1
|
2019-02-28 21:21:29 +00:00
|
|
|
|
|
|
|
result.blockPool = BlockPool.init(result.db)
|
|
|
|
result.attestationPool = AttestationPool.init(result.blockPool)
|
2019-01-25 14:17:35 +00:00
|
|
|
|
2019-03-18 03:54:08 +00:00
|
|
|
result.network = await createEth2Node(conf)
|
2019-03-28 14:03:19 +00:00
|
|
|
result.requestManager.init result.network
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
# TODO sync is called when a remote peer is connected - is that the right
|
|
|
|
# time to do so?
|
2019-03-18 03:54:08 +00:00
|
|
|
let sync = result.network.protocolState(BeaconSync)
|
2019-05-22 07:13:15 +00:00
|
|
|
sync.chainId = 0 # TODO specify chainId
|
2019-03-19 17:22:17 +00:00
|
|
|
sync.networkId = result.networkMetadata.networkId
|
2019-03-18 03:54:08 +00:00
|
|
|
sync.node = result
|
|
|
|
sync.db = result.db
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
result.stateCache = result.blockPool.loadTailState()
|
|
|
|
result.justifiedStateCache = result.stateCache
|
2018-11-23 23:58:49 +00:00
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
let addressFile = string(conf.dataDir) / "beacon_node.address"
|
|
|
|
result.network.saveConnectionAddressFile(addressFile)
|
2019-05-04 14:10:45 +00:00
|
|
|
result.beaconClock = BeaconClock.init(result.stateCache.data.data)
|
2019-04-06 07:46:07 +00:00
|
|
|
|
|
|
|
template withState(
|
|
|
|
pool: BlockPool, cache: var StateData, blockSlot: BlockSlot, body: untyped): untyped =
|
|
|
|
## Helper template that updates state to a particular BlockSlot - usage of
|
|
|
|
## cache is unsafe outside of block.
|
|
|
|
## TODO async transformations will lead to a race where cache gets updated
|
|
|
|
## while waiting for future to complete - catch this here somehow?
|
|
|
|
|
2019-04-29 08:14:22 +00:00
|
|
|
updateStateData(pool, cache, blockSlot)
|
2019-04-06 07:46:07 +00:00
|
|
|
|
2019-05-04 14:10:45 +00:00
|
|
|
template hashedState(): HashedBeaconState {.inject.} = cache.data
|
|
|
|
template state(): BeaconState {.inject.} = cache.data.data
|
2019-04-06 07:46:07 +00:00
|
|
|
template blck(): BlockRef {.inject.} = cache.blck
|
2019-05-04 14:10:45 +00:00
|
|
|
template root(): Eth2Digest {.inject.} = cache.data.root
|
2019-04-06 07:46:07 +00:00
|
|
|
|
|
|
|
body
|
2018-12-19 12:58:53 +00:00
|
|
|
|
|
|
|
proc connectToNetwork(node: BeaconNode) {.async.} =
|
2019-03-20 01:18:49 +00:00
|
|
|
var bootstrapNodes = newSeq[BootstrapAddr]()
|
|
|
|
|
|
|
|
for bootNode in node.networkMetadata.bootstrapNodes:
|
2019-05-22 07:13:15 +00:00
|
|
|
if bootNode.isSameNode(node.networkIdentity):
|
2019-03-20 01:18:49 +00:00
|
|
|
node.isBootstrapNode = true
|
|
|
|
else:
|
|
|
|
bootstrapNodes.add bootNode
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-03-19 17:22:17 +00:00
|
|
|
for bootNode in node.config.bootstrapNodes:
|
|
|
|
bootstrapNodes.add BootstrapAddr.init(bootNode)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
|
|
|
let bootstrapFile = string node.config.bootstrapNodesFile
|
|
|
|
if bootstrapFile.len > 0:
|
|
|
|
for ln in lines(bootstrapFile):
|
2019-03-05 22:54:08 +00:00
|
|
|
bootstrapNodes.add BootstrapAddr.init(string ln)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
|
|
|
if bootstrapNodes.len > 0:
|
2018-12-28 16:51:40 +00:00
|
|
|
info "Connecting to bootstrap nodes", bootstrapNodes
|
2018-12-19 12:58:53 +00:00
|
|
|
else:
|
2018-12-28 16:51:40 +00:00
|
|
|
info "Waiting for connections"
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2019-02-27 08:15:24 +00:00
|
|
|
await node.network.connectToNetwork(bootstrapNodes)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2018-12-05 13:58:41 +00:00
|
|
|
template findIt(s: openarray, predicate: untyped): int =
|
|
|
|
var res = -1
|
|
|
|
for i, it {.inject.} in s:
|
|
|
|
if predicate:
|
|
|
|
res = i
|
|
|
|
break
|
|
|
|
res
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
proc addLocalValidator(
|
|
|
|
node: BeaconNode, state: BeaconState, privKey: ValidatorPrivKey) =
|
|
|
|
let pubKey = privKey.pubKey()
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-07-01 09:13:14 +00:00
|
|
|
let idx = state.validators.findIt(it.pubKey == pubKey)
|
2019-03-18 03:54:08 +00:00
|
|
|
if idx == -1:
|
|
|
|
warn "Validator not in registry", pubKey
|
|
|
|
else:
|
2019-04-06 07:46:07 +00:00
|
|
|
node.attachedValidators.addLocalValidator(pubKey, privKey)
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
proc addLocalValidators(node: BeaconNode, state: BeaconState) =
|
2019-03-18 03:54:08 +00:00
|
|
|
for validatorKeyFile in node.config.validators:
|
2019-04-06 07:46:07 +00:00
|
|
|
node.addLocalValidator state, validatorKeyFile.load
|
2019-03-18 03:54:08 +00:00
|
|
|
|
|
|
|
for kind, file in walkDir(node.config.localValidatorsDir):
|
|
|
|
if kind in {pcFile, pcLinkToFile}:
|
2019-04-06 07:46:07 +00:00
|
|
|
node.addLocalValidator state, ValidatorPrivKey.init(readFile(file).string)
|
2018-12-05 13:58:41 +00:00
|
|
|
|
2018-12-28 16:51:40 +00:00
|
|
|
info "Local validators attached ", count = node.attachedValidators.count
|
2018-11-23 23:58:49 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
proc getAttachedValidator(
|
|
|
|
node: BeaconNode, state: BeaconState, idx: int): AttachedValidator =
|
2019-07-01 09:13:14 +00:00
|
|
|
let validatorKey = state.validators[idx].pubkey
|
2019-04-06 07:46:07 +00:00
|
|
|
node.attachedValidators.getValidator(validatorKey)
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
proc updateHead(node: BeaconNode, slot: Slot): BlockRef =
|
|
|
|
# Use head state for attestation resolution below
|
|
|
|
# TODO do we need to resolve attestations using all available head states?
|
2019-04-06 07:46:07 +00:00
|
|
|
node.blockPool.withState(
|
2019-05-01 09:19:29 +00:00
|
|
|
node.stateCache, BlockSlot(blck: node.blockPool.head.blck, slot: slot)):
|
2019-04-06 07:46:07 +00:00
|
|
|
# Check pending attestations - maybe we found some blocks for them
|
|
|
|
node.attestationPool.resolve(state)
|
|
|
|
|
|
|
|
# TODO move all of this logic to BlockPool
|
|
|
|
debug "Preparing for fork choice",
|
|
|
|
stateRoot = shortLog(root),
|
2019-05-22 07:13:15 +00:00
|
|
|
connectedPeers = node.network.peersCount,
|
2019-04-06 07:46:07 +00:00
|
|
|
stateSlot = humaneSlotNum(state.slot),
|
2019-07-01 07:53:42 +00:00
|
|
|
stateEpoch = humaneEpochNum(state.slot.computeEpochOfSlot)
|
2019-03-22 11:33:10 +00:00
|
|
|
|
2019-03-13 22:59:20 +00:00
|
|
|
let
|
|
|
|
justifiedHead = node.blockPool.latestJustifiedBlock()
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-03-14 13:33:56 +00:00
|
|
|
# TODO slot number is wrong here, it should be the start of the epoch that
|
|
|
|
# got finalized:
|
|
|
|
# https://github.com/ethereum/eth2.0-specs/issues/768
|
2019-04-06 07:46:07 +00:00
|
|
|
let newHead = node.blockPool.withState(
|
|
|
|
node.justifiedStateCache,
|
|
|
|
BlockSlot(blck: justifiedHead, slot: justifiedHead.slot)):
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
lmdGhost(node.attestationPool, state, justifiedHead)
|
2019-03-22 16:26:52 +00:00
|
|
|
info "Fork chosen",
|
|
|
|
newHeadSlot = humaneSlotNum(newHead.slot),
|
2019-07-01 07:53:42 +00:00
|
|
|
newHeadEpoch = humaneEpochNum(newHead.slot.computeEpochOfSlot),
|
2019-03-22 16:26:52 +00:00
|
|
|
newHeadBlockRoot = shortLog(newHead.root)
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
node.blockPool.updateHead(node.stateCache, newHead)
|
2019-03-13 22:59:20 +00:00
|
|
|
newHead
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
proc sendAttestation(node: BeaconNode,
|
2018-12-28 16:51:40 +00:00
|
|
|
validator: AttachedValidator,
|
2019-04-06 07:46:07 +00:00
|
|
|
attestationData: AttestationData,
|
2018-12-28 16:51:40 +00:00
|
|
|
committeeLen: int,
|
|
|
|
indexInCommittee: int) {.async.} =
|
2019-03-09 04:23:14 +00:00
|
|
|
let
|
2019-02-19 23:35:02 +00:00
|
|
|
validatorSignature = await validator.signAttestation(attestationData)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2019-03-20 20:01:48 +00:00
|
|
|
var aggregationBitfield = BitField.init(committeeLen)
|
|
|
|
set_bitfield_bit(aggregationBitfield, indexInCommittee)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
|
|
|
var attestation = Attestation(
|
|
|
|
data: attestationData,
|
2019-06-12 07:48:49 +00:00
|
|
|
signature: validatorSignature,
|
2019-07-01 07:53:42 +00:00
|
|
|
aggregation_bits: aggregationBitfield,
|
2019-02-12 22:50:02 +00:00
|
|
|
# Stub in phase0
|
2019-07-01 07:53:42 +00:00
|
|
|
custody_bits: BitField.init(committeeLen)
|
2019-02-12 22:50:02 +00:00
|
|
|
)
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-03-28 11:01:28 +00:00
|
|
|
node.network.broadcast(topicAttestations, attestation)
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-02-19 23:35:02 +00:00
|
|
|
info "Attestation sent",
|
2019-03-20 20:01:48 +00:00
|
|
|
attestationData = shortLog(attestationData),
|
2019-04-06 07:46:07 +00:00
|
|
|
validator = shortLog(validator),
|
2019-03-20 20:01:48 +00:00
|
|
|
signature = shortLog(validatorSignature)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2018-11-29 01:08:34 +00:00
|
|
|
proc proposeBlock(node: BeaconNode,
|
|
|
|
validator: AttachedValidator,
|
2019-03-22 15:49:37 +00:00
|
|
|
head: BlockRef,
|
|
|
|
slot: Slot): Future[BlockRef] {.async.} =
|
2019-03-14 13:33:56 +00:00
|
|
|
if head.slot > slot:
|
|
|
|
notice "Skipping proposal, we've already selected a newer head",
|
|
|
|
headSlot = humaneSlotNum(head.slot),
|
|
|
|
headBlockRoot = shortLog(head.root),
|
|
|
|
slot = humaneSlotNum(slot)
|
2019-03-22 15:49:37 +00:00
|
|
|
return head
|
2019-03-14 13:33:56 +00:00
|
|
|
|
|
|
|
if head.slot == slot:
|
|
|
|
# Weird, we should never see as head the same slot as we're proposing a
|
|
|
|
# block for - did someone else steal our slot? why didn't we discard it?
|
|
|
|
warn "Found head at same slot as we're supposed to propose for!",
|
|
|
|
headSlot = humaneSlotNum(head.slot),
|
|
|
|
headBlockRoot = shortLog(head.root)
|
|
|
|
# TODO investigate how and when this happens.. maybe it shouldn't be an
|
|
|
|
# assert?
|
|
|
|
doAssert false, "head slot matches proposal slot (!)"
|
|
|
|
# return
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
var (nroot, nblck) = node.blockPool.withState(
|
|
|
|
node.stateCache, BlockSlot(blck: head, slot: slot - 1)):
|
|
|
|
# To create a block, we'll first apply a partial block to the state, skipping
|
|
|
|
# some validations.
|
|
|
|
let
|
|
|
|
blockBody = BeaconBlockBody(
|
|
|
|
randao_reveal: validator.genRandaoReveal(state, slot),
|
|
|
|
eth1_data: node.mainchainMonitor.getBeaconBlockRef(),
|
|
|
|
attestations:
|
|
|
|
node.attestationPool.getAttestationsForBlock(state, slot))
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
var
|
|
|
|
newBlock = BeaconBlock(
|
|
|
|
slot: slot,
|
2019-06-14 13:50:47 +00:00
|
|
|
parent_root: head.root,
|
2019-04-06 07:46:07 +00:00
|
|
|
body: blockBody,
|
|
|
|
signature: ValidatorSig(), # we need the rest of the block first!
|
|
|
|
)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2019-05-04 14:10:45 +00:00
|
|
|
var tmpState = hashedState
|
2019-04-29 08:14:22 +00:00
|
|
|
|
2019-07-15 21:10:40 +00:00
|
|
|
let ok = state_transition(tmpState, newBlock, {skipValidation})
|
2019-06-12 07:48:49 +00:00
|
|
|
# TODO only enable in fast-fail debugging situations
|
|
|
|
# otherwise, bad attestations can bring down network
|
|
|
|
# doAssert ok # TODO: err, could this fail somehow?
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-05-04 14:10:45 +00:00
|
|
|
newBlock.state_root = tmpState.root
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-05-09 12:27:37 +00:00
|
|
|
let blockRoot = signing_root(newBlock)
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
# Careful, state no longer valid after here..
|
|
|
|
newBlock.signature =
|
2019-04-29 16:48:30 +00:00
|
|
|
await validator.signBlockProposal(state, slot, blockRoot)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
(blockRoot, newBlock)
|
|
|
|
|
|
|
|
let newBlockRef = node.blockPool.add(node.stateCache, nroot, nblck)
|
2019-03-27 20:17:01 +00:00
|
|
|
if newBlockRef == nil:
|
|
|
|
warn "Unable to add proposed block to block pool",
|
|
|
|
newBlock = shortLog(newBlock),
|
|
|
|
blockRoot = shortLog(blockRoot)
|
|
|
|
return head
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-02-19 23:35:02 +00:00
|
|
|
info "Block proposed",
|
2019-03-20 20:01:48 +00:00
|
|
|
blck = shortLog(newBlock),
|
2019-03-22 15:49:37 +00:00
|
|
|
blockRoot = shortLog(newBlockRef.root),
|
2019-04-06 07:46:07 +00:00
|
|
|
validator = shortLog(validator)
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-03-28 11:01:28 +00:00
|
|
|
node.network.broadcast(topicBeaconBlocks, newBlock)
|
2019-01-25 17:35:22 +00:00
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
return newBlockRef
|
2018-11-23 23:58:49 +00:00
|
|
|
|
2019-02-28 21:21:29 +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
|
|
|
|
debug "Attestation received",
|
2019-03-20 20:01:48 +00:00
|
|
|
attestationData = shortLog(attestation.data),
|
2019-06-12 07:48:49 +00:00
|
|
|
signature = shortLog(attestation.signature)
|
2019-02-21 04:42:17 +00:00
|
|
|
|
2019-03-28 17:06:43 +00:00
|
|
|
# TODO seems reasonable to use the latest head state here.. needs thinking
|
|
|
|
# though - maybe we should use the state from the block pointed to by
|
|
|
|
# the attestation for some of the check? Consider interop with block
|
|
|
|
# production!
|
2019-04-06 07:46:07 +00:00
|
|
|
node.blockPool.withState(node.stateCache,
|
2019-05-01 09:19:29 +00:00
|
|
|
BlockSlot(blck: node.blockPool.head.blck, slot: node.beaconClock.now().toSlot())):
|
2019-04-06 07:46:07 +00:00
|
|
|
node.attestationPool.add(state, attestation)
|
2019-02-21 04:42:17 +00:00
|
|
|
|
|
|
|
proc onBeaconBlock(node: BeaconNode, blck: BeaconBlock) =
|
2019-02-28 21:21:29 +00:00
|
|
|
# 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.
|
2019-05-09 12:27:37 +00:00
|
|
|
let blockRoot = signing_root(blck)
|
2019-02-28 21:21:29 +00:00
|
|
|
debug "Block received",
|
2019-03-20 20:01:48 +00:00
|
|
|
blck = shortLog(blck),
|
|
|
|
blockRoot = shortLog(blockRoot)
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
if node.blockPool.add(node.stateCache, blockRoot, blck).isNil:
|
2019-03-22 15:49:37 +00:00
|
|
|
return
|
2019-02-28 21:21:29 +00:00
|
|
|
|
|
|
|
# The block we received contains attestations, and we might not yet know about
|
|
|
|
# all of them. Let's add them to the attestation pool - in case they block
|
|
|
|
# is not yet resolved, neither will the attestations be!
|
2019-06-03 08:26:38 +00:00
|
|
|
# TODO shouldn't add attestations if the block turns out to be invalid..
|
2019-02-21 04:42:17 +00:00
|
|
|
for attestation in blck.body.attestations:
|
2019-06-03 08:26:38 +00:00
|
|
|
node.onAttestation(attestation)
|
2019-02-21 04:42:17 +00:00
|
|
|
|
2019-03-22 15:49:37 +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.
|
|
|
|
notice "Skipping attestation, head is too recent",
|
|
|
|
headSlot = humaneSlotNum(head.slot),
|
|
|
|
slot = humaneSlotNum(slot)
|
|
|
|
return
|
|
|
|
|
|
|
|
let attestationHead = head.findAncestorBySlot(slot)
|
2019-05-01 09:19:29 +00:00
|
|
|
if head != attestationHead.blck:
|
2019-03-22 15:49:37 +00:00
|
|
|
# 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 = humaneSlotNum(head.slot),
|
|
|
|
attestationHeadSlot = humaneSlotNum(attestationHead.slot),
|
|
|
|
attestationSlot = humaneSlotNum(slot)
|
|
|
|
|
2019-03-28 06:10:48 +00:00
|
|
|
debug "Checking attestations",
|
2019-05-01 09:19:29 +00:00
|
|
|
attestationHeadRoot = shortLog(attestationHead.blck.root),
|
2019-03-28 06:10:48 +00:00
|
|
|
attestationSlot = humaneSlotNum(slot)
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
|
|
|
|
# Collect data to send before node.stateCache grows stale
|
|
|
|
var attestations: seq[tuple[
|
|
|
|
data: AttestationData, committeeLen, indexInCommittee: int,
|
|
|
|
validator: AttachedValidator]]
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
# 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.
|
2019-05-01 09:19:29 +00:00
|
|
|
node.blockPool.withState(node.stateCache, attestationHead):
|
2019-06-24 09:21:56 +00:00
|
|
|
var cache = get_empty_per_epoch_cache()
|
2019-07-01 07:53:42 +00:00
|
|
|
let epoch = compute_epoch_of_slot(slot)
|
2019-07-02 14:31:48 +00:00
|
|
|
for committee_index in 0'u64 ..< get_committee_count(state, epoch):
|
2019-06-24 09:21:56 +00:00
|
|
|
## TODO verify that this is the correct mapping; it's consistent with
|
|
|
|
## other code
|
|
|
|
let
|
|
|
|
shard = committee_index mod SHARD_COUNT
|
|
|
|
committee = get_crosslink_committee(state, epoch, shard, cache)
|
|
|
|
for i, validatorIdx in committee:
|
2019-04-06 07:46:07 +00:00
|
|
|
let validator = node.getAttachedValidator(state, validatorIdx)
|
|
|
|
if validator != nil:
|
|
|
|
attestations.add (
|
2019-06-24 09:21:56 +00:00
|
|
|
makeAttestationData(state, shard, blck.root),
|
|
|
|
committee.len, i, validator)
|
2019-04-06 07:46:07 +00:00
|
|
|
|
|
|
|
for a in attestations:
|
|
|
|
traceAsyncErrors sendAttestation(
|
|
|
|
node, a.validator, a.data, a.committeeLen, a.indexInCommittee)
|
2019-03-22 15:49:37 +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 advanced the state to the new slot, but later we'll be
|
|
|
|
# proposing for it - basically, we're selecting proposer based on an
|
|
|
|
# empty slot.. wait for the committee selection to settle, then
|
|
|
|
# revisit this - we should be able to advance behind
|
2019-06-24 09:21:56 +00:00
|
|
|
var cache = get_empty_per_epoch_cache()
|
2019-04-06 07:46:07 +00:00
|
|
|
node.blockPool.withState(node.stateCache, BlockSlot(blck: head, slot: slot)):
|
|
|
|
let
|
2019-06-24 09:21:56 +00:00
|
|
|
proposerIdx = get_beacon_proposer_index(state, cache)
|
2019-04-06 07:46:07 +00:00
|
|
|
validator = node.getAttachedValidator(state, proposerIdx)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
if validator != nil:
|
|
|
|
return await proposeBlock(node, validator, head, slot)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
debug "Expecting proposal",
|
|
|
|
headRoot = shortLog(head.root),
|
|
|
|
slot = humaneSlotNum(slot),
|
2019-07-01 09:13:14 +00:00
|
|
|
proposer = shortLog(state.validators[proposerIdx].pubKey)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
|
|
|
return head
|
|
|
|
|
|
|
|
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.
|
|
|
|
## lastSlot: the last slot that we sucessfully processed, so we know where to
|
|
|
|
## start work from
|
|
|
|
## scheduledSlot: the slot that we were aiming for, in terms of timing
|
|
|
|
|
|
|
|
let
|
|
|
|
# The slot we should be at, according to the clock
|
|
|
|
slot = node.beaconClock.now().toSlot()
|
|
|
|
nextSlot = slot + 1
|
|
|
|
|
|
|
|
debug "Slot start",
|
|
|
|
lastSlot = humaneSlotNum(lastSlot),
|
|
|
|
scheduledSlot = humaneSlotNum(scheduledSlot),
|
|
|
|
slot = humaneSlotNum(slot)
|
|
|
|
|
|
|
|
if slot < lastSlot:
|
|
|
|
# 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",
|
|
|
|
slot = humaneSlotNum(slot),
|
|
|
|
scheduledSlot = humaneSlotNum(scheduledSlot)
|
|
|
|
|
|
|
|
addTimer(saturate(node.beaconClock.fromNow(nextSlot))) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(slot, nextSlot)
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
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
|
|
|
|
warn "Unable to keep up, skipping ahead without doing work",
|
|
|
|
lastSlot = humaneSlotNum(lastSlot),
|
|
|
|
slot = humaneSlotNum(slot),
|
|
|
|
scheduledSlot = humaneSlotNum(scheduledSlot)
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
var head = node.updateHead(slot)
|
|
|
|
|
|
|
|
# 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..
|
|
|
|
# Right now, we keep going
|
|
|
|
|
|
|
|
var curSlot = lastSlot + 1
|
|
|
|
while curSlot < slot:
|
|
|
|
# Timers may be delayed because we're busy processing, and we might have
|
|
|
|
# more work to do. We'll try to do so in an expedited way.
|
|
|
|
# TODO maybe even collect all work synchronously to avoid unnecessary
|
|
|
|
# state rewinds while waiting for async operations like validator
|
|
|
|
# signature..
|
|
|
|
notice "Catching up",
|
|
|
|
curSlot = humaneSlotNum(curSlot),
|
|
|
|
lastSlot = humaneSlotNum(lastSlot),
|
|
|
|
slot = humaneSlotNum(slot)
|
|
|
|
|
|
|
|
# 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 mid-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..
|
|
|
|
let
|
|
|
|
attestationStart = node.beaconClock.fromNow(slot)
|
|
|
|
halfSlot = seconds(int64(SECONDS_PER_SLOT div 2))
|
|
|
|
|
|
|
|
if attestationStart.inFuture or attestationStart.offset <= halfSlot:
|
2019-03-28 06:10:48 +00:00
|
|
|
let fromNow =
|
|
|
|
if attestationStart.inFuture: attestationStart.offset + halfSlot
|
|
|
|
else: halfSlot - attestationStart.offset
|
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
debug "Waiting to send attestations",
|
|
|
|
slot = humaneSlotNum(slot),
|
2019-03-28 06:10:48 +00:00
|
|
|
fromNow = shortLog(fromNow)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
2019-03-28 06:10:48 +00:00
|
|
|
await sleepAsync(fromNow)
|
2019-03-22 15:49:37 +00:00
|
|
|
|
|
|
|
# Time passed - we might need to select a new head in that case
|
|
|
|
head = node.updateHead(slot)
|
|
|
|
|
|
|
|
handleAttestations(node, head, slot)
|
|
|
|
|
|
|
|
# TODO ... and beacon clock might jump here also. sigh.
|
|
|
|
let
|
|
|
|
nextSlotStart = saturate(node.beaconClock.fromNow(nextSlot))
|
|
|
|
|
|
|
|
info "Scheduling slot actions",
|
|
|
|
lastSlot = humaneSlotNum(slot),
|
|
|
|
slot = humaneSlotNum(slot),
|
|
|
|
nextSlot = humaneSlotNum(nextSlot),
|
|
|
|
fromNow = shortLog(nextSlotStart)
|
|
|
|
|
|
|
|
addTimer(nextSlotStart) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(slot, nextSlot)
|
|
|
|
|
2019-03-27 20:17:01 +00:00
|
|
|
proc onSecond(node: BeaconNode, moment: Moment) {.async.} =
|
2019-04-26 16:38:56 +00:00
|
|
|
let missingBlocks = node.blockPool.checkMissing()
|
2019-03-28 14:03:19 +00:00
|
|
|
if missingBlocks.len > 0:
|
|
|
|
info "Requesting detected missing blocks", missingBlocks
|
|
|
|
node.requestManager.fetchAncestorBlocks(missingBlocks) do (b: BeaconBlock):
|
2019-06-17 11:08:05 +00:00
|
|
|
onBeaconBlock(node ,b)
|
2019-03-27 20:17:01 +00:00
|
|
|
|
|
|
|
let nextSecond = max(Moment.now(), moment + chronos.seconds(1))
|
|
|
|
addTimer(nextSecond) do (p: pointer):
|
|
|
|
asyncCheck node.onSecond(nextSecond)
|
|
|
|
|
2019-02-21 04:42:17 +00:00
|
|
|
proc run*(node: BeaconNode) =
|
2019-03-05 22:54:08 +00:00
|
|
|
waitFor node.network.subscribe(topicBeaconBlocks) do (blck: BeaconBlock):
|
2019-06-17 11:08:05 +00:00
|
|
|
onBeaconBlock(node, blck)
|
2019-02-21 04:42:17 +00:00
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
waitFor node.network.subscribe(topicAttestations) do (attestation: Attestation):
|
2019-02-21 04:42:17 +00:00
|
|
|
node.onAttestation(attestation)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
let
|
|
|
|
slot = node.beaconClock.now().toSlot()
|
|
|
|
startSlot =
|
|
|
|
if slot >= GENESIS_SLOT: slot + 1
|
|
|
|
else: GENESIS_SLOT + 1
|
|
|
|
fromNow = saturate(node.beaconClock.fromNow(startSlot))
|
|
|
|
|
|
|
|
info "Scheduling first slot action",
|
|
|
|
nextSlot = humaneSlotNum(startSlot),
|
|
|
|
fromNow = shortLog(fromNow)
|
2019-02-28 21:21:29 +00:00
|
|
|
|
2019-03-22 15:49:37 +00:00
|
|
|
addTimer(fromNow) do (p: pointer):
|
|
|
|
asyncCheck node.onSlotStart(startSlot - 1, startSlot)
|
2018-12-28 16:51:40 +00:00
|
|
|
|
2019-03-27 20:17:01 +00:00
|
|
|
let second = Moment.now() + chronos.seconds(1)
|
|
|
|
addTimer(second) do (p: pointer):
|
|
|
|
asyncCheck node.onSecond(second)
|
|
|
|
|
2019-01-25 17:35:22 +00:00
|
|
|
runForever()
|
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
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
proc start(node: BeaconNode, headState: BeaconState) =
|
2019-03-20 11:52:30 +00:00
|
|
|
# TODO: while it's nice to cheat by waiting for connections here, we
|
|
|
|
# actually need to make this part of normal application flow -
|
|
|
|
# losing all connections might happen at any time and we should be
|
|
|
|
# prepared to handle it.
|
|
|
|
waitFor node.connectToNetwork()
|
|
|
|
|
|
|
|
info "Starting beacon node",
|
2019-03-22 15:49:37 +00:00
|
|
|
slotsSinceFinalization =
|
|
|
|
int64(node.blockPool.finalizedHead.slot) -
|
|
|
|
int64(node.beaconClock.now()),
|
2019-04-06 07:46:07 +00:00
|
|
|
stateSlot = humaneSlotNum(headState.slot),
|
2019-03-20 11:52:30 +00:00
|
|
|
SHARD_COUNT,
|
|
|
|
SLOTS_PER_EPOCH,
|
|
|
|
SECONDS_PER_SLOT,
|
|
|
|
SPEC_VERSION
|
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
node.addLocalValidators(headState)
|
2019-03-20 11:52:30 +00:00
|
|
|
node.run()
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
when isMainModule:
|
2019-03-25 23:26:11 +00:00
|
|
|
randomize()
|
2019-03-18 03:54:08 +00:00
|
|
|
let config = BeaconNodeConf.load(version = fullVersionStr())
|
|
|
|
|
2019-01-21 19:42:37 +00:00
|
|
|
if config.logLevel != LogLevel.NONE:
|
|
|
|
setLogLevel(config.logLevel)
|
2019-01-16 23:01:15 +00:00
|
|
|
|
2019-07-11 02:36:07 +00:00
|
|
|
## Ctrl+C handling
|
|
|
|
proc controlCHandler() {.noconv.} =
|
|
|
|
when defined(windows):
|
|
|
|
# workaround for https://github.com/nim-lang/Nim/issues/4057
|
|
|
|
setupForeignThreadGc()
|
|
|
|
debug "Shutting down after having received SIGINT"
|
|
|
|
quit(1)
|
|
|
|
setControlCHook(controlCHandler)
|
|
|
|
|
2018-12-19 12:58:53 +00:00
|
|
|
case config.cmd
|
2019-03-19 17:22:17 +00:00
|
|
|
of createTestnet:
|
|
|
|
var deposits: seq[Deposit]
|
2019-03-27 12:06:06 +00:00
|
|
|
for i in config.firstValidator.int ..< config.totalValidators.int:
|
2019-03-19 17:22:17 +00:00
|
|
|
let depositFile = config.validatorsDir /
|
|
|
|
validatorFileBaseName(i) & ".deposit.json"
|
2019-06-19 13:41:54 +00:00
|
|
|
try:
|
|
|
|
deposits.add Json.loadFile(depositFile, Deposit)
|
|
|
|
except SerializationError as err:
|
|
|
|
stderr.write "Error while loading a deposit file:\n"
|
|
|
|
stderr.write err.formatMsg(depositFile), "\n"
|
|
|
|
stderr.write "Please regenerate the deposit files by running validator_keygen again\n"
|
|
|
|
quit 1
|
2019-03-19 17:22:17 +00:00
|
|
|
|
2019-07-10 12:23:02 +00:00
|
|
|
let initialState = initialize_beacon_state_from_eth1(
|
2019-03-19 17:22:17 +00:00
|
|
|
deposits,
|
2019-03-22 15:49:37 +00:00
|
|
|
uint64(times.toUnix(times.getTime()) + config.genesisOffset),
|
2019-07-01 13:20:55 +00:00
|
|
|
Eth1Data(), {skipValidation})
|
|
|
|
|
|
|
|
doAssert initialState.validators.len > 0
|
2019-03-19 17:22:17 +00:00
|
|
|
|
|
|
|
Json.saveFile(config.outputGenesis.string, initialState, pretty = true)
|
|
|
|
echo "Wrote ", config.outputGenesis.string
|
|
|
|
|
|
|
|
var
|
|
|
|
bootstrapAddress = getPersistenBootstrapAddr(
|
|
|
|
config, parseIpAddress(config.bootstrapAddress), Port config.bootstrapPort)
|
|
|
|
|
|
|
|
testnetMetadata = NetworkMetadata(
|
|
|
|
networkId: config.networkId,
|
2019-04-08 12:46:12 +00:00
|
|
|
networkGeneration: semanticVersion,
|
2019-03-25 16:46:31 +00:00
|
|
|
genesisRoot: hash_tree_root(initialState),
|
2019-03-19 17:22:17 +00:00
|
|
|
bootstrapNodes: @[bootstrapAddress],
|
|
|
|
numShards: SHARD_COUNT,
|
|
|
|
slotDuration: SECONDS_PER_SLOT,
|
|
|
|
slotsPerEpoch: SLOTS_PER_EPOCH,
|
2019-03-27 12:06:06 +00:00
|
|
|
totalValidators: config.totalValidators,
|
|
|
|
lastUserValidator: config.lastUserValidator)
|
2019-03-19 17:22:17 +00:00
|
|
|
|
|
|
|
Json.saveFile(config.outputNetwork.string, testnetMetadata, pretty = true)
|
|
|
|
echo "Wrote ", config.outputNetwork.string
|
|
|
|
|
|
|
|
of updateTestnet:
|
|
|
|
discard waitFor updateTestnetMetadata(config)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-03-25 23:26:11 +00:00
|
|
|
of importValidator:
|
2019-03-18 03:54:08 +00:00
|
|
|
template reportFailureFor(keyExpr) =
|
|
|
|
error "Failed to import validator key", key = keyExpr
|
|
|
|
programResult = 1
|
|
|
|
|
2019-03-19 19:50:22 +00:00
|
|
|
for keyFile in config.keyFiles:
|
2019-03-18 03:54:08 +00:00
|
|
|
try:
|
2019-03-25 23:26:11 +00:00
|
|
|
saveValidatorKey(keyFile.string.extractFilename,
|
|
|
|
readFile(keyFile.string), config)
|
2019-03-18 03:54:08 +00:00
|
|
|
except:
|
2019-03-19 19:50:22 +00:00
|
|
|
reportFailureFor keyFile.string
|
2019-03-18 03:54:08 +00:00
|
|
|
|
2019-03-25 23:26:11 +00:00
|
|
|
if config.keyFiles.len == 0:
|
2019-03-19 17:22:17 +00:00
|
|
|
if config.network in ["testnet0", "testnet1"]:
|
2019-03-18 03:54:08 +00:00
|
|
|
try:
|
2019-03-25 23:26:11 +00:00
|
|
|
let (keyName, key) = waitFor obtainTestnetKey(config)
|
|
|
|
saveValidatorKey(keyName, key, config)
|
2019-03-18 03:54:08 +00:00
|
|
|
except:
|
2019-03-25 23:26:11 +00:00
|
|
|
stderr.write "Failed to download key\n", getCurrentExceptionMsg()
|
2019-03-18 03:54:08 +00:00
|
|
|
quit 1
|
|
|
|
else:
|
|
|
|
echo "Validator keys can be downloaded only for testnets"
|
|
|
|
quit 1
|
|
|
|
|
2018-12-19 12:58:53 +00:00
|
|
|
of noCommand:
|
2018-12-28 16:51:40 +00:00
|
|
|
createPidFile(config.dataDir.string / "beacon_node.pid")
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
var node = waitFor BeaconNode.init(config)
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2019-04-06 07:46:07 +00:00
|
|
|
# TODO slightly ugly to rely on node.stateCache state here..
|
2019-03-22 14:35:20 +00:00
|
|
|
if node.nickname != "":
|
2019-05-04 14:10:45 +00:00
|
|
|
dynamicLogScope(node = node.nickname): node.start(node.stateCache.data.data)
|
2019-03-20 11:52:30 +00:00
|
|
|
else:
|
2019-05-04 14:10:45 +00:00
|
|
|
node.start(node.stateCache.data.data)
|