Merge commit '5150505e66cb9524af793d4f74261165a46daee0' into dev/etan/lc-wasm4

This commit is contained in:
Etan Kissling 2023-10-25 11:14:50 +02:00
commit 835d895120
No known key found for this signature in database
GPG Key ID: B21DA824C5A3D03D
175 changed files with 3847 additions and 1955 deletions

View File

@ -31,8 +31,8 @@ jobs:
cpu: amd64
- os: macos
cpu: amd64
#- os: windows
# cpu: amd64
- os: windows
cpu: amd64
branch: [~, upstream/version-1-6, upstream/version-2-0]
exclude:
- target:
@ -46,7 +46,7 @@ jobs:
branch: upstream/version-1-6
- target:
os: windows
branch: upstream/version-2-0
branch: ~
include:
- branch: upstream/version-1-6
branch-short: version-1-6
@ -61,10 +61,10 @@ jobs:
os: macos
builder: macos-11
shell: bash
#- target:
# os: windows
# builder: windows-2019
# shell: msys2 {0}
- target:
os: windows
builder: windows-2019
shell: msys2 {0}
defaults:
run:
@ -215,7 +215,7 @@ jobs:
if: ${{ !cancelled() }} && github.event_name == 'pull_request'
run: |
excluded_files="config.yaml"
excluded_extensions="ans|json|md|png|ssz|txt"
excluded_extensions="ans|json|md|png|service|ssz|txt"
current_year=$(date +"%Y")
outdated_files=()

10
.gitmodules vendored
View File

@ -24,7 +24,7 @@
path = vendor/nim-libp2p
url = https://github.com/status-im/nim-libp2p.git
ignore = untracked
branch = nimbus
branch = unstable
[submodule "vendor/nimbus-build-system"]
path = vendor/nimbus-build-system
url = https://github.com/status-im/nimbus-build-system.git
@ -59,7 +59,7 @@
path = vendor/nim-chronos
url = https://github.com/status-im/nim-chronos.git
ignore = untracked
branch = nimbus-v23.9.0
branch = master
[submodule "vendor/nim-chronicles"]
path = vendor/nim-chronicles
url = https://github.com/status-im/nim-chronicles.git
@ -222,6 +222,6 @@
branch = master
[submodule "vendor/holesky"]
path = vendor/holesky
url = https://github.com/eth-clients/holesky
ignore = untracked
branch = main
url = https://github.com/eth-clients/holesky
ignore = untracked
branch = main

View File

@ -252,11 +252,12 @@ OK: 1/1 Fail: 0/1 Skip: 0/1
+ validateAttestation OK
```
OK: 2/2 Fail: 0/2 Skip: 0/2
## Gossip validation - Extra
## Gossip validation - Altair
```diff
+ validateSyncCommitteeMessage OK
+ Period boundary OK
+ validateSyncCommitteeMessage - Duplicate pubkey OK
```
OK: 1/1 Fail: 0/1 Skip: 0/1
OK: 2/2 Fail: 0/2 Skip: 0/2
## Honest validator
```diff
+ General pubsub topics OK
@ -703,4 +704,4 @@ OK: 2/2 Fail: 0/2 Skip: 0/2
OK: 9/9 Fail: 0/9 Skip: 0/9
---TOTAL---
OK: 396/401 Fail: 0/401 Skip: 5/401
OK: 397/402 Fail: 0/402 Skip: 5/402

View File

