diff --git a/CLAUDE.md b/CLAUDE.md index 838158e00..fbae4997b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -902,11 +902,13 @@ transitions are in `ethlambda-types`, per the section above. Nothing above validation, deneb's and fulu's data availability, and gloas's payload-aware suites. - **EIP-8483 and PQ** (consensus-specs' `pq` branch feature forks, pinned at - `4c296784`, pq-devnet-1's spec: staggered aggregators of `4595f0fc`, VRF + `66f143ec`, pq-devnet-2's spec: staggered aggregators of `4595f0fc`, VRF secrets of `b5d422b2`, `X_MAX_COMMITTEE_COUNT_PER_SLOT` of `af898d07` (one per process, selected with the preset: absent it is the preset's `MAX_COMMITTEES_PER_SLOT_PQ`, above that it is refused at startup), - keccak256 legacy keys of `4c296784`) are `ForkName::Eip8483` and `ForkName::Pq` after gloas, selectors + keccak256 legacy keys of `4c296784`, preregistrations that expire by epoch + and are never replaced in place of `c8608e56`, EIP-8483 registrations + removed on exit of `a0d94fdc`, `X_COMMITTEE_COUNTS` of `66f143ec`) are `ForkName::Eip8483` and `ForkName::Pq` after gloas, selectors 8 and 9, implemented in the state transition and fork choice (`stf/{eip8483,pq}.rs`, `stf/epoch/pq.rs`, `helpers/pq.rs`, `upgrade_to_*`) and PQ's gossip rules (`gossip/pq.rs`, `p2p/src/beacon/pq.rs`: a PQ digest's diff --git a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs index e48768438..4bd215bac 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs @@ -872,6 +872,33 @@ mod tests { )); } + /// A slot whose start time does not fit in a `u64` of milliseconds is in + /// the future and nothing else (consensus-specs #5895): the saturating + /// slot start reads as later than any clock, so no rule takes such a + /// message for a current or past one. + #[test] + fn a_far_future_slot_is_future_and_neither_current_nor_past() { + use super::execution_payload_bid::is_current_or_next_slot; + use super::proposer_preferences::is_past_slot; + let config = Config { + genesis_time: 100, + ..Config::mainnet() + }; + for now_ms in [0, 100_000, 100_000 + 7 * config.slot_duration_ms] { + for slot in [ + u64::MAX, + u64::MAX - 1, + u64::MAX / config.slot_duration_ms + 1, + ] { + assert!(is_future_slot(&config, slot, now_ms)); + assert!(!is_past_slot(&config, slot, now_ms)); + assert!(!is_current_slot(&config, slot, now_ms)); + assert!(!is_current_or_next_slot(&config, slot, now_ms)); + } + assert!(is_future_epoch(&config, u64::MAX, now_ms)); + } + } + #[test] fn the_current_slot_holds_within_the_clock_disparity_at_either_edge() { let config = Config { diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index fd5b71bd0..34b667c25 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs @@ -1,6 +1,6 @@ //! Gossip validation for the PQ fork's topics //! (`specs/_features/pq/p2p-interface.md`, consensus-specs' `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! Every topic whose message carries a validator's or builder's signature //! carries an XMSS one instead, at the leaf the fork assigns that message, and diff --git a/crates/blockchain/state_transition/src/beacon/helpers/electra.rs b/crates/blockchain/state_transition/src/beacon/helpers/electra.rs index 893a5e383..dbc92c82a 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/electra.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/electra.rs @@ -767,6 +767,9 @@ pub fn get_next_sync_committee_indices(state: &BeaconState) -> Result = registrations + .iter() + .filter(|registration| registration.validator_index != validator_index) + .cloned() + .collect(); + inner.validator_pq_registrations = kept.into(); +} + +/// `remove_builder_pq_registration` (EIP-8483): the builder counterpart of +/// [`remove_validator_pq_registration`], by public key, since a builder index +/// is reused once its builder has withdrawn. +pub fn remove_builder_pq_registration(state: &mut BeaconState, builder_pubkey: &BlsPubkey) { + let BeaconState::Eip8483(inner) = state else { + return; + }; + let registrations = &inner.builder_pq_registrations; + if !registrations + .iter() + .any(|registration| registration.builder_pubkey == *builder_pubkey) + { + return; + } + let kept: Vec<_> = registrations + .iter() + .filter(|registration| registration.builder_pubkey != *builder_pubkey) + .cloned() + .collect(); + inner.builder_pq_registrations = kept.into(); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index 2c620a99f..86ada6fa7 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs @@ -1,6 +1,6 @@ //! Helpers the PQ fork adds or modifies (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! # Keys //! @@ -508,52 +508,28 @@ pub fn is_valid_indexed_attestation( // Preregistrations // --------------------------------------------------------------------------- -/// The slot of the outstanding parent payload, whose execution requests are -/// the ones being applied: what a preregistration's expiry is compared with. -fn parent_payload_slot(state: &pq::BeaconState) -> Slot { - state.latest_execution_payload_bid.slot -} - -/// `is_active_validator_preregistration`. -pub fn is_active_validator_preregistration( - state: &pq::BeaconState, - preregistration: &pq::ValidatorPreregistration, -) -> bool { - parent_payload_slot(state) < preregistration.expiry_slot -} - -/// `is_active_builder_preregistration`. -pub fn is_active_builder_preregistration( - state: &pq::BeaconState, - preregistration: &pq::BuilderPreregistration, -) -> bool { - parent_payload_slot(state) < preregistration.expiry_slot -} - -/// `get_active_validator_preregistration`. -pub fn get_active_validator_preregistration( - state: &pq::BeaconState, +/// `get_validator_preregistration`: the stored preregistration of `pubkey`. +/// A record binds its key for as long as it is in the state; the epoch +/// transition's sweep is what ends it. +pub fn get_validator_preregistration<'a>( + state: &'a pq::BeaconState, pubkey: &XmssPubkey, -) -> Option { +) -> Option<&'a pq::ValidatorPreregistration> { state .validator_preregistrations .iter() .find(|preregistration| preregistration.pubkey == *pubkey) - .filter(|preregistration| is_active_validator_preregistration(state, preregistration)) - .cloned() } -/// `get_active_builder_preregistration`. -pub fn get_active_builder_preregistration( - state: &pq::BeaconState, +/// `get_builder_preregistration`. +pub fn get_builder_preregistration<'a>( + state: &'a pq::BeaconState, pubkey: &XmssPubkey, -) -> Option { +) -> Option<&'a pq::BuilderPreregistration> { state .builder_preregistrations .iter() .find(|preregistration| preregistration.pubkey == *pubkey) - .filter(|preregistration| is_active_builder_preregistration(state, preregistration)) - .cloned() } /// The PQ state, mutably, or an error naming the function that needs one. diff --git a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs index f4a9bcf7b..cda13d88b 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs @@ -1,13 +1,17 @@ //! EIP-8483's block processing (consensus-specs //! `specs/_features/eip8483/beacon-chain.md`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! Gloas's block processing, with two more execution-layer request lists in //! the parent payload: validators and builders register post-quantum material -//! the PQ fork adopts. Everything but [`apply_parent_execution_payload`] and the -//! two request processors is gloas's own code, reached through the +//! the PQ fork adopts. Everything but the parent payload's two functions and +//! the two request processors is gloas's own code, reached through the //! gloas-family view (`containers::GloasFamily`). //! +//! A registration is removed when its validator or builder initiates an exit +//! (`helpers::mutators::remove_{validator,builder}_pq_registration`, called +//! where gloas's code initiates one), after which it cannot register again. +//! //! # A newer gloas underneath //! //! The `pq` branch builds on a newer gloas than this crate's pin. Its @@ -21,10 +25,11 @@ use crate::beacon::config::Config; use crate::beacon::constants; -use crate::beacon::containers::{BeaconState, eip8483}; +use crate::beacon::containers::{BeaconState, eip8483, gloas}; use crate::beacon::error::{Error, Result, verify}; use crate::beacon::helpers::accessors::{ActiveBalanceCache, PubkeyIndexCache}; -use crate::beacon::helpers::electra::has_execution_withdrawal_credential; +use crate::beacon::helpers::electra::has_compounding_withdrawal_credential; +use crate::beacon::helpers::misc::compute_epoch_at_slot; use crate::beacon::preset; use crate::beacon::primitives::{HashTreeRoot as _, ValidatorIndex}; use crate::beacon::stf::signatures::SignatureBatch; @@ -95,7 +100,14 @@ pub fn process_block( Ok(()) } -/// `process_parent_execution_payload`: gloas's, over EIP-8483's requests. +/// `process_parent_execution_payload` (modified in EIP-8483): gloas's, over +/// EIP-8483's requests. +/// +/// The first block after the fork may build on a full parent from before it, +/// whose bid commits to gloas's `ExecutionRequests`: a type with another +/// root even for the same content, and the upgrade cannot recompute the +/// commitment, since the state holds only the root. Such a parent's requests +/// are verified against the gloas type and carry no PQ registration. pub fn process_parent_execution_payload( state: &mut BeaconState, block: &eip8483::BeaconBlock, @@ -116,9 +128,33 @@ pub fn process_parent_execution_payload( return Ok(()); } + // [New in EIP8483] + let requests_root = if compute_epoch_at_slot(parent_bid.slot) < config.eip8483_fork_epoch { + // Parent was FULL before the fork: its bid commits to the gloas type. + verify( + requests.validator_pq_registrations.is_empty(), + "process_parent_execution_payload: len(requests.validator_pq_registrations) == 0", + )?; + verify( + requests.builder_pq_registrations.is_empty(), + "process_parent_execution_payload: len(requests.builder_pq_registrations) == 0", + )?; + gloas::ExecutionRequests { + deposits: requests.deposits.clone(), + withdrawals: requests.withdrawals.clone(), + consolidations: requests.consolidations.clone(), + builder_deposits: requests.builder_deposits.clone(), + builder_exits: requests.builder_exits.clone(), + } + .hash_tree_root() + } else { + requests.hash_tree_root() + }; + + // Parent was FULL: verify the bid commitment and apply the payload. verify( - requests.hash_tree_root() == parent_bid.execution_requests_root, - "process_parent_execution_payload: hash_tree_root(requests) == parent_bid.execution_requests_root", + requests_root == parent_bid.execution_requests_root, + "process_parent_execution_payload: requests_root == parent_bid.execution_requests_root", )?; apply_parent_execution_payload(state, requests, config, active_balances, pubkey_indices) } @@ -208,10 +244,10 @@ fn eip8483_state<'a>( } /// `process_validator_pq_registration_request`. Invalid requests are ignored. -/// No status is checked, so pending, active, exited and slashed validators can -/// all register, as long as the request comes from their withdrawal address -/// and neither half of its PQ data is registered already, to anyone, -/// themselves included. +/// A pending or active validator with compounding (`0x02`) credentials can +/// register, as long as the request comes from its withdrawal address and the +/// first 32 bytes of its PQ data, the public key, are not registered already, +/// to anyone, itself included. A validator that has initiated an exit cannot. pub fn process_validator_pq_registration_request( state: &mut BeaconState, request: &eip8483::ValidatorPqRegistrationRequest, @@ -225,8 +261,12 @@ pub fn process_validator_pq_registration_request( let validator_index = validator_index as ValidatorIndex; let validator = state.validator(validator_index)?; - // Verify the validator has execution withdrawal credentials. - if !has_execution_withdrawal_credential(validator) { + // Verify the validator has not initiated an exit. + if validator.exit_epoch != constants::FAR_FUTURE_EPOCH { + return Ok(()); + } + // Verify the validator has compounding withdrawal credentials. + if !has_compounding_withdrawal_credential(validator) { return Ok(()); } // Verify the request comes from the validator's withdrawal address. @@ -235,11 +275,12 @@ pub fn process_validator_pq_registration_request( } let inner = eip8483_state(state, "process_validator_pq_registration_request")?; - let (key_half, vrf_half) = request.pq_data.split_at(32); - // Verify the PQ data is not already registered. - if inner.validator_pq_registrations.iter().any(|registration| { - registration.pq_data[..32] == *key_half || registration.pq_data[32..] == *vrf_half - }) { + // Verify the first 32 bytes of the PQ data are not already registered. + if inner + .validator_pq_registrations + .iter() + .any(|registration| registration.pq_data[..32] == request.pq_data[..32]) + { return Ok(()); } @@ -263,8 +304,9 @@ pub fn process_validator_pq_registration_request( } /// `process_builder_pq_registration_request`. Invalid requests are ignored. -/// Active and exited builders can both register, as long as the request comes -/// from their execution address and its PQ data is not registered already. +/// A pending or active builder can register, as long as the request comes +/// from its execution address and its PQ data is not registered already. A +/// builder that has initiated an exit cannot. pub fn process_builder_pq_registration_request( state: &mut BeaconState, request: &eip8483::BuilderPqRegistrationRequest, @@ -278,6 +320,10 @@ pub fn process_builder_pq_registration_request( return Ok(()); }; + // Verify the builder has not initiated an exit. + if builder.withdrawable_epoch != constants::FAR_FUTURE_EPOCH { + return Ok(()); + } // Verify the request comes from the builder's execution address. if builder.execution_address != request.source_address { return Ok(()); @@ -363,3 +409,334 @@ pub fn get_execution_requests_list(requests: &eip8483::ExecutionRequests) -> Vec }) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + use crate::beacon::constants::{ + COMPOUNDING_WITHDRAWAL_PREFIX, ETH1_ADDRESS_WITHDRAWAL_PREFIX, FAR_FUTURE_EPOCH, + }; + use crate::beacon::fork::ForkName; + use crate::beacon::helpers::electra::initiate_validator_exit; + use crate::beacon::helpers::test_state::with_validators_at; + use crate::beacon::primitives::{BlsPubkey, Bytes32, ExecutionAddress, ExecutionBlockHash}; + use crate::beacon::stf::electra::process_consolidation_request; + use crate::beacon::stf::gloas::process_builder_exit_request; + + fn inner(state: &mut BeaconState) -> &mut eip8483::BeaconState { + match state { + BeaconState::Eip8483(inner) => inner, + _ => unreachable!("an EIP-8483 state"), + } + } + + /// Gives validator `index` its own key and credentials of `prefix` paying + /// an address of its own, and returns both. + fn credentialed( + state: &mut BeaconState, + index: u64, + prefix: u8, + ) -> (BlsPubkey, ExecutionAddress) { + let address = ExecutionAddress::repeat_byte(index as u8 + 1); + let pubkey = BlsPubkey([index as u8 + 1; 48]); + let validator = state.validator_mut(index).unwrap(); + validator.pubkey = pubkey; + validator.withdrawal_credentials = Bytes32::ZERO; + validator.withdrawal_credentials.0[0] = prefix; + validator.withdrawal_credentials.0[12..].copy_from_slice(&address.0); + (pubkey, address) + } + + /// PQ data whose key half is `key` and whose other half is `rest`. + fn pq_data(key: u8, rest: u8) -> eip8483::PqData { + let mut data = [rest; 64]; + data[..32].fill(key); + data + } + + fn register(state: &mut BeaconState, index: u64, prefix: u8, data: eip8483::PqData) { + let (validator_pubkey, source_address) = credentialed(state, index, prefix); + let request = eip8483::ValidatorPqRegistrationRequest { + source_address, + validator_pubkey, + pq_data: data, + }; + process_validator_pq_registration_request(state, &request).unwrap(); + } + + fn registered(state: &mut BeaconState) -> Vec<(u64, eip8483::PqData)> { + inner(state) + .validator_pq_registrations + .iter() + .map(|registration| (registration.validator_index, registration.pq_data)) + .collect() + } + + #[test] + fn only_a_compounding_validator_that_has_not_exited_registers() { + let mut state = with_validators_at(ForkName::Eip8483, 8); + // `0x01` credentials are execution credentials, but not compounding. + register( + &mut state, + 0, + ETH1_ADDRESS_WITHDRAWAL_PREFIX, + pq_data(0xa0, 1), + ); + assert!(registered(&mut state).is_empty()); + // An exiting validator cannot register. + state.validator_mut(1).unwrap().exit_epoch = 5; + register( + &mut state, + 1, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa1, 1), + ); + assert!(registered(&mut state).is_empty()); + + register( + &mut state, + 2, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa2, 1), + ); + assert_eq!(registered(&mut state), [(2, pq_data(0xa2, 1))]); + } + + #[test] + fn only_the_first_half_of_the_pq_data_must_be_new() { + let mut state = with_validators_at(ForkName::Eip8483, 8); + register( + &mut state, + 0, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa0, 7), + ); + // A key already registered is refused, to its own validator too. + register( + &mut state, + 1, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa0, 8), + ); + register( + &mut state, + 0, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa0, 9), + ); + assert_eq!(registered(&mut state), [(0, pq_data(0xa0, 7))]); + // The second half may repeat: another validator's, and its own when + // it registers a new key over its old one. + register( + &mut state, + 1, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa1, 7), + ); + register( + &mut state, + 0, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa2, 7), + ); + assert_eq!( + registered(&mut state), + [(0, pq_data(0xa2, 7)), (1, pq_data(0xa1, 7))] + ); + } + + #[test] + fn an_exit_removes_the_validators_registration_for_good() { + let mut state = with_validators_at(ForkName::Eip8483, 8); + let config = Config::active(); + for index in 0..3 { + register( + &mut state, + index, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa0 + index as u8, 1), + ); + } + initiate_validator_exit(&mut state, 1, &config, None).unwrap(); + assert_ne!(state.validator(1).unwrap().exit_epoch, FAR_FUTURE_EPOCH); + // The others keep theirs, in order. + assert_eq!( + registered(&mut state), + [(0, pq_data(0xa0, 1)), (2, pq_data(0xa2, 1))] + ); + // A second call, for a validator already exiting, removes nothing. + initiate_validator_exit(&mut state, 1, &config, None).unwrap(); + assert_eq!(registered(&mut state).len(), 2); + // And the exited validator cannot register again. + register( + &mut state, + 1, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xb1, 1), + ); + assert_eq!(registered(&mut state).len(), 2); + } + + #[test] + fn a_consolidation_removes_the_sources_registration() { + // 200 validators: the minimal config's churn then leaves balance for + // consolidations (see electra's own consolidation test). + let mut state = with_validators_at(ForkName::Eip8483, 200); + let mut config = Config::minimal(); + config.shard_committee_period = 0; + register( + &mut state, + 0, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa0, 1), + ); + register( + &mut state, + 1, + COMPOUNDING_WITHDRAWAL_PREFIX, + pq_data(0xa1, 1), + ); + let (source_pubkey, source_address) = + credentialed(&mut state, 0, COMPOUNDING_WITHDRAWAL_PREFIX); + let target_pubkey = state.validator(1).unwrap().pubkey; + + let request = crate::beacon::containers::electra::ConsolidationRequest { + source_address, + source_pubkey, + target_pubkey, + }; + process_consolidation_request( + &mut state, + &request, + &config, + &ActiveBalanceCache::default(), + &PubkeyIndexCache::default(), + ) + .unwrap(); + assert_ne!( + state.validator(0).unwrap().exit_epoch, + FAR_FUTURE_EPOCH, + "the consolidation must have been initiated" + ); + assert_eq!(registered(&mut state), [(1, pq_data(0xa1, 1))]); + } + + #[test] + fn a_builder_exit_removes_its_registration_for_good() { + let mut state = with_validators_at(ForkName::Eip8483, 8); + let config = Config::active(); + let builder = |seed: u8| gloas::Builder { + pubkey: BlsPubkey([seed; 48]), + version: constants::PAYLOAD_BUILDER_VERSION, + execution_address: ExecutionAddress::repeat_byte(seed), + balance: 1_000_000_000, + deposit_epoch: 0, + withdrawable_epoch: FAR_FUTURE_EPOCH, + }; + let state_inner = inner(&mut state); + state_inner.builders = vec![builder(1), builder(2)].into(); + // Both builders' placement is finalized, so both are active. + state_inner.finalized_checkpoint.epoch = 1; + let registration = |seed: u8| eip8483::BuilderPqRegistrationRequest { + source_address: ExecutionAddress::repeat_byte(seed), + builder_pubkey: BlsPubkey([seed; 48]), + pq_data: Bytes32::repeat_byte(0xc0 + seed), + }; + process_builder_pq_registration_request(&mut state, ®istration(1)).unwrap(); + process_builder_pq_registration_request(&mut state, ®istration(2)).unwrap(); + assert_eq!(inner(&mut state).builder_pq_registrations.len(), 2); + + let exit = gloas::BuilderExitRequest { + source_address: ExecutionAddress::repeat_byte(1), + pubkey: BlsPubkey([1; 48]), + }; + process_builder_exit_request(&mut state, &exit, &config).unwrap(); + let state_inner = inner(&mut state); + assert_ne!(state_inner.builders[0].withdrawable_epoch, FAR_FUTURE_EPOCH); + let left: Vec = state_inner + .builder_pq_registrations + .iter() + .map(|registration| registration.builder_pubkey) + .collect(); + assert_eq!(left, [BlsPubkey([2; 48])]); + + // The exited builder cannot register again, with new data either. + let again = eip8483::BuilderPqRegistrationRequest { + pq_data: Bytes32::repeat_byte(0xee), + ..registration(1) + }; + process_builder_pq_registration_request(&mut state, &again).unwrap(); + assert_eq!(inner(&mut state).builder_pq_registrations.len(), 1); + } + + /// A full parent from before the fork committed to gloas's requests type; + /// one from after it, to EIP-8483's. + #[test] + fn a_pre_fork_parents_requests_are_checked_against_the_gloas_type() { + let slots_per_epoch = preset::slots_per_epoch(); + let fork_epoch = 4; + let mut config = Config::active(); + config.eip8483_fork_epoch = fork_epoch; + + let requests = eip8483::ExecutionRequests::default(); + let extended_root = requests.hash_tree_root(); + let gloas_root = gloas::ExecutionRequests::default().hash_tree_root(); + assert_ne!( + extended_root, gloas_root, + "the two types commit differently" + ); + + let parent_hash = ExecutionBlockHash::repeat_byte(0x42); + let run = |parent_slot: u64, committed, requests: &eip8483::ExecutionRequests| { + let mut state = with_validators_at(ForkName::Eip8483, 8); + let state_inner = inner(&mut state); + state_inner.slot = fork_epoch * slots_per_epoch + 1; + state_inner.latest_execution_payload_bid.slot = parent_slot; + state_inner.latest_execution_payload_bid.block_hash = parent_hash; + state_inner + .latest_execution_payload_bid + .execution_requests_root = committed; + let mut block = eip8483::BeaconBlock::default(); + // The bid builds on the parent's payload: the parent was FULL. + block + .body + .signed_execution_payload_bid + .message + .parent_block_hash = parent_hash; + block.body.parent_execution_requests = requests.clone(); + process_parent_execution_payload( + &mut state, + &block, + &config, + &ActiveBalanceCache::default(), + &PubkeyIndexCache::default(), + ) + }; + + let pre_fork = fork_epoch * slots_per_epoch - 1; + let post_fork = fork_epoch * slots_per_epoch; + run(pre_fork, gloas_root, &requests).unwrap(); + assert!(run(pre_fork, extended_root, &requests).is_err()); + run(post_fork, extended_root, &requests).unwrap(); + assert!(run(post_fork, gloas_root, &requests).is_err()); + + // A pre-fork payload cannot have carried a PQ registration. + let mut with_registration = requests.clone(); + with_registration.validator_pq_registrations = + vec![eip8483::ValidatorPqRegistrationRequest { + source_address: Default::default(), + validator_pubkey: BlsPubkey([9; 48]), + pq_data: pq_data(1, 1), + }] + .into(); + assert!(run(pre_fork, gloas_root, &with_registration).is_err()); + let mut with_registration = requests.clone(); + with_registration.builder_pq_registrations = vec![eip8483::BuilderPqRegistrationRequest { + source_address: Default::default(), + builder_pubkey: BlsPubkey([9; 48]), + pq_data: Bytes32::repeat_byte(1), + }] + .into(); + assert!(run(pre_fork, gloas_root, &with_registration).is_err()); + } +} diff --git a/crates/blockchain/state_transition/src/beacon/stf/electra.rs b/crates/blockchain/state_transition/src/beacon/stf/electra.rs index 9ebc43eb3..fabd221ce 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/electra.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/electra.rs @@ -1635,6 +1635,10 @@ pub fn process_consolidation_request( pending_queue_fields(state, "process_consolidation_request")? .push_pending_consolidation(consolidation)?; + // [New in EIP8483] `initiate_validator_consolidation` removes the source + // validator's PQ registration. A no-op on every other fork. + crate::beacon::helpers::mutators::remove_validator_pq_registration(state, source_index); + Ok(()) } diff --git a/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs index 0c722994c..cb234a09c 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs @@ -1,6 +1,6 @@ //! The PQ fork's epoch processing (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! Gloas's driver without `process_sync_committee_updates` (sync committees are //! gone), with [`process_aggregation_committee_window`] and @@ -16,12 +16,11 @@ use crate::beacon::error::{Error, Result}; use crate::beacon::helpers::accessors::{CommitteeCache, get_current_epoch}; use crate::beacon::helpers::electra::{get_max_effective_balance, pending_queue_fields}; use crate::beacon::helpers::gloas::get_activation_churn_limit; -use crate::beacon::helpers::misc::compute_start_slot_at_epoch; +use crate::beacon::helpers::misc::{compute_epoch_at_slot, compute_start_slot_at_epoch}; use crate::beacon::helpers::mutators::increase_balance; use crate::beacon::helpers::pq::{ compute_aggregation_committees, compute_deposit_pubkey, compute_deposit_vrf_root, - is_active_builder_preregistration, is_active_validator_preregistration, is_legacy_pubkey, - pq_state, + is_legacy_pubkey, pq_state, }; use crate::beacon::preset; use crate::beacon::primitives::{Gwei, ValidatorIndex}; @@ -91,21 +90,26 @@ pub fn process_aggregation_committee_window(state: &mut BeaconState) -> Result<( Ok(()) } -/// `process_preregistration_expiry`: garbage collection only. Bindings are -/// enforced through `is_active_*_preregistration`, so when the sweep runs has -/// no effect on whether a binding is enforced or a request admitted. +/// `process_preregistration_expiry`: drops the records whose `expiry_epoch` +/// the latest payload's epoch has reached. +/// +/// The latest payload's epoch, not the state's: that payload's execution +/// requests are applied by the next block, so a record is kept until every +/// payload before its `expiry_epoch` has had its requests checked against it, +/// across empty epochs too. pub fn process_preregistration_expiry(state: &mut BeaconState) -> Result<()> { let inner = pq_state(state, "process_preregistration_expiry")?; + let latest_payload_epoch = compute_epoch_at_slot(inner.latest_execution_payload_bid.slot); let validators: Vec = inner .validator_preregistrations .iter() - .filter(|record| is_active_validator_preregistration(inner, record)) + .filter(|record| latest_payload_epoch < record.expiry_epoch) .cloned() .collect(); let builders: Vec = inner .builder_preregistrations .iter() - .filter(|record| is_active_builder_preregistration(inner, record)) + .filter(|record| latest_payload_epoch < record.expiry_epoch) .cloned() .collect(); inner.validator_preregistrations = validators.into(); diff --git a/crates/blockchain/state_transition/src/beacon/stf/gloas.rs b/crates/blockchain/state_transition/src/beacon/stf/gloas.rs index be36520e8..3415e1a67 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/gloas.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/gloas.rs @@ -1387,7 +1387,14 @@ pub fn process_builder_exit_request( return Ok(()); } - initiate_builder_exit(&mut inner, builder_index, config) + let builder_pubkey = inner.builders[builder_index as usize].pubkey; + initiate_builder_exit(&mut inner, builder_index, config)?; + + // [New in EIP8483] `initiate_builder_exit` removes the builder's PQ + // registration. A no-op on every other fork: PQ, the one other fork with + // a second caller of `initiate_builder_exit`, has no registrations. + crate::beacon::helpers::mutators::remove_builder_pq_registration(state, &builder_pubkey); + Ok(()) } // --------------------------------------------------------------------------- diff --git a/crates/blockchain/state_transition/src/beacon/stf/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/pq.rs index 6172b444f..b34ee06d1 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/pq.rs @@ -1,6 +1,6 @@ //! The PQ fork's block processing (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! Gloas's block processing with leanXMSS in place of BLS: //! @@ -41,10 +41,10 @@ use crate::beacon::helpers::gloas::{ use crate::beacon::helpers::misc::{compute_epoch_at_slot, compute_signing_root}; use crate::beacon::helpers::mutators::slash_validator; use crate::beacon::helpers::pq::{ - compute_deposit_pubkey, compute_xmss_leaf_index, get_active_builder_preregistration, - get_active_validator_preregistration, get_attestation_statements, get_committee_indices, - get_leaf_index, is_builder_bid_leaf_index, is_legacy_pubkey, is_valid_indexed_attestation, - is_valid_vrf_proof, pq_state, verify_aggregates, xmss_verify, + compute_deposit_pubkey, compute_xmss_leaf_index, get_attestation_statements, + get_builder_preregistration, get_committee_indices, get_leaf_index, + get_validator_preregistration, is_builder_bid_leaf_index, is_legacy_pubkey, + is_valid_indexed_attestation, is_valid_vrf_proof, pq_state, verify_aggregates, xmss_verify, }; use crate::beacon::helpers::predicates::{ is_active_validator, is_slashable_attestation_data, is_slashable_validator, @@ -52,7 +52,8 @@ use crate::beacon::helpers::predicates::{ use crate::beacon::helpers::target_balances::TargetBalanceDelta; use crate::beacon::preset; use crate::beacon::primitives::{ - ExecutionAddress, HashTreeRoot as _, Root, Slot, ValidatorIndex, XmssPubkey, XmssSignature, + Epoch, ExecutionAddress, HashTreeRoot as _, Root, Slot, ValidatorIndex, XmssPubkey, + XmssSignature, }; use crate::metrics::{StfPhase, timed, try_for_each_timed}; @@ -459,6 +460,16 @@ pub fn process_attestation( // --------------------------------------------------------------------------- /// `process_parent_execution_payload`: gloas's, over the PQ fork's requests. +/// +/// Every full parent is verified against the PQ type, one from before +/// `PQ_FORK_EPOCH` included: the specification says so in a note, and gives +/// PQ no branch like EIP-8483's for a pre-fork parent. `upgrade_to_pq` copies +/// that parent's bid unchanged, so its root commits to EIP-8483's +/// `ExecutionRequests`, which no PQ requests root equals (the two containers' +/// active fields differ). The first PQ block can therefore take a pre-fork +/// parent only as EMPTY. That is the specification's rule and is kept as +/// written: accepting such a parent as FULL here alone would follow a chain +/// no other client does. A network that is PQ from genesis never meets it. pub fn process_parent_execution_payload( state: &mut BeaconState, block: &pq::BeaconBlock, @@ -623,16 +634,16 @@ pub fn get_execution_requests_list(requests: &pq::ExecutionRequests) -> Vec Result<()> { let pubkey = compute_deposit_pubkey(&request.pubkey); let inner = pq_state(state, "process_deposit_request")?; - if let Some(preregistration) = get_active_validator_preregistration(inner, &pubkey) { + if let Some(preregistration) = get_validator_preregistration(inner, &pubkey) { if request.withdrawal_credentials != preregistration.withdrawal_credentials { return Ok(()); } @@ -696,7 +707,7 @@ pub fn process_consolidation_request( } /// `process_builder_deposit_request` (modified in PQ): no signature to check, -/// an active preregistration binds the key's credentials, and a legacy +/// a preregistration binds the key's credentials, and a legacy /// deposit's new builder initiates its exit at once. pub fn process_builder_deposit_request( state: &mut BeaconState, @@ -711,7 +722,7 @@ pub fn process_builder_deposit_request( let pubkey = compute_deposit_pubkey(&request.pubkey); { let inner = pq_state(state, "process_builder_deposit_request")?; - if let Some(preregistration) = get_active_builder_preregistration(inner, &pubkey) { + if let Some(preregistration) = get_builder_preregistration(inner, &pubkey) { if request.withdrawal_credentials != preregistration.withdrawal_credentials { return Ok(()); } @@ -780,62 +791,50 @@ pub fn process_builder_exit_request( /// `process_validator_preregistration_request` (EIP-8205): binds a key that /// has no validator and no pending deposit to its withdrawal credentials and -/// VRF root, until `PREREGISTRATION_EXPIRY_SLOTS` from now. An active binding -/// for the key makes a new request a no-op. +/// VRF root, until `PREREGISTRATION_EXPIRY_EPOCHS` from the current epoch. A +/// request is a no-op while the state holds `PREREGISTRATIONS_LIMIT` records +/// or one for the key, expired or not: the epoch transition's sweep is what +/// frees both. pub fn process_validator_preregistration_request( state: &mut BeaconState, request: &pq::ValidatorPreregistrationRequest, ) -> Result<()> { let pubkey = request.pubkey; - let record_key = pubkey.to_request_key(); - let registered = state - .iter_validators() - .any(|validator| validator.pubkey == record_key); - let inner = pq_state(state, "process_validator_preregistration_request")?; - - if get_active_validator_preregistration(inner, &pubkey).is_some() { - return Ok(()); + { + let inner = pq_state(state, "process_validator_preregistration_request")?; + if inner.validator_preregistrations.len() as u64 >= preset::preregistrations_limit() { + return Ok(()); + } + if get_validator_preregistration(inner, &pubkey).is_some() { + return Ok(()); + } + // A pubkey with a pending deposit cannot be preregistered. + if inner + .pending_deposits + .iter() + .any(|deposit| compute_deposit_pubkey(&deposit.pubkey) == pubkey) + { + return Ok(()); + } } // A pubkey with an existing validator cannot be preregistered. - if registered { - return Ok(()); - } - // A pubkey with a pending deposit cannot be preregistered. - if inner - .pending_deposits - .iter() - .any(|deposit| compute_deposit_pubkey(&deposit.pubkey) == pubkey) + let record_key = pubkey.to_request_key(); + if state + .iter_validators() + .any(|validator| validator.pubkey == record_key) { return Ok(()); } - // Only active records count towards the limit, so the timing of the - // garbage-collection sweep does not affect admission. - let active = inner - .validator_preregistrations - .iter() - .filter(|record| { - crate::beacon::helpers::pq::is_active_validator_preregistration(inner, record) - }) - .count() as u64; - if active >= preset::preregistrations_limit() { - return Ok(()); - } let preregistration = pq::ValidatorPreregistration { pubkey, withdrawal_credentials: request.withdrawal_credentials, vrf_root: request.vrf_root, - expiry_slot: expiry_slot(inner.slot)?, + expiry_epoch: expiry_epoch(state)?, }; - match inner + pq_state(state, "process_validator_preregistration_request")? .validator_preregistrations - .iter() - .position(|record| record.pubkey == pubkey) - { - // Replace the expired record in place. - Some(index) => inner.validator_preregistrations[index] = preregistration, - None => inner.validator_preregistrations.push(preregistration), - } + .push(preregistration); Ok(()) } @@ -848,50 +847,41 @@ pub fn process_builder_preregistration_request( ) -> Result<()> { let pubkey = request.pubkey; let record_key = pubkey.to_request_key(); - let inner = pq_state(state, "process_builder_preregistration_request")?; - - if get_active_builder_preregistration(inner, &pubkey).is_some() { - return Ok(()); - } - // A pubkey with an existing builder cannot be preregistered. - if inner - .builders - .iter() - .any(|builder| builder.pubkey == record_key) { - return Ok(()); - } - let active = inner - .builder_preregistrations - .iter() - .filter(|record| { - crate::beacon::helpers::pq::is_active_builder_preregistration(inner, record) - }) - .count() as u64; - if active >= preset::preregistrations_limit() { - return Ok(()); + let inner = pq_state(state, "process_builder_preregistration_request")?; + if inner.builder_preregistrations.len() as u64 >= preset::preregistrations_limit() { + return Ok(()); + } + if get_builder_preregistration(inner, &pubkey).is_some() { + return Ok(()); + } + // A pubkey with an existing builder cannot be preregistered. + if inner + .builders + .iter() + .any(|builder| builder.pubkey == record_key) + { + return Ok(()); + } } let preregistration = pq::BuilderPreregistration { pubkey, withdrawal_credentials: request.withdrawal_credentials, - expiry_slot: expiry_slot(inner.slot)?, + expiry_epoch: expiry_epoch(state)?, }; - match inner + pq_state(state, "process_builder_preregistration_request")? .builder_preregistrations - .iter() - .position(|record| record.pubkey == pubkey) - { - Some(index) => inner.builder_preregistrations[index] = preregistration, - None => inner.builder_preregistrations.push(preregistration), - } + .push(preregistration); Ok(()) } -fn expiry_slot(slot: Slot) -> Result { - slot.checked_add(preset::preregistration_expiry_slots()) +/// `get_current_epoch(state) + PREREGISTRATION_EXPIRY_EPOCHS`. +fn expiry_epoch(state: &BeaconState) -> Result { + get_current_epoch(state) + .checked_add(preset::preregistration_expiry_epochs()) .ok_or(Error::ArithmeticOverflow( - "state.slot + PREREGISTRATION_EXPIRY_SLOTS", + "get_current_epoch(state) + PREREGISTRATION_EXPIRY_EPOCHS", )) } @@ -1332,7 +1322,7 @@ mod tests { } #[test] - fn preregistrations_bind_deposits_and_expire() { + fn a_preregistration_binds_the_deposits_of_its_key() { let mut state = with_validators_at(ForkName::Pq, 64); let pubkey = XmssPubkey([0x55; 32]); let credentials = Bytes32::repeat_byte(0x01); @@ -1377,6 +1367,187 @@ mod tests { assert!(inner.validator_preregistrations.is_empty()); } + fn pq_inner(state: &mut BeaconState) -> &mut pq::BeaconState { + match state { + BeaconState::Pq(inner) => inner, + _ => unreachable!("a PQ state"), + } + } + + /// A stored record names the epoch it stops binding at, and holds its key + /// until the sweep drops it: a second request does not replace it. + #[test] + fn a_preregistration_is_stored_once_with_its_expiry_epoch() { + let mut state = with_validators_at(ForkName::Pq, 64); + // Mid-epoch, so a deadline counted in slots would differ. + let slot = 3 * preset::slots_per_epoch() + 5; + pq_inner(&mut state).slot = slot; + let expiry_epoch = 3 + preset::preregistration_expiry_epochs(); + + let pubkey = XmssPubkey([0x55; 32]); + let request = pq::ValidatorPreregistrationRequest { + pubkey, + withdrawal_credentials: Bytes32::repeat_byte(0x01), + vrf_root: Root::repeat_byte(0x77), + }; + process_validator_preregistration_request(&mut state, &request).unwrap(); + let stored = pq::ValidatorPreregistration { + pubkey, + withdrawal_credentials: request.withdrawal_credentials, + vrf_root: request.vrf_root, + expiry_epoch, + }; + assert_eq!( + pq_inner(&mut state).validator_preregistrations.to_vec(), + std::slice::from_ref(&stored) + ); + + let builder_request = pq::BuilderPreregistrationRequest { + pubkey, + withdrawal_credentials: Bytes32::repeat_byte(0x03), + }; + process_builder_preregistration_request(&mut state, &builder_request).unwrap(); + let stored_builder = pq::BuilderPreregistration { + pubkey, + withdrawal_credentials: builder_request.withdrawal_credentials, + expiry_epoch, + }; + assert_eq!( + pq_inner(&mut state).builder_preregistrations.to_vec(), + std::slice::from_ref(&stored_builder) + ); + + // Later requests for the same keys, with other bindings, change + // nothing, whatever the latest payload's slot says about expiry. + let inner = pq_inner(&mut state); + inner.slot = (expiry_epoch + 2) * preset::slots_per_epoch(); + inner.latest_execution_payload_bid.slot = inner.slot - 1; + let rebound = pq::ValidatorPreregistrationRequest { + withdrawal_credentials: Bytes32::repeat_byte(0x09), + ..request + }; + process_validator_preregistration_request(&mut state, &rebound).unwrap(); + let rebound = pq::BuilderPreregistrationRequest { + withdrawal_credentials: Bytes32::repeat_byte(0x09), + ..builder_request + }; + process_builder_preregistration_request(&mut state, &rebound).unwrap(); + let inner = pq_inner(&mut state); + assert_eq!(inner.validator_preregistrations.to_vec(), [stored]); + assert_eq!(inner.builder_preregistrations.to_vec(), [stored_builder]); + } + + /// The sweep compares the latest payload's epoch, not the state's, with + /// each record's `expiry_epoch`, and a swept key can be preregistered + /// again. + #[test] + fn the_expiry_sweep_follows_the_latest_payloads_epoch() { + use crate::beacon::stf::epoch::pq::process_preregistration_expiry; + let mut state = with_validators_at(ForkName::Pq, 64); + let slots_per_epoch = preset::slots_per_epoch(); + let record = |seed: u8, expiry_epoch: Epoch| pq::ValidatorPreregistration { + pubkey: XmssPubkey([seed; 32]), + expiry_epoch, + ..Default::default() + }; + let builder_record = |seed: u8, expiry_epoch: Epoch| pq::BuilderPreregistration { + pubkey: XmssPubkey([seed; 32]), + expiry_epoch, + ..Default::default() + }; + let inner = pq_inner(&mut state); + inner.validator_preregistrations = vec![record(1, 9), record(2, 10), record(3, 11)].into(); + inner.builder_preregistrations = vec![builder_record(4, 10), builder_record(5, 12)].into(); + // The state is epochs past every deadline, across empty slots: the + // last payload is still in epoch 9, whose requests the next block + // applies, so only the record expiring at 9 goes. + inner.slot = 20 * slots_per_epoch; + inner.latest_execution_payload_bid.slot = 10 * slots_per_epoch - 1; + process_preregistration_expiry(&mut state).unwrap(); + let inner = pq_inner(&mut state); + assert_eq!( + inner.validator_preregistrations.to_vec(), + [record(2, 10), record(3, 11)] + ); + assert_eq!( + inner.builder_preregistrations.to_vec(), + [builder_record(4, 10), builder_record(5, 12)] + ); + + // A payload in epoch 10 ends the records expiring at 10, in order. + inner.latest_execution_payload_bid.slot = 10 * slots_per_epoch; + process_preregistration_expiry(&mut state).unwrap(); + let inner = pq_inner(&mut state); + assert_eq!(inner.validator_preregistrations.to_vec(), [record(3, 11)]); + assert_eq!( + inner.builder_preregistrations.to_vec(), + [builder_record(5, 12)] + ); + + // The swept key is free again, from the state's current epoch. + let request = pq::ValidatorPreregistrationRequest { + pubkey: XmssPubkey([2; 32]), + ..Default::default() + }; + process_validator_preregistration_request(&mut state, &request).unwrap(); + let renewed = record(2, 20 + preset::preregistration_expiry_epochs()); + assert_eq!( + pq_inner(&mut state).validator_preregistrations.to_vec(), + [record(3, 11), renewed] + ); + } + + /// A list at `PREREGISTRATIONS_LIMIT` admits nothing, expired records + /// counted: only the sweep makes room. + #[test] + fn a_full_preregistration_list_admits_no_request() { + let mut state = with_validators_at(ForkName::Pq, 64); + let limit = preset::preregistrations_limit() as usize; + let inner = pq_inner(&mut state); + inner.slot = 5 * preset::slots_per_epoch(); + inner.latest_execution_payload_bid.slot = inner.slot - 1; + // Every record long expired. + inner.validator_preregistrations = + vec![pq::ValidatorPreregistration::default(); limit].into(); + inner.builder_preregistrations = vec![pq::BuilderPreregistration::default(); limit].into(); + + let pubkey = XmssPubkey([0x66; 32]); + let request = pq::ValidatorPreregistrationRequest { + pubkey, + ..Default::default() + }; + process_validator_preregistration_request(&mut state, &request).unwrap(); + let request = pq::BuilderPreregistrationRequest { + pubkey, + ..Default::default() + }; + process_builder_preregistration_request(&mut state, &request).unwrap(); + let inner = pq_inner(&mut state); + assert_eq!(inner.validator_preregistrations.len(), limit); + assert_eq!(inner.builder_preregistrations.len(), limit); + assert!(get_validator_preregistration(inner, &pubkey).is_none()); + assert!(get_builder_preregistration(inner, &pubkey).is_none()); + + // One below the limit, both are admitted. + inner.validator_preregistrations = + vec![pq::ValidatorPreregistration::default(); limit - 1].into(); + inner.builder_preregistrations = + vec![pq::BuilderPreregistration::default(); limit - 1].into(); + let request = pq::ValidatorPreregistrationRequest { + pubkey, + ..Default::default() + }; + process_validator_preregistration_request(&mut state, &request).unwrap(); + let request = pq::BuilderPreregistrationRequest { + pubkey, + ..Default::default() + }; + process_builder_preregistration_request(&mut state, &request).unwrap(); + let inner = pq_inner(&mut state); + assert!(get_validator_preregistration(inner, &pubkey).is_some()); + assert!(get_builder_preregistration(inner, &pubkey).is_some()); + } + #[test] fn a_voluntary_exit_request_exits_an_eligible_validator() { let mut state = with_validators_at(ForkName::Pq, 64); diff --git a/crates/blockchain/state_transition/src/beacon/upgrade.rs b/crates/blockchain/state_transition/src/beacon/upgrade.rs index 0960133ab..fb92d0226 100644 --- a/crates/blockchain/state_transition/src/beacon/upgrade.rs +++ b/crates/blockchain/state_transition/src/beacon/upgrade.rs @@ -1255,10 +1255,11 @@ pub fn upgrade_to_gloas(pre: &BeaconState, config: &Config) -> Result Result { let BeaconState::Gloas(pre) = pre else { return Err(Error::UnsupportedForFork { @@ -1550,6 +1551,11 @@ fn builder_of<'a>( /// unregistered builders' pending payments are settled or dropped, the sync /// committees and EIP-8483's registrations leave the state, and the aggregation /// committee window is initialized from the upgraded state. +/// +/// `latest_execution_payload_bid` is copied unchanged here too, and its +/// `execution_requests_root` may commit to EIP-8483's `ExecutionRequests`. +/// PQ has no rule like EIP-8483's for it: see +/// `stf::pq::process_parent_execution_payload`. pub fn upgrade_to_pq(pre: &BeaconState, config: &Config) -> Result { let quorum = crate::beacon::helpers::gloas::get_builder_payment_quorum_threshold(pre)?; let BeaconState::Eip8483(pre) = pre else { diff --git a/crates/common/crypto/src/vrf.rs b/crates/common/crypto/src/vrf.rs index feed42a8f..235cf2c88 100644 --- a/crates/common/crypto/src/vrf.rs +++ b/crates/common/crypto/src/vrf.rs @@ -1,6 +1,6 @@ //! The Beacon Chain PQ fork's VRF tree (consensus-specs //! `specs/_features/pq/{beacon-chain,validator}.md`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! XMSS signatures are not unique, so a proposer could grind a signature-based //! RANDAO reveal. A validator instead has a secret for each slot, derived from diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index 240e48230..8a24bb3dd 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -12,8 +12,9 @@ //! # What is left out //! //! - **Forks this build cannot process.** `HEZE_FORK_VERSION`/`HEZE_FORK_EPOCH` -//! and `EIP8321_FORK_VERSION`/`EIP8321_FORK_EPOCH` (its own later fork -//! schedule) stay out for the same reason `GLOAS_*` used to: a fork version +//! and `EIP8453_FORK_VERSION`/`EIP8453_FORK_EPOCH` (decoupled consensus on +//! top of PQ, with its `HEAD_VOTE_DUE_BPS`, `SUPPORT_CUTOFF_BPS` and +//! `VIEW_FREEZE_BPS`) stay out for the same reason `GLOAS_*` used to: a fork version //! stored here would give [`Config::fork_at_epoch`] a fork //! [`crate::beacon::fork::ForkName`] has no variant for, so each is //! reported as an unknown key instead. The rest are heze-era data keys, not @@ -23,6 +24,10 @@ //! `MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST` (EIP-7805's fork-choice-enforced //! inclusion lists), and `CONFIRMATION_BYZANTINE_THRESHOLD` (the Fast //! Confirmation Rule). +//! - **`MIN_TRANSACTION_GAS`** (gloas p2p, from v1.7.0-beta.5): it bounds an +//! envelope's transaction count in a gossip rule this build does not apply +//! yet (`docs/spec_deviations.md`, "PQ gossip is gloas's rules with the PQ +//! lines applied"). //! //! `PRESET_BASE` and `CONFIG_NAME` used to be left out as well, because they //! are strings and this struct is SSZ-encoded into the database. They are here diff --git a/crates/common/types/src/beacon/containers/eip8483.rs b/crates/common/types/src/beacon/containers/eip8483.rs index e3b078801..e617e8568 100644 --- a/crates/common/types/src/beacon/containers/eip8483.rs +++ b/crates/common/types/src/beacon/containers/eip8483.rs @@ -1,6 +1,6 @@ //! Containers whose shape is specific to EIP-8483 (consensus-specs //! `specs/_features/eip8483`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! EIP-8483 adds two execution-layer requests with which validators and //! builders register opaque post-quantum material: 64 bytes for a validator diff --git a/crates/common/types/src/beacon/containers/pq.rs b/crates/common/types/src/beacon/containers/pq.rs index d787013d2..932b5bc39 100644 --- a/crates/common/types/src/beacon/containers/pq.rs +++ b/crates/common/types/src/beacon/containers/pq.rs @@ -1,6 +1,6 @@ //! Containers whose shape is specific to the PQ fork (consensus-specs //! `specs/_features/pq`, on the `pq` branch at -//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). +//! `66f143ec87da07452e3059b0954584014043125e`). //! //! The fork replaces BLS with leanXMSS. Every signed container trades its //! `BLSSignature` for an [`XmssSignature`]; [`Attestation`] loses its signature @@ -410,7 +410,8 @@ pub struct ValidatorPreregistrationRequest { pub vrf_root: Root, } -/// A stored validator preregistration, enforced until `expiry_slot`. +/// A stored validator preregistration, enforced until `expiry_epoch`: the +/// absolute deadline computed when it was stored. #[derive( Debug, Clone, @@ -428,7 +429,7 @@ pub struct ValidatorPreregistration { pub withdrawal_credentials: Bytes32, pub vrf_root: Root, #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] - pub expiry_slot: Slot, + pub expiry_epoch: Epoch, } /// The builder counterpart of [`ValidatorPreregistrationRequest`]: a builder @@ -450,7 +451,7 @@ pub struct BuilderPreregistrationRequest { pub withdrawal_credentials: Bytes32, } -/// A stored builder preregistration, enforced until `expiry_slot`. +/// A stored builder preregistration, enforced until `expiry_epoch`. #[derive( Debug, Clone, @@ -467,7 +468,7 @@ pub struct BuilderPreregistration { pub pubkey: XmssPubkey, pub withdrawal_credentials: Bytes32, #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] - pub expiry_slot: Slot, + pub expiry_epoch: Epoch, } /// A voluntary exit, now an execution-layer request: the system contract diff --git a/crates/common/types/src/beacon/fork.rs b/crates/common/types/src/beacon/fork.rs index 0fc4160c7..5c25b4ada 100644 --- a/crates/common/types/src/beacon/fork.rs +++ b/crates/common/types/src/beacon/fork.rs @@ -45,7 +45,7 @@ fn beacon_snapshot_interval() -> u64 { /// /// [`ForkName::Eip8483`] and [`ForkName::Pq`] are consensus-specs feature /// forks (`specs/_features/{eip8483,pq}` on the `pq` branch, pinned at -/// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`), not mainnet upgrades: the +/// `66f143ec87da07452e3059b0954584014043125e`), not mainnet upgrades: the /// PQ fork replaces BLS with leanXMSS, and needs the EIP-8483 registrations /// made before it, so the two are scheduled in that order after gloas. Other /// forks after gloas exist upstream but are out of scope for this crate. diff --git a/crates/common/types/src/beacon/preset.rs b/crates/common/types/src/beacon/preset.rs index 3a4668d35..5875837b6 100644 --- a/crates/common/types/src/beacon/preset.rs +++ b/crates/common/types/src/beacon/preset.rs @@ -653,17 +653,12 @@ pub mod mainnet { /// `MAX_BLOB_COMMITMENTS_PER_BLOCK` commitments and an XMSS signature. pub const MAX_SIGNED_EXECUTION_PAYLOAD_BID_SIZE_PQ: usize = 199_240; - /// How many active preregistrations of one kind the state admits. - /// From `presets/mainnet/eip8205.yaml`: the PQ preset file does not list - /// it, and the specification's build loads every preset file of the - /// directory. + /// How many preregistrations of one kind the state holds. pub const PREREGISTRATIONS_LIMIT: u64 = 524_288; - /// How long a preregistration binds its key, in slots from the slot it was - /// stored at. From `presets/mainnet/eip8205.yaml`: the PQ preset file does not list - /// it, and the specification's build loads every preset file of the - /// directory. - pub const PREREGISTRATION_EXPIRY_SLOTS: u64 = 262_144; + /// How long a preregistration binds its key, in epochs from the epoch it + /// was stored in. + pub const PREREGISTRATION_EXPIRY_EPOCHS: u64 = 8_192; // --- State list lengths --- @@ -1254,17 +1249,12 @@ pub mod minimal { /// `MAX_BLOB_COMMITMENTS_PER_BLOCK` commitments and an XMSS signature. pub const MAX_SIGNED_EXECUTION_PAYLOAD_BID_SIZE_PQ: usize = 199_240; - /// How many active preregistrations of one kind the state admits. - /// `[customized]`, from `presets/minimal/eip8205.yaml`: the PQ preset file - /// does not list it, and the specification's build loads every preset - /// file of the directory. + /// How many preregistrations of one kind the state holds. `[customized]`. pub const PREREGISTRATIONS_LIMIT: u64 = 64; - /// How long a preregistration binds its key, in slots from the slot it was - /// stored at. `[customized]`, from `presets/minimal/eip8205.yaml`: the PQ preset file - /// does not list it, and the specification's build loads every preset - /// file of the directory. - pub const PREREGISTRATION_EXPIRY_SLOTS: u64 = 64; + /// How long a preregistration binds its key, in epochs from the epoch it + /// was stored in. `[customized]`. + pub const PREREGISTRATION_EXPIRY_EPOCHS: u64 = 8; // --- State list lengths --- @@ -1637,7 +1627,7 @@ per_preset! { max_signed_aggregate_and_proof_size_pq => MAX_SIGNED_AGGREGATE_AND_PROOF_SIZE_PQ: usize, max_attester_slashing_size_pq => MAX_ATTESTER_SLASHING_SIZE_PQ: usize, preregistrations_limit => PREREGISTRATIONS_LIMIT: u64, - preregistration_expiry_slots => PREREGISTRATION_EXPIRY_SLOTS: u64, + preregistration_expiry_epochs => PREREGISTRATION_EXPIRY_EPOCHS: u64, aggregation_committee_window_length => AGGREGATION_COMMITTEE_WINDOW_LENGTH: usize, } @@ -2256,13 +2246,13 @@ mod tests { MAX_ATTESTATIONS_PQ, MIN_ATTESTATION_INCLUSION_DELAY_PQ, MAX_VALIDATOR_PREREGISTRATION_REQUESTS_PER_PAYLOAD, MAX_BUILDER_PREREGISTRATION_REQUESTS_PER_PAYLOAD, MAX_VOLUNTARY_EXIT_REQUESTS_PER_PAYLOAD, - PREREGISTRATIONS_LIMIT, PREREGISTRATION_EXPIRY_SLOTS, + PREREGISTRATIONS_LIMIT, PREREGISTRATION_EXPIRY_EPOCHS, ); } - /// The PQ preset's values, pinned from `presets/{mainnet,minimal}/pq.yaml`, - /// `eip8483.yaml` and `eip8205.yaml` at consensus-specs' `pq` pin - /// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`. + /// The PQ preset's values, pinned from `presets/{mainnet,minimal}/pq.yaml` + /// and `eip8483.yaml` at consensus-specs' `pq` pin + /// `66f143ec87da07452e3059b0954584014043125e`. #[test] fn pq_pinned_values() { assert_eq!(mainnet::MAX_COMMITTEES_PER_SLOT_PQ, 16); @@ -2271,8 +2261,8 @@ mod tests { assert_eq!(minimal::MIN_ATTESTATION_INCLUSION_DELAY_PQ, 2); assert_eq!(mainnet::PREREGISTRATIONS_LIMIT, 1 << 19); assert_eq!(minimal::PREREGISTRATIONS_LIMIT, 64); - assert_eq!(mainnet::PREREGISTRATION_EXPIRY_SLOTS, 1 << 18); - assert_eq!(minimal::PREREGISTRATION_EXPIRY_SLOTS, 64); + assert_eq!(mainnet::PREREGISTRATION_EXPIRY_EPOCHS, 1 << 13); + assert_eq!(minimal::PREREGISTRATION_EXPIRY_EPOCHS, 8); assert_eq!(mainnet::MAX_STARK_PROOF_SIZE, 1 << 20); assert_eq!( mainnet::MAX_VALIDATOR_PQ_REGISTRATION_REQUESTS_PER_PAYLOAD, diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index ba58af15e..88553d419 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -1,20 +1,27 @@ # The PQ fork consensus-specs' `pq` branch (pinned here at -`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`, pq-devnet-1's spec) specifies an emergency fork that +`66f143ec87da07452e3059b0954584014043125e`, pq-devnet-2's spec) specifies an emergency fork that replaces BLS with leanXMSS, a hash-based signature scheme believed secure against a quantum adversary. It comes as two feature forks after gloas: 1. **EIP-8483** (`specs/_features/eip8483`): validators and builders register post-quantum material through two new execution-layer requests. A validator registers 64 bytes (an XMSS key and a VRF root), a builder 32 (an XMSS key). - Nothing else changes. + A validator needs compounding credentials to register, only the key half + of its 64 bytes has to be new, and a registration is removed when its + validator or builder initiates an exit, which also ends its right to + register. Nothing else changes. 2. **PQ** (`specs/_features/pq`): every validator and builder adopts the key it registered, BLS signatures become XMSS ones, sync committees and the light client protocol go, RANDAO reveals become VRF proofs, attestations lose their signatures to a block-wide STARK proof, voluntary exits move to the execution layer, and deposits carry a VRF root instead of a signature, guarded by - preregistrations (EIP-8205). A validator or builder that registered + preregistrations (EIP-8205). A preregistration binds its key from the + request until the epoch transition sweeps it, once the latest payload's + epoch reaches its `expiry_epoch` (`PREREGISTRATION_EXPIRY_EPOCHS` after + the epoch it was stored in); until then a second request for the key is a + no-op, expired or not. A validator or builder that registered nothing takes `keccak256(pubkey + domain)` of its BLS key as its XMSS key (and, a validator, as its VRF root), against which nothing verifies, and is exited (`compute_legacy_xmss_pubkey`, `compute_legacy_vrf_root`; SHA-256 @@ -518,15 +525,11 @@ asks for again. ## Running a devnet ethpandaops/ethereum-package's `pq` branch runs PQ-at-genesis devnets with -ethlambda as beacon node, validator client or both. This branch follows -consensus-specs `pq` at `4c296784`, pq-devnet-1's spec -(`notes.ethereum.org/@ethpandaops/pq-devnet-1`), and runs leanVM bindings -v0.19.2, the release pq-devnet-2 names. The other clients need not run that -release, only one with the same leanVM `PROTOCOL_VERSION`: v0.19.0, -pq-devnet-1's, makes and verifies the same proofs (see [Proofs](#proofs)). -The example below names pq-devnet-0's images for the other clients; swap in -their pq-devnet-1 images once published (the notes list them as TBD). Build -the image from the +ethlambda as beacon node, validator client or both. This branch targets +pq-devnet-2: consensus-specs `pq` at `66f143ec` and leanVM bindings v0.19.2 +(v0.19.0, pq-devnet-1's, makes and verifies the same proofs; see +[Proofs](#proofs)). The example below names pq-devnet-0's images for the +other clients; swap in their pq-devnet-2 images. Build the image from the repository root (`docker build -t ethlambda:pq-local .`: the node proves in process, so there is no sidecar to ship), then `kurtosis run --enclave pq --args-file params.yaml` with, for @@ -680,19 +683,25 @@ No consensus-specs release ships fixtures for either fork. The pyspec on the ```sh git clone https://github.com/ethereum/consensus-specs && cd consensus-specs -git checkout 4c296784bb6ff54cbdcf72ebdda2a1057cce8893 +git checkout 66f143ec87da07452e3059b0954584014043125e make test reftests=true fork=eip8483 preset=minimal make test reftests=true fork=pq preset=minimal ``` `reftests/` then holds `tests/minimal/{eip8483,pq}/...`, which unpack beside -the release's own forks under `consensus-spec-tests/tests/minimal/`. The -generator runs with XMSS inactive (key generation takes minutes in EthLib's -reference implementation), so the fixtures carry stub signatures and empty -proofs; the spec-test binary calls `helpers::pq::disable_xmss_verification` -for that reason, which accepts every XMSS signature and STARK proof the way -the pyspec's inactive stubs do. `GetLeafIndex` and the self-build empty -signature are still read from the bytes, as the pyspec's are. +the release's own forks under `consensus-spec-tests/tests/minimal/`. Up to +`4c296784` the generator ran with XMSS inactive (key generation took minutes +in EthLib's reference implementation), so the fixtures carried stub +signatures and empty proofs; the spec-test binary calls +`helpers::pq::disable_xmss_verification` for that reason, which accepts +every XMSS signature and STARK proof the way the pyspec's inactive stubs do. +`GetLeafIndex` and the self-build empty signature are still read from the +bytes, as the pyspec's are. At this pin the generator signs with real +leanXMSS keys wherever a case has signatures on (`c3e76688`, py-lean-pq +0.19.0; block proofs are still the concatenation), so a case that expects a +bad signature to be refused cannot pass while the binary keeps verification +off: the binary has to verify where the case does before these fixtures +mean what they say. The runners route both forks' cases already (operations, epoch processing, fork choice, rewards; the new `validator_pq_registration_request`, @@ -717,11 +726,13 @@ generated. - The ENR's `attnets` keeps the pre-PQ backbone across the PQ boundary: ethrex's `DiscoveryServer` cannot replace the served record at runtime (the same gap as its `eth2` entry, see `CLAUDE.md`). -- Interop at pq-devnet-1's spec (`4c296784`): its genesis and key - derivation are still TBD in the devnet notes, and until ethPandaOps' - generator and the other clients follow `b5d422b2`'s VRF rule and - `4c296784`'s keccak256 legacy keys, a mixed network cannot run. An - ethlambda-only network runs on files `ethlambda pq-keys` writes. +- Interop at pq-devnet-2's spec (`66f143ec`): not run yet. The devnet's + notes (`notes.ethereum.org/@ethpandaops/pq-devnet-2`) settle what + pq-devnet-1's left open, the key derivation (ERC-8517, which this client + follows) and the genesis generator, so a mixed network needs every + client's image at this pin: one that still stores `expiry_slot` computes + another state root from the first preregistration on. An ethlambda-only + network runs on files `ethlambda pq-keys` writes. - PQ block production does not weigh builder bids: it self-builds, and the PQ builder market it would read is filled but unused. - The pubkey index cache keys a pubkey by bytes 1 to 9, all zero for a PQ diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index 29a4170cb..2d96ea1f0 100644 --- a/docs/spec_deviations.md +++ b/docs/spec_deviations.md @@ -1005,7 +1005,7 @@ signature, whichever way the node answered. Three departures: ## EIP-8483 and PQ run on a newer gloas than the gloas fork does -consensus-specs' `pq` branch (`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`) is +consensus-specs' `pq` branch (`66f143ec87da07452e3059b0954584014043125e`) is based on a `master` newer than this repository's pin (`v1.7.0-beta.2`). Across every fork's `beacon-chain.md`, `fork.md` and `fork-choice.md`, the rules that changed in between are the three state-transition rules below, the four @@ -1073,9 +1073,11 @@ outcome to match. ## PQ fixtures run with XMSS verification off -consensus-specs generates its EIP-8483 and PQ fixtures with XMSS inactive, so -their signatures are stubs and their proofs empty, which the pyspec's inactive -`xmss.Verify` and `stark.VerifyAggregates` accept. The spec-test binary turns +consensus-specs generated its EIP-8483 and PQ fixtures with XMSS inactive up +to `4c296784`, so their signatures were stubs and their proofs empty, which +the pyspec's inactive `xmss.Verify` and `stark.VerifyAggregates` accept (from +`c3e76688` it signs with real leanXMSS keys where a case has signatures on; +see `docs/beacon_pq.md`, "Spec fixtures"). The spec-test binary turns this crate's verification off the same way (`helpers::pq::disable_xmss_verification`, compiled only with the `beacon-spec-tests` feature), so no PQ fixture checks a real signature. The @@ -1104,9 +1106,25 @@ gossip modules implement, so their deliberate departures carry over: - **The pubkey-only XMSS signature before any committee derivation.** - **"Passes validation" is "post-state is cached".** - **The newer master's bid rules are not taken**: the builder bid limit - (`get_builder_bid_limit`) and the per-builder bid counts. PQ's bid rule is - this repository's gloas bid rule over a PQ builder market, with XMSS - signatures and `[Modified in PQ]`'s builder-exit key comparison. + (`get_builder_bid_limit`, which from v1.7.0-beta.5 also leaves a builder's + pending withdrawals out of the balance it counts) and the per-builder bid + counts, the IGNORE of a bid received before the previous slot's payload + attestation deadline, and `is_bid_compatible_with_head`'s condition that a + bid on the head's parent is for the slot after the head and that the head + is late or its proposer equivocated. PQ's bid rule is this repository's + gloas bid rule over a PQ builder market, with XMSS signatures and + `[Modified in PQ]`'s builder-exit key comparison. +- **Nor are its two envelope rules**, both new in v1.7.0-beta.5 and inherited + by PQ unmodified: the REJECT of a payload with more transactions than + `get_max_payload_gas_limit(store, block) // MIN_TRANSACTION_GAS`, and the + REJECT of a payload whose `block_hash` is not + `compute_execution_block_hash`'s. A node with an execution client has it + judge both when the payload reaches it, so a payload failing either is not + imported, but this node does relay its envelope first. + `MIN_TRANSACTION_GAS` is therefore a config key the node reports as + ignored. They move with the gloas pin: a block-hash computation that is + wrong refuses every valid payload, and nothing in this repository can + check one yet. - **The proposer preferences domain is the one the specification names** (`compute_fork_version(proposal_epoch)`), where gloas's rule accepts any of three candidate domains for other clients' sake.