diff --git a/.gitignore b/.gitignore index 91270239a..3e4413e97 100644 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,6 @@ tests/core/pyspec/eth2spec/capella/ tests/core/pyspec/eth2spec/deneb/ tests/core/pyspec/eth2spec/electra/ tests/core/pyspec/eth2spec/whisk/ -tests/core/pyspec/eth2spec/eip7251/ tests/core/pyspec/eth2spec/eip7594/ # coverage reports diff --git a/configs/mainnet.yaml b/configs/mainnet.yaml index dd63b1ac8..55a973e9a 100644 --- a/configs/mainnet.yaml +++ b/configs/mainnet.yaml @@ -53,9 +53,6 @@ DENEB_FORK_EPOCH: 269568 # March 13, 2024, 01:55:35pm UTC # Electra ELECTRA_FORK_VERSION: 0x05000000 ELECTRA_FORK_EPOCH: 18446744073709551615 -# EIP7251 -EIP7251_FORK_VERSION: 0x06000000 # temporary stub -EIP7251_FORK_EPOCH: 18446744073709551615 # WHISK WHISK_FORK_VERSION: 0x08000000 # temporary stub WHISK_FORK_EPOCH: 18446744073709551615 @@ -163,6 +160,6 @@ NUMBER_OF_COLUMNS: 128 DATA_COLUMN_SIDECAR_SUBNET_COUNT: 32 MAX_REQUEST_DATA_COLUMN_SIDECARS: 16384 -# [New in EIP7251] -MIN_PER_EPOCH_CHURN_LIMIT_EIP7251: 128000000000 # 2**7 * 10**9 (= 128,000,000,000) +# [New in Electra:EIP7251] +MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA: 128000000000 # 2**7 * 10**9 (= 128,000,000,000) MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT: 256000000000 # 2**8 * 10**9 (= 256,000,000,000) diff --git a/configs/minimal.yaml b/configs/minimal.yaml index b819bd955..75e75ce9c 100644 --- a/configs/minimal.yaml +++ b/configs/minimal.yaml @@ -52,9 +52,6 @@ DENEB_FORK_EPOCH: 18446744073709551615 # Electra ELECTRA_FORK_VERSION: 0x05000001 ELECTRA_FORK_EPOCH: 18446744073709551615 -# EIP7251 -EIP7251_FORK_VERSION: 0x06000001 # temporary stub -EIP7251_FORK_EPOCH: 18446744073709551615 # WHISK WHISK_FORK_VERSION: 0x08000001 WHISK_FORK_EPOCH: 18446744073709551615 @@ -161,6 +158,6 @@ NUMBER_OF_COLUMNS: 128 DATA_COLUMN_SIDECAR_SUBNET_COUNT: 32 MAX_REQUEST_DATA_COLUMN_SIDECARS: 16384 -# [New in EIP7251] -MIN_PER_EPOCH_CHURN_LIMIT_EIP7251: 64000000000 # 2**6 * 10**9 (= 64,000,000,000) +# [New in Electra:EIP7251] +MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA: 64000000000 # 2**6 * 10**9 (= 64,000,000,000) MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT: 128000000000 # 2**7 * 10**9 (= 128,000,000,000) diff --git a/presets/mainnet/eip7251.yaml b/presets/mainnet/eip7251.yaml deleted file mode 100644 index ee543018e..000000000 --- a/presets/mainnet/eip7251.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Mainnet preset - EIP7251 - -# Gwei values -# --------------------------------------------------------------- -# 2**5 * 10**9 (= 32,000,000,000) Gwei -MIN_ACTIVATION_BALANCE: 32000000000 -# 2**11 * 10**9 (= 2,048,000,000,000) Gwei -MAX_EFFECTIVE_BALANCE_EIP7251: 2048000000000 - -# State list lengths -# --------------------------------------------------------------- -PENDING_BALANCE_DEPOSITS_LIMIT: 134217728 -PENDING_PARTIAL_WITHDRAWALS_LIMIT: 134217728 -PENDING_CONSOLIDATIONS_LIMIT: 262144 - -# Reward and penalty quotients -# --------------------------------------------------------------- -MIN_SLASHING_PENALTY_QUOTIENT_EIP7251: 4096 -WHISTLEBLOWER_REWARD_QUOTIENT_EIP7251: 4096 - -# Max operations per block -# --------------------------------------------------------------- -MAX_CONSOLIDATIONS: 1 - -# Execution -# --------------------------------------------------------------- -# 2**3 (= 8) partial withdrawals -MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD: 8 diff --git a/presets/mainnet/electra.yaml b/presets/mainnet/electra.yaml index e206a6505..76e2f9277 100644 --- a/presets/mainnet/electra.yaml +++ b/presets/mainnet/electra.yaml @@ -1,11 +1,30 @@ # Mainnet preset - Electra +# Gwei values +# --------------------------------------------------------------- +# 2**5 * 10**9 (= 32,000,000,000) Gwei +MIN_ACTIVATION_BALANCE: 32000000000 +# 2**11 * 10**9 (= 2,048,000,000,000) Gwei +MAX_EFFECTIVE_BALANCE_ELECTRA: 2048000000000 + +# State list lengths +# --------------------------------------------------------------- +PENDING_BALANCE_DEPOSITS_LIMIT: 134217728 +PENDING_PARTIAL_WITHDRAWALS_LIMIT: 134217728 +PENDING_CONSOLIDATIONS_LIMIT: 262144 + +# Reward and penalty quotients +# --------------------------------------------------------------- +MIN_SLASHING_PENALTY_QUOTIENT_ELECTRA: 4096 +WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA: 4096 + # # Max operations per block # --------------------------------------------------------------- # `uint64(2**0)` (= 1) MAX_ATTESTER_SLASHINGS_ELECTRA: 1 # `uint64(2 * 3)` (= 8) MAX_ATTESTATIONS_ELECTRA: 8 +MAX_CONSOLIDATIONS: 1 # Execution # --------------------------------------------------------------- @@ -13,3 +32,5 @@ MAX_ATTESTATIONS_ELECTRA: 8 MAX_DEPOSIT_RECEIPTS_PER_PAYLOAD: 8192 # 2**4 (= 16) exits MAX_EXECUTION_LAYER_EXITS: 16 +# 2**3 (= 8) partial withdrawals +MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD: 8 diff --git a/presets/minimal/eip7251.yaml b/presets/minimal/eip7251.yaml deleted file mode 100644 index 27ea22138..000000000 --- a/presets/minimal/eip7251.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Minimal preset - EIP7251 - -# Gwei values -# --------------------------------------------------------------- -# 2**5 * 10**9 (= 32,000,000,000) Gwei -MIN_ACTIVATION_BALANCE: 32000000000 -# 2**11 * 10**9 (= 2,048,000,000,000) Gwei -MAX_EFFECTIVE_BALANCE_EIP7251: 2048000000000 - -# State list lengths -# --------------------------------------------------------------- -PENDING_BALANCE_DEPOSITS_LIMIT: 134217728 -# [customized] smaller queue -PENDING_PARTIAL_WITHDRAWALS_LIMIT: 64 -# [customized] smaller queue -PENDING_CONSOLIDATIONS_LIMIT: 64 - -# Reward and penalty quotients -# --------------------------------------------------------------- -MIN_SLASHING_PENALTY_QUOTIENT_EIP7251: 4096 -WHISTLEBLOWER_REWARD_QUOTIENT_EIP7251: 4096 - -# Max operations per block -# --------------------------------------------------------------- -MAX_CONSOLIDATIONS: 1 - -# Execution -# --------------------------------------------------------------- -# [customized] 2**1 (= 2) -MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD: 2 diff --git a/presets/minimal/electra.yaml b/presets/minimal/electra.yaml index c7750a3cb..66d8b1fed 100644 --- a/presets/minimal/electra.yaml +++ b/presets/minimal/electra.yaml @@ -1,11 +1,32 @@ # Minimal preset - Electra +# Gwei values +# --------------------------------------------------------------- +# 2**5 * 10**9 (= 32,000,000,000) Gwei +MIN_ACTIVATION_BALANCE: 32000000000 +# 2**11 * 10**9 (= 2,048,000,000,000) Gwei +MAX_EFFECTIVE_BALANCE_ELECTRA: 2048000000000 + +# State list lengths +# --------------------------------------------------------------- +PENDING_BALANCE_DEPOSITS_LIMIT: 134217728 +# [customized] smaller queue +PENDING_PARTIAL_WITHDRAWALS_LIMIT: 64 +# [customized] smaller queue +PENDING_CONSOLIDATIONS_LIMIT: 64 + +# Reward and penalty quotients +# --------------------------------------------------------------- +MIN_SLASHING_PENALTY_QUOTIENT_ELECTRA: 4096 +WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA: 4096 + # # Max operations per block # --------------------------------------------------------------- # `uint64(2**0)` (= 1) MAX_ATTESTER_SLASHINGS_ELECTRA: 1 # `uint64(2 * 3)` (= 8) MAX_ATTESTATIONS_ELECTRA: 8 +MAX_CONSOLIDATIONS: 1 # Execution # --------------------------------------------------------------- @@ -13,3 +34,5 @@ MAX_ATTESTATIONS_ELECTRA: 8 MAX_DEPOSIT_RECEIPTS_PER_PAYLOAD: 4 # 2**4 (= 16) exits MAX_EXECUTION_LAYER_EXITS: 16 +# [customized] 2**1 (= 2) +MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD: 2 diff --git a/pysetup/constants.py b/pysetup/constants.py index 299f96132..0078b24dc 100644 --- a/pysetup/constants.py +++ b/pysetup/constants.py @@ -6,7 +6,6 @@ CAPELLA = 'capella' DENEB = 'deneb' ELECTRA = 'electra' EIP7594 = 'eip7594' -EIP7251 = 'eip7251' WHISK = 'whisk' diff --git a/pysetup/md_doc_paths.py b/pysetup/md_doc_paths.py index c7c9ebf04..a4a730e5a 100644 --- a/pysetup/md_doc_paths.py +++ b/pysetup/md_doc_paths.py @@ -9,7 +9,6 @@ from .constants import ( ELECTRA, WHISK, EIP7594, - EIP7251, ) @@ -21,7 +20,6 @@ PREVIOUS_FORK_OF = { DENEB: CAPELLA, ELECTRA: DENEB, WHISK: CAPELLA, - EIP7251: DENEB, EIP7594: DENEB, } diff --git a/pysetup/spec_builders/__init__.py b/pysetup/spec_builders/__init__.py index 63519f57f..ea74b50b7 100644 --- a/pysetup/spec_builders/__init__.py +++ b/pysetup/spec_builders/__init__.py @@ -5,7 +5,6 @@ from .capella import CapellaSpecBuilder from .deneb import DenebSpecBuilder from .electra import ElectraSpecBuilder from .whisk import WhiskSpecBuilder -from .eip7251 import EIP7251SpecBuilder from .eip7594 import EIP7594SpecBuilder @@ -13,6 +12,6 @@ spec_builders = { builder.fork: builder for builder in ( Phase0SpecBuilder, AltairSpecBuilder, BellatrixSpecBuilder, CapellaSpecBuilder, DenebSpecBuilder, - ElectraSpecBuilder, WhiskSpecBuilder, EIP7594SpecBuilder, EIP7251SpecBuilder, + ElectraSpecBuilder, WhiskSpecBuilder, EIP7594SpecBuilder, ) } diff --git a/pysetup/spec_builders/eip7251.py b/pysetup/spec_builders/eip7251.py deleted file mode 100644 index 6d9056e5f..000000000 --- a/pysetup/spec_builders/eip7251.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Dict - -from .base import BaseSpecBuilder -from ..constants import EIP7251 - - -class EIP7251SpecBuilder(BaseSpecBuilder): - fork: str = EIP7251 - - @classmethod - def imports(cls, preset_name: str): - return super().imports(preset_name) + f''' -from eth2spec.deneb import {preset_name} as deneb -''' - -## TODO: deal with changed gindices - - @classmethod - def hardcoded_ssz_dep_constants(cls) -> Dict[str, str]: - return { - 'FINALIZED_ROOT_GINDEX': 'GeneralizedIndex(169)', - 'CURRENT_SYNC_COMMITTEE_GINDEX': 'GeneralizedIndex(86)', - 'NEXT_SYNC_COMMITTEE_GINDEX': 'GeneralizedIndex(87)', - } diff --git a/pysetup/spec_builders/electra.py b/pysetup/spec_builders/electra.py index bee1e72e9..1f968a817 100644 --- a/pysetup/spec_builders/electra.py +++ b/pysetup/spec_builders/electra.py @@ -1,3 +1,4 @@ +from typing import Dict from .base import BaseSpecBuilder from ..constants import ELECTRA @@ -10,3 +11,13 @@ class ElectraSpecBuilder(BaseSpecBuilder): return f''' from eth2spec.deneb import {preset_name} as deneb ''' + +## TODO: deal with changed gindices + + @classmethod + def hardcoded_ssz_dep_constants(cls) -> Dict[str, str]: + return { + 'FINALIZED_ROOT_GINDEX': 'GeneralizedIndex(169)', + 'CURRENT_SYNC_COMMITTEE_GINDEX': 'GeneralizedIndex(86)', + 'NEXT_SYNC_COMMITTEE_GINDEX': 'GeneralizedIndex(87)', + } diff --git a/specs/_features/eip7251/fork.md b/specs/_features/eip7251/fork.md deleted file mode 100644 index 49e01ea7e..000000000 --- a/specs/_features/eip7251/fork.md +++ /dev/null @@ -1,137 +0,0 @@ -# EIP7251 -- Fork Logic - -**Notice**: This document is a work-in-progress for researchers and implementers. - -## Table of contents - - - - -- [Introduction](#introduction) -- [Configuration](#configuration) -- [Helper functions](#helper-functions) - - [Misc](#misc) - - [Modified `compute_fork_version`](#modified-compute_fork_version) -- [Fork to EIP7251](#fork-to-eip7251) - - [Fork trigger](#fork-trigger) - - [Upgrading the state](#upgrading-the-state) - - - -## Introduction - -This document describes the process of the EIP7251 upgrade. - -## Configuration - -Warning: this configuration is not definitive. - -| Name | Value | -| - | - | -| `EIP7251_FORK_VERSION` | `Version('0x06000000')` | -| `EIP7251_FORK_EPOCH` | `Epoch(18446744073709551615)` **TBD** | - -## Helper functions - -### Misc - -#### Modified `compute_fork_version` - -```python -def compute_fork_version(epoch: Epoch) -> Version: - """ - Return the fork version at the given ``epoch``. - """ - if epoch >= EIP7251_FORK_EPOCH: - return EIP7251_FORK_VERSION - if epoch >= DENEB_FORK_EPOCH: - return DENEB_FORK_VERSION - if epoch >= CAPELLA_FORK_EPOCH: - return CAPELLA_FORK_VERSION - if epoch >= BELLATRIX_FORK_EPOCH: - return BELLATRIX_FORK_VERSION - if epoch >= ALTAIR_FORK_EPOCH: - return ALTAIR_FORK_VERSION - return GENESIS_FORK_VERSION -``` - -## Fork to EIP7251 - -### Fork trigger - -TBD. This fork is defined for testing purposes, the EIP may be combined with other consensus-layer upgrade. -For now, we assume the condition will be triggered at epoch `EIP7251_FORK_EPOCH`. - -Note that for the pure EIP7251 networks, we don't apply `upgrade_to_eip7251` since it starts with EIP7251 version logic. - -### Upgrading the state - -If `state.slot % SLOTS_PER_EPOCH == 0` and `compute_epoch_at_slot(state.slot) == EIP7251_FORK_EPOCH`, -an irregular state change is made to upgrade to EIP7251. - -```python -def upgrade_to_eip7251(pre: deneb.BeaconState) -> BeaconState: - post = BeaconState( - # Versioning - genesis_time=pre.genesis_time, - genesis_validators_root=pre.genesis_validators_root, - slot=pre.slot, - fork=Fork( - previous_version=pre.fork.current_version, - current_version=EIP7251_FORK_VERSION, - epoch=deneb.get_current_epoch(pre), - ), - # History - latest_block_header=pre.latest_block_header, - block_roots=pre.block_roots, - state_roots=pre.state_roots, - historical_roots=pre.historical_roots, - # Eth1 - eth1_data=pre.eth1_data, - eth1_data_votes=pre.eth1_data_votes, - eth1_deposit_index=pre.eth1_deposit_index, - # Registry - validators=pre.validators, - balances=pre.balances, - # Randomness - randao_mixes=pre.randao_mixes, - # Slashings - slashings=pre.slashings, - # Participation - previous_epoch_participation=pre.previous_epoch_participation, - current_epoch_participation=pre.current_epoch_participation, - # Finality - justification_bits=pre.justification_bits, - previous_justified_checkpoint=pre.previous_justified_checkpoint, - current_justified_checkpoint=pre.current_justified_checkpoint, - finalized_checkpoint=pre.finalized_checkpoint, - # Inactivity - inactivity_scores=pre.inactivity_scores, - # Sync - current_sync_committee=pre.current_sync_committee, - next_sync_committee=pre.next_sync_committee, - # Execution-layer - latest_execution_payload_header=pre.latest_execution_payload_header, - # Withdrawals - next_withdrawal_index=pre.next_withdrawal_index, - next_withdrawal_validator_index=pre.next_withdrawal_validator_index, - # Deep history valid from Capella onwards - historical_summaries=pre.historical_summaries, - # [New in EIP7251] - deposit_balance_to_consume=0, - exit_balance_to_consume=get_activation_exit_churn_limit(pre), - earliest_exit_epoch=max([v.exit_epoch for v in pre.validators if v.exit_epoch != FAR_FUTURE_EPOCH]) + 1, - consolidation_balance_to_consume=get_consolidation_churn_limit(pre), - earliest_consolidation_epoch=compute_activation_exit_epoch(get_current_epoch(pre)), - pending_balance_deposits=[], - pending_partial_withdrawals=[], - pending_consolidations=[], - ) - - # Ensure early adopters of compounding credentials go through the activation churn - for index, validator in enumerate(post.validators): - if has_compounding_withdrawal_credential(validator): - queue_excess_active_balance(post, ValidatorIndex(index)) - - return post -``` diff --git a/specs/_features/eip7251/validator.md b/specs/_features/eip7251/validator.md deleted file mode 100644 index 455699383..000000000 --- a/specs/_features/eip7251/validator.md +++ /dev/null @@ -1,73 +0,0 @@ -# EIP-7251 -- Honest Validator - -## Table of contents - - - - - -- [Introduction](#introduction) -- [Prerequisites](#prerequisites) -- [Beacon chain responsibilities](#beacon-chain-responsibilities) - - [Block and sidecar proposal](#block-and-sidecar-proposal) - - [Constructing the `BeaconBlockBody`](#constructing-the-beaconblockbody) - - [ExecutionPayload](#executionpayload) - - - - -## Introduction - -This document represents the changes to be made in the code of an "honest validator". - -## Prerequisites - -This document is an extension of the [Deneb -- Honest Validator](../deneb/validator.md) guide. -All behaviors and definitions defined in this document, and documents it extends, carry over unless explicitly noted or overridden. - -All terminology, constants, functions, and protocol mechanics defined in the updated [Beacon Chain doc of EIP-7251](./beacon-chain.md) are requisite for this document and used throughout. -Please see related Beacon Chain doc before continuing and use them as a reference throughout. - -## Beacon chain responsibilities - -All validator responsibilities remain unchanged other than those noted below. - -### Block and sidecar proposal - -#### Constructing the `BeaconBlockBody` - -##### ExecutionPayload - -`prepare_execution_payload` is updated from the Deneb specs. - -*Note*: In this section, `state` is the state of the slot for the block proposal _without_ the block yet applied. -That is, `state` is the `previous_state` processed through any empty slots up to the assigned slot using `process_slots(previous_state, slot)`. - -*Note*: The only change to `prepare_execution_payload` is the new definition of `get_expected_withdrawals`. - -```python -def prepare_execution_payload(state: BeaconState, - safe_block_hash: Hash32, - finalized_block_hash: Hash32, - suggested_fee_recipient: ExecutionAddress, - execution_engine: ExecutionEngine) -> Optional[PayloadId]: - # Verify consistency of the parent hash with respect to the previous execution payload header - parent_hash = state.latest_execution_payload_header.block_hash - - # Set the forkchoice head and initiate the payload build process - withdrawals, _ = get_expected_withdrawals(state) # [Modified in EIP-7251] - - payload_attributes = PayloadAttributes( - timestamp=compute_timestamp_at_slot(state, state.slot), - prev_randao=get_randao_mix(state, get_current_epoch(state)), - suggested_fee_recipient=suggested_fee_recipient, - withdrawals=withdrawals, - parent_beacon_block_root=hash_tree_root(state.latest_block_header), - ) - return execution_engine.notify_forkchoice_updated( - head_block_hash=parent_hash, - safe_block_hash=safe_block_hash, - finalized_block_hash=finalized_block_hash, - payload_attributes=payload_attributes, - ) -``` diff --git a/specs/electra/beacon-chain.md b/specs/electra/beacon-chain.md index 23aa0553f..34caf3d6f 100644 --- a/specs/electra/beacon-chain.md +++ b/specs/electra/beacon-chain.md @@ -11,12 +11,25 @@ - [Introduction](#introduction) - [Constants](#constants) - [Misc](#misc) + - [Withdrawal prefixes](#withdrawal-prefixes) + - [Domains](#domains) - [Preset](#preset) + - [Gwei values](#gwei-values) + - [Rewards and penalties](#rewards-and-penalties) + - [State list lengths](#state-list-lengths) + - [Max operations per block](#max-operations-per-block) - [Execution](#execution) +- [Configuration](#configuration) + - [Validator cycle](#validator-cycle) - [Containers](#containers) - [New containers](#new-containers) - [`DepositReceipt`](#depositreceipt) - - [`ExecutionLayerExit`](#executionlayerexit) + - [`PendingBalanceDeposit`](#pendingbalancedeposit) + - [`PendingPartialWithdrawal`](#pendingpartialwithdrawal) + - [`ExecutionLayerWithdrawRequest`](#executionlayerwithdrawrequest) + - [`Consolidation`](#consolidation) + - [`SignedConsolidation`](#signedconsolidation) + - [`PendingConsolidation`](#pendingconsolidation) - [Extended Containers](#extended-containers) - [`Attestation`](#attestation) - [`IndexedAttestation`](#indexedattestation) @@ -27,15 +40,50 @@ - [Helper functions](#helper-functions) - [Misc](#misc-1) - [`get_committee_indices`](#get_committee_indices) + - [Predicates](#predicates) + - [Updated `is_eligible_for_activation_queue`](#updated-is_eligible_for_activation_queue) + - [New `is_compounding_withdrawal_credential`](#new-is_compounding_withdrawal_credential) + - [New `has_compounding_withdrawal_credential`](#new-has_compounding_withdrawal_credential) + - [New `has_execution_withdrawal_credential`](#new-has_execution_withdrawal_credential) + - [Updated `is_fully_withdrawable_validator`](#updated-is_fully_withdrawable_validator) + - [Updated `is_partially_withdrawable_validator`](#updated-is_partially_withdrawable_validator) - [Beacon state accessors](#beacon-state-accessors) + - [New `get_validator_max_effective_balance`](#new-get_validator_max_effective_balance) + - [New `get_churn_limit`](#new-get_churn_limit) + - [New `get_activation_exit_churn_limit`](#new-get_activation_exit_churn_limit) + - [New `get_consolidation_churn_limit`](#new-get_consolidation_churn_limit) + - [New `get_active_balance`](#new-get_active_balance) + - [New `get_pending_balance_to_withdraw`](#new-get_pending_balance_to_withdraw) - [Modified `get_attesting_indices`](#modified-get_attesting_indices) + - [Beacon state mutators](#beacon-state-mutators) + - [Updated `initiate_validator_exit`](#updated--initiate_validator_exit) + - [New `switch_to_compounding_validator`](#new-switch_to_compounding_validator) + - [New `queue_excess_active_balance`](#new-queue_excess_active_balance) + - [New `compute_exit_epoch_and_update_churn`](#new-compute_exit_epoch_and_update_churn) + - [New `compute_consolidation_epoch_and_update_churn`](#new-compute_consolidation_epoch_and_update_churn) + - [Updated `slash_validator`](#updated-slash_validator) - [Beacon chain state transition function](#beacon-chain-state-transition-function) + - [Epoch processing](#epoch-processing) + - [Updated `process_epoch`](#updated-process_epoch) + - [Updated `process_registry_updates`](#updated--process_registry_updates) + - [New `process_pending_balance_deposits`](#new-process_pending_balance_deposits) + - [New `process_pending_consolidations`](#new-process_pending_consolidations) + - [Updated `process_effective_balance_updates`](#updated-process_effective_balance_updates) - [Block processing](#block-processing) + - [Updated `get_expected_withdrawals`](#updated-get_expected_withdrawals) + - [Updated `process_withdrawals`](#updated-process_withdrawals) - [Modified `process_operations`](#modified-process_operations) - [Modified `process_attestation`](#modified-process_attestation) - - [New `process_deposit_receipt`](#new-process_deposit_receipt) - - [New `process_execution_layer_exit`](#new-process_execution_layer_exit) + - [Deposits](#deposits) + - [Updated `apply_deposit`](#updated--apply_deposit) + - [New `is_valid_deposit_signature`](#new-is_valid_deposit_signature) + - [Modified `add_validator_to_registry`](#modified-add_validator_to_registry) + - [Updated `get_validator_from_deposit`](#updated-get_validator_from_deposit) + - [New `process_deposit_receipt`](#new-process_deposit_receipt) + - [New `process_execution_layer_withdraw_request`](#new-process_execution_layer_withdraw_request) - [Modified `process_execution_payload`](#modified-process_execution_payload) + - [New `process_consolidation`](#new-process_consolidation) + - [Updated `process_voluntary_exit`](#updated-process_voluntary_exit) - [Testing](#testing) @@ -46,6 +94,7 @@ Electra is a consensus-layer upgrade containing a number of features. Including: * [EIP-6110](https://eips.ethereum.org/EIPS/eip-6110): Supply validator deposits on chain * [EIP-7002](https://eips.ethereum.org/EIPS/eip-7002): Execution layer triggerable exits +* [EIP-7251](https://eips.ethereum.org/EIPS/eip-7251): Increase the MAX_EFFECTIVE_BALANCE * [EIP-7549](https://eips.ethereum.org/EIPS/eip-7549): Move committee index outside Attestation *Note:* This specification is built upon [Deneb](../../deneb/beacon_chain.md) and is under active development. @@ -59,9 +108,52 @@ The following values are (non-configurable) constants used throughout the specif | Name | Value | Description | | - | - | - | | `UNSET_DEPOSIT_RECEIPTS_START_INDEX` | `uint64(2**64 - 1)` | *[New in Electra:EIP6110]* | +| `FULL_EXIT_REQUEST_AMOUNT` | `uint64(0)` | + +### Withdrawal prefixes + +| Name | Value | +| - | - | +| `BLS_WITHDRAWAL_PREFIX` | `Bytes1('0x00')` | +| `ETH1_ADDRESS_WITHDRAWAL_PREFIX` | `Bytes1('0x01')` | +| `COMPOUNDING_WITHDRAWAL_PREFIX` | `Bytes1('0x02')` | + +### Domains + +| Name | Value | +| - | - | +| `DOMAIN_CONSOLIDATION` | `DomainType('0x0B000000')` | ## Preset +### Gwei values + +| Name | Value | +| - | - | +| `MIN_ACTIVATION_BALANCE` | `Gwei(2**5 * 10**9)` (= 32,000,000,000) | +| `MAX_EFFECTIVE_BALANCE_ELECTRA` | `Gwei(2**11 * 10**9)` (= 2048,000,000,000) | + +### Rewards and penalties + +| Name | Value | +| - | - | +| `MIN_SLASHING_PENALTY_QUOTIENT_ELECTRA` | `uint64(2**12)` (= 4,096) | +| `WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA` | `uint64(2**12)` (= 4,096) | + +### State list lengths + +| Name | Value | Unit | +| - | - | :-: | +| `PENDING_BALANCE_DEPOSITS_LIMIT` | `uint64(2**27)` (= 134,217,728) | pending balance deposits | +| `PENDING_PARTIAL_WITHDRAWALS_LIMIT` | `uint64(2**27)` (= 134,217,728) | pending partial withdrawals | +| `PENDING_CONSOLIDATIONS_LIMIT` | `uint64(2**18)` (= 262,144) | pending consolidations | + +### Max operations per block + +| Name | Value | +| - | - | +| `MAX_CONSOLIDATIONS` | `uint64(1)` | + ### Execution | Name | Value | Description | @@ -70,6 +162,17 @@ The following values are (non-configurable) constants used throughout the specif | `MAX_EXECUTION_LAYER_EXITS` | `2**4` (= 16) | *[New in Electra:EIP7002]* | | `MAX_ATTESTER_SLASHINGS_ELECTRA` | `2**0` (= 1) | *[New in Electra:EIP7549]* | | `MAX_ATTESTATIONS_ELECTRA` | `2**3` (= 8) | *[New in Electra:EIP7549]* | +| `MAX_WITHDRAWAL_REQUESTS_PER_PAYLOAD` | `uint64(16)` | +| `MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD` | `uint64(2**3)` (= 8) | Maximum amount of partial withdrawals allowed in each payload | + +## Configuration + +### Validator cycle + +| Name | Value | +| - | - | +| `MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA` | `Gwei(2**7 * 10**9)` (= 128,000,000,000) | # Equivalent to 4 32 ETH validators +| `MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT` | `Gwei(2**8 * 10**9)` (256,000,000,000) | ## Containers @@ -88,14 +191,52 @@ class DepositReceipt(Container): index: uint64 ``` -#### `ExecutionLayerExit` - -*Note*: The container is new in EIP7002. +#### `PendingBalanceDeposit` ```python -class ExecutionLayerExit(Container): +class PendingBalanceDeposit(Container): + index: ValidatorIndex + amount: Gwei +``` + +#### `PendingPartialWithdrawal` + +```python +class PendingPartialWithdrawal(Container): + index: ValidatorIndex + amount: Gwei + withdrawable_epoch: Epoch +``` +#### `ExecutionLayerWithdrawRequest` + +```python +class ExecutionLayerWithdrawRequest(Container): source_address: ExecutionAddress validator_pubkey: BLSPubkey + amount: Gwei +``` + +#### `Consolidation` + +```python +class Consolidation(Container): + source_index: ValidatorIndex + target_index: ValidatorIndex + epoch: Epoch +``` + +#### `SignedConsolidation` +```python +class SignedConsolidation(Container): + message: Consolidation + signature: BLSSignature +``` + +#### `PendingConsolidation` +```python +class PendingConsolidation(Container): + source_index: ValidatorIndex + target_index: ValidatorIndex ``` ### Extended Containers @@ -138,6 +279,7 @@ class BeaconBlockBody(Container): execution_payload: ExecutionPayload # [Modified in Electra:EIP6110:EIP7002] bls_to_execution_changes: List[SignedBLSToExecutionChange, MAX_BLS_TO_EXECUTION_CHANGES] blob_kzg_commitments: List[KZGCommitment, MAX_BLOB_COMMITMENTS_PER_BLOCK] + consolidations: List[SignedConsolidation, MAX_CONSOLIDATIONS] # [New in Electra:EIP7251] ``` #### `ExecutionPayload` @@ -164,7 +306,8 @@ class ExecutionPayload(Container): blob_gas_used: uint64 excess_blob_gas: uint64 deposit_receipts: List[DepositReceipt, MAX_DEPOSIT_RECEIPTS_PER_PAYLOAD] # [New in Electra:EIP6110] - exits: List[ExecutionLayerExit, MAX_EXECUTION_LAYER_EXITS] # [New in Electra:EIP7002] + # [New in Electra:EIP7002:EIP7251] + withdraw_requests: List[ExecutionLayerWithdrawRequest, MAX_WITHDRAWAL_REQUESTS_PER_PAYLOAD] ``` #### `ExecutionPayloadHeader` @@ -191,7 +334,7 @@ class ExecutionPayloadHeader(Container): blob_gas_used: uint64 excess_blob_gas: uint64 deposit_receipts_root: Root # [New in Electra:EIP6110] - exits_root: Root # [New in Electra:EIP7002] + withdraw_requests_root: Root # [New in Electra:EIP7002:EIP7251] ``` #### `BeaconState` @@ -239,8 +382,16 @@ class BeaconState(Container): next_withdrawal_validator_index: ValidatorIndex # Deep history valid from Capella onwards historical_summaries: List[HistoricalSummary, HISTORICAL_ROOTS_LIMIT] - # [New in Electra:EIP6110] - deposit_receipts_start_index: uint64 + deposit_receipts_start_index: uint64 # [New in Electra:EIP6110] + deposit_balance_to_consume: Gwei # [New in Electra:EIP7251] + exit_balance_to_consume: Gwei # [New in Electra:EIP7251] + earliest_exit_epoch: Epoch # [New in Electra:EIP7251] + consolidation_balance_to_consume: Gwei # [New in Electra:EIP7251] + earliest_consolidation_epoch: Epoch # [New in Electra:EIP7251] + pending_balance_deposits: List[PendingBalanceDeposit, PENDING_BALANCE_DEPOSITS_LIMIT] # [New in Electra:EIP7251] + # [New in Electra:EIP7251] + pending_partial_withdrawals: List[PendingPartialWithdrawal, PENDING_PARTIAL_WITHDRAWALS_LIMIT] + pending_consolidations: List[PendingConsolidation, PENDING_CONSOLIDATIONS_LIMIT] # [New in Electra:EIP7251] ``` ## Helper functions @@ -254,8 +405,141 @@ def get_committee_indices(commitee_bits: Bitvector) -> Sequence[CommitteeIndex]: return [CommitteeIndex(index) for index, bit in enumerate(commitee_bits) if bit] ``` +### Predicates + +#### Updated `is_eligible_for_activation_queue` + +```python +def is_eligible_for_activation_queue(validator: Validator) -> bool: + """ + Check if ``validator`` is eligible to be placed into the activation queue. + """ + return ( + validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH + and validator.effective_balance >= MIN_ACTIVATION_BALANCE # [Modified in Electra:EIP7251] + ) +``` + +#### New `is_compounding_withdrawal_credential` + +```python +def is_compounding_withdrawal_credential(withdrawal_credentials: Bytes32) -> bool: + return withdrawal_credentials[:1] == COMPOUNDING_WITHDRAWAL_PREFIX +``` + +#### New `has_compounding_withdrawal_credential` + +```python +def has_compounding_withdrawal_credential(validator: Validator) -> bool: + """ + Check if ``validator`` has an 0x02 prefixed "compounding" withdrawal credential. + """ + return is_compounding_withdrawal_credential(validator.withdrawal_credentials) +``` + +#### New `has_execution_withdrawal_credential` + +```python +def has_execution_withdrawal_credential(validator: Validator) -> bool: + """ + Check if ``validator`` has a 0x01 or 0x02 prefixed withdrawal credential. + """ + return has_compounding_withdrawal_credential(validator) or has_eth1_withdrawal_credential(validator) +``` + +#### Updated `is_fully_withdrawable_validator` + +```python +def is_fully_withdrawable_validator(validator: Validator, balance: Gwei, epoch: Epoch) -> bool: + """ + Check if ``validator`` is fully withdrawable. + """ + return ( + has_execution_withdrawal_credential(validator) # [Modified in Electra:EIP7251] + and validator.withdrawable_epoch <= epoch + and balance > 0 + ) +``` + +#### Updated `is_partially_withdrawable_validator` + +```python +def is_partially_withdrawable_validator(validator: Validator, balance: Gwei) -> bool: + """ + Check if ``validator`` is partially withdrawable. + """ + max_effective_balance = get_validator_max_effective_balance(validator) + has_max_effective_balance = validator.effective_balance == max_effective_balance # [Modified in Electra:EIP7251] + has_excess_balance = balance > max_effective_balance # [Modified in Electra:EIP7251] + return ( + has_execution_withdrawal_credential(validator) # [Modified in Electra:EIP7251] + and has_max_effective_balance + and has_excess_balance + ) +``` + ### Beacon state accessors +#### New `get_validator_max_effective_balance` + +```python +def get_validator_max_effective_balance(validator: Validator) -> Gwei: + """ + Get max effective balance for ``validator``. + """ + if has_compounding_withdrawal_credential(validator): + return MAX_EFFECTIVE_BALANCE_ELECTRA + else: + return MIN_ACTIVATION_BALANCE +``` + +#### New `get_churn_limit` + +```python +def get_churn_limit(state: BeaconState) -> Gwei: + """ + Return the churn limit for the current epoch. + """ + churn = max( + MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA, + get_total_active_balance(state) // CHURN_LIMIT_QUOTIENT + ) + return churn - churn % EFFECTIVE_BALANCE_INCREMENT +``` + +#### New `get_activation_exit_churn_limit` + +```python +def get_activation_exit_churn_limit(state: BeaconState) -> Gwei: + """ + Return the churn limit for the current epoch dedicated to activations and exits. + """ + return min(MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT, get_churn_limit(state)) +``` + +#### New `get_consolidation_churn_limit` + +```python +def get_consolidation_churn_limit(state: BeaconState) -> Gwei: + return get_churn_limit(state) - get_activation_exit_churn_limit(state) +``` + +#### New `get_active_balance` + +```python +def get_active_balance(state: BeaconState, validator_index: ValidatorIndex) -> Gwei: + max_effective_balance = get_validator_max_effective_balance(state.validators[validator_index]) + return min(state.balances[validator_index], max_effective_balance) +``` + +#### New `get_pending_balance_to_withdraw` + +```python +def get_pending_balance_to_withdraw(state: BeaconState, validator_index: ValidatorIndex) -> Gwei: + return sum( + withdrawal.amount for withdrawal in state.pending_partial_withdrawals if withdrawal.index == validator_index) +``` + #### Modified `get_attesting_indices` ```python @@ -277,24 +561,353 @@ def get_attesting_indices(state: BeaconState, attestation: Attestation) -> Set[V return output ``` +### Beacon state mutators + +#### Updated `initiate_validator_exit` + +```python +def initiate_validator_exit(state: BeaconState, index: ValidatorIndex) -> None: + """ + Initiate the exit of the validator with index ``index``. + """ + # Return if validator already initiated exit + validator = state.validators[index] + if validator.exit_epoch != FAR_FUTURE_EPOCH: + return + + # Compute exit queue epoch [Modified in Electra:EIP7251] + exit_queue_epoch = compute_exit_epoch_and_update_churn(state, validator.effective_balance) + + # Set validator exit epoch and withdrawable epoch + validator.exit_epoch = exit_queue_epoch + validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY) +``` + +#### New `switch_to_compounding_validator` + +```python +def switch_to_compounding_validator(state: BeaconState, index: ValidatorIndex) -> None: + validator = state.validators[index] + if has_eth1_withdrawal_credential(validator): + validator.withdrawal_credentials[:1] = COMPOUNDING_WITHDRAWAL_PREFIX + queue_excess_active_balance(state, index) +``` + +#### New `queue_excess_active_balance` + +```python +def queue_excess_active_balance(state: BeaconState, index: ValidatorIndex) -> None: + balance = state.balances[index] + if balance > MIN_ACTIVATION_BALANCE: + excess_balance = balance - MIN_ACTIVATION_BALANCE + state.balances[index] = MIN_ACTIVATION_BALANCE + state.pending_balance_deposits.append( + PendingBalanceDeposit(index=index, amount=excess_balance) + ) +``` + +#### New `compute_exit_epoch_and_update_churn` + +```python +def compute_exit_epoch_and_update_churn(state: BeaconState, exit_balance: Gwei) -> Epoch: + earliest_exit_epoch = compute_activation_exit_epoch(get_current_epoch(state)) + per_epoch_churn = get_activation_exit_churn_limit(state) + # New epoch for exits. + if state.earliest_exit_epoch < earliest_exit_epoch: + state.earliest_exit_epoch = earliest_exit_epoch + state.exit_balance_to_consume = per_epoch_churn + + if exit_balance <= state.exit_balance_to_consume: + # Exit fits in the current earliest epoch. + state.exit_balance_to_consume -= exit_balance + else: + # Exit doesn't fit in the current earliest epoch. + balance_to_process = exit_balance - state.exit_balance_to_consume + additional_epochs, remainder = divmod(balance_to_process, per_epoch_churn) + state.earliest_exit_epoch += additional_epochs + 1 + state.exit_balance_to_consume = per_epoch_churn - remainder + + return state.earliest_exit_epoch +``` + +#### New `compute_consolidation_epoch_and_update_churn` + +```python +def compute_consolidation_epoch_and_update_churn(state: BeaconState, consolidation_balance: Gwei) -> Epoch: + earliest_consolidation_epoch = compute_activation_exit_epoch(get_current_epoch(state)) + per_epoch_consolidation_churn = get_consolidation_churn_limit(state) + # New epoch for consolidations. + if state.earliest_consolidation_epoch < earliest_consolidation_epoch: + state.earliest_consolidation_epoch = earliest_consolidation_epoch + state.consolidation_balance_to_consume = per_epoch_consolidation_churn + + if consolidation_balance <= state.consolidation_balance_to_consume: + # Consolidation fits in the current earliest consolidation epoch. + state.consolidation_balance_to_consume -= consolidation_balance + else: + # Consolidation doesn't fit in the current earliest epoch. + balance_to_process = consolidation_balance - state.consolidation_balance_to_consume + additional_epochs, remainder = divmod(balance_to_process, per_epoch_consolidation_churn) + state.earliest_consolidation_epoch += additional_epochs + 1 + state.consolidation_balance_to_consume = per_epoch_consolidation_churn - remainder + + return state.earliest_consolidation_epoch +``` + +#### Updated `slash_validator` + +```python +def slash_validator(state: BeaconState, + slashed_index: ValidatorIndex, + whistleblower_index: ValidatorIndex=None) -> None: + """ + Slash the validator with index ``slashed_index``. + """ + epoch = get_current_epoch(state) + initiate_validator_exit(state, slashed_index) + validator = state.validators[slashed_index] + validator.slashed = True + validator.withdrawable_epoch = max(validator.withdrawable_epoch, Epoch(epoch + EPOCHS_PER_SLASHINGS_VECTOR)) + state.slashings[epoch % EPOCHS_PER_SLASHINGS_VECTOR] += validator.effective_balance + # [Modified in Electra:EIP7251] + slashing_penalty = validator.effective_balance // MIN_SLASHING_PENALTY_QUOTIENT_ELECTRA + decrease_balance(state, slashed_index, slashing_penalty) + + # Apply proposer and whistleblower rewards + proposer_index = get_beacon_proposer_index(state) + if whistleblower_index is None: + whistleblower_index = proposer_index + whistleblower_reward = Gwei( + validator.effective_balance // WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA) # [Modified in Electra:EIP7251] + proposer_reward = Gwei(whistleblower_reward * PROPOSER_WEIGHT // WEIGHT_DENOMINATOR) + increase_balance(state, proposer_index, proposer_reward) + increase_balance(state, whistleblower_index, Gwei(whistleblower_reward - proposer_reward)) +``` + ## Beacon chain state transition function +### Epoch processing + +#### Updated `process_epoch` +```python +def process_epoch(state: BeaconState) -> None: + process_justification_and_finalization(state) + process_inactivity_updates(state) + process_rewards_and_penalties(state) + process_registry_updates(state) # [Modified in Electra:EIP7251] + process_slashings(state) + process_eth1_data_reset(state) + process_pending_balance_deposits(state) # [New in Electra:EIP7251] + process_pending_consolidations(state) # [New in Electra:EIP7251] + process_effective_balance_updates(state) # [Modified in Electra:EIP7251] + process_slashings_reset(state) + process_randao_mixes_reset(state) + process_historical_summaries_update(state) + process_participation_flag_updates(state) + process_sync_committee_updates(state) +``` + +#### Updated `process_registry_updates` + +`process_registry_updates` uses the updated definition of `initiate_validator_exit` +and changes how the activation epochs are computed for eligible validators. + +```python +def process_registry_updates(state: BeaconState) -> None: + # Process activation eligibility and ejections + for index, validator in enumerate(state.validators): + if is_eligible_for_activation_queue(validator): + validator.activation_eligibility_epoch = get_current_epoch(state) + 1 + + if ( + is_active_validator(validator, get_current_epoch(state)) + and validator.effective_balance <= EJECTION_BALANCE + ): + initiate_validator_exit(state, ValidatorIndex(index)) + + # Activate all eligible validators + activation_epoch = compute_activation_exit_epoch(get_current_epoch(state)) + for validator in state.validators: + if is_eligible_for_activation(state, validator): + validator.activation_epoch = activation_epoch +``` + +#### New `process_pending_balance_deposits` + +```python +def process_pending_balance_deposits(state: BeaconState) -> None: + available_for_processing = state.deposit_balance_to_consume + get_activation_exit_churn_limit(state) + processed_amount = 0 + next_deposit_index = 0 + + for deposit in state.pending_balance_deposits: + if processed_amount + deposit.amount > available_for_processing: + break + increase_balance(state, deposit.index, deposit.amount) + processed_amount += deposit.amount + next_deposit_index += 1 + + state.pending_balance_deposits = state.pending_balance_deposits[next_deposit_index:] + + if len(state.pending_balance_deposits) == 0: + state.deposit_balance_to_consume = Gwei(0) + else: + state.deposit_balance_to_consume = available_for_processing - processed_amount +``` + +#### New `process_pending_consolidations` + +```python +def process_pending_consolidations(state: BeaconState) -> None: + next_pending_consolidation = 0 + for pending_consolidation in state.pending_consolidations: + source_validator = state.validators[pending_consolidation.source_index] + if source_validator.slashed: + next_pending_consolidation += 1 + continue + if source_validator.withdrawable_epoch > get_current_epoch(state): + break + + # Churn any target excess active balance of target and raise its max + switch_to_compounding_validator(state, pending_consolidation.target_index) + # Move active balance to target. Excess balance is withdrawable. + active_balance = get_active_balance(state, pending_consolidation.source_index) + decrease_balance(state, pending_consolidation.source_index, active_balance) + increase_balance(state, pending_consolidation.target_index, active_balance) + next_pending_consolidation += 1 + + state.pending_consolidations = state.pending_consolidations[next_pending_consolidation:] +``` + +#### Updated `process_effective_balance_updates` + +`process_effective_balance_updates` is updated with a new limit for the maximum effective balance. + +```python +def process_effective_balance_updates(state: BeaconState) -> None: + # Update effective balances with hysteresis + for index, validator in enumerate(state.validators): + balance = state.balances[index] + HYSTERESIS_INCREMENT = uint64(EFFECTIVE_BALANCE_INCREMENT // HYSTERESIS_QUOTIENT) + DOWNWARD_THRESHOLD = HYSTERESIS_INCREMENT * HYSTERESIS_DOWNWARD_MULTIPLIER + UPWARD_THRESHOLD = HYSTERESIS_INCREMENT * HYSTERESIS_UPWARD_MULTIPLIER + EFFECTIVE_BALANCE_LIMIT = ( + MAX_EFFECTIVE_BALANCE_ELECTRA if has_compounding_withdrawal_credential(validator) + else MIN_ACTIVATION_BALANCE + ) + + if ( + balance + DOWNWARD_THRESHOLD < validator.effective_balance + or validator.effective_balance + UPWARD_THRESHOLD < balance + ): + validator.effective_balance = min(balance - balance % EFFECTIVE_BALANCE_INCREMENT, EFFECTIVE_BALANCE_LIMIT) +``` + ### Block processing ```python def process_block(state: BeaconState, block: BeaconBlock) -> None: process_block_header(state, block) - process_withdrawals(state, block.body.execution_payload) + process_withdrawals(state, block.body.execution_payload) # [Modified in Electra:EIP7251] process_execution_payload(state, block.body, EXECUTION_ENGINE) # [Modified in Electra:EIP6110] process_randao(state, block.body) process_eth1_data(state, block.body) - process_operations(state, block.body) # [Modified in Electra:EIP6110:EIP7002:EIP7549] + process_operations(state, block.body) # [Modified in Electra:EIP6110:EIP7002:EIP7549:EIP7251] process_sync_aggregate(state, block.body.sync_aggregate) ``` +#### Updated `get_expected_withdrawals` + +```python +def get_expected_withdrawals(state: BeaconState) -> Tuple[Sequence[Withdrawal], uint64]: + epoch = get_current_epoch(state) + withdrawal_index = state.next_withdrawal_index + validator_index = state.next_withdrawal_validator_index + withdrawals: List[Withdrawal] = [] + + # [New in Electra:EIP7251] Consume pending partial withdrawals + for withdrawal in state.pending_partial_withdrawals: + if withdrawal.withdrawable_epoch > epoch or len(withdrawals) == MAX_PARTIAL_WITHDRAWALS_PER_PAYLOAD: + break + + validator = state.validators[withdrawal.index] + has_sufficient_effective_balance = validator.effective_balance >= MIN_ACTIVATION_BALANCE + has_excess_balance = state.balances[withdrawal.index] > MIN_ACTIVATION_BALANCE + if validator.exit_epoch == FAR_FUTURE_EPOCH and has_sufficient_effective_balance and has_excess_balance: + withdrawable_balance = min(state.balances[withdrawal.index] - MIN_ACTIVATION_BALANCE, withdrawal.amount) + withdrawals.append(Withdrawal( + index=withdrawal_index, + validator_index=withdrawal.index, + address=ExecutionAddress(validator.withdrawal_credentials[12:]), + amount=withdrawable_balance, + )) + withdrawal_index += WithdrawalIndex(1) + + partial_withdrawals_count = len(withdrawals) + + # Sweep for remaining. + bound = min(len(state.validators), MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP) + for _ in range(bound): + validator = state.validators[validator_index] + balance = state.balances[validator_index] + if is_fully_withdrawable_validator(validator, balance, epoch): + withdrawals.append(Withdrawal( + index=withdrawal_index, + validator_index=validator_index, + address=ExecutionAddress(validator.withdrawal_credentials[12:]), + amount=balance, + )) + withdrawal_index += WithdrawalIndex(1) + elif is_partially_withdrawable_validator(validator, balance): + withdrawals.append(Withdrawal( + index=withdrawal_index, + validator_index=validator_index, + address=ExecutionAddress(validator.withdrawal_credentials[12:]), + amount=balance - get_validator_max_effective_balance(validator), # [Modified in Electra:EIP7251] + )) + withdrawal_index += WithdrawalIndex(1) + if len(withdrawals) == MAX_WITHDRAWALS_PER_PAYLOAD: + break + validator_index = ValidatorIndex((validator_index + 1) % len(state.validators)) + return withdrawals, partial_withdrawals_count +``` + +#### Updated `process_withdrawals` + +```python +def process_withdrawals(state: BeaconState, payload: ExecutionPayload) -> None: + expected_withdrawals, partial_withdrawals_count = get_expected_withdrawals(state) # [Modified in Electra:EIP7251] + + assert len(payload.withdrawals) == len(expected_withdrawals) + + for expected_withdrawal, withdrawal in zip(expected_withdrawals, payload.withdrawals): + assert withdrawal == expected_withdrawal + decrease_balance(state, withdrawal.validator_index, withdrawal.amount) + + # Update pending partial withdrawals [New in Electra:EIP7251] + state.pending_partial_withdrawals = state.pending_partial_withdrawals[partial_withdrawals_count:] + + # Update the next withdrawal index if this block contained withdrawals + if len(expected_withdrawals) != 0: + latest_withdrawal = expected_withdrawals[-1] + state.next_withdrawal_index = WithdrawalIndex(latest_withdrawal.index + 1) + + # Update the next validator index to start the next withdrawal sweep + if len(expected_withdrawals) == MAX_WITHDRAWALS_PER_PAYLOAD: + # Next sweep starts after the latest withdrawal's validator index + next_validator_index = ValidatorIndex((expected_withdrawals[-1].validator_index + 1) % len(state.validators)) + state.next_withdrawal_validator_index = next_validator_index + else: + # Advance sweep by the max length of the sweep if there was not a full set of withdrawals + next_index = state.next_withdrawal_validator_index + MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP + next_validator_index = ValidatorIndex(next_index % len(state.validators)) + state.next_withdrawal_validator_index = next_validator_index +``` + + #### Modified `process_operations` -*Note*: The function `process_operations` is modified to process `DepositReceipt` and `ExecutionLayerExit` operations included in the payload, along with the new attestation format. +*Note*: The function `process_operations` is modified to support all of the new functionality in Electra. ```python def process_operations(state: BeaconState, body: BeaconBlockBody) -> None: @@ -313,13 +926,13 @@ def process_operations(state: BeaconState, body: BeaconBlockBody) -> None: for_ops(body.proposer_slashings, process_proposer_slashing) for_ops(body.attester_slashings, process_attester_slashing) for_ops(body.attestations, process_attestation) # [Modified in Electra:EIP7549] - for_ops(body.deposits, process_deposit) - for_ops(body.voluntary_exits, process_voluntary_exit) - for_ops(body.execution_payload.exits, process_execution_layer_exit) # [New in Electra:EIP7002] + for_ops(body.deposits, process_deposit) # [Modified in Electra:EIP7251] + for_ops(body.voluntary_exits, process_voluntary_exit) # [Modified in Electra:EIP7251] for_ops(body.bls_to_execution_changes, process_bls_to_execution_change) - - # [New in EIP6110] - for_ops(body.execution_payload.deposit_receipts, process_deposit_receipt) + # [New in Electra:EIP7002:EIP7251] + for_ops(body.execution_payload.withdraw_requests, process_execution_layer_withdraw_request) + for_ops(body.execution_payload.deposit_receipts, process_deposit_receipt) # [New in Electra:EIP6110] + for_ops(body.consolidations, process_consolidation) # [New in Electra:EIP7251] ``` #### Modified `process_attestation` @@ -367,7 +980,89 @@ def process_attestation(state: BeaconState, attestation: Attestation) -> None: increase_balance(state, get_beacon_proposer_index(state), proposer_reward) ``` -#### New `process_deposit_receipt` +##### Deposits + +##### Updated `apply_deposit` + +*NOTE*: `process_deposit` is updated with a new definition of `apply_deposit`. + +```python +def apply_deposit(state: BeaconState, + pubkey: BLSPubkey, + withdrawal_credentials: Bytes32, + amount: uint64, + signature: BLSSignature) -> None: + validator_pubkeys = [v.pubkey for v in state.validators] + if pubkey not in validator_pubkeys: + # Verify the deposit signature (proof of possession) which is not checked by the deposit contract + if is_valid_deposit_signature(pubkey, withdrawal_credentials, amount, signature): + add_validator_to_registry(state, pubkey, withdrawal_credentials, amount) + else: + # Increase balance by deposit amount + index = ValidatorIndex(validator_pubkeys.index(pubkey)) + state.pending_balance_deposits.append( + PendingBalanceDeposit(index=index, amount=amount) + ) # [Modified in Electra:EIP-7251] + # Check if valid deposit switch to compounding credentials + if ( + is_compounding_withdrawal_credential(withdrawal_credentials) + and has_eth1_withdrawal_credential(state.validators[index]) + and is_valid_deposit_signature(pubkey, withdrawal_credentials, amount, signature) + ): + switch_to_compounding_validator(state, index) + +``` + +##### New `is_valid_deposit_signature` + +```python +def is_valid_deposit_signature(pubkey: BLSPubkey, + withdrawal_credentials: Bytes32, + amount: uint64, + signature: BLSSignature) -> bool: + deposit_message = DepositMessage( + pubkey=pubkey, + withdrawal_credentials=withdrawal_credentials, + amount=amount, + ) + domain = compute_domain(DOMAIN_DEPOSIT) # Fork-agnostic domain since deposits are valid across forks + signing_root = compute_signing_root(deposit_message, domain) + return bls.Verify(pubkey, signing_root, signature) +``` + +##### Modified `add_validator_to_registry` + +```python +def add_validator_to_registry(state: BeaconState, + pubkey: BLSPubkey, + withdrawal_credentials: Bytes32, + amount: uint64) -> None: + index = get_index_for_new_validator(state) + validator = get_validator_from_deposit(pubkey, withdrawal_credentials) + set_or_append_list(state.validators, index, validator) + set_or_append_list(state.balances, index, 0) # [Modified in Electra:EIP7251] + set_or_append_list(state.previous_epoch_participation, index, ParticipationFlags(0b0000_0000)) + set_or_append_list(state.current_epoch_participation, index, ParticipationFlags(0b0000_0000)) + set_or_append_list(state.inactivity_scores, index, uint64(0)) + state.pending_balance_deposits.append(PendingBalanceDeposit(index=index, amount=amount)) # [New in Electra:EIP7251] +``` + +##### Updated `get_validator_from_deposit` + +```python +def get_validator_from_deposit(pubkey: BLSPubkey, withdrawal_credentials: Bytes32) -> Validator: + return Validator( + pubkey=pubkey, + withdrawal_credentials=withdrawal_credentials, + activation_eligibility_epoch=FAR_FUTURE_EPOCH, + activation_epoch=FAR_FUTURE_EPOCH, + exit_epoch=FAR_FUTURE_EPOCH, + withdrawable_epoch=FAR_FUTURE_EPOCH, + effective_balance=0, # [Modified in Electra:EIP7251] + ) +``` + +##### New `process_deposit_receipt` *Note*: This function is new in Electra:EIP6110. @@ -386,23 +1081,33 @@ def process_deposit_receipt(state: BeaconState, deposit_receipt: DepositReceipt) ) ``` -#### New `process_execution_layer_exit` +#### New `process_execution_layer_withdraw_request` -*Note*: This function is new in Electra:EIP7002. +*Note*: This function is new in Electra following EIP-7002 and EIP-7251. ```python -def process_execution_layer_exit(state: BeaconState, execution_layer_exit: ExecutionLayerExit) -> None: +def process_execution_layer_withdraw_request( + state: BeaconState, + execution_layer_withdraw_request: ExecutionLayerWithdrawRequest +) -> None: + amount = execution_layer_withdraw_request.amount + is_full_exit_request = amount == FULL_EXIT_REQUEST_AMOUNT + + # If partial withdrawal queue is full, only full exits are processed + if len(state.pending_partial_withdrawals) >= PENDING_PARTIAL_WITHDRAWALS_LIMIT and not is_full_exit_request: + return + validator_pubkeys = [v.pubkey for v in state.validators] # Verify pubkey exists - pubkey_to_exit = execution_layer_exit.validator_pubkey - if pubkey_to_exit not in validator_pubkeys: + request_pubkey = execution_layer_withdraw_request.validator_pubkey + if request_pubkey not in validator_pubkeys: return - validator_index = ValidatorIndex(validator_pubkeys.index(pubkey_to_exit)) - validator = state.validators[validator_index] + index = ValidatorIndex(validator_pubkeys.index(request_pubkey)) + validator = state.validators[index] # Verify withdrawal credentials is_execution_address = validator.withdrawal_credentials[:1] == ETH1_ADDRESS_WITHDRAWAL_PREFIX - is_correct_source_address = validator.withdrawal_credentials[12:] == execution_layer_exit.source_address + is_correct_source_address = validator.withdrawal_credentials[12:] == execution_layer_withdraw_request.source_address if not (is_execution_address and is_correct_source_address): return # Verify the validator is active @@ -415,8 +1120,31 @@ def process_execution_layer_exit(state: BeaconState, execution_layer_exit: Execu if get_current_epoch(state) < validator.activation_epoch + SHARD_COMMITTEE_PERIOD: return - # Initiate exit - initiate_validator_exit(state, validator_index) + pending_balance_to_withdraw = get_pending_balance_to_withdraw(state, index) + + if is_full_exit_request: + # Only exit validator if it has no pending withdrawals in the queue + if pending_balance_to_withdraw == 0: + initiate_validator_exit(state, index) + + return + + has_sufficient_effective_balance = validator.effective_balance >= MIN_ACTIVATION_BALANCE + has_excess_balance = state.balances[index] > MIN_ACTIVATION_BALANCE + pending_balance_to_withdraw + + # Only allow partial withdrawals with compounding withdrawal credentials + if has_compounding_withdrawal_credential(validator) and has_sufficient_effective_balance and has_excess_balance: + to_withdraw = min( + state.balances[index] - MIN_ACTIVATION_BALANCE - pending_balance_to_withdraw, + amount + ) + exit_queue_epoch = compute_exit_epoch_and_update_churn(state, to_withdraw) + withdrawable_epoch = Epoch(exit_queue_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY) + state.pending_partial_withdrawals.append(PendingPartialWithdrawal( + index=index, + amount=to_withdraw, + withdrawable_epoch=withdrawable_epoch, + )) ``` #### Modified `process_execution_payload` @@ -464,10 +1192,82 @@ def process_execution_payload(state: BeaconState, body: BeaconBlockBody, executi blob_gas_used=payload.blob_gas_used, excess_blob_gas=payload.excess_blob_gas, deposit_receipts_root=hash_tree_root(payload.deposit_receipts), # [New in Electra:EIP6110] - exits_root=hash_tree_root(payload.exits), # [New in Electra:EIP7002] + withdraw_requests_root=hash_tree_root(payload.withdraw_requests), # [New in Electra:EIP7002:EIP7251] ) ``` +#### New `process_consolidation` + +```python +def process_consolidation(state: BeaconState, signed_consolidation: SignedConsolidation) -> None: + # If the pending consolidations queue is full, no consolidations are allowed in the block + assert len(state.pending_consolidations) < PENDING_CONSOLIDATIONS_LIMIT + # If there is too little available consolidation churn limit, no consolidations are allowed in the block + assert get_consolidation_churn_limit(state) > MIN_ACTIVATION_BALANCE + consolidation = signed_consolidation.message + # Verify that source != target, so a consolidation cannot be used as an exit. + assert consolidation.source_index != consolidation.target_index + + source_validator = state.validators[consolidation.source_index] + target_validator = state.validators[consolidation.target_index] + # Verify the source and the target are active + current_epoch = get_current_epoch(state) + assert is_active_validator(source_validator, current_epoch) + assert is_active_validator(target_validator, current_epoch) + # Verify exits for source and target have not been initiated + assert source_validator.exit_epoch == FAR_FUTURE_EPOCH + assert target_validator.exit_epoch == FAR_FUTURE_EPOCH + # Consolidations must specify an epoch when they become valid; they are not valid before then + assert current_epoch >= consolidation.epoch + + # Verify the source and the target have Execution layer withdrawal credentials + assert has_execution_withdrawal_credential(source_validator) + assert has_execution_withdrawal_credential(target_validator) + # Verify the same withdrawal address + assert source_validator.withdrawal_credentials[12:] == target_validator.withdrawal_credentials[12:] + + # Verify consolidation is signed by the source and the target + domain = compute_domain(DOMAIN_CONSOLIDATION, genesis_validators_root=state.genesis_validators_root) + signing_root = compute_signing_root(consolidation, domain) + pubkeys = [source_validator.pubkey, target_validator.pubkey] + assert bls.FastAggregateVerify(pubkeys, signing_root, signed_consolidation.signature) + + # Initiate source validator exit and append pending consolidation + source_validator.exit_epoch = compute_consolidation_epoch_and_update_churn( + state, source_validator.effective_balance) + source_validator.withdrawable_epoch = Epoch( + source_validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY + ) + state.pending_consolidations.append(PendingConsolidation( + source_index=consolidation.source_index, + target_index=consolidation.target_index + )) +``` + +#### Updated `process_voluntary_exit` + +```python +def process_voluntary_exit(state: BeaconState, signed_voluntary_exit: SignedVoluntaryExit) -> None: + voluntary_exit = signed_voluntary_exit.message + validator = state.validators[voluntary_exit.validator_index] + # Verify the validator is active + assert is_active_validator(validator, get_current_epoch(state)) + # Verify exit has not been initiated + assert validator.exit_epoch == FAR_FUTURE_EPOCH + # Exits must specify an epoch when they become valid; they are not valid before then + assert get_current_epoch(state) >= voluntary_exit.epoch + # Verify the validator has been active long enough + assert get_current_epoch(state) >= validator.activation_epoch + SHARD_COMMITTEE_PERIOD + # Only exit validator if it has no pending withdrawals in the queue + assert get_pending_balance_to_withdraw(state, voluntary_exit.validator_index) == 0 # [New in Electra:EIP7251] + # Verify signature + domain = compute_domain(DOMAIN_VOLUNTARY_EXIT, CAPELLA_FORK_VERSION, state.genesis_validators_root) + signing_root = compute_signing_root(voluntary_exit, domain) + assert bls.Verify(validator.pubkey, signing_root, signed_voluntary_exit.signature) + # Initiate exit + initiate_validator_exit(state, voluntary_exit.validator_index) +``` + ## Testing *Note*: The function `initialize_beacon_state_from_eth1` is modified for pure Electra testing only. @@ -475,6 +1275,7 @@ Modifications include: 1. Use `ELECTRA_FORK_VERSION` as the previous and current fork version. 2. Utilize the Electra `BeaconBlockBody` when constructing the initial `latest_block_header`. 3. *[New in Electra:EIP6110]* Add `deposit_receipts_start_index` variable to the genesis state initialization. +4. *[New in Electra:EIP7251]* Initialize new fields to support increasing the maximum effective balance. ```python def initialize_beacon_state_from_eth1(eth1_block_hash: Hash32, @@ -503,6 +1304,11 @@ def initialize_beacon_state_from_eth1(eth1_block_hash: Hash32, state.eth1_data.deposit_root = hash_tree_root(deposit_data_list) process_deposit(state, deposit) + # Process deposit balance updates + for deposit in state.pending_balance_deposits: + increase_balance(state, deposit.index, deposit.amount) + state.pending_balance_deposits = [] + # Process activations for index, validator in enumerate(state.validators): balance = state.balances[index] diff --git a/specs/electra/fork.md b/specs/electra/fork.md index 43670afa0..afc9e0912 100644 --- a/specs/electra/fork.md +++ b/specs/electra/fork.md @@ -139,9 +139,24 @@ def upgrade_to_electra(pre: deneb.BeaconState) -> BeaconState: next_withdrawal_validator_index=pre.next_withdrawal_validator_index, # Deep history valid from Capella onwards historical_summaries=pre.historical_summaries, - # EIP6110 - deposit_receipts_start_index=UNSET_DEPOSIT_RECEIPTS_START_INDEX, # [New in Electra:EIP6110] + # [New in Electra:EIP6110] + deposit_receipts_start_index=UNSET_DEPOSIT_RECEIPTS_START_INDEX, + # [New in Electra:EIP7251] + deposit_balance_to_consume=0, + exit_balance_to_consume=get_activation_exit_churn_limit(pre), + earliest_exit_epoch=max([v.exit_epoch for v in pre.validators if v.exit_epoch != FAR_FUTURE_EPOCH]) + 1, + consolidation_balance_to_consume=get_consolidation_churn_limit(pre), + earliest_consolidation_epoch=compute_activation_exit_epoch(get_current_epoch(pre)), + pending_balance_deposits=[], + pending_partial_withdrawals=[], + pending_consolidations=[], ) + # [New in Electra:EIP7251] + # Ensure early adopters of compounding credentials go through the activation churn + for index, validator in enumerate(post.validators): + if has_compounding_withdrawal_credential(validator): + queue_excess_active_balance(post, ValidatorIndex(index)) + return post ``` diff --git a/specs/electra/validator.md b/specs/electra/validator.md index 31cbd3e63..55c7bee88 100644 --- a/specs/electra/validator.md +++ b/specs/electra/validator.md @@ -13,6 +13,7 @@ - [Attester slashings](#attester-slashings) - [Attestations](#attestations) - [Deposits](#deposits) + - [Execution payload](#execution-payload) - [Attesting](#attesting) - [Construct attestation](#construct-attestation) - [Attestation aggregation](#attestation-aggregation) @@ -81,6 +82,42 @@ def get_eth1_pending_deposit_count(state: BeaconState) -> uint64: return uint64(0) ``` +#### Execution payload + +`prepare_execution_payload` is updated from the Deneb specs. + +*Note*: In this section, `state` is the state of the slot for the block proposal _without_ the block yet applied. +That is, `state` is the `previous_state` processed through any empty slots up to the assigned slot using `process_slots(previous_state, slot)`. + +*Note*: The only change to `prepare_execution_payload` is the new definition of `get_expected_withdrawals`. + +```python +def prepare_execution_payload(state: BeaconState, + safe_block_hash: Hash32, + finalized_block_hash: Hash32, + suggested_fee_recipient: ExecutionAddress, + execution_engine: ExecutionEngine) -> Optional[PayloadId]: + # Verify consistency of the parent hash with respect to the previous execution payload header + parent_hash = state.latest_execution_payload_header.block_hash + + # Set the forkchoice head and initiate the payload build process + withdrawals, _ = get_expected_withdrawals(state) # [Modified in EIP-7251] + + payload_attributes = PayloadAttributes( + timestamp=compute_timestamp_at_slot(state, state.slot), + prev_randao=get_randao_mix(state, get_current_epoch(state)), + suggested_fee_recipient=suggested_fee_recipient, + withdrawals=withdrawals, + parent_beacon_block_root=hash_tree_root(state.latest_block_header), + ) + return execution_engine.notify_forkchoice_updated( + head_block_hash=parent_hash, + safe_block_hash=safe_block_hash, + finalized_block_hash=finalized_block_hash, + payload_attributes=payload_attributes, + ) +``` + ## Attesting ### Construct attestation diff --git a/tests/core/pyspec/eth2spec/test/context.py b/tests/core/pyspec/eth2spec/test/context.py index 064bdea5c..ff2ab80b5 100644 --- a/tests/core/pyspec/eth2spec/test/context.py +++ b/tests/core/pyspec/eth2spec/test/context.py @@ -8,7 +8,6 @@ from eth2spec.utils import bls from .exceptions import SkippedTest from .helpers.constants import ( PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, ELECTRA, - EIP7251, EIP7594, WHISK, MINIMAL, @@ -523,7 +522,6 @@ with_deneb_and_later = with_all_phases_from(DENEB) with_electra_and_later = with_all_phases_from(ELECTRA) with_whisk_and_later = with_all_phases_from(WHISK, all_phases=ALLOWED_TEST_RUNNER_FORKS) with_eip7594_and_later = with_all_phases_from(EIP7594, all_phases=ALLOWED_TEST_RUNNER_FORKS) -with_eip7251_and_later = with_all_phases_from(EIP7251, all_phases=ALLOWED_TEST_RUNNER_FORKS) class quoted_str(str): diff --git a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_consolidation.py b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_consolidation.py index f87c01561..31b5dde1f 100644 --- a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_consolidation.py +++ b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_consolidation.py @@ -1,7 +1,7 @@ from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.context import ( spec_state_test, - with_eip7251_and_later, + with_electra_and_later, with_presets, always_bls, spec_test, @@ -25,7 +25,7 @@ from eth2spec.test.helpers.withdrawals import ( # *********************** -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -73,7 +73,7 @@ def test_basic_consolidation_in_current_consolidation_epoch(spec, state): assert state.validators[0].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -262,7 +262,7 @@ def test_basic_consolidation_with_compounding_credential(spec, state): assert state.validators[0].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -310,7 +310,7 @@ def test_consolidation_churn_limit_balance(spec, state): assert state.validators[0].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -357,7 +357,7 @@ def test_consolidation_balance_larger_than_churn_limit(spec, state): assert state.validators[0].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -404,7 +404,7 @@ def test_consolidation_balance_through_two_churn_epochs(spec, state): assert state.consolidation_balance_to_consume == expected_balance -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -461,7 +461,7 @@ def test_multiple_consolidations_below_churn(spec, state): assert state.validators[2 * i].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -515,7 +515,7 @@ def test_multiple_consolidations_equal_churn(spec, state): assert state.validators[2 * i].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -593,7 +593,7 @@ def test_multiple_consolidations_above_churn(spec, state): assert state.validators[2 * i].exit_epoch == expected_exit_epoch -@with_eip7251_and_later +@with_electra_and_later @with_presets([MINIMAL], "need sufficient consolidation churn limit") @with_custom_state( balances_fn=scaled_churn_balances_exceed_activation_exit_churn_limit, @@ -651,8 +651,7 @@ def test_multiple_consolidations_equal_twice_churn(spec, state): # Failing tests - -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_source_equals_target(spec, state): current_epoch = spec.get_current_epoch(state) @@ -678,7 +677,7 @@ def test_invalid_source_equals_target(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_exceed_pending_consolidations_limit(spec, state): state.pending_consolidations = [ @@ -727,7 +726,7 @@ def test_invalid_not_enough_consolidation_churn_available(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_exited_source(spec, state): current_epoch = spec.get_current_epoch(state) @@ -749,7 +748,7 @@ def test_invalid_exited_source(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_exited_target(spec, state): current_epoch = spec.get_current_epoch(state) @@ -772,7 +771,7 @@ def test_invalid_exited_target(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_inactive_source(spec, state): current_epoch = spec.get_current_epoch(state) @@ -794,7 +793,7 @@ def test_invalid_inactive_source(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_inactive_target(spec, state): current_epoch = spec.get_current_epoch(state) @@ -817,7 +816,7 @@ def test_invalid_inactive_target(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_no_execution_withdrawal_credential(spec, state): current_epoch = spec.get_current_epoch(state) @@ -835,7 +834,7 @@ def test_invalid_no_execution_withdrawal_credential(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_different_credentials(spec, state): current_epoch = spec.get_current_epoch(state) @@ -856,7 +855,7 @@ def test_invalid_different_credentials(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test @always_bls def test_invalid_source_signature(spec, state): @@ -880,7 +879,7 @@ def test_invalid_source_signature(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test @always_bls def test_invalid_target_signature(spec, state): @@ -904,7 +903,7 @@ def test_invalid_target_signature(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_invalid_before_specified_epoch(spec, state): current_epoch = spec.get_current_epoch(state) diff --git a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_deposit.py b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_deposit.py new file mode 100644 index 000000000..196b61e77 --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_deposit.py @@ -0,0 +1,284 @@ +from eth2spec.test.helpers.deposits import ( + build_deposit, + prepare_state_and_deposit, + run_deposit_processing_electra, + run_deposit_processing_electra_with_specific_fork_version, + sign_deposit_data, +) +from eth2spec.test.helpers.keys import privkeys, pubkeys + +from eth2spec.test.context import ( + spec_state_test, + with_electra_and_later, + always_bls, +) + + +@with_electra_and_later +@spec_state_test +def test_new_deposit_under_min_activation_balance(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + # effective balance will be 1 EFFECTIVE_BALANCE_INCREMENT smaller because of this small decrement. + amount = spec.MIN_ACTIVATION_BALANCE - 1 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_new_deposit_min(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + amount = spec.MIN_DEPOSIT_AMOUNT + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_new_deposit_between_min_and_max(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE_electra // 2 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_new_deposit_max(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + # effective balance will be exactly the same as balance. + amount = spec.MAX_EFFECTIVE_BALANCE_electra + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_new_deposit_over_max(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE_electra + 1 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +# @with_electra_and_later +# @spec_state_test +# def test_top_up__max_effective_balance(spec, state): +# validator_index = 0 +# amount = spec.MAX_EFFECTIVE_BALANCE_electra // 4 +# deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + +# state.balances[validator_index] = spec.MAX_EFFECTIVE_BALANCE_electra +# state.validators[validator_index].effective_balance = spec.MAX_EFFECTIVE_BALANCE_electra + +# yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + +# assert state.balances[validator_index] == spec.MAX_EFFECTIVE_BALANCE_electra + amount +# assert state.validators[validator_index].effective_balance == spec.MAX_EFFECTIVE_BALANCE_electra + +@with_electra_and_later +@spec_state_test +@always_bls +def test_correct_sig_but_forked_state(spec, state): + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE + # deposits will always be valid, regardless of the current fork + state.fork.current_version = spec.Version('0x1234abcd') + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +@always_bls +def test_incorrect_sig_new_deposit(spec, state): + # fresh deposit = next validator index = validator appended to registry + validator_index = len(state.validators) + amount = spec.MIN_ACTIVATION_BALANCE + deposit = prepare_state_and_deposit(spec, state, validator_index, amount) + yield from run_deposit_processing_electra(spec, state, deposit, validator_index, effective=False) + + +@with_electra_and_later +@spec_state_test +def test_top_up__max_effective_balance(spec, state): + validator_index = 0 + amount = spec.MAX_EFFECTIVE_BALANCE // 4 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + + state.balances[validator_index] = spec.MAX_EFFECTIVE_BALANCE + state.validators[validator_index].effective_balance = spec.MAX_EFFECTIVE_BALANCE + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + assert state.validators[validator_index].effective_balance == spec.MAX_EFFECTIVE_BALANCE + + +@with_electra_and_later +@spec_state_test +def test_top_up__less_effective_balance(spec, state): + validator_index = 0 + amount = spec.MAX_EFFECTIVE_BALANCE // 4 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + + initial_balance = spec.MAX_EFFECTIVE_BALANCE - 1000 + initial_effective_balance = spec.MAX_EFFECTIVE_BALANCE - spec.EFFECTIVE_BALANCE_INCREMENT + state.balances[validator_index] = initial_balance + state.validators[validator_index].effective_balance = initial_effective_balance + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + # unchanged effective balance + assert state.validators[validator_index].effective_balance == initial_effective_balance + + +@with_electra_and_later +@spec_state_test +def test_top_up__zero_balance(spec, state): + validator_index = 0 + amount = spec.MAX_EFFECTIVE_BALANCE // 4 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) + + initial_balance = 0 + initial_effective_balance = 0 + state.balances[validator_index] = initial_balance + state.validators[validator_index].effective_balance = initial_effective_balance + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + # unchanged effective balance + assert state.validators[validator_index].effective_balance == initial_effective_balance + + +@with_electra_and_later +@spec_state_test +@always_bls +def test_incorrect_sig_top_up(spec, state): + validator_index = 0 + amount = spec.MAX_EFFECTIVE_BALANCE // 4 + deposit = prepare_state_and_deposit(spec, state, validator_index, amount) + + # invalid signatures, in top-ups, are allowed! + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_incorrect_withdrawal_credentials_top_up(spec, state): + validator_index = 0 + amount = spec.MAX_EFFECTIVE_BALANCE // 4 + withdrawal_credentials = spec.BLS_WITHDRAWAL_PREFIX + spec.hash(b"junk")[1:] + deposit = prepare_state_and_deposit( + spec, + state, + validator_index, + amount, + withdrawal_credentials=withdrawal_credentials + ) + + # inconsistent withdrawal credentials, in top-ups, are allowed! + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_invalid_wrong_deposit_for_deposit_count(spec, state): + deposit_data_leaves = [spec.DepositData() for _ in range(len(state.validators))] + + # build root for deposit_1 + index_1 = len(deposit_data_leaves) + pubkey_1 = pubkeys[index_1] + privkey_1 = privkeys[index_1] + _, _, deposit_data_leaves = build_deposit( + spec, + deposit_data_leaves, + pubkey_1, + privkey_1, + spec.MAX_EFFECTIVE_BALANCE, + withdrawal_credentials=b'\x00' * 32, + signed=True, + ) + deposit_count_1 = len(deposit_data_leaves) + + # build root for deposit_2 + index_2 = len(deposit_data_leaves) + pubkey_2 = pubkeys[index_2] + privkey_2 = privkeys[index_2] + deposit_2, root_2, deposit_data_leaves = build_deposit( + spec, + deposit_data_leaves, + pubkey_2, + privkey_2, + spec.MAX_EFFECTIVE_BALANCE, + withdrawal_credentials=b'\x00' * 32, + signed=True, + ) + + # state has root for deposit_2 but is at deposit_count for deposit_1 + state.eth1_data.deposit_root = root_2 + state.eth1_data.deposit_count = deposit_count_1 + + yield from run_deposit_processing_electra(spec, state, deposit_2, index_2, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_invalid_bad_merkle_proof(spec, state): + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE + deposit = prepare_state_and_deposit(spec, state, validator_index, amount) + + # mess up merkle branch + deposit.proof[5] = spec.Bytes32() + + sign_deposit_data(spec, deposit.data, privkeys[validator_index]) + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_key_validate_invalid_subgroup(spec, state): + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE + + # All-zero pubkey would not pass `bls.KeyValidate`, but `process_deposit` would not throw exception. + pubkey = b'\x00' * 48 + + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, pubkey=pubkey, signed=True) + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +def test_key_validate_invalid_decompression(spec, state): + validator_index = len(state.validators) + amount = spec.MAX_EFFECTIVE_BALANCE + + # `deserialization_fails_infinity_with_true_b_flag` BLS G1 deserialization test case. + # This pubkey would not pass `bls.KeyValidate`, but `process_deposit` would not throw exception. + pubkey_hex = 'c01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + pubkey = bytes.fromhex(pubkey_hex) + + deposit = prepare_state_and_deposit(spec, state, validator_index, amount, pubkey=pubkey, signed=True) + + yield from run_deposit_processing_electra(spec, state, deposit, validator_index) + + +@with_electra_and_later +@spec_state_test +@always_bls +def test_ineffective_deposit_with_bad_fork_version(spec, state): + yield from run_deposit_processing_electra_with_specific_fork_version( + spec, + state, + fork_version=spec.Version('0xAaBbCcDd'), + effective=False, + ) diff --git a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_execution_layer_withdraw_request.py b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_execution_layer_withdraw_request.py index 2ff92cfe6..065e5eab1 100644 --- a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_execution_layer_withdraw_request.py +++ b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_process_execution_layer_withdraw_request.py @@ -1,7 +1,7 @@ from eth2spec.test.context import ( spec_state_test, expect_assertion_error, - with_eip7251_and_later, + with_electra_and_later, with_presets, ) from eth2spec.test.helpers.constants import MINIMAL @@ -20,8 +20,7 @@ from eth2spec.test.helpers.withdrawals import ( # Modified tests from 7002. Just testing EL-triggered exits, not partial withdrawals - -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_basic_exit(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit @@ -104,7 +103,7 @@ def test_basic_exit_with_full_partial_withdrawal_queue(spec, state): # Invalid tests -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_incorrect_source_address(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit @@ -129,7 +128,7 @@ def test_incorrect_source_address(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_incorrect_withdrawal_credential_prefix(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit @@ -158,7 +157,7 @@ def test_incorrect_withdrawal_credential_prefix(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_on_exit_initiated_validator(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit @@ -184,7 +183,7 @@ def test_on_exit_initiated_validator(spec, state): ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_activation_epoch_less_than_shard_committee_period(spec, state): current_epoch = spec.get_current_epoch(state) @@ -212,8 +211,7 @@ def test_activation_epoch_less_than_shard_committee_period(spec, state): # Partial withdrawals tests - -@with_eip7251_and_later +@with_electra_and_later @spec_state_test @with_presets([MINIMAL]) def test_basic_partial_withdrawal_request(spec, state): diff --git a/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_voluntary_exit.py b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_voluntary_exit.py new file mode 100644 index 000000000..ba28f34ec --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/eip7251/block_processing/test_voluntary_exit.py @@ -0,0 +1,441 @@ +from eth2spec.test.helpers.constants import (MINIMAL, MAINNET) +from eth2spec.test.context import ( + spec_state_test, + with_electra_and_later, + with_presets, + always_bls, + spec_test, single_phase, + with_custom_state, + scaled_churn_balances_min_churn_limit, +) +from eth2spec.test.helpers.keys import pubkey_to_privkey +from eth2spec.test.helpers.voluntary_exits import ( + run_voluntary_exit_processing, + sign_voluntary_exit, +) +# ******************** +# * EXIT QUEUE TESTS * +# ******************** + + +@with_electra_and_later +@spec_state_test +def test_min_balance_exit(spec, state): + # This state has 64 validators each with 32 ETH + expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + churn_limit = spec.get_activation_exit_churn_limit(state) + # Set the balance to consume equal to churn limit + state.exit_balance_to_consume = churn_limit + + yield "pre", state + # Exit validators, all which fit in the churn limit + spec.initiate_validator_exit(state, 0) + yield "post", state + + # Check exit queue churn is set + assert state.exit_balance_to_consume == churn_limit - spec.MIN_ACTIVATION_BALANCE + # Check exit epoch + assert state.validators[0].exit_epoch == expected_exit_epoch + + +@with_electra_and_later +@spec_state_test +def test_min_balance_exits_up_to_churn(spec, state): + # This state has 64 validators each with 32 ETH + single_validator_balance = spec.MIN_ACTIVATION_BALANCE + expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + churn_limit = spec.get_activation_exit_churn_limit(state) + # Set the balance to consume equal to churn limit + state.exit_balance_to_consume = churn_limit + + yield "pre", state + # Exit validators, all which fit in the churn limit + for i in range(churn_limit // spec.MIN_ACTIVATION_BALANCE): + validator_index = i + spec.initiate_validator_exit(state, validator_index) + yield f"post{i}", state + # Check exit queue churn is set + assert state.exit_balance_to_consume == churn_limit - single_validator_balance * (i + 1) + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + yield "post", state + + +@with_electra_and_later +@spec_state_test +def test_min_balance_exits_above_churn(spec, state): + # This state has 64 validators each with 32 ETH + single_validator_balance = spec.MIN_ACTIVATION_BALANCE + expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + churn_limit = spec.get_activation_exit_churn_limit(state) + # Set the balance to consume equal to churn limit + state.exit_balance_to_consume = churn_limit + + yield "pre", state + # Exit validators, all which fit in the churn limit + for i in range(churn_limit // spec.MIN_ACTIVATION_BALANCE): + validator_index = i + spec.initiate_validator_exit(state, validator_index) + # Check exit queue churn is set + assert state.exit_balance_to_consume == churn_limit - single_validator_balance * (i + 1) + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + + # Exit balance has been fully consumed + assert state.exit_balance_to_consume == 0 + + # Exit an additional validator, doesn't fit in the churn limit, so exit + # epoch is incremented + validator_index = churn_limit // spec.MIN_ACTIVATION_BALANCE + spec.initiate_validator_exit(state, validator_index) + + yield "post", state + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + 1 + # Check exit balance to consume is set + assert state.exit_balance_to_consume == churn_limit - single_validator_balance + + +# @with_electra_and_later +# @spec_state_test +# def test_exit_balance_to_consume_large_validator(spec, state): +# # Set 0th validator effective balance to 2048 ETH +# state.validators[0].effective_balance = spec.MAX_EFFECTIVE_BALANCE_electra +# churn_limit = spec.get_validator_churn_limit(state) +# expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) +# expected_exit_epoch += spec.MAX_EFFECTIVE_BALANCE_electra // churn_limit + +# validator_index = 0 +# spec.initiate_validator_exit(state, validator_index) +# # Check exit epoch +# assert state.validators[validator_index].exit_epoch == expected_exit_epoch +# # Check exit_balance_to_consume +# assert state.exit_balance_to_consume == churn_limit - (spec.MAX_EFFECTIVE_BALANCE_electra % churn_limit) +# # Check earliest_exit_epoch +# assert state.earliest_exit_epoch == expected_exit_epoch + +@with_electra_and_later +@spec_state_test +@with_presets([MAINNET], "With CHURN_LIMIT_QUOTIENT=32, can't change validator balance without changing churn_limit") +def test_max_balance_exit(spec, state): + churn_limit = spec.get_activation_exit_churn_limit(state) + assert churn_limit == spec.MIN_ACTIVATION_BALANCE * spec.config.MIN_PER_EPOCH_CHURN_LIMIT + + # Set 0th validator effective balance to 2048 ETH + state.validators[0].effective_balance = spec.MAX_EFFECTIVE_BALANCE_electra + yield 'pre', state + + expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + # Validator consumes exit churn for 16 epochs, exits at the 17th one + expected_exit_epoch += (spec.MAX_EFFECTIVE_BALANCE_electra // churn_limit) + + validator_index = 0 + spec.initiate_validator_exit(state, validator_index) + yield 'post', state + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + # Check exit_balance_to_consume + assert state.exit_balance_to_consume == churn_limit + # Check earliest_exit_epoch + assert state.earliest_exit_epoch == expected_exit_epoch + + +@with_electra_and_later +@spec_state_test +@with_presets([MAINNET], "With CHURN_LIMIT_QUOTIENT=32, can't change validator balance without changing churn_limit") +def test_exit_with_balance_equal_to_churn_limit(spec, state): + churn_limit = spec.get_activation_exit_churn_limit(state) + + # Set 0th validator effective balance to churn_limit + state.validators[0].effective_balance = churn_limit + yield 'pre', state + + validator_index = 0 + spec.initiate_validator_exit(state, validator_index) + + yield 'post', state + # Validator consumes churn limit fully in the current epoch + assert (state.validators[validator_index].exit_epoch == + spec.compute_activation_exit_epoch(spec.get_current_epoch(state))) + # Check exit_balance_to_consume + assert state.exit_balance_to_consume == 0 + # Check earliest_exit_epoch + assert state.earliest_exit_epoch == state.validators[validator_index].exit_epoch + + +@with_electra_and_later +@spec_state_test +@with_presets([MAINNET], "With CHURN_LIMIT_QUOTIENT=32, can't change validator balance without changing churn_limit") +def test_exit_churn_limit_balance_existing_churn_(spec, state): + cl = spec.get_activation_exit_churn_limit(state) + + # set exit epoch to the first available one and set exit balance to consume to full churn limit + state.earliest_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + state.exit_balance_to_consume = cl + # consume some churn in exit epoch + state.exit_balance_to_consume -= 1000000000 + + # Set 0th validator effective balance to the churn limit + state.validators[0].effective_balance = cl + + yield 'pre', state + + # The existing 1 ETH churn will push an extra epoch + expected_exit_epoch = state.earliest_exit_epoch + 1 + + yield 'post', state + validator_index = 0 + spec.initiate_validator_exit(state, validator_index) + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + # Check balance consumed in exit epoch is the remainder 1 ETH + assert state.exit_balance_to_consume == cl - 1000000000 + # check earliest exit epoch + assert expected_exit_epoch == state.earliest_exit_epoch + + +@with_electra_and_later +@spec_state_test +@with_presets([MAINNET], "With CHURN_LIMIT_QUOTIENT=32, can't change validator balance without changing churn_limit") +def test_multi_epoch_exit_existing_churn(spec, state): + cl = spec.get_activation_exit_churn_limit(state) + + # set exit epoch to the first available one and set exit balance to consume to full churn limit + state.earliest_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + state.exit_balance_to_consume = cl + # consume some churn in exit epoch + state.exit_balance_to_consume -= 1000000000 + + # Set 0th validator effective balance to 2x the churn limit + state.validators[0].effective_balance = 2 * cl + + yield 'pre', state + # Two extra epochs will be necessary + expected_exit_epoch = spec.compute_activation_exit_epoch(spec.get_current_epoch(state)) + 2 + + validator_index = 0 + spec.initiate_validator_exit(state, validator_index) + yield 'post', state + # Check exit epoch + assert state.validators[validator_index].exit_epoch == expected_exit_epoch + # Check balance consumed in exit epoch is the remainder 1 ETH + assert state.exit_balance_to_consume == cl - 1000000000 + # check earliest exit epoch + assert expected_exit_epoch == state.earliest_exit_epoch + + +# Repurposed from phase0 voluntary exit tests, should disable the phase0 ones + +def run_test_success_exit_queue(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + churn_limit = spec.get_activation_exit_churn_limit(state) + # exit `MAX_EXITS_PER_EPOCH` + max_exits = churn_limit // spec.MIN_ACTIVATION_BALANCE + initial_indices = spec.get_active_validator_indices(state, current_epoch)[:max_exits] + + # Prepare a bunch of exits, based on the current state + exit_queue = [] + for index in initial_indices: + privkey = pubkey_to_privkey[state.validators[index].pubkey] + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=index), privkey) + + exit_queue.append(signed_voluntary_exit) + + # Now run all the exits + for voluntary_exit in exit_queue: + # the function yields data, but we are just interested in running it here, ignore yields. + for _ in run_voluntary_exit_processing(spec, state, voluntary_exit): + continue + + # exit an additional validator + validator_index = spec.get_active_validator_indices(state, current_epoch)[-1] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + # This is the interesting part of the test: on a pre-state with a full exit queue, + # when processing an additional exit, it results in an exit in a later epoch + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) + + for index in initial_indices: + assert ( + state.validators[validator_index].exit_epoch == + state.validators[index].exit_epoch + 1 + ) + assert state.earliest_exit_epoch == state.validators[validator_index].exit_epoch + consumed_churn = spec.MIN_ACTIVATION_BALANCE * (max_exits + 1) + assert state.exit_balance_to_consume == churn_limit - (consumed_churn % churn_limit) + + +@with_electra_and_later +@spec_state_test +def test_success_exit_queue__min_churn(spec, state): + yield from run_test_success_exit_queue(spec, state) + + +@with_electra_and_later +@with_presets([MINIMAL], + reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") +@spec_test +@with_custom_state(balances_fn=scaled_churn_balances_min_churn_limit, + threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) +@single_phase +def test_success_exit_queue__scaled_churn(spec, state): + churn_limit = spec.get_activation_exit_churn_limit(state) + assert churn_limit > spec.config.MIN_PER_EPOCH_CHURN_LIMIT + yield from run_test_success_exit_queue(spec, state) + + +# After here no modifications were made, can just leave them in phase0 as is + +@with_electra_and_later +@spec_state_test +def test_basic(spec, state): + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) + + assert state.validators[validator_index].exit_epoch == spec.compute_activation_exit_epoch(current_epoch) + + +@with_electra_and_later +@spec_state_test +@always_bls +def test_invalid_incorrect_signature(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + + voluntary_exit = spec.VoluntaryExit( + epoch=current_epoch, + validator_index=validator_index, + ) + signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, 12345) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_default_exit_epoch_subsequent_exit(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + # Exit one validator prior to this new one + exited_index = spec.get_active_validator_indices(state, current_epoch)[-1] + state.validators[exited_index].exit_epoch = current_epoch - 1 + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) + + assert state.validators[validator_index].exit_epoch == spec.compute_activation_exit_epoch(current_epoch) + + +@with_electra_and_later +@spec_state_test +def test_invalid_validator_exit_in_future(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + voluntary_exit = spec.VoluntaryExit( + epoch=current_epoch + 1, + validator_index=validator_index, + ) + signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, privkey) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_invalid_validator_incorrect_validator_index(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + voluntary_exit = spec.VoluntaryExit( + epoch=current_epoch, + validator_index=len(state.validators), + ) + signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, privkey) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_invalid_validator_not_active(spec, state): + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + state.validators[validator_index].activation_epoch = spec.FAR_FUTURE_EPOCH + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_invalid_validator_already_exited(spec, state): + # move state forward SHARD_COMMITTEE_PERIOD epochs to allow validator able to exit + state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH + + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + # but validator already has exited + state.validators[validator_index].exit_epoch = current_epoch + 2 + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) + + +@with_electra_and_later +@spec_state_test +def test_invalid_validator_not_active_long_enough(spec, state): + current_epoch = spec.get_current_epoch(state) + validator_index = spec.get_active_validator_indices(state, current_epoch)[0] + privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] + + signed_voluntary_exit = sign_voluntary_exit( + spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) + + assert ( + current_epoch - state.validators[validator_index].activation_epoch < + spec.config.SHARD_COMMITTEE_PERIOD + ) + + yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) diff --git a/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_balance_deposits.py b/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_balance_deposits.py index f668793b0..42783d31e 100644 --- a/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_balance_deposits.py +++ b/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_balance_deposits.py @@ -1,11 +1,11 @@ from eth2spec.test.helpers.epoch_processing import run_epoch_processing_with from eth2spec.test.context import ( spec_state_test, - with_eip7251_and_later, + with_electra_and_later, ) -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_pending_deposit_min_activation_balance(spec, state): index = 0 @@ -23,7 +23,7 @@ def test_pending_deposit_min_activation_balance(spec, state): assert state.pending_balance_deposits == [] -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_pending_deposit_balance_equal_churn(spec, state): index = 0 @@ -40,7 +40,7 @@ def test_pending_deposit_balance_equal_churn(spec, state): assert state.pending_balance_deposits == [] -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_pending_deposit_balance_above_churn(spec, state): index = 0 @@ -64,7 +64,7 @@ def test_pending_deposit_balance_above_churn(spec, state): ] -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_pending_deposit_preexisting_churn(spec, state): index = 0 @@ -85,7 +85,7 @@ def test_pending_deposit_preexisting_churn(spec, state): assert state.pending_balance_deposits == [] -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_multiple_pending_deposits_below_churn(spec, state): amount = 10**9 @@ -106,7 +106,7 @@ def test_multiple_pending_deposits_below_churn(spec, state): assert state.pending_balance_deposits == [] -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_multiple_pending_deposits_above_churn(spec, state): # set third deposit to be over the churn diff --git a/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_consolidations.py b/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_consolidations.py index 41cc37813..4f588746e 100644 --- a/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_consolidations.py +++ b/tests/core/pyspec/eth2spec/test/eip7251/epoch_processing/test_process_pending_consolidations.py @@ -1,7 +1,7 @@ from eth2spec.test.helpers.epoch_processing import run_epoch_processing_with from eth2spec.test.context import ( spec_state_test, - with_eip7251_and_later, + with_electra_and_later, ) # *********************** @@ -9,7 +9,7 @@ from eth2spec.test.context import ( # *********************** -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_basic_pending_consolidation(spec, state): current_epoch = spec.get_current_epoch(state) @@ -78,7 +78,7 @@ def test_consolidation_not_yet_withdrawable_validator(spec, state): assert state.pending_consolidations == pre_pending_consolidations -@with_eip7251_and_later +@with_electra_and_later @spec_state_test def test_skip_consolidation_when_source_slashed(spec, state): current_epoch = spec.get_current_epoch(state) diff --git a/tests/core/pyspec/eth2spec/test/eip7251/unittests/test_config_invariants.py b/tests/core/pyspec/eth2spec/test/eip7251/unittests/test_config_invariants.py index 7acad99ef..5501c62f2 100644 --- a/tests/core/pyspec/eth2spec/test/eip7251/unittests/test_config_invariants.py +++ b/tests/core/pyspec/eth2spec/test/eip7251/unittests/test_config_invariants.py @@ -1,11 +1,11 @@ from eth2spec.test.context import ( single_phase, spec_test, - with_eip7251_and_later, + with_electra_and_later, ) -@with_eip7251_and_later +@with_electra_and_later @spec_test @single_phase def test_withdrawals(spec): diff --git a/tests/core/pyspec/eth2spec/test/helpers/constants.py b/tests/core/pyspec/eth2spec/test/helpers/constants.py index 771d1b2c3..61ae170f0 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/constants.py +++ b/tests/core/pyspec/eth2spec/test/helpers/constants.py @@ -19,7 +19,6 @@ CUSTODY_GAME = SpecForkName('custody_game') DAS = SpecForkName('das') ELECTRA = SpecForkName('electra') WHISK = SpecForkName('whisk') -EIP7251 = SpecForkName('eip7251') EIP7594 = SpecForkName('eip7594') # @@ -38,7 +37,6 @@ ALL_PHASES = ( DENEB, ELECTRA, # Experimental patches - EIP7251, EIP7594, ) # The forks that have light client specs @@ -59,7 +57,6 @@ PREVIOUS_FORK_OF = { ELECTRA: DENEB, # Experimental patches WHISK: CAPELLA, - EIP7251: DENEB, EIP7594: DENEB, } diff --git a/tests/core/pyspec/eth2spec/test/helpers/forks.py b/tests/core/pyspec/eth2spec/test/helpers/forks.py index c288b3e6e..5ea03c31b 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/forks.py +++ b/tests/core/pyspec/eth2spec/test/helpers/forks.py @@ -1,6 +1,6 @@ from .constants import ( PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, - ELECTRA, WHISK, EIP7251, + ELECTRA, WHISK, PREVIOUS_FORK_OF, ) @@ -41,10 +41,6 @@ def is_post_electra(spec): return is_post_fork(spec.fork, ELECTRA) -def is_post_eip7251(spec): - return is_post_fork(spec.fork, EIP7251) - - def is_post_whisk(spec): return is_post_fork(spec.fork, WHISK) diff --git a/tests/core/pyspec/eth2spec/test/helpers/genesis.py b/tests/core/pyspec/eth2spec/test/helpers/genesis.py index b817576fa..3896b4173 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/genesis.py +++ b/tests/core/pyspec/eth2spec/test/helpers/genesis.py @@ -6,7 +6,7 @@ from eth2spec.test.helpers.execution_payload import ( compute_el_header_block_hash, ) from eth2spec.test.helpers.forks import ( - is_post_altair, is_post_bellatrix, is_post_capella, is_post_electra, is_post_whisk, is_post_eip7251, + is_post_altair, is_post_bellatrix, is_post_capella, is_post_electra, is_post_whisk, ) from eth2spec.test.helpers.keys import pubkeys from eth2spec.test.helpers.whisk import compute_whisk_initial_tracker_cached, compute_whisk_initial_k_commitment_cached @@ -148,7 +148,7 @@ def create_genesis_state(spec, validator_balances, activation_threshold): for i in range(spec.WHISK_PROPOSER_TRACKERS_COUNT): state.whisk_proposer_trackers[i] = compute_whisk_initial_tracker_cached(i % vc) - if is_post_eip7251(spec): + if is_post_electra(spec): state.deposit_balance_to_consume = 0 state.exit_balance_to_consume = 0 state.earliest_exit_epoch = spec.GENESIS_EPOCH diff --git a/tests/core/pyspec/eth2spec/test/phase0/unittests/test_config_invariants.py b/tests/core/pyspec/eth2spec/test/phase0/unittests/test_config_invariants.py index d7e60f160..2e6df558f 100644 --- a/tests/core/pyspec/eth2spec/test/phase0/unittests/test_config_invariants.py +++ b/tests/core/pyspec/eth2spec/test/phase0/unittests/test_config_invariants.py @@ -4,7 +4,7 @@ from eth2spec.test.context import ( ) from eth2spec.test.helpers.constants import UINT64_MAX from eth2spec.test.helpers.forks import ( - is_post_altair, is_post_bellatrix, is_post_eip7251, + is_post_altair, is_post_bellatrix, is_post_electra, ) @@ -58,8 +58,8 @@ def test_incentives(spec, state): assert spec.MIN_SLASHING_PENALTY_QUOTIENT_BELLATRIX <= spec.WHISTLEBLOWER_REWARD_QUOTIENT elif is_post_altair(spec): assert spec.MIN_SLASHING_PENALTY_QUOTIENT_ALTAIR <= spec.WHISTLEBLOWER_REWARD_QUOTIENT - elif is_post_eip7251(spec): - assert spec.MIN_SLASHING_PENALTY_QUOTIENT_EIP7251 <= spec.WHISTLEBLOWER_REWARD_QUOTIENT_EIP7251 + elif is_post_electra(spec): + assert spec.MIN_SLASHING_PENALTY_QUOTIENT_ELECTRA <= spec.WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA else: assert spec.MIN_SLASHING_PENALTY_QUOTIENT <= spec.WHISTLEBLOWER_REWARD_QUOTIENT