diff --git a/.github/workflows/test-suite.yml b/.github/workflows/test-suite.yml index c501c8cabf4..a8db6fab8fd 100644 --- a/.github/workflows/test-suite.yml +++ b/.github/workflows/test-suite.yml @@ -309,7 +309,7 @@ jobs: run: | make - name: Install lcli - # TODO: uncomment after the version of lcli in https://github.com/sigp/lighthouse/pull/5137 + # TODO: uncomment after the version of lcli in https://github.com/sigp/lighthouse/pull/5137 # is installed on the runners # if: env.SELF_HOSTED_RUNNERS == 'false' run: make install-lcli diff --git a/Makefile b/Makefile index 6b6418cb83d..4b2d0f6c5d5 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ PROFILE ?= release # List of all hard forks. This list is used to set env variables for several tests so that # they run for different forks. -FORKS=phase0 altair merge capella deneb +FORKS=phase0 altair merge capella deneb electra # Extra flags for Cargo CARGO_INSTALL_EXTRA_FLAGS?= diff --git a/beacon_node/beacon_chain/src/attestation_rewards.rs b/beacon_node/beacon_chain/src/attestation_rewards.rs index abd676d7389..5ee19278ae3 100644 --- a/beacon_node/beacon_chain/src/attestation_rewards.rs +++ b/beacon_node/beacon_chain/src/attestation_rewards.rs @@ -57,7 +57,8 @@ impl BeaconChain { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => self.compute_attestation_rewards_altair(state, validators), + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => self.compute_attestation_rewards_altair(state, validators), } } diff --git a/beacon_node/beacon_chain/src/attestation_verification.rs b/beacon_node/beacon_chain/src/attestation_verification.rs index 019e87309fd..52fae2ade39 100644 --- a/beacon_node/beacon_chain/src/attestation_verification.rs +++ b/beacon_node/beacon_chain/src/attestation_verification.rs @@ -1065,7 +1065,7 @@ pub fn verify_propagation_slot_range( let earliest_permissible_slot = match current_fork { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => one_epoch_prior, // EIP-7045 - ForkName::Deneb => one_epoch_prior + ForkName::Deneb | ForkName::Electra => one_epoch_prior .epoch(E::slots_per_epoch()) .start_slot(E::slots_per_epoch()), }; diff --git a/beacon_node/beacon_chain/src/beacon_block_streamer.rs b/beacon_node/beacon_chain/src/beacon_block_streamer.rs index 4f4f8ed1fe0..a1f7c99067e 100644 --- a/beacon_node/beacon_chain/src/beacon_block_streamer.rs +++ b/beacon_node/beacon_chain/src/beacon_block_streamer.rs @@ -15,7 +15,8 @@ use types::{ SignedBlindedBeaconBlock, Slot, }; use types::{ - ExecutionPayload, ExecutionPayloadCapella, ExecutionPayloadHeader, ExecutionPayloadMerge, + ExecutionPayload, ExecutionPayloadCapella, ExecutionPayloadElectra, ExecutionPayloadHeader, + ExecutionPayloadMerge, }; #[derive(PartialEq)] @@ -98,6 +99,7 @@ fn reconstruct_default_header_block( ForkName::Merge => ExecutionPayloadMerge::default().into(), ForkName::Capella => ExecutionPayloadCapella::default().into(), ForkName::Deneb => ExecutionPayloadDeneb::default().into(), + ForkName::Electra => ExecutionPayloadElectra::default().into(), ForkName::Base | ForkName::Altair => { return Err(Error::PayloadReconstruction(format!( "Block with fork variant {} has execution payload", @@ -712,12 +714,13 @@ mod tests { } #[tokio::test] - async fn check_all_blocks_from_altair_to_deneb() { + async fn check_all_blocks_from_altair_to_electra() { let slots_per_epoch = MinimalEthSpec::slots_per_epoch() as usize; - let num_epochs = 8; + let num_epochs = 10; let bellatrix_fork_epoch = 2usize; let capella_fork_epoch = 4usize; let deneb_fork_epoch = 6usize; + let electra_fork_epoch = 8usize; let num_blocks_produced = num_epochs * slots_per_epoch; let mut spec = test_spec::(); @@ -725,6 +728,7 @@ mod tests { spec.bellatrix_fork_epoch = Some(Epoch::new(bellatrix_fork_epoch as u64)); spec.capella_fork_epoch = Some(Epoch::new(capella_fork_epoch as u64)); spec.deneb_fork_epoch = Some(Epoch::new(deneb_fork_epoch as u64)); + spec.electra_fork_epoch = Some(Epoch::new(electra_fork_epoch as u64)); let harness = get_harness(VALIDATOR_COUNT, spec.clone()); // go to bellatrix fork @@ -833,12 +837,13 @@ mod tests { } #[tokio::test] - async fn check_fallback_altair_to_deneb() { + async fn check_fallback_altair_to_electra() { let slots_per_epoch = MinimalEthSpec::slots_per_epoch() as usize; - let num_epochs = 8; + let num_epochs = 10; let bellatrix_fork_epoch = 2usize; let capella_fork_epoch = 4usize; let deneb_fork_epoch = 6usize; + let electra_fork_epoch = 8usize; let num_blocks_produced = num_epochs * slots_per_epoch; let mut spec = test_spec::(); @@ -846,6 +851,7 @@ mod tests { spec.bellatrix_fork_epoch = Some(Epoch::new(bellatrix_fork_epoch as u64)); spec.capella_fork_epoch = Some(Epoch::new(capella_fork_epoch as u64)); spec.deneb_fork_epoch = Some(Epoch::new(deneb_fork_epoch as u64)); + spec.electra_fork_epoch = Some(Epoch::new(electra_fork_epoch as u64)); let harness = get_harness(VALIDATOR_COUNT, spec); diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index deeda491dca..fcfbb05ed2f 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -4923,7 +4923,10 @@ impl BeaconChain { // allows it to run concurrently with things like attestation packing. let prepare_payload_handle = match &state { BeaconState::Base(_) | BeaconState::Altair(_) => None, - BeaconState::Merge(_) | BeaconState::Capella(_) | BeaconState::Deneb(_) => { + BeaconState::Merge(_) + | BeaconState::Capella(_) + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => { let prepare_payload_handle = get_execution_payload( self.clone(), &state, @@ -5284,6 +5287,41 @@ impl BeaconChain { execution_payload_value, ) } + BeaconState::Electra(_) => { + let (payload, kzg_commitments, maybe_blobs_and_proofs, execution_payload_value) = + block_contents + .ok_or(BlockProductionError::MissingExecutionPayload)? + .deconstruct(); + + ( + BeaconBlock::Electra(BeaconBlockElectra { + slot, + proposer_index, + parent_root, + state_root: Hash256::zero(), + body: BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings: proposer_slashings.into(), + attester_slashings: attester_slashings.into(), + attestations: attestations.into(), + deposits: deposits.into(), + voluntary_exits: voluntary_exits.into(), + sync_aggregate: sync_aggregate + .ok_or(BlockProductionError::MissingSyncAggregate)?, + execution_payload: payload + .try_into() + .map_err(|_| BlockProductionError::InvalidPayloadFork)?, + bls_to_execution_changes: bls_to_execution_changes.into(), + blob_kzg_commitments: kzg_commitments + .ok_or(BlockProductionError::InvalidPayloadFork)?, + }, + }), + maybe_blobs_and_proofs, + execution_payload_value, + ) + } }; let block = SignedBeaconBlock::from_block( @@ -5607,7 +5645,7 @@ impl BeaconChain { let prepare_slot_fork = self.spec.fork_name_at_slot::(prepare_slot); let withdrawals = match prepare_slot_fork { ForkName::Base | ForkName::Altair | ForkName::Merge => None, - ForkName::Capella | ForkName::Deneb => { + ForkName::Capella | ForkName::Deneb | ForkName::Electra => { let chain = self.clone(); self.spawn_blocking_handle( move || { @@ -5622,7 +5660,9 @@ impl BeaconChain { let parent_beacon_block_root = match prepare_slot_fork { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => None, - ForkName::Deneb => Some(pre_payload_attributes.parent_beacon_block_root), + ForkName::Deneb | ForkName::Electra => { + Some(pre_payload_attributes.parent_beacon_block_root) + } }; let payload_attributes = PayloadAttributes::new( @@ -6662,7 +6702,11 @@ impl BeaconChain { .map_err(Error::InconsistentFork)?; match fork_name { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => { + ForkName::Altair + | ForkName::Merge + | ForkName::Capella + | ForkName::Deneb + | ForkName::Electra => { LightClientBootstrap::from_beacon_state(&mut state, &block, &self.spec) .map(|bootstrap| Some((bootstrap, fork_name))) .map_err(Error::LightClientError) diff --git a/beacon_node/beacon_chain/src/electra_readiness.rs b/beacon_node/beacon_chain/src/electra_readiness.rs new file mode 100644 index 00000000000..0e911bf37ec --- /dev/null +++ b/beacon_node/beacon_chain/src/electra_readiness.rs @@ -0,0 +1,123 @@ +//! Provides tools for checking if a node is ready for the Electra upgrade and following merge +//! transition. + +use crate::{BeaconChain, BeaconChainTypes}; +use execution_layer::http::{ + ENGINE_FORKCHOICE_UPDATED_V3, ENGINE_GET_PAYLOAD_V3, ENGINE_NEW_PAYLOAD_V3, +}; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::time::Duration; +use types::*; + +/// The time before the Electra fork when we will start issuing warnings about preparation. +use super::merge_readiness::SECONDS_IN_A_WEEK; +pub const ELECTRA_READINESS_PREPARATION_SECONDS: u64 = SECONDS_IN_A_WEEK * 2; +pub const ENGINE_CAPABILITIES_REFRESH_INTERVAL: u64 = 300; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type")] +pub enum ElectraReadiness { + /// The execution engine is electra-enabled (as far as we can tell) + Ready, + /// We are connected to an execution engine which doesn't support the V3 engine api methods + V3MethodsNotSupported { error: String }, + /// The transition configuration with the EL failed, there might be a problem with + /// connectivity, authentication or a difference in configuration. + ExchangeCapabilitiesFailed { error: String }, + /// The user has not configured an execution endpoint + NoExecutionEndpoint, +} + +impl fmt::Display for ElectraReadiness { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ElectraReadiness::Ready => { + write!(f, "This node appears ready for Electra.") + } + ElectraReadiness::ExchangeCapabilitiesFailed { error } => write!( + f, + "Could not exchange capabilities with the \ + execution endpoint: {}", + error + ), + ElectraReadiness::NoExecutionEndpoint => write!( + f, + "The --execution-endpoint flag is not specified, this is a \ + requirement post-merge" + ), + ElectraReadiness::V3MethodsNotSupported { error } => write!( + f, + "Execution endpoint does not support Electra methods: {}", + error + ), + } + } +} + +impl BeaconChain { + /// Returns `true` if electra epoch is set and Electra fork has occurred or will + /// occur within `ELECTRA_READINESS_PREPARATION_SECONDS` + pub fn is_time_to_prepare_for_electra(&self, current_slot: Slot) -> bool { + if let Some(electra_epoch) = self.spec.electra_fork_epoch { + let electra_slot = electra_epoch.start_slot(T::EthSpec::slots_per_epoch()); + let electra_readiness_preparation_slots = + ELECTRA_READINESS_PREPARATION_SECONDS / self.spec.seconds_per_slot; + // Return `true` if Electra has happened or is within the preparation time. + current_slot + electra_readiness_preparation_slots > electra_slot + } else { + // The Electra fork epoch has not been defined yet, no need to prepare. + false + } + } + + /// Attempts to connect to the EL and confirm that it is ready for electra. + pub async fn check_electra_readiness(&self) -> ElectraReadiness { + if let Some(el) = self.execution_layer.as_ref() { + match el + .get_engine_capabilities(Some(Duration::from_secs( + ENGINE_CAPABILITIES_REFRESH_INTERVAL, + ))) + .await + { + Err(e) => { + // The EL was either unreachable or responded with an error + ElectraReadiness::ExchangeCapabilitiesFailed { + error: format!("{:?}", e), + } + } + Ok(capabilities) => { + // TODO(electra): Update in the event we get V4s. + let mut missing_methods = String::from("Required Methods Unsupported:"); + let mut all_good = true; + if !capabilities.get_payload_v3 { + missing_methods.push(' '); + missing_methods.push_str(ENGINE_GET_PAYLOAD_V3); + all_good = false; + } + if !capabilities.forkchoice_updated_v3 { + missing_methods.push(' '); + missing_methods.push_str(ENGINE_FORKCHOICE_UPDATED_V3); + all_good = false; + } + if !capabilities.new_payload_v3 { + missing_methods.push(' '); + missing_methods.push_str(ENGINE_NEW_PAYLOAD_V3); + all_good = false; + } + + if all_good { + ElectraReadiness::Ready + } else { + ElectraReadiness::V3MethodsNotSupported { + error: missing_methods, + } + } + } + } + } else { + ElectraReadiness::NoExecutionEndpoint + } + } +} diff --git a/beacon_node/beacon_chain/src/execution_payload.rs b/beacon_node/beacon_chain/src/execution_payload.rs index c1bd0b439ad..b3804f0d23a 100644 --- a/beacon_node/beacon_chain/src/execution_payload.rs +++ b/beacon_node/beacon_chain/src/execution_payload.rs @@ -412,7 +412,7 @@ pub fn get_execution_payload( let latest_execution_payload_header_block_hash = state.latest_execution_payload_header()?.block_hash(); let withdrawals = match state { - &BeaconState::Capella(_) | &BeaconState::Deneb(_) => { + &BeaconState::Capella(_) | &BeaconState::Deneb(_) | &BeaconState::Electra(_) => { Some(get_expected_withdrawals(state, spec)?.into()) } &BeaconState::Merge(_) => None, @@ -420,7 +420,7 @@ pub fn get_execution_payload( &BeaconState::Base(_) | &BeaconState::Altair(_) => None, }; let parent_beacon_block_root = match state { - BeaconState::Deneb(_) => Some(parent_block_root), + BeaconState::Deneb(_) | BeaconState::Electra(_) => Some(parent_block_root), BeaconState::Merge(_) | BeaconState::Capella(_) => None, // These shouldn't happen but they're here to make the pattern irrefutable BeaconState::Base(_) | BeaconState::Altair(_) => None, diff --git a/beacon_node/beacon_chain/src/lib.rs b/beacon_node/beacon_chain/src/lib.rs index 529f269be10..7721c9b00ff 100644 --- a/beacon_node/beacon_chain/src/lib.rs +++ b/beacon_node/beacon_chain/src/lib.rs @@ -20,6 +20,7 @@ pub mod chain_config; pub mod data_availability_checker; pub mod deneb_readiness; mod early_attester_cache; +pub mod electra_readiness; mod errors; pub mod eth1_chain; mod eth1_finalization_cache; diff --git a/beacon_node/beacon_chain/src/test_utils.rs b/beacon_node/beacon_chain/src/test_utils.rs index 5370294d8a7..51b299f1190 100644 --- a/beacon_node/beacon_chain/src/test_utils.rs +++ b/beacon_node/beacon_chain/src/test_utils.rs @@ -458,6 +458,10 @@ where mock.server.execution_block_generator().cancun_time = spec.deneb_fork_epoch.map(|epoch| { genesis_time + spec.seconds_per_slot * E::slots_per_epoch() * epoch.as_u64() }); + mock.server.execution_block_generator().prague_time = + spec.electra_fork_epoch.map(|epoch| { + genesis_time + spec.seconds_per_slot * E::slots_per_epoch() * epoch.as_u64() + }); self } @@ -579,6 +583,9 @@ pub fn mock_execution_layer_from_parts( let cancun_time = spec.deneb_fork_epoch.map(|epoch| { HARNESS_GENESIS_TIME + spec.seconds_per_slot * T::slots_per_epoch() * epoch.as_u64() }); + let prague_time = spec.electra_fork_epoch.map(|epoch| { + HARNESS_GENESIS_TIME + spec.seconds_per_slot * T::slots_per_epoch() * epoch.as_u64() + }); let trusted_setup: TrustedSetup = serde_json::from_reader(TRUSTED_SETUP_BYTES) .map_err(|e| format!("Unable to read trusted setup file: {}", e)) @@ -590,6 +597,7 @@ pub fn mock_execution_layer_from_parts( DEFAULT_TERMINAL_BLOCK, shanghai_time, cancun_time, + prague_time, Some(JwtKey::from_slice(&DEFAULT_JWT_SECRET).unwrap()), spec.clone(), Some(kzg), @@ -877,7 +885,9 @@ where | SignedBeaconBlock::Altair(_) | SignedBeaconBlock::Merge(_) | SignedBeaconBlock::Capella(_) => (signed_block, None), - SignedBeaconBlock::Deneb(_) => (signed_block, block_response.blob_items), + SignedBeaconBlock::Deneb(_) | SignedBeaconBlock::Electra(_) => { + (signed_block, block_response.blob_items) + } }; (block_contents, block_response.state) @@ -939,7 +949,9 @@ where | SignedBeaconBlock::Altair(_) | SignedBeaconBlock::Merge(_) | SignedBeaconBlock::Capella(_) => (signed_block, None), - SignedBeaconBlock::Deneb(_) => (signed_block, block_response.blob_items), + SignedBeaconBlock::Deneb(_) | SignedBeaconBlock::Electra(_) => { + (signed_block, block_response.blob_items) + } }; (block_contents, pre_state) } @@ -2497,48 +2509,73 @@ pub fn generate_rand_block_and_blobs( let inner = map_fork_name!(fork_name, BeaconBlock, <_>::random_for_test(rng)); let mut block = SignedBeaconBlock::from_block(inner, types::Signature::random_for_test(rng)); let mut blob_sidecars = vec![]; - if let Ok(message) = block.message_deneb_mut() { - // Get either zero blobs or a random number of blobs between 1 and Max Blobs. - let payload: &mut FullPayloadDeneb = &mut message.body.execution_payload; - let num_blobs = match num_blobs { - NumBlobs::Random => rng.gen_range(1..=E::max_blobs_per_block()), - NumBlobs::None => 0, - }; - let (bundle, transactions) = - execution_layer::test_utils::generate_blobs::(num_blobs).unwrap(); - payload.execution_payload.transactions = <_>::default(); - for tx in Vec::from(transactions) { - payload.execution_payload.transactions.push(tx).unwrap(); - } - message.body.blob_kzg_commitments = bundle.commitments.clone(); + let bundle = match block { + SignedBeaconBlock::Deneb(SignedBeaconBlockDeneb { + ref mut message, .. + }) => { + // Get either zero blobs or a random number of blobs between 1 and Max Blobs. + let payload: &mut FullPayloadDeneb = &mut message.body.execution_payload; + let num_blobs = match num_blobs { + NumBlobs::Random => rng.gen_range(1..=E::max_blobs_per_block()), + NumBlobs::None => 0, + }; + let (bundle, transactions) = + execution_layer::test_utils::generate_blobs::(num_blobs).unwrap(); - let eth2::types::BlobsBundle { - commitments, - proofs, - blobs, - } = bundle; + payload.execution_payload.transactions = <_>::default(); + for tx in Vec::from(transactions) { + payload.execution_payload.transactions.push(tx).unwrap(); + } + message.body.blob_kzg_commitments = bundle.commitments.clone(); + bundle + } + SignedBeaconBlock::Electra(SignedBeaconBlockElectra { + ref mut message, .. + }) => { + // Get either zero blobs or a random number of blobs between 1 and Max Blobs. + let payload: &mut FullPayloadElectra = &mut message.body.execution_payload; + let num_blobs = match num_blobs { + NumBlobs::Random => rng.gen_range(1..=E::max_blobs_per_block()), + NumBlobs::None => 0, + }; + let (bundle, transactions) = + execution_layer::test_utils::generate_blobs::(num_blobs).unwrap(); - for (index, ((blob, kzg_commitment), kzg_proof)) in blobs - .into_iter() - .zip(commitments.into_iter()) - .zip(proofs.into_iter()) - .enumerate() - { - blob_sidecars.push(BlobSidecar { - index: index as u64, - blob: blob.clone(), - kzg_commitment, - kzg_proof, - signed_block_header: block.signed_block_header(), - kzg_commitment_inclusion_proof: block - .message() - .body() - .kzg_commitment_merkle_proof(index) - .unwrap(), - }); + payload.execution_payload.transactions = <_>::default(); + for tx in Vec::from(transactions) { + payload.execution_payload.transactions.push(tx).unwrap(); + } + message.body.blob_kzg_commitments = bundle.commitments.clone(); + bundle } - } + _ => return (block, blob_sidecars), + }; + let eth2::types::BlobsBundle { + commitments, + proofs, + blobs, + } = bundle; + + for (index, ((blob, kzg_commitment), kzg_proof)) in blobs + .into_iter() + .zip(commitments.into_iter()) + .zip(proofs.into_iter()) + .enumerate() + { + blob_sidecars.push(BlobSidecar { + index: index as u64, + blob: blob.clone(), + kzg_commitment, + kzg_proof, + signed_block_header: block.signed_block_header(), + kzg_commitment_inclusion_proof: block + .message() + .body() + .kzg_commitment_merkle_proof(index) + .unwrap(), + }); + } (block, blob_sidecars) } diff --git a/beacon_node/beacon_chain/tests/attestation_verification.rs b/beacon_node/beacon_chain/tests/attestation_verification.rs index 2501768c789..3432604cc93 100644 --- a/beacon_node/beacon_chain/tests/attestation_verification.rs +++ b/beacon_node/beacon_chain/tests/attestation_verification.rs @@ -342,7 +342,7 @@ impl GossipTester { E::slots_per_epoch() + 1 } // EIP-7045 - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let epoch_slot_offset = (self.slot() % E::slots_per_epoch()).as_u64(); if epoch_slot_offset != 0 { E::slots_per_epoch() + epoch_slot_offset @@ -1235,7 +1235,7 @@ async fn attestation_to_finalized_block() { .chain .verify_unaggregated_attestation_for_gossip(&attestation, Some(subnet_id)); assert!( - matches!(res, Err(AttnError:: HeadBlockFinalized { beacon_block_root }) + matches!(res, Err(AttnError::HeadBlockFinalized { beacon_block_root }) if beacon_block_root == earlier_block_root ) ); diff --git a/beacon_node/beacon_chain/tests/validator_monitor.rs b/beacon_node/beacon_chain/tests/validator_monitor.rs index d9ff57b1b0a..f595e5037e2 100644 --- a/beacon_node/beacon_chain/tests/validator_monitor.rs +++ b/beacon_node/beacon_chain/tests/validator_monitor.rs @@ -203,8 +203,12 @@ async fn produces_missed_blocks() { // making sure that the cache reloads when the epoch changes // in that scenario the slot that missed a block is the first slot of the epoch validator_index_to_monitor = 7; - // We are adding other validators to monitor as thoses one will miss a block depending on - // the fork name specified when running the test as the proposer cache differs depending on the fork name (cf. seed) + // We are adding other validators to monitor as these ones will miss a block depending on + // the fork name specified when running the test as the proposer cache differs depending on + // the fork name (cf. seed) + // + // If you are adding a new fork and seeing errors, print + // `validator_indexes[slot_in_epoch.as_usize()]` and add it below. let validator_index_to_monitor_altair = 2; // Same as above but for the merge upgrade let validator_index_to_monitor_merge = 4; @@ -212,6 +216,9 @@ async fn produces_missed_blocks() { let validator_index_to_monitor_capella = 11; // Same as above but for the deneb upgrade let validator_index_to_monitor_deneb = 3; + // Same as above but for the electra upgrade + let validator_index_to_monitor_electra = 6; + let harness2 = get_harness( validator_count, vec![ @@ -220,6 +227,7 @@ async fn produces_missed_blocks() { validator_index_to_monitor_merge, validator_index_to_monitor_capella, validator_index_to_monitor_deneb, + validator_index_to_monitor_electra, ], ); let advance_slot_by = 9; @@ -243,6 +251,10 @@ async fn produces_missed_blocks() { duplicate_block_root = *_state2.block_roots().get(idx as usize).unwrap(); validator_indexes = _state2.get_beacon_proposer_indices(&harness2.spec).unwrap(); validator_index = validator_indexes[slot_in_epoch.as_usize()]; + // If you are adding a new fork and seeing errors, it means the fork seed has changed the + // validator_index. Uncomment this line, run the test again and add the resulting index to the + // list above. + //eprintln!("new index which needs to be added => {:?}", validator_index); let beacon_proposer_cache = harness2 .chain diff --git a/beacon_node/client/src/notifier.rs b/beacon_node/client/src/notifier.rs index 8a0e5ce223a..912babdae31 100644 --- a/beacon_node/client/src/notifier.rs +++ b/beacon_node/client/src/notifier.rs @@ -2,6 +2,7 @@ use crate::metrics; use beacon_chain::{ capella_readiness::CapellaReadiness, deneb_readiness::DenebReadiness, + electra_readiness::ElectraReadiness, merge_readiness::{GenesisExecutionPayloadStatus, MergeConfig, MergeReadiness}, BeaconChain, BeaconChainTypes, ExecutionStatus, }; @@ -321,6 +322,7 @@ pub fn spawn_notifier( merge_readiness_logging(current_slot, &beacon_chain, &log).await; capella_readiness_logging(current_slot, &beacon_chain, &log).await; deneb_readiness_logging(current_slot, &beacon_chain, &log).await; + electra_readiness_logging(current_slot, &beacon_chain, &log).await; } }; @@ -512,8 +514,7 @@ async fn deneb_readiness_logging( error!( log, "Execution endpoint required"; - "info" => "you need a Deneb enabled execution engine to validate blocks, see: \ - https://lighthouse-book.sigmaprime.io/merge-migration.html" + "info" => "you need a Deneb enabled execution engine to validate blocks." ); return; } @@ -542,6 +543,66 @@ async fn deneb_readiness_logging( ), } } +/// Provides some helpful logging to users to indicate if their node is ready for Electra. +async fn electra_readiness_logging( + current_slot: Slot, + beacon_chain: &BeaconChain, + log: &Logger, +) { + // TODO(electra): Once Electra has features, this code can be swapped back. + let electra_completed = false; + //let electra_completed = beacon_chain + // .canonical_head + // .cached_head() + // .snapshot + // .beacon_block + // .message() + // .body() + // .execution_payload() + // .map_or(false, |payload| payload.electra_placeholder().is_ok()); + + let has_execution_layer = beacon_chain.execution_layer.is_some(); + + if electra_completed && has_execution_layer + || !beacon_chain.is_time_to_prepare_for_electra(current_slot) + { + return; + } + + if electra_completed && !has_execution_layer { + // When adding a new fork, add a check for the next fork readiness here. + error!( + log, + "Execution endpoint required"; + "info" => "you need a Electra enabled execution engine to validate blocks." + ); + return; + } + + match beacon_chain.check_electra_readiness().await { + ElectraReadiness::Ready => { + info!( + log, + "Ready for Electra"; + "info" => "ensure the execution endpoint is updated to the latest Electra/Prague release" + ) + } + readiness @ ElectraReadiness::ExchangeCapabilitiesFailed { error: _ } => { + error!( + log, + "Not ready for Electra"; + "hint" => "the execution endpoint may be offline", + "info" => %readiness, + ) + } + readiness => warn!( + log, + "Not ready for Electra"; + "hint" => "try updating the execution endpoint", + "info" => %readiness, + ), + } +} async fn genesis_execution_payload_logging( beacon_chain: &BeaconChain, diff --git a/beacon_node/execution_layer/src/block_hash.rs b/beacon_node/execution_layer/src/block_hash.rs index 074ef8b0c14..9bc03c9a059 100644 --- a/beacon_node/execution_layer/src/block_hash.rs +++ b/beacon_node/execution_layer/src/block_hash.rs @@ -236,4 +236,34 @@ mod test { .unwrap(); test_rlp_encoding(&header, None, expected_hash); } + + #[test] + fn test_rlp_encode_block_electra() { + let header = ExecutionBlockHeader { + parent_hash: Hash256::from_str("172864416698b842f4c92f7b476be294b4ef720202779df194cd225f531053ab").unwrap(), + ommers_hash: Hash256::from_str("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347").unwrap(), + beneficiary: Address::from_str("878705ba3f8bc32fcf7f4caa1a35e72af65cf766").unwrap(), + state_root: Hash256::from_str("c6457d0df85c84c62d1c68f68138b6e796e8a44fb44de221386fb2d5611c41e0").unwrap(), + transactions_root: Hash256::from_str("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421").unwrap(), + receipts_root: Hash256::from_str("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421").unwrap(), + logs_bloom:<[u8; 256]>::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap().into(), + difficulty: 0.into(), + number: 97.into(), + gas_limit: 27482534.into(), + gas_used: 0.into(), + timestamp: 1692132829u64, + extra_data: hex::decode("d883010d00846765746888676f312e32302e37856c696e7578").unwrap(), + mix_hash: Hash256::from_str("0b493c22d2ad4ca76c77ae6ad916af429b42b1dc98fdcb8e5ddbd049bbc5d623").unwrap(), + nonce: Hash64::zero(), + base_fee_per_gas: 2374u64.into(), + withdrawals_root: Some(Hash256::from_str("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421").unwrap()), + blob_gas_used: Some(0x0u64), + excess_blob_gas: Some(0x0u64), + parent_beacon_block_root: Some(Hash256::from_str("f7d327d2c04e4f12e9cdd492e53d39a1d390f8b1571e3b2a22ac6e1e170e5b1a").unwrap()), + }; + let expected_hash = + Hash256::from_str("a7448e600ead0a23d16f96aa46e8dea9eef8a7c5669a5f0a5ff32709afe9c408") + .unwrap(); + test_rlp_encoding(&header, None, expected_hash); + } } diff --git a/beacon_node/execution_layer/src/engine_api.rs b/beacon_node/execution_layer/src/engine_api.rs index 511b38892c6..ebdae9caf25 100644 --- a/beacon_node/execution_layer/src/engine_api.rs +++ b/beacon_node/execution_layer/src/engine_api.rs @@ -24,7 +24,11 @@ pub use types::{ ExecutionPayloadRef, FixedVector, ForkName, Hash256, Transactions, Uint256, VariableList, Withdrawal, Withdrawals, }; -use types::{ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadMerge, KzgProofs}; + +use types::{ + ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadElectra, ExecutionPayloadMerge, + KzgProofs, +}; pub mod auth; pub mod http; @@ -32,7 +36,8 @@ pub mod json_structures; mod new_payload_request; pub use new_payload_request::{ - NewPayloadRequest, NewPayloadRequestCapella, NewPayloadRequestDeneb, NewPayloadRequestMerge, + NewPayloadRequest, NewPayloadRequestCapella, NewPayloadRequestDeneb, NewPayloadRequestElectra, + NewPayloadRequestMerge, }; pub const LATEST_TAG: &str = "latest"; @@ -150,7 +155,7 @@ pub struct ExecutionBlock { /// Representation of an execution block with enough detail to reconstruct a payload. #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive(Clone, Debug, PartialEq, Serialize, Deserialize,), serde(bound = "T: EthSpec", rename_all = "camelCase"), @@ -184,12 +189,12 @@ pub struct ExecutionBlockWithTransactions { #[serde(rename = "hash")] pub block_hash: ExecutionBlockHash, pub transactions: Vec, - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub withdrawals: Vec, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] #[serde(with = "serde_utils::u64_hex_be")] pub blob_gas_used: u64, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] #[serde(with = "serde_utils::u64_hex_be")] pub excess_blob_gas: u64, } @@ -271,6 +276,34 @@ impl TryFrom> for ExecutionBlockWithTransactions blob_gas_used: block.blob_gas_used, excess_blob_gas: block.excess_blob_gas, }), + ExecutionPayload::Electra(block) => { + Self::Electra(ExecutionBlockWithTransactionsElectra { + parent_hash: block.parent_hash, + fee_recipient: block.fee_recipient, + state_root: block.state_root, + receipts_root: block.receipts_root, + logs_bloom: block.logs_bloom, + prev_randao: block.prev_randao, + block_number: block.block_number, + gas_limit: block.gas_limit, + gas_used: block.gas_used, + timestamp: block.timestamp, + extra_data: block.extra_data, + base_fee_per_gas: block.base_fee_per_gas, + block_hash: block.block_hash, + transactions: block + .transactions + .iter() + .map(|tx| Transaction::decode(&Rlp::new(tx))) + .collect::, _>>()?, + withdrawals: Vec::from(block.withdrawals) + .into_iter() + .map(|withdrawal| withdrawal.into()) + .collect(), + blob_gas_used: block.blob_gas_used, + excess_blob_gas: block.excess_blob_gas, + }) + } }; Ok(json_payload) } @@ -390,7 +423,7 @@ pub struct ProposeBlindedBlockResponse { } #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes(derive(Clone, Debug, PartialEq),), map_into(ExecutionPayload), map_ref_into(ExecutionPayloadRef), @@ -405,10 +438,12 @@ pub struct GetPayloadResponse { pub execution_payload: ExecutionPayloadCapella, #[superstruct(only(Deneb), partial_getter(rename = "execution_payload_deneb"))] pub execution_payload: ExecutionPayloadDeneb, + #[superstruct(only(Electra), partial_getter(rename = "execution_payload_electra"))] + pub execution_payload: ExecutionPayloadElectra, pub block_value: Uint256, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] pub blobs_bundle: BlobsBundle, - #[superstruct(only(Deneb), partial_getter(copy))] + #[superstruct(only(Deneb, Electra), partial_getter(copy))] pub should_override_builder: bool, } @@ -462,6 +497,11 @@ impl From> inner.block_value, Some(inner.blobs_bundle), ), + GetPayloadResponse::Electra(inner) => ( + ExecutionPayload::Electra(inner.execution_payload), + inner.block_value, + Some(inner.blobs_bundle), + ), } } } @@ -562,7 +602,35 @@ impl ExecutionPayloadBodyV1 { })) } else { Err(format!( - "block {} is post capella but payload body doesn't have withdrawals", + "block {} is post-capella but payload body doesn't have withdrawals", + header.block_hash + )) + } + } + ExecutionPayloadHeader::Electra(header) => { + if let Some(withdrawals) = self.withdrawals { + Ok(ExecutionPayload::Electra(ExecutionPayloadElectra { + parent_hash: header.parent_hash, + fee_recipient: header.fee_recipient, + state_root: header.state_root, + receipts_root: header.receipts_root, + logs_bloom: header.logs_bloom, + prev_randao: header.prev_randao, + block_number: header.block_number, + gas_limit: header.gas_limit, + gas_used: header.gas_used, + timestamp: header.timestamp, + extra_data: header.extra_data, + base_fee_per_gas: header.base_fee_per_gas, + block_hash: header.block_hash, + transactions: self.transactions, + withdrawals, + blob_gas_used: header.blob_gas_used, + excess_blob_gas: header.excess_blob_gas, + })) + } else { + Err(format!( + "block {} is post-capella but payload body doesn't have withdrawals", header.block_hash )) } diff --git a/beacon_node/execution_layer/src/engine_api/http.rs b/beacon_node/execution_layer/src/engine_api/http.rs index 0604f15c43b..6614edfef3b 100644 --- a/beacon_node/execution_layer/src/engine_api/http.rs +++ b/beacon_node/execution_layer/src/engine_api/http.rs @@ -740,6 +740,14 @@ impl HttpJsonRpc { ) .await?, ), + ForkName::Electra => ExecutionBlockWithTransactions::Electra( + self.rpc_request( + ETH_GET_BLOCK_BY_HASH, + params, + ETH_GET_BLOCK_BY_HASH_TIMEOUT * self.execution_timeout_multiplier, + ) + .await?, + ), ForkName::Base | ForkName::Altair => { return Err(Error::UnsupportedForkVariant(format!( "called get_block_by_hash_with_txns with fork {:?}", @@ -783,7 +791,7 @@ impl HttpJsonRpc { Ok(response.into()) } - pub async fn new_payload_v3( + pub async fn new_payload_v3_deneb( &self, new_payload_request_deneb: NewPayloadRequestDeneb<'_, T>, ) -> Result { @@ -804,6 +812,27 @@ impl HttpJsonRpc { Ok(response.into()) } + pub async fn new_payload_v3_electra( + &self, + new_payload_request_electra: NewPayloadRequestElectra<'_, T>, + ) -> Result { + let params = json!([ + JsonExecutionPayload::V4(new_payload_request_electra.execution_payload.clone().into()), + new_payload_request_electra.versioned_hashes, + new_payload_request_electra.parent_beacon_block_root, + ]); + + let response: JsonPayloadStatusV1 = self + .rpc_request( + ENGINE_NEW_PAYLOAD_V3, + params, + ENGINE_NEW_PAYLOAD_TIMEOUT * self.execution_timeout_multiplier, + ) + .await?; + + Ok(response.into()) + } + pub async fn get_payload_v1( &self, payload_id: PayloadId, @@ -855,7 +884,7 @@ impl HttpJsonRpc { .await?; Ok(JsonGetPayloadResponse::V2(response).into()) } - ForkName::Base | ForkName::Altair | ForkName::Deneb => Err( + ForkName::Base | ForkName::Altair | ForkName::Deneb | ForkName::Electra => Err( Error::UnsupportedForkVariant(format!("called get_payload_v2 with {}", fork_name)), ), } @@ -879,6 +908,16 @@ impl HttpJsonRpc { .await?; Ok(JsonGetPayloadResponse::V3(response).into()) } + ForkName::Electra => { + let response: JsonGetPayloadResponseV4 = self + .rpc_request( + ENGINE_GET_PAYLOAD_V3, + params, + ENGINE_GET_PAYLOAD_TIMEOUT * self.execution_timeout_multiplier, + ) + .await?; + Ok(JsonGetPayloadResponse::V4(response).into()) + } ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => Err( Error::UnsupportedForkVariant(format!("called get_payload_v3 with {}", fork_name)), ), @@ -1069,7 +1108,15 @@ impl HttpJsonRpc { } NewPayloadRequest::Deneb(new_payload_request_deneb) => { if engine_capabilities.new_payload_v3 { - self.new_payload_v3(new_payload_request_deneb).await + self.new_payload_v3_deneb(new_payload_request_deneb).await + } else { + Err(Error::RequiredMethodUnsupported("engine_newPayloadV3")) + } + } + NewPayloadRequest::Electra(new_payload_request_electra) => { + if engine_capabilities.new_payload_v3 { + self.new_payload_v3_electra(new_payload_request_electra) + .await } else { Err(Error::RequiredMethodUnsupported("engine_newPayloadV3")) } @@ -1095,7 +1142,7 @@ impl HttpJsonRpc { Err(Error::RequiredMethodUnsupported("engine_getPayload")) } } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { if engine_capabilities.get_payload_v3 { self.get_payload_v3(fork_name, payload_id).await } else { @@ -1775,7 +1822,7 @@ mod test { "extraData":"0x", "baseFeePerGas":"0x7", "blockHash":"0x6359b8381a370e2f54072a5784ddd78b6ed024991558c511d4452eb4f6ac898c", - "transactions":[] + "transactions":[], } })], |client| async move { @@ -1799,7 +1846,7 @@ mod test { extra_data: vec![].into(), base_fee_per_gas: Uint256::from(7), block_hash: ExecutionBlockHash::from_str("0x6359b8381a370e2f54072a5784ddd78b6ed024991558c511d4452eb4f6ac898c").unwrap(), - transactions: vec![].into(), + transactions: vec![].into(), }); assert_eq!(payload, expected); @@ -1846,7 +1893,7 @@ mod test { "extraData":"0x", "baseFeePerGas":"0x7", "blockHash":"0x3559e851470f6e7bbed1db474980683e8c315bfce99b2a6ef47c057c04de7858", - "transactions":[] + "transactions":[], }], }) ) diff --git a/beacon_node/execution_layer/src/engine_api/json_structures.rs b/beacon_node/execution_layer/src/engine_api/json_structures.rs index feb6c99748c..7b87807d9a6 100644 --- a/beacon_node/execution_layer/src/engine_api/json_structures.rs +++ b/beacon_node/execution_layer/src/engine_api/json_structures.rs @@ -60,7 +60,7 @@ pub struct JsonPayloadIdResponse { } #[superstruct( - variants(V1, V2, V3), + variants(V1, V2, V3, V4), variant_attributes( derive(Debug, PartialEq, Default, Serialize, Deserialize,), serde(bound = "T: EthSpec", rename_all = "camelCase"), @@ -93,12 +93,12 @@ pub struct JsonExecutionPayload { pub block_hash: ExecutionBlockHash, #[serde(with = "ssz_types::serde_utils::list_of_hex_var_list")] pub transactions: Transactions, - #[superstruct(only(V2, V3))] + #[superstruct(only(V2, V3, V4))] pub withdrawals: VariableList, - #[superstruct(only(V3))] + #[superstruct(only(V3, V4))] #[serde(with = "serde_utils::u64_hex_be")] pub blob_gas_used: u64, - #[superstruct(only(V3))] + #[superstruct(only(V3, V4))] #[serde(with = "serde_utils::u64_hex_be")] pub excess_blob_gas: u64, } @@ -178,12 +178,42 @@ impl From> for JsonExecutionPayloadV3 { } } +impl From> for JsonExecutionPayloadV4 { + fn from(payload: ExecutionPayloadElectra) -> Self { + JsonExecutionPayloadV4 { + parent_hash: payload.parent_hash, + fee_recipient: payload.fee_recipient, + state_root: payload.state_root, + receipts_root: payload.receipts_root, + logs_bloom: payload.logs_bloom, + prev_randao: payload.prev_randao, + block_number: payload.block_number, + gas_limit: payload.gas_limit, + gas_used: payload.gas_used, + timestamp: payload.timestamp, + extra_data: payload.extra_data, + base_fee_per_gas: payload.base_fee_per_gas, + block_hash: payload.block_hash, + transactions: payload.transactions, + withdrawals: payload + .withdrawals + .into_iter() + .map(Into::into) + .collect::>() + .into(), + blob_gas_used: payload.blob_gas_used, + excess_blob_gas: payload.excess_blob_gas, + } + } +} + impl From> for JsonExecutionPayload { fn from(execution_payload: ExecutionPayload) -> Self { match execution_payload { ExecutionPayload::Merge(payload) => JsonExecutionPayload::V1(payload.into()), ExecutionPayload::Capella(payload) => JsonExecutionPayload::V2(payload.into()), ExecutionPayload::Deneb(payload) => JsonExecutionPayload::V3(payload.into()), + ExecutionPayload::Electra(payload) => JsonExecutionPayload::V4(payload.into()), } } } @@ -234,6 +264,7 @@ impl From> for ExecutionPayloadCapella } } } + impl From> for ExecutionPayloadDeneb { fn from(payload: JsonExecutionPayloadV3) -> Self { ExecutionPayloadDeneb { @@ -263,18 +294,48 @@ impl From> for ExecutionPayloadDeneb { } } +impl From> for ExecutionPayloadElectra { + fn from(payload: JsonExecutionPayloadV4) -> Self { + ExecutionPayloadElectra { + parent_hash: payload.parent_hash, + fee_recipient: payload.fee_recipient, + state_root: payload.state_root, + receipts_root: payload.receipts_root, + logs_bloom: payload.logs_bloom, + prev_randao: payload.prev_randao, + block_number: payload.block_number, + gas_limit: payload.gas_limit, + gas_used: payload.gas_used, + timestamp: payload.timestamp, + extra_data: payload.extra_data, + base_fee_per_gas: payload.base_fee_per_gas, + block_hash: payload.block_hash, + transactions: payload.transactions, + withdrawals: payload + .withdrawals + .into_iter() + .map(Into::into) + .collect::>() + .into(), + blob_gas_used: payload.blob_gas_used, + excess_blob_gas: payload.excess_blob_gas, + } + } +} + impl From> for ExecutionPayload { fn from(json_execution_payload: JsonExecutionPayload) -> Self { match json_execution_payload { JsonExecutionPayload::V1(payload) => ExecutionPayload::Merge(payload.into()), JsonExecutionPayload::V2(payload) => ExecutionPayload::Capella(payload.into()), JsonExecutionPayload::V3(payload) => ExecutionPayload::Deneb(payload.into()), + JsonExecutionPayload::V4(payload) => ExecutionPayload::Electra(payload.into()), } } } #[superstruct( - variants(V1, V2, V3), + variants(V1, V2, V3, V4), variant_attributes( derive(Debug, PartialEq, Serialize, Deserialize), serde(bound = "T: EthSpec", rename_all = "camelCase") @@ -291,11 +352,13 @@ pub struct JsonGetPayloadResponse { pub execution_payload: JsonExecutionPayloadV2, #[superstruct(only(V3), partial_getter(rename = "execution_payload_v3"))] pub execution_payload: JsonExecutionPayloadV3, + #[superstruct(only(V4), partial_getter(rename = "execution_payload_v4"))] + pub execution_payload: JsonExecutionPayloadV4, #[serde(with = "serde_utils::u256_hex_be")] pub block_value: Uint256, - #[superstruct(only(V3))] + #[superstruct(only(V3, V4))] pub blobs_bundle: JsonBlobsBundleV1, - #[superstruct(only(V3))] + #[superstruct(only(V3, V4))] pub should_override_builder: bool, } @@ -322,6 +385,14 @@ impl From> for GetPayloadResponse { should_override_builder: response.should_override_builder, }) } + JsonGetPayloadResponse::V4(response) => { + GetPayloadResponse::Electra(GetPayloadResponseElectra { + execution_payload: response.execution_payload.into(), + block_value: response.block_value, + blobs_bundle: response.blobs_bundle.into(), + should_override_builder: response.should_override_builder, + }) + } } } } diff --git a/beacon_node/execution_layer/src/engine_api/new_payload_request.rs b/beacon_node/execution_layer/src/engine_api/new_payload_request.rs index b9527ed09db..6b6df13b704 100644 --- a/beacon_node/execution_layer/src/engine_api/new_payload_request.rs +++ b/beacon_node/execution_layer/src/engine_api/new_payload_request.rs @@ -7,10 +7,12 @@ use types::{ BeaconBlockRef, BeaconStateError, EthSpec, ExecutionBlockHash, ExecutionPayload, ExecutionPayloadRef, Hash256, VersionedHash, }; -use types::{ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadMerge}; +use types::{ + ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadElectra, ExecutionPayloadMerge, +}; #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes(derive(Clone, Debug, PartialEq),), map_into(ExecutionPayload), map_ref_into(ExecutionPayloadRef), @@ -31,9 +33,11 @@ pub struct NewPayloadRequest<'block, E: EthSpec> { pub execution_payload: &'block ExecutionPayloadCapella, #[superstruct(only(Deneb), partial_getter(rename = "execution_payload_deneb"))] pub execution_payload: &'block ExecutionPayloadDeneb, - #[superstruct(only(Deneb))] + #[superstruct(only(Electra), partial_getter(rename = "execution_payload_electra"))] + pub execution_payload: &'block ExecutionPayloadElectra, + #[superstruct(only(Deneb, Electra))] pub versioned_hashes: Vec, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] pub parent_beacon_block_root: Hash256, } @@ -43,6 +47,7 @@ impl<'block, E: EthSpec> NewPayloadRequest<'block, E> { Self::Merge(payload) => payload.execution_payload.parent_hash, Self::Capella(payload) => payload.execution_payload.parent_hash, Self::Deneb(payload) => payload.execution_payload.parent_hash, + Self::Electra(payload) => payload.execution_payload.parent_hash, } } @@ -51,6 +56,7 @@ impl<'block, E: EthSpec> NewPayloadRequest<'block, E> { Self::Merge(payload) => payload.execution_payload.block_hash, Self::Capella(payload) => payload.execution_payload.block_hash, Self::Deneb(payload) => payload.execution_payload.block_hash, + Self::Electra(payload) => payload.execution_payload.block_hash, } } @@ -59,6 +65,7 @@ impl<'block, E: EthSpec> NewPayloadRequest<'block, E> { Self::Merge(payload) => payload.execution_payload.block_number, Self::Capella(payload) => payload.execution_payload.block_number, Self::Deneb(payload) => payload.execution_payload.block_number, + Self::Electra(payload) => payload.execution_payload.block_number, } } @@ -67,6 +74,7 @@ impl<'block, E: EthSpec> NewPayloadRequest<'block, E> { Self::Merge(request) => ExecutionPayloadRef::Merge(request.execution_payload), Self::Capella(request) => ExecutionPayloadRef::Capella(request.execution_payload), Self::Deneb(request) => ExecutionPayloadRef::Deneb(request.execution_payload), + Self::Electra(request) => ExecutionPayloadRef::Electra(request.execution_payload), } } @@ -75,6 +83,7 @@ impl<'block, E: EthSpec> NewPayloadRequest<'block, E> { Self::Merge(request) => ExecutionPayload::Merge(request.execution_payload.clone()), Self::Capella(request) => ExecutionPayload::Capella(request.execution_payload.clone()), Self::Deneb(request) => ExecutionPayload::Deneb(request.execution_payload.clone()), + Self::Electra(request) => ExecutionPayload::Electra(request.execution_payload.clone()), } } @@ -157,6 +166,16 @@ impl<'a, E: EthSpec> TryFrom> for NewPayloadRequest<'a, E> .collect(), parent_beacon_block_root: block_ref.parent_root, })), + BeaconBlockRef::Electra(block_ref) => Ok(Self::Electra(NewPayloadRequestElectra { + execution_payload: &block_ref.body.execution_payload.execution_payload, + versioned_hashes: block_ref + .body + .blob_kzg_commitments + .iter() + .map(kzg_commitment_to_versioned_hash) + .collect(), + parent_beacon_block_root: block_ref.parent_root, + })), } } } @@ -173,6 +192,7 @@ impl<'a, E: EthSpec> TryFrom> for NewPayloadRequest<' execution_payload: payload, })), ExecutionPayloadRef::Deneb(_) => Err(Self::Error::IncorrectStateVariant), + ExecutionPayloadRef::Electra(_) => Err(Self::Error::IncorrectStateVariant), } } } diff --git a/beacon_node/execution_layer/src/lib.rs b/beacon_node/execution_layer/src/lib.rs index 69b84adbb8f..0fc952a8c21 100644 --- a/beacon_node/execution_layer/src/lib.rs +++ b/beacon_node/execution_layer/src/lib.rs @@ -51,7 +51,8 @@ use types::{ }; use types::{ BeaconStateError, BlindedPayload, ChainSpec, Epoch, ExecPayload, ExecutionPayloadCapella, - ExecutionPayloadMerge, FullPayload, ProposerPreparationData, PublicKeyBytes, Signature, Slot, + ExecutionPayloadElectra, ExecutionPayloadMerge, FullPayload, ProposerPreparationData, + PublicKeyBytes, Signature, Slot, }; mod block_hash; @@ -111,6 +112,12 @@ impl TryFrom> for ProvenancedPayload BlockProposalContents::PayloadAndBlobs { + payload: ExecutionPayloadHeader::Electra(builder_bid.header).into(), + block_value: builder_bid.value, + kzg_commitments: builder_bid.blob_kzg_commitments, + blobs_and_proofs: None, + }, }; Ok(ProvenancedPayload::Builder( BlockProposalContentsType::Blinded(block_proposal_contents), @@ -1771,6 +1778,7 @@ impl ExecutionLayer { ForkName::Merge => ExecutionPayloadMerge::default().into(), ForkName::Capella => ExecutionPayloadCapella::default().into(), ForkName::Deneb => ExecutionPayloadDeneb::default().into(), + ForkName::Electra => ExecutionPayloadElectra::default().into(), ForkName::Base | ForkName::Altair => { return Err(Error::InvalidForkForPayload); } @@ -1839,6 +1847,7 @@ impl ExecutionLayer { ForkName::Merge => Ok(Some(ExecutionPayloadMerge::default().into())), ForkName::Capella => Ok(Some(ExecutionPayloadCapella::default().into())), ForkName::Deneb => Ok(Some(ExecutionPayloadDeneb::default().into())), + ForkName::Electra => Ok(Some(ExecutionPayloadElectra::default().into())), ForkName::Base | ForkName::Altair => Err(ApiError::UnsupportedForkVariant( format!("called get_payload_by_hash_from_engine with {}", fork), )), @@ -1938,6 +1947,35 @@ impl ExecutionLayer { excess_blob_gas: deneb_block.excess_blob_gas, }) } + ExecutionBlockWithTransactions::Electra(electra_block) => { + let withdrawals = VariableList::new( + electra_block + .withdrawals + .into_iter() + .map(Into::into) + .collect(), + ) + .map_err(ApiError::DeserializeWithdrawals)?; + ExecutionPayload::Electra(ExecutionPayloadElectra { + parent_hash: electra_block.parent_hash, + fee_recipient: electra_block.fee_recipient, + state_root: electra_block.state_root, + receipts_root: electra_block.receipts_root, + logs_bloom: electra_block.logs_bloom, + prev_randao: electra_block.prev_randao, + block_number: electra_block.block_number, + gas_limit: electra_block.gas_limit, + gas_used: electra_block.gas_used, + timestamp: electra_block.timestamp, + extra_data: electra_block.extra_data, + base_fee_per_gas: electra_block.base_fee_per_gas, + block_hash: electra_block.block_hash, + transactions: convert_transactions(electra_block.transactions)?, + withdrawals, + blob_gas_used: electra_block.blob_gas_used, + excess_blob_gas: electra_block.excess_blob_gas, + }) + } }; Ok(Some(payload)) diff --git a/beacon_node/execution_layer/src/test_utils/execution_block_generator.rs b/beacon_node/execution_layer/src/test_utils/execution_block_generator.rs index 6af988fa88f..82aa8f41873 100644 --- a/beacon_node/execution_layer/src/test_utils/execution_block_generator.rs +++ b/beacon_node/execution_layer/src/test_utils/execution_block_generator.rs @@ -22,8 +22,8 @@ use tree_hash::TreeHash; use tree_hash_derive::TreeHash; use types::{ Blob, ChainSpec, EthSpec, ExecutionBlockHash, ExecutionPayload, ExecutionPayloadCapella, - ExecutionPayloadDeneb, ExecutionPayloadHeader, ExecutionPayloadMerge, ForkName, Hash256, - Transaction, Transactions, Uint256, + ExecutionPayloadDeneb, ExecutionPayloadElectra, ExecutionPayloadHeader, ExecutionPayloadMerge, + ForkName, Hash256, Transaction, Transactions, Uint256, }; use super::DEFAULT_TERMINAL_BLOCK; @@ -130,8 +130,9 @@ pub struct ExecutionBlockGenerator { /* * Post-merge fork triggers */ - pub shanghai_time: Option, // withdrawals + pub shanghai_time: Option, // capella pub cancun_time: Option, // deneb + pub prague_time: Option, // electra /* * deneb stuff */ @@ -153,6 +154,7 @@ impl ExecutionBlockGenerator { terminal_block_hash: ExecutionBlockHash, shanghai_time: Option, cancun_time: Option, + prague_time: Option, kzg: Option, ) -> Self { let mut gen = Self { @@ -168,6 +170,7 @@ impl ExecutionBlockGenerator { payload_ids: <_>::default(), shanghai_time, cancun_time, + prague_time, blobs_bundles: <_>::default(), kzg: kzg.map(Arc::new), rng: make_rng(), @@ -203,11 +206,14 @@ impl ExecutionBlockGenerator { } pub fn get_fork_at_timestamp(&self, timestamp: u64) -> ForkName { - match self.cancun_time { - Some(fork_time) if timestamp >= fork_time => ForkName::Deneb, - _ => match self.shanghai_time { - Some(fork_time) if timestamp >= fork_time => ForkName::Capella, - _ => ForkName::Merge, + match self.prague_time { + Some(fork_time) if timestamp >= fork_time => ForkName::Electra, + _ => match self.cancun_time { + Some(fork_time) if timestamp >= fork_time => ForkName::Deneb, + _ => match self.shanghai_time { + Some(fork_time) if timestamp >= fork_time => ForkName::Capella, + _ => ForkName::Merge, + }, }, } } @@ -514,6 +520,7 @@ impl ExecutionBlockGenerator { let execution_payload = self.build_new_execution_payload(head_block_hash, &parent, id, &attributes)?; + self.payload_ids.insert(id, execution_payload); Some(id) @@ -601,30 +608,52 @@ impl ExecutionBlockGenerator { }), _ => unreachable!(), }, - PayloadAttributes::V3(pa) => ExecutionPayload::Deneb(ExecutionPayloadDeneb { - parent_hash: head_block_hash, - fee_recipient: pa.suggested_fee_recipient, - receipts_root: Hash256::repeat_byte(42), - state_root: Hash256::repeat_byte(43), - logs_bloom: vec![0; 256].into(), - prev_randao: pa.prev_randao, - block_number: parent.block_number() + 1, - gas_limit: GAS_LIMIT, - gas_used: GAS_USED, - timestamp: pa.timestamp, - extra_data: "block gen was here".as_bytes().to_vec().into(), - base_fee_per_gas: Uint256::one(), - block_hash: ExecutionBlockHash::zero(), - transactions: vec![].into(), - withdrawals: pa.withdrawals.clone().into(), - blob_gas_used: 0, - excess_blob_gas: 0, - }), + PayloadAttributes::V3(pa) => match self.get_fork_at_timestamp(pa.timestamp) { + ForkName::Deneb => ExecutionPayload::Deneb(ExecutionPayloadDeneb { + parent_hash: head_block_hash, + fee_recipient: pa.suggested_fee_recipient, + receipts_root: Hash256::repeat_byte(42), + state_root: Hash256::repeat_byte(43), + logs_bloom: vec![0; 256].into(), + prev_randao: pa.prev_randao, + block_number: parent.block_number() + 1, + gas_limit: GAS_LIMIT, + gas_used: GAS_USED, + timestamp: pa.timestamp, + extra_data: "block gen was here".as_bytes().to_vec().into(), + base_fee_per_gas: Uint256::one(), + block_hash: ExecutionBlockHash::zero(), + transactions: vec![].into(), + withdrawals: pa.withdrawals.clone().into(), + blob_gas_used: 0, + excess_blob_gas: 0, + }), + ForkName::Electra => ExecutionPayload::Electra(ExecutionPayloadElectra { + parent_hash: head_block_hash, + fee_recipient: pa.suggested_fee_recipient, + receipts_root: Hash256::repeat_byte(42), + state_root: Hash256::repeat_byte(43), + logs_bloom: vec![0; 256].into(), + prev_randao: pa.prev_randao, + block_number: parent.block_number() + 1, + gas_limit: GAS_LIMIT, + gas_used: GAS_USED, + timestamp: pa.timestamp, + extra_data: "block gen was here".as_bytes().to_vec().into(), + base_fee_per_gas: Uint256::one(), + block_hash: ExecutionBlockHash::zero(), + transactions: vec![].into(), + withdrawals: pa.withdrawals.clone().into(), + blob_gas_used: 0, + excess_blob_gas: 0, + }), + _ => unreachable!(), + }, }; match execution_payload.fork_name() { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => {} - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { // get random number between 0 and Max Blobs let mut rng = self.rng.lock(); let num_blobs = rng.gen::() % (T::max_blobs_per_block() + 1); @@ -758,6 +787,11 @@ pub fn generate_genesis_header( *header.block_hash_mut() = genesis_block_hash.unwrap_or_default(); Some(header) } + ForkName::Electra => { + let mut header = ExecutionPayloadHeader::Electra(<_>::default()); + *header.block_hash_mut() = genesis_block_hash.unwrap_or_default(); + Some(header) + } } } @@ -830,6 +864,7 @@ mod test { None, None, None, + None, ); for i in 0..=TERMINAL_BLOCK { diff --git a/beacon_node/execution_layer/src/test_utils/handle_rpc.rs b/beacon_node/execution_layer/src/test_utils/handle_rpc.rs index 623c1c9548a..bc289eebb5b 100644 --- a/beacon_node/execution_layer/src/test_utils/handle_rpc.rs +++ b/beacon_node/execution_layer/src/test_utils/handle_rpc.rs @@ -105,14 +105,18 @@ pub async fn handle_rpc( .map(|jep| JsonExecutionPayload::V1(jep)) }) .map_err(|s| (s, BAD_PARAMS_ERROR_CODE))?, - ENGINE_NEW_PAYLOAD_V3 => get_param::>(params, 0) - .map(|jep| JsonExecutionPayload::V3(jep)) + ENGINE_NEW_PAYLOAD_V3 => get_param::>(params, 0) + .map(|jep| JsonExecutionPayload::V4(jep)) .or_else(|_| { - get_param::>(params, 0) - .map(|jep| JsonExecutionPayload::V2(jep)) + get_param::>(params, 0) + .map(|jep| JsonExecutionPayload::V3(jep)) .or_else(|_| { - get_param::>(params, 0) - .map(|jep| JsonExecutionPayload::V1(jep)) + get_param::>(params, 0) + .map(|jep| JsonExecutionPayload::V2(jep)) + .or_else(|_| { + get_param::>(params, 0) + .map(|jep| JsonExecutionPayload::V1(jep)) + }) }) }) .map_err(|s| (s, BAD_PARAMS_ERROR_CODE))?, @@ -123,7 +127,7 @@ pub async fn handle_rpc( .execution_block_generator .read() .get_fork_at_timestamp(*request.timestamp()); - // validate method called correctly according to shanghai fork time + // validate method called correctly according to fork time match fork { ForkName::Merge => { if matches!(request, JsonExecutionPayload::V2(_)) { @@ -156,14 +160,40 @@ pub async fn handle_rpc( ForkName::Deneb => { if method == ENGINE_NEW_PAYLOAD_V1 || method == ENGINE_NEW_PAYLOAD_V2 { return Err(( - format!("{} called after deneb fork!", method), + format!("{} called after Deneb fork!", method), + GENERIC_ERROR_CODE, + )); + } + if matches!(request, JsonExecutionPayload::V1(_)) { + return Err(( + format!( + "{} called with `ExecutionPayloadV1` after Deneb fork!", + method + ), + GENERIC_ERROR_CODE, + )); + } + if matches!(request, JsonExecutionPayload::V2(_)) { + return Err(( + format!( + "{} called with `ExecutionPayloadV2` after Deneb fork!", + method + ), + GENERIC_ERROR_CODE, + )); + } + } + ForkName::Electra => { + if method == ENGINE_NEW_PAYLOAD_V1 || method == ENGINE_NEW_PAYLOAD_V2 { + return Err(( + format!("{} called after Electra fork!", method), GENERIC_ERROR_CODE, )); } if matches!(request, JsonExecutionPayload::V1(_)) { return Err(( format!( - "{} called with `ExecutionPayloadV1` after deneb fork!", + "{} called with `ExecutionPayloadV1` after Electra fork!", method ), GENERIC_ERROR_CODE, @@ -172,7 +202,16 @@ pub async fn handle_rpc( if matches!(request, JsonExecutionPayload::V2(_)) { return Err(( format!( - "{} called with `ExecutionPayloadV2` after deneb fork!", + "{} called with `ExecutionPayloadV2` after Electra fork!", + method + ), + GENERIC_ERROR_CODE, + )); + } + if matches!(request, JsonExecutionPayload::V3(_)) { + return Err(( + format!( + "{} called with `ExecutionPayloadV3` after Electra fork!", method ), GENERIC_ERROR_CODE, @@ -245,7 +284,7 @@ pub async fn handle_rpc( FORK_REQUEST_MISMATCH_ERROR_CODE, )); } - // validate method called correctly according to deneb fork time + // validate method called correctly according to cancun fork time if ctx .execution_block_generator .read() @@ -254,7 +293,20 @@ pub async fn handle_rpc( && (method == ENGINE_GET_PAYLOAD_V1 || method == ENGINE_GET_PAYLOAD_V2) { return Err(( - format!("{} called after deneb fork!", method), + format!("{} called after Deneb fork!", method), + FORK_REQUEST_MISMATCH_ERROR_CODE, + )); + } + // validate method called correctly according to prague fork time + if ctx + .execution_block_generator + .read() + .get_fork_at_timestamp(response.timestamp()) + == ForkName::Electra + && method == ENGINE_GET_PAYLOAD_V1 + { + return Err(( + format!("{} called after Electra fork!", method), FORK_REQUEST_MISMATCH_ERROR_CODE, )); } @@ -295,6 +347,20 @@ pub async fn handle_rpc( }) .unwrap() } + JsonExecutionPayload::V4(execution_payload) => { + serde_json::to_value(JsonGetPayloadResponseV4 { + execution_payload, + block_value: DEFAULT_MOCK_EL_PAYLOAD_VALUE_WEI.into(), + blobs_bundle: maybe_blobs + .ok_or(( + "No blobs returned despite V4 Payload".to_string(), + GENERIC_ERROR_CODE, + ))? + .into(), + should_override_builder: false, + }) + .unwrap() + } _ => unreachable!(), }), _ => unreachable!(), @@ -328,7 +394,7 @@ pub async fn handle_rpc( .map(|opt| opt.map(JsonPayloadAttributes::V1)) .transpose() } - ForkName::Capella | ForkName::Deneb => { + ForkName::Capella | ForkName::Deneb | ForkName::Electra => { get_param::>(params, 1) .map(|opt| opt.map(JsonPayloadAttributes::V2)) .transpose() @@ -392,7 +458,7 @@ pub async fn handle_rpc( )); } } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { if method == ENGINE_FORKCHOICE_UPDATED_V1 { return Err(( format!("{} called after Deneb fork!", method), diff --git a/beacon_node/execution_layer/src/test_utils/mock_builder.rs b/beacon_node/execution_layer/src/test_utils/mock_builder.rs index 759348bb41c..85fcbc09ac5 100644 --- a/beacon_node/execution_layer/src/test_utils/mock_builder.rs +++ b/beacon_node/execution_layer/src/test_utils/mock_builder.rs @@ -15,7 +15,8 @@ use task_executor::TaskExecutor; use tempfile::NamedTempFile; use tree_hash::TreeHash; use types::builder_bid::{ - BuilderBid, BuilderBidCapella, BuilderBidDeneb, BuilderBidMerge, SignedBuilderBid, + BuilderBid, BuilderBidCapella, BuilderBidDeneb, BuilderBidElectra, BuilderBidMerge, + SignedBuilderBid, }; use types::{ Address, BeaconState, ChainSpec, EthSpec, ExecPayload, ExecutionPayload, @@ -85,6 +86,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.fee_recipient = fee_recipient; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.fee_recipient = fee_recipient; + } } } @@ -99,6 +103,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.gas_limit = gas_limit; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.gas_limit = gas_limit; + } } } @@ -117,6 +124,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.parent_hash = ExecutionBlockHash::from_root(parent_hash); } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.parent_hash = ExecutionBlockHash::from_root(parent_hash); + } } } @@ -131,6 +141,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.prev_randao = prev_randao; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.prev_randao = prev_randao; + } } } @@ -145,6 +158,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.block_number = block_number; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.block_number = block_number; + } } } @@ -159,6 +175,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.timestamp = timestamp; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.timestamp = timestamp; + } } } @@ -173,6 +192,9 @@ impl BidStuff for BuilderBid { ExecutionPayloadHeaderRefMut::Deneb(header) => { header.withdrawals_root = withdrawals_root; } + ExecutionPayloadHeaderRefMut::Electra(header) => { + header.withdrawals_root = withdrawals_root; + } } } @@ -320,6 +342,9 @@ pub fn serve( SignedBlindedBeaconBlock::Deneb(block) => { block.message.body.execution_payload.tree_hash_root() } + SignedBlindedBeaconBlock::Electra(block) => { + block.message.body.execution_payload.tree_hash_root() + } }; let fork_name = builder.spec.fork_name_at_slot::(slot); @@ -455,7 +480,7 @@ pub fn serve( .map_err(|_| reject("couldn't get prev randao"))?; let expected_withdrawals = match fork { ForkName::Base | ForkName::Altair | ForkName::Merge => None, - ForkName::Capella | ForkName::Deneb => Some( + ForkName::Capella | ForkName::Deneb | ForkName::Electra => Some( builder .beacon_client .get_expected_withdrawals(&StateId::Head) @@ -477,7 +502,7 @@ pub fn serve( expected_withdrawals, None, ), - ForkName::Deneb => PayloadAttributes::new( + ForkName::Deneb | ForkName::Electra => PayloadAttributes::new( timestamp, *prev_randao, fee_recipient, @@ -521,6 +546,17 @@ pub fn serve( ) = payload_response.into(); match fork { + ForkName::Electra => BuilderBid::Electra(BuilderBidElectra { + header: payload + .as_electra() + .map_err(|_| reject("incorrect payload variant"))? + .into(), + blob_kzg_commitments: maybe_blobs_bundle + .map(|b| b.commitments) + .unwrap_or_default(), + value: Uint256::from(DEFAULT_BUILDER_PAYLOAD_VALUE_WEI), + pubkey: builder.builder_sk.public_key().compress(), + }), ForkName::Deneb => BuilderBid::Deneb(BuilderBidDeneb { header: payload .as_deneb() @@ -560,6 +596,17 @@ pub fn serve( Option>, ) = payload_response.into(); match fork { + ForkName::Electra => BuilderBid::Electra(BuilderBidElectra { + header: payload + .as_electra() + .map_err(|_| reject("incorrect payload variant"))? + .into(), + blob_kzg_commitments: maybe_blobs_bundle + .map(|b| b.commitments) + .unwrap_or_default(), + value: Uint256::from(DEFAULT_BUILDER_PAYLOAD_VALUE_WEI), + pubkey: builder.builder_sk.public_key().compress(), + }), ForkName::Deneb => BuilderBid::Deneb(BuilderBidDeneb { header: payload .as_deneb() diff --git a/beacon_node/execution_layer/src/test_utils/mock_execution_layer.rs b/beacon_node/execution_layer/src/test_utils/mock_execution_layer.rs index 3dd49404393..ed7b8bad114 100644 --- a/beacon_node/execution_layer/src/test_utils/mock_execution_layer.rs +++ b/beacon_node/execution_layer/src/test_utils/mock_execution_layer.rs @@ -27,6 +27,7 @@ impl MockExecutionLayer { DEFAULT_TERMINAL_BLOCK, None, None, + None, Some(JwtKey::from_slice(&DEFAULT_JWT_SECRET).unwrap()), spec, None, @@ -39,6 +40,7 @@ impl MockExecutionLayer { terminal_block: u64, shanghai_time: Option, cancun_time: Option, + prague_time: Option, jwt_key: Option, spec: ChainSpec, kzg: Option, @@ -54,6 +56,7 @@ impl MockExecutionLayer { spec.terminal_block_hash, shanghai_time, cancun_time, + prague_time, kzg, ); diff --git a/beacon_node/execution_layer/src/test_utils/mod.rs b/beacon_node/execution_layer/src/test_utils/mod.rs index 425329a520a..aaea257af6c 100644 --- a/beacon_node/execution_layer/src/test_utils/mod.rs +++ b/beacon_node/execution_layer/src/test_utils/mod.rs @@ -66,6 +66,7 @@ pub struct MockExecutionConfig { pub terminal_block_hash: ExecutionBlockHash, pub shanghai_time: Option, pub cancun_time: Option, + pub prague_time: Option, } impl Default for MockExecutionConfig { @@ -78,6 +79,7 @@ impl Default for MockExecutionConfig { server_config: Config::default(), shanghai_time: None, cancun_time: None, + prague_time: None, } } } @@ -99,7 +101,8 @@ impl MockServer { ExecutionBlockHash::zero(), None, // FIXME(capella): should this be the default? None, // FIXME(deneb): should this be the default? - None, // FIXME(deneb): should this be the default? + None, // FIXME(electra): should this be the default? + None, ) } @@ -116,6 +119,7 @@ impl MockServer { server_config, shanghai_time, cancun_time, + prague_time, } = config; let last_echo_request = Arc::new(RwLock::new(None)); let preloaded_responses = Arc::new(Mutex::new(vec![])); @@ -125,6 +129,7 @@ impl MockServer { terminal_block_hash, shanghai_time, cancun_time, + prague_time, kzg, ); @@ -187,6 +192,7 @@ impl MockServer { terminal_block_hash: ExecutionBlockHash, shanghai_time: Option, cancun_time: Option, + prague_time: Option, kzg: Option, ) -> Self { Self::new_with_config( @@ -199,6 +205,7 @@ impl MockServer { terminal_block_hash, shanghai_time, cancun_time, + prague_time, }, kzg, ) diff --git a/beacon_node/http_api/src/build_block_contents.rs b/beacon_node/http_api/src/build_block_contents.rs index 37b4049c0c6..7e3778b3fbb 100644 --- a/beacon_node/http_api/src/build_block_contents.rs +++ b/beacon_node/http_api/src/build_block_contents.rs @@ -15,7 +15,7 @@ pub fn build_block_contents( ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => Ok( ProduceBlockV3Response::Full(FullBlockContents::Block(block.block)), ), - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let BeaconBlockResponse { block, state: _, diff --git a/beacon_node/http_api/src/publish_blocks.rs b/beacon_node/http_api/src/publish_blocks.rs index 2a962014278..52e77753ce4 100644 --- a/beacon_node/http_api/src/publish_blocks.rs +++ b/beacon_node/http_api/src/publish_blocks.rs @@ -85,7 +85,7 @@ pub async fn publish_block { + SignedBeaconBlock::Deneb(_) | SignedBeaconBlock::Electra(_) => { let mut pubsub_messages = vec![PubsubMessage::BeaconBlock(block)]; if let Some(blob_sidecars) = blobs_opt { for (blob_index, blob) in blob_sidecars.into_iter().enumerate() { diff --git a/beacon_node/http_api/tests/tests.rs b/beacon_node/http_api/tests/tests.rs index ae109f93241..113227e2e69 100644 --- a/beacon_node/http_api/tests/tests.rs +++ b/beacon_node/http_api/tests/tests.rs @@ -1931,9 +1931,9 @@ impl ApiTester { pub async fn test_get_config_spec(self) -> Self { let result = self .client - .get_config_spec::() + .get_config_spec::() .await - .map(|res| ConfigAndPreset::Deneb(res.data)) + .map(|res| ConfigAndPreset::Electra(res.data)) .unwrap(); let expected = ConfigAndPreset::from_chain_spec::(&self.chain.spec, None); diff --git a/beacon_node/lighthouse_network/src/config.rs b/beacon_node/lighthouse_network/src/config.rs index c1af1b8fb78..85f8b1f848d 100644 --- a/beacon_node/lighthouse_network/src/config.rs +++ b/beacon_node/lighthouse_network/src/config.rs @@ -448,7 +448,11 @@ pub fn gossipsub_config( ) -> Vec { let topic_bytes = message.topic.as_str().as_bytes(); match fork_context.current_fork() { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => { + ForkName::Altair + | ForkName::Merge + | ForkName::Capella + | ForkName::Deneb + | ForkName::Electra => { let topic_len_bytes = topic_bytes.len().to_le_bytes(); let mut vec = Vec::with_capacity( prefix.len() + topic_len_bytes.len() + topic_bytes.len() + message.data.len(), diff --git a/beacon_node/lighthouse_network/src/rpc/codec/base.rs b/beacon_node/lighthouse_network/src/rpc/codec/base.rs index 4085ac17b73..a792d1b4bdf 100644 --- a/beacon_node/lighthouse_network/src/rpc/codec/base.rs +++ b/beacon_node/lighthouse_network/src/rpc/codec/base.rs @@ -195,11 +195,13 @@ mod tests { let merge_fork_epoch = Epoch::new(2); let capella_fork_epoch = Epoch::new(3); let deneb_fork_epoch = Epoch::new(4); + let electra_fork_epoch = Epoch::new(5); chain_spec.altair_fork_epoch = Some(altair_fork_epoch); chain_spec.bellatrix_fork_epoch = Some(merge_fork_epoch); chain_spec.capella_fork_epoch = Some(capella_fork_epoch); chain_spec.deneb_fork_epoch = Some(deneb_fork_epoch); + chain_spec.electra_fork_epoch = Some(electra_fork_epoch); let current_slot = match fork_name { ForkName::Base => Slot::new(0), @@ -207,6 +209,7 @@ mod tests { ForkName::Merge => merge_fork_epoch.start_slot(Spec::slots_per_epoch()), ForkName::Capella => capella_fork_epoch.start_slot(Spec::slots_per_epoch()), ForkName::Deneb => deneb_fork_epoch.start_slot(Spec::slots_per_epoch()), + ForkName::Electra => electra_fork_epoch.start_slot(Spec::slots_per_epoch()), }; ForkContext::new::(current_slot, Hash256::zero(), &chain_spec) } diff --git a/beacon_node/lighthouse_network/src/rpc/codec/ssz_snappy.rs b/beacon_node/lighthouse_network/src/rpc/codec/ssz_snappy.rs index c3c198adc48..0d0afeb791d 100644 --- a/beacon_node/lighthouse_network/src/rpc/codec/ssz_snappy.rs +++ b/beacon_node/lighthouse_network/src/rpc/codec/ssz_snappy.rs @@ -19,7 +19,8 @@ use types::ChainSpec; use types::{ BlobSidecar, EthSpec, ForkContext, ForkName, Hash256, LightClientBootstrap, RuntimeVariableList, SignedBeaconBlock, SignedBeaconBlockAltair, SignedBeaconBlockBase, - SignedBeaconBlockCapella, SignedBeaconBlockDeneb, SignedBeaconBlockMerge, + SignedBeaconBlockCapella, SignedBeaconBlockDeneb, SignedBeaconBlockElectra, + SignedBeaconBlockMerge, }; use unsigned_varint::codec::Uvi; @@ -402,6 +403,9 @@ fn context_bytes( return match **ref_box_block { // NOTE: If you are adding another fork type here, be sure to modify the // `fork_context.to_context_bytes()` function to support it as well! + SignedBeaconBlock::Electra { .. } => { + fork_context.to_context_bytes(ForkName::Electra) + } SignedBeaconBlock::Deneb { .. } => { fork_context.to_context_bytes(ForkName::Deneb) } @@ -625,6 +629,11 @@ fn handle_rpc_response( Some(ForkName::Deneb) => Ok(Some(RPCResponse::BlocksByRange(Arc::new( SignedBeaconBlock::Deneb(SignedBeaconBlockDeneb::from_ssz_bytes(decoded_buffer)?), )))), + Some(ForkName::Electra) => Ok(Some(RPCResponse::BlocksByRange(Arc::new( + SignedBeaconBlock::Electra(SignedBeaconBlockElectra::from_ssz_bytes( + decoded_buffer, + )?), + )))), None => Err(RPCError::ErrorResponse( RPCResponseErrorCode::InvalidRequest, format!( @@ -651,6 +660,11 @@ fn handle_rpc_response( Some(ForkName::Deneb) => Ok(Some(RPCResponse::BlocksByRoot(Arc::new( SignedBeaconBlock::Deneb(SignedBeaconBlockDeneb::from_ssz_bytes(decoded_buffer)?), )))), + Some(ForkName::Electra) => Ok(Some(RPCResponse::BlocksByRoot(Arc::new( + SignedBeaconBlock::Electra(SignedBeaconBlockElectra::from_ssz_bytes( + decoded_buffer, + )?), + )))), None => Err(RPCError::ErrorResponse( RPCResponseErrorCode::InvalidRequest, format!( @@ -700,11 +714,13 @@ mod tests { let merge_fork_epoch = Epoch::new(2); let capella_fork_epoch = Epoch::new(3); let deneb_fork_epoch = Epoch::new(4); + let electra_fork_epoch = Epoch::new(5); chain_spec.altair_fork_epoch = Some(altair_fork_epoch); chain_spec.bellatrix_fork_epoch = Some(merge_fork_epoch); chain_spec.capella_fork_epoch = Some(capella_fork_epoch); chain_spec.deneb_fork_epoch = Some(deneb_fork_epoch); + chain_spec.electra_fork_epoch = Some(electra_fork_epoch); let current_slot = match fork_name { ForkName::Base => Slot::new(0), @@ -712,6 +728,7 @@ mod tests { ForkName::Merge => merge_fork_epoch.start_slot(Spec::slots_per_epoch()), ForkName::Capella => capella_fork_epoch.start_slot(Spec::slots_per_epoch()), ForkName::Deneb => deneb_fork_epoch.start_slot(Spec::slots_per_epoch()), + ForkName::Electra => electra_fork_epoch.start_slot(Spec::slots_per_epoch()), }; ForkContext::new::(current_slot, Hash256::zero(), &chain_spec) } diff --git a/beacon_node/lighthouse_network/src/rpc/protocol.rs b/beacon_node/lighthouse_network/src/rpc/protocol.rs index 44a32eff2de..e57276d8792 100644 --- a/beacon_node/lighthouse_network/src/rpc/protocol.rs +++ b/beacon_node/lighthouse_network/src/rpc/protocol.rs @@ -17,9 +17,9 @@ use tokio_util::{ compat::{Compat, FuturesAsyncReadCompatExt}, }; use types::{ - BeaconBlock, BeaconBlockAltair, BeaconBlockBase, BeaconBlockCapella, BeaconBlockMerge, - BlobSidecar, ChainSpec, EmptyBlock, EthSpec, ForkContext, ForkName, MainnetEthSpec, Signature, - SignedBeaconBlock, + BeaconBlock, BeaconBlockAltair, BeaconBlockBase, BeaconBlockCapella, BeaconBlockElectra, + BeaconBlockMerge, BlobSidecar, ChainSpec, EmptyBlock, EthSpec, ForkContext, ForkName, + MainnetEthSpec, Signature, SignedBeaconBlock, }; lazy_static! { @@ -65,6 +65,13 @@ lazy_static! { .as_ssz_bytes() .len(); + pub static ref SIGNED_BEACON_BLOCK_ELECTRA_MAX_WITHOUT_PAYLOAD: usize = SignedBeaconBlock::::from_block( + BeaconBlock::Electra(BeaconBlockElectra::full(&MainnetEthSpec::default_spec())), + Signature::empty(), + ) + .as_ssz_bytes() + .len(); + /// The `BeaconBlockMerge` block has an `ExecutionPayload` field which has a max size ~16 GiB for future proofing. /// We calculate the value from its fields instead of constructing the block and checking the length. /// Note: This is only the theoretical upper bound. We further bound the max size we receive over the network @@ -83,6 +90,12 @@ lazy_static! { + types::ExecutionPayload::::max_execution_payload_deneb_size() // adding max size of execution payload (~16gb) + ssz::BYTES_PER_LENGTH_OFFSET // Adding the additional offsets for the `ExecutionPayload` + (::ssz_fixed_len() * ::max_blobs_per_block()) + + ssz::BYTES_PER_LENGTH_OFFSET; // Length offset for the blob commitments field. + // + pub static ref SIGNED_BEACON_BLOCK_ELECTRA_MAX: usize = *SIGNED_BEACON_BLOCK_ELECTRA_MAX_WITHOUT_PAYLOAD + + types::ExecutionPayload::::max_execution_payload_electra_size() // adding max size of execution payload (~16gb) + + ssz::BYTES_PER_LENGTH_OFFSET // Adding the additional ssz offset for the `ExecutionPayload` field + + (::ssz_fixed_len() * ::max_blobs_per_block()) + ssz::BYTES_PER_LENGTH_OFFSET; // Length offset for the blob commitments field. pub static ref ERROR_TYPE_MIN: usize = @@ -112,6 +125,7 @@ pub fn max_rpc_size(fork_context: &ForkContext, max_chunk_size: usize) -> usize ForkName::Merge => max_chunk_size, ForkName::Capella => max_chunk_size, ForkName::Deneb => max_chunk_size, + ForkName::Electra => max_chunk_size, } } @@ -138,7 +152,11 @@ pub fn rpc_block_limits_by_fork(current_fork: ForkName) -> RpcLimits { ), ForkName::Deneb => RpcLimits::new( *SIGNED_BEACON_BLOCK_BASE_MIN, // Base block is smaller than altair and merge blocks - *SIGNED_BEACON_BLOCK_DENEB_MAX, // EIP 4844 block is larger than all prior fork blocks + *SIGNED_BEACON_BLOCK_DENEB_MAX, // Deneb block is larger than all prior fork blocks + ), + ForkName::Electra => RpcLimits::new( + *SIGNED_BEACON_BLOCK_BASE_MIN, // Base block is smaller than altair and merge blocks + *SIGNED_BEACON_BLOCK_ELECTRA_MAX, // Electra block is larger than Deneb block ), } } diff --git a/beacon_node/lighthouse_network/src/types/pubsub.rs b/beacon_node/lighthouse_network/src/types/pubsub.rs index 13cd8d6d557..3d76dd28dc8 100644 --- a/beacon_node/lighthouse_network/src/types/pubsub.rs +++ b/beacon_node/lighthouse_network/src/types/pubsub.rs @@ -10,9 +10,9 @@ use types::{ Attestation, AttesterSlashing, BlobSidecar, EthSpec, ForkContext, ForkName, LightClientFinalityUpdate, LightClientOptimisticUpdate, ProposerSlashing, SignedAggregateAndProof, SignedBeaconBlock, SignedBeaconBlockAltair, SignedBeaconBlockBase, - SignedBeaconBlockCapella, SignedBeaconBlockDeneb, SignedBeaconBlockMerge, - SignedBlsToExecutionChange, SignedContributionAndProof, SignedVoluntaryExit, SubnetId, - SyncCommitteeMessage, SyncSubnetId, + SignedBeaconBlockCapella, SignedBeaconBlockDeneb, SignedBeaconBlockElectra, + SignedBeaconBlockMerge, SignedBlsToExecutionChange, SignedContributionAndProof, + SignedVoluntaryExit, SubnetId, SyncCommitteeMessage, SyncSubnetId, }; #[derive(Debug, Clone, PartialEq)] @@ -191,6 +191,10 @@ impl PubsubMessage { SignedBeaconBlockDeneb::from_ssz_bytes(data) .map_err(|e| format!("{:?}", e))?, ), + Some(ForkName::Electra) => SignedBeaconBlock::::Electra( + SignedBeaconBlockElectra::from_ssz_bytes(data) + .map_err(|e| format!("{:?}", e))?, + ), None => { return Err(format!( "Unknown gossipsub fork digest: {:?}", @@ -202,7 +206,7 @@ impl PubsubMessage { } GossipKind::BlobSidecar(blob_index) => { match fork_context.from_context_bytes(gossip_topic.fork_digest) { - Some(ForkName::Deneb) => { + Some(ForkName::Deneb | ForkName::Electra) => { let blob_sidecar = Arc::new( BlobSidecar::from_ssz_bytes(data) .map_err(|e| format!("{:?}", e))?, diff --git a/beacon_node/lighthouse_network/src/types/topics.rs b/beacon_node/lighthouse_network/src/types/topics.rs index cc329e828e5..a27fc8525f4 100644 --- a/beacon_node/lighthouse_network/src/types/topics.rs +++ b/beacon_node/lighthouse_network/src/types/topics.rs @@ -59,6 +59,7 @@ pub fn fork_core_topics(fork_name: &ForkName, spec: &ChainSpec) -> V deneb_topics.append(&mut deneb_blob_topics); deneb_topics } + ForkName::Electra => vec![], } } diff --git a/beacon_node/lighthouse_network/tests/common.rs b/beacon_node/lighthouse_network/tests/common.rs index cd8b73cc1c9..9ca7eeb2308 100644 --- a/beacon_node/lighthouse_network/tests/common.rs +++ b/beacon_node/lighthouse_network/tests/common.rs @@ -25,11 +25,13 @@ pub fn fork_context(fork_name: ForkName) -> ForkContext { let merge_fork_epoch = Epoch::new(2); let capella_fork_epoch = Epoch::new(3); let deneb_fork_epoch = Epoch::new(4); + let electra_fork_epoch = Epoch::new(5); chain_spec.altair_fork_epoch = Some(altair_fork_epoch); chain_spec.bellatrix_fork_epoch = Some(merge_fork_epoch); chain_spec.capella_fork_epoch = Some(capella_fork_epoch); chain_spec.deneb_fork_epoch = Some(deneb_fork_epoch); + chain_spec.electra_fork_epoch = Some(electra_fork_epoch); let current_slot = match fork_name { ForkName::Base => Slot::new(0), @@ -37,6 +39,7 @@ pub fn fork_context(fork_name: ForkName) -> ForkContext { ForkName::Merge => merge_fork_epoch.start_slot(E::slots_per_epoch()), ForkName::Capella => capella_fork_epoch.start_slot(E::slots_per_epoch()), ForkName::Deneb => deneb_fork_epoch.start_slot(E::slots_per_epoch()), + ForkName::Electra => electra_fork_epoch.start_slot(E::slots_per_epoch()), }; ForkContext::new::(current_slot, Hash256::zero(), &chain_spec) } diff --git a/beacon_node/network/src/network_beacon_processor/rpc_methods.rs b/beacon_node/network/src/network_beacon_processor/rpc_methods.rs index 34c72b324af..af5593de23d 100644 --- a/beacon_node/network/src/network_beacon_processor/rpc_methods.rs +++ b/beacon_node/network/src/network_beacon_processor/rpc_methods.rs @@ -350,7 +350,9 @@ impl NetworkBeaconProcessor { .epoch() .map_or(self.chain.spec.max_request_blocks, |epoch| { match self.chain.spec.fork_name_at_epoch(epoch) { - ForkName::Deneb => self.chain.spec.max_request_blocks_deneb, + ForkName::Deneb | ForkName::Electra => { + self.chain.spec.max_request_blocks_deneb + } ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => { self.chain.spec.max_request_blocks } diff --git a/beacon_node/network/src/sync/block_lookups/tests.rs b/beacon_node/network/src/sync/block_lookups/tests.rs index 414b4886fd7..2822cb7ba0b 100644 --- a/beacon_node/network/src/sync/block_lookups/tests.rs +++ b/beacon_node/network/src/sync/block_lookups/tests.rs @@ -237,7 +237,7 @@ fn test_single_block_lookup_happy_path() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -285,7 +285,7 @@ fn test_single_block_lookup_empty_response() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -313,7 +313,7 @@ fn test_single_block_lookup_wrong_response() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -351,7 +351,7 @@ fn test_single_block_lookup_failure() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -383,7 +383,7 @@ fn test_single_block_lookup_becomes_parent_request() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -413,7 +413,7 @@ fn test_single_block_lookup_becomes_parent_request() { rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } rig.expect_empty_network(); @@ -442,7 +442,7 @@ fn test_parent_lookup_happy_path() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } @@ -493,7 +493,7 @@ fn test_parent_lookup_wrong_response() { let id1 = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } @@ -559,7 +559,7 @@ fn test_parent_lookup_empty_response() { let id1 = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } @@ -614,7 +614,7 @@ fn test_parent_lookup_rpc_failure() { let id1 = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } @@ -676,7 +676,7 @@ fn test_parent_lookup_too_many_attempts() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) && i == 1 { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) && i == 1 { let _ = rig.expect_parent_request(ResponseType::Blob); } match i % 2 { @@ -755,7 +755,7 @@ fn test_parent_lookup_too_many_download_attempts_no_blacklist() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) && i == 1 { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) && i == 1 { let _ = rig.expect_parent_request(ResponseType::Blob); } if i % 2 != 0 { @@ -823,7 +823,7 @@ fn test_parent_lookup_too_many_processing_attempts_must_blacklist() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) && i == 0 { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) && i == 0 { let _ = rig.expect_parent_request(ResponseType::Blob); } // The request fails. It should be tried again. @@ -841,7 +841,7 @@ fn test_parent_lookup_too_many_processing_attempts_must_blacklist() { // Now fail processing a block in the parent request for i in 0..PROCESSING_FAILURES { let id = dbg!(rig.expect_parent_request(response_type)); - if matches!(fork_name, ForkName::Deneb) && i != 0 { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) && i != 0 { let _ = rig.expect_parent_request(ResponseType::Blob); } // If we're in deneb, a blob request should have been triggered as well, @@ -901,7 +901,7 @@ fn test_parent_lookup_too_deep() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } // the block @@ -969,7 +969,7 @@ fn test_single_block_lookup_ignored_response() { let id = rig.expect_lookup_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_lookup_request(ResponseType::Blob); } @@ -1024,7 +1024,7 @@ fn test_parent_lookup_ignored_response() { // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } @@ -1103,7 +1103,7 @@ fn test_same_chain_race_condition() { let id = rig.expect_parent_request(response_type); // If we're in deneb, a blob request should have been triggered as well, // we don't require a response because we're generateing 0-blob blocks in this test. - if matches!(fork_name, ForkName::Deneb) { + if matches!(fork_name, ForkName::Deneb | ForkName::Electra) { let _ = rig.expect_parent_request(ResponseType::Blob); } // the block diff --git a/beacon_node/network/src/sync/range_sync/range.rs b/beacon_node/network/src/sync/range_sync/range.rs index 6ce277e5d25..8fbc186a1b7 100644 --- a/beacon_node/network/src/sync/range_sync/range.rs +++ b/beacon_node/network/src/sync/range_sync/range.rs @@ -530,7 +530,7 @@ mod tests { panic!("Should have sent a batch request to the peer") }; let blob_req_id = match fork_name { - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { if let Ok(NetworkMessage::SendRequest { peer_id, request: _, diff --git a/beacon_node/store/src/impls/execution_payload.rs b/beacon_node/store/src/impls/execution_payload.rs index 6445dad3886..a874031ca27 100644 --- a/beacon_node/store/src/impls/execution_payload.rs +++ b/beacon_node/store/src/impls/execution_payload.rs @@ -2,7 +2,7 @@ use crate::{DBColumn, Error, StoreItem}; use ssz::{Decode, Encode}; use types::{ BlobSidecarList, EthSpec, ExecutionPayload, ExecutionPayloadCapella, ExecutionPayloadDeneb, - ExecutionPayloadMerge, + ExecutionPayloadElectra, ExecutionPayloadMerge, }; macro_rules! impl_store_item { @@ -25,6 +25,7 @@ macro_rules! impl_store_item { impl_store_item!(ExecutionPayloadMerge); impl_store_item!(ExecutionPayloadCapella); impl_store_item!(ExecutionPayloadDeneb); +impl_store_item!(ExecutionPayloadElectra); impl_store_item!(BlobSidecarList); /// This fork-agnostic implementation should be only used for writing. @@ -41,12 +42,18 @@ impl StoreItem for ExecutionPayload { } fn from_store_bytes(bytes: &[u8]) -> Result { - ExecutionPayloadDeneb::from_ssz_bytes(bytes) - .map(Self::Deneb) + ExecutionPayloadElectra::from_ssz_bytes(bytes) + .map(Self::Electra) .or_else(|_| { - ExecutionPayloadCapella::from_ssz_bytes(bytes) - .map(Self::Capella) - .or_else(|_| ExecutionPayloadMerge::from_ssz_bytes(bytes).map(Self::Merge)) + ExecutionPayloadDeneb::from_ssz_bytes(bytes) + .map(Self::Deneb) + .or_else(|_| { + ExecutionPayloadCapella::from_ssz_bytes(bytes) + .map(Self::Capella) + .or_else(|_| { + ExecutionPayloadMerge::from_ssz_bytes(bytes).map(Self::Merge) + }) + }) }) .map_err(Into::into) } diff --git a/beacon_node/store/src/partial_beacon_state.rs b/beacon_node/store/src/partial_beacon_state.rs index 62686bec6e5..c62d05fa46e 100644 --- a/beacon_node/store/src/partial_beacon_state.rs +++ b/beacon_node/store/src/partial_beacon_state.rs @@ -14,7 +14,7 @@ use types::*; /// /// Utilises lazy-loading from separate storage for its vector fields. #[superstruct( - variants(Base, Altair, Merge, Capella, Deneb), + variants(Base, Altair, Merge, Capella, Deneb, Electra), variant_attributes(derive(Debug, PartialEq, Clone, Encode, Decode)) )] #[derive(Debug, PartialEq, Clone, Encode)] @@ -66,9 +66,9 @@ where pub current_epoch_attestations: VariableList, T::MaxPendingAttestations>, // Participation (Altair and later) - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub previous_epoch_participation: VariableList, - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub current_epoch_participation: VariableList, // Finality @@ -78,13 +78,13 @@ where pub finalized_checkpoint: Checkpoint, // Inactivity - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub inactivity_scores: VariableList, // Light-client sync committees - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub current_sync_committee: Arc>, - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub next_sync_committee: Arc>, // Execution @@ -103,15 +103,20 @@ where partial_getter(rename = "latest_execution_payload_header_deneb") )] pub latest_execution_payload_header: ExecutionPayloadHeaderDeneb, + #[superstruct( + only(Electra), + partial_getter(rename = "latest_execution_payload_header_electra") + )] + pub latest_execution_payload_header: ExecutionPayloadHeaderElectra, // Capella - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub next_withdrawal_index: u64, - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub next_withdrawal_validator_index: u64, #[ssz(skip_serializing, skip_deserializing)] - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub historical_summaries: Option>, } @@ -243,6 +248,23 @@ impl PartialBeaconState { ], [historical_summaries] ), + BeaconState::Electra(s) => impl_from_state_forgetful!( + s, + outer, + Electra, + PartialBeaconStateElectra, + [ + previous_epoch_participation, + current_epoch_participation, + current_sync_committee, + next_sync_committee, + inactivity_scores, + latest_execution_payload_header, + next_withdrawal_index, + next_withdrawal_validator_index + ], + [historical_summaries] + ), } } @@ -488,6 +510,22 @@ impl TryInto> for PartialBeaconState { ], [historical_summaries] ), + PartialBeaconState::Electra(inner) => impl_try_into_beacon_state!( + inner, + Electra, + BeaconStateElectra, + [ + previous_epoch_participation, + current_epoch_participation, + current_sync_committee, + next_sync_committee, + inactivity_scores, + latest_execution_payload_header, + next_withdrawal_index, + next_withdrawal_validator_index + ], + [historical_summaries] + ), }; Ok(state) } diff --git a/common/eth2/src/types.rs b/common/eth2/src/types.rs index 4dee868e1d9..2830b2e45f3 100644 --- a/common/eth2/src/types.rs +++ b/common/eth2/src/types.rs @@ -1032,6 +1032,9 @@ impl ForkVersionDeserialize for SsePayloadAttributes { ForkName::Deneb => serde_json::from_value(value) .map(Self::V3) .map_err(serde::de::Error::custom), + ForkName::Electra => serde_json::from_value(value) + .map(Self::V3) + .map_err(serde::de::Error::custom), ForkName::Base | ForkName::Altair => Err(serde::de::Error::custom(format!( "SsePayloadAttributes deserialization for {fork_name} not implemented" ))), @@ -1599,7 +1602,7 @@ impl FullBlockContents { BeaconBlock::from_ssz_bytes_for_fork(bytes, fork_name) .map(|block| FullBlockContents::Block(block)) } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let mut builder = ssz::SszDecoderBuilder::new(bytes); builder.register_anonymous_variable_length_item()?; @@ -1660,7 +1663,7 @@ impl ForkVersionDeserialize for FullBlockContents { BeaconBlock::deserialize_by_fork::<'de, D>(value, fork_name)?, )) } - ForkName::Deneb => Ok(FullBlockContents::BlockContents( + ForkName::Deneb | ForkName::Electra => Ok(FullBlockContents::BlockContents( BlockContents::deserialize_by_fork::<'de, D>(value, fork_name)?, )), } @@ -1759,7 +1762,7 @@ impl PublishBlockRequest { SignedBeaconBlock::from_ssz_bytes_for_fork(bytes, fork_name) .map(|block| PublishBlockRequest::Block(Arc::new(block))) } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let mut builder = ssz::SszDecoderBuilder::new(bytes); builder.register_anonymous_variable_length_item()?; builder.register_type::>()?; @@ -1843,9 +1846,9 @@ impl TryFrom>> for PublishBlockRequest { | SignedBeaconBlock::Altair(_) | SignedBeaconBlock::Merge(_) | SignedBeaconBlock::Capella(_) => Ok(PublishBlockRequest::Block(block)), - SignedBeaconBlock::Deneb(_) => { - Err("deneb block contents cannot be fully constructed from just the signed block") - } + SignedBeaconBlock::Deneb(_) | SignedBeaconBlock::Electra(_) => Err( + "post-Deneb block contents cannot be fully constructed from just the signed block", + ), } } } @@ -1953,7 +1956,7 @@ impl ForkVersionDeserialize for FullPayloadContents { ForkName::Merge | ForkName::Capella => serde_json::from_value(value) .map(Self::Payload) .map_err(serde::de::Error::custom), - ForkName::Deneb => serde_json::from_value(value) + ForkName::Deneb | ForkName::Electra => serde_json::from_value(value) .map(Self::PayloadAndBlobs) .map_err(serde::de::Error::custom), ForkName::Base | ForkName::Altair => Err(serde::de::Error::custom(format!( diff --git a/common/eth2_network_config/built_in_network_configs/chiado/config.yaml b/common/eth2_network_config/built_in_network_configs/chiado/config.yaml index 8064ea55563..c869d9cfc83 100644 --- a/common/eth2_network_config/built_in_network_configs/chiado/config.yaml +++ b/common/eth2_network_config/built_in_network_configs/chiado/config.yaml @@ -46,7 +46,9 @@ CAPELLA_FORK_EPOCH: 244224 # Wed May 24 2023 13:12:00 GMT+0000 # Deneb DENEB_FORK_VERSION: 0x0400006f DENEB_FORK_EPOCH: 516608 # Wed Jan 31 2024 18:15:40 GMT+0000 - +# Electra +ELECTRA_FORK_VERSION: 0x0500006f +ELECTRA_FORK_EPOCH: 18446744073709551615 # Time parameters # --------------------------------------------------------------- diff --git a/common/eth2_network_config/built_in_network_configs/gnosis/config.yaml b/common/eth2_network_config/built_in_network_configs/gnosis/config.yaml index 2311d6db0f9..7558b482506 100644 --- a/common/eth2_network_config/built_in_network_configs/gnosis/config.yaml +++ b/common/eth2_network_config/built_in_network_configs/gnosis/config.yaml @@ -42,12 +42,9 @@ CAPELLA_FORK_EPOCH: 648704 # Deneb DENEB_FORK_VERSION: 0x04000064 DENEB_FORK_EPOCH: 889856 # 2024-03-11T18:30:20.000Z -# Sharding -SHARDING_FORK_VERSION: 0x03000064 -SHARDING_FORK_EPOCH: 18446744073709551615 - -# TBD, 2**32 is a placeholder. Merge transition approach is in active R&D. -TRANSITION_TOTAL_DIFFICULTY: 4294967296 +# Electra +ELECTRA_FORK_VERSION: 0x05000064 +ELECTRA_FORK_EPOCH: 18446744073709551615 # Time parameters diff --git a/common/eth2_network_config/built_in_network_configs/holesky/config.yaml b/common/eth2_network_config/built_in_network_configs/holesky/config.yaml index 1104791ed5b..947924a7d16 100644 --- a/common/eth2_network_config/built_in_network_configs/holesky/config.yaml +++ b/common/eth2_network_config/built_in_network_configs/holesky/config.yaml @@ -28,14 +28,15 @@ BELLATRIX_FORK_EPOCH: 0 TERMINAL_TOTAL_DIFFICULTY: 0 TERMINAL_BLOCK_HASH: 0x0000000000000000000000000000000000000000000000000000000000000000 TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH: 18446744073709551615 - # Capella CAPELLA_FORK_VERSION: 0x04017000 CAPELLA_FORK_EPOCH: 256 - # Deneb DENEB_FORK_VERSION: 0x05017000 DENEB_FORK_EPOCH: 29696 +# Electra +ELECTRA_FORK_VERSION: 0x06017000 +ELECTRA_FORK_EPOCH: 18446744073709551615 # Time parameters # --------------------------------------------------------------- diff --git a/common/eth2_network_config/built_in_network_configs/mainnet/config.yaml b/common/eth2_network_config/built_in_network_configs/mainnet/config.yaml index b29ecfc6d38..c8695123ab0 100644 --- a/common/eth2_network_config/built_in_network_configs/mainnet/config.yaml +++ b/common/eth2_network_config/built_in_network_configs/mainnet/config.yaml @@ -50,6 +50,9 @@ CAPELLA_FORK_EPOCH: 194048 # April 12, 2023, 10:27:35pm UTC # Deneb DENEB_FORK_VERSION: 0x04000000 DENEB_FORK_EPOCH: 269568 # March 13, 2024, 01:55:35pm UTC +# Electra +ELECTRA_FORK_VERSION: 0x05000000 +ELECTRA_FORK_EPOCH: 18446744073709551615 # Time parameters diff --git a/consensus/fork_choice/src/fork_choice.rs b/consensus/fork_choice/src/fork_choice.rs index 625dc245f49..0177b4089e5 100644 --- a/consensus/fork_choice/src/fork_choice.rs +++ b/consensus/fork_choice/src/fork_choice.rs @@ -764,7 +764,8 @@ where (parent_justified, parent_finalized) } else { let justification_and_finalization_state = match block { - BeaconBlockRef::Deneb(_) + BeaconBlockRef::Electra(_) + | BeaconBlockRef::Deneb(_) | BeaconBlockRef::Capella(_) | BeaconBlockRef::Merge(_) | BeaconBlockRef::Altair(_) => match progressive_balances_mode { diff --git a/consensus/fork_choice/tests/tests.rs b/consensus/fork_choice/tests/tests.rs index 649fbcc5559..2f82605df06 100644 --- a/consensus/fork_choice/tests/tests.rs +++ b/consensus/fork_choice/tests/tests.rs @@ -1385,12 +1385,12 @@ async fn progressive_balances_cache_proposer_slashing() { .await .unwrap() // Note: This test may fail if the shuffling used changes, right now it re-runs with - // deterministic shuffling. A shuffling change my cause the slashed proposer to propose + // deterministic shuffling. A shuffling change may cause the slashed proposer to propose // again in the next epoch, which results in a block processing failure // (`HeaderInvalid::ProposerSlashed`). The harness should be re-worked to successfully skip // the slot in this scenario rather than panic-ing. The same applies to // `progressive_balances_cache_attester_slashing`. - .apply_blocks(1) + .apply_blocks(2) .await .add_previous_epoch_proposer_slashing(MainnetEthSpec::slots_per_epoch()) .await diff --git a/consensus/state_processing/src/common/get_attestation_participation.rs b/consensus/state_processing/src/common/get_attestation_participation.rs index e4e30230af5..c8b5dd96ed5 100644 --- a/consensus/state_processing/src/common/get_attestation_participation.rs +++ b/consensus/state_processing/src/common/get_attestation_participation.rs @@ -53,7 +53,7 @@ pub fn get_attestation_participation_flag_indices( participation_flag_indices.push(TIMELY_TARGET_FLAG_INDEX); } } - &BeaconState::Deneb(_) => { + &BeaconState::Deneb(_) | &BeaconState::Electra(_) => { if is_matching_target { // [Modified in Deneb:EIP7045] participation_flag_indices.push(TIMELY_TARGET_FLAG_INDEX); diff --git a/consensus/state_processing/src/common/slash_validator.rs b/consensus/state_processing/src/common/slash_validator.rs index d8b1c1a1076..a65e2a88430 100644 --- a/consensus/state_processing/src/common/slash_validator.rs +++ b/consensus/state_processing/src/common/slash_validator.rs @@ -56,7 +56,8 @@ pub fn slash_validator( BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => whistleblower_reward + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => whistleblower_reward .safe_mul(PROPOSER_WEIGHT)? .safe_div(WEIGHT_DENOMINATOR)?, }; diff --git a/consensus/state_processing/src/genesis.rs b/consensus/state_processing/src/genesis.rs index 5f71e33371b..9bd6d04775a 100644 --- a/consensus/state_processing/src/genesis.rs +++ b/consensus/state_processing/src/genesis.rs @@ -4,6 +4,7 @@ use super::per_block_processing::{ use crate::common::DepositDataTree; use crate::upgrade::{ upgrade_to_altair, upgrade_to_bellatrix, upgrade_to_capella, upgrade_to_deneb, + upgrade_to_electra, }; use safe_arith::{ArithError, SafeArith}; use tree_hash::TreeHash; @@ -104,8 +105,25 @@ pub fn initialize_beacon_state_from_eth1( // Override latest execution payload header. // See https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/beacon-chain.md#testing - if let Some(ExecutionPayloadHeader::Deneb(header)) = execution_payload_header { - *state.latest_execution_payload_header_deneb_mut()? = header; + if let Some(ExecutionPayloadHeader::Deneb(ref header)) = execution_payload_header { + *state.latest_execution_payload_header_deneb_mut()? = header.clone(); + } + } + + // Upgrade to electra if configured from genesis. + if spec + .electra_fork_epoch + .map_or(false, |fork_epoch| fork_epoch == T::genesis_epoch()) + { + upgrade_to_electra(&mut state, spec)?; + + // Remove intermediate Deneb fork from `state.fork`. + state.fork_mut().previous_version = spec.electra_fork_version; + + // Override latest execution payload header. + // See https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/beacon-chain.md#testing + if let Some(ExecutionPayloadHeader::Electra(header)) = execution_payload_header { + *state.latest_execution_payload_header_electra_mut()? = header.clone(); } } diff --git a/consensus/state_processing/src/per_block_processing.rs b/consensus/state_processing/src/per_block_processing.rs index b9a147a5ad5..c9a96dc766a 100644 --- a/consensus/state_processing/src/per_block_processing.rs +++ b/consensus/state_processing/src/per_block_processing.rs @@ -433,6 +433,12 @@ pub fn process_execution_payload>( _ => return Err(BlockProcessingError::IncorrectStateType), } } + ExecutionPayloadHeaderRefMut::Electra(header_mut) => { + match payload.to_execution_payload_header() { + ExecutionPayloadHeader::Electra(header) => *header_mut = header, + _ => return Err(BlockProcessingError::IncorrectStateType), + } + } } Ok(()) @@ -451,7 +457,7 @@ pub fn is_merge_transition_complete(state: &BeaconState) -> bool .latest_execution_payload_header() .map(|header| !header.is_default_with_zero_roots()) .unwrap_or(false), - BeaconState::Deneb(_) | BeaconState::Capella(_) => true, + BeaconState::Electra(_) | BeaconState::Deneb(_) | BeaconState::Capella(_) => true, BeaconState::Base(_) | BeaconState::Altair(_) => false, } } @@ -549,7 +555,7 @@ pub fn process_withdrawals>( ) -> Result<(), BlockProcessingError> { match state { BeaconState::Merge(_) => Ok(()), - BeaconState::Capella(_) | BeaconState::Deneb(_) => { + BeaconState::Capella(_) | BeaconState::Deneb(_) | BeaconState::Electra(_) => { let expected_withdrawals = get_expected_withdrawals(state, spec)?; let expected_root = expected_withdrawals.tree_hash_root(); let withdrawals_root = payload.withdrawals_root()?; diff --git a/consensus/state_processing/src/per_block_processing/process_operations.rs b/consensus/state_processing/src/per_block_processing/process_operations.rs index 33e30bfb2fa..9ae1f00c3cb 100644 --- a/consensus/state_processing/src/per_block_processing/process_operations.rs +++ b/consensus/state_processing/src/per_block_processing/process_operations.rs @@ -265,7 +265,8 @@ pub fn process_attestations>( BeaconBlockBodyRef::Altair(_) | BeaconBlockBodyRef::Merge(_) | BeaconBlockBodyRef::Capella(_) - | BeaconBlockBodyRef::Deneb(_) => { + | BeaconBlockBodyRef::Deneb(_) + | BeaconBlockBodyRef::Electra(_) => { altair_deneb::process_attestations( state, block_body.attestations(), diff --git a/consensus/state_processing/src/per_block_processing/signature_sets.rs b/consensus/state_processing/src/per_block_processing/signature_sets.rs index fcd324e9eb1..2fe5a14802d 100644 --- a/consensus/state_processing/src/per_block_processing/signature_sets.rs +++ b/consensus/state_processing/src/per_block_processing/signature_sets.rs @@ -398,7 +398,7 @@ where state.genesis_validators_root(), ), // EIP-7044 - BeaconState::Deneb(_) => spec.compute_domain( + BeaconState::Deneb(_) | BeaconState::Electra(_) => spec.compute_domain( Domain::VoluntaryExit, spec.capella_fork_version, state.genesis_validators_root(), diff --git a/consensus/state_processing/src/per_block_processing/verify_attestation.rs b/consensus/state_processing/src/per_block_processing/verify_attestation.rs index b7aa4643e48..7527ac1bb8c 100644 --- a/consensus/state_processing/src/per_block_processing/verify_attestation.rs +++ b/consensus/state_processing/src/per_block_processing/verify_attestation.rs @@ -46,7 +46,7 @@ pub fn verify_attestation_for_block_inclusion<'ctxt, T: EthSpec>( ); } // [Modified in Deneb:EIP7045] - BeaconState::Deneb(_) => {} + BeaconState::Deneb(_) | BeaconState::Electra(_) => {} } verify_attestation_for_state(state, attestation, ctxt, verify_signatures, spec) diff --git a/consensus/state_processing/src/per_epoch_processing.rs b/consensus/state_processing/src/per_epoch_processing.rs index d5d06037cd8..2f6416132c4 100644 --- a/consensus/state_processing/src/per_epoch_processing.rs +++ b/consensus/state_processing/src/per_epoch_processing.rs @@ -40,7 +40,9 @@ pub fn process_epoch( match state { BeaconState::Base(_) => base::process_epoch(state, spec), BeaconState::Altair(_) | BeaconState::Merge(_) => altair::process_epoch(state, spec), - BeaconState::Capella(_) | BeaconState::Deneb(_) => capella::process_epoch(state, spec), + BeaconState::Capella(_) | BeaconState::Deneb(_) | BeaconState::Electra(_) => { + capella::process_epoch(state, spec) + } } } diff --git a/consensus/state_processing/src/per_slot_processing.rs b/consensus/state_processing/src/per_slot_processing.rs index e89a78c4d84..63cfc5b9c67 100644 --- a/consensus/state_processing/src/per_slot_processing.rs +++ b/consensus/state_processing/src/per_slot_processing.rs @@ -1,5 +1,6 @@ use crate::upgrade::{ upgrade_to_altair, upgrade_to_bellatrix, upgrade_to_capella, upgrade_to_deneb, + upgrade_to_electra, }; use crate::{per_epoch_processing::EpochProcessingSummary, *}; use safe_arith::{ArithError, SafeArith}; @@ -61,10 +62,14 @@ pub fn per_slot_processing( if spec.capella_fork_epoch == Some(state.current_epoch()) { upgrade_to_capella(state, spec)?; } - // Deneb + // Deneb. if spec.deneb_fork_epoch == Some(state.current_epoch()) { upgrade_to_deneb(state, spec)?; } + // Electra. + if spec.electra_fork_epoch == Some(state.current_epoch()) { + upgrade_to_electra(state, spec)?; + } } Ok(summary) diff --git a/consensus/state_processing/src/upgrade.rs b/consensus/state_processing/src/upgrade.rs index 1509ee0e50f..98602c66ba3 100644 --- a/consensus/state_processing/src/upgrade.rs +++ b/consensus/state_processing/src/upgrade.rs @@ -1,9 +1,11 @@ pub mod altair; pub mod capella; pub mod deneb; +pub mod electra; pub mod merge; pub use altair::upgrade_to_altair; pub use capella::upgrade_to_capella; pub use deneb::upgrade_to_deneb; +pub use electra::upgrade_to_electra; pub use merge::upgrade_to_bellatrix; diff --git a/consensus/state_processing/src/upgrade/electra.rs b/consensus/state_processing/src/upgrade/electra.rs new file mode 100644 index 00000000000..8d5a8dc2a56 --- /dev/null +++ b/consensus/state_processing/src/upgrade/electra.rs @@ -0,0 +1,74 @@ +use std::mem; +use types::{BeaconState, BeaconStateElectra, BeaconStateError as Error, ChainSpec, EthSpec, Fork}; + +/// Transform a `Deneb` state into an `Electra` state. +pub fn upgrade_to_electra( + pre_state: &mut BeaconState, + spec: &ChainSpec, +) -> Result<(), Error> { + let epoch = pre_state.current_epoch(); + let pre = pre_state.as_deneb_mut()?; + + // Where possible, use something like `mem::take` to move fields from behind the &mut + // reference. For other fields that don't have a good default value, use `clone`. + // + // Fixed size vectors get cloned because replacing them would require the same size + // allocation as cloning. + let post = BeaconState::Electra(BeaconStateElectra { + // 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: spec.electra_fork_version, + epoch, + }, + // History + latest_block_header: pre.latest_block_header.clone(), + block_roots: pre.block_roots.clone(), + state_roots: pre.state_roots.clone(), + historical_roots: mem::take(&mut pre.historical_roots), + // Eth1 + eth1_data: pre.eth1_data.clone(), + eth1_data_votes: mem::take(&mut pre.eth1_data_votes), + eth1_deposit_index: pre.eth1_deposit_index, + // Registry + validators: mem::take(&mut pre.validators), + balances: mem::take(&mut pre.balances), + // Randomness + randao_mixes: pre.randao_mixes.clone(), + // Slashings + slashings: pre.slashings.clone(), + // `Participation + previous_epoch_participation: mem::take(&mut pre.previous_epoch_participation), + current_epoch_participation: mem::take(&mut pre.current_epoch_participation), + // Finality + justification_bits: pre.justification_bits.clone(), + previous_justified_checkpoint: pre.previous_justified_checkpoint, + current_justified_checkpoint: pre.current_justified_checkpoint, + finalized_checkpoint: pre.finalized_checkpoint, + // Inactivity + inactivity_scores: mem::take(&mut pre.inactivity_scores), + // Sync committees + current_sync_committee: pre.current_sync_committee.clone(), + next_sync_committee: pre.next_sync_committee.clone(), + // Execution + latest_execution_payload_header: pre.latest_execution_payload_header.upgrade_to_electra(), + // Capella + next_withdrawal_index: pre.next_withdrawal_index, + next_withdrawal_validator_index: pre.next_withdrawal_validator_index, + historical_summaries: pre.historical_summaries.clone(), + // Caches + total_active_balance: pre.total_active_balance, + progressive_balances_cache: mem::take(&mut pre.progressive_balances_cache), + committee_caches: mem::take(&mut pre.committee_caches), + pubkey_cache: mem::take(&mut pre.pubkey_cache), + exit_cache: mem::take(&mut pre.exit_cache), + tree_hash_cache: mem::take(&mut pre.tree_hash_cache), + }); + + *pre_state = post; + + Ok(()) +} diff --git a/consensus/types/presets/gnosis/electra.yaml b/consensus/types/presets/gnosis/electra.yaml new file mode 100644 index 00000000000..cafdcbbf8d3 --- /dev/null +++ b/consensus/types/presets/gnosis/electra.yaml @@ -0,0 +1,3 @@ +# Gnosis preset - Electra + +ELECTRA_PLACEHOLDER: 0 diff --git a/consensus/types/presets/mainnet/electra.yaml b/consensus/types/presets/mainnet/electra.yaml new file mode 100644 index 00000000000..64d8b97b631 --- /dev/null +++ b/consensus/types/presets/mainnet/electra.yaml @@ -0,0 +1,3 @@ +# Mainnet preset - Electra + +ELECTRA_PLACEHOLDER: 0 diff --git a/consensus/types/presets/minimal/electra.yaml b/consensus/types/presets/minimal/electra.yaml new file mode 100644 index 00000000000..3baa7fa8161 --- /dev/null +++ b/consensus/types/presets/minimal/electra.yaml @@ -0,0 +1,3 @@ +# Minimal preset - Electra + +ELECTRA_PLACEHOLDER: 0 diff --git a/consensus/types/src/beacon_block.rs b/consensus/types/src/beacon_block.rs index 5853f4d0829..f61f76d979a 100644 --- a/consensus/types/src/beacon_block.rs +++ b/consensus/types/src/beacon_block.rs @@ -12,7 +12,7 @@ use tree_hash_derive::TreeHash; /// A block of the `BeaconChain`. #[superstruct( - variants(Base, Altair, Merge, Capella, Deneb), + variants(Base, Altair, Merge, Capella, Deneb, Electra), variant_attributes( derive( Debug, @@ -69,6 +69,8 @@ pub struct BeaconBlock = FullPayload pub body: BeaconBlockBodyCapella, #[superstruct(only(Deneb), partial_getter(rename = "body_deneb"))] pub body: BeaconBlockBodyDeneb, + #[superstruct(only(Electra), partial_getter(rename = "body_electra"))] + pub body: BeaconBlockBodyElectra, } pub type BlindedBeaconBlock = BeaconBlock>; @@ -124,8 +126,9 @@ impl> BeaconBlock { /// Usually it's better to prefer `from_ssz_bytes` which will decode the correct variant based /// on the fork slot. pub fn any_from_ssz_bytes(bytes: &[u8]) -> Result { - BeaconBlockDeneb::from_ssz_bytes(bytes) - .map(BeaconBlock::Deneb) + BeaconBlockElectra::from_ssz_bytes(bytes) + .map(BeaconBlock::Electra) + .or_else(|_| BeaconBlockDeneb::from_ssz_bytes(bytes).map(BeaconBlock::Deneb)) .or_else(|_| BeaconBlockCapella::from_ssz_bytes(bytes).map(BeaconBlock::Capella)) .or_else(|_| BeaconBlockMerge::from_ssz_bytes(bytes).map(BeaconBlock::Merge)) .or_else(|_| BeaconBlockAltair::from_ssz_bytes(bytes).map(BeaconBlock::Altair)) @@ -221,6 +224,7 @@ impl<'a, T: EthSpec, Payload: AbstractExecPayload> BeaconBlockRef<'a, T, Payl BeaconBlockRef::Merge { .. } => ForkName::Merge, BeaconBlockRef::Capella { .. } => ForkName::Capella, BeaconBlockRef::Deneb { .. } => ForkName::Deneb, + BeaconBlockRef::Electra { .. } => ForkName::Electra, } } @@ -595,6 +599,83 @@ impl> EmptyBlock for BeaconBlockDene } } +impl> BeaconBlockElectra { + /// Return a Electra block where the block has maximum size. + pub fn full(spec: &ChainSpec) -> Self { + let base_block: BeaconBlockBase<_, Payload> = BeaconBlockBase::full(spec); + let bls_to_execution_changes = vec![ + SignedBlsToExecutionChange { + message: BlsToExecutionChange { + validator_index: 0, + from_bls_pubkey: PublicKeyBytes::empty(), + to_execution_address: Address::zero(), + }, + signature: Signature::empty() + }; + T::max_bls_to_execution_changes() + ] + .into(); + let sync_aggregate = SyncAggregate { + sync_committee_signature: AggregateSignature::empty(), + sync_committee_bits: BitVector::default(), + }; + BeaconBlockElectra { + slot: spec.genesis_slot, + proposer_index: 0, + parent_root: Hash256::zero(), + state_root: Hash256::zero(), + body: BeaconBlockBodyElectra { + proposer_slashings: base_block.body.proposer_slashings, + attester_slashings: base_block.body.attester_slashings, + attestations: base_block.body.attestations, + deposits: base_block.body.deposits, + voluntary_exits: base_block.body.voluntary_exits, + bls_to_execution_changes, + sync_aggregate, + randao_reveal: Signature::empty(), + eth1_data: Eth1Data { + deposit_root: Hash256::zero(), + block_hash: Hash256::zero(), + deposit_count: 0, + }, + graffiti: Graffiti::default(), + execution_payload: Payload::Electra::default(), + blob_kzg_commitments: VariableList::empty(), + }, + } + } +} + +impl> EmptyBlock for BeaconBlockElectra { + /// Returns an empty Electra block to be used during genesis. + fn empty(spec: &ChainSpec) -> Self { + BeaconBlockElectra { + slot: spec.genesis_slot, + proposer_index: 0, + parent_root: Hash256::zero(), + state_root: Hash256::zero(), + body: BeaconBlockBodyElectra { + randao_reveal: Signature::empty(), + eth1_data: Eth1Data { + deposit_root: Hash256::zero(), + block_hash: Hash256::zero(), + deposit_count: 0, + }, + graffiti: Graffiti::default(), + proposer_slashings: VariableList::empty(), + attester_slashings: VariableList::empty(), + attestations: VariableList::empty(), + deposits: VariableList::empty(), + voluntary_exits: VariableList::empty(), + sync_aggregate: SyncAggregate::empty(), + execution_payload: Payload::Electra::default(), + bls_to_execution_changes: VariableList::empty(), + blob_kzg_commitments: VariableList::empty(), + }, + } + } +} + // We can convert pre-Bellatrix blocks without payloads into blocks "with" payloads. impl From>> for BeaconBlockBase> @@ -675,6 +756,7 @@ impl_from!(BeaconBlockAltair, >, >, |body impl_from!(BeaconBlockMerge, >, >, |body: BeaconBlockBodyMerge<_, _>| body.into()); impl_from!(BeaconBlockCapella, >, >, |body: BeaconBlockBodyCapella<_, _>| body.into()); impl_from!(BeaconBlockDeneb, >, >, |body: BeaconBlockBodyDeneb<_, _>| body.into()); +impl_from!(BeaconBlockElectra, >, >, |body: BeaconBlockBodyElectra<_, _>| body.into()); // We can clone blocks with payloads to blocks without payloads, without cloning the payload. macro_rules! impl_clone_as_blinded { @@ -707,6 +789,7 @@ impl_clone_as_blinded!(BeaconBlockAltair, >, >, >); impl_clone_as_blinded!(BeaconBlockCapella, >, >); impl_clone_as_blinded!(BeaconBlockDeneb, >, >); +impl_clone_as_blinded!(BeaconBlockElectra, >, >); // A reference to a full beacon block can be cloned into a blinded beacon block, without cloning the // execution payload. @@ -822,7 +905,7 @@ mod tests { } #[test] - fn roundtrip_4844_block() { + fn roundtrip_deneb_block() { let rng = &mut XorShiftRng::from_seed([42; 16]); let spec = &ForkName::Deneb.make_genesis_spec(MainnetEthSpec::default_spec()); @@ -840,6 +923,26 @@ mod tests { }); } + #[test] + fn roundtrip_electra_block() { + let rng = &mut XorShiftRng::from_seed([42; 16]); + let spec = &ForkName::Electra.make_genesis_spec(MainnetEthSpec::default_spec()); + + let inner_block = BeaconBlockElectra { + slot: Slot::random_for_test(rng), + proposer_index: u64::random_for_test(rng), + parent_root: Hash256::random_for_test(rng), + state_root: Hash256::random_for_test(rng), + body: BeaconBlockBodyElectra::random_for_test(rng), + }; + + let block = BeaconBlock::Electra(inner_block.clone()); + + test_ssz_tree_hash_pair_with(&block, &inner_block, |bytes| { + BeaconBlock::from_ssz_bytes(bytes, spec) + }); + } + #[test] fn decode_base_and_altair() { type E = MainnetEthSpec; @@ -857,10 +960,13 @@ mod tests { let capella_slot = capella_epoch.start_slot(E::slots_per_epoch()); let deneb_epoch = capella_epoch + 1; let deneb_slot = deneb_epoch.start_slot(E::slots_per_epoch()); + let electra_epoch = deneb_epoch + 1; + let electra_slot = electra_epoch.start_slot(E::slots_per_epoch()); spec.altair_fork_epoch = Some(altair_epoch); spec.capella_fork_epoch = Some(capella_epoch); spec.deneb_fork_epoch = Some(deneb_epoch); + spec.electra_fork_epoch = Some(electra_epoch); // BeaconBlockBase { @@ -934,7 +1040,7 @@ mod tests { slot: deneb_slot, ..<_>::random_for_test(rng) }); - // It's invalid to have an Capella block with a epoch lower than the fork epoch. + // It's invalid to have a Deneb block with a epoch lower than the fork epoch. let bad_block = { let mut bad = good_block.clone(); *bad.slot_mut() = capella_slot; @@ -949,5 +1055,28 @@ mod tests { BeaconBlock::from_ssz_bytes(&bad_block.as_ssz_bytes(), &spec) .expect_err("bad deneb block cannot be decoded"); } + + // BeaconBlockElectra + { + let good_block = BeaconBlock::Electra(BeaconBlockElectra { + slot: electra_slot, + ..<_>::random_for_test(rng) + }); + // It's invalid to have an Electra block with a epoch lower than the fork epoch. + let bad_block = { + let mut bad = good_block.clone(); + *bad.slot_mut() = deneb_slot; + bad + }; + + assert_eq!( + BeaconBlock::from_ssz_bytes(&good_block.as_ssz_bytes(), &spec) + .expect("good electra block can be decoded"), + good_block + ); + // TODO(electra): once the Electra block is changed from Deneb, update this to match + // the other forks. + assert!(BeaconBlock::from_ssz_bytes(&bad_block.as_ssz_bytes(), &spec).is_ok()); + } } } diff --git a/consensus/types/src/beacon_block_body.rs b/consensus/types/src/beacon_block_body.rs index 976d51a5c90..6672aa869c7 100644 --- a/consensus/types/src/beacon_block_body.rs +++ b/consensus/types/src/beacon_block_body.rs @@ -29,7 +29,7 @@ pub const BLOB_KZG_COMMITMENTS_INDEX: usize = 11; /// /// This *superstruct* abstracts over the hard-fork. #[superstruct( - variants(Base, Altair, Merge, Capella, Deneb), + variants(Base, Altair, Merge, Capella, Deneb, Electra), variant_attributes( derive( Debug, @@ -67,7 +67,7 @@ pub struct BeaconBlockBody = FullPay pub attestations: VariableList, T::MaxAttestations>, pub deposits: VariableList, pub voluntary_exits: VariableList, - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub sync_aggregate: SyncAggregate, // We flatten the execution payload so that serde can use the name of the inner type, // either `execution_payload` for full payloads, or `execution_payload_header` for blinded @@ -81,10 +81,13 @@ pub struct BeaconBlockBody = FullPay #[superstruct(only(Deneb), partial_getter(rename = "execution_payload_deneb"))] #[serde(flatten)] pub execution_payload: Payload::Deneb, - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Electra), partial_getter(rename = "execution_payload_electra"))] + #[serde(flatten)] + pub execution_payload: Payload::Electra, + #[superstruct(only(Capella, Deneb, Electra))] pub bls_to_execution_changes: VariableList, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] pub blob_kzg_commitments: KzgCommitments, #[superstruct(only(Base, Altair))] #[ssz(skip_serializing, skip_deserializing)] @@ -107,6 +110,7 @@ impl<'a, T: EthSpec, Payload: AbstractExecPayload> BeaconBlockBodyRef<'a, T, Self::Merge(body) => Ok(Payload::Ref::from(&body.execution_payload)), Self::Capella(body) => Ok(Payload::Ref::from(&body.execution_payload)), Self::Deneb(body) => Ok(Payload::Ref::from(&body.execution_payload)), + Self::Electra(body) => Ok(Payload::Ref::from(&body.execution_payload)), } } @@ -177,6 +181,67 @@ impl<'a, T: EthSpec, Payload: AbstractExecPayload> BeaconBlockBodyRef<'a, T, // Join the proofs for the subtree and the main tree proof.append(&mut proof_body); + debug_assert_eq!(proof.len(), T::kzg_proof_inclusion_proof_depth()); + Ok(proof.into()) + } + // TODO(electra): De-duplicate proof computation. + Self::Electra(body) => { + // We compute the branches by generating 2 merkle trees: + // 1. Merkle tree for the `blob_kzg_commitments` List object + // 2. Merkle tree for the `BeaconBlockBody` container + // We then merge the branches for both the trees all the way up to the root. + + // Part1 (Branches for the subtree rooted at `blob_kzg_commitments`) + // + // Branches for `blob_kzg_commitments` without length mix-in + let depth = T::max_blob_commitments_per_block() + .next_power_of_two() + .ilog2(); + let leaves: Vec<_> = body + .blob_kzg_commitments + .iter() + .map(|commitment| commitment.tree_hash_root()) + .collect(); + let tree = MerkleTree::create(&leaves, depth as usize); + let (_, mut proof) = tree + .generate_proof(index, depth as usize) + .map_err(Error::MerkleTreeError)?; + + // Add the branch corresponding to the length mix-in. + let length = body.blob_kzg_commitments.len(); + let usize_len = std::mem::size_of::(); + let mut length_bytes = [0; BYTES_PER_CHUNK]; + length_bytes + .get_mut(0..usize_len) + .ok_or(Error::MerkleTreeError(MerkleTreeError::PleaseNotifyTheDevs))? + .copy_from_slice(&length.to_le_bytes()); + let length_root = Hash256::from_slice(length_bytes.as_slice()); + proof.push(length_root); + + // Part 2 + // Branches for `BeaconBlockBody` container + let leaves = [ + body.randao_reveal.tree_hash_root(), + body.eth1_data.tree_hash_root(), + body.graffiti.tree_hash_root(), + body.proposer_slashings.tree_hash_root(), + body.attester_slashings.tree_hash_root(), + body.attestations.tree_hash_root(), + body.deposits.tree_hash_root(), + body.voluntary_exits.tree_hash_root(), + body.sync_aggregate.tree_hash_root(), + body.execution_payload.tree_hash_root(), + body.bls_to_execution_changes.tree_hash_root(), + body.blob_kzg_commitments.tree_hash_root(), + ]; + let beacon_block_body_depth = leaves.len().next_power_of_two().ilog2() as usize; + let tree = MerkleTree::create(&leaves, beacon_block_body_depth); + let (_, mut proof_body) = tree + .generate_proof(BLOB_KZG_COMMITMENTS_INDEX, beacon_block_body_depth) + .map_err(Error::MerkleTreeError)?; + // Join the proofs for the subtree and the main tree + proof.append(&mut proof_body); + debug_assert_eq!(proof.len(), T::kzg_proof_inclusion_proof_depth()); Ok(proof.into()) } @@ -199,6 +264,7 @@ impl<'a, T: EthSpec, Payload: AbstractExecPayload> BeaconBlockBodyRef<'a, T, BeaconBlockBodyRef::Merge { .. } => ForkName::Merge, BeaconBlockBodyRef::Capella { .. } => ForkName::Capella, BeaconBlockBodyRef::Deneb { .. } => ForkName::Deneb, + BeaconBlockBodyRef::Electra { .. } => ForkName::Electra, } } } @@ -467,6 +533,50 @@ impl From>> } } +impl From>> + for ( + BeaconBlockBodyElectra>, + Option>, + ) +{ + fn from(body: BeaconBlockBodyElectra>) -> Self { + let BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings, + attester_slashings, + attestations, + deposits, + voluntary_exits, + sync_aggregate, + execution_payload: FullPayloadElectra { execution_payload }, + bls_to_execution_changes, + blob_kzg_commitments, + } = body; + + ( + BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings, + attester_slashings, + attestations, + deposits, + voluntary_exits, + sync_aggregate, + execution_payload: BlindedPayloadElectra { + execution_payload_header: From::from(&execution_payload), + }, + bls_to_execution_changes, + blob_kzg_commitments: blob_kzg_commitments.clone(), + }, + Some(execution_payload), + ) + } +} + // We can clone a full block into a blinded block, without cloning the payload. impl BeaconBlockBodyBase> { pub fn clone_as_blinded(&self) -> BeaconBlockBodyBase> { @@ -584,6 +694,42 @@ impl BeaconBlockBodyDeneb> { } } +impl BeaconBlockBodyElectra> { + pub fn clone_as_blinded(&self) -> BeaconBlockBodyElectra> { + let BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings, + attester_slashings, + attestations, + deposits, + voluntary_exits, + sync_aggregate, + execution_payload: FullPayloadElectra { execution_payload }, + bls_to_execution_changes, + blob_kzg_commitments, + } = self; + + BeaconBlockBodyElectra { + randao_reveal: randao_reveal.clone(), + eth1_data: eth1_data.clone(), + graffiti: *graffiti, + proposer_slashings: proposer_slashings.clone(), + attester_slashings: attester_slashings.clone(), + attestations: attestations.clone(), + deposits: deposits.clone(), + voluntary_exits: voluntary_exits.clone(), + sync_aggregate: sync_aggregate.clone(), + execution_payload: BlindedPayloadElectra { + execution_payload_header: execution_payload.into(), + }, + bls_to_execution_changes: bls_to_execution_changes.clone(), + blob_kzg_commitments: blob_kzg_commitments.clone(), + } + } +} + impl From>> for ( BeaconBlockBody>, diff --git a/consensus/types/src/beacon_state.rs b/consensus/types/src/beacon_state.rs index 8bef7281f8b..a9817b73423 100644 --- a/consensus/types/src/beacon_state.rs +++ b/consensus/types/src/beacon_state.rs @@ -181,7 +181,7 @@ impl From for Hash256 { /// The state of the `BeaconChain` at some slot. #[superstruct( - variants(Base, Altair, Merge, Capella, Deneb), + variants(Base, Altair, Merge, Capella, Deneb, Electra), variant_attributes( derive( Derivative, @@ -261,9 +261,9 @@ where pub current_epoch_attestations: VariableList, T::MaxPendingAttestations>, // Participation (Altair and later) - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub previous_epoch_participation: VariableList, - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub current_epoch_participation: VariableList, // Finality @@ -278,13 +278,13 @@ where // Inactivity #[serde(with = "ssz_types::serde_utils::quoted_u64_var_list")] - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub inactivity_scores: VariableList, // Light-client sync committees - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub current_sync_committee: Arc>, - #[superstruct(only(Altair, Merge, Capella, Deneb))] + #[superstruct(only(Altair, Merge, Capella, Deneb, Electra))] pub next_sync_committee: Arc>, // Execution @@ -303,16 +303,21 @@ where partial_getter(rename = "latest_execution_payload_header_deneb") )] pub latest_execution_payload_header: ExecutionPayloadHeaderDeneb, + #[superstruct( + only(Electra), + partial_getter(rename = "latest_execution_payload_header_electra") + )] + pub latest_execution_payload_header: ExecutionPayloadHeaderElectra, // Capella - #[superstruct(only(Capella, Deneb), partial_getter(copy))] + #[superstruct(only(Capella, Deneb, Electra), partial_getter(copy))] #[serde(with = "serde_utils::quoted_u64")] pub next_withdrawal_index: u64, - #[superstruct(only(Capella, Deneb), partial_getter(copy))] + #[superstruct(only(Capella, Deneb, Electra), partial_getter(copy))] #[serde(with = "serde_utils::quoted_u64")] pub next_withdrawal_validator_index: u64, // Deep history valid from Capella onwards. - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub historical_summaries: VariableList, // Caching (not in the spec) @@ -449,6 +454,7 @@ impl BeaconState { BeaconState::Merge { .. } => ForkName::Merge, BeaconState::Capella { .. } => ForkName::Capella, BeaconState::Deneb { .. } => ForkName::Deneb, + BeaconState::Electra { .. } => ForkName::Electra, } } @@ -759,6 +765,9 @@ impl BeaconState { BeaconState::Deneb(state) => Ok(ExecutionPayloadHeaderRef::Deneb( &state.latest_execution_payload_header, )), + BeaconState::Electra(state) => Ok(ExecutionPayloadHeaderRef::Electra( + &state.latest_execution_payload_header, + )), } } @@ -776,6 +785,9 @@ impl BeaconState { BeaconState::Deneb(state) => Ok(ExecutionPayloadHeaderRefMut::Deneb( &mut state.latest_execution_payload_header, )), + BeaconState::Electra(state) => Ok(ExecutionPayloadHeaderRefMut::Electra( + &mut state.latest_execution_payload_header, + )), } } @@ -1227,6 +1239,11 @@ impl BeaconState { &mut state.balances, &mut state.progressive_balances_cache, ), + BeaconState::Electra(state) => ( + &mut state.validators, + &mut state.balances, + &mut state.progressive_balances_cache, + ), } } @@ -1348,7 +1365,7 @@ impl BeaconState { | BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) => self.get_churn_limit(spec)?, - BeaconState::Deneb(_) => std::cmp::min( + BeaconState::Deneb(_) | BeaconState::Electra(_) => std::cmp::min( spec.max_per_epoch_activation_churn_limit, self.get_churn_limit(spec)?, ), @@ -1443,6 +1460,7 @@ impl BeaconState { BeaconState::Merge(state) => Ok(&mut state.current_epoch_participation), BeaconState::Capella(state) => Ok(&mut state.current_epoch_participation), BeaconState::Deneb(state) => Ok(&mut state.current_epoch_participation), + BeaconState::Electra(state) => Ok(&mut state.current_epoch_participation), } } else if epoch == self.previous_epoch() { match self { @@ -1451,6 +1469,7 @@ impl BeaconState { BeaconState::Merge(state) => Ok(&mut state.previous_epoch_participation), BeaconState::Capella(state) => Ok(&mut state.previous_epoch_participation), BeaconState::Deneb(state) => Ok(&mut state.previous_epoch_participation), + BeaconState::Electra(state) => Ok(&mut state.previous_epoch_participation), } } else { Err(BeaconStateError::EpochOutOfBounds) @@ -1763,6 +1782,7 @@ impl BeaconState { BeaconState::Merge(inner) => BeaconState::Merge(inner.clone()), BeaconState::Capella(inner) => BeaconState::Capella(inner.clone()), BeaconState::Deneb(inner) => BeaconState::Deneb(inner.clone()), + BeaconState::Electra(inner) => BeaconState::Electra(inner.clone()), }; if config.committee_caches { res.committee_caches_mut() @@ -1943,6 +1963,7 @@ impl CompareFields for BeaconState { (BeaconState::Merge(x), BeaconState::Merge(y)) => x.compare_fields(y), (BeaconState::Capella(x), BeaconState::Capella(y)) => x.compare_fields(y), (BeaconState::Deneb(x), BeaconState::Deneb(y)) => x.compare_fields(y), + (BeaconState::Electra(x), BeaconState::Electra(y)) => x.compare_fields(y), _ => panic!("compare_fields: mismatched state variants",), } } diff --git a/consensus/types/src/beacon_state/progressive_balances_cache.rs b/consensus/types/src/beacon_state/progressive_balances_cache.rs index 6c0682480bf..e6305fa8bc9 100644 --- a/consensus/types/src/beacon_state/progressive_balances_cache.rs +++ b/consensus/types/src/beacon_state/progressive_balances_cache.rs @@ -182,6 +182,7 @@ pub fn is_progressive_balances_enabled(state: &BeaconState) -> bo BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => true, + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => true, } } diff --git a/consensus/types/src/builder_bid.rs b/consensus/types/src/builder_bid.rs index f43585000a5..9a0b3f7927c 100644 --- a/consensus/types/src/builder_bid.rs +++ b/consensus/types/src/builder_bid.rs @@ -1,8 +1,8 @@ use crate::beacon_block_body::KzgCommitments; use crate::{ ChainSpec, EthSpec, ExecutionPayloadHeaderCapella, ExecutionPayloadHeaderDeneb, - ExecutionPayloadHeaderMerge, ExecutionPayloadHeaderRef, ExecutionPayloadHeaderRefMut, ForkName, - ForkVersionDeserialize, SignedRoot, Uint256, + ExecutionPayloadHeaderElectra, ExecutionPayloadHeaderMerge, ExecutionPayloadHeaderRef, + ExecutionPayloadHeaderRefMut, ForkName, ForkVersionDeserialize, SignedRoot, Uint256, }; use bls::PublicKeyBytes; use bls::Signature; @@ -11,7 +11,7 @@ use superstruct::superstruct; use tree_hash_derive::TreeHash; #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive(PartialEq, Debug, Serialize, Deserialize, TreeHash, Clone), serde(bound = "E: EthSpec", deny_unknown_fields) @@ -29,7 +29,9 @@ pub struct BuilderBid { pub header: ExecutionPayloadHeaderCapella, #[superstruct(only(Deneb), partial_getter(rename = "header_deneb"))] pub header: ExecutionPayloadHeaderDeneb, - #[superstruct(only(Deneb))] + #[superstruct(only(Electra), partial_getter(rename = "header_electra"))] + pub header: ExecutionPayloadHeaderElectra, + #[superstruct(only(Deneb, Electra))] pub blob_kzg_commitments: KzgCommitments, #[serde(with = "serde_utils::quoted_u256")] pub value: Uint256, @@ -80,6 +82,7 @@ impl ForkVersionDeserialize for BuilderBid { ForkName::Merge => Self::Merge(serde_json::from_value(value).map_err(convert_err)?), ForkName::Capella => Self::Capella(serde_json::from_value(value).map_err(convert_err)?), ForkName::Deneb => Self::Deneb(serde_json::from_value(value).map_err(convert_err)?), + ForkName::Electra => Self::Electra(serde_json::from_value(value).map_err(convert_err)?), ForkName::Base | ForkName::Altair => { return Err(serde::de::Error::custom(format!( "BuilderBid failed to deserialize: unsupported fork '{}'", diff --git a/consensus/types/src/chain_spec.rs b/consensus/types/src/chain_spec.rs index 88f989d2a5a..34db63c6e13 100644 --- a/consensus/types/src/chain_spec.rs +++ b/consensus/types/src/chain_spec.rs @@ -169,6 +169,13 @@ pub struct ChainSpec { pub deneb_fork_version: [u8; 4], pub deneb_fork_epoch: Option, + /* + * Electra hard fork params + */ + pub electra_fork_version: [u8; 4], + /// The Electra fork epoch is optional, with `None` representing "Electra never happens". + pub electra_fork_epoch: Option, + /* * Networking */ @@ -282,15 +289,18 @@ impl ChainSpec { /// Returns the name of the fork which is active at `epoch`. pub fn fork_name_at_epoch(&self, epoch: Epoch) -> ForkName { - match self.deneb_fork_epoch { - Some(fork_epoch) if epoch >= fork_epoch => ForkName::Deneb, - _ => match self.capella_fork_epoch { - Some(fork_epoch) if epoch >= fork_epoch => ForkName::Capella, - _ => match self.bellatrix_fork_epoch { - Some(fork_epoch) if epoch >= fork_epoch => ForkName::Merge, - _ => match self.altair_fork_epoch { - Some(fork_epoch) if epoch >= fork_epoch => ForkName::Altair, - _ => ForkName::Base, + match self.electra_fork_epoch { + Some(fork_epoch) if epoch >= fork_epoch => ForkName::Electra, + _ => match self.deneb_fork_epoch { + Some(fork_epoch) if epoch >= fork_epoch => ForkName::Deneb, + _ => match self.capella_fork_epoch { + Some(fork_epoch) if epoch >= fork_epoch => ForkName::Capella, + _ => match self.bellatrix_fork_epoch { + Some(fork_epoch) if epoch >= fork_epoch => ForkName::Merge, + _ => match self.altair_fork_epoch { + Some(fork_epoch) if epoch >= fork_epoch => ForkName::Altair, + _ => ForkName::Base, + }, }, }, }, @@ -305,6 +315,7 @@ impl ChainSpec { ForkName::Merge => self.bellatrix_fork_version, ForkName::Capella => self.capella_fork_version, ForkName::Deneb => self.deneb_fork_version, + ForkName::Electra => self.electra_fork_version, } } @@ -316,6 +327,7 @@ impl ChainSpec { ForkName::Merge => self.bellatrix_fork_epoch, ForkName::Capella => self.capella_fork_epoch, ForkName::Deneb => self.deneb_fork_epoch, + ForkName::Electra => self.electra_fork_epoch, } } @@ -327,6 +339,7 @@ impl ChainSpec { BeaconState::Merge(_) => self.inactivity_penalty_quotient_bellatrix, BeaconState::Capella(_) => self.inactivity_penalty_quotient_bellatrix, BeaconState::Deneb(_) => self.inactivity_penalty_quotient_bellatrix, + BeaconState::Electra(_) => self.inactivity_penalty_quotient_bellatrix, } } @@ -341,6 +354,7 @@ impl ChainSpec { BeaconState::Merge(_) => self.proportional_slashing_multiplier_bellatrix, BeaconState::Capella(_) => self.proportional_slashing_multiplier_bellatrix, BeaconState::Deneb(_) => self.proportional_slashing_multiplier_bellatrix, + BeaconState::Electra(_) => self.proportional_slashing_multiplier_bellatrix, } } @@ -355,6 +369,7 @@ impl ChainSpec { BeaconState::Merge(_) => self.min_slashing_penalty_quotient_bellatrix, BeaconState::Capella(_) => self.min_slashing_penalty_quotient_bellatrix, BeaconState::Deneb(_) => self.min_slashing_penalty_quotient_bellatrix, + BeaconState::Electra(_) => self.min_slashing_penalty_quotient_bellatrix, } } @@ -513,7 +528,7 @@ impl ChainSpec { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => { self.max_blocks_by_root_request } - ForkName::Deneb => self.max_blocks_by_root_request_deneb, + ForkName::Deneb | ForkName::Electra => self.max_blocks_by_root_request_deneb, } } @@ -522,7 +537,7 @@ impl ChainSpec { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => { self.max_request_blocks } - ForkName::Deneb => self.max_request_blocks_deneb, + ForkName::Deneb | ForkName::Electra => self.max_request_blocks_deneb, }; max_request_blocks as usize } @@ -683,6 +698,12 @@ impl ChainSpec { deneb_fork_version: [0x04, 0x00, 0x00, 0x00], deneb_fork_epoch: Some(Epoch::new(269568)), + /* + * Electra hard fork params + */ + electra_fork_version: [0x05, 00, 00, 00], + electra_fork_epoch: None, + /* * Network specific */ @@ -779,6 +800,9 @@ impl ChainSpec { // Deneb deneb_fork_version: [0x04, 0x00, 0x00, 0x01], deneb_fork_epoch: None, + // Electra + electra_fork_version: [0x05, 0x00, 0x00, 0x01], + electra_fork_epoch: None, // Other network_id: 2, // lighthouse testnet network id deposit_chain_id: 5, @@ -946,6 +970,12 @@ impl ChainSpec { deneb_fork_version: [0x04, 0x00, 0x00, 0x64], deneb_fork_epoch: Some(Epoch::new(889856)), + /* + * Electra hard fork params + */ + electra_fork_version: [0x05, 0x00, 0x00, 0x64], + electra_fork_epoch: None, + /* * Network specific */ @@ -1069,6 +1099,14 @@ pub struct Config { #[serde(deserialize_with = "deserialize_fork_epoch")] pub deneb_fork_epoch: Option>, + #[serde(default = "default_electra_fork_version")] + #[serde(with = "serde_utils::bytes_4_hex")] + electra_fork_version: [u8; 4], + #[serde(default)] + #[serde(serialize_with = "serialize_fork_epoch")] + #[serde(deserialize_with = "deserialize_fork_epoch")] + pub electra_fork_epoch: Option>, + #[serde(with = "serde_utils::quoted_u64")] seconds_per_slot: u64, #[serde(with = "serde_utils::quoted_u64")] @@ -1177,6 +1215,11 @@ fn default_deneb_fork_version() -> [u8; 4] { [0xff, 0xff, 0xff, 0xff] } +fn default_electra_fork_version() -> [u8; 4] { + // This value shouldn't be used. + [0xff, 0xff, 0xff, 0xff] +} + /// Placeholder value: 2^256-2^10 (115792089237316195423570985008687907853269984665640564039457584007913129638912). /// /// Taken from https://github.com/ethereum/consensus-specs/blob/d5e4828aecafaf1c57ef67a5f23c4ae7b08c5137/configs/mainnet.yaml#L15-L16 @@ -1386,19 +1429,27 @@ impl Config { altair_fork_epoch: spec .altair_fork_epoch .map(|epoch| MaybeQuoted { value: epoch }), + bellatrix_fork_version: spec.bellatrix_fork_version, bellatrix_fork_epoch: spec .bellatrix_fork_epoch .map(|epoch| MaybeQuoted { value: epoch }), + capella_fork_version: spec.capella_fork_version, capella_fork_epoch: spec .capella_fork_epoch .map(|epoch| MaybeQuoted { value: epoch }), + deneb_fork_version: spec.deneb_fork_version, deneb_fork_epoch: spec .deneb_fork_epoch .map(|epoch| MaybeQuoted { value: epoch }), + electra_fork_version: spec.electra_fork_version, + electra_fork_epoch: spec + .electra_fork_epoch + .map(|epoch| MaybeQuoted { value: epoch }), + seconds_per_slot: spec.seconds_per_slot, seconds_per_eth1_block: spec.seconds_per_eth1_block, min_validator_withdrawability_delay: spec.min_validator_withdrawability_delay, @@ -1468,6 +1519,8 @@ impl Config { capella_fork_version, deneb_fork_epoch, deneb_fork_version, + electra_fork_epoch, + electra_fork_version, seconds_per_slot, seconds_per_eth1_block, min_validator_withdrawability_delay, @@ -1522,6 +1575,8 @@ impl Config { capella_fork_version, deneb_fork_epoch: deneb_fork_epoch.map(|q| q.value), deneb_fork_version, + electra_fork_epoch: electra_fork_epoch.map(|q| q.value), + electra_fork_version, seconds_per_slot, seconds_per_eth1_block, min_validator_withdrawability_delay, diff --git a/consensus/types/src/config_and_preset.rs b/consensus/types/src/config_and_preset.rs index b651d34af36..4d7520f5bdd 100644 --- a/consensus/types/src/config_and_preset.rs +++ b/consensus/types/src/config_and_preset.rs @@ -1,6 +1,6 @@ use crate::{ consts::altair, AltairPreset, BasePreset, BellatrixPreset, CapellaPreset, ChainSpec, Config, - DenebPreset, EthSpec, ForkName, + DenebPreset, ElectraPreset, EthSpec, ForkName, }; use maplit::hashmap; use serde::{Deserialize, Serialize}; @@ -12,7 +12,7 @@ use superstruct::superstruct; /// /// Mostly useful for the API. #[superstruct( - variants(Capella, Deneb), + variants(Capella, Deneb, Electra), variant_attributes(derive(Serialize, Deserialize, Debug, PartialEq, Clone)) )] #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] @@ -29,9 +29,12 @@ pub struct ConfigAndPreset { pub bellatrix_preset: BellatrixPreset, #[serde(flatten)] pub capella_preset: CapellaPreset, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] #[serde(flatten)] pub deneb_preset: DenebPreset, + #[superstruct(only(Electra))] + #[serde(flatten)] + pub electra_preset: ElectraPreset, /// The `extra_fields` map allows us to gracefully decode fields intended for future hard forks. #[serde(flatten)] pub extra_fields: HashMap, @@ -46,11 +49,29 @@ impl ConfigAndPreset { let capella_preset = CapellaPreset::from_chain_spec::(spec); let extra_fields = get_extra_fields(spec); - if spec.deneb_fork_epoch.is_some() + if spec.electra_fork_epoch.is_some() + || fork_name.is_none() + || fork_name == Some(ForkName::Electra) + { + let deneb_preset = DenebPreset::from_chain_spec::(spec); + let electra_preset = ElectraPreset::from_chain_spec::(spec); + + ConfigAndPreset::Electra(ConfigAndPresetElectra { + config, + base_preset, + altair_preset, + bellatrix_preset, + capella_preset, + deneb_preset, + electra_preset, + extra_fields, + }) + } else if spec.deneb_fork_epoch.is_some() || fork_name.is_none() || fork_name == Some(ForkName::Deneb) { let deneb_preset = DenebPreset::from_chain_spec::(spec); + ConfigAndPreset::Deneb(ConfigAndPresetDeneb { config, base_preset, @@ -136,8 +157,8 @@ mod test { .write(false) .open(tmp_file.as_ref()) .expect("error while opening the file"); - let from: ConfigAndPresetDeneb = + let from: ConfigAndPresetElectra = serde_yaml::from_reader(reader).expect("error while deserializing"); - assert_eq!(ConfigAndPreset::Deneb(from), yamlconfig); + assert_eq!(ConfigAndPreset::Electra(from), yamlconfig); } } diff --git a/consensus/types/src/eth_spec.rs b/consensus/types/src/eth_spec.rs index 446267facc1..a2972b722a2 100644 --- a/consensus/types/src/eth_spec.rs +++ b/consensus/types/src/eth_spec.rs @@ -134,6 +134,11 @@ pub trait EthSpec: /// Must be set to `BytesPerFieldElement * FieldElementsPerBlob`. type BytesPerBlob: Unsigned + Clone + Sync + Send + Debug + PartialEq; + /* + * New in Electra + */ + type ElectraPlaceholder: Unsigned + Clone + Sync + Send + Debug + PartialEq; + fn default_spec() -> ChainSpec; fn spec_name() -> EthSpecId; @@ -273,10 +278,15 @@ pub trait EthSpec: fn bytes_per_blob() -> usize { Self::BytesPerBlob::to_usize() } + /// Returns the `KZG_COMMITMENT_INCLUSION_PROOF_DEPTH` preset for this specification. fn kzg_proof_inclusion_proof_depth() -> usize { Self::KzgCommitmentInclusionProofDepth::to_usize() } + + fn electra_placeholder() -> usize { + Self::ElectraPlaceholder::to_usize() + } } /// Macro to inherit some type values from another EthSpec. @@ -327,6 +337,7 @@ impl EthSpec for MainnetEthSpec { type SlotsPerEth1VotingPeriod = U2048; // 64 epochs * 32 slots per epoch type MaxBlsToExecutionChanges = U16; type MaxWithdrawalsPerPayload = U16; + type ElectraPlaceholder = U16; fn default_spec() -> ChainSpec { ChainSpec::mainnet() @@ -378,7 +389,8 @@ impl EthSpec for MinimalEthSpec { MaxExtraDataBytes, MaxBlsToExecutionChanges, MaxBlobsPerBlock, - BytesPerFieldElement + BytesPerFieldElement, + ElectraPlaceholder }); fn default_spec() -> ChainSpec { @@ -430,6 +442,7 @@ impl EthSpec for GnosisEthSpec { type BytesPerFieldElement = U32; type BytesPerBlob = U131072; type KzgCommitmentInclusionProofDepth = U17; + type ElectraPlaceholder = U16; fn default_spec() -> ChainSpec { ChainSpec::gnosis() diff --git a/consensus/types/src/execution_payload.rs b/consensus/types/src/execution_payload.rs index 1dc5951b253..bc729fd2888 100644 --- a/consensus/types/src/execution_payload.rs +++ b/consensus/types/src/execution_payload.rs @@ -15,7 +15,7 @@ pub type Transactions = VariableList< pub type Withdrawals = VariableList::MaxWithdrawalsPerPayload>; #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive( Default, @@ -81,12 +81,12 @@ pub struct ExecutionPayload { pub block_hash: ExecutionBlockHash, #[serde(with = "ssz_types::serde_utils::list_of_hex_var_list")] pub transactions: Transactions, - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] pub withdrawals: Withdrawals, - #[superstruct(only(Deneb), partial_getter(copy))] + #[superstruct(only(Deneb, Electra), partial_getter(copy))] #[serde(with = "serde_utils::quoted_u64")] pub blob_gas_used: u64, - #[superstruct(only(Deneb), partial_getter(copy))] + #[superstruct(only(Deneb, Electra), partial_getter(copy))] #[serde(with = "serde_utils::quoted_u64")] pub excess_blob_gas: u64, } @@ -110,6 +110,7 @@ impl ExecutionPayload { ForkName::Merge => ExecutionPayloadMerge::from_ssz_bytes(bytes).map(Self::Merge), ForkName::Capella => ExecutionPayloadCapella::from_ssz_bytes(bytes).map(Self::Capella), ForkName::Deneb => ExecutionPayloadDeneb::from_ssz_bytes(bytes).map(Self::Deneb), + ForkName::Electra => ExecutionPayloadElectra::from_ssz_bytes(bytes).map(Self::Electra), } } @@ -149,6 +150,19 @@ impl ExecutionPayload { // Max size of variable length `withdrawals` field + (T::max_withdrawals_per_payload() * ::ssz_fixed_len()) } + + #[allow(clippy::arithmetic_side_effects)] + /// Returns the maximum size of an execution payload. + pub fn max_execution_payload_electra_size() -> usize { + // Fixed part + ExecutionPayloadElectra::::default().as_ssz_bytes().len() + // Max size of variable length `extra_data` field + + (T::max_extra_data_bytes() * ::ssz_fixed_len()) + // Max size of variable length `transactions` field + + (T::max_transactions_per_payload() * (ssz::BYTES_PER_LENGTH_OFFSET + T::max_bytes_per_transaction())) + // Max size of variable length `withdrawals` field + + (T::max_withdrawals_per_payload() * ::ssz_fixed_len()) + } } impl ForkVersionDeserialize for ExecutionPayload { @@ -164,6 +178,7 @@ impl ForkVersionDeserialize for ExecutionPayload { ForkName::Merge => Self::Merge(serde_json::from_value(value).map_err(convert_err)?), ForkName::Capella => Self::Capella(serde_json::from_value(value).map_err(convert_err)?), ForkName::Deneb => Self::Deneb(serde_json::from_value(value).map_err(convert_err)?), + ForkName::Electra => Self::Electra(serde_json::from_value(value).map_err(convert_err)?), ForkName::Base | ForkName::Altair => { return Err(serde::de::Error::custom(format!( "ExecutionPayload failed to deserialize: unsupported fork '{}'", @@ -180,6 +195,7 @@ impl ExecutionPayload { ExecutionPayload::Merge(_) => ForkName::Merge, ExecutionPayload::Capella(_) => ForkName::Capella, ExecutionPayload::Deneb(_) => ForkName::Deneb, + ExecutionPayload::Electra(_) => ForkName::Electra, } } } diff --git a/consensus/types/src/execution_payload_header.rs b/consensus/types/src/execution_payload_header.rs index 9a2be345a8a..652683a7279 100644 --- a/consensus/types/src/execution_payload_header.rs +++ b/consensus/types/src/execution_payload_header.rs @@ -8,7 +8,7 @@ use tree_hash::TreeHash; use tree_hash_derive::TreeHash; #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive( Default, @@ -76,14 +76,14 @@ pub struct ExecutionPayloadHeader { pub block_hash: ExecutionBlockHash, #[superstruct(getter(copy))] pub transactions_root: Hash256, - #[superstruct(only(Capella, Deneb))] + #[superstruct(only(Capella, Deneb, Electra))] #[superstruct(getter(copy))] pub withdrawals_root: Hash256, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] #[serde(with = "serde_utils::quoted_u64")] #[superstruct(getter(copy))] pub blob_gas_used: u64, - #[superstruct(only(Deneb))] + #[superstruct(only(Deneb, Electra))] #[serde(with = "serde_utils::quoted_u64")] #[superstruct(getter(copy))] pub excess_blob_gas: u64, @@ -104,6 +104,9 @@ impl ExecutionPayloadHeader { ExecutionPayloadHeaderCapella::from_ssz_bytes(bytes).map(Self::Capella) } ForkName::Deneb => ExecutionPayloadHeaderDeneb::from_ssz_bytes(bytes).map(Self::Deneb), + ForkName::Electra => { + ExecutionPayloadHeaderElectra::from_ssz_bytes(bytes).map(Self::Electra) + } } } } @@ -163,6 +166,30 @@ impl ExecutionPayloadHeaderCapella { } } +impl ExecutionPayloadHeaderDeneb { + pub fn upgrade_to_electra(&self) -> ExecutionPayloadHeaderElectra { + ExecutionPayloadHeaderElectra { + parent_hash: self.parent_hash, + fee_recipient: self.fee_recipient, + state_root: self.state_root, + receipts_root: self.receipts_root, + logs_bloom: self.logs_bloom.clone(), + prev_randao: self.prev_randao, + block_number: self.block_number, + gas_limit: self.gas_limit, + gas_used: self.gas_used, + timestamp: self.timestamp, + extra_data: self.extra_data.clone(), + base_fee_per_gas: self.base_fee_per_gas, + block_hash: self.block_hash, + transactions_root: self.transactions_root, + withdrawals_root: self.withdrawals_root, + blob_gas_used: self.blob_gas_used, + excess_blob_gas: self.excess_blob_gas, + } + } +} + impl<'a, T: EthSpec> From<&'a ExecutionPayloadMerge> for ExecutionPayloadHeaderMerge { fn from(payload: &'a ExecutionPayloadMerge) -> Self { Self { @@ -183,6 +210,7 @@ impl<'a, T: EthSpec> From<&'a ExecutionPayloadMerge> for ExecutionPayloadHead } } } + impl<'a, T: EthSpec> From<&'a ExecutionPayloadCapella> for ExecutionPayloadHeaderCapella { fn from(payload: &'a ExecutionPayloadCapella) -> Self { Self { @@ -229,6 +257,30 @@ impl<'a, T: EthSpec> From<&'a ExecutionPayloadDeneb> for ExecutionPayloadHead } } +impl<'a, T: EthSpec> From<&'a ExecutionPayloadElectra> for ExecutionPayloadHeaderElectra { + fn from(payload: &'a ExecutionPayloadElectra) -> Self { + Self { + parent_hash: payload.parent_hash, + fee_recipient: payload.fee_recipient, + state_root: payload.state_root, + receipts_root: payload.receipts_root, + logs_bloom: payload.logs_bloom.clone(), + prev_randao: payload.prev_randao, + block_number: payload.block_number, + gas_limit: payload.gas_limit, + gas_used: payload.gas_used, + timestamp: payload.timestamp, + extra_data: payload.extra_data.clone(), + base_fee_per_gas: payload.base_fee_per_gas, + block_hash: payload.block_hash, + transactions_root: payload.transactions.tree_hash_root(), + withdrawals_root: payload.withdrawals.tree_hash_root(), + blob_gas_used: payload.blob_gas_used, + excess_blob_gas: payload.excess_blob_gas, + } + } +} + // These impls are required to work around an inelegance in `to_execution_payload_header`. // They only clone headers so they should be relatively cheap. impl<'a, T: EthSpec> From<&'a Self> for ExecutionPayloadHeaderMerge { @@ -249,6 +301,12 @@ impl<'a, T: EthSpec> From<&'a Self> for ExecutionPayloadHeaderDeneb { } } +impl<'a, T: EthSpec> From<&'a Self> for ExecutionPayloadHeaderElectra { + fn from(payload: &'a Self) -> Self { + payload.clone() + } +} + impl<'a, T: EthSpec> From> for ExecutionPayloadHeader { fn from(payload: ExecutionPayloadRef<'a, T>) -> Self { map_execution_payload_ref_into_execution_payload_header!( @@ -289,6 +347,18 @@ impl TryFrom> for ExecutionPayloadHeaderDe } } +impl TryFrom> for ExecutionPayloadHeaderElectra { + type Error = BeaconStateError; + fn try_from(header: ExecutionPayloadHeader) -> Result { + match header { + ExecutionPayloadHeader::Electra(execution_payload_header) => { + Ok(execution_payload_header) + } + _ => Err(BeaconStateError::IncorrectStateVariant), + } + } +} + impl ForkVersionDeserialize for ExecutionPayloadHeader { fn deserialize_by_fork<'de, D: serde::Deserializer<'de>>( value: serde_json::value::Value, @@ -305,6 +375,7 @@ impl ForkVersionDeserialize for ExecutionPayloadHeader { ForkName::Merge => Self::Merge(serde_json::from_value(value).map_err(convert_err)?), ForkName::Capella => Self::Capella(serde_json::from_value(value).map_err(convert_err)?), ForkName::Deneb => Self::Deneb(serde_json::from_value(value).map_err(convert_err)?), + ForkName::Electra => Self::Electra(serde_json::from_value(value).map_err(convert_err)?), ForkName::Base | ForkName::Altair => { return Err(serde::de::Error::custom(format!( "ExecutionPayloadHeader failed to deserialize: unsupported fork '{}'", diff --git a/consensus/types/src/fork_context.rs b/consensus/types/src/fork_context.rs index 9992892714c..033dfcc612e 100644 --- a/consensus/types/src/fork_context.rs +++ b/consensus/types/src/fork_context.rs @@ -62,6 +62,13 @@ impl ForkContext { )); } + if spec.electra_fork_epoch.is_some() { + fork_to_digest.push(( + ForkName::Electra, + ChainSpec::compute_fork_digest(spec.electra_fork_version, genesis_validators_root), + )); + } + let fork_to_digest: HashMap = fork_to_digest.into_iter().collect(); let digest_to_fork = fork_to_digest diff --git a/consensus/types/src/fork_name.rs b/consensus/types/src/fork_name.rs index 7a3b026d300..fbe53c56896 100644 --- a/consensus/types/src/fork_name.rs +++ b/consensus/types/src/fork_name.rs @@ -14,6 +14,7 @@ pub enum ForkName { Merge, Capella, Deneb, + Electra, } impl ForkName { @@ -24,6 +25,7 @@ impl ForkName { ForkName::Merge, ForkName::Capella, ForkName::Deneb, + ForkName::Electra, ] } @@ -42,6 +44,7 @@ impl ForkName { spec.bellatrix_fork_epoch = None; spec.capella_fork_epoch = None; spec.deneb_fork_epoch = None; + spec.electra_fork_epoch = None; spec } ForkName::Altair => { @@ -49,6 +52,7 @@ impl ForkName { spec.bellatrix_fork_epoch = None; spec.capella_fork_epoch = None; spec.deneb_fork_epoch = None; + spec.electra_fork_epoch = None; spec } ForkName::Merge => { @@ -56,6 +60,7 @@ impl ForkName { spec.bellatrix_fork_epoch = Some(Epoch::new(0)); spec.capella_fork_epoch = None; spec.deneb_fork_epoch = None; + spec.electra_fork_epoch = None; spec } ForkName::Capella => { @@ -63,6 +68,7 @@ impl ForkName { spec.bellatrix_fork_epoch = Some(Epoch::new(0)); spec.capella_fork_epoch = Some(Epoch::new(0)); spec.deneb_fork_epoch = None; + spec.electra_fork_epoch = None; spec } ForkName::Deneb => { @@ -70,6 +76,15 @@ impl ForkName { spec.bellatrix_fork_epoch = Some(Epoch::new(0)); spec.capella_fork_epoch = Some(Epoch::new(0)); spec.deneb_fork_epoch = Some(Epoch::new(0)); + spec.electra_fork_epoch = None; + spec + } + ForkName::Electra => { + spec.altair_fork_epoch = Some(Epoch::new(0)); + spec.bellatrix_fork_epoch = Some(Epoch::new(0)); + spec.capella_fork_epoch = Some(Epoch::new(0)); + spec.deneb_fork_epoch = Some(Epoch::new(0)); + spec.electra_fork_epoch = Some(Epoch::new(0)); spec } } @@ -85,6 +100,7 @@ impl ForkName { ForkName::Merge => Some(ForkName::Altair), ForkName::Capella => Some(ForkName::Merge), ForkName::Deneb => Some(ForkName::Capella), + ForkName::Electra => Some(ForkName::Deneb), } } @@ -97,7 +113,8 @@ impl ForkName { ForkName::Altair => Some(ForkName::Merge), ForkName::Merge => Some(ForkName::Capella), ForkName::Capella => Some(ForkName::Deneb), - ForkName::Deneb => None, + ForkName::Deneb => Some(ForkName::Electra), + ForkName::Electra => None, } } } @@ -147,6 +164,10 @@ macro_rules! map_fork_name_with { let (value, extra_data) = $body; ($t::Deneb(value), extra_data) } + ForkName::Electra => { + let (value, extra_data) = $body; + ($t::Electra(value), extra_data) + } } }; } @@ -161,6 +182,7 @@ impl FromStr for ForkName { "bellatrix" | "merge" => ForkName::Merge, "capella" => ForkName::Capella, "deneb" => ForkName::Deneb, + "electra" => ForkName::Electra, _ => return Err(format!("unknown fork name: {}", fork_name)), }) } @@ -174,6 +196,7 @@ impl Display for ForkName { ForkName::Merge => "bellatrix".fmt(f), ForkName::Capella => "capella".fmt(f), ForkName::Deneb => "deneb".fmt(f), + ForkName::Electra => "electra".fmt(f), } } } diff --git a/consensus/types/src/lib.rs b/consensus/types/src/lib.rs index e216a5da66b..26d40e2399d 100644 --- a/consensus/types/src/lib.rs +++ b/consensus/types/src/lib.rs @@ -112,11 +112,13 @@ pub use crate::attestation_duty::AttestationDuty; pub use crate::attester_slashing::AttesterSlashing; pub use crate::beacon_block::{ BeaconBlock, BeaconBlockAltair, BeaconBlockBase, BeaconBlockCapella, BeaconBlockDeneb, - BeaconBlockMerge, BeaconBlockRef, BeaconBlockRefMut, BlindedBeaconBlock, EmptyBlock, + BeaconBlockElectra, BeaconBlockMerge, BeaconBlockRef, BeaconBlockRefMut, BlindedBeaconBlock, + EmptyBlock, }; pub use crate::beacon_block_body::{ BeaconBlockBody, BeaconBlockBodyAltair, BeaconBlockBodyBase, BeaconBlockBodyCapella, - BeaconBlockBodyDeneb, BeaconBlockBodyMerge, BeaconBlockBodyRef, BeaconBlockBodyRefMut, + BeaconBlockBodyDeneb, BeaconBlockBodyElectra, BeaconBlockBodyMerge, BeaconBlockBodyRef, + BeaconBlockBodyRefMut, }; pub use crate::beacon_block_header::BeaconBlockHeader; pub use crate::beacon_committee::{BeaconCommittee, OwnedBeaconCommittee}; @@ -125,7 +127,9 @@ pub use crate::blob_sidecar::{BlobSidecar, BlobSidecarList, BlobsList}; pub use crate::bls_to_execution_change::BlsToExecutionChange; pub use crate::chain_spec::{ChainSpec, Config, Domain}; pub use crate::checkpoint::Checkpoint; -pub use crate::config_and_preset::{ConfigAndPreset, ConfigAndPresetCapella, ConfigAndPresetDeneb}; +pub use crate::config_and_preset::{ + ConfigAndPreset, ConfigAndPresetCapella, ConfigAndPresetDeneb, ConfigAndPresetElectra, +}; pub use crate::contribution_and_proof::ContributionAndProof; pub use crate::deposit::{Deposit, DEPOSIT_TREE_DEPTH}; pub use crate::deposit_data::DepositData; @@ -137,12 +141,13 @@ pub use crate::eth_spec::EthSpecId; pub use crate::execution_block_hash::ExecutionBlockHash; pub use crate::execution_block_header::ExecutionBlockHeader; pub use crate::execution_payload::{ - ExecutionPayload, ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadMerge, - ExecutionPayloadRef, Transaction, Transactions, Withdrawals, + ExecutionPayload, ExecutionPayloadCapella, ExecutionPayloadDeneb, ExecutionPayloadElectra, + ExecutionPayloadMerge, ExecutionPayloadRef, Transaction, Transactions, Withdrawals, }; pub use crate::execution_payload_header::{ ExecutionPayloadHeader, ExecutionPayloadHeaderCapella, ExecutionPayloadHeaderDeneb, - ExecutionPayloadHeaderMerge, ExecutionPayloadHeaderRef, ExecutionPayloadHeaderRefMut, + ExecutionPayloadHeaderElectra, ExecutionPayloadHeaderMerge, ExecutionPayloadHeaderRef, + ExecutionPayloadHeaderRefMut, }; pub use crate::fork::Fork; pub use crate::fork_context::ForkContext; @@ -175,11 +180,14 @@ pub use crate::participation_flags::ParticipationFlags; pub use crate::participation_list::ParticipationList; pub use crate::payload::{ AbstractExecPayload, BlindedPayload, BlindedPayloadCapella, BlindedPayloadDeneb, - BlindedPayloadMerge, BlindedPayloadRef, BlockType, ExecPayload, FullPayload, - FullPayloadCapella, FullPayloadDeneb, FullPayloadMerge, FullPayloadRef, OwnedExecPayload, + BlindedPayloadElectra, BlindedPayloadMerge, BlindedPayloadRef, BlockType, ExecPayload, + FullPayload, FullPayloadCapella, FullPayloadDeneb, FullPayloadElectra, FullPayloadMerge, + FullPayloadRef, OwnedExecPayload, }; pub use crate::pending_attestation::PendingAttestation; -pub use crate::preset::{AltairPreset, BasePreset, BellatrixPreset, CapellaPreset, DenebPreset}; +pub use crate::preset::{ + AltairPreset, BasePreset, BellatrixPreset, CapellaPreset, DenebPreset, ElectraPreset, +}; pub use crate::proposer_preparation_data::ProposerPreparationData; pub use crate::proposer_slashing::ProposerSlashing; pub use crate::relative_epoch::{Error as RelativeEpochError, RelativeEpoch}; @@ -190,8 +198,8 @@ pub use crate::signed_aggregate_and_proof::SignedAggregateAndProof; pub use crate::signed_beacon_block::{ ssz_tagged_signed_beacon_block, ssz_tagged_signed_beacon_block_arc, SignedBeaconBlock, SignedBeaconBlockAltair, SignedBeaconBlockBase, SignedBeaconBlockCapella, - SignedBeaconBlockDeneb, SignedBeaconBlockHash, SignedBeaconBlockMerge, - SignedBlindedBeaconBlock, + SignedBeaconBlockDeneb, SignedBeaconBlockElectra, SignedBeaconBlockHash, + SignedBeaconBlockMerge, SignedBlindedBeaconBlock, }; pub use crate::signed_beacon_block_header::SignedBeaconBlockHeader; pub use crate::signed_bls_to_execution_change::SignedBlsToExecutionChange; diff --git a/consensus/types/src/light_client_bootstrap.rs b/consensus/types/src/light_client_bootstrap.rs index d4e85a351d5..43bab325f3c 100644 --- a/consensus/types/src/light_client_bootstrap.rs +++ b/consensus/types/src/light_client_bootstrap.rs @@ -69,16 +69,11 @@ impl LightClientBootstrap { pub fn from_ssz_bytes(bytes: &[u8], fork_name: ForkName) -> Result { let bootstrap = match fork_name { ForkName::Altair | ForkName::Merge => { - let header = LightClientBootstrapAltair::from_ssz_bytes(bytes)?; - Self::Altair(header) + Self::Altair(LightClientBootstrapAltair::from_ssz_bytes(bytes)?) } - ForkName::Capella => { - let header = LightClientBootstrapCapella::from_ssz_bytes(bytes)?; - Self::Capella(header) - } - ForkName::Deneb => { - let header = LightClientBootstrapDeneb::from_ssz_bytes(bytes)?; - Self::Deneb(header) + ForkName::Capella => Self::Capella(LightClientBootstrapCapella::from_ssz_bytes(bytes)?), + ForkName::Deneb | ForkName::Electra => { + Self::Deneb(LightClientBootstrapDeneb::from_ssz_bytes(bytes)?) } ForkName::Base => { return Err(ssz::DecodeError::BytesInvalid(format!( @@ -117,7 +112,7 @@ impl LightClientBootstrap { current_sync_committee, current_sync_committee_branch, }), - ForkName::Deneb => Self::Deneb(LightClientBootstrapDeneb { + ForkName::Deneb | ForkName::Electra => Self::Deneb(LightClientBootstrapDeneb { header: LightClientHeaderDeneb::block_to_light_client_header(block)?, current_sync_committee, current_sync_committee_branch, @@ -134,14 +129,12 @@ impl ForkVersionDeserialize for LightClientBootstrap { fork_name: ForkName, ) -> Result { match fork_name { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => { - Ok(serde_json::from_value::>(value) - .map_err(serde::de::Error::custom))? - } ForkName::Base => Err(serde::de::Error::custom(format!( "LightClientBootstrap failed to deserialize: unsupported fork '{}'", fork_name ))), + _ => Ok(serde_json::from_value::>(value) + .map_err(serde::de::Error::custom))?, } } } diff --git a/consensus/types/src/light_client_finality_update.rs b/consensus/types/src/light_client_finality_update.rs index 247ec87cde1..288527e91cb 100644 --- a/consensus/types/src/light_client_finality_update.rs +++ b/consensus/types/src/light_client_finality_update.rs @@ -106,7 +106,7 @@ impl LightClientFinalityUpdate { }; Self::Capella(finality_update) } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let finality_update = LightClientFinalityUpdateDeneb { attested_header: LightClientHeaderDeneb::block_to_light_client_header( attested_block, @@ -136,16 +136,13 @@ impl LightClientFinalityUpdate { pub fn from_ssz_bytes(bytes: &[u8], fork_name: ForkName) -> Result { let finality_update = match fork_name { ForkName::Altair | ForkName::Merge => { - let finality_update = LightClientFinalityUpdateAltair::from_ssz_bytes(bytes)?; - Self::Altair(finality_update) + Self::Altair(LightClientFinalityUpdateAltair::from_ssz_bytes(bytes)?) } ForkName::Capella => { - let finality_update = LightClientFinalityUpdateCapella::from_ssz_bytes(bytes)?; - Self::Capella(finality_update) + Self::Capella(LightClientFinalityUpdateCapella::from_ssz_bytes(bytes)?) } - ForkName::Deneb => { - let finality_update = LightClientFinalityUpdateDeneb::from_ssz_bytes(bytes)?; - Self::Deneb(finality_update) + ForkName::Deneb | ForkName::Electra => { + Self::Deneb(LightClientFinalityUpdateDeneb::from_ssz_bytes(bytes)?) } ForkName::Base => { return Err(ssz::DecodeError::BytesInvalid(format!( @@ -164,14 +161,14 @@ impl ForkVersionDeserialize for LightClientFinalityUpdate { fork_name: ForkName, ) -> Result { match fork_name { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => Ok( - serde_json::from_value::>(value) - .map_err(serde::de::Error::custom), - )?, ForkName::Base => Err(serde::de::Error::custom(format!( "LightClientFinalityUpdate failed to deserialize: unsupported fork '{}'", fork_name ))), + _ => Ok( + serde_json::from_value::>(value) + .map_err(serde::de::Error::custom), + )?, } } } diff --git a/consensus/types/src/light_client_header.rs b/consensus/types/src/light_client_header.rs index 0ac3db6e038..728c75d5a1a 100644 --- a/consensus/types/src/light_client_header.rs +++ b/consensus/types/src/light_client_header.rs @@ -81,7 +81,7 @@ impl LightClientHeader { ForkName::Capella => LightClientHeader::Capella( LightClientHeaderCapella::block_to_light_client_header(block)?, ), - ForkName::Deneb => LightClientHeader::Deneb( + ForkName::Deneb | ForkName::Electra => LightClientHeader::Deneb( LightClientHeaderDeneb::block_to_light_client_header(block)?, ), }; @@ -91,16 +91,13 @@ impl LightClientHeader { pub fn from_ssz_bytes(bytes: &[u8], fork_name: ForkName) -> Result { let header = match fork_name { ForkName::Altair | ForkName::Merge => { - let header = LightClientHeaderAltair::from_ssz_bytes(bytes)?; - LightClientHeader::Altair(header) + LightClientHeader::Altair(LightClientHeaderAltair::from_ssz_bytes(bytes)?) } ForkName::Capella => { - let header = LightClientHeaderCapella::from_ssz_bytes(bytes)?; - LightClientHeader::Capella(header) + LightClientHeader::Capella(LightClientHeaderCapella::from_ssz_bytes(bytes)?) } - ForkName::Deneb => { - let header = LightClientHeaderDeneb::from_ssz_bytes(bytes)?; - LightClientHeader::Deneb(header) + ForkName::Deneb | ForkName::Electra => { + LightClientHeader::Deneb(LightClientHeaderDeneb::from_ssz_bytes(bytes)?) } ForkName::Base => { return Err(ssz::DecodeError::BytesInvalid(format!( @@ -198,7 +195,7 @@ impl ForkVersionDeserialize for LightClientHeader { ForkName::Capella => serde_json::from_value(value) .map(|light_client_header| Self::Capella(light_client_header)) .map_err(serde::de::Error::custom), - ForkName::Deneb => serde_json::from_value(value) + ForkName::Deneb | ForkName::Electra => serde_json::from_value(value) .map(|light_client_header| Self::Deneb(light_client_header)) .map_err(serde::de::Error::custom), ForkName::Base => Err(serde::de::Error::custom(format!( diff --git a/consensus/types/src/light_client_optimistic_update.rs b/consensus/types/src/light_client_optimistic_update.rs index 88f287d753e..c292927a6b5 100644 --- a/consensus/types/src/light_client_optimistic_update.rs +++ b/consensus/types/src/light_client_optimistic_update.rs @@ -70,36 +70,27 @@ impl LightClientOptimisticUpdate { .fork_name(chain_spec) .map_err(|_| Error::InconsistentFork)? { - ForkName::Altair | ForkName::Merge => { - let optimistic_update = LightClientOptimisticUpdateAltair { - attested_header: LightClientHeaderAltair::block_to_light_client_header( - attested_block, - )?, - sync_aggregate, - signature_slot, - }; - Self::Altair(optimistic_update) - } - ForkName::Capella => { - let optimistic_update = LightClientOptimisticUpdateCapella { - attested_header: LightClientHeaderCapella::block_to_light_client_header( - attested_block, - )?, - sync_aggregate, - signature_slot, - }; - Self::Capella(optimistic_update) - } - ForkName::Deneb => { - let optimistic_update = LightClientOptimisticUpdateDeneb { - attested_header: LightClientHeaderDeneb::block_to_light_client_header( - attested_block, - )?, - sync_aggregate, - signature_slot, - }; - Self::Deneb(optimistic_update) - } + ForkName::Altair | ForkName::Merge => Self::Altair(LightClientOptimisticUpdateAltair { + attested_header: LightClientHeaderAltair::block_to_light_client_header( + attested_block, + )?, + sync_aggregate, + signature_slot, + }), + ForkName::Capella => Self::Capella(LightClientOptimisticUpdateCapella { + attested_header: LightClientHeaderCapella::block_to_light_client_header( + attested_block, + )?, + sync_aggregate, + signature_slot, + }), + ForkName::Deneb | ForkName::Electra => Self::Deneb(LightClientOptimisticUpdateDeneb { + attested_header: LightClientHeaderDeneb::block_to_light_client_header( + attested_block, + )?, + sync_aggregate, + signature_slot, + }), ForkName::Base => return Err(Error::AltairForkNotActive), }; @@ -130,16 +121,13 @@ impl LightClientOptimisticUpdate { pub fn from_ssz_bytes(bytes: &[u8], fork_name: ForkName) -> Result { let optimistic_update = match fork_name { ForkName::Altair | ForkName::Merge => { - let optimistic_update = LightClientOptimisticUpdateAltair::from_ssz_bytes(bytes)?; - Self::Altair(optimistic_update) + Self::Altair(LightClientOptimisticUpdateAltair::from_ssz_bytes(bytes)?) } ForkName::Capella => { - let optimistic_update = LightClientOptimisticUpdateCapella::from_ssz_bytes(bytes)?; - Self::Capella(optimistic_update) + Self::Capella(LightClientOptimisticUpdateCapella::from_ssz_bytes(bytes)?) } - ForkName::Deneb => { - let optimistic_update = LightClientOptimisticUpdateDeneb::from_ssz_bytes(bytes)?; - Self::Deneb(optimistic_update) + ForkName::Deneb | ForkName::Electra => { + Self::Deneb(LightClientOptimisticUpdateDeneb::from_ssz_bytes(bytes)?) } ForkName::Base => { return Err(ssz::DecodeError::BytesInvalid(format!( @@ -158,14 +146,14 @@ impl ForkVersionDeserialize for LightClientOptimisticUpdate { fork_name: ForkName, ) -> Result { match fork_name { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => Ok( - serde_json::from_value::>(value) - .map_err(serde::de::Error::custom), - )?, ForkName::Base => Err(serde::de::Error::custom(format!( "LightClientOptimisticUpdate failed to deserialize: unsupported fork '{}'", fork_name ))), + _ => Ok( + serde_json::from_value::>(value) + .map_err(serde::de::Error::custom), + )?, } } } diff --git a/consensus/types/src/light_client_update.rs b/consensus/types/src/light_client_update.rs index 09cc1950990..af9cbc16610 100644 --- a/consensus/types/src/light_client_update.rs +++ b/consensus/types/src/light_client_update.rs @@ -129,14 +129,12 @@ impl ForkVersionDeserialize for LightClientUpdate { fork_name: ForkName, ) -> Result { match fork_name { - ForkName::Altair | ForkName::Merge | ForkName::Capella | ForkName::Deneb => { - Ok(serde_json::from_value::>(value) - .map_err(serde::de::Error::custom))? - } ForkName::Base => Err(serde::de::Error::custom(format!( "LightClientUpdate failed to deserialize: unsupported fork '{}'", fork_name ))), + _ => Ok(serde_json::from_value::>(value) + .map_err(serde::de::Error::custom))?, } } } @@ -216,7 +214,7 @@ impl LightClientUpdate { signature_slot: block.slot(), }) } - ForkName::Deneb => { + ForkName::Deneb | ForkName::Electra => { let attested_header = LightClientHeaderDeneb::block_to_light_client_header(attested_block)?; let finalized_header = @@ -239,16 +237,11 @@ impl LightClientUpdate { pub fn from_ssz_bytes(bytes: &[u8], fork_name: ForkName) -> Result { let update = match fork_name { ForkName::Altair | ForkName::Merge => { - let update = LightClientUpdateAltair::from_ssz_bytes(bytes)?; - Self::Altair(update) - } - ForkName::Capella => { - let update = LightClientUpdateCapella::from_ssz_bytes(bytes)?; - Self::Capella(update) + Self::Altair(LightClientUpdateAltair::from_ssz_bytes(bytes)?) } - ForkName::Deneb => { - let update = LightClientUpdateDeneb::from_ssz_bytes(bytes)?; - Self::Deneb(update) + ForkName::Capella => Self::Capella(LightClientUpdateCapella::from_ssz_bytes(bytes)?), + ForkName::Deneb | ForkName::Electra => { + Self::Deneb(LightClientUpdateDeneb::from_ssz_bytes(bytes)?) } ForkName::Base => { return Err(ssz::DecodeError::BytesInvalid(format!( diff --git a/consensus/types/src/payload.rs b/consensus/types/src/payload.rs index 4e83e3abf60..c65ed9366be 100644 --- a/consensus/types/src/payload.rs +++ b/consensus/types/src/payload.rs @@ -82,12 +82,14 @@ pub trait AbstractExecPayload: + TryInto + TryInto + TryInto + + TryInto { type Ref<'a>: ExecPayload + Copy + From<&'a Self::Merge> + From<&'a Self::Capella> - + From<&'a Self::Deneb>; + + From<&'a Self::Deneb> + + From<&'a Self::Electra>; type Merge: OwnedExecPayload + Into @@ -101,10 +103,14 @@ pub trait AbstractExecPayload: + Into + for<'a> From>> + TryFrom>; + type Electra: OwnedExecPayload + + Into + + for<'a> From>> + + TryFrom>; } #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive( Debug, @@ -145,6 +151,8 @@ pub struct FullPayload { pub execution_payload: ExecutionPayloadCapella, #[superstruct(only(Deneb), partial_getter(rename = "execution_payload_deneb"))] pub execution_payload: ExecutionPayloadDeneb, + #[superstruct(only(Electra), partial_getter(rename = "execution_payload_electra"))] + pub execution_payload: ExecutionPayloadElectra, } impl From> for ExecutionPayload { @@ -251,6 +259,9 @@ impl ExecPayload for FullPayload { FullPayload::Deneb(ref inner) => { Ok(inner.execution_payload.withdrawals.tree_hash_root()) } + FullPayload::Electra(ref inner) => { + Ok(inner.execution_payload.withdrawals.tree_hash_root()) + } } } @@ -258,6 +269,7 @@ impl ExecPayload for FullPayload { match self { FullPayload::Merge(_) | FullPayload::Capella(_) => Err(Error::IncorrectStateVariant), FullPayload::Deneb(ref inner) => Ok(inner.execution_payload.blob_gas_used), + FullPayload::Electra(ref inner) => Ok(inner.execution_payload.blob_gas_used), } } @@ -287,6 +299,7 @@ impl FullPayload { ForkName::Merge => Ok(FullPayloadMerge::default().into()), ForkName::Capella => Ok(FullPayloadCapella::default().into()), ForkName::Deneb => Ok(FullPayloadDeneb::default().into()), + ForkName::Electra => Ok(FullPayloadElectra::default().into()), } } } @@ -376,6 +389,9 @@ impl<'b, T: EthSpec> ExecPayload for FullPayloadRef<'b, T> { FullPayloadRef::Deneb(inner) => { Ok(inner.execution_payload.withdrawals.tree_hash_root()) } + FullPayloadRef::Electra(inner) => { + Ok(inner.execution_payload.withdrawals.tree_hash_root()) + } } } @@ -385,6 +401,7 @@ impl<'b, T: EthSpec> ExecPayload for FullPayloadRef<'b, T> { Err(Error::IncorrectStateVariant) } FullPayloadRef::Deneb(inner) => Ok(inner.execution_payload.blob_gas_used), + FullPayloadRef::Electra(inner) => Ok(inner.execution_payload.blob_gas_used), } } @@ -406,6 +423,7 @@ impl AbstractExecPayload for FullPayload { type Merge = FullPayloadMerge; type Capella = FullPayloadCapella; type Deneb = FullPayloadDeneb; + type Electra = FullPayloadElectra; } impl From> for FullPayload { @@ -424,7 +442,7 @@ impl TryFrom> for FullPayload { } #[superstruct( - variants(Merge, Capella, Deneb), + variants(Merge, Capella, Deneb, Electra), variant_attributes( derive( Debug, @@ -464,6 +482,8 @@ pub struct BlindedPayload { pub execution_payload_header: ExecutionPayloadHeaderCapella, #[superstruct(only(Deneb), partial_getter(rename = "execution_payload_deneb"))] pub execution_payload_header: ExecutionPayloadHeaderDeneb, + #[superstruct(only(Electra), partial_getter(rename = "execution_payload_electra"))] + pub execution_payload_header: ExecutionPayloadHeaderElectra, } impl<'a, T: EthSpec> From> for BlindedPayload { @@ -546,6 +566,9 @@ impl ExecPayload for BlindedPayload { Ok(inner.execution_payload_header.withdrawals_root) } BlindedPayload::Deneb(ref inner) => Ok(inner.execution_payload_header.withdrawals_root), + BlindedPayload::Electra(ref inner) => { + Ok(inner.execution_payload_header.withdrawals_root) + } } } @@ -555,6 +578,7 @@ impl ExecPayload for BlindedPayload { Err(Error::IncorrectStateVariant) } BlindedPayload::Deneb(ref inner) => Ok(inner.execution_payload_header.blob_gas_used), + BlindedPayload::Electra(ref inner) => Ok(inner.execution_payload_header.blob_gas_used), } } @@ -643,6 +667,9 @@ impl<'b, T: EthSpec> ExecPayload for BlindedPayloadRef<'b, T> { Ok(inner.execution_payload_header.withdrawals_root) } BlindedPayloadRef::Deneb(inner) => Ok(inner.execution_payload_header.withdrawals_root), + BlindedPayloadRef::Electra(inner) => { + Ok(inner.execution_payload_header.withdrawals_root) + } } } @@ -652,6 +679,7 @@ impl<'b, T: EthSpec> ExecPayload for BlindedPayloadRef<'b, T> { Err(Error::IncorrectStateVariant) } BlindedPayloadRef::Deneb(inner) => Ok(inner.execution_payload_header.blob_gas_used), + BlindedPayloadRef::Electra(inner) => Ok(inner.execution_payload_header.blob_gas_used), } } @@ -944,12 +972,20 @@ impl_exec_payload_for_fork!( ExecutionPayloadDeneb, Deneb ); +impl_exec_payload_for_fork!( + BlindedPayloadElectra, + FullPayloadElectra, + ExecutionPayloadHeaderElectra, + ExecutionPayloadElectra, + Electra +); impl AbstractExecPayload for BlindedPayload { type Ref<'a> = BlindedPayloadRef<'a, T>; type Merge = BlindedPayloadMerge; type Capella = BlindedPayloadCapella; type Deneb = BlindedPayloadDeneb; + type Electra = BlindedPayloadElectra; } impl From> for BlindedPayload { @@ -981,6 +1017,11 @@ impl From> for BlindedPayload { execution_payload_header, }) } + ExecutionPayloadHeader::Electra(execution_payload_header) => { + Self::Electra(BlindedPayloadElectra { + execution_payload_header, + }) + } } } } @@ -997,6 +1038,9 @@ impl From> for ExecutionPayloadHeader { BlindedPayload::Deneb(blinded_payload) => { ExecutionPayloadHeader::Deneb(blinded_payload.execution_payload_header) } + BlindedPayload::Electra(blinded_payload) => { + ExecutionPayloadHeader::Electra(blinded_payload.execution_payload_header) + } } } } diff --git a/consensus/types/src/preset.rs b/consensus/types/src/preset.rs index 63a372ea1c9..28eebce1513 100644 --- a/consensus/types/src/preset.rs +++ b/consensus/types/src/preset.rs @@ -226,6 +226,21 @@ impl DenebPreset { } } +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub struct ElectraPreset { + #[serde(with = "serde_utils::quoted_u64")] + pub electra_placeholder: u64, +} + +impl ElectraPreset { + pub fn from_chain_spec(_spec: &ChainSpec) -> Self { + Self { + electra_placeholder: 0, + } + } +} + #[cfg(test)] mod test { use super::*; @@ -267,6 +282,9 @@ mod test { let deneb: DenebPreset = preset_from_file(&preset_name, "deneb.yaml"); assert_eq!(deneb, DenebPreset::from_chain_spec::(&spec)); + + let electra: ElectraPreset = preset_from_file(&preset_name, "electra.yaml"); + assert_eq!(electra, ElectraPreset::from_chain_spec::(&spec)); } #[test] diff --git a/consensus/types/src/signed_beacon_block.rs b/consensus/types/src/signed_beacon_block.rs index 4914c1d29aa..da4ac392362 100644 --- a/consensus/types/src/signed_beacon_block.rs +++ b/consensus/types/src/signed_beacon_block.rs @@ -37,7 +37,7 @@ impl From for Hash256 { /// A `BeaconBlock` and a signature from its proposer. #[superstruct( - variants(Base, Altair, Merge, Capella, Deneb), + variants(Base, Altair, Merge, Capella, Deneb, Electra), variant_attributes( derive( Debug, @@ -78,6 +78,8 @@ pub struct SignedBeaconBlock = FullP pub message: BeaconBlockCapella, #[superstruct(only(Deneb), partial_getter(rename = "message_deneb"))] pub message: BeaconBlockDeneb, + #[superstruct(only(Electra), partial_getter(rename = "message_electra"))] + pub message: BeaconBlockElectra, pub signature: Signature, } @@ -157,6 +159,9 @@ impl> SignedBeaconBlock BeaconBlock::Deneb(message) => { SignedBeaconBlock::Deneb(SignedBeaconBlockDeneb { message, signature }) } + BeaconBlock::Electra(message) => { + SignedBeaconBlock::Electra(SignedBeaconBlockElectra { message, signature }) + } } } @@ -467,6 +472,62 @@ impl SignedBeaconBlockDeneb> { } } +impl SignedBeaconBlockElectra> { + pub fn into_full_block( + self, + execution_payload: ExecutionPayloadElectra, + ) -> SignedBeaconBlockElectra> { + let SignedBeaconBlockElectra { + message: + BeaconBlockElectra { + slot, + proposer_index, + parent_root, + state_root, + body: + BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings, + attester_slashings, + attestations, + deposits, + voluntary_exits, + sync_aggregate, + execution_payload: BlindedPayloadElectra { .. }, + bls_to_execution_changes, + blob_kzg_commitments, + }, + }, + signature, + } = self; + SignedBeaconBlockElectra { + message: BeaconBlockElectra { + slot, + proposer_index, + parent_root, + state_root, + body: BeaconBlockBodyElectra { + randao_reveal, + eth1_data, + graffiti, + proposer_slashings, + attester_slashings, + attestations, + deposits, + voluntary_exits, + sync_aggregate, + execution_payload: FullPayloadElectra { execution_payload }, + bls_to_execution_changes, + blob_kzg_commitments, + }, + }, + signature, + } + } +} + impl SignedBeaconBlock> { pub fn try_into_full_block( self, @@ -484,11 +545,15 @@ impl SignedBeaconBlock> { (SignedBeaconBlock::Deneb(block), Some(ExecutionPayload::Deneb(payload))) => { SignedBeaconBlock::Deneb(block.into_full_block(payload)) } + (SignedBeaconBlock::Electra(block), Some(ExecutionPayload::Electra(payload))) => { + SignedBeaconBlock::Electra(block.into_full_block(payload)) + } // avoid wildcard matching forks so that compiler will // direct us here when a new fork has been added (SignedBeaconBlock::Merge(_), _) => return None, (SignedBeaconBlock::Capella(_), _) => return None, (SignedBeaconBlock::Deneb(_), _) => return None, + (SignedBeaconBlock::Electra(_), _) => return None, }; Some(full_block) } @@ -631,6 +696,9 @@ pub mod ssz_tagged_signed_beacon_block { ForkName::Deneb => Ok(SignedBeaconBlock::Deneb( SignedBeaconBlockDeneb::from_ssz_bytes(body)?, )), + ForkName::Electra => Ok(SignedBeaconBlock::Electra( + SignedBeaconBlockElectra::from_ssz_bytes(body)?, + )), } } } @@ -722,7 +790,14 @@ mod test { BeaconBlock::Capella(BeaconBlockCapella::empty(spec)), sig.clone(), ), - SignedBeaconBlock::from_block(BeaconBlock::Deneb(BeaconBlockDeneb::empty(spec)), sig), + SignedBeaconBlock::from_block( + BeaconBlock::Deneb(BeaconBlockDeneb::empty(spec)), + sig.clone(), + ), + SignedBeaconBlock::from_block( + BeaconBlock::Electra(BeaconBlockElectra::empty(spec)), + sig, + ), ]; for block in blocks { diff --git a/consensus/types/src/voluntary_exit.rs b/consensus/types/src/voluntary_exit.rs index a24f7376a1b..74175423e34 100644 --- a/consensus/types/src/voluntary_exit.rs +++ b/consensus/types/src/voluntary_exit.rs @@ -46,7 +46,7 @@ impl VoluntaryExit { spec.fork_version_for_name(fork_name) } // EIP-7044 - ForkName::Deneb => spec.fork_version_for_name(ForkName::Capella), + ForkName::Deneb | ForkName::Electra => spec.fork_version_for_name(ForkName::Capella), }; let domain = spec.compute_domain(Domain::VoluntaryExit, fork_version, genesis_validators_root); diff --git a/lcli/src/create_payload_header.rs b/lcli/src/create_payload_header.rs index 5c96035851e..7706aa5a2a6 100644 --- a/lcli/src/create_payload_header.rs +++ b/lcli/src/create_payload_header.rs @@ -6,7 +6,7 @@ use std::io::Write; use std::time::{SystemTime, UNIX_EPOCH}; use types::{ EthSpec, ExecutionPayloadHeader, ExecutionPayloadHeaderCapella, ExecutionPayloadHeaderDeneb, - ExecutionPayloadHeaderMerge, ForkName, + ExecutionPayloadHeaderElectra, ExecutionPayloadHeaderMerge, ForkName, }; pub fn run(matches: &ArgMatches) -> Result<(), String> { @@ -48,6 +48,14 @@ pub fn run(matches: &ArgMatches) -> Result<(), String> { prev_randao: eth1_block_hash.into_root(), ..ExecutionPayloadHeaderDeneb::default() }), + ForkName::Electra => ExecutionPayloadHeader::Electra(ExecutionPayloadHeaderElectra { + gas_limit, + base_fee_per_gas, + timestamp: genesis_time, + block_hash: eth1_block_hash, + prev_randao: eth1_block_hash.into_root(), + ..ExecutionPayloadHeaderElectra::default() + }), }; let mut file = File::create(file_name).map_err(|_| "Unable to create file".to_string())?; diff --git a/lcli/src/main.rs b/lcli/src/main.rs index 17fafe6ec1e..e1472dd118f 100644 --- a/lcli/src/main.rs +++ b/lcli/src/main.rs @@ -433,7 +433,7 @@ fn main() { .takes_value(true) .default_value("bellatrix") .help("The fork for which the execution payload header should be created.") - .possible_values(&["merge", "bellatrix", "capella", "deneb"]) + .possible_values(&["merge", "bellatrix", "capella", "deneb", "electra"]) ) ) .subcommand( @@ -597,7 +597,7 @@ fn main() { .value_name("EPOCH") .takes_value(true) .help( - "The epoch at which to enable the Merge hard fork", + "The epoch at which to enable the Bellatrix hard fork", ), ) .arg( @@ -615,7 +615,16 @@ fn main() { .value_name("EPOCH") .takes_value(true) .help( - "The epoch at which to enable the deneb hard fork", + "The epoch at which to enable the Deneb hard fork", + ), + ) + .arg( + Arg::with_name("electra-fork-epoch") + .long("electra-fork-epoch") + .value_name("EPOCH") + .takes_value(true) + .help( + "The epoch at which to enable the Electra hard fork", ), ) .arg( @@ -946,6 +955,14 @@ fn main() { .help("The payload timestamp that enables Cancun. No default is provided \ until Cancun is triggered on mainnet.") ) + .arg( + Arg::with_name("prague-time") + .long("prague-time") + .value_name("UNIX_TIMESTAMP") + .takes_value(true) + .help("The payload timestamp that enables Prague. No default is provided \ + until Prague is triggered on mainnet.") + ) ) .get_matches(); diff --git a/lcli/src/mock_el.rs b/lcli/src/mock_el.rs index 094e23c3b40..83ab3ea427a 100644 --- a/lcli/src/mock_el.rs +++ b/lcli/src/mock_el.rs @@ -18,6 +18,7 @@ pub fn run(mut env: Environment, matches: &ArgMatches) -> Result< let all_payloads_valid: bool = parse_required(matches, "all-payloads-valid")?; let shanghai_time = parse_required(matches, "shanghai-time")?; let cancun_time = parse_optional(matches, "cancun-time")?; + let prague_time = parse_optional(matches, "prague-time")?; let handle = env.core_context().executor.handle().unwrap(); let spec = &T::default_spec(); @@ -35,6 +36,7 @@ pub fn run(mut env: Environment, matches: &ArgMatches) -> Result< terminal_block_hash: spec.terminal_block_hash, shanghai_time: Some(shanghai_time), cancun_time, + prague_time, }; let kzg = None; let server: MockServer = MockServer::new_with_config(&handle, config, kzg); diff --git a/lcli/src/new_testnet.rs b/lcli/src/new_testnet.rs index 47db1036d98..aa0997729cd 100644 --- a/lcli/src/new_testnet.rs +++ b/lcli/src/new_testnet.rs @@ -11,6 +11,7 @@ use ssz::Encode; use state_processing::process_activations; use state_processing::upgrade::{ upgrade_to_altair, upgrade_to_bellatrix, upgrade_to_capella, upgrade_to_deneb, + upgrade_to_electra, }; use std::fs::File; use std::io::Read; @@ -21,8 +22,8 @@ use types::ExecutionBlockHash; use types::{ test_utils::generate_deterministic_keypairs, Address, BeaconState, ChainSpec, Config, Epoch, Eth1Data, EthSpec, ExecutionPayloadHeader, ExecutionPayloadHeaderCapella, - ExecutionPayloadHeaderDeneb, ExecutionPayloadHeaderMerge, ForkName, Hash256, Keypair, - PublicKey, Validator, + ExecutionPayloadHeaderDeneb, ExecutionPayloadHeaderElectra, ExecutionPayloadHeaderMerge, + ForkName, Hash256, Keypair, PublicKey, Validator, }; pub fn run(testnet_dir_path: PathBuf, matches: &ArgMatches) -> Result<(), String> { @@ -91,6 +92,10 @@ pub fn run(testnet_dir_path: PathBuf, matches: &ArgMatches) -> Resul spec.deneb_fork_epoch = Some(fork_epoch); } + if let Some(fork_epoch) = parse_optional(matches, "electra-fork-epoch")? { + spec.electra_fork_epoch = Some(fork_epoch); + } + if let Some(ttd) = parse_optional(matches, "ttd")? { spec.terminal_total_difficulty = ttd; } @@ -121,6 +126,10 @@ pub fn run(testnet_dir_path: PathBuf, matches: &ArgMatches) -> Resul ExecutionPayloadHeaderDeneb::::from_ssz_bytes(bytes.as_slice()) .map(ExecutionPayloadHeader::Deneb) } + ForkName::Electra => { + ExecutionPayloadHeaderElectra::::from_ssz_bytes(bytes.as_slice()) + .map(ExecutionPayloadHeader::Electra) + } } .map_err(|e| format!("SSZ decode failed: {:?}", e)) }) @@ -293,7 +302,7 @@ fn initialize_state_with_validators( state.fork_mut().previous_version = spec.altair_fork_version; } - // Similarly, perform an upgrade to the merge if configured from genesis. + // Similarly, perform an upgrade to Bellatrix if configured from genesis. if spec .bellatrix_fork_epoch .map_or(false, |fork_epoch| fork_epoch == T::genesis_epoch()) @@ -312,13 +321,14 @@ fn initialize_state_with_validators( } } + // Similarly, perform an upgrade to Capella if configured from genesis. if spec .capella_fork_epoch .map_or(false, |fork_epoch| fork_epoch == T::genesis_epoch()) { upgrade_to_capella(&mut state, spec).unwrap(); - // Remove intermediate fork from `state.fork`. + // Remove intermediate Bellatrix fork from `state.fork`. state.fork_mut().previous_version = spec.capella_fork_version; // Override latest execution payload header. @@ -330,13 +340,14 @@ fn initialize_state_with_validators( } } + // Similarly, perform an upgrade to Deneb if configured from genesis. if spec .deneb_fork_epoch .map_or(false, |fork_epoch| fork_epoch == T::genesis_epoch()) { upgrade_to_deneb(&mut state, spec).unwrap(); - // Remove intermediate fork from `state.fork`. + // Remove intermediate Capella fork from `state.fork`. state.fork_mut().previous_version = spec.deneb_fork_version; // Override latest execution payload header. @@ -348,6 +359,25 @@ fn initialize_state_with_validators( } } + // Similarly, perform an upgrade to Electra if configured from genesis. + if spec + .electra_fork_epoch + .map_or(false, |fork_epoch| fork_epoch == T::genesis_epoch()) + { + upgrade_to_electra(&mut state, spec).unwrap(); + + // Remove intermediate Deneb fork from `state.fork`. + state.fork_mut().previous_version = spec.electra_fork_version; + + // Override latest execution payload header. + // See https://github.com/ethereum/consensus-specs/blob/v1.1.0/specs/bellatrix/beacon-chain.md#testing + if let ExecutionPayloadHeader::Electra(ref header) = execution_payload_header { + *state + .latest_execution_payload_header_electra_mut() + .or(Err("mismatched fork".to_string()))? = header.clone(); + } + } + // Now that we have our validators, initialize the caches (including the committees) state.build_caches(spec).unwrap(); diff --git a/lcli/src/parse_ssz.rs b/lcli/src/parse_ssz.rs index 453169cdc51..82158c1456e 100644 --- a/lcli/src/parse_ssz.rs +++ b/lcli/src/parse_ssz.rs @@ -81,6 +81,11 @@ pub fn run_parse_ssz( "SignedBeaconBlockDeneb" => { decode_and_print(&bytes, SignedBeaconBlockDeneb::::from_ssz_bytes, format)? } + "SignedBeaconBlockElectra" => decode_and_print( + &bytes, + SignedBeaconBlockElectra::::from_ssz_bytes, + format, + )?, "BeaconState" => decode_and_print::>( &bytes, |bytes| BeaconState::from_ssz_bytes(bytes, spec), @@ -101,6 +106,9 @@ pub fn run_parse_ssz( "BeaconStateDeneb" => { decode_and_print(&bytes, BeaconStateDeneb::::from_ssz_bytes, format)? } + "BeaconStateElectra" => { + decode_and_print(&bytes, BeaconStateElectra::::from_ssz_bytes, format)? + } "BlobSidecar" => decode_and_print(&bytes, BlobSidecar::::from_ssz_bytes, format)?, other => return Err(format!("Unknown type: {}", other)), }; diff --git a/scripts/local_testnet/genesis.json b/scripts/local_testnet/genesis.json index eda3b312f68..26003bed5df 100644 --- a/scripts/local_testnet/genesis.json +++ b/scripts/local_testnet/genesis.json @@ -14,6 +14,7 @@ "mergeNetsplitBlock": 0, "shanghaiTime": 0, "cancunTime": 0, + "pragueTime": 0, "terminalTotalDifficulty": 0, "terminalTotalDifficultyPassed": true }, diff --git a/scripts/local_testnet/setup.sh b/scripts/local_testnet/setup.sh index d7a6016aa80..419cba19ed9 100755 --- a/scripts/local_testnet/setup.sh +++ b/scripts/local_testnet/setup.sh @@ -29,6 +29,7 @@ lcli \ --bellatrix-fork-epoch $BELLATRIX_FORK_EPOCH \ --capella-fork-epoch $CAPELLA_FORK_EPOCH \ --deneb-fork-epoch $DENEB_FORK_EPOCH \ + --electra-fork-epoch $ELECTRA_FORK_EPOCH \ --ttd $TTD \ --eth1-block-hash $ETH1_BLOCK_HASH \ --eth1-id $CHAIN_ID \ diff --git a/scripts/local_testnet/setup_time.sh b/scripts/local_testnet/setup_time.sh index 21a8ae7ac15..36f7fc4e997 100755 --- a/scripts/local_testnet/setup_time.sh +++ b/scripts/local_testnet/setup_time.sh @@ -28,5 +28,8 @@ sed -i 's/"shanghaiTime".*$/"shanghaiTime": '"$CAPELLA_TIME"',/g' $genesis_file CANCUN_TIME=$((GENESIS_TIME + (DENEB_FORK_EPOCH * $SLOT_PER_EPOCH * SECONDS_PER_SLOT))) echo $CANCUN_TIME sed -i 's/"cancunTime".*$/"cancunTime": '"$CANCUN_TIME"',/g' $genesis_file +PRAGUE_TIME=$((GENESIS_TIME + (ELECTRA_FORK_EPOCH * $SLOT_PER_EPOCH * SECONDS_PER_SLOT))) +echo $PRAGUE_TIME +sed -i 's/"pragueTime".*$/"pragueTime": '"$PRAGUE_TIME"',/g' $genesis_file cat $genesis_file diff --git a/scripts/local_testnet/start_local_testnet.sh b/scripts/local_testnet/start_local_testnet.sh index 512b1e98d16..77422095130 100755 --- a/scripts/local_testnet/start_local_testnet.sh +++ b/scripts/local_testnet/start_local_testnet.sh @@ -103,7 +103,7 @@ echo "executing: ./setup.sh >> $LOG_DIR/setup.log" ./setup.sh >> $LOG_DIR/setup.log 2>&1 # Call setup_time.sh to update future hardforks time in the EL genesis file based on the CL genesis time -./setup_time.sh genesis.json +./setup_time.sh $genesis_file # Delay to let boot_enr.yaml to be created execute_command_add_PID bootnode.log ./bootnode.sh @@ -134,6 +134,7 @@ sleeping 20 # Reset the `genesis.json` config file fork times. sed -i 's/"shanghaiTime".*$/"shanghaiTime": 0,/g' $genesis_file sed -i 's/"cancunTime".*$/"cancunTime": 0,/g' $genesis_file +sed -i 's/"pragueTime".*$/"pragueTime": 0,/g' $genesis_file for (( bn=1; bn<=$BN_COUNT; bn++ )); do secret=$DATADIR/geth_datadir$bn/geth/jwtsecret diff --git a/scripts/local_testnet/vars.env b/scripts/local_testnet/vars.env index 31274d2c575..9bdec71ff78 100644 --- a/scripts/local_testnet/vars.env +++ b/scripts/local_testnet/vars.env @@ -44,8 +44,9 @@ CHAIN_ID=4242 # Hard fork configuration ALTAIR_FORK_EPOCH=0 BELLATRIX_FORK_EPOCH=0 -CAPELLA_FORK_EPOCH=1 -DENEB_FORK_EPOCH=2 +CAPELLA_FORK_EPOCH=0 +DENEB_FORK_EPOCH=1 +ELECTRA_FORK_EPOCH=9999999 TTD=0 diff --git a/scripts/tests/vars.env b/scripts/tests/vars.env index ffe7ac4aecd..4d8f9db64e4 100644 --- a/scripts/tests/vars.env +++ b/scripts/tests/vars.env @@ -43,6 +43,7 @@ ALTAIR_FORK_EPOCH=0 BELLATRIX_FORK_EPOCH=0 CAPELLA_FORK_EPOCH=0 DENEB_FORK_EPOCH=0 +ELECTRA_FORK_EPOCH=18446744073709551615 TTD=0 @@ -63,4 +64,3 @@ BN_ARGS="" # Enable doppelganger detection VC_ARGS=" --enable-doppelganger-protection " - diff --git a/testing/ef_tests/src/cases/common.rs b/testing/ef_tests/src/cases/common.rs index d75880b2969..342a48ba46c 100644 --- a/testing/ef_tests/src/cases/common.rs +++ b/testing/ef_tests/src/cases/common.rs @@ -66,6 +66,7 @@ pub fn previous_fork(fork_name: ForkName) -> ForkName { ForkName::Merge => ForkName::Altair, ForkName::Capella => ForkName::Merge, ForkName::Deneb => ForkName::Capella, + ForkName::Electra => ForkName::Deneb, } } diff --git a/testing/ef_tests/src/cases/epoch_processing.rs b/testing/ef_tests/src/cases/epoch_processing.rs index c3b03ae1fee..bf12ce013e5 100644 --- a/testing/ef_tests/src/cases/epoch_processing.rs +++ b/testing/ef_tests/src/cases/epoch_processing.rs @@ -102,7 +102,8 @@ impl EpochTransition for JustificationAndFinalization { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => { + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => { let justification_and_finalization_state = altair::process_justification_and_finalization( state, @@ -126,7 +127,8 @@ impl EpochTransition for RewardsAndPenalties { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => altair::process_rewards_and_penalties( + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => altair::process_rewards_and_penalties( state, &altair::ParticipationCache::new(state, spec).unwrap(), spec, @@ -156,7 +158,8 @@ impl EpochTransition for Slashings { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => { + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => { process_slashings( state, altair::ParticipationCache::new(state, spec) @@ -208,7 +211,7 @@ impl EpochTransition for HistoricalRootsUpdate { impl EpochTransition for HistoricalSummariesUpdate { fn run(state: &mut BeaconState, _spec: &ChainSpec) -> Result<(), EpochProcessingError> { match state { - BeaconState::Capella(_) | BeaconState::Deneb(_) => { + BeaconState::Capella(_) | BeaconState::Deneb(_) | BeaconState::Electra(_) => { process_historical_summaries_update(state) } _ => Ok(()), @@ -233,7 +236,8 @@ impl EpochTransition for SyncCommitteeUpdates { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => altair::process_sync_committee_updates(state, spec), + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => altair::process_sync_committee_updates(state, spec), } } } @@ -245,7 +249,8 @@ impl EpochTransition for InactivityUpdates { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => altair::process_inactivity_updates( + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => altair::process_inactivity_updates( state, &altair::ParticipationCache::new(state, spec).unwrap(), spec, @@ -261,7 +266,8 @@ impl EpochTransition for ParticipationFlagUpdates { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => altair::process_participation_flag_updates(state), + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => altair::process_participation_flag_updates(state), } } } @@ -312,7 +318,7 @@ impl> Case for EpochProcessing { T::name() != "participation_record_updates" && T::name() != "historical_summaries_update" } - ForkName::Capella | ForkName::Deneb => { + ForkName::Capella | ForkName::Deneb | ForkName::Electra => { T::name() != "participation_record_updates" && T::name() != "historical_roots_update" } diff --git a/testing/ef_tests/src/cases/fork.rs b/testing/ef_tests/src/cases/fork.rs index 58498ca62bf..be8a344a35a 100644 --- a/testing/ef_tests/src/cases/fork.rs +++ b/testing/ef_tests/src/cases/fork.rs @@ -5,6 +5,7 @@ use crate::decode::{ssz_decode_state, yaml_decode_file}; use serde::Deserialize; use state_processing::upgrade::{ upgrade_to_altair, upgrade_to_bellatrix, upgrade_to_capella, upgrade_to_deneb, + upgrade_to_electra, }; use types::BeaconState; @@ -65,6 +66,7 @@ impl Case for ForkTest { ForkName::Merge => upgrade_to_bellatrix(&mut result_state, spec).map(|_| result_state), ForkName::Capella => upgrade_to_capella(&mut result_state, spec).map(|_| result_state), ForkName::Deneb => upgrade_to_deneb(&mut result_state, spec).map(|_| result_state), + ForkName::Electra => upgrade_to_electra(&mut result_state, spec).map(|_| result_state), }; compare_beacon_state_results_without_caches(&mut result, &mut expected) diff --git a/testing/ef_tests/src/cases/merkle_proof_validity.rs b/testing/ef_tests/src/cases/merkle_proof_validity.rs index 5553df588b6..a2e831ade59 100644 --- a/testing/ef_tests/src/cases/merkle_proof_validity.rs +++ b/testing/ef_tests/src/cases/merkle_proof_validity.rs @@ -2,7 +2,9 @@ use super::*; use crate::decode::{ssz_decode_file, ssz_decode_state, yaml_decode_file}; use serde::Deserialize; use tree_hash::Hash256; -use types::{BeaconBlockBody, BeaconBlockBodyDeneb, BeaconState}; +use types::{ + BeaconBlockBody, BeaconBlockBodyDeneb, BeaconBlockBodyElectra, BeaconState, FullPayload, +}; #[derive(Debug, Clone, Deserialize)] pub struct Metadata { @@ -92,7 +94,7 @@ pub struct KzgInclusionMerkleProofValidity { impl LoadCase for KzgInclusionMerkleProofValidity { fn load_from_dir(path: &Path, fork_name: ForkName) -> Result { - let block = match fork_name { + let block: BeaconBlockBody> = match fork_name { ForkName::Base | ForkName::Altair | ForkName::Merge | ForkName::Capella => { return Err(Error::InternalError(format!( "KZG inclusion merkle proof validity test skipped for {:?}", @@ -100,7 +102,11 @@ impl LoadCase for KzgInclusionMerkleProofValidity { ))) } ForkName::Deneb => { - ssz_decode_file::>(&path.join("object.ssz_snappy"))? + ssz_decode_file::>(&path.join("object.ssz_snappy"))?.into() + } + ForkName::Electra => { + ssz_decode_file::>(&path.join("object.ssz_snappy"))? + .into() } }; let merkle_proof = yaml_decode_file(&path.join("proof.yaml"))?; @@ -114,7 +120,7 @@ impl LoadCase for KzgInclusionMerkleProofValidity { Ok(Self { metadata, - block: block.into(), + block, merkle_proof, }) } diff --git a/testing/ef_tests/src/cases/operations.rs b/testing/ef_tests/src/cases/operations.rs index 40cacb173fb..34919425c40 100644 --- a/testing/ef_tests/src/cases/operations.rs +++ b/testing/ef_tests/src/cases/operations.rs @@ -99,7 +99,8 @@ impl Operation for Attestation { BeaconState::Altair(_) | BeaconState::Merge(_) | BeaconState::Capella(_) - | BeaconState::Deneb(_) => { + | BeaconState::Deneb(_) + | BeaconState::Electra(_) => { initialize_progressive_balances_cache(state, None, spec)?; altair_deneb::process_attestation( state, diff --git a/testing/ef_tests/src/cases/transition.rs b/testing/ef_tests/src/cases/transition.rs index 58e1226b7e6..927589948a2 100644 --- a/testing/ef_tests/src/cases/transition.rs +++ b/testing/ef_tests/src/cases/transition.rs @@ -53,6 +53,13 @@ impl LoadCase for TransitionTest { spec.capella_fork_epoch = Some(Epoch::new(0)); spec.deneb_fork_epoch = Some(metadata.fork_epoch); } + ForkName::Electra => { + spec.altair_fork_epoch = Some(Epoch::new(0)); + spec.bellatrix_fork_epoch = Some(Epoch::new(0)); + spec.capella_fork_epoch = Some(Epoch::new(0)); + spec.deneb_fork_epoch = Some(Epoch::new(0)); + spec.electra_fork_epoch = Some(metadata.fork_epoch); + } } // Load blocks diff --git a/testing/ef_tests/src/handler.rs b/testing/ef_tests/src/handler.rs index 0295ff1bd49..59b5cb6ba74 100644 --- a/testing/ef_tests/src/handler.rs +++ b/testing/ef_tests/src/handler.rs @@ -18,13 +18,20 @@ pub trait Handler { fn handler_name(&self) -> String; + // Add forks here to exclude them from EF spec testing. Helpful for adding future or + // unspecified forks. + // TODO(electra): Enable Electra once spec tests are available. + fn disabled_forks(&self) -> Vec { + vec![ForkName::Electra] + } + fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool { Self::Case::is_enabled_for_fork(fork_name) } fn run(&self) { for fork_name in ForkName::list_all() { - if self.is_enabled_for_fork(fork_name) { + if !self.disabled_forks().contains(&fork_name) && self.is_enabled_for_fork(fork_name) { self.run_for_fork(fork_name) } } diff --git a/validator_client/src/beacon_node_fallback.rs b/validator_client/src/beacon_node_fallback.rs index 23458d327b9..7e3a876c5a9 100644 --- a/validator_client/src/beacon_node_fallback.rs +++ b/validator_client/src/beacon_node_fallback.rs @@ -306,6 +306,14 @@ impl CandidateBeaconNode { "endpoint_deneb_fork_epoch" => ?beacon_node_spec.deneb_fork_epoch, "hint" => UPDATE_REQUIRED_LOG_HINT, ); + } else if beacon_node_spec.electra_fork_epoch != spec.electra_fork_epoch { + warn!( + log, + "Beacon node has mismatched Electra fork epoch"; + "endpoint" => %self.beacon_node, + "endpoint_electra_fork_epoch" => ?beacon_node_spec.electra_fork_epoch, + "hint" => UPDATE_REQUIRED_LOG_HINT, + ); } Ok(()) diff --git a/validator_client/src/http_api/test_utils.rs b/validator_client/src/http_api/test_utils.rs index 49ea4ef5b11..8bb56e87a32 100644 --- a/validator_client/src/http_api/test_utils.rs +++ b/validator_client/src/http_api/test_utils.rs @@ -250,9 +250,9 @@ impl ApiTester { pub async fn test_get_lighthouse_spec(self) -> Self { let result = self .client - .get_lighthouse_spec::() + .get_lighthouse_spec::() .await - .map(|res| ConfigAndPreset::Capella(res.data)) + .map(|res| ConfigAndPreset::Electra(res.data)) .unwrap(); let expected = ConfigAndPreset::from_chain_spec::(&E::default_spec(), None); diff --git a/validator_client/src/http_api/tests.rs b/validator_client/src/http_api/tests.rs index ba46ea63b36..ce1937d4379 100644 --- a/validator_client/src/http_api/tests.rs +++ b/validator_client/src/http_api/tests.rs @@ -210,9 +210,9 @@ impl ApiTester { pub async fn test_get_lighthouse_spec(self) -> Self { let result = self .client - .get_lighthouse_spec::() + .get_lighthouse_spec::() .await - .map(|res| ConfigAndPreset::Deneb(res.data)) + .map(|res| ConfigAndPreset::Electra(res.data)) .unwrap(); let expected = ConfigAndPreset::from_chain_spec::(&E::default_spec(), None); diff --git a/validator_client/src/signing_method/web3signer.rs b/validator_client/src/signing_method/web3signer.rs index d7d74c94487..2de30ab2cf6 100644 --- a/validator_client/src/signing_method/web3signer.rs +++ b/validator_client/src/signing_method/web3signer.rs @@ -28,6 +28,7 @@ pub enum ForkName { Bellatrix, Capella, Deneb, + Electra, } #[derive(Debug, PartialEq, Serialize)] @@ -101,6 +102,11 @@ impl<'a, T: EthSpec, Payload: AbstractExecPayload> Web3SignerObject<'a, T, Pa block: None, block_header: Some(block.block_header()), }), + BeaconBlock::Electra(_) => Ok(Web3SignerObject::BeaconBlock { + version: ForkName::Electra, + block: None, + block_header: Some(block.block_header()), + }), } } diff --git a/validator_client/src/validator_store.rs b/validator_client/src/validator_store.rs index 62805710e49..0a00dad9beb 100644 --- a/validator_client/src/validator_store.rs +++ b/validator_client/src/validator_store.rs @@ -369,7 +369,7 @@ impl ValidatorStore { } } // EIP-7044 - ForkName::Deneb => SigningContext { + ForkName::Deneb | ForkName::Electra => SigningContext { domain, epoch: signing_epoch, fork: Fork {