@ -1,4 +1,4 @@
2023-09-08 v23.9.0
2023-09-12 v23.9.0
==================
Nimbus `v23.9.0` is a `low-urgency` upgrade providing full support for the upcoming [Holešky testnet](https://github.com/eth-clients/holesky) and simplifying the required configuration for using [remote signers](https://nimbus.guide/web3signer.html).
@ -16,6 +16,7 @@ We've been hard at work researching and developing a GossipSub protocol upgrade,
https://github.com/status-im/nimbus-eth2/pull/5389
* Nimbus now supports the upcoming Holešky testnet:
https://nimbus.guide/holesky.html
https://github.com/status-im/nimbus-eth2/pull/5337
* Faster validator registry processing reduces the time spent by Nimbus in state transitions and replays:

View File

@ -2829,6 +2829,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - mainnet/altair/fork_choice/on_block/pyspec_tests/on_block_bad_parent_root OK
ForkChoice - mainnet/altair/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - mainnet/altair/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - mainnet/altair/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_bloc OK
+ ForkChoice - mainnet/altair/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_slo OK
+ ForkChoice - mainnet/bellatrix/fork_choice/ex_ante/pyspec_tests/ex_ante_attestations_is_gr OK
+ ForkChoice - mainnet/bellatrix/fork_choice/ex_ante/pyspec_tests/ex_ante_sandwich_with_boos OK
@ -2845,6 +2846,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - mainnet/bellatrix/fork_choice/on_block/pyspec_tests/on_block_bad_parent_root OK
ForkChoice - mainnet/bellatrix/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - mainnet/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - mainnet/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_b OK
+ ForkChoice - mainnet/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_ OK
ForkChoice - mainnet/bellatrix/fork_choice/on_merge_block/pyspec_tests/all_valid Skip
ForkChoice - mainnet/bellatrix/fork_choice/on_merge_block/pyspec_tests/block_lookup_failed Skip
@ -2865,6 +2867,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - mainnet/capella/fork_choice/on_block/pyspec_tests/on_block_bad_parent_root OK
ForkChoice - mainnet/capella/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - mainnet/capella/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - mainnet/capella/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_blo OK
+ ForkChoice - mainnet/capella/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_sl OK
+ ForkChoice - mainnet/deneb/fork_choice/ex_ante/pyspec_tests/ex_ante_attestations_is_greate OK
+ ForkChoice - mainnet/deneb/fork_choice/ex_ante/pyspec_tests/ex_ante_sandwich_with_boost_no OK
@ -2878,12 +2881,18 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - mainnet/deneb/fork_choice/get_head/pyspec_tests/shorter_chain_but_heavier_wei OK
+ ForkChoice - mainnet/deneb/fork_choice/get_head/pyspec_tests/split_tie_breaker_no_attestat OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/basic OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/invalid_data_unavailable OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/invalid_incorrect_proof OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/invalid_wrong_blobs_length OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/invalid_wrong_proofs_length OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/on_block_bad_parent_root OK
ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_block OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_slot OK
+ ForkChoice - mainnet/deneb/fork_choice/on_block/pyspec_tests/simple_blob_data OK
```
OK: 60/68 Fail: 0/68 Skip: 8/68
OK: 69/77 Fail: 0/77 Skip: 8/77
## Sync
```diff
+ Sync - mainnet/bellatrix/sync/optimistic/pyspec_tests/from_syncing_to_invalid OK
@ -2893,4 +2902,4 @@ OK: 60/68 Fail: 0/68 Skip: 8/68
OK: 3/3 Fail: 0/3 Skip: 0/3
---TOTAL---
OK: 2327/2335 Fail: 0/2335 Skip: 8/2335
OK: 2336/2344 Fail: 0/2344 Skip: 8/2344

View File

@ -1873,6 +1873,9 @@ OK: 12/12 Fail: 0/12 Skip: 0/12
OK: 1/1 Fail: 0/1 Skip: 0/1
## EF - Deneb - Epoch Processing - Registry updates [Preset: minimal]
```diff
+ Registry updates - activation_churn_limit__equal_to_activation_limit [Preset: minimal] OK
+ Registry updates - activation_churn_limit__greater_than_activation_limit [Preset: minimal] OK
+ Registry updates - activation_churn_limit__less_than_activation_limit [Preset: minimal] OK
+ Registry updates - activation_queue_activation_and_ejection__1 [Preset: minimal] OK
+ Registry updates - activation_queue_activation_and_ejection__churn_limit [Preset: minimal] OK
+ Registry updates - activation_queue_activation_and_ejection__exceed_churn_limit [Preset: m OK
@ -1889,7 +1892,7 @@ OK: 1/1 Fail: 0/1 Skip: 0/1
+ Registry updates - ejection_past_churn_limit_scaled [Preset: minimal] OK
+ Registry updates - invalid_large_withdrawable_epoch [Preset: minimal] OK
```
OK: 15/15 Fail: 0/15 Skip: 0/15
OK: 18/18 Fail: 0/18 Skip: 0/18
## EF - Deneb - Epoch Processing - Rewards and penalties [Preset: minimal]
```diff
+ Rewards and penalties - almost_empty_attestations [Preset: minimal] OK
@ -2993,6 +2996,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/on_block_finalized_skip_slot OK
ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_bloc OK
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_slo OK
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/pull_up_on_tick OK
+ ForkChoice - minimal/altair/fork_choice/on_block/pyspec_tests/pull_up_past_epoch_block OK
@ -3038,6 +3042,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/on_block_finalized_skip_s OK
ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_b OK
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_ OK
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/pull_up_on_tick OK
+ ForkChoice - minimal/bellatrix/fork_choice/on_block/pyspec_tests/pull_up_past_epoch_block OK
@ -3087,6 +3092,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/on_block_finalized_skip_slo OK
ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_blo OK
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_sl OK
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/pull_up_on_tick OK
+ ForkChoice - minimal/capella/fork_choice/on_block/pyspec_tests/pull_up_past_epoch_block OK
@ -3116,6 +3122,10 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/basic OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/incompatible_justification_up OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/incompatible_justification_up OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/invalid_data_unavailable OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/invalid_incorrect_proof OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/invalid_wrong_blobs_length OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/invalid_wrong_proofs_length OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/justification_update_beginnin OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/justification_update_end_of_e OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/justification_withholding OK
@ -3132,9 +3142,11 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/on_block_finalized_skip_slots OK
ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/on_block_future_block Skip
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/proposer_boost OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/proposer_boost_is_first_block OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/proposer_boost_root_same_slot OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/pull_up_on_tick OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/pull_up_past_epoch_block OK
+ ForkChoice - minimal/deneb/fork_choice/on_block/pyspec_tests/simple_blob_data OK
+ ForkChoice - minimal/deneb/fork_choice/reorg/pyspec_tests/delayed_justification_current_ep OK
+ ForkChoice - minimal/deneb/fork_choice/reorg/pyspec_tests/delayed_justification_previous_e OK
+ ForkChoice - minimal/deneb/fork_choice/reorg/pyspec_tests/include_votes_another_empty_chai OK
@ -3146,7 +3158,7 @@ OK: 6/6 Fail: 0/6 Skip: 0/6
+ ForkChoice - minimal/deneb/fork_choice/withholding/pyspec_tests/withholding_attack OK
+ ForkChoice - minimal/deneb/fork_choice/withholding/pyspec_tests/withholding_attack_unviabl OK
```
OK: 176/184 Fail: 0/184 Skip: 8/184
OK: 185/193 Fail: 0/193 Skip: 8/193
## Sync
```diff
+ Sync - minimal/bellatrix/sync/optimistic/pyspec_tests/from_syncing_to_invalid OK
@ -3156,4 +3168,4 @@ OK: 176/184 Fail: 0/184 Skip: 8/184
OK: 3/3 Fail: 0/3 Skip: 0/3
---TOTAL---
OK: 2566/2574 Fail: 0/2574 Skip: 8/2574
OK: 2578/2586 Fail: 0/2586 Skip: 8/2586

View File

@ -118,17 +118,31 @@ ifneq ($(OS), Windows_NT)
PLATFORM_SPECIFIC_TARGETS += gnosis-build
endif
# We don't need the `vendor/holesky/public-keys/all.txt` file but fetching it
# may trigger 'This repository is over its data quota' from GitHub
GIT_SUBMODULE_CONFIG := -c lfs.fetchexclude=/public-keys/all.txt
ifeq ($(NIM_PARAMS),)
# "variables.mk" was not included, so we update the submodules.
#
# The `git reset ...` will try to fix a `make update` that was interrupted
# with Ctrl+C after deleting the working copy and before getting a chance to
# restore it in $(BUILD_SYSTEM_DIR).
GIT_SUBMODULE_UPDATE := git submodule update --init --recursive
# `vendor/holesky` requires Git LFS
ifeq (, $(shell which git-lfs))
ifeq ($(shell uname), Darwin)
$(error Git LFS not installed. Run 'brew install git-lfs' to set up)
else
$(error Git LFS not installed)
endif
endif
GIT_SUBMODULE_UPDATE := git $(GIT_SUBMODULE_CONFIG) submodule update --init --recursive
.DEFAULT:
+@ echo -e "Git submodules not found. Running '$(GIT_SUBMODULE_UPDATE)'.\n"; \
$(GIT_SUBMODULE_UPDATE) && \
git submodule foreach --quiet 'git reset --quiet --hard' && \
git submodule foreach --quiet 'git $(GIT_SUBMODULE_CONFIG) reset --quiet --hard' && \
echo
# Now that the included *.mk files appeared, and are newer than this file, Make will restart itself:
# https://www.gnu.org/software/make/manual/make.html#Remaking-Makefiles
@ -307,7 +321,7 @@ consensus_spec_tests_minimal: | build deps
MAKE="$(MAKE)" V="$(V)" $(ENV_SCRIPT) scripts/compile_nim_program.sh \
$@ \
"tests/consensus_spec/consensus_spec_tests_preset.nim" \
$(NIM_PARAMS) -d:const_preset=minimal $(TEST_MODULES_FLAGS) && \
$(NIM_PARAMS) -d:const_preset=minimal -d:FIELD_ELEMENTS_PER_BLOB=4 $(TEST_MODULES_FLAGS) && \
echo -e $(BUILD_END_MSG) "build/$@"
# Tests we only run for the default preset

View File

@ -16,7 +16,7 @@ from ./spec/datatypes/capella import
from ./spec/datatypes/deneb import ExecutionPayloadHeader
type
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconstate
# Memory-representation-equivalent to a phase0 BeaconState for in-place SSZ
# reading and writing
Phase0BeaconStateNoImmutableValidators* = object
@ -69,7 +69,7 @@ type
current_justified_checkpoint*: Checkpoint
finalized_checkpoint*: Checkpoint
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#beaconstate
# Memory-representation-equivalent to an Altair BeaconState for in-place SSZ
# reading and writing
AltairBeaconStateNoImmutableValidators* = object
@ -186,7 +186,7 @@ type
# Execution
latest_execution_payload_header*: bellatrix.ExecutionPayloadHeader # [New in Bellatrix]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconstate
# with indirect changes via ExecutionPayload
# Memory-representation-equivalent to a Capella BeaconState for in-place SSZ
# reading and writing
@ -258,7 +258,7 @@ type
HashList[HistoricalSummary,
Limit HISTORICAL_ROOTS_LIMIT] # [New in Capella]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconstate
# with indirect changes via ExecutionPayloadHeader
# Memory-representation-equivalent to a Deneb BeaconState for in-place SSZ
# reading and writing

View File

@ -122,23 +122,26 @@ func getPayloadBuilderAddress*(config: BeaconNodeConf): Opt[string] =
else:
Opt.none(string)
proc getPayloadBuilderAddress*(
node: BeaconNode, pubkey: ValidatorPubKey): Opt[string] =
let defaultPayloadBuilderAddress = node.config.getPayloadBuilderAddress
if node.keymanagerHost.isNil:
defaultPayloadBuilderAddress
else:
node.keymanagerHost[].getBuilderConfig(pubkey).valueOr:
defaultPayloadBuilderAddress
proc getPayloadBuilderClient*(
node: BeaconNode, validator_index: uint64): RestResult[RestClientRef] =
if not node.config.payloadBuilderEnable:
return err "Payload builder globally disabled"
let
defaultPayloadBuilderAddress = node.config.getPayloadBuilderAddress
pubkey = withState(node.dag.headState):
if validator_index >= forkyState.data.validators.lenu64:
return err "Validator index too high"
forkyState.data.validators.item(validator_index).pubkey
payloadBuilderAddress =
if node.keymanagerHost.isNil:
defaultPayloadBuilderAddress
else:
node.keymanagerHost[].getBuilderConfig(pubkey).valueOr:
defaultPayloadBuilderAddress
payloadBuilderAddress = node.getPayloadBuilderAddress(pubkey)
if payloadBuilderAddress.isNone:
return err "Payload builder disabled"

View File

@ -46,12 +46,14 @@ proc initLightClient*(
wallSlot = node.currentSlot
withBlck(signedBlock):
when consensusFork >= ConsensusFork.Bellatrix:
if blck.message.is_execution_block:
template blckPayload(): auto = blck.message.body.execution_payload
if forkyBlck.message.is_execution_block:
template blckPayload(): auto =
forkyBlck.message.body.execution_payload
if not blckPayload.block_hash.isZero:
# engine_newPayloadV1
discard await node.elManager.newExecutionPayload(blck.message)
discard await node.elManager.newExecutionPayload(
forkyBlck.message)
# Retain optimistic head for other `forkchoiceUpdated` callers.
# May temporarily block `forkchoiceUpdatedV1` calls, e.g., Geth:
@ -60,7 +62,7 @@ proc initLightClient*(
# Once DAG sync catches up or as new optimistic heads are fetched
# the situation recovers
node.consensusManager[].setOptimisticHead(
blck.toBlockId(), blckPayload.block_hash)
forkyBlck.toBlockId(), blckPayload.block_hash)
# engine_forkchoiceUpdatedV1 or engine_forkchoiceUpdatedV2,
# depending on pre or post-Shapella
@ -73,7 +75,8 @@ proc initLightClient*(
finalizedBlockHash = beaconHead.finalizedExecutionPayloadHash,
payloadAttributes = none attributes)
case node.dag.cfg.consensusForkAtEpoch(blck.message.slot.epoch)
case node.dag.cfg.consensusForkAtEpoch(
forkyBlck.message.slot.epoch)
of ConsensusFork.Deneb:
callForkchoiceUpdated(PayloadAttributesV3)
of ConsensusFork.Capella:
@ -173,7 +176,7 @@ proc updateLightClientFromDag*(node: BeaconNode) =
const lcDataFork = lcDataForkAtConsensusFork(consensusFork)
when lcDataFork > LightClientDataFork.None:
header = ForkedLightClientHeader(kind: lcDataFork)
header.forky(lcDataFork) = blck.toLightClientHeader(lcDataFork)
header.forky(lcDataFork) = forkyBlck.toLightClientHeader(lcDataFork)
else: raiseAssert "Unreachable"
let current_sync_committee = block:
let tmpState = assignClone(node.dag.headState)

View File

@ -29,6 +29,8 @@ import
./el/el_conf,
./filepath
from fork_choice/fork_choice_types
import ForkChoiceVersion
from consensus_object_pools/block_pools_types_light_client
import LightClientDataImportMode
@ -549,7 +551,7 @@ type
name: "dump" .}: bool
directPeers* {.
desc: "The list of privileged, secure and known peers to connect and maintain the connection to, this requires a not random netkey-file. In the complete multiaddress format like: /ip4/<address>/tcp/<port>/p2p/<peerId-public-key>. Peering agreements are established out of band and must be reciprocal."
desc: "The list of privileged, secure and known peers to connect and maintain the connection to. This requires a not random netkey-file. In the multiaddress format like: /ip4/<address>/tcp/<port>/p2p/<peerId-public-key>, or enr format (enr:-xx). Peering agreements are established out of band and must be reciprocal"
name: "direct-peer" .}: seq[string]
doppelgangerDetection* {.
@ -641,6 +643,12 @@ type
desc: "Bandwidth estimate for the node (bits per second)"
name: "debug-bandwidth-estimate" .}: Option[Natural]
forkChoiceVersion* {.
hidden
desc: "Forkchoice version to use. " &
"Must be one of: stable"
name: "debug-forkchoice-version" .}: Option[ForkChoiceVersion]
of BNStartUpCmd.wallets:
case walletsCmd* {.command.}: WalletsCmd
of WalletsCmd.create:

View File

@ -7,8 +7,8 @@ to specs:
- blocks: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_block
- aggregate attestations: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_aggregate_and_proof
- unaggregated attestation: https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/p2p-interface.md#beacon_attestation_subnet_id
- voluntary exits: https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.1/specs/phase0/p2p-interface.md#voluntary_exit
- Attester slashings: https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/p2p-interface.md#attester_slashing
- voluntary exits: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#voluntary_exit
- Attester slashings: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#attester_slashing
- Proposer slashings: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#proposer_slashing
After "gossip validation" the consensus objects can be rebroadcasted as they are optimistically good, however for internal processing further verification is needed.

View File

@ -90,6 +90,7 @@ declareGauge attestation_pool_block_attestation_packing_time,
proc init*(T: type AttestationPool, dag: ChainDAGRef,
quarantine: ref Quarantine,
forkChoiceVersion = ForkChoiceVersion.Stable,
onAttestation: OnAttestationCallback = nil): T =
## Initialize an AttestationPool from the dag `headState`
## The `finalized_root` works around the finalized_checkpoint of the genesis block
@ -97,7 +98,7 @@ proc init*(T: type AttestationPool, dag: ChainDAGRef,
let finalizedEpochRef = dag.getFinalizedEpochRef()
var forkChoice = ForkChoice.init(
finalizedEpochRef, dag.finalizedHead.blck)
finalizedEpochRef, dag.finalizedHead.blck, forkChoiceVersion)
# Feed fork choice with unfinalized history - during startup, block pool only
# keeps track of a single history so we just need to follow it
@ -152,7 +153,7 @@ proc init*(T: type AttestationPool, dag: ChainDAGRef,
default(FinalityCheckpoints)
withBlck(blck):
forkChoice.process_block(
dag, epochRef, blckRef, unrealized, blck.message,
dag, epochRef, blckRef, unrealized, forkyBlck.message,
blckRef.slot.start_beacon_time)
doAssert status.isOk(), "Error in preloading the fork choice: " & $status.error
@ -559,7 +560,7 @@ proc getAttestationsForBlock*(pool: var AttestationPool,
cache: var StateCache): seq[Attestation] =
## Retrieve attestations that may be added to a new block at the slot of the
## given state
## https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/validator.md#attestations
## https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/validator.md#attestations
let newBlockSlot = state.data.slot.uint64
if newBlockSlot < MIN_ATTESTATION_INCLUSION_DELAY:
@ -742,7 +743,7 @@ func getAggregatedAttestation*(pool: var AttestationPool,
index: CommitteeIndex): Opt[Attestation] =
## Select the attestation that has the most votes going for it in the given
## slot/index
## https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/validator.md#construct-aggregate
## https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/validator.md#construct-aggregate
let candidateIdx = pool.candidateIdx(slot)
if candidateIdx.isNone:
return Opt.none(Attestation)
@ -772,7 +773,7 @@ proc getBeaconHead*(
finalizedExecutionPayloadHash =
pool.dag.loadExecutionBlockHash(pool.dag.finalizedHead.blck)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/fork_choice/safe-block.md#get_safe_execution_payload_hash
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/fork_choice/safe-block.md#get_safe_execution_payload_hash
safeBlockRoot = pool.forkChoice.get_safe_beacon_block_root()
safeBlock = pool.dag.getBlockRef(safeBlockRoot)
safeExecutionPayloadHash =

View File

@ -279,7 +279,7 @@ type
# balances, as used in fork choice
effective_balances_bytes*: seq[byte]
OnBlockAdded[T] = proc(
OnBlockAdded[T: ForkyTrustedSignedBeaconBlock] = proc(
blckRef: BlockRef, blck: T, epochRef: EpochRef,
unrealized: FinalityCheckpoints) {.gcsafe, raises: [].}
OnPhase0BlockAdded* = OnBlockAdded[phase0.TrustedSignedBeaconBlock]
@ -321,6 +321,20 @@ type
block_root* {.serializedFieldName: "block".}: Eth2Digest
optimistic* {.serializedFieldName: "execution_optimistic".}: Option[bool]
template OnBlockAddedCallback*(kind: static ConsensusFork): auto =
when kind == ConsensusFork.Deneb:
typedesc[OnDenebBlockAdded]
elif kind == ConsensusFork.Capella:
typedesc[OnCapellaBlockAdded]
elif kind == ConsensusFork.Bellatrix:
typedesc[OnBellatrixBlockAdded]
elif kind == ConsensusFork.Altair:
typedesc[OnAltairBlockAdded]
elif kind == ConsensusFork.Phase0:
typedesc[OnPhase0BlockAdded]
else:
static: raiseAssert "Unreachable"
func proposer_dependent_slot*(epochRef: EpochRef): Slot =
epochRef.key.epoch.proposer_dependent_slot()
@ -434,7 +448,7 @@ func init*(t: typedesc[EventBeaconBlockObject],
optimistic: Option[bool]): EventBeaconBlockObject =
withBlck(v):
EventBeaconBlockObject(
slot: blck.message.slot,
block_root: blck.root,
slot: forkyBlck.message.slot,
block_root: forkyBlck.root,
optimistic: optimistic
)

View File

@ -286,8 +286,8 @@ proc getForkedBlock*(
let fork = dag.cfg.consensusForkAtEpoch(bid.slot.epoch)
result.ok(ForkedTrustedSignedBeaconBlock(kind: fork))
withBlck(result.get()):
type T = type(blck)
blck = getBlock(dag, bid, T).valueOr:
type T = type(forkyBlck)
forkyBlck = getBlock(dag, bid, T).valueOr:
getBlock(
dag.era, getStateField(dag.headState, historical_roots).asSeq,
dag.headState.historical_summaries().asSeq,
@ -310,7 +310,7 @@ proc getBlockId*(db: BeaconChainDB, root: Eth2Digest): Opt[BlockId] =
# Shouldn't happen too often but..
let
blck = forked.get()
summary = withBlck(blck): blck.message.toBeaconBlockSummary()
summary = withBlck(blck): forkyBlck.message.toBeaconBlockSummary()
debug "Writing summary", blck = shortLog(blck)
db.putBeaconBlockSummary(root, summary)
return ok(BlockId(root: root, slot: summary.slot))
@ -1129,7 +1129,7 @@ proc init*(T: type ChainDAGRef, cfg: RuntimeConfig, db: BeaconChainDB,
# should have `previous_version` set to `current_version` while
# this doesn't happen to be the case in network that go through
# regular hard-fork upgrades. See for example:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#testing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#testing
if stateFork.current_version != configFork.current_version:
error "State from database does not match network, check --network parameter",
tail = dag.tail, headRef, stateFork, configFork
@ -1393,9 +1393,9 @@ proc computeRandaoMix(
## Compute the requested RANDAO mix for `bdata` without `state`, if possible.
withBlck(bdata):
when consensusFork >= ConsensusFork.Bellatrix:
if blck.message.is_execution_block:
var mix = eth2digest(blck.message.body.randao_reveal.toRaw())
mix.data.mxor blck.message.body.execution_payload.prev_randao.data
if forkyBlck.message.is_execution_block:
var mix = eth2digest(forkyBlck.message.body.randao_reveal.toRaw())
mix.data.mxor forkyBlck.message.body.execution_payload.prev_randao.data
return ok mix
Opt.none(Eth2Digest)
@ -1424,14 +1424,15 @@ proc computeRandaoMix*(
while bid.slot > ancestorSlot:
let bdata = ? dag.getForkedBlock(bid)
withBlck(bdata): # See `process_randao` / `process_randao_mixes_reset`
mix.data.mxor eth2digest(blck.message.body.randao_reveal.toRaw()).data
mix.data.mxor eth2digest(
forkyBlck.message.body.randao_reveal.toRaw()).data
bid = ? dag.parent(bid)
ok()
# Mix in RANDAO from `bid`
if ancestorSlot < bid.slot:
withBlck(bdata):
mix = eth2digest(blck.message.body.randao_reveal.toRaw())
mix = eth2digest(forkyBlck.message.body.randao_reveal.toRaw())
? mixToAncestor(? dag.parent(bid))
else:
mix.reset()
@ -1931,7 +1932,7 @@ proc pruneBlocksDAG(dag: ChainDAGRef) =
prunedHeads = hlen - dag.heads.len,
dagPruneDur = Moment.now() - startTick
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/sync/optimistic.md#helpers
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/sync/optimistic.md#helpers
template is_optimistic*(dag: ChainDAGRef, bid: BlockId): bool =
let blck =
if bid.slot <= dag.finalizedHead.slot:
@ -2251,7 +2252,7 @@ proc loadExecutionBlockHash*(dag: ChainDAGRef, bid: BlockId): Eth2Digest =
withBlck(blockData):
when consensusFork >= ConsensusFork.Bellatrix:
blck.message.body.execution_payload.block_hash
forkyBlck.message.body.execution_payload.block_hash
else:
ZERO_HASH

View File

@ -218,7 +218,8 @@ proc initLightClientBootstrapForPeriod(
if not dag.lcDataStore.db.hasSyncCommittee(period):
dag.lcDataStore.db.putSyncCommittee(
period, forkyState.data.current_sync_committee)
dag.lcDataStore.db.putHeader(blck.toLightClientHeader(lcDataFork))
dag.lcDataStore.db.putHeader(
forkyBlck.toLightClientHeader(lcDataFork))
dag.lcDataStore.db.putCurrentSyncCommitteeBranch(
bid.slot, forkyState.data.build_proof(
altair.CURRENT_SYNC_COMMITTEE_INDEX).get)
@ -275,7 +276,7 @@ proc initLightClientUpdateForPeriod(
numParticipants =
withBlck(bdata):
when consensusFork >= ConsensusFork.Altair:
blck.message.body.sync_aggregate.num_active_participants
forkyBlck.message.body.sync_aggregate.num_active_participants
else: raiseAssert "Unreachable"
if numParticipants >= maxParticipants:
maxParticipants = numParticipants
@ -368,7 +369,7 @@ proc initLightClientUpdateForPeriod(
const lcDataFork = lcDataForkAtConsensusFork(consensusFork)
update = ForkedLightClientUpdate(kind: lcDataFork)
template forkyUpdate: untyped = update.forky(lcDataFork)
forkyUpdate.attested_header = blck.toLightClientHeader(lcDataFork)
forkyUpdate.attested_header = forkyBlck.toLightClientHeader(lcDataFork)
forkyUpdate.next_sync_committee = forkyState.data.next_sync_committee
forkyUpdate.next_sync_committee_branch =
forkyState.data.build_proof(altair.NEXT_SYNC_COMMITTEE_INDEX).get
@ -387,7 +388,8 @@ proc initLightClientUpdateForPeriod(
withForkyUpdate(update):
when lcDataFork > LightClientDataFork.None:
when lcDataFork >= lcDataForkAtConsensusFork(consensusFork):
forkyUpdate.finalized_header = blck.toLightClientHeader(lcDataFork)
forkyUpdate.finalized_header =
forkyBlck.toLightClientHeader(lcDataFork)
else: raiseAssert "Unreachable"
let bdata = dag.getExistingForkedBlock(signatureBid).valueOr:
dag.handleUnexpectedLightClientError(signatureBid.slot)
@ -397,7 +399,7 @@ proc initLightClientUpdateForPeriod(
withForkyUpdate(update):
when lcDataFork > LightClientDataFork.None:
forkyUpdate.sync_aggregate =
blck.asSigned().message.body.sync_aggregate
forkyBlck.asSigned().message.body.sync_aggregate
else: raiseAssert "Unreachable"
withForkyUpdate(update):
when lcDataFork > LightClientDataFork.None:
@ -478,7 +480,7 @@ template lazy_header(name: untyped): untyped {.dirty.} =
else:
withBlck(bdata.get):
when data_fork >= lcDataForkAtConsensusFork(consensusFork):
obj.name = blck.toLightClientHeader(data_fork)
obj.name = forkyBlck.toLightClientHeader(data_fork)
else: raiseAssert "Unreachable"
`name _ ptr` = addr obj.name
`name _ ok`
@ -496,7 +498,7 @@ template lazy_header(name: untyped): untyped {.dirty.} =
obj.migrateToDataFork(data_fork)
withBlck(bdata.get):
when data_fork >= lcDataForkAtConsensusFork(consensusFork):
obj.forky(data_fork).name = blck.toLightClientHeader(data_fork)
obj.forky(data_fork).name = forkyBlck.toLightClientHeader(data_fork)
else: raiseAssert "Unreachable"
`name _ ptr` = addr obj.forky(data_fork).name
`name _ ok`
@ -745,7 +747,7 @@ proc initLightClientDataCache*(dag: ChainDAGRef) =
# Create `LightClientUpdate` instances
if i < blocks.high:
dag.createLightClientUpdates(
forkyState, blck, parentBid = blocks[i + 1])
forkyState, forkyBlck, parentBid = blocks[i + 1])
else: raiseAssert "Unreachable"
let lightClientEndTick = Moment.now()
@ -882,7 +884,8 @@ proc processFinalizationForLightClient*(
withBlck(bdata):
when consensusFork >= ConsensusFork.Altair:
const lcDataFork = lcDataForkAtConsensusFork(consensusFork)
dag.lcDataStore.db.putHeader(blck.toLightClientHeader(lcDataFork))
dag.lcDataStore.db.putHeader(
forkyBlck.toLightClientHeader(lcDataFork))
else: raiseAssert "Unreachable"
dag.lcDataStore.db.putCurrentSyncCommitteeBranch(
bid.slot, dag.getLightClientData(bid).current_sync_committee_branch)
@ -1006,7 +1009,7 @@ proc getLightClientBootstrap*(
when consensusFork >= ConsensusFork.Altair:
const lcDataFork = lcDataForkAtConsensusFork(consensusFork)
let
header = blck.toLightClientHeader(lcDataFork)
header = forkyBlck.toLightClientHeader(lcDataFork)
bootstrap = dag.getLightClientBootstrap(header)
if bootstrap.kind > LightClientDataFork.None:
dag.lcDataStore.db.putHeader(header)

View File

@ -25,7 +25,7 @@ logScope: topics = "spec_cache"
func count_active_validators*(shufflingRef: ShufflingRef): uint64 =
shufflingRef.shuffled_active_validator_indices.lenu64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_committee_count_per_slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_committee_count_per_slot
func get_committee_count_per_slot*(shufflingRef: ShufflingRef): uint64 =
get_committee_count_per_slot(count_active_validators(shufflingRef))
@ -38,7 +38,7 @@ func get_committee_index*(shufflingRef: ShufflingRef, index: uint64):
Result[CommitteeIndex, cstring] =
check_attestation_index(index, get_committee_count_per_slot(shufflingRef))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_beacon_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_committee
iterator get_beacon_committee*(
shufflingRef: ShufflingRef, slot: Slot, committee_index: CommitteeIndex):
(int, ValidatorIndex) =
@ -51,7 +51,7 @@ iterator get_beacon_committee*(
committees_per_slot * SLOTS_PER_EPOCH
): yield (index_in_committee, idx)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_beacon_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_committee
func get_beacon_committee*(
shufflingRef: ShufflingRef, slot: Slot, committee_index: CommitteeIndex):
seq[ValidatorIndex] =
@ -64,7 +64,7 @@ func get_beacon_committee*(
committees_per_slot * SLOTS_PER_EPOCH
)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_beacon_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_committee
func get_beacon_committee_len*(
shufflingRef: ShufflingRef, slot: Slot, committee_index: CommitteeIndex): uint64 =
## Return the number of members in the beacon committee at ``slot`` for ``index``.
@ -76,7 +76,7 @@ func get_beacon_committee_len*(
committees_per_slot * SLOTS_PER_EPOCH
)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_attesting_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_attesting_indices
iterator get_attesting_indices*(shufflingRef: ShufflingRef,
slot: Slot,
committee_index: CommitteeIndex,
@ -155,7 +155,7 @@ func get_attesting_indices_one*(shufflingRef: ShufflingRef,
res = some(validator_index)
res
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_attesting_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_attesting_indices
func get_attesting_indices*(shufflingRef: ShufflingRef,
slot: Slot,
committee_index: CommitteeIndex,

View File

@ -228,7 +228,7 @@ proc restValidatorExit(config: BeaconNodeConf) {.async.} =
block:
let s = spec.getOrDefault("DENEB_FORK_EPOCH", $FAR_FUTURE_EPOCH)
Epoch(Base10.decode(uint64, s).get(uint64(FAR_FUTURE_EPOCH)))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#voluntary-exits
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#voluntary-exits
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#modified-process_voluntary_exit
if currentEpoch >= denebForkEpoch:
let capellaForkVersion =

View File

@ -10,11 +10,11 @@
import
std/[deques, strformat, strutils, sequtils, tables, typetraits, uri, json],
# Nimble packages:
chronos, metrics, chronicles/timings, stint/endians2,
chronos, metrics, chronicles/timings,
json_rpc/[client, errors],
web3, web3/ethhexstrings, web3/engine_api,
eth/common/[eth_types, transaction],
eth/async_utils, stew/[assign2, byteutils, objects, results, shims/hashes],
eth/async_utils, stew/[assign2, byteutils, objects, results, shims/hashes, endians2],
# Local modules:
../spec/[deposit_snapshots, eth2_merkleization, forks, helpers],
../spec/datatypes/[base, phase0, bellatrix, deneb],
@ -353,7 +353,7 @@ proc trackEngineApiRequest(connection: ELConnection,
deadline.addCallback do (udata: pointer) {.gcsafe, raises: [].}:
if not request.finished:
request.cancel()
request.cancelSoon()
engine_api_timeouts.inc(1, [connection.engineUrl.url, requestName])
if not failureAllowed:
connection.setDegradedState(requestName, 0, "Request timed out")
@ -944,7 +944,7 @@ proc getPayload*(m: ELManager,
var bestPayloadIdx = none int
for idx, req in requests:
if not req.finished:
req.cancel()
req.cancelSoon()
elif req.failed:
error "Failed to get execution payload from EL",
url = m.elConnections[idx].engineUrl.url,
@ -1059,12 +1059,12 @@ proc selectConnectionForChainSyncing(m: ELManager): Future[ELConnection] {.async
await firstCompletedFuture(connectionsFuts)
except CancelledError as err:
for future in connectionsFuts:
future.cancel()
future.cancelSoon()
raise err
for future in connectionsFuts:
if future != firstConnected:
future.cancel()
future.cancelSoon()
return m.elConnections[find(connectionsFuts, firstConnected)]
@ -1447,7 +1447,7 @@ proc exchangeTransitionConfiguration*(m: ELManager) {.async.} =
var cancelled = 0
for idx, req in requests:
if not req.finished:
req.cancel()
req.cancelSoon()
inc cancelled
if cancelled == requests.len:
@ -1871,7 +1871,7 @@ proc new*(T: type ELManager,
proc safeCancel(fut: var Future[void]) =
if not fut.isNil and not fut.finished:
fut.cancel()
fut.cancelSoon()
fut = nil
func clear(chain: var Eth1Chain) =

View File

@ -7,7 +7,7 @@
{.push raises: [].}
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/tests/core/pyspec/eth2spec/utils/merkle_minimal.py
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/tests/core/pyspec/eth2spec/utils/merkle_minimal.py
# Merkle tree helpers
# ---------------------------------------------------------------

View File

@ -1,5 +1,5 @@
# Fork choice implementations
References:
- https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/fork-choice.md
- https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/fork-choice.md
- https://github.com/protolambda/lmd-ghost

View File

@ -49,11 +49,13 @@ func compute_deltas(
logScope: topics = "fork_choice"
func init*(
T: type ForkChoiceBackend, checkpoints: FinalityCheckpoints): T =
T(proto_array: ProtoArray.init(checkpoints))
T: type ForkChoiceBackend, checkpoints: FinalityCheckpoints,
version: ForkChoiceVersion): T =
T(proto_array: ProtoArray.init(checkpoints, version))
proc init*(
T: type ForkChoice, epochRef: EpochRef, blck: BlockRef): T =
T: type ForkChoice, epochRef: EpochRef, blck: BlockRef,
version: ForkChoiceVersion): T =
## Initialize a fork choice context for a finalized state - in the finalized
## state, the justified and finalized checkpoints are the same, so only one
## is used here
@ -65,10 +67,13 @@ proc init*(
backend: ForkChoiceBackend.init(
FinalityCheckpoints(
justified: checkpoint,
finalized: checkpoint)),
finalized: checkpoint),
version),
checkpoints: Checkpoints(
version: version,
justified: BalanceCheckpoint(
checkpoint: checkpoint,
total_active_balance: epochRef.total_active_balance,
balances: epochRef.effective_balances),
finalized: checkpoint,
best_justified: checkpoint))
@ -94,6 +99,7 @@ proc update_justified(
store = self.justified.checkpoint, state = justified
self.justified = BalanceCheckpoint(
checkpoint: Checkpoint(root: blck.root, epoch: epochRef.epoch),
total_active_balance: epochRef.total_active_balance,
balances: epochRef.effective_balances)
proc update_justified(
@ -287,7 +293,9 @@ proc process_block*(self: var ForkChoice,
# Add proposer score boost if the block is timely
let slot = self.checkpoints.time.slotOrZero
if slot == blck.slot and self.checkpoints.time < slot.attestation_deadline:
if slot == blck.slot and
self.checkpoints.time < slot.attestation_deadline and
self.checkpoints.proposer_boost_root == ZERO_HASH:
self.checkpoints.proposer_boost_root = blckRef.root
# Update checkpoints in store if necessary
@ -315,10 +323,11 @@ proc process_block*(self: var ForkChoice,
ok()
func find_head*(
func find_head(
self: var ForkChoiceBackend,
current_epoch: Epoch,
checkpoints: FinalityCheckpoints,
justified_total_active_balance: Gwei,
justified_state_balances: seq[Gwei],
proposer_boost_root: Eth2Digest
): FcResult[Eth2Digest] =
@ -337,7 +346,7 @@ func find_head*(
# Apply score changes
? self.proto_array.applyScoreChanges(
deltas, current_epoch, checkpoints,
justified_state_balances, proposer_boost_root)
justified_total_active_balance, proposer_boost_root)
self.balances = justified_state_balances
@ -361,10 +370,11 @@ proc get_head*(self: var ForkChoice,
FinalityCheckpoints(
justified: self.checkpoints.justified.checkpoint,
finalized: self.checkpoints.finalized),
self.checkpoints.justified.total_active_balance,
self.checkpoints.justified.balances,
self.checkpoints.proposer_boost_root)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/fork_choice/safe-block.md#get_safe_beacon_block_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/fork_choice/safe-block.md#get_safe_beacon_block_root
func get_safe_beacon_block_root*(self: ForkChoice): Eth2Digest =
# Use most recent justified block as a stopgap
self.checkpoints.justified.checkpoint.root

View File

@ -29,6 +29,14 @@ import
# ----------------------------------------------------------------------
type
ForkChoiceVersion* {.pure.} = enum
## Controls which version of fork choice to run.
Stable = "stable"
## Use current version from stable Ethereum consensus specifications
Pr3431 = "pr3431"
## https://github.com/ethereum/consensus-specs/pull/3431
## https://github.com/ethereum/consensus-specs/issues/3466
fcKind* = enum
## Fork Choice Error Kinds
fcFinalizedNodeUnknown
@ -88,6 +96,7 @@ type
## Subtracted from logical index to get the physical index
ProtoArray* = object
version*: ForkChoiceVersion
currentEpoch*: Epoch
checkpoints*: FinalityCheckpoints
nodes*: ProtoNodes
@ -107,9 +116,11 @@ type
BalanceCheckpoint* = object
checkpoint*: Checkpoint
total_active_balance*: Gwei
balances*: seq[Gwei]
Checkpoints* = object
version*: ForkChoiceVersion
time*: BeaconTime
justified*: BalanceCheckpoint
finalized*: Checkpoint

View File

@ -90,7 +90,8 @@ func nodeLeadsToViableHead(
# ----------------------------------------------------------------------
func init*(
T: type ProtoArray, checkpoints: FinalityCheckpoints): T =
T: type ProtoArray, checkpoints: FinalityCheckpoints,
version: ForkChoiceVersion): T =
let node = ProtoNode(
bid: BlockId(
slot: checkpoints.finalized.epoch.start_slot,
@ -102,7 +103,8 @@ func init*(
bestChild: none(int),
bestDescendant: none(int))
T(checkpoints: checkpoints,
T(version: version,
checkpoints: checkpoints,
nodes: ProtoNodes(buf: @[node], offset: 0),
indices: {node.bid.root: 0}.toTable())
@ -124,18 +126,15 @@ iterator realizePendingCheckpoints*(
self.currentEpochTips.clear()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/fork-choice.md#get_weight
func calculateProposerBoost(validatorBalances: openArray[Gwei]): uint64 =
var total_balance: uint64
for balance in validatorBalances:
total_balance += balance
let committee_weight = total_balance div SLOTS_PER_EPOCH
func calculateProposerBoost(justifiedTotalActiveBalance: Gwei): Gwei =
let committee_weight = justifiedTotalActiveBalance div SLOTS_PER_EPOCH
(committee_weight * PROPOSER_SCORE_BOOST) div 100
func applyScoreChanges*(self: var ProtoArray,
deltas: var openArray[Delta],
currentEpoch: Epoch,
checkpoints: FinalityCheckpoints,
newBalances: openArray[Gwei],
justifiedTotalActiveBalance: Gwei,
proposerBoostRoot: Eth2Digest): FcResult[void] =
## Iterate backwards through the array, touching all nodes and their parents
## and potentially the best-child of each parent.
@ -167,7 +166,7 @@ func applyScoreChanges*(self: var ProtoArray,
self.nodes.buf[nodePhysicalIdx]
# Default value, if not otherwise set in first node loop
var proposerBoostScore: uint64
var proposerBoostScore: Gwei
# Iterate backwards through all the indices in `self.nodes`
for nodePhysicalIdx in countdown(self.nodes.len - 1, 0):
@ -192,7 +191,7 @@ func applyScoreChanges*(self: var ProtoArray,
#
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/fork-choice.md#get_weight
if (not proposerBoostRoot.isZero) and proposerBoostRoot == node.bid.root:
proposerBoostScore = calculateProposerBoost(newBalances)
proposerBoostScore = calculateProposerBoost(justifiedTotalActiveBalance)
if nodeDelta >= 0 and
high(Delta) - nodeDelta < proposerBoostScore.int64:
return err ForkChoiceError(
@ -531,17 +530,25 @@ func nodeIsViableForHead(
self.checkpoints.justified.epoch == GENESIS_EPOCH or
node.checkpoints.justified.epoch == self.checkpoints.justified.epoch
# If the previous epoch is justified, the block should be pulled-up.
# In this case, check that unrealized justification is higher than the store
# and that the voting source is not more than two epochs ago
if not correctJustified and self.isPreviousEpochJustified and
node.bid.slot.epoch == self.currentEpoch:
let unrealized =
self.currentEpochTips.getOrDefault(nodeIdx, node.checkpoints)
correctJustified =
unrealized.justified.epoch >= self.checkpoints.justified.epoch and
node.checkpoints.justified.epoch + 2 >= self.currentEpoch
if not correctJustified:
case self.version
of ForkChoiceVersion.Stable:
# If the previous epoch is justified, the block should be pulled-up.
# In this case, check that unrealized justification is higher than the
# store and that the voting source is not more than two epochs ago
if self.isPreviousEpochJustified and
node.bid.slot.epoch == self.currentEpoch:
let unrealized =
self.currentEpochTips.getOrDefault(nodeIdx, node.checkpoints)
correctJustified =
unrealized.justified.epoch >= self.checkpoints.justified.epoch and
node.checkpoints.justified.epoch + 2 >= self.currentEpoch
of ForkChoiceVersion.Pr3431:
# The voting source should be either at the same height as the store's
# justified checkpoint or not more than two epochs ago
correctJustified =
node.checkpoints.justified.epoch + 2 >= self.currentEpoch
return
if not correctJustified:
false

View File

@ -102,4 +102,4 @@ proc firstCompleted*[T](futs: varargs[Future[T]]): Future[T] =
subFuture.addCallback(cb, cast[pointer](subFuture))
retFuture.cancelCallback = proc (udata: pointer) =
subFuture.cancel()
subFuture.cancelSoon()

View File

@ -9,11 +9,11 @@ This folder holds a collection of modules to:
Gossip validation is different from consensus verification in particular for blocks.
- Blocks: https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/p2p-interface.md#beacon_block
- Blocks: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_block
- Attestations (aggregated): https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_aggregate_and_proof
- Attestations (unaggregated): https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#attestation-subnets
- Voluntary exits: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#voluntary_exit
- Proposer slashings: https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/p2p-interface.md#proposer_slashing
- Proposer slashings: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#proposer_slashing
- Attester slashing: https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/p2p-interface.md#attester_slashing
There are multiple consumers of validated consensus objects:

View File

@ -388,10 +388,10 @@ proc enqueueBlock*(
maybeFinalized = false,
validationDur = Duration()) =
withBlck(blck):
if blck.message.slot <= self.consensusManager.dag.finalizedHead.slot:
if forkyBlck.message.slot <= self.consensusManager.dag.finalizedHead.slot:
# let backfill blocks skip the queue - these are always "fast" to process
# because there are no state rewinds to deal with
let res = self.storeBackfillBlock(blck, blobs)
let res = self.storeBackfillBlock(forkyBlck, blobs)
resfut.complete(res)
return
@ -732,25 +732,25 @@ proc storeBlock(
quarantined = shortLog(quarantined.root)
withBlck(quarantined):
when typeof(blck).toFork() < ConsensusFork.Deneb:
when typeof(forkyBlck).toFork() < ConsensusFork.Deneb:
self[].enqueueBlock(
MsgSource.gossip, quarantined, Opt.none(BlobSidecars))
else:
if len(blck.message.body.blob_kzg_commitments) == 0:
if len(forkyBlck.message.body.blob_kzg_commitments) == 0:
self[].enqueueBlock(
MsgSource.gossip, quarantined, Opt.some(BlobSidecars @[]))
else:
if (let res = checkBloblessSignature(self[], blck); res.isErr):
if (let res = checkBloblessSignature(self[], forkyBlck); res.isErr):
warn "Failed to verify signature of unorphaned blobless block",
blck = shortLog(blck),
blck = shortLog(forkyBlck),
error = res.error()
continue
if self.blobQuarantine[].hasBlobs(blck):
let blobs = self.blobQuarantine[].popBlobs(blck.root)
if self.blobQuarantine[].hasBlobs(forkyBlck):
let blobs = self.blobQuarantine[].popBlobs(forkyBlck.root)
self[].enqueueBlock(MsgSource.gossip, quarantined, Opt.some(blobs))
else:
if not self.consensusManager.quarantine[].addBlobless(
dag.finalizedHead.slot, blck):
dag.finalizedHead.slot, forkyBlck):
notice "Block quarantine full (blobless)",
blockRoot = shortLog(quarantined.root),
signature = shortLog(quarantined.signature)
@ -795,7 +795,7 @@ proc processBlock(
let res = withBlck(entry.blck):
await self.storeBlock(
entry.src, wallTime, blck, entry.blobs, entry.maybeFinalized,
entry.src, wallTime, forkyBlck, entry.blobs, entry.maybeFinalized,
entry.queueTick, entry.validationDur)
if res.isErr and res.error[1] == ProcessingStatus.notCompleted:
@ -804,7 +804,7 @@ proc processBlock(
# - MUST NOT optimistically import the block.
# - MUST NOT apply the block to the fork choice store.
# - MAY queue the block for later processing.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/sync/optimistic.md#execution-engine-errors
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/sync/optimistic.md#execution-engine-errors
await sleepAsync(chronos.seconds(1))
self[].enqueueBlock(
entry.src, entry.blck, entry.blobs, entry.resfut, entry.maybeFinalized,

View File

@ -658,7 +658,7 @@ proc processSignedContributionAndProof*(
err(v.error())
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
proc processLightClientFinalityUpdate*(
self: var Eth2Processor, src: MsgSource,
finality_update: ForkedLightClientFinalityUpdate
@ -674,7 +674,7 @@ proc processLightClientFinalityUpdate*(
beacon_light_client_finality_update_dropped.inc(1, [$v.error[0]])
v
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_optimistic_update
proc processLightClientOptimisticUpdate*(
self: var Eth2Processor, src: MsgSource,
optimistic_update: ForkedLightClientOptimisticUpdate

View File

@ -99,18 +99,19 @@ func check_propagation_slot_range(
# The spec value of ATTESTATION_PROPAGATION_SLOT_RANGE is 32, but it can
# retransmit attestations on the cusp of being out of spec, and which by
# the time they reach their destination might be out of spec.
const ATTESTATION_PROPAGATION_SLOT_RANGE = 28
if msgSlot + ATTESTATION_PROPAGATION_SLOT_RANGE < pastSlot.slot:
const TIME_IN_FLIGHT_BUFFER = 4
static: doAssert ATTESTATION_PROPAGATION_SLOT_RANGE > TIME_IN_FLIGHT_BUFFER
if msgSlot + (ATTESTATION_PROPAGATION_SLOT_RANGE - TIME_IN_FLIGHT_BUFFER) <
pastSlot.slot:
return errIgnore("Attestation slot in the past")
else:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_attestation_subnet_id
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_attestation_subnet_id
# "[IGNORE] the epoch of attestation.data.slot is either the current or
# previous epoch (with a MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance) -- i.e.
# compute_epoch_at_slot(attestation.data.slot) in
# (get_previous_epoch(state), get_current_epoch(state))"
#
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# "[IGNORE] the epoch of aggregate.data.slot is either the current or
# previous epoch (with a MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance) -- i.e.
# compute_epoch_at_slot(aggregate.data.slot) in
@ -301,7 +302,7 @@ template validateBeaconBlockBellatrix(
# cannot occur here, because Nimbus's optimistic sync waits for either
# `ACCEPTED` or `SYNCING` from the EL to get this far.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#blob_sidecar_subnet_id
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#blob_sidecar_subnet_id
proc validateBlobSidecar*(
dag: ChainDAGRef, quarantine: ref Quarantine,
blobQuarantine: ref BlobQuarantine,sbs: SignedBlobSidecar,
@ -560,7 +561,7 @@ proc validateBeaconBlock*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_attestation_subnet_id
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
proc validateAttestation*(
pool: ref AttestationPool,
batchCrypto: ref BatchCrypto,
@ -590,7 +591,7 @@ proc validateAttestation*(
# >= attestation.data.slot (a client MAY queue future attestations for
# processing at the appropriate slot).
#
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_attestation_subnet_id
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_attestation_subnet_id
# modifies this for Deneb and newer forks.
block:
let v = check_propagation_slot_range(
@ -731,7 +732,7 @@ proc validateAttestation*(
return ok((validator_index, sig))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#beacon_aggregate_and_proof
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
proc validateAggregate*(
pool: ref AttestationPool,
batchCrypto: ref BatchCrypto,
@ -762,7 +763,7 @@ proc validateAggregate*(
# MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance) -- i.e. aggregate.data.slot +
# ATTESTATION_PROPAGATION_SLOT_RANGE >= current_slot >= aggregate.data.slot
#
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof
# modifies this for Deneb and newer forks.
block:
let v = check_propagation_slot_range(
@ -1170,14 +1171,11 @@ proc validateContribution*(
checkSignature: bool
): Future[Result[
(BlockId, CookedSig, seq[ValidatorIndex]), ValidationError]] {.async.} =
let
syncCommitteeSlot = msg.message.contribution.slot
# [IGNORE] The contribution's slot is for the current slot
# (with a MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance)
# i.e. contribution.slot == current_slot.
block:
let v = check_slot_exact(syncCommitteeSlot, wallTime)
# [IGNORE] The contribution's slot is for the current slot
# (with a MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance)
# i.e. contribution.slot == current_slot.
let v = check_slot_exact(msg.message.contribution.slot, wallTime)
if v.isErr(): # [IGNORE]
return err(v.error())
@ -1220,7 +1218,7 @@ proc validateContribution*(
# between validation and use - nonetheless, a design that avoids it and
# stays safe would be nice
participants = dag.syncCommitteeParticipants(
msg.message.contribution.slot, subcommitteeIdx)
msg.message.contribution.slot + 1, subcommitteeIdx)
if aggregator_index notin participants:
return dag.checkedReject("Contribution: aggregator not in subcommittee")
@ -1307,7 +1305,7 @@ proc validateContribution*(
return ok((blck.bid, sig, participants))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_finality_update
proc validateLightClientFinalityUpdate*(
pool: var LightClientPool, dag: ChainDAGRef,
finality_update: ForkedLightClientFinalityUpdate,
@ -1343,7 +1341,7 @@ proc validateLightClientFinalityUpdate*(
pool.latestForwardedFinalitySlot = finalized_slot
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
proc validateLightClientOptimisticUpdate*(
pool: var LightClientPool, dag: ChainDAGRef,
optimistic_update: ForkedLightClientOptimisticUpdate,

View File

@ -528,7 +528,7 @@ func toValidationError(
# previously forwarded `optimistic_update`s
errIgnore($r.error)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
proc processLightClientFinalityUpdate*(
self: var LightClientProcessor, src: MsgSource,
finality_update: ForkedLightClientFinalityUpdate
@ -543,7 +543,7 @@ proc processLightClientFinalityUpdate*(
self.latestFinalityUpdate = finality_update.toOptimistic
v
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_finality_update
proc processLightClientOptimisticUpdate*(
self: var LightClientProcessor, src: MsgSource,
optimistic_update: ForkedLightClientOptimisticUpdate

View File

@ -94,7 +94,7 @@ typedef struct ETHConsensusConfig ETHConsensusConfig;
* based on the given `config.yaml` file content - If successful.
* @return `NULL` - If the given `config.yaml` is malformed or incompatible.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/configs/README.md
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/configs/README.md
*/
ETH_RESULT_USE_CHECK
ETHConsensusConfig *ETHConsensusConfigCreateFromYaml(const char *configFileContent);
@ -152,8 +152,8 @@ typedef struct ETHBeaconState ETHBeaconState;
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconstate
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#beaconstate
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#beaconstate
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/capella/beacon-chain.md#beaconstate
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/configs/README.md
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconstate
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/configs/README.md
*/
ETH_RESULT_USE_CHECK
ETHBeaconState *ETHBeaconStateCreateFromSsz(
@ -198,7 +198,7 @@ ETHRoot *ETHBeaconStateCopyGenesisValidatorsRoot(const ETHBeaconState *state);
*
* @param root Merkle root.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/phase0/beacon-chain.md#custom-types
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#custom-types
*/
void ETHRootDestroy(ETHRoot *root);
@ -576,7 +576,7 @@ typedef struct ETHLightClientHeader ETHLightClientHeader;
*
* @return Latest finalized header.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
*/
ETH_RESULT_USE_CHECK
const ETHLightClientHeader *ETHLightClientStoreGetFinalizedHeader(
@ -595,7 +595,7 @@ const ETHLightClientHeader *ETHLightClientStoreGetFinalizedHeader(
* @return Whether or not the next sync committee is currently known.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_next_sync_committee_known
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/altair/light-client/light-client.md
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/light-client.md
*/
ETH_RESULT_USE_CHECK
bool ETHLightClientStoreIsNextSyncCommitteeKnown(const ETHLightClientStore *store);
@ -669,7 +669,7 @@ void ETHLightClientHeaderDestroy(ETHLightClientHeader *header);
*
* @return Pointer to a copy of the given header's beacon block root.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/phase0/beacon-chain.md#hash_tree_root
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#hash_tree_root
*/
ETH_RESULT_USE_CHECK
ETHRoot *ETHLightClientHeaderCopyBeaconRoot(
@ -692,7 +692,7 @@ typedef struct ETHBeaconBlockHeader ETHBeaconBlockHeader;
*
* @return Beacon block header.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/phase0/beacon-chain.md#beaconblockheader
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblockheader
*/
ETH_RESULT_USE_CHECK
const ETHBeaconBlockHeader *ETHLightClientHeaderGetBeacon(
@ -795,7 +795,7 @@ typedef struct ETHExecutionPayloadHeader ETHExecutionPayloadHeader;
*
* @return Execution payload header.
*
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#executionpayloadheader
* @see https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#executionpayloadheader
*/
ETH_RESULT_USE_CHECK
const ETHExecutionPayloadHeader *ETHLightClientHeaderGetExecution(

View File

@ -79,7 +79,7 @@ proc ETHConsensusConfigCreateFromYaml(
## * `NULL` - If the given `config.yaml` is malformed or incompatible.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/configs/README.md
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/configs/README.md
let cfg = RuntimeConfig.new()
try:
cfg[] = readRuntimeConfig($configFileContent, "config.yaml")[0]
@ -143,11 +143,11 @@ proc ETHBeaconStateCreateFromSsz(
## * `NULL` - If the given `sszBytes` is malformed.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/configs/README.md
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconstate
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/configs/README.md
let
consensusFork = decodeEthConsensusVersion($consensusVersion).valueOr:
return nil
@ -196,7 +196,7 @@ proc ETHRootDestroy(root: ptr Eth2Digest) {.exported.} =
## * `root` - Merkle root.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#custom-types
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#custom-types
root.destroy()
proc ETHForkDigestsCreateFromState(
@ -215,7 +215,7 @@ proc ETHForkDigestsCreateFromState(
## * Pointer to an initialized fork digests cache based on the beacon state.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_fork_digest
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_fork_digest
let forkDigests = ForkDigests.new()
forkDigests[] = ForkDigests.init(
cfg[], getStateField(state[], genesis_validators_root))
@ -266,7 +266,7 @@ proc ETHBeaconClockGetSlot(beaconClock: ptr BeaconClock): cint {.exported.} =
## * `0` - If genesis is still pending.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#custom-types
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#custom-types
beaconClock[].now().slotOrZero().cint
const lcDataFork = LightClientDataFork.high
@ -325,8 +325,8 @@ proc ETHLightClientStoreCreateFromBootstrap(
## See:
## * https://ethereum.github.io/beacon-APIs/?urls.primaryName=v2.4.1#/Beacon/getLightClientBootstrap
## * https://ethereum.github.io/beacon-APIs/?urls.primaryName=v2.4.1#/Events/eventstream
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/light-client.md
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/weak-subjectivity.md#weak-subjectivity-period
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/light-client.md
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/weak-subjectivity.md#weak-subjectivity-period
let
mediaType = MediaType.init($mediaType)
consensusFork = decodeEthConsensusVersion($consensusVersion).valueOr:
@ -732,7 +732,7 @@ func ETHLightClientStoreGetFinalizedHeader(
## * Latest finalized header.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
addr store[].finalized_header
func ETHLightClientStoreIsNextSyncCommitteeKnown(
@ -751,8 +751,8 @@ func ETHLightClientStoreIsNextSyncCommitteeKnown(
## * Whether or not the next sync committee is currently known.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_next_sync_committee_known
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/light-client.md
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_next_sync_committee_known
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/light-client.md
store[].is_next_sync_committee_known
func ETHLightClientStoreGetOptimisticHeader(
@ -771,7 +771,7 @@ func ETHLightClientStoreGetOptimisticHeader(
## * Latest optimistic header.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
addr store[].optimistic_header
func ETHLightClientStoreGetSafetyThreshold(
@ -792,7 +792,7 @@ func ETHLightClientStoreGetSafetyThreshold(
## * Light client store safety threshold.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#get_safety_threshold
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#get_safety_threshold
store[].get_safety_threshold.cint
proc ETHLightClientHeaderCreateCopy(
@ -838,7 +838,7 @@ proc ETHLightClientHeaderCopyBeaconRoot(
## * Pointer to a copy of the given header's beacon block root.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#hash_tree_root
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#hash_tree_root
discard cfg # Future-proof against new fields, see `get_lc_execution_root`.
let root = Eth2Digest.new()
root[] = header[].beacon.hash_tree_root()
@ -860,7 +860,7 @@ func ETHLightClientHeaderGetBeacon(
## * Beacon block header.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblockheader
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblockheader
addr header[].beacon
func ETHBeaconBlockHeaderGetSlot(
@ -948,7 +948,7 @@ proc ETHLightClientHeaderCopyExecutionHash(
## * Pointer to a copy of the given header's execution block hash.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#executionpayloadheader
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#executionpayloadheader
discard cfg # Future-proof against SSZ execution block header, EIP-6404ff.
let root = Eth2Digest.new()
root[] = header[].execution.block_hash
@ -973,7 +973,7 @@ func ETHLightClientHeaderGetExecution(
## * Execution payload header.
##
## See:
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#executionpayloadheader
## * https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#executionpayloadheader
addr header[].execution
func ETHExecutionPayloadHeaderGetParentHash(
@ -1564,6 +1564,9 @@ proc ETHTransactionsCreateFromJson(
if data.hash.asEth2Digest != hash:
return nil
template isEven(x: int64): bool =
(x and 1) == 0
# Compute from execution address
var rawSig {.noinit.}: array[65, byte]
rawSig[0 ..< 32] = tx.R.toBytesBE()

View File

@ -353,7 +353,7 @@ proc installMessageValidators*(
digest = forkDigests[].atConsensusFork(contextFork)
# light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_finality_update
lightClient.network.addValidator(
getLightClientFinalityUpdateTopic(digest), proc (
msg: lcDataFork.LightClientFinalityUpdate
@ -361,7 +361,7 @@ proc installMessageValidators*(
validate(msg, contextFork, processLightClientFinalityUpdate))
# light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
lightClient.network.addValidator(
getLightClientOptimisticUpdateTopic(digest), proc (
msg: lcDataFork.LightClientOptimisticUpdate

View File

@ -48,6 +48,8 @@ type
ErrorMsg = List[byte, 256]
SendResult* = Result[void, cstring]
DirectPeers = Table[PeerId, seq[MultiAddress]]
# TODO: This is here only to eradicate a compiler
# warning about unused import (rpc/messages).
GossipMsg = messages.Message
@ -77,6 +79,7 @@ type
forkDigests*: ref ForkDigests
rng*: ref HmacDrbgContext
peers*: Table[PeerId, Peer]
directPeers*: DirectPeers
validTopics: HashSet[string]
peerPingerHeartbeatFut: Future[void]
peerTrimmerHeartbeatFut: Future[void]
@ -1314,7 +1317,7 @@ proc dialPeer(node: Eth2Node, peerAddr: PeerAddr, index = 0) {.async.} =
await workfut or deadline
if workfut.finished():
if not deadline.finished():
deadline.cancel()
deadline.cancelSoon()
inc nbc_successful_dials
else:
debug "Connection to remote peer timed out"
@ -1509,6 +1512,7 @@ proc trimConnections(node: Eth2Node, count: int) =
var toKick = count
for peerId in scores.keys:
if peerId in node.directPeers: continue
debug "kicking peer", peerId, score=scores[peerId]
asyncSpawn node.getPeer(peerId).disconnect(PeerScoreLow)
dec toKick
@ -1793,6 +1797,7 @@ proc new(T: type Eth2Node,
switch: Switch, pubsub: GossipSub,
ip: Option[ValidIpAddress], tcpPort, udpPort: Option[Port],
privKey: keys.PrivateKey, discovery: bool,
directPeers: DirectPeers,
rng: ref HmacDrbgContext): T {.raises: [CatchableError].} =
when not defined(local_testnet):
let
@ -1835,6 +1840,7 @@ proc new(T: type Eth2Node,
rng: rng,
connectTimeout: connectTimeout,
seenThreshold: seenThreshold,
directPeers: directPeers,
quota: TokenBucket.new(maxGlobalQuota, fullReplenishTime)
)
@ -2258,9 +2264,7 @@ func gossipId(
data: openArray[byte], phase0Prefix, topic: string): seq[byte] =
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#topics-and-messages
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/p2p-interface.md#topics-and-messages
const
MESSAGE_DOMAIN_INVALID_SNAPPY = [0x00'u8, 0x00, 0x00, 0x00]
MESSAGE_DOMAIN_VALID_SNAPPY = [0x01'u8, 0x00, 0x00, 0x00]
const MESSAGE_DOMAIN_VALID_SNAPPY = [0x01'u8, 0x00, 0x00, 0x00]
let messageDigest = withEth2Hash:
h.update(MESSAGE_DOMAIN_VALID_SNAPPY)
@ -2315,6 +2319,24 @@ proc createEth2Node*(rng: ref HmacDrbgContext,
except CatchableError as exc: raise exc
except Exception as exc: raiseAssert exc.msg
directPeers = block:
var res: DirectPeers
for s in config.directPeers:
let (peerId, address) =
if s.startsWith("enr:"):
let
typedEnr = parseBootstrapAddress(s).get().toTypedRecord().get()
peerAddress = toPeerAddr(typedEnr, tcpProtocol).get()
(peerAddress.peerId, peerAddress.addrs[0])
elif s.startsWith("/"):
parseFullAddress(s).tryGet()
else:
fatal "direct peers address should start with / (multiaddress) or enr:", conf=s
quit 1
res.mgetOrPut(peerId, @[]).add(address)
info "Adding privileged direct peer", peerId, address
res
hostAddress = tcpEndPoint(config.listenAddress, config.tcpPort)
announcedAddresses = if extIp.isNone() or extTcpPort.isNone(): @[]
else: @[tcpEndPoint(extIp.get(), extTcpPort.get())]
@ -2373,19 +2395,7 @@ proc createEth2Node*(rng: ref HmacDrbgContext,
behaviourPenaltyWeight: -15.9,
behaviourPenaltyDecay: 0.986,
disconnectBadPeers: true,
directPeers:
block:
var res = initTable[PeerId, seq[MultiAddress]]()
if config.directPeers.len > 0:
for s in config.directPeers:
let
maddress = MultiAddress.init(s).tryGet()
mpeerId = maddress[multiCodec("p2p")].tryGet()
peerId = PeerId.init(mpeerId.protoAddress().tryGet()).tryGet()
res.mgetOrPut(peerId, @[]).add(maddress)
info "Adding priviledged direct peer", peerId, address = maddress
res
,
directPeers: directPeers,
bandwidthEstimatebps: config.bandwidthEstimate.get(100_000_000)
)
pubsub = GossipSub.init(
@ -2404,7 +2414,7 @@ proc createEth2Node*(rng: ref HmacDrbgContext,
let node = Eth2Node.new(
config, cfg, enrForkId, discoveryForkId, forkDigests, getBeaconTime, switch, pubsub, extIp,
extTcpPort, extUdpPort, netKeys.seckey.asEthKey,
discovery = config.discv5Enabled, rng = rng)
discovery = config.discv5Enabled, directPeers, rng = rng)
node.pubsub.subscriptionValidator =
proc(topic: string): bool {.gcsafe, raises: [].} =

View File

@ -114,19 +114,21 @@ proc waitForEvent[A, B](pool: PeerPool[A, B], eventType: EventType,
var fut2 = outgoingEvent(eventType).wait()
try:
discard await one(fut1, fut2)
if fut1.finished:
if not(fut2.finished):
fut2.cancel()
if fut1.finished():
if not(fut2.finished()):
await fut2.cancelAndWait()
incomingEvent(eventType).clear()
else:
if not(fut1.finished):
fut1.cancel()
if not(fut1.finished()):
await fut1.cancelAndWait()
outgoingEvent(eventType).clear()
except CancelledError as exc:
if not(fut1.finished):
fut1.cancel()
if not(fut2.finished):
fut2.cancel()
var pending: seq[FutureBase]
if not(fut1.finished()):
pending.add(fut1.cancelAndWait())
if not(fut2.finished()):
pending.add(fut2.cancelAndWait())
await noCancel allFutures(pending)
raise exc
elif PeerType.Incoming in filter:
await incomingEvent(eventType).wait()

View File

@ -313,8 +313,8 @@ proc initFullNode(
let
quarantine = newClone(
Quarantine.init())
attestationPool = newClone(
AttestationPool.init(dag, quarantine, onAttestationReceived))
attestationPool = newClone(AttestationPool.init(
dag, quarantine, config.forkChoiceVersion.get, onAttestationReceived))
syncCommitteeMsgPool = newClone(
SyncCommitteeMsgPool.init(rng, dag.cfg, onSyncContribution))
lightClientPool = newClone(
@ -344,11 +344,11 @@ proc initFullNode(
maybeFinalized: bool):
Future[Result[void, VerifierError]] =
withBlck(signedBlock):
when typeof(blck).toFork() >= ConsensusFork.Deneb:
if not blobQuarantine[].hasBlobs(blck):
when typeof(forkyBlck).toFork() >= ConsensusFork.Deneb:
if not blobQuarantine[].hasBlobs(forkyBlck):
# We don't have all the blobs for this block, so we have
# to put it in blobless quarantine.
if not quarantine[].addBlobless(dag.finalizedHead.slot, blck):
if not quarantine[].addBlobless(dag.finalizedHead.slot, forkyBlck):
Future.completed(
Result[void, VerifierError].err(VerifierError.UnviableFork),
"rmanBlockVerifier")
@ -357,7 +357,7 @@ proc initFullNode(
Result[void, VerifierError].err(VerifierError.MissingParent),
"rmanBlockVerifier")
else:
let blobs = blobQuarantine[].popBlobs(blck.root)
let blobs = blobQuarantine[].popBlobs(forkyBlck.root)
blockProcessor[].addBlock(MsgSource.gossip, signedBlock,
Opt.some(blobs),
maybeFinalized = maybeFinalized)
@ -700,6 +700,7 @@ proc init*(T: type BeaconNode,
getStateField(dag.headState, genesis_validators_root)
let
keystoreCache = KeystoreCacheRef.init()
slashingProtectionDB =
SlashingProtectionDB.init(
getStateField(dag.headState, genesis_validators_root),
@ -711,6 +712,7 @@ proc init*(T: type BeaconNode,
keymanagerHost = if keymanagerInitResult.server != nil:
newClone KeymanagerHost.init(
validatorPool,
keystoreCache,
rng,
keymanagerInitResult.token,
config.validatorsDir,
@ -749,7 +751,7 @@ proc init*(T: type BeaconNode,
restServer: restServer,
keymanagerHost: keymanagerHost,
keymanagerServer: keymanagerInitResult.server,
keystoreCache: KeystoreCacheRef.init(),
keystoreCache: keystoreCache,
eventBus: eventBus,
gossipState: {},
blocksGossipState: {},
@ -1188,9 +1190,9 @@ proc pruneBlobs(node: BeaconNode, slot: Slot) =
for i in startIndex..<SLOTS_PER_EPOCH:
let blck = node.dag.getForkedBlock(blocks[int(i)]).valueOr: continue
withBlck(blck):
when typeof(blck).toFork() < ConsensusFork.Deneb: continue
when typeof(forkyBlck).toFork() < ConsensusFork.Deneb: continue
else:
for j in 0..len(blck.message.body.blob_kzg_commitments) - 1:
for j in 0..len(forkyBlck.message.body.blob_kzg_commitments) - 1:
if node.db.delBlobSidecar(blocks[int(i)].root, BlobIndex(j)):
count = count + 1
debug "pruned blobs", count, blobPruneEpoch
@ -1568,7 +1570,7 @@ proc installMessageValidators(node: BeaconNode) =
MsgSource.gossip, msg)))
when consensusFork >= ConsensusFork.Capella:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/p2p-interface.md#bls_to_execution_change
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/p2p-interface.md#bls_to_execution_change
node.network.addAsyncValidator(
getBlsToExecutionChangeTopic(digest), proc (
msg: SignedBLSToExecutionChange
@ -1579,7 +1581,7 @@ proc installMessageValidators(node: BeaconNode) =
when consensusFork >= ConsensusFork.Deneb:
# blob_sidecar_{index}
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#blob_sidecar_subnet_id
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#blob_sidecar_subnet_id
for i in 0 ..< BLOB_SIDECAR_SUBNET_COUNT:
closureScope: # Needed for inner `proc`; don't lift it out of loop.
let idx = i
@ -1902,6 +1904,13 @@ proc doRunBeaconNode(config: var BeaconNodeConf, rng: ref HmacDrbgContext) {.rai
# works
for node in metadata.bootstrapNodes:
config.bootstrapNodes.add node
if config.forkChoiceVersion.isNone:
config.forkChoiceVersion =
if metadata.cfg.DENEB_FORK_EPOCH != FAR_FUTURE_EPOCH:
# https://github.com/ethereum/pm/issues/844#issuecomment-1673359012
some(ForkChoiceVersion.Pr3431)
else:
some(ForkChoiceVersion.Stable)
## Ctrl+C handling
proc controlCHandler() {.noconv.} =
@ -2164,6 +2173,7 @@ programMain:
# permissions are insecure.
quit QuitFailure
setupFileLimits()
setupLogging(config.logLevel, config.logStdout, config.logFile)
## This Ctrl+C handler exits the program in non-graceful way.

View File

@ -106,6 +106,17 @@ when defaultChroniclesStream.outputs.type.arity == 2:
from std/os import splitFile
from "."/filepath import secureCreatePath
proc setupFileLimits*() =
when not defined(windows):
# In addition to databases and sockets, we need a file descriptor for every
# validator - setting it to 16k should provide sufficient margin
let
limit = getMaxOpenFiles2().valueOr(16384)
if limit < 16384:
setMaxOpenFiles2(16384).isOkOr:
warn "Cannot increase open file limit", err = osErrorMsg(error)
proc setupLogging*(
logLevel: string, stdoutKind: StdoutLogKind, logFile: Option[OutFile]) =
# In the cfg file for nimbus, we create two formats: textlines and json.

View File

@ -115,22 +115,22 @@ programMain:
# `engine_forkchoiceUpdatedV1` under any of the following conditions:
# `headBlockHash` references a block which `timestamp` is greater or
# equal to the Shanghai timestamp
if blck.message.is_execution_block:
template payload(): auto = blck.message.body.execution_payload
if forkyBlck.message.is_execution_block:
template payload(): auto = forkyBlck.message.body.execution_payload
if elManager != nil and not payload.block_hash.isZero:
discard await elManager.newExecutionPayload(blck.message)
discard await elManager.newExecutionPayload(forkyBlck.message)
discard await elManager.forkchoiceUpdated(
headBlockHash = payload.block_hash,
safeBlockHash = payload.block_hash, # stub value
finalizedBlockHash = ZERO_HASH,
payloadAttributes = none PayloadAttributesV2)
elif consensusFork >= ConsensusFork.Bellatrix:
if blck.message.is_execution_block:
template payload(): auto = blck.message.body.execution_payload
if forkyBlck.message.is_execution_block:
template payload(): auto = forkyBlck.message.body.execution_payload
if elManager != nil and not payload.block_hash.isZero:
discard await elManager.newExecutionPayload(blck.message)
discard await elManager.newExecutionPayload(forkyBlck.message)
discard await elManager.forkchoiceUpdated(
headBlockHash = payload.block_hash,
safeBlockHash = payload.block_hash, # stub value

View File

@ -420,7 +420,7 @@ proc asyncRun*(sn: SigningNodeRef) {.async.} =
pending.add(cancelAndWait(sn.runKeystoreCachePruningLoopFut))
pending.add(sn.stop())
pending.add(sn.close())
await allFutures(pending)
await noCancel allFutures(pending)
template runWithSignals(sn: SigningNodeRef, body: untyped): bool =
let future = body
@ -434,7 +434,7 @@ template runWithSignals(sn: SigningNodeRef, body: untyped): bool =
pending.add(cancelAndWait(sn.sigintHandleFut))
if not(sn.sigtermHandleFut.finished()):
pending.add(cancelAndWait(sn.sigtermHandleFut))
await allFutures(pending)
await noCancel allFutures(pending)
false
else:
true
@ -446,7 +446,7 @@ template runWithSignals(sn: SigningNodeRef, body: untyped): bool =
pending.add(cancelAndWait(sn.sigintHandleFut))
if not(sn.sigtermHandleFut.finished()):
pending.add(cancelAndWait(sn.sigtermHandleFut))
await allFutures(pending)
await noCancel allFutures(pending)
false
proc runSigningNode(config: SigningNodeConf) {.async.} =

View File

@ -19,8 +19,21 @@ proc initGenesis(vc: ValidatorClientRef): Future[RestGenesis] {.async.} =
var nodes = vc.beaconNodes
while true:
var pendingRequests: seq[Future[RestResponse[GetGenesisResponse]]]
for node in nodes:
debug "Requesting genesis information", endpoint = node
let offlineNodes = vc.offlineNodes()
if len(offlineNodes) == 0:
let sleepDuration = 2.seconds
info "Could not resolve beacon nodes, repeating",
sleep_time = sleepDuration
await sleepAsync(sleepDuration)
for node in vc.nonameNodes():
let status = checkName(node)
node.updateStatus(status, ApiNodeFailure())
if status == RestBeaconNodeStatus.Noname:
warn "Cannot initialize beacon node", node = node, status = status
continue
for node in offlineNodes:
debug "Requesting genesis information", node = node
pendingRequests.add(node.client.getGenesis())
try:
@ -240,7 +253,8 @@ proc new*(T: type ValidatorClientRef,
warn "Unable to initialize remote beacon node",
url = $url, error = res.error()
else:
debug "Beacon node was initialized", node = res.get()
if res.get().status != RestBeaconNodeStatus.Noname:
debug "Beacon node was initialized", node = res.get()
servers.add(res.get())
let missingRoles = getMissingRoles(servers)
if len(missingRoles) != 0:
@ -296,7 +310,10 @@ proc asyncInit(vc: ValidatorClientRef): Future[ValidatorClientRef] {.async.} =
beacon_nodes_count = len(vc.beaconNodes)
for node in vc.beaconNodes:
notice "Beacon node initialized", node = node
if node.status == RestBeaconNodeStatus.Offline:
notice "Beacon node initialized", node = node
else:
notice "Cannot initialize beacon node", node = node, status = node.status
vc.beaconGenesis = await vc.initGenesis()
info "Genesis information", genesis_time = vc.beaconGenesis.genesis_time,
@ -347,9 +364,10 @@ proc asyncInit(vc: ValidatorClientRef): Future[ValidatorClientRef] {.async.} =
vc.blockService = await BlockServiceRef.init(vc)
vc.syncCommitteeService = await SyncCommitteeServiceRef.init(vc)
vc.keymanagerServer = keymanagerInitResult.server
if vc.keymanagerServer != nil:
if not(isNil(vc.keymanagerServer)):
vc.keymanagerHost = newClone KeymanagerHost.init(
validatorPool,
vc.keystoreCache,
vc.rng,
keymanagerInitResult.token,
vc.config.validatorsDir,
@ -394,14 +412,16 @@ proc runPreGenesisWaitingLoop(vc: ValidatorClientRef) {.async.} =
try:
await sleepAsync(vc.beaconClock.durationToNextSlot())
false
except CancelledError:
except CancelledError as exc:
debug "Pre-genesis waiting loop was interrupted"
true
raise exc
except CatchableError as exc:
error "Pre-genesis waiting loop failed with unexpected error",
err_name = $exc.name, err_msg = $exc.msg
true
vc.preGenesisEvent.fire()
if not(breakLoop):
vc.preGenesisEvent.fire()
proc runGenesisWaitingLoop(vc: ValidatorClientRef) {.async.} =
var breakLoop = false
@ -419,14 +439,16 @@ proc runGenesisWaitingLoop(vc: ValidatorClientRef) {.async.} =
try:
await sleepAsync(vc.beaconClock.durationToNextSlot())
false
except CancelledError:
except CancelledError as exc:
debug "Genesis waiting loop was interrupted"
true
raise exc
except CatchableError as exc:
error "Genesis waiting loop failed with unexpected error",
err_name = $exc.name, err_msg = $exc.msg
true
vc.genesisEvent.fire()
if not(breakLoop):
vc.genesisEvent.fire()
proc asyncRun*(vc: ValidatorClientRef) {.async.} =
vc.fallbackService.start()
@ -437,8 +459,8 @@ proc asyncRun*(vc: ValidatorClientRef) {.async.} =
vc.blockService.start()
vc.syncCommitteeService.start()
if not isNil(vc.keymanagerServer):
doAssert vc.keymanagerHost != nil
if not(isNil(vc.keymanagerServer)):
doAssert not(isNil(vc.keymanagerHost))
vc.keymanagerServer.router.installKeymanagerHandlers(vc.keymanagerHost[])
vc.keymanagerServer.start()
@ -471,9 +493,10 @@ proc asyncRun*(vc: ValidatorClientRef) {.async.} =
debug "Stopping main processing loop"
var pending: seq[Future[void]]
if not(vc.runSlotLoopFut.finished()):
if not(isNil(vc.runSlotLoopFut)) and not(vc.runSlotLoopFut.finished()):
pending.add(vc.runSlotLoopFut.cancelAndWait())
if not(vc.runKeystoreCachePruningLoopFut.finished()):
if not(isNil(vc.runKeystoreCachePruningLoopFut)) and
not(vc.runKeystoreCachePruningLoopFut.finished()):
pending.add(vc.runKeystoreCachePruningLoopFut.cancelAndWait())
if not(doppelEventFut.finished()):
pending.add(doppelEventFut.cancelAndWait())
@ -534,5 +557,6 @@ programMain:
# and avoid using system resources (such as urandom) after that
rng = HmacDrbgContext.new()
setupFileLimits()
setupLogging(config.logLevel, config.logStdout, config.logFile)
waitFor runValidatorClient(config, rng)

View File

@ -799,12 +799,12 @@ proc installBeaconApiHandlers*(router: var RestRouter, node: BeaconNode) =
RestApiResponse.jsonResponseWOpt(
[
(
root: blck.root,
root: forkyBlck.root,
canonical: node.dag.isCanonical(
BlockId(root: blck.root, slot: blck.message.slot)),
BlockId(root: forkyBlck.root, slot: forkyBlck.message.slot)),
header: (
message: blck.toBeaconBlockHeader,
signature: blck.signature
message: forkyBlck.toBeaconBlockHeader,
signature: forkyBlck.signature
)
)
],
@ -826,12 +826,12 @@ proc installBeaconApiHandlers*(router: var RestRouter, node: BeaconNode) =
withBlck(bdata):
RestApiResponse.jsonResponseWOpt(
(
root: blck.root,
root: forkyBlck.root,
canonical: node.dag.isCanonical(
BlockId(root: blck.root, slot: blck.message.slot)),
BlockId(root: forkyBlck.root, slot: forkyBlck.message.slot)),
header: (
message: blck.toBeaconBlockHeader,
signature: blck.signature
message: forkyBlck.toBeaconBlockHeader,
signature: forkyBlck.signature
)
),
node.getBlockOptimistic(bdata)
@ -1024,8 +1024,8 @@ proc installBeaconApiHandlers*(router: var RestRouter, node: BeaconNode) =
return RestApiResponse.jsonError(Http400, InvalidBlockObjectError)
let res = withBlck(forked):
blck.root = hash_tree_root(blck.message)
await node.router.routeSignedBeaconBlock(blck,
forkyBlck.root = hash_tree_root(forkyBlck.message)
await node.router.routeSignedBeaconBlock(forkyBlck,
Opt.none(SignedBlobSidecars))
if res.isErr():
@ -1115,7 +1115,7 @@ proc installBeaconApiHandlers*(router: var RestRouter, node: BeaconNode) =
return
withBlck(bdata):
RestApiResponse.jsonResponseWOpt(
blck.message.body.attestations.asSeq(),
forkyBlck.message.body.attestations.asSeq(),
node.getBlockOptimistic(bdata)
)

View File

@ -88,7 +88,7 @@ proc installConfigApiHandlers*(router: var RestRouter, node: BeaconNode) =
MAX_VOLUNTARY_EXITS:
Base10.toString(MAX_VOLUNTARY_EXITS),
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/altair.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/altair.yaml
INACTIVITY_PENALTY_QUOTIENT_ALTAIR:
Base10.toString(INACTIVITY_PENALTY_QUOTIENT_ALTAIR),
MIN_SLASHING_PENALTY_QUOTIENT_ALTAIR:
@ -104,7 +104,7 @@ proc installConfigApiHandlers*(router: var RestRouter, node: BeaconNode) =
UPDATE_TIMEOUT:
Base10.toString(UPDATE_TIMEOUT),
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/bellatrix.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/bellatrix.yaml
INACTIVITY_PENALTY_QUOTIENT_BELLATRIX:
Base10.toString(INACTIVITY_PENALTY_QUOTIENT_BELLATRIX),
MIN_SLASHING_PENALTY_QUOTIENT_BELLATRIX:
@ -120,7 +120,7 @@ proc installConfigApiHandlers*(router: var RestRouter, node: BeaconNode) =
MAX_EXTRA_DATA_BYTES:
Base10.toString(uint64(MAX_EXTRA_DATA_BYTES)),
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/capella.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/capella.yaml
MAX_BLS_TO_EXECUTION_CHANGES:
Base10.toString(uint64(MAX_BLS_TO_EXECUTION_CHANGES)),
MAX_WITHDRAWALS_PER_PAYLOAD:
@ -183,6 +183,8 @@ proc installConfigApiHandlers*(router: var RestRouter, node: BeaconNode) =
Base10.toString(cfg.MIN_PER_EPOCH_CHURN_LIMIT),
CHURN_LIMIT_QUOTIENT:
Base10.toString(cfg.CHURN_LIMIT_QUOTIENT),
MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT:
Base10.toString(cfg.MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT),
PROPOSER_SCORE_BOOST:
Base10.toString(PROPOSER_SCORE_BOOST),
DEPOSIT_CHAIN_ID:

View File

@ -87,7 +87,9 @@ proc installDebugApiHandlers*(router: var RestRouter, node: BeaconNode) =
var response = GetForkChoiceResponse(
justified_checkpoint: forkChoice.checkpoints.justified.checkpoint,
finalized_checkpoint: forkChoice.checkpoints.finalized)
finalized_checkpoint: forkChoice.checkpoints.finalized,
extra_data: RestExtraData(
version: some($forkChoice.backend.proto_array.version)))
for item in forkChoice.backend.proto_array:
let

View File

@ -8,6 +8,7 @@
{.push raises: [].}
import
std/sequtils,
stew/results,
chronicles,
./rest_utils,
@ -160,12 +161,6 @@ proc installEventApiHandlers*(router: var RestRouter, node: BeaconNode) =
# One of the handlers finished, it means that connection has been droped, so
# we cancelling all other handlers.
let pending =
block:
var res: seq[Future[void]]
for fut in handlers:
if not(fut.finished()):
fut.cancel()
res.add(fut)
res
await allFutures(pending)
handlers.filterIt(not(it.finished())).mapIt(it.cancelAndWait())
await noCancel allFutures(pending)
return

View File

@ -185,7 +185,8 @@ proc installKeymanagerHandlers*(router: var RestRouter, host: KeymanagerHost) =
for index, item in request.keystores:
let res = importKeystore(host.validatorPool[], host.rng[],
host.validatorsDir, host.secretsDir,
item, request.passwords[index])
item, request.passwords[index],
host.keystoreCache)
if res.isErr():
let failure = res.error()
case failure.status

View File

@ -414,17 +414,17 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
return
withBlck(message.blck):
let data =
when blck is deneb.BeaconBlock:
when forkyBlck is deneb.BeaconBlock:
let bundle = message.blobsBundleOpt.get()
let blockRoot = hash_tree_root(blck)
let blockRoot = hash_tree_root(forkyBlck)
var sidecars = newSeqOfCap[BlobSidecar](bundle.blobs.len)
for i in 0..<bundle.blobs.len:
let sidecar = deneb.BlobSidecar(
block_root: blockRoot,
index: BlobIndex(i),
slot: blck.slot,
block_parent_root: blck.parent_root,
proposer_index: blck.proposer_index,
slot: forkyBlck.slot,
block_parent_root: forkyBlck.parent_root,
proposer_index: forkyBlck.proposer_index,
blob: bundle.blobs[i],
kzg_commitment: bundle.kzgs[i],
kzg_proof: bundle.proofs[i]
@ -432,19 +432,21 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
sidecars.add(sidecar)
DenebBlockContents(
`block`: blck,
`block`: forkyBlck,
blob_sidecars: List[BlobSidecar,
Limit MAX_BLOBS_PER_BLOCK].init(sidecars))
elif blck is phase0.BeaconBlock or blck is altair.BeaconBlock or
blck is bellatrix.BeaconBlock or blck is capella.BeaconBlock:
blck
elif forkyBlck is phase0.BeaconBlock or
forkyBlck is altair.BeaconBlock or
forkyBlck is bellatrix.BeaconBlock or
forkyBlck is capella.BeaconBlock:
forkyBlck
else:
static: raiseAssert "produceBlockV2 received unexpected version"
if contentType == sszMediaType:
let headers = [("eth-consensus-version", message.blck.kind.toString())]
RestApiResponse.sszResponse(blck, headers)
RestApiResponse.sszResponse(forkyBlck, headers)
elif contentType == jsonMediaType:
RestApiResponse.jsonResponseWVersion(blck, message.blck.kind)
RestApiResponse.jsonResponseWVersion(forkyBlck, message.blck.kind)
else:
raiseAssert "preferredContentType() returns invalid content type"
@ -568,7 +570,7 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
if res.isErr():
return RestApiResponse.jsonError(Http400, res.error())
withBlck(res.get().blck):
return responseVersioned(blck, contextFork)
return responseVersioned(forkyBlck, contextFork)
# https://ethereum.github.io/beacon-APIs/#/Validator/produceAttestationData
router.api(MethodGet, "/eth/v1/validator/attestation_data") do (

View File

@ -145,10 +145,10 @@ const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/validator.md#broadcast-sync-committee-contribution
syncContributionSlotOffset* = TimeDiff(nanoseconds:
NANOSECONDS_PER_SLOT.int64 * 2 div INTERVALS_PER_SLOT)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#sync-committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#sync-committee
lightClientFinalityUpdateSlotOffset* = TimeDiff(nanoseconds:
NANOSECONDS_PER_SLOT.int64 div INTERVALS_PER_SLOT)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#sync-committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#sync-committee
lightClientOptimisticUpdateSlotOffset* = TimeDiff(nanoseconds:
NANOSECONDS_PER_SLOT.int64 div INTERVALS_PER_SLOT)
@ -196,14 +196,14 @@ func since_epoch_start*(slot: Slot): uint64 = # aka compute_slots_since_epoch_st
template is_epoch*(slot: Slot): bool =
slot.since_epoch_start == 0
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_start_slot_at_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_start_slot_at_epoch
func start_slot*(epoch: Epoch): Slot = # aka compute_start_slot_at_epoch
## Return the start slot of ``epoch``.
const maxEpoch = Epoch(FAR_FUTURE_SLOT div SLOTS_PER_EPOCH)
if epoch >= maxEpoch: FAR_FUTURE_SLOT
else: Slot(epoch * SLOTS_PER_EPOCH)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_previous_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_previous_epoch
func get_previous_epoch*(current_epoch: Epoch): Epoch =
## Return the previous epoch (unless the current epoch is ``GENESIS_EPOCH``).
if current_epoch == GENESIS_EPOCH:

View File

@ -22,7 +22,7 @@ from ./datatypes/capella import BeaconState, ExecutionPayloadHeader, Withdrawal
export extras, forks, validator, chronicles
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#increase_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#increase_balance
func increase_balance*(balance: var Gwei, delta: Gwei) =
balance += delta
@ -32,7 +32,7 @@ func increase_balance*(
if delta != 0: # avoid dirtying the balance cache if not needed
increase_balance(state.balances.mitem(index), delta)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#decrease_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#decrease_balance
func decrease_balance*(balance: var Gwei, delta: Gwei) =
balance =
if delta > balance:
@ -66,13 +66,13 @@ func get_validator_from_deposit*(deposit: DepositData):
effective_balance: effective_balance
)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_activation_exit_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_activation_exit_epoch
func compute_activation_exit_epoch*(epoch: Epoch): Epoch =
## Return the epoch during which validator activations and exits initiated in
## ``epoch`` take effect.
epoch + 1 + MAX_SEED_LOOKAHEAD
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_validator_churn_limit
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_validator_churn_limit
func get_validator_churn_limit*(
cfg: RuntimeConfig, state: ForkyBeaconState, cache: var StateCache):
uint64 =
@ -82,7 +82,16 @@ func get_validator_churn_limit*(
count_active_validators(
state, state.get_current_epoch(), cache) div cfg.CHURN_LIMIT_QUOTIENT)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#initiate_validator_exit
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/beacon-chain.md#new-get_validator_activation_churn_limit
func get_validator_activation_churn_limit*(
cfg: RuntimeConfig, state: deneb.BeaconState, cache: var StateCache):
uint64 =
## Return the validator activation churn limit for the current epoch.
min(
cfg.MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT,
get_validator_churn_limit(cfg, state, cache))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#initiate_validator_exit
func initiate_validator_exit*(
cfg: RuntimeConfig, state: var ForkyBeaconState,
index: ValidatorIndex, cache: var StateCache): Result[void, cstring] =
@ -134,8 +143,8 @@ func initiate_validator_exit*(
from ./datatypes/deneb import BeaconState
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#modified-slash_validator
func get_slashing_penalty*(state: ForkyBeaconState,
validator_effective_balance: Gwei): Gwei =
# TODO Consider whether this is better than splitting the functions apart; in
@ -150,15 +159,15 @@ func get_slashing_penalty*(state: ForkyBeaconState,
else:
{.fatal: "invalid BeaconState type".}
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#modified-slash_validator
func get_whistleblower_reward*(validator_effective_balance: Gwei): Gwei =
validator_effective_balance div WHISTLEBLOWER_REWARD_QUOTIENT
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#modified-slash_validator
func get_proposer_reward(state: ForkyBeaconState, whistleblower_reward: Gwei): Gwei =
when state is phase0.BeaconState:
whistleblower_reward div PROPOSER_REWARD_QUOTIENT
@ -168,9 +177,9 @@ func get_proposer_reward(state: ForkyBeaconState, whistleblower_reward: Gwei): G
else:
{.fatal: "invalid BeaconState type".}
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-slash_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#modified-slash_validator
proc slash_validator*(
cfg: RuntimeConfig, state: var ForkyBeaconState,
slashed_index: ValidatorIndex, cache: var StateCache):
@ -222,7 +231,7 @@ proc slash_validator*(
func genesis_time_from_eth1_timestamp*(cfg: RuntimeConfig, eth1_timestamp: uint64): uint64 =
eth1_timestamp + cfg.GENESIS_DELAY
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#genesis-block
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#genesis-block
func get_initial_beacon_block*(state: phase0.HashedBeaconState):
phase0.TrustedSignedBeaconBlock =
# The genesis block is implicitly trusted
@ -246,7 +255,7 @@ func get_initial_beacon_block*(state: altair.HashedBeaconState):
altair.TrustedSignedBeaconBlock(
message: message, root: hash_tree_root(message))
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/beacon-chain.md#testing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#testing
func get_initial_beacon_block*(state: bellatrix.HashedBeaconState):
bellatrix.TrustedSignedBeaconBlock =
# The genesis block is implicitly trusted
@ -287,7 +296,7 @@ func get_initial_beacon_block*(state: ForkedHashedBeaconState):
withState(state):
ForkedTrustedSignedBeaconBlock.init(get_initial_beacon_block(forkyState))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_block_root_at_slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_block_root_at_slot
func get_block_root_at_slot*(state: ForkyBeaconState, slot: Slot): Eth2Digest =
## Return the block root at a recent ``slot``.
@ -305,7 +314,7 @@ func get_block_root_at_slot*(
withState(state):
get_block_root_at_slot(forkyState.data, slot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_block_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_block_root
func get_block_root*(state: ForkyBeaconState, epoch: Epoch): Eth2Digest =
## Return the block root at the start of a recent ``epoch``.
get_block_root_at_slot(state, epoch.start_slot())
@ -380,7 +389,7 @@ proc is_valid_indexed_attestation*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_attesting_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_attesting_indices
iterator get_attesting_indices_iter*(state: ForkyBeaconState,
data: AttestationData,
bits: CommitteeValidatorsBits,
@ -401,7 +410,7 @@ iterator get_attesting_indices_iter*(state: ForkyBeaconState,
if bits[index_in_committee]:
yield validator_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_attesting_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_attesting_indices
func get_attesting_indices*(state: ForkyBeaconState,
data: AttestationData,
bits: CommitteeValidatorsBits,
@ -454,7 +463,7 @@ proc is_valid_indexed_attestation*(
# Attestation validation
# ------------------------------------------------------------------------------------------
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attestations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attestations
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/p2p-interface.md#beacon_attestation_subnet_id
func check_attestation_slot_target*(data: AttestationData): Result[Slot, cstring] =
@ -471,8 +480,8 @@ func check_attestation_target_epoch(
ok(data.target.epoch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attestations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#modified-process_attestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attestations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-process_attestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#modified-process_attestation
func check_attestation_inclusion(
consensusFork: static ConsensusFork, attestation_slot: Slot,
@ -502,7 +511,7 @@ func check_attestation_index*(
Result[CommitteeIndex, cstring] =
check_attestation_index(data.index, committees_per_slot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_attestation_participation_flag_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_attestation_participation_flag_indices
func get_attestation_participation_flag_indices(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState,
data: AttestationData, inclusion_delay: uint64): set[TimelyFlag] =
@ -574,7 +583,7 @@ func get_attestation_participation_flag_indices(
# TODO these duplicate some stuff in state_transition_epoch which uses TotalBalances
# better to centralize around that if feasible
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_total_active_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_total_active_balance
func get_total_active_balance*(state: ForkyBeaconState, cache: var StateCache): Gwei =
## Return the combined effective balance of the active validators.
## Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei
@ -590,7 +599,7 @@ func get_total_active_balance*(state: ForkyBeaconState, cache: var StateCache):
cache.total_active_balance[epoch] = tab
return tab
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_base_reward_per_increment
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_base_reward_per_increment
func get_base_reward_per_increment_sqrt*(
total_active_balance_sqrt: uint64): Gwei =
EFFECTIVE_BALANCE_INCREMENT * BASE_REWARD_FACTOR div total_active_balance_sqrt
@ -599,7 +608,7 @@ func get_base_reward_per_increment*(
total_active_balance: Gwei): Gwei =
get_base_reward_per_increment_sqrt(integer_squareroot(total_active_balance))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_base_reward
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_base_reward
func get_base_reward(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState |
deneb.BeaconState,
@ -610,7 +619,7 @@ func get_base_reward(
state.validators[index].effective_balance div EFFECTIVE_BALANCE_INCREMENT
increments * base_reward_per_increment
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attestations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attestations
proc check_attestation*(
state: ForkyBeaconState, attestation: SomeAttestation, flags: UpdateFlags,
cache: var StateCache): Result[void, cstring] =
@ -645,7 +654,7 @@ proc check_attestation*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#new-process_bls_to_execution_change
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#new-process_bls_to_execution_change
proc check_bls_to_execution_change*(
genesisFork: Fork, state: capella.BeaconState | deneb.BeaconState,
signed_address_change: SignedBLSToExecutionChange, flags: UpdateFlags):
@ -751,7 +760,7 @@ proc process_attestation*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_next_sync_committee_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_next_sync_committee_indices
func get_next_sync_committee_keys(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState |
deneb.BeaconState):
@ -789,12 +798,12 @@ func get_next_sync_committee_keys(
i += 1'u64
res
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#has_eth1_withdrawal_credential
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#has_eth1_withdrawal_credential
func has_eth1_withdrawal_credential*(validator: Validator): bool =
## Check if ``validator`` has an 0x01 prefixed "eth1" withdrawal credential.
validator.withdrawal_credentials.data[0] == ETH1_ADDRESS_WITHDRAWAL_PREFIX
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#is_fully_withdrawable_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#is_fully_withdrawable_validator
func is_fully_withdrawable_validator(
validator: Validator, balance: Gwei, epoch: Epoch): bool =
## Check if ``validator`` is fully withdrawable.
@ -812,7 +821,7 @@ func is_partially_withdrawable_validator(
has_eth1_withdrawal_credential(validator) and
has_max_effective_balance and has_excess_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#new-get_expected_withdrawals
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#new-get_expected_withdrawals
func get_expected_withdrawals*(
state: capella.BeaconState | deneb.BeaconState): seq[Withdrawal] =
let
@ -848,7 +857,7 @@ func get_expected_withdrawals*(
validator_index = (validator_index + 1) mod num_validators
withdrawals
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_next_sync_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_next_sync_committee
func get_next_sync_committee*(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState |
deneb.BeaconState):

View File

@ -98,7 +98,7 @@ export
# API
# ----------------------------------------------------------------------
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#bls-signatures
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#bls-signatures
func toPubKey*(privkey: ValidatorPrivKey): CookedPubKey =
## Derive a public key from a private key
@ -206,7 +206,7 @@ func finish*(agg: AggregateSignature): CookedSig {.inline.} =
sig.finish(agg)
CookedSig(sig)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#bls-signatures
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#bls-signatures
func blsVerify*(
pubkey: CookedPubKey, message: openArray[byte],
signature: CookedSig): bool =
@ -219,7 +219,7 @@ func blsVerify*(
## to enforce correct usage.
PublicKey(pubkey).verify(message, blscurve.Signature(signature))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#bls-signatures
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#bls-signatures
proc blsVerify*(
pubkey: ValidatorPubKey, message: openArray[byte],
signature: CookedSig): bool =

View File

@ -40,7 +40,7 @@ static:
doAssert ord(TIMELY_HEAD_FLAG_INDEX) == 2
const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/altair/beacon-chain.md#incentivization-weights
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#incentivization-weights
TIMELY_SOURCE_WEIGHT* = 14
TIMELY_TARGET_WEIGHT* = 26
TIMELY_HEAD_WEIGHT* = 14
@ -55,17 +55,17 @@ const
TARGET_AGGREGATORS_PER_SYNC_SUBCOMMITTEE* = 16
SYNC_COMMITTEE_SUBNET_COUNT* = 4
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#constants
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#constants
# All of these indices are rooted in `BeaconState`.
# The first member (`genesis_time`) is 32, subsequent members +1 each.
# If there are ever more than 32 members in `BeaconState`, indices change!
# `FINALIZED_ROOT_INDEX` is one layer deeper, i.e., `52 * 2 + 1`.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/ssz/merkle-proofs.md
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/ssz/merkle-proofs.md
FINALIZED_ROOT_INDEX* = 105.GeneralizedIndex # `finalized_checkpoint` > `root`
CURRENT_SYNC_COMMITTEE_INDEX* = 54.GeneralizedIndex # `current_sync_committee`
NEXT_SYNC_COMMITTEE_INDEX* = 55.GeneralizedIndex # `next_sync_committee`
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/altair/beacon-chain.md#inactivity-penalties
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#inactivity-penalties
INACTIVITY_SCORE_BIAS* = 4
INACTIVITY_SCORE_RECOVERY_RATE* = 16
@ -88,7 +88,7 @@ type
## effectively making the cost of clearing the cache higher than the typical
## gains
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#syncaggregate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#syncaggregate
SyncAggregate* = object
sync_committee_bits*: BitArray[SYNC_COMMITTEE_SIZE]
sync_committee_signature*: ValidatorSig
@ -97,7 +97,7 @@ type
sync_committee_bits*: BitArray[SYNC_COMMITTEE_SIZE]
sync_committee_signature*: TrustedSig
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#synccommittee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#synccommittee
SyncCommittee* = object
pubkeys*: HashArray[Limit SYNC_COMMITTEE_SIZE, ValidatorPubKey]
aggregate_pubkey*: ValidatorPubKey
@ -165,12 +165,12 @@ type
NextSyncCommitteeBranch* =
array[log2trunc(NEXT_SYNC_COMMITTEE_INDEX), Eth2Digest]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientheader
LightClientHeader* = object
beacon*: BeaconBlockHeader
## Beacon block header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
LightClientBootstrap* = object
header*: LightClientHeader
## Header matching the requested beacon block root
@ -179,7 +179,7 @@ type
## Current sync committee corresponding to `header.beacon.state_root`
current_sync_committee_branch*: CurrentSyncCommitteeBranch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientupdate
LightClientUpdate* = object
attested_header*: LightClientHeader
## Header attested to by the sync committee
@ -198,7 +198,7 @@ type
signature_slot*: Slot
## Slot at which the aggregate signature was created (untrusted)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
LightClientFinalityUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -212,7 +212,7 @@ type
# Slot at which the aggregate signature was created (untrusted)
signature_slot*: Slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
LightClientOptimisticUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -238,7 +238,7 @@ type
LightClientBootstrap |
SomeLightClientUpdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientstore
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientstore
LightClientStore* = object
finalized_header*: LightClientHeader
## Header that is finalized
@ -347,7 +347,7 @@ type
data*: BeaconState
root*: Eth2Digest # hash_tree_root(data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblock
BeaconBlock* = object
## For each slot, a proposer is chosen from the validator pool to propose
## a new block. Once the block as been proposed, it is transmitted to
@ -404,7 +404,7 @@ type
state_root*: Eth2Digest
body*: TrustedBeaconBlockBody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#beaconblockbody
BeaconBlockBody* = object
randao_reveal*: ValidatorSig
eth1_data*: Eth1Data
@ -481,7 +481,7 @@ type
# [New in Altair]
sync_aggregate*: TrustedSyncAggregate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signedbeaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedbeaconblock
SignedBeaconBlock* = object
message*: BeaconBlock
signature*: ValidatorSig
@ -659,7 +659,7 @@ chronicles.formatIt SyncCommitteeContribution: shortLog(it)
chronicles.formatIt ContributionAndProof: shortLog(it)
chronicles.formatIt SignedContributionAndProof: shortLog(it)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_valid_light_client_header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_valid_light_client_header
func is_valid_light_client_header*(
header: LightClientHeader, cfg: RuntimeConfig): bool =
true

View File

@ -74,7 +74,7 @@ export
tables, results, json_serialization, timer, sszTypes, beacon_time, crypto,
digest, presets
const SPEC_VERSION* = "1.4.0-beta.1"
const SPEC_VERSION* = "1.4.0-beta.2-hotfix"
## Spec version we're aiming to be compatible with, right now
const
@ -146,7 +146,7 @@ template ethAmountUnit*(typ: type) {.dirty.} =
ethAmountUnit Ether
type
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#custom-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#custom-types
Eth2Domain* = array[32, byte]
ValidatorIndex* = distinct uint32
@ -191,7 +191,7 @@ type
# SSZ / hashing purposes
JustificationBits* = distinct uint8
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#proposerslashing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#proposerslashing
ProposerSlashing* = object
signed_header_1*: SignedBeaconBlockHeader
signed_header_2*: SignedBeaconBlockHeader
@ -203,7 +203,7 @@ type
signed_header_1*: TrustedSignedBeaconBlockHeader
signed_header_2*: TrustedSignedBeaconBlockHeader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attesterslashing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attesterslashing
AttesterSlashing* = object
attestation_1*: IndexedAttestation
attestation_2*: IndexedAttestation
@ -215,7 +215,7 @@ type
attestation_1*: TrustedIndexedAttestation
attestation_2*: TrustedIndexedAttestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#indexedattestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#indexedattestation
IndexedAttestation* = object
attesting_indices*: List[uint64, Limit MAX_VALIDATORS_PER_COMMITTEE]
data*: AttestationData
@ -231,7 +231,7 @@ type
CommitteeValidatorsBits* = BitList[Limit MAX_VALIDATORS_PER_COMMITTEE]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attestation
Attestation* = object
aggregation_bits*: CommitteeValidatorsBits
data*: AttestationData
@ -247,17 +247,17 @@ type
ForkDigest* = distinct array[4, byte]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#forkdata
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#forkdata
ForkData* = object
current_version*: Version
genesis_validators_root*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#checkpoint
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#checkpoint
Checkpoint* = object
epoch*: Epoch
root*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#AttestationData
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#AttestationData
AttestationData* = object
slot*: Slot
@ -270,20 +270,20 @@ type
source*: Checkpoint
target*: Checkpoint
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#deposit
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#deposit
Deposit* = object
proof*: array[DEPOSIT_CONTRACT_TREE_DEPTH + 1, Eth2Digest]
## Merkle path to deposit root
data*: DepositData
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#depositmessage
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#depositmessage
DepositMessage* = object
pubkey*: ValidatorPubKey
withdrawal_credentials*: Eth2Digest
amount*: Gwei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#depositdata
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#depositdata
DepositData* = object
pubkey*: ValidatorPubKey
withdrawal_credentials*: Eth2Digest
@ -293,7 +293,7 @@ type
signature*: ValidatorSig
## Signing over DepositMessage
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#voluntaryexit
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#voluntaryexit
VoluntaryExit* = object
epoch*: Epoch
## Earliest epoch when voluntary exit can be processed
@ -321,7 +321,7 @@ type
pubkey*: CookedPubKey
withdrawal_credentials*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#validator
Validator* = object
pubkey*: ValidatorPubKey
@ -352,12 +352,12 @@ type
proposer_index*: uint64 # `ValidatorIndex` after validation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#historicalbatch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#historicalbatch
HistoricalBatch* = object
block_roots* : array[SLOTS_PER_HISTORICAL_ROOT, Eth2Digest]
state_roots* : array[SLOTS_PER_HISTORICAL_ROOT, Eth2Digest]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#fork
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#fork
Fork* = object
previous_version*: Version
current_version*: Version
@ -365,13 +365,13 @@ type
epoch*: Epoch
## Epoch of latest fork
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#eth1data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#eth1data
Eth1Data* = object
deposit_root*: Eth2Digest
deposit_count*: uint64
block_hash*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signedvoluntaryexit
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedvoluntaryexit
SignedVoluntaryExit* = object
message*: VoluntaryExit
signature*: ValidatorSig
@ -380,7 +380,7 @@ type
message*: VoluntaryExit
signature*: TrustedSig
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblockheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblockheader
BeaconBlockHeader* = object
slot*: Slot
proposer_index*: uint64 # `ValidatorIndex` after validation
@ -388,14 +388,14 @@ type
state_root*: Eth2Digest
body_root*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signingdata
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signingdata
SigningData* = object
object_root*: Eth2Digest
domain*: Eth2Domain
GraffitiBytes* = distinct array[MAX_GRAFFITI_SIZE, byte]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signedbeaconblockheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedbeaconblockheader
SignedBeaconBlockHeader* = object
message*: BeaconBlockHeader
signature*: ValidatorSig
@ -428,12 +428,12 @@ type
sync_committees*: Table[SyncCommitteePeriod, SyncCommitteeCache]
# This matches the mutable state of the Solidity deposit contract
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/solidity_deposit_contract/deposit_contract.sol
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/solidity_deposit_contract/deposit_contract.sol
DepositContractState* = object
branch*: array[DEPOSIT_CONTRACT_TREE_DEPTH, Eth2Digest]
deposit_count*: array[32, byte] # Uint256
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#validator
ValidatorStatus* = object
# This is a validator without the expensive, immutable, append-only parts
# serialized. They're represented in memory to allow in-place SSZ reading
@ -459,7 +459,7 @@ type
withdrawable_epoch*: Epoch
## When validator can withdraw funds
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#validator
ValidatorStatusCapella* = object
# This is a validator without the expensive, immutable, append-only parts
# serialized. They're represented in memory to allow in-place SSZ reading

View File

@ -34,7 +34,7 @@ const
NEWPAYLOAD_TIMEOUT* = 8.seconds
type
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#custom-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#custom-types
Transaction* = List[byte, Limit MAX_BYTES_PER_TRANSACTION]
ExecutionAddress* = object
@ -45,7 +45,7 @@ type
PayloadID* = array[8, byte]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#executionpayload
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#executionpayload
ExecutionPayload* = object
# Execution block header fields
parent_hash*: Eth2Digest
@ -73,7 +73,7 @@ type
executionPayload*: ExecutionPayload
blockValue*: Wei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#executionpayloadheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#executionpayloadheader
ExecutionPayloadHeader* = object
# Execution block header fields
parent_hash*: Eth2Digest
@ -103,7 +103,7 @@ type
parent_hash*: Eth2Digest
total_difficulty*: Eth2Digest # uint256
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#beaconstate
BeaconState* = object
# Versioning
genesis_time*: uint64
@ -171,7 +171,7 @@ type
data*: BeaconState
root*: Eth2Digest # hash_tree_root(data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#beaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblock
BeaconBlock* = object
## For each slot, a proposer is chosen from the validator pool to propose
## a new block. Once the block as been proposed, it is transmitted to
@ -228,7 +228,7 @@ type
state_root*: Eth2Digest
body*: TrustedBeaconBlockBody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#beaconblockbody
BeaconBlockBody* = object
randao_reveal*: ValidatorSig
eth1_data*: Eth1Data
@ -306,7 +306,7 @@ type
# Execution
execution_payload*: ExecutionPayload # [New in Bellatrix]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signedbeaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedbeaconblock
SignedBeaconBlock* = object
message*: BeaconBlock
signature*: ValidatorSig

View File

@ -27,43 +27,43 @@ import
export json_serialization, base
const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#constants
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#constants
# This index is rooted in `BeaconBlockBody`.
# The first member (`randao_reveal`) is 16, subsequent members +1 each.
# If there are ever more than 16 members in `BeaconBlockBody`, indices change!
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/ssz/merkle-proofs.md
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/ssz/merkle-proofs.md
EXECUTION_PAYLOAD_INDEX* = 25.GeneralizedIndex # `execution_payload`
type
SignedBLSToExecutionChangeList* =
List[SignedBLSToExecutionChange, Limit MAX_BLS_TO_EXECUTION_CHANGES]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#withdrawal
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#withdrawal
Withdrawal* = object
index*: WithdrawalIndex
validator_index*: uint64
address*: ExecutionAddress
amount*: Gwei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#blstoexecutionchange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#blstoexecutionchange
BLSToExecutionChange* = object
validator_index*: uint64
from_bls_pubkey*: ValidatorPubKey
to_execution_address*: ExecutionAddress
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#signedblstoexecutionchange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#signedblstoexecutionchange
SignedBLSToExecutionChange* = object
message*: BLSToExecutionChange
signature*: ValidatorSig
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#historicalsummary
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#historicalsummary
HistoricalSummary* = object
# `HistoricalSummary` matches the components of the phase0
# `HistoricalBatch` making the two hash_tree_root-compatible.
block_summary_root*: Eth2Digest
state_summary_root*: Eth2Digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#executionpayload
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#executionpayload
ExecutionPayload* = object
# Execution block header fields
parent_hash*: Eth2Digest
@ -93,7 +93,7 @@ type
executionPayload*: ExecutionPayload
blockValue*: Wei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#executionpayloadheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#executionpayloadheader
ExecutionPayloadHeader* = object
# Execution block header fields
parent_hash*: Eth2Digest
@ -122,7 +122,7 @@ type
ExecutionBranch* =
array[log2trunc(EXECUTION_PAYLOAD_INDEX), Eth2Digest]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
LightClientHeader* = object
beacon*: BeaconBlockHeader
## Beacon block header
@ -131,7 +131,7 @@ type
## Execution payload header corresponding to `beacon.body_root` (from Capella onward)
execution_branch*: ExecutionBranch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
LightClientBootstrap* = object
header*: LightClientHeader
## Header matching the requested beacon block root
@ -140,7 +140,7 @@ type
## Current sync committee corresponding to `header.beacon.state_root`
current_sync_committee_branch*: altair.CurrentSyncCommitteeBranch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientupdate
LightClientUpdate* = object
attested_header*: LightClientHeader
## Header attested to by the sync committee
@ -159,7 +159,7 @@ type
signature_slot*: Slot
## Slot at which the aggregate signature was created (untrusted)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
LightClientFinalityUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -173,7 +173,7 @@ type
# Slot at which the aggregate signature was created (untrusted)
signature_slot*: Slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
LightClientOptimisticUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -199,7 +199,7 @@ type
LightClientBootstrap |
SomeLightClientUpdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientstore
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientstore
LightClientStore* = object
finalized_header*: LightClientHeader
## Header that is finalized
@ -220,7 +220,7 @@ type
## (used to compute safety threshold)
current_max_active_participants*: uint64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconstate
BeaconState* = object
# Versioning
genesis_time*: uint64
@ -299,7 +299,7 @@ type
data*: BeaconState
root*: Eth2Digest # hash_tree_root(data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblock
BeaconBlock* = object
## For each slot, a proposer is chosen from the validator pool to propose
## a new block. Once the block as been proposed, it is transmitted to
@ -356,7 +356,7 @@ type
state_root*: Eth2Digest
body*: TrustedBeaconBlockBody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconblockbody
BeaconBlockBody* = object
randao_reveal*: ValidatorSig
eth1_data*: Eth1Data
@ -650,7 +650,7 @@ func shortLog*(v: SignedBLSToExecutionChange): auto =
signature: shortLog(v.signature)
)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#get_lc_execution_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#get_lc_execution_root
func get_lc_execution_root*(
header: LightClientHeader, cfg: RuntimeConfig): Eth2Digest =
let epoch = header.beacon.slot.epoch
@ -660,7 +660,7 @@ func get_lc_execution_root*(
ZERO_HASH
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-is_valid_light_client_header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#modified-is_valid_light_client_header
func is_valid_light_client_header*(
header: LightClientHeader, cfg: RuntimeConfig): bool =
let epoch = header.beacon.slot.epoch
@ -677,13 +677,13 @@ func is_valid_light_client_header*(
get_subtree_index(EXECUTION_PAYLOAD_INDEX),
header.beacon.body_root)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_header_to_capella*(
pre: altair.LightClientHeader): LightClientHeader =
LightClientHeader(
beacon: pre.beacon)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_bootstrap_to_capella*(
pre: altair.LightClientBootstrap): LightClientBootstrap =
LightClientBootstrap(
@ -691,7 +691,7 @@ func upgrade_lc_bootstrap_to_capella*(
current_sync_committee: pre.current_sync_committee,
current_sync_committee_branch: pre.current_sync_committee_branch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_update_to_capella*(
pre: altair.LightClientUpdate): LightClientUpdate =
LightClientUpdate(
@ -703,7 +703,7 @@ func upgrade_lc_update_to_capella*(
sync_aggregate: pre.sync_aggregate,
signature_slot: pre.signature_slot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_finality_update_to_capella*(
pre: altair.LightClientFinalityUpdate): LightClientFinalityUpdate =
LightClientFinalityUpdate(
@ -713,7 +713,7 @@ func upgrade_lc_finality_update_to_capella*(
sync_aggregate: pre.sync_aggregate,
signature_slot: pre.signature_slot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_optimistic_update_to_capella*(
pre: altair.LightClientOptimisticUpdate): LightClientOptimisticUpdate =
LightClientOptimisticUpdate(
@ -764,7 +764,7 @@ chronicles.formatIt LightClientUpdate: shortLog(it)
chronicles.formatIt LightClientFinalityUpdate: shortLog(it)
chronicles.formatIt LightClientOptimisticUpdate: shortLog(it)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/fork.md#upgrading-the-store
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/fork.md#upgrading-the-store
func upgrade_lc_store_to_capella*(
pre: altair.LightClientStore): LightClientStore =
let best_valid_update =

View File

@ -36,7 +36,7 @@ const
FAR_FUTURE_EPOCH* = Epoch(not 0'u64)
FAR_FUTURE_PERIOD* = SyncCommitteePeriod(not 0'u64)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#domain-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#domain-types
DOMAIN_BEACON_PROPOSER* = DomainType([byte 0x00, 0x00, 0x00, 0x00])
DOMAIN_BEACON_ATTESTER* = DomainType([byte 0x01, 0x00, 0x00, 0x00])
DOMAIN_RANDAO* = DomainType([byte 0x02, 0x00, 0x00, 0x00])
@ -46,12 +46,12 @@ const
DOMAIN_AGGREGATE_AND_PROOF* = DomainType([byte 0x06, 0x00, 0x00, 0x00])
DOMAIN_APPLICATION_MASK* = DomainType([byte 0x00, 0x00, 0x00, 0x01])
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/altair/beacon-chain.md#domain-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#domain-types
DOMAIN_SYNC_COMMITTEE* = DomainType([byte 0x07, 0x00, 0x00, 0x00])
DOMAIN_SYNC_COMMITTEE_SELECTION_PROOF* = DomainType([byte 0x08, 0x00, 0x00, 0x00])
DOMAIN_CONTRIBUTION_AND_PROOF* = DomainType([byte 0x09, 0x00, 0x00, 0x00])
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#domain-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#domain-types
DOMAIN_BLS_TO_EXECUTION_CHANGE* = DomainType([byte 0x0a, 0x00, 0x00, 0x00])
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#domain-types
@ -60,16 +60,18 @@ const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/fork-choice.md#configuration
PROPOSER_SCORE_BOOST*: uint64 = 40
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#configuration
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#configuration
BLOB_SIDECAR_SUBNET_COUNT*: uint64 = 6
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/p2p-interface.md#configuration
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#configuration
MAX_REQUEST_BLOCKS* = 1024'u64
RESP_TIMEOUT* = 10
RESP_TIMEOUT* = 10'u64
ATTESTATION_PROPAGATION_SLOT_RANGE*: uint64 = 32
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/p2p-interface.md#configuration
GOSSIP_MAX_SIZE* = 10'u64 * 1024 * 1024 # bytes
MAX_CHUNK_SIZE* = 10'u64 * 1024 * 1024 # bytes
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#configuration
MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS* = 4096'u64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#configuration
MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS*: uint64 = 4096
MAX_REQUEST_BLOCKS_DENEB*: uint64 = 128 # TODO Make use of in request code

View File

@ -30,7 +30,7 @@ from kzg4844 import KzgCommitment, KzgProof
export json_serialization, base, kzg4844
const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/polynomial-commitments.md#constants
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/polynomial-commitments.md#constants
BYTES_PER_FIELD_ELEMENT = 32
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#blob
@ -50,7 +50,7 @@ type
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#custom-types
BlobIndex* = uint64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/polynomial-commitments.md#custom-types
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/polynomial-commitments.md#custom-types
Blob* = array[BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB, byte]
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/deneb/p2p-interface.md#blobsidecar
@ -67,7 +67,7 @@ type
kzg_proof*: KzgProof
## Allows for quick verification of kzg_commitment
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#signedblobsidecar
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#signedblobsidecar
SignedBlobSidecar* = object
message*: BlobSidecar
signature*: ValidatorSig
@ -110,7 +110,7 @@ type
proofs*:seq[KZGProof]
blobs*: Blobs
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/deneb/beacon-chain.md#executionpayloadheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#executionpayloadheader
ExecutionPayloadHeader* = object
# Execution block header fields
parent_hash*: Eth2Digest
@ -131,13 +131,13 @@ type
## Hash of execution block
transactions_root*: Eth2Digest
withdrawals_root*: Eth2Digest
blob_gas_used*: uint64 # [New in Deneb]
excess_blob_gas*: uint64 # [New in Deneb]
blob_gas_used*: uint64 # [New in Deneb:EIP4844]
excess_blob_gas*: uint64 # [New in Deneb:EIP4844]
ExecutePayload* = proc(
execution_payload: ExecutionPayload): bool {.gcsafe, raises: [].}
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/sync-protocol.md#modified-lightclientheader
LightClientHeader* = object
beacon*: BeaconBlockHeader
## Beacon block header
@ -146,7 +146,7 @@ type
## Execution payload header corresponding to `beacon.body_root` (from Capella onward)
execution_branch*: capella.ExecutionBranch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientbootstrap
LightClientBootstrap* = object
header*: LightClientHeader
## Header matching the requested beacon block root
@ -155,7 +155,7 @@ type
## Current sync committee corresponding to `header.beacon.state_root`
current_sync_committee_branch*: altair.CurrentSyncCommitteeBranch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientupdate
LightClientUpdate* = object
attested_header*: LightClientHeader
## Header attested to by the sync committee
@ -174,7 +174,7 @@ type
signature_slot*: Slot
## Slot at which the aggregate signature was created (untrusted)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientfinalityupdate
LightClientFinalityUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -188,7 +188,7 @@ type
# Slot at which the aggregate signature was created (untrusted)
signature_slot*: Slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientoptimisticupdate
LightClientOptimisticUpdate* = object
# Header attested to by the sync committee
attested_header*: LightClientHeader
@ -214,7 +214,7 @@ type
LightClientBootstrap |
SomeLightClientUpdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#lightclientstore
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#lightclientstore
LightClientStore* = object
finalized_header*: LightClientHeader
## Header that is finalized
@ -235,7 +235,7 @@ type
## (used to compute safety threshold)
current_max_active_participants*: uint64
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/capella/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconstate
# changes indirectly via ExecutionPayloadHeader
BeaconState* = object
# Versioning
@ -313,7 +313,7 @@ type
data*: BeaconState
root*: Eth2Digest # hash_tree_root(data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblock
BeaconBlock* = object
## For each slot, a proposer is chosen from the validator pool to propose
## a new block. Once the block as been proposed, it is transmitted to
@ -370,7 +370,7 @@ type
state_root*: Eth2Digest
body*: TrustedBeaconBlockBody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.1/specs/deneb/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#beaconblockbody
BeaconBlockBody* = object
randao_reveal*: ValidatorSig
eth1_data*: Eth1Data
@ -451,7 +451,7 @@ type
bls_to_execution_changes*: SignedBLSToExecutionChangeList
blob_kzg_commitments*: KzgCommitments # [New in Deneb]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#signedbeaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedbeaconblock
SignedBeaconBlock* = object
message*: BeaconBlock
signature*: ValidatorSig
@ -575,7 +575,7 @@ func shortLog*(v: ExecutionPayload): auto =
func shortLog*(x: seq[BlobIdentifier]): string =
"[" & x.mapIt(shortLog(it.block_root) & "/" & $it.index).join(", ") & "]"
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/sync-protocol.md#modified-get_lc_execution_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/sync-protocol.md#modified-get_lc_execution_root
func get_lc_execution_root*(
header: LightClientHeader, cfg: RuntimeConfig): Eth2Digest =
let epoch = header.beacon.slot.epoch
@ -604,7 +604,7 @@ func get_lc_execution_root*(
ZERO_HASH
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/sync-protocol.md#modified-is_valid_light_client_header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/sync-protocol.md#modified-is_valid_light_client_header
func is_valid_light_client_header*(
header: LightClientHeader, cfg: RuntimeConfig): bool =
let epoch = header.beacon.slot.epoch
@ -626,7 +626,7 @@ func is_valid_light_client_header*(
get_subtree_index(EXECUTION_PAYLOAD_INDEX),
header.beacon.body_root)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_header_to_deneb*(
pre: capella.LightClientHeader): LightClientHeader =
LightClientHeader(
@ -651,7 +651,7 @@ func upgrade_lc_header_to_deneb*(
excess_blob_gas: 0), # [New in Deneb:EIP4844]
execution_branch: pre.execution_branch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_bootstrap_to_deneb*(
pre: capella.LightClientBootstrap): LightClientBootstrap =
LightClientBootstrap(
@ -659,7 +659,7 @@ func upgrade_lc_bootstrap_to_deneb*(
current_sync_committee: pre.current_sync_committee,
current_sync_committee_branch: pre.current_sync_committee_branch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_update_to_deneb*(
pre: capella.LightClientUpdate): LightClientUpdate =
LightClientUpdate(
@ -671,7 +671,7 @@ func upgrade_lc_update_to_deneb*(
sync_aggregate: pre.sync_aggregate,
signature_slot: pre.signature_slot)
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/deneb/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_finality_update_to_deneb*(
pre: capella.LightClientFinalityUpdate): LightClientFinalityUpdate =
LightClientFinalityUpdate(
@ -681,7 +681,7 @@ func upgrade_lc_finality_update_to_deneb*(
sync_aggregate: pre.sync_aggregate,
signature_slot: pre.signature_slot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/fork.md#upgrading-light-client-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-light-client-data
func upgrade_lc_optimistic_update_to_deneb*(
pre: capella.LightClientOptimisticUpdate): LightClientOptimisticUpdate =
LightClientOptimisticUpdate(
@ -732,7 +732,7 @@ chronicles.formatIt LightClientUpdate: shortLog(it)
chronicles.formatIt LightClientFinalityUpdate: shortLog(it)
chronicles.formatIt LightClientOptimisticUpdate: shortLog(it)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/light-client/fork.md#upgrading-the-store
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/light-client/fork.md#upgrading-the-store
func upgrade_lc_store_to_deneb*(
pre: capella.LightClientStore): LightClientStore =
let best_valid_update =

View File

@ -22,7 +22,7 @@ import
export base
type
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#beaconstate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconstate
BeaconState* = object
# Versioning
genesis_time*: uint64
@ -111,7 +111,7 @@ type
data*: BeaconState
root*: Eth2Digest # hash_tree_root(data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblock
BeaconBlock* = object
## For each slot, a proposer is chosen from the validator pool to propose
## a new block. Once the block as been proposed, it is transmitted to
@ -167,7 +167,7 @@ type
state_root*: Eth2Digest
body*: TrustedBeaconBlockBody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beaconblockbody
BeaconBlockBody* = object
randao_reveal*: ValidatorSig
eth1_data*: Eth1Data
@ -219,7 +219,7 @@ type
deposits*: List[Deposit, Limit MAX_DEPOSITS]
voluntary_exits*: List[TrustedSignedVoluntaryExit, Limit MAX_VOLUNTARY_EXITS]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#signedbeaconblock
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#signedbeaconblock
SignedBeaconBlock* = object
message*: BeaconBlock
signature*: ValidatorSig

View File

@ -7,7 +7,7 @@
# Consensus hash function / digest
#
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#hash
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#hash
#
# In Phase 0 the beacon chain is deployed with SHA256 (SHA2-256).
# Note that is is different from Keccak256 (often mistakenly called SHA3-256)

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
import std/[typetraits, strutils]
import stew/[assign2, results, base10, byteutils], presto/common,
import stew/[assign2, results, base10, byteutils, endians2], presto/common,
libp2p/peerid, serialization, json_serialization,
json_serialization/std/[options, net, sets],
chronicles
@ -278,7 +278,7 @@ proc jsonResponseBlock*(t: typedesc[RestApiResponse],
if execOpt.isSome():
writer.writeField("execution_optimistic", execOpt.get())
withBlck(data):
writer.writeField("data", blck)
writer.writeField("data", forkyBlck)
writer.endRecord()
stream.getOutput(seq[byte])
except SerializationError:
@ -1887,7 +1887,7 @@ proc readValue*(reader: var JsonReader[RestJson],
reader.raiseUnexpectedValue("Incorrect deneb block format")
value = ForkedSignedBeaconBlock.init(res.get())
withBlck(value):
blck.root = hash_tree_root(blck.message)
forkyBlck.root = hash_tree_root(forkyBlck.message)
proc writeValue*(
writer: var JsonWriter[RestJson], value: ForkedSignedBeaconBlock
@ -3320,10 +3320,10 @@ func readSszResBytes(T: typedesc[RestBlockTypes],
try:
readSszBytes(data, res)
ok(res)
except MalformedSszError as exc:
err("Invalid SSZ object")
except SszSizeMismatchError:
err("Incorrect SSZ object's size")
except SszError:
err("Invalid SSZ object")
proc decodeBytes*[T: DecodeConsensysTypes](
t: typedesc[T],

View File

@ -8,7 +8,7 @@
import
chronos,
stew/results,
stew/[results, endians2],
presto/client,
../helpers,
"."/[rest_common, eth2_rest_serialization]

View File

@ -574,7 +574,7 @@ type
extra_data*: Option[RestNodeExtraData]
RestExtraData* = object
discard
version*: Option[string]
GetForkChoiceResponse* = object
justified_checkpoint*: Checkpoint
@ -627,7 +627,7 @@ func init*(t: typedesc[ValidatorIdent], v: ValidatorPubKey): ValidatorIdent =
func init*(t: typedesc[RestBlockInfo],
v: ForkedTrustedSignedBeaconBlock): RestBlockInfo =
withBlck(v):
RestBlockInfo(slot: blck.message.slot, blck: blck.root)
RestBlockInfo(slot: forkyBlck.message.slot, blck: forkyBlck.root)
func init*(t: typedesc[RestValidator], index: ValidatorIndex,
balance: uint64, status: string,

View File

@ -10,6 +10,7 @@
# Import this module to get access to `hash_tree_root` for spec types
import
stew/endians2,
ssz_serialization/[merkleization, proofs],
./ssz_codec

View File

@ -20,8 +20,9 @@ from ./datatypes/deneb import SignedBeaconBlock, TrustedSignedBeaconBlock
export phase0, altair, ssz_codec, ssz_serialization, eth2_merkleization
proc readAndUpdateRoot(data: openArray[byte], val: var auto, updateRoot = true) {.
raises: [MalformedSszError, SszSizeMismatchError].} =
proc readAndUpdateRoot(
data: openArray[byte], val: var auto, updateRoot = true
) {.raises: [SszError].} =
readSszValue(data, val)
if updateRoot:
val.root = hash_tree_root(val.message)
@ -64,8 +65,9 @@ template readSszBytes*(
data: openArray[byte], val: var auto, updateRoot: bool) =
readSszValue(data, val)
func readSszBytes(T: type, data: openArray[byte], updateRoot = true): T {.
raises: [MalformedSszError, SszSizeMismatchError].} =
func readSszBytes(
T: type, data: openArray[byte], updateRoot = true
): T {.raises: [SszError].} =
var res: T
readSszBytes(data, res, updateRoot)
res

View File

@ -766,30 +766,30 @@ template withBlck*(
case x.kind
of ConsensusFork.Phase0:
const consensusFork {.inject, used.} = ConsensusFork.Phase0
template blck: untyped {.inject.} = x.phase0Data
template forkyBlck: untyped {.inject.} = x.phase0Data
body
of ConsensusFork.Altair:
const consensusFork {.inject, used.} = ConsensusFork.Altair
template blck: untyped {.inject.} = x.altairData
template forkyBlck: untyped {.inject.} = x.altairData
body
of ConsensusFork.Bellatrix:
const consensusFork {.inject, used.} = ConsensusFork.Bellatrix
template blck: untyped {.inject.} = x.bellatrixData
template forkyBlck: untyped {.inject.} = x.bellatrixData
body
of ConsensusFork.Capella:
const consensusFork {.inject, used.} = ConsensusFork.Capella
template blck: untyped {.inject.} = x.capellaData
template forkyBlck: untyped {.inject.} = x.capellaData
body
of ConsensusFork.Deneb:
const consensusFork {.inject, used.} = ConsensusFork.Deneb
template blck: untyped {.inject.} = x.denebData
template forkyBlck: untyped {.inject.} = x.denebData
body
func proposer_index*(x: ForkedBeaconBlock): uint64 =
withBlck(x): blck.proposer_index
withBlck(x): forkyBlck.proposer_index
func hash_tree_root*(x: ForkedBeaconBlock): Eth2Digest =
withBlck(x): hash_tree_root(blck)
withBlck(x): hash_tree_root(forkyBlck)
func hash_tree_root*(x: Web3SignerForkedBeaconBlock): Eth2Digest =
hash_tree_root(x.data)
@ -810,29 +810,29 @@ template getForkedBlockField*(
template signature*(x: ForkedSignedBeaconBlock |
ForkedMsgTrustedSignedBeaconBlock |
ForkedSignedBlindedBeaconBlock): ValidatorSig =
withBlck(x): blck.signature
withBlck(x): forkyBlck.signature
template signature*(x: ForkedTrustedSignedBeaconBlock): TrustedSig =
withBlck(x): blck.signature
withBlck(x): forkyBlck.signature
template root*(x: ForkedSignedBeaconBlock |
ForkedMsgTrustedSignedBeaconBlock |
ForkedTrustedSignedBeaconBlock): Eth2Digest =
withBlck(x): blck.root
withBlck(x): forkyBlck.root
template slot*(x: ForkedSignedBeaconBlock |
ForkedMsgTrustedSignedBeaconBlock |
ForkedTrustedSignedBeaconBlock): Slot =
withBlck(x): blck.message.slot
withBlck(x): forkyBlck.message.slot
template shortLog*(x: ForkedBeaconBlock | ForkedBlindedBeaconBlock): auto =
withBlck(x): shortLog(blck)
withBlck(x): shortLog(forkyBlck)
template shortLog*(x: ForkedSignedBeaconBlock |
ForkedMsgTrustedSignedBeaconBlock |
ForkedTrustedSignedBeaconBlock |
ForkedSignedBlindedBeaconBlock): auto =
withBlck(x): shortLog(blck)
withBlck(x): shortLog(forkyBlck)
chronicles.formatIt ForkedBeaconBlock: it.shortLog
chronicles.formatIt ForkedSignedBeaconBlock: it.shortLog
@ -849,27 +849,27 @@ template withStateAndBlck*(
of ConsensusFork.Deneb:
const consensusFork {.inject.} = ConsensusFork.Deneb
template forkyState: untyped {.inject.} = s.denebData
template blck: untyped {.inject.} = b.denebData
template forkyBlck: untyped {.inject.} = b.denebData
body
of ConsensusFork.Capella:
const consensusFork {.inject.} = ConsensusFork.Capella
template forkyState: untyped {.inject.} = s.capellaData
template blck: untyped {.inject.} = b.capellaData
template forkyBlck: untyped {.inject.} = b.capellaData
body
of ConsensusFork.Bellatrix:
const consensusFork {.inject.} = ConsensusFork.Bellatrix
template forkyState: untyped {.inject.} = s.bellatrixData
template blck: untyped {.inject.} = b.bellatrixData
template forkyBlck: untyped {.inject.} = b.bellatrixData
body
of ConsensusFork.Altair:
const consensusFork {.inject.} = ConsensusFork.Altair
template forkyState: untyped {.inject.} = s.altairData
template blck: untyped {.inject.} = b.altairData
template forkyBlck: untyped {.inject.} = b.altairData
body
of ConsensusFork.Phase0:
const consensusFork {.inject.} = ConsensusFork.Phase0
template forkyState: untyped {.inject.} = s.phase0Data
template blck: untyped {.inject.} = b.phase0Data
template forkyBlck: untyped {.inject.} = b.phase0Data
body
func toBeaconBlockHeader*(
@ -893,7 +893,7 @@ template toBeaconBlockHeader*(
blckParam: ForkedMsgTrustedSignedBeaconBlock |
ForkedTrustedSignedBeaconBlock): BeaconBlockHeader =
## Reduce a given signed beacon block to its `BeaconBlockHeader`.
withBlck(blckParam): blck.toBeaconBlockHeader()
withBlck(blckParam): forkyBlck.toBeaconBlockHeader()
func genesisFork*(cfg: RuntimeConfig): Fork =
Fork(
@ -1036,9 +1036,9 @@ func readSszForkedSignedBeaconBlock*(
kind: cfg.consensusForkAtEpoch(header.slot.epoch()))
withBlck(result):
readSszBytes(data, blck)
readSszBytes(data, forkyBlck)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_fork_data_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_fork_data_root
func compute_fork_data_root*(current_version: Version,
genesis_validators_root: Eth2Digest): Eth2Digest =
## Return the 32-byte fork data root for the ``current_version`` and
@ -1050,7 +1050,7 @@ func compute_fork_data_root*(current_version: Version,
genesis_validators_root: genesis_validators_root
))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_fork_digest
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_fork_digest
func compute_fork_digest*(current_version: Version,
genesis_validators_root: Eth2Digest): ForkDigest =
## Return the 4-byte fork digest for the ``current_version`` and
@ -1087,7 +1087,7 @@ func toBlockId*(blck: SomeForkySignedBeaconBlock): BlockId =
func toBlockId*(blck: ForkedSignedBeaconBlock |
ForkedMsgTrustedSignedBeaconBlock |
ForkedTrustedSignedBeaconBlock): BlockId =
withBlck(blck): BlockId(root: blck.root, slot: blck.message.slot)
withBlck(blck): BlockId(root: forkyBlck.root, slot: forkyBlck.message.slot)
func historical_summaries*(state: ForkedHashedBeaconState):
HashList[HistoricalSummary, Limit HISTORICAL_ROOTS_LIMIT] =

View File

@ -816,7 +816,7 @@ func migratingToDataFork*[
upgradedObject.migrateToDataFork(newKind)
upgradedObject
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/full-node.md#block_to_light_client_header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/full-node.md#block_to_light_client_header
func toAltairLightClientHeader(
blck: # `SomeSignedBeaconBlock` doesn't work here (Nim 1.6)
phase0.SignedBeaconBlock | phase0.TrustedSignedBeaconBlock |
@ -826,7 +826,7 @@ func toAltairLightClientHeader(
altair.LightClientHeader(
beacon: blck.message.toBeaconBlockHeader())
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/light-client/full-node.md#modified-block_to_light_client_header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/light-client/full-node.md#modified-block_to_light_client_header
func toCapellaLightClientHeader(
blck: # `SomeSignedBeaconBlock` doesn't work here (Nim 1.6)
phase0.SignedBeaconBlock | phase0.TrustedSignedBeaconBlock |

View File

@ -26,7 +26,7 @@ export
eth2_merkleization, forks, rlp, ssz_codec
func toEther*(gwei: Gwei): Ether =
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/weak-subjectivity.md#constants
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/weak-subjectivity.md#constants
const ETH_TO_GWEI = 1_000_000_000
(gwei div ETH_TO_GWEI).Ether
@ -49,7 +49,7 @@ func shortLog*(v: FinalityCheckpoints): auto =
chronicles.formatIt FinalityCheckpoints: it.shortLog
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#integer_squareroot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#integer_squareroot
func integer_squareroot*(n: SomeInteger): SomeInteger =
## Return the largest integer ``x`` such that ``x**2 <= n``.
doAssert n >= 0'u64
@ -62,7 +62,7 @@ func integer_squareroot*(n: SomeInteger): SomeInteger =
y = (x + n div x) div 2
x
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#is_active_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#is_active_validator
func is_active_validator*(validator: Validator, epoch: Epoch): bool =
## Check if ``validator`` is active.
validator.activation_epoch <= epoch and epoch < validator.exit_epoch
@ -100,23 +100,23 @@ func get_active_validator_indices_len*(
withState(state):
get_active_validator_indices_len(forkyState.data, epoch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_current_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_current_epoch
func get_current_epoch*(state: ForkyBeaconState): Epoch =
## Return the current epoch.
state.slot.epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_current_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_current_epoch
func get_current_epoch*(state: ForkedHashedBeaconState): Epoch =
## Return the current epoch.
withState(state): get_current_epoch(forkyState.data)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_previous_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_previous_epoch
func get_previous_epoch*(
state: ForkyBeaconState | ForkedHashedBeaconState): Epoch =
## Return the previous epoch (unless the current epoch is ``GENESIS_EPOCH``).
get_previous_epoch(get_current_epoch(state))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_randao_mix
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_randao_mix
func get_randao_mix*(state: ForkyBeaconState, epoch: Epoch): Eth2Digest =
## Return the randao mix at a recent ``epoch``.
state.randao_mixes[epoch mod EPOCHS_PER_HISTORICAL_VECTOR]
@ -138,7 +138,7 @@ func uint_to_bytes*(x: uint32): array[4, byte] = toBytesLE(x)
func uint_to_bytes*(x: uint16): array[2, byte] = toBytesLE(x)
func uint_to_bytes*(x: uint8): array[1, byte] = toBytesLE(x)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_domain
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_domain
func compute_domain*(
domain_type: DomainType,
fork_version: Version,
@ -152,7 +152,7 @@ func compute_domain*(
result[0..3] = domain_type.data
result[4..31] = fork_data_root.data.toOpenArray(0, 27)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_domain
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_domain
func get_domain*(
fork: Fork,
domain_type: DomainType,
@ -173,7 +173,7 @@ func get_domain*(
## of a message.
get_domain(state.fork, domain_type, epoch, state.genesis_validators_root)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_signing_root
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_signing_root
func compute_signing_root*(ssz_object: auto, domain: Eth2Domain): Eth2Digest =
## Return the signing root for the corresponding signing data.
let domain_wrapped_object = SigningData(
@ -182,7 +182,7 @@ func compute_signing_root*(ssz_object: auto, domain: Eth2Domain): Eth2Digest =
)
hash_tree_root(domain_wrapped_object)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_seed
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_seed
func get_seed*(
state: ForkyBeaconState, epoch: Epoch, domain_type: DomainType,
mix: Eth2Digest): Eth2Digest =
@ -201,17 +201,17 @@ func get_seed*(state: ForkyBeaconState, epoch: Epoch, domain_type: DomainType):
epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1)
state.get_seed(epoch, domain_type, mix)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#add_flag
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#add_flag
func add_flag*(flags: ParticipationFlags, flag_index: TimelyFlag): ParticipationFlags =
let flag = ParticipationFlags(1'u8 shl ord(flag_index))
flags or flag
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#has_flag
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#has_flag
func has_flag*(flags: ParticipationFlags, flag_index: TimelyFlag): bool =
let flag = ParticipationFlags(1'u8 shl ord(flag_index))
(flags and flag) == flag
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_sync_committee_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_sync_committee_update
template is_sync_committee_update*(update: SomeForkyLightClientUpdate): bool =
when update is SomeForkyLightClientUpdateWithSyncCommittee:
update.next_sync_committee_branch !=
@ -219,7 +219,7 @@ template is_sync_committee_update*(update: SomeForkyLightClientUpdate): bool =
else:
false
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_finality_update
template is_finality_update*(update: SomeForkyLightClientUpdate): bool =
when update is SomeForkyLightClientUpdateWithFinality:
update.finality_branch !=
@ -227,19 +227,19 @@ template is_finality_update*(update: SomeForkyLightClientUpdate): bool =
else:
false
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_next_sync_committee_known
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_next_sync_committee_known
template is_next_sync_committee_known*(store: ForkyLightClientStore): bool =
store.next_sync_committee !=
static(default(typeof(store.next_sync_committee)))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#get_safety_threshold
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#get_safety_threshold
func get_safety_threshold*(store: ForkyLightClientStore): uint64 =
max(
store.previous_max_active_participants,
store.current_max_active_participants
) div 2
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#is_better_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#is_better_update
type LightClientUpdateMetadata* = object
attested_slot*, finalized_slot*, signature_slot*: Slot
has_sync_committee*, has_finality*: bool
@ -330,24 +330,24 @@ template is_better_update*[
new_update: A, old_update: B): bool =
is_better_data(toMeta(new_update), toMeta(old_update))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
func contextEpoch*(bootstrap: ForkyLightClientBootstrap): Epoch =
bootstrap.header.beacon.slot.epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
func contextEpoch*(update: SomeForkyLightClientUpdate): Epoch =
update.attested_header.beacon.slot.epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#is_merge_transition_complete
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#is_merge_transition_complete
func is_merge_transition_complete*(
state: bellatrix.BeaconState | capella.BeaconState | deneb.BeaconState): bool =
const defaultExecutionPayloadHeader =
default(typeof(state.latest_execution_payload_header))
state.latest_execution_payload_header != defaultExecutionPayloadHeader
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/sync/optimistic.md#helpers
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/sync/optimistic.md#helpers
func is_execution_block*(blck: SomeForkyBeaconBlock): bool =
when typeof(blck).toFork >= ConsensusFork.Bellatrix:
const defaultExecutionPayload =
@ -356,7 +356,7 @@ func is_execution_block*(blck: SomeForkyBeaconBlock): bool =
else:
false
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#is_merge_transition_block
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#is_merge_transition_block
func is_merge_transition_block(
state: bellatrix.BeaconState | capella.BeaconState | deneb.BeaconState,
body: bellatrix.BeaconBlockBody | bellatrix.TrustedBeaconBlockBody |
@ -369,7 +369,7 @@ func is_merge_transition_block(
not is_merge_transition_complete(state) and
body.execution_payload != defaultExecutionPayload
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#is_execution_enabled
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#is_execution_enabled
func is_execution_enabled*(
state: bellatrix.BeaconState | capella.BeaconState | deneb.BeaconState,
body: bellatrix.BeaconBlockBody | bellatrix.TrustedBeaconBlockBody |
@ -380,7 +380,7 @@ func is_execution_enabled*(
deneb.SigVerifiedBeaconBlockBody): bool =
is_merge_transition_block(state, body) or is_merge_transition_complete(state)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#compute_timestamp_at_slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#compute_timestamp_at_slot
func compute_timestamp_at_slot*(state: ForkyBeaconState, slot: Slot): uint64 =
# Note: This function is unsafe with respect to overflows and underflows.
let slots_since_genesis = slot - GENESIS_SLOT

View File

@ -1369,7 +1369,7 @@ func makeWithdrawalCredentials*(k: ValidatorPubKey): Eth2Digest =
bytes.data[0] = BLS_WITHDRAWAL_PREFIX.uint8
bytes
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/deposit-contract.md#withdrawal-credentials
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/deposit-contract.md#withdrawal-credentials
proc makeWithdrawalCredentials*(k: CookedPubKey): Eth2Digest =
makeWithdrawalCredentials(k.toPubKey())

View File

@ -15,7 +15,7 @@ import
from ../consensus_object_pools/block_pools_types import VerifierError
export block_pools_types.VerifierError
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#initialize_light_client_store
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#initialize_light_client_store
func initialize_light_client_store*(
trusted_block_root: Eth2Digest,
bootstrap: ForkyLightClientBootstrap,
@ -42,7 +42,7 @@ func initialize_light_client_store*(
current_sync_committee: bootstrap.current_sync_committee,
optimistic_header: bootstrap.header))
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#validate_light_client_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#validate_light_client_update
proc validate_light_client_update*(
store: ForkyLightClientStore,
update: SomeForkyLightClientUpdate,
@ -158,7 +158,7 @@ proc validate_light_client_update*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#apply_light_client_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#apply_light_client_update
func apply_light_client_update(
store: var ForkyLightClientStore,
update: SomeForkyLightClientUpdate): bool =
@ -189,7 +189,7 @@ func apply_light_client_update(
didProgress = true
didProgress
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_store_force_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_store_force_update
type
ForceUpdateResult* = enum
NoUpdate,
@ -222,7 +222,7 @@ func process_light_client_store_force_update*(
store.best_valid_update.reset()
res
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/sync-protocol.md#process_light_client_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/sync-protocol.md#process_light_client_update
proc process_light_client_update*(
store: var ForkyLightClientStore,
update: SomeForkyLightClientUpdate,

View File

@ -15,7 +15,7 @@ export base
const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/p2p-interface.md#topics-and-messages
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/p2p-interface.md#topics-and-messages
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/p2p-interface.md#topics-and-messages
topicBeaconBlocksSuffix* = "beacon_block/ssz_snappy"
topicVoluntaryExitsSuffix* = "voluntary_exit/ssz_snappy"
topicProposerSlashingsSuffix* = "proposer_slashing/ssz_snappy"
@ -23,16 +23,16 @@ const
topicAggregateAndProofsSuffix* = "beacon_aggregate_and_proof/ssz_snappy"
topicBlsToExecutionChangeSuffix* = "bls_to_execution_change/ssz_snappy"
# The spec now includes this as a bare integer as `RESP_TIMEOUT`
RESP_TIMEOUT_DUR* = RESP_TIMEOUT.seconds
const
# The spec now includes this as a bare uint64 as `RESP_TIMEOUT`
RESP_TIMEOUT_DUR* = RESP_TIMEOUT.int64.seconds
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#configuration
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#configuration
MAX_REQUEST_LIGHT_CLIENT_UPDATES* = 128
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/p2p-interface.md#configuration
MAX_REQUEST_BLOCKS_DENEB* = 128 # TODO Make use of in request code
MAX_REQUEST_BLOB_SIDECARS* = MAX_REQUEST_BLOCKS_DENEB * MAX_BLOBS_PER_BLOCK
# TODO MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/p2p-interface.md#configuration
MAX_REQUEST_BLOB_SIDECARS*: uint64 =
MAX_REQUEST_BLOCKS_DENEB * MAX_BLOBS_PER_BLOCK
defaultEth2TcpPort* = 9000
defaultEth2TcpPortDesc* = $defaultEth2TcpPort
@ -63,11 +63,11 @@ func getAttesterSlashingsTopic*(forkDigest: ForkDigest): string =
func getAggregateAndProofsTopic*(forkDigest: ForkDigest): string =
eth2Prefix(forkDigest) & topicAggregateAndProofsSuffix
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/p2p-interface.md#topics-and-messages
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/p2p-interface.md#topics-and-messages
func getBlsToExecutionChangeTopic*(forkDigest: ForkDigest): string =
eth2Prefix(forkDigest) & topicBlsToExecutionChangeSuffix
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/phase0/validator.md#broadcast-attestation
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/validator.md#broadcast-attestation
func compute_subnet_for_attestation*(
committees_per_slot: uint64, slot: Slot, committee_index: CommitteeIndex):
SubnetId =
@ -105,16 +105,16 @@ func getBlobSidecarTopic*(forkDigest: ForkDigest,
subnet_id: SubnetId): string =
eth2Prefix(forkDigest) & "blob_sidecar_" & $subnet_id & "/ssz_snappy"
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/validator.md#sidecar
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/deneb/validator.md#sidecar
func compute_subnet_for_blob_sidecar*(blob_index: BlobIndex): SubnetId =
SubnetId(blob_index mod BLOB_SIDECAR_SUBNET_COUNT)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_finality_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_finality_update
func getLightClientFinalityUpdateTopic*(forkDigest: ForkDigest): string =
## For broadcasting or obtaining the latest `LightClientFinalityUpdate`.
eth2Prefix(forkDigest) & "light_client_finality_update/ssz_snappy"
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#light_client_optimistic_update
func getLightClientOptimisticUpdateTopic*(forkDigest: ForkDigest): string =
## For broadcasting or obtaining the latest `LightClientOptimisticUpdate`.
eth2Prefix(forkDigest) & "light_client_optimistic_update/ssz_snappy"

View File

@ -17,13 +17,17 @@ export constants
export stint, ethtypes.toHex, ethtypes.`==`
const
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#withdrawal-prefixes
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#withdrawal-prefixes
BLS_WITHDRAWAL_PREFIX*: byte = 0
ETH1_ADDRESS_WITHDRAWAL_PREFIX*: byte = 1
# Constants from `validator.md` not covered by config/presets in the spec
TARGET_AGGREGATORS_PER_COMMITTEE*: uint64 = 16
# Not used anywhere; only for network preset checking
EPOCHS_PER_RANDOM_SUBNET_SUBSCRIPTION: uint64 = 256
MESSAGE_DOMAIN_INVALID_SNAPPY = 0'u64
TTFB_TIMEOUT = 5'u64
type
Version* = distinct array[4, byte]
@ -67,6 +71,7 @@ type
EJECTION_BALANCE*: uint64
MIN_PER_EPOCH_CHURN_LIMIT*: uint64
CHURN_LIMIT_QUOTIENT*: uint64
MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT*: uint64
# Fork choice
# TODO PROPOSER_SCORE_BOOST*: uint64
@ -190,7 +195,8 @@ when const_preset == "mainnet":
MIN_PER_EPOCH_CHURN_LIMIT: 4,
# 2**16 (= 65,536)
CHURN_LIMIT_QUOTIENT: 65536,
# [New in Deneb:EIP7514] 2**3 (= 8)
MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT: 8,
# Deposit contract
# ---------------------------------------------------------------
@ -295,7 +301,8 @@ elif const_preset == "gnosis":
MIN_PER_EPOCH_CHURN_LIMIT: 4,
# 2**16 (= 65,536)
CHURN_LIMIT_QUOTIENT: 4096,
# [New in Deneb:EIP7514] 2**3 (= 8)
MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT: 8,
# Deposit contract
# ---------------------------------------------------------------
@ -391,10 +398,12 @@ elif const_preset == "minimal":
INACTIVITY_SCORE_RECOVERY_RATE: 16,
# 2**4 * 10**9 (= 16,000,000,000) Gwei
EJECTION_BALANCE: 16000000000'u64,
# 2**2 (= 4)
MIN_PER_EPOCH_CHURN_LIMIT: 4,
# [customized] more easily demonstrate the difference between this value and the activation churn limit
MIN_PER_EPOCH_CHURN_LIMIT: 2,
# [customized] scale queue churn at much lower validator counts for testing
CHURN_LIMIT_QUOTIENT: 32,
# [New in Deneb:EIP7514] [customized]
MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT: 4,
# Deposit contract
@ -591,6 +600,11 @@ proc readRuntimeConfig*(
checkCompatibility ATTESTATION_SUBNET_PREFIX_BITS
checkCompatibility BLOB_SIDECAR_SUBNET_COUNT
checkCompatibility MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS
checkCompatibility RESP_TIMEOUT
checkCompatibility TTFB_TIMEOUT
checkCompatibility MESSAGE_DOMAIN_INVALID_SNAPPY
checkCompatibility MAX_REQUEST_BLOCKS_DENEB
checkCompatibility ATTESTATION_PROPAGATION_SLOT_RANGE
# Isn't being used as a preset in the usual way: at any time, there's one correct value
checkCompatibility PROPOSER_SCORE_BOOST

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mainnet preset - Altair
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/altair.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/altair.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Gnosis preset - Bellatrix
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/bellatrix.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/bellatrix.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mainnet preset - Altair
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/altair.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/altair.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mainnet preset - Bellatrix
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/bellatrix.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/bellatrix.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mainnet preset - Capella
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/capella.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/capella.yaml
const
# Max operations per block
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mainnet preset - Deneb
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/mainnet/deneb.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/mainnet/deneb.yaml
const
# `uint64(4096)`
FIELD_ELEMENTS_PER_BLOB*: uint64 = 4096

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Minimal preset - Altair
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/minimal/altair.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/minimal/altair.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Minimal preset - Bellatrix
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/minimal/bellatrix.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/minimal/bellatrix.yaml
const
# Updated penalty values
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Minimal preset - Capella
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/minimal/capella.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/minimal/capella.yaml
const
# Max operations per block
# ---------------------------------------------------------------

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Minimal preset - Deneb
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/presets/minimal/deneb.yaml
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/presets/minimal/deneb.yaml
const
# [customized]
FIELD_ELEMENTS_PER_BLOB*: uint64 = 4

View File

@ -388,7 +388,7 @@ proc verify_builder_signature*(
let signing_root = compute_builder_signing_root(fork, msg)
blsVerify(pubkey, signing_root.data, signature)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#new-process_bls_to_execution_change
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#new-process_bls_to_execution_change
func compute_bls_to_execution_change_signing_root*(
genesisFork: Fork, genesis_validators_root: Eth2Digest,
msg: BLSToExecutionChange): Eth2Digest =

View File

@ -82,7 +82,7 @@ func aggregateAttesters(
# Aggregation spec requires non-empty collection
# - https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04
# Consensus specs require at least one attesting index in attestation
# - https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#is_valid_indexed_attestation
# - https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#is_valid_indexed_attestation
return err("aggregateAttesters: no attesting indices")
let
@ -108,7 +108,7 @@ func aggregateAttesters(
# Aggregation spec requires non-empty collection
# - https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04
# Consensus specs require at least one attesting index in attestation
# - https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#is_valid_indexed_attestation
# - https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#is_valid_indexed_attestation
return err("aggregateAttesters: no attesting indices")
var attestersAgg{.noinit.}: AggregatePublicKey

View File

@ -6,7 +6,6 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
{.push raises: [].}
{.pragma: raisesssz, raises: [MalformedSszError, SszSizeMismatchError].}
import
std/[typetraits],
@ -27,7 +26,8 @@ template toSszType*(v: Version): auto = distinctBase(v)
template toSszType*(v: JustificationBits): auto = distinctBase(v)
template toSszType*(v: EpochParticipationFlags): auto = asList v
func fromSszBytes*(T: type GraffitiBytes, data: openArray[byte]): T {.raisesssz.} =
func fromSszBytes*(
T: type GraffitiBytes, data: openArray[byte]): T {.raises: [SszError].} =
if data.len != sizeof(result):
raiseIncorrectSize T
copyMem(result.addr, unsafeAddr data[0], sizeof(result))
@ -41,22 +41,28 @@ template fromSszBytes*(T: type Epoch, bytes: openArray[byte]): T =
template fromSszBytes*(T: type SyncCommitteePeriod, bytes: openArray[byte]): T =
T fromSszBytes(uint64, bytes)
func fromSszBytes*(T: type ForkDigest, bytes: openArray[byte]): T {.raisesssz.} =
func fromSszBytes*(
T: type ForkDigest, bytes: openArray[byte]): T {.raises: [SszError].} =
if bytes.len != sizeof(result):
raiseIncorrectSize T
copyMem(result.addr, unsafeAddr bytes[0], sizeof(result))
func fromSszBytes*(T: type Version, bytes: openArray[byte]): T {.raisesssz.} =
func fromSszBytes*(
T: type Version, bytes: openArray[byte]): T {.raises: [SszError].} =
if bytes.len != sizeof(result):
raiseIncorrectSize T
copyMem(result.addr, unsafeAddr bytes[0], sizeof(result))
func fromSszBytes*(T: type JustificationBits, bytes: openArray[byte]): T {.raisesssz.} =
func fromSszBytes*(
T: type JustificationBits, bytes: openArray[byte]
): T {.raises: [SszError].} =
if bytes.len != sizeof(result):
raiseIncorrectSize T
copyMem(result.addr, unsafeAddr bytes[0], sizeof(result))
func fromSszBytes*(T: type EpochParticipationFlags, bytes: openArray[byte]): T {.raisesssz.} =
func fromSszBytes*(
T: type EpochParticipationFlags, bytes: openArray[byte]
): T {.raises: [SszError].} =
# TODO https://github.com/nim-lang/Nim/issues/21123
let tmp = cast[ptr List[ParticipationFlags, Limit VALIDATOR_REGISTRY_LIMIT]](addr result)
readSszValue(bytes, tmp[])

View File

@ -6,7 +6,7 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# State transition, as described in
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
#
# The entry point is `state_transition` which is at the bottom of the file!
#
@ -70,7 +70,7 @@ proc verify_block_signature(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
func verifyStateRoot(
state: ForkyBeaconState,
blck: ForkyBeaconBlock | ForkySigVerifiedBeaconBlock):
@ -126,7 +126,7 @@ func clear_epoch_from_cache(cache: var StateCache, epoch: Epoch) =
for slot in epoch.slots():
cache.beacon_proposer_indices.del slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#beacon-chain-state-transition-function
proc advance_slot(
cfg: RuntimeConfig,
state: var ForkyBeaconState, previous_slot_state_root: Eth2Digest,
@ -373,7 +373,7 @@ template partialBeaconBlock*(
when consensusFork >= ConsensusFork.Bellatrix:
res.body.execution_payload = execution_payload.executionPayload
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/validator.md#block-proposal
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/validator.md#block-proposal
when consensusFork >= ConsensusFork.Capella:
res.body.bls_to_execution_changes =
validator_changes.bls_to_execution_changes
@ -438,7 +438,7 @@ proc makeBeaconBlock*(
forkyState.data.latest_execution_payload_header.transactions_root =
transactions_root.get
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#beaconblockbody
# Effectively hash_tree_root(ExecutionPayload) with the beacon block
# body, with the execution payload replaced by the execution payload
# header. htr(payload) == htr(payload header), so substitute.
@ -456,7 +456,7 @@ proc makeBeaconBlock*(
hash_tree_root(validator_changes.bls_to_execution_changes)])
elif consensusFork == ConsensusFork.Deneb:
when executionPayload is deneb.ExecutionPayloadForSigning:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.0/specs/deneb/beacon-chain.md#beaconblockbody
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#beaconblockbody
forkyState.data.latest_block_header.body_root = hash_tree_root(
[hash_tree_root(randao_reveal),
hash_tree_root(eth1_data),

View File

@ -6,10 +6,10 @@
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# State transition - block processing, as described in
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#block-processing
#
# The entry point is `process_block` which is at the bottom of this file.
@ -38,7 +38,7 @@ from ./datatypes/capella import
export extras, phase0, altair
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#block-header
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#block-header
func process_block_header*(
state: var ForkyBeaconState, blck: SomeForkyBeaconBlock,
flags: UpdateFlags, cache: var StateCache): Result[void, cstring] =
@ -80,7 +80,7 @@ func `xor`[T: array](a, b: T): T =
for i in 0..<result.len:
result[i] = a[i] xor b[i]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#randao
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#randao
proc process_randao(
state: var ForkyBeaconState, body: SomeForkyBeaconBlockBody,
flags: UpdateFlags, cache: var StateCache): Result[void, cstring] =
@ -113,7 +113,7 @@ proc process_randao(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#eth1-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#eth1-data
func process_eth1_data(
state: var ForkyBeaconState,
body: SomeForkyBeaconBlockBody): Result[void, cstring] =
@ -126,14 +126,14 @@ func process_eth1_data(
state.eth1_data = body.eth1_data
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#is_slashable_validator
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#is_slashable_validator
func is_slashable_validator(validator: Validator, epoch: Epoch): bool =
# Check if ``validator`` is slashable.
(not validator.slashed) and
(validator.activation_epoch <= epoch) and
(epoch < validator.withdrawable_epoch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#proposer-slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#proposer-slashings
proc check_proposer_slashing*(
state: ForkyBeaconState, proposer_slashing: SomeProposerSlashing,
flags: UpdateFlags):
@ -182,7 +182,7 @@ proc check_proposer_slashing*(
withState(state):
check_proposer_slashing(forkyState.data, proposer_slashing, flags)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#proposer-slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#proposer-slashings
proc process_proposer_slashing*(
cfg: RuntimeConfig, state: var ForkyBeaconState,
proposer_slashing: SomeProposerSlashing, flags: UpdateFlags,
@ -192,7 +192,7 @@ proc process_proposer_slashing*(
? slash_validator(cfg, state, proposer_index, cache)
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#is_slashable_attestation_data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#is_slashable_attestation_data
func is_slashable_attestation_data(
data_1: AttestationData, data_2: AttestationData): bool =
## Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG
@ -204,7 +204,7 @@ func is_slashable_attestation_data(
(data_1.source.epoch < data_2.source.epoch and
data_2.target.epoch < data_1.target.epoch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attester-slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attester-slashings
proc check_attester_slashing*(
state: ForkyBeaconState,
attester_slashing: SomeAttesterSlashing,
@ -246,7 +246,7 @@ proc check_attester_slashing*(
withState(state):
check_attester_slashing(forkyState.data, attester_slashing, flags)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#attester-slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#attester-slashings
proc process_attester_slashing*(
cfg: RuntimeConfig,
state: var ForkyBeaconState,
@ -330,7 +330,7 @@ proc process_deposit*(cfg: RuntimeConfig,
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#voluntary-exits
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#voluntary-exits
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/beacon-chain.md#modified-process_voluntary_exit
proc check_voluntary_exit*(
cfg: RuntimeConfig,
@ -388,7 +388,7 @@ proc check_voluntary_exit*(
withState(state):
check_voluntary_exit(cfg, forkyState.data, signed_voluntary_exit, flags)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#voluntary-exits
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#voluntary-exits
proc process_voluntary_exit*(
cfg: RuntimeConfig,
state: var ForkyBeaconState,
@ -418,8 +418,8 @@ proc process_bls_to_execution_change*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#operations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#modified-process_operations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#operations
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#modified-process_operations
proc process_operations(cfg: RuntimeConfig,
state: var ForkyBeaconState,
body: SomeForkyBeaconBlockBody,
@ -452,7 +452,7 @@ proc process_operations(cfg: RuntimeConfig,
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#sync-aggregate-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#sync-aggregate-processing
func get_participant_reward*(total_active_balance: Gwei): Gwei =
let
total_active_increments =
@ -465,11 +465,11 @@ func get_participant_reward*(total_active_balance: Gwei): Gwei =
WEIGHT_DENOMINATOR div SLOTS_PER_EPOCH
max_participant_rewards div SYNC_COMMITTEE_SIZE
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#sync-aggregate-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#sync-aggregate-processing
func get_proposer_reward*(participant_reward: Gwei): Gwei =
participant_reward * PROPOSER_WEIGHT div (WEIGHT_DENOMINATOR - PROPOSER_WEIGHT)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#sync-aggregate-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#sync-aggregate-processing
proc process_sync_aggregate*(
state: var (altair.BeaconState | bellatrix.BeaconState |
capella.BeaconState | deneb.BeaconState),
@ -673,7 +673,7 @@ proc process_execution_payload*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#new-process_withdrawals
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#new-process_withdrawals
func process_withdrawals*(
state: var (capella.BeaconState | deneb.BeaconState),
payload: capella.ExecutionPayload | deneb.ExecutionPayload):
@ -791,7 +791,10 @@ proc validate_blobs*(expected_kzg_commitments: seq[KzgCommitment],
if proofs.len != blobs.len:
return err("validate_blobs: different proof and blob lengths")
if verifyProofs(blobs, expected_kzg_commitments, proofs).isErr():
let res = verifyProofs(blobs, expected_kzg_commitments, proofs).valueOr:
return err("validate_blobs: proof verification error")
if not res:
return err("validate_blobs: proof verification failed")
ok()
@ -815,7 +818,7 @@ proc process_block*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/altair/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#block-processing
# TODO workaround for https://github.com/nim-lang/Nim/issues/18095
# copy of datatypes/altair.nim
type SomeAltairBlock =
@ -845,7 +848,7 @@ proc process_block*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#block-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#block-processing
# TODO workaround for https://github.com/nim-lang/Nim/issues/18095
type SomeBellatrixBlock =
bellatrix.BeaconBlock | bellatrix.SigVerifiedBeaconBlock | bellatrix.TrustedBeaconBlock

View File

@ -7,8 +7,8 @@
# State transition - epoch processing, as described in
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/capella/beacon-chain.md#epoch-processing
#
# The entry point is `process_epoch`, which is at the bottom of this file.
@ -39,7 +39,7 @@ export extras, phase0, altair
logScope: topics = "consens"
# Accessors that implement the max condition in `get_total_balance`:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_total_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_total_balance
template current_epoch*(v: TotalBalances): Gwei =
max(EFFECTIVE_BALANCE_INCREMENT, v.current_epoch_raw)
template previous_epoch*(v: TotalBalances): Gwei =
@ -154,7 +154,7 @@ func process_attestations*(
if v.flags.contains RewardFlags.isPreviousEpochHeadAttester:
info.balances.previous_epoch_head_attesters_raw += validator_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#helpers
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#helpers
# get_eligible_validator_indices
func is_eligible_validator*(validator: RewardStatus): bool =
validator.flags.contains(RewardFlags.isActiveInPreviousEpoch) or
@ -241,7 +241,7 @@ func is_unslashed_participating_index(
has_flag(epoch_participation[].item(validator_index), flag_index) and
not state.validators[validator_index].slashed
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#justification-and-finalization
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#justification-and-finalization
type FinalityState = object
slot: Slot
current_epoch_ancestor_root: Eth2Digest
@ -309,7 +309,7 @@ proc weigh_justification_and_finalization(
## state.justification_bits[1:] = state.justification_bits[:-1]
## state.justification_bits[0] = 0b0
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#misc
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#misc
const JUSTIFICATION_BITS_LENGTH = 4
state.justification_bits = JustificationBits(
@ -386,7 +386,7 @@ proc weigh_justification_and_finalization(
current_epoch = current_epoch,
checkpoint = shortLog(state.finalized_checkpoint)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#justification-and-finalization
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#justification-and-finalization
proc process_justification_and_finalization*(
state: var phase0.BeaconState,
balances: TotalBalances, flags: UpdateFlags = {}) =
@ -422,7 +422,7 @@ proc compute_unrealized_finality*(
justified: finalityState.current_justified_checkpoint,
finalized: finalityState.finalized_checkpoint)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#justification-and-finalization
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#justification-and-finalization
proc process_justification_and_finalization*(
state: var (altair.BeaconState | bellatrix.BeaconState |
capella.BeaconState | deneb.BeaconState),
@ -458,7 +458,7 @@ proc compute_unrealized_finality*(
justified: finalityState.current_justified_checkpoint,
finalized: finalityState.finalized_checkpoint)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#helpers
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#helpers
func get_base_reward_sqrt*(state: phase0.BeaconState, index: ValidatorIndex,
total_balance_sqrt: auto): Gwei =
# Spec function recalculates total_balance every time, which creates an
@ -506,7 +506,7 @@ func get_attestation_component_delta(is_unslashed_attester: bool,
else:
RewardDelta(penalties: base_reward)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#components-of-attestation-deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#components-of-attestation-deltas
func get_source_delta*(validator: RewardStatus,
base_reward: uint64,
balances: TotalBalances,
@ -584,7 +584,7 @@ func get_inactivity_penalty_delta*(validator: RewardStatus,
delta
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_attestation_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_attestation_deltas
func get_attestation_deltas(
state: phase0.BeaconState, info: var phase0.EpochInfo) =
## Update rewards with attestation reward/penalty deltas for each validator.
@ -629,7 +629,7 @@ func get_attestation_deltas(
info.validators[proposer_index].delta.add(
proposer_delta.get()[1])
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_base_reward
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_base_reward
func get_base_reward_increment*(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState |
deneb.BeaconState,
@ -640,7 +640,7 @@ func get_base_reward_increment*(
state.validators[index].effective_balance div EFFECTIVE_BALANCE_INCREMENT
increments * base_reward_per_increment
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_flag_index_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_flag_index_deltas
func get_flag_index_reward*(
state: altair.BeaconState | bellatrix.BeaconState | capella.BeaconState |
deneb.BeaconState,
@ -654,18 +654,18 @@ func get_flag_index_reward*(
else:
0.Gwei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_flag_index_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_flag_index_deltas
func get_unslashed_participating_increment*(
info: altair.EpochInfo | bellatrix.BeaconState, flag_index: TimelyFlag): Gwei =
info.balances.previous_epoch[flag_index] div EFFECTIVE_BALANCE_INCREMENT
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_flag_index_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_flag_index_deltas
func get_active_increments*(
info: altair.EpochInfo | bellatrix.BeaconState): Gwei =
info.balances.current_epoch div EFFECTIVE_BALANCE_INCREMENT
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#get_flag_index_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#modified-get_inactivity_penalty_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#get_flag_index_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#modified-get_inactivity_penalty_deltas
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/beacon-chain.md#modified-get_inactivity_penalty_deltas
# Combines get_flag_index_deltas() and get_inactivity_penalty_deltas()
iterator get_flag_and_inactivity_deltas*(
@ -812,7 +812,7 @@ func process_rewards_and_penalties*(
from std/heapqueue import HeapQueue, `[]`, len, push, replace
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#registry-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#registry-updates
func process_registry_updates*(
cfg: RuntimeConfig, state: var ForkyBeaconState, cache: var StateCache):
Result[void, cstring] =
@ -839,7 +839,11 @@ func process_registry_updates*(
## Queue validators eligible for activation and not dequeued for activation
var activation_queue: HeapQueue[(uint64, uint32)]
let churn_limit = get_validator_churn_limit(cfg, state, cache)
let churn_limit =
when typeof(state).toFork >= ConsensusFork.Deneb:
get_validator_activation_churn_limit(cfg, state, cache)
else:
get_validator_churn_limit(cfg, state, cache)
for vidx in state.validators.vindices:
if is_eligible_for_activation_queue(state.validators.item(vidx)):
state.validators.mitem(vidx).activation_eligibility_epoch =
@ -859,8 +863,8 @@ func process_registry_updates*(
elif val_key > activation_queue[0]:
discard activation_queue.replace val_key
## Dequeued validators for activation up to churn limit (without resetting
## activation epoch)
## Dequeued validators for activation up to activation churn limit
## (without resetting activation epoch)
doAssert activation_queue.len.uint64 <= churn_limit
for i in 0 ..< activation_queue.len:
let (_, vidx_complement) = activation_queue[i]
@ -870,9 +874,9 @@ func process_registry_updates*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/bellatrix/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#slashings
func get_adjusted_total_slashing_balance*(
state: ForkyBeaconState, total_balance: Gwei): Gwei =
const multiplier =
@ -890,15 +894,15 @@ func get_adjusted_total_slashing_balance*(
min(sum(state.slashings.data) * multiplier, total_balance)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#slashings
func slashing_penalty_applies*(validator: Validator, epoch: Epoch): bool =
validator.slashed and
epoch + EPOCHS_PER_SLASHINGS_VECTOR div 2 == validator.withdrawable_epoch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#slashings
func get_slashing_penalty*(validator: Validator,
adjusted_total_slashing_balance,
total_balance: Gwei): Gwei =
@ -908,9 +912,9 @@ func get_slashing_penalty*(validator: Validator,
adjusted_total_slashing_balance
penalty_numerator div total_balance * increment
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/bellatrix/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/bellatrix/beacon-chain.md#slashings
func process_slashings*(state: var ForkyBeaconState, total_balance: Gwei) =
let
epoch = get_current_epoch(state)
@ -924,7 +928,7 @@ func process_slashings*(state: var ForkyBeaconState, total_balance: Gwei) =
validator[], adjusted_total_slashing_balance, total_balance)
decrease_balance(state, vidx, penalty)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#eth1-data-votes-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#eth1-data-votes-updates
func process_eth1_data_reset*(state: var ForkyBeaconState) =
let next_epoch = get_current_epoch(state) + 1
@ -932,7 +936,7 @@ func process_eth1_data_reset*(state: var ForkyBeaconState) =
if next_epoch mod EPOCHS_PER_ETH1_VOTING_PERIOD == 0:
state.eth1_data_votes = default(type state.eth1_data_votes)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#effective-balances-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#effective-balances-updates
func process_effective_balance_updates*(state: var ForkyBeaconState) =
# Update effective balances with hysteresis
for vidx in state.validators.vindices:
@ -954,14 +958,14 @@ func process_effective_balance_updates*(state: var ForkyBeaconState) =
if new_effective_balance != effective_balance:
state.validators.mitem(vidx).effective_balance = new_effective_balance
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#slashings-balances-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#slashings-balances-updates
func process_slashings_reset*(state: var ForkyBeaconState) =
let next_epoch = get_current_epoch(state) + 1
# Reset slashings
state.slashings[int(next_epoch mod EPOCHS_PER_SLASHINGS_VECTOR)] = 0.Gwei
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#randao-mixes-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#randao-mixes-updates
func process_randao_mixes_reset*(state: var ForkyBeaconState) =
let
current_epoch = get_current_epoch(state)
@ -974,12 +978,12 @@ func process_randao_mixes_reset*(state: var ForkyBeaconState) =
func compute_historical_root*(state: var ForkyBeaconState): Eth2Digest =
# Equivalent to hash_tree_root(foo: HistoricalBatch), but without using
# significant additional stack or heap.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#historicalbatch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#historicalbatch
# In response to https://github.com/status-im/nimbus-eth2/issues/921
hash_tree_root([
hash_tree_root(state.block_roots), hash_tree_root(state.state_roots)])
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#historical-roots-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#historical-roots-updates
func process_historical_roots_update*(state: var ForkyBeaconState) =
## Set historical root accumulator
let next_epoch = get_current_epoch(state) + 1
@ -987,7 +991,7 @@ func process_historical_roots_update*(state: var ForkyBeaconState) =
if next_epoch mod (SLOTS_PER_HISTORICAL_ROOT div SLOTS_PER_EPOCH) == 0:
# Equivalent to hash_tree_root(foo: HistoricalBatch), but without using
# significant additional stack or heap.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#historicalbatch
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#historicalbatch
# In response to https://github.com/status-im/nimbus-eth2/issues/921
if not state.historical_roots.add state.compute_historical_root():
raiseAssert "no more room for historical roots, so long and thanks for the fish!"
@ -999,7 +1003,7 @@ func process_participation_record_updates*(state: var phase0.BeaconState) =
state.previous_epoch_attestations.clear()
swap(state.previous_epoch_attestations, state.current_epoch_attestations)
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#participation-flags-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#participation-flags-updates
func process_participation_flag_updates*(
state: var (altair.BeaconState | bellatrix.BeaconState |
capella.BeaconState | deneb.BeaconState)) =
@ -1013,7 +1017,7 @@ func process_participation_flag_updates*(
# grows. New elements are automatically initialized to 0, as required.
doAssert state.current_epoch_participation.asList.setLen(state.validators.len)
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#sync-committee-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#sync-committee-updates
func process_sync_committee_updates*(
state: var (altair.BeaconState | bellatrix.BeaconState |
capella.BeaconState | deneb.BeaconState)) =
@ -1022,7 +1026,7 @@ func process_sync_committee_updates*(
state.current_sync_committee = state.next_sync_committee
state.next_sync_committee = get_next_sync_committee(state)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#inactivity-scores
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#inactivity-scores
func process_inactivity_updates*(
cfg: RuntimeConfig,
state: var (altair.BeaconState | bellatrix.BeaconState |
@ -1059,7 +1063,7 @@ func process_inactivity_updates*(
if pre_inactivity_score != inactivity_score:
state.inactivity_scores[index] = inactivity_score
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#historical-summaries-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#historical-summaries-updates
func process_historical_summaries_update*(
state: var (capella.BeaconState | deneb.BeaconState)):
Result[void, cstring] =
@ -1075,7 +1079,7 @@ func process_historical_summaries_update*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#epoch-processing
proc process_epoch*(
cfg: RuntimeConfig, state: var phase0.BeaconState, flags: UpdateFlags,
cache: var StateCache, info: var phase0.EpochInfo): Result[void, cstring] =
@ -1163,10 +1167,10 @@ proc process_epoch*(
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#rewards-and-penalties
process_rewards_and_penalties(cfg, state, info) # [Modified in Altair]
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#registry-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#registry-updates
? process_registry_updates(cfg, state, cache)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
process_slashings(state, info.balances.current_epoch) # [Modified in Altair]
process_eth1_data_reset(state)
@ -1179,7 +1183,7 @@ proc process_epoch*(
ok()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/capella/beacon-chain.md#epoch-processing
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/capella/beacon-chain.md#epoch-processing
proc process_epoch*(
cfg: RuntimeConfig,
state: var (capella.BeaconState | deneb.BeaconState),
@ -1190,7 +1194,7 @@ proc process_epoch*(
info.init(state)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#justification-and-finalization
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#justification-and-finalization
process_justification_and_finalization(state, info.balances, flags)
# state.slot hasn't been incremented yet.
@ -1209,10 +1213,10 @@ proc process_epoch*(
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/beacon-chain.md#rewards-and-penalties
process_rewards_and_penalties(cfg, state, info)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#registry-updates
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#registry-updates
? process_registry_updates(cfg, state, cache)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/beacon-chain.md#slashings
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/beacon-chain.md#slashings
process_slashings(state, info.balances.current_epoch)
process_eth1_data_reset(state)

View File

@ -21,8 +21,8 @@ const
PIVOT_VIEW_SIZE = SEED_SIZE + ROUND_SIZE
TOTAL_SIZE = PIVOT_VIEW_SIZE + POSITION_WINDOW_SIZE
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_shuffled_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_shuffled_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_committee
# Port of https://github.com/protolambda/zrnt/blob/master/eth2/beacon/shuffle.go
# Shuffles or unshuffles, depending on the `dir` (true for shuffling, false for unshuffling
func shuffle_list*(input: var seq[ValidatorIndex], seed: Eth2Digest) =
@ -160,13 +160,13 @@ func get_shuffled_active_validator_indices*(
withState(state):
cache.get_shuffled_active_validator_indices(forkyState.data, epoch)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_active_validator_indices
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_active_validator_indices
func count_active_validators*(state: ForkyBeaconState,
epoch: Epoch,
cache: var StateCache): uint64 =
cache.get_shuffled_active_validator_indices(state, epoch).lenu64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_committee_count_per_slot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_committee_count_per_slot
func get_committee_count_per_slot*(num_active_validators: uint64): uint64 =
clamp(
num_active_validators div SLOTS_PER_EPOCH div TARGET_COMMITTEE_SIZE,
@ -191,7 +191,7 @@ iterator get_committee_indices*(committee_count_per_slot: uint64): CommitteeInde
let committee_index = CommitteeIndex.init(idx).expect("value clamped")
yield committee_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_committee
func compute_committee_slice*(
active_validators, index, count: uint64): Slice[int] =
doAssert active_validators <= ValidatorIndex.high.uint64
@ -237,7 +237,7 @@ func compute_committee_len*(
(slice.b - slice.a + 1).uint64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_beacon_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_committee
iterator get_beacon_committee*(
state: ForkyBeaconState, slot: Slot, index: CommitteeIndex,
cache: var StateCache): (int, ValidatorIndex) =
@ -277,7 +277,7 @@ func get_beacon_committee*(
withState(state):
get_beacon_committee(forkyState.data, slot, index, cache)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-alpha.3/specs/phase0/beacon-chain.md#get_beacon_committee
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_committee
func get_beacon_committee_len*(
state: ForkyBeaconState, slot: Slot, index: CommitteeIndex,
cache: var StateCache): uint64 =
@ -301,7 +301,7 @@ func get_beacon_committee_len*(
withState(state):
get_beacon_committee_len(forkyState.data, slot, index, cache)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_shuffled_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_shuffled_index
func compute_shuffled_index*(
index: uint64, index_count: uint64, seed: Eth2Digest): uint64 =
## Return the shuffled index corresponding to ``seed`` (and ``index_count``).
@ -336,7 +336,7 @@ func compute_shuffled_index*(
cur_idx_permuted
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#compute_proposer_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#compute_proposer_index
func compute_proposer_index(state: ForkyBeaconState,
indices: seq[ValidatorIndex], seed: Eth2Digest): Opt[ValidatorIndex] =
## Return from ``indices`` a random index sampled by effective balance.
@ -363,7 +363,7 @@ func compute_proposer_index(state: ForkyBeaconState,
return Opt.some(candidate_index)
i += 1
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_beacon_proposer_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_proposer_index
func get_beacon_proposer_index*(
state: ForkyBeaconState, cache: var StateCache, slot: Slot):
Opt[ValidatorIndex] =
@ -401,7 +401,7 @@ func get_beacon_proposer_index*(
return res
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#get_beacon_proposer_index
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#get_beacon_proposer_index
func get_beacon_proposer_index*(state: ForkyBeaconState, cache: var StateCache):
Opt[ValidatorIndex] =
## Return the beacon proposer index at the current slot.

View File

@ -10,10 +10,10 @@
import
./datatypes/base, ./beaconstate, ./forks, ./helpers
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/weak-subjectivity.md#configuration
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/weak-subjectivity.md#configuration
const SAFETY_DECAY* = 10'u64
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/weak-subjectivity.md#compute_weak_subjectivity_period
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/weak-subjectivity.md#compute_weak_subjectivity_period
func compute_weak_subjectivity_period(
cfg: RuntimeConfig, state: ForkyBeaconState): uint64 =
## Returns the weak subjectivity period for the current ``state``.
@ -49,7 +49,7 @@ func compute_weak_subjectivity_period(
ws_period
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/weak-subjectivity.md#is_within_weak_subjectivity_period
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/weak-subjectivity.md#is_within_weak_subjectivity_period
func is_within_weak_subjectivity_period*(cfg: RuntimeConfig, current_slot: Slot,
ws_state: ForkedHashedBeaconState,
ws_checkpoint: Checkpoint): bool =

View File

@ -187,7 +187,7 @@ func getBeaconStateDiffSummary*(state0: capella.BeaconState):
if state0.eth1_data_votes.len > 0:
# replaceOrAddEncodeEth1Votes will check whether it needs to replace or add
# the votes. Which happens is a function of effectively external data, i.e.
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/phase0/beacon-chain.md#eth1-data
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/phase0/beacon-chain.md#eth1-data
# notes it depends on things not deterministic, from a pure consensus-layer
# perspective. It thus must distinguish between adding and replacing votes,
# which it accomplishes by checking lengths and the most recent votes. This

View File

@ -110,7 +110,7 @@ proc isGossipSupported*(
finalizedPeriod = self.getFinalizedPeriod(),
isNextSyncCommitteeKnown = self.isNextSyncCommitteeKnown())
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
proc doRequest(
e: typedesc[Bootstrap],
peer: Peer,
@ -119,7 +119,7 @@ proc doRequest(
raises: [IOError].} =
peer.lightClientBootstrap(blockRoot)
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
type LightClientUpdatesByRangeResponse =
NetRes[List[ForkedLightClientUpdate, MAX_REQUEST_LIGHT_CLIENT_UPDATES]]
proc doRequest(
@ -138,7 +138,7 @@ proc doRequest(
raise newException(ResponseError, e.error)
return response
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
proc doRequest(
e: typedesc[FinalityUpdate],
peer: Peer
@ -146,7 +146,7 @@ proc doRequest(
raises: [IOError].} =
peer.lightClientFinalityUpdate()
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
proc doRequest(
e: typedesc[OptimisticUpdate],
peer: Peer
@ -281,7 +281,7 @@ proc query[E](
progressFut.complete()
except CancelledError as exc:
if not progressFut.finished:
progressFut.cancel()
progressFut.cancelSoon()
except CatchableError as exc:
discard
finally:
@ -311,7 +311,7 @@ proc query[E](
doneFut.complete()
break
if not workers[i].finished:
workers[i].cancel()
workers[i].cancelSoon()
while true:
try:
await allFutures(workers[0 ..< maxCompleted])
@ -326,7 +326,7 @@ proc query[E](
continue
if not progressFut.finished:
progressFut.cancel()
progressFut.cancelSoon()
return progressFut.completed
template query[E](
@ -335,7 +335,7 @@ template query[E](
): Future[bool] =
self.query(e, Nothing())
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/light-client.md#light-client-sync-process
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/light-client.md#light-client-sync-process
proc loop(self: LightClientManager) {.async.} =
var nextSyncTaskTime = self.getBeaconTime()
while true:

View File

@ -353,7 +353,7 @@ proc start*(rman: var RequestManager) =
proc stop*(rman: RequestManager) =
## Stop Request Manager's loop.
if not(isNil(rman.blockLoopFuture)):
rman.blockLoopFuture.cancel()
rman.blockLoopFuture.cancelSoon()
if not(isNil(rman.blobLoopFuture)):
rman.blobLoopFuture.cancel()
rman.blobLoopFuture.cancelSoon()

View File

@ -630,18 +630,15 @@ proc toTimeLeftString*(d: Duration): string =
proc syncClose[A, B](man: SyncManager[A, B], guardTaskFut: Future[void],
speedTaskFut: Future[void]) {.async.} =
guardTaskFut.cancel()
speedTaskFut.cancel()
await allFutures(guardTaskFut, speedTaskFut)
let pendingTasks =
block:
var res: seq[Future[void]]
for worker in man.workers:
doAssert(worker.status in {Sleeping, WaitingPeer})
worker.future.cancel()
res.add(worker.future)
res
await allFutures(pendingTasks)
var pending: seq[FutureBase]
if not(guardTaskFut.finished()):
pending.add(guardTaskFut.cancelAndWait())
if not(speedTaskFut.finished()):
pending.add(speedTaskFut.cancelAndWait())
for worker in man.workers:
doAssert(worker.status in {Sleeping, WaitingPeer})
pending.add(worker.future.cancelAndWait())
await noCancel allFutures(pending)
proc syncLoop[A, B](man: SyncManager[A, B]) {.async.} =
logScope:

View File

@ -283,7 +283,7 @@ p2pProtocol BeaconSync(version = 1,
{.libp2pProtocol("ping", 1, isRequired = true).} =
return peer.network.metadata.seq_number
# https://github.com/ethereum/consensus-specs/blob/v1.3.0/specs/altair/p2p-interface.md#transitioning-from-v1-to-v2
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/p2p-interface.md#transitioning-from-v1-to-v2
proc getMetaData(peer: Peer): uint64
{.libp2pProtocol("metadata", 1, isRequired = true).} =
raise newException(InvalidInputsError, "GetMetaData v1 unsupported")
@ -548,7 +548,7 @@ p2pProtocol BeaconSync(version = 1,
debug "BlobSidecar range request done",
peer, startSlot, count = reqCount, found
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientbootstrap
proc lightClientBootstrap(
peer: Peer,
blockRoot: Eth2Digest,
@ -576,7 +576,7 @@ p2pProtocol BeaconSync(version = 1,
debug "LC bootstrap request done", peer, blockRoot
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#lightclientupdatesbyrange
proc lightClientUpdatesByRange(
peer: Peer,
startPeriod: SyncCommitteePeriod,
@ -621,7 +621,7 @@ p2pProtocol BeaconSync(version = 1,
debug "LC updates by range request done", peer, startPeriod, count, found
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientfinalityupdate
proc lightClientFinalityUpdate(
peer: Peer,
response: SingleChunkResponse[ForkedLightClientFinalityUpdate])
@ -648,7 +648,7 @@ p2pProtocol BeaconSync(version = 1,
debug "LC finality update request done", peer
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/p2p-interface.md#getlightclientoptimisticupdate
proc lightClientOptimisticUpdate(
peer: Peer,
response: SingleChunkResponse[ForkedLightClientOptimisticUpdate])

View File

@ -181,7 +181,7 @@ proc doTrustedNodeSync*(
let stateId =
case syncTarget.kind
of TrustedNodeSyncKind.TrustedBlockRoot:
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/altair/light-client/light-client.md#light-client-sync-process
# https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.2/specs/altair/light-client/light-client.md#light-client-sync-process
const lcDataFork = LightClientDataFork.high
var bestViableCheckpoint: Opt[tuple[slot: Slot, state_root: Eth2Digest]]
func trackBestViableCheckpoint(store: lcDataFork.LightClientStore) =
@ -487,18 +487,18 @@ proc doTrustedNodeSync*(
of TrustedNodeSyncKind.TrustedBlockRoot:
# Trust-minimized sync: the server is only trusted for
# data availability, responses must be verified
dag.addBackfillBlock(blck)
dag.addBackfillBlock(forkyBlck)
of TrustedNodeSyncKind.StateId:
# The server is fully trusted to provide accurate data;
# it could have provided a malicious state
dag.addBackfillBlock(blck.asSigVerified())
dag.addBackfillBlock(forkyBlck.asSigVerified())
if res.isErr():
case res.error()
of VerifierError.Invalid,
VerifierError.MissingParent,
VerifierError.UnviableFork:
error "Got invalid block from trusted node - is it on the right network?",
blck = shortLog(blck), err = res.error()
blck = shortLog(forkyBlck), err = res.error()
quit 1
of VerifierError.Duplicate:
discard

View File

@ -114,7 +114,7 @@ proc produceBlindedBlock(
error "An unexpected error occurred while getting blinded block data",
error_name = exc.name, error_msg = exc.msg
return Opt.none(PreparedBlindedBeaconBlock)
blockRoot = withBlck(beaconBlock): hash_tree_root(blck)
blockRoot = withBlck(beaconBlock): hash_tree_root(forkyBlck)
return Opt.some(
PreparedBlindedBeaconBlock(blockRoot: blockRoot, data: beaconBlock))
@ -734,7 +734,7 @@ proc runBlockPollMonitor(service: BlockServiceRef,
proc runBlockMonitor(service: BlockServiceRef) {.async.} =
let
vc = service.client
blockNodes = vc.filterNodes(AllBeaconNodeStatuses,
blockNodes = vc.filterNodes(ResolvedBeaconNodeStatuses,
{BeaconNodeRole.BlockProposalData})
let pendingTasks =
case vc.config.monitoringType

View File

@ -118,6 +118,7 @@ type
BeaconNodeServer* = object
client*: RestClientRef
uri*: Uri
endpoint*: string
config*: VCRuntimeConfig
ident*: Opt[string]
@ -146,6 +147,8 @@ type
proofs*: Table[ValidatorPubKey, SyncCommitteeSelectionProof]
RestBeaconNodeStatus* {.pure.} = enum
Invalid, ## BN address is invalid.
Noname, ## BN address could not be resolved yet.
Offline, ## BN is offline.
Online, ## BN is online, passed checkOnline() check.
Incompatible, ## BN configuration is NOT compatible with VC.
@ -284,6 +287,22 @@ const
## are enabled by default.
AllBeaconNodeStatuses* = {
RestBeaconNodeStatus.Invalid,
RestBeaconNodeStatus.Noname,
RestBeaconNodeStatus.Offline,
RestBeaconNodeStatus.Online,
RestBeaconNodeStatus.Incompatible,
RestBeaconNodeStatus.Compatible,
RestBeaconNodeStatus.NotSynced,
RestBeaconNodeStatus.OptSynced,
RestBeaconNodeStatus.Synced,
RestBeaconNodeStatus.UnexpectedCode,
RestBeaconNodeStatus.UnexpectedResponse,
RestBeaconNodeStatus.BrokenClock,
RestBeaconNodeStatus.InternalError
}
ResolvedBeaconNodeStatuses* = {
RestBeaconNodeStatus.Offline,
RestBeaconNodeStatus.Online,
RestBeaconNodeStatus.Incompatible,
@ -341,6 +360,8 @@ proc `$`*(roles: set[BeaconNodeRole]): string =
proc `$`*(status: RestBeaconNodeStatus): string =
case status
of RestBeaconNodeStatus.Invalid: "invalid-address"
of RestBeaconNodeStatus.Noname: "dns-error"
of RestBeaconNodeStatus.Offline: "offline"
of RestBeaconNodeStatus.Online: "online"
of RestBeaconNodeStatus.Incompatible: "incompatible"
@ -548,11 +569,23 @@ proc updateStatus*(node: BeaconNodeServerRef,
node = node
case status
of RestBeaconNodeStatus.Invalid:
if node.status != status:
warn "Beacon node could not be used"
node.status = status
of RestBeaconNodeStatus.Noname:
if node.status != status:
warn "Beacon node address cannot be resolved"
node.status = status
of RestBeaconNodeStatus.Offline:
if node.status != status:
warn "Beacon node down",
reason = failure.getFailureReason()
node.status = status
if node.status in {RestBeaconNodeStatus.Invalid,
RestBeaconNodeStatus.Noname}:
notice "Beacon node address has been resolved"
node.status = status
else:
warn "Beacon node down", reason = failure.getFailureReason()
node.status = status
of RestBeaconNodeStatus.Online:
if node.status != status:
let version = if node.ident.isSome(): node.ident.get() else: "<missing>"
@ -717,25 +750,38 @@ proc normalizeUri*(r: Uri): Result[Uri, cstring] =
ok(normalized)
proc initClient*(uri: Uri): Result[RestClientRef, HttpAddressErrorType] =
let
flags = {RestClientFlag.CommaSeparatedArray}
socketFlags = {SocketFlags.TcpNoDelay}
address = ? getHttpAddress(uri)
client = RestClientRef.new(address, flags = flags,
socketFlags = socketFlags)
ok(client)
proc init*(t: typedesc[BeaconNodeServerRef], remote: Uri,
index: int): Result[BeaconNodeServerRef, string] =
doAssert(index >= 0)
let
flags = {RestClientFlag.CommaSeparatedArray}
socketFlags = {SocketFlags.TcpNoDelay}
remoteUri = normalizeUri(remote).valueOr:
return err($error)
client = RestClientRef.new($remoteUri, flags = flags,
socketFlags = socketFlags).valueOr:
return err($error)
roles = parseRoles(remoteUri.anchor).valueOr:
return err($error)
let server = BeaconNodeServerRef(
client: client, endpoint: $remoteUri, index: index, roles: roles,
logIdent: $client.address.getUri(),
status: RestBeaconNodeStatus.Offline
)
server =
block:
let res = initClient(remoteUri)
if res.isOk():
BeaconNodeServerRef(
client: res.get(), endpoint: $remoteUri, index: index,
roles: roles, logIdent: $(res.get().address.getUri()),
uri: remoteUri, status: RestBeaconNodeStatus.Offline)
else:
if res.error.isCriticalError():
return err(res.error.toString())
BeaconNodeServerRef(
client: nil, endpoint: $remoteUri, index: index,
roles: roles, logIdent: $remoteUri, uri: remoteUri,
status: RestBeaconNodeStatus.Noname)
ok(server)
proc getMissingRoles*(n: openArray[BeaconNodeServerRef]): set[BeaconNodeRole] =

View File

@ -371,8 +371,19 @@ proc pollForSyncCommitteeDuties*(service: DutiesServiceRef) {.async.} =
var counts: array[2, tuple[period: SyncCommitteePeriod, count: int]]
counts[0] = (currentPeriod,
await service.pollForSyncCommitteeDuties(currentPeriod))
counts[1] = (nextPeriod,
await service.pollForSyncCommitteeDuties(nextPeriod))
const
numDelayEpochs = 4 # Chosen empirically
numLookaheadEpochs =
max(EPOCHS_PER_SYNC_COMMITTEE_PERIOD, numDelayEpochs) -
numDelayEpochs + 1
if (currentEpoch + numLookaheadEpochs) >= nextPeriod.start_epoch:
counts[1] = (nextPeriod,
await service.pollForSyncCommitteeDuties(nextPeriod))
else:
# Skip fetching `nextPeriod` until sync committees are likely known,
# as determined by `numDelayEpochs` from sync committee period start.
counts[1] = (nextPeriod, 0)
if (counts[0].count == 0) and (counts[1].count == 0):
debug "No new sync committee duties received", slot = currentSlot

View File

@ -45,6 +45,12 @@ proc filterNodes*(vc: ValidatorClientRef, statuses: set[RestBeaconNodeStatus],
vc.beaconNodes.filterIt((it.roles * roles != {}) and
(it.status in statuses))
proc nonameNodes*(vc: ValidatorClientRef): seq[BeaconNodeServerRef] =
vc.beaconNodes.filterIt(it.status == RestBeaconNodeStatus.Noname)
proc offlineNodes*(vc: ValidatorClientRef): seq[BeaconNodeServerRef] =
vc.beaconNodes.filterIt(it.status == RestBeaconNodeStatus.Offline)
proc otherNodes*(vc: ValidatorClientRef): seq[BeaconNodeServerRef] =
vc.beaconNodes.filterIt(it.status != RestBeaconNodeStatus.Synced)
@ -91,6 +97,25 @@ proc waitNodes*(vc: ValidatorClientRef, timeoutFut: Future[void],
inc(iterations)
proc checkName*(
node: BeaconNodeServerRef): RestBeaconNodeStatus {.raises: [].} =
## Could return only {Invalid, Noname, Offline}
logScope: endpoint = node
let client =
block:
let res = initClient(node.uri)
if res.isErr():
return
case res.error
of CriticalHttpAddressError:
RestBeaconNodeStatus.Invalid
of RecoverableHttpAddressError:
RestBeaconNodeStatus.Noname
res.get()
node.client = client
RestBeaconNodeStatus.Offline
proc checkCompatible(
vc: ValidatorClientRef,
node: BeaconNodeServerRef
@ -225,6 +250,10 @@ proc checkOnline(
func getReason(status: RestBeaconNodeStatus): string =
case status
of RestBeaconNodeStatus.Invalid:
"Beacon node address invalid"
of RestBeaconNodeStatus.Noname:
"Beacon node address cannot be resolved"
of RestBeaconNodeStatus.Offline:
"Connection with node has been lost"
of RestBeaconNodeStatus.Online:
@ -237,6 +266,15 @@ proc checkNode(vc: ValidatorClientRef,
let nstatus = node.status
debug "Checking beacon node", endpoint = node, status = node.status
if nstatus in {RestBeaconNodeStatus.Noname}:
let
status = node.checkName()
failure = ApiNodeFailure.init(ApiFailure.NoError, "checkName",
node, status.getReason())
node.updateStatus(status, failure)
if status != RestBeaconNodeStatus.Offline:
return nstatus != status
if nstatus in {RestBeaconNodeStatus.Offline,
RestBeaconNodeStatus.UnexpectedCode,
RestBeaconNodeStatus.UnexpectedResponse,
@ -408,7 +446,8 @@ proc runTimeMonitor(service: FallbackServiceRef,
proc processTimeMonitoring(service: FallbackServiceRef) {.async.} =
let
vc = service.client
blockNodes = vc.filterNodes(AllBeaconNodeStatuses, AllBeaconNodeRoles)
blockNodes = vc.filterNodes(
ResolvedBeaconNodeStatuses, AllBeaconNodeRoles)
var pendingChecks: seq[Future[void]]

View File

@ -409,16 +409,21 @@ proc getExecutionPayload(
get_expected_withdrawals(forkyState.data)
else:
@[]
payload = await node.elManager.getPayload(
PayloadType, beaconHead.blck.bid.root, executionHead, latestSafe,
latestFinalized, timestamp, random, feeRecipient, withdrawals)
if payload.isNone:
info "Requesting engine payload",
beaconHead = shortLog(beaconHead.blck),
executionHead = shortLog(executionHead),
validatorIndex = validator_index,
feeRecipient = $feeRecipient
let payload = (await node.elManager.getPayload(
PayloadType, beaconHead.blck.bid.root, executionHead, latestSafe,
latestFinalized, timestamp, random, feeRecipient, withdrawals)).valueOr:
error "Failed to obtain execution payload from EL",
executionHeadBlock = executionHead
return Opt.none(PayloadType)
return Opt.some payload.get
return Opt.some payload
except CatchableError as err:
beacon_block_payload_errors.inc()
error "Error creating non-empty execution payload",
@ -684,7 +689,8 @@ proc getUnsignedBlindedBeaconBlock[
consensusFork == ConsensusFork.Capella)):
return err("getUnsignedBlindedBeaconBlock: mismatched block/payload types")
else:
return ok constructSignableBlindedBlock[T](blck, executionPayloadHeader)
return ok constructSignableBlindedBlock[T](
forkyBlck, executionPayloadHeader)
else:
return err("getUnsignedBlindedBeaconBlock: attempt to construct pre-Bellatrix blinded block")
@ -886,7 +892,7 @@ proc makeBlindedBeaconBlockForHeadAndSlot*[
(consensusFork == ConsensusFork.Capella and
EPH is capella.ExecutionPayloadHeader)):
return ok (constructPlainBlindedBlock[BBB, EPH](
blck, executionPayloadHeader), bidValue)
forkyBlck, executionPayloadHeader), bidValue)
else:
return err("makeBlindedBeaconBlockForHeadAndSlot: mismatched block/payload types")
else:
@ -1040,7 +1046,7 @@ proc proposeBlockAux(
withBlck(forkedBlck):
let
blockRoot = hash_tree_root(blck)
blockRoot = hash_tree_root(forkyBlck)
signingRoot = compute_block_signing_root(
fork, genesis_validators_root, slot, blockRoot)
@ -1049,7 +1055,7 @@ proc proposeBlockAux(
.registerBlock(validator_index, validator.pubkey, slot, signingRoot)
let blobSidecarsOpt =
when blck is deneb.BeaconBlock:
when forkyBlck is deneb.BeaconBlock:
var sidecars: seq[BlobSidecar]
let bundle = collectedBids.engineBlockFut.read.get().blobsBundleOpt.get
let (blobs, kzgs, proofs) = (bundle.blobs, bundle.kzgs, bundle.proofs)
@ -1058,23 +1064,25 @@ proc proposeBlockAux(
block_root: blockRoot,
index: BlobIndex(i),
slot: slot,
block_parent_root: blck.parent_root,
proposer_index: blck.proposer_index,
block_parent_root: forkyBlck.parent_root,
proposer_index: forkyBlck.proposer_index,
blob: blobs[i],
kzg_commitment: kzgs[i],
kzg_proof: proofs[i]
)
sidecars.add(sidecar)
Opt.some(sidecars)
elif blck is phase0.BeaconBlock or blck is altair.BeaconBlock or
blck is bellatrix.BeaconBlock or blck is capella.BeaconBlock:
elif forkyBlck is phase0.BeaconBlock or
forkyBlck is altair.BeaconBlock or
forkyBlck is bellatrix.BeaconBlock or
forkyBlck is capella.BeaconBlock:
Opt.none(seq[BlobSidecar])
else:
static: doAssert "Unknown BeaconBlock type"
if notSlashable.isErr:
warn "Slashing protection activated for block proposal",
blockRoot = shortLog(blockRoot), blck = shortLog(blck),
blockRoot = shortLog(blockRoot), blck = shortLog(forkyBlck),
signingRoot = shortLog(signingRoot),
validator = validator.pubkey,
slot = slot,
@ -1092,28 +1100,30 @@ proc proposeBlockAux(
return head
res.get()
signedBlock =
when blck is phase0.BeaconBlock:
when forkyBlck is phase0.BeaconBlock:
phase0.SignedBeaconBlock(
message: blck, signature: signature, root: blockRoot)
elif blck is altair.BeaconBlock:
message: forkyBlck, signature: signature, root: blockRoot)
elif forkyBlck is altair.BeaconBlock:
altair.SignedBeaconBlock(
message: blck, signature: signature, root: blockRoot)
elif blck is bellatrix.BeaconBlock:
message: forkyBlck, signature: signature, root: blockRoot)
elif forkyBlck is bellatrix.BeaconBlock:
bellatrix.SignedBeaconBlock(
message: blck, signature: signature, root: blockRoot)
elif blck is capella.BeaconBlock:
message: forkyBlck, signature: signature, root: blockRoot)
elif forkyBlck is capella.BeaconBlock:
capella.SignedBeaconBlock(
message: blck, signature: signature, root: blockRoot)
elif blck is deneb.BeaconBlock:
message: forkyBlck, signature: signature, root: blockRoot)
elif forkyBlck is deneb.BeaconBlock:
deneb.SignedBeaconBlock(
message: blck, signature: signature, root: blockRoot)
message: forkyBlck, signature: signature, root: blockRoot)
else:
static: doAssert "Unknown SignedBeaconBlock type"
signedBlobs =
when blck is phase0.BeaconBlock or blck is altair.BeaconBlock or
blck is bellatrix.BeaconBlock or blck is capella.BeaconBlock:
when forkyBlck is phase0.BeaconBlock or
forkyBlck is altair.BeaconBlock or
forkyBlck is bellatrix.BeaconBlock or
forkyBlck is capella.BeaconBlock:
Opt.none(SignedBlobSidecars)
elif blck is deneb.BeaconBlock:
elif forkyBlck is deneb.BeaconBlock:
var signed: seq[SignedBlobSidecar]
let blobSidecars = blobSidecarsOpt.get()
for i in 0..<blobs.len:
@ -1139,7 +1149,7 @@ proc proposeBlockAux(
return head # Validation errors logged in router
notice "Block proposed",
blockRoot = shortLog(blockRoot), blck = shortLog(blck),
blockRoot = shortLog(blockRoot), blck = shortLog(forkyBlck),
signature = shortLog(signature), validator = shortLog(validator)
beacon_blocks_proposed.inc()
@ -1551,17 +1561,24 @@ proc getValidatorRegistration(
return ok validatorRegistration
proc registerValidators*(node: BeaconNode, epoch: Epoch) {.async.} =
proc registerValidatorsPerBuilder(
node: BeaconNode, payloadBuilderAddress: string, epoch: Epoch,
attachedValidatorPubkeys: seq[ValidatorPubKey]) {.async.} =
const HttpOk = 200
try:
if not node.config.payloadBuilderEnable: return
const HttpOk = 200
let payloadBuilderClient = node.getPayloadBuilderClient(0).valueOr:
let payloadBuilderClient =
RestClientRef.new(payloadBuilderAddress).valueOr:
debug "Unable to initialize payload builder client while registering validators",
payloadBuilderAddress, epoch,
err = error
return
if payloadBuilderClient.isNil:
debug "registerValidatorsPerBuilder: got nil payload builder REST client reference",
payloadBuilderAddress, epoch
return
let restBuilderStatus = awaitWithTimeout(payloadBuilderClient.checkBuilderStatus(),
BUILDER_STATUS_DELAY_TOLERANCE):
debug "Timeout when obtaining builder status"
@ -1573,11 +1590,6 @@ proc registerValidators*(node: BeaconNode, epoch: Epoch) {.async.} =
builderStatus = restBuilderStatus
return
# The async aspect of signing the registrations can cause the attached
# validators to change during the loop.
let attachedValidatorPubkeys =
toSeq(node.attachedValidators[].validators.keys)
const emptyNestedSeq = @[newSeq[SignedValidatorRegistrationV1](0)]
# https://github.com/ethereum/builder-specs/blob/v0.3.0/specs/bellatrix/validator.md#validator-registration
# Seed with single empty inner list to avoid special cases
@ -1678,6 +1690,23 @@ proc registerValidators*(node: BeaconNode, epoch: Epoch) {.async.} =
warn "registerValidators: exception",
error = exc.msg
proc registerValidators*(node: BeaconNode, epoch: Epoch) {.async.} =
if not node.config.payloadBuilderEnable: return
var builderKeys: Table[string, seq[ValidatorPubKey]]
for pubkey in node.attachedValidators[].validators.keys:
let payloadBuilderAddress = node.getPayloadBuilderAddress(pubkey).valueOr:
continue
if payloadBuilderAddress in builderKeys:
builderKeys[payloadBuilderAddress].add pubkey
else:
builderKeys[payloadBuilderAddress] = @[pubkey]
for payloadBuilderAddress in builderKeys.keys:
await node.registerValidatorsPerBuilder(
payloadBuilderAddress, epoch, builderKeys[payloadBuilderAddress])
proc updateValidators(
node: BeaconNode, validators: openArray[Validator]) =
# Since validator indicies are stable, we only check the "updated" range -

View File

@ -80,6 +80,7 @@ type
KeymanagerHost* = object
validatorPool*: ref ValidatorPool
keystoreCache*: KeystoreCacheRef
rng*: ref HmacDrbgContext
keymanagerToken*: string
validatorsDir*: string
@ -111,6 +112,7 @@ func dispose*(decryptor: var MultipleKeystoresDecryptor) =
func init*(T: type KeymanagerHost,
validatorPool: ref ValidatorPool,
keystoreCache: KeystoreCacheRef,
rng: ref HmacDrbgContext,
keymanagerToken: string,
validatorsDir: string,
@ -123,6 +125,7 @@ func init*(T: type KeymanagerHost,
getForkFn: GetForkFn,
getGenesisFn: GetGenesisFn): T =
T(validatorPool: validatorPool,
keystoreCache: keystoreCache,
rng: rng,
keymanagerToken: keymanagerToken,
validatorsDir: validatorsDir,
@ -1339,18 +1342,13 @@ proc importKeystore*(pool: var ValidatorPool,
rng: var HmacDrbgContext,
validatorsDir, secretsDir: string,
keystore: Keystore,
password: string): ImportResult[KeystoreData] {.
password: string,
cache: KeystoreCacheRef): ImportResult[KeystoreData] {.
raises: [].} =
let keypass = KeystorePass.init(password)
let privateKey =
block:
let res = decryptKeystore(keystore, keypass)
if res.isOk():
res.get()
else:
return err(
AddValidatorFailure.init(AddValidatorStatus.failed, res.error()))
let
keypass = KeystorePass.init(password)
privateKey = decryptKeystore(keystore, keypass, cache).valueOr:
return err(AddValidatorFailure.init(AddValidatorStatus.failed, error))
publicKey = privateKey.toPubKey()
keyName = publicKey.fsName
keystoreDir = validatorsDir / keyName

View File

@ -47,6 +47,9 @@ proc unblindAndRouteBlockMEV*(
node: BeaconNode, payloadBuilderRestClient: RestClientRef,
blindedBlock: capella_mev.SignedBlindedBeaconBlock):
Future[Result[Opt[BlockRef], string]] {.async.} =
info "Proposing blinded Builder API block",
blindedBlock = shortLog(blindedBlock)
# By time submitBlindedBlock is called, must already have done slashing
# protection check
let unblindedPayload =

Some files were not shown because too many files have changed in this diff Show More