Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/net/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -469,6 +470,9 @@ pub enum PqGossipObject {
/// For `proposer_preferences`, already recorded in the node's PQ builder
/// market.
ProposerPreferences(Box<PqSignedProposerPreferences>),
/// 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<PqAttesterSlashing>),
}

#[protocol]
Expand Down
16 changes: 11 additions & 5 deletions crates/net/p2p/src/beacon/pq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(_) => {}
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/net/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
231 changes: 211 additions & 20 deletions crates/net/rpc/src/beacon/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
//!
Expand All @@ -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,
Expand All @@ -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,
};
Expand Down Expand Up @@ -79,23 +84,31 @@ async fn get_proposer_slashings(State(store): State<Store>) -> 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<Store>) -> 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,
}));
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<Store>) -> Response {
let data = store.operation_pool().voluntary_exits();
crate::json_response(serde_json::json!({ "data": data }))
Expand All @@ -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<Store>,
Extension(p2p): Extension<RpcToP2PRef>,
body: Bytes,
) -> Response {
if wall_fork(&store) >= ForkName::Pq {
let Ok(slashing) = serde_json::from_slice::<pq::AttesterSlashing>(&body) else {
return ApiError::BadRequest("invalid request body").into_response();
};
return respond(
accept_pq_attester_slashing(&store, &p2p, slashing).await,
"attester slashing",
);
}
submit::<electra::AttesterSlashing>(&store, &p2p, &body, "attester slashing", |op| {
BeaconOperation::AttesterSlashing(op)
})
Expand Down Expand Up @@ -179,7 +203,12 @@ async fn submit<T: DeserializeOwned>(
let Ok(operation) = serde_json::from_slice::<T>(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");
Expand Down Expand Up @@ -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());
Expand All @@ -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 });
Expand Down Expand Up @@ -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)]));
}
}
Loading