2021-03-26 06:52:01 +00:00
|
|
|
# beacon_chain
|
2022-01-04 09:45:38 +00:00
|
|
|
# Copyright (c) 2018-2022 Status Research & Development GmbH
|
2021-03-26 06:52:01 +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.
|
|
|
|
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
import
|
2019-10-25 10:59:56 +00:00
|
|
|
options, tables, sets, macros,
|
2020-03-22 20:54:47 +00:00
|
|
|
chronicles, chronos, stew/ranges/bitranges, libp2p/switch,
|
2022-01-12 14:50:30 +00:00
|
|
|
../spec/datatypes/[phase0, altair, bellatrix],
|
2021-08-12 13:08:20 +00:00
|
|
|
../spec/[helpers, forks, network],
|
2021-10-19 14:09:26 +00:00
|
|
|
".."/[beacon_clock],
|
2021-03-05 13:12:00 +00:00
|
|
|
../networking/eth2_network,
|
|
|
|
../consensus_object_pools/blockchain_dag
|
2019-03-12 15:03:14 +00:00
|
|
|
|
2019-11-11 01:28:13 +00:00
|
|
|
logScope:
|
|
|
|
topics = "sync"
|
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
const
|
2020-08-05 23:22:12 +00:00
|
|
|
MAX_REQUEST_BLOCKS = 1024
|
2020-05-23 22:24:47 +00:00
|
|
|
|
2020-10-09 13:44:51 +00:00
|
|
|
blockByRootLookupCost = allowedOpsPerSecondCost(50)
|
|
|
|
blockResponseCost = allowedOpsPerSecondCost(100)
|
|
|
|
blockByRangeLookupCost = allowedOpsPerSecondCost(20)
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
type
|
2020-04-20 14:59:18 +00:00
|
|
|
StatusMsg* = object
|
|
|
|
forkDigest*: ForkDigest
|
|
|
|
finalizedRoot*: Eth2Digest
|
|
|
|
finalizedEpoch*: Epoch
|
|
|
|
headRoot*: Eth2Digest
|
|
|
|
headSlot*: Slot
|
|
|
|
|
2019-07-08 13:19:52 +00:00
|
|
|
ValidatorSetDeltaFlags {.pure.} = enum
|
|
|
|
Activation = 0
|
|
|
|
Exit = 1
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
ValidatorChangeLogEntry* = object
|
|
|
|
case kind*: ValidatorSetDeltaFlags
|
2018-12-03 17:46:22 +00:00
|
|
|
of Activation:
|
2018-11-29 01:08:34 +00:00
|
|
|
pubkey: ValidatorPubKey
|
2018-11-23 23:58:49 +00:00
|
|
|
else:
|
|
|
|
index: uint32
|
|
|
|
|
2019-09-08 22:03:41 +00:00
|
|
|
BeaconSyncNetworkState* = ref object
|
2021-06-01 11:13:40 +00:00
|
|
|
dag*: ChainDAGRef
|
2021-08-19 10:45:31 +00:00
|
|
|
getBeaconTime*: GetBeaconTimeFn
|
2019-02-18 10:34:39 +00:00
|
|
|
|
2019-09-08 22:03:41 +00:00
|
|
|
BeaconSyncPeerState* = ref object
|
2020-09-23 15:58:02 +00:00
|
|
|
statusLastTime*: chronos.Moment
|
2020-04-20 14:59:18 +00:00
|
|
|
statusMsg*: StatusMsg
|
2019-09-08 22:03:41 +00:00
|
|
|
|
2019-07-03 07:35:05 +00:00
|
|
|
BlockRootSlot* = object
|
|
|
|
blockRoot: Eth2Digest
|
|
|
|
slot: Slot
|
|
|
|
|
2020-08-05 23:22:12 +00:00
|
|
|
BlockRootsList* = List[Eth2Digest, Limit MAX_REQUEST_BLOCKS]
|
2019-11-25 14:36:25 +00:00
|
|
|
|
2021-07-07 09:09:47 +00:00
|
|
|
proc readChunkPayload*(conn: Connection, peer: Peer,
|
|
|
|
MsgType: type ForkedSignedBeaconBlock): Future[NetRes[ForkedSignedBeaconBlock]] {.async.} =
|
|
|
|
var contextBytes: ForkDigest
|
|
|
|
try:
|
|
|
|
await conn.readExactly(addr contextBytes, sizeof contextBytes)
|
2021-12-05 17:32:41 +00:00
|
|
|
except CatchableError:
|
2021-07-07 09:09:47 +00:00
|
|
|
return neterr UnexpectedEOF
|
|
|
|
|
|
|
|
if contextBytes == peer.network.forkDigests.phase0:
|
2021-08-10 20:46:35 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, phase0.SignedBeaconBlock)
|
2021-07-07 09:09:47 +00:00
|
|
|
if res.isOk:
|
2021-08-24 19:49:51 +00:00
|
|
|
return ok ForkedSignedBeaconBlock.init(res.get)
|
2021-07-07 09:09:47 +00:00
|
|
|
else:
|
|
|
|
return err(res.error)
|
|
|
|
elif contextBytes == peer.network.forkDigests.altair:
|
2021-08-10 20:46:35 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, altair.SignedBeaconBlock)
|
2021-07-07 09:09:47 +00:00
|
|
|
if res.isOk:
|
2021-08-24 19:49:51 +00:00
|
|
|
return ok ForkedSignedBeaconBlock.init(res.get)
|
2021-07-07 09:09:47 +00:00
|
|
|
else:
|
|
|
|
return err(res.error)
|
2022-01-05 14:24:15 +00:00
|
|
|
elif contextBytes == peer.network.forkDigests.bellatrix:
|
2022-01-12 14:50:30 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, bellatrix.SignedBeaconBlock)
|
2021-09-29 16:44:43 +00:00
|
|
|
if res.isOk:
|
|
|
|
return ok ForkedSignedBeaconBlock.init(res.get)
|
|
|
|
else:
|
|
|
|
return err(res.error)
|
2021-07-07 09:09:47 +00:00
|
|
|
else:
|
|
|
|
return neterr InvalidContextBytes
|
|
|
|
|
|
|
|
proc sendResponseChunk*(response: UntypedResponse,
|
|
|
|
val: ForkedSignedBeaconBlock): Future[void] =
|
|
|
|
inc response.writtenChunks
|
|
|
|
|
|
|
|
case val.kind
|
|
|
|
of BeaconBlockFork.Phase0:
|
|
|
|
response.stream.writeChunk(some ResponseCode.Success,
|
2021-10-18 16:37:27 +00:00
|
|
|
SSZ.encode(val.phase0Data),
|
2022-01-08 20:06:34 +00:00
|
|
|
response.peer.network.forkDigests.phase0.data)
|
2021-07-07 09:09:47 +00:00
|
|
|
of BeaconBlockFork.Altair:
|
|
|
|
response.stream.writeChunk(some ResponseCode.Success,
|
2021-10-18 16:37:27 +00:00
|
|
|
SSZ.encode(val.altairData),
|
2022-01-08 20:06:34 +00:00
|
|
|
response.peer.network.forkDigests.altair.data)
|
2022-01-04 09:45:38 +00:00
|
|
|
of BeaconBlockFork.Bellatrix:
|
2021-09-27 14:22:58 +00:00
|
|
|
response.stream.writeChunk(some ResponseCode.Success,
|
2022-01-24 16:23:13 +00:00
|
|
|
SSZ.encode(val.bellatrixData),
|
2022-01-08 20:06:34 +00:00
|
|
|
response.peer.network.forkDigests.bellatrix.data)
|
2021-07-07 09:09:47 +00:00
|
|
|
|
2020-09-06 08:39:25 +00:00
|
|
|
func shortLog*(s: StatusMsg): auto =
|
2020-05-11 18:08:52 +00:00
|
|
|
(
|
|
|
|
forkDigest: s.forkDigest,
|
|
|
|
finalizedRoot: shortLog(s.finalizedRoot),
|
|
|
|
finalizedEpoch: shortLog(s.finalizedEpoch),
|
|
|
|
headRoot: shortLog(s.headRoot),
|
|
|
|
headSlot: shortLog(s.headSlot)
|
|
|
|
)
|
|
|
|
chronicles.formatIt(StatusMsg): shortLog(it)
|
|
|
|
|
2020-06-20 07:24:33 +00:00
|
|
|
func disconnectReasonName(reason: uint64): string =
|
|
|
|
# haha, nim doesn't support uint64 in `case`!
|
|
|
|
if reason == uint64(ClientShutDown): "Client shutdown"
|
|
|
|
elif reason == uint64(IrrelevantNetwork): "Irrelevant network"
|
|
|
|
elif reason == uint64(FaultOrError): "Fault or error"
|
|
|
|
else: "Disconnected (" & $reason & ")"
|
|
|
|
|
2020-05-11 18:08:52 +00:00
|
|
|
proc getCurrentStatus*(state: BeaconSyncNetworkState): StatusMsg {.gcsafe.} =
|
2019-09-09 23:55:01 +00:00
|
|
|
let
|
2021-06-01 11:13:40 +00:00
|
|
|
dag = state.dag
|
|
|
|
headBlock = dag.head
|
2021-08-19 10:45:31 +00:00
|
|
|
wallTimeSlot = state.getBeaconTime().slotOrZero
|
2019-09-09 23:55:01 +00:00
|
|
|
|
2019-09-11 16:45:22 +00:00
|
|
|
StatusMsg(
|
2021-08-09 12:54:45 +00:00
|
|
|
forkDigest: state.dag.forkDigestAtEpoch(wallTimeSlot.epoch),
|
2021-04-08 08:24:25 +00:00
|
|
|
finalizedRoot:
|
2021-06-11 17:51:46 +00:00
|
|
|
getStateField(dag.headState.data, finalized_checkpoint).root,
|
2021-04-08 08:24:25 +00:00
|
|
|
finalizedEpoch:
|
2021-06-11 17:51:46 +00:00
|
|
|
getStateField(dag.headState.data, finalized_checkpoint).epoch,
|
2020-05-11 18:08:52 +00:00
|
|
|
headRoot: headBlock.root,
|
|
|
|
headSlot: headBlock.slot)
|
2019-09-08 22:03:41 +00:00
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
proc handleStatus(peer: Peer,
|
|
|
|
state: BeaconSyncNetworkState,
|
|
|
|
ourStatus: StatusMsg,
|
|
|
|
theirStatus: StatusMsg): Future[void] {.gcsafe.}
|
2019-09-08 13:08:44 +00:00
|
|
|
|
2020-05-11 18:08:52 +00:00
|
|
|
proc setStatusMsg(peer: Peer, statusMsg: StatusMsg) {.gcsafe.}
|
|
|
|
|
2021-03-26 06:52:01 +00:00
|
|
|
{.pop.} # TODO fix p2p macro for raises
|
2021-07-07 09:09:47 +00:00
|
|
|
|
2018-11-29 01:08:34 +00:00
|
|
|
p2pProtocol BeaconSync(version = 1,
|
2019-09-08 22:03:41 +00:00
|
|
|
networkState = BeaconSyncNetworkState,
|
|
|
|
peerState = BeaconSyncPeerState):
|
2019-02-18 10:34:39 +00:00
|
|
|
|
2020-08-10 10:58:34 +00:00
|
|
|
onPeerConnected do (peer: Peer, incoming: bool) {.async.}:
|
2020-06-11 05:14:26 +00:00
|
|
|
debug "Peer connected",
|
2021-10-21 11:01:29 +00:00
|
|
|
peer, peerId = shortLog(peer.peerId), incoming
|
2020-08-10 10:58:34 +00:00
|
|
|
# Per the eth2 protocol, whoever dials must send a status message when
|
|
|
|
# connected for the first time, but because of how libp2p works, there may
|
|
|
|
# be a race between incoming and outgoing connections and disconnects that
|
|
|
|
# makes the incoming flag unreliable / obsolete by the time we get to
|
|
|
|
# this point - instead of making assumptions, we'll just send a status
|
|
|
|
# message redundantly.
|
2020-11-10 18:41:04 +00:00
|
|
|
# TODO(zah)
|
|
|
|
# the spec does not prohibit sending the extra status message on
|
2020-08-10 10:58:34 +00:00
|
|
|
# incoming connections, but it should not be necessary - this would
|
|
|
|
# need a dedicated flow in libp2p that resolves the race conditions -
|
|
|
|
# this needs more thinking around the ordering of events and the
|
|
|
|
# given incoming flag
|
|
|
|
let
|
|
|
|
ourStatus = peer.networkState.getCurrentStatus()
|
2020-11-12 15:30:12 +00:00
|
|
|
theirStatus = await peer.status(ourStatus, timeout = RESP_TIMEOUT)
|
2019-09-09 23:55:01 +00:00
|
|
|
|
2020-08-10 10:58:34 +00:00
|
|
|
if theirStatus.isOk:
|
|
|
|
await peer.handleStatus(peer.networkState,
|
|
|
|
ourStatus, theirStatus.get())
|
|
|
|
else:
|
2020-10-01 18:56:42 +00:00
|
|
|
debug "Status response not received in time",
|
2021-06-10 09:17:17 +00:00
|
|
|
peer, errorKind = theirStatus.error.kind
|
2020-12-07 18:47:07 +00:00
|
|
|
await peer.disconnect(FaultOrError)
|
2019-02-18 10:34:39 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
proc status(peer: Peer,
|
|
|
|
theirStatus: StatusMsg,
|
|
|
|
response: SingleChunkResponse[StatusMsg])
|
|
|
|
{.async, libp2pProtocol("status", 1).} =
|
|
|
|
let ourStatus = peer.networkState.getCurrentStatus()
|
|
|
|
trace "Sending status message", peer = peer, status = ourStatus
|
|
|
|
await response.send(ourStatus)
|
|
|
|
await peer.handleStatus(peer.networkState, ourStatus, theirStatus)
|
|
|
|
|
|
|
|
proc ping(peer: Peer, value: uint64): uint64
|
|
|
|
{.libp2pProtocol("ping", 1).} =
|
|
|
|
return peer.network.metadata.seq_number
|
|
|
|
|
2021-08-10 20:46:35 +00:00
|
|
|
proc getMetaData(peer: Peer): phase0.MetaData
|
2020-05-23 22:24:47 +00:00
|
|
|
{.libp2pProtocol("metadata", 1).} =
|
2021-08-10 20:46:35 +00:00
|
|
|
return peer.network.phase0metadata
|
2021-07-07 09:09:47 +00:00
|
|
|
|
|
|
|
proc getMetadata_v2(peer: Peer): altair.MetaData
|
|
|
|
{.libp2pProtocol("metadata", 2).} =
|
2020-05-23 22:24:47 +00:00
|
|
|
return peer.network.metadata
|
|
|
|
|
2020-06-25 10:23:10 +00:00
|
|
|
proc beaconBlocksByRange(
|
|
|
|
peer: Peer,
|
|
|
|
startSlot: Slot,
|
2020-08-05 23:22:12 +00:00
|
|
|
reqCount: uint64,
|
|
|
|
reqStep: uint64,
|
2021-08-10 20:46:35 +00:00
|
|
|
response: MultipleChunksResponse[phase0.SignedBeaconBlock])
|
2020-06-25 10:23:10 +00:00
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_range", 1).} =
|
2020-08-05 23:22:12 +00:00
|
|
|
trace "got range request", peer, startSlot,
|
|
|
|
count = reqCount, step = reqStep
|
2020-10-09 13:44:51 +00:00
|
|
|
if reqCount > 0'u64 and reqStep > 0'u64:
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
var blocks: array[MAX_REQUEST_BLOCKS, BlockId]
|
2020-05-23 22:24:47 +00:00
|
|
|
let
|
2021-06-01 11:13:40 +00:00
|
|
|
dag = peer.networkState.dag
|
2020-05-23 22:24:47 +00:00
|
|
|
# Limit number of blocks in response
|
2020-08-05 23:22:12 +00:00
|
|
|
count = int min(reqCount, blocks.lenu64)
|
2019-09-08 22:03:41 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
let
|
|
|
|
endIndex = count - 1
|
|
|
|
startIndex =
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
dag.getBlockRange(startSlot, reqStep, blocks.toOpenArray(0, endIndex))
|
2020-10-09 13:44:51 +00:00
|
|
|
peer.updateRequestQuota(
|
|
|
|
blockByRangeLookupCost +
|
|
|
|
max(0, endIndex - startIndex + 1).float * blockResponseCost)
|
2020-10-13 12:37:25 +00:00
|
|
|
peer.awaitNonNegativeRequestQuota()
|
2019-02-18 10:34:39 +00:00
|
|
|
|
2020-08-27 06:32:51 +00:00
|
|
|
for i in startIndex..endIndex:
|
|
|
|
trace "wrote response block",
|
|
|
|
slot = blocks[i].slot, roor = shortLog(blocks[i].root)
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
let blk = dag.getForkedBlock(blocks[i])
|
|
|
|
if blk.isSome():
|
|
|
|
let blck = blk.get()
|
|
|
|
case blck.kind
|
|
|
|
of BeaconBlockFork.Phase0:
|
|
|
|
await response.write(blck.phase0Data.asSigned)
|
2022-01-17 11:19:58 +00:00
|
|
|
else:
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
# Skipping all subsequent blocks should be OK because the spec says:
|
|
|
|
# "Clients MAY limit the number of blocks in the response."
|
|
|
|
# https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#beaconblocksbyrange
|
|
|
|
#
|
|
|
|
# Also, our response would be indistinguishable from a node
|
|
|
|
# that have been synced exactly to the altair transition slot.
|
|
|
|
break
|
2019-05-22 07:13:15 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
debug "Block range request done",
|
2020-08-05 23:22:12 +00:00
|
|
|
peer, startSlot, count, reqStep, found = count - startIndex
|
2020-10-09 13:44:51 +00:00
|
|
|
else:
|
2020-10-13 12:37:25 +00:00
|
|
|
raise newException(InvalidInputsError, "Empty range requested")
|
2019-08-05 00:00:49 +00:00
|
|
|
|
2020-06-25 10:23:10 +00:00
|
|
|
proc beaconBlocksByRoot(
|
|
|
|
peer: Peer,
|
2020-08-21 18:50:46 +00:00
|
|
|
# Please note that the SSZ list here ensures that the
|
|
|
|
# spec constant MAX_REQUEST_BLOCKS is enforced:
|
2020-06-25 10:23:10 +00:00
|
|
|
blockRoots: BlockRootsList,
|
2021-08-10 20:46:35 +00:00
|
|
|
response: MultipleChunksResponse[phase0.SignedBeaconBlock])
|
2020-06-25 10:23:10 +00:00
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_root", 1).} =
|
2020-10-09 13:44:51 +00:00
|
|
|
if blockRoots.len == 0:
|
2020-10-13 12:37:25 +00:00
|
|
|
raise newException(InvalidInputsError, "No blocks requested")
|
2020-10-09 13:44:51 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
let
|
2021-06-01 11:13:40 +00:00
|
|
|
dag = peer.networkState.dag
|
2020-05-23 22:24:47 +00:00
|
|
|
count = blockRoots.len
|
2020-04-22 06:18:45 +00:00
|
|
|
|
2020-10-09 13:44:51 +00:00
|
|
|
peer.updateRequestQuota(count.float * blockByRootLookupCost)
|
2020-10-13 12:37:25 +00:00
|
|
|
peer.awaitNonNegativeRequestQuota()
|
2020-04-21 06:43:39 +00:00
|
|
|
|
2020-10-09 13:44:51 +00:00
|
|
|
var found = 0
|
2020-08-27 06:32:51 +00:00
|
|
|
for i in 0..<count:
|
limit by-root requests to non-finalized blocks (#3293)
* limit by-root requests to non-finalized blocks
Presently, we keep a mapping from block root to `BlockRef` in memory -
this has simplified reasoning about the dag, but is not sustainable with
the chain growing.
We can distinguish between two cases where by-root access is useful:
* unfinalized blocks - this is where the beacon chain is operating
generally, by validating incoming data as interesting for future fork
choice decisions - bounded by the length of the unfinalized period
* finalized blocks - historical access in the REST API etc - no bounds,
really
In this PR, we limit the by-root block index to the first use case:
finalized chain data can more efficiently be addressed by slot number.
Future work includes:
* limiting the `BlockRef` horizon in general - each instance is 40
bytes+overhead which adds up - this needs further refactoring to deal
with the tail vs state problem
* persisting the finalized slot-to-hash index - this one also keeps
growing unbounded (albeit slowly)
Anyway, this PR easily shaves ~128mb of memory usage at the time of
writing.
* No longer honor `BeaconBlocksByRoot` requests outside of the
non-finalized period - previously, Nimbus would generously return any
block through this libp2p request - per the spec, finalized blocks
should be fetched via `BeaconBlocksByRange` instead.
* return `Opt[BlockRef]` instead of `nil` when blocks can't be found -
this becomes a lot more common now and thus deserves more attention
* `dag.blocks` -> `dag.forkBlocks` - this index only carries unfinalized
blocks from now - `finalizedBlocks` covers the other `BlockRef`
instances
* in backfill, verify that the last backfilled block leads back to
genesis, or panic
* add backfill timings to log
* fix missing check that `BlockRef` block can be fetched with
`getForkedBlock` reliably
* shortcut doppelganger check when feature is not enabled
* in REST/JSON-RPC, fetch blocks without involving `BlockRef`
* fix dag.blocks ref
2022-01-21 11:33:16 +00:00
|
|
|
let blockRef = dag.getBlockRef(blockRoots[i])
|
|
|
|
if blockRef.isSome():
|
|
|
|
let blk = dag.getForkedBlock(blockRef[])
|
2021-07-15 19:01:07 +00:00
|
|
|
case blk.kind
|
|
|
|
of BeaconBlockFork.Phase0:
|
2021-10-18 16:37:27 +00:00
|
|
|
await response.write(blk.phase0Data.asSigned)
|
2021-07-15 19:01:07 +00:00
|
|
|
inc found
|
2022-01-04 09:45:38 +00:00
|
|
|
of BeaconBlockFork.Altair, BeaconBlockFork.Bellatrix:
|
2021-07-15 19:01:07 +00:00
|
|
|
# Skipping this block should be fine because the spec says:
|
|
|
|
# "Clients MAY limit the number of blocks in the response."
|
2021-08-20 23:37:45 +00:00
|
|
|
# https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#beaconblocksbyroot
|
2021-07-15 19:01:07 +00:00
|
|
|
#
|
|
|
|
# Also, our response would be indistinguishable from a node
|
|
|
|
# that have been synced exactly to the altair transition slot.
|
|
|
|
continue
|
2021-07-07 09:09:47 +00:00
|
|
|
|
|
|
|
peer.updateRequestQuota(found.float * blockResponseCost)
|
|
|
|
|
|
|
|
debug "Block root request done",
|
|
|
|
peer, roots = blockRoots.len, count, found
|
|
|
|
|
|
|
|
proc beaconBlocksByRange_v2(
|
|
|
|
peer: Peer,
|
|
|
|
startSlot: Slot,
|
|
|
|
reqCount: uint64,
|
|
|
|
reqStep: uint64,
|
|
|
|
response: MultipleChunksResponse[ForkedSignedBeaconBlock])
|
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_range", 2).} =
|
|
|
|
trace "got range request", peer, startSlot,
|
|
|
|
count = reqCount, step = reqStep
|
|
|
|
if reqCount > 0'u64 and reqStep > 0'u64:
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
var blocks: array[MAX_REQUEST_BLOCKS, BlockId]
|
2021-07-07 09:09:47 +00:00
|
|
|
let
|
|
|
|
dag = peer.networkState.dag
|
|
|
|
# Limit number of blocks in response
|
|
|
|
count = int min(reqCount, blocks.lenu64)
|
|
|
|
|
|
|
|
let
|
|
|
|
endIndex = count - 1
|
|
|
|
startIndex =
|
|
|
|
dag.getBlockRange(startSlot, reqStep,
|
|
|
|
blocks.toOpenArray(0, endIndex))
|
|
|
|
peer.updateRequestQuota(
|
|
|
|
blockByRangeLookupCost +
|
|
|
|
max(0, endIndex - startIndex + 1).float * blockResponseCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
for i in startIndex..endIndex:
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
let
|
limit by-root requests to non-finalized blocks (#3293)
* limit by-root requests to non-finalized blocks
Presently, we keep a mapping from block root to `BlockRef` in memory -
this has simplified reasoning about the dag, but is not sustainable with
the chain growing.
We can distinguish between two cases where by-root access is useful:
* unfinalized blocks - this is where the beacon chain is operating
generally, by validating incoming data as interesting for future fork
choice decisions - bounded by the length of the unfinalized period
* finalized blocks - historical access in the REST API etc - no bounds,
really
In this PR, we limit the by-root block index to the first use case:
finalized chain data can more efficiently be addressed by slot number.
Future work includes:
* limiting the `BlockRef` horizon in general - each instance is 40
bytes+overhead which adds up - this needs further refactoring to deal
with the tail vs state problem
* persisting the finalized slot-to-hash index - this one also keeps
growing unbounded (albeit slowly)
Anyway, this PR easily shaves ~128mb of memory usage at the time of
writing.
* No longer honor `BeaconBlocksByRoot` requests outside of the
non-finalized period - previously, Nimbus would generously return any
block through this libp2p request - per the spec, finalized blocks
should be fetched via `BeaconBlocksByRange` instead.
* return `Opt[BlockRef]` instead of `nil` when blocks can't be found -
this becomes a lot more common now and thus deserves more attention
* `dag.blocks` -> `dag.forkBlocks` - this index only carries unfinalized
blocks from now - `finalizedBlocks` covers the other `BlockRef`
instances
* in backfill, verify that the last backfilled block leads back to
genesis, or panic
* add backfill timings to log
* fix missing check that `BlockRef` block can be fetched with
`getForkedBlock` reliably
* shortcut doppelganger check when feature is not enabled
* in REST/JSON-RPC, fetch blocks without involving `BlockRef`
* fix dag.blocks ref
2022-01-21 11:33:16 +00:00
|
|
|
blck = dag.getForkedBlock(blocks[i]).valueOr:
|
|
|
|
continue
|
Backfill support for ChainDAG (#3171)
In the ChainDAG, 3 block pointers are kept: genesis, tail and head. This
PR adds one more block pointer: the backfill block which represents the
block that has been backfilled so far.
When doing a checkpoint sync, a random block is given as starting point
- this is the tail block, and we require that the tail block has a
corresponding state.
When backfilling, we end up with blocks without corresponding states,
hence we cannot use `tail` as a backfill pointer - there is no state.
Nonetheless, we need to keep track of where we are in the backfill
process between restarts, such that we can answer GetBeaconBlocksByRange
requests.
This PR adds the basic support for backfill handling - it needs to be
integrated with backfill sync, and the REST API needs to be adjusted to
take advantage of the new backfilled blocks when responding to certain
requests.
Future work will also enable moving the tail in either direction:
* pruning means moving the tail forward in time and removing states
* backwards means recreating past states from genesis, such that
intermediate states are recreated step by step all the way to the tail -
at that point, tail, genesis and backfill will match up.
* backfilling is done when backfill != genesis - later, this will be the
WSS checkpoint instead
2021-12-13 13:36:06 +00:00
|
|
|
|
limit by-root requests to non-finalized blocks (#3293)
* limit by-root requests to non-finalized blocks
Presently, we keep a mapping from block root to `BlockRef` in memory -
this has simplified reasoning about the dag, but is not sustainable with
the chain growing.
We can distinguish between two cases where by-root access is useful:
* unfinalized blocks - this is where the beacon chain is operating
generally, by validating incoming data as interesting for future fork
choice decisions - bounded by the length of the unfinalized period
* finalized blocks - historical access in the REST API etc - no bounds,
really
In this PR, we limit the by-root block index to the first use case:
finalized chain data can more efficiently be addressed by slot number.
Future work includes:
* limiting the `BlockRef` horizon in general - each instance is 40
bytes+overhead which adds up - this needs further refactoring to deal
with the tail vs state problem
* persisting the finalized slot-to-hash index - this one also keeps
growing unbounded (albeit slowly)
Anyway, this PR easily shaves ~128mb of memory usage at the time of
writing.
* No longer honor `BeaconBlocksByRoot` requests outside of the
non-finalized period - previously, Nimbus would generously return any
block through this libp2p request - per the spec, finalized blocks
should be fetched via `BeaconBlocksByRange` instead.
* return `Opt[BlockRef]` instead of `nil` when blocks can't be found -
this becomes a lot more common now and thus deserves more attention
* `dag.blocks` -> `dag.forkBlocks` - this index only carries unfinalized
blocks from now - `finalizedBlocks` covers the other `BlockRef`
instances
* in backfill, verify that the last backfilled block leads back to
genesis, or panic
* add backfill timings to log
* fix missing check that `BlockRef` block can be fetched with
`getForkedBlock` reliably
* shortcut doppelganger check when feature is not enabled
* in REST/JSON-RPC, fetch blocks without involving `BlockRef`
* fix dag.blocks ref
2022-01-21 11:33:16 +00:00
|
|
|
await response.write(blck.asSigned)
|
2021-07-07 09:09:47 +00:00
|
|
|
|
|
|
|
debug "Block range request done",
|
|
|
|
peer, startSlot, count, reqStep, found = count - startIndex
|
|
|
|
else:
|
|
|
|
raise newException(InvalidInputsError, "Empty range requested")
|
|
|
|
|
|
|
|
proc beaconBlocksByRoot_v2(
|
|
|
|
peer: Peer,
|
|
|
|
# Please note that the SSZ list here ensures that the
|
|
|
|
# spec constant MAX_REQUEST_BLOCKS is enforced:
|
|
|
|
blockRoots: BlockRootsList,
|
|
|
|
response: MultipleChunksResponse[ForkedSignedBeaconBlock])
|
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_root", 2).} =
|
|
|
|
|
|
|
|
if blockRoots.len == 0:
|
|
|
|
raise newException(InvalidInputsError, "No blocks requested")
|
|
|
|
|
|
|
|
let
|
|
|
|
dag = peer.networkState.dag
|
|
|
|
count = blockRoots.len
|
|
|
|
|
|
|
|
peer.updateRequestQuota(count.float * blockByRootLookupCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
var found = 0
|
|
|
|
for i in 0..<count:
|
limit by-root requests to non-finalized blocks (#3293)
* limit by-root requests to non-finalized blocks
Presently, we keep a mapping from block root to `BlockRef` in memory -
this has simplified reasoning about the dag, but is not sustainable with
the chain growing.
We can distinguish between two cases where by-root access is useful:
* unfinalized blocks - this is where the beacon chain is operating
generally, by validating incoming data as interesting for future fork
choice decisions - bounded by the length of the unfinalized period
* finalized blocks - historical access in the REST API etc - no bounds,
really
In this PR, we limit the by-root block index to the first use case:
finalized chain data can more efficiently be addressed by slot number.
Future work includes:
* limiting the `BlockRef` horizon in general - each instance is 40
bytes+overhead which adds up - this needs further refactoring to deal
with the tail vs state problem
* persisting the finalized slot-to-hash index - this one also keeps
growing unbounded (albeit slowly)
Anyway, this PR easily shaves ~128mb of memory usage at the time of
writing.
* No longer honor `BeaconBlocksByRoot` requests outside of the
non-finalized period - previously, Nimbus would generously return any
block through this libp2p request - per the spec, finalized blocks
should be fetched via `BeaconBlocksByRange` instead.
* return `Opt[BlockRef]` instead of `nil` when blocks can't be found -
this becomes a lot more common now and thus deserves more attention
* `dag.blocks` -> `dag.forkBlocks` - this index only carries unfinalized
blocks from now - `finalizedBlocks` covers the other `BlockRef`
instances
* in backfill, verify that the last backfilled block leads back to
genesis, or panic
* add backfill timings to log
* fix missing check that `BlockRef` block can be fetched with
`getForkedBlock` reliably
* shortcut doppelganger check when feature is not enabled
* in REST/JSON-RPC, fetch blocks without involving `BlockRef`
* fix dag.blocks ref
2022-01-21 11:33:16 +00:00
|
|
|
let blockRef = dag.getBlockRef(blockRoots[i])
|
|
|
|
if blockRef.isSome():
|
|
|
|
let blk = dag.getForkedBlock(blockRef[])
|
2021-07-07 09:09:47 +00:00
|
|
|
await response.write(blk.asSigned)
|
2020-05-23 22:24:47 +00:00
|
|
|
inc found
|
2019-08-05 00:00:49 +00:00
|
|
|
|
2020-10-09 13:44:51 +00:00
|
|
|
peer.updateRequestQuota(found.float * blockResponseCost)
|
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
debug "Block root request done",
|
|
|
|
peer, roots = blockRoots.len, count, found
|
|
|
|
|
2020-05-26 17:07:18 +00:00
|
|
|
proc goodbye(peer: Peer,
|
2020-06-20 07:24:33 +00:00
|
|
|
reason: uint64)
|
2020-05-26 17:07:18 +00:00
|
|
|
{.async, libp2pProtocol("goodbye", 1).} =
|
2020-06-20 07:24:33 +00:00
|
|
|
debug "Received Goodbye message", reason = disconnectReasonName(reason), peer
|
2019-05-22 07:13:15 +00:00
|
|
|
|
2021-07-15 19:01:07 +00:00
|
|
|
proc useSyncV2*(state: BeaconSyncNetworkState): bool =
|
|
|
|
let
|
2021-08-19 10:45:31 +00:00
|
|
|
wallTimeSlot = state.getBeaconTime().slotOrZero
|
2021-07-15 19:01:07 +00:00
|
|
|
|
|
|
|
wallTimeSlot.epoch >= state.dag.cfg.ALTAIR_FORK_EPOCH
|
|
|
|
|
|
|
|
proc useSyncV2*(peer: Peer): bool =
|
|
|
|
peer.networkState(BeaconSync).useSyncV2()
|
|
|
|
|
2020-05-11 18:08:52 +00:00
|
|
|
proc setStatusMsg(peer: Peer, statusMsg: StatusMsg) =
|
2020-10-30 12:33:52 +00:00
|
|
|
debug "Peer status", peer, statusMsg
|
2020-05-11 18:08:52 +00:00
|
|
|
peer.state(BeaconSync).statusMsg = statusMsg
|
2020-09-23 15:58:02 +00:00
|
|
|
peer.state(BeaconSync).statusLastTime = Moment.now()
|
2020-05-11 18:08:52 +00:00
|
|
|
|
|
|
|
proc updateStatus*(peer: Peer): Future[bool] {.async.} =
|
|
|
|
## Request `status` of remote peer ``peer``.
|
|
|
|
let
|
|
|
|
nstate = peer.networkState(BeaconSync)
|
|
|
|
ourStatus = getCurrentStatus(nstate)
|
|
|
|
|
2020-11-12 15:30:12 +00:00
|
|
|
let theirFut = awaitne peer.status(ourStatus, timeout = RESP_TIMEOUT)
|
2020-05-11 18:08:52 +00:00
|
|
|
if theirFut.failed():
|
2020-09-23 15:58:02 +00:00
|
|
|
return false
|
2020-05-11 18:08:52 +00:00
|
|
|
else:
|
|
|
|
let theirStatus = theirFut.read()
|
2020-05-12 22:37:07 +00:00
|
|
|
if theirStatus.isOk:
|
|
|
|
peer.setStatusMsg(theirStatus.get)
|
2020-09-23 15:58:02 +00:00
|
|
|
return true
|
|
|
|
else:
|
|
|
|
return false
|
2020-05-11 18:08:52 +00:00
|
|
|
|
2020-11-20 10:00:22 +00:00
|
|
|
proc getHeadSlot*(peer: Peer): Slot =
|
2020-05-11 18:08:52 +00:00
|
|
|
## Returns head slot for specific peer ``peer``.
|
2021-08-17 09:51:39 +00:00
|
|
|
peer.state(BeaconSync).statusMsg.headSlot
|
2020-05-11 18:08:52 +00:00
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
proc handleStatus(peer: Peer,
|
|
|
|
state: BeaconSyncNetworkState,
|
|
|
|
ourStatus: StatusMsg,
|
|
|
|
theirStatus: StatusMsg) {.async, gcsafe.} =
|
Implement split preset/config support (#2710)
* Implement split preset/config support
This is the initial bulk refactor to introduce runtime config values in
a number of places, somewhat replacing the existing mechanism of loading
network metadata.
It still needs more work, this is the initial refactor that introduces
runtime configuration in some of the places that need it.
The PR changes the way presets and constants work, to match the spec. In
particular, a "preset" now refers to the compile-time configuration
while a "cfg" or "RuntimeConfig" is the dynamic part.
A single binary can support either mainnet or minimal, but not both.
Support for other presets has been removed completely (can be readded,
in case there's need).
There's a number of outstanding tasks:
* `SECONDS_PER_SLOT` still needs fixing
* loading custom runtime configs needs redoing
* checking constants against YAML file
* yeerongpilly support
`build/nimbus_beacon_node --network=yeerongpilly --discv5:no --log-level=DEBUG`
* load fork epoch from config
* fix fork digest sent in status
* nicer error string for request failures
* fix tools
* one more
* fixup
* fixup
* fixup
* use "standard" network definition folder in local testnet
Files are loaded from their standard locations, including genesis etc,
to conform to the format used in the `eth2-networks` repo.
* fix launch scripts, allow unknown config values
* fix base config of rest test
* cleanups
* bundle mainnet config using common loader
* fix spec links and names
* only include supported preset in binary
* drop yeerongpilly, add altair-devnet-0, support boot_enr.yaml
2021-07-12 13:01:38 +00:00
|
|
|
if theirStatus.forkDigest != ourStatus.forkDigest:
|
2020-10-01 18:56:42 +00:00
|
|
|
debug "Irrelevant peer", peer, theirStatus, ourStatus
|
2019-09-09 23:55:01 +00:00
|
|
|
await peer.disconnect(IrrelevantNetwork)
|
2020-05-13 06:37:58 +00:00
|
|
|
else:
|
|
|
|
peer.setStatusMsg(theirStatus)
|
2020-11-26 19:23:45 +00:00
|
|
|
if peer.connectionState == Connecting:
|
|
|
|
# As soon as we get here it means that we passed handshake succesfully. So
|
|
|
|
# we can add this peer to PeerPool.
|
|
|
|
await peer.handlePeer()
|
2019-12-02 15:38:18 +00:00
|
|
|
|
2021-06-01 11:13:40 +00:00
|
|
|
proc initBeaconSync*(network: Eth2Node, dag: ChainDAGRef,
|
2021-08-19 10:45:31 +00:00
|
|
|
getBeaconTime: GetBeaconTimeFn) =
|
2020-04-15 02:41:22 +00:00
|
|
|
var networkState = network.protocolState(BeaconSync)
|
2021-06-01 11:13:40 +00:00
|
|
|
networkState.dag = dag
|
2021-08-19 10:45:31 +00:00
|
|
|
networkState.getBeaconTime = getBeaconTime
|