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].}
|
|
|
|
|
2022-03-22 20:23:36 +00:00
|
|
|
# References to `vFuture` refer to the pre-release proposal of the libp2p based
|
|
|
|
# light client sync protocol. Conflicting release versions are not in use.
|
|
|
|
# https://github.com/ethereum/consensus-specs/pull/2802
|
|
|
|
|
2018-11-23 23:58:49 +00:00
|
|
|
import
|
2022-05-05 11:00:02 +00:00
|
|
|
std/[options, tables, sets, macros],
|
|
|
|
chronicles, chronos, snappy/codec,
|
|
|
|
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
|
2022-03-22 20:23:36 +00:00
|
|
|
# https://github.com/ethereum/consensus-specs/blob/vFuture/specs/altair/sync-protocol.md#configuration
|
|
|
|
MAX_REQUEST_LIGHT_CLIENT_UPDATES = 128
|
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)
|
2022-03-22 20:23:36 +00:00
|
|
|
lightClientUpdateResponseCost = allowedOpsPerSecondCost(100)
|
|
|
|
lightClientUpdateByRangeLookupCost = allowedOpsPerSecondCost(20)
|
|
|
|
lightClientBootstrapLookupCost = allowedOpsPerSecondCost(5)
|
|
|
|
lightClientBootstrapResponseCost = allowedOpsPerSecondCost(100)
|
2020-10-09 13:44:51 +00:00
|
|
|
|
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
|
|
|
|
2022-05-05 09:17:14 +00:00
|
|
|
template readChunkPayload*(
|
|
|
|
conn: Connection, peer: Peer, MsgType: type ForkySignedBeaconBlock):
|
|
|
|
Future[NetRes[MsgType]] =
|
|
|
|
readChunkPayload(conn, peer, maxChunkSize(MsgType), MsgType)
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
proc readChunkPayload*(
|
2022-05-05 05:45:35 +00:00
|
|
|
conn: Connection, peer: Peer, maxChunkSize: uint32,
|
|
|
|
MsgType: type (ref ForkedSignedBeaconBlock)):
|
2022-02-07 17:20:10 +00:00
|
|
|
Future[NetRes[MsgType]] {.async.} =
|
2021-07-07 09:09:47 +00:00
|
|
|
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
|
|
|
|
|
2022-05-05 05:45:35 +00:00
|
|
|
# Ignores maxChunkSize; needs to be consistent formal parameters,
|
|
|
|
# but this function is where that's determined.
|
2021-07-07 09:09:47 +00:00
|
|
|
if contextBytes == peer.network.forkDigests.phase0:
|
2022-05-05 09:17:14 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, phase0.SignedBeaconBlock)
|
2021-07-07 09:09:47 +00:00
|
|
|
if res.isOk:
|
2022-02-07 17:20:10 +00:00
|
|
|
return ok newClone(ForkedSignedBeaconBlock.init(res.get))
|
2021-07-07 09:09:47 +00:00
|
|
|
else:
|
|
|
|
return err(res.error)
|
|
|
|
elif contextBytes == peer.network.forkDigests.altair:
|
2022-05-05 09:17:14 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, altair.SignedBeaconBlock)
|
2021-07-07 09:09:47 +00:00
|
|
|
if res.isOk:
|
2022-02-07 17:20:10 +00:00
|
|
|
return ok newClone(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-05-05 09:17:14 +00:00
|
|
|
let res = await readChunkPayload(conn, peer, bellatrix.SignedBeaconBlock)
|
2021-09-29 16:44:43 +00:00
|
|
|
if res.isOk:
|
2022-02-07 17:20:10 +00:00
|
|
|
return ok newClone(ForkedSignedBeaconBlock.init(res.get))
|
2021-09-29 16:44:43 +00:00
|
|
|
else:
|
|
|
|
return err(res.error)
|
2021-07-07 09:09:47 +00:00
|
|
|
else:
|
|
|
|
return neterr InvalidContextBytes
|
|
|
|
|
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 & ")"
|
|
|
|
|
2022-01-26 16:20:21 +00:00
|
|
|
proc getCurrentStatus(state: BeaconSyncNetworkState): StatusMsg =
|
2019-09-09 23:55:01 +00:00
|
|
|
let
|
2021-06-01 11:13:40 +00:00
|
|
|
dag = state.dag
|
2022-01-26 16:20:21 +00:00
|
|
|
wallSlot = state.getBeaconTime().slotOrZero
|
2019-09-09 23:55:01 +00:00
|
|
|
|
2019-09-11 16:45:22 +00:00
|
|
|
StatusMsg(
|
2022-01-26 16:20:21 +00:00
|
|
|
forkDigest: dag.forkDigestAtEpoch(wallSlot.epoch),
|
|
|
|
finalizedRoot: dag.finalizedHead.blck.root,
|
|
|
|
finalizedEpoch: dag.finalizedHead.slot.epoch,
|
|
|
|
headRoot: dag.head.root,
|
|
|
|
headSlot: dag.head.slot)
|
|
|
|
|
|
|
|
proc checkStatusMsg(state: BeaconSyncNetworkState, status: StatusMsg):
|
|
|
|
Result[void, cstring] =
|
|
|
|
let
|
|
|
|
dag = state.dag
|
|
|
|
wallSlot = (state.getBeaconTime() + MAXIMUM_GOSSIP_CLOCK_DISPARITY).slotOrZero
|
|
|
|
|
|
|
|
if status.finalizedEpoch > status.headSlot.epoch:
|
|
|
|
# Can be equal during genesis or checkpoint start
|
|
|
|
return err("finalized epoch newer than head")
|
|
|
|
|
|
|
|
if status.headSlot > wallSlot:
|
|
|
|
return err("head more recent than wall clock")
|
|
|
|
|
|
|
|
if dag.forkDigestAtEpoch(wallSlot.epoch) != status.forkDigest:
|
|
|
|
return err("fork digests differ")
|
|
|
|
|
|
|
|
if status.finalizedEpoch <= dag.finalizedHead.slot.epoch:
|
|
|
|
let blockId = dag.getBlockIdAtSlot(status.finalizedEpoch.start_slot())
|
2022-03-15 08:24:55 +00:00
|
|
|
if blockId.isSome and
|
|
|
|
(not status.finalizedRoot.isZero) and
|
|
|
|
status.finalizedRoot != blockId.get().bid.root:
|
2022-01-26 16:20:21 +00:00
|
|
|
return err("peer following different finality")
|
|
|
|
|
|
|
|
ok()
|
2019-09-08 22:03:41 +00:00
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
proc handleStatus(peer: Peer,
|
|
|
|
state: BeaconSyncNetworkState,
|
2022-01-26 16:20:21 +00:00
|
|
|
theirStatus: StatusMsg): Future[bool] {.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:
|
2022-01-26 16:20:21 +00:00
|
|
|
discard await peer.handleStatus(peer.networkState, theirStatus.get())
|
2020-08-10 10:58:34 +00:00
|
|
|
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)
|
2022-01-26 16:20:21 +00:00
|
|
|
discard await peer.handleStatus(peer.networkState, theirStatus)
|
2020-05-23 22:24:47 +00:00
|
|
|
|
|
|
|
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).} =
|
2022-02-07 17:20:10 +00:00
|
|
|
# TODO Semantically, this request should return a non-ref, but doing so
|
|
|
|
# runs into extreme inefficiency due to the compiler introducing
|
|
|
|
# hidden copies - in future nim versions with move support, this should
|
|
|
|
# be revisited
|
|
|
|
# TODO This code is more complicated than it needs to be, since the type
|
|
|
|
# of the multiple chunks response is not actually used in this server
|
|
|
|
# implementation (it's used to derive the signature of the client
|
|
|
|
# function, not in the code below!)
|
|
|
|
# TODO although you can't tell from this function definition, a magic
|
|
|
|
# client call that returns `seq[ref SignedBeaconBlock]` will
|
|
|
|
# will be generated by the libp2p macro - we guarantee that seq items
|
|
|
|
# are `not-nil` in the implementation
|
2020-08-05 23:22:12 +00:00
|
|
|
trace "got range request", peer, startSlot,
|
|
|
|
count = reqCount, step = reqStep
|
2022-02-07 17:20:10 +00:00
|
|
|
if reqCount == 0'u64 or reqStep == 0'u64:
|
|
|
|
raise newException(InvalidInputsError, "Empty range requested")
|
2019-09-08 22:03:41 +00:00
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
let
|
|
|
|
dag = peer.networkState.dag
|
|
|
|
|
|
|
|
if startSlot.epoch >= dag.cfg.ALTAIR_FORK_EPOCH:
|
|
|
|
# "Clients MAY limit the number of blocks in the response."
|
|
|
|
# https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#beaconblocksbyrange
|
|
|
|
debug "Block range v1 request for post-altair range",
|
|
|
|
peer, startSlot, reqCount, reqStep
|
|
|
|
return
|
|
|
|
|
|
|
|
var blocks: array[MAX_REQUEST_BLOCKS, BlockId]
|
|
|
|
|
|
|
|
let
|
|
|
|
# Limit number of blocks in response
|
|
|
|
count = int min(reqCount, blocks.lenu64)
|
|
|
|
endIndex = count - 1
|
|
|
|
startIndex =
|
|
|
|
dag.getBlockRange(startSlot, reqStep, blocks.toOpenArray(0, endIndex))
|
|
|
|
|
|
|
|
peer.updateRequestQuota(blockByRangeLookupCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
var
|
|
|
|
found = 0
|
|
|
|
bytes: seq[byte]
|
|
|
|
|
|
|
|
for i in startIndex..endIndex:
|
|
|
|
if blocks[i].slot.epoch >= dag.cfg.ALTAIR_FORK_EPOCH:
|
|
|
|
# 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
|
2022-05-05 11:00:02 +00:00
|
|
|
if dag.getBlockSZ(blocks[i], bytes):
|
|
|
|
let uncompressedLen = uncompressedLenFramed(bytes).valueOr:
|
|
|
|
warn "Cannot read block size, database corrupt?",
|
|
|
|
bytes = bytes.len(), blck = shortLog(blocks[i])
|
|
|
|
continue
|
2022-02-07 17:20:10 +00:00
|
|
|
|
|
|
|
peer.updateRequestQuota(blockResponseCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
await response.writeBytesSZ(uncompressedLen, bytes, []) # phase0 bytes
|
2022-02-07 17:20:10 +00:00
|
|
|
|
|
|
|
inc found
|
|
|
|
|
|
|
|
debug "Block range request done",
|
|
|
|
peer, startSlot, count, reqStep, found
|
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).} =
|
2022-02-07 17:20:10 +00:00
|
|
|
# TODO Semantically, this request should return a non-ref, but doing so
|
|
|
|
# runs into extreme inefficiency due to the compiler introducing
|
|
|
|
# hidden copies - in future nim versions with move support, this should
|
|
|
|
# be revisited
|
|
|
|
# TODO This code is more complicated than it needs to be, since the type
|
|
|
|
# of the multiple chunks response is not actually used in this server
|
|
|
|
# implementation (it's used to derive the signature of the client
|
|
|
|
# function, not in the code below!)
|
|
|
|
# TODO although you can't tell from this function definition, a magic
|
|
|
|
# client call that returns `seq[ref SignedBeaconBlock]` will
|
|
|
|
# will be generated by the libp2p macro - we guarantee that seq items
|
|
|
|
# are `not-nil` in the implementation
|
|
|
|
|
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
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
var
|
|
|
|
found = 0
|
|
|
|
bytes: seq[byte]
|
|
|
|
|
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-08-27 06:32:51 +00:00
|
|
|
for i in 0..<count:
|
2022-02-07 17:20:10 +00:00
|
|
|
let
|
|
|
|
blockRef = dag.getBlockRef(blockRoots[i]).valueOr:
|
2021-07-15 19:01:07 +00:00
|
|
|
continue
|
2021-07-07 09:09:47 +00:00
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
if blockRef.slot.epoch >= dag.cfg.ALTAIR_FORK_EPOCH:
|
|
|
|
# Skipping this block should be fine 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#beaconblocksbyroot
|
|
|
|
#
|
|
|
|
# Also, our response would be indistinguishable from a node
|
|
|
|
# that have been synced exactly to the altair transition slot.
|
|
|
|
continue
|
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
if dag.getBlockSZ(blockRef.bid, bytes):
|
|
|
|
let uncompressedLen = uncompressedLenFramed(bytes).valueOr:
|
|
|
|
warn "Cannot read block size, database corrupt?",
|
|
|
|
bytes = bytes.len(), blck = shortLog(blockRef)
|
|
|
|
continue
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
peer.updateRequestQuota(blockResponseCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
await response.writeBytesSZ(uncompressedLen, bytes, []) # phase0
|
2022-02-07 17:20:10 +00:00
|
|
|
inc found
|
2021-07-07 09:09:47 +00:00
|
|
|
|
|
|
|
debug "Block root request done",
|
|
|
|
peer, roots = blockRoots.len, count, found
|
|
|
|
|
|
|
|
proc beaconBlocksByRange_v2(
|
|
|
|
peer: Peer,
|
|
|
|
startSlot: Slot,
|
|
|
|
reqCount: uint64,
|
|
|
|
reqStep: uint64,
|
2022-02-07 17:20:10 +00:00
|
|
|
response: MultipleChunksResponse[ref ForkedSignedBeaconBlock])
|
2021-07-07 09:09:47 +00:00
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_range", 2).} =
|
2022-02-07 17:20:10 +00:00
|
|
|
# TODO Semantically, this request should return a non-ref, but doing so
|
|
|
|
# runs into extreme inefficiency due to the compiler introducing
|
|
|
|
# hidden copies - in future nim versions with move support, this should
|
|
|
|
# be revisited
|
|
|
|
# TODO This code is more complicated than it needs to be, since the type
|
|
|
|
# of the multiple chunks response is not actually used in this server
|
|
|
|
# implementation (it's used to derive the signature of the client
|
|
|
|
# function, not in the code below!)
|
|
|
|
# TODO although you can't tell from this function definition, a magic
|
|
|
|
# client call that returns `seq[ref ForkedSignedBeaconBlock]` will
|
|
|
|
# will be generated by the libp2p macro - we guarantee that seq items
|
|
|
|
# are `not-nil` in the implementation
|
|
|
|
|
2021-07-07 09:09:47 +00:00
|
|
|
trace "got range request", peer, startSlot,
|
|
|
|
count = reqCount, step = reqStep
|
2022-02-07 17:20:10 +00:00
|
|
|
if reqCount == 0 or reqStep == 0:
|
2021-07-07 09:09:47 +00:00
|
|
|
raise newException(InvalidInputsError, "Empty range requested")
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
var blocks: array[MAX_REQUEST_BLOCKS, BlockId]
|
|
|
|
let
|
|
|
|
dag = peer.networkState.dag
|
|
|
|
# Limit number of blocks in response
|
|
|
|
count = int min(reqCount, blocks.lenu64)
|
|
|
|
endIndex = count - 1
|
|
|
|
startIndex =
|
|
|
|
dag.getBlockRange(startSlot, reqStep,
|
|
|
|
blocks.toOpenArray(0, endIndex))
|
|
|
|
|
|
|
|
peer.updateRequestQuota(blockByRangeLookupCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
var
|
|
|
|
found = 0
|
|
|
|
bytes: seq[byte]
|
|
|
|
|
|
|
|
for i in startIndex..endIndex:
|
2022-05-05 11:00:02 +00:00
|
|
|
if dag.getBlockSZ(blocks[i], bytes):
|
|
|
|
let uncompressedLen = uncompressedLenFramed(bytes).valueOr:
|
|
|
|
warn "Cannot read block size, database corrupt?",
|
|
|
|
bytes = bytes.len(), blck = shortLog(blocks[i])
|
|
|
|
continue
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
peer.updateRequestQuota(blockResponseCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
await response.writeBytesSZ(
|
|
|
|
uncompressedLen, bytes,
|
|
|
|
dag.forkDigestAtEpoch(blocks[i].slot.epoch).data)
|
2022-02-07 17:20:10 +00:00
|
|
|
|
|
|
|
inc found
|
|
|
|
|
|
|
|
debug "Block range request done",
|
|
|
|
peer, startSlot, count, reqStep
|
|
|
|
|
2021-07-07 09:09:47 +00:00
|
|
|
proc beaconBlocksByRoot_v2(
|
|
|
|
peer: Peer,
|
|
|
|
# Please note that the SSZ list here ensures that the
|
|
|
|
# spec constant MAX_REQUEST_BLOCKS is enforced:
|
|
|
|
blockRoots: BlockRootsList,
|
2022-02-07 17:20:10 +00:00
|
|
|
response: MultipleChunksResponse[ref ForkedSignedBeaconBlock])
|
2021-07-07 09:09:47 +00:00
|
|
|
{.async, libp2pProtocol("beacon_blocks_by_root", 2).} =
|
2022-02-07 17:20:10 +00:00
|
|
|
# TODO Semantically, this request should return a non-ref, but doing so
|
|
|
|
# runs into extreme inefficiency due to the compiler introducing
|
|
|
|
# hidden copies - in future nim versions with move support, this should
|
|
|
|
# be revisited
|
|
|
|
# TODO This code is more complicated than it needs to be, since the type
|
|
|
|
# of the multiple chunks response is not actually used in this server
|
|
|
|
# implementation (it's used to derive the signature of the client
|
|
|
|
# function, not in the code below!)
|
|
|
|
# TODO although you can't tell from this function definition, a magic
|
|
|
|
# client call that returns `seq[ref ForkedSignedBeaconBlock]` will
|
|
|
|
# will be generated by the libp2p macro - we guarantee that seq items
|
|
|
|
# are `not-nil` in the implementation
|
2021-07-07 09:09:47 +00:00
|
|
|
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()
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
var
|
|
|
|
found = 0
|
|
|
|
bytes: seq[byte]
|
|
|
|
|
2021-07-07 09:09:47 +00:00
|
|
|
for i in 0..<count:
|
2022-02-07 17:20:10 +00:00
|
|
|
let
|
|
|
|
blockRef = dag.getBlockRef(blockRoots[i]).valueOr:
|
|
|
|
continue
|
2019-08-05 00:00:49 +00:00
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
if dag.getBlockSZ(blockRef.bid, bytes):
|
|
|
|
let uncompressedLen = uncompressedLenFramed(bytes).valueOr:
|
|
|
|
warn "Cannot read block size, database corrupt?",
|
|
|
|
bytes = bytes.len(), blck = shortLog(blockRef)
|
|
|
|
continue
|
|
|
|
|
2022-02-07 17:20:10 +00:00
|
|
|
peer.updateRequestQuota(blockResponseCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
2022-05-05 11:00:02 +00:00
|
|
|
await response.writeBytesSZ(
|
|
|
|
uncompressedLen, bytes,
|
|
|
|
dag.forkDigestAtEpoch(blockRef.slot.epoch).data)
|
2022-02-07 17:20:10 +00:00
|
|
|
|
|
|
|
inc found
|
2020-10-09 13:44:51 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
debug "Block root request done",
|
|
|
|
peer, roots = blockRoots.len, count, found
|
|
|
|
|
2022-03-22 20:23:36 +00:00
|
|
|
# https://github.com/ethereum/consensus-specs/blob/vFuture/specs/altair/sync-protocol.md#bestlightclientupdatesbyrange
|
|
|
|
proc bestLightClientUpdatesByRange(
|
|
|
|
peer: Peer,
|
|
|
|
startPeriod: SyncCommitteePeriod,
|
|
|
|
reqCount: uint64,
|
|
|
|
response: MultipleChunksResponse[altair.LightClientUpdate])
|
|
|
|
{.async, libp2pProtocol("best_light_client_updates_by_range", 0,
|
|
|
|
isLightClientRequest = true).} =
|
|
|
|
trace "Received LC updates by range request", peer, startPeriod, reqCount
|
|
|
|
if reqCount == 0'u64:
|
|
|
|
raise newException(InvalidInputsError, "Empty range requested")
|
|
|
|
let dag = peer.networkState.dag
|
|
|
|
doAssert dag.serveLightClientData
|
|
|
|
|
|
|
|
let
|
|
|
|
headPeriod = dag.head.slot.sync_committee_period
|
|
|
|
# Limit number of updates in response
|
|
|
|
maxSupportedCount =
|
|
|
|
if startPeriod > headPeriod:
|
|
|
|
0'u64
|
|
|
|
else:
|
|
|
|
min(headPeriod + 1 - startPeriod, MAX_REQUEST_LIGHT_CLIENT_UPDATES)
|
|
|
|
count = min(reqCount, maxSupportedCount)
|
|
|
|
onePastPeriod = startPeriod + count
|
|
|
|
|
|
|
|
peer.updateRequestQuota(count.float * lightClientUpdateByRangeLookupCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
var found = 0
|
|
|
|
for period in startPeriod..<onePastPeriod:
|
|
|
|
let update = dag.getBestLightClientUpdateForPeriod(period)
|
|
|
|
if update.isSome:
|
|
|
|
await response.write(update.get)
|
|
|
|
inc found
|
|
|
|
|
|
|
|
peer.updateRequestQuota(found.float * lightClientUpdateResponseCost)
|
|
|
|
|
|
|
|
debug "LC updates by range request done", peer, startPeriod, count, found
|
|
|
|
|
|
|
|
if found == 0 and count > 0:
|
|
|
|
raise newException(ResourceUnavailableError,
|
|
|
|
"No light client update available")
|
|
|
|
|
|
|
|
# https://github.com/ethereum/consensus-specs/blob/vFuture/specs/altair/sync-protocol.md#getlatestlightclientupdate
|
|
|
|
proc latestLightClientUpdate(
|
|
|
|
peer: Peer,
|
|
|
|
response: SingleChunkResponse[altair.LightClientUpdate])
|
|
|
|
{.async, libp2pProtocol("latest_light_client_update", 0,
|
|
|
|
isLightClientRequest = true).} =
|
|
|
|
trace "Received latest LC update request", peer
|
|
|
|
let dag = peer.networkState.dag
|
|
|
|
doAssert dag.serveLightClientData
|
|
|
|
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
let update = dag.getLatestLightClientUpdate
|
|
|
|
if update.isSome:
|
|
|
|
await response.send(update.get)
|
|
|
|
else:
|
|
|
|
raise newException(ResourceUnavailableError,
|
|
|
|
"No light client update available")
|
|
|
|
|
|
|
|
peer.updateRequestQuota(lightClientUpdateResponseCost)
|
|
|
|
|
|
|
|
# https://github.com/ethereum/consensus-specs/blob/vFuture/specs/altair/sync-protocol.md#getoptimisticlightclientupdate
|
|
|
|
proc optimisticLightClientUpdate(
|
|
|
|
peer: Peer,
|
|
|
|
response: SingleChunkResponse[OptimisticLightClientUpdate])
|
|
|
|
{.async, libp2pProtocol("optimistic_light_client_update", 0,
|
|
|
|
isLightClientRequest = true).} =
|
|
|
|
trace "Received optimistic LC update request", peer
|
|
|
|
let dag = peer.networkState.dag
|
|
|
|
doAssert dag.serveLightClientData
|
|
|
|
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
let optimistic_update = dag.getOptimisticLightClientUpdate
|
|
|
|
if optimistic_update.isSome:
|
|
|
|
await response.send(optimistic_update.get)
|
|
|
|
else:
|
|
|
|
raise newException(ResourceUnavailableError,
|
|
|
|
"No optimistic light client update available")
|
|
|
|
|
|
|
|
peer.updateRequestQuota(lightClientUpdateResponseCost)
|
|
|
|
|
|
|
|
# https://github.com/ethereum/consensus-specs/blob/vFuture/specs/altair/sync-protocol.md#getlightclientbootstrap
|
|
|
|
proc lightClientBootstrap(
|
|
|
|
peer: Peer,
|
|
|
|
blockRoot: Eth2Digest,
|
|
|
|
response: SingleChunkResponse[altair.LightClientBootstrap])
|
|
|
|
{.async, libp2pProtocol("light_client_bootstrap", 0,
|
|
|
|
isLightClientRequest = true).} =
|
|
|
|
trace "Received LC bootstrap request", peer, blockRoot
|
|
|
|
let dag = peer.networkState.dag
|
|
|
|
doAssert dag.serveLightClientData
|
|
|
|
|
|
|
|
peer.updateRequestQuota(lightClientBootstrapLookupCost)
|
|
|
|
peer.awaitNonNegativeRequestQuota()
|
|
|
|
|
|
|
|
let bootstrap = dag.getLightClientBootstrap(blockRoot)
|
|
|
|
if bootstrap.isOk:
|
|
|
|
await response.send(bootstrap.get)
|
|
|
|
else:
|
|
|
|
raise newException(ResourceUnavailableError,
|
|
|
|
"No light client bootstrap available")
|
|
|
|
|
|
|
|
peer.updateRequestQuota(lightClientBootstrapResponseCost)
|
|
|
|
|
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
|
|
|
|
2022-01-26 16:20:21 +00:00
|
|
|
proc handleStatus(peer: Peer,
|
|
|
|
state: BeaconSyncNetworkState,
|
|
|
|
theirStatus: StatusMsg): Future[bool] {.async, gcsafe.} =
|
|
|
|
let
|
|
|
|
res = checkStatusMsg(state, theirStatus)
|
|
|
|
|
|
|
|
return if res.isErr():
|
|
|
|
debug "Irrelevant peer", peer, theirStatus, err = res.error()
|
|
|
|
await peer.disconnect(IrrelevantNetwork)
|
|
|
|
false
|
|
|
|
else:
|
|
|
|
peer.setStatusMsg(theirStatus)
|
|
|
|
|
|
|
|
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()
|
|
|
|
true
|
|
|
|
|
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:
|
2022-01-26 16:20:21 +00:00
|
|
|
return await peer.handleStatus(nstate, theirStatus.get())
|
2020-09-23 15:58:02 +00:00
|
|
|
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
|
|
|
|
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
|