diff --git a/Cargo.lock b/Cargo.lock index effbce401..e89970e43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2189,6 +2189,7 @@ dependencies = [ "axum", "bs58", "ethlambda-blockchain", + "ethlambda-crypto", "ethlambda-engine", "ethlambda-fork-choice", "ethlambda-metrics", diff --git a/crates/net/api/src/lib.rs b/crates/net/api/src/lib.rs index 6bb0d90e1..89f00ae00 100644 --- a/crates/net/api/src/lib.rs +++ b/crates/net/api/src/lib.rs @@ -12,6 +12,7 @@ use ethlambda_types::{ electra::SingleAttestation, gloas::{PayloadAttestationMessage, SignedExecutionPayloadBid, SignedProposerPreferences}, pq::{ + AttesterSlashing as PqAttesterSlashing, PayloadAttestationMessage as PqPayloadAttestationMessage, SignedAggregateAndProof as PqSignedAggregateAndProof, SignedProposerPreferences as PqSignedProposerPreferences, @@ -469,6 +470,9 @@ pub enum PqGossipObject { /// For `proposer_preferences`, already recorded in the node's PQ builder /// market. ProposerPreferences(Box), + /// For `attester_slashing`, already pooled by the caller. It names no + /// slot, so it goes out under the digest of the wall clock's slot. + AttesterSlashing(Box), } #[protocol] diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index 3f5267eb6..e4f88b0a7 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -595,15 +595,16 @@ pub(crate) fn publish_pq_gossip( use libp2p::gossipsub::IdentTopic; use libssz::SszEncode as _; + let Some(beacon) = server.wire.beacon() else { + warn!("A PQ message reached a lean node; dropping it"); + return; + }; let slot = match &object { PqGossipObject::Attestation { attestation, .. } => attestation.data.slot, PqGossipObject::Aggregate { aggregate, .. } => aggregate.message.aggregate.data.slot, PqGossipObject::PayloadAttestation(message) => message.data.slot, PqGossipObject::ProposerPreferences(preferences) => preferences.message.proposal_slot, - }; - let Some(beacon) = server.wire.beacon() else { - warn!(slot, "A PQ message reached a lean node; dropping it"); - return; + PqGossipObject::AttesterSlashing(_) => crate::gossipsub::beacon_wall_slot(beacon), }; let Some(digest) = beacon.publish_digest(slot) else { warn!( @@ -670,6 +671,11 @@ pub(crate) fn publish_pq_gossip( preferences.to_ssz(), None, ), + PqGossipObject::AttesterSlashing(slashing) => ( + beacon_topics::topic_name(digest, beacon_topics::ATTESTER_SLASHING), + slashing.to_ssz(), + None, + ), }; let compressed = crate::gossipsub::compress_message(&bytes); let pq_hook = if let Some(agg) = is_aggregate @@ -730,7 +736,7 @@ pub(crate) fn publish_pq_gossip( ); } // Read by bid validation and block production, never by fork choice. - PqGossipObject::ProposerPreferences(_) => {} + PqGossipObject::ProposerPreferences(_) | PqGossipObject::AttesterSlashing(_) => {} } } diff --git a/crates/net/rpc/Cargo.toml b/crates/net/rpc/Cargo.toml index 5dd33923b..36d6fe96a 100644 --- a/crates/net/rpc/Cargo.toml +++ b/crates/net/rpc/Cargo.toml @@ -42,6 +42,7 @@ futures-util = "0.3" rayon.workspace = true [dev-dependencies] +ethlambda-crypto.workspace = true ethlambda-validator = { workspace = true, features = ["test-utils"] } spawned-concurrency.workspace = true ethlambda-state-transition = { workspace = true, features = ["test-utils"] } diff --git a/crates/net/rpc/src/beacon/operations.rs b/crates/net/rpc/src/beacon/operations.rs index 9c9b3b1fd..3374bb599 100644 --- a/crates/net/rpc/src/beacon/operations.rs +++ b/crates/net/rpc/src/beacon/operations.rs @@ -5,7 +5,7 @@ //! | Route | GET | POST | //! |---|---|---| //! | `/eth/v1/beacon/pool/proposer_slashings` | pool list | one `ProposerSlashing` | -//! | `/eth/v2/beacon/pool/attester_slashings` | pool list, with `version` and `Eth-Consensus-Version` | one electra `AttesterSlashing` | +//! | `/eth/v2/beacon/pool/attester_slashings` | pool list, with `version` and `Eth-Consensus-Version` | one electra `AttesterSlashing`, or PQ's from PQ on | //! | `/eth/v1/beacon/pool/voluntary_exits` | pool list | one `SignedVoluntaryExit` | //! | `/eth/v1/beacon/pool/bls_to_execution_changes` | pool list | array of `SignedBLSToExecutionChange` | //! @@ -19,6 +19,10 @@ //! its own messages. An accepted operation is pooled, for block production, //! and published. Validating first is not optional: a peer that relays invalid //! operations has its gossipsub score cut. +//! +//! The PQ fork's attester slashing carries proofs where electra's carries +//! signatures. From PQ on, the attester slashings route reads and returns +//! PQ's container and checks it with PQ's gossip rules. use axum::{ Extension, Router, @@ -28,14 +32,15 @@ use axum::{ response::{IntoResponse, Response}, routing::get, }; -use ethlambda_network_api::RpcToP2PRef; +use ethlambda_network_api::{PqGossipObject, RpcToP2PRef}; use ethlambda_state_transition::beacon::gossip::{ - Outcome, + self, Outcome, operations::{SeenOperations, validate}, }; use ethlambda_storage::Store; use ethlambda_types::beacon::{ - containers::{capella::SignedBLSToExecutionChange, electra, shared}, + containers::{capella::SignedBLSToExecutionChange, electra, pq, shared}, + fork::ForkName, operation::BeaconOperation, signing::compute_epoch_at_slot, }; @@ -79,16 +84,17 @@ async fn get_proposer_slashings(State(store): State) -> Response { /// missing, and a validator client would then decode the list as the wrong /// fork's container. /// -/// The pool holds electra-shaped slashings. Their JSON is the same for every -/// fork (the containers differ only in the SSZ list bound of the attesting -/// indices), so no conversion is needed for the version to be honest. +/// Before PQ, the pool's electra-shaped slashings. Their JSON is the same for +/// every fork up to PQ (the containers differ only in the SSZ list bound of +/// the attesting indices), so no conversion is needed for the version to be +/// honest. From PQ on, the pool's PQ slashings. async fn get_attester_slashings(State(store): State) -> Response { - let fork = store - .config() - .fork_at_epoch(compute_epoch_at_slot(crate::beacon::node::wall_slot( - &store, - ))); - let data = store.operation_pool().attester_slashings(); + let fork = wall_fork(&store); + let data = if fork >= ForkName::Pq { + serde_json::json!(store.operation_pool().pq_attester_slashings()) + } else { + serde_json::json!(store.operation_pool().attester_slashings()) + }; let response = crate::json_response(serde_json::json!({ "version": fork.as_str(), "data": data, @@ -96,6 +102,13 @@ async fn get_attester_slashings(State(store): State) -> Response { with_consensus_version(response, fork) } +/// The fork of the wall clock's current epoch. +fn wall_fork(store: &Store) -> ForkName { + store + .config() + .fork_at_epoch(compute_epoch_at_slot(crate::beacon::node::wall_slot(store))) +} + async fn get_voluntary_exits(State(store): State) -> Response { let data = store.operation_pool().voluntary_exits(); crate::json_response(serde_json::json!({ "data": data })) @@ -117,11 +130,22 @@ async fn post_proposer_slashing( .await } +/// Read as the container of the wall clock's fork, as the GET route answers +/// with it. async fn post_attester_slashing( State(store): State, Extension(p2p): Extension, body: Bytes, ) -> Response { + if wall_fork(&store) >= ForkName::Pq { + let Ok(slashing) = serde_json::from_slice::(&body) else { + return ApiError::BadRequest("invalid request body").into_response(); + }; + return respond( + accept_pq_attester_slashing(&store, &p2p, slashing).await, + "attester slashing", + ); + } submit::(&store, &p2p, &body, "attester slashing", |op| { BeaconOperation::AttesterSlashing(op) }) @@ -179,7 +203,12 @@ async fn submit( let Ok(operation) = serde_json::from_slice::(body) else { return ApiError::BadRequest("invalid request body").into_response(); }; - match accept(store, p2p, wrap(operation), kind).await { + respond(accept(store, p2p, wrap(operation), kind).await, kind) +} + +/// The response to one submitted operation `accept` judged. +fn respond(accepted: Result<(), Rejection>, kind: &'static str) -> Response { + match accepted { Ok(()) => StatusCode::OK.into_response(), Err(Rejection::Refused(message)) => { warn!(kind, reason = %message, "Refused a submitted operation"); @@ -230,12 +259,7 @@ async fn accept( Rejection::Internal("validation did not complete") })? }; - if outcome != Outcome::Accept { - let (verdict, reason) = outcome.labels(); - return Err(Rejection::Refused(format!( - "{kind} refused: {verdict}: {reason}" - ))); - } + judged(outcome, kind)?; // Pooled as well as published: gossip never delivers a node its own // messages, so without this a block this node proposes would miss it. store.operation_pool().insert(operation.clone()); @@ -245,6 +269,55 @@ async fn accept( Ok(()) } +/// [`accept`] for the PQ fork's attester slashing, under PQ's gossip rules. +async fn accept_pq_attester_slashing( + store: &Store, + p2p: &RpcToP2PRef, + slashing: pq::AttesterSlashing, +) -> Result<(), Rejection> { + let kind = "attester slashing"; + // The proof checks are STARK verifications, so they run off the async + // threads. + let outcome = { + let store = store.clone(); + let slashing = slashing.clone(); + tokio::task::spawn_blocking(move || { + match gossip::pq::attester_slashing_cheap_checks(&SeenOperations::default(), &slashing) + { + Ok(()) => gossip::pq::attester_slashing_stateful_checks(&store, &slashing), + Err(outcome) => outcome, + } + }) + .await + .map_err(|err| { + error!(%err, kind, "Operation validation task failed"); + Rejection::Internal("validation did not complete") + })? + }; + judged(outcome, kind)?; + // Pooled as well as published, as in `accept`: gossip never delivers a + // node its own messages, and the GET route lists the pool. + store + .operation_pool() + .insert_pq_attester_slashing(slashing.clone()); + p2p.publish_pq_gossip(PqGossipObject::AttesterSlashing(Box::new(slashing))) + .map_err(|_| Rejection::Internal("the network actor is not running"))?; + debug!(kind, "Accepted PQ operation for gossip"); + Ok(()) +} + +/// `Ok` for an accepted operation, and the refusal naming the verdict +/// otherwise. +fn judged(outcome: Outcome, kind: &'static str) -> Result<(), Rejection> { + if outcome == Outcome::Accept { + return Ok(()); + } + let (verdict, reason) = outcome.labels(); + Err(Rejection::Refused(format!( + "{kind} refused: {verdict}: {reason}" + ))) +} + /// The Beacon API's error body, with a message built at run time. fn bad_request(message: String) -> Response { let body = serde_json::json!({ "code": 400, "message": message }); @@ -585,4 +658,122 @@ mod tests { vec![BeaconOperation::BlsToExecutionChange(good)] ); } + + /// From PQ on, a PQ attester slashing whose proofs verify is pooled and + /// gossiped as PQ's, and the pool list answers with it under `pq`. One + /// whose proof fails is refused, and neither pooled nor gossiped. + #[tokio::test] + async fn from_pq_on_a_pq_attester_slashing_is_pooled_and_published() { + use ethlambda_crypto::lean_xmss; + use ethlambda_state_transition::beacon::helpers::{ + pq::attestation_message, test_state::with_validators_at, + }; + use ethlambda_types::beacon::{ + config::Config, + containers::shared::{AttestationData, Checkpoint}, + primitives::{Root, XmssPubkey, XmssSignature}, + }; + + const SLASHINGS: &str = "/eth/v2/beacon/pool/attester_slashings"; + let config = Config::mainnet() + .with_fork_epoch(ForkName::Gloas, 0) + .with_fork_epoch(ForkName::Eip8483, 0) + .with_fork_epoch(ForkName::Pq, 0); + let mut state = with_validators_at(ForkName::Pq, 64); + let slashed = 5; + let slot = state.slot(); + let vote = |root_byte: u8| AttestationData { + slot, + index: 0, + beacon_block_root: Root::repeat_byte(root_byte), + source: Checkpoint::default(), + target: Checkpoint { + epoch: compute_epoch_at_slot(slot), + root: Root::ZERO, + }, + }; + let (_, leaf) = attestation_message(&state, &vote(1)).unwrap(); + let secret = lean_xmss::range_key(&[7; 32], leaf as u32, leaf as u32); + let BeaconState::Pq(inner) = &mut state else { + unreachable!("built at PQ") + }; + inner + .validators + .get_mut(slashed as usize) + .unwrap() + .record + .pubkey = XmssPubkey(secret.public_key().to_bytes()).to_request_key(); + state.apply_pending_mutations(); + let indexed = |data: AttestationData, proven: bool| { + let (message, leaf) = attestation_message(&state, &data).unwrap(); + let proof = if proven { + let signature = secret.sign(&message.0, leaf as u32).unwrap(); + XmssSignature(signature.to_bytes().try_into().unwrap()) + .0 + .to_vec() + } else { + Vec::new() + }; + pq::IndexedAttestation { + attesting_indices: vec![slashed].into(), + data, + proof: proof.try_into().unwrap(), + } + }; + let slashing = |proven| pq::AttesterSlashing { + attestation_1: indexed(vote(1), true), + attestation_2: indexed(vote(2), proven), + }; + let (store, _root) = crate::test_utils::beacon_store_with_config(state.clone(), config); + let fixture = Fixture { + store, + state: state.clone(), + network: Arc::new(RecordingNetwork::default()), + }; + + let body = serde_json::to_vec(&slashing(false)).unwrap(); + let (status, json) = post(&fixture, SLASHINGS, body).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!( + json["message"], + "attester slashing refused: reject: invalid_operation" + ); + assert!( + fixture + .store + .operation_pool() + .pq_attester_slashings() + .is_empty() + ); + assert!(fixture.network.pq_gossip.lock().unwrap().is_empty()); + + let body = serde_json::to_vec(&slashing(true)).unwrap(); + let (status, _) = post(&fixture, SLASHINGS, body).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + fixture.store.operation_pool().pq_attester_slashings(), + vec![slashing(true)] + ); + assert!( + fixture + .store + .operation_pool() + .attester_slashings() + .is_empty() + ); + let published = fixture.network.pq_gossip.lock().unwrap().clone(); + assert!( + matches!( + &published[..], + [PqGossipObject::AttesterSlashing(published)] if **published == slashing(true) + ), + "{published:?}" + ); + + let (status, headers, json) = get(&fixture, SLASHINGS).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["eth-consensus-version"], "pq"); + assert_eq!(json["version"], "pq"); + assert_eq!(json["data"], serde_json::json!([slashing(true)])); + } } diff --git a/crates/net/rpc/src/lib.rs b/crates/net/rpc/src/lib.rs index 7b70668e9..5c76376c0 100644 --- a/crates/net/rpc/src/lib.rs +++ b/crates/net/rpc/src/lib.rs @@ -573,6 +573,7 @@ pub(crate) mod test_utils { >, pub(crate) operations: std::sync::Mutex>, + pub(crate) pq_gossip: std::sync::Mutex>, pub(crate) subscriptions: std::sync::Mutex>, pub(crate) pq_subscriptions: std::sync::Mutex>, pub(crate) blocks: @@ -613,8 +614,9 @@ pub(crate) mod test_utils { impl ethlambda_network_api::RpcToP2P for RecordingNetwork { fn publish_pq_gossip( &self, - _object: ethlambda_network_api::PqGossipObject, + object: ethlambda_network_api::PqGossipObject, ) -> Result<(), spawned_concurrency::error::ActorError> { + self.pq_gossip.lock().unwrap().push(object); Ok(()) } diff --git a/crates/storage/src/pools/operation.rs b/crates/storage/src/pools/operation.rs index fb84af0f5..0a4c4ff71 100644 --- a/crates/storage/src/pools/operation.rs +++ b/crates/storage/src/pools/operation.rs @@ -1,5 +1,6 @@ //! Proposer slashings, attester slashings, voluntary exits and BLS changes -//! this node has validated, held until a block packs them. +//! this node has validated, held until a block packs them. The PQ fork's two +//! slashings, which carry its own containers, have their own lists. //! //! Only operations that already passed gossip (or Beacon API pool) validation //! go in, so this is pure data: it never checks a signature. Each kind is @@ -15,6 +16,7 @@ use ethlambda_types::{ BeaconState, capella::SignedBLSToExecutionChange, electra::AttesterSlashing, + pq, shared::{ProposerSlashing, SignedVoluntaryExit, Validator}, }, operation::BeaconOperation, @@ -35,6 +37,10 @@ pub struct OperationPool { voluntary_exits: BTreeMap, /// Keyed by the validator whose credentials change. bls_to_execution_changes: BTreeMap, + /// The PQ fork's proposer slashings, keyed by the slashed proposer. + pq_proposer_slashings: BTreeMap, + /// The PQ fork's attester slashings, keyed by `hash_tree_root`. + pq_attester_slashings: BTreeMap, } /// The specification's `is_slashable_validator`. @@ -73,6 +79,20 @@ impl OperationPool { insert_first(&mut self.bls_to_execution_changes, key, change) } + /// Keeps the first PQ proposer slashing per proposer. Returns whether this + /// one was new. Callers insert only validated operations. + pub fn insert_pq_proposer_slashing(&mut self, slashing: pq::ProposerSlashing) -> bool { + let key = slashing.signed_header_1.message.proposer_index; + insert_first(&mut self.pq_proposer_slashings, key, slashing) + } + + /// Keeps the first PQ attester slashing per `hash_tree_root`. Returns + /// whether this one was new. Callers insert only validated operations. + pub fn insert_pq_attester_slashing(&mut self, slashing: pq::AttesterSlashing) -> bool { + let key = slashing.hash_tree_root(); + insert_first(&mut self.pq_attester_slashings, key, slashing) + } + /// Insert `operation` into its list. `false` if its key was already held. pub fn insert(&mut self, operation: BeaconOperation) -> bool { match operation { @@ -103,12 +123,23 @@ impl OperationPool { self.bls_to_execution_changes.values().cloned().collect() } + /// Every PQ proposer slashing held, in proposer order. + pub fn pq_proposer_slashings(&self) -> Vec { + self.pq_proposer_slashings.values().cloned().collect() + } + + /// Every PQ attester slashing held, in root order. + pub fn pq_attester_slashings(&self) -> Vec { + self.pq_attester_slashings.values().cloned().collect() + } + /// Drop what `state` (the head state) already makes pointless: exits of /// validators whose `exit_epoch != FAR_FUTURE_EPOCH`, proposer slashings /// whose proposer is no longer slashable, attester slashings whose /// attesting-index intersection holds no slashable validator, and BLS /// changes whose validator's credentials no longer start with - /// `BLS_WITHDRAWAL_PREFIX`. Slashable is the specification's + /// `BLS_WITHDRAWAL_PREFIX`. The PQ slashings follow the same rules as the + /// others. Slashable is the specification's /// `is_slashable_validator` at the state's current epoch. An index the /// state does not know is treated as pointless. pub fn prune(&mut self, state: &BeaconState) { @@ -131,21 +162,36 @@ impl OperationPool { }); self.proposer_slashings.retain(|&index, _| slashable(index)); self.attester_slashings.retain(|_, slashing| { - let first: HashSet = slashing - .attestation_1 - .attesting_indices - .iter() - .copied() - .collect(); - slashing - .attestation_2 - .attesting_indices - .iter() - .any(|index| first.contains(index) && slashable(*index)) + slashes_any( + &slashing.attestation_1.attesting_indices, + &slashing.attestation_2.attesting_indices, + slashable, + ) + }); + self.pq_proposer_slashings + .retain(|&index, _| slashable(index)); + self.pq_attester_slashings.retain(|_, slashing| { + slashes_any( + &slashing.attestation_1.attesting_indices, + &slashing.attestation_2.attesting_indices, + slashable, + ) }); } } +/// Whether an index both attestations name is `slashable`. +fn slashes_any<'a>( + first: impl IntoIterator, + second: impl IntoIterator, + slashable: impl Fn(ValidatorIndex) -> bool, +) -> bool { + let first: HashSet = first.into_iter().copied().collect(); + second + .into_iter() + .any(|index| first.contains(index) && slashable(*index)) +} + /// Inserts `value` unless `key` is taken; returns whether it was inserted. fn insert_first(map: &mut BTreeMap, key: K, value: V) -> bool { match map.entry(key) { @@ -369,6 +415,73 @@ mod tests { assert!(pool.attester_slashings().is_empty()); } + fn pq_proposer_slashing(proposer_index: ValidatorIndex, slot: u64) -> pq::ProposerSlashing { + let mut slashing = pq::ProposerSlashing::default(); + slashing.signed_header_1.message = BeaconBlockHeader { + slot, + proposer_index, + ..Default::default() + }; + slashing.signed_header_2.message = slashing.signed_header_1.message.clone(); + slashing + } + + fn pq_attester_slashing(first: &[u64], second: &[u64], slot: u64) -> pq::AttesterSlashing { + let attestation = |indices: &[u64]| { + let mut attestation = pq::IndexedAttestation { + attesting_indices: indices.to_vec().into(), + data: Default::default(), + proof: Default::default(), + }; + attestation.data.slot = slot; + attestation + }; + pq::AttesterSlashing { + attestation_1: attestation(first), + attestation_2: attestation(second), + } + } + + #[test] + fn the_first_pq_slashing_per_key_is_kept() { + let mut pool = OperationPool::default(); + assert!(pool.insert_pq_proposer_slashing(pq_proposer_slashing(3, 1))); + assert!(!pool.insert_pq_proposer_slashing(pq_proposer_slashing(3, 2))); + assert_eq!( + pool.pq_proposer_slashings(), + vec![pq_proposer_slashing(3, 1)] + ); + assert!(pool.insert_pq_attester_slashing(pq_attester_slashing(&[1, 2], &[2], 1))); + assert!(!pool.insert_pq_attester_slashing(pq_attester_slashing(&[1, 2], &[2], 1))); + assert!(pool.insert_pq_attester_slashing(pq_attester_slashing(&[1, 2], &[2], 2))); + assert_eq!(pool.pq_attester_slashings().len(), 2); + assert!(pool.proposer_slashings().is_empty()); + assert!(pool.attester_slashings().is_empty()); + } + + #[test] + fn prune_drops_pq_slashings_with_nobody_left_to_slash() { + let mut slashed = active_validator(); + slashed.slashed = true; + let state = state_with(vec![active_validator(), slashed.clone(), slashed]); + let mut pool = OperationPool::default(); + pool.insert_pq_proposer_slashing(pq_proposer_slashing(0, 1)); + pool.insert_pq_proposer_slashing(pq_proposer_slashing(1, 1)); + // Validator 0 is slashable but only in the first attestation. + pool.insert_pq_attester_slashing(pq_attester_slashing(&[0, 1, 2], &[1, 2], 1)); + // Validator 0 is in both. + pool.insert_pq_attester_slashing(pq_attester_slashing(&[0, 1], &[0, 1], 2)); + pool.prune(&state); + assert_eq!( + pool.pq_proposer_slashings(), + vec![pq_proposer_slashing(0, 1)] + ); + assert_eq!( + pool.pq_attester_slashings(), + vec![pq_attester_slashing(&[0, 1], &[0, 1], 2)] + ); + } + #[test] fn the_first_bls_change_per_validator_is_kept() { let mut pool = OperationPool::default();