2022-03-11 20:28:10 +00:00
|
|
|
# beacon_chain
|
|
|
|
# Copyright (c) 2022 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
|
|
|
# This implements the pre-release proposal of the libp2p based light client sync
|
|
|
|
# protocol. See https://github.com/ethereum/consensus-specs/pull/2802
|
|
|
|
|
|
|
|
import
|
|
|
|
# Status libraries
|
|
|
|
stew/[bitops2, objects],
|
|
|
|
chronos,
|
|
|
|
# Beacon chain internals
|
|
|
|
../spec/datatypes/[phase0, altair, bellatrix],
|
|
|
|
"."/[block_pools_types, blockchain_dag]
|
|
|
|
|
|
|
|
logScope: topics = "chaindag"
|
|
|
|
|
|
|
|
type
|
|
|
|
HashedBeaconStateWithSyncCommittee =
|
|
|
|
bellatrix.HashedBeaconState |
|
|
|
|
altair.HashedBeaconState
|
|
|
|
|
|
|
|
TrustedSignedBeaconBlockWithSyncAggregate =
|
|
|
|
bellatrix.TrustedSignedBeaconBlock |
|
|
|
|
altair.TrustedSignedBeaconBlock
|
|
|
|
|
|
|
|
template nextEpochBoundarySlot(slot: Slot): Slot =
|
|
|
|
## Compute the first possible epoch boundary state slot of a `Checkpoint`
|
|
|
|
## referring to a block at given slot.
|
|
|
|
(slot + (SLOTS_PER_EPOCH - 1)).epoch.start_slot
|
|
|
|
|
2022-06-14 08:19:11 +00:00
|
|
|
func computeEarliestLightClientSlot(dag: ChainDAGRef): Slot =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Compute the earliest slot for which light client data is retained.
|
|
|
|
let
|
|
|
|
minSupportedSlot = max(
|
|
|
|
dag.cfg.ALTAIR_FORK_EPOCH.start_slot,
|
|
|
|
dag.lightClientCache.importTailSlot)
|
2022-03-16 07:20:40 +00:00
|
|
|
currentSlot = getStateField(dag.headState, slot)
|
2022-03-11 20:28:10 +00:00
|
|
|
if currentSlot < minSupportedSlot:
|
|
|
|
return minSupportedSlot
|
|
|
|
|
|
|
|
let
|
|
|
|
MIN_EPOCHS_FOR_BLOCK_REQUESTS =
|
|
|
|
dag.cfg.MIN_VALIDATOR_WITHDRAWABILITY_DELAY +
|
|
|
|
dag.cfg.CHURN_LIMIT_QUOTIENT div 2
|
|
|
|
MIN_SLOTS_FOR_BLOCK_REQUESTS =
|
|
|
|
MIN_EPOCHS_FOR_BLOCK_REQUESTS * SLOTS_PER_EPOCH
|
2022-03-19 08:58:55 +00:00
|
|
|
if currentSlot - minSupportedSlot < MIN_SLOTS_FOR_BLOCK_REQUESTS:
|
|
|
|
return minSupportedSlot
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
let earliestSlot = currentSlot - MIN_SLOTS_FOR_BLOCK_REQUESTS
|
2022-03-19 08:58:55 +00:00
|
|
|
max(earliestSlot.sync_committee_period.start_slot, minSupportedSlot)
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-03-20 10:58:59 +00:00
|
|
|
proc updateExistingState(
|
|
|
|
dag: ChainDAGRef, state: var ForkedHashedBeaconState, bsi: BlockSlotId,
|
|
|
|
save: bool, cache: var StateCache): bool =
|
|
|
|
## Wrapper around `updateState` for states expected to exist.
|
|
|
|
let ok = dag.updateState(state, bsi, save, cache)
|
|
|
|
if not ok:
|
|
|
|
error "State failed to load unexpectedly", bsi, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
ok
|
|
|
|
|
|
|
|
template withUpdatedExistingState(
|
|
|
|
dag: ChainDAGRef, state: var ForkedHashedBeaconState,
|
|
|
|
bsiParam: BlockSlotId, okBody: untyped, failureBody: untyped): untyped =
|
|
|
|
## Wrapper around `withUpdatedState` for states expected to exist.
|
|
|
|
block:
|
|
|
|
let bsi = bsiParam
|
|
|
|
dag.withUpdatedState(state, bsiParam) do:
|
|
|
|
okBody
|
|
|
|
do:
|
|
|
|
error "State failed to load unexpectedly", bsi, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
failureBody
|
|
|
|
|
|
|
|
proc getExistingBlockIdAtSlot(dag: ChainDAGRef, slot: Slot): Opt[BlockSlotId] =
|
|
|
|
## Wrapper around `getBlockIdAtSlot` for blocks expected to exist.
|
|
|
|
let bsi = dag.getBlockIdAtSlot(slot)
|
|
|
|
if bsi.isErr:
|
|
|
|
error "Block failed to load unexpectedly", slot, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
bsi
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
proc existingParent(dag: ChainDAGRef, bid: BlockId): Opt[BlockId] =
|
2022-03-20 10:58:59 +00:00
|
|
|
## Wrapper around `parent` for parents known to exist.
|
|
|
|
let parent = dag.parent(bid)
|
|
|
|
if parent.isErr:
|
|
|
|
error "Parent failed to load unexpectedly", bid, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
parent
|
|
|
|
|
2022-06-14 08:19:11 +00:00
|
|
|
proc getExistingForkedBlock(
|
2022-03-20 10:58:59 +00:00
|
|
|
dag: ChainDAGRef, bid: BlockId): Opt[ForkedTrustedSignedBeaconBlock] =
|
|
|
|
## Wrapper around `getForkedBlock` for blocks expected to exist.
|
|
|
|
let bdata = dag.getForkedBlock(bid)
|
|
|
|
if bdata.isErr:
|
|
|
|
error "Block failed to load unexpectedly", bid, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
bdata
|
|
|
|
|
2022-06-07 17:01:11 +00:00
|
|
|
proc existingCurrentSyncCommitteeForPeriod(
|
2022-03-11 20:28:10 +00:00
|
|
|
dag: ChainDAGRef,
|
2022-03-16 07:20:40 +00:00
|
|
|
tmpState: var ForkedHashedBeaconState,
|
2022-03-20 10:58:59 +00:00
|
|
|
period: SyncCommitteePeriod): Opt[SyncCommittee] =
|
2022-06-07 17:01:11 +00:00
|
|
|
## Wrapper around `currentSyncCommitteeForPeriod` for states known to exist.
|
|
|
|
let syncCommittee = dag.currentSyncCommitteeForPeriod(tmpState, period)
|
|
|
|
if syncCommittee.isErr:
|
|
|
|
error "Current sync committee failed to load unexpectedly",
|
|
|
|
period, tail = dag.tail.slot
|
|
|
|
doAssert verifyFinalization notin dag.updateFlags
|
|
|
|
syncCommittee
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
template syncCommitteeRoot(
|
|
|
|
state: HashedBeaconStateWithSyncCommittee): Eth2Digest =
|
|
|
|
## Compute a root to uniquely identify `current_sync_committee` and
|
|
|
|
## `next_sync_committee`.
|
|
|
|
withEth2Hash:
|
|
|
|
h.update state.data.current_sync_committee.hash_tree_root().data
|
|
|
|
h.update state.data.next_sync_committee.hash_tree_root().data
|
|
|
|
|
|
|
|
proc syncCommitteeRootForPeriod(
|
|
|
|
dag: ChainDAGRef,
|
2022-03-16 07:20:40 +00:00
|
|
|
tmpState: var ForkedHashedBeaconState,
|
2022-03-20 10:58:59 +00:00
|
|
|
period: SyncCommitteePeriod): Opt[Eth2Digest] =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Compute a root to uniquely identify `current_sync_committee` and
|
|
|
|
## `next_sync_committee` for a given sync committee period.
|
|
|
|
## For non-finalized periods, follow the chain as selected by fork choice.
|
2022-06-14 20:02:03 +00:00
|
|
|
let lowSlot = max(dag.tail.slot, dag.cfg.ALTAIR_FORK_EPOCH.start_slot)
|
|
|
|
if period < lowSlot.sync_committee_period:
|
|
|
|
return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
|
|
|
periodStartSlot = period.start_slot
|
2022-06-14 20:02:03 +00:00
|
|
|
syncCommitteeSlot = max(periodStartSlot, lowSlot)
|
2022-03-20 10:58:59 +00:00
|
|
|
bsi = ? dag.getExistingBlockIdAtSlot(syncCommitteeSlot)
|
|
|
|
dag.withUpdatedExistingState(tmpState, bsi) do:
|
2022-03-16 07:20:40 +00:00
|
|
|
withState(state):
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
2022-03-20 10:58:59 +00:00
|
|
|
ok state.syncCommitteeRoot
|
2022-03-11 20:28:10 +00:00
|
|
|
else: raiseAssert "Unreachable"
|
2022-03-20 10:58:59 +00:00
|
|
|
do: err()
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
proc getLightClientData(
|
|
|
|
dag: ChainDAGRef,
|
|
|
|
bid: BlockId): CachedLightClientData =
|
|
|
|
## Fetch cached light client data about a given block.
|
|
|
|
## Data must be cached (`cacheLightClientData`) before calling this function.
|
|
|
|
try: dag.lightClientCache.data[bid]
|
|
|
|
except KeyError: raiseAssert "Unreachable"
|
|
|
|
|
2022-06-14 20:13:00 +00:00
|
|
|
proc cacheLightClientData(
|
|
|
|
dag: ChainDAGRef, state: HashedBeaconStateWithSyncCommittee, bid: BlockId) =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Cache data for a given block and its post-state to speed up creating future
|
|
|
|
## `LightClientUpdate` and `LightClientBootstrap` instances that refer to this
|
|
|
|
## block and state.
|
2022-05-23 12:02:54 +00:00
|
|
|
var cachedData {.noinit.}: CachedLightClientData
|
2022-03-11 20:28:10 +00:00
|
|
|
state.data.build_proof(
|
2022-05-23 12:02:54 +00:00
|
|
|
altair.CURRENT_SYNC_COMMITTEE_INDEX,
|
|
|
|
cachedData.current_sync_committee_branch)
|
2022-03-11 20:28:10 +00:00
|
|
|
state.data.build_proof(
|
2022-05-23 12:02:54 +00:00
|
|
|
altair.NEXT_SYNC_COMMITTEE_INDEX,
|
|
|
|
cachedData.next_sync_committee_branch)
|
|
|
|
cachedData.finalized_slot =
|
|
|
|
state.data.finalized_checkpoint.epoch.start_slot
|
2022-03-11 20:28:10 +00:00
|
|
|
state.data.build_proof(
|
2022-05-23 12:02:54 +00:00
|
|
|
altair.FINALIZED_ROOT_INDEX,
|
|
|
|
cachedData.finality_branch)
|
|
|
|
if dag.lightClientCache.data.hasKeyOrPut(bid, cachedData):
|
2022-03-11 20:28:10 +00:00
|
|
|
doAssert false, "Redundant `cacheLightClientData` call"
|
|
|
|
|
|
|
|
proc deleteLightClientData*(dag: ChainDAGRef, bid: BlockId) =
|
|
|
|
## Delete cached light client data for a given block. This needs to be called
|
|
|
|
## when a block becomes unreachable due to finalization of a different fork.
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.None:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
dag.lightClientCache.data.del bid
|
|
|
|
|
|
|
|
template lazy_header(name: untyped): untyped {.dirty.} =
|
|
|
|
## `createLightClientUpdates` helper to lazily load a known block header.
|
|
|
|
var `name ptr`: ptr[BeaconBlockHeader]
|
2022-04-08 16:22:49 +00:00
|
|
|
template `assign _ name`(target: var BeaconBlockHeader,
|
2022-05-23 12:02:54 +00:00
|
|
|
bid: BlockId): bool =
|
2022-03-11 20:28:10 +00:00
|
|
|
if `name ptr` != nil:
|
|
|
|
target = `name ptr`[]
|
2022-05-23 12:02:54 +00:00
|
|
|
true
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
let bdata = dag.getExistingForkedBlock(bid)
|
|
|
|
if bdata.isOk:
|
2022-06-14 15:31:10 +00:00
|
|
|
target = bdata.get.toBeaconBlockHeader()
|
2022-05-23 12:02:54 +00:00
|
|
|
`name ptr` = addr target
|
|
|
|
bdata.isOk
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
template lazy_data(name: untyped): untyped {.dirty.} =
|
|
|
|
## `createLightClientUpdates` helper to lazily load cached light client state.
|
|
|
|
var `name` {.noinit.}: CachedLightClientData
|
2022-05-23 12:02:54 +00:00
|
|
|
`name`.finalized_slot = FAR_FUTURE_SLOT
|
|
|
|
template `load _ name`(bid: BlockId) =
|
|
|
|
if `name`.finalized_slot == FAR_FUTURE_SLOT:
|
2022-03-11 20:28:10 +00:00
|
|
|
`name` = dag.getLightClientData(bid)
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
template lazy_bid(name: untyped): untyped {.dirty.} =
|
|
|
|
## `createLightClientUpdates` helper to lazily load a block id.
|
|
|
|
var
|
|
|
|
`name` = BlockId(slot: FAR_FUTURE_SLOT)
|
|
|
|
`name _ ok` = true
|
|
|
|
template `load _ name`(slot: Slot): bool =
|
|
|
|
if `name _ ok` and `name`.slot == FAR_FUTURE_SLOT:
|
|
|
|
let bsi = dag.getBlockIdAtSlot(slot)
|
|
|
|
if bsi.isErr:
|
|
|
|
`name _ ok` = false
|
|
|
|
else:
|
|
|
|
`name` = bsi.get.bid
|
|
|
|
`name _ ok`
|
|
|
|
|
2022-03-11 20:28:10 +00:00
|
|
|
proc createLightClientUpdates(
|
|
|
|
dag: ChainDAGRef,
|
|
|
|
state: HashedBeaconStateWithSyncCommittee,
|
|
|
|
blck: TrustedSignedBeaconBlockWithSyncAggregate,
|
2022-03-20 10:58:59 +00:00
|
|
|
parent_bid: BlockId) =
|
2022-05-23 12:02:54 +00:00
|
|
|
## Create `LightClientUpdate` instances for a given block and its post-state,
|
|
|
|
## and keep track of best / latest ones. Data about the parent block's
|
|
|
|
## post-state must be cached (`cacheLightClientData`) before calling this.
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
# Verify sync committee has sufficient participants
|
|
|
|
template sync_aggregate(): auto = blck.message.body.sync_aggregate
|
|
|
|
template sync_committee_bits(): auto = sync_aggregate.sync_committee_bits
|
|
|
|
let num_active_participants = countOnes(sync_committee_bits).uint64
|
|
|
|
if num_active_participants < MIN_SYNC_COMMITTEE_PARTICIPANTS:
|
|
|
|
return
|
|
|
|
|
|
|
|
# Verify attested block (parent) is recent enough and that state is available
|
2022-05-23 12:02:54 +00:00
|
|
|
template attested_bid(): auto = parent_bid
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
|
|
|
earliest_slot = dag.computeEarliestLightClientSlot
|
2022-05-23 12:02:54 +00:00
|
|
|
attested_slot = attested_bid.slot
|
2022-03-11 20:28:10 +00:00
|
|
|
if attested_slot < earliest_slot:
|
|
|
|
return
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Lazy variables to hold historic data
|
2022-03-11 20:28:10 +00:00
|
|
|
lazy_header(attested_header)
|
|
|
|
lazy_data(attested_data)
|
2022-05-23 12:02:54 +00:00
|
|
|
lazy_bid(finalized_bid)
|
2022-03-11 20:28:10 +00:00
|
|
|
lazy_header(finalized_header)
|
2022-05-23 12:02:54 +00:00
|
|
|
|
|
|
|
# Update latest light client data
|
|
|
|
template latest(): auto = dag.lightClientCache.latest
|
|
|
|
var
|
|
|
|
newFinality = false
|
|
|
|
newOptimistic = false
|
|
|
|
let
|
|
|
|
signature_slot = blck.message.slot
|
|
|
|
is_later =
|
|
|
|
if attested_slot != latest.attested_header.slot:
|
|
|
|
attested_slot > latest.attested_header.slot
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
signature_slot > latest.signature_slot
|
|
|
|
if is_later and latest.attested_header.assign_attested_header(attested_bid):
|
|
|
|
load_attested_data(attested_bid)
|
|
|
|
let finalized_slot = attested_data.finalized_slot
|
|
|
|
if finalized_slot == latest.finalized_header.slot:
|
|
|
|
latest.finality_branch = attested_data.finality_branch
|
|
|
|
elif finalized_slot == GENESIS_SLOT:
|
|
|
|
latest.finalized_header.reset()
|
|
|
|
latest.finality_branch = attested_data.finality_branch
|
|
|
|
elif load_finalized_bid(finalized_slot) and
|
|
|
|
latest.finalized_header.assign_finalized_header(finalized_bid):
|
|
|
|
latest.finality_branch = attested_data.finality_branch
|
|
|
|
newFinality = true
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
latest.finalized_header.reset()
|
|
|
|
latest.finality_branch.reset()
|
|
|
|
latest.sync_aggregate = isomorphicCast[SyncAggregate](sync_aggregate)
|
|
|
|
latest.signature_slot = signature_slot
|
|
|
|
newOptimistic = true
|
|
|
|
|
|
|
|
# Track best light client data for current period
|
|
|
|
let
|
|
|
|
attested_period = attested_slot.sync_committee_period
|
|
|
|
signature_period = signature_slot.sync_committee_period
|
|
|
|
if attested_period == signature_period:
|
|
|
|
template next_sync_committee(): auto = state.data.next_sync_committee
|
|
|
|
|
2022-06-14 15:31:10 +00:00
|
|
|
let isCommitteeFinalized = dag.isNextSyncCommitteeFinalized(attested_period)
|
2022-05-23 12:02:54 +00:00
|
|
|
var best =
|
2022-06-14 15:31:10 +00:00
|
|
|
if isCommitteeFinalized:
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.best.getOrDefault(attested_period)
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
let key = (attested_period, state.syncCommitteeRoot)
|
|
|
|
dag.lightClientCache.pendingBest.getOrDefault(key)
|
|
|
|
|
|
|
|
load_attested_data(attested_bid)
|
|
|
|
let
|
|
|
|
finalized_slot = attested_data.finalized_slot
|
|
|
|
meta = LightClientUpdateMetadata(
|
|
|
|
attested_slot: attested_slot,
|
|
|
|
finalized_slot: finalized_slot,
|
|
|
|
signature_slot: signature_slot,
|
|
|
|
has_sync_committee: true,
|
|
|
|
has_finality: load_finalized_bid(finalized_slot),
|
|
|
|
num_active_participants: num_active_participants)
|
|
|
|
is_better = is_better_data(meta, best.toMeta)
|
|
|
|
if is_better and best.attested_header.assign_attested_header(attested_bid):
|
|
|
|
best.next_sync_committee = next_sync_committee
|
|
|
|
best.next_sync_committee_branch = attested_data.next_sync_committee_branch
|
|
|
|
if finalized_slot == best.finalized_header.slot:
|
|
|
|
best.finality_branch = attested_data.finality_branch
|
|
|
|
elif finalized_slot == GENESIS_SLOT:
|
|
|
|
best.finalized_header.reset()
|
|
|
|
best.finality_branch = attested_data.finality_branch
|
|
|
|
elif meta.has_finality and
|
|
|
|
best.finalized_header.assign_finalized_header(finalized_bid):
|
|
|
|
best.finality_branch = attested_data.finality_branch
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
best.finalized_header.reset()
|
|
|
|
best.finality_branch.reset()
|
|
|
|
best.sync_aggregate = isomorphicCast[SyncAggregate](sync_aggregate)
|
|
|
|
best.signature_slot = signature_slot
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-06-14 15:31:10 +00:00
|
|
|
if isCommitteeFinalized:
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.best[attested_period] = best
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "Best LC update for period improved",
|
2022-05-23 12:02:54 +00:00
|
|
|
period = attested_period, update = best
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
let key = (attested_period, state.syncCommitteeRoot)
|
|
|
|
dag.lightClientCache.pendingBest[key] = best
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "Best LC update for period improved",
|
2022-05-23 12:02:54 +00:00
|
|
|
period = key, update = best
|
|
|
|
|
|
|
|
if newFinality and dag.onLightClientFinalityUpdate != nil:
|
|
|
|
dag.onLightClientFinalityUpdate(latest)
|
|
|
|
if newOptimistic and dag.onLightClientOptimisticUpdate != nil:
|
|
|
|
dag.onLightClientOptimisticUpdate(latest.toOptimistic)
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
proc processNewBlockForLightClient*(
|
|
|
|
dag: ChainDAGRef,
|
2022-03-16 07:20:40 +00:00
|
|
|
state: ForkedHashedBeaconState,
|
2022-03-11 20:28:10 +00:00
|
|
|
signedBlock: ForkyTrustedSignedBeaconBlock,
|
2022-03-20 10:58:59 +00:00
|
|
|
parentBid: BlockId) =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Update light client data with information from a new block.
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.None:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
if signedBlock.message.slot < dag.computeEarliestLightClientSlot:
|
|
|
|
return
|
|
|
|
|
|
|
|
when signedBlock is bellatrix.TrustedSignedBeaconBlock:
|
2022-06-14 20:13:00 +00:00
|
|
|
dag.cacheLightClientData(state.bellatrixData, signedBlock.toBlockId())
|
2022-03-20 10:58:59 +00:00
|
|
|
dag.createLightClientUpdates(state.bellatrixData, signedBlock, parentBid)
|
2022-03-11 20:28:10 +00:00
|
|
|
elif signedBlock is altair.TrustedSignedBeaconBlock:
|
2022-06-14 20:13:00 +00:00
|
|
|
dag.cacheLightClientData(state.altairData, signedBlock.toBlockId())
|
2022-03-20 10:58:59 +00:00
|
|
|
dag.createLightClientUpdates(state.altairData, signedBlock, parentBid)
|
2022-03-11 20:28:10 +00:00
|
|
|
elif signedBlock is phase0.TrustedSignedBeaconBlock:
|
2022-05-23 12:02:54 +00:00
|
|
|
raiseAssert "Unreachable" # `earliestSlot` cannot be before Altair
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
|
|
|
{.error: "Unreachable".}
|
|
|
|
|
|
|
|
proc processHeadChangeForLightClient*(dag: ChainDAGRef) =
|
|
|
|
## Update light client data to account for a new head block.
|
|
|
|
## Note that `dag.finalizedHead` is not yet updated when this is called.
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.None:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
2022-06-14 15:31:10 +00:00
|
|
|
let earliestSlot = dag.computeEarliestLightClientSlot
|
|
|
|
if dag.head.slot < earliestSlot:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Update `best` from `pendingBest` to ensure light client data
|
|
|
|
# only refers to sync committees as selected by fork choice
|
2022-03-11 20:28:10 +00:00
|
|
|
let headPeriod = dag.head.slot.sync_committee_period
|
2022-06-14 15:31:10 +00:00
|
|
|
if not dag.isNextSyncCommitteeFinalized(headPeriod):
|
|
|
|
let
|
|
|
|
earliestPeriod = earliestSlot.sync_committee_period
|
|
|
|
lowPeriod = max(dag.firstNonFinalizedPeriod, earliestPeriod)
|
|
|
|
if headPeriod > lowPeriod:
|
2022-03-11 20:28:10 +00:00
|
|
|
var tmpState = assignClone(dag.headState)
|
2022-06-14 15:31:10 +00:00
|
|
|
for period in lowPeriod ..< headPeriod:
|
2022-03-20 10:58:59 +00:00
|
|
|
let
|
|
|
|
syncCommitteeRoot =
|
|
|
|
dag.syncCommitteeRootForPeriod(tmpState[], period).valueOr:
|
|
|
|
continue
|
|
|
|
key = (period, syncCommitteeRoot)
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.best[period] =
|
|
|
|
dag.lightClientCache.pendingBest.getOrDefault(key)
|
2022-06-14 15:31:10 +00:00
|
|
|
withState(dag.headState): # Common case separate to avoid `tmpState` copy
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
let key = (headPeriod, state.syncCommitteeRoot)
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.best[headPeriod] =
|
|
|
|
dag.lightClientCache.pendingBest.getOrDefault(key)
|
2022-03-11 20:28:10 +00:00
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
proc processFinalizationForLightClient*(
|
|
|
|
dag: ChainDAGRef, oldFinalizedHead: BlockSlot) =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Prune cached data that is no longer useful for creating future
|
|
|
|
## `LightClientUpdate` and `LightClientBootstrap` instances.
|
|
|
|
## This needs to be called whenever `finalized_checkpoint` changes.
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.None:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
let
|
2022-03-20 10:58:59 +00:00
|
|
|
earliestSlot = dag.computeEarliestLightClientSlot
|
2022-03-11 20:28:10 +00:00
|
|
|
finalizedSlot = dag.finalizedHead.slot
|
2022-03-20 10:58:59 +00:00
|
|
|
if finalizedSlot < earliestSlot:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Cache `LightClientBootstrap` for newly finalized epoch boundary blocks
|
|
|
|
let lowSlot = max(oldFinalizedHead.slot + 1, earliestSlot)
|
|
|
|
var boundarySlot = finalizedSlot
|
|
|
|
while boundarySlot >= lowSlot:
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
2022-05-23 12:02:54 +00:00
|
|
|
bsi = dag.getExistingBlockIdAtSlot(boundarySlot).valueOr:
|
2022-03-11 20:28:10 +00:00
|
|
|
break
|
2022-05-23 12:02:54 +00:00
|
|
|
bid = bsi.bid
|
|
|
|
if bid.slot >= lowSlot:
|
|
|
|
dag.lightClientCache.bootstrap[bid.slot] =
|
|
|
|
CachedLightClientBootstrap(
|
|
|
|
current_sync_committee_branch:
|
|
|
|
dag.getLightClientData(bid).current_sync_committee_branch)
|
|
|
|
boundarySlot = bid.slot.nextEpochBoundarySlot
|
|
|
|
if boundarySlot < SLOTS_PER_EPOCH:
|
|
|
|
break
|
|
|
|
boundarySlot -= SLOTS_PER_EPOCH
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Prune light client data that is no longer referrable by future updates
|
2022-03-11 20:28:10 +00:00
|
|
|
var bidsToDelete: seq[BlockId]
|
|
|
|
for bid, data in dag.lightClientCache.data:
|
2022-06-14 15:31:10 +00:00
|
|
|
if bid.slot >= dag.finalizedHead.blck.slot:
|
2022-05-23 12:02:54 +00:00
|
|
|
continue
|
2022-03-11 20:28:10 +00:00
|
|
|
bidsToDelete.add bid
|
|
|
|
for bid in bidsToDelete:
|
|
|
|
dag.lightClientCache.data.del bid
|
|
|
|
|
|
|
|
# Prune bootstrap data that is no longer relevant
|
|
|
|
var slotsToDelete: seq[Slot]
|
|
|
|
for slot in dag.lightClientCache.bootstrap.keys:
|
|
|
|
if slot < earliestSlot:
|
|
|
|
slotsToDelete.add slot
|
|
|
|
for slot in slotsToDelete:
|
|
|
|
dag.lightClientCache.bootstrap.del slot
|
|
|
|
|
|
|
|
# Prune best `LightClientUpdate` that are no longer relevant
|
|
|
|
let earliestPeriod = earliestSlot.sync_committee_period
|
|
|
|
var periodsToDelete: seq[SyncCommitteePeriod]
|
2022-05-23 12:02:54 +00:00
|
|
|
for period in dag.lightClientCache.best.keys:
|
2022-03-11 20:28:10 +00:00
|
|
|
if period < earliestPeriod:
|
|
|
|
periodsToDelete.add period
|
|
|
|
for period in periodsToDelete:
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.best.del period
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
# Prune best `LightClientUpdate` referring to non-finalized sync committees
|
|
|
|
# that are no longer relevant, i.e., orphaned or too old
|
2022-06-14 15:31:10 +00:00
|
|
|
let firstNonFinalizedPeriod = dag.firstNonFinalizedPeriod
|
2022-03-11 20:28:10 +00:00
|
|
|
var keysToDelete: seq[(SyncCommitteePeriod, Eth2Digest)]
|
2022-05-23 12:02:54 +00:00
|
|
|
for (period, committeeRoot) in dag.lightClientCache.pendingBest.keys:
|
2022-06-14 15:31:10 +00:00
|
|
|
if period < firstNonFinalizedPeriod:
|
2022-03-11 20:28:10 +00:00
|
|
|
keysToDelete.add (period, committeeRoot)
|
|
|
|
for key in keysToDelete:
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.lightClientCache.pendingBest.del key
|
|
|
|
|
|
|
|
proc initLightClientBootstrapForPeriod(
|
|
|
|
dag: ChainDAGRef,
|
|
|
|
period: SyncCommitteePeriod) =
|
|
|
|
## Compute and cache `LightClientBootstrap` data for all finalized
|
|
|
|
## epoch boundary blocks within a given sync committee period.
|
2022-06-14 15:31:10 +00:00
|
|
|
if not dag.isNextSyncCommitteeFinalized(period):
|
2022-05-23 12:02:54 +00:00
|
|
|
return
|
|
|
|
let
|
|
|
|
earliestSlot = dag.computeEarliestLightClientSlot
|
2022-06-14 15:31:10 +00:00
|
|
|
periodStartSlot = period.start_slot
|
2022-05-23 12:02:54 +00:00
|
|
|
periodEndSlot = periodStartSlot + SLOTS_PER_SYNC_COMMITTEE_PERIOD - 1
|
|
|
|
if periodEndSlot < earliestSlot:
|
|
|
|
return
|
|
|
|
|
|
|
|
let startTick = Moment.now()
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "Caching LC bootstrap data for period", period
|
2022-05-23 12:02:54 +00:00
|
|
|
defer:
|
|
|
|
let endTick = Moment.now()
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "LC bootstrap data for period cached", period,
|
2022-05-23 12:02:54 +00:00
|
|
|
cacheDur = endTick - startTick
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
let
|
|
|
|
lowSlot = max(periodStartSlot, earliestSlot)
|
|
|
|
highSlot = min(periodEndSlot, dag.finalizedHead.blck.slot)
|
|
|
|
lowBoundarySlot = lowSlot.nextEpochBoundarySlot
|
|
|
|
highBoundarySlot = highSlot.nextEpochBoundarySlot
|
|
|
|
var
|
|
|
|
tmpState = assignClone(dag.headState)
|
|
|
|
tmpCache: StateCache
|
|
|
|
nextBoundarySlot = lowBoundarySlot
|
|
|
|
while nextBoundarySlot <= highBoundarySlot:
|
|
|
|
defer: nextBoundarySlot += SLOTS_PER_EPOCH
|
|
|
|
let
|
|
|
|
bsi = dag.getExistingBlockIdAtSlot(nextBoundarySlot).valueOr:
|
|
|
|
continue
|
|
|
|
bid = bsi.bid
|
|
|
|
boundarySlot = bid.slot.nextEpochBoundarySlot
|
|
|
|
if boundarySlot == nextBoundarySlot and bid.slot >= lowSlot and
|
|
|
|
not dag.lightClientCache.bootstrap.hasKey(bid.slot):
|
|
|
|
var cachedBootstrap {.noinit.}: CachedLightClientBootstrap
|
|
|
|
if not dag.updateExistingState(
|
|
|
|
tmpState[], bid.atSlot, save = false, tmpCache):
|
|
|
|
continue
|
|
|
|
withStateVars(tmpState[]):
|
|
|
|
withState(state):
|
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
state.data.build_proof(
|
|
|
|
altair.CURRENT_SYNC_COMMITTEE_INDEX,
|
|
|
|
cachedBootstrap.current_sync_committee_branch)
|
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
dag.lightClientCache.bootstrap[bid.slot] = cachedBootstrap
|
|
|
|
|
|
|
|
proc initLightClientUpdateForPeriod(
|
2022-03-11 20:28:10 +00:00
|
|
|
dag: ChainDAGRef, period: SyncCommitteePeriod) =
|
2022-05-23 12:02:54 +00:00
|
|
|
## Compute and cache the best `LightClientUpdate` within a given
|
|
|
|
## sync committee period up through the finalized head block.
|
|
|
|
## Non-finalized blocks are processed incrementally.
|
2022-06-14 15:31:10 +00:00
|
|
|
if not dag.isNextSyncCommitteeFinalized(period):
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
|
|
|
let
|
|
|
|
earliestSlot = dag.computeEarliestLightClientSlot
|
2022-06-14 15:31:10 +00:00
|
|
|
periodStartSlot = period.start_slot
|
2022-03-11 20:28:10 +00:00
|
|
|
periodEndSlot = periodStartSlot + SLOTS_PER_SYNC_COMMITTEE_PERIOD - 1
|
|
|
|
if periodEndSlot < earliestSlot:
|
|
|
|
return
|
2022-05-23 12:02:54 +00:00
|
|
|
if dag.lightClientCache.best.hasKey(period):
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
2022-06-14 15:31:10 +00:00
|
|
|
|
2022-03-11 20:28:10 +00:00
|
|
|
let startTick = Moment.now()
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "Computing best LC update for period", period
|
2022-05-23 12:02:54 +00:00
|
|
|
proc logBest(endTick = Moment.now()) =
|
2022-03-20 10:58:59 +00:00
|
|
|
# Using a helper function reduces code size as the `defer` beneath is
|
|
|
|
# replicated on every `return`, and the log statement allocates another
|
|
|
|
# copy of the arguments on the stack for each instantiation (~1 MB stack!)
|
2022-06-14 15:31:10 +00:00
|
|
|
debug "Best LC update for period computed",
|
2022-05-23 12:02:54 +00:00
|
|
|
period, update = dag.lightClientCache.best.getOrDefault(period),
|
2022-03-11 20:28:10 +00:00
|
|
|
computeDur = endTick - startTick
|
2022-05-23 12:02:54 +00:00
|
|
|
defer: logBest()
|
2022-03-11 20:28:10 +00:00
|
|
|
|
Prune `BlockRef` on finalization (#3513)
Up til now, the block dag has been using `BlockRef`, a structure adapted
for a full DAG, to represent all of chain history. This is a correct and
simple design, but does not exploit the linearity of the chain once
parts of it finalize.
By pruning the in-memory `BlockRef` structure at finalization, we save,
at the time of writing, a cool ~250mb (or 25%:ish) chunk of memory
landing us at a steady state of ~750mb normal memory usage for a
validating node.
Above all though, we prevent memory usage from growing proportionally
with the length of the chain, something that would not be sustainable
over time - instead, the steady state memory usage is roughly
determined by the validator set size which grows much more slowly. With
these changes, the core should remain sustainable memory-wise post-merge
all the way to withdrawals (when the validator set is expected to grow).
In-memory indices are still used for the "hot" unfinalized portion of
the chain - this ensure that consensus performance remains unchanged.
What changes is that for historical access, we use a db-based linear
slot index which is cache-and-disk-friendly, keeping the cost for
accessing historical data at a similar level as before, achieving the
savings at no percievable cost to functionality or performance.
A nice collateral benefit is the almost-instant startup since we no
longer load any large indicies at dag init.
The cost of this functionality instead can be found in the complexity of
having to deal with two ways of traversing the chain - by `BlockRef` and
by slot.
* use `BlockId` instead of `BlockRef` where finalized / historical data
may be required
* simplify clearance pre-advancement
* remove dag.finalizedBlocks (~50:ish mb)
* remove `getBlockAtSlot` - use `getBlockIdAtSlot` instead
* `parent` and `atSlot` for `BlockId` now require a `ChainDAGRef`
instance, unlike `BlockRef` traversal
* prune `BlockRef` parents on finality (~200:ish mb)
* speed up ChainDAG init by not loading finalized history index
* mess up light client server error handling - this need revisiting :)
2022-03-17 17:42:56 +00:00
|
|
|
proc maxParticipantsBlock(
|
2022-05-23 12:02:54 +00:00
|
|
|
dag: ChainDAGRef, highBid: BlockId, lowSlot: Slot): Opt[BlockId] =
|
2022-03-11 20:28:10 +00:00
|
|
|
## Determine the earliest block with most sync committee signatures among
|
2022-03-20 10:58:59 +00:00
|
|
|
## ancestors of `highBid` with at least `lowSlot` as parent block slot.
|
2022-05-23 12:02:54 +00:00
|
|
|
## Return `err` if no block with `MIN_SYNC_COMMITTEE_PARTICIPANTS` exists.
|
2022-03-11 20:28:10 +00:00
|
|
|
var
|
2022-05-23 12:02:54 +00:00
|
|
|
maxParticipants = MIN_SYNC_COMMITTEE_PARTICIPANTS
|
|
|
|
maxBid: Opt[BlockId]
|
2022-03-20 10:58:59 +00:00
|
|
|
bid = highBid
|
Prune `BlockRef` on finalization (#3513)
Up til now, the block dag has been using `BlockRef`, a structure adapted
for a full DAG, to represent all of chain history. This is a correct and
simple design, but does not exploit the linearity of the chain once
parts of it finalize.
By pruning the in-memory `BlockRef` structure at finalization, we save,
at the time of writing, a cool ~250mb (or 25%:ish) chunk of memory
landing us at a steady state of ~750mb normal memory usage for a
validating node.
Above all though, we prevent memory usage from growing proportionally
with the length of the chain, something that would not be sustainable
over time - instead, the steady state memory usage is roughly
determined by the validator set size which grows much more slowly. With
these changes, the core should remain sustainable memory-wise post-merge
all the way to withdrawals (when the validator set is expected to grow).
In-memory indices are still used for the "hot" unfinalized portion of
the chain - this ensure that consensus performance remains unchanged.
What changes is that for historical access, we use a db-based linear
slot index which is cache-and-disk-friendly, keeping the cost for
accessing historical data at a similar level as before, achieving the
savings at no percievable cost to functionality or performance.
A nice collateral benefit is the almost-instant startup since we no
longer load any large indicies at dag init.
The cost of this functionality instead can be found in the complexity of
having to deal with two ways of traversing the chain - by `BlockRef` and
by slot.
* use `BlockId` instead of `BlockRef` where finalized / historical data
may be required
* simplify clearance pre-advancement
* remove dag.finalizedBlocks (~50:ish mb)
* remove `getBlockAtSlot` - use `getBlockIdAtSlot` instead
* `parent` and `atSlot` for `BlockId` now require a `ChainDAGRef`
instance, unlike `BlockRef` traversal
* prune `BlockRef` parents on finality (~200:ish mb)
* speed up ChainDAG init by not loading finalized history index
* mess up light client server error handling - this need revisiting :)
2022-03-17 17:42:56 +00:00
|
|
|
while true:
|
2022-03-20 10:58:59 +00:00
|
|
|
let parentBid = dag.parent(bid).valueOr:
|
Prune `BlockRef` on finalization (#3513)
Up til now, the block dag has been using `BlockRef`, a structure adapted
for a full DAG, to represent all of chain history. This is a correct and
simple design, but does not exploit the linearity of the chain once
parts of it finalize.
By pruning the in-memory `BlockRef` structure at finalization, we save,
at the time of writing, a cool ~250mb (or 25%:ish) chunk of memory
landing us at a steady state of ~750mb normal memory usage for a
validating node.
Above all though, we prevent memory usage from growing proportionally
with the length of the chain, something that would not be sustainable
over time - instead, the steady state memory usage is roughly
determined by the validator set size which grows much more slowly. With
these changes, the core should remain sustainable memory-wise post-merge
all the way to withdrawals (when the validator set is expected to grow).
In-memory indices are still used for the "hot" unfinalized portion of
the chain - this ensure that consensus performance remains unchanged.
What changes is that for historical access, we use a db-based linear
slot index which is cache-and-disk-friendly, keeping the cost for
accessing historical data at a similar level as before, achieving the
savings at no percievable cost to functionality or performance.
A nice collateral benefit is the almost-instant startup since we no
longer load any large indicies at dag init.
The cost of this functionality instead can be found in the complexity of
having to deal with two ways of traversing the chain - by `BlockRef` and
by slot.
* use `BlockId` instead of `BlockRef` where finalized / historical data
may be required
* simplify clearance pre-advancement
* remove dag.finalizedBlocks (~50:ish mb)
* remove `getBlockAtSlot` - use `getBlockIdAtSlot` instead
* `parent` and `atSlot` for `BlockId` now require a `ChainDAGRef`
instance, unlike `BlockRef` traversal
* prune `BlockRef` parents on finality (~200:ish mb)
* speed up ChainDAG init by not loading finalized history index
* mess up light client server error handling - this need revisiting :)
2022-03-17 17:42:56 +00:00
|
|
|
break
|
2022-03-20 10:58:59 +00:00
|
|
|
if parentBid.slot < lowSlot:
|
Prune `BlockRef` on finalization (#3513)
Up til now, the block dag has been using `BlockRef`, a structure adapted
for a full DAG, to represent all of chain history. This is a correct and
simple design, but does not exploit the linearity of the chain once
parts of it finalize.
By pruning the in-memory `BlockRef` structure at finalization, we save,
at the time of writing, a cool ~250mb (or 25%:ish) chunk of memory
landing us at a steady state of ~750mb normal memory usage for a
validating node.
Above all though, we prevent memory usage from growing proportionally
with the length of the chain, something that would not be sustainable
over time - instead, the steady state memory usage is roughly
determined by the validator set size which grows much more slowly. With
these changes, the core should remain sustainable memory-wise post-merge
all the way to withdrawals (when the validator set is expected to grow).
In-memory indices are still used for the "hot" unfinalized portion of
the chain - this ensure that consensus performance remains unchanged.
What changes is that for historical access, we use a db-based linear
slot index which is cache-and-disk-friendly, keeping the cost for
accessing historical data at a similar level as before, achieving the
savings at no percievable cost to functionality or performance.
A nice collateral benefit is the almost-instant startup since we no
longer load any large indicies at dag init.
The cost of this functionality instead can be found in the complexity of
having to deal with two ways of traversing the chain - by `BlockRef` and
by slot.
* use `BlockId` instead of `BlockRef` where finalized / historical data
may be required
* simplify clearance pre-advancement
* remove dag.finalizedBlocks (~50:ish mb)
* remove `getBlockAtSlot` - use `getBlockIdAtSlot` instead
* `parent` and `atSlot` for `BlockId` now require a `ChainDAGRef`
instance, unlike `BlockRef` traversal
* prune `BlockRef` parents on finality (~200:ish mb)
* speed up ChainDAG init by not loading finalized history index
* mess up light client server error handling - this need revisiting :)
2022-03-17 17:42:56 +00:00
|
|
|
break
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
2022-03-20 10:58:59 +00:00
|
|
|
bdata = dag.getExistingForkedBlock(bid).valueOr:
|
|
|
|
break
|
2022-03-11 20:28:10 +00:00
|
|
|
numParticipants =
|
|
|
|
withBlck(bdata):
|
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
countOnes(blck.message.body.sync_aggregate.sync_committee_bits)
|
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
if numParticipants >= maxParticipants:
|
|
|
|
maxParticipants = numParticipants
|
2022-05-23 12:02:54 +00:00
|
|
|
maxBid = ok bid
|
2022-03-20 10:58:59 +00:00
|
|
|
bid = parentBid
|
|
|
|
maxBid
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
# Determine the block in the period with highest sync committee participation
|
|
|
|
let
|
|
|
|
lowSlot = max(periodStartSlot, earliestSlot)
|
|
|
|
highSlot = min(periodEndSlot, dag.finalizedHead.blck.slot)
|
2022-03-20 10:58:59 +00:00
|
|
|
highBsi = dag.getExistingBlockIdAtSlot(highSlot).valueOr:
|
|
|
|
return
|
|
|
|
highBid = highBsi.bid
|
2022-05-23 12:02:54 +00:00
|
|
|
maxParticipantsBid = dag.maxParticipantsBlock(highBid, lowSlot).valueOr:
|
2022-06-14 15:31:10 +00:00
|
|
|
dag.lightClientCache.best[period] = default(altair.LightClientUpdate)
|
2022-05-23 12:02:54 +00:00
|
|
|
return
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
# The block with highest participation may refer to a `finalized_checkpoint`
|
|
|
|
# in a different sync committee period. If that is the case, search for a
|
|
|
|
# later block with a `finalized_checkpoint` within the given sync committee
|
|
|
|
# period, despite it having a lower sync committee participation
|
|
|
|
var
|
|
|
|
tmpState = assignClone(dag.headState)
|
2022-05-23 12:02:54 +00:00
|
|
|
signatureBid = BlockId(slot: FAR_FUTURE_SLOT)
|
|
|
|
finalizedBid = BlockId(slot: FAR_FUTURE_SLOT)
|
|
|
|
while true:
|
|
|
|
if signatureBid.slot == FAR_FUTURE_SLOT:
|
|
|
|
signatureBid = maxParticipantsBid
|
|
|
|
else:
|
|
|
|
let nextLowSlot = signatureBid.slot + 1
|
|
|
|
signatureBid = dag.maxParticipantsBlock(highBid, nextLowSlot).valueOr:
|
|
|
|
signatureBid = maxParticipantsBid
|
|
|
|
break
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
2022-05-23 12:02:54 +00:00
|
|
|
attestedBid = dag.existingParent(signatureBid).valueOr:
|
2022-03-20 10:58:59 +00:00
|
|
|
continue
|
2022-03-11 20:28:10 +00:00
|
|
|
finalizedEpoch = block:
|
2022-03-20 10:58:59 +00:00
|
|
|
dag.withUpdatedExistingState(tmpState[], attestedBid.atSlot) do:
|
2022-03-16 07:20:40 +00:00
|
|
|
withState(state):
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
state.data.finalized_checkpoint.epoch
|
|
|
|
else: raiseAssert "Unreachable"
|
2022-03-20 10:58:59 +00:00
|
|
|
do: continue
|
|
|
|
finalizedSlot = finalizedEpoch.start_slot
|
2022-05-23 12:02:54 +00:00
|
|
|
finalizedBsi = dag.getBlockIdAtSlot(finalizedSlot).valueOr:
|
2022-03-20 10:58:59 +00:00
|
|
|
continue
|
2022-05-23 12:02:54 +00:00
|
|
|
if finalizedBid.slot >= lowSlot:
|
2022-03-20 10:58:59 +00:00
|
|
|
finalizedBid = finalizedBsi.bid
|
2022-05-23 12:02:54 +00:00
|
|
|
break
|
|
|
|
if signatureBid == maxParticipantsBid:
|
|
|
|
finalizedBid = finalizedBsi.bid # For fallback `break` at start of loop
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Save best light client data for given period
|
2022-06-14 15:31:10 +00:00
|
|
|
var update {.noinit.}: altair.LightClientUpdate
|
2022-05-23 12:02:54 +00:00
|
|
|
let attestedBid = dag.existingParent(signatureBid).valueOr:
|
|
|
|
return
|
|
|
|
dag.withUpdatedExistingState(tmpState[], attestedBid.atSlot) do:
|
|
|
|
let bdata = dag.getExistingForkedBlock(bid).valueOr:
|
2022-03-20 10:58:59 +00:00
|
|
|
return
|
2022-05-23 12:02:54 +00:00
|
|
|
withStateAndBlck(state, bdata):
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
2022-06-14 15:31:10 +00:00
|
|
|
update.attested_header = blck.toBeaconBlockHeader()
|
2022-05-23 12:02:54 +00:00
|
|
|
update.next_sync_committee = state.data.next_sync_committee
|
|
|
|
state.data.build_proof(
|
|
|
|
altair.NEXT_SYNC_COMMITTEE_INDEX,
|
|
|
|
update.next_sync_committee_branch)
|
|
|
|
if finalizedBid.slot == FAR_FUTURE_SLOT:
|
|
|
|
update.finality_branch.reset()
|
|
|
|
else:
|
2022-03-11 20:28:10 +00:00
|
|
|
state.data.build_proof(
|
2022-05-23 12:02:54 +00:00
|
|
|
altair.FINALIZED_ROOT_INDEX,
|
|
|
|
update.finality_branch)
|
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
do: return
|
|
|
|
if finalizedBid.slot == FAR_FUTURE_SLOT or finalizedBid.slot == GENESIS_SLOT:
|
|
|
|
update.finalized_header.reset()
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
let bdata = dag.getExistingForkedBlock(finalizedBid).valueOr:
|
2022-03-20 10:58:59 +00:00
|
|
|
return
|
2022-03-11 20:28:10 +00:00
|
|
|
withBlck(bdata):
|
2022-06-14 15:31:10 +00:00
|
|
|
update.finalized_header = blck.toBeaconBlockHeader()
|
2022-05-23 12:02:54 +00:00
|
|
|
let bdata = dag.getExistingForkedBlock(signatureBid).valueOr:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
2022-05-23 12:02:54 +00:00
|
|
|
withBlck(bdata):
|
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
update.sync_aggregate =
|
|
|
|
isomorphicCast[SyncAggregate](blck.message.body.sync_aggregate)
|
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
update.signature_slot = signatureBid.slot
|
|
|
|
dag.lightClientCache.best[period] = update
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
proc initLightClientCache*(dag: ChainDAGRef) =
|
|
|
|
## Initialize cached light client data
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.None:
|
2022-03-11 20:28:10 +00:00
|
|
|
return
|
2022-03-19 08:58:55 +00:00
|
|
|
dag.lightClientCache.importTailSlot = dag.tail.slot
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.OnlyNew:
|
2022-03-20 10:58:59 +00:00
|
|
|
dag.lightClientCache.importTailSlot = dag.head.slot
|
|
|
|
var earliestSlot = dag.computeEarliestLightClientSlot
|
2022-03-11 20:28:10 +00:00
|
|
|
if dag.head.slot < earliestSlot:
|
|
|
|
return
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Import light client data for finalized period through finalized head
|
2022-03-11 20:28:10 +00:00
|
|
|
let
|
|
|
|
finalizedSlot = dag.finalizedHead.slot
|
|
|
|
finalizedPeriod = finalizedSlot.sync_committee_period
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.initLightClientBootstrapForPeriod(finalizedPeriod)
|
|
|
|
dag.initLightClientUpdateForPeriod(finalizedPeriod)
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
let lightClientStartTick = Moment.now()
|
|
|
|
debug "Initializing cached light client data"
|
|
|
|
|
2022-03-20 10:58:59 +00:00
|
|
|
template handleUnexpectedError(buggedBid: BlockId) =
|
|
|
|
# Light client data is expected to be available from `earliestSlot` onward.
|
|
|
|
# If there is an error, adjust `importTailSlot` to avoid failed lookups of
|
|
|
|
# cached light client data. For new blocks / states, the caches can always
|
|
|
|
# be updated incrementally, because those blocks / states are passed in
|
|
|
|
# directly. It is only historical blocks (or sync committees) that depend
|
|
|
|
# on a potentially corrupted database.
|
|
|
|
doAssert buggedBid.slot > dag.lightClientCache.importTailSlot
|
|
|
|
dag.lightClientCache.importTailSlot = buggedBid.slot + 1
|
|
|
|
earliestSlot = dag.computeEarliestLightClientSlot
|
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Build list of block to process.
|
2022-03-11 20:28:10 +00:00
|
|
|
# As it is slow to load states in descending order,
|
2022-05-23 12:02:54 +00:00
|
|
|
# build a reverse todo list to then process them in ascending order
|
2022-03-20 10:58:59 +00:00
|
|
|
let lowSlot = max(finalizedSlot, earliestSlot)
|
2022-03-11 20:28:10 +00:00
|
|
|
var
|
2022-05-23 12:02:54 +00:00
|
|
|
blocks = newSeqOfCap[BlockId](dag.head.slot - lowSlot + 1)
|
2022-03-20 10:58:59 +00:00
|
|
|
bid = dag.head.bid
|
|
|
|
while bid.slot > lowSlot:
|
2022-05-23 12:02:54 +00:00
|
|
|
blocks.add bid
|
2022-03-20 10:58:59 +00:00
|
|
|
bid = dag.existingParent(bid).valueOr:
|
|
|
|
handleUnexpectedError(bid)
|
|
|
|
break
|
2022-05-23 12:02:54 +00:00
|
|
|
if bid.slot == lowSlot:
|
|
|
|
blocks.add bid
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
# Process blocks (reuses `dag.headState`, but restores it to the current head)
|
|
|
|
var
|
|
|
|
tmpState = assignClone(dag.headState)
|
|
|
|
tmpCache, cache: StateCache
|
|
|
|
oldCheckpoint: Checkpoint
|
|
|
|
cpIndex = 0
|
2022-05-23 12:02:54 +00:00
|
|
|
for i in countdown(blocks.high, blocks.low):
|
|
|
|
bid = blocks[i]
|
2022-03-20 10:58:59 +00:00
|
|
|
if not dag.updateExistingState(
|
|
|
|
dag.headState, bid.atSlot, save = false, cache):
|
|
|
|
handleUnexpectedError(bid)
|
|
|
|
continue
|
2022-03-11 20:28:10 +00:00
|
|
|
withStateVars(dag.headState):
|
2022-03-20 10:58:59 +00:00
|
|
|
let bdata = dag.getExistingForkedBlock(bid).valueOr:
|
|
|
|
handleUnexpectedError(bid)
|
|
|
|
continue
|
2022-03-16 07:20:40 +00:00
|
|
|
withStateAndBlck(state, bdata):
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
2022-05-23 12:02:54 +00:00
|
|
|
# Cache light client data (non-finalized blocks may refer to this)
|
2022-06-14 20:13:00 +00:00
|
|
|
dag.cacheLightClientData(state, blck.toBlockId())
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-05-23 12:02:54 +00:00
|
|
|
# Create `LightClientUpdate` instances
|
|
|
|
if bid.slot != lowSlot:
|
|
|
|
dag.createLightClientUpdates(state, blck, parentBid = blocks[i + 1])
|
2022-03-11 20:28:10 +00:00
|
|
|
else: raiseAssert "Unreachable"
|
|
|
|
|
|
|
|
let lightClientEndTick = Moment.now()
|
|
|
|
debug "Initialized cached light client data",
|
|
|
|
initDur = lightClientEndTick - lightClientStartTick
|
|
|
|
|
|
|
|
# Import historic data
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.Full:
|
2022-05-23 12:02:54 +00:00
|
|
|
let earliestPeriod = earliestSlot.sync_committee_period
|
2022-03-11 20:28:10 +00:00
|
|
|
for period in earliestPeriod ..< finalizedPeriod:
|
|
|
|
dag.initLightClientBootstrapForPeriod(period)
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.initLightClientUpdateForPeriod(period)
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
proc getLightClientBootstrap*(
|
|
|
|
dag: ChainDAGRef,
|
2022-03-20 10:58:59 +00:00
|
|
|
blockRoot: Eth2Digest): Opt[altair.LightClientBootstrap] =
|
2022-06-14 09:03:39 +00:00
|
|
|
if not dag.lightClientDataServe:
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
let bdata = dag.getForkedBlock(blockRoot).valueOr:
|
2022-05-23 12:02:54 +00:00
|
|
|
debug "LC bootstrap unavailable: Block not found", blockRoot
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
|
|
|
|
withBlck(bdata):
|
2022-03-20 10:58:59 +00:00
|
|
|
let slot = blck.message.slot
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
let earliestSlot = dag.computeEarliestLightClientSlot
|
|
|
|
if slot < earliestSlot:
|
2022-05-23 12:02:54 +00:00
|
|
|
debug "LC bootstrap unavailable: Block too old", slot
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
if slot > dag.finalizedHead.blck.slot:
|
2022-05-23 12:02:54 +00:00
|
|
|
debug "LC bootstrap unavailable: Not finalized", blockRoot
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-05-23 12:02:54 +00:00
|
|
|
var cachedBootstrap = dag.lightClientCache.bootstrap.getOrDefault(slot)
|
2022-03-11 20:28:10 +00:00
|
|
|
if cachedBootstrap.current_sync_committee_branch.isZeroMemory:
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.OnDemand:
|
2022-03-20 10:58:59 +00:00
|
|
|
let bsi = ? dag.getExistingBlockIdAtSlot(slot)
|
2022-03-11 20:28:10 +00:00
|
|
|
var tmpState = assignClone(dag.headState)
|
2022-03-20 10:58:59 +00:00
|
|
|
dag.withUpdatedExistingState(tmpState[], bsi) do:
|
2022-03-16 07:20:40 +00:00
|
|
|
withState(state):
|
2022-03-11 20:28:10 +00:00
|
|
|
when stateFork >= BeaconStateFork.Altair:
|
|
|
|
state.data.build_proof(
|
|
|
|
altair.CURRENT_SYNC_COMMITTEE_INDEX,
|
|
|
|
cachedBootstrap.current_sync_committee_branch)
|
|
|
|
else: raiseAssert "Unreachable"
|
2022-03-20 10:58:59 +00:00
|
|
|
do: return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
dag.lightClientCache.bootstrap[slot] = cachedBootstrap
|
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
debug "LC bootstrap unavailable: Data not cached", slot
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-03-11 20:28:10 +00:00
|
|
|
|
2022-03-20 10:58:59 +00:00
|
|
|
let period = slot.sync_committee_period
|
2022-03-11 20:28:10 +00:00
|
|
|
var tmpState = assignClone(dag.headState)
|
|
|
|
var bootstrap {.noinit.}: altair.LightClientBootstrap
|
|
|
|
bootstrap.header =
|
2022-06-14 15:31:10 +00:00
|
|
|
blck.toBeaconBlockHeader()
|
2022-03-11 20:28:10 +00:00
|
|
|
bootstrap.current_sync_committee =
|
2022-06-07 17:01:11 +00:00
|
|
|
? dag.existingCurrentSyncCommitteeForPeriod(tmpState[], period)
|
2022-03-11 20:28:10 +00:00
|
|
|
bootstrap.current_sync_committee_branch =
|
|
|
|
cachedBootstrap.current_sync_committee_branch
|
2022-03-20 10:58:59 +00:00
|
|
|
return ok bootstrap
|
2022-03-11 20:28:10 +00:00
|
|
|
else:
|
2022-05-23 12:02:54 +00:00
|
|
|
debug "LC bootstrap unavailable: Block before Altair", slot
|
2022-03-20 10:58:59 +00:00
|
|
|
return err()
|
2022-05-23 12:02:54 +00:00
|
|
|
|
|
|
|
proc getLightClientUpdateForPeriod*(
|
|
|
|
dag: ChainDAGRef,
|
|
|
|
period: SyncCommitteePeriod): Option[altair.LightClientUpdate] =
|
2022-06-14 09:03:39 +00:00
|
|
|
if not dag.lightClientDataServe:
|
2022-05-23 12:02:54 +00:00
|
|
|
return
|
|
|
|
|
2022-06-14 09:03:39 +00:00
|
|
|
if dag.lightClientDataImportMode == LightClientDataImportMode.OnDemand:
|
2022-05-23 12:02:54 +00:00
|
|
|
dag.initLightClientUpdateForPeriod(period)
|
|
|
|
result = some(dag.lightClientCache.best.getOrDefault(period))
|
|
|
|
let numParticipants = countOnes(result.get.sync_aggregate.sync_committee_bits)
|
|
|
|
if numParticipants < MIN_SYNC_COMMITTEE_PARTICIPANTS:
|
|
|
|
result.reset()
|
|
|
|
|
|
|
|
proc getLightClientFinalityUpdate*(
|
|
|
|
dag: ChainDAGRef): Option[altair.LightClientFinalityUpdate] =
|
2022-06-14 09:03:39 +00:00
|
|
|
if not dag.lightClientDataServe:
|
2022-05-23 12:02:54 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
result = some(dag.lightClientCache.latest)
|
|
|
|
let numParticipants = countOnes(result.get.sync_aggregate.sync_committee_bits)
|
|
|
|
if numParticipants < MIN_SYNC_COMMITTEE_PARTICIPANTS:
|
|
|
|
result.reset()
|
|
|
|
|
|
|
|
proc getLightClientOptimisticUpdate*(
|
|
|
|
dag: ChainDAGRef): Option[altair.LightClientOptimisticUpdate] =
|
2022-06-14 09:03:39 +00:00
|
|
|
if not dag.lightClientDataServe:
|
2022-05-23 12:02:54 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
result = some(dag.lightClientCache.latest.toOptimistic)
|
|
|
|
let numParticipants = countOnes(result.get.sync_aggregate.sync_committee_bits)
|
|
|
|
if numParticipants < MIN_SYNC_COMMITTEE_PARTICIPANTS:
|
|
|
|
result.reset()
|