From 24a9e5a63fd1a346d4b9cb5d43cc9b2ec1a46e58 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 11:35:06 -0300 Subject: [PATCH 01/25] feat(validator): attest once the slot's block is in, not always at the deadline The duty loop slept until ATTESTATION_DUE_BPS(_GLOAS) every slot, so every vote went out after the deadline, behind every client that votes on the block. Follow the first beacon node's head events and cut the wait short once a head at the slot is reported, as the honest-validator guide asks. The deadline stays the fallback. --- crates/validator/src/head_events.rs | 305 ++++++++++++++++++++++++++++ crates/validator/src/lib.rs | 29 ++- 2 files changed, 332 insertions(+), 2 deletions(-) create mode 100644 crates/validator/src/head_events.rs diff --git a/crates/validator/src/head_events.rs b/crates/validator/src/head_events.rs new file mode 100644 index 000000000..242cf286c --- /dev/null +++ b/crates/validator/src/head_events.rs @@ -0,0 +1,305 @@ +//! The beacon node's `head` events, used only to attest early. +//! +//! The honest-validator guide has an attester vote once it has seen a valid +//! block for its slot *or* once `ATTESTATION_DUE_BPS` of the slot has passed, +//! whichever comes first. The duty loop used to wait for the deadline every +//! slot, so this client's votes always went out after it, a full deadline +//! behind clients that vote on the block. This module is the "has seen the +//! block" half. +//! +//! It is a hint and nothing more. The duty loop still runs on its own clock +//! (see [`crate::slot_clock`]): the event stream is best-effort by contract and +//! may drop events, so the deadline stays the fallback, and a stream that is +//! down, slow or never connects costs the early vote only, never the duty. +//! +//! # Only the first beacon node +//! +//! `attestation_data` is asked of the beacon nodes in order, so the vote is +//! the first healthy node's head. A head event from another node could wake +//! the duty before that node has the block, and the vote would then name the +//! previous head. Listening to the first node alone keeps the wake and the +//! answer on one node; when it is down, the duty falls back to the deadline. + +use std::time::Duration; + +use ethlambda_types::beacon::primitives::Slot; +use reqwest::Client; +use serde::Deserialize; +use tokio::sync::watch; +use tokio_util::sync::CancellationToken; +use tracing::{debug, info, warn}; + +/// How long establishing the stream's connection may take. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); + +/// How long the stream may stay silent before it is reopened. A node sends a +/// head event every slot it imports a block in, so a minute of silence is a +/// connection that died without closing, or a chain that is not moving, and +/// reopening costs nothing in the second case. +const IDLE_TIMEOUT: Duration = Duration::from_secs(60); + +/// The wait before reopening a stream that failed, doubled on every failure +/// in a row up to [`MAX_BACKOFF`]. +const INITIAL_BACKOFF: Duration = Duration::from_millis(500); +const MAX_BACKOFF: Duration = Duration::from_secs(12); + +/// The highest head slot the beacon node has reported, shared with the duty +/// loop. +#[derive(Debug, Clone)] +pub struct HeadWatch { + head_slot: watch::Receiver, +} + +impl HeadWatch { + /// Subscribes to `base_url`'s `head` events on a task of its own, which + /// reconnects until `shutdown` is cancelled. + pub fn spawn(base_url: &str, shutdown: CancellationToken) -> Self { + let (sender, head_slot) = watch::channel(0); + let url = format!( + "{}/eth/v1/events?topics=head", + base_url.trim_end_matches('/') + ); + tokio::spawn(async move { + tokio::select! { + () = shutdown.cancelled() => {} + () = follow(url, sender) => {} + } + }); + Self { head_slot } + } + + /// A watch no event ever reaches, so every duty waits for its deadline. + pub fn never() -> Self { + let (_sender, head_slot) = watch::channel(0); + Self { head_slot } + } + + /// Resolves once the node has reported a head at `slot` or later, which + /// may already be the case. Never resolves if the stream has stopped for + /// good, so callers race it against their deadline. + pub async fn head_at(&self, slot: Slot) { + let mut head_slot = self.head_slot.clone(); + if head_slot.wait_for(|head| *head >= slot).await.is_err() { + std::future::pending::<()>().await; + } + } +} + +/// Sleeps for `deadline`, or less if the node reports a head at `slot` first. +/// Returns whether the head cut the wait short. +pub async fn until_deadline_or_head(deadline: Duration, head: &HeadWatch, slot: Slot) -> bool { + if deadline.is_zero() { + return false; + } + tokio::select! { + biased; + () = head.head_at(slot) => true, + () = tokio::time::sleep(deadline) => false, + } +} + +/// Reads the stream at `url` into `sender`, reopening it whenever it fails or +/// ends. Returns only when every receiver is gone. +async fn follow(url: String, sender: watch::Sender) { + let client = match Client::builder().connect_timeout(CONNECT_TIMEOUT).build() { + Ok(client) => client, + Err(err) => { + warn!(%err, "Cannot build the head event client; attesting at the deadline only"); + return; + } + }; + let mut backoff = INITIAL_BACKOFF; + loop { + match read_stream(&client, &url, &sender, &mut backoff).await { + Ok(()) => debug!(%url, "Head event stream ended; reopening"), + Err(err) => debug!(%url, %err, "Head event stream failed; reopening"), + } + if sender.is_closed() { + return; + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(MAX_BACKOFF); + } +} + +/// One connection's worth of events. Resets `backoff` once the stream is open. +async fn read_stream( + client: &Client, + url: &str, + sender: &watch::Sender, + backoff: &mut Duration, +) -> Result<(), String> { + let mut response = client + .get(url) + .header(reqwest::header::ACCEPT, "text/event-stream") + .send() + .await + .map_err(|err| err.to_string())?; + if !response.status().is_success() { + return Err(format!("status {}", response.status())); + } + info!(%url, "Following the beacon node's head events to attest on the block"); + *backoff = INITIAL_BACKOFF; + + let mut parser = EventParser::default(); + loop { + let chunk = tokio::time::timeout(IDLE_TIMEOUT, response.chunk()) + .await + .map_err(|_| "idle".to_string())? + .map_err(|err| err.to_string())?; + let Some(chunk) = chunk else { + return Ok(()); + }; + for slot in parser.push(&chunk) { + sender.send_if_modified(|head| { + let higher = slot > *head; + if higher { + *head = slot; + } + higher + }); + } + } +} + +/// An incremental `text/event-stream` reader that yields the slot of every +/// `head` event, and skips everything else. +#[derive(Debug, Default)] +struct EventParser { + pending: Vec, +} + +#[derive(Deserialize)] +struct HeadData { + #[serde(deserialize_with = "quoted_or_bare")] + slot: Slot, +} + +fn quoted_or_bare<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Either { + Quoted(String), + Bare(Slot), + } + match Either::deserialize(deserializer)? { + Either::Quoted(text) => text.parse().map_err(serde::de::Error::custom), + Either::Bare(slot) => Ok(slot), + } +} + +impl EventParser { + /// Feeds `bytes` in and returns the head slots of the events it completed. + fn push(&mut self, bytes: &[u8]) -> Vec { + self.pending.extend_from_slice(bytes); + let mut slots = Vec::new(); + while let Some((end, separator)) = find_event_end(&self.pending) { + let event: Vec = self.pending.drain(..end + separator).collect(); + if let Some(slot) = head_slot(&event[..end]) { + slots.push(slot); + } + } + slots + } +} + +/// Where the first complete event ends and how long its blank-line separator +/// is, for either line ending the format allows. +fn find_event_end(buffer: &[u8]) -> Option<(usize, usize)> { + let lf = buffer.windows(2).position(|window| window == b"\n\n"); + let crlf = buffer.windows(4).position(|window| window == b"\r\n\r\n"); + match (lf, crlf) { + (Some(lf), Some(crlf)) if crlf < lf => Some((crlf, 4)), + (Some(lf), _) => Some((lf, 2)), + (None, Some(crlf)) => Some((crlf, 4)), + (None, None) => None, + } +} + +/// The slot of one event, if it is a well-formed `head` event. +fn head_slot(event: &[u8]) -> Option { + let event = std::str::from_utf8(event).ok()?; + let mut name = None; + let mut data = String::new(); + for line in event.lines() { + let line = line.trim_end_matches('\r'); + if let Some(value) = line.strip_prefix("event:") { + name = Some(value.trim()); + } else if let Some(value) = line.strip_prefix("data:") { + if !data.is_empty() { + data.push('\n'); + } + data.push_str(value.strip_prefix(' ').unwrap_or(value)); + } + } + if name != Some("head") { + return None; + } + serde_json::from_str::(&data) + .ok() + .map(|head| head.slot) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEAD: &str = "event: head\ndata: {\"slot\":\"10\",\"block\":\"0x00\"}\n\n"; + + #[test] + fn a_head_event_yields_its_slot() { + let mut parser = EventParser::default(); + assert_eq!(parser.push(HEAD.as_bytes()), vec![10]); + } + + #[test] + fn an_event_split_across_chunks_is_read_once_whole() { + let mut parser = EventParser::default(); + let (first, second) = HEAD.split_at(17); + assert!(parser.push(first.as_bytes()).is_empty()); + assert_eq!(parser.push(second.as_bytes()), vec![10]); + } + + #[test] + fn other_events_comments_and_crlf_are_handled() { + let mut parser = EventParser::default(); + let stream = ": keep-alive\n\n\ + event: block\ndata: {\"slot\":\"11\"}\n\n\ + event: head\r\ndata: {\"slot\":12}\r\n\r\n"; + assert_eq!(parser.push(stream.as_bytes()), vec![12]); + } + + #[test] + fn a_malformed_head_event_is_skipped() { + let mut parser = EventParser::default(); + let stream = format!("event: head\ndata: {{\"slot\":\"x\"}}\n\n{HEAD}"); + assert_eq!(parser.push(stream.as_bytes()), vec![10]); + } + + #[tokio::test(start_paused = true)] + async fn the_deadline_is_the_fallback_without_a_head() { + let woke_early = + until_deadline_or_head(Duration::from_secs(3), &HeadWatch::never(), 5).await; + assert!(!woke_early); + } + + #[tokio::test(start_paused = true)] + async fn a_head_at_the_slot_cuts_the_wait_short() { + let (sender, head_slot) = watch::channel(0); + let head = HeadWatch { head_slot }; + let waiting = tokio::spawn({ + let head = head.clone(); + async move { until_deadline_or_head(Duration::from_secs(3), &head, 5).await } + }); + tokio::time::sleep(Duration::from_millis(500)).await; + sender.send_replace(4); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + !waiting.is_finished(), + "a head at an earlier slot is not this slot's block" + ); + sender.send_replace(5); + assert!(waiting.await.unwrap()); + drop(sender); + } +} diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 6b5ad2646..bdba5a415 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -32,6 +32,7 @@ pub mod doppelganger; pub mod duties; pub mod error; pub mod exit; +pub mod head_events; pub mod http_api; pub(crate) mod in_flight; pub mod keys; @@ -550,6 +551,14 @@ pub async fn run(config: ValidatorConfig, stop: impl Future head_events::HeadWatch::spawn(url, shutdown.clone()), + None => head_events::HeadWatch::never(), + }; let mut keymanager = None; if let Some(address) = config.keymanager { let token = http_api::load_or_create_token(&config.validators_dir)?; @@ -775,7 +784,13 @@ pub async fn run(config: ValidatorConfig, stop: impl Future( committee: &[crate::beacon_node::dto::PtcDutyDto], sync_duties: &[crate::beacon_node::dto::SyncDutyDto], store: &RwLock, + head: &head_events::HeadWatch, ) { // The sync committee work runs beside the attester and PTC work rather // than after it: its deadline is not ordered against theirs (gloas moves // it before the attestation) and each is bounded by the slot on its own. let attest_then_ptc = async { if !slot_duties.is_empty() { - tokio::time::sleep(clock.until_attestation(slot, SystemTime::now())).await; + // At the deadline, or as soon as the slot's block is in, whichever + // comes first, as the honest-validator guide has it. + let deadline = clock.until_attestation(slot, SystemTime::now()); + if head_events::until_deadline_or_head(deadline, head, slot).await { + debug!(%slot, "The slot's block is in; attesting ahead of the deadline"); + } attest_and_aggregate(attestation, aggregation, clock, slot, slot_duties, store).await; } @@ -2899,6 +2921,7 @@ mod tests { &committee, &[], &store, + &head_events::HeadWatch::never(), ) .await; @@ -3036,6 +3059,7 @@ mod tests { &[], &duties, &store, + &head_events::HeadWatch::never(), ) .await; @@ -3073,6 +3097,7 @@ mod tests { &[ptc_duty(3, 5)], &[], &store, + &head_events::HeadWatch::never(), ) .await; assert_eq!(node.payload_attestation_data_call_count(), 0); From 45d07cd220845537220754d5e0ee438efc3d7ad3 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 11:35:11 -0300 Subject: [PATCH 02/25] perf(rpc): check a submitted PQ attestation batch in parallel, off the executor post_pq_attestations ran one leanXMSS verification after another on the async handler, so the last vote of a validator client's batch waited for every other one's and the worker thread was held throughout. Run it on spawn_blocking, check the batch with rayon, and publish in submission order. --- Cargo.lock | 1 + crates/net/rpc/Cargo.toml | 3 ++ crates/net/rpc/src/beacon/pool.rs | 58 ++++++++++++++++++++++--------- docs/beacon_pq.md | 8 ++++- 4 files changed, 52 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7393b9052..145e5e236 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2179,6 +2179,7 @@ dependencies = [ "libssz 0.3.0 (git+https://github.com/lambdaclass/libssz?rev=5cb14378ffdadcb51b387c003567e2630d0c7073)", "libssz-derive 0.3.0 (git+https://github.com/lambdaclass/libssz?rev=5cb14378ffdadcb51b387c003567e2630d0c7073)", "libssz-types 0.3.0 (git+https://github.com/lambdaclass/libssz?rev=5cb14378ffdadcb51b387c003567e2630d0c7073)", + "rayon", "reqwest", "serde", "serde_json", diff --git a/crates/net/rpc/Cargo.toml b/crates/net/rpc/Cargo.toml index 32849860c..de9576f21 100644 --- a/crates/net/rpc/Cargo.toml +++ b/crates/net/rpc/Cargo.toml @@ -36,6 +36,9 @@ jemalloc_pprof.workspace = true reqwest.workspace = true thiserror.workspace = true futures-util = "0.3" +# A submitted batch of PQ attestations is checked in parallel: each one is a +# leanXMSS verification (`beacon::pool::post_pq_attestations`). +rayon.workspace = true [dev-dependencies] ethlambda-validator = { workspace = true, features = ["test-utils"] } diff --git a/crates/net/rpc/src/beacon/pool.rs b/crates/net/rpc/src/beacon/pool.rs index 2310724fd..3f51d7bb6 100644 --- a/crates/net/rpc/src/beacon/pool.rs +++ b/crates/net/rpc/src/beacon/pool.rs @@ -101,7 +101,16 @@ async fn post_pool_attestations( .and_then(|value| value.to_str().ok()) == Some(ForkName::Pq.as_str()); if is_pq { - return post_pq_attestations(&store, &p2p, &headers, &body); + // Off the executor: every attestation in the batch is a leanXMSS + // verification, which would otherwise hold this worker thread, and + // every other request queued on it, for the whole batch. + let checked = tokio::task::spawn_blocking(move || { + post_pq_attestations(&store, &p2p, &headers, &body) + }) + .await; + return checked.unwrap_or_else(|_| { + ApiError::Internal("PQ attestation validation task failed").into_response() + }); } let header_fork = match submission_fork(&headers) { Ok(fork) => fork, @@ -206,26 +215,41 @@ fn post_pq_attestations( .unwrap_or(0); let config = store.config(); // A fresh cache: the node gossips its own validator client's votes once. + // Only read by the checks, so the parallel ones below can share it. let seen = SeenAttestations::new(std::num::NonZeroUsize::MIN); + // Checked in parallel, since each is a leanXMSS verification and a + // validator client submits its whole slot's votes as one batch; checked + // one after another, the last vote in the batch waited for every other + // one's verification before it was published. Published below in the + // order submitted, so the failures still name positions in the array. + use rayon::prelude::*; + let verdicts: Vec<(u64, Outcome)> = attestations + .par_iter() + .map(|attestation| { + let committees_per_slot = store + .committee_cache() + .committees(&state, attestation.data.target.epoch) + .committees_per_slot(); + let subnet_id = pq_gossip::compute_subnet_for_attestation( + committees_per_slot, + attestation.data.slot, + attestation.committee_index, + &config, + ); + let verdict = pq_gossip::attestation_cheap_checks(&seen, store, attestation, now_ms) + .err() + .unwrap_or_else(|| { + pq_gossip::attestation_stateful_checks(store, attestation, subnet_id) + }); + (subnet_id, verdict) + }) + .collect(); let mut failures = Vec::new(); - for (index, attestation) in attestations.into_iter().enumerate() { + for (index, (attestation, (subnet_id, verdict))) in + attestations.into_iter().zip(verdicts).enumerate() + { let slot = attestation.data.slot; let validator = attestation.attester_index; - let committees_per_slot = store - .committee_cache() - .committees(&state, attestation.data.target.epoch) - .committees_per_slot(); - let subnet_id = pq_gossip::compute_subnet_for_attestation( - committees_per_slot, - slot, - attestation.committee_index, - &config, - ); - let verdict = pq_gossip::attestation_cheap_checks(&seen, store, &attestation, now_ms) - .err() - .unwrap_or_else(|| { - pq_gossip::attestation_stateful_checks(store, &attestation, subnet_id) - }); let published = match verdict { Outcome::Accept => { // This node's own aggregator may be collecting the committee. diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 11559abd4..0bc7fac2e 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -389,7 +389,13 @@ A start drops the leaves of slots more than two epochs back, which nothing asks for again. - **Attesting**: a `SingleAttestation` signed at the target epoch's leaf, - published on one of PQ's 16 subnets. + published on one of PQ's 16 subnets. The client votes as soon as its first + beacon node reports a `head` event at the slot, or at the attestation + deadline if none arrives first (`head_events`), as the honest-validator + guide asks; it used to wait for the deadline every slot, which put its + votes behind every client that votes on the block. The node checks a + submitted batch in parallel, off the async executor, and publishes it in + submission order. - **The PTC vote**: as gloas's, signed at the slot's PTC leaf. - **Proposing**: the client sends its VRF proof for the slot (the RANDAO reveal) to `POST /eth/v1/validator/pq_blocks/{slot}`, signs the block and From aad0dc9cf85807a59807cf8749c71d4f261b6667 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 11:52:43 -0300 Subject: [PATCH 03/25] Revert "feat(validator): attest once the slot's block is in, not always at the deadline" This reverts commit 24a9e5a63fd1a346d4b9cb5d43cc9b2ec1a46e58. --- crates/validator/src/head_events.rs | 305 ---------------------------- crates/validator/src/lib.rs | 29 +-- 2 files changed, 2 insertions(+), 332 deletions(-) delete mode 100644 crates/validator/src/head_events.rs diff --git a/crates/validator/src/head_events.rs b/crates/validator/src/head_events.rs deleted file mode 100644 index 242cf286c..000000000 --- a/crates/validator/src/head_events.rs +++ /dev/null @@ -1,305 +0,0 @@ -//! The beacon node's `head` events, used only to attest early. -//! -//! The honest-validator guide has an attester vote once it has seen a valid -//! block for its slot *or* once `ATTESTATION_DUE_BPS` of the slot has passed, -//! whichever comes first. The duty loop used to wait for the deadline every -//! slot, so this client's votes always went out after it, a full deadline -//! behind clients that vote on the block. This module is the "has seen the -//! block" half. -//! -//! It is a hint and nothing more. The duty loop still runs on its own clock -//! (see [`crate::slot_clock`]): the event stream is best-effort by contract and -//! may drop events, so the deadline stays the fallback, and a stream that is -//! down, slow or never connects costs the early vote only, never the duty. -//! -//! # Only the first beacon node -//! -//! `attestation_data` is asked of the beacon nodes in order, so the vote is -//! the first healthy node's head. A head event from another node could wake -//! the duty before that node has the block, and the vote would then name the -//! previous head. Listening to the first node alone keeps the wake and the -//! answer on one node; when it is down, the duty falls back to the deadline. - -use std::time::Duration; - -use ethlambda_types::beacon::primitives::Slot; -use reqwest::Client; -use serde::Deserialize; -use tokio::sync::watch; -use tokio_util::sync::CancellationToken; -use tracing::{debug, info, warn}; - -/// How long establishing the stream's connection may take. -const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); - -/// How long the stream may stay silent before it is reopened. A node sends a -/// head event every slot it imports a block in, so a minute of silence is a -/// connection that died without closing, or a chain that is not moving, and -/// reopening costs nothing in the second case. -const IDLE_TIMEOUT: Duration = Duration::from_secs(60); - -/// The wait before reopening a stream that failed, doubled on every failure -/// in a row up to [`MAX_BACKOFF`]. -const INITIAL_BACKOFF: Duration = Duration::from_millis(500); -const MAX_BACKOFF: Duration = Duration::from_secs(12); - -/// The highest head slot the beacon node has reported, shared with the duty -/// loop. -#[derive(Debug, Clone)] -pub struct HeadWatch { - head_slot: watch::Receiver, -} - -impl HeadWatch { - /// Subscribes to `base_url`'s `head` events on a task of its own, which - /// reconnects until `shutdown` is cancelled. - pub fn spawn(base_url: &str, shutdown: CancellationToken) -> Self { - let (sender, head_slot) = watch::channel(0); - let url = format!( - "{}/eth/v1/events?topics=head", - base_url.trim_end_matches('/') - ); - tokio::spawn(async move { - tokio::select! { - () = shutdown.cancelled() => {} - () = follow(url, sender) => {} - } - }); - Self { head_slot } - } - - /// A watch no event ever reaches, so every duty waits for its deadline. - pub fn never() -> Self { - let (_sender, head_slot) = watch::channel(0); - Self { head_slot } - } - - /// Resolves once the node has reported a head at `slot` or later, which - /// may already be the case. Never resolves if the stream has stopped for - /// good, so callers race it against their deadline. - pub async fn head_at(&self, slot: Slot) { - let mut head_slot = self.head_slot.clone(); - if head_slot.wait_for(|head| *head >= slot).await.is_err() { - std::future::pending::<()>().await; - } - } -} - -/// Sleeps for `deadline`, or less if the node reports a head at `slot` first. -/// Returns whether the head cut the wait short. -pub async fn until_deadline_or_head(deadline: Duration, head: &HeadWatch, slot: Slot) -> bool { - if deadline.is_zero() { - return false; - } - tokio::select! { - biased; - () = head.head_at(slot) => true, - () = tokio::time::sleep(deadline) => false, - } -} - -/// Reads the stream at `url` into `sender`, reopening it whenever it fails or -/// ends. Returns only when every receiver is gone. -async fn follow(url: String, sender: watch::Sender) { - let client = match Client::builder().connect_timeout(CONNECT_TIMEOUT).build() { - Ok(client) => client, - Err(err) => { - warn!(%err, "Cannot build the head event client; attesting at the deadline only"); - return; - } - }; - let mut backoff = INITIAL_BACKOFF; - loop { - match read_stream(&client, &url, &sender, &mut backoff).await { - Ok(()) => debug!(%url, "Head event stream ended; reopening"), - Err(err) => debug!(%url, %err, "Head event stream failed; reopening"), - } - if sender.is_closed() { - return; - } - tokio::time::sleep(backoff).await; - backoff = (backoff * 2).min(MAX_BACKOFF); - } -} - -/// One connection's worth of events. Resets `backoff` once the stream is open. -async fn read_stream( - client: &Client, - url: &str, - sender: &watch::Sender, - backoff: &mut Duration, -) -> Result<(), String> { - let mut response = client - .get(url) - .header(reqwest::header::ACCEPT, "text/event-stream") - .send() - .await - .map_err(|err| err.to_string())?; - if !response.status().is_success() { - return Err(format!("status {}", response.status())); - } - info!(%url, "Following the beacon node's head events to attest on the block"); - *backoff = INITIAL_BACKOFF; - - let mut parser = EventParser::default(); - loop { - let chunk = tokio::time::timeout(IDLE_TIMEOUT, response.chunk()) - .await - .map_err(|_| "idle".to_string())? - .map_err(|err| err.to_string())?; - let Some(chunk) = chunk else { - return Ok(()); - }; - for slot in parser.push(&chunk) { - sender.send_if_modified(|head| { - let higher = slot > *head; - if higher { - *head = slot; - } - higher - }); - } - } -} - -/// An incremental `text/event-stream` reader that yields the slot of every -/// `head` event, and skips everything else. -#[derive(Debug, Default)] -struct EventParser { - pending: Vec, -} - -#[derive(Deserialize)] -struct HeadData { - #[serde(deserialize_with = "quoted_or_bare")] - slot: Slot, -} - -fn quoted_or_bare<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { - #[derive(Deserialize)] - #[serde(untagged)] - enum Either { - Quoted(String), - Bare(Slot), - } - match Either::deserialize(deserializer)? { - Either::Quoted(text) => text.parse().map_err(serde::de::Error::custom), - Either::Bare(slot) => Ok(slot), - } -} - -impl EventParser { - /// Feeds `bytes` in and returns the head slots of the events it completed. - fn push(&mut self, bytes: &[u8]) -> Vec { - self.pending.extend_from_slice(bytes); - let mut slots = Vec::new(); - while let Some((end, separator)) = find_event_end(&self.pending) { - let event: Vec = self.pending.drain(..end + separator).collect(); - if let Some(slot) = head_slot(&event[..end]) { - slots.push(slot); - } - } - slots - } -} - -/// Where the first complete event ends and how long its blank-line separator -/// is, for either line ending the format allows. -fn find_event_end(buffer: &[u8]) -> Option<(usize, usize)> { - let lf = buffer.windows(2).position(|window| window == b"\n\n"); - let crlf = buffer.windows(4).position(|window| window == b"\r\n\r\n"); - match (lf, crlf) { - (Some(lf), Some(crlf)) if crlf < lf => Some((crlf, 4)), - (Some(lf), _) => Some((lf, 2)), - (None, Some(crlf)) => Some((crlf, 4)), - (None, None) => None, - } -} - -/// The slot of one event, if it is a well-formed `head` event. -fn head_slot(event: &[u8]) -> Option { - let event = std::str::from_utf8(event).ok()?; - let mut name = None; - let mut data = String::new(); - for line in event.lines() { - let line = line.trim_end_matches('\r'); - if let Some(value) = line.strip_prefix("event:") { - name = Some(value.trim()); - } else if let Some(value) = line.strip_prefix("data:") { - if !data.is_empty() { - data.push('\n'); - } - data.push_str(value.strip_prefix(' ').unwrap_or(value)); - } - } - if name != Some("head") { - return None; - } - serde_json::from_str::(&data) - .ok() - .map(|head| head.slot) -} - -#[cfg(test)] -mod tests { - use super::*; - - const HEAD: &str = "event: head\ndata: {\"slot\":\"10\",\"block\":\"0x00\"}\n\n"; - - #[test] - fn a_head_event_yields_its_slot() { - let mut parser = EventParser::default(); - assert_eq!(parser.push(HEAD.as_bytes()), vec![10]); - } - - #[test] - fn an_event_split_across_chunks_is_read_once_whole() { - let mut parser = EventParser::default(); - let (first, second) = HEAD.split_at(17); - assert!(parser.push(first.as_bytes()).is_empty()); - assert_eq!(parser.push(second.as_bytes()), vec![10]); - } - - #[test] - fn other_events_comments_and_crlf_are_handled() { - let mut parser = EventParser::default(); - let stream = ": keep-alive\n\n\ - event: block\ndata: {\"slot\":\"11\"}\n\n\ - event: head\r\ndata: {\"slot\":12}\r\n\r\n"; - assert_eq!(parser.push(stream.as_bytes()), vec![12]); - } - - #[test] - fn a_malformed_head_event_is_skipped() { - let mut parser = EventParser::default(); - let stream = format!("event: head\ndata: {{\"slot\":\"x\"}}\n\n{HEAD}"); - assert_eq!(parser.push(stream.as_bytes()), vec![10]); - } - - #[tokio::test(start_paused = true)] - async fn the_deadline_is_the_fallback_without_a_head() { - let woke_early = - until_deadline_or_head(Duration::from_secs(3), &HeadWatch::never(), 5).await; - assert!(!woke_early); - } - - #[tokio::test(start_paused = true)] - async fn a_head_at_the_slot_cuts_the_wait_short() { - let (sender, head_slot) = watch::channel(0); - let head = HeadWatch { head_slot }; - let waiting = tokio::spawn({ - let head = head.clone(); - async move { until_deadline_or_head(Duration::from_secs(3), &head, 5).await } - }); - tokio::time::sleep(Duration::from_millis(500)).await; - sender.send_replace(4); - tokio::time::sleep(Duration::from_millis(500)).await; - assert!( - !waiting.is_finished(), - "a head at an earlier slot is not this slot's block" - ); - sender.send_replace(5); - assert!(waiting.await.unwrap()); - drop(sender); - } -} diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index bdba5a415..6b5ad2646 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -32,7 +32,6 @@ pub mod doppelganger; pub mod duties; pub mod error; pub mod exit; -pub mod head_events; pub mod http_api; pub(crate) mod in_flight; pub mod keys; @@ -551,14 +550,6 @@ pub async fn run(config: ValidatorConfig, stop: impl Future head_events::HeadWatch::spawn(url, shutdown.clone()), - None => head_events::HeadWatch::never(), - }; let mut keymanager = None; if let Some(address) = config.keymanager { let token = http_api::load_or_create_token(&config.validators_dir)?; @@ -784,13 +775,7 @@ pub async fn run(config: ValidatorConfig, stop: impl Future( committee: &[crate::beacon_node::dto::PtcDutyDto], sync_duties: &[crate::beacon_node::dto::SyncDutyDto], store: &RwLock, - head: &head_events::HeadWatch, ) { // The sync committee work runs beside the attester and PTC work rather // than after it: its deadline is not ordered against theirs (gloas moves // it before the attestation) and each is bounded by the slot on its own. let attest_then_ptc = async { if !slot_duties.is_empty() { - // At the deadline, or as soon as the slot's block is in, whichever - // comes first, as the honest-validator guide has it. - let deadline = clock.until_attestation(slot, SystemTime::now()); - if head_events::until_deadline_or_head(deadline, head, slot).await { - debug!(%slot, "The slot's block is in; attesting ahead of the deadline"); - } + tokio::time::sleep(clock.until_attestation(slot, SystemTime::now())).await; attest_and_aggregate(attestation, aggregation, clock, slot, slot_duties, store).await; } @@ -2921,7 +2899,6 @@ mod tests { &committee, &[], &store, - &head_events::HeadWatch::never(), ) .await; @@ -3059,7 +3036,6 @@ mod tests { &[], &duties, &store, - &head_events::HeadWatch::never(), ) .await; @@ -3097,7 +3073,6 @@ mod tests { &[ptc_duty(3, 5)], &[], &store, - &head_events::HeadWatch::never(), ) .await; assert_eq!(node.payload_attestation_data_call_count(), 0); From a5eb14e2cbd820c6bf6216b742bf53415177029f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:10:49 -0300 Subject: [PATCH 04/25] feat(validator): attest when the slot's block arrives, vote PTC when its payload does The validator client signed attestations, sync committee messages and PTC votes at their clock offsets only. The specification asks for whichever comes first: the slot's block (its payload and blob data, for the PTC vote) or the offset. Every other validator client the issue surveys attests on the block by default. beacon_node/events.rs reads GET /eth/v1/events with Response::chunk and a small SSE parser (reqwest's stream feature would change Cargo.lock), on a client of its own with a connect timeout and a 60 s idle timeout. head_monitor.rs reads every configured node's stream, one connection per topic (head, plus execution_payload_available when gloas is scheduled), reconnecting with backoff, and wakes each duty on the earlier of its event and its clock offset. The early attempt signs only when the node's answer names the event's block (and, for the PTC vote, says payload_present and blob_data_available); otherwise nothing is recorded, and the duty asks again on the next report about the slot it has not tried (the answering node's own, typically) or runs at its deadline, so each duty is still signed at most once a slot. The services gained a fetch half and a sign half for that check. A stream that idles out (quiet by design before gloas, on a node with no keep-alives) reopens with debug logging only. The duty loop's sleep to the first duty now ends on the block too, and the PTC vote runs beside attest+aggregate rather than after the aggregation. --disable-event-stream turns it all off. ethlambda_validator_duty_triggers_total{duty,trigger} counts what started each duty. Closes #829. --- bin/ethlambda/src/validator.rs | 13 + crates/validator/src/attestation.rs | 33 +- crates/validator/src/beacon_node/events.rs | 827 ++++++++++++ crates/validator/src/beacon_node/mock.rs | 116 +- crates/validator/src/beacon_node/mod.rs | 1 + crates/validator/src/head_monitor.rs | 1324 +++++++++++++++++++ crates/validator/src/lib.rs | 152 ++- crates/validator/src/metrics.rs | 58 +- crates/validator/src/payload_attestation.rs | 89 +- crates/validator/src/slot_clock.rs | 4 +- crates/validator/src/sync_committee.rs | 51 +- docs/cli.md | 63 +- docs/metrics.md | 4 +- 13 files changed, 2636 insertions(+), 99 deletions(-) create mode 100644 crates/validator/src/beacon_node/events.rs create mode 100644 crates/validator/src/head_monitor.rs diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index d268dd40d..d0651928f 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -205,6 +205,17 @@ pub(crate) struct ValidatorOptions { /// instead, about 2.4 s per key across the cores. #[arg(long)] pub(crate) xmss_cache_url: Option, + + /// Read no beacon node's event stream: every attestation and sync + /// committee message waits for its offset into the slot, and every + /// payload timeliness committee vote for its deadline, even when the + /// slot's block or payload has already arrived. + /// + /// On by default, the stream lets those duties go out as soon as the + /// block (or the payload) does. Off is for a beacon node whose stream is + /// broken, or a proxy in front of it that holds events back. + #[arg(long, default_value = "false")] + pub(crate) disable_event_stream: bool, } impl ValidatorOptions { @@ -325,6 +336,7 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { doppelganger_protection: options.enable_doppelganger_protection, vrf_state_url: options.vrf_state_url, xmss_cache_url: options.xmss_cache_url, + event_stream: !options.disable_event_stream, }; ethlambda_validator::run(config, stop) .await @@ -356,6 +368,7 @@ mod tests { enable_doppelganger_protection: false, vrf_state_url: None, xmss_cache_url: None, + disable_event_stream: false, } } diff --git a/crates/validator/src/attestation.rs b/crates/validator/src/attestation.rs index ac345f721..9a8c58b23 100644 --- a/crates/validator/src/attestation.rs +++ b/crates/validator/src/attestation.rs @@ -111,7 +111,39 @@ impl AttestationService { data: None, }); } + let data = self.attestation_data(slot).await?; + self.attest_with(slot, duties, store, data).await + } + /// The beacon node's attestation data for `slot`, checked as [`Self::attest`] + /// checks it, with nothing recorded and nothing signed. + /// + /// For a caller that must look at the data before committing to it: the + /// duty loop's early trigger signs only data that names the block a head + /// event announced, and otherwise leaves the duty to its deadline (see + /// [`crate::head_monitor`]). Whatever it decides, it makes one call to + /// [`Self::attest_with`] or [`Self::attest`] for the slot, never both. + pub async fn attestation_data(&self, slot: Slot) -> Result { + let slot_fork = self + .context + .config + .fork_at_epoch(compute_epoch_at_slot(slot)); + let data = self.beacon_node.attestation_data(slot, slot_fork).await?; + validate_attestation_data(slot, slot_fork, &data)?; + Ok(data) + } + + /// [`Self::attest`], over `data` already fetched for `slot` with + /// [`Self::attestation_data`] instead of fetching it here. + /// + /// The same rule holds: one call of this or [`Self::attest`] per slot. + pub async fn attest_with( + &self, + slot: Slot, + duties: &[AttesterDutyDto], + store: &RwLock, + data: AttestationData, + ) -> Result { // The fork of the slot, by this client's own schedule, decides which // `index` the answer may carry: from gloas it is the payload signal. // It is signed as received, never reset to zero. @@ -119,7 +151,6 @@ impl AttestationService { .context .config .fork_at_epoch(compute_epoch_at_slot(slot)); - let data = self.beacon_node.attestation_data(slot, slot_fork).await?; // Checked again here, having already been checked by the // implementation this call went through (see the contract on diff --git a/crates/validator/src/beacon_node/events.rs b/crates/validator/src/beacon_node/events.rs new file mode 100644 index 000000000..c0204b63b --- /dev/null +++ b/crates/validator/src/beacon_node/events.rs @@ -0,0 +1,827 @@ +//! The beacon node's event stream, `GET /eth/v1/events`, read as +//! server-sent events. +//! +//! Only the two topics the duty loop acts on are read (see +//! [`crate::head_monitor`]): `head`, and from gloas +//! `execution_payload_available`. Everything else a node might send is +//! skipped. +//! +//! # No new dependency +//! +//! `reqwest`'s `bytes_stream` needs its `stream` feature, which would pull +//! `futures-util` and `tokio-util` into reqwest's own dependency set. The body +//! is read with [`reqwest::Response::chunk`] instead, which every build has, +//! and the frames are parsed here by [`SseParser`]: the format is a few lines +//! of the HTML specification's "Server-sent events" section, and an event this +//! client reads is a few hundred bytes. +//! +//! # A stream is best-effort +//! +//! A node drops events for a subscriber that reads too slowly, restarts, or +//! sits behind a proxy that buffers. Nothing here is relied on for a duty to +//! happen: the slot clock's offsets stay every duty's deadline, and an event +//! can only make a duty earlier (see `crate::slot_clock`). + +use std::collections::VecDeque; +use std::time::Duration; + +use async_trait::async_trait; +use ethlambda_types::beacon::primitives::{Root, Slot}; +use reqwest::{Client, StatusCode}; +use serde::Deserialize; +use tracing::warn; + +use crate::beacon_node::dto::{parse_root, quoted_u64}; +use crate::error::{BeaconNodeFailure, Error, Result}; + +/// How long establishing the connection may take: the bound +/// `HttpBeaconNode` puts on its own requests. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); + +/// How long the node may take to answer a subscription with its status and +/// headers, once connected: `HttpBeaconNode`'s bound on a whole request. A +/// node streams its events after the headers, so this bounds only the start, +/// and a node that takes the connection and never answers does not hold the +/// reader on it. +const RESPONSE_TIMEOUT: Duration = Duration::from_secs(8); + +/// How long an open stream may send nothing at all before it is taken for +/// dead and opened again. +/// +/// Four times the 15-second keep-alive interval ethlambda's node sends on an +/// idle stream (axum's default), so a live stream there never trips it. Other +/// nodes may send keep-alives less often or not at all, and a stream that is +/// quiet by design (`execution_payload_available` before gloas) then trips it +/// every minute: that reopen is routine, and is logged at debug (see +/// [`is_idle_timeout`]). What it guards against is a connection whose far end +/// is gone without a word, which would otherwise hold a stream open that never +/// delivers again. +pub const IDLE_TIMEOUT: Duration = Duration::from_secs(60); + +/// The most one event may take, its `event:` and `data:` lines together, +/// before the stream is dropped as broken. +/// +/// An event this client reads is a few hundred bytes. The cap is what stops a +/// node that sends an endless line from growing the buffer without bound. +pub const MAX_FRAME_BYTES: usize = 64 * 1024; + +/// How much of a refused subscription's body an error carries. +const ERROR_BODY_LIMIT: usize = 1024; + +/// A Beacon API event topic this client reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Topic { + /// Fork choice picked a new head. + Head, + /// Gloas: a block's execution payload, and its blob data, are available. + ExecutionPayloadAvailable, +} + +impl Topic { + /// The topic's name on the wire, both in the `topics` query and on the + /// `event:` line. + pub fn as_str(self) -> &'static str { + match self { + Topic::Head => "head", + Topic::ExecutionPayloadAvailable => "execution_payload_available", + } + } +} + +/// An event the duty loop acts on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeEvent { + Head(HeadEvent), + PayloadAvailable(PayloadAvailableEvent), +} + +/// What a `head` event says that this client uses: the head's slot and root, +/// and whether the execution client has validated it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HeadEvent { + pub slot: Slot, + pub block: Root, + pub execution_optimistic: bool, +} + +/// An `execution_payload_available` event: the payload of the block at +/// `block_root`, in `slot`, and its blob data, are available to the node. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PayloadAvailableEvent { + pub slot: Slot, + pub block_root: Root, +} + +/// `head`'s payload, less the fields this client does not read (the state +/// root, `epoch_transition` and the two dependent roots). +#[derive(Deserialize)] +struct HeadDto { + #[serde(deserialize_with = "quoted_u64::deserialize")] + slot: u64, + block: String, + /// `Option` and read as `false` when absent, as `head_block_root`'s + /// answer is: a node that predates the field does not do optimistic sync. + execution_optimistic: Option, +} + +/// `execution_payload_available`'s payload. +#[derive(Deserialize)] +struct PayloadAvailableDto { + #[serde(deserialize_with = "quoted_u64::deserialize")] + slot: u64, + block_root: String, +} + +/// The event `frame` carries, `None` for a topic this client does not read, +/// or an error naming what is wrong with one it does. +pub fn decode(frame: &SseFrame) -> Option> { + let event = if frame.event == Topic::Head.as_str() { + serde_json::from_str::(&frame.data) + .map_err(|err| Error::Decode(format!("head event: {err}"))) + .and_then(|dto| { + Ok(NodeEvent::Head(HeadEvent { + slot: dto.slot, + block: parse_root(&dto.block)?, + execution_optimistic: dto.execution_optimistic.unwrap_or(false), + })) + }) + } else if frame.event == Topic::ExecutionPayloadAvailable.as_str() { + serde_json::from_str::(&frame.data) + .map_err(|err| Error::Decode(format!("execution_payload_available event: {err}"))) + .and_then(|dto| { + Ok(NodeEvent::PayloadAvailable(PayloadAvailableEvent { + slot: dto.slot, + block_root: parse_root(&dto.block_root)?, + })) + }) + } else { + return None; + }; + Some(event) +} + +/// One server-sent event: its `event:` name and its `data:` lines. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SseFrame { + /// `message` when the frame named none, as the format specifies. + pub event: String, + /// Every `data:` line of the frame, joined with `\n`. + pub data: String, +} + +/// An event, its `event:` and `data:` lines together, ran past +/// [`MAX_FRAME_BYTES`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FrameTooLong; + +/// Server-sent events, parsed from a body that arrives in pieces cut +/// anywhere. +/// +/// The HTML specification's "Server-sent events" interpretation, less what +/// this client has no use for (`id:` and `retry:` are read and ignored: a +/// reconnect asks for the stream afresh, on this client's own backoff): +/// +/// - A line ends at `\n`, `\r\n` or `\r`, and a `\r\n` split between two +/// pieces is still one line end. +/// - A line starting with `:` is a comment: a keep-alive, or ethlambda's and +/// Lighthouse's `: error - dropped N messages`. +/// - `field: value` sets a field, with one space after the colon dropped if +/// there is one; a line with no colon is a field with an empty value. +/// - `data:` lines accumulate, joined with `\n`; a blank line ends the frame, +/// and a frame with no `data:` line is dropped. +/// - A byte-order mark at the very start of the stream is dropped. +/// +/// Bytes are buffered, not text, since a piece can end in the middle of a +/// UTF-8 sequence; each line is decoded once it is whole, and the line-ending +/// bytes cannot occur inside a multi-byte sequence. +#[derive(Debug, Default)] +pub struct SseParser { + /// The line being read, without its ending. + line: Vec, + /// The frame's `event:` value, empty until one arrives. + event: String, + /// The frame's `data:` lines so far, `None` until one arrives. + data: Option, + /// The last byte read ended a line with `\r`, so a `\n` that follows + /// belongs to that ending. + after_cr: bool, + /// A line has been read, so a byte-order mark is no longer the stream's + /// first character. + started: bool, +} + +impl SseParser { + /// Feed the next piece of the body, and take every frame it completes. + /// + /// An error leaves the parser in no state worth continuing from: the + /// caller drops the stream. + pub fn push(&mut self, bytes: &[u8]) -> std::result::Result, FrameTooLong> { + let mut frames = Vec::new(); + for &byte in bytes { + match byte { + b'\n' if self.after_cr => self.after_cr = false, + b'\n' | b'\r' => { + self.after_cr = byte == b'\r'; + frames.extend(self.end_line()); + } + _ => { + self.after_cr = false; + self.line.push(byte); + } + } + let held = + self.line.len() + self.event.len() + self.data.as_ref().map_or(0, String::len); + if held > MAX_FRAME_BYTES { + return Err(FrameTooLong); + } + } + Ok(frames) + } + + /// Act on the line just ended, returning the frame it completes, if any. + fn end_line(&mut self) -> Option { + let bytes = std::mem::take(&mut self.line); + let text = String::from_utf8_lossy(&bytes); + let mut line: &str = &text; + if !self.started { + self.started = true; + line = line.strip_prefix('\u{feff}').unwrap_or(line); + } + + if line.is_empty() { + return self.dispatch(); + } + if line.starts_with(':') { + return None; + } + let (field, value) = match line.split_once(':') { + Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), + None => (line, ""), + }; + match field { + "event" => self.event = value.to_string(), + "data" => match &mut self.data { + Some(data) => { + data.push('\n'); + data.push_str(value); + } + None => self.data = Some(value.to_string()), + }, + // `id`, `retry`, and any field the format does not define. + _ => {} + } + None + } + + /// End the frame being built. Its fields are cleared whether or not it + /// had any data to dispatch. + fn dispatch(&mut self) -> Option { + let event = std::mem::take(&mut self.event); + let data = self.data.take()?; + let event = if event.is_empty() { + "message".to_string() + } else { + event + }; + Some(SseFrame { event, data }) + } +} + +/// Where a beacon node's events come from. +/// +/// A trait so the duty loop's triggers can be driven by a scripted mock (see +/// `beacon_node::mock`), as [`crate::beacon_node::BeaconNodeApi`] is. +#[async_trait] +pub trait EventSource: Send + Sync { + /// Open the node's stream for `topics`. + /// + /// An `Err` when the node cannot be reached or refuses the subscription. + async fn subscribe(&self, topics: &[Topic]) -> Result>; +} + +/// One open event stream. +#[async_trait] +pub trait EventStream: Send { + /// The next event this client reads, `Ok(None)` once the node has closed + /// the stream, or an `Err` once it broke. Either way the stream is done. + async fn next_event(&mut self) -> Result>; +} + +/// An [`EventSource`] reading one beacon node's `GET /eth/v1/events`. +pub struct HttpEventSource { + base_url: String, + /// Its own client, not `HttpBeaconNode`'s: that one's total timeout runs + /// until a body is finished, and a stream's never is. This one bounds the + /// connection alone, and [`IDLE_TIMEOUT`] the silence on it. + client: Client, +} + +impl HttpEventSource { + /// A source for the node at `base_url`, a trailing slash stripped as + /// `HttpBeaconNode::new` strips one. + pub fn new(base_url: impl Into) -> Result { + let base_url = base_url.into().trim_end_matches('/').to_string(); + let client = Client::builder() + .connect_timeout(CONNECT_TIMEOUT) + .build() + .map_err(|err| transport(&base_url, &err))?; + Ok(Self { base_url, client }) + } + + pub fn base_url(&self) -> &str { + &self.base_url + } +} + +#[async_trait] +impl EventSource for HttpEventSource { + async fn subscribe(&self, topics: &[Topic]) -> Result> { + // The specification's form, one `topics` per topic, rather than the + // comma-joined list some nodes also accept. The duty loop opens one + // topic per stream anyway (see `head_monitor`), so the two forms are + // the same request. + let query = topics + .iter() + .map(|topic| format!("topics={}", topic.as_str())) + .collect::>() + .join("&"); + let url = format!("{}/eth/v1/events?{query}", self.base_url); + let request = self + .client + .get(&url) + .header(reqwest::header::ACCEPT, "text/event-stream") + .send(); + let response = tokio::time::timeout(RESPONSE_TIMEOUT, request) + .await + .map_err(|_| Error::BeaconNode { + url: self.base_url.clone(), + failure: BeaconNodeFailure::Timeout, + detail: format!( + "the event stream was not answered within {} s", + RESPONSE_TIMEOUT.as_secs() + ), + })? + .map_err(|err| transport(&self.base_url, &err))?; + let status = response.status(); + if status != StatusCode::OK { + return Err(Error::BeaconNodeStatus { + status: status.as_u16(), + body: body_excerpt(response).await, + }); + } + Ok(Box::new(HttpEventStream { + base_url: self.base_url.clone(), + response, + parser: SseParser::default(), + decoded: VecDeque::new(), + })) + } +} + +/// A stream [`HttpEventSource`] opened. +struct HttpEventStream { + base_url: String, + response: reqwest::Response, + parser: SseParser, + /// Events a body piece completed and `next_event` has not handed out. + decoded: VecDeque, +} + +#[async_trait] +impl EventStream for HttpEventStream { + async fn next_event(&mut self) -> Result> { + loop { + if let Some(event) = self.decoded.pop_front() { + return Ok(Some(event)); + } + let chunk = match tokio::time::timeout(IDLE_TIMEOUT, self.response.chunk()).await { + Err(_) => { + return Err(Error::BeaconNode { + url: self.base_url.clone(), + failure: BeaconNodeFailure::Timeout, + detail: format!( + "the event stream sent nothing for {} s", + IDLE_TIMEOUT.as_secs() + ), + }); + } + Ok(Err(err)) => return Err(transport(&self.base_url, &err)), + Ok(Ok(None)) => return Ok(None), + Ok(Ok(Some(chunk))) => chunk, + }; + let frames = self.parser.push(&chunk).map_err(|FrameTooLong| { + Error::Decode(format!( + "an event on {}'s stream runs past {MAX_FRAME_BYTES} bytes", + self.base_url + )) + })?; + for frame in frames { + match decode(&frame) { + Some(Ok(event)) => self.decoded.push_back(event), + // One bad event is skipped, not the stream: the next + // slot's may well be fine, and the duty has its deadline. + Some(Err(err)) => warn!( + node = %self.base_url, + event = %frame.event, + %err, + "Skipping a malformed event from the beacon node" + ), + None => {} + } + } + } + } +} + +/// Whether `err`, from [`EventStream::next_event`], is a stream that went +/// quiet for [`IDLE_TIMEOUT`] rather than one that broke. +/// +/// The stream's client has no total timeout, so a timeout on an open stream +/// can only be that one. +pub fn is_idle_timeout(err: &Error) -> bool { + matches!( + err, + Error::BeaconNode { + failure: BeaconNodeFailure::Timeout, + .. + } + ) +} + +/// A `reqwest` failure as this crate's beacon-node error. +fn transport(base_url: &str, err: &reqwest::Error) -> Error { + Error::BeaconNode { + url: base_url.to_string(), + failure: BeaconNodeFailure::classify(err), + detail: err.to_string(), + } +} + +/// The start of a refused subscription's body, as one line, for the error. +/// Read a piece at a time and only up to [`ERROR_BODY_LIMIT`], so a node +/// answering with an endless body cannot hold the reconnect on it. +async fn body_excerpt(mut response: reqwest::Response) -> String { + let mut bytes = Vec::new(); + while bytes.len() < ERROR_BODY_LIMIT { + let Ok(Ok(Some(chunk))) = tokio::time::timeout(CONNECT_TIMEOUT, response.chunk()).await + else { + break; + }; + bytes.extend_from_slice(&chunk[..chunk.len().min(ERROR_BODY_LIMIT - bytes.len())]); + } + ethlambda_types::text::one_line(&String::from_utf8_lossy(&bytes), ERROR_BODY_LIMIT) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(event: &str, data: &str) -> SseFrame { + SseFrame { + event: event.to_string(), + data: data.to_string(), + } + } + + fn root_hex(byte: u8) -> String { + format!("0x{}", hex::encode([byte; 32])) + } + + fn head_json(slot: u64, byte: u8, optimistic: bool) -> String { + format!( + r#"{{"slot":"{slot}","block":"{}","state":"{}","epoch_transition":false,"previous_duty_dependent_root":"{}","current_duty_dependent_root":"{}","execution_optimistic":{optimistic}}}"#, + root_hex(byte), + root_hex(0xee), + root_hex(0xdd), + root_hex(0xcc), + ) + } + + // The parser. + + #[test] + fn a_frame_ends_at_a_blank_line() { + let mut parser = SseParser::default(); + let frames = parser + .push(b"event: head\ndata: {\"a\":1}\n\n") + .expect("parses"); + assert_eq!(frames, vec![frame("head", "{\"a\":1}")]); + } + + #[test] + fn nothing_is_dispatched_before_the_blank_line() { + let mut parser = SseParser::default(); + assert!( + parser + .push(b"event: head\ndata: x\n") + .expect("parses") + .is_empty() + ); + assert_eq!( + parser.push(b"\n").expect("parses"), + vec![frame("head", "x")] + ); + } + + /// A body cut at every byte gives the same frames as one piece: lines, + /// fields and the blank line are reassembled whatever the cut. + #[test] + fn a_frame_split_at_every_byte_is_the_same_frame() { + let body = b": keep-alive\n\nevent: head\ndata: first\n\nevent: block\ndata: second\n\n"; + let mut parser = SseParser::default(); + let mut frames = Vec::new(); + for byte in body { + frames.extend(parser.push(std::slice::from_ref(byte)).expect("parses")); + } + assert_eq!( + frames, + vec![frame("head", "first"), frame("block", "second")] + ); + } + + /// `\r\n` and a lone `\r` end lines as `\n` does, and a `\r\n` cut between + /// two pieces is one line end, not a line end and a blank line. + #[test] + fn every_line_ending_is_one_line_end() { + let mut parser = SseParser::default(); + assert_eq!( + parser + .push(b"event: head\r\ndata: a\r\n\r\n") + .expect("parses"), + vec![frame("head", "a")] + ); + assert_eq!( + parser.push(b"event: head\rdata: b\r\r").expect("parses"), + vec![frame("head", "b")] + ); + assert!(parser.push(b"event: head\r").expect("parses").is_empty()); + assert!(parser.push(b"\ndata: c\r").expect("parses").is_empty()); + assert_eq!( + parser.push(b"\n\r\n").expect("parses"), + vec![frame("head", "c")] + ); + } + + #[test] + fn comments_are_skipped() { + let mut parser = SseParser::default(); + let frames = parser + .push(b": error - dropped 3 messages\n\n:\nevent: head\n: in between\ndata: x\n\n") + .expect("parses"); + assert_eq!(frames, vec![frame("head", "x")]); + } + + #[test] + fn data_lines_are_joined_with_newlines() { + let mut parser = SseParser::default(); + let frames = parser + .push(b"data: one\ndata:two\ndata\n\n") + .expect("parses"); + assert_eq!(frames, vec![frame("message", "one\ntwo\n")]); + } + + /// Only one space after the colon is dropped; the rest is the value. + #[test] + fn one_space_after_the_colon_is_dropped() { + let mut parser = SseParser::default(); + let frames = parser.push(b"event:head\ndata: x\n\n").expect("parses"); + assert_eq!(frames, vec![frame("head", " x")]); + } + + /// A frame with no data is dropped, and its `event:` does not leak into + /// the next one. + #[test] + fn a_frame_without_data_is_dropped_and_forgotten() { + let mut parser = SseParser::default(); + let frames = parser + .push(b"event: head\nid: 7\nretry: 100\n\ndata: x\n\n") + .expect("parses"); + assert_eq!(frames, vec![frame("message", "x")]); + } + + #[test] + fn a_byte_order_mark_at_the_start_is_dropped() { + let mut parser = SseParser::default(); + let frames = parser + .push(b"\xef\xbb\xbfevent: head\ndata: x\n\n") + .expect("parses"); + assert_eq!(frames, vec![frame("head", "x")]); + } + + /// A multi-byte character cut between two pieces is decoded whole. + #[test] + fn a_character_split_between_pieces_survives() { + let mut parser = SseParser::default(); + let body = "data: Platåberget\n\n".as_bytes(); + let cut = body + .iter() + .position(|&byte| byte >= 0x80) + .expect("non-ascii") + + 1; + assert!(parser.push(&body[..cut]).expect("parses").is_empty()); + assert_eq!( + parser.push(&body[cut..]).expect("parses"), + vec![frame("message", "Platåberget")] + ); + } + + #[test] + fn an_endless_line_is_refused() { + let mut parser = SseParser::default(); + let long = vec![b'a'; MAX_FRAME_BYTES + 1]; + assert_eq!(parser.push(&long), Err(FrameTooLong)); + } + + /// Many data lines, each short, are bounded together. + #[test] + fn an_endless_frame_is_refused() { + let mut parser = SseParser::default(); + let line = format!("data: {}\n", "a".repeat(1000)); + let mut result = Ok(Vec::new()); + for _ in 0..(MAX_FRAME_BYTES / 1000 + 2) { + result = parser.push(line.as_bytes()); + if result.is_err() { + break; + } + } + assert_eq!(result, Err(FrameTooLong)); + } + + // Decoding. + + #[test] + fn a_head_event_decodes() { + let event = decode(&frame("head", &head_json(10, 0xab, false))) + .expect("a topic this client reads") + .expect("decodes"); + assert_eq!( + event, + NodeEvent::Head(HeadEvent { + slot: 10, + block: Root::from([0xab; 32]), + execution_optimistic: false, + }) + ); + } + + #[test] + fn an_optimistic_head_says_so() { + let event = decode(&frame("head", &head_json(10, 0xab, true))) + .expect("a topic this client reads") + .expect("decodes"); + assert!(matches!( + event, + NodeEvent::Head(HeadEvent { + execution_optimistic: true, + .. + }) + )); + } + + /// A node that predates `execution_optimistic` does not sync optimistically. + #[test] + fn a_head_without_the_optimistic_flag_is_not_optimistic() { + let data = format!(r#"{{"slot":"3","block":"{}"}}"#, root_hex(1)); + let event = decode(&frame("head", &data)) + .expect("a topic this client reads") + .expect("decodes"); + assert!(matches!( + event, + NodeEvent::Head(HeadEvent { + execution_optimistic: false, + .. + }) + )); + } + + #[test] + fn a_payload_available_event_decodes() { + let data = format!(r#"{{"slot":"12","block_root":"{}"}}"#, root_hex(7)); + let event = decode(&frame("execution_payload_available", &data)) + .expect("a topic this client reads") + .expect("decodes"); + assert_eq!( + event, + NodeEvent::PayloadAvailable(PayloadAvailableEvent { + slot: 12, + block_root: Root::from([7; 32]), + }) + ); + } + + #[test] + fn a_topic_this_client_does_not_read_is_skipped() { + assert!(decode(&frame("block", &head_json(1, 1, false))).is_none()); + assert!(decode(&frame("message", "{}")).is_none()); + } + + /// The Beacon API quotes integers; a bare one, or a short root, is an + /// error rather than a guess. + #[test] + fn a_malformed_event_is_an_error() { + let bare = format!(r#"{{"slot":10,"block":"{}"}}"#, root_hex(1)); + assert!(matches!( + decode(&frame("head", &bare)), + Some(Err(Error::Decode(_))) + )); + let short = r#"{"slot":"10","block":"0xabcd"}"#; + assert!(matches!( + decode(&frame("head", short)), + Some(Err(Error::Decode(_))) + )); + } + + // Over HTTP. + + /// A node serving `body` on `/eth/v1/events` with `status`, recording + /// each request's query. + async fn serve( + status: u16, + body: String, + ) -> ( + HttpEventSource, + std::sync::Arc>>, + ) { + use axum::response::IntoResponse as _; + + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let recorded = seen.clone(); + let handler = move |uri: axum::http::Uri| { + let (recorded, body) = (recorded.clone(), body.clone()); + async move { + recorded + .lock() + .expect("lock") + .push(uri.query().unwrap_or_default().to_string()); + ( + axum::http::StatusCode::from_u16(status).expect("a status"), + [(axum::http::header::CONTENT_TYPE, "text/event-stream")], + body, + ) + .into_response() + } + }; + let app = axum::Router::new().route("/eth/v1/events", axum::routing::get(handler)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("binds"); + let address = listener.local_addr().expect("address"); + tokio::spawn(async move { axum::serve(listener, app).await }); + let source = HttpEventSource::new(format!("http://{address}/")).expect("builds"); + (source, seen) + } + + /// The stream is read through to the node closing it: keep-alives and + /// topics this client does not read are skipped, its own are decoded. + #[tokio::test] + async fn a_stream_is_read_until_the_node_closes_it() { + let body = format!( + ": keep-alive\n\nevent: block\ndata: {{\"slot\":\"9\"}}\n\nevent: head\ndata: {}\n\n", + head_json(10, 0xab, false) + ); + let (source, seen) = serve(200, body).await; + + let mut stream = source.subscribe(&[Topic::Head]).await.expect("opens"); + let event = stream.next_event().await.expect("reads"); + assert_eq!( + event, + Some(NodeEvent::Head(HeadEvent { + slot: 10, + block: Root::from([0xab; 32]), + execution_optimistic: false, + })) + ); + assert_eq!(stream.next_event().await.expect("reads"), None); + assert_eq!(*seen.lock().expect("lock"), vec!["topics=head".to_string()]); + } + + #[tokio::test] + async fn each_topic_is_its_own_query_parameter() { + let (source, seen) = serve(200, String::new()).await; + source + .subscribe(&[Topic::Head, Topic::ExecutionPayloadAvailable]) + .await + .expect("opens"); + assert_eq!( + *seen.lock().expect("lock"), + vec!["topics=head&topics=execution_payload_available".to_string()] + ); + } + + /// A refused subscription is an error carrying the node's status, so the + /// caller backs off and asks again. + #[tokio::test] + async fn a_refused_subscription_is_an_error() { + let refusal = r#"{"code":400,"message":"Invalid topic"}"#.to_string(); + let (source, _) = serve(400, refusal).await; + let refused = source.subscribe(&[Topic::ExecutionPayloadAvailable]).await; + match refused { + Err(Error::BeaconNodeStatus { status, body }) => { + assert_eq!(status, 400); + assert!(body.contains("Invalid topic"), "body: {body}"); + } + Err(other) => panic!("expected the node's status, got {other:?}"), + Ok(_) => panic!("expected the node's status, got a stream"), + } + } +} diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index 034dbb009..ac678bc68 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -1,7 +1,7 @@ //! A `BeaconNodeApi` that answers from values a test sets, used by the duty //! service tests. Compiled only under `cfg(test)`. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; use async_trait::async_trait; @@ -25,6 +25,7 @@ use crate::beacon_node::dto::{ AttesterDutyDto, CommitteeSubscriptionDto, ProposerDutyDto, ProposerPreparationDto, PtcDutyDto, SingleAttestationDto, SyncCommitteeSubscriptionDto, SyncDutyDto, }; +use crate::beacon_node::events::{EventSource, EventStream, NodeEvent, Topic}; use crate::beacon_node::{ AggregateAttestation, AggregateKind, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, @@ -239,6 +240,82 @@ pub struct MockBeaconNode { pub liveness_requests: Mutex)>>, /// How long `liveness` takes before it answers, as a hung node would. pub liveness_delay: Option, + /// The event streams `subscribe` hands out, one per call, in order: the + /// first one for any topic asked for, or scripted for any topic (`None`). + /// Once none fits, a subscription fails as an unreachable node's does. + pub event_streams: Mutex, ScriptedStream)>>, + /// The topics of every `subscribe` call, in call order. + pub event_subscriptions: Mutex>>, +} + +/// One step of a scripted event stream. +#[derive(Debug, Clone, Copy)] +pub enum StreamStep { + /// Send nothing for this long. + Wait(std::time::Duration), + /// Deliver this event. + Event(NodeEvent), +} + +/// What a scripted stream does once its steps run out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StreamEnd { + /// The node closes it. + Close, + /// It breaks, as a dropped connection does. + Fail, + /// It stays open and sends nothing more. + Hang, +} + +/// An event stream the mock hands out: its steps, then its end. +#[derive(Debug, Clone)] +pub struct ScriptedStream { + pub steps: VecDeque, + pub end: StreamEnd, +} + +#[async_trait] +impl EventStream for ScriptedStream { + async fn next_event(&mut self) -> Result> { + while let Some(step) = self.steps.pop_front() { + match step { + StreamStep::Wait(delay) => tokio::time::sleep(delay).await, + StreamStep::Event(event) => return Ok(Some(event)), + } + } + match self.end { + StreamEnd::Close => Ok(None), + StreamEnd::Fail => Err(Error::BeaconNode { + url: "mock".to_string(), + failure: BeaconNodeFailure::Body, + detail: "the event stream broke".to_string(), + }), + StreamEnd::Hang => std::future::pending().await, + } + } +} + +#[async_trait] +impl EventSource for MockBeaconNode { + async fn subscribe(&self, topics: &[Topic]) -> Result> { + self.event_subscriptions + .lock() + .expect("lock") + .push(topics.to_vec()); + let mut streams = self.event_streams.lock().expect("lock"); + let fits = streams + .iter() + .position(|(topic, _)| topic.is_none_or(|topic| topics.contains(&topic))); + match fits.and_then(|position| streams.remove(position)) { + Some((_, stream)) => Ok(Box::new(stream)), + None => Err(Error::BeaconNode { + url: "mock".to_string(), + failure: BeaconNodeFailure::Connect, + detail: "no event stream scripted".to_string(), + }), + } + } } impl MockBeaconNode { @@ -393,6 +470,43 @@ impl MockBeaconNode { self } + /// Answer `attestation_data` naming `root` as the head block. Over + /// [`Self::with_attestation_data`], which names the zero root. + pub fn with_attestation_block_root(mut self, root: Root) -> Self { + if let Some(data) = &mut self.attestation_data { + data.beacon_block_root = root; + } + self + } + + /// Hand `steps`, then `end`, to the next `subscribe`, whatever its topic, + /// that no stream scripted before this one goes to. + pub fn with_event_stream(self, steps: Vec, end: StreamEnd) -> Self { + self.script_stream(None, steps, end) + } + + /// [`Self::with_event_stream`], for a subscription to `topic` only. + pub fn with_topic_stream(self, topic: Topic, steps: Vec, end: StreamEnd) -> Self { + self.script_stream(Some(topic), steps, end) + } + + fn script_stream(self, topic: Option, steps: Vec, end: StreamEnd) -> Self { + let stream = ScriptedStream { + steps: steps.into(), + end, + }; + self.event_streams + .lock() + .expect("lock") + .push_back((topic, stream)); + self + } + + /// The topics of every `subscribe` call, in call order. + pub fn event_subscriptions(&self) -> Vec> { + self.event_subscriptions.lock().expect("lock").clone() + } + /// Answer `produce_block` with a minimal well-formed electra block for /// `slot`, proposed by `proposer_index`. /// diff --git a/crates/validator/src/beacon_node/mod.rs b/crates/validator/src/beacon_node/mod.rs index ea973fbed..312c07ce4 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -27,6 +27,7 @@ use ethlambda_types::beacon::containers::gloas; pub mod block_contents; pub mod dto; +pub mod events; pub mod fallback; pub mod http; diff --git a/crates/validator/src/head_monitor.rs b/crates/validator/src/head_monitor.rs new file mode 100644 index 000000000..74d8b6ff7 --- /dev/null +++ b/crates/validator/src/head_monitor.rs @@ -0,0 +1,1324 @@ +//! Signing when the slot's block arrives, not only at the clock's deadline. +//! +//! # What the specification asks +//! +//! An attester signs "when either (a) the validator has received a valid +//! block from the expected block proposer for the assigned `slot` or (b) +//! `get_attestation_due_ms()` milliseconds has transpired since the start of +//! the slot -- whichever comes first" (phase0 `validator.md`; gloas moves only +//! the deadline). A sync committee member signs its message on the same two +//! conditions, against its own deadline (altair `validator.md`). A payload +//! timeliness committee member votes "as soon as it has seen the execution +//! payload envelope and blob data for the block, and no later than +//! `get_payload_attestation_due_ms()`" (gloas `validator.md`), and may vote +//! `blob_data_available = False` only once that deadline has passed. +//! +//! The clock alone answers (b). This module answers (a), from the beacon +//! nodes' event streams ([`crate::beacon_node::events`]), so a vote leaves +//! when its block does, and the aggregators publishing at +//! `AGGREGATE_DUE_BPS` (`CONTRIBUTION_DUE_BPS`, and the next proposer, for +//! the other two) have that much longer to receive it. +//! +//! # The triggers +//! +//! - **Attestation and sync committee message:** a `head` event whose slot is +//! the duty's, and whose head the execution client has validated +//! (`execution_optimistic` false). `head` rather than `block`: the data a +//! vote signs names the node's head, and a block imported but not made head +//! (a late one fork choice passes over) would only give data for its parent. +//! It is also the event that says whether the head is optimistic. +//! Lighthouse, Teku, Prysm, Lodestar and Vouch wake on `head` as well. +//! - **Payload timeliness committee vote:** an `execution_payload_available` +//! event for the slot, read only when the network schedules gloas. Never +//! the `head`: the block alone is not what the vote is about. On an +//! ethlambda node the event follows the envelope's import, which waits for +//! the payload to verify and for every sampled column of its blobs, so it +//! means the blob data too. +//! +//! # The node's answer has to bear the event out +//! +//! An event only says when to ask. What is signed is still what the node +//! answers, through `FallbackBeaconNode` as at the deadline, and the early +//! attempt signs it only when it is about the event's block: +//! +//! - attestation data whose `beacon_block_root` is the event's block; +//! - a head root that is the event's block; +//! - payload attestation data for the event's block that says both +//! `payload_present` and `blob_data_available`. An early vote is therefore +//! always one that saw both. +//! +//! Anything else (another root, a failed request, a 204, a payload not called +//! present) is a `mismatch`: nothing was recorded and nothing signed. The +//! duty then waits for the next report about the slot that it has not tried +//! (another node's, or another block's), and asks again on it; with none +//! before the deadline it runs at the deadline, exactly as it would have with +//! no event. That is what keeps one signature per duty per slot: another +//! attempt follows only ones that stopped before recording anything, and an +//! attempt that got as far as recording is final for the slot whatever became +//! of it, as [`AttestationService::attest`]'s rule against retrying requires. +//! +//! # Every node's stream +//! +//! Each configured beacon node's stream is read, not only the first's, so +//! the early trigger survives the first node being down. An event from any of +//! them wakes the duty, the first node's report preferred when several are +//! new. The check above is what makes reading all of them safe: when the node +//! that answers has not imported the event's block yet, its answer names the +//! parent (or there is none) and that attempt declines. Its own report of the +//! block, when it comes, is a new one, so the duty asks again then, and only +//! the deadline is left if it never comes in time. +//! +//! # The clock stays the deadline +//! +//! A stream is best-effort (see [`crate::beacon_node::events`]). One that is +//! down, or has said nothing about the slot, leaves each duty to its clock +//! offset, as before this module. Each stream reopens on its own with backoff, +//! and once every reader is gone a duty waits for its deadline, never fires +//! for want of one. `--disable-event-stream` reads no stream at all. +//! +//! # Not here +//! +//! - No wait after the block. Vouch waits 500 ms and Nimbus half the +//! attestation offset before attesting; Lodestar's default, like this, is +//! none. The block has reached the node by the time it is head there, and +//! anything later only shortens what the vote has to reach the aggregators. +//! - Aggregation and sync contributions keep their own offsets: they fold +//! other validators' votes, which arrive on the clock. +//! - The `head` event's dependent roots are not read. Fetching duties again +//! when one changes is a separate change. + +use std::sync::Arc; +use std::time::Duration; + +use ethlambda_types::ShortRoot; +use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH; +use ethlambda_types::beacon::primitives::{Root, Slot}; +use tokio::sync::{RwLock, watch}; +use tokio::task::JoinHandle; +use tokio::time::Instant; +use tracing::{debug, info, warn}; + +use crate::attestation::{AttestationService, Attested}; +use crate::beacon_node::BeaconNodeApi; +use crate::beacon_node::dto::{AttesterDutyDto, PtcDutyDto, SyncDutyDto}; +use crate::beacon_node::events::{EventSource, HttpEventSource, NodeEvent, Topic, is_idle_timeout}; +use crate::error::Result; +use crate::keys::ValidatorStore; +use crate::metrics; +use crate::payload_attestation::PayloadAttestationService; +use crate::sync_committee::SyncCommitteeService; + +/// The first wait before a stream is opened again. +const RECONNECT_MIN: Duration = Duration::from_secs(1); + +/// The longest wait before a stream is opened again, which the wait doubles +/// up to while a node stays unreachable. +/// +/// About a mainnet slot, so a node that comes back costs at most a slot or so +/// of early votes, and one that stays down costs a request every twelve +/// seconds. A stream that delivered an event, or stayed open this long, is +/// opened again after [`RECONNECT_MIN`]. +const RECONNECT_MAX: Duration = Duration::from_secs(12); + +/// A duty an event can start early. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Duty { + Attestation, + SyncCommitteeMessage, + PayloadAttestation, +} + +impl Duty { + pub const ALL: [Duty; 3] = [ + Duty::Attestation, + Duty::SyncCommitteeMessage, + Duty::PayloadAttestation, + ]; + + /// The `duty` label of `ethlambda_validator_duty_triggers_total`. + pub fn as_str(self) -> &'static str { + match self { + Duty::Attestation => "attestation", + Duty::SyncCommitteeMessage => "sync_committee_message", + Duty::PayloadAttestation => "payload_attestation", + } + } +} + +/// What started one slot's duty. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fired { + /// A node's event for the slot, borne out by the node's answer. + Event, + /// The clock's offset, with no event for the slot before it. + Deadline, + /// The clock's offset, after an event the node's answer did not bear out. + Mismatch, +} + +impl Fired { + pub const ALL: [Fired; 3] = [Fired::Event, Fired::Deadline, Fired::Mismatch]; + + /// The `trigger` label of `ethlambda_validator_duty_triggers_total`. + pub fn as_str(self) -> &'static str { + match self { + Fired::Event => "event", + Fired::Deadline => "deadline", + Fired::Mismatch => "mismatch", + } + } +} + +/// A block one node reported on one topic. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Reported { + slot: Slot, + root: Root, +} + +/// What each node last reported on one topic, by its position in +/// `--beacon-nodes`. +type Reports = Vec>; + +/// The readers of every node's streams. Dropping it stops them. +pub struct HeadMonitor { + readers: Vec>, +} + +impl Drop for HeadMonitor { + fn drop(&mut self) { + for reader in &self.readers { + reader.abort(); + } + } +} + +/// Read every beacon node's event stream, or none with `enabled` off. +/// +/// `config` is the chain's, from the node's `/eth/v1/config/spec`: a network +/// that schedules gloas also gets the `execution_payload_available` streams. +/// The monitor, when there is one, must be kept for as long as the triggers +/// are used; the triggers outlive it safely, as deadlines alone. +pub fn start( + beacon_nodes: &[String], + config: &Config, + enabled: bool, +) -> Result<(Option, DutyTriggers)> { + if !enabled { + info!( + "Event stream off (--disable-event-stream): attestations, sync committee messages and \ + payload votes wait for their deadlines" + ); + return Ok((None, DutyTriggers::off())); + } + let sources = beacon_nodes + .iter() + .map(|url| { + let source = HttpEventSource::new(url)?; + let name = source.base_url().to_string(); + Ok((name, Arc::new(source) as Arc)) + }) + .collect::>>()?; + let payloads = config.gloas_fork_epoch != FAR_FUTURE_EPOCH; + let (monitor, triggers) = HeadMonitor::spawn(sources, payloads); + Ok((Some(monitor), triggers)) +} + +impl HeadMonitor { + /// One reader for each source's `head` stream, and with `payloads` one + /// for its `execution_payload_available` stream as well. + /// + /// A connection per topic rather than one for both: a node that refuses + /// the gloas topic (one that predates it) then costs the payload trigger + /// alone, not the head's. + pub fn spawn( + sources: Vec<(String, Arc)>, + payloads: bool, + ) -> (Self, DutyTriggers) { + let (heads, head_reports) = watch::channel(vec![None; sources.len()]); + let (payloads_seen, payload_reports) = watch::channel(vec![None; sources.len()]); + let mut readers = Vec::new(); + for (position, (name, source)) in sources.into_iter().enumerate() { + let reader = follow( + name.clone(), + source.clone(), + Topic::Head, + heads.clone(), + position, + ); + readers.push(tokio::spawn(reader)); + if payloads { + let topic = Topic::ExecutionPayloadAvailable; + let reader = follow(name, source, topic, payloads_seen.clone(), position); + readers.push(tokio::spawn(reader)); + } + } + let triggers = DutyTriggers { + heads: Some(head_reports), + payloads: payloads.then_some(payload_reports), + }; + (Self { readers }, triggers) + } +} + +/// Read `source`'s `topic` stream into `reports[position]` for the life of +/// the process, opening it again whenever it ends. +async fn follow( + name: String, + source: Arc, + topic: Topic, + reports: watch::Sender, + position: usize, +) { + let mut backoff = RECONNECT_MIN; + // Failures to open in a row, so a node that stays down warns once. + let mut refused: u32 = 0; + // The last stream went quiet rather than broke, so opening it again is + // routine: a stream silent by design, on a node that sends no + // keep-alives, does it every `IDLE_TIMEOUT`. + let mut went_quiet = false; + loop { + match source.subscribe(&[topic]).await { + Ok(mut stream) => { + if went_quiet { + debug!(node = %name, topic = topic.as_str(), "Event stream reopened"); + } else { + info!(node = %name, topic = topic.as_str(), "Reading the beacon node's event stream"); + } + refused = 0; + metrics::inc_event_streams_open(); + let opened = Instant::now(); + let mut delivered = false; + let broken = loop { + match stream.next_event().await { + Ok(Some(event)) => { + delivered = true; + note(&reports, position, topic, event); + } + Ok(None) => break None, + Err(err) => break Some(err), + } + }; + metrics::dec_event_streams_open(); + went_quiet = broken.as_ref().is_some_and(is_idle_timeout); + match broken { + Some(err) if went_quiet => debug!( + node = %name, + topic = topic.as_str(), + %err, + "Event stream went quiet; opening it again" + ), + Some(err) => warn!( + node = %name, + topic = topic.as_str(), + %err, + "Beacon node event stream broke; opening it again" + ), + None => warn!( + node = %name, + topic = topic.as_str(), + "Beacon node closed its event stream; opening it again" + ), + } + if delivered || opened.elapsed() >= RECONNECT_MAX { + backoff = RECONNECT_MIN; + } + } + Err(err) => { + refused += 1; + went_quiet = false; + if refused == 1 { + warn!( + node = %name, + topic = topic.as_str(), + %err, + "Cannot open the beacon node's event stream; its duties wait for their \ + deadlines until it opens" + ); + } else { + debug!(node = %name, topic = topic.as_str(), %err, refused, "Event stream still unavailable"); + } + } + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(RECONNECT_MAX); + } +} + +/// Record `event`, read from `topic`'s stream of the node at `position`. +/// +/// A node's report only moves forward: one about an earlier slot than it +/// last reported is not kept, so a reorg back to an older head cannot take +/// back a block already seen for the slot. That is harmless, since the +/// node's own answer is checked before anything is signed. An optimistic +/// head is not a block received in the sense the specification means, and +/// is not kept either. +fn note(reports: &watch::Sender, position: usize, topic: Topic, event: NodeEvent) { + let reported = match (topic, event) { + (Topic::Head, NodeEvent::Head(head)) => { + if head.execution_optimistic { + debug!( + slot = head.slot, + "Head is optimistic; not a reason to sign early" + ); + return; + } + Reported { + slot: head.slot, + root: head.block, + } + } + (Topic::ExecutionPayloadAvailable, NodeEvent::PayloadAvailable(payload)) => Reported { + slot: payload.slot, + root: payload.block_root, + }, + // Not what this stream was opened for. + _ => return, + }; + reports.send_if_modified(|reports| match reports.get_mut(position) { + Some(held) if held.is_none_or(|last| last.slot <= reported.slot && last != reported) => { + *held = Some(reported); + true + } + _ => false, + }); +} + +/// When each early-capable duty may start: the earlier of its clock offset +/// and the event that answers the specification's condition (a). Cheap to +/// clone. +/// +/// [`Self::off`] has no events, so every wait is the deadline alone. +#[derive(Debug, Clone, Default)] +pub struct DutyTriggers { + heads: Option>, + payloads: Option>, +} + +impl DutyTriggers { + /// Triggers that only ever wait for the deadline. + pub fn off() -> Self { + Self::default() + } + + /// Wait at most `wait` for a node to report a head at `slot`, and answer + /// its block, or `None` once `wait` has passed. + /// + /// What the duty loop sleeps on between a slot's proposal and the rest of + /// its duties, so an early head is not held back by that sleep. + pub async fn head_within(&self, slot: Slot, wait: Duration) -> Option { + let deadline = Instant::now() + wait; + SlotReports::new(self.heads.clone(), slot, deadline) + .next() + .await + } + + /// Attest for `slot` when a node reports the slot's block as its head, or + /// once `wait` (the attestation offset, from now) has passed, whichever + /// comes first; one attempt at most signs. See the module doc. + pub async fn attest( + &self, + service: &AttestationService, + slot: Slot, + wait: Duration, + duties: &[AttesterDutyDto], + store: &RwLock, + ) -> Result { + self.attest_traced(service, slot, wait, duties, store) + .await + .1 + } + + /// [`Self::attest`], also saying what started it. + async fn attest_traced( + &self, + service: &AttestationService, + slot: Slot, + wait: Duration, + duties: &[AttesterDutyDto], + store: &RwLock, + ) -> (Fired, Result) { + let deadline = Instant::now() + wait; + let mut reports = SlotReports::new(self.heads.clone(), slot, deadline); + let mut fired = Fired::Deadline; + while let Some(block) = reports.next().await { + match service.attestation_data(slot).await { + Ok(data) if data.beacon_block_root == block => { + debug!(%slot, block = %ShortRoot(&block.0), "Slot's block is the head; attesting now"); + metrics::inc_duty_trigger(Duty::Attestation, Fired::Event); + let attested = service.attest_with(slot, duties, store, data).await; + return (Fired::Event, attested); + } + Ok(data) => debug!( + %slot, + event_block = %ShortRoot(&block.0), + data_block = %ShortRoot(&data.beacon_block_root.0), + "Attestation data names another block than the head event; waiting for the next report or the deadline" + ), + Err(err) => debug!( + %slot, + %err, + "No attestation data on the head event; waiting for the next report or the deadline" + ), + } + fired = Fired::Mismatch; + } + metrics::inc_duty_trigger(Duty::Attestation, fired); + tokio::time::sleep_until(deadline).await; + (fired, service.attest(slot, duties, store).await) + } + + /// Sign `slot`'s sync committee messages when a node reports the slot's + /// block as its head, or once `wait` (the sync message offset, from now) + /// has passed, whichever comes first; one attempt at most signs. See the + /// module doc. + pub async fn publish_sync_messages( + &self, + service: &SyncCommitteeService, + slot: Slot, + wait: Duration, + duties: &[SyncDutyDto], + store: &RwLock, + ) -> Result> { + self.sync_traced(service, slot, wait, duties, store).await.1 + } + + /// [`Self::publish_sync_messages`], also saying what started it. + async fn sync_traced( + &self, + service: &SyncCommitteeService, + slot: Slot, + wait: Duration, + duties: &[SyncDutyDto], + store: &RwLock, + ) -> (Fired, Result>) { + let deadline = Instant::now() + wait; + let mut reports = SlotReports::new(self.heads.clone(), slot, deadline); + let mut fired = Fired::Deadline; + while let Some(block) = reports.next().await { + match service.head_block_root().await { + Ok(root) if root == block => { + debug!(%slot, block = %ShortRoot(&block.0), "Slot's block is the head; signing sync committee messages now"); + metrics::inc_duty_trigger(Duty::SyncCommitteeMessage, Fired::Event); + let published = service + .publish_messages_over(slot, duties, store, root) + .await; + return (Fired::Event, published); + } + Ok(root) => debug!( + %slot, + event_block = %ShortRoot(&block.0), + head = %ShortRoot(&root.0), + "Head root is another block than the head event; waiting for the next report or the deadline" + ), + Err(err) => debug!( + %slot, + %err, + "No head root on the head event; waiting for the next report or the deadline" + ), + } + fired = Fired::Mismatch; + } + metrics::inc_duty_trigger(Duty::SyncCommitteeMessage, fired); + tokio::time::sleep_until(deadline).await; + (fired, service.publish_messages(slot, duties, store).await) + } + + /// Cast `slot`'s payload timeliness committee votes when a node reports + /// the slot's payload and its blob data available, or once `wait` (the + /// payload attestation offset, from now) has passed, whichever comes + /// first; one attempt at most signs. The block alone never starts it. + /// See the module doc. + pub async fn attest_payload( + &self, + service: &PayloadAttestationService, + slot: Slot, + wait: Duration, + committee: &[PtcDutyDto], + store: &RwLock, + ) -> Result { + self.payload_traced(service, slot, wait, committee, store) + .await + .1 + } + + /// [`Self::attest_payload`], also saying what started it. + async fn payload_traced( + &self, + service: &PayloadAttestationService, + slot: Slot, + wait: Duration, + committee: &[PtcDutyDto], + store: &RwLock, + ) -> (Fired, Result) { + let deadline = Instant::now() + wait; + let mut reports = SlotReports::new(self.payloads.clone(), slot, deadline); + let mut fired = Fired::Deadline; + while let Some(block) = reports.next().await { + match service.data(slot).await { + Ok(Some(data)) + if data.beacon_block_root == block + && data.payload_present + && data.blob_data_available => + { + debug!(%slot, block = %ShortRoot(&block.0), "Slot's payload is available; voting now"); + metrics::inc_duty_trigger(Duty::PayloadAttestation, Fired::Event); + let voted = service.attest_with(slot, committee, store, data).await; + return (Fired::Event, voted); + } + Ok(Some(data)) => debug!( + %slot, + event_block = %ShortRoot(&block.0), + data_block = %ShortRoot(&data.beacon_block_root.0), + payload_present = data.payload_present, + blob_data_available = data.blob_data_available, + "Payload attestation data does not bear out the payload event; waiting for the next report or the deadline" + ), + Ok(None) => debug!( + %slot, + "No block known for the payload event's slot; waiting for the next report or the deadline" + ), + Err(err) => debug!( + %slot, + %err, + "No payload attestation data on the payload event; waiting for the next report or the deadline" + ), + } + fired = Fired::Mismatch; + } + metrics::inc_duty_trigger(Duty::PayloadAttestation, fired); + tokio::time::sleep_until(deadline).await; + (fired, service.attest(slot, committee, store).await) + } +} + +/// One duty's view of a topic's reports about its slot, until its deadline. +struct SlotReports { + /// `None` when the triggers are off. + receiver: Option>, + slot: Slot, + deadline: Instant, + /// The reports already handed out, as (node position, block), so each + /// starts at most one attempt. + tried: Vec<(usize, Root)>, +} + +impl SlotReports { + fn new(receiver: Option>, slot: Slot, deadline: Instant) -> Self { + Self { + receiver, + slot, + deadline, + tried: Vec::new(), + } + } + + /// The block of the next report about the slot not handed out before, + /// as soon as a node makes one, the first node's when several are new; + /// `None` at the deadline. + /// + /// A report the node's answer did not bear out is not handed out again, + /// but a later one is: the answering node's own report of the block, + /// arriving after another node's, or a node's report of another block at + /// the slot. So an early attempt declined because the answering node had + /// not imported the block yet is made again once it has. + /// + /// With no reports to read (the triggers are off), or once every reader is + /// gone, this is the deadline alone: a stream that no longer exists never + /// starts a duty early. + async fn next(&mut self) -> Option { + let Self { + receiver, + slot, + deadline, + tried, + } = self; + let Some(receiver) = receiver.as_mut() else { + tokio::time::sleep_until(*deadline).await; + return None; + }; + // At or past the deadline the clock has already answered, and an event + // would only add a request before the attempt that is due anyway. + if Instant::now() >= *deadline { + return None; + } + let slot = *slot; + let handed_out: &[(usize, Root)] = &tried[..]; + let reported = receiver.wait_for(|reports| untried(reports, slot, handed_out).is_some()); + // The answer is copied out of the channel's guard in the same statement, + // so the guard is never held across an await. + let seen = tokio::time::timeout_at(*deadline, reported) + .await + .map(|seen| seen.map(|reports| untried(&reports, slot, handed_out))); + match seen { + Ok(Ok(Some((position, block)))) => { + tried.push((position, block)); + Some(block) + } + // Every reader is gone: only the clock is left. + Ok(Err(_)) => { + tokio::time::sleep_until(*deadline).await; + None + } + // The deadline. (`wait_for` returns only once a report is new, so + // a `None` there cannot happen; if it did, the deadline attempt + // is the safe answer.) + Ok(Ok(None)) | Err(_) => None, + } + } +} + +/// The first node's report about `slot` that is not in `tried`, with the +/// node's position. +fn untried(reports: &Reports, slot: Slot, tried: &[(usize, Root)]) -> Option<(usize, Root)> { + reports.iter().enumerate().find_map(|(position, reported)| { + reported + .filter(|reported| reported.slot == slot && !tried.contains(&(position, reported.root))) + .map(|reported| (position, reported.root)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::beacon_node::dto::encode_hex; + use crate::beacon_node::events::{HeadEvent, PayloadAvailableEvent}; + use crate::beacon_node::mock::{MockBeaconNode, StreamEnd, StreamStep}; + use crate::signing::SigningContext; + use crate::slashing_protection::SlashingProtection; + use crate::test_support::store_with_keys; + use ethlambda_types::beacon::containers::gloas::PayloadAttestationData; + use ethlambda_types::beacon::fork::ForkName; + use ethlambda_types::beacon::preset::slots_per_epoch; + use ethlambda_types::beacon::primitives::BlsPubkey; + + /// The attestation and sync committee tests' slot, in epoch 3. + const SLOT: Slot = 96; + /// How long each duty is given before its deadline. + const WAIT: Duration = Duration::from_secs(4); + + fn block() -> Root { + Root::repeat_byte(0xb1) + } + + fn other_block() -> Root { + Root::repeat_byte(0xb2) + } + + fn after(millis: u64) -> StreamStep { + StreamStep::Wait(Duration::from_millis(millis)) + } + + fn head(slot: Slot, block: Root) -> StreamStep { + StreamStep::Event(NodeEvent::Head(HeadEvent { + slot, + block, + execution_optimistic: false, + })) + } + + fn optimistic_head(slot: Slot, block: Root) -> StreamStep { + StreamStep::Event(NodeEvent::Head(HeadEvent { + slot, + block, + execution_optimistic: true, + })) + } + + fn payload(slot: Slot, block_root: Root) -> StreamStep { + StreamStep::Event(NodeEvent::PayloadAvailable(PayloadAvailableEvent { + slot, + block_root, + })) + } + + /// The triggers for `nodes`' scripted streams, in order. + fn read_streams(nodes: &[Arc], payloads: bool) -> (HeadMonitor, DutyTriggers) { + let sources = nodes + .iter() + .map(|node| ("mock".to_string(), node.clone() as Arc)) + .collect(); + HeadMonitor::spawn(sources, payloads) + } + + fn key() -> (RwLock, BlsPubkey) { + let (store, pubkeys) = store_with_keys(1); + (RwLock::new(store), pubkeys[0]) + } + + // Attestations. + + /// A node whose attestation data for [`SLOT`] names `root`. + fn attesting(root: Root) -> MockBeaconNode { + MockBeaconNode::new() + .with_attestation_data(SLOT) + .with_attestation_block_root(root) + } + + fn attester_duty(pubkey: &BlsPubkey) -> AttesterDutyDto { + AttesterDutyDto { + pubkey: encode_hex(&pubkey.0), + validator_index: 1, + committee_index: 0, + committee_length: 128, + committees_at_slot: 1, + validator_committee_index: 0, + slot: SLOT, + is_aggregator: None, + } + } + + fn attestation_service(node: &Arc) -> AttestationService { + let context = SigningContext::new(Config::mainnet(), Root::ZERO); + AttestationService::new( + node.clone(), + Arc::new(context), + SlashingProtection::in_memory(), + ) + } + + /// Attest for [`SLOT`] through `triggers`, answering what started it and + /// how long that took. + async fn attest( + triggers: &DutyTriggers, + node: &Arc, + ) -> (Fired, Attested, Duration) { + let (store, pubkey) = key(); + let service = attestation_service(node); + let started = Instant::now(); + let (fired, attested) = triggers + .attest_traced(&service, SLOT, WAIT, &[attester_duty(&pubkey)], &store) + .await; + (fired, attested.expect("attests"), started.elapsed()) + } + + /// The head event for the slot starts the attestation then, a second in, + /// not at the deadline, and nothing asks or signs again after it. + #[tokio::test(start_paused = true)] + async fn a_head_event_for_the_slot_attests_then_and_only_once() { + let node = Arc::new( + attesting(block()) + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, attested, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert_eq!(attested.published, 1); + assert!( + took < WAIT, + "attested {took:?} in, the deadline is {WAIT:?}" + ); + + tokio::time::sleep(WAIT * 2).await; + assert_eq!(node.attestation_data_call_count(), 1); + assert_eq!(node.submitted().len(), 1); + } + + /// With nothing on the stream, the clock alone starts the duty. + #[tokio::test(start_paused = true)] + async fn no_event_attests_at_the_deadline() { + let node = Arc::new(attesting(block()).with_event_stream(Vec::new(), StreamEnd::Hang)); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, attested, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert_eq!(attested.published, 1); + assert!(took >= WAIT, "attested {took:?} in, before the deadline"); + assert_eq!(node.attestation_data_call_count(), 1); + } + + /// With the stream off, likewise. + #[tokio::test(start_paused = true)] + async fn with_the_stream_off_every_duty_waits_for_its_deadline() { + let node = Arc::new(attesting(block())); + + let (fired, attested, took) = attest(&DutyTriggers::off(), &node).await; + assert_eq!(fired, Fired::Deadline); + assert_eq!(attested.published, 1); + assert!(took >= WAIT); + assert!(node.event_subscriptions().is_empty()); + } + + /// A head for the slot before, or the one after, is not this slot's + /// block arriving. + #[tokio::test(start_paused = true)] + async fn a_head_event_for_another_slot_does_not_attest() { + let node = Arc::new(attesting(block()).with_event_stream( + vec![ + after(500), + head(SLOT - 1, block()), + after(500), + head(SLOT + 1, block()), + ], + StreamEnd::Hang, + )); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, _, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert!(took >= WAIT); + assert_eq!(node.attestation_data_call_count(), 1); + } + + /// A head the execution client has not validated is not a block received. + #[tokio::test(start_paused = true)] + async fn an_optimistic_head_does_not_attest() { + let node = Arc::new(attesting(block()).with_event_stream( + vec![after(1_000), optimistic_head(SLOT, block())], + StreamEnd::Hang, + )); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, _, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert!(took >= WAIT); + } + + /// The node's data names another block than the event's: nothing is + /// signed on the event, and the deadline attempt signs once. + #[tokio::test(start_paused = true)] + async fn data_for_another_block_waits_for_the_deadline() { + let node = Arc::new( + attesting(other_block()) + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, attested, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Mismatch); + assert!(took >= WAIT, "the mismatch must wait for the deadline"); + assert_eq!(attested.published, 1); + assert_eq!( + node.attestation_data_call_count(), + 2, + "asked on the event and at the deadline" + ); + assert_eq!(node.submitted().len(), 1, "signed once, at the deadline"); + } + + /// An event that comes once the deadline attempt has started changes + /// nothing: the duty is not attempted again. + #[tokio::test(start_paused = true)] + async fn an_event_after_the_deadline_signs_nothing_twice() { + let late = WAIT.as_millis() as u64 + 1_000; + let node = Arc::new( + attesting(block()) + .with_event_stream(vec![after(late), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, _, _) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + tokio::time::sleep(WAIT * 2).await; + assert_eq!(node.attestation_data_call_count(), 1); + assert_eq!(node.submitted().len(), 1); + } + + /// A stream that breaks mid-slot, with the node then unreachable, costs + /// the early trigger and nothing else. + #[tokio::test(start_paused = true)] + async fn a_stream_dropped_mid_slot_still_attests_at_the_deadline() { + let node = Arc::new(attesting(block()).with_event_stream( + vec![after(500), head(SLOT - 1, block()), after(500)], + StreamEnd::Fail, + )); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, attested, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert_eq!(attested.published, 1); + assert!(took >= WAIT); + assert!( + node.event_subscriptions().len() >= 2, + "the reader tried to open the stream again" + ); + } + + /// A stream that breaks and comes back within the slot still delivers + /// the slot's block in time. + #[tokio::test(start_paused = true)] + async fn a_stream_reopened_mid_slot_still_attests_early() { + let node = Arc::new( + attesting(block()) + .with_event_stream(vec![after(500)], StreamEnd::Fail) + .with_event_stream(vec![after(500), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, _, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert!(took < WAIT); + assert_eq!(node.event_subscriptions().len(), 2); + } + + /// Triggers that outlive their monitor are the deadline alone. + #[tokio::test(start_paused = true)] + async fn triggers_without_their_readers_wait_for_the_deadline() { + let node = Arc::new( + attesting(block()) + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + drop(monitor); + + let (fired, _, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert!(took >= WAIT); + } + + /// Every node's stream is read: the first node saying nothing does not + /// stop the second's event from starting the duty. + #[tokio::test(start_paused = true)] + async fn an_event_from_any_node_starts_the_duty() { + let silent = Arc::new(MockBeaconNode::new()); + let reporting = Arc::new( + MockBeaconNode::new() + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(&[silent, reporting], false); + let node = Arc::new(attesting(block())); + + let (fired, _, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert!(took < WAIT); + } + + /// A second node reports the block first, while the node that answers + /// has not imported it: that attempt declines, and the answering node's + /// own report, a second later, starts the duty after all, still before + /// the deadline. + #[tokio::test(start_paused = true)] + async fn a_declined_attempt_is_made_again_on_the_next_report() { + let answering = Arc::new( + MockBeaconNode::new() + .with_event_stream(vec![after(2_000), head(SLOT, block())], StreamEnd::Hang), + ); + let ahead = Arc::new( + MockBeaconNode::new() + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(&[answering, ahead], false); + // Until the answering node has the block, it has no data to give. + let node = Arc::new(attesting(block()).failing_call("attestation_data", "no block yet")); + let imports = node.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(1_500)).await; + imports.stop_failing("attestation_data"); + }); + + let (fired, attested, took) = attest(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert_eq!(attested.published, 1); + assert!( + took < WAIT, + "attested {took:?} in, the deadline is {WAIT:?}" + ); + assert_eq!( + node.attestation_data_call_count(), + 1, + "one answer, on the second report: the failed request is not counted" + ); + assert_eq!(node.submitted().len(), 1); + } + + /// The duty loop's wait before the slot's duties ends on the slot's block. + #[tokio::test(start_paused = true)] + async fn the_wait_before_the_slots_duties_ends_on_its_block() { + let node = Arc::new( + MockBeaconNode::new() + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let started = Instant::now(); + assert_eq!(triggers.head_within(SLOT, WAIT).await, Some(block())); + assert!(started.elapsed() < WAIT); + assert_eq!(triggers.head_within(SLOT + 1, WAIT).await, None); + } + + // Sync committee messages. + + fn sync_service(node: &Arc) -> SyncCommitteeService { + let config = Config::mainnet().with_fork_epoch(ForkName::Altair, 0); + SyncCommitteeService::new( + node.clone(), + Arc::new(SigningContext::new(config, Root::ZERO)), + ) + } + + async fn sign_sync( + triggers: &DutyTriggers, + node: &Arc, + ) -> (Fired, Option, Duration) { + let (store, pubkey) = key(); + let duty = SyncDutyDto { + pubkey: encode_hex(&pubkey.0), + validator_index: 1, + validator_sync_committee_indices: vec![0], + }; + let service = sync_service(node); + let started = Instant::now(); + let (fired, signed) = triggers + .sync_traced(&service, SLOT, WAIT, &[duty], &store) + .await; + (fired, signed.expect("signs"), started.elapsed()) + } + + #[tokio::test(start_paused = true)] + async fn a_head_event_for_the_slot_signs_the_sync_message_then() { + let node = Arc::new( + MockBeaconNode::new() + .with_head_root(block()) + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, signed, took) = sign_sync(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert_eq!(signed, Some(block())); + assert!(took < WAIT); + let sent = node.submitted_sync_messages(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].beacon_block_root, block()); + } + + /// A node whose head is not yet the event's block signs at the deadline, + /// over whatever its head is then, and only then. + #[tokio::test(start_paused = true)] + async fn a_head_root_for_another_block_signs_at_the_deadline() { + let node = Arc::new( + MockBeaconNode::new() + .with_head_root(other_block()) + .with_event_stream(vec![after(1_000), head(SLOT, block())], StreamEnd::Hang), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, signed, took) = sign_sync(&triggers, &node).await; + assert_eq!(fired, Fired::Mismatch); + assert_eq!(signed, Some(other_block())); + assert!(took >= WAIT); + assert_eq!(node.submitted_sync_messages().len(), 1); + } + + #[tokio::test(start_paused = true)] + async fn no_event_signs_the_sync_message_at_the_deadline() { + let node = Arc::new(MockBeaconNode::new().with_head_root(block())); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); + + let (fired, _, took) = sign_sync(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert!(took >= WAIT); + assert_eq!(node.submitted_sync_messages().len(), 1); + } + + // Payload timeliness committee votes. + + const GLOAS_EPOCH: u64 = 10; + + fn gloas_slot() -> Slot { + GLOAS_EPOCH * slots_per_epoch() + 4 + } + + fn payload_data(present: bool, blobs: bool) -> PayloadAttestationData { + PayloadAttestationData { + beacon_block_root: block(), + slot: gloas_slot(), + payload_present: present, + blob_data_available: blobs, + } + } + + async fn vote(triggers: &DutyTriggers, node: &Arc) -> (Fired, usize, Duration) { + let (store, pubkey) = key(); + let duty = PtcDutyDto { + pubkey: encode_hex(&pubkey.0), + validator_index: 1, + slot: gloas_slot(), + }; + let config = Config::mainnet().with_fork_epoch(ForkName::Gloas, GLOAS_EPOCH); + let context = Arc::new(SigningContext::new(config, Root::ZERO)); + let service = PayloadAttestationService::new(node.clone(), context); + let started = Instant::now(); + let (fired, voted) = triggers + .payload_traced(&service, gloas_slot(), WAIT, &[duty], &store) + .await; + (fired, voted.expect("votes"), started.elapsed()) + } + + /// The payload, with its blobs, starts the vote early. + #[tokio::test(start_paused = true)] + async fn the_payload_event_for_the_slot_votes_then() { + let node = Arc::new( + MockBeaconNode::new() + .with_payload_attestation_data(payload_data(true, true)) + .with_topic_stream( + Topic::ExecutionPayloadAvailable, + vec![after(2_000), payload(gloas_slot(), block())], + StreamEnd::Hang, + ), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), true); + + let (fired, voted, took) = vote(&triggers, &node).await; + assert_eq!(fired, Fired::Event); + assert_eq!(voted, 1); + assert!(took < WAIT); + assert_eq!(node.payload_attestation_data_call_count(), 1); + } + + /// The slot's block, as head, is not its payload: the vote waits. + #[tokio::test(start_paused = true)] + async fn the_block_alone_does_not_start_the_vote() { + let node = Arc::new( + MockBeaconNode::new() + .with_payload_attestation_data(payload_data(true, true)) + .with_topic_stream( + Topic::Head, + vec![after(500), head(gloas_slot(), block())], + StreamEnd::Hang, + ) + .with_topic_stream( + Topic::ExecutionPayloadAvailable, + Vec::new(), + StreamEnd::Hang, + ), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), true); + + let (fired, voted, took) = vote(&triggers, &node).await; + assert_eq!(fired, Fired::Deadline); + assert_eq!(voted, 1); + assert!(took >= WAIT); + assert_eq!(node.payload_attestation_data_call_count(), 1); + } + + /// An event whose data does not call the payload present, or its blob + /// data available, is not voted on early: such a vote may only be cast + /// once the deadline has passed. + #[tokio::test(start_paused = true)] + async fn a_payload_the_data_does_not_call_present_waits_for_the_deadline() { + for (present, blobs) in [(false, true), (true, false)] { + let node = Arc::new( + MockBeaconNode::new() + .with_payload_attestation_data(payload_data(present, blobs)) + .with_topic_stream( + Topic::ExecutionPayloadAvailable, + vec![after(1_000), payload(gloas_slot(), block())], + StreamEnd::Hang, + ), + ); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), true); + + let (fired, voted, took) = vote(&triggers, &node).await; + assert_eq!(fired, Fired::Mismatch, "present {present}, blobs {blobs}"); + assert_eq!(voted, 1, "voted once, at the deadline"); + assert!(took >= WAIT); + assert_eq!(node.payload_attestation_data_call_count(), 2); + let sent = node.submitted_payload_attestations(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].data, payload_data(present, blobs)); + } + } + + /// Without gloas scheduled only `head` is asked for; with it, each topic + /// gets its own stream. + #[tokio::test(start_paused = true)] + async fn the_payload_topic_is_read_only_when_gloas_is_scheduled() { + let before = Arc::new(MockBeaconNode::new()); + let (_before, _) = read_streams(std::slice::from_ref(&before), false); + let gloas = Arc::new(MockBeaconNode::new()); + let (_gloas, _) = read_streams(std::slice::from_ref(&gloas), true); + tokio::time::sleep(Duration::from_millis(10)).await; + + assert_eq!(before.event_subscriptions(), vec![vec![Topic::Head]]); + let mut asked = gloas.event_subscriptions(); + asked.sort_by_key(|topics| topics.first().map(|topic| topic.as_str())); + assert_eq!( + asked, + vec![vec![Topic::ExecutionPayloadAvailable], vec![Topic::Head]] + ); + } + + // What each node reports. + + #[test] + fn a_report_moves_forward_only() { + let (reports, seen) = watch::channel(vec![None]); + let at = |slot| { + NodeEvent::Head(HeadEvent { + slot, + block: block(), + execution_optimistic: false, + }) + }; + note(&reports, 0, Topic::Head, at(10)); + note(&reports, 0, Topic::Head, at(9)); + assert_eq!(untried(&seen.borrow(), 10, &[]), Some((0, block()))); + assert_eq!(untried(&seen.borrow(), 9, &[]), None); + } + + /// An event of the other topic, on a stream opened for one, is ignored. + #[test] + fn an_event_off_its_topic_is_ignored() { + let (reports, seen) = watch::channel(vec![None]); + let event = NodeEvent::PayloadAvailable(PayloadAvailableEvent { + slot: 10, + block_root: block(), + }); + note(&reports, 0, Topic::Head, event); + assert_eq!(untried(&seen.borrow(), 10, &[]), None); + } + + /// When two nodes report different blocks for the slot, the first node's + /// is the one the duty checks the data against, and once it was tried, + /// the other's comes next. + #[test] + fn the_first_nodes_report_wins_and_the_next_follows() { + let reports = vec![ + Some(Reported { + slot: 10, + root: block(), + }), + Some(Reported { + slot: 10, + root: other_block(), + }), + ]; + assert_eq!(untried(&reports, 10, &[]), Some((0, block()))); + assert_eq!( + untried(&reports, 10, &[(0, block())]), + Some((1, other_block())) + ); + assert_eq!( + untried(&reports, 10, &[(0, block()), (1, other_block())]), + None + ); + let reports = vec![ + None, + Some(Reported { + slot: 10, + root: other_block(), + }), + ]; + assert_eq!(untried(&reports, 10, &[]), Some((1, other_block()))); + } + + /// The same block reported by a second node is a new report: it is how a + /// declined attempt is made again once the answering node has the block. + #[test] + fn the_same_block_from_another_node_is_a_new_report() { + let reports = vec![ + Some(Reported { + slot: 10, + root: block(), + }), + Some(Reported { + slot: 10, + root: block(), + }), + ]; + assert_eq!(untried(&reports, 10, &[(1, block())]), Some((0, block()))); + } +} diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 6b5ad2646..fa445c05d 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -32,6 +32,7 @@ pub mod doppelganger; pub mod duties; pub mod error; pub mod exit; +pub mod head_monitor; pub mod http_api; pub(crate) mod in_flight; pub mod keys; @@ -108,6 +109,7 @@ use crate::beacon_node::fallback::FallbackBeaconNode; use crate::beacon_node::http::HttpBeaconNode; use crate::beacon_node::{BeaconNodeApi, ValidatorEntry}; use crate::duties::DutiesService; +use crate::head_monitor::DutyTriggers; use crate::in_flight::InFlight; use crate::keys::ValidatorStore; use crate::payload_attestation::PayloadAttestationService; @@ -175,6 +177,12 @@ pub struct ValidatorConfig { /// `xmss_cache_url`), so a key loads instead of being built. See /// [`load_xmss_cache`]. pub xmss_cache_url: Option, + + /// Read the beacon nodes' event streams, so attestations and sync + /// committee messages go out when the slot's block arrives and payload + /// votes when its payload does, rather than only at their deadlines. See + /// [`head_monitor`]. + pub event_stream: bool, } /// Builder proposals: register each validator with the beacon node's builder @@ -493,6 +501,10 @@ pub async fn run(config: ValidatorConfig, stop: impl Future( attestation: &AttestationService, aggregation: &AggregationService, payload_attestation: &PayloadAttestationService, sync_committee: &SyncCommitteeService, + triggers: &DutyTriggers, clock: &SlotClock, slot: u64, slot_duties: &[crate::beacon_node::dto::AttesterDutyDto], @@ -1070,34 +1090,42 @@ async fn serve_slot_duties( sync_duties: &[crate::beacon_node::dto::SyncDutyDto], store: &RwLock, ) { - // The sync committee work runs beside the attester and PTC work rather - // than after it: its deadline is not ordered against theirs (gloas moves - // it before the attestation) and each is bounded by the slot on its own. - let attest_then_ptc = async { + let attest = async { if !slot_duties.is_empty() { - tokio::time::sleep(clock.until_attestation(slot, SystemTime::now())).await; - attest_and_aggregate(attestation, aggregation, clock, slot, slot_duties, store).await; + attest_and_aggregate( + attestation, + aggregation, + triggers, + clock, + slot, + slot_duties, + store, + ) + .await; } - + }; + let vote = async { if clock.is_gloas(slot) && !committee.is_empty() { - tokio::time::sleep(clock.until_payload_attestation(slot, SystemTime::now())).await; - payload_attest(payload_attestation, clock, slot, committee, store).await; + payload_attest(payload_attestation, triggers, clock, slot, committee, store).await; } }; tokio::join!( - attest_then_ptc, - sync_committee_duty(sync_committee, clock, slot, sync_duties, store) + attest, + vote, + sync_committee_duty(sync_committee, triggers, clock, slot, sync_duties, store) ); } -/// Run one slot's sync committee duty: sign the head at the message deadline, -/// then aggregate at the contribution deadline if a root was signed. +/// Run one slot's sync committee duty: sign the head when the slot's block +/// arrives or at the message deadline, whichever comes first, then aggregate +/// at the contribution deadline if a root was signed. /// /// Each half is bounded by the end of the slot, like the other duties, and /// failures are logged and counted rather than propagated. Nothing here is /// slashable, so abandoning a half costs only that half. async fn sync_committee_duty( service: &SyncCommitteeService, + triggers: &DutyTriggers, clock: &SlotClock, slot: u64, duties: &[crate::beacon_node::dto::SyncDutyDto], @@ -1106,27 +1134,30 @@ async fn sync_committee_duty( if duties.is_empty() { return; } - tokio::time::sleep(clock.until_sync_message(slot, SystemTime::now())).await; - let budget = clock.remaining_in(slot, SystemTime::now()); - let root = - match tokio::time::timeout(budget, service.publish_messages(slot, duties, store)).await { - Ok(Ok(root)) => root, - Ok(Err(err)) => { - error!(%slot, %err, "Failed to publish sync committee messages for this slot"); - metrics::inc_sync_committee_failures(); - metrics::set_beacon_node_available(false); - return; - } - Err(_) => { - warn!( - %slot, - budget_ms = budget.as_millis() as u64, - "Sync committee messages ran past the end of their slot and were abandoned" - ); - metrics::inc_sync_committee_failures(); - return; - } - }; + let now = SystemTime::now(); + let (wait, budget) = ( + clock.until_sync_message(slot, now), + clock.remaining_in(slot, now), + ); + let messages = triggers.publish_sync_messages(service, slot, wait, duties, store); + let root = match tokio::time::timeout(budget, messages).await { + Ok(Ok(root)) => root, + Ok(Err(err)) => { + error!(%slot, %err, "Failed to publish sync committee messages for this slot"); + metrics::inc_sync_committee_failures(); + metrics::set_beacon_node_available(false); + return; + } + Err(_) => { + warn!( + %slot, + budget_ms = budget.as_millis() as u64, + "Sync committee messages ran past the end of their slot and were abandoned" + ); + metrics::inc_sync_committee_failures(); + return; + } + }; let Some(root) = root else { return; }; @@ -1150,14 +1181,16 @@ async fn sync_committee_duty( } } -/// Run one slot's attestation duty and, when it produced data, the aggregation -/// duty that follows it. +/// Run one slot's attestation duty, when the slot's block arrives or at the +/// attester offset, whichever comes first, and, when it produced data, the +/// aggregation duty that follows it at its own offset. /// /// Split out of the loop so the loop can go on to the payload committee duty /// whether or not this client has an attester duty in the slot. async fn attest_and_aggregate( attestation: &AttestationService, aggregation: &AggregationService, + triggers: &DutyTriggers, clock: &SlotClock, slot: u64, slot_duties: &[crate::beacon_node::dto::AttesterDutyDto], @@ -1178,8 +1211,13 @@ async fn attest_and_aggregate( // the same target. That is the intended outcome and matches `attest`'s // own "do not retry within a slot" rule; the attestation is simply // lost. - let budget = clock.remaining_in(slot, SystemTime::now()); - let attempt = tokio::time::timeout(budget, attestation.attest(slot, slot_duties, store)); + let now = SystemTime::now(); + let (wait, budget) = ( + clock.until_attestation(slot, now), + clock.remaining_in(slot, now), + ); + let attested = triggers.attest(attestation, slot, wait, slot_duties, store); + let attempt = tokio::time::timeout(budget, attested); match attempt.await.unwrap_or_else(|_| { warn!( %slot, @@ -1228,8 +1266,9 @@ async fn attest_and_aggregate( } } -/// Run one slot's payload timeliness committee duty, bounded by what is left of -/// the slot. +/// Run one slot's payload timeliness committee duty, when the slot's payload +/// and its blob data are available or three quarters into the slot, +/// whichever comes first, bounded by what is left of the slot. /// /// The budget is the end of the slot, like the aggregation's and for the same /// reason: this is the last duty in its slot, so the only thing past its @@ -1242,13 +1281,19 @@ async fn attest_and_aggregate( /// and counted rather than propagated, like every other duty's. async fn payload_attest( service: &PayloadAttestationService, + triggers: &DutyTriggers, clock: &SlotClock, slot: u64, committee: &[crate::beacon_node::dto::PtcDutyDto], store: &RwLock, ) { - let budget = clock.remaining_in(slot, SystemTime::now()); - let attempt = tokio::time::timeout(budget, service.attest(slot, committee, store)); + let now = SystemTime::now(); + let (wait, budget) = ( + clock.until_payload_attestation(slot, now), + clock.remaining_in(slot, now), + ); + let votes = triggers.attest_payload(service, slot, wait, committee, store); + let attempt = tokio::time::timeout(budget, votes); match attempt.await { Ok(Ok(_)) => {} Ok(Err(err)) => { @@ -2893,6 +2938,7 @@ mod tests { &AggregationService::new(node.clone(), context.clone()), &PayloadAttestationService::new(node.clone(), context.clone()), &SyncCommitteeService::new(node.clone(), context.clone()), + &DutyTriggers::off(), &clock, slot, &[], @@ -3030,6 +3076,7 @@ mod tests { &AggregationService::new(node.clone(), context.clone()), &PayloadAttestationService::new(node.clone(), context.clone()), &SyncCommitteeService::new(node.clone(), context.clone()), + &DutyTriggers::off(), &clock, slot, &[], @@ -3067,6 +3114,7 @@ mod tests { &AggregationService::new(node.clone(), context.clone()), &PayloadAttestationService::new(node.clone(), context.clone()), &SyncCommitteeService::new(node.clone(), context.clone()), + &DutyTriggers::off(), &clock, 5, &[], diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index 050a0fc38..a0c0142c7 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -7,10 +7,12 @@ use std::sync::LazyLock; use ethlambda_metrics::{ - Histogram, IntCounter, IntGauge, TimingGuard, register_histogram, register_int_counter, - register_int_gauge, + Histogram, IntCounter, IntCounterVec, IntGauge, TimingGuard, register_histogram, + register_int_counter, register_int_counter_vec, register_int_gauge, }; +use crate::head_monitor::{Duty, Fired}; + static VALIDATORS_LOADED: LazyLock = LazyLock::new(|| { register_int_gauge!( "ethlambda_validator_validators_loaded", @@ -444,6 +446,36 @@ static DOPPELGANGER_CHECK_FAILURES_TOTAL: LazyLock = LazyLock::new(| .unwrap() }); +/// What started each slot's attestation, sync committee message and payload +/// timeliness committee vote, once per duty per slot. See +/// `crate::head_monitor`. +/// +/// `event` is the beacon node's event for the slot's block (its payload, for +/// the vote), confirmed by the node's own data. `deadline` is the clock's +/// offset with no such event before it, which is every slot with the event +/// stream off or down. `mismatch` is an event the node's data did not bear +/// out, so the duty waited for its deadline after all: a rise there points +/// at beacon nodes that disagree with each other, or a vote whose payload was +/// announced but not seen present. +static DUTY_TRIGGERS_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "ethlambda_validator_duty_triggers_total", + "Slot duties by what started them: the beacon node's event, or the clock's deadline", + &["duty", "trigger"] + ) + .unwrap() +}); + +/// Event streams open, one per beacon node and topic. Zero with +/// `--disable-event-stream`. +static EVENT_STREAMS_OPEN: LazyLock = LazyLock::new(|| { + register_int_gauge!( + "ethlambda_validator_event_streams_open", + "Beacon node event streams open, one per node and topic" + ) + .unwrap() +}); + /// Register every series with the Prometheus registry so `/metrics` lists them /// at zero from startup, rather than only after whatever first touches them. /// @@ -493,6 +525,13 @@ pub fn init() { LazyLock::force(&PUBLICATION_DELAY_SECONDS); LazyLock::force(&SLASHING_PROTECTION_WRITE_SECONDS); LazyLock::force(&SLASHING_PROTECTION_WRITE_FAILURES_TOTAL); + // A labelled series exists only once a label pair is touched. + for duty in Duty::ALL { + for fired in Fired::ALL { + DUTY_TRIGGERS_TOTAL.with_label_values(&[duty.as_str(), fired.as_str()]); + } + } + LazyLock::force(&EVENT_STREAMS_OPEN); } pub fn set_validators_loaded(count: u64) { @@ -663,6 +702,21 @@ pub fn inc_slashing_protection_write_failures() { SLASHING_PROTECTION_WRITE_FAILURES_TOTAL.inc(); } +/// Count what started one slot's `duty`. +pub fn inc_duty_trigger(duty: Duty, fired: Fired) { + DUTY_TRIGGERS_TOTAL + .with_label_values(&[duty.as_str(), fired.as_str()]) + .inc(); +} + +pub fn inc_event_streams_open() { + EVENT_STREAMS_OPEN.inc(); +} + +pub fn dec_event_streams_open() { + EVENT_STREAMS_OPEN.dec(); +} + /// Record how long after a slot's start its attestations were accepted. pub fn observe_publication_delay(seconds: f64) { PUBLICATION_DELAY_SECONDS.observe(seconds); diff --git a/crates/validator/src/payload_attestation.rs b/crates/validator/src/payload_attestation.rs index 1a406bf1e..9816a7a69 100644 --- a/crates/validator/src/payload_attestation.rs +++ b/crates/validator/src/payload_attestation.rs @@ -11,9 +11,14 @@ //! //! # Timing //! -//! Due at `PAYLOAD_ATTESTATION_DUE_BPS` of the slot, three quarters of the way -//! in, which is when the node's view of the payload is as complete as it will -//! be. See [`crate::slot_clock::SlotClock::until_payload_attestation`]. +//! As soon as the node has the slot's payload and its blob data, and no later +//! than `PAYLOAD_ATTESTATION_DUE_BPS` of the slot, three quarters of the way +//! in. The early trigger is the node's `execution_payload_available` event for +//! the slot's block, and it signs only data that says both are there: the +//! block alone never starts the vote (see [`crate::head_monitor`]). Otherwise +//! the vote waits for the deadline, when the node's view of the payload is as +//! complete as it will be. See +//! [`crate::slot_clock::SlotClock::until_payload_attestation`]. //! //! # No block, no vote //! @@ -34,7 +39,9 @@ use std::collections::HashSet; use std::sync::Arc; -use ethlambda_types::beacon::containers::gloas::PayloadAttestationMessage; +use ethlambda_types::beacon::containers::gloas::{ + PayloadAttestationData, PayloadAttestationMessage, +}; use ethlambda_types::beacon::primitives::{Slot, ValidatorIndex}; use tokio::sync::RwLock; use tracing::{error, info, warn}; @@ -85,37 +92,53 @@ impl PayloadAttestationService { duties: &[PtcDutyDto], store: &RwLock, ) -> Result { - if duties.is_empty() { - return Ok(0); - } - // Cheap pre-check, so a slot already served costs the node no request. - let pending: Vec<&PtcDutyDto> = { - let done = self.lock(); - duties - .iter() - .filter(|duty| !done.contains(&(duty.validator_index, slot))) - .collect() - }; - if pending.is_empty() { + if self.pending(slot, duties).is_empty() { return Ok(0); } - let Some(data) = self.beacon_node.payload_attestation_data(slot).await? else { + let Some(data) = self.data(slot).await? else { info!(%slot, "No block known for this slot; not voting on its payload"); return Ok(0); }; + self.attest_with(slot, duties, store, data).await + } + + /// What the node says the committee should vote at `slot`, checked to be + /// about `slot`, with nothing recorded and nothing signed. `None` when the + /// node knows no block for the slot (204). + /// + /// For a caller that must look at the data before committing to it: the + /// duty loop's early trigger votes only on data that says the payload and + /// its blob data are there, and otherwise leaves the duty to its deadline + /// (see [`crate::head_monitor`]). + pub async fn data(&self, slot: Slot) -> Result> { + let data = self.beacon_node.payload_attestation_data(slot).await?; + if let Some(data) = &data { + check_slot(slot, data)?; + } + Ok(data) + } + + /// [`Self::attest`], over `data` already fetched for `slot` with + /// [`Self::data`] instead of fetching it here. + pub async fn attest_with( + &self, + slot: Slot, + duties: &[PtcDutyDto], + store: &RwLock, + data: PayloadAttestationData, + ) -> Result { + let pending = self.pending(slot, duties); + if pending.is_empty() { + return Ok(0); + } // Checked again here, having already been checked by the // implementation (see `BeaconNodeApi::payload_attestation_data`), for // the reason the attestation duty does: the trait is public, and this // is the last point before the data becomes a signature. - if data.slot != slot { - return Err(crate::error::Error::InconsistentResponse(format!( - "requested payload attestation data for slot {slot}, node answered for slot {}", - data.slot - ))); - } + check_slot(slot, &data)?; // From PQ a leanXMSS signature at the slot's PTC leaf, which // `crate::pq` guards against a second message. @@ -257,6 +280,15 @@ impl PayloadAttestationService { Ok(published) } + /// The duties not yet served for `slot`. + fn pending<'d>(&self, slot: Slot, duties: &'d [PtcDutyDto]) -> Vec<&'d PtcDutyDto> { + let done = self.lock(); + duties + .iter() + .filter(|duty| !done.contains(&(duty.validator_index, slot))) + .collect() + } + /// Record that `validator` is being served for `slot`. `false` when it /// already was, or when the record is unusable, which is treated as a /// refusal for the reason the other guards' poisoned locks are. @@ -279,6 +311,17 @@ impl PayloadAttestationService { } } +/// `data` is about `slot`, or the node answered a question it was not asked. +fn check_slot(slot: Slot, data: &PayloadAttestationData) -> Result<()> { + if data.slot != slot { + return Err(crate::error::Error::InconsistentResponse(format!( + "requested payload attestation data for slot {slot}, node answered for slot {}", + data.slot + ))); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/validator/src/slot_clock.rs b/crates/validator/src/slot_clock.rs index 09259d3c8..407ddd733 100644 --- a/crates/validator/src/slot_clock.rs +++ b/crates/validator/src/slot_clock.rs @@ -3,7 +3,9 @@ //! Seeded once from the beacon node's genesis, then independent of it. It is //! deliberately not driven by the node's event stream: that stream is //! best-effort by contract, dropping events for a slow subscriber, and a -//! dropped event must not mean a missed duty. +//! dropped event must not mean a missed duty. The stream can only start a duty +//! earlier than the offset this clock gives (see `crate::head_monitor`); the +//! offset stays its deadline. use std::time::{Duration, SystemTime, UNIX_EPOCH}; diff --git a/crates/validator/src/sync_committee.rs b/crates/validator/src/sync_committee.rs index 767536b7a..9474eec23 100644 --- a/crates/validator/src/sync_committee.rs +++ b/crates/validator/src/sync_committee.rs @@ -3,7 +3,9 @@ //! # What is owed //! //! A member of the current sync committee signs the head block root once per -//! slot (`SyncCommitteeMessage`), at the sync-message deadline. The 512 seats +//! slot (`SyncCommitteeMessage`), when the slot's block arrives or at the +//! sync-message deadline, whichever comes first (see +//! [`crate::head_monitor`]). The 512 seats //! are split into four subcommittees; within each, a few members are selected //! by a hash of their selection proof to fold the subcommittee's messages into //! a `SyncCommitteeContribution` and publish it, which is how the messages @@ -110,18 +112,11 @@ impl SyncCommitteeService { duties: &[SyncDutyDto], store: &RwLock, ) -> Result> { - let pending: Vec<&SyncDutyDto> = { - let done = self.lock(); - duties - .iter() - .filter(|duty| !done.contains(&(duty.validator_index, slot))) - .collect() - }; - if pending.is_empty() { + if self.pending(slot, duties).is_empty() { return Ok(None); } - let root = match self.beacon_node.head_block_root().await { + let root = match self.head_block_root().await { Ok(root) => root, Err(Error::BeaconNodeSyncing) => { warn!(%slot, "Head is optimistic or the node is syncing; not signing sync committee messages"); @@ -129,6 +124,33 @@ impl SyncCommitteeService { } Err(err) => return Err(err), }; + self.publish_messages_over(slot, duties, store, root).await + } + + /// The head root a message would sign, with nothing recorded and nothing + /// signed. `BeaconNodeSyncing` for a head the node reports optimistic. + /// + /// For a caller that must look at the root before committing to it: the + /// duty loop's early trigger signs only the block a head event announced, + /// and otherwise leaves the duty to its deadline (see + /// [`crate::head_monitor`]). + pub async fn head_block_root(&self) -> Result { + self.beacon_node.head_block_root().await + } + + /// [`Self::publish_messages`] over `root`, a head root already fetched + /// with [`Self::head_block_root`], instead of fetching it here. + pub async fn publish_messages_over( + &self, + slot: Slot, + duties: &[SyncDutyDto], + store: &RwLock, + root: Root, + ) -> Result> { + let pending = self.pending(slot, duties); + if pending.is_empty() { + return Ok(None); + } // Recorded one by one, then signed all at once, each within the // signing budget: a hung remote signer costs only its own keys' @@ -319,6 +341,15 @@ impl SyncCommitteeService { Ok(signed.len()) } + /// The duties not yet served for `slot`. + fn pending<'d>(&self, slot: Slot, duties: &'d [SyncDutyDto]) -> Vec<&'d SyncDutyDto> { + let done = self.lock(); + duties + .iter() + .filter(|duty| !done.contains(&(duty.validator_index, slot))) + .collect() + } + fn record(&self, validator: ValidatorIndex, slot: Slot) -> bool { let Ok(mut done) = self.done.lock() else { error!(%slot, "Sync committee record is poisoned; refusing to sign"); diff --git a/docs/cli.md b/docs/cli.md index fa333834f..6f2b34e51 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -389,6 +389,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | `--builder-min-bid` | `0` | The smallest builder bid, in gwei, a gloas block may be built on: sent as `produceBlockV4`'s `min_bid`, so the node takes no p2p bid whose value plus execution payment is below it, however the boost factor weighs it. Gloas only. Worth setting with `--prefer-builder-proposals`, which otherwise takes a 1-gwei bid over the local payload. `0` sets no floor. Taken with or without `--builder-proposals`: without it, it is the floor for the bid a node may build on when its own execution client fails at the slot | | `--init-slashing-protection` | off | Register every loaded key with no slashing-protection record as never having signed, instead of refusing to start. Dangerous: only for keys that have signed nothing anywhere for at least two epochs, and even then it rules out a double vote only, not a surround of an older vote; a key with a history should bring it instead. Never lowers an existing record; remove it once the keys are registered, and startup warns while it is set for nothing | | `--enable-doppelganger-protection` | off | Sign no attestation or block for a validator until the beacon node has seen it stay silent for a full epoch, and stop if it sees one act meanwhile. Applies at every start and to every key the keymanager API imports, and costs two to three epochs of attestations each time. See [Doppelganger protection](#doppelganger-protection) | +| `--disable-event-stream` | off | Read no beacon node's event stream, so every attestation, sync committee message and payload timeliness committee vote waits for its offset into the slot. One flag for what Lighthouse splits between `--disable-beacon-head-monitor` and `--disable-payload-available-monitor`; Prysm's nearest is `--disable-attest-timely`. For a node whose stream is broken, or a proxy in front of it that holds events back. See [Duties start on the block](#duties-start-on-the-block) | ### What it does today @@ -445,7 +446,9 @@ dependent root. Each slot it wakes at the boundary. If one of its validators proposes that slot, it signs the RANDAO reveal, asks the beacon node for a block, checks that the block is for the slot and proposer it asked about, signs it and publishes -it. One third into the slot it fetches the attestation data, checks that it is +it. When the slot's block becomes a beacon node's head, or one third into the +slot at the latest (see [Duties start on the block](#duties-start-on-the-block)), +it fetches the attestation data, checks that it is for the slot it asked about and that its `index` is one the slot's fork allows (0 before gloas, 0 or 1 from it, where it is the payload signal), signs for every validator due that slot, and submits the batch. A node whose answer fails @@ -499,21 +502,26 @@ validators it holds, for this epoch and the next when they are gloas ones. The gloas fork epoch's are the exception: a node cannot know them before the fork, so they are fetched at the fork epoch's first slot rather than as the previous epoch's lookahead. When an epoch's schedule could not be fetched, the client -asks again after each slot's duties until it has one. A member sleeps until `PAYLOAD_ATTESTATION_DUE_BPS` of the -slot, asks the node for the +asks again after each slot's duties until it has one. A member waits for a +node's `execution_payload_available` for the slot, or for +`PAYLOAD_ATTESTATION_DUE_BPS` of the slot at the latest, asks the node for the payload attestation data, signs it under the PTC domain and submits it. A `204` (the node knows no block for the slot) means no vote. So a gloas slot runs in -this order: propose at the boundary, attest at `ATTESTATION_DUE_BPS_GLOAS`, -aggregate at `AGGREGATE_DUE_BPS_GLOAS`, then the committee vote. The attestation -and the committee vote are each bounded by the end of the slot. +this order: propose at the boundary, attest on the block or at +`ATTESTATION_DUE_BPS_GLOAS`, aggregate at `AGGREGATE_DUE_BPS_GLOAS`, and the +committee vote on the payload or at its deadline, beside the other two rather +than after them, since a payload that arrives early can come before the +aggregation. The attestation and the committee vote are each bounded by the +end of the slot. Sync committee duties run beside the attester and committee work, not after it. Each epoch the client fetches its sync duties for the current period and the next (`POST /eth/v1/validator/duties/sync/{epoch}`, asked at the period's first epoch) and posts `sync_committee_subscriptions` for the current period's seats, until the period's end, so the node joins the subnets. The next period's are -added once its boundary is within four epochs. A member sleeps until -`SYNC_MESSAGE_DUE_BPS` (`SYNC_MESSAGE_DUE_BPS_GLOAS` from gloas), reads +added once its boundary is within four epochs. A member waits for the slot's +block, or for `SYNC_MESSAGE_DUE_BPS` (`SYNC_MESSAGE_DUE_BPS_GLOAS` from gloas) +at the latest, reads `/eth/v1/beacon/blocks/head/root`, signs it and submits one message per validator. It refuses to sign when the node reports the head optimistic. A member selected by the selection-proof hash for a subnet then waits for @@ -604,6 +612,45 @@ committee offsets (`SYNC_MESSAGE_DUE_BPS`, `CONTRIBUTION_DUE_BPS` and their a fallback, since deployed nodes still send it. A node sending both is required to agree with itself. +### Duties start on the block + +The offsets are deadlines, not start times. The specification has an attester +sign once it has the slot's block or once the offset has passed, whichever comes +first, a sync committee member likewise, and a payload timeliness committee +member as soon as it has seen the payload and its blob data. So the client reads +every beacon node's `GET /eth/v1/events`, one connection per topic: `head`, and +on a network that schedules gloas `execution_payload_available` as well. + +- A `head` for the current slot, not `execution_optimistic`, starts the slot's + attestation and sync committee message. +- An `execution_payload_available` for the current slot starts its committee + vote. The block alone never does. +- What is signed is still the node's answer, fetched through the usual failover, + and the early attempt signs it only if it is about the event's block: the + attestation data's `beacon_block_root`, the head root, or payload attestation + data that also says `payload_present` and `blob_data_available`. Otherwise + nothing is recorded or signed, and the duty asks again on the next report + about the slot it has not tried (another node's, or another block's), or + runs at its offset if none comes, as it would have with no event. Each duty + is signed at most once a slot either way. +- An event from any node starts a duty. The check above is what makes that safe + when the node answering has not imported the block yet: that attempt + declines, and the answering node's own report of the block starts the next. +- A stream that drops is opened again after a second, the wait doubling to 12 + seconds while the node stays unreachable. One silent for a minute is taken + for dead and opened again, logged at debug only, since a stream quiet by + design (`execution_payload_available` before gloas, on a node that sends no + keep-alives) does that every minute. While a stream is down the duties keep + their offsets, so a broken stream costs the early start and nothing else. +- Aggregation and sync contributions keep their own offsets, and nothing waits + after the block before attesting. + +`ethlambda_validator_duty_triggers_total` counts what started each duty (see +[Metrics](./metrics.md#validator-client)). An ethlambda beacon node builds its +`single_attestation` events while any client is subscribed to any topic, so this +client's subscription turns that work on (see +[`rpc.md`](rpc.md#get-ethv1events)). `--disable-event-stream` reads no stream. + ### Proposer duties are less durable than attester ones Worth knowing if a proposal is ever missed after a reorg. An attester schedule diff --git a/docs/metrics.md b/docs/metrics.md index eb7266894..e12be07b8 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -948,7 +948,9 @@ and absent is not the same as zero. | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | | `ethlambda_validator_slashing_protection_write_failures_total` | Counter | Slashing-protection writes that failed, each leaving its messages unsigned. Should read zero; anything else points at the disk under `--validators-dir` | -| `ethlambda_validator_publication_delay_seconds` | Histogram | Slot start to attestations accepted. The headline health number: it should sit near the one-third-slot duty offset | +| `ethlambda_validator_publication_delay_seconds` | Histogram | Slot start to attestations accepted. The headline health number: it should sit shortly after the slot's block arrives, and no later than just past the one-third-slot duty offset, where it sits for a slot whose block came late or not at all, or with `--disable-event-stream` | +| `ethlambda_validator_duty_triggers_total` | Counter | What started each slot's duty, once per duty per slot. `duty`: `attestation`, `sync_committee_message`, `payload_attestation`. `trigger`: `event` (a beacon node's `head` for the slot, or its `execution_payload_available` for the vote, borne out by the node's answer), `deadline` (no event for the slot before the offset: every slot with `--disable-event-stream` or the streams down) or `mismatch` (an event the node's answer did not bear out, so the duty waited for its offset after all). A steady `mismatch` share points at beacon nodes that disagree with each other, or payloads announced and not seen present | +| `ethlambda_validator_event_streams_open` | Gauge | Beacon node event streams open: one per node for `head`, and one more per node for `execution_payload_available` on a network that schedules gloas. A stream missing from that count costs its node's early starts, not a duty | Three of these distinguish failures that look alike on a dashboard but have different causes, and the distinction is the reason they are separate series: From 38762c3d9b610cabfd5f2953ed91c8b37b1b2564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:59:05 -0300 Subject: [PATCH 05/25] fix(validator): count open event streams with a guard, warn once on streams that end at once The open-stream gauge was incremented when a stream opened and decremented after it ended, so a reader aborted mid-stream (HeadMonitor's drop) left its stream counted. It is now a guard dropped with the reader's future. A node that keeps handing out streams that break or close before delivering any event logged a warning and an info line on every reconnect, forever. The first such end still warns; later ones, and the reopens between them, log at debug until a stream delivers an event or goes quiet, as repeated refused subscriptions already did. Docs: CLAUDE.md's gloas validator-client sentence and the comment above the proposer preparations still described the offsets as start times. --- CLAUDE.md | 10 +++++++--- crates/validator/src/head_monitor.rs | 27 ++++++++++++++++++++++++--- crates/validator/src/lib.rs | 15 ++++++++------- crates/validator/src/metrics.rs | 20 ++++++++++++++++---- 4 files changed, 55 insertions(+), 17 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4a88ee126..512a4f58f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -990,10 +990,14 @@ transitions are in `ethlambda-types`, per the section above. Nothing above boundary (block published bare, then the proposer-signed envelope with `Eth-Blob-Data-Included: true`, both inside the proposal's attester-offset budget; an envelope failure is logged and counted, not a failed proposal), - attest at `ATTESTATION_DUE_BPS_GLOAS`, aggregate at `AGGREGATE_DUE_BPS_GLOAS`, - then the PTC vote at `PAYLOAD_ATTESTATION_DUE_BPS`. Sync committee duties + attest on the slot's block (a node's `head` event) or at `ATTESTATION_DUE_BPS_GLOAS` + at the latest, aggregate at `AGGREGATE_DUE_BPS_GLOAS`, and, beside those rather + than after them, the PTC vote on its payload (`execution_payload_available`) or at + `PAYLOAD_ATTESTATION_DUE_BPS` at the latest (`crate::head_monitor`; see + `docs/cli.md`, "Duties start on the block"). Sync committee duties (`SyncCommitteeService`, `crates/validator/src/sync_committee.rs`) run at every fork: - one message per validator over the head root at `SYNC_MESSAGE_DUE_BPS(_GLOAS)` + one message per validator over the head root, on the block or at + `SYNC_MESSAGE_DUE_BPS(_GLOAS)` at the latest (refused while the head is optimistic), then contributions for each selected (validator, subnet) pair at `CONTRIBUTION_DUE_BPS(_GLOAS)`, with subscriptions re-sent every epoch for the current and next period. The node pools the messages diff --git a/crates/validator/src/head_monitor.rs b/crates/validator/src/head_monitor.rs index 74d8b6ff7..3ff098d09 100644 --- a/crates/validator/src/head_monitor.rs +++ b/crates/validator/src/head_monitor.rs @@ -274,6 +274,9 @@ async fn follow( let mut backoff = RECONNECT_MIN; // Failures to open in a row, so a node that stays down warns once. let mut refused: u32 = 0; + // Streams in a row that broke or closed before delivering an event, so a + // node that keeps handing out streams that end at once warns once too. + let mut fruitless: u32 = 0; // The last stream went quiet rather than broke, so opening it again is // routine: a stream silent by design, on a node that sends no // keep-alives, does it every `IDLE_TIMEOUT`. @@ -281,13 +284,13 @@ async fn follow( loop { match source.subscribe(&[topic]).await { Ok(mut stream) => { - if went_quiet { + if went_quiet || fruitless > 1 { debug!(node = %name, topic = topic.as_str(), "Event stream reopened"); } else { info!(node = %name, topic = topic.as_str(), "Reading the beacon node's event stream"); } refused = 0; - metrics::inc_event_streams_open(); + let open = metrics::OpenEventStream::count(); let opened = Instant::now(); let mut delivered = false; let broken = loop { @@ -300,8 +303,13 @@ async fn follow( Err(err) => break Some(err), } }; - metrics::dec_event_streams_open(); + drop(open); went_quiet = broken.as_ref().is_some_and(is_idle_timeout); + fruitless = if delivered || went_quiet { + 0 + } else { + fruitless + 1 + }; match broken { Some(err) if went_quiet => debug!( node = %name, @@ -309,6 +317,19 @@ async fn follow( %err, "Event stream went quiet; opening it again" ), + Some(err) if fruitless > 1 => debug!( + node = %name, + topic = topic.as_str(), + %err, + fruitless, + "Event stream broke again before delivering an event" + ), + None if fruitless > 1 => debug!( + node = %name, + topic = topic.as_str(), + fruitless, + "Event stream closed again before delivering an event" + ), Some(err) => warn!( node = %name, topic = topic.as_str(), diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index fa445c05d..3f86be787 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -821,13 +821,14 @@ pub async fn run(config: ValidatorConfig, stop: impl Future Self { + EVENT_STREAMS_OPEN.inc(); + Self(()) + } } -pub fn dec_event_streams_open() { - EVENT_STREAMS_OPEN.dec(); +impl Drop for OpenEventStream { + fn drop(&mut self) { + EVENT_STREAMS_OPEN.dec(); + } } /// Record how long after a slot's start its attestations were accepted. From 403fc7a225086e606bbb6bb080c90946cc0d074b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:28:06 -0300 Subject: [PATCH 06/25] fix(validator): bound early requests by the duty's deadline, end the pre-duty wait on a payload too An early attempt's request (attestation data, head root, payload attestation data) was awaited past the deadline: one still out then, and answering a mismatch, started the deadline attempt late. Each is now bounded by the deadline and dropped there, counted as a mismatch, so from the deadline on a duty runs exactly as it would with no event. The duty loop's wait before the slot's duties watched head reports only, so with a node's head stream down and its payload stream up the committee vote waited for the first duty's offset. `report_within` (was `head_within`) ends on either topic's report for the slot. A refused subscription's body excerpt bounded each piece's read rather than the whole read, so a body trickled a byte at a time could hold the reconnect for many minutes. One timeout now covers the whole read. Docs: the PTC deadline's doc in slot_clock.rs, the sync committee module doc, and spec_deviations.md, whose "signs a sync committee message at the deadline only" entry is no longer a deviation and is removed. --- crates/validator/src/beacon_node/events.rs | 22 ++++--- crates/validator/src/head_monitor.rs | 77 ++++++++++++++++++---- crates/validator/src/lib.rs | 11 ++-- crates/validator/src/metrics.rs | 3 +- crates/validator/src/slot_clock.rs | 5 +- crates/validator/src/sync_committee.rs | 5 +- docs/cli.md | 5 +- docs/metrics.md | 2 +- docs/spec_deviations.md | 9 --- 9 files changed, 94 insertions(+), 45 deletions(-) diff --git a/crates/validator/src/beacon_node/events.rs b/crates/validator/src/beacon_node/events.rs index c0204b63b..c087f3d94 100644 --- a/crates/validator/src/beacon_node/events.rs +++ b/crates/validator/src/beacon_node/events.rs @@ -458,17 +458,21 @@ fn transport(base_url: &str, err: &reqwest::Error) -> Error { } /// The start of a refused subscription's body, as one line, for the error. -/// Read a piece at a time and only up to [`ERROR_BODY_LIMIT`], so a node -/// answering with an endless body cannot hold the reconnect on it. +/// Read a piece at a time, only up to [`ERROR_BODY_LIMIT`], and within one +/// [`CONNECT_TIMEOUT`] for the whole read rather than one per piece, so a node +/// answering with an endless or trickled body cannot hold the reconnect on it. async fn body_excerpt(mut response: reqwest::Response) -> String { let mut bytes = Vec::new(); - while bytes.len() < ERROR_BODY_LIMIT { - let Ok(Ok(Some(chunk))) = tokio::time::timeout(CONNECT_TIMEOUT, response.chunk()).await - else { - break; - }; - bytes.extend_from_slice(&chunk[..chunk.len().min(ERROR_BODY_LIMIT - bytes.len())]); - } + let read = async { + while bytes.len() < ERROR_BODY_LIMIT { + let Ok(Some(chunk)) = response.chunk().await else { + break; + }; + bytes.extend_from_slice(&chunk[..chunk.len().min(ERROR_BODY_LIMIT - bytes.len())]); + } + }; + // Whatever arrived by then is the excerpt. + let _ = tokio::time::timeout(CONNECT_TIMEOUT, read).await; ethlambda_types::text::one_line(&String::from_utf8_lossy(&bytes), ERROR_BODY_LIMIT) } diff --git a/crates/validator/src/head_monitor.rs b/crates/validator/src/head_monitor.rs index 3ff098d09..3340e2a67 100644 --- a/crates/validator/src/head_monitor.rs +++ b/crates/validator/src/head_monitor.rs @@ -48,14 +48,17 @@ //! always one that saw both. //! //! Anything else (another root, a failed request, a 204, a payload not called -//! present) is a `mismatch`: nothing was recorded and nothing signed. The -//! duty then waits for the next report about the slot that it has not tried +//! present, or an answer still outstanding at the deadline, which is dropped +//! there) is a `mismatch`: nothing was recorded and nothing signed. The duty +//! then waits for the next report about the slot that it has not tried //! (another node's, or another block's), and asks again on it; with none //! before the deadline it runs at the deadline, exactly as it would have with //! no event. That is what keeps one signature per duty per slot: another //! attempt follows only ones that stopped before recording anything, and an //! attempt that got as far as recording is final for the slot whatever became //! of it, as [`AttestationService::attest`]'s rule against retrying requires. +//! And no early request outlives the deadline, so an event can make a duty +//! earlier but never later. //! //! # Every node's stream //! @@ -423,16 +426,25 @@ impl DutyTriggers { Self::default() } - /// Wait at most `wait` for a node to report a head at `slot`, and answer - /// its block, or `None` once `wait` has passed. + /// Wait at most `wait` for a node to report a head at `slot`, or its + /// payload available, and answer the reported block, or `None` once + /// `wait` has passed. /// /// What the duty loop sleeps on between a slot's proposal and the rest of - /// its duties, so an early head is not held back by that sleep. - pub async fn head_within(&self, slot: Slot, wait: Duration) -> Option { + /// its duties, so no early trigger is held back by that sleep. A payload + /// report ends it too: with a node's head stream down and its payload + /// stream up, the committee vote then starts on the payload rather than + /// at the first duty's offset. + pub async fn report_within(&self, slot: Slot, wait: Duration) -> Option { let deadline = Instant::now() + wait; - SlotReports::new(self.heads.clone(), slot, deadline) - .next() - .await + let mut heads = SlotReports::new(self.heads.clone(), slot, deadline); + let mut payloads = SlotReports::new(self.payloads.clone(), slot, deadline); + // Each answers `None` only at the deadline, so the first to finish is + // either a report or the deadline itself. + tokio::select! { + block = heads.next() => block, + block = payloads.next() => block, + } } /// Attest for `slot` when a node reports the slot's block as its head, or @@ -464,7 +476,15 @@ impl DutyTriggers { let mut reports = SlotReports::new(self.heads.clone(), slot, deadline); let mut fired = Fired::Deadline; while let Some(block) = reports.next().await { - match service.attestation_data(slot).await { + // Bounded by the deadline, so an early request still out then + // never delays the deadline attempt (see the module doc). + let early = service.attestation_data(slot); + let Ok(fetched) = tokio::time::timeout_at(deadline, early).await else { + debug!(%slot, "Attestation data still outstanding at the deadline; attesting at the deadline instead"); + fired = Fired::Mismatch; + continue; + }; + match fetched { Ok(data) if data.beacon_block_root == block => { debug!(%slot, block = %ShortRoot(&block.0), "Slot's block is the head; attesting now"); metrics::inc_duty_trigger(Duty::Attestation, Fired::Event); @@ -518,7 +538,13 @@ impl DutyTriggers { let mut reports = SlotReports::new(self.heads.clone(), slot, deadline); let mut fired = Fired::Deadline; while let Some(block) = reports.next().await { - match service.head_block_root().await { + let early = service.head_block_root(); + let Ok(fetched) = tokio::time::timeout_at(deadline, early).await else { + debug!(%slot, "Head root still outstanding at the deadline; signing at the deadline instead"); + fired = Fired::Mismatch; + continue; + }; + match fetched { Ok(root) if root == block => { debug!(%slot, block = %ShortRoot(&block.0), "Slot's block is the head; signing sync committee messages now"); metrics::inc_duty_trigger(Duty::SyncCommitteeMessage, Fired::Event); @@ -577,7 +603,13 @@ impl DutyTriggers { let mut reports = SlotReports::new(self.payloads.clone(), slot, deadline); let mut fired = Fired::Deadline; while let Some(block) = reports.next().await { - match service.data(slot).await { + let early = service.data(slot); + let Ok(fetched) = tokio::time::timeout_at(deadline, early).await else { + debug!(%slot, "Payload attestation data still outstanding at the deadline; voting at the deadline instead"); + fired = Fired::Mismatch; + continue; + }; + match fetched { Ok(Some(data)) if data.beacon_block_root == block && data.payload_present @@ -1054,9 +1086,26 @@ mod tests { let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), false); let started = Instant::now(); - assert_eq!(triggers.head_within(SLOT, WAIT).await, Some(block())); + assert_eq!(triggers.report_within(SLOT, WAIT).await, Some(block())); + assert!(started.elapsed() < WAIT); + assert_eq!(triggers.report_within(SLOT + 1, WAIT).await, None); + } + + /// A payload report ends that wait as well, so a node whose head stream + /// is down but whose payload stream is up does not hold the committee + /// vote to the first duty's offset. + #[tokio::test(start_paused = true)] + async fn the_wait_before_the_slots_duties_ends_on_its_payload() { + let node = Arc::new(MockBeaconNode::new().with_topic_stream( + Topic::ExecutionPayloadAvailable, + vec![after(1_000), payload(SLOT, block())], + StreamEnd::Hang, + )); + let (_monitor, triggers) = read_streams(std::slice::from_ref(&node), true); + + let started = Instant::now(); + assert_eq!(triggers.report_within(SLOT, WAIT).await, Some(block())); assert!(started.elapsed() < WAIT); - assert_eq!(triggers.head_within(SLOT + 1, WAIT).await, None); } // Sync committee messages. diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 3f86be787..b520727a1 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -784,12 +784,13 @@ pub async fn run(config: ValidatorConfig, stop: impl Future = LazyLock::new(| /// the vote), confirmed by the node's own data. `deadline` is the clock's /// offset with no such event before it, which is every slot with the event /// stream off or down. `mismatch` is an event the node's data did not bear -/// out, so the duty waited for its deadline after all: a rise there points +/// out (or had not answered by the deadline), so the duty waited for its +/// deadline after all: a rise there points /// at beacon nodes that disagree with each other, or a vote whose payload was /// announced but not seen present. static DUTY_TRIGGERS_TOTAL: LazyLock = LazyLock::new(|| { diff --git a/crates/validator/src/slot_clock.rs b/crates/validator/src/slot_clock.rs index 407ddd733..4ab2bf808 100644 --- a/crates/validator/src/slot_clock.rs +++ b/crates/validator/src/slot_clock.rs @@ -255,8 +255,9 @@ impl SlotClock { /// How long from `now` until the payload timeliness committee's duty for /// `slot`, or zero once that instant has passed. /// - /// The PTC counterpart to [`Self::until_aggregation`]: the loop sleeps on - /// it between aggregation and the committee vote. + /// The PTC counterpart to [`Self::until_aggregation`]: the committee + /// vote's deadline, which it waits for unless a beacon node reports the + /// slot's payload available first (see `crate::head_monitor`). pub fn until_payload_attestation(&self, slot: Slot, now: SystemTime) -> Duration { self.payload_attestation_time(slot) .duration_since(now) diff --git a/crates/validator/src/sync_committee.rs b/crates/validator/src/sync_committee.rs index 9474eec23..41bd66c83 100644 --- a/crates/validator/src/sync_committee.rs +++ b/crates/validator/src/sync_committee.rs @@ -13,8 +13,9 @@ //! //! # Which slot, and which root //! -//! The message carries the wall slot and the head root at the deadline, which -//! may be an older block when slots were skipped. A member assigned to wall +//! The message carries the wall slot and the head root when it is signed (on +//! the slot's block, or at the deadline), which may be an older block when +//! slots were skipped. A member assigned to wall //! slot `S` signs for `S - 1`; the caller picks the duties accordingly (see //! [`crate::duties::DutiesService::sync_at_slot`]). //! diff --git a/docs/cli.md b/docs/cli.md index 6f2b34e51..eaad50d01 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -631,8 +631,9 @@ on a network that schedules gloas `execution_payload_available` as well. data that also says `payload_present` and `blob_data_available`. Otherwise nothing is recorded or signed, and the duty asks again on the next report about the slot it has not tried (another node's, or another block's), or - runs at its offset if none comes, as it would have with no event. Each duty - is signed at most once a slot either way. + runs at its offset if none comes, as it would have with no event. An answer + still outstanding at the offset is dropped there, so an event never makes a + duty later. Each duty is signed at most once a slot either way. - An event from any node starts a duty. The check above is what makes that safe when the node answering has not imported the block yet: that attempt declines, and the answering node's own report of the block starts the next. diff --git a/docs/metrics.md b/docs/metrics.md index e12be07b8..e5ae3164c 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -949,7 +949,7 @@ and absent is not the same as zero. | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | | `ethlambda_validator_slashing_protection_write_failures_total` | Counter | Slashing-protection writes that failed, each leaving its messages unsigned. Should read zero; anything else points at the disk under `--validators-dir` | | `ethlambda_validator_publication_delay_seconds` | Histogram | Slot start to attestations accepted. The headline health number: it should sit shortly after the slot's block arrives, and no later than just past the one-third-slot duty offset, where it sits for a slot whose block came late or not at all, or with `--disable-event-stream` | -| `ethlambda_validator_duty_triggers_total` | Counter | What started each slot's duty, once per duty per slot. `duty`: `attestation`, `sync_committee_message`, `payload_attestation`. `trigger`: `event` (a beacon node's `head` for the slot, or its `execution_payload_available` for the vote, borne out by the node's answer), `deadline` (no event for the slot before the offset: every slot with `--disable-event-stream` or the streams down) or `mismatch` (an event the node's answer did not bear out, so the duty waited for its offset after all). A steady `mismatch` share points at beacon nodes that disagree with each other, or payloads announced and not seen present | +| `ethlambda_validator_duty_triggers_total` | Counter | What started each slot's duty, once per duty per slot. `duty`: `attestation`, `sync_committee_message`, `payload_attestation`. `trigger`: `event` (a beacon node's `head` for the slot, or its `execution_payload_available` for the vote, borne out by the node's answer), `deadline` (no event for the slot before the offset: every slot with `--disable-event-stream` or the streams down) or `mismatch` (an event the node's answer did not bear out, or had not answered by the offset, so the duty waited for its offset after all). A steady `mismatch` share points at beacon nodes that disagree with each other, or payloads announced and not seen present | | `ethlambda_validator_event_streams_open` | Gauge | Beacon node event streams open: one per node for `head`, and one more per node for `execution_payload_available` on a network that schedules gloas. A stream missing from that count costs its node's early starts, not a duty | Three of these distinguish failures that look alike on a dashboard but have diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index 17a4cc850..c8ad82a25 100644 --- a/docs/spec_deviations.md +++ b/docs/spec_deviations.md @@ -910,15 +910,6 @@ contributions only. never the block. - Messages from earlier slots over the same root are not packed. -## The validator client signs a sync committee message at the deadline only - -`validator.md` ("Prepare sync committee message") has a member sign as soon as -it sees the block for the slot, or at the sync-message deadline, whichever -comes first. The validator client signs once, at the deadline -(`SYNC_MESSAGE_DUE_BPS`, or its gloas variant), over the head root it then -reads, and refuses to when that root is optimistic -(`specs/bellatrix/optimistic-sync.md`). - ## The validator client's builder proposals With `--builder-proposals` the validator client registers its validators with From f4c679c5c1a7d454482e20db7564ecb6486fa674 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 11:52:51 -0300 Subject: [PATCH 07/25] docs(pq): attest and vote PTC on head_monitor's events, not head_events --- docs/beacon_pq.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 0bc7fac2e..1e2053324 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -389,14 +389,15 @@ A start drops the leaves of slots more than two epochs back, which nothing asks for again. - **Attesting**: a `SingleAttestation` signed at the target epoch's leaf, - published on one of PQ's 16 subnets. The client votes as soon as its first - beacon node reports a `head` event at the slot, or at the attestation - deadline if none arrives first (`head_events`), as the honest-validator - guide asks; it used to wait for the deadline every slot, which put its + published on one of PQ's 16 subnets. The client votes once a beacon node + reports a non-optimistic `head` at the slot whose block the attestation + data names, or at the attestation deadline otherwise (`head_monitor`, as at + every fork); it used to wait for the deadline every slot, which put its votes behind every client that votes on the block. The node checks a submitted batch in parallel, off the async executor, and publishes it in submission order. -- **The PTC vote**: as gloas's, signed at the slot's PTC leaf. +- **The PTC vote**: as gloas's, signed at the slot's PTC leaf, on the slot's + `execution_payload_available` or at the PTC deadline. - **Proposing**: the client sends its VRF proof for the slot (the RANDAO reveal) to `POST /eth/v1/validator/pq_blocks/{slot}`, signs the block and the envelope revealing its self-built payload at their leaves, and publishes From 401938757b475fe367d73cf97cf6d67be1849581 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:07:17 -0300 Subject: [PATCH 08/25] feat(pq): prove in process with leanVM bindings v0.17.0, drop the sidecar pq-devnet-1 runs one leanVM release for signer, prover and verifier: bindings v0.17.0 (1e997c99), which removed leanvm-sidecar and its client API in favour of lean_vm's in-process setup/aggregate/from_bytes. A proof from another revision does not verify. - claims and lean_xmss move to 1e997c99 (no wire change); leanvm_sidecar becomes lean_vm with the experimental prover, the one the pq-devnet-0 sidecar ran. cpu_tiers stays off: it needs leanVM's tier-rustc wrapper, and the node's own CPU baseline already gives the prover its clmul. - stark::sidecar becomes stark::leanvm: same Lighthouse claim mapping, merges folded MAX_RECURSIONS at a time, verification in process. With nothing to be unreachable, try_verify_aggregates, SidecarUnreachable and the prover_unreachable IGNORE go. - The node installs the backend itself once --network says PQ is scheduled; --pq-prover-socket becomes --pq-prover-threads. - The image no longer builds a sidecar. ethlambda-pq stays as a shim that execs ethlambda (LEANVM_THREADS -> --pq-prover-threads), so pq-devnet-0 launchers keep working; the publish workflow's leanvm_rev input goes. --- .github/workflows/docker_publish.yaml | 6 - Cargo.lock | 241 ++++++++++++-- Cargo.toml | 28 +- Dockerfile | 35 +- bin/ethlambda/pq/ethlambda-pq | 126 +------ bin/ethlambda/src/cli.rs | 19 +- bin/ethlambda/src/main.rs | 31 +- .../state_transition/src/beacon/gossip/mod.rs | 5 - .../state_transition/src/beacon/gossip/pq.rs | 12 +- .../state_transition/src/beacon/helpers/pq.rs | 13 - crates/common/crypto/Cargo.toml | 2 +- crates/common/crypto/src/stark.rs | 86 ++--- .../src/stark/{sidecar.rs => leanvm.rs} | 315 ++++++++---------- leanvm-revision | 2 +- 14 files changed, 454 insertions(+), 467 deletions(-) rename crates/common/crypto/src/stark/{sidecar.rs => leanvm.rs} (51%) diff --git a/.github/workflows/docker_publish.yaml b/.github/workflows/docker_publish.yaml index ac598b4ea..bf9f8e12d 100644 --- a/.github/workflows/docker_publish.yaml +++ b/.github/workflows/docker_publish.yaml @@ -13,10 +13,6 @@ on: tags: description: "Docker image tags, comma-separated (e.g., devnet5,devnet5-fix)" required: true - leanvm_rev: - description: "leanVM commit, tag or branch to build the PQ prover sidecar from (blank: the one in leanvm-revision)" - required: false - default: "" permissions: contents: read @@ -112,11 +108,9 @@ jobs: with: context: . file: ./Dockerfile - # An empty LEANVM_REV builds the sidecar from leanvm-revision. build-args: | GIT_COMMIT=${{ github.sha }} GIT_BRANCH=${{ github.ref_name }} - LEANVM_REV=${{ inputs.leanvm_rev }} ${{ matrix.variant.build_args }} push: true tags: ${{ steps.prep.outputs.tags }} diff --git a/Cargo.lock b/Cargo.lock index 145e5e236..79ea90445 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "aggregation" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "claims", + "fiat_shamir_prover", + "isa", + "keccak256", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", + "lean_sphincs", + "lean_xmss", + "stable_lean_vm_core", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", + "zkdsl_compiler", +] + [[package]] name = "ahash" version = "0.8.12" @@ -1092,7 +1112,7 @@ dependencies = [ [[package]] name = "claims" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" dependencies = [ "lean_sphincs", "lean_xmss", @@ -2068,6 +2088,7 @@ dependencies = [ "ethlambda-types", "hex", "keccak 0.1.6", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", "lean_xmss", "leanvm", "pbkdf2", @@ -2076,7 +2097,6 @@ dependencies = [ "rayon", "sha2", "sha3 0.10.9", - "sidecar", "thiserror 2.0.21", "tracing", "zk_alloc", @@ -2630,6 +2650,74 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "experimental_dispatch" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_lean_vm_core", + "isa", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs", + "experimental_primitives", + "fiat_shamir_prover", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr", + "experimental_parallel", + "experimental_pcs", + "experimental_primitives", + "fiat_shamir_prover", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_parallel" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "libc", +] + +[[package]] +name = "experimental_pcs" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives", + "fiat_shamir_prover", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_primitives" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover", + "keccak256", +] + [[package]] name = "eyre" version = "0.6.12" @@ -2717,6 +2805,15 @@ dependencies = [ "serde", ] +[[package]] +name = "fiat_shamir_prover" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256", + "verifier", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3662,6 +3759,14 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "isa" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "verifier", +] + [[package]] name = "itertools" version = "0.10.5" @@ -3833,7 +3938,7 @@ dependencies = [ [[package]] name = "keccak256" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" [[package]] name = "konst" @@ -3889,10 +3994,22 @@ name = "lean_compiler" version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad#48a904208d682848dac0e18ef8b01ebfc40df9ad" dependencies = [ - "lean_vm", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "primitives", ] +[[package]] +name = "lean_da" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + [[package]] name = "lean_da" version = "0.1.0" @@ -3909,11 +4026,28 @@ dependencies = [ [[package]] name = "lean_sphincs" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" dependencies = [ "keccak256", ] +[[package]] +name = "lean_vm" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "aggregation", + "claims", + "experimental_dispatch", + "isa", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", + "lean_sphincs", + "lean_vrf", + "lean_xmss", + "stable_lean_vm_core", + "verifier", +] + [[package]] name = "lean_vm" version = "0.1.0" @@ -3928,10 +4062,18 @@ dependencies = [ "zk_alloc", ] +[[package]] +name = "lean_vrf" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256", +] + [[package]] name = "lean_xmss" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" dependencies = [ "keccak256", ] @@ -3942,8 +4084,8 @@ version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad#48a904208d682848dac0e18ef8b01ebfc40df9ad" dependencies = [ "clap", - "lean_da", - "lean_vm", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "primitives", "rand 0.9.4", "rec_aggregation", @@ -5780,8 +5922,8 @@ dependencies = [ "bincode", "flock", "lean_compiler", - "lean_da", - "lean_vm", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "parallel", "pcs", "primitives", @@ -6522,17 +6664,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "sidecar" -version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" -dependencies = [ - "claims", - "lean_sphincs", - "lean_xmss", - "verifier", -] - [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -6701,6 +6832,62 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stable_keccak_gkr" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "fiat_shamir_prover", + "stable_parallel", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_lean_vm_core" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "fiat_shamir_prover", + "isa", + "stable_keccak_gkr", + "stable_parallel", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_parallel" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "stable_pcs" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "fiat_shamir_prover", + "stable_parallel", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_primitives" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "fiat_shamir_prover", + "isa", + "keccak256", + "stable_parallel", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -7412,7 +7599,7 @@ dependencies = [ [[package]] name = "verifier" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" [[package]] name = "version_check" @@ -8315,6 +8502,16 @@ dependencies = [ "libc", ] +[[package]] +name = "zkdsl_compiler" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "isa", + "keccak256", + "verifier", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index 4173f9e33..c3da37855 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -129,21 +129,21 @@ sha3 = "0.10.9" # hashes pay for a streaming hasher's buffering. keccak = "0.1.6" -# The client of leanVM's `leanvm-sidecar` (`crates/sidecar` without its -# `server` feature, which builds no prover) and its claim encoding: the PQ -# fork's attestation proofs as the PQ devnet makes them, real leanVM STARKs -# over leanXMSS signatures rather than the specification's concatenation +# leanVM's in-process prover (`lean_vm`) and its claim encoding: the PQ fork's +# attestation proofs as the PQ devnet makes them, real leanVM STARKs over +# leanXMSS signatures rather than the specification's concatenation # (`ethlambda_crypto::stark`); and leanVM's leanXMSS, which signs and verifies. -# Pinned to bindings v0.15.0, the release pq-devnet-0 runs for its signer, -# prover, verifier and sidecar. The sidecar binary is built and started -# outside the node (the image's `leanvm-revision` file and `ethlambda-pq` -# supervisor), and the client refuses one whose hello names another protocol -# version or verifier tag; beyond that nothing on the wire detects a -# mismatch, a proof from an incompatible revision just fails to verify. Not -# the `leanvm` revision below, which lean consensus proves with. -leanvm_sidecar = { package = "sidecar", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } -leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } -leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } +# Pinned to bindings v0.17.0 (1e997c99), the one release pq-devnet-1 runs for +# its signer, prover and verifier: a proof from another revision does not +# verify, and nothing on the wire says why. `experimental_prover` is the +# prover the pq-devnet-0 sidecar ran; it makes the same proofs as the stable +# one, faster. leanVM's `cpu_tiers` is not enabled: it needs leanVM's +# `scripts/tier-rustc` as `RUSTC_WRAPPER`, and the node's own CPU baseline +# (`.cargo/config.toml`) already gives the prover its carryless multiply. +# Not the `leanvm` revision below, which lean consensus proves with. +leanvm_prover = { package = "lean_vm", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69", features = ["experimental_prover"] } +leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69" } +leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69" } # XMSS signatures + recursive aggregation, through leanVM's own facade crate: # it re-exports the aggregation API, the `xmss` module (keys, signing, and the diff --git a/Dockerfile b/Dockerfile index 7adc984a7..10d52bde8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,32 +1,5 @@ # syntax=docker.io/docker/dockerfile:1.7-labs -# leanVM's prover sidecar, which the `ethlambda-pq` supervisor starts beside -# the node on a network scheduling the PQ fork, as Lighthouse's image does. -# Built from the revision in `leanvm-revision` (bindings v0.15.0, the release -# pq-devnet-0 runs), or from `--build-arg LEANVM_REV=`: -# which prover a devnet runs is chosen here, not by the node, whose client -# only requires the sidecar's protocol version and verifier tag to be its own. -# The commit built is recorded at /usr/local/share/ethlambda/leanvm-revision. -# leanVM's own .cargo/config.toml builds with `-C target-cpu=native`, which on -# CI's arm64 runner (Neoverse, with SVE) gives a binary that dies with SIGILL -# on Apple silicon, and on an amd64 runner with AVX-512 one that dies on hosts -# without it. ethlambda's config replaces it, so the sidecar gets the node's -# own portable CPU baseline (and the carryless-multiply features leanVM needs). -FROM rust:1.97-bookworm AS sidecar -ARG LEANVM_REV="" -COPY leanvm-revision /leanvm-revision -COPY .cargo/config.toml /ethlambda-cargo-config.toml -RUN rev="${LEANVM_REV:-$(tr -d '[:space:]' < /leanvm-revision)}" \ - && test -n "$rev" \ - && git clone -q https://github.com/leanEthereum/leanVM.git /leanVM \ - && cd /leanVM \ - && git checkout -q "$rev" \ - && mkdir -p .cargo \ - && cp /ethlambda-cargo-config.toml .cargo/config.toml \ - && cargo build --release -p leanvm-sidecar --features experimental_prover \ - && cp target/release/leanvm-sidecar /leanvm-sidecar \ - && git rev-parse HEAD > /leanvm-revision-built - FROM rust:1.97-bookworm AS chef WORKDIR /app @@ -106,10 +79,12 @@ LABEL org.opencontainers.image.version=$VERSION # Copy ethlambda over from the build stage COPY --from=builder /app/ethlambda /usr/local/bin -# The PQ prover sidecar and its supervisor, `ethlambda-pq beacon ` -COPY --from=sidecar /leanvm-sidecar /usr/local/bin/leanvm-sidecar -COPY --from=sidecar /leanvm-revision-built /usr/local/share/ethlambda/leanvm-revision +# pq-devnet-0's launcher name, `ethlambda-pq beacon `, kept for +# launchers that still use it. leanVM bindings v0.17.0 proves in the node, so +# there is no sidecar to start: the script only runs `ethlambda`. The leanVM +# revision the node proves with is the one in `leanvm-revision`. COPY --chmod=755 bin/ethlambda/pq/ethlambda-pq /usr/local/bin/ethlambda-pq +COPY leanvm-revision /usr/local/share/ethlambda/leanvm-revision # Copy licenses COPY LICENSE ./ diff --git a/bin/ethlambda/pq/ethlambda-pq b/bin/ethlambda/pq/ethlambda-pq index d5bd3dc2a..ce6e952c9 100755 --- a/bin/ethlambda/pq/ethlambda-pq +++ b/bin/ethlambda/pq/ethlambda-pq @@ -1,120 +1,18 @@ #!/bin/bash -# Runs `ethlambda` with a leanVM prover sidecar beside it, for a network that -# schedules the PQ fork, adapted from Lighthouse's `lighthouse-pq-bn`: -# `ethlambda-pq beacon ` starts the sidecar on a private socket, waits -# for it to listen, then starts `ethlambda --pq-prover-socket `. +# Kept so a launcher written for pq-devnet-0's image (`ethlambda-pq beacon +# `, as ethereum-package's pq branch runs it) still starts the node. # -# The node exiting stops the sidecar, and the script exits with the node's -# status. The sidecar exiting does not stop the node: it is started again on -# the same socket, and the node's client reconnects on its next request. -# Meanwhile the node proves nothing, and a gossip aggregate it cannot verify -# is ignored rather than held against its sender. The pause before a restart -# starts at one second and doubles, up to 32, while the sidecar keeps exiting -# within a minute of starting. After LEANVM_MAX_RESTARTS (default 10) such -# exits in a row, the script stops the node too: a sidecar that cannot run -# (killed for memory at every warm-up, say) is then reported, not retried -# forever. +# pq-devnet-0 ran leanVM's prover as a separate `leanvm-sidecar`, which this +# script started and supervised. leanVM bindings v0.17.0, pq-devnet-1's +# release, removed the sidecar: the node proves in process on a network that +# schedules the PQ fork, so this script only runs `ethlambda `. # -# Which sidecar is this script's choice, not the node's: -# - LEANVM_SIDECAR: the executable (default: `leanvm-sidecar` on PATH, the one -# the image builds from the leanVM revision in `leanvm-revision`, recorded at -# /usr/local/share/ethlambda/leanvm-revision). -# - LEANVM_THREADS: how many threads it proves on (default 0: one per core). -# The node refuses a sidecar speaking another protocol version or proving for -# another verifier than its client. +# LEANVM_THREADS, the sidecar's thread count, is still honored: it becomes +# `--pq-prover-threads` (0, the default: one per core). LEANVM_SIDECAR and +# LEANVM_MAX_RESTARTS no longer mean anything and are ignored. set -eu -sidecar=${LEANVM_SIDECAR:-leanvm-sidecar} -threads=${LEANVM_THREADS:-0} -max_restarts=${LEANVM_MAX_RESTARTS:-10} -revision_file=/usr/local/share/ethlambda/leanvm-revision -if [[ -z ${LEANVM_SIDECAR:-} && -r $revision_file ]]; then - echo "ethlambda-pq: starting $sidecar (leanVM $(cat "$revision_file")) on $threads threads (0: one per core)" >&2 -else - echo "ethlambda-pq: starting $sidecar on $threads threads (0: one per core)" >&2 +if [[ -n ${LEANVM_THREADS:-} ]]; then + exec ethlambda "$@" --pq-prover-threads "$LEANVM_THREADS" fi - -socket_dir=$(mktemp -d "${TMPDIR:-/tmp}/leanvm.XXXXXXXX") -socket_path="$socket_dir/prover.sock" -prover_pid= -prover_started=0 -node_pid= - -cleanup() { - if [[ -n "$node_pid" ]]; then - kill "$node_pid" 2>/dev/null || true - wait "$node_pid" 2>/dev/null || true - fi - if [[ -n "$prover_pid" ]]; then - kill "$prover_pid" 2>/dev/null || true - wait "$prover_pid" 2>/dev/null || true - fi - rm -f -- "$socket_path" "$socket_path.lock" - rmdir -- "$socket_dir" 2>/dev/null || true -} - -trap cleanup EXIT -trap 'exit 143' TERM -trap 'exit 130' INT - -start_sidecar() { - # A sidecar killed outright leaves its socket and lock behind. - rm -f -- "$socket_path" "$socket_path.lock" - "$sidecar" --socket "$socket_path" --threads "$threads" & - prover_pid=$! - prover_started=$SECONDS -} - -start_sidecar -ready_deadline=$((SECONDS + 120)) -until [[ -S "$socket_path" ]]; do - if ! kill -0 "$prover_pid" 2>/dev/null; then - echo "ethlambda-pq: $sidecar exited before creating its socket" >&2 - exit 1 - fi - if (( SECONDS >= ready_deadline )); then - echo "ethlambda-pq: $sidecar did not create its socket within 120 seconds" >&2 - exit 1 - fi - sleep 0.1 -done - -ethlambda "$@" --pq-prover-socket "$socket_path" & -node_pid=$! - -# Short polls rather than one long sleep for the pause, so a TERM is handled -# within a fraction of a second whatever the script is waiting for. -delay=1 -failures=0 -restart_at=0 -while kill -0 "$node_pid" 2>/dev/null; do - if [[ -n "$prover_pid" ]] && ! kill -0 "$prover_pid" 2>/dev/null; then - prover_status=0 - wait "$prover_pid" || prover_status=$? - prover_pid= - lived=$((SECONDS - prover_started)) - if (( lived >= 60 )); then - delay=1 - failures=0 - else - failures=$((failures + 1)) - fi - if (( failures >= max_restarts )); then - echo "ethlambda-pq: $sidecar exited within a minute of starting $failures times in a row; stopping ethlambda" >&2 - exit 1 - fi - echo "ethlambda-pq: $sidecar exited (status $prover_status) after ${lived}s while ethlambda was running; restarting it in ${delay}s" >&2 - restart_at=$((SECONDS + delay)) - delay=$((delay * 2 > 32 ? 32 : delay * 2)) - fi - if [[ -z "$prover_pid" ]] && (( SECONDS >= restart_at )); then - start_sidecar - echo "ethlambda-pq: restarted $sidecar" >&2 - fi - sleep 0.2 -done - -status=0 -wait "$node_pid" || status=$? -node_pid= -exit "$status" +exec ethlambda "$@" diff --git a/bin/ethlambda/src/cli.rs b/bin/ethlambda/src/cli.rs index 96ae53c89..88be49357 100644 --- a/bin/ethlambda/src/cli.rs +++ b/bin/ethlambda/src/cli.rs @@ -420,19 +420,12 @@ pub(crate) struct MainnetOptions { )] pub(crate) bootnodes: Vec, - /// The Unix socket of a running `leanvm-sidecar`, which makes and checks - /// the PQ fork's attestation proofs as leanVM STARKs, the encoding the PQ - /// devnet's clients use. Something else starts the sidecar, as for - /// Lighthouse: the image's `ethlambda-pq` supervisor does, and picks which - /// build. The node refuses one speaking another protocol version or - /// proving for another verifier than its client (leanVM - /// `c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764`, bindings v0.15.0). - /// - /// Without it, the node uses the specification's reference encoding (a - /// proof is the signatures concatenated), which only another node on the - /// reference accepts. - #[arg(long)] - pub(crate) pq_prover_socket: Option, + /// How many threads leanVM's in-process prover runs on, 0 for one per + /// core. Read only on a network that schedules the PQ fork, whose + /// attestation proofs this node makes and checks with leanVM (bindings + /// v0.17.0) in process. + #[arg(long, default_value_t = 0)] + pub(crate) pq_prover_threads: usize, /// Base URL of a builder API endpoint, normally MEV-Boost (for example /// `http://127.0.0.1:18550`) or a relay directly. Without it every block diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 03d788216..c7eb93f72 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -399,17 +399,6 @@ async fn run_node(options: Options) -> eyre::Result<()> { ); ethlambda_crypto::init_leanvm(lean.prover_arena); } - // The PQ fork's attestation proofs: leanVM proofs from a sidecar this node - // starts, or one already listening, the specification's reference - // encoding otherwise. Before anything can verify a proof, since the first - // one used stays installed. - if let Network::Mainnet { mainnet, .. } = &network { - use ethlambda_crypto::stark::{self, sidecar::SidecarConfig}; - if let Some(socket) = &mainnet.pq_prover_socket { - stark::install_sidecar(SidecarConfig::new(socket.clone())) - .wrap_err("cannot use the leanVM prover sidecar")?; - } - } // Initialize metrics ethlambda_blockchain::metrics::init(); @@ -479,6 +468,26 @@ async fn run_node(options: Options) -> eyre::Result<()> { let spec = network::NetworkSpec::parse(&mainnet.network)?; let source = network::NetworkSource::resolve(&spec)?; let bootnodes = beacon_bootnodes(&mainnet.bootnodes, source.bootnodes(), discovery_ip)?; + // The PQ fork's attestation proofs: leanVM proofs, made and + // checked in this process, on a network that schedules PQ (the + // specification's reference encoding otherwise, which nothing + // there uses). Here, once the network says whether it does, and + // before anything can verify a proof, since the first backend + // used stays installed. + let pq_epoch = source.config().pq_fork_epoch; + if pq_epoch != ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH { + use ethlambda_crypto::stark::{self, leanvm::LeanVmConfig}; + let config = LeanVmConfig { + threads: mainnet.pq_prover_threads, + ..LeanVmConfig::default() + }; + info!( + pq_epoch, + threads = config.threads, + "Starting leanVM's prover for the PQ fork" + ); + stark::install_leanvm(config).wrap_err("cannot start leanVM's prover")?; + } (Some(source), bootnodes) } }; diff --git a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs index 18e723ea6..e48768438 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs @@ -211,10 +211,6 @@ pub enum IgnoreReason { AlreadyExiting, /// The head state's sync committees cannot answer for the message's period. SyncCommitteeUnavailable, - /// A PQ aggregate's proof could not be checked: the prover sidecar did not - /// answer, as while `ethlambda-pq` restarts it. Nothing is known about the - /// proof, so this is not the sender's fault. - ProverUnreachable, } impl IgnoreReason { @@ -258,7 +254,6 @@ impl IgnoreReason { Self::BeforeFork => "before_fork", Self::AlreadyExiting => "already_exiting", Self::SyncCommitteeUnavailable => "sync_committee_unavailable", - Self::ProverUnreachable => "prover_unreachable", } } } diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index 15d89ae3e..42ba207dd 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs @@ -61,7 +61,7 @@ use crate::beacon::helpers::misc::{ use crate::beacon::helpers::pq::{ compute_xmss_attestation_leaf_index, compute_xmss_leaf_index, get_aggregation_committee, get_attestation_statements, get_attesting_indices, get_committee_indices, - is_valid_indexed_attestation, try_verify_aggregates, xmss_verify, + is_valid_indexed_attestation, verify_aggregates, xmss_verify, }; use crate::beacon::helpers::predicates::{is_slashable_attestation_data, is_slashable_validator}; use crate::beacon::lean_boundary::lean_block_unreachable; @@ -331,15 +331,11 @@ pub fn aggregate_stateful_checks( if !aggregators.contains(&aggregator_index) { return Err(Outcome::Reject(RejectReason::NotAggregator)); } - // [Modified in PQ] [REJECT] The aggregate stark is valid. A prover sidecar - // that did not answer (restarting, say) judged nothing, so the aggregate - // is IGNOREd rather than its sender penalized for it. + // [Modified in PQ] [REJECT] The aggregate stark is valid. let statements = get_attestation_statements(&state, aggregate, &committees) .map_err(|_| Outcome::Reject(RejectReason::AggregateProof))?; - match try_verify_aggregates(&statements, &aggregate_and_proof.proof) { - Ok(true) => {} - Ok(false) => return Err(Outcome::Reject(RejectReason::AggregateProof)), - Err(_) => return Err(Outcome::Ignore(IgnoreReason::ProverUnreachable)), + if !verify_aggregates(&statements, &aggregate_and_proof.proof) { + return Err(Outcome::Reject(RejectReason::AggregateProof)); } let attesting_indices = get_attesting_indices(&state, aggregate, &committees) .map_err(|_| Outcome::Ignore(IgnoreReason::Internal))?; diff --git a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index 7396adc31..367ace3c7 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs @@ -105,19 +105,6 @@ pub fn verify_aggregates(statements: &[AggregateStatement], proof: &[u8]) -> boo stark::verify_aggregates(statements, proof) } -/// [`verify_aggregates`], with a prover sidecar that could not be reached -/// told apart from a proof that does not verify (`stark::try_verify_aggregates`), -/// for gossip, which IGNOREs what it could not judge. -pub fn try_verify_aggregates( - statements: &[AggregateStatement], - proof: &[u8], -) -> std::result::Result { - if !xmss_verification_enabled() { - return Ok(true); - } - stark::try_verify_aggregates(statements, proof) -} - // --------------------------------------------------------------------------- // Misc // --------------------------------------------------------------------------- diff --git a/crates/common/crypto/Cargo.toml b/crates/common/crypto/Cargo.toml index c55273174..02def5121 100644 --- a/crates/common/crypto/Cargo.toml +++ b/crates/common/crypto/Cargo.toml @@ -23,7 +23,7 @@ pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] } leanvm.workspace = true leanvm_claims.workspace = true leanvm_lean_xmss.workspace = true -leanvm_sidecar.workspace = true +leanvm_prover.workspace = true postcard.workspace = true thiserror.workspace = true diff --git a/crates/common/crypto/src/stark.rs b/crates/common/crypto/src/stark.rs index 4c8160c67..f1d09c5b1 100644 --- a/crates/common/crypto/src/stark.rs +++ b/crates/common/crypto/src/stark.rs @@ -7,9 +7,9 @@ //! of every statement's public keys, in statement order and within a //! statement in public-key order, and verification checks each in turn. It //! is what the specification's fixtures use. -//! - **Sidecar** ([`install_sidecar`]): real leanVM proofs, made and checked -//! by a `leanvm-sidecar` process over a Unix socket, as the PQ devnet's -//! other clients make them. See [`sidecar`]. +//! - **leanVM** ([`install_leanvm`]): real leanVM proofs, made and checked +//! in this process (bindings v0.17.0), as the PQ devnet's other clients make +//! them. See [`leanvm`]. //! //! The two encodings are not interchangeable: a node verifies only the proofs //! its own backend makes, so every node of a network must run the same one. @@ -25,12 +25,12 @@ use rayon::prelude::*; use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; -pub mod sidecar; +pub mod leanvm; /// The backend every proof of this process goes through. enum Backend { Reference, - Sidecar(sidecar::SidecarBackend), + LeanVm(leanvm::LeanVmBackend), } static BACKEND: OnceLock = OnceLock::new(); @@ -39,22 +39,25 @@ fn backend() -> &'static Backend { BACKEND.get_or_init(|| Backend::Reference) } -/// Makes every proof of this process a leanVM proof from the sidecar at -/// `config.socket`, after checking it answers with this protocol and -/// verifier. Call once, at startup, before anything proves or verifies: -/// whichever backend is first used stays for the life of the process. -pub fn install_sidecar(config: sidecar::SidecarConfig) -> Result<(), sidecar::Error> { - let backend = sidecar::SidecarBackend::connect(config)?; +/// Makes every proof of this process a leanVM proof, made and checked in +/// process, after starting leanVM's prover pool (seconds). Call once, at +/// startup, before anything proves or verifies: whichever backend is first +/// used stays for the life of the process. +pub fn install_leanvm(config: leanvm::LeanVmConfig) -> Result<(), leanvm::Error> { + if BACKEND.get().is_some() { + return Err(leanvm::Error::AlreadyInstalled); + } + let backend = leanvm::LeanVmBackend::setup(config)?; BACKEND - .set(Backend::Sidecar(backend)) - .map_err(|_| sidecar::Error::AlreadyInstalled) + .set(Backend::LeanVm(backend)) + .map_err(|_| leanvm::Error::AlreadyInstalled) } -/// The installed backend's name, for logs: `reference` or `sidecar`. +/// The installed backend's name, for logs: `reference` or `leanvm`. pub fn backend_name() -> &'static str { match backend() { Backend::Reference => "reference", - Backend::Sidecar(_) => "sidecar", + Backend::LeanVm(_) => "leanvm", } } @@ -90,15 +93,15 @@ pub enum ProveError { expected: u64, found: u64, }, - #[error("the prover sidecar failed: {0}")] - Sidecar(String), + #[error("leanVM could not prove: {0}")] + LeanVm(String), } /// `stark.ProveAggregates(statements, signatures)`: `signatures[i][j]` is the /// signature of `statements[i].pubkeys[j]`. The reference verifies nothing -/// and only asserts the shapes line up; the sidecar refuses a signature that -/// does not verify. Blocks the calling thread for as long as the proof takes, -/// which under the sidecar is seconds. +/// and only asserts the shapes line up; leanVM refuses a signature that does +/// not verify. Blocks the calling thread for as long as the proof takes, +/// which under leanVM is seconds, and leanVM makes one proof at a time. pub fn prove_aggregates>( statements: &[AggregateStatement], signatures: &[Vec], @@ -111,7 +114,7 @@ pub fn prove_aggregates>( .flat_map(|signature| signature.as_ref()) .copied() .collect()), - Backend::Sidecar(sidecar) => sidecar.prove(statements, signatures), + Backend::LeanVm(leanvm) => leanvm.prove(statements, signatures), } } @@ -127,49 +130,20 @@ pub fn merge_proofs, P: AsRef<[u8]>>( .flat_map(|(_, proof)| proof.as_ref()) .copied() .collect()), - Backend::Sidecar(sidecar) => sidecar.merge(children), + Backend::LeanVm(leanvm) => leanvm.merge(children), } } /// `stark.VerifyAggregates(statements, proof)`. Under the reference, `true` /// only if `proof` holds, for each statement in turn and each of its public /// keys in order, a signature `xmss.Verify` accepts at the statement's leaf -/// index and message, and nothing else. Under the sidecar, whether the leanVM -/// proof proves every `(public key, message)` claim; it cannot check the leaf -/// indices, which leanVM proofs do not attest. A sidecar that cannot answer -/// reads as `false`, and is logged; [`try_verify_aggregates`] tells it apart. +/// index and message, and nothing else. Under leanVM, whether the proof +/// proves every `(public key, message)` claim; it cannot check the leaf +/// indices, which leanVM proofs do not attest. pub fn verify_aggregates(statements: &[AggregateStatement], proof: &[u8]) -> bool { - try_verify_aggregates(statements, proof).unwrap_or_else(|err| { - tracing::error!(%err, "The prover sidecar could not verify an attestation proof"); - false - }) -} - -/// The sidecar could not be asked: no connection, or one that failed or timed -/// out, as while `ethlambda-pq` restarts it. Says nothing about the proof. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("the prover sidecar could not be reached: {0}")] -pub struct SidecarUnreachable(pub String); - -/// [`verify_aggregates`], with a sidecar that could not be reached told apart -/// from a proof that does not verify, so gossip can IGNORE a message it could -/// not judge rather than penalize the peer that sent it. Only a connection -/// failure is [`SidecarUnreachable`]: a sidecar that answered and refused the -/// request is logged and reads as `false`, as an invalid proof does. -pub fn try_verify_aggregates( - statements: &[AggregateStatement], - proof: &[u8], -) -> Result { match backend() { - Backend::Reference => Ok(reference_verify(statements, proof)), - Backend::Sidecar(sidecar) => match sidecar.verify(statements, proof) { - Ok(valid) => Ok(valid), - Err(sidecar::Error::Io(err)) => Err(SidecarUnreachable(err.to_string())), - Err(err) => { - tracing::error!(%err, "The prover sidecar refused to verify an attestation proof"); - Ok(false) - } - }, + Backend::Reference => reference_verify(statements, proof), + Backend::LeanVm(leanvm) => leanvm.verify(statements, proof), } } diff --git a/crates/common/crypto/src/stark/sidecar.rs b/crates/common/crypto/src/stark/leanvm.rs similarity index 51% rename from crates/common/crypto/src/stark/sidecar.rs rename to crates/common/crypto/src/stark/leanvm.rs index 57783bb45..d0b202005 100644 --- a/crates/common/crypto/src/stark/sidecar.rs +++ b/crates/common/crypto/src/stark/leanvm.rs @@ -1,16 +1,13 @@ -//! Attestation proofs from a `leanvm-sidecar` process, over its Unix socket -//! (protocol version 1, `bins/leanvm-sidecar/README.md` in the leanVM -//! repository). +//! Attestation proofs made and checked by leanVM in this process (bindings +//! v0.17.0, [`LEANVM_REV`]). //! //! The PQ devnet does not run the specification's reference concatenation: -//! its clients prove with leanVM, through this sidecar. The wire protocol is -//! leanVM's own client crate at the revision the workspace pins -//! ([`LEANVM_REV`]). The sidecar itself is started outside this process, as -//! for Lighthouse, and may be built from another revision: the hello is -//! checked for this client's protocol version and verifier tag, and nothing -//! else on the wire detects a mismatch. Proofs only have to verify with the -//! other clients' verifiers, so which revision a devnet proves with is the -//! devnet's choice, within that tag. +//! its clients prove with leanVM. pq-devnet-0 did it through a separate +//! `leanvm-sidecar` process; v0.17.0 removed the sidecar, and every client now +//! proves in-process through `lean_vm`'s `setup`, `aggregate` and +//! `AggregateProof::{from_bytes, verify}`. Proofs only verify against a +//! verifier of the same release, and nothing on the wire says so: a proof from +//! another revision simply fails to verify. //! //! The mapping from the specification's statements is Lighthouse's, so the //! two clients' proofs verify against each other: @@ -19,118 +16,99 @@ //! flattens to the sorted, deduplicated list of its pairs (the verifier only //! accepts a claim list strictly sorted by the 64 bytes `pubkey || message`). //! - **The leaf index is not part of a claim** (leanEthereum/leanVM#787), so -//! [`SidecarBackend::verify`] shows each key signed the message at *some* -//! leaf, not at the statement's. [`SidecarBackend::prove`] refuses +//! [`LeanVmBackend::verify`] shows each key signed the message at *some* +//! leaf, not at the statement's. [`LeanVmBackend::prove`] refuses //! signatures made at another leaf, since it sees them. -//! - The empty proof stands for "nothing to prove" (the sidecar refuses to -//! prove zero claims), and verifies only against no claims. +//! - The empty proof stands for "nothing to prove" (leanVM refuses to prove +//! zero claims), and verifies only against no claims. //! - A merge folds the children [`MAX_CHILDREN_PER_AGGREGATE`] at a time, //! round after round, until one proof remains. //! -//! Two connections are kept, opened on first use and reopened after a -//! failure: one for proving, where requests queue in the sidecar, and one for -//! verifying, which the sidecar answers without waiting for proofs in -//! progress. +//! leanVM runs one proof at a time per process ("a second waits for the +//! first"), on a thread pool of its own that [`LeanVmBackend::setup`] starts. +//! Verification does not wait for a proof in progress. -use std::path::PathBuf; -use std::sync::Mutex; -use std::time::{Duration, Instant}; +use std::time::Instant; use leanvm_claims::{AggregateClaims, OutputClaims}; use leanvm_lean_xmss::{LeanXmssPublicKey, LeanXmssSignature}; -use leanvm_sidecar::{Client, SidecarError}; +use leanvm_prover::AggregateProof; use super::{AggregateStatement, ProveError}; use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; -/// The most children one aggregate request takes. -pub const MAX_CHILDREN_PER_AGGREGATE: usize = 16; +/// The most children one aggregate takes (leanVM's `MAX_RECURSIONS`). +pub const MAX_CHILDREN_PER_AGGREGATE: usize = leanvm_prover::MAX_RECURSIONS; -/// The leanVM revision the workspace's sidecar client is pinned to (bindings -/// v0.15.0). A sidecar from another revision is accepted when its hello -/// carries this client's protocol version and verifier tag. -pub const LEANVM_REV: &str = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764"; +/// The leanVM revision the workspace proves and verifies with (bindings +/// v0.17.0). Every node of a network must run the same one. +pub const LEANVM_REV: &str = "1e997c9927d3e7fafa2b813734f56e25d7a4da69"; #[derive(Debug, thiserror::Error)] pub enum Error { - #[error("sidecar connection: {0}")] - Io(#[from] std::io::Error), - #[error("sidecar: {0}")] - Sidecar(String), + #[error("leanVM: {0}")] + LeanVm(String), #[error("a proof backend is already installed")] AlreadyInstalled, - #[error("the sidecar proved {found} claims, {expected} were asked")] + #[error("leanVM proved {found} claims, {expected} were asked")] ClaimsMismatch { expected: usize, found: usize }, #[error("child {0} has claims and an empty proof, or a proof and no claims")] MalformedChild(usize), -} - -impl From for Error { - fn from(error: SidecarError) -> Self { - match error { - SidecarError::Io(error) => Error::Io(error), - other => Error::Sidecar(format!("{other:?}")), - } - } + #[error("child {0}'s proof does not decode")] + UndecodableChild(usize), + #[error("log_inv_rate {0} is outside leanVM's {min}..={max}", min = leanvm_prover::MIN_LOG_INV_RATE, max = leanvm_prover::MAX_LOG_INV_RATE)] + LogInvRate(u8), } impl From for ProveError { fn from(error: Error) -> Self { - ProveError::Sidecar(error.to_string()) + ProveError::LeanVm(error.to_string()) } } #[derive(Debug, Clone, PartialEq, Eq)] -pub struct SidecarConfig { - /// The Unix socket `leanvm-sidecar --socket` listens on. - pub socket: PathBuf, - /// `log_inv_rate` of the proofs requested, 1 to 4: a higher rate gives - /// smaller proofs that take longer to make. A proof verifies whatever rate - /// it was made at. +pub struct LeanVmConfig { + /// How many threads leanVM's prover pool runs, 0 for one per core. + pub threads: usize, + /// `log_inv_rate` of the proofs made, within leanVM's bounds: a higher + /// rate gives smaller proofs that take longer to make. A proof verifies + /// whatever rate it was made at. pub log_inv_rate: u8, - /// How long one prove or merge request may wait on the sidecar, queueing - /// behind others included. - pub prove_timeout: Duration, - /// How long one verify request may wait on the sidecar. - pub verify_timeout: Duration, } -impl SidecarConfig { - /// Lighthouse's defaults. - pub fn new(socket: impl Into) -> Self { +impl Default for LeanVmConfig { + /// One thread per core, at the rate pq-devnet-0's sidecars proved at + /// (Lighthouse's default). + fn default() -> Self { Self { - socket: socket.into(), + threads: 0, log_inv_rate: 2, - prove_timeout: Duration::from_secs(300), - verify_timeout: Duration::from_secs(30), } } } -pub struct SidecarBackend { - config: SidecarConfig, - prove_connection: Mutex>, - verify_connection: Mutex>, +pub struct LeanVmBackend { + log_inv_rate: usize, } -impl SidecarBackend { - /// Opens both connections now, checking each hello (magic, protocol - /// version, verifier tag), so a missing or incompatible sidecar is - /// reported at startup. - pub fn connect(config: SidecarConfig) -> Result { - let prove_connection = open(&config, config.prove_timeout)?; - let verify_connection = open(&config, config.verify_timeout)?; +impl LeanVmBackend { + /// Starts leanVM's prover pool and builds its aggregation program, which + /// verifying needs too. Takes seconds; call once, at startup. + pub fn setup(config: LeanVmConfig) -> Result { + let rate = usize::from(config.log_inv_rate); + if !(leanvm_prover::MIN_LOG_INV_RATE..=leanvm_prover::MAX_LOG_INV_RATE).contains(&rate) { + return Err(Error::LogInvRate(config.log_inv_rate)); + } + let started = Instant::now(); + leanvm_prover::setup(config.threads); tracing::info!( - socket = %config.socket.display(), - prover = prove_connection.prover(), - client_leanvm_rev = LEANVM_REV, - "Connected to the leanVM prover sidecar" + threads = config.threads, + log_inv_rate = config.log_inv_rate, + leanvm_rev = LEANVM_REV, + elapsed_ms = started.elapsed().as_millis() as u64, + "leanVM prover ready, in process" ); - Ok(Self { - config, - prove_connection: Mutex::new(Some(prove_connection)), - verify_connection: Mutex::new(Some(verify_connection)), - }) + Ok(Self { log_inv_rate: rate }) } pub(super) fn prove>( @@ -176,79 +154,74 @@ impl SidecarBackend { }) }) .collect(); - Ok(self.aggregate(&[], &raw_signatures, &expected)?) + let proof = self.aggregate(&[], raw_signatures, &expected)?; + Ok(proof.to_bytes()) } pub(super) fn merge, P: AsRef<[u8]>>( &self, children: &[(S, P)], ) -> Result, ProveError> { - let mut level: Vec<(AggregateClaims, Vec)> = Vec::with_capacity(children.len()); + let mut level: Vec<(AggregateClaims, AggregateProof)> = Vec::with_capacity(children.len()); for (index, (statements, proof)) in children.iter().enumerate() { let claims = statements_to_claims(statements.as_ref()); match (claims.lean_xmss.is_empty(), proof.as_ref().is_empty()) { (true, true) => {} - (false, false) => level.push((claims, proof.as_ref().to_vec())), + (false, false) => { + let proof = AggregateProof::from_bytes(proof.as_ref()) + .ok_or(Error::UndecodableChild(index))?; + level.push((claims, proof)); + } _ => return Err(Error::MalformedChild(index).into()), } } while level.len() > 1 { let mut next = Vec::with_capacity(level.len().div_ceil(MAX_CHILDREN_PER_AGGREGATE)); - for chunk in level.chunks(MAX_CHILDREN_PER_AGGREGATE) { - if let [only] = chunk { - next.push(only.clone()); + let mut rest = level.into_iter().peekable(); + while rest.peek().is_some() { + let chunk: Vec<_> = rest.by_ref().take(MAX_CHILDREN_PER_AGGREGATE).collect(); + if chunk.len() == 1 { + next.extend(chunk); continue; } - let expected = union(chunk); - let proof = self.aggregate(chunk, &[], &expected)?; + let expected = union(&chunk); + let proof = self.aggregate(&chunk, Vec::new(), &expected)?; next.push((expected, proof)); } level = next; } - Ok(level.pop().map(|(_, proof)| proof).unwrap_or_default()) + Ok(level + .pop() + .map(|(_, proof)| proof.to_bytes()) + .unwrap_or_default()) } - pub(super) fn verify( - &self, - statements: &[AggregateStatement], - proof: &[u8], - ) -> Result { + pub(super) fn verify(&self, statements: &[AggregateStatement], proof: &[u8]) -> bool { let claims = statements_to_claims(statements); if claims.lean_xmss.is_empty() || proof.is_empty() { - return Ok(claims.lean_xmss.is_empty() && proof.is_empty()); + return claims.lean_xmss.is_empty() && proof.is_empty(); } - with_connection( - &self.config, - &self.verify_connection, - self.config.verify_timeout, - |client| client.verify(&claims, proof), - ) + AggregateProof::from_bytes(proof).is_some_and(|proof| proof.verify(&claims)) } - /// One aggregate request on the proving connection. Checks the sidecar - /// proved exactly `expected`. + /// One aggregate. Checks leanVM proved exactly `expected`. fn aggregate( &self, - children: &[(AggregateClaims, Vec)], - raw_signatures: &[(LeanXmssPublicKey, Message, LeanXmssSignature)], + children: &[(AggregateClaims, AggregateProof)], + raw_signatures: Vec<(LeanXmssPublicKey, Message, LeanXmssSignature)>, expected: &AggregateClaims, - ) -> Result, Error> { + ) -> Result { let started = Instant::now(); - let (claims, proof) = with_connection( - &self.config, - &self.prove_connection, - self.config.prove_timeout, - |client| { - client.aggregate( - children, - raw_signatures, - &[], - &[], - OutputClaims::All, - usize::from(self.config.log_inv_rate), - ) - }, - )?; + let signatures = raw_signatures.len(); + let (claims, proof) = leanvm_prover::aggregate( + children, + raw_signatures, + Vec::new(), + None, + OutputClaims::All, + self.log_inv_rate, + ) + .map_err(|err| Error::LeanVm(err.to_string()))?; if claims != *expected { return Err(Error::ClaimsMismatch { expected: expected.num_signature_claims(), @@ -257,9 +230,8 @@ impl SidecarBackend { } tracing::debug!( children = children.len(), - signatures = raw_signatures.len(), + signatures, claims = claims.num_signature_claims(), - proof_bytes = proof.len(), elapsed_ms = started.elapsed().as_millis() as u64, "Proved an attestation aggregate" ); @@ -295,7 +267,7 @@ pub fn statements_to_claims(statements: &[AggregateStatement]) -> AggregateClaim /// The claims a proof of all of `children` attests: their union, strictly /// sorted. -fn union(children: &[(AggregateClaims, Vec)]) -> AggregateClaims { +fn union(children: &[(AggregateClaims, AggregateProof)]) -> AggregateClaims { let mut lean_xmss: Vec<_> = children .iter() .flat_map(|(claims, _)| claims.lean_xmss.iter().copied()) @@ -309,54 +281,6 @@ fn union(children: &[(AggregateClaims, Vec)]) -> AggregateClaims { } } -fn open(config: &SidecarConfig, timeout: Duration) -> Result { - let client = Client::connect(&config.socket)?; - client.set_timeout(Some(timeout))?; - Ok(client) -} - -/// Runs `call` on the connection in `slot`, opening it first if needed. A -/// connection that fails is dropped, as the protocol requires after anything -/// but a rejection; if a reused one failed other than by timing out, the -/// sidecar may have restarted, so this reconnects and tries once more. -fn with_connection( - config: &SidecarConfig, - slot: &Mutex>, - timeout: Duration, - mut call: impl FnMut(&mut Client) -> Result, -) -> Result { - let mut slot = slot - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let mut reused = slot.is_some(); - loop { - let client = match slot.as_mut() { - Some(client) => client, - None => slot.insert(open(config, timeout)?), - }; - match call(client) { - Ok(value) => return Ok(value), - Err(SidecarError::Rejected(rejection, message)) => { - return Err(Error::Sidecar(format!("{rejection:?}: {message}"))); - } - Err(SidecarError::Io(error)) - if reused - && !matches!( - error.kind(), - std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock - ) => - { - *slot = None; - reused = false; - } - Err(error) => { - *slot = None; - return Err(error.into()); - } - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -411,4 +335,49 @@ mod tests { expected.push(0); assert_eq!(statements_to_claims(&statements).to_bytes(), expected); } + + #[test] + fn a_rate_outside_leanvms_bounds_is_refused() { + let config = LeanVmConfig { + threads: 0, + log_inv_rate: 0, + }; + assert!(matches!( + LeanVmBackend::setup(config), + Err(Error::LogInvRate(0)) + )); + } + + /// End to end on leanVM itself: two committees' proofs, merged, verify + /// against their concatenated statements and nothing else. Seconds of + /// proving, so ignored by default; `cargo test -p ethlambda-crypto + /// --profile release-fast -- --ignored leanvm` runs it. + #[test] + #[ignore = "proves with leanVM: seconds per proof"] + fn leanvm_proofs_merge_and_verify() { + use crate::lean_xmss::range_key; + let backend = LeanVmBackend::setup(LeanVmConfig::default()).unwrap(); + let signed = |seed: u8, leaf: u32, message: &Message| { + let key = range_key(&[seed; 32], leaf, leaf); + let signature = key.sign(message, leaf).unwrap().to_bytes(); + (key.public_key().to_bytes(), signature) + }; + let (m1, m2): (Message, Message) = ([1; 32], [2; 32]); + let (a, sig_a) = signed(10, 40, &m1); + let (b, sig_b) = signed(11, 40, &m1); + let (c, sig_c) = signed(12, 41, &m2); + let first = [statement(&[a, b], 40, m1)]; + let second = [statement(&[c], 41, m2)]; + let one = backend.prove(&first, &[vec![&sig_a, &sig_b]]).unwrap(); + let two = backend.prove(&second, &[vec![&sig_c]]).unwrap(); + assert!(backend.verify(&first, &one)); + assert!(!backend.verify(&second, &one)); + let merged = backend + .merge(&[(&first[..], &one[..]), (&second[..], &two[..])]) + .unwrap(); + let both = [first[0].clone(), second[0].clone()]; + assert!(backend.verify(&both, &merged)); + assert!(!backend.verify(&first, &merged)); + assert!(!backend.verify(&both, &merged[..merged.len() - 1])); + } } diff --git a/leanvm-revision b/leanvm-revision index a4c800f4e..54105bf76 100644 --- a/leanvm-revision +++ b/leanvm-revision @@ -1 +1 @@ -c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764 +1e997c9927d3e7fafa2b813734f56e25d7a4da69 From f8f43aceebe9b1bb6580ec7381db60e672a0b9ea Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:13:47 -0300 Subject: [PATCH 09/25] feat(pq): staggered aggregators again, as consensus-specs pq 4595f0fc has them Reverts e033029d (the move back to pq-devnet-0's unstaggered aggregators): pq-devnet-1 runs consensus-specs pq at or after 4595f0fc, which staggers a committee's aggregators by their seat in its aggregation committee (AGGREGATION_CUTOFF_BPS, AGGREGATE_DUE_BPS_PQ, AGGREGATOR_DELAY_BPS) and has one skip an aggregate a received one already covers. Merged with what landed since the revert: - The node's prover proves per seat, with the per-pass cost line of cd849e37 (now per seat) and b28ae833's genesis rule: the first slot to seal is the wall clock's until its last seat's cutoff, so a node started before genesis still proves slot 0. - The validator client's seats sign in parallel off the duty task, as 908e88df has them. - Tests on the runtime preset accessors; aggregator_position in the test duty helpers #880 brought. Config's layout is 8's again; DB_VERSION goes to 10 rather than back to 8, so a pq-devnet-0 (version 9) directory is refused rather than misread. --- CLAUDE.md | 16 +- bin/ethlambda/src/main.rs | 5 + .../src/beacon/fork_choice.rs | 50 +++ crates/common/types/src/beacon/config.rs | 50 +++ crates/net/p2p/src/beacon/pq.rs | 9 +- crates/net/rpc/src/beacon/pool.rs | 25 +- crates/net/rpc/src/beacon/pq_aggregation.rs | 173 ++++++----- crates/net/rpc/src/beacon/pq_proposal.rs | 3 +- crates/net/rpc/src/beacon/validator.rs | 46 ++- crates/storage/src/pools/pq_signature.rs | 290 +++++++++++++++--- crates/storage/src/store.rs | 18 +- crates/validator/src/aggregation.rs | 61 +++- crates/validator/src/attestation.rs | 1 + crates/validator/src/beacon_node/dto.rs | 63 ++++ crates/validator/src/beacon_node/fallback.rs | 24 +- crates/validator/src/duties.rs | 1 + crates/validator/src/head_monitor.rs | 1 + crates/validator/src/lib.rs | 3 +- crates/validator/src/slot_clock.rs | 43 +++ crates/validator/src/subscriptions.rs | 1 + docs/beacon_pq.md | 31 +- 21 files changed, 725 insertions(+), 189 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 512a4f58f..d71b02f82 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -894,8 +894,8 @@ transitions are in `ethlambda-types`, per the section above. Nothing above `pq` branch, see `docs/beacon_pq.md`, "Running a devnet"), with its own validators: the validator client derives each validator's leanXMSS key and VRF seed from its BLS key - (`ethlambda_crypto::pq_keys`) and attests, aggregates, casts PTC votes and - proposes, each signature + (`ethlambda_crypto::pq_keys`) and attests, aggregates (staggered by its seat + in the aggregation committee), casts PTC votes and proposes, each signature at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all `2^31` leaves, each `keccak256(vrf_seed || le64(slot))`) takes minutes of every core per key, so a background thread hashes it after startup (in a @@ -1222,13 +1222,11 @@ behavior. in-memory map stays as a write-through cache in front of the table. Pruned on finalization to the same horizon as `LiveChain` (the finalized block's own slot, keeping that block's own entry). -- `DB_VERSION` is 9: `Config` lost PQ's aggregation timing keys - (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`, - consensus-specs `4595f0fc`) with the move back to `2f43bc0f`, so a version - 8 directory's stored config decodes into the wrong fields. (8 added the - EIP-8483 and PQ fork versions and epochs, - `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY` and - `ATTESTATION_SUBNET_COUNT_PQ`; 7 moved `States` +- `DB_VERSION` is 8: `Config` gained the EIP-8483 and PQ fork versions and + epochs, `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, PQ's aggregation + timing (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, + `AGGREGATOR_DELAY_BPS`) and `ATTESTATION_SUBNET_COUNT_PQ`, so a version 7 + directory's stored config decodes into the wrong fields. (7 moved `States` and `StateDiffs` from root keys to slot||root keys, the block's slot looked up from `BlockHeaders` by readers, so `Store::prune_finalized_states` can range-delete finalized states; 6 was diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index c7eb93f72..66c738ed8 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -2086,6 +2086,11 @@ fn first_config_difference( // Compared below: when an unregistered validator becomes withdrawable // at the PQ fork is a state-transition rule. unregistered_validator_withdrawability_delay: _, + // PQ's aggregation timing: when an aggregator proves and broadcasts, + // which changes no block's validity. + aggregation_cutoff_bps: _, + aggregate_due_bps_pq: _, + aggregator_delay_bps: _, // Validator cycle: compared below. Churn and inactivity-leak // parameters change which exits, activations and inactivity scores a diff --git a/crates/blockchain/state_transition/src/beacon/fork_choice.rs b/crates/blockchain/state_transition/src/beacon/fork_choice.rs index 5028ac87d..f47bc9010 100644 --- a/crates/blockchain/state_transition/src/beacon/fork_choice.rs +++ b/crates/blockchain/state_transition/src/beacon/fork_choice.rs @@ -4357,6 +4357,31 @@ pub fn get_payload_due_ms(config: &Config) -> u64 { get_slot_component_duration_ms(config.payload_due_bps, config) } +/// `get_aggregate_due_ms` as PQ modifies it (`pq/fork-choice.md`): how far +/// into a slot, in milliseconds, the aggregator at `position` in its +/// aggregation committee broadcasts its aggregate. +/// +/// The aggregators of a committee are staggered, `AGGREGATOR_DELAY_BPS` +/// apart in the committee's order, so a later one can skip an aggregate an +/// earlier one already covered. Named apart from the earlier forks' +/// `get_aggregate_due_ms`, which takes no position and which nothing in this +/// crate implements: its reader is the validator client's clock. +pub fn get_pq_aggregate_due_ms(position: u64, config: &Config) -> u64 { + let delay_ms = get_slot_component_duration_ms(config.aggregator_delay_bps, config); + get_slot_component_duration_ms(config.aggregate_due_bps_pq, config) + .saturating_add(position.saturating_mul(delay_ms)) +} + +/// `get_aggregation_cutoff_ms` (PQ `fork-choice.md`): how far into a slot, in +/// milliseconds, the aggregator at `position` in its aggregation committee +/// stops collecting attestations. From then until +/// [`get_pq_aggregate_due_ms`] it proves the ones it has. +pub fn get_aggregation_cutoff_ms(position: u64, config: &Config) -> u64 { + let delay_ms = get_slot_component_duration_ms(config.aggregator_delay_bps, config); + get_slot_component_duration_ms(config.aggregation_cutoff_bps, config) + .saturating_add(position.saturating_mul(delay_ms)) +} + // --------------------------------------------------------------------------- // Merge transition helpers (bellatrix) // --------------------------------------------------------------------------- @@ -6562,6 +6587,31 @@ mod tests { use crate::beacon::helpers::test_state; use crate::beacon::primitives::BlsSignature; + /// PQ `validator.md`'s table for a 12-second slot: each seat of an + /// aggregation committee stops collecting and broadcasts 0.6 s after the + /// one before it, with 2.4 s in between to prove. + #[test] + fn pq_aggregators_are_staggered_by_their_seat() { + let config = Config::mainnet(); + assert_eq!(config.slot_duration_ms, 12_000); + let expected = [ + (4_800, 7_200), + (5_400, 7_800), + (6_000, 8_400), + (6_600, 9_000), + ]; + for (position, (cutoff, due)) in (0..constants::AGGREGATORS_PER_COMMITTEE).zip(expected) { + assert_eq!(get_aggregation_cutoff_ms(position, &config), cutoff); + assert_eq!(get_pq_aggregate_due_ms(position, &config), due); + } + // The last seat still broadcasts within the slot, on both presets. + for config in [Config::mainnet(), Config::minimal()] { + let last = constants::AGGREGATORS_PER_COMMITTEE - 1; + assert!(get_pq_aggregate_due_ms(last, &config) <= config.slot_duration_ms); + assert!(get_aggregation_cutoff_ms(0, &config) > get_attestation_due_ms(0, &config)); + } + } + /// A store backed by a fresh in-memory backend, with every checkpoint at /// its default (genesis) value and no anchor block or state written. /// Tests populate only what the function under test actually reads. diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index cdbe94253..af8795b97 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -434,6 +434,25 @@ pub struct Config { /// `compute_validators`). #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub unregistered_validator_withdrawability_delay: Epoch, + /// PQ: basis points of [`Self::slot_duration_ms`] by which the first + /// aggregator of an aggregation committee stops collecting attestations + /// and starts proving its aggregate; each later one stops + /// [`Self::aggregator_delay_bps`] after the one before it + /// (`get_aggregation_cutoff_ms`). + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregation_cutoff_bps: u64, + /// PQ: [`Self::aggregate_due_bps_gloas`]'s replacement, the basis points + /// by which the first aggregator of an aggregation committee broadcasts + /// its aggregate; later than gloas's, to leave time to prove one + /// (`get_aggregate_due_ms` modified in PQ). + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregate_due_bps_pq: u64, + /// PQ: basis points of [`Self::slot_duration_ms`] between the cutoffs, + /// and between the broadcasts, of two aggregators next to each other in + /// an aggregation committee. Staggering them lets a later aggregator + /// skip an aggregate an earlier one already covered. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregator_delay_bps: u64, // -- Validator cycle ----------------------------------------------------- /// Score points added to a validator's inactivity score for each epoch it @@ -774,6 +793,9 @@ impl Config { payload_attestation_due_bps: 7_500, min_builder_withdrawability_delay: 64, unregistered_validator_withdrawability_delay: 16_384, + aggregation_cutoff_bps: 4_000, + aggregate_due_bps_pq: 6_000, + aggregator_delay_bps: 500, inactivity_score_bias: 4, inactivity_score_recovery_rate: 16, @@ -914,6 +936,9 @@ impl Config { payload_attestation_due_bps: 7_500, min_builder_withdrawability_delay: 2, unregistered_validator_withdrawability_delay: 16_384, + aggregation_cutoff_bps: 4_000, + aggregate_due_bps_pq: 6_000, + aggregator_delay_bps: 500, inactivity_score_bias: 4, inactivity_score_recovery_rate: 16, @@ -1304,6 +1329,31 @@ mod tests { assert_eq!(config.max_request_payloads, 128); } + #[test] + fn pq_timing_keys_are_claimed_and_parse() { + let yaml = "UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY: 8\n\ + AGGREGATION_CUTOFF_BPS: 3500\nAGGREGATE_DUE_BPS_PQ: 5500\n\ + AGGREGATOR_DELAY_BPS: 250\n"; + let config: Config = serde_yaml_ng::from_str(yaml).unwrap(); + assert_eq!(config.unregistered_validator_withdrawability_delay, 8); + assert_eq!(config.aggregation_cutoff_bps, 3_500); + assert_eq!(config.aggregate_due_bps_pq, 5_500); + assert_eq!(config.aggregator_delay_bps, 250); + } + + /// consensus-specs' `test_config_invariants` for PQ: an aggregator stops + /// collecting before it broadcasts, and the last aggregator of a full + /// aggregation committee still broadcasts within the slot. + #[test] + fn pq_aggregation_timing_fits_the_slot() { + for config in [Config::mainnet(), Config::minimal()] { + assert!(config.aggregation_cutoff_bps < config.aggregate_due_bps_pq); + let last_delay = + (constants::AGGREGATORS_PER_COMMITTEE - 1) * config.aggregator_delay_bps; + assert!(config.aggregate_due_bps_pq + last_delay <= constants::BASIS_POINTS); + } + } + #[test] fn max_blobs_per_block_selects_the_active_schedule_entry() { let config = Config::mainnet(); diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index 6c29c0437..a16a037f4 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -218,7 +218,11 @@ impl PqValidated { } /// Hold an accepted aggregate for block production, which merges the proofs -/// of the ones it packs (PQ `validator.md`, "Proof"). +/// of the ones it packs (PQ `validator.md`, "Proof"), and record its +/// attesters as broadcast, which this node's own aggregators compare theirs +/// against before broadcasting (`should_broadcast_aggregate`). Both the +/// aggregates gossip accepted and the ones this node published come through +/// here. fn pool_aggregate( store: &Store, signed: &pq::SignedAggregateAndProof, @@ -230,6 +234,9 @@ fn pool_aggregate( let [committee_index] = committees[..] else { return; }; + store + .pq_signature_pool() + .note_broadcast(&aggregate.data, committee_index, attesting_indices); store.pq_aggregate_pool().insert(PooledPqAggregate { attestation: aggregate.clone(), committee_index, diff --git a/crates/net/rpc/src/beacon/pool.rs b/crates/net/rpc/src/beacon/pool.rs index 3f51d7bb6..614bf7046 100644 --- a/crates/net/rpc/src/beacon/pool.rs +++ b/crates/net/rpc/src/beacon/pool.rs @@ -701,11 +701,23 @@ async fn get_aggregate_attestation( crate::shared::content::with_consensus_version(response, fork) } +/// The 404 [`get_pq_aggregate`] answers for an aggregate it will not hand +/// out to be broadcast. The validator client reads any 404 here as nothing +/// to publish. +const PQ_AGGREGATE_ALREADY_COVERED: &str = + "an aggregate already broadcast for this committee covers every attester of this one"; + /// [`get_aggregate_attestation`] at a PQ slot: the committee's aggregate /// this node proved from the votes it collected for its aggregators (see /// [`crate::beacon::pq_aggregation`]), with its proof. A request racing the -/// proof waits for it until the slot's signatures are sealed and proved, for -/// at most a few seconds; a 404 when there is none. +/// proof waits for it, for at most a few seconds; a 404 when there is none. +/// +/// Also a 404 when an aggregate already broadcast for the same vote and +/// committee, by another aggregator or an earlier one of this node, includes +/// every attester of this one: PQ `validator.md`'s +/// `should_broadcast_aggregate` answers no, since gossip would ignore it. The +/// validator client asks at its aggregator's own broadcast time, so the +/// answer is the one that time calls for. async fn get_pq_aggregate(store: &Store, query: &AggregateQuery, headers: &HeaderMap) -> Response { use ethlambda_types::beacon::containers::pq; use libssz::SszEncode as _; @@ -732,6 +744,15 @@ async fn get_pq_aggregate(store: &Store, query: &AggregateQuery, headers: &Heade if let Err(err) = require_validated(store, aggregate.attestation.data.beacon_block_root) { return err.into_response(); } + let covered = store.pq_signature_pool().is_covered( + query.slot, + query.attestation_data_root, + query.committee_index, + &aggregate.attesting_indices, + ); + if covered { + return ApiError::NotFound(PQ_AGGREGATE_ALREADY_COVERED).into_response(); + } let answer = pq::ProvenAggregate { aggregate: aggregate.attestation.clone(), proof: aggregate.proof.clone(), diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index be738b792..9fc87c807 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -1,15 +1,21 @@ //! PQ aggregation for this node's validator client. //! //! A PQ aggregator proves its committee's signatures instead of aggregating -//! them (PQ `validator.md`, "Aggregate stark"), and proving takes the -//! sidecar seconds, too long to run inside the `aggregate_attestation` -//! request. So, as Lighthouse's PQ branch does, the node proves ahead: the -//! validator client names the committees it aggregates for through +//! them (PQ `validator.md`, "Aggregate stark"), and proving takes leanVM +//! seconds, too long to run inside the `aggregate_attestation` request. So, +//! as Lighthouse's PQ branch does, the node proves ahead: the validator +//! client names the committees it aggregates for through //! `beacon_committee_subscriptions`, the node collects their validated votes' -//! signatures ([`ethlambda_storage::pools::PqSignaturePool`]), and once a slot -//! the task here seals that slot's signatures halfway between the -//! attestation and aggregate deadlines and proves each committee's before the -//! aggregate deadline, largest first. The endpoint then answers with what was +//! signatures ([`ethlambda_storage::pools::PqSignaturePool`]), and proves +//! each committee's at its aggregator's cutoff. +//! +//! The aggregators of a committee are staggered by their seat in its +//! aggregation committee (PQ `validator.md`, "Construct aggregate"): the one +//! at `position` stops collecting at `get_aggregation_cutoff_ms(position)` and +//! broadcasts at `get_aggregate_due_ms(position)`. The task here wakes at +//! each seat's cutoff in turn, proves what was collected for the committees +//! one of this node's validators holds that seat in, and ends the slot's +//! collection after the last seat's. The endpoint then answers with what was //! proved, and the aggregate also goes into the pool block production packs //! from, since gossip never hands a node its own messages. @@ -17,8 +23,11 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use ethlambda_state_transition::beacon::{ - fork_choice::{get_attestation_due_ms, get_slot_component_duration_ms}, - helpers::{accessors::CommitteeCacheExt as _, pq::get_attestation_statements}, + fork_choice::{get_aggregation_cutoff_ms, get_pq_aggregate_due_ms}, + helpers::{ + accessors::CommitteeCacheExt as _, + pq::{get_aggregation_committee, get_attestation_statements}, + }, }; use ethlambda_storage::{ Store, @@ -26,6 +35,7 @@ use ethlambda_storage::{ }; use ethlambda_types::beacon::{ config::Config, + constants::AGGREGATORS_PER_COMMITTEE, containers::{BeaconState, pq}, fork::ForkName, primitives::Slot, @@ -36,8 +46,8 @@ use tracing::{debug, info, warn}; use crate::beacon::validator::head; -/// Start proving PQ aggregates once a slot, if the network schedules PQ. -/// Stops with `shutdown`. +/// Start proving PQ aggregates at every aggregator's cutoff, if the network +/// schedules PQ. Stops with `shutdown`. pub(crate) fn spawn(store: Store, shutdown: CancellationToken) { let config = store.config(); if config.fork_epoch(ForkName::Pq) == u64::MAX { @@ -50,35 +60,54 @@ pub(crate) fn spawn(store: Store, shutdown: CancellationToken) { loop { let slot = next_slot_to_seal(&config, now_ms()).max(next); next = slot + 1; - let cutoff = collection_cutoff_ms(&config, slot); - let wait = Duration::from_millis(cutoff.saturating_sub(now_ms())); - tokio::select! { - () = shutdown.cancelled() => return, - () = tokio::time::sleep(wait) => {} - } - if config.fork_at_epoch(compute_epoch_at_slot(slot)) != ForkName::Pq { - continue; + for position in 0..AGGREGATORS_PER_COMMITTEE { + let cutoff = + slot_start_ms(&config, slot) + get_aggregation_cutoff_ms(position, &config); + let wait = Duration::from_millis(cutoff.saturating_sub(now_ms())); + tokio::select! { + () = shutdown.cancelled() => return, + () = tokio::time::sleep(wait) => {} + } + if config.fork_at_epoch(compute_epoch_at_slot(slot)) == ForkName::Pq { + prove_seat(&store, &config, slot, position).await; + } } - prove_slot(&store, &config, slot).await; + // The last seat's cutoff has passed: nothing more is collected. + store.pq_signature_pool().seal(slot); } }); } -/// Seal `slot`'s collected signatures and prove what the time to its -/// aggregate deadline allows. -async fn prove_slot(store: &Store, config: &Config, slot: Slot) { - let groups = store.pq_signature_pool().seal(slot); - if groups.is_empty() { +/// The committees of `slot` in which one of this node's aggregators holds +/// seat `position` of the aggregation committee, as `state` names them. +fn committees_at_seat(store: &Store, state: &BeaconState, slot: Slot, position: u64) -> Vec { + // Bound first, so the pool's lock is not held while committees are read. + let aggregators = store.pq_signature_pool().aggregators(slot); + aggregators + .into_iter() + .filter(|(committee, validators)| { + get_aggregation_committee(state, slot, *committee).is_ok_and(|members| { + members + .get(position as usize) + .is_some_and(|member| validators.contains(member)) + }) + }) + .map(|(committee, _)| committee) + .collect() +} + +/// Prove what `slot` collected for the committees whose aggregator at +/// `position` is this node's, before that aggregator's broadcast time. +async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { + if store.pq_signature_pool().aggregators(slot).is_empty() { return; } - let deadline_ms = slot_start_ms(config, slot) + aggregate_due_ms(config, slot); + let deadline_ms = slot_start_ms(config, slot) + get_pq_aggregate_due_ms(position, config); let Some(budget) = deadline_ms.checked_sub(now_ms()).filter(|&left| left > 0) else { - warn!(%slot, "No time left to prove this slot's PQ aggregates"); + warn!(%slot, position, "No time left to prove this seat's PQ aggregates"); return; }; let deadline = Instant::now() + Duration::from_millis(budget); - let committees = groups.len(); - let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); let store = store.clone(); let spawned = Instant::now(); let job = tokio::task::spawn_blocking(move || { @@ -89,12 +118,18 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { let state = match head(&store) { Ok((_, state)) => state, Err(err) => { - warn!(%slot, ?err, "Could not read the head state to prove this slot's PQ aggregates"); + warn!(%slot, position, ?err, "Could not read the head state to prove this seat's PQ aggregates"); return; } }; + let committees = committees_at_seat(&store, &state, slot, position); + if committees.is_empty() { + return; + } let state_ms = started.elapsed().as_millis() as u64; - let mut groups = groups; + let mut groups = store.pq_signature_pool().collected(slot, &committees); + let committees = groups.len(); + let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the // deadline. groups.sort_by_key(|group| std::cmp::Reverse(group.signatures.len())); @@ -102,7 +137,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { let mut prove_ms_total = 0u64; for group in groups { if Instant::now() >= deadline { - warn!(%slot, "The PQ aggregate deadline passed with committees left to prove"); + warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); break; } let committee = group.committee_index; @@ -117,6 +152,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { info!( %slot, committee, + position, attesters = aggregate.attesting_indices.len(), proof_bytes = aggregate.proof.len(), prove_ms, @@ -132,6 +168,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { warn!( %slot, committee, + position, attesters = aggregate.attesting_indices.len(), prove_ms, took_ms, @@ -144,6 +181,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { debug!( %slot, committee, + position, signatures = collected, took_ms, %err, @@ -152,10 +190,11 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { } } } - // One line for the slot's whole proving pass: what the sidecar was - // asked for, what it cost, and what the budget left undone. + // One line for the seat's whole proving pass: what leanVM was asked + // for, what it cost, and what the budget left undone. info!( %slot, + position, committees, signatures, proved, @@ -167,7 +206,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { prove_ms = prove_ms_total, took_ms = started.elapsed().as_millis() as u64, budget_ms = budget, - "Finished proving this slot's PQ aggregates" + "Finished proving this seat's PQ aggregates" ); }); let _ = job.await; @@ -249,41 +288,19 @@ fn slot_start_ms(config: &Config, slot: Slot) -> u64 { } /// The first slot whose signatures are still being collected at `now_ms`: -/// slot 0 before genesis, then the wall clock's slot until its collection -/// cutoff and the next one after it. Taking the wall clock's slot plus one -/// skipped slot 0 on a node started before genesis, whose aggregators' votes -/// were then never proved. +/// slot 0 before genesis, then the wall clock's slot until its last seat's +/// collection cutoff and the next one after it. Taking the wall clock's slot +/// plus one skipped slot 0 on a node started before genesis, whose +/// aggregators' votes were then never proved. fn next_slot_to_seal(config: &Config, now_ms: u64) -> Slot { let genesis_ms = config.genesis_time.saturating_mul(1000); let Some(elapsed) = now_ms.checked_sub(genesis_ms) else { return 0; }; let slot = elapsed / config.slot_duration_ms.max(1); - if now_ms < collection_cutoff_ms(config, slot) { - slot - } else { - slot + 1 - } -} - -/// How far into `slot` its aggregates are due. -fn aggregate_due_ms(config: &Config, slot: Slot) -> u64 { - let gloas_on = config.fork_at_epoch(compute_epoch_at_slot(slot)) >= ForkName::Gloas; - let basis_points = if gloas_on { - config.aggregate_due_bps_gloas - } else { - config.aggregate_due_bps - }; - get_slot_component_duration_ms(basis_points, config) -} - -/// When `slot`'s signatures stop being collected: halfway from the -/// attestation deadline to the aggregate deadline. -fn collection_cutoff_ms(config: &Config, slot: Slot) -> u64 { - let attestation_due = get_attestation_due_ms(compute_epoch_at_slot(slot), config); - let aggregate_due = aggregate_due_ms(config, slot); - let window = aggregate_due.saturating_sub(attestation_due); - slot_start_ms(config, slot) + attestation_due + window / 2 + let last_cutoff = slot_start_ms(config, slot) + + get_aggregation_cutoff_ms(AGGREGATORS_PER_COMMITTEE - 1, config); + if now_ms < last_cutoff { slot } else { slot + 1 } } #[cfg(test)] @@ -291,30 +308,32 @@ mod tests { use super::*; #[test] - fn signatures_are_collected_until_halfway_to_the_aggregate_deadline() { + fn each_seat_proves_between_its_cutoff_and_its_broadcast() { let mut config = Config::mainnet(); config.genesis_time = 100; - config.gloas_fork_epoch = 0; - // Gloas timing: attestations at 25% of 12 s, aggregates at 50%. assert_eq!(slot_start_ms(&config, 2), 100_000 + 24_000); - assert_eq!(aggregate_due_ms(&config, 2), 6_000); - assert_eq!(collection_cutoff_ms(&config, 2), 124_000 + 3_000 + 1_500); + for position in 0..AGGREGATORS_PER_COMMITTEE { + let cutoff = get_aggregation_cutoff_ms(position, &config); + let due = get_pq_aggregate_due_ms(position, &config); + // 2.4 s to prove on a 12 s slot, whatever the seat. + assert_eq!(due - cutoff, 2_400); + } } #[test] fn the_next_slot_to_seal_starts_at_genesis() { let mut config = Config::mainnet(); config.genesis_time = 100; - config.gloas_fork_epoch = 0; - // Before genesis: slot 0, whose cutoff is 4.5 s into it. + // Before genesis: slot 0, whose last seat (3) stops collecting + // 40% + 3 * 5% of 12 s in, at 6.6 s. assert_eq!(next_slot_to_seal(&config, 0), 0); assert_eq!(next_slot_to_seal(&config, 99_999), 0); - assert_eq!(next_slot_to_seal(&config, 104_499), 0); - assert_eq!(next_slot_to_seal(&config, 104_500), 1); - // Mid-slot: that slot until its cutoff, the next one from then on. + assert_eq!(next_slot_to_seal(&config, 106_599), 0); + assert_eq!(next_slot_to_seal(&config, 106_600), 1); + // Mid-slot: that slot until its last cutoff, the next one from then on. assert_eq!(next_slot_to_seal(&config, 124_000), 2); - assert_eq!(next_slot_to_seal(&config, 128_499), 2); - assert_eq!(next_slot_to_seal(&config, 128_500), 3); + assert_eq!(next_slot_to_seal(&config, 130_599), 2); + assert_eq!(next_slot_to_seal(&config, 130_600), 3); assert_eq!(next_slot_to_seal(&config, 135_999), 3); } } diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index 9fcdef70d..1585c208a 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -115,7 +115,8 @@ impl PqBlobs { #[derive(Debug, Deserialize)] struct ProducePqBlock { - /// The proposer's VRF proof for the slot: the leaf, then its branch. + /// The proposer's VRF proof for the slot: the secret, then its leaf's + /// branch. randao_reveal: Vec, #[serde(default)] graffiti: Option, diff --git a/crates/net/rpc/src/beacon/validator.rs b/crates/net/rpc/src/beacon/validator.rs index f65d893bb..f8c4e8cc0 100644 --- a/crates/net/rpc/src/beacon/validator.rs +++ b/crates/net/rpc/src/beacon/validator.rs @@ -295,11 +295,11 @@ fn liveness(store: &Store, epoch: &str, indices: &[String]) -> Result, + /// A PQ aggregator's index in its aggregation committee, which staggers + /// it: the `position` of `get_aggregation_cutoff_ms` and + /// `get_aggregate_due_ms` (PQ `validator.md`, "Construct aggregate"). + /// Absent for a validator that is not one. + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "quoted_position" + )] + aggregator_position: Option, +} + +/// An aggregator's position as the Beacon API writes an integer: a decimal +/// string. Only called for `Some`, since `None` is skipped. +fn quoted_position( + position: &Option, + serializer: S, +) -> Result { + serializer.collect_str(&position.unwrap_or_default()) } /// `POST /eth/v1/validator/duties/attester/{epoch}`, with the validator @@ -765,10 +786,14 @@ fn attester_duties( .map_err(|_| ApiError::Internal("committee names an unknown validator"))?; // A state not yet at PQ (the fork's first epoch, asked // early) names no aggregation committee: not an aggregator. - let is_aggregator = is_pq.then(|| { + let aggregator_position = if is_pq { get_aggregation_committee(&state, slot, committee_index) - .is_ok_and(|members| members.contains(&validator_index)) - }); + .ok() + .and_then(|members| members.iter().position(|&m| m == validator_index)) + .map(|seat| seat as u64) + } else { + None + }; duties.push(AttesterDuty { pubkey: ApiPubkey::of(&state, validator.pubkey), validator_index, @@ -777,7 +802,8 @@ fn attester_duties( committees_at_slot, validator_committee_index: position as u64, slot, - is_aggregator, + is_aggregator: is_pq.then_some(aggregator_position.is_some()), + aggregator_position, }); } } diff --git a/crates/storage/src/pools/pq_signature.rs b/crates/storage/src/pools/pq_signature.rs index a81d0a37c..4fb4ba3a3 100644 --- a/crates/storage/src/pools/pq_signature.rs +++ b/crates/storage/src/pools/pq_signature.rs @@ -5,9 +5,16 @@ //! signatures with an `AttestationProof` instead of aggregating them. The //! validator client names the committees it aggregates for through //! `beacon_committee_subscriptions`; this pool keeps the signatures of -//! validated single attestations for those committees only, seals each slot's -//! once its collection window closes, and holds what the node proved from -//! them for the aggregate endpoint to answer with. +//! validated single attestations for those committees only, hands what it +//! has collected to the prover at each of its aggregators' cutoffs, and holds +//! what the node proved from them for the aggregate endpoint to answer with. +//! +//! The aggregators of a committee are staggered (`get_aggregation_cutoff_ms`), +//! so a slot's signatures are read more than once and its collection ends at +//! the last cutoff ([`PqSignaturePool::seal`]). The pool also records the +//! attesters of every aggregate broadcast for those committees, gossip's and +//! this node's own, which is what `should_broadcast_aggregate` compares an +//! aggregate against before it is broadcast. //! //! In memory only, and a few slots deep: an aggregate is published within its //! own slot. @@ -36,6 +43,13 @@ fn max_groups_per_slot() -> usize { preset::max_committees_per_slot_pq() * 4 } +/// How many broadcast aggregates' attester sets the pool keeps per +/// `(AttestationData, committee)`. Gossip accepts one aggregate per +/// aggregator and epoch, and only one no earlier aggregate covers, so a +/// committee's `AGGREGATORS_PER_COMMITTEE` aggregators fill at most that +/// many; twice that leaves room without letting a peer grow the record. +const MAX_BROADCAST_SETS: usize = 8; + /// `(slot, data root, committee index)`. type Key = (Slot, Root, u64); @@ -52,12 +66,16 @@ pub struct CommitteeSignatures { /// Signatures awaiting proof and the aggregates proved from them. #[derive(Debug, Default)] pub struct PqSignaturePool { - /// `(slot, committee)` this node's validators aggregate for. - subscriptions: BTreeSet<(Slot, u64)>, + /// The validators of this node that aggregate for each `(slot, + /// committee)`. + subscriptions: BTreeMap<(Slot, u64), BTreeSet>, raw: BTreeMap, proven: BTreeMap>, - /// The latest slot whose signatures were handed to the prover: later - /// signatures for it are not collected. + /// The attesters, sorted, of each aggregate broadcast for a subscribed + /// committee: the ones gossip accepted and the ones this node published. + broadcast: BTreeMap>>, + /// The latest slot whose collection ended: later signatures for it are + /// not collected. sealed_slot: Option, } @@ -66,26 +84,48 @@ impl PqSignaturePool { let earliest = now.saturating_sub(RETAINED_SLOTS - 1); self.raw.retain(|(slot, _, _), _| *slot >= earliest); self.proven.retain(|(slot, _, _), _| *slot >= earliest); - self.subscriptions.retain(|(slot, _)| *slot >= now); + self.broadcast.retain(|(slot, _, _), _| *slot >= earliest); + self.subscriptions.retain(|(slot, _), _| *slot >= now); } - /// Collect `committee`'s signatures at `slot`, which one of this node's - /// validators aggregates for. Refused for a past slot, one more than two + /// Collect `committee`'s signatures at `slot`, which `validator`, one of + /// this node's, aggregates for. Refused for a past slot, one more than two /// epochs ahead, or a committee index PQ cannot have. - pub fn subscribe(&mut self, now: Slot, slot: Slot, committee: u64) -> bool { + pub fn subscribe( + &mut self, + now: Slot, + slot: Slot, + committee: u64, + validator: ValidatorIndex, + ) -> bool { self.prune(now); let accepted = slot >= now && slot <= now.saturating_add(2 * preset::slots_per_epoch()) && committee < preset::max_committees_per_slot_pq() as u64; if accepted { - self.subscriptions.insert((slot, committee)); + let aggregators = self.subscriptions.entry((slot, committee)).or_default(); + // A committee has `AGGREGATORS_PER_COMMITTEE` aggregators; more + // names than a committee has members is a caller's mistake, and + // the bound keeps the record from growing with it. + if aggregators.len() < preset::MAX_VALIDATORS_PER_COMMITTEE { + aggregators.insert(validator); + } } accepted } /// Whether this node collects `committee`'s signatures at `slot`. pub fn is_subscribed(&self, slot: Slot, committee: u64) -> bool { - self.subscriptions.contains(&(slot, committee)) + self.subscriptions.contains_key(&(slot, committee)) + } + + /// The committees of `slot` this node aggregates for, each with its + /// aggregators among this node's validators. + pub fn aggregators(&self, slot: Slot) -> Vec<(u64, Vec)> { + self.subscriptions + .range((slot, 0)..=(slot, u64::MAX)) + .map(|(&(_, committee), validators)| (committee, validators.iter().copied().collect())) + .collect() } /// Keep a validated attestation's signature, if its committee is one this @@ -97,7 +137,7 @@ impl PqSignaturePool { let committee = attestation.committee_index; if slot < now || self.sealed_slot.is_some_and(|sealed| slot <= sealed) - || !self.subscriptions.contains(&(slot, committee)) + || !self.subscriptions.contains_key(&(slot, committee)) { return false; } @@ -128,27 +168,43 @@ impl PqSignaturePool { kept } - /// Hand `slot`'s collected signatures to the prover, at most once per - /// slot. Signatures arriving for it afterwards are not collected. - pub fn seal(&mut self, slot: Slot) -> Vec { + /// What `slot` has collected so far for `committees`, for an aggregator + /// whose cutoff has come. Collection goes on for the aggregators after + /// it, until [`Self::seal`]. + pub fn collected(&self, slot: Slot, committees: &[u64]) -> Vec { + self.raw + .range((slot, Root::ZERO, 0)..) + .take_while(|((held, _, _), _)| *held == slot) + .filter(|((_, _, committee), _)| committees.contains(committee)) + .map(|(_, group)| group.clone()) + .collect() + } + + /// End `slot`'s collection, once its last aggregator's cutoff has passed: + /// its signatures are dropped and none arriving afterwards is kept. + pub fn seal(&mut self, slot: Slot) { self.prune(slot); if self.sealed_slot.is_some_and(|sealed| slot <= sealed) { - return Vec::new(); + return; } self.sealed_slot = Some(slot); - let later = self.raw.split_off(&(slot + 1, Root::ZERO, 0)); - std::mem::replace(&mut self.raw, later) - .into_iter() - .filter(|((held, _, _), _)| *held == slot) - .map(|(_, group)| group) - .collect() + self.raw = self.raw.split_off(&(slot + 1, Root::ZERO, 0)); } /// Hold an aggregate this node proved, for the aggregate endpoint. + /// + /// A later seat proves from more signatures than an earlier one, so the + /// aggregate covering more attesters is the one kept. pub fn insert_proven(&mut self, aggregate: Arc) { let data = &aggregate.attestation.data; let key = (data.slot, data.hash_tree_root(), aggregate.committee_index); - self.proven.insert(key, aggregate); + let better = self + .proven + .get(&key) + .is_none_or(|held| aggregate.attesting_indices.len() > held.attesting_indices.len()); + if better { + self.proven.insert(key, aggregate); + } } /// The aggregate this node proved for `committee`'s vote on the data @@ -162,10 +218,65 @@ impl PqSignaturePool { self.proven.get(&(slot, data_root, committee)).cloned() } - /// Whether `slot`'s signatures were already handed to the prover. + /// Whether `slot`'s collection has ended. pub fn is_sealed(&self, slot: Slot) -> bool { self.sealed_slot.is_some_and(|sealed| slot <= sealed) } + + /// Record an aggregate broadcast for `committee`'s vote on `data`, with + /// the attesters it covers: one gossip accepted, or one this node + /// published. Kept only for committees this node aggregates for. + pub fn note_broadcast( + &mut self, + data: &AttestationData, + committee: u64, + attesting_indices: &[ValidatorIndex], + ) { + if !self.subscriptions.contains_key(&(data.slot, committee)) { + return; + } + let mut attesters = attesting_indices.to_vec(); + attesters.sort_unstable(); + attesters.dedup(); + let sets = self + .broadcast + .entry((data.slot, data.hash_tree_root(), committee)) + .or_default(); + if sets.iter().any(|held| is_superset(held, &attesters)) { + return; + } + sets.retain(|held| !is_superset(&attesters, held)); + if sets.len() < MAX_BROADCAST_SETS { + sets.push(attesters); + } + } + + /// Whether an aggregate already broadcast for the same data and committee + /// includes all of `attesting_indices`: the negation of PQ + /// `validator.md`'s `should_broadcast_aggregate`. Each broadcast + /// aggregate is compared on its own, since a proposer includes one per + /// committee: two that only together cover the attesters do not make an + /// aggregate redundant. An identical one does. + pub fn is_covered( + &self, + slot: Slot, + data_root: Root, + committee: u64, + attesting_indices: &[ValidatorIndex], + ) -> bool { + let mut attesters = attesting_indices.to_vec(); + attesters.sort_unstable(); + self.broadcast + .get(&(slot, data_root, committee)) + .is_some_and(|sets| sets.iter().any(|held| is_superset(held, &attesters))) + } +} + +/// Whether sorted `held` includes every element of `wanted`. +fn is_superset(held: &[ValidatorIndex], wanted: &[ValidatorIndex]) -> bool { + wanted + .iter() + .all(|validator| held.binary_search(validator).is_ok()) } #[cfg(test)] @@ -186,47 +297,138 @@ mod tests { } #[test] - fn signatures_need_a_subscription_and_a_slot_seals_once() { + fn signatures_need_a_subscription_and_are_read_until_the_slot_seals() { let mut pool = PqSignaturePool::default(); assert!(!pool.insert(3, &vote(3, 0, 7, 1))); - assert!(pool.subscribe(3, 3, 0)); + assert!(pool.subscribe(3, 3, 0, 7)); assert!(pool.insert(3, &vote(3, 0, 7, 1))); // The first signature per attester wins. assert!(!pool.insert(3, &vote(3, 0, 7, 1))); - assert!(pool.insert(3, &vote(3, 0, 8, 1))); // Another committee of the slot is not subscribed. assert!(!pool.insert(3, &vote(3, 1, 9, 1))); - let sealed = pool.seal(3); - let [group] = sealed.as_slice() else { - panic!("one group to prove"); + // The first aggregator's cutoff reads what there is, and collection + // goes on for the next one. + let attesters = |pool: &PqSignaturePool| -> Vec> { + pool.collected(3, &[0]) + .iter() + .map(|group| group.signatures.keys().copied().collect()) + .collect() }; - assert_eq!( - group.signatures.keys().copied().collect::>(), - vec![7, 8] - ); - // Nothing more is collected for a sealed slot, nor sealed twice. + assert_eq!(attesters(&pool), vec![vec![7]]); + assert!(pool.insert(3, &vote(3, 0, 8, 1))); + assert_eq!(attesters(&pool), vec![vec![7, 8]]); + // Only the committees asked for are read. + assert!(pool.collected(3, &[1]).is_empty()); + assert!(pool.collected(4, &[0]).is_empty()); + + // Nothing more is collected for a sealed slot. + pool.seal(3); + assert!(pool.is_sealed(3)); + assert!(pool.collected(3, &[0]).is_empty()); assert!(!pool.insert(3, &vote(3, 0, 10, 1))); - assert!(pool.seal(3).is_empty()); + } + + #[test] + fn sealing_a_slot_keeps_the_next_ones_signatures() { + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 7); + pool.subscribe(3, 4, 0, 7); + pool.insert(3, &vote(3, 0, 7, 1)); + pool.insert(3, &vote(4, 0, 7, 1)); + pool.seal(3); + assert_eq!(pool.collected(4, &[0]).len(), 1); } #[test] fn a_slot_holds_a_bounded_number_of_groups() { let mut pool = PqSignaturePool::default(); - pool.subscribe(3, 3, 0); + pool.subscribe(3, 3, 0, 7); for root in 0..=max_groups_per_slot() as u8 { pool.insert(3, &vote(3, 0, root as u64, root)); } - assert_eq!(pool.seal(3).len(), max_groups_per_slot()); + assert_eq!(pool.collected(3, &[0]).len(), max_groups_per_slot()); } #[test] fn subscriptions_are_bounded_in_time_and_committee() { let mut pool = PqSignaturePool::default(); - assert!(!pool.subscribe(10, 9, 0)); - assert!(!pool.subscribe(10, 10 + 2 * preset::slots_per_epoch() + 1, 0)); - assert!(!pool.subscribe(10, 10, preset::max_committees_per_slot_pq() as u64)); - assert!(pool.subscribe(10, 12, 1)); + assert!(!pool.subscribe(10, 9, 0, 1)); + assert!(!pool.subscribe(10, 10 + 2 * preset::slots_per_epoch() + 1, 0, 1)); + assert!(!pool.subscribe(10, 10, preset::max_committees_per_slot_pq() as u64, 1)); + assert!(pool.subscribe(10, 12, 1, 1)); assert!(pool.is_subscribed(12, 1)); } + + #[test] + fn a_committees_aggregators_are_the_validators_that_subscribed() { + let mut pool = PqSignaturePool::default(); + pool.subscribe(10, 12, 1, 40); + pool.subscribe(10, 12, 1, 30); + pool.subscribe(10, 12, 1, 40); + pool.subscribe(10, 12, 3, 50); + pool.subscribe(10, 13, 0, 60); + assert_eq!(pool.aggregators(12), vec![(1, vec![30, 40]), (3, vec![50])]); + assert!(pool.aggregators(11).is_empty()); + } + + /// PQ `validator.md`'s table for `should_broadcast_aggregate`: whether an + /// aggregator in a committee of four broadcasts an aggregate with + /// attesters 0 and 1, given the aggregates already broadcast. + #[test] + fn an_aggregate_is_redundant_only_when_one_broadcast_covers_it() { + let data = vote(3, 0, 0, 1).data; + let root = data.hash_tree_root(); + let covered_given = |broadcast: &[&[ValidatorIndex]]| { + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 0); + for attesters in broadcast { + pool.note_broadcast(&data, 0, attesters); + } + pool.is_covered(3, root, 0, &[0, 1]) + }; + // Nothing to compare against. + assert!(!covered_given(&[])); + // `1000` lacks attester 1. + assert!(!covered_given(&[&[0]])); + // `1110` has attesters 0 and 1. + assert!(covered_given(&[&[0, 1, 2]])); + // `1100`: an identical aggregate counts as a superset. + assert!(covered_given(&[&[1, 0]])); + // `1000` and `0100`: neither has both. + assert!(!covered_given(&[&[0], &[1]])); + // `0011` has neither. + assert!(!covered_given(&[&[2, 3]])); + } + + #[test] + fn broadcasts_are_kept_per_vote_and_committee_and_only_when_subscribed() { + let data = vote(3, 0, 0, 1).data; + let other = vote(3, 0, 0, 2).data; + let mut pool = PqSignaturePool::default(); + // Not a committee this node aggregates for: nothing is kept. + pool.note_broadcast(&data, 0, &[0, 1]); + assert!(!pool.is_covered(3, data.hash_tree_root(), 0, &[0])); + + pool.subscribe(3, 3, 0, 0); + pool.subscribe(3, 3, 1, 0); + pool.note_broadcast(&data, 0, &[0, 1]); + assert!(pool.is_covered(3, data.hash_tree_root(), 0, &[0])); + // Another vote of the committee, and another committee's same vote. + assert!(!pool.is_covered(3, other.hash_tree_root(), 0, &[0])); + assert!(!pool.is_covered(3, data.hash_tree_root(), 1, &[0])); + + // A set a later one covers is dropped, so the record stays small. + for extra in 2..40 { + let attesters: Vec = (0..=extra).collect(); + pool.note_broadcast(&data, 0, &attesters); + } + let key = (3, data.hash_tree_root(), 0); + assert_eq!(pool.broadcast[&key].len(), 1); + // Disjoint sets are capped. + for attester in 100..140 { + pool.note_broadcast(&data, 0, &[attester]); + } + assert_eq!(pool.broadcast[&key].len(), MAX_BROADCAST_SETS); + } } diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 1b7d49f84..15ece934b 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -226,16 +226,20 @@ const KEY_STATES_PRUNED_BELOW: &[u8] = b"states_pruned_below"; /// same policy every previous change followed. /// /// 8 widened `Config` with the EIP-8483 and PQ fork versions and epochs, -/// `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY` and -/// `ATTESTATION_SUBNET_COUNT_PQ`, so a directory written by +/// `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, PQ's aggregation timing +/// (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`) +/// and `ATTESTATION_SUBNET_COUNT_PQ`, so a directory written by /// version 7 decodes into the wrong fields, the same consequence as 3, 4 and /// 6. /// -/// 9 narrowed `Config` again: the PQ aggregation timing keys of consensus-specs -/// `4595f0fc` (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, -/// `AGGREGATOR_DELAY_BPS`) left with the move back to `2f43bc0f`, so a -/// directory a version 8 build wrote with them decodes into the wrong fields. -pub const DB_VERSION: u64 = 9; +/// 9 (pq-devnet-0) narrowed `Config` again: the PQ aggregation timing keys of +/// consensus-specs `4595f0fc` left with the move back to `2f43bc0f`. +/// +/// 10 (pq-devnet-1) puts them back, so a directory version 9 wrote decodes +/// into the wrong fields. Not 8 again, although the layout is 8's: a number +/// stands for one history, and nothing should read a version 9 directory as +/// the version before it. +pub const DB_VERSION: u64 = 10; /// The consensus protocol a data directory holds. /// diff --git a/crates/validator/src/aggregation.rs b/crates/validator/src/aggregation.rs index e9a66dc78..54837e938 100644 --- a/crates/validator/src/aggregation.rs +++ b/crates/validator/src/aggregation.rs @@ -34,6 +34,7 @@ use std::collections::BTreeMap; use std::sync::Arc; +use std::time::SystemTime; use ethlambda_types::beacon::containers::electra; use ethlambda_types::beacon::containers::gloas; @@ -49,6 +50,7 @@ use crate::beacon_node::{AggregateKind, BeaconNodeApi, SignedAggregates}; use crate::error::{Error, Result}; use crate::keys::ValidatorStore; use crate::signing::{AggregateAndProofRef, SigningContext, sign_all}; +use crate::slot_clock::SlotClock; /// An `AggregateAndProof` of either fork, held between building it and /// signing it. @@ -94,27 +96,58 @@ impl AggregationService { /// "Broadcast aggregate"). There is no selection proof, and the proof of /// the attesters' signatures is the node's: it collects them and proves /// ahead, since proving takes seconds. + /// + /// The aggregators are staggered by seat: the one at `position` publishes + /// at `get_aggregate_due_ms(position)`, so this waits for each seat's time + /// in turn. The node answers 404 for an aggregate one already broadcast + /// covers (`should_broadcast_aggregate`), which skips it here. pub async fn aggregate_pq( &self, + clock: &SlotClock, slot: Slot, data: &AttestationData, duties: &[AttesterDutyDto], ) -> Result { - use ethlambda_types::beacon::constants::LEAF_OFFSET_AGGREGATE_AND_PROOF; - use ethlambda_types::beacon::containers::pq; - - let selected: Vec<&AttesterDutyDto> = duties + let mut by_seat: BTreeMap> = BTreeMap::new(); + for duty in duties .iter() .filter(|duty| duty.is_aggregator == Some(true)) - .collect(); - if selected.is_empty() { - return Ok(0); + { + by_seat + .entry(duty.aggregator_position.unwrap_or(0)) + .or_default() + .push(duty); + } + let mut published = 0; + for (position, seated) in by_seat { + let due = clock.pq_aggregation_time(slot, position); + let wait = due.duration_since(SystemTime::now()).unwrap_or_default(); + tokio::time::sleep(wait).await; + match self.publish_pq_seat(slot, data, &seated).await { + Ok(count) => published += count, + Err(err) => { + warn!(%slot, position, %err, "Failed to publish this seat's PQ aggregates") + } + } } + Ok(published) + } + + /// Fetch, sign and publish the aggregates of the aggregators `selected`, + /// all at one seat of their committees' aggregation committees. + async fn publish_pq_seat( + &self, + slot: Slot, + data: &AttestationData, + selected: &[&AttesterDutyDto], + ) -> Result { + use ethlambda_types::beacon::constants::LEAF_OFFSET_AGGREGATE_AND_PROOF; + use ethlambda_types::beacon::containers::pq; // One fetch per committee, as for the other forks. let data_root = data.hash_tree_root(); let mut aggregates = BTreeMap::new(); - for duty in &selected { + for duty in selected { if aggregates.contains_key(&duty.committee_index) { continue; } @@ -126,13 +159,14 @@ impl AggregationService { Ok(aggregate) => { aggregates.insert(duty.committee_index, aggregate); } - // The node proved nothing for the committee: no votes reached - // it, or the proof missed the aggregate deadline. - Err(Error::BeaconNodeStatus { status: 404, body }) => warn!( + // A 404 also when another aggregator's broadcast already + // covers every attester: nothing to publish, as the + // specification has it. The node's message says which. + Err(Error::BeaconNodeStatus { status: 404, body }) => info!( %slot, committee = duty.committee_index, reason = %body, - "No PQ aggregate available for this committee" + "No PQ aggregate to publish for this committee" ), Err(err) => warn!( %slot, @@ -144,7 +178,7 @@ impl AggregationService { } let mut owed = Vec::new(); - for duty in &selected { + for duty in selected { let Some(proven) = aggregates.get(&duty.committee_index) else { continue; }; @@ -472,6 +506,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/attestation.rs b/crates/validator/src/attestation.rs index 9a8c58b23..072263a22 100644 --- a/crates/validator/src/attestation.rs +++ b/crates/validator/src/attestation.rs @@ -435,6 +435,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index bbdd19f6b..3b32990ed 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -59,6 +59,20 @@ pub mod quoted_u64 { } } +/// An optional quoted 64-bit integer: absent (or `null`) is `None`. Used with +/// `#[serde(default)]` so a field older nodes do not send is simply missing. +pub mod quoted_u64_option { + use serde::{Deserialize as _, Deserializer}; + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|text| text.parse().map_err(serde::de::Error::custom)) + .transpose() + } +} + /// A list of 64-bit integers, each quoted, as `validator_sync_committee_indices` /// and `sync_committee_indices` carry them. pub mod quoted_u64_vec { @@ -218,6 +232,12 @@ pub struct AttesterDutyDto { /// before PQ, where aggregators select themselves with a BLS proof. #[serde(default)] pub is_aggregator: Option, + /// A PQ aggregator's index in its aggregation committee, which staggers + /// its broadcast (`get_aggregate_due_ms(position)`, PQ `validator.md`). + /// Absent from a node that does not send it, which is read as the first + /// seat: the earliest time, and the one gloas-style nodes assume. + #[serde(default, with = "quoted_u64_option")] + pub aggregator_position: Option, } /// One proposer duty, from `GET /eth/v1/validator/duties/proposer/{epoch}`. @@ -653,6 +673,11 @@ pub fn config_from_spec_response(value: &serde_json::Value) -> Result { "PAYLOAD_ATTESTATION_DUE_BPS", &mut config.payload_attestation_due_bps, ), + // PQ's staggered aggregators. Absent keeps the specification's + // defaults (4000, 6000, 500). + ("AGGREGATION_CUTOFF_BPS", &mut config.aggregation_cutoff_bps), + ("AGGREGATE_DUE_BPS_PQ", &mut config.aggregate_due_bps_pq), + ("AGGREGATOR_DELAY_BPS", &mut config.aggregator_delay_bps), ] { if let Some(bps) = spec_u64(value, key)? { *field = bps; @@ -1140,6 +1165,44 @@ mod tests { assert_eq!(config.payload_attestation_due_bps, 7_500); } + #[test] + fn the_pq_aggregation_offsets_are_read_and_default_to_the_specification() { + let response = serde_json::json!({ + "AGGREGATION_CUTOFF_BPS": "3000", + "AGGREGATE_DUE_BPS_PQ": "5500", + "AGGREGATOR_DELAY_BPS": "400", + }); + let config = config_from_spec_response(&response).expect("builds"); + assert_eq!(config.aggregation_cutoff_bps, 3_000); + assert_eq!(config.aggregate_due_bps_pq, 5_500); + assert_eq!(config.aggregator_delay_bps, 400); + + let config = config_from_spec_response(&serde_json::json!({})).expect("builds"); + assert_eq!(config.aggregation_cutoff_bps, 4_000); + assert_eq!(config.aggregate_due_bps_pq, 6_000); + assert_eq!(config.aggregator_delay_bps, 500); + } + + #[test] + fn an_attester_dutys_aggregator_position_is_optional() { + let duty = |extra: serde_json::Value| { + let mut value = serde_json::json!({ + "pubkey": "0x00", "validator_index": "1", "committee_index": "2", + "committee_length": "3", "committees_at_slot": "4", + "validator_committee_index": "0", "slot": "5", + }); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value::(value).unwrap() + }; + assert_eq!(duty(serde_json::json!({})).aggregator_position, None); + let seated = duty(serde_json::json!({"is_aggregator": true, "aggregator_position": "2"})); + assert_eq!(seated.is_aggregator, Some(true)); + assert_eq!(seated.aggregator_position, Some(2)); + } + /// A node that has not moved to the basis-point form keeps the defaults, /// which are the right answer for every network that predates it. #[test] diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 47db70f05..8979b399a 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -635,14 +635,15 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } - /// A 404 is a node that proved nothing for this committee: no votes for it - /// reached the node, or its proof missed the deadline. Another node may - /// still hold votes, so the walk goes on past it, but when every node - /// answered 404 that is the committee's answer, which comes back as the - /// last node's [`Error::BeaconNodeStatus`] for the caller to report with - /// the node's reason, rather than as every node failing. Any other failure - /// among them still warns here, since the node that failed may have held - /// the votes. + /// A 404 is a node with nothing to publish for this committee: it holds + /// no votes for it, or (the aggregators' later seats, every slot with two + /// of them) an aggregate already broadcast covers every attester this one + /// would. Another node may still hold votes, so the walk goes on past it, + /// but when every node answered 404 that is the committee's answer, which + /// comes back as the last node's [`Error::BeaconNodeStatus`] without the + /// missed-duty warning: the specification has the aggregator publish + /// nothing then. Any other failure among them still warns, since the node + /// that failed may have held the votes. async fn pq_aggregate( &self, slot: Slot, @@ -971,9 +972,10 @@ mod tests { assert_eq!(genesis.genesis_time, 1_606_824_023); } - /// Every node having no PQ aggregate is the committee's answer, so it comes - /// back as the 404 itself; a node that failed outright among them may have - /// held the votes, which is a failure. + /// Every node having no PQ aggregate is the committee's answer (a later + /// aggregator seat whose committee is already covered), so it comes back + /// as the 404 itself; a node that failed outright among them may have held + /// the votes, which is a failure. #[tokio::test] async fn a_pq_aggregate_no_node_holds_is_the_404_not_a_failure() { let fallback = FallbackBeaconNode::new(vec![MockBeaconNode::new(), MockBeaconNode::new()]); diff --git a/crates/validator/src/duties.rs b/crates/validator/src/duties.rs index c2ff2ed61..1012b8c46 100644 --- a/crates/validator/src/duties.rs +++ b/crates/validator/src/duties.rs @@ -442,6 +442,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/head_monitor.rs b/crates/validator/src/head_monitor.rs index 3340e2a67..7e9905f4e 100644 --- a/crates/validator/src/head_monitor.rs +++ b/crates/validator/src/head_monitor.rs @@ -819,6 +819,7 @@ mod tests { validator_committee_index: 0, slot: SLOT, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index b520727a1..1938a70e7 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -1343,7 +1343,7 @@ async fn aggregate( // PQ aggregators are the aggregation committee and publish what the node // proved; see `AggregationService::aggregate_pq`. let outcome = if data.target.epoch >= aggregation.pq_fork_epoch() { - tokio::time::timeout(budget, aggregation.aggregate_pq(slot, data, duties)).await + tokio::time::timeout(budget, aggregation.aggregate_pq(clock, slot, data, duties)).await } else { tokio::time::timeout(budget, aggregation.aggregate(slot, data, duties, store)).await }; @@ -3430,6 +3430,7 @@ mod tests { validator_committee_index: 0, slot: 3200, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/slot_clock.rs b/crates/validator/src/slot_clock.rs index 4ab2bf808..ed347703e 100644 --- a/crates/validator/src/slot_clock.rs +++ b/crates/validator/src/slot_clock.rs @@ -90,6 +90,11 @@ impl SlotClock { self.config.fork_at_epoch(self.epoch_of(slot)) >= ForkName::Gloas } + /// Whether `slot` is a PQ slot. + pub fn is_pq(&self, slot: Slot) -> bool { + self.config.fork_at_epoch(self.epoch_of(slot)) >= ForkName::Pq + } + /// The slot containing `now`, or `None` before genesis. /// /// Divides in milliseconds, not seconds, so a chain whose slot is not a @@ -156,7 +161,13 @@ impl SlotClock { /// After the attester offset on every network the specification ships, /// necessarily: an aggregator folds together votes its beacon node has /// collected, and before the attesters have voted there is nothing to fold. + /// + /// At a PQ slot this is the first aggregator seat's time; a later seat + /// waits further, until [`Self::pq_aggregation_time`] for its position. pub fn aggregation_time(&self, slot: Slot) -> SystemTime { + if self.is_pq(slot) { + return self.pq_aggregation_time(slot, 0); + } let bps = if self.is_gloas(slot) { self.config.aggregate_due_bps_gloas } else { @@ -165,6 +176,17 @@ impl SlotClock { self.offset_into(slot, bps) } + /// When the PQ aggregator at `position` in its aggregation committee + /// broadcasts for `slot`: PQ's `get_aggregate_due_ms(position)`, the first + /// seat's offset plus `position` aggregator delays, each rounded down to + /// a millisecond on its own as the specification rounds them. + pub fn pq_aggregation_time(&self, slot: Slot, position: u64) -> SystemTime { + let component = |bps: u64| bps.saturating_mul(self.slot_duration_ms) / BASIS_POINTS; + let offset_ms = component(self.config.aggregate_due_bps_pq) + .saturating_add(position.saturating_mul(component(self.config.aggregator_delay_bps))); + self.start_of(slot) + Duration::from_millis(offset_ms) + } + /// When the sync committee message for `slot` is signed. /// /// The fork of `slot` picks the offset, as it does for attestations: @@ -377,6 +399,27 @@ mod tests { UNIX_EPOCH + Duration::from_secs(GENESIS + offset_secs) } + /// PQ `validator.md`'s 12-second example: the seats broadcast at 7.2, + /// 7.8, 8.4 and 9.0 s, and a PQ slot's aggregation duty wakes for the + /// first. + #[test] + fn pq_aggregators_broadcast_staggered_by_their_seat() { + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 1); + let clock = SlotClock::from_config(GENESIS, &config); + let slot = slots_per_epoch() + 2; + assert!(clock.is_pq(slot) && !clock.is_pq(slot - slots_per_epoch())); + for (position, offset_ms) in [(0, 7_200), (1, 7_800), (2, 8_400), (3, 9_000)] { + assert_eq!( + clock.pq_aggregation_time(slot, position), + clock.start_of(slot) + Duration::from_millis(offset_ms) + ); + } + assert_eq!( + clock.aggregation_time(slot), + clock.pq_aggregation_time(slot, 0) + ); + } + #[test] fn a_slot_ends_where_the_next_begins() { let clock = clock(); diff --git a/crates/validator/src/subscriptions.rs b/crates/validator/src/subscriptions.rs index 69997dcd5..68b445c29 100644 --- a/crates/validator/src/subscriptions.rs +++ b/crates/validator/src/subscriptions.rs @@ -221,6 +221,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 1e2053324..133d3bb39 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -64,7 +64,7 @@ changes. | EIP-8483 gossip | `gossip`, `ethlambda_p2p::beacon::decode` | attestations, aggregates and attester slashings decode and validate as gloas's; blocks, envelopes and columns are ignored | | Block production | `pq_block_production`, `rpc::beacon::pq_proposal` | self-build; attestations packed from validated aggregates, their proofs merged under a deadline; blobs, their columns gossiped with the envelope. Every block it built on the devnet was canonical on Lighthouse | | VRF tree | `ethlambda_crypto::vrf` | the specification's Keccak-256 tree over all `2^31` leaves, each `keccak256(vrf_seed \|\| le64(slot))`; known answers from ethereum-package's published state. Restorable from a compact state (root and leaf 0's branch), which the package publishes for its genesis validators and `ethlambda pq-keys` writes | -| Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | +| Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; aggregators staggered by seat; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | | Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead on the sidecar | | Beacon API | `rpc::beacon::{pool, pq_proposal, ptc, proposal}` | PQ attestations, aggregates (in and out), payload attestations, blocks, envelopes and `POST /eth/v1/validator/pq_blocks/{slot}`; the other endpoints refuse PQ's signed containers | @@ -423,18 +423,23 @@ asks for again. two, as `pq/p2p-interface.md` asks. - **Aggregating**: a PQ aggregator is a member of its committee's aggregation committee, which the attester duties report as - `is_aggregator`. Every aggregator broadcasts at gloas's aggregate deadline - (`AGGREGATE_DUE_BPS_GLOAS`, 6 s into a 12-second slot); `2f43bc0f` neither - staggers them nor has them skip a covered aggregate (consensus-specs' - later `4595f0fc` does both; branch `pq-devnet-0-b5d422b2` follows it). - Proving takes seconds, so the node proves ahead, as Lighthouse's PQ branch - does: the client's committee subscriptions join the committee's subnet and - register it, the node keeps the validated votes' signatures for registered - committees, and halfway between the attestation and aggregate deadlines - seals the slot and proves each committee before the aggregate deadline. - `GET aggregate_attestation` then answers the proved aggregate and its - proof, or a 404 when the node proved none, and the client signs the - `AggregateAndProof` at the slot's aggregate leaf. + `is_aggregator`, with its seat in it as `aggregator_position`. The seats + are staggered (PQ `validator.md`, "Construct aggregate"): the one at + `position` stops collecting at `get_aggregation_cutoff_ms(position)` + (`AGGREGATION_CUTOFF_BPS` plus `position` times `AGGREGATOR_DELAY_BPS`) and + broadcasts at `get_aggregate_due_ms(position)` (`AGGREGATE_DUE_BPS_PQ` plus + the same delay); on a 12-second slot that is 4.8 s and 7.2 s for the first + seat, each later one 0.6 s after. Proving takes seconds, so the node proves + ahead, as Lighthouse's PQ branch does: the client's committee subscriptions + join the committee's subnet and register it with the aggregating validator, + the node keeps the validated votes' signatures for registered committees, + and at each seat's cutoff proves what it has for the committees one of its + validators holds that seat in. The client asks for each aggregate at its + seat's broadcast time; `GET aggregate_attestation` answers the proved + aggregate and its proof, or a 404 when an aggregate already broadcast for + the committee, gossip's or this node's, covers every attester of it + (`should_broadcast_aggregate`). The client signs the `AggregateAndProof` at + the slot's aggregate leaf. ## Running a devnet From e03f41859ea166776dffdb30d5e7519d20d795fd Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:16:51 -0300 Subject: [PATCH 10/25] feat(pq): VRF leaves commit to revealed secrets, as consensus-specs pq b5d422b2 has them Reverts beb567c9 (the move back to pq-devnet-0's revealed leaves): from b5d422b2 a VRF leaf is keccak256("VRF_LEAF" || secret || le64(slot)) over the slot's secret keccak256("VRF_SECRET" || seed || le64(slot)), and the proof reveals the secret, not the leaf. leanVM bindings v0.17.0's lean_vrf, pq-devnet-1's release, follows the same rule. A VRF tree a pq-devnet-0 validator client stored is refused at load (WrongSeed: both stored formats are re-derived from the seed) and hashed again under the new rule, so an upgraded directory never proves with one. tooling/pq-devnet stays deleted (5c2fab24: ethereum-package's pq branch runs ethlambda); CLAUDE.md keeps the current text until the docs pass. --- CLAUDE.md | 3 +- .../state_transition/src/beacon/gossip/pq.rs | 2 +- .../state_transition/src/beacon/helpers/pq.rs | 11 +- .../src/beacon/stf/eip8483.rs | 2 +- .../src/beacon/stf/epoch/pq.rs | 2 +- .../state_transition/src/beacon/stf/pq.rs | 64 +++-- crates/common/crypto/src/vrf.rs | 233 +++++++++--------- crates/common/types/src/beacon/constants.rs | 3 + .../types/src/beacon/containers/eip8483.rs | 2 +- .../common/types/src/beacon/containers/pq.rs | 2 +- crates/common/types/src/beacon/fork.rs | 2 +- crates/common/types/src/beacon/preset.rs | 2 +- crates/validator/src/pq.rs | 4 +- docs/beacon_pq.md | 57 +++-- docs/spec_deviations.md | 2 +- 15 files changed, 216 insertions(+), 175 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d71b02f82..cd4e0d4e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -878,7 +878,6 @@ 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 - `2f43bc0f`, the pq-devnet-0 spec; branch `pq-devnet-0-b5d422b2` follows `b5d422b2`) 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_*`) @@ -897,7 +896,7 @@ transitions are in `ethlambda-types`, per the section above. Nothing above (`ethlambda_crypto::pq_keys`) and attests, aggregates (staggered by its seat in the aggregation committee), casts PTC votes and proposes, each signature at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all - `2^31` leaves, each `keccak256(vrf_seed || le64(slot))`) takes minutes of + `2^31` leaves, each committing to its slot's secret) takes about 100 s of every core per key, so a background thread hashes it after startup (in a rayon pool of its own: on the global one it starves every leanXMSS signature until done) and stores its upper nodes in diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index 42ba207dd..b3ab616fc 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! 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/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index 367ace3c7..c8799d55e 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! # Keys //! @@ -188,11 +188,14 @@ pub fn is_builder_bid_leaf_index(leaf_index: u64) -> bool { (start..start + constants::XMSS_BUILDER_BID_LEAVES).contains(&leaf_index) } -/// `is_valid_vrf_proof`: whether `proof` opens the leaf at index `slot` of the -/// tree under the VRF root of the validator at `validator_index`. +/// `is_valid_vrf_proof`: whether `proof` reveals the secret that the leaf at +/// index `slot` of the tree under the VRF root of the validator at +/// `validator_index` commits to. /// /// The tree is hashed with Keccak-256, not the SHA-256 of -/// `is_valid_merkle_branch`, and `proof[0]` is the leaf itself. +/// `is_valid_merkle_branch`, and its leaf is `compute_vrf_leaf` of the +/// revealed secret and the slot: the branch holds only commitments, so a +/// reveal gives away no other slot's secret. pub fn is_valid_vrf_proof( state: &BeaconState, validator_index: ValidatorIndex, diff --git a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs index 95c7cb16d..a4a363b8e 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs @@ -1,6 +1,6 @@ //! EIP-8483's block processing (consensus-specs //! `specs/_features/eip8483/beacon-chain.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! Gloas's block processing, with two more execution-layer request lists in //! the parent payload: validators and builders register post-quantum material 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 0750579b1..8f08dfba4 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! Gloas's driver without `process_sync_committee_updates` (sync committees are //! gone), with [`process_aggregation_committee_window`] and diff --git a/crates/blockchain/state_transition/src/beacon/stf/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/pq.rs index ad6f6644c..a3cda6156 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! Gloas's block processing with leanXMSS in place of BLS: //! @@ -9,7 +9,7 @@ //! (`compute_xmss_leaf_index`), a bid at any of the bid leaves; //! - attestations carry no signature: the block's `proof` covers all of them, //! checked once in [`process_stark`] after every attestation is processed; -//! - the RANDAO reveal is a VRF proof, the leaf the proposer's committed +//! - the RANDAO reveal is a VRF proof, the secret the proposer's committed //! tree holds for the slot ([`process_randao`]); //! - voluntary exits are execution-layer requests, and the body loses //! `voluntary_exits`, `sync_aggregate`, `bls_to_execution_changes` and @@ -135,8 +135,8 @@ pub fn verify_block_signature(state: &BeaconState, signed_block: &pq::SignedBeac } /// `process_randao` (modified in PQ): the reveal is the proposer's VRF proof -/// for the slot, and the leaf it reveals is mixed in. The proposer committed -/// to its leaves when it registered its VRF root, so it cannot grind the +/// for the slot, and the secret it reveals is mixed in. The proposer committed +/// to its secrets when it registered its VRF root, so it cannot grind the /// reveal and can only withhold its block, as with BLS. pub fn process_randao( state: &mut BeaconState, @@ -995,17 +995,17 @@ mod tests { ) } - /// A VRF proof for `slot` under a root it determines: the leaf and every - /// sibling chosen, the root folded up from the leaf, as - /// `is_valid_vrf_proof` folds. - fn vrf_proof_and_root(slot: Slot, leaf: Bytes32) -> (pq::VrfProof, Root) { + /// A VRF proof for `slot` under a root it determines: the secret and + /// every sibling chosen, the root folded up from the leaf committing to + /// the secret, as `is_valid_vrf_proof` folds. + fn vrf_proof_and_root(slot: Slot, secret: Bytes32) -> (pq::VrfProof, Root) { let siblings: Vec = (0..constants::VRF_TREE_DEPTH) // Distinct from any node a test folds, so no level's order is moot. .map(|level| Bytes32::repeat_byte(level as u8 + 0x40)) .collect(); let branch = siblings.iter().map(|sibling| &sibling.0); - let root = ethlambda_crypto::vrf::fold_vrf_branch(&leaf.0, branch, slot); - let mut proof = vec![leaf]; + let root = ethlambda_crypto::vrf::fold_vrf_branch(&secret.0, branch, slot); + let mut proof = vec![secret]; proof.extend(siblings); ( pq::VrfProof::try_from(proof).expect("VRF_TREE_DEPTH + 1 roots"), @@ -1026,44 +1026,50 @@ mod tests { } #[test] - fn a_valid_vrf_proof_mixes_its_leaf_in() { + fn a_valid_vrf_proof_mixes_its_secret_in() { let mut state = with_validators_at(ForkName::Pq, 64); let slot = state.slot(); let proposer = get_beacon_proposer_index(&state).unwrap(); - let leaf = Bytes32::repeat_byte(0xab); - let (proof, root) = vrf_proof_and_root(slot, leaf); + let secret = Bytes32::repeat_byte(0xab); + let (proof, root) = vrf_proof_and_root(slot, secret); set_key(&mut state, proposer, XmssPubkey::default(), root); let epoch = get_current_epoch(&state); let previous = get_randao_mix(&state, epoch); process_randao(&mut state, &proof, RandaoVerification::Verify).unwrap(); - let expected = hash(&[&previous.0[..], &leaf.0, &constants::DOMAIN_RANDAO].concat()); + let expected = hash(&[&previous.0[..], &secret.0, &constants::DOMAIN_RANDAO].concat()); assert_eq!(get_randao_mix(&state, epoch), expected); } #[test] - fn a_vrf_proof_for_another_slot_or_leaf_is_refused() { + fn a_vrf_proof_for_another_slot_or_secret_is_refused() { let mut state = with_validators_at(ForkName::Pq, 64); let slot = state.slot(); let proposer = get_beacon_proposer_index(&state).unwrap(); - // A root opening the leaf at the next slot: the same leaf and branch - // revealed at this slot fold to a different root. + // A root committing to the secret at the next slot: the same secret + // and branch revealed at this slot fold to a different root. let (proof, next_slot_root) = vrf_proof_and_root(slot + 1, Bytes32::repeat_byte(1)); set_key(&mut state, proposer, XmssPubkey::default(), next_slot_root); assert!(process_randao(&mut state.clone(), &proof, RandaoVerification::Verify).is_err()); let (_, root) = vrf_proof_and_root(slot, Bytes32::repeat_byte(1)); set_key(&mut state, proposer, XmssPubkey::default(), root); - let (wrong_leaf, _) = vrf_proof_and_root(slot, Bytes32::repeat_byte(2)); + let (wrong_secret, _) = vrf_proof_and_root(slot, Bytes32::repeat_byte(2)); assert!( - process_randao(&mut state.clone(), &wrong_leaf, RandaoVerification::Verify).is_err() + process_randao( + &mut state.clone(), + &wrong_secret, + RandaoVerification::Verify + ) + .is_err() ); // Block production's skip still mixes the reveal in, unchecked. - assert!(process_randao(&mut state, &wrong_leaf, RandaoVerification::Skip).is_ok()); + assert!(process_randao(&mut state, &wrong_secret, RandaoVerification::Skip).is_ok()); } - /// The tree is hashed with Keccak-256 (`2f43bc0f`). A proof whose root is - /// folded with SHA-256, the rule before it, is refused. + /// The tree is hashed with Keccak-256 and its leaf commits to the secret + /// and the slot. A proof whose root is folded with SHA-256 from the + /// secret itself, the rule before both changes, is refused. #[test] fn a_vrf_proof_under_the_earlier_sha256_tree_is_refused() { let mut state = with_validators_at(ForkName::Pq, 64); @@ -1085,6 +1091,20 @@ mod tests { assert!(process_randao(&mut state, &proof, RandaoVerification::Verify).is_err()); } + /// The leaf commits to the whole slot, while the branch reads only its + /// low `VRF_TREE_DEPTH` bits: a proof for `slot` does not also open + /// `slot + 2^31`, which walks the same path. + #[test] + fn a_vrf_leaf_commits_to_its_whole_slot() { + let mut state = with_validators_at(ForkName::Pq, 64); + let slot = state.slot(); + let (proof, root) = vrf_proof_and_root(slot, Bytes32::repeat_byte(0xab)); + set_key(&mut state, 0, XmssPubkey::default(), root); + assert!(is_valid_vrf_proof(&state, 0, slot, &proof).unwrap()); + let same_path = slot + (1 << constants::VRF_TREE_DEPTH); + assert!(!is_valid_vrf_proof(&state, 0, same_path, &proof).unwrap()); + } + #[test] fn the_block_signature_is_checked_at_the_slots_proposer_leaf() { let mut state = with_validators_at(ForkName::Pq, 64); diff --git a/crates/common/crypto/src/vrf.rs b/crates/common/crypto/src/vrf.rs index 9530a7335..1cdc6d8ed 100644 --- a/crates/common/crypto/src/vrf.rs +++ b/crates/common/crypto/src/vrf.rs @@ -1,32 +1,37 @@ //! The Beacon Chain PQ fork's VRF tree (consensus-specs //! `specs/_features/pq/{beacon-chain,validator}.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`, the pq-devnet-0 spec). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! XMSS signatures are not unique, so a proposer could grind a signature-based -//! RANDAO reveal. A validator instead registers as its VRF root the root of a -//! Merkle tree of depth [`VRF_TREE_DEPTH`], hashed with Keccak-256, whose leaf -//! for a slot is `keccak256(vrf_seed || le64(slot))`. Its reveal is the leaf -//! followed by the leaf's branch (a `VRFProof`). +//! RANDAO reveal. A validator instead has a secret for each slot, derived from +//! its VRF seed, and registers as its VRF root the root of a Merkle tree of +//! depth [`VRF_TREE_DEPTH`], hashed with Keccak-256, whose leaf for a slot +//! commits to that slot's secret. Its reveal is the secret followed by the +//! leaf's branch (a `VRFProof`). The branch holds only commitments, so +//! proposing at one slot reveals no other slot's secret. //! -//! The verifying half ([`fold_vrf_branch`]) is the state transition's -//! `is_valid_vrf_proof`. The deriving half ([`compute_vrf_leaf`], -//! [`compute_vrf_node`], [`VrfTree`]) is the validator's. +//! The verifying half ([`compute_vrf_leaf`], [`fold_vrf_branch`]) is the +//! state transition's `is_valid_vrf_proof`. The deriving half +//! ([`compute_vrf_secret`], [`compute_vrf_node`], [`VrfTree`]) is the +//! validator's. //! //! # Cost //! -//! A leaf hashes its index with the seed, so no two leaves are equal and -//! nothing but hashing all `2^31` of them yields the root: about two -//! Keccak-256 calls a leaf, 4.3 billion a tree. [`VrfTree::build`] runs them -//! across cores and keeps the `2^15` nodes [`SUBTREE_DEPTH`] levels above the -//! leaves (1 MiB), from which a proof rebuilds one `2^16`-leaf subtree. -//! [`VrfTree::to_bytes`] and [`VrfTree::from_bytes`] carry those nodes, so a -//! tree is hashed once per seed, not once per start. ethereum-package -//! publishes each genesis validator's root and leaf 0's branch, from which -//! [`VrfTree::from_state_record`] proves without hashing the tree. - -use ethlambda_types::beacon::constants::VRF_TREE_DEPTH; +//! A leaf commits to its index as well as its secret, so no two leaves are +//! equal and nothing but hashing all `2^31` of them yields the root: three +//! Keccak-256 calls a leaf, about 6.4 billion a tree. [`VrfTree::build`] runs +//! them across cores and keeps the `2^15` nodes [`SUBTREE_DEPTH`] levels +//! above the leaves (1 MiB), from which a proof rebuilds one `2^16`-leaf +//! subtree. [`VrfTree::to_bytes`] and [`VrfTree::from_bytes`] carry those +//! nodes, so a tree is hashed once per seed, not once per start. On an Apple +//! M4 Max's 14 cores a tree takes about 100 seconds and a proof 30 ms. + +use ethlambda_types::beacon::constants::{VRF_LEAF_DOMAIN, VRF_TREE_DEPTH}; use rayon::prelude::*; +/// The specification's `VRF_SECRET_DOMAIN` (`validator.md`). +pub const VRF_SECRET_DOMAIN: &[u8] = b"VRF_SECRET"; + /// How many levels above the leaves the nodes a [`VrfTree`] keeps are: a /// proof rebuilds one subtree of this depth, about 200,000 hashes. const SUBTREE_DEPTH: usize = 16; @@ -36,7 +41,7 @@ const SUBTREE_DEPTH: usize = 16; /// [`VrfTree::from_state_record`]. pub const STATE_RECORD_SIZE: usize = 32 + 4 + 32 * VRF_TREE_DEPTH; -/// A node of the tree, or a seed. +/// A node of the tree, a secret, or a seed. pub type Node = [u8; 32]; /// Keccak-256's rate: the bytes one permutation absorbs. @@ -44,8 +49,8 @@ const KECCAK_RATE: usize = 136; /// The specification's `keccak256`, over the concatenation of `parts`. /// -/// Every input the tree hashes (a leaf's preimage, a pair of nodes) is at -/// most 64 bytes, under one block, so this pads it into a +/// Every input the tree hashes (a secret's preimage, a leaf's, a pair of +/// nodes) is at most 64 bytes, under one block, so this pads it into a /// single block and runs the permutation once rather than going through a /// streaming hasher, which the full tree's billions of calls notice. /// @@ -79,10 +84,16 @@ fn hash_pair(left: &Node, right: &Node) -> Node { keccak256(&[left, right]) } -/// `compute_vrf_leaf`: the leaf at `index` of the VRF tree derived from -/// `vrf_seed`, `keccak256(vrf_seed || uint_to_bytes(index))`. -pub fn compute_vrf_leaf(vrf_seed: &Node, index: u64) -> Node { - keccak256(&[vrf_seed, &index.to_le_bytes()]) +/// `compute_vrf_secret`: the secret for `index` of the VRF tree derived from +/// `vrf_seed`. +pub fn compute_vrf_secret(vrf_seed: &Node, index: u64) -> Node { + keccak256(&[VRF_SECRET_DOMAIN, vrf_seed, &index.to_le_bytes()]) +} + +/// `compute_vrf_leaf`: the leaf at `index` of a VRF tree, which commits to +/// `secret`. +pub fn compute_vrf_leaf(secret: &Node, index: u64) -> Node { + keccak256(&[VRF_LEAF_DOMAIN, secret, &index.to_le_bytes()]) } /// `compute_vrf_node`: the node at `index` among the nodes `height` levels @@ -104,7 +115,7 @@ pub fn compute_vrf_node(vrf_seed: &Node, height: usize, index: u64) -> Node { let mut finished: Vec = Vec::with_capacity(height + 1); for offset in 0..1u64 << height { let leaf_index = first_leaf + offset; - let mut node = compute_vrf_leaf(vrf_seed, leaf_index); + let mut node = compute_vrf_leaf(&compute_vrf_secret(vrf_seed, leaf_index), leaf_index); // Each trailing one bit of `offset` is a level whose left sibling is // already finished. for _ in 0..offset.trailing_ones() { @@ -116,16 +127,16 @@ pub fn compute_vrf_node(vrf_seed: &Node, height: usize, index: u64) -> Node { finished.pop().expect("the last leaf folds up to the node") } -/// The root a `VRFProof` folds to at `slot`: its revealed `leaf`, hashed up -/// through `branch` (siblings bottom-up) on the side each bit of `slot` -/// gives. `is_valid_vrf_proof` is this compared with the proposer's -/// registered VRF root. +/// The root a `VRFProof` folds to at `slot`: the leaf committing to `secret` +/// at index `slot`, hashed up through `branch` (siblings bottom-up) on the +/// side each bit of `slot` gives. `is_valid_vrf_proof` is this compared with +/// the proposer's registered VRF root. pub fn fold_vrf_branch<'a>( - leaf: &Node, + secret: &Node, branch: impl IntoIterator, slot: u64, ) -> Node { - let mut value = *leaf; + let mut value = compute_vrf_leaf(secret, slot); for (height, sibling) in branch.into_iter().enumerate() { value = if (slot >> height) & 1 == 1 { hash_pair(sibling, &value) @@ -220,7 +231,7 @@ impl VrfTree { actual: 32 * branch.len(), }); } - if fold_vrf_branch(&compute_vrf_leaf(&vrf_seed, 0), &branch, 0) != root { + if fold_vrf_branch(&compute_vrf_secret(&vrf_seed, 0), &branch, 0) != root { return Err(VrfTreeError::WrongSeed); } Ok(Self { @@ -303,9 +314,9 @@ impl VrfTree { } } - /// `compute_vrf_proof`: the leaf at index `slot`, then its branch, - /// siblings bottom-up. `None` for a slot past the tree's last leaf, which - /// no proof exists for. + /// `compute_vrf_proof`: the secret for `slot`, then the branch of the leaf + /// at index `slot`, siblings bottom-up. `None` for a slot past the tree's + /// last leaf, which no proof exists for. pub fn proof(&self, slot: u64) -> Option> { if slot >> self.depth != 0 { return None; @@ -314,9 +325,9 @@ impl VrfTree { let subtree = slot >> subtree_depth; let first_leaf = subtree << subtree_depth; let mut proof = Vec::with_capacity(self.depth + 1); - proof.push(compute_vrf_leaf(&self.seed, slot)); + proof.push(compute_vrf_secret(&self.seed, slot)); let mut nodes: Vec = (first_leaf..first_leaf + (1 << subtree_depth)) - .map(|index| compute_vrf_leaf(&self.seed, index)) + .map(|index| compute_vrf_leaf(&compute_vrf_secret(&self.seed, index), index)) .collect(); reduce(&mut nodes, (slot - first_leaf) as usize, &mut proof); match &self.kept { @@ -343,7 +354,8 @@ impl VrfTree { /// What the tree keeps, then its root: everything [`Self::from_bytes`] /// needs beside the seed. A tree hashed in full keeps its nodes /// [`SUBTREE_DEPTH`] levels up (1 MiB), one restored from a compact - /// state keeps leaf 0's branch (1 KiB). + /// state keeps leaf 0's branch (1 KiB). They are commitments, so the + /// bytes reveal no secret. pub fn to_bytes(&self) -> Vec { let mut bytes = match &self.kept { Kept::Subtrees(subtree_roots) => subtree_roots.concat(), @@ -411,6 +423,7 @@ fn reduce(nodes: &mut Vec, mut index: usize, branch: &mut Vec) { #[cfg(test)] mod tests { use super::*; + use sha2::Digest as _; fn hex32(text: &str) -> Node { hex::decode(text).unwrap().try_into().unwrap() @@ -424,7 +437,7 @@ mod tests { /// The specification's `compute_vrf_node`, as it is written. fn recursive_node(vrf_seed: &Node, height: usize, index: u64) -> Node { if height == 0 { - return compute_vrf_leaf(vrf_seed, index); + return compute_vrf_leaf(&compute_vrf_secret(vrf_seed, index), index); } let left = recursive_node(vrf_seed, height - 1, 2 * index); let right = recursive_node(vrf_seed, height - 1, 2 * index + 1); @@ -473,7 +486,7 @@ mod tests { } #[test] - fn a_proof_reveals_its_slots_leaf_and_folds_to_the_root() { + fn a_proof_reveals_its_slots_secret_and_folds_to_the_root() { let seed = seed(); let depth = SUBTREE_DEPTH + 2; let tree = VrfTree::with_depth(seed, depth); @@ -482,90 +495,88 @@ mod tests { for slot in [0, 1, 5, (1 << SUBTREE_DEPTH) - 1, 1 << SUBTREE_DEPTH, last] { let proof = tree.proof(slot).unwrap(); assert_eq!(proof.len(), depth + 1); - assert_eq!(proof[0], compute_vrf_leaf(&seed, slot), "slot {slot}"); + assert_eq!(proof[0], compute_vrf_secret(&seed, slot), "slot {slot}"); assert_eq!( fold_vrf_branch(&proof[0], &proof[1..], slot), root, "slot {slot}" ); - // The branch opens this leaf only: not at the neighbouring index, - // and not another leaf at this one. + // The leaf commits to its index: the same secret and branch do not + // open the neighbouring leaf, nor does another secret this one. assert_ne!(fold_vrf_branch(&proof[0], &proof[1..], slot ^ 1), root); assert_ne!(fold_vrf_branch(&[1; 32], &proof[1..], slot), root); } assert!(tree.proof(last + 1).is_none()); } - /// Validator 0 of ethereum-package's default mnemonic: its VRF root and - /// leaf 0's branch as the package publishes them - /// (`static_files/xmss-keys/b9dec4e1daa17dfe.vrf`, record 0, from - /// eth-beacon-genesis, an independent implementation), and the VRF seed - /// its signing key derives. - const PUBLISHED_ROOT: &str = "2c8d6a710d3a22803be6490fef9c9247e30ac68793bffb7cbc151d17f8313cb0"; - const PUBLISHED_BRANCH: [&str; VRF_TREE_DEPTH] = [ - "3b553e1e307ad6190a1c81579244b4cc5ef3689bb306e406c286df6f149f3385", - "bdff49fdadccf691e8463ad83c9144bb1f1dd3be2cc65d61cb65194a11d44778", - "b3188264c7dbdfc2097fef24d373f8f0fdde3700f1c7dda868d4d1dfff3ea735", - "bc747d9befb30d217afb5ef24b2130b3939a18cbb12e8ff9cad8ea43d666f328", - "2826365c053905094470eb39f801babe15bb56dfede5d3d89c60f94bec94c6cc", - "b054a7ce37d45e7dc9574b25815b33ef9d5d02dfba2c5867c15c6ce6ce4f87e0", - "8d48edeef8615159f8e9a5c3ff7d59dc13063cb5a246dec9caf01573514257d9", - "410a426beda2a00182b63294eac078460157987ce4f7c8d16008d6a82970b278", - "c01def0ca03beffc51029b7e13f50e39169df10c82f7130d5f7b9c5e8f876d28", - "5a29cca22a1043e0724dc105e1204f0c2f1956e4d634b7fda4f124f0f3dbe7ae", - "cd69bff80485b514887c3282ba6e7411e745928f4d253a12b1cc6b658b362a87", - "f79eb3ba9c7015ff12e965a793f36930aa667af852669424018c1e652742ec76", - "7b577ddefc00fab0447df555c5d59f76e4e49656fb0f6e565969cccae4ce7dcc", - "a82515f2a8c036495e924da314d087473d1d7d4acc6a97ec767bcf16e97292f2", - "36d25a6b0464f79c531d9338e6645fb0559816f66aa3ea7616c5194cc0da924a", - "438ab193ca00bdf0e5b75855f94bb32e778fbffe85d370284b878b8835968dd6", - "1305124c8db86859bcf9110c72a2231bce1bc2bf44443032775d90d1e76b3667", - "ece380acfc342142a937a48d3ea84e3397421f3db74a9122bcea245a4fceb43e", - "a8e932e0dd6ec363635fdb0b30ea60d24cc1a861904c879e236c0e77f9efa562", - "123e8cef55f55b0dd4f3d0758fd52aa270c53d3f230393112a404216fc10743f", - "760a6fcab9db4b616b94ad3882dea4d434a849f6d1a03fa507c648d904ec641d", - "32a9196616c33e77daecac4d5fbafd131b0968899e1a440cb4f05d868a0deb7f", - "0a9cf6b998c2736cc5c5a137b335261b1ee68671345b1c9a17f208026f4146a5", - "cb310e30dc647396390e107f0ec081689d9b84c965b340b7d6949b4be00fe461", - "fc097343ba9eed74f88793de989d6f250eb852eacb7d70a76f65ffbbbde906ee", - "1d7fd2ea64087c2a054a78558ed0e578047c06c2fa033dd0cbc3c2a33b88b06e", - "44d7360b2aacc44b9c969859104c1ecfa4d8da6c410fab927969d28bf6335e38", - "d8af842dfc83814f0291c4ad67ce2b74e83cefbddf870d1a7352793d027abc6f", - "6de1e6d637d9a2965eff8b036c0a8c37dcdd85f95f4327a87821b1c10f1eefeb", - "1b4c477849c185cb826bd541d5a31d83cc5d603b8d5b5d137de2babe4535705d", - "d1ed2b30f968fa3b5daac6544cf01bb549ad0c70b50a2f56057e89dbbf4e7d72", - ]; - - fn published_seed() -> Node { - crate::pq_keys::vrf_seed(&hex32( - "0dce41fa73ae9f6bdfd51df4d422d75eee174553dba5fd450c4437e4ed3fc903", - )) + /// A proof's branch holds commitments only: no node of it is a secret of + /// the tree, in particular not the neighbouring slot's, which the leaf + /// sibling was before leaves committed to secrets. + #[test] + fn a_proof_reveals_no_other_secret() { + let seed = seed(); + let tree = VrfTree::with_depth(seed, 4); + let proof = tree.proof(6).unwrap(); + let secrets: Vec = (0..16) + .map(|index| compute_vrf_secret(&seed, index)) + .collect(); + assert!(proof[1..].iter().all(|node| !secrets.contains(node))); + assert_eq!(proof[1], compute_vrf_leaf(&secrets[7], 7)); } - /// The leaf rule, the little-endian index and the fold's order, against - /// what ethPandaOps' genesis tooling registered: the branch's lower - /// levels are this seed's nodes, and leaf 0 folds through the whole - /// branch to the published root, so the published state restores. + /// Known answers from a transcription of the specification's functions + /// over an independent Keccak-256, for the seed `00 01 .. 1f`: the domain + /// tags, the little-endian index and the order of every concatenation. #[test] - fn matches_ethereum_packages_published_state() { - let seed = published_seed(); - let branch: Vec = PUBLISHED_BRANCH.iter().map(|node| hex32(node)).collect(); - for (height, sibling) in branch.iter().enumerate().take(11) { - assert_eq!( - compute_vrf_node(&seed, height, 1), - *sibling, - "height {height}" - ); - } - let root = hex32(PUBLISHED_ROOT); + fn known_answers() { + let seed = seed(); + let secret = compute_vrf_secret(&seed, 0); assert_eq!( - fold_vrf_branch(&compute_vrf_leaf(&seed, 0), &branch, 0), - root + secret, + hex32("568e22331e25e613a84a6a86df3f442e2f7f994ccce0b746088fb737c2bc0e20") ); - let tree = VrfTree::from_compact_state(seed, root, branch).unwrap(); - let proof = tree.proof(9).unwrap(); - assert_eq!(proof[0], compute_vrf_leaf(&seed, 9)); - assert_eq!(fold_vrf_branch(&proof[0], &proof[1..], 9), root); + assert_eq!( + compute_vrf_secret(&seed, (1 << 31) - 1), + hex32("7d65715bc75677b7ae70b0e3a287a883b6424dbdc7fe12476e14a2a28e5f4a72") + ); + assert_eq!( + compute_vrf_leaf(&secret, 0), + hex32("7858a2fe40f519a1db8508fba150a5d89a2f8e6e5c784eb6b5c36728a4364af2") + ); + assert_eq!( + compute_vrf_node(&seed, 4, 5), + hex32("e216d7728aa69ed5ff228641a373039fb56c1bdda676edf8e012443af726e8c6") + ); + assert_eq!( + compute_vrf_node(&seed, 3, (1 << 28) - 1), + hex32("c70649c366c4690b4d9977254f45cef88aa2cb4f0b0a0b08e8d42a6f95a5020e") + ); + + // A depth-10 tree's proofs are the first eleven nodes of the full + // tree's `compute_vrf_proof`. SHA-256 fingerprints their bytes. + let tree = VrfTree::with_depth(seed, 10); + assert_eq!( + tree.root(), + hex32("e2fd22f54650f9bb431288d5632b94b406024a411db4fef773eacec0fae253bb") + ); + for (slot, fingerprint) in [ + ( + 0, + "53b437b21a44e9def0f0a202bf515f0182f652a758a0446318262d9d612687db", + ), + ( + 5, + "f22b4ec50f24ae2754eddd04eefd08e52d63b1c13aa863f6b9c4df064afaf9f8", + ), + ( + 1023, + "dc21b0ac18f3119cc77117d501050a2c4fa90299aa285bb5e9cd8b90bd575d07", + ), + ] { + let proof = tree.proof(slot).unwrap().concat(); + let digest: Node = sha2::Sha256::digest(proof).into(); + assert_eq!(digest, hex32(fingerprint), "slot {slot}"); + } } #[test] @@ -665,7 +676,7 @@ mod tests { let seed = seed(); let mut branch = VrfTree::with_depth(seed, SUBTREE_DEPTH).compact_state().1; branch.extend((SUBTREE_DEPTH..VRF_TREE_DEPTH).map(|height| [height as u8; 32])); - let root = fold_vrf_branch(&compute_vrf_leaf(&seed, 0), &branch, 0); + let root = fold_vrf_branch(&compute_vrf_secret(&seed, 0), &branch, 0); let tree = VrfTree::from_compact_state(seed, root, branch).unwrap(); let record = tree.to_state_record(); diff --git a/crates/common/types/src/beacon/constants.rs b/crates/common/types/src/beacon/constants.rs index 3888c5bd5..e0d1607bc 100644 --- a/crates/common/types/src/beacon/constants.rs +++ b/crates/common/types/src/beacon/constants.rs @@ -465,6 +465,9 @@ pub const XMSS_LEAVES_PER_SLOT: u64 = 1 << 3; /// The depth of the tree under a validator's VRF root: a leaf per slot. pub const VRF_TREE_DEPTH: usize = 31; +/// Prefixed to a secret and its index to derive the leaf of a VRF tree that +/// commits to the secret (`compute_vrf_leaf`). +pub const VRF_LEAF_DOMAIN: &[u8] = b"VRF_LEAF"; /// The slot leaf a beacon block (and so a proposer slashing's headers) is /// signed at. diff --git a/crates/common/types/src/beacon/containers/eip8483.rs b/crates/common/types/src/beacon/containers/eip8483.rs index 712ac2ca4..e21c6fd9a 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! 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 043bfd7a1..f71c9dc55 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 -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). //! //! The fork replaces BLS with leanXMSS. Every signed container trades its //! `BLSSignature` for an [`XmssSignature`]; [`Attestation`] loses its signature diff --git a/crates/common/types/src/beacon/fork.rs b/crates/common/types/src/beacon/fork.rs index 89c064185..9ef050167 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 -/// `2f43bc0f989f47af81df390a90bc1f78e2436323`), not mainnet upgrades: the +/// `b5d422b255db80c9bbc48f515370655ecc8bf6e5`), 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 3154c3ff0..9f382aea3 100644 --- a/crates/common/types/src/beacon/preset.rs +++ b/crates/common/types/src/beacon/preset.rs @@ -2262,7 +2262,7 @@ mod tests { /// The PQ preset's values, pinned from `presets/{mainnet,minimal}/pq.yaml`, /// `eip8483.yaml` and `eip8205.yaml` at consensus-specs' `pq` pin - /// `2f43bc0f989f47af81df390a90bc1f78e2436323`. + /// `b5d422b255db80c9bbc48f515370655ecc8bf6e5`. #[test] fn pq_pinned_values() { assert_eq!(mainnet::MAX_COMMITTEES_PER_SLOT_PQ, 16); diff --git a/crates/validator/src/pq.rs b/crates/validator/src/pq.rs index 7d0b1ca52..a28997955 100644 --- a/crates/validator/src/pq.rs +++ b/crates/validator/src/pq.rs @@ -1460,7 +1460,7 @@ mod tests { let proof = vrf_proof(&pubkey, 5).unwrap(); assert_eq!(proof.len(), 32); - assert_eq!(proof[0].0, vrf::compute_vrf_leaf(&vrf_seed, 5)); + assert_eq!(proof[0].0, vrf::compute_vrf_secret(&vrf_seed, 5)); let branch = proof[1..].iter().map(|node| &node.0); let root: [u8; 32] = bytes[bytes.len() - 32..].try_into().unwrap(); assert_eq!(vrf::fold_vrf_branch(&proof[0].0, branch, 5), root); @@ -1480,7 +1480,7 @@ mod tests { fn stand_in_state_record(vrf_seed: vrf::Node) -> Vec { let mut branch = vrf::VrfTree::with_depth(vrf_seed, 16).compact_state().1; branch.extend((16..31).map(|height| [height as u8; 32])); - let root = vrf::fold_vrf_branch(&vrf::compute_vrf_leaf(&vrf_seed, 0), &branch, 0); + let root = vrf::fold_vrf_branch(&vrf::compute_vrf_secret(&vrf_seed, 0), &branch, 0); vrf::VrfTree::from_compact_state(vrf_seed, root, branch) .unwrap() .to_state_record() diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 133d3bb39..1e95ea939 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -1,7 +1,7 @@ # The PQ fork -consensus-specs' `pq` branch (pinned here at the pq-devnet-0 spec, -`2f43bc0f989f47af81df390a90bc1f78e2436323`) specifies an emergency fork that +consensus-specs' `pq` branch (pinned here at +`b5d422b255db80c9bbc48f515370655ecc8bf6e5`) 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: @@ -265,26 +265,27 @@ previous, current and lookahead epochs. ## The VRF tree XMSS signatures are not unique, so a RANDAO reveal signed with one could be -ground. A validator instead registers as its VRF root the root of a Merkle -tree of depth `VRF_TREE_DEPTH` (31), hashed with Keccak-256, whose leaf for a -slot is `compute_vrf_leaf(vrf_seed, slot) = keccak256(vrf_seed || le64(slot))` -(consensus-specs `pq` at `2f43bc0f`, the pq-devnet-0 spec). The reveal is the -leaf followed by its branch, and `process_randao` mixes the leaf in. - -The root costs the whole tree: a leaf hashes its index, so no two leaves are -equal and no subtree can be reused, about two Keccak-256 calls for each of -`2^31` leaves (`vrf::tests::the_whole_tree_...`, `--ignored`). -ethereum-package publishes each genesis validator's root and leaf 0's branch, -which `ethlambda_crypto::vrf::tests::matches_ethereum_packages_published_state` -checks validator 0's against. +ground. A validator instead has a secret for each slot, +`compute_vrf_secret(vrf_seed, slot)`, and registers as its VRF root the root +of a Merkle tree of depth `VRF_TREE_DEPTH` (31), hashed with Keccak-256, +whose leaf for a slot is `compute_vrf_leaf(secret, slot)`: a hash of +`VRF_LEAF_DOMAIN`, the secret and the slot. The reveal is the secret followed +by the leaf's branch, and `process_randao` mixes the secret in. + +Two consequences, both deliberate in the specification: + +- **A reveal discloses only its own slot's secret.** The branch holds + commitments, never secrets. (Before `b5d422b2` the leaf was the secret + itself, so the sibling leaf in a branch was the neighbouring slot's reveal.) +- **The root costs the whole tree.** A leaf commits to its index, so no two + leaves are equal and no subtree can be reused: the root takes three + Keccak-256 calls for each of `2^31` leaves, about 100 seconds of all 14 + cores of an Apple M4 Max (`vrf::tests::the_whole_tree_...`, `--ignored`). `is_valid_vrf_proof` folds the branch itself (`vrf::fold_vrf_branch`), not -through the SHA-256 `is_valid_merkle_branch`. It reads the slot's low 31 bits -only, so a proof for `slot` also opens `slot + 2^31`, as the specification -has it. - -consensus-specs' later `b5d422b2` makes each leaf commit to a per-slot secret -and reveals the secret instead; branch `pq-devnet-0-b5d422b2` follows it. +through the SHA-256 `is_valid_merkle_branch`. The leaf commits to the whole +slot while the branch reads only its low 31 bits, so a proof for `slot` does +not open `slot + 2^31`. ## Inclusion delay @@ -358,14 +359,13 @@ it: 2. With `--vrf-state-url` (a URL or a path), the key's record in a file of precomputed states, read at its validator index: ethereum-package's `vrf_state_url` format, 1028 bytes a validator (the root, four zero - bytes, then leaf 0's branch), which ethereum-package publishes for its - genesis validators and `ethlambda pq-keys` writes. The record must fold - the key's own leaf 0 to its root, so a record of another validator's, or - of another VRF rule's, falls through to the next source. + bytes, then leaf 0's branch), which `ethlambda pq-keys` writes. The + record must fold the key's own leaf 0 to its root, so a record of another + validator's, or of another VRF rule's, falls through to the next source. A proof then hashes only the leaves below the slot's highest bit, a few milliseconds on a young chain. 3. The whole tree, hashed. It keeps the `2^15` nodes 16 levels above the - leaves (1 MiB), and a proof rebuilds one + leaves (1 MiB, commitments only, so no secret), and a proof rebuilds one `2^16`-leaf subtree, about 30 ms. The hashing runs in a rayon pool of its own, one thread short of the cores: leanXMSS signing parallelizes on rayon's global pool, which runs a job from outside it only once a @@ -548,7 +548,7 @@ 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 2f43bc0f989f47af81df390a90bc1f78e2436323 +git checkout b5d422b255db80c9bbc48f515370655ecc8bf6e5 make test reftests=true fork=eip8483 preset=minimal make test reftests=true fork=pq preset=minimal ``` @@ -589,6 +589,11 @@ generated. all known a slot earlier, so a node could merge during slot `N - 1` for a proposer it serves, where today a slow merge costs every attestation but one. +- Interop on `b5d422b2`'s VRF rule: neither ethPandaOps' genesis generator + nor Lighthouse's PQ branch uses it yet, so the published key and state + files fail `is_valid_vrf_proof`, and a network with Lighthouse cannot run. + An ethlambda-only network runs on files `ethlambda pq-keys` writes (see + `tooling/pq-devnet/README.md`). - 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 c8ad82a25..69d01633f 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 (`2f43bc0f989f47af81df390a90bc1f78e2436323`) is +consensus-specs' `pq` branch (`b5d422b255db80c9bbc48f515370655ecc8bf6e5`) 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 From 0999097266bdd8c141c4f45fc594a92332896d0b Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:22:45 -0300 Subject: [PATCH 11/25] feat(pq): X_MAX_COMMITTEE_COUNT_PER_SLOT caps PQ committees, as consensus-specs pq af898d07 has it A temporary, testing-only config key that replaces MAX_COMMITTEES_PER_SLOT_PQ in PQ's get_committee_count_per_slot, so a small devnet can put its validators into fewer, larger committees. Mainnet 16 and minimal 4, each equal to its preset's MAX_COMMITTEES_PER_SLOT_PQ, which it may not exceed. The state transition counts committees from a state alone, so the cap is selected once per process from the network's config.yaml, beside the preset (network::select_committee_cap, after select_preset), and read through config::x_max_committee_count_per_slot(). Unset, as in the spec tests, it is the preset's value, which the specification's configs equal. A value outside 1..=MAX_COMMITTEES_PER_SLOT_PQ is moved into range with a warning. A resume refuses a changed cap, since it reshuffles every PQ committee. The field rides on DB_VERSION 10 (still unreleased). --- bin/ethlambda/src/main.rs | 4 ++ bin/ethlambda/src/network/built_in.rs | 1 + bin/ethlambda/src/network/dir.rs | 1 + bin/ethlambda/src/network/mod.rs | 20 ++++++ .../src/beacon/helpers/accessors.rs | 6 +- crates/common/types/src/beacon/config.rs | 72 ++++++++++++++++++- 6 files changed, 101 insertions(+), 3 deletions(-) diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 66c738ed8..46b22a3a2 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -2105,6 +2105,9 @@ fn first_config_difference( max_per_epoch_activation_exit_churn_limit: _, churn_limit_quotient_gloas: _, max_per_epoch_activation_churn_limit_gloas: _, + // Compared below: PQ's committee cap decides every PQ committee, so + // which attestations and aggregates a block may carry. + x_max_committee_count_per_slot: _, // Fork choice: weighting/timing knobs a node applies to its own view // of the chain. They change which head a node *prefers*, not which @@ -2256,6 +2259,7 @@ fn first_config_difference( max_per_epoch_activation_exit_churn_limit, churn_limit_quotient_gloas, max_per_epoch_activation_churn_limit_gloas, + x_max_committee_count_per_slot, consolidation_churn_limit_quotient, max_blobs_per_block_deneb, max_blobs_per_block_electra, diff --git a/bin/ethlambda/src/network/built_in.rs b/bin/ethlambda/src/network/built_in.rs index 5e9dcad23..cc4b3cd90 100644 --- a/bin/ethlambda/src/network/built_in.rs +++ b/bin/ethlambda/src/network/built_in.rs @@ -72,6 +72,7 @@ impl BuiltInNetwork { .wrap_err_with(|| format!("the built-in {} config.yaml did not parse", self.name()))?; super::select_preset(parsed.config.preset_base.as_str())?; super::check_constants(&parsed.config)?; + super::select_committee_cap(&parsed.config); // A built-in config can carry a fork whose keys this build does not // even claim (heze), which the ignored-keys warning below says. A fork // whose keys it claims but whose rules it does not follow is diff --git a/bin/ethlambda/src/network/dir.rs b/bin/ethlambda/src/network/dir.rs index 7bbe82aaa..e53ece90d 100644 --- a/bin/ethlambda/src/network/dir.rs +++ b/bin/ethlambda/src/network/dir.rs @@ -97,6 +97,7 @@ impl NetworkDir { path: config_path.clone(), source, })?; + super::select_committee_cap(&parsed.config); let genesis_path = base.join(GENESIS_STATE_FILE); let genesis_bytes = read_required_bytes(&genesis_path)?; diff --git a/bin/ethlambda/src/network/mod.rs b/bin/ethlambda/src/network/mod.rs index 5f9426157..916045fd9 100644 --- a/bin/ethlambda/src/network/mod.rs +++ b/bin/ethlambda/src/network/mod.rs @@ -107,6 +107,26 @@ pub(crate) fn select_preset(declared: &str) -> Result Ok(preset) } +/// Makes the network's `X_MAX_COMMITTEE_COUNT_PER_SLOT` the cap every PQ +/// committee count of this process uses (consensus-specs pq `af898d07`). +/// After [`select_preset`], whose `MAX_COMMITTEES_PER_SLOT_PQ` bounds it: a +/// value above that, or zero, is moved into range with a warning rather than +/// refused, since the key is a testing knob and `CommitteeBits` could not +/// hold more committees anyway. +pub(crate) fn select_committee_cap(config: &Config) { + let declared = config.x_max_committee_count_per_slot; + let cap = ethlambda_types::beacon::config::select_x_max_committee_count_per_slot(config); + if cap != declared { + tracing::warn!( + declared, + used = cap, + max_committees_per_slot_pq = + ethlambda_types::beacon::preset::max_committees_per_slot_pq(), + "X_MAX_COMMITTEE_COUNT_PER_SLOT is outside 1..=MAX_COMMITTEES_PER_SLOT_PQ; using the nearest value" + ); + } +} + /// One `config.yaml` key that the node runs on a compile-time constant for, /// set to another value. #[derive(Debug)] diff --git a/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs index 7749dd19e..d11f8431c 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs @@ -142,7 +142,9 @@ pub fn committee_count_per_slot(active_count: u64) -> u64 { } /// The most committees a slot of `fork` has: `MAX_COMMITTEES_PER_SLOT`, or -/// the PQ fork's `MAX_COMMITTEES_PER_SLOT_PQ`. +/// the PQ fork's `X_MAX_COMMITTEE_COUNT_PER_SLOT` (consensus-specs pq +/// `af898d07`; at most `MAX_COMMITTEES_PER_SLOT_PQ`, and equal to it unless a +/// devnet lowers it). /// /// The PQ fork's cap applies to every epoch a PQ state is asked about, /// including a previous epoch that ran before the fork: the specification's @@ -150,7 +152,7 @@ pub fn committee_count_per_slot(active_count: u64) -> u64 { /// are recomputed under the new cap. pub fn max_committees_per_slot(fork: ForkName) -> u64 { if fork == ForkName::Pq { - preset::max_committees_per_slot_pq() as u64 + ethlambda_types::beacon::config::x_max_committee_count_per_slot() } else { preset::max_committees_per_slot() as u64 } diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index af8795b97..be4e25e40 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -52,7 +52,7 @@ use libssz_types::SszList; use crate::beacon::constants; use crate::beacon::fork::ForkName; use crate::beacon::lean_fork_unreachable; -use crate::beacon::preset::Preset; +use crate::beacon::preset::{self, Preset}; use crate::beacon::primitives::{Epoch, ExecutionBlockHash, Gwei, U256, Uint256, Version}; use crate::chain_config::ChainConfig; use crate::constants::INTERVALS_PER_SLOT; @@ -508,6 +508,15 @@ pub struct Config { /// builder-registry value; see [`Self::churn_limit_quotient_gloas`]. #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub max_per_epoch_activation_churn_limit_gloas: Gwei, + /// PQ (consensus-specs pq `af898d07`): the most committees a PQ slot has, + /// `MAX_COMMITTEES_PER_SLOT_PQ` replaced in `get_committee_count_per_slot`. + /// Temporary and testing-only: a devnet lowers it to put its validators + /// into fewer, larger committees. It may not exceed the preset's + /// `MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`; the + /// state transition reads it through + /// [`x_max_committee_count_per_slot`], which the node sets from this. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub x_max_committee_count_per_slot: u64, // -- Fork choice --------------------------------------------------------- /// Percentage boost, relative to a single committee's weight, given to a @@ -678,6 +687,45 @@ pub struct Config { /// configuration for a missing key, and a network that predates a field should /// still load. Mainnet is the right fallback because every other network is /// described as a deviation from it. +/// The PQ committee cap this process runs on, `0` until +/// [`select_x_max_committee_count_per_slot`] sets one. +static X_MAX_COMMITTEE_COUNT_PER_SLOT: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + +/// Makes `config`'s `X_MAX_COMMITTEE_COUNT_PER_SLOT` the cap every PQ +/// committee count of this process uses, and returns it. +/// +/// One per process, like the preset (see `beacon::preset`): the state +/// transition reads it from a state alone, which carries no config. A value +/// above the preset's `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification +/// forbids and `CommitteeBits` cannot hold, is lowered to it, and a zero is +/// raised to one; the caller warns when the returned value differs from the +/// file's. +pub fn select_x_max_committee_count_per_slot(config: &Config) -> u64 { + let cap = committee_cap_within_preset( + config.x_max_committee_count_per_slot, + preset::max_committees_per_slot_pq() as u64, + ); + X_MAX_COMMITTEE_COUNT_PER_SLOT.store(cap, std::sync::atomic::Ordering::Relaxed); + cap +} + +/// `declared` moved into `1..=max_committees_per_slot_pq`. +fn committee_cap_within_preset(declared: u64, max_committees_per_slot_pq: u64) -> u64 { + declared.clamp(1, max_committees_per_slot_pq) +} + +/// `X_MAX_COMMITTEE_COUNT_PER_SLOT` as selected for this process, or the +/// preset's `MAX_COMMITTEES_PER_SLOT_PQ` when none was: the specification's +/// own configs set the two equal, so a process that never selects one (a +/// spec test, a lean node) runs on the specification's value. +pub fn x_max_committee_count_per_slot() -> u64 { + match X_MAX_COMMITTEE_COUNT_PER_SLOT.load(std::sync::atomic::Ordering::Relaxed) { + 0 => preset::max_committees_per_slot_pq() as u64, + cap => cap, + } +} + impl Default for Config { fn default() -> Self { Self::mainnet() @@ -807,6 +855,7 @@ impl Config { max_per_epoch_activation_exit_churn_limit: 256_000_000_000, churn_limit_quotient_gloas: 32_768, max_per_epoch_activation_churn_limit_gloas: 256_000_000_000, + x_max_committee_count_per_slot: 16, proposer_score_boost: 40, reorg_head_weight_threshold: 20, @@ -950,6 +999,7 @@ impl Config { max_per_epoch_activation_exit_churn_limit: 128_000_000_000, churn_limit_quotient_gloas: 16, max_per_epoch_activation_churn_limit_gloas: 128_000_000_000, + x_max_committee_count_per_slot: 4, proposer_score_boost: 40, reorg_head_weight_threshold: 20, @@ -1329,6 +1379,26 @@ mod tests { assert_eq!(config.max_request_payloads, 128); } + #[test] + fn the_pq_committee_cap_is_claimed_and_parses() { + assert_eq!(Config::mainnet().x_max_committee_count_per_slot, 16); + assert_eq!(Config::minimal().x_max_committee_count_per_slot, 4); + let config: Config = + serde_yaml_ng::from_str("X_MAX_COMMITTEE_COUNT_PER_SLOT: 1\n").unwrap(); + assert_eq!(config.x_max_committee_count_per_slot, 1); + // Absent, it is mainnet's, like every other key a file omits. + let config: Config = serde_yaml_ng::from_str("CONFIG_NAME: x\n").unwrap(); + assert_eq!(config.x_max_committee_count_per_slot, 16); + } + + #[test] + fn the_pq_committee_cap_stays_within_committee_bits() { + assert_eq!(committee_cap_within_preset(4, 16), 4); + assert_eq!(committee_cap_within_preset(16, 16), 16); + assert_eq!(committee_cap_within_preset(16, 4), 4); + assert_eq!(committee_cap_within_preset(0, 16), 1); + } + #[test] fn pq_timing_keys_are_claimed_and_parse() { let yaml = "UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY: 8\n\ From 9fa5f2a1e6d2dfa8cd56328f2bf9723a89da2344 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:22:45 -0300 Subject: [PATCH 12/25] feat(pq): legacy XMSS keys and VRF roots are keccak256, as consensus-specs pq 4c296784 has them compute_legacy_xmss_pubkey and compute_legacy_vrf_root hash the BLS key and domain byte with keccak256, the VRF tree's hash, rather than sha256; the RANDAO mix and aggregation committee seeds stay on sha256. The fork upgrade gives these to every validator and builder that registered no PQ key, and a deposit for a new one looks its key up by them. ethlambda_crypto::keccak256 wraps sha3's Keccak256; a test checks it against the VRF tree's single-block permutation and the empty-input digest, and another that the legacy keys are no longer the sha256 ones. --- .../state_transition/src/beacon/helpers/pq.rs | 29 ++++++++++++++++++- crates/common/crypto/src/lib.rs | 12 ++++++-- crates/common/crypto/src/vrf.rs | 19 ++++++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) diff --git a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index c8799d55e..464848323 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs @@ -121,11 +121,15 @@ pub fn compute_legacy_vrf_root(pubkey: &BlsPubkey) -> Root { legacy_digest(pubkey, constants::LEGACY_VRF_ROOT_DOMAIN) } +/// `keccak256(pubkey + domain)`. SHA-256 before consensus-specs pq +/// `4c296784`, which moved both legacy derivations to the hash the VRF tree +/// already uses; the RANDAO mix and the aggregation committee seeds stay on +/// SHA-256. fn legacy_digest(pubkey: &BlsPubkey, domain: u8) -> Bytes32 { let mut input = Vec::with_capacity(pubkey.0.len() + 1); input.extend_from_slice(&pubkey.0); input.push(domain); - hash(&input) + ethlambda_types::primitives::H256(ethlambda_crypto::keccak256(&input)) } /// `is_legacy_pubkey`: whether a 48-byte request key names a BLS key (made @@ -599,6 +603,29 @@ mod tests { ); } + /// consensus-specs pq `4c296784`: `keccak256(pubkey + domain)`, the + /// domain one byte, not `sha256`. + #[test] + fn legacy_keys_are_keccak256_of_the_bls_key_and_domain() { + let bls = BlsPubkey([0xa5; 48]); + let digest = |domain: u8| { + let mut input = bls.0.to_vec(); + input.push(domain); + ethlambda_crypto::keccak256(&input) + }; + assert_eq!( + compute_legacy_xmss_pubkey(&bls).0, + digest(constants::LEGACY_XMSS_PUBKEY_DOMAIN) + ); + assert_eq!( + compute_legacy_vrf_root(&bls).0, + digest(constants::LEGACY_VRF_ROOT_DOMAIN) + ); + let mut sha_input = bls.0.to_vec(); + sha_input.push(constants::LEGACY_XMSS_PUBKEY_DOMAIN); + assert_ne!(compute_legacy_xmss_pubkey(&bls).0, hash(&sha_input).0); + } + /// A PQ state at `slot` whose block root at each earlier slot is /// `roots[slot]`: a skipped slot repeats the root before it. fn pq_state_with_roots(slot: Slot, roots: &[u8]) -> BeaconState { diff --git a/crates/common/crypto/src/lib.rs b/crates/common/crypto/src/lib.rs index f25c7def1..5bf70f883 100644 --- a/crates/common/crypto/src/lib.rs +++ b/crates/common/crypto/src/lib.rs @@ -48,7 +48,7 @@ pub mod bls; /// The Beacon Chain PQ fork's leanXMSS signatures (the specification's `xmss` /// module), over Keccak-256. Not the XMSS of [`signature`]. pub mod lean_xmss; -/// leanVM's own leanXMSS (bindings v0.15.0): what a validator signs with and +/// leanVM's own leanXMSS (bindings v0.17.0): what a validator signs with and /// what [`lean_xmss::verify`] runs, re-exported so a signer depends on one pin. pub use leanvm_lean_xmss; mod metrics; @@ -57,7 +57,8 @@ mod metrics; pub mod pq_keys; pub mod signature; /// The Beacon Chain PQ fork's proofs of many leanXMSS signatures (the -/// specification's `stark` module), in its reference concatenation encoding. +/// specification's `stark` module): its reference concatenation encoding, or +/// leanVM proofs made in process. pub mod stark; /// The Beacon Chain PQ fork's VRF tree, whose openings are its RANDAO /// reveals: verification for the state transition, derivation for a @@ -67,6 +68,13 @@ pub mod vrf; #[cfg(feature = "shadow-integration")] pub mod shadow_cost; +/// The Beacon Chain PQ fork's `keccak256` (Ethereum's Keccak-256, with +/// Keccak's original padding, not SHA3-256's), over `data`. +pub fn keccak256(data: &[u8]) -> [u8; 32] { + use sha3::{Digest as _, Keccak256}; + Keccak256::digest(data).into() +} + /// log(1/rate) for the WHIR commitment scheme used inside the aggregation prover. const LOG_INV_RATE: usize = 2; diff --git a/crates/common/crypto/src/vrf.rs b/crates/common/crypto/src/vrf.rs index 1cdc6d8ed..ef355150f 100644 --- a/crates/common/crypto/src/vrf.rs +++ b/crates/common/crypto/src/vrf.rs @@ -423,6 +423,25 @@ fn reduce(nodes: &mut Vec, mut index: usize, branch: &mut Vec) { #[cfg(test)] mod tests { use super::*; + + /// The single-block permutation here and the streaming hasher behind + /// [`crate::keccak256`] agree, and both are Keccak-256 (the empty input's + /// digest), not SHA3-256. + #[test] + fn keccak256_is_keccak_and_agrees_with_the_streaming_hasher() { + assert_eq!( + hex::encode(keccak256(&[])), + "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" + ); + for len in [0usize, 1, 49, 64, 135] { + let input: Vec = (0..len as u8).collect(); + assert_eq!( + keccak256(&[&input]), + crate::keccak256(&input), + "{len} bytes" + ); + } + } use sha2::Digest as _; fn hex32(text: &str) -> Node { From b8d430bc2ea204871ad14a4e6ffed804f371a95c Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 16:25:29 -0300 Subject: [PATCH 13/25] docs(pq): pq-devnet-1, consensus-specs pq at 4c296784 and leanVM bindings v0.17.0 The spec pin moves from b5d422b2 to 4c296784 in every module doc, the preset test and the docs (no preset changed in between; 9bd63ad0 and 32919f0f only wrap and reformat the xmss/stark calls). docs/beacon_pq.md describes in-process proving and what became of the sidecar and its supervisor, the committee cap, the keccak256 legacy keys, and running pq-devnet-1; cli.md swaps --pq-prover-socket for --pq-prover-threads; metrics.md loses prover_unreachable; CLAUDE.md follows, DB_VERSION 10 included. --- CLAUDE.md | 46 ++--- .../state_transition/src/beacon/gossip/pq.rs | 2 +- .../state_transition/src/beacon/helpers/pq.rs | 2 +- .../src/beacon/stf/eip8483.rs | 2 +- .../src/beacon/stf/epoch/pq.rs | 2 +- .../state_transition/src/beacon/stf/pq.rs | 2 +- crates/common/crypto/src/vrf.rs | 2 +- .../types/src/beacon/containers/eip8483.rs | 2 +- .../common/types/src/beacon/containers/pq.rs | 2 +- crates/common/types/src/beacon/fork.rs | 2 +- crates/common/types/src/beacon/preset.rs | 2 +- docs/beacon_pq.md | 169 +++++++++--------- docs/cli.md | 2 +- docs/metrics.md | 4 +- docs/spec_deviations.md | 12 +- 15 files changed, 132 insertions(+), 121 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index cd4e0d4e4..282493e10 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -300,18 +300,19 @@ actual_slot = finalized_slot + 1 + relative_index signatures, a port of leanVM `4af2cddd`'s Rust implementation pinned by consensus-specs' and leanVM's known answers), and proves many signatures at once through `ethlambda_crypto::stark`: the specification's reference (the - signatures concatenated) by default, or real leanVM proofs from a - `leanvm-sidecar` process (leanVM `c5ee9d239`, bindings v0.15.0, the - release pq-devnet-0 runs for its signer, prover, verifier and sidecar), - which is what the PQ devnet runs. The node only connects to a sidecar - (`--pq-prover-socket`); as for Lighthouse, something else starts it: the - image's `ethlambda-pq` supervisor (`bin/ethlambda/pq/`), run as - `ethlambda-pq beacon `. The image builds `leanvm-sidecar` from the - revision in the root `leanvm-revision` file (or `--build-arg LEANVM_REV`), - so which prover a devnet runs is chosen outside the node; the node's client - only refuses a sidecar with another protocol version or verifier tag. - The two encodings do not verify each other's proofs. Never pass one - scheme's key to the other + signatures concatenated), or real leanVM proofs made in process + (`stark::leanvm`, leanVM `1e997c99`, bindings v0.17.0, the one release + pq-devnet-1 runs for signer, prover and verifier; `lean_vm` with its + experimental prover, `cpu_tiers` off). `run_node` installs leanVM as soon + as `--network` resolves to a network that schedules PQ, on + `--pq-prover-threads` threads (0: one per core); the reference is then + only what the spec tests run. v0.17.0 removed pq-devnet-0's + `leanvm-sidecar`, so the image builds none, and `ethlambda-pq` + (`bin/ethlambda/pq/`) is now a shim that execs `ethlambda`, kept for + launchers that still call it. A proof from another leanVM revision does not + verify, and nothing on the wire says why; the root `leanvm-revision` file + names the pin. The two encodings do not verify each other's proofs. Never + pass one scheme's key to the other - Wire sizes: `PUBLIC_KEY_SIZE` (`common/types/src/state.rs`) and `SIGNATURE_SIZE` (`common/types/src/attestation.rs`), static-asserted against leanVM's scheme constants in `common/crypto/src/signature.rs` @@ -878,7 +879,9 @@ 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 - `b5d422b2`) are `ForkName::Eip8483` and `ForkName::Pq` after gloas, selectors + `4c296784`, pq-devnet-1's spec: staggered aggregators of `4595f0fc`, VRF + secrets of `b5d422b2`, `X_MAX_COMMITTEE_COUNT_PER_SLOT` of `af898d07`, + keccak256 legacy keys of `4c296784`) 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 @@ -914,8 +917,8 @@ transitions are in `ethlambda-types`, per the section above. Nothing above client survives a restart. The beacon node builds PQ blocks through `POST /eth/v1/validator/pq_blocks/{slot}` (`rpc/src/beacon/pq_proposal.rs`, `pq_block_production.rs`), packing attestations from the validated - aggregates in `Store::pq_aggregate_pool` with their proofs merged on the - sidecar under a deadline (one unmerged attestation when it misses), and + aggregates in `Store::pq_aggregate_pool` with their proofs merged by + leanVM under a deadline (one unmerged attestation when it misses), and proves its aggregators' committees ahead (`rpc/src/beacon/pq_aggregation.rs`, `Store::pq_signature_pool`). Blobs travel as in gloas: the node keeps the blobs of the payload it built and the envelope endpoint publishes their @@ -1221,11 +1224,14 @@ behavior. in-memory map stays as a write-through cache in front of the table. Pruned on finalization to the same horizon as `LiveChain` (the finalized block's own slot, keeping that block's own entry). -- `DB_VERSION` is 8: `Config` gained the EIP-8483 and PQ fork versions and - epochs, `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, PQ's aggregation - timing (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, - `AGGREGATOR_DELAY_BPS`) and `ATTESTATION_SUBNET_COUNT_PQ`, so a version 7 - directory's stored config decodes into the wrong fields. (7 moved `States` +- `DB_VERSION` is 10 (pq-devnet-1): `Config` has PQ's aggregation timing + (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`) + again and `X_MAX_COMMITTEE_COUNT_PER_SLOT`, so a pq-devnet-0 (version 9, + without the timing keys) directory's stored config decodes into the wrong + fields. (9 dropped the timing keys for pq-devnet-0's `2f43bc0f`; 8 gave + `Config` the EIP-8483 and PQ fork versions and epochs, + `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, the timing keys and + `ATTESTATION_SUBNET_COUNT_PQ`; 7 moved `States` and `StateDiffs` from root keys to slot||root keys, the block's slot looked up from `BlockHeaders` by readers, so `Store::prune_finalized_states` can range-delete finalized states; 6 was diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index b3ab616fc..968d64fb3 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! 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/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index 464848323..af6f25a23 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! # Keys //! diff --git a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs index a4a363b8e..f4a9bcf7b 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs @@ -1,6 +1,6 @@ //! EIP-8483's block processing (consensus-specs //! `specs/_features/eip8483/beacon-chain.md`, on the `pq` branch at -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's block processing, with two more execution-layer request lists in //! the parent payload: validators and builders register post-quantum material 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 8f08dfba4..d49eb9696 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's driver without `process_sync_committee_updates` (sync committees are //! gone), with [`process_aggregation_committee_window`] and diff --git a/crates/blockchain/state_transition/src/beacon/stf/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/pq.rs index a3cda6156..6172b444f 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's block processing with leanXMSS in place of BLS: //! diff --git a/crates/common/crypto/src/vrf.rs b/crates/common/crypto/src/vrf.rs index ef355150f..feed42a8f 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! 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/containers/eip8483.rs b/crates/common/types/src/beacon/containers/eip8483.rs index e21c6fd9a..e3b078801 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! 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 f71c9dc55..d787013d2 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 -//! `b5d422b255db80c9bbc48f515370655ecc8bf6e5`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! The fork replaces BLS with leanXMSS. Every signed container trades its //! `BLSSignature` for an [`XmssSignature`]; [`Attestation`] loses its signature diff --git a/crates/common/types/src/beacon/fork.rs b/crates/common/types/src/beacon/fork.rs index 9ef050167..0fc4160c7 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 -/// `b5d422b255db80c9bbc48f515370655ecc8bf6e5`), not mainnet upgrades: the +/// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`), 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 9f382aea3..3a4668d35 100644 --- a/crates/common/types/src/beacon/preset.rs +++ b/crates/common/types/src/beacon/preset.rs @@ -2262,7 +2262,7 @@ mod tests { /// The PQ preset's values, pinned from `presets/{mainnet,minimal}/pq.yaml`, /// `eip8483.yaml` and `eip8205.yaml` at consensus-specs' `pq` pin - /// `b5d422b255db80c9bbc48f515370655ecc8bf6e5`. + /// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`. #[test] fn pq_pinned_values() { assert_eq!(mainnet::MAX_COMMITTEES_PER_SLOT_PQ, 16); diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 1e95ea939..9094a1e8e 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -1,7 +1,7 @@ # The PQ fork consensus-specs' `pq` branch (pinned here at -`b5d422b255db80c9bbc48f515370655ecc8bf6e5`) specifies an emergency fork that +`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`, pq-devnet-1'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: @@ -14,7 +14,11 @@ against a quantum adversary. It comes as two feature forks after gloas: 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). + preregistrations (EIP-8205). 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 + before `4c296784`). Both are `ForkName`s (`Eip8483`, `Pq`), between `Gloas` and `Lean`, on-disk selectors 8 and 9. Neither is scheduled on a public network. **The node @@ -50,7 +54,7 @@ changes. | Layer | Where | Status | | --- | --- | --- | | leanXMSS sign/verify | `ethlambda_crypto::lean_xmss` | KAT-pinned against consensus-specs and leanVM | -| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs through a running `leanvm-sidecar` (`--pq-prover-socket`), which the image's `ethlambda-pq` supervisor starts (see [Proofs](#proofs)) | +| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs made in process (bindings v0.17.0) on a network that schedules PQ (see [Proofs](#proofs)) | | Containers | `ethlambda_types::beacon::containers::{eip8483, pq}` | SSZ round trips, gaps per the spec; the maximal aggregate, attester slashing and bid encode to `pq.yaml`'s size bounds | | Fork upgrades | `upgrade::{upgrade_to_eip8483, upgrade_to_pq}` | unit-tested | | Block processing | `stf::{eip8483, pq}` | unit-tested with real XMSS keys | @@ -65,7 +69,7 @@ changes. | Block production | `pq_block_production`, `rpc::beacon::pq_proposal` | self-build; attestations packed from validated aggregates, their proofs merged under a deadline; blobs, their columns gossiped with the envelope. Every block it built on the devnet was canonical on Lighthouse | | VRF tree | `ethlambda_crypto::vrf` | the specification's Keccak-256 tree over all `2^31` leaves, each `keccak256(vrf_seed \|\| le64(slot))`; known answers from ethereum-package's published state. Restorable from a compact state (root and leaf 0's branch), which the package publishes for its genesis validators and `ethlambda pq-keys` writes | | Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; aggregators staggered by seat; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | -| Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead on the sidecar | +| Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead with leanVM, seat by seat | | Beacon API | `rpc::beacon::{pool, pq_proposal, ptc, proposal}` | PQ attestations, aggregates (in and out), payload attestations, blocks, envelopes and `POST /eth/v1/validator/pq_blocks/{slot}`; the other endpoints refuse PQ's signed containers | ## Gossip @@ -139,57 +143,45 @@ over a few leaves only, for tests. `ethlambda_crypto::stark` proves, merges and verifies the fork's attestation proofs through one of two backends, chosen once per process: -- **Reference** (the default): the specification's stand-in for a recursive - STARK. A proof is the signatures concatenated in statement order, and - verification checks each, plus the exact length. It is capped by - `MAX_STARK_PROOF_SIZE` (1 MiB), about 436 signatures per block. The - specification's fixtures use it. -- **Sidecar** (`--pq-prover-socket`, `stark::install_sidecar`): real leanVM - proofs, made and checked by a `leanvm-sidecar` process over a Unix socket, - through leanVM's own client crate at `c5ee9d239` (bindings v0.15.0, - `sidecar::LEANVM_REV`), the release pq-devnet-0 runs for its signer, - prover, verifier and sidecar. A statement list maps to leanVM - claims as Lighthouse maps it: the sorted, deduplicated - `(public key, message)` pairs, the empty proof for no claims, and merges - folded sixteen children at a time. -- **Who starts the sidecar**: not the node, as for Lighthouse. The image's - `ethlambda-pq` supervisor (`bin/ethlambda/pq/ethlambda-pq`, Lighthouse's - `lighthouse-pq-bn` adapted) starts it on a private socket, waits for it to - listen, and runs `ethlambda --pq-prover-socket `. The node - exiting stops the sidecar. The sidecar exiting does not stop the node - (Lighthouse's script stops it): the sidecar is started again on the same - socket after a pause (one second, doubling to 32 while it keeps dying - within a minute), and the node's client reconnects on its next request. - Until then the node proves nothing, gossip aggregates it cannot verify are - IGNOREd (`prover_unreachable`) rather than held against their senders, and - a block whose proof it could not check fails import and is fetched again - later (there is no bad-block cache). The gap is the sidecar's warm-up, not - the pause: on the local devnet, a sidecar on 2 threads killed mid-run - served again 50 s later (12 s at the container's start, on an idle - machine). Its node's head stood still meanwhile, so the two blocks it - proposed were built on a stale head and orphaned, and it imported the - block it had missed 8 s after the sidecar came back. After - `LEANVM_MAX_RESTARTS` (10) quick exits in a row the supervisor stops the - node too. `LEANVM_THREADS` sets the - sidecar's proving threads, `LEANVM_SIDECAR` another executable. The image - builds `leanvm-sidecar` from the commit in the root `leanvm-revision` file, - or from - `--build-arg LEANVM_REV` (the publish workflow's `leanvm_rev` input), and - records the commit at `/usr/local/share/ethlambda/leanvm-revision`. The - node's client refuses a sidecar whose hello names another protocol version - or verifier tag; any other revision is accepted, and its proofs only have - to verify with the other clients' verifiers (Teku's v0.16.0 sidecar and - ethlambda's v0.15.0 one verified each other's on the interop devnet). A - verifier-tag change needs `sidecar::LEANVM_REV` and the client crates - moved with it. +- **Reference**: the specification's stand-in for a recursive STARK. A proof + is the signatures concatenated in statement order, and verification checks + each, plus the exact length. It is capped by `MAX_STARK_PROOF_SIZE` (1 MiB), + about 436 signatures per block. The specification's fixtures use it, and so + does any process that never installs leanVM. +- **leanVM** (`stark::install_leanvm`, `stark::leanvm`): real leanVM proofs, + made and checked in this process by `lean_vm` at `1e997c99` (bindings + v0.17.0, `leanvm::LEANVM_REV`), the one release pq-devnet-1 runs for its + signer, prover and verifier. A statement list maps to leanVM claims as + Lighthouse maps it: the sorted, deduplicated `(public key, message)` pairs, + the empty proof for no claims, and merges folded sixteen children + (`MAX_RECURSIONS`) at a time. The node installs it itself, as soon as + `--network` resolves to a network that schedules PQ, after + `lean_vm::setup` starts the prover's pool (`--pq-prover-threads`, 0 for + one thread per core) and builds its aggregation program. leanVM proves one + proof at a time per process; verifying does not wait for a proof. + It builds with leanVM's experimental prover (the one pq-devnet-0's + sidecar ran; the same proofs as the stable one, faster). leanVM's + `cpu_tiers` stays off: it needs leanVM's `scripts/tier-rustc` as the + rustc wrapper, and the node's own CPU baseline (`.cargo/config.toml`) + already gives the prover its carryless multiply. + +pq-devnet-0 ran the prover as a separate `leanvm-sidecar` (bindings v0.15.0), +which the image built and its `ethlambda-pq` supervisor started and +restarted; while it restarted, gossip aggregates were IGNOREd +(`prover_unreachable`). v0.17.0 removed the sidecar and its client API, so +the image builds none, nothing can be unreachable, and `ethlambda-pq` is a +shim that execs `ethlambda` (`LEANVM_THREADS` becomes `--pq-prover-threads`) +for launchers that still call it. A proof from another leanVM revision does +not verify, and nothing on the wire says why: the root `leanvm-revision` +file names the pin, and the image records it at +`/usr/local/share/ethlambda/leanvm-revision`. The encodings are not interchangeable, so every node of a network must use -the same backend; the PQ devnet's Lighthouse accepts only the sidecar. A -leanVM proof does not attest the leaf a signature was made at, so the sidecar -backend checks that each key signed the message at *some* leaf -(`docs/spec_deviations.md`). Lighthouse's blocks replay through ethlambda's -state transition with every proof verified this way, state root for state -root. +the same backend; the PQ devnet runs leanVM. A leanVM proof does not attest +the leaf a signature was made at, so the leanVM backend checks that each key +signed the message at *some* leaf (`docs/spec_deviations.md`). On +pq-devnet-0, Lighthouse's blocks replayed through ethlambda's state +transition with every proof verified this way, state root for state root. ### Leaves @@ -251,9 +243,18 @@ fork too, and those are not applied to any fork yet, the PQ forks included. See ## Committees -The PQ fork caps a slot's committees at `MAX_COMMITTEES_PER_SLOT_PQ` (16 on -mainnet, 4 on minimal), for every epoch a PQ state is asked about, including a -previous epoch that ran before the fork. The committee cache's `ShufflingKey` +The PQ fork caps a slot's committees at `X_MAX_COMMITTEE_COUNT_PER_SLOT` (16 +on mainnet, 4 on minimal), for every epoch a PQ state is asked about, +including a previous epoch that ran before the fork. The key is a temporary, +testing-only config value (`af898d07`): a devnet lowers it to put its +validators into fewer, larger committees. It may not exceed the preset's +`MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`. The state +transition counts committees from a state alone, so the node selects the cap +once per process from the network's `config.yaml`, beside the preset +(`network::select_committee_cap`); a value out of range is moved into it +with a warning, a process that selects none (the spec tests) runs on the +preset's value, which the specification's own configs equal, and a resume +refuses a changed cap. The committee cache's `ShufflingKey` carries the cap, since a state either side of the fork names the same epoch and deciding block but a different shuffling. @@ -405,7 +406,7 @@ asks for again. the payload, and meanwhile packs attestations: it picks, from the aggregates it validated, what `process_attestation` accepts at the slot and credits someone new, as `compute_on_chain_aggregate` shapes them, and merges - their proofs in `process_stark`'s order on the sidecar. A merge must end + their proofs in `process_stark`'s order with leanVM. A merge must end three quarters of the way to the attestation deadline (Lighthouse's bound). One child needs no merge; when more do not finish in time, the block packs the most valuable single-committee attestation alone, whose proof is the @@ -444,12 +445,14 @@ 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 (its -`.github/tests/cl-pq.yaml` names every client's `pq-devnet-0` image; the -pq-devnet-0 notes, `notes.ethereum.org/@ethpandaops/pq-devnet-0`, pin the -rest). Build the image from the repository root (`docker build -t -ethlambda:pq-local .`: it ships `leanvm-sidecar`, built from the commit in -`leanvm-revision`, and the `ethlambda-pq` supervisor), then `kurtosis run +ethlambda as beacon node, validator client or both. This branch targets +pq-devnet-1 (`notes.ethereum.org/@ethpandaops/pq-devnet-1`): consensus-specs +`pq` at `4c296784` and leanVM bindings v0.17.0, which every client must run, +since proofs from another revision do not verify. 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 +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 example, ethlambda next to Teku and Lodestar, and Silver's beacon node behind ethlambda's validator client (Silver has no client of its own): @@ -460,8 +463,8 @@ participants: el_image: ethpandaops/geth:glamsterdam-devnet-8 cl_type: ethlambda cl_image: ethlambda:pq-local - cl_extra_env_vars: - LEANVM_THREADS: "2" + cl_extra_params: + - --pq-prover-threads=2 vc_type: ethlambda vc_image: ethlambda:pq-local validator_count: 16 @@ -498,17 +501,21 @@ package runs `ethereum/client-go:latest`. What the package does for ethlambda on a PQ network: -- It runs the beacon node as `ethlambda-pq beacon `: the supervisor - starts the sidecar on a private socket, waits for it to listen, and runs - the node on it, restarting the sidecar if it exits (see [Proofs](#proofs)). - `LEANVM_THREADS` (through `cl_extra_env_vars`) caps the sidecar's threads. +- It runs the beacon node as `ethlambda-pq beacon `, pq-devnet-0's + sidecar supervisor, which is now a shim that execs `ethlambda` (see + [Proofs](#proofs)); `LEANVM_THREADS`, if set, becomes + `--pq-prover-threads`. - It passes the validator client `--init-slashing-protection` and, for its default mnemonic, the leanXMSS tree caches and VRF tree states it publishes for that mnemonic's first 10000 validators (`--xmss-cache-url`, `--vrf-state-url`). The client refuses a flag given twice, so `vc_extra_params` must not repeat them. - Its genesis generator gives each validator the leanXMSS key and VRF seed - the validator client derives from the BLS key. For another mnemonic, or + the validator client derives from the BLS key. pq-devnet-1's VRF rule is + `b5d422b2`'s (leaves commit to revealed secrets), and its legacy keys are + keccak256 (`4c296784`): tree states and keys published for pq-devnet-0's + rule fail their check against the seed, and the validator client then + hashes the tree itself (minutes a key) rather than use them. For another mnemonic, or past the published 10000, `ethlambda pq-keys --mnemonic ... --count N --output-dir keys` writes the key file the generator reads (`xmss_pubkey_url`) and the VRF states (`vrf_state_url`); every root @@ -520,10 +527,10 @@ Limits worth knowing: asserts every slot has an attester, so with fewer, epoch processing fails at the first epoch boundary (`compute_balance_weighted_selection: total > 0`) and the chain stops. The specification does the same. -- **Memory.** Every `leanvm-sidecar` warms up by proving twice and stays - large. In Docker Desktop's default 8 GB VM a second sidecar next to - Lighthouse's has had the kernel kill Lighthouse's. Set `LEANVM_THREADS` on - nodes that only verify. +- **Memory.** leanVM's prover keeps the pages of its largest proof resident + for the life of the process (its jemalloc never decays dirty pages), now + inside the node rather than in a sidecar. On Docker Desktop's default 8 GB + VM, give a node that only verifies fewer `--pq-prover-threads`. - **Lighthouse's envelopes over req/resp.** Its `pq-devnet-0` image (last checked at `sha256:f571048f`) answered `execution_payload_envelopes_by_{range,root}` with a gloas-shaped envelope @@ -533,7 +540,7 @@ Limits worth knowing: What shows interop working: the beacon APIs agree on the head and finality; ethlambda's `lean_beacon_gossip_validation_total` is all `accept` (blocks, -envelopes, aggregates with their proofs checked through the sidecar, +envelopes, aggregates with their proofs checked by leanVM, attestations, payload attestations, proposer preferences); `lean_beacon_aggregate_total{outcome="applied"}` rises; every envelope is `VALID` (`Execution payload envelope verified ... status=Valid`); every block @@ -548,7 +555,7 @@ 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 b5d422b255db80c9bbc48f515370655ecc8bf6e5 +git checkout 4c296784bb6ff54cbdcf72ebdda2a1057cce8893 make test reftests=true fork=eip8483 preset=minimal make test reftests=true fork=pq preset=minimal ``` @@ -589,11 +596,11 @@ generated. all known a slot earlier, so a node could merge during slot `N - 1` for a proposer it serves, where today a slow merge costs every attestation but one. -- Interop on `b5d422b2`'s VRF rule: neither ethPandaOps' genesis generator - nor Lighthouse's PQ branch uses it yet, so the published key and state - files fail `is_valid_vrf_proof`, and a network with Lighthouse cannot run. - An ethlambda-only network runs on files `ethlambda pq-keys` writes (see - `tooling/pq-devnet/README.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. - 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/cli.md b/docs/cli.md index eaad50d01..9f640c6ac 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -165,7 +165,7 @@ something specific here. |---|---|---| | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | -| `--pq-prover-socket` | none | The Unix socket of a running `leanvm-sidecar`, which makes and checks the PQ fork's attestation proofs as leanVM STARKs, the encoding the PQ devnet's clients use. The node refuses a sidecar whose protocol version or verifier tag differs from its client's (leanVM `c5ee9d239`, bindings v0.15.0). Without it the node uses the specification's reference encoding (the signatures concatenated), which only another node on the reference accepts. Read only on a network scheduling PQ. The image's `ethlambda-pq` supervisor (`bin/ethlambda/pq/`, as Lighthouse's `lighthouse-pq-bn`) starts a sidecar and passes this flag: `ethlambda-pq beacon `, with `LEANVM_THREADS` for its proving threads (0, the default: one per core) and `LEANVM_SIDECAR` for another executable than the image's `leanvm-sidecar` | +| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.17.0 (`1e997c99`, the release pq-devnet-1 runs; a proof from another revision does not verify). The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, diff --git a/docs/metrics.md b/docs/metrics.md index e5ae3164c..502be902c 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -450,9 +450,7 @@ The two topics add reasons the others do not, all `reason` label values on `lean_beacon_gossip_validation_total`: `outside_epoch_window`, `covered_bits` (aggregate only), `unknown_block`, `state_unavailable`, `finalized_not_ancestor`, `ancestry_unknown`, `payload_envelope_unseen` and -`payload_optimistic` (gloas only), and `prover_unreachable` (PQ aggregate -only: the prover sidecar did not answer, so the proof was not judged) on the -ignore side; +`payload_optimistic` (gloas only) on the ignore side; `epoch_mismatch`, `no_participants` (aggregate only), `non_zero_data_index`, `committee_bits` (aggregate only), `committee_index`, `bits_length` (aggregate only), `not_aggregator` (aggregate only), `not_in_committee`, diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index 69d01633f..38515fec7 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 (`b5d422b255db80c9bbc48f515370655ecc8bf6e5`) is +consensus-specs' `pq` branch (`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`) 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 @@ -1125,15 +1125,15 @@ Two more: The specification's `stark.VerifyAggregates` checks each signature at its statement's leaf index, and its reference implementation does (a proof is the signatures concatenated). The PQ devnet's clients prove with leanVM -instead, through a `leanvm-sidecar` (`--pq-prover-socket`, -`ethlambda_crypto::stark::sidecar`), and a leanVM proof attests only +instead, in process from bindings v0.17.0 (`ethlambda_crypto::stark::leanvm`, +installed on any network that schedules PQ), and a leanVM proof attests only `(public key, message)` claims (leanEthereum/leanVM#787). So under the -sidecar backend a proof shows each key signed the message at *some* leaf, +leanVM backend a proof shows each key signed the message at *some* leaf, not at the statement's. Proving still refuses a signature made at another leaf, since it sees the signatures, which is Lighthouse's behavior too. The two encodings are not interchangeable: a node verifies only the backend it -runs, so a network picks one, and the reference stays the default for the -specification's fixtures. +runs, so a network picks one, and the reference stays what the +specification's fixtures run. ## The genesis block's body carries the state's bid from gloas on From 7a9d431888b8f571e30a45e4b9606bab564ecd2f Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:27 -0300 Subject: [PATCH 14/25] fix(pq): catch leanVM panics, check the prover at startup, test it in CI leanVM now runs in the node's own process, on the threads that import blocks and judge gossip, where pq-devnet-0's sidecar could crash on an input and be restarted. Every call into it goes through guarded(), which turns a panic into a proof that does not verify, or one that was not made, instead of an unwind through the chain actor. LeanVmBackend::setup now ends with a self-check: one throwaway signature proved and verified, and checked not to verify against another claim. A prover that cannot run on the machine is reported at startup, not at the first aggregation duty. measure() proves the same input several rounds over, for pq-prover-check. More prover threads than cores are lowered to the cores with a warning rather than oversubscribed. Tests: garbage and truncated bytes in a proof's place verify against nothing; a signature at another leaf than its statement's is refused; the leanVM pin is the same in the constant, the manifest and leanvm-revision. The end-to-end prover test stays ignored for a plain cargo test (minutes unoptimized) and make test-consensus, so CI, runs it by name. --- Makefile | 3 + crates/common/crypto/src/stark.rs | 7 +- crates/common/crypto/src/stark/leanvm.rs | 292 +++++++++++++++++++++-- 3 files changed, 277 insertions(+), 25 deletions(-) diff --git a/Makefile b/Makefile index 80430d0a7..c8fe497bc 100644 --- a/Makefile +++ b/Makefile @@ -41,6 +41,9 @@ test: test-consensus test-node ## 🧪 Run all tests test-consensus: leanSpec/fixtures ## 🧪 Run the consensus half of the workspace suite $(TEST) $(addprefix -p ,$(CONSENSUS_CRATES)) + # The PQ fork's leanVM prover, end to end: ignored by a plain `cargo test`, + # which spends minutes on it unoptimized. A second or two here. + $(TEST) -p ethlambda-crypto --lib -- --ignored leanvm_proofs_merge_and_verify test-node: leanSpec/fixtures slashing-protection-interchange-tests ## 🧪 Run the node half of the workspace suite $(TEST) --workspace $(addprefix --exclude ,$(CONSENSUS_CRATES)) diff --git a/crates/common/crypto/src/stark.rs b/crates/common/crypto/src/stark.rs index f1d09c5b1..2e1b7690c 100644 --- a/crates/common/crypto/src/stark.rs +++ b/crates/common/crypto/src/stark.rs @@ -40,9 +40,10 @@ fn backend() -> &'static Backend { } /// Makes every proof of this process a leanVM proof, made and checked in -/// process, after starting leanVM's prover pool (seconds). Call once, at -/// startup, before anything proves or verifies: whichever backend is first -/// used stays for the life of the process. +/// process, after starting leanVM's prover pool and passing its self-check +/// (about a second). Call once, at startup, before anything proves or +/// verifies: whichever backend is first used stays for the life of the +/// process. pub fn install_leanvm(config: leanvm::LeanVmConfig) -> Result<(), leanvm::Error> { if BACKEND.get().is_some() { return Err(leanvm::Error::AlreadyInstalled); diff --git a/crates/common/crypto/src/stark/leanvm.rs b/crates/common/crypto/src/stark/leanvm.rs index d0b202005..af85cc2ba 100644 --- a/crates/common/crypto/src/stark/leanvm.rs +++ b/crates/common/crypto/src/stark/leanvm.rs @@ -26,9 +26,14 @@ //! //! leanVM runs one proof at a time per process ("a second waits for the //! first"), on a thread pool of its own that [`LeanVmBackend::setup`] starts. -//! Verification does not wait for a proof in progress. +//! Verification takes no lock and runs on the calling thread, so it does not +//! wait for a proof in progress. +//! +//! Every call into leanVM goes through [`guarded`], which catches a panic +//! inside it: see there for why that matters more in process than it did +//! behind a socket. -use std::time::Instant; +use std::time::{Duration, Instant}; use leanvm_claims::{AggregateClaims, OutputClaims}; use leanvm_lean_xmss::{LeanXmssPublicKey, LeanXmssSignature}; @@ -58,6 +63,50 @@ pub enum Error { UndecodableChild(usize), #[error("log_inv_rate {0} is outside leanVM's {min}..={max}", min = leanvm_prover::MIN_LOG_INV_RATE, max = leanvm_prover::MAX_LOG_INV_RATE)] LogInvRate(u8), + #[error("leanVM panicked in {call}: {reason}")] + Panicked { call: &'static str, reason: String }, + #[error("leanVM failed its self-check: {0}")] + SelfCheck(String), +} + +/// Runs one call into leanVM, catching a panic inside it. +/// +/// pq-devnet-0 ran leanVM in a sidecar, where an input that crashed it cost +/// a restart of that process. In process, the caller is the thread importing +/// a block or judging gossip, and the proof bytes come from peers: a panic +/// must fail the one proof, not unwind through the chain actor. Verification +/// shares no lock with proving, so it goes on whatever a panic left behind; +/// proving may not (leanVM's signer cache does not tolerate a poisoned lock), +/// and then every later proof fails here the same way, loudly. +fn guarded(call: &'static str, run: impl FnOnce() -> T) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).map_err(|panic| { + let reason = panic + .downcast_ref::<&str>() + .map(|reason| (*reason).to_string()) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_else(|| "no message".to_string()); + tracing::error!(call, %reason, "leanVM panicked"); + Error::Panicked { call, reason } + }) +} + +/// The seed of the throwaway key [`LeanVmBackend::self_check`] signs with. +/// Public, so the key protects nothing, and the rule that a seed backs one +/// key only ([`lean_xmss::range_key`]) costs it nothing: the check builds it +/// over as many leaves as it is asked to prove. +const SELF_CHECK_SEED: [u8; 32] = *b"ethlambda leanVM self-check key."; + +/// The most signatures [`LeanVmBackend::self_check`] proves at once: twice the +/// largest committee, and within the throwaway key's first bottom tree. +pub const MAX_SELF_CHECK_SIGNATURES: u32 = 4096; + +/// What [`LeanVmBackend::self_check`] measured. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SelfCheck { + pub signatures: usize, + pub prove: Duration, + pub verify: Duration, + pub proof_bytes: usize, } impl From for ProveError { @@ -93,22 +142,95 @@ pub struct LeanVmBackend { impl LeanVmBackend { /// Starts leanVM's prover pool and builds its aggregation program, which - /// verifying needs too. Takes seconds; call once, at startup. + /// verifying needs too, then proves and verifies one signature + /// ([`Self::self_check`]): a prover that cannot run on this machine is + /// reported here, at startup, rather than at the first aggregation duty. + /// Takes about a second; call once. + /// + /// More threads than the machine has cores are lowered to the cores, + /// with a warning: leanVM would oversubscribe them. pub fn setup(config: LeanVmConfig) -> Result { let rate = usize::from(config.log_inv_rate); if !(leanvm_prover::MIN_LOG_INV_RATE..=leanvm_prover::MAX_LOG_INV_RATE).contains(&rate) { return Err(Error::LogInvRate(config.log_inv_rate)); } + let cores = std::thread::available_parallelism().map_or(1, usize::from); + let threads = threads_within(config.threads, cores); + if threads != config.threads { + tracing::warn!( + asked = config.threads, + cores, + "More leanVM prover threads than cores; using one per core" + ); + } let started = Instant::now(); - leanvm_prover::setup(config.threads); + guarded("setup", || leanvm_prover::setup(threads))?; + let backend = Self { log_inv_rate: rate }; + let setup_ms = started.elapsed().as_millis() as u64; + let check = backend.self_check(1)?; tracing::info!( - threads = config.threads, + threads, log_inv_rate = config.log_inv_rate, leanvm_rev = LEANVM_REV, - elapsed_ms = started.elapsed().as_millis() as u64, + setup_ms, + self_check_prove_ms = check.prove.as_millis() as u64, + self_check_verify_ms = check.verify.as_millis() as u64, "leanVM prover ready, in process" ); - Ok(Self { log_inv_rate: rate }) + Ok(backend) + } + + /// Proves `signatures` leanXMSS signatures of a throwaway key, each over + /// its own message at its own leaf, and checks that the proof verifies + /// against those claims and against no others. The times are the prover's + /// and the verifier's alone, without the signing. + /// + /// As many claims as a committee of `signatures` attesters gives, so the + /// proving time is what one seat's aggregate of that size costs here. + pub fn self_check(&self, signatures: usize) -> Result { + let input = self_check_input(signatures)?; + self.prove_and_verify(input.statements, &input.signatures) + } + + /// [`Self::self_check`] `rounds` times over one input, signed once: what + /// proving costs on this machine round after round, the first paying for + /// whatever the prover sets up on first use. + pub fn measure(&self, signatures: usize, rounds: usize) -> Result, Error> { + let input = self_check_input(signatures)?; + (0..rounds) + .map(|_| self.prove_and_verify(input.statements.clone(), &input.signatures)) + .collect() + } + + fn prove_and_verify( + &self, + mut statements: Vec, + signed: &[Vec>], + ) -> Result { + let started = Instant::now(); + let proof = self + .prove(&statements, signed) + .map_err(|err| Error::SelfCheck(format!("proving: {err}")))?; + let prove = started.elapsed(); + let started = Instant::now(); + if !self.verify(&statements, &proof) { + return Err(Error::SelfCheck("the proof it made does not verify".into())); + } + let verify = started.elapsed(); + // And against nothing else: a verifier that accepts every proof is + // worse than one that accepts none. + statements[0].message[31] ^= 1; + if self.verify(&statements, &proof) { + return Err(Error::SelfCheck( + "the proof verifies against a claim it does not prove".into(), + )); + } + Ok(SelfCheck { + signatures: statements.len(), + prove, + verify, + proof_bytes: proof.len(), + }) } pub(super) fn prove>( @@ -168,7 +290,7 @@ impl LeanVmBackend { match (claims.lean_xmss.is_empty(), proof.as_ref().is_empty()) { (true, true) => {} (false, false) => { - let proof = AggregateProof::from_bytes(proof.as_ref()) + let proof = guarded("decode", || AggregateProof::from_bytes(proof.as_ref()))? .ok_or(Error::UndecodableChild(index))?; level.push((claims, proof)); } @@ -201,7 +323,12 @@ impl LeanVmBackend { if claims.lean_xmss.is_empty() || proof.is_empty() { return claims.lean_xmss.is_empty() && proof.is_empty(); } - AggregateProof::from_bytes(proof).is_some_and(|proof| proof.verify(&claims)) + // A panic reads as a proof that does not verify: the bytes are a + // peer's, and whatever they did to the verifier, they proved nothing. + guarded("verify", || { + AggregateProof::from_bytes(proof).is_some_and(|proof| proof.verify(&claims)) + }) + .unwrap_or(false) } /// One aggregate. Checks leanVM proved exactly `expected`. @@ -213,14 +340,16 @@ impl LeanVmBackend { ) -> Result { let started = Instant::now(); let signatures = raw_signatures.len(); - let (claims, proof) = leanvm_prover::aggregate( - children, - raw_signatures, - Vec::new(), - None, - OutputClaims::All, - self.log_inv_rate, - ) + let (claims, proof) = guarded("aggregate", || { + leanvm_prover::aggregate( + children, + raw_signatures, + Vec::new(), + None, + OutputClaims::All, + self.log_inv_rate, + ) + })? .map_err(|err| Error::LeanVm(err.to_string()))?; if claims != *expected { return Err(Error::ClaimsMismatch { @@ -239,6 +368,65 @@ impl LeanVmBackend { } } +/// What [`LeanVmBackend::self_check`] proves: statements of one public key +/// each, and each statement's one signature, in the same order. +struct SelfCheckInput { + statements: Vec, + signatures: Vec>>, +} + +/// `signatures` statements of one signature each, by one throwaway key over +/// its first leaves, with their signatures as [`LeanVmBackend::prove`] takes +/// them. +/// +/// One key rather than one per signature: a claim is a `(public key, +/// message)` pair, so the prover's work is the same, and a key's leaves share +/// a bottom tree that is built once. Its signatures are then independent and +/// made in parallel; the tree is built first, since a signature that had to +/// build it would do so with rayon from inside a rayon task. +fn self_check_input(signatures: usize) -> Result { + use rayon::prelude::*; + let count = u32::try_from(signatures) + .ok() + .filter(|count| (1..=MAX_SELF_CHECK_SIGNATURES).contains(count)) + .ok_or_else(|| { + Error::SelfCheck(format!( + "cannot prove {signatures} signatures: 1 to {MAX_SELF_CHECK_SIGNATURES}" + )) + })?; + let key = lean_xmss::range_key(&SELF_CHECK_SEED, 0, count - 1); + key.prepare(0) + .map_err(|err| Error::SelfCheck(format!("building the key: {err}")))?; + let pubkey = key.public_key().to_bytes(); + let signed: Vec<(AggregateStatement, Vec>)> = (0..count) + .into_par_iter() + .map(|leaf| { + let mut message: Message = [0x5c; 32]; + message[..4].copy_from_slice(&leaf.to_le_bytes()); + let signature = key + .sign(&message, leaf) + .map_err(|err| Error::SelfCheck(format!("signing: {err}")))?; + let statement = AggregateStatement { + pubkeys: vec![pubkey], + leaf_index: u64::from(leaf), + message, + }; + Ok((statement, vec![signature.to_bytes()])) + }) + .collect::>()?; + let (statements, signatures) = signed.into_iter().unzip(); + Ok(SelfCheckInput { + statements, + signatures, + }) +} + +/// `asked` prover threads on a machine of `cores`: 0 (one per core) as it is, +/// and never more than the cores. +fn threads_within(asked: usize, cores: usize) -> usize { + asked.min(cores) +} + /// The claims a proof of `statements` attests: every `(pubkey, message)` /// pair, strictly sorted by its bytes, without duplicates. No leanSPHINCS /// claims and no DA commitment. @@ -348,15 +536,58 @@ mod tests { )); } - /// End to end on leanVM itself: two committees' proofs, merged, verify - /// against their concatenated statements and nothing else. Seconds of - /// proving, so ignored by default; `cargo test -p ethlambda-crypto - /// --profile release-fast -- --ignored leanvm` runs it. #[test] - #[ignore = "proves with leanVM: seconds per proof"] + fn a_panic_inside_leanvm_is_an_error_not_an_unwind() { + let caught = guarded("test", || -> u8 { panic!("boom {}", 7) }); + assert!(matches!( + caught, + Err(Error::Panicked { call: "test", reason }) if reason == "boom 7" + )); + assert_eq!(guarded("test", || 3).unwrap(), 3); + } + + #[test] + fn prover_threads_never_exceed_the_cores() { + assert_eq!(threads_within(0, 8), 0); + assert_eq!(threads_within(2, 8), 2); + assert_eq!(threads_within(8, 8), 8); + assert_eq!(threads_within(64, 8), 8); + } + + /// The places that name the leanVM revision agree: this module's + /// constant, the workspace manifest's three `rev`s, and the root + /// `leanvm-revision` file, which the image build reads. + #[test] + fn the_leanvm_pin_is_the_same_everywhere() { + let file = include_str!("../../../../../leanvm-revision").trim(); + assert_eq!(file, LEANVM_REV, "leanvm-revision"); + let manifest = include_str!("../../../../../Cargo.toml"); + for package in ["lean_vm", "claims", "lean_xmss"] { + let named = format!("package = \"{package}\""); + let line = manifest + .lines() + .find(|line| line.contains(&named)) + .unwrap_or_else(|| panic!("no {package} dependency in the workspace manifest")); + assert!(line.contains(&format!("rev = \"{LEANVM_REV}\"")), "{line}"); + } + } + + /// End to end on leanVM itself: `setup` proves and verifies its + /// self-check, then two committees' proofs, merged, verify against their + /// concatenated statements and nothing else, and bytes that are no proof + /// verify against nothing. + /// + /// Ignored by a plain `cargo test`, which spends minutes on it + /// unoptimized; `make test-consensus`, and so CI, runs it by name under + /// `release-fast`, where it takes a second or two. + #[test] + #[ignore = "minutes unoptimized: `make test-consensus` runs it by name"] fn leanvm_proofs_merge_and_verify() { use crate::lean_xmss::range_key; let backend = LeanVmBackend::setup(LeanVmConfig::default()).unwrap(); + let check = backend.self_check(4).unwrap(); + assert_eq!(check.signatures, 4); + assert!(check.proof_bytes > 0); let signed = |seed: u8, leaf: u32, message: &Message| { let key = range_key(&[seed; 32], leaf, leaf); let signature = key.sign(message, leaf).unwrap().to_bytes(); @@ -379,5 +610,22 @@ mod tests { assert!(backend.verify(&both, &merged)); assert!(!backend.verify(&first, &merged)); assert!(!backend.verify(&both, &merged[..merged.len() - 1])); + // What a peer can send in a proof's place. + assert!(!backend.verify(&both, &[0xff; 64])); + assert!(!backend.verify(&both, &u64::MAX.to_le_bytes())); + let mut flipped = merged.clone(); + *flipped.last_mut().unwrap() ^= 1; + assert!(!backend.verify(&both, &flipped)); + // A signature made at another leaf than the statement's is refused + // before leanVM sees it, since the proof would not attest the leaf. + let wrong_leaf = [statement(&[c], 42, m2)]; + assert!(matches!( + backend.prove(&wrong_leaf, &[vec![&sig_c]]), + Err(ProveError::LeafIndex { + expected: 42, + found: 41, + .. + }) + )); } } From 16a1951520daec61851d7f9f1471f792f131e9f9 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:44 -0300 Subject: [PATCH 15/25] feat(pq): ethlambda pq-prover-check, what leanVM's prover does on this host A seat has the window from its cutoff to its broadcast to prove in, 2.4 s of a 12-second slot, and leanVM makes one proof at a time. Whether a host keeps up depends on its cores and on which CPU instructions the build uses, which nothing showed before a devnet's first aggregation duty. The command starts the prover as the node does, proves and verifies an aggregate of --signatures claims --rounds times, and reports each round against that window. No network, no data directory. --- bin/ethlambda/src/command.rs | 6 ++ bin/ethlambda/src/main.rs | 6 ++ bin/ethlambda/src/pq_prover_check.rs | 119 +++++++++++++++++++++++++++ 3 files changed, 131 insertions(+) create mode 100644 bin/ethlambda/src/pq_prover_check.rs diff --git a/bin/ethlambda/src/command.rs b/bin/ethlambda/src/command.rs index c72109a90..8a26c4447 100644 --- a/bin/ethlambda/src/command.rs +++ b/bin/ethlambda/src/command.rs @@ -34,6 +34,7 @@ const EXPLICIT: &[&str] = &[ SLASHING_PROTECTION, KEYGEN, PQ_KEYS, + PQ_PROVER_CHECK, "help", "-h", "--help", @@ -50,6 +51,7 @@ const VOLUNTARY_EXIT: &str = "voluntary-exit"; const SLASHING_PROTECTION: &str = "slashing-protection"; const KEYGEN: &str = "keygen"; const PQ_KEYS: &str = "pq-keys"; +const PQ_PROVER_CHECK: &str = "pq-prover-check"; #[derive(Debug, clap::Parser)] #[command( @@ -103,6 +105,9 @@ pub(crate) enum Command { /// Write a Beacon Chain PQ-fork genesis's leanXMSS keys and VRF roots for /// a mnemonic's validators, in ethPandaOps' genesis tooling's file formats. PqKeys(crate::pq_keys::PqKeysOptions), + /// Prove and verify a PQ-fork aggregate with leanVM on this machine, and + /// report what it took against an aggregator seat's proving window. + PqProverCheck(crate::pq_prover_check::PqProverCheckOptions), } /// Parse the process arguments, exiting the way clap does on a parse error, @@ -473,6 +478,7 @@ mod tests { SLASHING_PROTECTION, KEYGEN, PQ_KEYS, + PQ_PROVER_CHECK, ] { let args = [OsString::from("ethlambda"), OsString::from(token)]; assert_eq!( diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 46b22a3a2..eb0d56012 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -9,6 +9,7 @@ mod fd_limit; mod keygen; mod network; mod pq_keys; +mod pq_prover_check; mod shutdown; mod slashing_protection; mod validator; @@ -138,6 +139,11 @@ fn main() -> eyre::Result<()> { init_info_stderr_logging()?; pq_keys::run(options) } + // Seconds of every core, for a report on stderr: as keygen. + Command::PqProverCheck(options) => { + init_info_stderr_logging()?; + pq_prover_check::run(options) + } } } diff --git a/bin/ethlambda/src/pq_prover_check.rs b/bin/ethlambda/src/pq_prover_check.rs new file mode 100644 index 000000000..165bcad05 --- /dev/null +++ b/bin/ethlambda/src/pq_prover_check.rs @@ -0,0 +1,119 @@ +//! What leanVM's prover does on this machine (`ethlambda pq-prover-check`). +//! +//! On a network that schedules the PQ fork, the node proves each of its +//! aggregators' committees between that seat's cutoff and its broadcast: the +//! difference of `AGGREGATE_DUE_BPS_PQ` and `AGGREGATION_CUTOFF_BPS`, 2.4 s of +//! a 12-second slot. leanVM makes one proof at a time, so a proof that does +//! not fit is an aggregate that is never broadcast. How long one takes +//! depends on the host: its cores, and which instructions its CPU has that +//! the build can use. +//! +//! This starts the prover as the node does, proves and verifies an aggregate +//! of as many signatures as asked, a few times over, and reports what each +//! round took against that budget. It touches no network and no data +//! directory, so it answers before a devnet's genesis rather than at its +//! first aggregation duty. + +use std::time::Duration; + +use ethlambda_crypto::stark::leanvm::{ + LEANVM_REV, LeanVmBackend, LeanVmConfig, MAX_SELF_CHECK_SIGNATURES, +}; +use ethlambda_types::beacon::config::Config; +use eyre::WrapErr as _; +use tracing::{info, warn}; + +#[derive(Debug, clap::Args)] +pub(crate) struct PqProverCheckOptions { + /// How many signatures one aggregate proves: the attesters of one + /// committee. + #[arg( + long, + default_value_t = 128, + value_parser = clap::value_parser!(u32).range(1..=i64::from(MAX_SELF_CHECK_SIGNATURES)) + )] + signatures: u32, + + /// How many threads leanVM's prover runs on, 0 for one per core: the + /// node's `--pq-prover-threads`. + #[arg(long, default_value_t = 0)] + threads: usize, + + /// How many times to prove. The first round pays for whatever the prover + /// sets up on first use. + #[arg(long, default_value_t = 3, value_parser = clap::value_parser!(u32).range(1..))] + rounds: u32, +} + +pub(crate) fn run(options: PqProverCheckOptions) -> eyre::Result<()> { + let config = LeanVmConfig { + threads: options.threads, + ..LeanVmConfig::default() + }; + let backend = LeanVmBackend::setup(config).wrap_err("cannot start leanVM's prover")?; + let signatures = options.signatures as usize; + let rounds = backend + .measure(signatures, options.rounds as usize) + .wrap_err("leanVM's prover failed")?; + + let budget = seat_budget(&Config::mainnet()); + for (round, check) in rounds.iter().enumerate() { + info!( + round = round + 1, + signatures, + prove_ms = check.prove.as_millis() as u64, + verify_ms = check.verify.as_millis() as u64, + proof_bytes = check.proof_bytes, + "Proved and verified an aggregate" + ); + } + let slowest = rounds + .iter() + .map(|check| check.prove) + .max() + .unwrap_or_default(); + let (slowest_ms, budget_ms) = (slowest.as_millis() as u64, budget.as_millis() as u64); + if slowest < budget { + info!( + signatures, + slowest_ms, + budget_ms, + leanvm_rev = LEANVM_REV, + "One aggregate of this size fits a seat's proving window on a 12-second slot" + ); + } else { + warn!( + signatures, + slowest_ms, + budget_ms, + leanvm_rev = LEANVM_REV, + "One aggregate of this size does not fit a seat's proving window on a 12-second \ + slot: this host would miss its aggregates" + ); + } + Ok(()) +} + +/// How long a seat has to prove on `config`'s timing: from its cutoff to its +/// broadcast, the same for every seat. +fn seat_budget(config: &Config) -> Duration { + let bps = config + .aggregate_due_bps_pq + .saturating_sub(config.aggregation_cutoff_bps); + Duration::from_millis(bps.saturating_mul(config.slot_duration_ms) / 10_000) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// PQ `validator.md`'s 12-second example: a seat stops collecting at 4.8 s + /// and broadcasts at 7.2 s. + #[test] + fn a_seat_has_the_cutoff_to_broadcast_window_to_prove_in() { + assert_eq!( + seat_budget(&Config::mainnet()), + Duration::from_millis(2_400) + ); + } +} From dd187f988ec32d6c19cf9aaddeccfd5ec8b7e59e Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:44 -0300 Subject: [PATCH 16/25] fix(pq): an absent X_MAX_COMMITTEE_COUNT_PER_SLOT is the preset's, one above it is refused Two things the first version of the cap got wrong: - An absent key parsed as mainnet's 16, like every key, and was then lowered to the preset's value with a warning. A minimal network whose config.yaml predates the key (every pq-devnet-0 one) warned at each start about a value its file never set. An absent key now takes the preset's MAX_COMMITTEES_PER_SLOT_PQ, which the specification's configs equal, and the config says so afterwards, so the data directory and /eth/v1/config/spec hold what the node runs on. - A value above the preset's was lowered with a warning. The specification says it must not exceed it, and a node that quietly ran another cap than the file's would shuffle other committees than peers that refused or ran it. It is now a startup error naming both values. Also restores the doc comment of Config's Default impl, which the cap's statics had been inserted under. --- bin/ethlambda/src/network/built_in.rs | 4 +- bin/ethlambda/src/network/config_file.rs | 12 +++- bin/ethlambda/src/network/dir.rs | 15 ++++- bin/ethlambda/src/network/mod.rs | 69 ++++++++++++++----- crates/common/types/src/beacon/config.rs | 84 ++++++++++++++++-------- 5 files changed, 135 insertions(+), 49 deletions(-) diff --git a/bin/ethlambda/src/network/built_in.rs b/bin/ethlambda/src/network/built_in.rs index cc4b3cd90..8f333874a 100644 --- a/bin/ethlambda/src/network/built_in.rs +++ b/bin/ethlambda/src/network/built_in.rs @@ -68,11 +68,11 @@ impl BuiltInNetwork { /// Build this network's configuration, genesis values and bootnode list. pub(crate) fn resolve(self) -> eyre::Result { let chain = self.chain(); - let parsed = ConfigFile::parse(chain.config_yaml) + let mut parsed = ConfigFile::parse(chain.config_yaml) .wrap_err_with(|| format!("the built-in {} config.yaml did not parse", self.name()))?; super::select_preset(parsed.config.preset_base.as_str())?; super::check_constants(&parsed.config)?; - super::select_committee_cap(&parsed.config); + super::select_committee_cap(&mut parsed)?; // A built-in config can carry a fork whose keys this build does not // even claim (heze), which the ignored-keys warning below says. A fork // whose keys it claims but whose rules it does not follow is diff --git a/bin/ethlambda/src/network/config_file.rs b/bin/ethlambda/src/network/config_file.rs index 3c5731509..166640564 100644 --- a/bin/ethlambda/src/network/config_file.rs +++ b/bin/ethlambda/src/network/config_file.rs @@ -27,6 +27,11 @@ pub(crate) struct ConfigFile { pub(crate) config: Config, /// Keys no field claimed: a typo, or a fork this build cannot process. pub(crate) ignored: Vec, + /// Whether the file carried `X_MAX_COMMITTEE_COUNT_PER_SLOT`. An absent + /// key parses as mainnet's value, like every other, and for this one + /// that is not what an absent key means: see + /// [`super::select_committee_cap`]. + pub(crate) committee_cap_declared: bool, } #[derive(Debug, thiserror::Error)] @@ -61,13 +66,18 @@ impl ConfigFile { document.contains_key("SLOT_DURATION_MS"), )?; + let committee_cap_declared = document.contains_key("X_MAX_COMMITTEE_COUNT_PER_SLOT"); let claimed = config_field_names(); let ignored = document .into_keys() .filter(|key| !claimed.contains(&key.as_str())) .collect(); - Ok(Self { config, ignored }) + Ok(Self { + config, + ignored, + committee_cap_declared, + }) } /// Log what was ignored, as one line naming each key. diff --git a/bin/ethlambda/src/network/dir.rs b/bin/ethlambda/src/network/dir.rs index e53ece90d..54bb82d65 100644 --- a/bin/ethlambda/src/network/dir.rs +++ b/bin/ethlambda/src/network/dir.rs @@ -55,6 +55,12 @@ pub(crate) enum NetworkDirError { #[source] source: super::ConstantsMismatch, }, + #[error("{}: {source}", path.display())] + CommitteeCap { + path: PathBuf, + #[source] + source: ethlambda_types::beacon::config::CommitteeCapTooLarge, + }, // `{fork:?}` rather than `{fork}`: `ForkName` exposes `as_str` and does not // implement `Display`. #[error("{} did not decode as a {fork:?} BeaconState: {reason}", path.display())] @@ -77,7 +83,7 @@ impl NetworkDir { pub(crate) fn load(base: &Path) -> Result { let config_path = base.join(CONFIG_FILE); let text = read_required(&config_path)?; - let parsed = ConfigFile::parse(&text).map_err(|source| NetworkDirError::Config { + let mut parsed = ConfigFile::parse(&text).map_err(|source| NetworkDirError::Config { path: config_path.clone(), source, })?; @@ -97,7 +103,12 @@ impl NetworkDir { path: config_path.clone(), source, })?; - super::select_committee_cap(&parsed.config); + super::select_committee_cap(&mut parsed).map_err(|source| { + NetworkDirError::CommitteeCap { + path: config_path.clone(), + source, + } + })?; let genesis_path = base.join(GENESIS_STATE_FILE); let genesis_bytes = read_required_bytes(&genesis_path)?; diff --git a/bin/ethlambda/src/network/mod.rs b/bin/ethlambda/src/network/mod.rs index 916045fd9..4f0b2c635 100644 --- a/bin/ethlambda/src/network/mod.rs +++ b/bin/ethlambda/src/network/mod.rs @@ -11,7 +11,11 @@ pub(crate) mod dir; use std::path::PathBuf; -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{ + CommitteeCapTooLarge, Config, select_x_max_committee_count_per_slot, +}; + +use self::config_file::ConfigFile; use ethlambda_types::beacon::preset::{Preset, PresetAlreadyActive}; pub(crate) use built_in::BuiltInNetwork; @@ -107,24 +111,27 @@ pub(crate) fn select_preset(declared: &str) -> Result Ok(preset) } -/// Makes the network's `X_MAX_COMMITTEE_COUNT_PER_SLOT` the cap every PQ -/// committee count of this process uses (consensus-specs pq `af898d07`). -/// After [`select_preset`], whose `MAX_COMMITTEES_PER_SLOT_PQ` bounds it: a -/// value above that, or zero, is moved into range with a warning rather than -/// refused, since the key is a testing knob and `CommitteeBits` could not -/// hold more committees anyway. -pub(crate) fn select_committee_cap(config: &Config) { - let declared = config.x_max_committee_count_per_slot; - let cap = ethlambda_types::beacon::config::select_x_max_committee_count_per_slot(config); - if cap != declared { - tracing::warn!( - declared, - used = cap, - max_committees_per_slot_pq = - ethlambda_types::beacon::preset::max_committees_per_slot_pq(), - "X_MAX_COMMITTEE_COUNT_PER_SLOT is outside 1..=MAX_COMMITTEES_PER_SLOT_PQ; using the nearest value" - ); +/// Settles the network's `X_MAX_COMMITTEE_COUNT_PER_SLOT` and makes it the +/// cap every PQ committee count of this process uses (consensus-specs pq +/// `af898d07`). After [`select_preset`], whose `MAX_COMMITTEES_PER_SLOT_PQ` +/// it is read against: +/// +/// - A file that omits the key gets the preset's value, not the mainnet 16 +/// every other absent key falls back to. The specification's own configs +/// set the two equal, and a minimal network whose file predates the key +/// must not be given more committees than its `CommitteeBits` can name. +/// The value is written into the config, so the data directory and +/// `/eth/v1/config/spec` hold what the node runs on. +/// - A value above the preset's is refused, as the specification forbids it: +/// a client that ran it would name committees an attestation cannot, and +/// one that silently lowered it would shuffle another chain than its peers. +pub(crate) fn select_committee_cap(parsed: &mut ConfigFile) -> Result<(), CommitteeCapTooLarge> { + if !parsed.committee_cap_declared { + parsed.config.x_max_committee_count_per_slot = + ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64; } + select_x_max_committee_count_per_slot(&parsed.config)?; + Ok(()) } /// One `config.yaml` key that the node runs on a compile-time constant for, @@ -470,6 +477,32 @@ mod tests { /// The specification's own configs must pass, or every built-in network /// and every devnet derived from one would be refused. + /// A file that omits `X_MAX_COMMITTEE_COUNT_PER_SLOT` runs on its + /// preset's `MAX_COMMITTEES_PER_SLOT_PQ`, not on the mainnet value the key + /// parsed as, and its config says so afterwards. + #[test] + fn an_absent_committee_cap_is_the_presets() { + let mut parsed = ConfigFile::parse("CONFIG_NAME: devnet\n").unwrap(); + assert!(!parsed.committee_cap_declared); + // Whatever another preset's default would have left there. + parsed.config.x_max_committee_count_per_slot = u64::MAX; + select_committee_cap(&mut parsed).unwrap(); + assert_eq!( + parsed.config.x_max_committee_count_per_slot, + ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64 + ); + } + + #[test] + fn a_committee_cap_above_the_presets_is_refused() { + let above = ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64 + 1; + let yaml = format!("X_MAX_COMMITTEE_COUNT_PER_SLOT: {above}\n"); + let mut parsed = ConfigFile::parse(&yaml).unwrap(); + assert!(parsed.committee_cap_declared); + let err = select_committee_cap(&mut parsed).unwrap_err(); + assert_eq!((err.declared, err.max), (above, above - 1)); + } + #[test] fn the_shipped_configs_match_the_compiled_constants() { check_constants(&Config::mainnet()).unwrap(); diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index be4e25e40..c60506e14 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -515,6 +515,11 @@ pub struct Config { /// `MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`; the /// state transition reads it through /// [`x_max_committee_count_per_slot`], which the node sets from this. + /// + /// Like every key, absent from a file it parses as mainnet's value. For + /// this one that is wrong on a minimal network, so the node replaces an + /// absent key with its preset's `MAX_COMMITTEES_PER_SLOT_PQ` once the + /// preset is selected (`network::select_committee_cap` in the binary). #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub x_max_committee_count_per_slot: u64, @@ -680,39 +685,49 @@ pub struct Config { pub min_epochs_for_block_requests: u64, } -/// Mainnet's values, which is what an absent key in a `config.yaml` falls back -/// to. -/// -/// Deserialization is deliberately permissive: no client surveyed rejects a -/// configuration for a missing key, and a network that predates a field should -/// still load. Mainnet is the right fallback because every other network is -/// described as a deviation from it. /// The PQ committee cap this process runs on, `0` until /// [`select_x_max_committee_count_per_slot`] sets one. static X_MAX_COMMITTEE_COUNT_PER_SLOT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// An `X_MAX_COMMITTEE_COUNT_PER_SLOT` above the preset's +/// `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification says it must not +/// exceed: `CommitteeBits` has that many bits, so a slot with more committees +/// could not name them all in an attestation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error( + "X_MAX_COMMITTEE_COUNT_PER_SLOT is {declared}, above MAX_COMMITTEES_PER_SLOT_PQ ({max}), \ + the most committees an attestation's committee bits can name" +)] +pub struct CommitteeCapTooLarge { + pub declared: u64, + pub max: u64, +} + /// Makes `config`'s `X_MAX_COMMITTEE_COUNT_PER_SLOT` the cap every PQ /// committee count of this process uses, and returns it. /// -/// One per process, like the preset (see `beacon::preset`): the state -/// transition reads it from a state alone, which carries no config. A value -/// above the preset's `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification -/// forbids and `CommitteeBits` cannot hold, is lowered to it, and a zero is -/// raised to one; the caller warns when the returned value differs from the -/// file's. -pub fn select_x_max_committee_count_per_slot(config: &Config) -> u64 { - let cap = committee_cap_within_preset( +/// One per process, like the preset (see `beacon::preset`), and selected +/// after it: the state transition counts committees from a state alone, which +/// carries no config. Refuses a value above the active preset's +/// `MAX_COMMITTEES_PER_SLOT_PQ` and stores nothing then. +pub fn select_x_max_committee_count_per_slot(config: &Config) -> Result { + let cap = committee_cap( config.x_max_committee_count_per_slot, preset::max_committees_per_slot_pq() as u64, - ); + )?; X_MAX_COMMITTEE_COUNT_PER_SLOT.store(cap, std::sync::atomic::Ordering::Relaxed); - cap + Ok(cap) } -/// `declared` moved into `1..=max_committees_per_slot_pq`. -fn committee_cap_within_preset(declared: u64, max_committees_per_slot_pq: u64) -> u64 { - declared.clamp(1, max_committees_per_slot_pq) +/// The cap a `declared` `X_MAX_COMMITTEE_COUNT_PER_SLOT` gives under a preset +/// of `max` committees per slot. A zero is one: `get_committee_count_per_slot` +/// never goes below one committee, whatever the cap. +fn committee_cap(declared: u64, max: u64) -> Result { + if declared > max { + return Err(CommitteeCapTooLarge { declared, max }); + } + Ok(declared.max(1)) } /// `X_MAX_COMMITTEE_COUNT_PER_SLOT` as selected for this process, or the @@ -726,6 +741,13 @@ pub fn x_max_committee_count_per_slot() -> u64 { } } +/// Mainnet's values, which is what an absent key in a `config.yaml` falls back +/// to. +/// +/// Deserialization is deliberately permissive: no client surveyed rejects a +/// configuration for a missing key, and a network that predates a field should +/// still load. Mainnet is the right fallback because every other network is +/// described as a deviation from it. impl Default for Config { fn default() -> Self { Self::mainnet() @@ -1386,17 +1408,27 @@ mod tests { let config: Config = serde_yaml_ng::from_str("X_MAX_COMMITTEE_COUNT_PER_SLOT: 1\n").unwrap(); assert_eq!(config.x_max_committee_count_per_slot, 1); - // Absent, it is mainnet's, like every other key a file omits. + // Absent, it parses as mainnet's, like every other key a file omits; + // the node then replaces it with its preset's value. let config: Config = serde_yaml_ng::from_str("CONFIG_NAME: x\n").unwrap(); assert_eq!(config.x_max_committee_count_per_slot, 16); } #[test] - fn the_pq_committee_cap_stays_within_committee_bits() { - assert_eq!(committee_cap_within_preset(4, 16), 4); - assert_eq!(committee_cap_within_preset(16, 16), 16); - assert_eq!(committee_cap_within_preset(16, 4), 4); - assert_eq!(committee_cap_within_preset(0, 16), 1); + fn the_pq_committee_cap_may_not_exceed_committee_bits() { + assert_eq!(committee_cap(1, 16), Ok(1)); + assert_eq!(committee_cap(4, 16), Ok(4)); + assert_eq!(committee_cap(16, 16), Ok(16)); + // Mainnet's value on a minimal preset, and anything else above it. + let too_large = CommitteeCapTooLarge { + declared: 16, + max: 4, + }; + assert_eq!(committee_cap(16, 4), Err(too_large)); + assert!(too_large.to_string().contains("is 16, above")); + // `max(1, min(cap, ..))` in the specification: a zero cap is one + // committee, not none. + assert_eq!(committee_cap(0, 16), Ok(1)); } #[test] From 3e56b1d582f3a93cded68892312a33a9025c2ffc Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:44 -0300 Subject: [PATCH 17/25] perf(pq): a later seat does not prove again what an earlier one proved A committee's seats are staggered 0.6 s apart and one node can hold several. Unless a vote arrived between two cutoffs, the later seat collected exactly what the earlier one proved, and proving it again took the prover, which makes one proof at a time, as long again for an aggregate insert_proven would not keep and should_broadcast_aggregate rules out once the earlier seat has broadcast. The held aggregate still answers the later seat's request. PqSignaturePool::is_proven says so, and the seat's cost line counts already_proven. --- crates/net/rpc/src/beacon/pq_aggregation.rs | 10 +++- crates/storage/src/pools/pq_signature.rs | 61 +++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index 9fc87c807..b25b9cff6 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -14,7 +14,8 @@ //! at `position` stops collecting at `get_aggregation_cutoff_ms(position)` and //! broadcasts at `get_aggregate_due_ms(position)`. The task here wakes at //! each seat's cutoff in turn, proves what was collected for the committees -//! one of this node's validators holds that seat in, and ends the slot's +//! one of this node's validators holds that seat in (unless an earlier seat +//! of this node already proved every vote collected), and ends the slot's //! collection after the last seat's. The endpoint then answers with what was //! proved, and the aggregate also goes into the pool block production packs //! from, since gossip never hands a node its own messages. @@ -129,6 +130,10 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { let state_ms = started.elapsed().as_millis() as u64; let mut groups = store.pq_signature_pool().collected(slot, &committees); let committees = groups.len(); + // What an earlier seat of this node already proved in full is not + // proved again: see `PqSignaturePool::is_proven`. + groups.retain(|group| !store.pq_signature_pool().is_proven(group)); + let already_proven = committees - groups.len(); let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the // deadline. @@ -198,9 +203,10 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { committees, signatures, proved, + already_proven, failed, late, - unproved = committees - proved - failed - late, + unproved = committees - already_proven - proved - failed - late, queued_ms, state_ms, prove_ms = prove_ms_total, diff --git a/crates/storage/src/pools/pq_signature.rs b/crates/storage/src/pools/pq_signature.rs index 4fb4ba3a3..de095995d 100644 --- a/crates/storage/src/pools/pq_signature.rs +++ b/crates/storage/src/pools/pq_signature.rs @@ -218,6 +218,30 @@ impl PqSignaturePool { self.proven.get(&(slot, data_root, committee)).cloned() } + /// Whether the aggregate this node holds for `group`'s vote already + /// proves every signature `group` has. + /// + /// A committee's seats are staggered, and one node can hold several of + /// them. Unless a vote arrived between two of their cutoffs, the later + /// seat collected what the earlier one proved: proving it again takes the + /// prover seconds, one proof at a time, for an aggregate the endpoint + /// would not even keep ([`Self::insert_proven`] keeps the larger one) and + /// that `should_broadcast_aggregate` rules out once the earlier seat has + /// broadcast. The held aggregate still answers the later seat's request. + pub fn is_proven(&self, group: &CommitteeSignatures) -> bool { + let key = ( + group.data.slot, + group.data.hash_tree_root(), + group.committee_index, + ); + self.proven.get(&key).is_some_and(|held| { + group + .signatures + .keys() + .all(|signer| held.attesting_indices.binary_search(signer).is_ok()) + }) + } + /// Whether `slot`'s collection has ended. pub fn is_sealed(&self, slot: Slot) -> bool { self.sealed_slot.is_some_and(|sealed| slot <= sealed) @@ -401,6 +425,43 @@ mod tests { assert!(!covered_given(&[&[2, 3]])); } + /// A later seat has something to prove only when it collected a vote the + /// held aggregate lacks. + #[test] + fn a_group_is_proven_once_the_held_aggregate_has_all_its_signers() { + use ethlambda_types::beacon::containers::pq::Attestation; + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 7); + pool.insert(3, &vote(3, 0, 10, 1)); + pool.insert(3, &vote(3, 0, 11, 1)); + let collected = |pool: &PqSignaturePool| pool.collected(3, &[0]).remove(0); + assert!(!pool.is_proven(&collected(&pool)), "nothing held yet"); + + // The first seat proves the two votes it collected. + let group = collected(&pool); + pool.insert_proven(Arc::new(PooledPqAggregate { + attestation: Attestation { + aggregation_bits: Default::default(), + data: group.data, + committee_bits: Default::default(), + }, + committee_index: 0, + attesting_indices: vec![10, 11], + proof: Default::default(), + })); + assert!(pool.is_proven(&collected(&pool))); + + // A third vote reaches the next seat before its cutoff. + pool.insert(3, &vote(3, 0, 12, 1)); + assert!(!pool.is_proven(&collected(&pool))); + + // Another vote on other data is its own group, with nothing held. + pool.insert(3, &vote(3, 0, 13, 2)); + let groups = pool.collected(3, &[0]); + assert_eq!(groups.len(), 2); + assert!(groups.iter().all(|group| !pool.is_proven(group))); + } + #[test] fn broadcasts_are_kept_per_vote_and_committee_and_only_when_subscribed() { let data = vote(3, 0, 0, 1).data; From ffbfc20a71e677ada747f2a8c7d1c63cbc9ffd80 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:45 -0300 Subject: [PATCH 18/25] fix(validator): PQ aggregator seats publish side by side, not in turn The node holds an aggregate request for up to three seconds while the proof asked for is still being made. Seats were served one after another, so a held request for the seat due at 7.2 s kept the seats due at 7.8, 8.4 and 9.0 s from even asking until 10.2 s. Each seat now waits for its own time and runs on its own. The mock can hold pq_aggregate requests and records when each arrived. --- crates/validator/src/aggregation.rs | 75 ++++++++++++++++++++---- crates/validator/src/beacon_node/mock.rs | 24 +++++++- 2 files changed, 86 insertions(+), 13 deletions(-) diff --git a/crates/validator/src/aggregation.rs b/crates/validator/src/aggregation.rs index 54837e938..d18ac2c49 100644 --- a/crates/validator/src/aggregation.rs +++ b/crates/validator/src/aggregation.rs @@ -98,9 +98,12 @@ impl AggregationService { /// ahead, since proving takes seconds. /// /// The aggregators are staggered by seat: the one at `position` publishes - /// at `get_aggregate_due_ms(position)`, so this waits for each seat's time - /// in turn. The node answers 404 for an aggregate one already broadcast - /// covers (`should_broadcast_aggregate`), which skips it here. + /// at `get_aggregate_due_ms(position)`. Each seat waits for its own time + /// and then runs on its own, beside the others: the node may hold a + /// seat's request for seconds while a proof is still being made, and a + /// seat served in turn behind it would publish that much late, into the + /// seats after it. The node answers 404 for an aggregate one already + /// broadcast covers (`should_broadcast_aggregate`), which skips it here. pub async fn aggregate_pq( &self, clock: &SlotClock, @@ -118,19 +121,21 @@ impl AggregationService { .or_default() .push(duty); } - let mut published = 0; - for (position, seated) in by_seat { + let seats = by_seat.into_iter().map(|(position, seated)| async move { let due = clock.pq_aggregation_time(slot, position); let wait = due.duration_since(SystemTime::now()).unwrap_or_default(); tokio::time::sleep(wait).await; - match self.publish_pq_seat(slot, data, &seated).await { - Ok(count) => published += count, - Err(err) => { + self.publish_pq_seat(slot, data, &seated) + .await + .inspect_err(|err| { warn!(%slot, position, %err, "Failed to publish this seat's PQ aggregates") - } - } - } - Ok(published) + }) + .unwrap_or(0) + }); + Ok(futures_util::future::join_all(seats) + .await + .into_iter() + .sum()) } /// Fetch, sign and publish the aggregates of the aggregators `selected`, @@ -491,6 +496,52 @@ mod tests { } } + /// Each PQ seat asks for its aggregate at its own time. The node holds a + /// request while a proof is still being made, here for three seconds: + /// the next seat, due 0.6 s after the first, must not wait behind it. + #[tokio::test(start_paused = true)] + async fn a_slow_answer_for_one_pq_seat_does_not_delay_the_next() { + use std::time::{Duration, UNIX_EPOCH}; + + let held = Duration::from_secs(3); + let node = Arc::new(MockBeaconNode::new().with_pq_aggregate_delay(held)); + let service = AggregationService::new(node.clone(), context()); + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 0); + // Slot 64 began within the last second. + let slot = 64; + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + let clock = SlotClock::from_config(now.as_secs() - slot * 12, &config); + let (_, pubkey) = store(); + let seat = |position: u64| AttesterDutyDto { + is_aggregator: Some(true), + aggregator_position: Some(position), + // A committee each, so each seat has its own request. + ..duty(&pubkey, position, slot, position) + }; + + let started = tokio::time::Instant::now(); + let published = service + .aggregate_pq(&clock, slot, &data(slot), &[seat(0), seat(1)]) + .await + .expect("a 404 is no error"); + assert_eq!(published, 0, "the mock proves no aggregate"); + + let calls = node.pq_aggregate_calls(); + assert_eq!(calls.len(), 2); + let (first, second) = (calls[0].0 - started, calls[1].0 - started); + // 7.2 s and 7.8 s into the slot, less the fraction of a second the + // slot is already old. + assert!(first > Duration::from_millis(6_200) && first <= Duration::from_millis(7_200)); + let apart = second - first; + assert!( + apart > Duration::from_millis(550) && apart < Duration::from_millis(650), + "the second seat asked {apart:?} after the first" + ); + // Both answers were held three seconds, side by side. + let took = started.elapsed(); + assert!(took < first + held + Duration::from_secs(1), "{took:?}"); + } + fn duty( pubkey: &BlsPubkey, validator_index: u64, diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index ac678bc68..9d649db4c 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -196,6 +196,12 @@ pub struct MockBeaconNode { /// What `payload_attestation_data` answers with. `None` is the 204. pub payload_attestation_data: Option, pub payload_attestation_data_calls: Mutex, + /// How long `pq_aggregate` holds a request before answering, as a node + /// does while the proof asked for is still being made. + pub pq_aggregate_delay: std::time::Duration, + /// When each `pq_aggregate` call arrived and for which committee, in + /// arrival order. + pub pq_aggregate_calls: Mutex>, pub submitted_payload_attestations: Mutex>, /// The fork each `attestation_data` call named, in call order. pub attestation_data_forks: Mutex>, @@ -470,6 +476,17 @@ impl MockBeaconNode { self } + /// Hold every `pq_aggregate` request for `delay` before answering it. + pub fn with_pq_aggregate_delay(mut self, delay: std::time::Duration) -> Self { + self.pq_aggregate_delay = delay; + self + } + + /// When each `pq_aggregate` call arrived and for which committee. + pub fn pq_aggregate_calls(&self) -> Vec<(tokio::time::Instant, u64)> { + self.pq_aggregate_calls.lock().expect("lock").clone() + } + /// Answer `attestation_data` naming `root` as the head block. Over /// [`Self::with_attestation_data`], which names the zero root. pub fn with_attestation_block_root(mut self, root: Root) -> Self { @@ -1286,8 +1303,13 @@ impl BeaconNodeApi for MockBeaconNode { &self, _slot: Slot, _attestation_data_root: Root, - _committee_index: u64, + committee_index: u64, ) -> Result { + self.pq_aggregate_calls + .lock() + .expect("lock") + .push((tokio::time::Instant::now(), committee_index)); + tokio::time::sleep(self.pq_aggregate_delay).await; self.guard("pq_aggregate")?; // What a node with nothing to publish for the committee answers. Err(Error::BeaconNodeStatus { From 3d6d0f1dfaac81401a8468326c8bd647d84b1bc7 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:45 -0300 Subject: [PATCH 19/25] perf(pq): build the image's prover with leanVM's CPU tiers Without them leanVM's prover runs on the build's portable baseline (x86-64-v3 with PCLMULQDQ), and on a host with AVX-512, GFNI or VPCLMULQDQ says so on stderr at the first proof: slower than the CPU allows, and slower than the other clients' leanVM builds, which pick a tier at run time. The leanvm-cpu-tiers feature compiles the prover once more per tier. A tier only gets its instructions under leanVM's scripts/tier-rustc as RUSTC_WRAPPER, which the Dockerfile fetches at the pinned revision and sets before cargo chef cook; every other crate is compiled as before. Off by default, so an ordinary build does not compile the copies; the image builds with it. Cargo.lock gains the tier crates. --- Cargo.lock | 455 ++++++++++++++++++++++++++++++++ Dockerfile | 24 +- bin/ethlambda/Cargo.toml | 3 + crates/common/crypto/Cargo.toml | 7 + 4 files changed, 487 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 79ea90445..80e1c18c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2656,6 +2656,13 @@ version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" dependencies = [ "experimental_lean_vm_core", + "experimental_lean_vm_core_armaes", + "experimental_lean_vm_core_armsha3", + "experimental_lean_vm_core_x86avx2", + "experimental_lean_vm_core_x86v3clmul", + "experimental_lean_vm_core_x86v3gfni", + "experimental_lean_vm_core_x86v4", + "experimental_lean_vm_core_x86v4gfni", "isa", "verifier", ] @@ -2673,6 +2680,97 @@ dependencies = [ "verifier", ] +[[package]] +name = "experimental_keccak_gkr_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_armaes", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_armsha3", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86avx2", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v3clmul", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v3gfni", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v4", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v4gfni", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "tracing", + "verifier", +] + [[package]] name = "experimental_lean_vm_core" version = "0.1.0" @@ -2688,6 +2786,111 @@ dependencies = [ "verifier", ] +[[package]] +name = "experimental_lean_vm_core_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_armaes", + "experimental_parallel", + "experimental_pcs_armaes", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_armsha3", + "experimental_parallel", + "experimental_pcs_armsha3", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_x86avx2", + "experimental_parallel", + "experimental_pcs_x86avx2", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_x86v3clmul", + "experimental_parallel", + "experimental_pcs_x86v3clmul", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_x86v3gfni", + "experimental_parallel", + "experimental_pcs_x86v3gfni", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_x86v4", + "experimental_parallel", + "experimental_pcs_x86v4", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_keccak_gkr_x86v4gfni", + "experimental_parallel", + "experimental_pcs_x86v4gfni", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "isa", + "tracing", + "verifier", +] + [[package]] name = "experimental_parallel" version = "0.1.0" @@ -2708,6 +2911,90 @@ dependencies = [ "verifier", ] +[[package]] +name = "experimental_pcs_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "tracing", + "verifier", +] + [[package]] name = "experimental_primitives" version = "0.1.0" @@ -2718,6 +3005,76 @@ dependencies = [ "keccak256", ] +[[package]] +name = "experimental_primitives_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_armaes", + "keccak256_armaes", +] + +[[package]] +name = "experimental_primitives_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_armsha3", + "keccak256_armsha3", +] + +[[package]] +name = "experimental_primitives_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86avx2", + "keccak256_x86avx2", +] + +[[package]] +name = "experimental_primitives_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v3clmul", + "keccak256_x86v3clmul", +] + +[[package]] +name = "experimental_primitives_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v3gfni", + "keccak256_x86v3gfni", +] + +[[package]] +name = "experimental_primitives_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v4", + "keccak256_x86v4", +] + +[[package]] +name = "experimental_primitives_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v4gfni", + "keccak256_x86v4gfni", +] + [[package]] name = "eyre" version = "0.6.12" @@ -2814,6 +3171,69 @@ dependencies = [ "verifier", ] +[[package]] +name = "fiat_shamir_prover_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_armaes", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_armsha3", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_x86avx2", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_x86v3clmul", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_x86v3gfni", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_x86v4", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +dependencies = [ + "keccak256_x86v4gfni", + "verifier", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3940,6 +4360,41 @@ name = "keccak256" version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +[[package]] +name = "keccak256_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + +[[package]] +name = "keccak256_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" + [[package]] name = "konst" version = "0.2.20" diff --git a/Dockerfile b/Dockerfile index 10d52bde8..a459dda5e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,12 +20,32 @@ COPY --from=planner /app/recipe.json recipe.json # cached deps are compiled with default flags and cargo reuses them. COPY .cargo/ .cargo/ +# leanVM's PQ prover is compiled once more per CPU tier (AVX-512, GFNI and +# VPCLMULQDQ on x86-64, SHA3 on arm64), and picks the fastest one the host has +# at run time: one image for every host, as the other clients' leanVM builds +# are. A tier only gets its instructions when rustc is wrapped by leanVM's own +# `scripts/tier-rustc`, which adds a tier's target features to that tier's +# crates and leaves every other crate as asked, so the node itself keeps the +# portable baseline in `.cargo/config.toml`. Fetched at the pinned revision +# (`leanvm-revision`, which a test holds equal to the workspace's `rev`), so +# the wrapper is the one the prover's sources were written against. Set before +# `cargo chef cook`, which is what compiles the tiers. A build without the +# `leanvm-cpu-tiers` feature has no tier crates, and the wrapper changes +# nothing in it. +COPY leanvm-revision leanvm-revision +RUN rev="$(tr -d '[:space:]' < leanvm-revision)" \ + && test -n "$rev" \ + && curl -fsSL "https://raw.githubusercontent.com/leanEthereum/leanVM/${rev}/scripts/tier-rustc" \ + -o /usr/local/bin/leanvm-tier-rustc \ + && chmod +x /usr/local/bin/leanvm-tier-rustc +ENV RUSTC_WRAPPER=/usr/local/bin/leanvm-tier-rustc + # Build profile, release by default ARG BUILD_PROFILE=release ENV BUILD_PROFILE=$BUILD_PROFILE -# Extra Cargo features -ARG FEATURES="" +# Cargo features. `leanvm-cpu-tiers` by default: see the wrapper above. +ARG FEATURES="leanvm-cpu-tiers" ENV FEATURES=$FEATURES # Disable default features (e.g. for `shadow-integration`, which must drop the diff --git a/bin/ethlambda/Cargo.toml b/bin/ethlambda/Cargo.toml index 852039a51..75ffb1d5d 100644 --- a/bin/ethlambda/Cargo.toml +++ b/bin/ethlambda/Cargo.toml @@ -17,6 +17,9 @@ jemalloc = ["dep:tikv-jemallocator"] # The quinn-udp UDP fallback is a Cargo `[patch]` (which cannot be feature-gated), # injected at build time by `shadow/build.sh` / `make shadow-build`. shadow-integration = ["ethlambda-crypto/shadow-integration"] +# The PQ prover's CPU tiers: see `ethlambda-crypto`'s feature of the same +# name. The Dockerfile builds with it, and with the wrapper it needs. +leanvm-cpu-tiers = ["ethlambda-crypto/leanvm-cpu-tiers"] [dependencies] ethlambda-blockchain.workspace = true diff --git a/crates/common/crypto/Cargo.toml b/crates/common/crypto/Cargo.toml index 02def5121..54c0d612c 100644 --- a/crates/common/crypto/Cargo.toml +++ b/crates/common/crypto/Cargo.toml @@ -31,6 +31,13 @@ tracing.workspace = true [features] shadow-integration = [] +# leanVM's PQ prover compiled once more per CPU tier (AVX-512, GFNI and +# VPCLMULQDQ on x86-64, SHA3 on arm64), the fastest tier the running CPU has +# picked at run time. Only a build with leanVM's `scripts/tier-rustc` as +# `RUSTC_WRAPPER` gives the tiers their instructions, which the Dockerfile +# does; without the wrapper the feature compiles the copies and uses none. +# Off by default so that an ordinary build does not compile them. +leanvm-cpu-tiers = ["leanvm_prover/cpu_tiers"] [dev-dependencies] hex.workspace = true From 22d16f45ec80ced17a3a7e6d057eca06179615a4 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:13:46 -0300 Subject: [PATCH 20/25] docs(pq): the prover's guard, self-check, tiers and cost; the cap's rules; seats Also corrects the memory note: the node's jemalloc returns a proof's buffers like any freed memory. It is leanVM's own builds that keep them (dirty_decay_ms:-1), which MALLOC_CONF can ask of the node too. --- CLAUDE.md | 34 +++++++++++++++------ docs/beacon_pq.md | 75 ++++++++++++++++++++++++++++++++++++----------- docs/cli.md | 19 +++++++++++- 3 files changed, 101 insertions(+), 27 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 282493e10..81e95aeb1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,7 +102,9 @@ make test # All tests + forkchoice spec tests `make test` is `test-consensus` plus `test-node`, two halves CI runs as separate jobs because together they no longer fit a runner's disk. `CONSENSUS_CRATES` in the Makefile names the first; `test-node` is the workspace minus it. Run one half -directly when iterating on it. +directly when iterating on it. `test-consensus` also runs the PQ fork's +end-to-end leanVM prover test by name (`leanvm_proofs_merge_and_verify`, ignored +by a plain `cargo test`, which spends minutes on it unoptimized). ### Docs-only changes skip CI @@ -303,16 +305,27 @@ actual_slot = finalized_slot + 1 + relative_index signatures concatenated), or real leanVM proofs made in process (`stark::leanvm`, leanVM `1e997c99`, bindings v0.17.0, the one release pq-devnet-1 runs for signer, prover and verifier; `lean_vm` with its - experimental prover, `cpu_tiers` off). `run_node` installs leanVM as soon + experimental prover). `run_node` installs leanVM as soon as `--network` resolves to a network that schedules PQ, on - `--pq-prover-threads` threads (0: one per core); the reference is then - only what the spec tests run. v0.17.0 removed pq-devnet-0's + `--pq-prover-threads` threads (0: one per core, never more than the + cores); the reference is then only what the spec tests run. Setup ends + with a self-check (one signature proved and verified) that fails startup, + and every call into leanVM is wrapped in `leanvm::guarded`, since a panic + there would otherwise unwind into the chain actor importing a block: it + reads as a proof that does not verify, or was not made. The image builds + the prover with leanVM's CPU tiers (`leanvm-cpu-tiers` feature plus + leanVM's `scripts/tier-rustc` as `RUSTC_WRAPPER`, fetched by the + Dockerfile at the pinned revision), picked at run time; a plain `cargo + build` has no tiers and proves on `.cargo/config.toml`'s baseline. + `ethlambda pq-prover-check` measures the prover on a host against a + seat's 2.4 s proving window. v0.17.0 removed pq-devnet-0's `leanvm-sidecar`, so the image builds none, and `ethlambda-pq` (`bin/ethlambda/pq/`) is now a shim that execs `ethlambda`, kept for launchers that still call it. A proof from another leanVM revision does not verify, and nothing on the wire says why; the root `leanvm-revision` file - names the pin. The two encodings do not verify each other's proofs. Never - pass one scheme's key to the other + names the pin (a test holds it equal to the manifest's `rev`s, and the + Dockerfile reads it). The two encodings do not verify each other's proofs. + Never pass one scheme's key to the other - Wire sizes: `PUBLIC_KEY_SIZE` (`common/types/src/state.rs`) and `SIGNATURE_SIZE` (`common/types/src/attestation.rs`), static-asserted against leanVM's scheme constants in `common/crypto/src/signature.rs` @@ -880,7 +893,9 @@ transitions are in `ethlambda-types`, per the section above. Nothing above suites. - **EIP-8483 and PQ** (consensus-specs' `pq` branch feature forks, pinned at `4c296784`, pq-devnet-1's spec: staggered aggregators of `4595f0fc`, VRF - secrets of `b5d422b2`, `X_MAX_COMMITTEE_COUNT_PER_SLOT` of `af898d07`, + 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 8 and 9, implemented in the state transition and fork choice (`stf/{eip8483,pq}.rs`, `stf/epoch/pq.rs`, `helpers/pq.rs`, `upgrade_to_*`) @@ -897,8 +912,9 @@ transitions are in `ethlambda-types`, per the section above. Nothing above with its own validators: the validator client derives each validator's leanXMSS key and VRF seed from its BLS key (`ethlambda_crypto::pq_keys`) and attests, aggregates (staggered by its seat - in the aggregation committee), casts PTC votes and proposes, each signature - at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all + in the aggregation committee, each seat on its own; the node skips a seat's + proof when an earlier seat of its own already proved every vote collected), + casts PTC votes and proposes, each signature at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all `2^31` leaves, each committing to its slot's secret) takes about 100 s of every core per key, so a background thread hashes it after startup (in a rayon pool of its own: on the global one it starves every leanXMSS diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index defeb9f10..a8831f7e6 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -157,13 +157,37 @@ proofs through one of two backends, chosen once per process: (`MAX_RECURSIONS`) at a time. The node installs it itself, as soon as `--network` resolves to a network that schedules PQ, after `lean_vm::setup` starts the prover's pool (`--pq-prover-threads`, 0 for - one thread per core) and builds its aggregation program. leanVM proves one - proof at a time per process; verifying does not wait for a proof. - It builds with leanVM's experimental prover (the one pq-devnet-0's - sidecar ran; the same proofs as the stable one, faster). leanVM's - `cpu_tiers` stays off: it needs leanVM's `scripts/tier-rustc` as the - rustc wrapper, and the node's own CPU baseline (`.cargo/config.toml`) - already gives the prover its carryless multiply. + one thread per core, and never more than the cores) and builds its + aggregation program. leanVM proves one proof at a time per process; + verifying takes no lock and runs on the calling thread, so it does not + wait for a proof. +- **The self-check.** Setup ends by proving and verifying one throwaway + signature, and checking the proof does not verify against another claim. + A prover that cannot run on the machine stops the node at startup rather + than missing every aggregation duty, and the `leanVM prover ready` line + carries what the proof and its check took. +- **Panics stay inside.** In a sidecar, an input that crashed leanVM cost + that process a restart. In the node, the caller is the thread importing a + block or judging gossip, and the proof bytes are a peer's. Every call into + leanVM is wrapped (`leanvm::guarded`): a panic in the verifier reads as a + proof that does not verify, one in the prover as a proof that was not + made, and both are logged as `leanVM panicked`. +- **The build.** leanVM's experimental prover (the one pq-devnet-0's sidecar + ran; the same proofs as the stable one, faster). The image builds with the + `leanvm-cpu-tiers` feature and leanVM's `scripts/tier-rustc` as + `RUSTC_WRAPPER` (the Dockerfile fetches it at the pinned revision): the + prover is compiled once more per CPU tier (AVX-512, GFNI and VPCLMULQDQ + on x86-64, SHA3 on arm64) and picks the fastest one the host has at run + time, as the other clients' leanVM builds do. Every other crate keeps the + portable baseline in `.cargo/config.toml`. A build without the feature, + which is what `cargo build` gives, proves on that baseline alone, and + leanVM says so on stderr at the first proof when the CPU has more. +- **What it costs.** `ethlambda pq-prover-check` proves and verifies an + aggregate of `--signatures` claims (128 by default) on the machine it runs + on and reports each round against a seat's proving window, 2.4 s of a + 12-second slot. On 14 cores of an Apple M4 Max, a `release-fast` build + proves 128 signatures in about 0.28 s and 512 in about 0.86 s; verifying + takes about 6 ms either way, and the proofs are 160 to 200 KB. pq-devnet-0 ran the prover as a separate `leanvm-sidecar` (bindings v0.15.0), which the image built and its `ethlambda-pq` supervisor started and @@ -251,10 +275,14 @@ validators into fewer, larger committees. It may not exceed the preset's `MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`. The state transition counts committees from a state alone, so the node selects the cap once per process from the network's `config.yaml`, beside the preset -(`network::select_committee_cap`); a value out of range is moved into it -with a warning, a process that selects none (the spec tests) runs on the -preset's value, which the specification's own configs equal, and a resume -refuses a changed cap. The committee cache's `ShufflingKey` +(`network::select_committee_cap`). A file that omits the key runs on its +preset's `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification's own +configs set it to, not on the mainnet 16 an absent key otherwise parses as: +a minimal network whose file predates the key keeps its four committees. A +value above the preset's is refused at startup, as the specification +forbids it; a zero is one committee, as `get_committee_count_per_slot` has +it. A process that selects no cap (the spec tests) runs on the preset's +value, and a resume refuses a changed cap. The committee cache's `ShufflingKey` carries the cap, since a state either side of the fork names the same epoch and deciding block but a different shuffling. @@ -435,8 +463,13 @@ asks for again. join the committee's subnet and register it with the aggregating validator, the node keeps the validated votes' signatures for registered committees, and at each seat's cutoff proves what it has for the committees one of its - validators holds that seat in. The client asks for each aggregate at its - seat's broadcast time; `GET aggregate_attestation` answers the proved + validators holds that seat in. A node holding two seats of one committee + proves at the later one only if a vote arrived since the earlier one's + proof (`PqSignaturePool::is_proven`): otherwise the aggregate would be the + same, for as long again on a prover that makes one proof at a time. The + client asks for each aggregate at its seat's broadcast time, every seat on + its own, so a request the node holds while a proof is still being made + does not delay the seats after it; `GET aggregate_attestation` answers the proved aggregate and its proof, or a 404 when an aggregate already broadcast for the committee, gossip's or this node's, covers every attester of it (`should_broadcast_aggregate`). The client signs the `AggregateAndProof` at @@ -521,16 +554,24 @@ What the package does for ethlambda on a PQ network: (`xmss_pubkey_url`) and the VRF states (`vrf_state_url`); every root hashes a whole tree, minutes a validator, and the run is resumable. +Before genesis, `docker run --rm --entrypoint ethlambda ethlambda:pq-local +pq-prover-check` on a devnet host says whether its prover keeps up with a +committee of 128 (see [Proofs](#proofs)). + Limits worth knowing: - **At least 32 validators** on the mainnet preset: gloas's `compute_ptc` asserts every slot has an attester, so with fewer, epoch processing fails at the first epoch boundary (`compute_balance_weighted_selection: total > 0`) and the chain stops. The specification does the same. -- **Memory.** leanVM's prover keeps the pages of its largest proof resident - for the life of the process (its jemalloc never decays dirty pages), now - inside the node rather than in a sidecar. On Docker Desktop's default 8 GB - VM, give a node that only verifies fewer `--pq-prover-threads`. +- **Memory.** A proof's buffers are now the node's own allocations, on top + of everything else it holds, where they were a sidecar's. The node's + jemalloc returns them to the kernel some seconds after the proof, as it + does any freed memory. leanVM's own builds instead keep them + (`dirty_decay_ms:-1`), so the next proof does not fault each page in + again, at the price of the process holding its peak; the image's + jemalloc reads `MALLOC_CONF`, so `MALLOC_CONF=dirty_decay_ms:-1` trades + the same way, for the whole node. Not measured here. - **Lighthouse's envelopes over req/resp.** Its `pq-devnet-0` image (last checked at `sha256:f571048f`) answered `execution_payload_envelopes_by_{range,root}` with a gloas-shaped envelope diff --git a/docs/cli.md b/docs/cli.md index 9f640c6ac..81490bb00 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -165,7 +165,7 @@ something specific here. |---|---|---| | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | -| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.17.0 (`1e997c99`, the release pq-devnet-1 runs; a proof from another revision does not verify). The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | +| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.17.0 (`1e997c99`, the release pq-devnet-1 runs; a proof from another revision does not verify). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, @@ -970,6 +970,23 @@ names (EIP-7044), an epoch from before deneb included, so a pre-signed exit stays valid across every fork to come. The command signs that way, and the [keymanager API](#the-keymanager-api)'s `voluntary_exit` route does too. +## `pq-prover-check` + +Proves and verifies one PQ-fork aggregate with leanVM on the machine it runs +on, and reports what it took against an aggregator seat's proving window +(2.4 s of a 12-second slot). No network and no data directory: it answers +whether a host keeps up before a devnet's genesis. + +| Flag | Default | Description | +|------|---------|-------------| +| `--signatures` | `128` | How many signatures the aggregate proves, 1 to 4096: one committee's attesters | +| `--threads` | `0` | leanVM prover threads, 0 for one per core: the node's `--pq-prover-threads` | +| `--rounds` | `3` | How many times to prove; the first round pays for whatever the prover sets up on first use | + +Each round logs `prove_ms`, `verify_ms` and `proof_bytes`, and the last line +says whether the slowest round fits the window (a warning when it does not). +See [`beacon_pq.md`](beacon_pq.md#proofs) for what the prover is built with. + ## `slashing-protection` Moves the validator client's EIP-3076 history in and out of its From 6039075e0552bf2ac8640da2f543810266dbe853 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Thu, 26 Nov 2026 19:34:22 -0300 Subject: [PATCH 21/25] chore(pq): leanVM bindings v0.19.0 (351f7ae4), the release pq-devnet-1 launches on pq-devnet-1 moved from v0.17.0 to v0.19.0 for every client, and takes no other revision. Between the two: - v0.18.0: setup picks the experimental prover's CPU tier (so a build that leaves some of the CPU unused says so at startup, not at the first proof), and faster leanXMSS key generation and signing. - v0.19.0: lean_xmss::MAX_CACHED_BOTTOM_TREES is renamed DEFAULT_BOTTOM_TREE_CACHE_SIZE and is 8, not 4 (only a comment named it here); signing hashes chain steps in batches; PROTOCOL_VERSION, bumped on every STARK-breaking change, which the prover's startup line and pq-prover-check now report (1). No wire or file format changes: the proved program, the verifier's tag, the claim encoding and the key cache layout are the same, and a cache file with two bottom trees (xmss_cache_url's 14696-byte records) still loads. scripts/tier-rustc is unchanged. Also corrects the manifest comment that still said cpu_tiers was not enabled. --- CLAUDE.md | 2 +- Cargo.lock | 136 +++++++++++------------ Cargo.toml | 20 ++-- Dockerfile | 2 +- bin/ethlambda/pq/ethlambda-pq | 7 +- bin/ethlambda/src/cli.rs | 2 +- bin/ethlambda/src/pq_prover_check.rs | 4 +- crates/common/crypto/src/lib.rs | 2 +- crates/common/crypto/src/stark.rs | 2 +- crates/common/crypto/src/stark/leanvm.rs | 20 +++- docs/beacon_pq.md | 8 +- docs/cli.md | 2 +- docs/spec_deviations.md | 2 +- leanvm-revision | 2 +- 14 files changed, 112 insertions(+), 99 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 81e95aeb1..444ebde41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -303,7 +303,7 @@ actual_slot = finalized_slot + 1 + relative_index consensus-specs' and leanVM's known answers), and proves many signatures at once through `ethlambda_crypto::stark`: the specification's reference (the signatures concatenated), or real leanVM proofs made in process - (`stark::leanvm`, leanVM `1e997c99`, bindings v0.17.0, the one release + (`stark::leanvm`, leanVM `351f7ae4`, bindings v0.19.0, the one release pq-devnet-1 runs for signer, prover and verifier; `lean_vm` with its experimental prover). `run_node` installs leanVM as soon as `--network` resolves to a network that schedules PQ, on diff --git a/Cargo.lock b/Cargo.lock index 80e1c18c7..18bcc9fd6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -55,13 +55,13 @@ dependencies = [ [[package]] name = "aggregation" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "claims", "fiat_shamir_prover", "isa", "keccak256", - "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", "lean_sphincs", "lean_xmss", "stable_lean_vm_core", @@ -1112,7 +1112,7 @@ dependencies = [ [[package]] name = "claims" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "lean_sphincs", "lean_xmss", @@ -2088,7 +2088,7 @@ dependencies = [ "ethlambda-types", "hex", "keccak 0.1.6", - "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", "lean_xmss", "leanvm", "pbkdf2", @@ -2653,7 +2653,7 @@ dependencies = [ [[package]] name = "experimental_dispatch" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_lean_vm_core", "experimental_lean_vm_core_armaes", @@ -2670,7 +2670,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs", @@ -2683,7 +2683,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_armaes", @@ -2696,7 +2696,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_armsha3", @@ -2709,7 +2709,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_x86avx2", @@ -2722,7 +2722,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_x86v3clmul", @@ -2735,7 +2735,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_x86v3gfni", @@ -2748,7 +2748,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_x86v4", @@ -2761,7 +2761,7 @@ dependencies = [ [[package]] name = "experimental_keccak_gkr_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_pcs_x86v4gfni", @@ -2774,7 +2774,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr", "experimental_parallel", @@ -2789,7 +2789,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_armaes", "experimental_parallel", @@ -2804,7 +2804,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_armsha3", "experimental_parallel", @@ -2819,7 +2819,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_x86avx2", "experimental_parallel", @@ -2834,7 +2834,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_x86v3clmul", "experimental_parallel", @@ -2849,7 +2849,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_x86v3gfni", "experimental_parallel", @@ -2864,7 +2864,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_x86v4", "experimental_parallel", @@ -2879,7 +2879,7 @@ dependencies = [ [[package]] name = "experimental_lean_vm_core_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_keccak_gkr_x86v4gfni", "experimental_parallel", @@ -2894,7 +2894,7 @@ dependencies = [ [[package]] name = "experimental_parallel" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "libc", ] @@ -2902,7 +2902,7 @@ dependencies = [ [[package]] name = "experimental_pcs" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives", @@ -2914,7 +2914,7 @@ dependencies = [ [[package]] name = "experimental_pcs_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_armaes", @@ -2926,7 +2926,7 @@ dependencies = [ [[package]] name = "experimental_pcs_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_armsha3", @@ -2938,7 +2938,7 @@ dependencies = [ [[package]] name = "experimental_pcs_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_x86avx2", @@ -2950,7 +2950,7 @@ dependencies = [ [[package]] name = "experimental_pcs_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_x86v3clmul", @@ -2962,7 +2962,7 @@ dependencies = [ [[package]] name = "experimental_pcs_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_x86v3gfni", @@ -2974,7 +2974,7 @@ dependencies = [ [[package]] name = "experimental_pcs_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_x86v4", @@ -2986,7 +2986,7 @@ dependencies = [ [[package]] name = "experimental_pcs_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "experimental_primitives_x86v4gfni", @@ -2998,7 +2998,7 @@ dependencies = [ [[package]] name = "experimental_primitives" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover", @@ -3008,7 +3008,7 @@ dependencies = [ [[package]] name = "experimental_primitives_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_armaes", @@ -3018,7 +3018,7 @@ dependencies = [ [[package]] name = "experimental_primitives_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_armsha3", @@ -3028,7 +3028,7 @@ dependencies = [ [[package]] name = "experimental_primitives_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_x86avx2", @@ -3038,7 +3038,7 @@ dependencies = [ [[package]] name = "experimental_primitives_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_x86v3clmul", @@ -3048,7 +3048,7 @@ dependencies = [ [[package]] name = "experimental_primitives_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_x86v3gfni", @@ -3058,7 +3058,7 @@ dependencies = [ [[package]] name = "experimental_primitives_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_x86v4", @@ -3068,7 +3068,7 @@ dependencies = [ [[package]] name = "experimental_primitives_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "experimental_parallel", "fiat_shamir_prover_x86v4gfni", @@ -3165,7 +3165,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", "verifier", @@ -3174,7 +3174,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_armaes", "verifier", @@ -3183,7 +3183,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_armsha3", "verifier", @@ -3192,7 +3192,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_x86avx2", "verifier", @@ -3201,7 +3201,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_x86v3clmul", "verifier", @@ -3210,7 +3210,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_x86v3gfni", "verifier", @@ -3219,7 +3219,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_x86v4", "verifier", @@ -3228,7 +3228,7 @@ dependencies = [ [[package]] name = "fiat_shamir_prover_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256_x86v4gfni", "verifier", @@ -4182,7 +4182,7 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "isa" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "verifier", ] @@ -4358,42 +4358,42 @@ dependencies = [ [[package]] name = "keccak256" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_armaes" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_armsha3" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_x86avx2" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_x86v3clmul" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_x86v3gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_x86v4" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "keccak256_x86v4gfni" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "konst" @@ -4456,7 +4456,7 @@ dependencies = [ [[package]] name = "lean_da" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", "stable_pcs", @@ -4481,7 +4481,7 @@ dependencies = [ [[package]] name = "lean_sphincs" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", ] @@ -4489,13 +4489,13 @@ dependencies = [ [[package]] name = "lean_vm" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "aggregation", "claims", "experimental_dispatch", "isa", - "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69)", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", "lean_sphincs", "lean_vrf", "lean_xmss", @@ -4520,7 +4520,7 @@ dependencies = [ [[package]] name = "lean_vrf" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", ] @@ -4528,7 +4528,7 @@ dependencies = [ [[package]] name = "lean_xmss" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", ] @@ -7290,7 +7290,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stable_keccak_gkr" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "fiat_shamir_prover", "stable_parallel", @@ -7303,7 +7303,7 @@ dependencies = [ [[package]] name = "stable_lean_vm_core" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "fiat_shamir_prover", "isa", @@ -7318,12 +7318,12 @@ dependencies = [ [[package]] name = "stable_parallel" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "stable_pcs" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "fiat_shamir_prover", "stable_parallel", @@ -7335,7 +7335,7 @@ dependencies = [ [[package]] name = "stable_primitives" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "fiat_shamir_prover", "isa", @@ -8054,7 +8054,7 @@ dependencies = [ [[package]] name = "verifier" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "version_check" @@ -8960,7 +8960,7 @@ dependencies = [ [[package]] name = "zkdsl_compiler" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=1e997c9927d3e7fafa2b813734f56e25d7a4da69#1e997c9927d3e7fafa2b813734f56e25d7a4da69" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "isa", "keccak256", diff --git a/Cargo.toml b/Cargo.toml index c3da37855..05a8eb9a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -133,17 +133,17 @@ keccak = "0.1.6" # attestation proofs as the PQ devnet makes them, real leanVM STARKs over # leanXMSS signatures rather than the specification's concatenation # (`ethlambda_crypto::stark`); and leanVM's leanXMSS, which signs and verifies. -# Pinned to bindings v0.17.0 (1e997c99), the one release pq-devnet-1 runs for -# its signer, prover and verifier: a proof from another revision does not -# verify, and nothing on the wire says why. `experimental_prover` is the -# prover the pq-devnet-0 sidecar ran; it makes the same proofs as the stable -# one, faster. leanVM's `cpu_tiers` is not enabled: it needs leanVM's -# `scripts/tier-rustc` as `RUSTC_WRAPPER`, and the node's own CPU baseline -# (`.cargo/config.toml`) already gives the prover its carryless multiply. +# Pinned to bindings v0.19.0 (351f7ae4), the one release pq-devnet-1 runs for +# its signer, prover and verifier; the devnet takes no other revision. +# `experimental_prover` is the prover the pq-devnet-0 sidecar ran; it makes +# the same proofs as the stable one, faster. leanVM's `cpu_tiers` is behind +# `ethlambda-crypto`'s `leanvm-cpu-tiers` feature, off by default: it only +# does anything under leanVM's `scripts/tier-rustc` as `RUSTC_WRAPPER`, which +# the Dockerfile sets. # Not the `leanvm` revision below, which lean consensus proves with. -leanvm_prover = { package = "lean_vm", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69", features = ["experimental_prover"] } -leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69" } -leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "1e997c9927d3e7fafa2b813734f56e25d7a4da69" } +leanvm_prover = { package = "lean_vm", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80", features = ["experimental_prover"] } +leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80" } +leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80" } # XMSS signatures + recursive aggregation, through leanVM's own facade crate: # it re-exports the aggregation API, the `xmss` module (keys, signing, and the diff --git a/Dockerfile b/Dockerfile index a459dda5e..1b2650b0e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -100,7 +100,7 @@ LABEL org.opencontainers.image.version=$VERSION # Copy ethlambda over from the build stage COPY --from=builder /app/ethlambda /usr/local/bin # pq-devnet-0's launcher name, `ethlambda-pq beacon `, kept for -# launchers that still use it. leanVM bindings v0.17.0 proves in the node, so +# launchers that still use it. Since bindings v0.17.0 leanVM proves in the node, so # there is no sidecar to start: the script only runs `ethlambda`. The leanVM # revision the node proves with is the one in `leanvm-revision`. COPY --chmod=755 bin/ethlambda/pq/ethlambda-pq /usr/local/bin/ethlambda-pq diff --git a/bin/ethlambda/pq/ethlambda-pq b/bin/ethlambda/pq/ethlambda-pq index ce6e952c9..c29282897 100755 --- a/bin/ethlambda/pq/ethlambda-pq +++ b/bin/ethlambda/pq/ethlambda-pq @@ -3,9 +3,10 @@ # `, as ethereum-package's pq branch runs it) still starts the node. # # pq-devnet-0 ran leanVM's prover as a separate `leanvm-sidecar`, which this -# script started and supervised. leanVM bindings v0.17.0, pq-devnet-1's -# release, removed the sidecar: the node proves in process on a network that -# schedules the PQ fork, so this script only runs `ethlambda `. +# script started and supervised. leanVM bindings v0.17.0 removed the sidecar: +# the node proves in process on a network that schedules the PQ fork +# (pq-devnet-1 runs bindings v0.19.0), so this script only runs +# `ethlambda `. # # LEANVM_THREADS, the sidecar's thread count, is still honored: it becomes # `--pq-prover-threads` (0, the default: one per core). LEANVM_SIDECAR and diff --git a/bin/ethlambda/src/cli.rs b/bin/ethlambda/src/cli.rs index 88be49357..5f86eec0e 100644 --- a/bin/ethlambda/src/cli.rs +++ b/bin/ethlambda/src/cli.rs @@ -423,7 +423,7 @@ pub(crate) struct MainnetOptions { /// How many threads leanVM's in-process prover runs on, 0 for one per /// core. Read only on a network that schedules the PQ fork, whose /// attestation proofs this node makes and checks with leanVM (bindings - /// v0.17.0) in process. + /// v0.19.0) in process. #[arg(long, default_value_t = 0)] pub(crate) pq_prover_threads: usize, diff --git a/bin/ethlambda/src/pq_prover_check.rs b/bin/ethlambda/src/pq_prover_check.rs index 165bcad05..651b6a893 100644 --- a/bin/ethlambda/src/pq_prover_check.rs +++ b/bin/ethlambda/src/pq_prover_check.rs @@ -17,7 +17,7 @@ use std::time::Duration; use ethlambda_crypto::stark::leanvm::{ - LEANVM_REV, LeanVmBackend, LeanVmConfig, MAX_SELF_CHECK_SIGNATURES, + LEANVM_REV, LeanVmBackend, LeanVmConfig, MAX_SELF_CHECK_SIGNATURES, PROTOCOL_VERSION, }; use ethlambda_types::beacon::config::Config; use eyre::WrapErr as _; @@ -79,6 +79,7 @@ pub(crate) fn run(options: PqProverCheckOptions) -> eyre::Result<()> { slowest_ms, budget_ms, leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, "One aggregate of this size fits a seat's proving window on a 12-second slot" ); } else { @@ -87,6 +88,7 @@ pub(crate) fn run(options: PqProverCheckOptions) -> eyre::Result<()> { slowest_ms, budget_ms, leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, "One aggregate of this size does not fit a seat's proving window on a 12-second \ slot: this host would miss its aggregates" ); diff --git a/crates/common/crypto/src/lib.rs b/crates/common/crypto/src/lib.rs index 5bf70f883..2742eeddb 100644 --- a/crates/common/crypto/src/lib.rs +++ b/crates/common/crypto/src/lib.rs @@ -48,7 +48,7 @@ pub mod bls; /// The Beacon Chain PQ fork's leanXMSS signatures (the specification's `xmss` /// module), over Keccak-256. Not the XMSS of [`signature`]. pub mod lean_xmss; -/// leanVM's own leanXMSS (bindings v0.17.0): what a validator signs with and +/// leanVM's own leanXMSS (bindings v0.19.0): what a validator signs with and /// what [`lean_xmss::verify`] runs, re-exported so a signer depends on one pin. pub use leanvm_lean_xmss; mod metrics; diff --git a/crates/common/crypto/src/stark.rs b/crates/common/crypto/src/stark.rs index 2e1b7690c..3d2b0d738 100644 --- a/crates/common/crypto/src/stark.rs +++ b/crates/common/crypto/src/stark.rs @@ -8,7 +8,7 @@ //! statement in public-key order, and verification checks each in turn. It //! is what the specification's fixtures use. //! - **leanVM** ([`install_leanvm`]): real leanVM proofs, made and checked -//! in this process (bindings v0.17.0), as the PQ devnet's other clients make +//! in this process (bindings v0.19.0), as the PQ devnet's other clients make //! them. See [`leanvm`]. //! //! The two encodings are not interchangeable: a node verifies only the proofs diff --git a/crates/common/crypto/src/stark/leanvm.rs b/crates/common/crypto/src/stark/leanvm.rs index af85cc2ba..3d8f3aaa3 100644 --- a/crates/common/crypto/src/stark/leanvm.rs +++ b/crates/common/crypto/src/stark/leanvm.rs @@ -1,5 +1,5 @@ //! Attestation proofs made and checked by leanVM in this process (bindings -//! v0.17.0, [`LEANVM_REV`]). +//! v0.19.0, [`LEANVM_REV`]). //! //! The PQ devnet does not run the specification's reference concatenation: //! its clients prove with leanVM. pq-devnet-0 did it through a separate @@ -45,9 +45,14 @@ use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; /// The most children one aggregate takes (leanVM's `MAX_RECURSIONS`). pub const MAX_CHILDREN_PER_AGGREGATE: usize = leanvm_prover::MAX_RECURSIONS; +/// leanVM's own count of its STARK-breaking changes: proofs and signatures +/// verify between two builds exactly when this is the same in both. What to +/// compare with another client's when a proof of theirs does not verify. +pub const PROTOCOL_VERSION: u32 = leanvm_prover::PROTOCOL_VERSION; + /// The leanVM revision the workspace proves and verifies with (bindings -/// v0.17.0). Every node of a network must run the same one. -pub const LEANVM_REV: &str = "1e997c9927d3e7fafa2b813734f56e25d7a4da69"; +/// v0.19.0). Every node of a network must run the same one. +pub const LEANVM_REV: &str = "351f7ae421529ce164ed747eee1f78bdeaec3e80"; #[derive(Debug, thiserror::Error)] pub enum Error { @@ -117,7 +122,8 @@ impl From for ProveError { #[derive(Debug, Clone, PartialEq, Eq)] pub struct LeanVmConfig { - /// How many threads leanVM's prover pool runs, 0 for one per core. + /// How many threads leanVM's prover pool runs, 0 for one per physical + /// core. pub threads: usize, /// `log_inv_rate` of the proofs made, within leanVM's bounds: a higher /// rate gives smaller proofs that take longer to make. A proof verifies @@ -148,7 +154,10 @@ impl LeanVmBackend { /// Takes about a second; call once. /// /// More threads than the machine has cores are lowered to the cores, - /// with a warning: leanVM would oversubscribe them. + /// with a warning: leanVM would oversubscribe them. Setup also picks the + /// prover's CPU tier (since bindings v0.18.0), so a build that leaves + /// some of this CPU unused says so on stderr here, not at the first + /// proof. pub fn setup(config: LeanVmConfig) -> Result { let rate = usize::from(config.log_inv_rate); if !(leanvm_prover::MIN_LOG_INV_RATE..=leanvm_prover::MAX_LOG_INV_RATE).contains(&rate) { @@ -172,6 +181,7 @@ impl LeanVmBackend { threads, log_inv_rate = config.log_inv_rate, leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, setup_ms, self_check_prove_ms = check.prove.as_millis() as u64, self_check_verify_ms = check.verify.as_millis() as u64, diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index a8831f7e6..f57f9a574 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -54,7 +54,7 @@ changes. | Layer | Where | Status | | --- | --- | --- | | leanXMSS sign/verify | `ethlambda_crypto::lean_xmss` | KAT-pinned against consensus-specs and leanVM | -| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs made in process (bindings v0.17.0) on a network that schedules PQ (see [Proofs](#proofs)) | +| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs made in process (bindings v0.19.0) on a network that schedules PQ (see [Proofs](#proofs)) | | Containers | `ethlambda_types::beacon::containers::{eip8483, pq}` | SSZ round trips, gaps per the spec; the maximal aggregate, attester slashing and bid encode to `pq.yaml`'s size bounds | | Fork upgrades | `upgrade::{upgrade_to_eip8483, upgrade_to_pq}` | unit-tested | | Block processing | `stf::{eip8483, pq}` | unit-tested with real XMSS keys | @@ -149,8 +149,8 @@ proofs through one of two backends, chosen once per process: about 436 signatures per block. The specification's fixtures use it, and so does any process that never installs leanVM. - **leanVM** (`stark::install_leanvm`, `stark::leanvm`): real leanVM proofs, - made and checked in this process by `lean_vm` at `1e997c99` (bindings - v0.17.0, `leanvm::LEANVM_REV`), the one release pq-devnet-1 runs for its + made and checked in this process by `lean_vm` at `351f7ae4` (bindings + v0.19.0, `leanvm::LEANVM_REV`), the one release pq-devnet-1 runs for its signer, prover and verifier. A statement list maps to leanVM claims as Lighthouse maps it: the sorted, deduplicated `(public key, message)` pairs, the empty proof for no claims, and merges folded sixteen children @@ -480,7 +480,7 @@ asks for again. ethpandaops/ethereum-package's `pq` branch runs PQ-at-genesis devnets with ethlambda as beacon node, validator client or both. This branch targets pq-devnet-1 (`notes.ethereum.org/@ethpandaops/pq-devnet-1`): consensus-specs -`pq` at `4c296784` and leanVM bindings v0.17.0, which every client must run, +`pq` at `4c296784` and leanVM bindings v0.19.0, which every client must run, since proofs from another revision do not verify. 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 diff --git a/docs/cli.md b/docs/cli.md index 81490bb00..5d70b2a2e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -165,7 +165,7 @@ something specific here. |---|---|---| | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | -| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.17.0 (`1e997c99`, the release pq-devnet-1 runs; a proof from another revision does not verify). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | +| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.19.0 (`351f7ae4`, the release pq-devnet-1 runs, and the only one it takes). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index 38515fec7..18d1ca234 100644 --- a/docs/spec_deviations.md +++ b/docs/spec_deviations.md @@ -1125,7 +1125,7 @@ Two more: The specification's `stark.VerifyAggregates` checks each signature at its statement's leaf index, and its reference implementation does (a proof is the signatures concatenated). The PQ devnet's clients prove with leanVM -instead, in process from bindings v0.17.0 (`ethlambda_crypto::stark::leanvm`, +instead, in process from bindings v0.19.0 (`ethlambda_crypto::stark::leanvm`, installed on any network that schedules PQ), and a leanVM proof attests only `(public key, message)` claims (leanEthereum/leanVM#787). So under the leanVM backend a proof shows each key signed the message at *some* leaf, diff --git a/leanvm-revision b/leanvm-revision index 54105bf76..75f098b90 100644 --- a/leanvm-revision +++ b/leanvm-revision @@ -1 +1 @@ -1e997c9927d3e7fafa2b813734f56e25d7a4da69 +351f7ae421529ce164ed747eee1f78bdeaec3e80 From 065f80e552af8cd51a3207c43278933b38a957f7 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Thu, 26 Nov 2026 19:36:49 -0300 Subject: [PATCH 22/25] feat(validator): publish each PQ attestation as soon as it is signed pq-devnet-1 asks clients to sign in parallel on every core and publish each attestation as it is signed, not once the whole batch is done: pq-devnet-0's attestations went out five to ten seconds into the slot that way and missed the aggregation cutoff. ethlambda already signed a duty's keys in parallel, and then published the batch in one request. Normally that is a few signatures' time, but a key that has to build a bottom tree at signing time takes seconds, and every other key's vote waited for it. pq::sign_each hands each signature over the moment it exists (one leaf record flush for the batch, as before). AttestationService publishes it with whatever else was signed by then, each request on its own, so none waits for a slower key or for an earlier request's answer. Failing every request is the error the single request used to be; failing some is logged and the rest count as published. Other forks, and PQ's PTC votes and aggregates, publish as before. --- CLAUDE.md | 3 +- crates/validator/src/attestation.rs | 223 ++++++++++++++++++++++++---- crates/validator/src/metrics.rs | 4 + crates/validator/src/pq.rs | 102 +++++++++++-- docs/beacon_pq.md | 7 +- 5 files changed, 298 insertions(+), 41 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 444ebde41..8de3b50a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -911,7 +911,8 @@ transitions are in `ethlambda-types`, per the section above. Nothing above `pq` branch, see `docs/beacon_pq.md`, "Running a devnet"), with its own validators: the validator client derives each validator's leanXMSS key and VRF seed from its BLS key - (`ethlambda_crypto::pq_keys`) and attests, aggregates (staggered by its seat + (`ethlambda_crypto::pq_keys`) and attests (each vote published as soon as + it is signed, `pq::sign_each`, not once the batch is), aggregates (staggered by its seat in the aggregation committee, each seat on its own; the node skips a seat's proof when an earlier seat of its own already proved every vote collected), casts PTC votes and proposes, each signature at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all diff --git a/crates/validator/src/attestation.rs b/crates/validator/src/attestation.rs index 072263a22..5d26debe3 100644 --- a/crates/validator/src/attestation.rs +++ b/crates/validator/src/attestation.rs @@ -288,34 +288,16 @@ impl AttestationService { // the full budget after the attestation offset (see // `SIGNING_BUDGET` for what that leaves before aggregation). // - // From PQ a leanXMSS signature at the target epoch's leaf, over the - // same signing root: the slashing protection record above already - // guards that leaf (one per target epoch). Those keys are derived from - // local keystores at startup, so they sign here, with no round trip, - // in parallel off this task (`pq::sign_all`). - let signatures: Vec> = { - let _timing = crate::metrics::time_signing(); - if is_pq { - let root = self.context.attestation_signing_root(&data); - let leaf = crate::pq::attestation_leaf(data.target.epoch); - let requests = to_sign - .iter() - .map(|(_, pubkey)| crate::pq::SignRequest { - pubkey: *pubkey, - leaf, - root, - }) - .collect(); - crate::pq::sign_all(requests) - .await - .into_iter() - .map(|signature| { - signature - .map(|signature| encode_hex(&signature.0)) - .map_err(|err| err.to_string()) - }) - .collect() - } else { + // From PQ the keys are leanXMSS ones derived from local keystores, + // and nothing is published whole: see `publish_pq_as_signed`. + if is_pq { + return self + .publish_pq_as_signed(slot, &to_sign, data, &data_dto, fork_name, refused) + .await; + } + let signatures: Vec> = + { + let _timing = crate::metrics::time_signing(); sign_all(to_sign.iter().map(|(_, pubkey)| { (*pubkey, self.context.sign_attestation(store, pubkey, &data)) })) @@ -327,8 +309,7 @@ impl AttestationService { .map_err(|err| err.to_string()) }) .collect() - } - }; + }; let mut attestations = Vec::with_capacity(to_sign.len()); for ((duty, _), signature) in to_sign.iter().zip(signatures) { @@ -378,6 +359,136 @@ impl AttestationService { data: Some(data), }) } + + /// The PQ fork's half of [`Self::attest_with`]: signs `to_sign`'s + /// attestations with leanXMSS at the target epoch's leaf, which the + /// slashing protection record already guards (one per target epoch), and + /// publishes each as soon as its signature exists. + /// + /// Not once the batch is signed. The keys sign in parallel, so a batch + /// is normally a few signatures' time away, but a key that has to build a + /// bottom tree first takes seconds, and a vote held for it misses the + /// aggregators' cutoff with it: pq-devnet-0's clients published five to + /// ten seconds into the slot that way. A signature goes out with whatever + /// else was signed by the time it is picked up, so the requests are as + /// few as the signing is fast, and none waits for a slower key or for an + /// earlier request's answer. + /// + /// Failing every request is the error the batch's one request used to + /// be; failing some is logged, and the rest count as published. + async fn publish_pq_as_signed( + &self, + slot: Slot, + to_sign: &[(&AttesterDutyDto, BlsPubkey)], + data: AttestationData, + data_dto: &AttestationDataOutDto, + fork_name: &str, + refused: usize, + ) -> Result { + use futures_util::stream::{FuturesUnordered, StreamExt as _}; + + let root = self.context.attestation_signing_root(&data); + let leaf = crate::pq::attestation_leaf(data.target.epoch); + let requests = to_sign + .iter() + .map(|(_, pubkey)| crate::pq::SignRequest { + pubkey: *pubkey, + leaf, + root, + }) + .collect(); + // Observed when the last signature is in, as the batch's timing was. + let mut timing = Some(crate::metrics::time_signing()); + let mut signed = crate::pq::sign_each(requests); + let mut requests_out = FuturesUnordered::new(); + let (mut answered, mut submitted, mut published) = (0usize, 0usize, 0usize); + let mut failure = None; + loop { + tokio::select! { + next = signed.recv(), if timing.is_some() => { + let Some(first) = next else { + timing = None; + continue; + }; + let mut ready = vec![first]; + while let Ok(more) = signed.try_recv() { + ready.push(more); + } + answered += ready.len(); + let attestations: Vec = ready + .into_iter() + .filter_map(|(position, signature)| { + let (duty, _) = to_sign[position]; + // One validator failing must not cost the others + // their attestation. + let signature = signature + .inspect_err(|err| { + error!(%slot, validator = duty.validator_index, %err, "Failed to sign attestation"); + crate::metrics::inc_signing_failures(); + }) + .ok()?; + Some(SingleAttestationDto { + committee_index: duty.committee_index, + attester_index: duty.validator_index, + data: data_dto.clone(), + signature: encode_hex(&signature.0), + }) + }) + .collect(); + if attestations.is_empty() { + continue; + } + submitted += attestations.len(); + requests_out.push(async move { + self.beacon_node + .submit_attestations(&attestations, fork_name) + .await + }); + } + Some(answer) = requests_out.next(), if !requests_out.is_empty() => match answer { + Ok(count) => published += count, + Err(err) => { + warn!(%slot, %err, "Failed to publish some of this slot's attestations"); + failure = Some(err); + } + }, + else => break, + } + } + if answered < to_sign.len() { + // The signing task died before answering for these. + let unsigned = to_sign.len() - answered; + error!(%slot, unsigned, "The PQ signing task ended before signing every attestation"); + crate::metrics::inc_signing_failures_by(unsigned as u64); + } + if submitted == 0 { + return Ok(Attested { + published: 0, + refused, + data: Some(data), + }); + } + if published == 0 + && let Some(err) = failure + { + return Err(err); + } + if published < submitted { + warn!( + %slot, + published, + submitted, + "Some attestations in this slot's batch were rejected by the beacon node" + ); + } + info!(%slot, count = published, "Published attestations"); + crate::metrics::inc_attestations_published(published as u64); + Ok(Attested { + published, + refused, + data: Some(data), + }) + } } #[cfg(test)] @@ -734,6 +845,58 @@ mod tests { assert_eq!(data.target.epoch, 3); } + /// At a PQ slot each attestation is published as soon as it is signed: + /// every one exactly once, however many requests that took, with a + /// leanXMSS signature, and a validator whose signature fails costs only + /// its own vote. + #[tokio::test] + async fn pq_attestations_are_each_published_once_and_a_failure_costs_one_vote() { + use ethlambda_types::beacon::fork::ForkName; + + let mut keyless_secret = secret(); + keyless_secret[31] ^= 0x02; + let mut store = ValidatorStore::new(); + let first = store.insert_secret("first", &secret()).expect("inserts"); + let second = store + .insert_secret("second", &other_secret()) + .expect("inserts"); + let keyless = store + .insert_secret("keyless", &keyless_secret) + .expect("inserts"); + // A PQ client derives a leanXMSS key for each local key at startup. + // The third never got one, so its signature fails. + crate::pq::derive_and_register(first, &secret(), 0, None); + crate::pq::derive_and_register(second, &other_secret(), 0, None); + let store = RwLock::new(store); + + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 0); + let context = Arc::new(SigningContext::new(config, Root::ZERO)); + let node = Arc::new(MockBeaconNode::new().with_attestation_data(96)); + let service = + AttestationService::new(node.clone(), context, SlashingProtection::in_memory()); + let duties = [ + duty(&encode_hex(&first.0), 11, 96, 3), + duty(&encode_hex(&second.0), 12, 96, 3), + duty(&encode_hex(&keyless.0), 13, 96, 3), + ]; + + let attested = service.attest(96, &duties, &store).await.expect("attests"); + + assert_eq!(attested.published, 2); + assert_eq!(attested.data.expect("data").slot, 96); + let submitted = node.submitted(); + let mut attesters: Vec = submitted.iter().map(|vote| vote.attester_index).collect(); + attesters.sort_unstable(); + assert_eq!( + attesters, + vec![11, 12], + "each signed vote once, the unsigned one never" + ); + let hex_len = 2 + 2 * ethlambda_crypto::lean_xmss::SIGNATURE_SIZE; + assert!(submitted.iter().all(|vote| vote.signature.len() == hex_len)); + assert_eq!(node.last_submitted_fork_name().as_deref(), Some("pq")); + } + /// With no duty there is nothing to fetch, so there is no data either. /// A zeroed default here would have the aggregation duty ask for the /// aggregate of an attestation nobody made. diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index 9c24d3d8a..9fa795569 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -559,6 +559,10 @@ pub fn inc_signing_failures() { SIGNING_FAILURES_TOTAL.inc(); } +pub fn inc_signing_failures_by(count: u64) { + SIGNING_FAILURES_TOTAL.inc_by(count); +} + pub fn inc_attestations_refused() { ATTESTATIONS_REFUSED_TOTAL.inc(); } diff --git a/crates/validator/src/pq.rs b/crates/validator/src/pq.rs index a28997955..efa59fcdb 100644 --- a/crates/validator/src/pq.rs +++ b/crates/validator/src/pq.rs @@ -85,7 +85,8 @@ pub const VRF_TREE_DIRECTORY: &str = "pq_vrf_trees"; /// leanXMSS trees, one file per validator, named by its BLS public key: /// [`TREE_FILE_MAGIC`], the key's public key, leanVM's `cache_to_bytes` (the /// top tree's cached level and that of every bottom tree the key holds, at -/// most `MAX_CACHED_BOTTOM_TREES`; about 25 KB), then an HMAC-SHA256 tag over +/// most `DEFAULT_BOTTOM_TREE_CACHE_SIZE`, eight since leanVM bindings v0.19.0; +/// about 46 KB), then an HMAC-SHA256 tag over /// all of it under a key derived from the XMSS seed ([`tree_mac_key`]), so /// only a file this client wrote for this seed loads. Lighthouse's and /// Teku's PQ branches keep the same thing the same way. Written whenever a @@ -961,6 +962,23 @@ pub struct SignRequest { /// the async runtime. pub fn sign_batch(requests: &[SignRequest]) -> Vec> { use rayon::prelude::*; + let checked = claim_batch(requests); + requests + .par_iter() + .zip(checked) + .map(|(request, checked)| { + let (key, leaf_index) = checked?; + Ok(sign_claimed(request, &key, leaf_index)) + }) + .collect() +} + +/// Each request's key and leaf, with the leaf claimed for its root in the +/// durable record: what happens before any signature of a batch exists, one +/// write and one flush for all of it. A request whose key is unknown, whose +/// leaf is out of range or already spent on another root is an error at its +/// position, and claims nothing. +fn claim_batch(requests: &[SignRequest]) -> Vec, u32), PqSignError>> { let mut checked: Vec, u32), PqSignError>> = requests .iter() .map(|request| { @@ -987,14 +1005,7 @@ pub fn sign_batch(requests: &[SignRequest]) -> Vec) -> Vec, +) -> tokio::sync::mpsc::UnboundedReceiver<(usize, Result)> { + let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); + if requests.is_empty() { + return receiver; + } + tokio::task::spawn_blocking(move || { + use rayon::prelude::*; + let checked = claim_batch(&requests); + requests + .par_iter() + .zip(checked) + .enumerate() + .for_each(|(position, (request, checked))| { + let signed = + checked.map(|(key, leaf_index)| sign_claimed(request, &key, leaf_index)); + // A receiver that is gone abandoned the duty, as when its + // slot ended: the leaf is spent either way. + let _ = sender.send((position, signed)); + }); + }); + receiver +} + /// One [`sign_all`] signature. pub async fn sign(pubkey: &BlsPubkey, leaf: u64, root: Root) -> Result { let request = SignRequest { @@ -1095,6 +1141,44 @@ mod tests { assert_ne!(attestation_leaf(0) >> 16, slot_leaf(0, 0) >> 16); } + /// `sign_each` answers every request once, at its position, with the + /// signature the batch signer makes, and an unsignable request is an + /// error at its own position only. + #[tokio::test] + async fn each_signature_is_handed_over_once_at_its_position() { + let pubkey = BlsPubkey([41; 48]); + derive_and_register(pubkey, &[41; 32], 0, None); + let leaf = attestation_leaf(3); + let root = Root::from([5; 32]); + let known = SignRequest { pubkey, leaf, root }; + let unknown = SignRequest { + pubkey: BlsPubkey([42; 48]), + leaf, + root, + }; + + let mut signed = sign_each(vec![unknown, known]); + let mut answers = Vec::new(); + while let Some(answer) = signed.recv().await { + answers.push(answer); + } + answers.sort_by_key(|(position, _)| *position); + + assert_eq!(answers.len(), 2); + assert!(matches!( + answers[0], + (0, Err(PqSignError::UnknownValidator)) + )); + let (1, Ok(signature)) = &answers[1] else { + panic!("the known key signs at position 1"); + }; + // Signing is deterministic: the batch signer gives the same bytes. + let batch = sign_batch(&[known]); + assert_eq!(batch[0].as_ref().expect("signs").0, signature.0); + // No requests, no answers. + assert!(sign_each(Vec::new()).recv().await.is_none()); + } + #[test] fn a_request_key_maps_back_and_a_leaf_signs_once() { let secret = [7u8; 32]; diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index f57f9a574..5e8120965 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -418,7 +418,12 @@ A start drops the leaves of slots more than two epochs back, which nothing asks for again. - **Attesting**: a `SingleAttestation` signed at the target epoch's leaf, - published on one of PQ's 16 subnets. The client votes once a beacon node + published on one of PQ's 16 subnets. Each one is published as soon as its + signature exists (`AttestationService::publish_pq_as_signed`, + `pq::sign_each`), with whatever else was signed by then, not once the + slot's batch is signed: a key that has to build a bottom tree first takes + seconds, and held for it, every other key's vote would miss the + aggregators' cutoff too. The client votes once a beacon node reports a non-optimistic `head` at the slot whose block the attestation data names, or at the attestation deadline otherwise (`head_monitor`, as at every fork); it used to wait for the deadline every slot, which put its From 8a64c3c8b55ef713b6eb480c3712ca632a1513b6 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Mon, 30 Nov 2026 17:50:02 -0300 Subject: [PATCH 23/25] feat: follow GAS_LIMIT_SCHEDULE on pq-devnet-1 (validator default + PQ self-build target) (#953) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem pq-devnet-1's `config.yaml` schedules a gas limit of 200M from epoch 0 through `GAS_LIMIT_SCHEDULE` ([EIP-8261](https://eips.ethereum.org/EIPS/eip-8261)). Devops reported that ethlambda votes the gas limit down. The chain shows something more specific: **ethlambda never moves it.** Over slots 20213–23212, each canonical block's gas limit compared with its parent's (Dora's slots API): | Client | Raises | Lowers | Keeps | |---|---|---|---| | lighthouse | 444 | 0 | 0 | | teku | 437 | 0 | 0 | | lodestar | 405 | 0 | 0 | | grandine | 281 | 0 | 0 | | **ethlambda** | 0 | 0 | **272** | | prysm | 0 | 0 | 472 | | nimbus | 0 | 273 | 0 | | silver | 0 | 267 | 0 | | unlabelled proposer | 0 | 102 | 0 | Two things in this branch cause it: 1. **The validator client never reads the schedule.** Its default target gas limit is a fixed 60M, and the ansible deployment doesn't pass `--gas-limit`. It signs 60M into every PQ proposer preference. 2. **The beacon node's PQ self-build ignores the preferences anyway.** `prepare_pq_proposal` builds every PQ payload toward `parent_bid.gas_limit`, so whatever a preference says, ethlambda's own blocks keep the parent's limit. Gloas's self-build does read the preferences (`prepare_gloas_proposal_on`); the PQ one never did. ## What this does ### 1. `GAS_LIMIT_SCHEDULE` (port of #873) **Beacon node:** - Parses `GAS_LIMIT_SCHEDULE` into `Config` and serves it on `/eth/v1/config/spec`. - Stores it in a `Metadata` row of its own, so the `config` row's encoding and `DB_VERSION` (10) don't change. - A directory written before this change resumes and gains the row. **Validator client:** - `--gas-limit` no longer has a default. - Each validator's gas limit resolves in this order: its own override, then `--gas-limit`, then the schedule's value for the duty's epoch, then 60M. - The epoch is the proposal's for preferences, BLS and PQ alike. `publish_pq_epoch` is a call site #873 never saw. **Differences from #873:** - **No chain check:** this branch doesn't have it (#854). The schedule is followed by a small module of its own instead; see part 3. - **Test helper:** `gas_limit_schedule_text` moved from `chain_check` to `proposer_settings`. - **`dto` tests:** they use a local `spec_with` in place of main's `complete_spec`, since this branch's spec parser accepts absent keys. - **Docs:** comments that said `DB_VERSION` 7 now say 10. ### 2. PQ payloads follow the proposer's preferences (new) - **The rule:** `prepare_pq_proposal` takes the PQ builder market. When it holds the proposer's own signed preferences for the slot, under the slot's dependent root, it builds toward their `target_gas_limit`, as gloas's self-build does. Otherwise it keeps the parent's limit, as before. - **Callers:** both pass the node's one PQ market: the `pq_blocks` endpoint, and the chain actor's payload preparation ahead of the slot (`PayloadPreparation::pq_builder_market`, wired in `main.rs`). - **Prepared builds:** the actor's `AttributesKey` now includes the PQ preferences, so a build prepared before they arrived is redone. Production and preparation still ask for the same attributes. - **Fee recipient:** unchanged, still `prepare_beacon_proposer`'s. ### 3. The schedule is read off every beacon node, every epoch (review fix) Before this change, the schedule came from whichever node answered the startup `/eth/v1/config/spec`. If that node served no `GAS_LIMIT_SCHEDULE`, or one `check_rules` refuses, every preference targeted 60M until a restart, even with another node serving the right schedule. Nothing was logged. `crates/validator/src/gas_limit_schedule.rs` now: - **Asks every node:** all `--beacon-nodes` at once, taking the first non-empty schedule in that order. - **Repeats every epoch:** it reads at startup and again each epoch on its own task, aborted when the client stops. A node that comes up, or starts serving the key, later is followed without a restart. - **Keeps a held schedule** while no node serves one. A node restarted on an old build is likelier than the network dropping its schedule. - **Warns** when no node serves a schedule while gloas is scheduled and `--gas-limit` is unset, once per run of empty reads. ### Not done EIP-8261 says a client SHOULD warn when an operator's gas limit is above the scheduled value. #873 doesn't, and neither does this. ## Checked - **Real config:** the beacon node from this branch, started on `ethpandaops/pq-devnets`' `network-configs/devnet-1/metadata`, serves `"GAS_LIMIT_SCHEDULE": [{"EPOCH": "0", "GAS_LIMIT": "200000000"}]`, no longer among its ignored keys. - **New tests:** - `a_pq_preference_carries_the_scheduled_gas_limit` (validator). - `a_pq_proposal_takes_the_gas_target_of_its_proposers_own_preferences` (blockchain): the proposer's own preference is used; none held, another validator's, or another dependent root fall back to the parent's limit. - **Reviewer's scenario, real binaries:** a beacon node on pq-devnet-1's config, behind a proxy that strips `GAS_LIMIT_SCHEDULE`, is listed first, then the node itself. The previous build started with `gas_limit_schedule=[]`, silently. This one logs `Took the gas limit schedule a beacon node serves … node=1 schedule=[0: 200000000]`. With only the stripped node it warns `No beacon node serves a usable GAS_LIMIT_SCHEDULE while gloas is scheduled …`. - **`gas_limit_schedule` unit tests:** - the first serving node wins over an empty or down one; - order decides between two serving nodes; - a schedule is followed when it appears, kept when it disappears, and replaced by another; - no answer changes nothing; - the warning is given once per run, and only when it matters. - **Suites:** `cargo test` for `ethlambda-validator`, `ethlambda-types`, `ethlambda-storage` (with `rocksdb`), `ethlambda-rpc`, `ethlambda-blockchain --lib` and the `ethlambda` binary all pass. That includes #873's tests. `make fmt` and `make lint` are clean. - **Not yet run on a devnet.** The expected result is that ethlambda's blocks join the "raises" column, at the usual ~1/1024 per block, toward 200M. --- CLAUDE.md | 19 +- README.md | 2 +- bin/ethlambda/src/main.rs | 152 +++++- bin/ethlambda/src/network/config_file.rs | 82 +++- bin/ethlambda/src/validator.rs | 32 +- .../fixtures/networks/devnet/config.yaml | 4 +- crates/blockchain/src/payload_attributes.rs | 124 ++++- crates/common/types/src/beacon/config.rs | 461 +++++++++++++++++- crates/net/rpc/src/beacon/config.rs | 45 +- crates/net/rpc/src/beacon/pq_proposal.rs | 20 +- crates/storage/src/store.rs | 224 ++++++++- crates/validator/src/beacon_node/dto.rs | 137 +++++- crates/validator/src/beacon_node/fallback.rs | 5 +- crates/validator/src/beacon_node/http.rs | 17 +- crates/validator/src/beacon_node/mock.rs | 16 +- crates/validator/src/gas_limit_schedule.rs | 297 +++++++++++ crates/validator/src/http_api/proposer.rs | 47 +- crates/validator/src/lib.rs | 29 +- crates/validator/src/preferences.rs | 99 +++- crates/validator/src/proposer_settings.rs | 263 ++++++++-- crates/validator/src/registration.rs | 67 ++- docs/beacon_pq.md | 5 +- docs/cli.md | 4 +- docs/data_storage.md | 32 +- docs/rpc.md | 13 +- 25 files changed, 2037 insertions(+), 159 deletions(-) create mode 100644 crates/validator/src/gas_limit_schedule.rs diff --git a/CLAUDE.md b/CLAUDE.md index b703ca42c..557aaab35 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -554,7 +554,15 @@ the next fork the node cannot follow: the first refuses such an anchor with `UnsupportedFork`, the second warns once per scheduled fork for which `ForkName::is_followed` answers no (the one place that says which forks the node follows). The ignored-keys warning only ever names heze's keys and -`GAS_LIMIT_SCHEDULE`/`INCLUSION_LIST_DUE_BPS`. +`INCLUSION_LIST_DUE_BPS`. `GAS_LIMIT_SCHEDULE` (EIP-8261) is a `Config` field +served on `/eth/v1/config/spec` and stored in a `Metadata` row of its own +(`config_gas_limit_schedule`), not in `Metadata["config"]`'s encoding, where it +takes zero bytes. That is the pattern for every `Config` key added after +`DB_VERSION` 10 (`CONFIG_ROWS` in `store.rs`): no version bump, and a directory +that predates the key resumes, with a beacon resume adding the config file's +value (`Store::fill_missing_config_keys`) instead of failing. `ConfigFile::parse` +refuses a schedule with an entry before `GLOAS_FORK_EPOCH`, two at one epoch, +or more than 32 entries. Platåberget (the Glamsterdam testnet) is already past its `GLOAS_FORK_EPOCH`, so its checkpoint anchor is a gloas state: it is accepted, starts with no payload known (head EMPTY), and its first FULL child is held until the anchor's @@ -1033,7 +1041,14 @@ transitions are in `ethlambda-types`, per the section above. Nothing above client do), unconditionally, re-sending each kept one once an epoch (a node holds them in memory only), and `produceBlockV4` carries the boost factor and `--builder-min-bid`. `--gas-limit` sets the target gas limit the preferences - carry, which the node's own gloas payload is built toward. + carry, which the node's own gloas payload is built toward; without it, the + one the beacon node's `GAS_LIMIT_SCHEDULE` names for the proposal's epoch, + else 60M (`gas_limit_schedule`: every node's `/eth/v1/config/spec` is read + at startup and again every epoch, the first non-empty schedule in + `--beacon-nodes` order is handed to `ProposerSettings`, one held is kept + while no node serves one, and a missing one is warned about while gloas is + scheduled and `--gas-limit` unset; an unusable schedule reads as empty, with + a warning). It keeps EIP-3076 minimal-watermark slashing protection in `--validators-dir/slashing_protection.json` (`crate::slashing_protection`), durable before every block (blinded ones included) and attestation signature; diff --git a/README.md b/README.md index 3e8eae4cb..df56ce897 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ beacon node. | `--secrets-dir` | One password file per keystore, named after the validator's public key | | `--suggested-fee-recipient` | Execution address for block rewards, `0x`-prefixed. Optional, but without it the beacon node picks an address that is not yours | | `--graffiti` | Text for proposed blocks, at most 32 bytes | -| `--gas-limit` | The gas limit validators target (default `60000000`). From gloas the beacon node builds this client's own payloads toward it, so set it on a network whose limit is elsewhere. Sepolia and Platåberget schedule `200000000`: pass `--gas-limit 200000000` there (until [#795](https://github.com/lambdaclass/ethlambda/issues/795)) | +| `--gas-limit` | The gas limit validators target. From gloas the beacon node builds this client's own payloads toward it. Without it, the gas limit the network's `GAS_LIMIT_SCHEDULE` names for the proposal's epoch (Sepolia's and Platåberget's name `200000000`, pq-devnet-1's too), else `60000000` | | `--builder-proposals` | Propose builder blocks before gloas: register each validator with the beacon node's builder (`--builder` on an ethlambda node) and sign a blinded block when the builder's bid wins. Off by default. From gloas, with or without it, a node that cannot build the payload itself may build on a builder's p2p bid, and that block is signed | | `--enable-keymanager` | Serve the keymanager API on `--keymanager-port` (default `5062`). Off by default, since it mutates key material | | `--enable-doppelganger-protection` | Sign no attestation or block for a key until the beacon node has seen it stay silent for a full epoch, and stop if another client turns out to be running it. Costs two to three epochs of attestations per start. Off by default | diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 349b83989..e8956b9e0 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -943,6 +943,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { let rpc_sync_status = sync_status.clone(); let rpc_events = events.clone(); let rpc_builder_market = builder_market.clone(); + let rpc_pq_builder_market = pq_builder_market.clone(); let rpc_fee_recipients = fee_recipients.clone(); // The payload builds the chain actor starts ahead of their slots, which // block production collects. @@ -993,7 +994,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { p2p: rpc_p2p, payload_attestation_pool: payload_attestation_pool.clone(), builder_market: rpc_builder_market, - pq_builder_market: pq_builder_market.clone(), + pq_builder_market: rpc_pq_builder_market, sync_committee_pool: sync_committee_pool.clone(), fee_recipients: rpc_fee_recipients, prepared_payloads: rpc_prepared_payloads, @@ -1051,6 +1052,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { ethlambda_blockchain::PayloadPreparation { fee_recipients, builder_market, + pq_builder_market, always_prepare: always_prepare_payload, prepared_payloads, prepared_pq_attestations, @@ -2202,6 +2204,13 @@ fn first_config_difference( max_request_blob_sidecars_electra: _, max_request_data_column_sidecars: _, min_epochs_for_block_requests: _, + + // Advisory, a validator client's default gas limit: the specification + // says it adds no validity rule, so the file's always wins, through + // the caller's `replace_config`. In a directory that predates its + // row, `persisted` already holds the file's + // (`Store::fill_missing_config_keys`). + gas_limit_schedule: _, } = persisted; compare!(preset_base); @@ -2396,13 +2405,23 @@ async fn fetch_initial_beacon_state( .max(state.slot()); let processed_through = compute_epoch_at_slot(processed_slot); - let persisted = store.config(); + // A config key this directory predates has no stored value to + // compare, so it is added from the config file rather than + // refused; `replace_config` below writes it. + let (persisted, added) = store.fill_missing_config_keys(&config); if let Some(difference) = first_config_difference(&persisted, &config, processed_through) { error!(%difference, "Persisted config disagrees with the network config"); return Err(checkpoint_sync::CheckpointSyncError::ConfigChanged { difference }); } + // Only once the resume is accepted: a refused one adds nothing. + for key in &added { + info!( + key, + "Config key this data directory predates; adding the config file's" + ); + } // Not a chain value, so not refused (see `first_config_difference`). if persisted.config_name != config.config_name { warn!( @@ -2430,11 +2449,9 @@ async fn fetch_initial_beacon_state( // Whatever differs now is a value this directory does not // contradict, so the config file wins: the node runs on the // persisted config, and keeping the stored one would leave it on - // the old fork schedule. `replace_config` needs the only handle - // to the cached config, hence the `drop`. - let config_changed = *persisted != config; - drop(persisted); - if config_changed { + // the old fork schedule. A key added above has no row yet, which + // `replace_config` writes too. + if persisted != config || !added.is_empty() { store.replace_config(config.clone()); } @@ -3680,6 +3697,127 @@ validators: ); } + /// `GAS_LIMIT_SCHEDULE` is stored in a `Metadata` row of its own: + /// - a fresh directory writes it, so a reopened one carries the schedule + /// with no config file involved; + /// - a directory that predates the row (written by an older build; + /// simulated here by deleting the row) still resumes, with the key added + /// from the config file and written, and the `config` row unchanged; + /// - a changed schedule in the file is followed and stored. + #[tokio::test] + async fn the_gas_limit_schedule_is_stored_and_added_to_a_directory_that_predates_it() { + use ethlambda_storage::Table; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + // The schedule's row, as `ethlambda_storage`'s `CONFIG_ROWS` names it. + const SCHEDULE_ROW: &[u8] = b"config_gas_limit_schedule"; + let row = |backend: &Arc, key: &[u8]| { + backend + .begin_read() + .unwrap() + .get(Table::Metadata, key) + .unwrap() + }; + + let dir = tempfile::tempdir().unwrap(); + std::fs::copy( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/networks/devnet/config.yaml"), + dir.path().join("config.yaml"), + ) + .unwrap(); + let state = beacon::mainnet_genesis_state().unwrap(); + std::fs::write(dir.path().join("genesis.ssz"), state.to_ssz()).unwrap(); + let backend: Arc = Arc::new(InMemoryBackend::new()); + + // The devnet's file carries an empty schedule; give the loaded config + // one, as a file that schedules a gas limit would. + let first = GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }; + let load = |entries: Vec| { + let mut loaded = network::dir::NetworkDir::load(dir.path()).unwrap(); + loaded.config.gas_limit_schedule = entries.into(); + network::NetworkSource::Loaded(Box::new(loaded)) + }; + + let Ok(fresh) = fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first])).await + else { + panic!("first run anchors"); + }; + assert_eq!(fresh.config().gas_limit_schedule.entries(), [first]); + drop(fresh); + + let stored = Store::from_db_state(backend.clone()) + .expect("reopen") + .expect("populated directory"); + assert_eq!( + stored.config().gas_limit_schedule.entries(), + [first], + "the schedule is read back from its row" + ); + drop(stored); + + // A directory written before the row existed. + assert!( + row(&backend, SCHEDULE_ROW).is_some(), + "the fresh run wrote it" + ); + let config_row = row(&backend, b"config").expect("config row"); + let mut batch = backend.begin_write().unwrap(); + batch + .delete_batch(Table::Metadata, vec![SCHEDULE_ROW.to_vec()]) + .unwrap(); + batch.commit().unwrap(); + let predating = Store::from_db_state(backend.clone()) + .expect("a directory without the row loads") + .expect("populated directory"); + assert!(predating.config().gas_limit_schedule.is_empty()); + drop(predating); + + let Ok(resumed) = + fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first])).await + else { + panic!("a directory that predates the key resumes"); + }; + assert_eq!(resumed.config().gas_limit_schedule.entries(), [first]); + drop(resumed); + assert!( + row(&backend, SCHEDULE_ROW).is_some(), + "the resume writes the key it added" + ); + assert_eq!( + row(&backend, b"config").expect("config row"), + config_row, + "the config row is left as it was" + ); + + // The file schedules another entry. + let second = GasLimitScheduleEntry { + epoch: 200, + gas_limit: 300_000_000, + }; + let Ok(followed) = + fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first, second])).await + else { + panic!("a changed schedule resumes"); + }; + assert_eq!( + followed.config().gas_limit_schedule.entries(), + [first, second] + ); + drop(followed); + let reopened = Store::from_db_state(backend) + .expect("reopen") + .expect("populated directory"); + assert_eq!( + reopened.config().gas_limit_schedule.entries(), + [first, second], + "the changed schedule is stored" + ); + } + /// `churn_limit_quotient` is one of the state-transition fields the /// original field list omitted entirely: a directory with a different /// churn quotient from its config file accepted a different set of diff --git a/bin/ethlambda/src/network/config_file.rs b/bin/ethlambda/src/network/config_file.rs index 166640564..8e642c331 100644 --- a/bin/ethlambda/src/network/config_file.rs +++ b/bin/ethlambda/src/network/config_file.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{Config, GasLimitScheduleError}; use serde::Deserialize; use serde::de::{IgnoredAny, Visitor}; @@ -52,6 +52,11 @@ pub(crate) enum ConfigFileError { (SECONDS_PER_SLOT * 1000) to fit in a u64" )] SlotDurationOverflow { seconds: u64 }, + /// A schedule the specification forbids. Refused rather than read, as + /// Lighthouse refuses it: with two entries at one epoch there is no one + /// gas limit to report for it. + #[error("GAS_LIMIT_SCHEDULE is malformed: {0}")] + GasLimitSchedule(#[from] GasLimitScheduleError), } impl ConfigFile { @@ -65,6 +70,7 @@ impl ConfigFile { document.contains_key("SECONDS_PER_SLOT"), document.contains_key("SLOT_DURATION_MS"), )?; + config.gas_limit_schedule.check(config.gloas_fork_epoch)?; let committee_cap_declared = document.contains_key("X_MAX_COMMITTEE_COUNT_PER_SLOT"); let claimed = config_field_names(); @@ -260,7 +266,6 @@ mod tests { for key in [ "HEZE_FORK_VERSION", "HEZE_FORK_EPOCH", - "GAS_LIMIT_SCHEDULE", "INCLUSION_LIST_DUE_BPS", ] { assert!( @@ -270,6 +275,79 @@ mod tests { } } + #[test] + fn the_gas_limit_schedule_is_claimed_rather_than_ignored() { + // The devnet's is empty, Sepolia's and Platåberget's are not; none is + // reported as ignored any more. + for text in [ + DEVNET, + include_str!("../../assets/sepolia/config.yaml"), + include_str!("../../assets/plataberget/config.yaml"), + ] { + let parsed = ConfigFile::parse(text).unwrap(); + assert!( + !parsed.ignored.iter().any(|key| key == "GAS_LIMIT_SCHEDULE"), + "GAS_LIMIT_SCHEDULE reported as ignored" + ); + } + let sepolia = ConfigFile::parse(include_str!("../../assets/sepolia/config.yaml")).unwrap(); + assert_eq!( + sepolia.config.gas_limit_schedule.gas_limit_at(353_024), + Some(200_000_000) + ); + } + + #[test] + fn a_gas_limit_schedule_the_specification_forbids_is_refused() { + let before_gloas = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 9\n", + " GAS_LIMIT: 100000000\n", + ); + let err = ConfigFile::parse(before_gloas).unwrap_err(); + assert!( + matches!( + err, + ConfigFileError::GasLimitSchedule(GasLimitScheduleError::BeforeGloas { + epoch: 9, + gloas_fork_epoch: 10 + }) + ), + "got {err}" + ); + + let shared_epoch = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 100000000\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 200000000\n", + ); + let err = ConfigFile::parse(shared_epoch).unwrap_err(); + assert!( + matches!( + err, + ConfigFileError::GasLimitSchedule(GasLimitScheduleError::DuplicateEpoch { + epoch: 10 + }) + ), + "got {err}" + ); + + // Starting at the fork itself is allowed. + let from_gloas = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 100000000\n", + " - EPOCH: 11\n", + " GAS_LIMIT: 200000000\n", + ); + ConfigFile::parse(from_gloas).unwrap(); + } + #[test] fn the_gloas_keys_are_claimed_rather_than_ignored() { // GLOAS_* and PAYLOAD_DUE_BPS used to be reported as ignored diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index d0651928f..b1b0b8a42 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -6,9 +6,7 @@ use std::path::PathBuf; use ethlambda_types::beacon::primitives::{Bytes32, ExecutionAddress, H160}; -use ethlambda_validator::proposer_settings::{ - DEFAULT_GAS_LIMIT, GRAFFITI_BYTES, graffiti_from_text, -}; +use ethlambda_validator::proposer_settings::{GRAFFITI_BYTES, graffiti_from_text}; use ethlambda_validator::{BuilderProposals, ValidatorConfig}; use eyre::WrapErr as _; @@ -81,17 +79,14 @@ pub(crate) struct ValidatorOptions { /// Before gloas it goes into builder registrations (with /// `--builder-proposals`). From gloas it goes into the proposer /// preferences, published for every proposal, and the beacon node builds - /// this client's own payloads toward it too, so on a network whose gas - /// limit is not the default, set it or every proposal pulls the limit - /// toward 60M. Sepolia and Platåberget schedule 200000000: pass - /// `--gas-limit 200000000` there. The network config's - /// `GAS_LIMIT_SCHEDULE` is not read yet (#795). - #[arg( - long, - default_value_t = DEFAULT_GAS_LIMIT, - value_parser = clap::value_parser!(u64).range(1..) - )] - pub(crate) gas_limit: u64, + /// this client's own payloads toward it too. + /// + /// Without it, the gas limit is the one the network's `GAS_LIMIT_SCHEDULE` + /// (read off the beacon node's `/eth/v1/config/spec`) names for the + /// proposal's epoch, and 60000000 for an epoch it names none, or when the + /// node does not serve the key. + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + pub(crate) gas_limit: Option, /// Serve the keymanager API: keystores, remote keys, plus each validator's /// own fee recipient, graffiti and gas limit. @@ -357,7 +352,7 @@ mod tests { metrics_port: 5064, graffiti: graffiti.to_string(), suggested_fee_recipient: None, - gas_limit: DEFAULT_GAS_LIMIT, + gas_limit: None, enable_keymanager: false, web3signer_url: None, builder_proposals: false, @@ -394,11 +389,12 @@ mod tests { Cli::try_parse_from(base.iter().chain(extra)).map(|cli| cli.options) } + /// Unset unless given, so the network's schedule can supply the default. #[test] - fn the_gas_limit_defaults_to_60m_and_takes_any_positive_value() { - assert_eq!(parse(&[]).expect("parses").gas_limit, DEFAULT_GAS_LIMIT); + fn the_gas_limit_is_unset_by_default_and_takes_any_positive_value() { + assert_eq!(parse(&[]).expect("parses").gas_limit, None); let options = parse(&["--gas-limit", "200000000"]).expect("parses"); - assert_eq!(options.gas_limit, 200_000_000); + assert_eq!(options.gas_limit, Some(200_000_000)); parse(&["--gas-limit", "0"]).expect_err("a zero gas limit is a mistake"); } diff --git a/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml b/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml index 5e491f0cb..8b89a197d 100644 --- a/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml +++ b/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml @@ -203,8 +203,8 @@ BLOB_SCHEDULE: - EPOCH: 419072 # January 7, 2026, 01:01:11am UTC MAX_BLOBS_PER_BLOCK: 21 -# Keys a kurtosis-generated config carries that mainnet's does not. GLOAS_* and -# PAYLOAD_DUE_BPS are claimed by `Config` now; GAS_LIMIT_SCHEDULE, +# Keys a kurtosis-generated config carries that mainnet's does not. GLOAS_*, +# PAYLOAD_DUE_BPS and GAS_LIMIT_SCHEDULE are claimed by `Config` now; # HEZE_FORK_VERSION, HEZE_FORK_EPOCH, and INCLUSION_LIST_DUE_BPS are still # deliberately present: this build cannot process heze, so they must land in # the ignored-key warning rather than in Config. diff --git a/crates/blockchain/src/payload_attributes.rs b/crates/blockchain/src/payload_attributes.rs index c8a10af2f..be8e5b063 100644 --- a/crates/blockchain/src/payload_attributes.rs +++ b/crates/blockchain/src/payload_attributes.rs @@ -37,7 +37,9 @@ use ethlambda_engine::{CustodyColumns, EngineClient, ForkchoiceStateV1}; use ethlambda_state_transition::beacon::block_production::{ PayloadInputs, advance_to_slot, payload_inputs, }; -use ethlambda_state_transition::beacon::builder_market::SharedBuilderMarket; +use ethlambda_state_transition::beacon::builder_market::{ + PqBuilderMarket, SharedBuilderMarket, SharedPqBuilderMarket, +}; use ethlambda_state_transition::beacon::fork_choice::{ advance_to_epoch_start, get_head_node, should_build_on_full, }; @@ -105,6 +107,9 @@ pub fn prepared_fee_recipient( pub struct PayloadPreparation { pub fee_recipients: FeeRecipients, pub builder_market: SharedBuilderMarket, + /// The PQ fork's proposer preferences, which PQ block production reads + /// its gas target from (see [`prepare_pq_proposal`]). + pub pq_builder_market: SharedPqBuilderMarket, /// `--always-prepare-payload`. pub always_prepare: bool, /// The payload builds the actor started ahead of their slots, shared @@ -466,9 +471,11 @@ fn prepare_gloas_proposal_on( } /// Everything a PQ block at a slot builds on: [`GloasProposal`]'s -/// counterpart for PQ's own production endpoint (`pq_blocks/{slot}`). PQ has -/// no proposer preferences in production, so the fee recipient is -/// `prepare_beacon_proposer`'s, else the zero address. +/// counterpart for PQ's own production endpoint (`pq_blocks/{slot}`). The fee +/// recipient is `prepare_beacon_proposer`'s, else the zero address. The gas +/// target is the one the proposer's own signed PQ preferences for the slot +/// name, when this node holds them, else the parent's gas limit (see +/// [`pq_preferred_gas_limit`]). pub struct PqProposal { /// The head state advanced to the proposal slot. pub state: BeaconState, @@ -487,6 +494,7 @@ pub struct PqProposal { /// preparation ahead of the slot, so the two compute the same attributes. pub fn prepare_pq_proposal( store: &Store, + market: &PqBuilderMarket, head_root: H256, head_state: &BeaconState, slot: Slot, @@ -495,12 +503,13 @@ pub fn prepare_pq_proposal( return Err(ProposalError::NotAfterHead); } let build_on_full = parent_builds_on_full(store, head_root, slot)?; - prepare_pq_proposal_on(store, head_root, head_state, slot, build_on_full) + prepare_pq_proposal_on(store, market, head_root, head_state, slot, build_on_full) } /// [`prepare_pq_proposal`] with the parent payload branch already chosen. fn prepare_pq_proposal_on( store: &Store, + market: &PqBuilderMarket, head_root: H256, head_state: &BeaconState, slot: Slot, @@ -535,8 +544,14 @@ fn prepare_pq_proposal_on( })?; let proposer = get_beacon_proposer_index(&state) .map_err(|_| ProposalError::Internal("no proposer for the slot"))?; - let inputs = pq_payload_inputs(&state, build_on_full, &parent_requests, &config) + let mut inputs = pq_payload_inputs(&state, build_on_full, &parent_requests, &config) .map_err(|_| ProposalError::Internal("computing the payload attributes failed"))?; + // As gloas's self-build does: without this the payload is built toward + // the parent's gas limit, so the network's `GAS_LIMIT_SCHEDULE`, which + // the validator client signs into its preferences, never moved it. + if let Some(target) = pq_preferred_gas_limit(market, head_state, head_root, slot, proposer) { + inputs.target_gas_limit = target; + } Ok(PqProposal { state, inputs, @@ -546,6 +561,23 @@ fn prepare_pq_proposal_on( }) } +/// The target gas limit of `proposer`'s own signed PQ preferences for +/// `slot`, under the dependent root `head_root`'s chain gives the slot, when +/// this node holds them. Preferences another validator signed for the slot +/// (the slot moved to it in a reorg) do not count. +fn pq_preferred_gas_limit( + market: &PqBuilderMarket, + head_state: &BeaconState, + head_root: H256, + slot: Slot, + proposer: ValidatorIndex, +) -> Option { + dependent_root_at(head_state, head_root, slot) + .and_then(|dependent_root| market.preferences(slot, dependent_root)) + .filter(|signed| signed.message.validator_index == proposer) + .map(|signed| signed.message.target_gas_limit) +} + // --------------------------------------------------------------------------- // The event // --------------------------------------------------------------------------- @@ -690,9 +722,15 @@ pub(crate) fn next_payload( // whose preparation this is too ([`prepare_pq_proposal`]). ForkName::Pq => { let build_on_full = choose_build_on_full()?; - let proposal = - prepare_pq_proposal_on(store, head_root, head_state, proposal_slot, build_on_full) - .map_err(|err| format!("preparing the proposal failed: {err:?}"))?; + let proposal = prepare_pq_proposal_on( + store, + &preparation.pq_builder_market, + head_root, + head_state, + proposal_slot, + build_on_full, + ) + .map_err(|err| format!("preparing the proposal failed: {err:?}"))?; if !prepares_for(proposal.proposer) { return Ok(None); } @@ -761,8 +799,10 @@ pub(crate) struct AttributesKey { /// gloas, and while no status is recorded for the head, in which case the /// worker chooses. pub(crate) build_on_full: Option, - /// Gloas: the fee recipient and gas target of the proposer's signed - /// preferences for the slot, once this node holds them. + /// Gloas and PQ: the fee recipient and gas target of the proposer's + /// signed preferences for the slot, once this node holds them. PQ + /// production reads only the gas target, but a change to either starts + /// another build, which is harmless. pub(crate) preferences: Option<(ExecutionAddress, u64)>, } @@ -801,8 +841,23 @@ pub(crate) fn attributes_key( }); (build_on_full(), preferences) } - // PQ production takes no proposer preferences. - ForkName::Pq => (build_on_full(), None), + // PQ production takes the gas target from them + // ([`prepare_pq_proposal`]), so their arrival starts another build. + ForkName::Pq => { + let preferences = dependent_root_at(head_state, head_root, proposal_slot) + .and_then(|root| { + preparation + .pq_builder_market + .preferences(proposal_slot, root) + }) + .map(|signed| { + ( + signed.message.fee_recipient, + signed.message.target_gas_limit, + ) + }); + (build_on_full(), preferences) + } _ => (None, None), }; AttributesKey { @@ -1195,6 +1250,49 @@ mod tests { } } + /// PQ block production builds toward the gas target of the proposer's + /// own signed PQ preferences for the slot, under the dependent root the + /// head's chain gives it: the network's `GAS_LIMIT_SCHEDULE` reaches the + /// payload through them. Without them, another validator's, or ones + /// under another dependent root, it keeps the parent's gas limit. + #[test] + fn a_pq_proposal_takes_the_gas_target_of_its_proposers_own_preferences() { + use ethlambda_types::beacon::containers::gloas::ProposerPreferences; + + let (_, head_root, head_state) = fulu_store(); + let slot = head_state.slot() + 1; + let dependent_root = dependent_root_at(&head_state, head_root, slot).expect("in range"); + let proposer = 7; + let preferences = |validator_index, dependent_root| pq::SignedProposerPreferences { + message: ProposerPreferences { + dependent_root, + proposal_slot: slot, + validator_index, + fee_recipient: ExecutionAddress::ZERO, + target_gas_limit: 200_000_000, + }, + signature: Default::default(), + }; + let lookup = |market: &PqBuilderMarket| { + pq_preferred_gas_limit(market, &head_state, head_root, slot, proposer) + }; + + let market = PqBuilderMarket::default(); + assert_eq!(lookup(&market), None, "none held"); + assert!(market.record_preferences(preferences(proposer, dependent_root), slot - 1)); + assert_eq!(lookup(&market), Some(200_000_000)); + + let another_validators = PqBuilderMarket::default(); + let theirs = preferences(proposer + 1, dependent_root); + assert!(another_validators.record_preferences(theirs, slot - 1)); + assert_eq!(lookup(&another_validators), None, "another validator's"); + + let another_root = PqBuilderMarket::default(); + let stale = preferences(proposer, H256::repeat_byte(0x99)); + assert!(another_root.record_preferences(stale, slot - 1)); + assert_eq!(lookup(&another_root), None, "under another dependent root"); + } + #[test] fn a_registered_proposer_gets_the_attributes_block_production_would_send() { let (store, head_root, head_state) = fulu_store(); diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index c60506e14..4d053ba82 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -16,9 +16,8 @@ //! schedule) 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. `GAS_LIMIT_SCHEDULE` (gloas-era) -//! stays out too, since it is a list rather than a scalar. The rest are -//! heze-era data keys, not gloas's, with no reader in this build at all: +//! reported as an unknown key instead. The rest are heze-era data keys, not +//! gloas's, with no reader in this build at all: //! `INCLUSION_LIST_DUE_BPS`, `MAX_REQUEST_INCLUSION_LIST`, //! `MIN_SLOTS_FOR_INCLUSION_LISTS_REQUESTS`, and //! `MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST` (EIP-7805's fork-choice-enforced @@ -31,6 +30,11 @@ //! value it reports from the one `Config` the store holds, rather than having //! the name threaded to it separately from startup. //! +//! `GAS_LIMIT_SCHEDULE` (gloas, EIP-8261) is a field for the same reason, but +//! one stored in a `Metadata` row of its own rather than in this struct's +//! encoding: see [`GasLimitSchedule`]. It is advisory, a validator client's +//! default gas limit, so nothing a node checks depends on it. +//! //! Networking values and the deposit contract identity used to be left out too, //! on the grounds that the state transition never reads them. They are here now //! because they have a second reader: `/eth/v1/config/spec` must echo every key @@ -84,6 +88,235 @@ pub struct BlobScheduleEntry { /// version. pub const MAX_BLOB_SCHEDULE_ENTRIES: usize = 32; +/// How many gas-limit-schedule entries a [`GasLimitSchedule`] can carry. +/// +/// A storage bound, not a consensus one, like [`MAX_BLOB_SCHEDULE_ENTRIES`]: +/// the schedule's own row is a bounded SSZ list. A beacon node refuses a +/// config file naming more ([`GasLimitSchedule::check`]); a validator client, +/// which stores nothing, takes any length. +pub const MAX_GAS_LIMIT_SCHEDULE_ENTRIES: usize = 32; + +/// One entry in gloas's gas limit schedule (EIP-8261): from `epoch` onward, +/// until a later entry takes over, `gas_limit` is the network's default and +/// recommended maximum gas limit. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, SszEncode, SszDecode, serde::Deserialize, serde::Serialize, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub struct GasLimitScheduleEntry { + /// The first epoch this entry applies to. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub epoch: Epoch, + /// The gas limit from `epoch` onward. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub gas_limit: u64, +} + +/// `GAS_LIMIT_SCHEDULE`: the gas limit a validator targets by default, per +/// epoch (EIP-8261). Possibly empty. +/// +/// Advisory: the specification says it introduces no validity rules, so no +/// block, bid or preference is judged against it. Its reader is a validator +/// client, which targets [`Self::gas_limit_at`] its proposal's epoch when its +/// operator named no gas limit. +/// +/// Held ascending by epoch, whatever order the file lists it in: the +/// specification recommends that order, and `/eth/v1/config/spec` reports it +/// in it. +/// +/// A beacon node holds at most [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] entries, +/// since [`Self::check`] refuses more, so its schedule always fits the stored +/// row. Deserializing takes any length: a validator client reading a node's +/// schedule stores nothing. +/// +/// # Stored in a row of its own +/// +/// [`Config`] is persisted SSZ-encoded under `Metadata["config"]`, a positional +/// container: a new field there would leave every row written before it +/// undecodable, which is a `DB_VERSION` bump with no migration. So this field +/// takes zero bytes in that encoding (this type's `SszEncode`/`SszDecode` write +/// and read nothing, keeping the row byte for byte what it was), and the +/// storage crate keeps the schedule in a `Metadata` row of its own instead, +/// encoded by [`Self::to_row_ssz`]. A directory written before that row existed +/// simply has none: a beacon resume reports the key as missing and adds the +/// config file's, rather than failing. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +#[serde( + from = "Vec", + into = "Vec" +)] +pub struct GasLimitSchedule(Vec); + +/// The schedule's stored row: an SSZ list, ascending by epoch. +type GasLimitScheduleRow = SszList; + +impl GasLimitSchedule { + /// The entries, ascending by epoch. + pub fn entries(&self) -> &[GasLimitScheduleEntry] { + &self.0 + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The gas limit scheduled for `epoch`: that of the latest entry at or + /// before it, or `None` when every entry is later (or there is none). + /// + /// This is gloas's `get_scheduled_gas_limit`. + pub fn gas_limit_at(&self, epoch: Epoch) -> Option { + self.0 + .iter() + .rev() + .find(|entry| entry.epoch <= epoch) + .map(|entry| entry.gas_limit) + } + + /// Whether a beacon node can run on this schedule: it holds at most + /// [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] entries, which is what its stored + /// row can hold, and it keeps [`Self::check_rules`]. + pub fn check(&self, gloas_fork_epoch: Epoch) -> Result<(), GasLimitScheduleError> { + if self.0.len() > MAX_GAS_LIMIT_SCHEDULE_ENTRIES { + return Err(GasLimitScheduleError::TooManyEntries { + entries: self.0.len(), + }); + } + self.check_rules(gloas_fork_epoch) + } + + /// Whether the schedule keeps the specification's two rules (no two + /// entries share an epoch, and none is before `gloas_fork_epoch`), and + /// names no zero gas limit, which no validator could target (`--gas-limit` + /// and the keymanager refuse one too). + /// + /// Without [`Self::check`]'s bound on the entries: a validator client + /// reading a node's schedule stores none of it, and checks it with this. + pub fn check_rules(&self, gloas_fork_epoch: Epoch) -> Result<(), GasLimitScheduleError> { + if let Some(entry) = self.0.iter().find(|entry| entry.epoch < gloas_fork_epoch) { + return Err(GasLimitScheduleError::BeforeGloas { + epoch: entry.epoch, + gloas_fork_epoch, + }); + } + if let Some(pair) = self + .0 + .windows(2) + .find(|pair| pair[0].epoch == pair[1].epoch) + { + return Err(GasLimitScheduleError::DuplicateEpoch { + epoch: pair[0].epoch, + }); + } + if let Some(entry) = self.0.iter().find(|entry| entry.gas_limit == 0) { + return Err(GasLimitScheduleError::ZeroGasLimit { epoch: entry.epoch }); + } + Ok(()) + } + + /// The schedule as its own `Metadata` row stores it: an SSZ + /// `List[GasLimitScheduleEntry, MAX_GAS_LIMIT_SCHEDULE_ENTRIES]`. + /// + /// # Panics + /// + /// If the schedule holds more than [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] + /// entries. A beacon node's config file is refused before that + /// ([`Self::check`]), so only a schedule built in code can. + pub fn to_row_ssz(&self) -> Vec { + let row = GasLimitScheduleRow::try_from(self.0.clone()).unwrap_or_else(|_| { + panic!( + "a gas limit schedule of {} entries is over the {MAX_GAS_LIMIT_SCHEDULE_ENTRIES} \ + its row can hold", + self.0.len() + ) + }); + libssz::SszEncode::to_ssz(&row) + } + + /// Decode the schedule's own `Metadata` row ([`Self::to_row_ssz`]). + pub fn from_row_ssz(bytes: &[u8]) -> Result { + let row = ::from_ssz_bytes(bytes)?; + Ok(Self::from(row.to_vec())) + } +} + +/// Sorted on the way in, stably, so entries the file lists out of order are +/// held in epoch order and two sharing an epoch keep the file's order. +impl From> for GasLimitSchedule { + fn from(mut entries: Vec) -> Self { + entries.sort_by_key(|entry| entry.epoch); + Self(entries) + } +} + +impl From for Vec { + fn from(schedule: GasLimitSchedule) -> Self { + schedule.0 + } +} + +/// A `GAS_LIMIT_SCHEDULE` a beacon node refuses: one too long for it to store, +/// or one that breaks the specification's rules. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum GasLimitScheduleError { + #[error( + "{entries} entries, more than the {MAX_GAS_LIMIT_SCHEDULE_ENTRIES} this node can store" + )] + TooManyEntries { entries: usize }, + #[error( + "an entry at epoch {epoch} is before GLOAS_FORK_EPOCH ({gloas_fork_epoch}), \ + which the schedule must not start before" + )] + BeforeGloas { + epoch: Epoch, + gloas_fork_epoch: Epoch, + }, + #[error("two entries share epoch {epoch}")] + DuplicateEpoch { epoch: Epoch }, + #[error("the entry at epoch {epoch} names a gas limit of zero")] + ZeroGasLimit { epoch: Epoch }, +} + +/// Zero bytes inside [`Config`]'s encoding: see "Stored in a row of its own" +/// on [`GasLimitSchedule`]. The row itself is [`GasLimitSchedule::to_row_ssz`]. +impl libssz::SszEncode for GasLimitSchedule { + fn is_fixed_size() -> bool { + true + } + + fn fixed_size() -> usize { + 0 + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn ssz_append(&self, _buf: &mut Vec) {} +} + +/// Zero bytes inside [`Config`]'s encoding, decoded as the empty schedule, +/// which the storage crate then fills from the schedule's own row: see +/// "Stored in a row of its own" on [`GasLimitSchedule`]. +impl libssz::SszDecode for GasLimitSchedule { + fn is_fixed_size() -> bool { + true + } + + fn fixed_size() -> usize { + 0 + } + + fn from_ssz_bytes(bytes: &[u8]) -> Result { + if !bytes.is_empty() { + return Err(libssz::DecodeError::InvalidFixedLength { + expected: 0, + got: bytes.len(), + }); + } + Ok(Self::default()) + } +} + /// How many bytes a [`ConfigName`] can hold. /// /// A storage bound, not a consensus one, for the same reason as @@ -683,6 +916,16 @@ pub struct Config { pub max_request_data_column_sidecars: u64, #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub min_epochs_for_block_requests: u64, + + // -- Stored in rows of their own ---------------------------------------- + // Every key added after `DB_VERSION` 10 goes here: it takes zero bytes in + // `Metadata["config"]`, and the storage crate keeps it in a `Metadata` row + // of its own, so a directory that predates the key loads, and a resume + // adds the config file's value instead of failing. + /// Gloas (EIP-8261): the gas limit schedule, a validator client's default + /// gas limit per epoch. Empty when the file omits it, as mainnet's does. + /// See [`GasLimitSchedule`]. + pub gas_limit_schedule: GasLimitSchedule, } /// The PQ committee cap this process runs on, `0` until @@ -946,6 +1189,8 @@ impl Config { max_request_blob_sidecars_electra: 1_152, max_request_data_column_sidecars: 16_384, min_epochs_for_block_requests: 33_024, + + gas_limit_schedule: GasLimitSchedule::default(), } } @@ -1080,6 +1325,8 @@ impl Config { max_request_blob_sidecars_electra: 1_152, max_request_data_column_sidecars: 16_384, min_epochs_for_block_requests: 33_024, + + gas_limit_schedule: GasLimitSchedule::default(), } } @@ -1830,6 +2077,214 @@ mod tests { assert!(json.get("GENESIS_TIME").is_none()); } + fn gas_limit_entry(epoch: Epoch, gas_limit: u64) -> GasLimitScheduleEntry { + GasLimitScheduleEntry { epoch, gas_limit } + } + + #[test] + fn the_gas_limit_schedule_parses_and_is_looked_up_by_epoch() { + // Listed out of order and with bare and quoted integers, both of + // which a `config.yaml` may carry. + let yaml = concat!( + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 200\n", + " GAS_LIMIT: 150000000\n", + " - EPOCH: '100'\n", + " GAS_LIMIT: '100000000'\n", + " - EPOCH: 300\n", + " GAS_LIMIT: 200000000\n", + ); + let config: Config = serde_yaml_ng::from_str(yaml).unwrap(); + let schedule = &config.gas_limit_schedule; + assert_eq!( + schedule.entries(), + [ + gas_limit_entry(100, 100_000_000), + gas_limit_entry(200, 150_000_000), + gas_limit_entry(300, 200_000_000), + ], + "held ascending by epoch" + ); + + // Before the first entry nothing is scheduled. + assert_eq!(schedule.gas_limit_at(0), None); + assert_eq!(schedule.gas_limit_at(99), None); + // Each entry from its own epoch until the next one's. + assert_eq!(schedule.gas_limit_at(100), Some(100_000_000)); + assert_eq!(schedule.gas_limit_at(199), Some(100_000_000)); + assert_eq!(schedule.gas_limit_at(200), Some(150_000_000)); + assert_eq!(schedule.gas_limit_at(299), Some(150_000_000)); + assert_eq!(schedule.gas_limit_at(300), Some(200_000_000)); + assert_eq!(schedule.gas_limit_at(Epoch::MAX), Some(200_000_000)); + } + + #[test] + fn an_absent_or_empty_gas_limit_schedule_schedules_nothing() { + let absent: Config = serde_yaml_ng::from_str("SECONDS_PER_SLOT: 12").unwrap(); + assert!(absent.gas_limit_schedule.is_empty()); + assert_eq!(absent.gas_limit_schedule.gas_limit_at(Epoch::MAX), None); + + let empty: Config = serde_yaml_ng::from_str("GAS_LIMIT_SCHEDULE: []").unwrap(); + assert!(empty.gas_limit_schedule.is_empty()); + assert!(Config::mainnet().gas_limit_schedule.is_empty()); + } + + #[test] + fn the_built_in_networks_schedules_parse_from_their_files() { + let sepolia: Config = serde_yaml_ng::from_str(include_str!( + "../../../../../bin/ethlambda/assets/sepolia/config.yaml" + )) + .unwrap(); + assert_eq!( + sepolia.gas_limit_schedule.entries(), + [gas_limit_entry(353_024, 200_000_000)] + ); + assert_eq!(sepolia.gas_limit_schedule.gas_limit_at(353_023), None); + assert_eq!( + sepolia.gas_limit_schedule.gas_limit_at(353_024), + Some(200_000_000) + ); + + let plataberget: Config = serde_yaml_ng::from_str(include_str!( + "../../../../../bin/ethlambda/assets/plataberget/config.yaml" + )) + .unwrap(); + assert_eq!( + plataberget.gas_limit_schedule.entries(), + [gas_limit_entry(1_566, 200_000_000)] + ); + // Platåberget's gloas starts at 1536, before its schedule does. + assert_eq!(plataberget.gas_limit_schedule.gas_limit_at(1_536), None); + assert_eq!( + plataberget.gas_limit_schedule.gas_limit_at(1_566), + Some(200_000_000) + ); + } + + #[test] + fn a_gas_limit_schedule_breaking_the_specifications_rules_is_named() { + let schedule = GasLimitSchedule::from(vec![gas_limit_entry(20, 1), gas_limit_entry(10, 2)]); + assert_eq!(schedule.check(10), Ok(())); + assert_eq!( + schedule.check(11), + Err(GasLimitScheduleError::BeforeGloas { + epoch: 10, + gloas_fork_epoch: 11 + }) + ); + + let duplicate = GasLimitSchedule::from(vec![ + gas_limit_entry(10, 1), + gas_limit_entry(20, 2), + gas_limit_entry(10, 3), + ]); + assert_eq!( + duplicate.check(0), + Err(GasLimitScheduleError::DuplicateEpoch { epoch: 10 }) + ); + + let zero = GasLimitSchedule::from(vec![gas_limit_entry(10, 1), gas_limit_entry(20, 0)]); + assert_eq!( + zero.check(0), + Err(GasLimitScheduleError::ZeroGasLimit { epoch: 20 }) + ); + assert_eq!(GasLimitSchedule::default().check(Epoch::MAX), Ok(())); + } + + /// The schedule must leave `Metadata["config"]`'s encoding alone: rows + /// written before the field existed decode unchanged, and no `DB_VERSION` + /// bump is needed. Decoding that row gives an empty schedule; the storage + /// crate fills it from the schedule's own row. + #[test] + fn the_config_row_leaves_the_gas_limit_schedule_to_its_own_row() { + let mut scheduled = Config::mainnet(); + scheduled.gas_limit_schedule = vec![gas_limit_entry(100, 200_000_000)].into(); + + let bytes = scheduled.to_ssz(); + assert_eq!(bytes, Config::mainnet().to_ssz()); + assert_eq!(scheduled.encoded_len(), Config::mainnet().encoded_len()); + + let decoded = Config::from_ssz_bytes(&bytes).expect("valid config"); + assert!(decoded.gas_limit_schedule.is_empty()); + assert_eq!(decoded, Config::mainnet()); + // `PartialEq` still compares the field, so a resume that finds the + // stored schedule (its row's) differing from the file's rewrites it. + assert_ne!(decoded, scheduled); + + assert_eq!(GasLimitSchedule::default().to_ssz(), Vec::::new()); + assert!(GasLimitSchedule::from_ssz_bytes(&[0]).is_err()); + } + + #[test] + fn the_gas_limit_schedule_row_round_trips() { + let schedule = GasLimitSchedule::from(vec![ + gas_limit_entry(1_566, 200_000_000), + gas_limit_entry(1_536, 60_000_000), + ]); + let decoded = GasLimitSchedule::from_row_ssz(&schedule.to_row_ssz()).expect("valid row"); + assert_eq!(decoded, schedule); + assert_eq!(decoded.gas_limit_at(1_566), Some(200_000_000)); + + let empty = GasLimitSchedule::default(); + assert_eq!( + GasLimitSchedule::from_row_ssz(&empty.to_row_ssz()), + Ok(empty) + ); + // One byte is not a whole 16-byte entry. + assert!(GasLimitSchedule::from_row_ssz(&[0]).is_err()); + } + + /// The stored row holds at most `MAX_GAS_LIMIT_SCHEDULE_ENTRIES`, so + /// `check` (a beacon node's config file) refuses a longer schedule rather + /// than the write failing. Deserializing alone does not: a validator + /// client reads a node's schedule and stores nothing. + #[test] + fn a_gas_limit_schedule_longer_than_its_row_is_refused_by_check_only() { + let schedule = |count: usize| { + let entries = (0..count as u64).map(|epoch| gas_limit_entry(epoch, 60_000_000)); + GasLimitSchedule::from(entries.collect::>()) + }; + assert_eq!(schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES).check(0), Ok(())); + assert_eq!( + schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1).check(0), + Err(GasLimitScheduleError::TooManyEntries { + entries: MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1 + }) + ); + + let entry = |epoch| format!(" - EPOCH: {epoch}\n GAS_LIMIT: 60000000\n"); + let over: String = (0..=MAX_GAS_LIMIT_SCHEDULE_ENTRIES).map(entry).collect(); + let parsed: Config = serde_yaml_ng::from_str(&format!("GAS_LIMIT_SCHEDULE:\n{over}")) + .expect("deserializing takes any length"); + assert_eq!( + parsed.gas_limit_schedule.entries().len(), + MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1 + ); + } + + #[test] + fn the_gas_limit_schedule_serializes_as_a_list_of_quoted_entries() { + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![ + gas_limit_entry(100, 75_000_000), + gas_limit_entry(42, 60_000_000), + ] + .into(); + + let json = serde_json::to_value(&config).expect("serializes"); + assert_eq!( + json["GAS_LIMIT_SCHEDULE"], + serde_json::json!([ + {"EPOCH": "42", "GAS_LIMIT": "60000000"}, + {"EPOCH": "100", "GAS_LIMIT": "75000000"}, + ]) + ); + + // An empty schedule is still reported, as the file may carry it. + let json = serde_json::to_value(Config::mainnet()).expect("serializes"); + assert_eq!(json["GAS_LIMIT_SCHEDULE"], serde_json::json!([])); + } + #[test] fn the_blob_schedule_serializes_as_a_list_of_quoted_entries() { let mut config = Config::mainnet(); diff --git a/crates/net/rpc/src/beacon/config.rs b/crates/net/rpc/src/beacon/config.rs index e4316ccdb..c9c8fb1f2 100644 --- a/crates/net/rpc/src/beacon/config.rs +++ b/crates/net/rpc/src/beacon/config.rs @@ -18,7 +18,13 @@ //! //! The configuration keys include gloas's (`GLOAS_*` and the other gloas //! timing and churn keys), since `Config` holds them and this serializes the -//! whole of it. The preset and constant keys are the ones lighthouse reports +//! whole of it. That includes `GAS_LIMIT_SCHEDULE` (EIP-8261), a list of +//! `{"EPOCH", "GAS_LIMIT"}` entries with quoted values, ascending by epoch, as +//! `BLOB_SCHEDULE` is reported and as lighthouse reports it. It is reported +//! empty when the network schedules nothing, where lighthouse leaves the key +//! out while gloas is unscheduled: the specification's own `config.yaml`s +//! carry it empty, and this endpoint echoes every key a `config.yaml` carries. +//! A validator client takes its default gas limit from it. The preset and constant keys are the ones lighthouse reports //! plus gloas's own, from `presets/*/gloas.yaml` and `beacon-chain.md`'s //! constants (`PTC_SIZE`, `DOMAIN_BEACON_BUILDER`, ...), less keys the //! specification does not define at all (`GAS_LIMIT_ADJUSTMENT_FACTOR`, @@ -496,6 +502,43 @@ mod tests { assert!(data["MIN_BUILDER_WITHDRAWABILITY_DELAY"].is_string()); } + /// The fixture's `Config::mainnet()` schedules no gas limit, which is + /// reported as an empty list rather than left out. + #[tokio::test] + async fn the_spec_reports_an_empty_gas_limit_schedule() { + let json = get_spec_json().await; + assert_eq!(json["data"]["GAS_LIMIT_SCHEDULE"], serde_json::json!([])); + } + + /// The shape lighthouse reports and validator clients read: quoted + /// values, ascending by epoch. + #[test] + fn the_spec_reports_the_gas_limit_schedule_as_quoted_entries() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![ + GasLimitScheduleEntry { + epoch: 400_000, + gas_limit: 300_000_000, + }, + GasLimitScheduleEntry { + epoch: 353_024, + gas_limit: 200_000_000, + }, + ] + .into(); + + let data = spec(&config); + assert_eq!( + data["GAS_LIMIT_SCHEDULE"], + serde_json::json!([ + {"EPOCH": "353024", "GAS_LIMIT": "200000000"}, + {"EPOCH": "400000", "GAS_LIMIT": "300000000"}, + ]) + ); + } + #[tokio::test] async fn the_fork_schedule_lists_scheduled_forks_with_quoted_epochs() { let fixture = beacon_fixture(64); diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index ce98e052b..d400d4181 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -45,6 +45,7 @@ use ethlambda_blockchain::{ }; use ethlambda_engine::{EngineClient, types::ClientVersionV1}; use ethlambda_state_transition::beacon::{ + builder_market::SharedPqBuilderMarket, helpers::pq::is_valid_vrf_proof, pq_block_production::{PqBlockInputs, assemble_pq_block, parse_pq_execution_requests}, }; @@ -132,6 +133,7 @@ async fn post_produce_pq_block( Extension(custody): Extension, Extension(OwnVersion(own_version)): Extension, Extension(sync_status): Extension, + Extension(pq_market): Extension, blob_cache: Option>, ahead: Option>, ahead_attestations: Option>, @@ -163,6 +165,7 @@ async fn post_produce_pq_block( &store, &engine, &fee_recipients, + &pq_market, &custody, ahead.as_ref().map(|Extension(ahead)| ahead), ahead_attestations.as_ref().map(|Extension(ahead)| ahead), @@ -194,6 +197,7 @@ async fn produce( store: &Store, engine: &EngineClient, fee_recipients: &FeeRecipients, + pq_market: &SharedPqBuilderMarket, custody: &NodeCustodyColumns, ahead: Option<&PreparedPayloads>, ahead_attestations: Option<&PreparedPqAttestations>, @@ -212,13 +216,15 @@ async fn produce( proposer, build_on_full, parent_requests, - } = prepare_pq_proposal(store, head_root, &head_state, slot).map_err(|err| match err { - ProposalError::NotAfterHead => ApiError::BadRequest("slot is not after the head block"), - ProposalError::ParentEnvelopeMissing => { - ApiError::ServiceUnavailable("the parent's payload envelope is not held to build on") - } - ProposalError::Internal(message) => ApiError::Internal(message), - })?; + } = prepare_pq_proposal(store, pq_market, head_root, &head_state, slot).map_err( + |err| match err { + ProposalError::NotAfterHead => ApiError::BadRequest("slot is not after the head block"), + ProposalError::ParentEnvelopeMissing => ApiError::ServiceUnavailable( + "the parent's payload envelope is not held to build on", + ), + ProposalError::Internal(message) => ApiError::Internal(message), + }, + )?; if !is_valid_vrf_proof(&state, proposer, slot, &randao_reveal).unwrap_or(false) { return Err(ApiError::BadRequest("invalid randao_reveal")); } diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 15ece934b..3013d660c 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -25,7 +25,7 @@ use ethlambda_types::{ bits_is_subset, validator_indices, }, beacon::{ - config::Config, + config::{Config, GasLimitSchedule}, constants::NUM_BLOCK_TIMELINESS_DEADLINES, containers::{ BeaconState, Checkpoint as BeaconCheckpoint, DataColumnSidecar, SignedBeaconBlock, @@ -126,7 +126,65 @@ impl ForkCheckpoints { /// configuration can still compare it against a wall clock. const KEY_TIME: &[u8] = b"time"; /// Key for "config" field of the Store. Its value has type [`Config`] and it's SSZ-encoded. +/// +/// Every key added to `Config` after [`DB_VERSION`] 10 takes zero bytes in this +/// row's encoding and lives in a row of its own instead: see [`CONFIG_ROWS`]. const KEY_CONFIG: &[u8] = b"config"; + +/// A `Config` key stored in a `Metadata` row of its own, outside +/// [`KEY_CONFIG`]'s encoding. +/// +/// `KEY_CONFIG` holds a positional SSZ container, which has no notion of a +/// missing key: a field added to it leaves every row written before it +/// undecodable, so each one used to cost a [`DB_VERSION`] bump and a resync of +/// every data directory. A key with a row of its own does not: +/// - **an older directory** has no row, which [`Store::fill_missing_config_keys`] +/// reports and a beacon resume fills from the config file, then writes, instead +/// of failing; +/// - **an older build** never looks for the row, and still decodes `KEY_CONFIG`, +/// since the key's field takes zero bytes there. +/// +/// So a new `Config` key gets an entry in [`CONFIG_ROWS`], a zero-width field +/// encoding inside `Config`, and a row codec of its own. Its zero-width decode +/// must give the value `Config::lean` holds: a lean resume never fills a +/// missing row, so a lean directory that predates the key runs on that decode. +struct ConfigRow { + /// The key's name in a `config.yaml`, for logs. + name: &'static str, + /// Its `Metadata` key. + key: &'static [u8], + /// The field's value, as its row stores it. + encode: fn(&Config) -> Vec, + /// Decode a row into the field. + decode: fn(&[u8], &mut Config) -> Result<(), libssz::DecodeError>, + /// Copy the field from the first config into the second. + copy: fn(&Config, &mut Config), +} + +/// Every [`ConfigRow`], in no particular order. +const CONFIG_ROWS: &[ConfigRow] = &[ConfigRow { + name: "GAS_LIMIT_SCHEDULE", + key: b"config_gas_limit_schedule", + encode: |config| config.gas_limit_schedule.to_row_ssz(), + decode: |bytes, config| { + config.gas_limit_schedule = GasLimitSchedule::from_row_ssz(bytes)?; + Ok(()) + }, + copy: |from, into| into.gas_limit_schedule = from.gas_limit_schedule.clone(), +}]; + +/// The `Metadata` entries that store `config`: [`KEY_CONFIG`] and every +/// [`CONFIG_ROWS`] row. Written together, so the rows can never describe two +/// different configs. +fn config_entries(config: &Config) -> Vec<(Vec, Vec)> { + let rows = CONFIG_ROWS + .iter() + .map(|row| (row.key.to_vec(), (row.encode)(config))); + std::iter::once((KEY_CONFIG.to_vec(), config.to_ssz())) + .chain(rows) + .collect() +} + /// Key for "head" field of the Store. Its value has type [`H256`] and it's SSZ-encoded. const KEY_HEAD: &[u8] = b"head"; /// Key for "safe_target" field of the Store. Its value has type [`H256`] and it's SSZ-encoded. @@ -239,6 +297,9 @@ const KEY_STATES_PRUNED_BELOW: &[u8] = b"states_pruned_below"; /// into the wrong fields. Not 8 again, although the layout is 8's: a number /// stands for one history, and nothing should read a version 9 directory as /// the version before it. +/// +/// A `Config` key added since 10 needs no bump: it gets a row of its own (see +/// `ConfigRow`), which a directory written before it simply lacks. pub const DB_VERSION: u64 = 10; /// The consensus protocol a data directory holds. @@ -1524,11 +1585,20 @@ impl Store { .expect("read anchor slot") .expect("a versioned directory always carries an anchor slot"); - ( - Config::from_ssz_bytes(&bytes).expect("valid config"), - chain, - anchor_slot, - ) + let mut config = Config::from_ssz_bytes(&bytes).expect("valid config"); + // A key whose row is absent stays as `KEY_CONFIG` decoded it + // (empty): the directory predates it, and a resume fills it from + // the config file (`fill_missing_config_keys`). + for row in CONFIG_ROWS { + let Some(bytes) = view.get(Table::Metadata, row.key).expect("get config row") + else { + continue; + }; + (row.decode)(&bytes, &mut config) + .unwrap_or_else(|err| panic!("invalid {} row: {err:?}", row.name)); + } + + (config, chain, anchor_slot) }; info!(?chain, anchor_slot, "Loaded store from persisted DB state"); @@ -1821,7 +1891,7 @@ impl Store { let mut batch = backend.begin_write().expect("write batch"); // Metadata - let metadata_entries = vec![ + let mut metadata_entries = vec![ (KEY_DB_VERSION.to_vec(), DB_VERSION.to_ssz()), (KEY_CHAIN.to_vec(), vec![Chain::Lean.selector()]), (KEY_PRESET.to_vec(), vec![Preset::active().selector()]), @@ -1829,13 +1899,13 @@ impl Store { // millisecond, so the value that means "the clock has not // advanced past genesis" is genesis itself. (KEY_TIME.to_vec(), runtime_config.genesis_time_ms().to_ssz()), - (KEY_CONFIG.to_vec(), runtime_config.to_ssz()), (KEY_HEAD.to_vec(), anchor_block_root.to_ssz()), (KEY_SAFE_TARGET.to_vec(), anchor_block_root.to_ssz()), (KEY_LATEST_JUSTIFIED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_LATEST_FINALIZED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_ANCHOR_SLOT.to_vec(), anchor_slot.to_ssz()), ]; + metadata_entries.extend(config_entries(&runtime_config)); batch .put_batch(Table::Metadata, metadata_entries) .expect("put metadata"); @@ -1935,7 +2005,7 @@ impl Store { // and the finalized slot it is advancing *past*, so both chains have // to start with those rows present rather than have that one writer // grow an absent-key branch. - let metadata_entries = vec![ + let mut metadata_entries = vec![ (KEY_DB_VERSION.to_vec(), DB_VERSION.to_ssz()), (KEY_CHAIN.to_vec(), vec![Chain::Beacon.selector()]), (KEY_PRESET.to_vec(), vec![Preset::active().selector()]), @@ -1944,7 +2014,6 @@ impl Store { // anchor's own time; the seed matters only for the window before // it does. (KEY_TIME.to_vec(), runtime_config.genesis_time_ms().to_ssz()), - (KEY_CONFIG.to_vec(), runtime_config.to_ssz()), (KEY_HEAD.to_vec(), anchor_block_root.to_ssz()), (KEY_LATEST_JUSTIFIED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_LATEST_FINALIZED.to_vec(), anchor_checkpoint.to_ssz()), @@ -1958,6 +2027,7 @@ impl Store { ), (KEY_ANCHOR_SLOT.to_vec(), anchor_slot.to_ssz()), ]; + metadata_entries.extend(config_entries(&runtime_config)); let mut batch = backend.begin_write().expect("write batch"); batch @@ -2216,10 +2286,42 @@ impl Store { Arc::get_mut(&mut self.config).is_some(), "replace_config needs the only handle to the cached config" ); - self.set_metadata(KEY_CONFIG, &config); + // `KEY_CONFIG` and every `CONFIG_ROWS` row, in one commit; this is also + // what adds a row the directory predates. + let mut batch = self.backend.begin_write().expect("write batch"); + batch + .put_batch(Table::Metadata, config_entries(&config)) + .expect("put config"); + batch.commit().expect("commit"); self.config = Arc::new(config); } + /// This store's config with every key the directory predates taken from + /// `supplied`, plus those keys' names. + /// + /// A predated key is a `ConfigRow` with no row in this directory. Its + /// field holds whatever [`Store::from_db_state`] left there (empty), which + /// is not a value this directory ever recorded. So the caller should + /// compare the returned config, not [`Store::config`], against the config + /// file, then hand the file's to [`Store::replace_config`] to write the + /// missing rows. Reads only. + pub fn fill_missing_config_keys(&self, supplied: &Config) -> (Config, Vec<&'static str>) { + let view = self.backend.begin_read().expect("read view"); + let mut config = (*self.config).clone(); + let mut missing = Vec::new(); + for row in CONFIG_ROWS { + if view + .get(Table::Metadata, row.key) + .expect("get config row") + .is_none() + { + (row.copy)(supplied, &mut config); + missing.push(row.name); + } + } + (config, missing) + } + /// Which consensus protocol this data directory holds. /// /// Infallible for the same reason [`Store::config`] is: fixed at bootstrap @@ -9267,6 +9369,106 @@ mod tests { assert_eq!(store.head().expect("head"), anchor.root); } + /// A beacon directory over `config`, as `init_beacon` writes one. + fn beacon_directory(config: Config) -> Arc { + let backend = Arc::new(InMemoryBackend::new()); + let anchor = BeaconCheckpoint { + epoch: 0, + root: H256::from([1u8; 32]), + }; + Store::init_beacon( + backend.clone(), + 1_606_824_023, + config, + anchor.root, + Store::beacon_checkpoint_as_stored(anchor), + 0, + ); + backend + } + + fn scheduled_config() -> Config { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }] + .into(); + config + } + + /// Every `CONFIG_ROWS` key is written at bootstrap and read back on a + /// resume, and none is reported missing. + #[test] + fn a_config_key_stored_in_its_own_row_is_read_back() { + let scheduled = scheduled_config(); + let backend = beacon_directory(scheduled.clone()); + + let store = Store::from_db_state(backend).unwrap().unwrap(); + + assert_eq!( + store.config().gas_limit_schedule, + scheduled.gas_limit_schedule + ); + let (filled, missing) = store.fill_missing_config_keys(&Config::mainnet()); + assert!(missing.is_empty(), "{missing:?}"); + assert_eq!(filled.gas_limit_schedule, scheduled.gas_limit_schedule); + + // An empty schedule (mainnet's, Hoodi's) is written as a row too, so + // every later resume finds it rather than adding it again. + let unscheduled = Store::from_db_state(beacon_directory(Config::mainnet())) + .unwrap() + .unwrap(); + let (filled, missing) = unscheduled.fill_missing_config_keys(&scheduled); + assert!(missing.is_empty(), "{missing:?}"); + assert!(filled.gas_limit_schedule.is_empty()); + } + + /// A directory written before a key's row existed loads, reports the key + /// missing, and takes its value from the supplied config. Its `config` + /// row is the same bytes an older build wrote and reads. + #[test] + fn a_directory_that_predates_a_config_row_reports_the_key_missing() { + let scheduled = scheduled_config(); + let backend = beacon_directory(scheduled.clone()); + let config_row = backend + .begin_read() + .unwrap() + .get(Table::Metadata, KEY_CONFIG) + .unwrap() + .expect("config row"); + assert_eq!( + config_row, + Config::mainnet().to_ssz(), + "the config row does not carry the schedule" + ); + let mut batch = backend.begin_write().unwrap(); + let keys = CONFIG_ROWS.iter().map(|row| row.key.to_vec()).collect(); + batch.delete_batch(Table::Metadata, keys).unwrap(); + batch.commit().unwrap(); + + let mut store = Store::from_db_state(backend.clone()).unwrap().unwrap(); + assert!(store.config().gas_limit_schedule.is_empty()); + let (filled, missing) = store.fill_missing_config_keys(&scheduled); + assert_eq!(missing, ["GAS_LIMIT_SCHEDULE"]); + assert_eq!(filled, scheduled); + + // What a resume does next: the file's config, rows included. + store.replace_config(scheduled.clone()); + let reopened = Store::from_db_state(backend).unwrap().unwrap(); + assert_eq!( + reopened.config().gas_limit_schedule, + scheduled.gas_limit_schedule + ); + assert!( + reopened + .fill_missing_config_keys(&Config::mainnet()) + .1 + .is_empty() + ); + } + #[test] fn a_store_hands_back_the_runtime_config_it_persisted() { let backend = Arc::new(InMemoryBackend::new()); diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index 3b32990ed..662f3c771 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -28,7 +28,7 @@ //! two of the endpoints used here, but no implementation exercises it: see the //! design document's "Wire format" section for the evidence. -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{Config, GasLimitSchedule}; use ethlambda_types::beacon::containers::electra::{ AggregationBits, Attestation, CommitteeBits, SignedAggregateAndProof, }; @@ -41,6 +41,8 @@ use ethlambda_types::beacon::primitives::{ }; use libssz::SszDecode as _; use serde::{Deserialize, Serialize}; +use std::sync::atomic::{AtomicBool, Ordering}; +use tracing::{debug, warn}; use crate::error::{Error, Result}; @@ -570,7 +572,10 @@ fn spec_u64(value: &serde_json::Value, key: &str) -> Result> { /// separately, by [`crate::adopt_preset`]. /// /// Only the keys read below are overridden: the slot length, the duty -/// offsets, `SHARD_COMMITTEE_PERIOD` and the fork schedule. Every other +/// offsets, `SHARD_COMMITTEE_PERIOD`, the fork schedule and +/// `GAS_LIMIT_SCHEDULE`. An absent or unusable `GAS_LIMIT_SCHEDULE` is an +/// empty schedule, which leaves the default gas limit to `DEFAULT_GAS_LIMIT`, +/// rather than an error (see [`gas_limit_schedule_of`]). Every other /// `Config` field is mainnet's whatever the node reports, so code in this /// crate that starts reading one has to read its key here first. /// @@ -706,10 +711,53 @@ pub fn config_from_spec_response(value: &serde_json::Value) -> Result { config = config.with_fork_version(fork, version); } } + // After the loop: the schedule's rules read the gloas epoch. + config.gas_limit_schedule = gas_limit_schedule_of(value, config.gloas_fork_epoch); Ok(config) } +/// `GAS_LIMIT_SCHEDULE`: the default gas limit, per epoch, when `--gas-limit` +/// names none. +/// +/// Empty when the node does not serve it, or serves `null` (how Go's JSON +/// encoder writes a nil slice), which falls back to `DEFAULT_GAS_LIMIT`. Also +/// empty, with a warning, when the node serves one this client cannot decode +/// or that breaks [`GasLimitSchedule::check_rules`]: the schedule only names +/// a default and identifies no chain, so it is no reason to stop using the +/// node. +/// +/// The warning is given once per process; any later one is at `debug`. +fn gas_limit_schedule_of(value: &serde_json::Value, gloas_fork_epoch: Epoch) -> GasLimitSchedule { + static WARNED: AtomicBool = AtomicBool::new(false); + let Some(field) = value + .get("GAS_LIMIT_SCHEDULE") + .filter(|field| !field.is_null()) + else { + return GasLimitSchedule::default(); + }; + // serde's message can quote the node's own text, so it is written out + // and bounded like every other JSON decode error from a node. + let schedule = serde_json::from_value::(field.clone()) + .map_err(|err| super::http::decode_text(&err)) + .and_then(|schedule| { + let checked = schedule.check_rules(gloas_fork_epoch); + checked.map(|()| schedule).map_err(|err| err.to_string()) + }); + schedule.unwrap_or_else(|detail| { + if WARNED.swap(true, Ordering::Relaxed) { + debug!(%detail, "Ignoring a GAS_LIMIT_SCHEDULE a beacon node serves"); + } else { + warn!( + %detail, + "A beacon node serves a GAS_LIMIT_SCHEDULE this client cannot use; ignoring it, \ + so the default gas limit comes from another node or DEFAULT_GAS_LIMIT" + ); + } + GasLimitSchedule::default() + }) +} + impl TryFrom<&AttestationDto> for Attestation { type Error = Error; @@ -1296,6 +1344,91 @@ mod tests { assert!(matches!(err, Error::Decode(_)), "got {err:?}"); } + /// A spec response holding only `keys`, as quoted strings: on this + /// branch an absent key keeps its default. + fn spec_with(keys: &[(&str, &str)]) -> serde_json::Value { + let mut spec = serde_json::json!({}); + for (key, value) in keys { + spec[*key] = serde_json::Value::String((*value).to_string()); + } + spec + } + + /// The schedule in the shape a beacon node serves it (this one's and + /// lighthouse's), looked up at the proposal's epoch; a node that does not + /// serve the key, or serves it empty, schedules nothing. + #[test] + fn the_gas_limit_schedule_is_read_and_defaults_to_empty() { + // A complete response with `GAS_LIMIT_SCHEDULE` set to `schedule`, + // gloas at Sepolia's epoch so the entries are not before it. + let serving = |schedule: serde_json::Value| { + let mut response = spec_with(&[ + ("GLOAS_FORK_EPOCH", "353024"), + ("GLOAS_FORK_VERSION", "0x90000075"), + ]); + response["GAS_LIMIT_SCHEDULE"] = schedule; + response + }; + + let response = serving(serde_json::json!([ + {"EPOCH": "353024", "GAS_LIMIT": "200000000"}, + {"EPOCH": "400000", "GAS_LIMIT": "300000000"}, + ])); + let config = config_from_spec_response(&response).expect("builds"); + let schedule = &config.gas_limit_schedule; + assert_eq!(schedule.entries().len(), 2); + assert_eq!(schedule.gas_limit_at(353_023), None); + assert_eq!(schedule.gas_limit_at(353_024), Some(200_000_000)); + assert_eq!(schedule.gas_limit_at(400_000), Some(300_000_000)); + + let config = config_from_spec_response(&spec_with(&[])).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + let response = serving(serde_json::json!([])); + let config = config_from_spec_response(&response).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + // Go's encoder writes a nil slice as `null`. + let response = serving(serde_json::Value::Null); + let config = config_from_spec_response(&response).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + } + + /// A schedule the client cannot use is ignored, not an error: it only + /// names a default gas limit, so it must not cost the client the node. + /// That covers one that does not decode and one that breaks the rules a + /// beacon node holds its own to (gloas at epoch 100 here). + #[test] + fn an_unusable_gas_limit_schedule_is_ignored() { + let serving = |schedule: serde_json::Value| { + let mut response = spec_with(&[]); + response["GLOAS_FORK_EPOCH"] = serde_json::json!("100"); + response["GLOAS_FORK_VERSION"] = serde_json::json!("0x07000000"); + response["GAS_LIMIT_SCHEDULE"] = schedule; + response + }; + let unusable = [ + serde_json::json!("200000000"), + serde_json::json!([{"EPOCH": "100", "LIMIT": "200000000"}]), + serde_json::json!([ + {"EPOCH": "100", "GAS_LIMIT": "100000000"}, + {"EPOCH": "100", "GAS_LIMIT": "200000000"}, + ]), + serde_json::json!([{"EPOCH": "99", "GAS_LIMIT": "200000000"}]), + serde_json::json!([{"EPOCH": "100", "GAS_LIMIT": "0"}]), + ]; + for schedule in unusable { + let config = config_from_spec_response(&serving(schedule.clone())) + .unwrap_or_else(|err| panic!("{schedule}: {err:?}")); + assert!(config.gas_limit_schedule.is_empty(), "{schedule}"); + } + + let usable = serving(serde_json::json!([{"EPOCH": "100", "GAS_LIMIT": "200000000"}])); + let config = config_from_spec_response(&usable).expect("builds"); + assert_eq!( + config.gas_limit_schedule.gas_limit_at(100), + Some(200_000_000) + ); + } + #[test] fn a_sync_duty_parses_its_quoted_indices() { let duty: SyncDutyDto = serde_json::from_value(serde_json::json!({ diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 8979b399a..ce0e67da8 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -50,9 +50,10 @@ impl FallbackBeaconNode { Self { nodes } } - /// The nodes, in order, for a test outside this module that drives a + /// The nodes, in `--beacon-nodes` order: for a caller that must hear + /// every node rather than the first that answers (the gas limit schedule, + /// see [`crate::gas_limit_schedule`]), and for a test that drives a /// service through the fallback and then inspects each mock. - #[cfg(test)] pub(crate) fn nodes(&self) -> &[B] { &self.nodes } diff --git a/crates/validator/src/beacon_node/http.rs b/crates/validator/src/beacon_node/http.rs index e4bc57263..6dc2f87bb 100644 --- a/crates/validator/src/beacon_node/http.rs +++ b/crates/validator/src/beacon_node/http.rs @@ -119,6 +119,14 @@ fn error_text(text: &str) -> String { ethlambda_types::text::one_line(text, ERROR_TEXT_LIMIT) } +/// A JSON answer's decode error as [`error_text`] writes it. serde's message +/// can quote the node's own text, the whole of an unexpected string among +/// it, so it is bounded and written out like a failed answer's body before +/// it reaches an error and the log line that prints it. +pub(crate) fn decode_text(err: &serde_json::Error) -> String { + error_text(&err.to_string()) +} + /// [`read_error_body`] as [`error_text`] shows it. async fn error_body(response: reqwest::Response) -> String { error_text(&read_error_body(response).await) @@ -633,10 +641,11 @@ impl BeaconNodeApi for HttpBeaconNode { /// Fetches the network's configuration, as far as this client reads it. /// - /// The spec endpoint returns every configuration value as a quoted - /// string. Only the keys [`config_from_spec_response`] names are read - /// (the fork schedule, the slot duration, the duty offsets and - /// `SHARD_COMMITTEE_PERIOD`); the rest of `Config` keeps its mainnet + /// The spec endpoint returns every scalar configuration value as a quoted + /// string, and a schedule as a list of objects. Only the keys + /// [`config_from_spec_response`] names are read (the fork schedule, the + /// slot duration, the duty offsets, `SHARD_COMMITTEE_PERIOD` and + /// `GAS_LIMIT_SCHEDULE`); the rest of `Config` keeps its mainnet /// defaults, so nothing in this client may rely on those. async fn spec(&self) -> Result { let response: DataResponse = self.get("/eth/v1/config/spec").await?; diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index 9d649db4c..e37545691 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -59,6 +59,8 @@ pub struct MockBeaconNode { /// When set, every method fails with this message, regardless of `failures`. pub fail_everything: Option, pub genesis: Option, + /// What `spec` answers; `Config::mainnet()` while unset. + pub spec: Mutex>, pub syncing: bool, /// Tracking a head its execution client has not validated. Separate from /// `syncing`, because the pair a real node can report and this client must @@ -459,6 +461,17 @@ impl MockBeaconNode { *self.proposer_duties_v2_calls.lock().expect("lock") } + /// Answers `spec` with `config` rather than `Config::mainnet()`. + pub fn with_spec(self, config: Config) -> Self { + self.set_spec(config); + self + } + + /// What `spec` answers from now on. + pub fn set_spec(&self, config: Config) { + *self.spec.lock().expect("lock") = Some(config); + } + pub fn with_attestation_data(mut self, slot: Slot) -> Self { self.attestation_data = Some(AttestationData { slot, @@ -962,7 +975,8 @@ impl BeaconNodeApi for MockBeaconNode { async fn spec(&self) -> Result { self.guard("spec")?; - Ok(Config::mainnet()) + let spec = self.spec.lock().expect("lock").clone(); + Ok(spec.unwrap_or_else(Config::mainnet)) } async fn is_optimistic_or_syncing(&self) -> Result { diff --git a/crates/validator/src/gas_limit_schedule.rs b/crates/validator/src/gas_limit_schedule.rs new file mode 100644 index 000000000..be09b8087 --- /dev/null +++ b/crates/validator/src/gas_limit_schedule.rs @@ -0,0 +1,297 @@ +//! The network's `GAS_LIMIT_SCHEDULE` (EIP-8261), read off every beacon node. +//! +//! The schedule names the default gas limit of a validator with neither its +//! own override nor `--gas-limit` ([`ProposerSettings`]). It identifies no +//! chain, so no node is trusted over another for it, and a node that serves +//! none must not cost the client the schedule another node serves: the first +//! node in `--beacon-nodes` order that serves a non-empty one is taken. An +//! unusable schedule (one that does not decode, or breaks the rules a beacon +//! node holds its own config to) reads as empty, with a warning, in +//! [`crate::beacon_node::dto::config_from_spec_response`]. +//! +//! Read at startup, then again every epoch by [`run`], so a node that comes +//! up, or starts serving the key, after the client started is followed +//! without a restart. Without that, a client whose first node served no +//! schedule would sign the built-in 60M into every proposer preference until +//! restarted, pulling the gas limit away from the network's. +//! +//! A schedule once held is kept while the nodes that answer serve none: a node +//! restarted on a build that predates the key, or on a broken config, is far +//! likelier than a network dropping its schedule, and falling back to 60M is +//! exactly what this module exists to avoid. A node serving another non-empty +//! schedule replaces it. Preferences already signed keep the gas limit they +//! were signed with; each one signed after a change carries the new one. + +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use ethlambda_types::beacon::config::GasLimitSchedule; +use futures_util::future::join_all; +use tracing::{info, warn}; + +use crate::beacon_node::BeaconNodeApi; +use crate::beacon_node::fallback::FallbackBeaconNode; +use crate::proposer_settings::{DEFAULT_GAS_LIMIT, ProposerSettings, gas_limit_schedule_text}; +use crate::slot_clock::SlotClock; + +/// One round of asking every node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ScheduleRead { + /// How many nodes answered `/eth/v1/config/spec` at all. + pub answered: usize, + /// The first non-empty schedule in `--beacon-nodes` order, with that + /// node's position, or `None` when no node that answered serves one. + pub served: Option<(usize, GasLimitSchedule)>, +} + +/// Asks every node for its spec at once, so a node that hangs until its +/// request timeout delays the round by that timeout only, and takes the first +/// non-empty schedule in `nodes`' order. +pub(crate) async fn read(nodes: &[B]) -> ScheduleRead { + let answers = join_all(nodes.iter().map(|node| node.spec())).await; + let answered = answers.iter().filter(|answer| answer.is_ok()).count(); + let served = answers.into_iter().enumerate().find_map(|(node, answer)| { + let schedule = answer.ok()?.gas_limit_schedule; + (!schedule.is_empty()).then_some((node, schedule)) + }); + ScheduleRead { answered, served } +} + +/// What one [`ScheduleFollower::apply`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Applied { + /// No node answered: nothing changed. + NoAnswer, + /// A node served the schedule already held. + Unchanged, + /// A node served another schedule, now held and in the settings. + Took, + /// Nodes answered but none serves a schedule; whatever was held is kept. + /// `warned` when this read gave the warning, which is once per run of + /// such reads, and only while the schedule matters. + NoneServed { warned: bool }, +} + +/// The schedule the client holds, and what it has said about it. +pub(crate) struct ScheduleFollower { + settings: Arc, + held: GasLimitSchedule, + /// Whether an empty schedule changes what this client signs: gloas is + /// scheduled (the schedule applies only from it) and `--gas-limit` was + /// not given (which would override it). Only then is a missing schedule + /// worth a warning. + matters: bool, + /// Whether the warning for the current run of empty reads was given, so + /// it is given once per run rather than every epoch. + warned_empty: bool, +} + +impl ScheduleFollower { + pub(crate) fn new(settings: Arc, matters: bool) -> Self { + Self { + settings, + held: GasLimitSchedule::default(), + matters, + warned_empty: false, + } + } + + pub(crate) fn held(&self) -> &GasLimitSchedule { + &self.held + } + + /// Takes `read` into the proposer settings, logging a change, and warning + /// once when no node serves a schedule while one matters. + pub(crate) fn apply(&mut self, read: ScheduleRead) -> Applied { + let Some((node, schedule)) = read.served else { + // Nothing to go on when no node answered; when some did, none + // serves a schedule, and one held is kept (see the module doc). + if read.answered == 0 { + return Applied::NoAnswer; + } + let warn_now = self.matters && !self.warned_empty; + if warn_now { + self.warned_empty = true; + if self.held.is_empty() { + warn!( + answered = read.answered, + default_gas_limit = DEFAULT_GAS_LIMIT, + "No beacon node serves a usable GAS_LIMIT_SCHEDULE while gloas is \ + scheduled; validators without --gas-limit or their own gas limit \ + target the default until one does" + ); + } else { + warn!( + answered = read.answered, + kept = %gas_limit_schedule_text(&self.held), + "No beacon node serves a GAS_LIMIT_SCHEDULE any more; keeping the one \ + held" + ); + } + } + return Applied::NoneServed { warned: warn_now }; + }; + self.warned_empty = false; + if schedule == self.held { + return Applied::Unchanged; + } + info!( + node, + previous = %gas_limit_schedule_text(&self.held), + schedule = %gas_limit_schedule_text(&schedule), + "Took the gas limit schedule a beacon node serves; validators without --gas-limit \ + or their own gas limit target it" + ); + self.settings.set_gas_limit_schedule(schedule.clone()); + self.held = schedule; + Applied::Took + } +} + +/// How far into an epoch's first slot the schedule is read again: half a +/// slot, clear of the boundary's duties. +fn read_time(clock: &SlotClock, epoch_start_slot: u64) -> SystemTime { + clock.start_of(epoch_start_slot) + clock.slot_duration() / 2 +} + +/// Reads the schedule off every node once an epoch, for as long as the client +/// runs. Spawned by [`crate::run`] and aborted when it returns. +pub(crate) async fn run( + nodes: Arc>, + clock: SlotClock, + mut follower: ScheduleFollower, +) { + let slots_per_epoch = ethlambda_types::beacon::preset::slots_per_epoch(); + loop { + let now = SystemTime::now(); + // The next epoch's read; before genesis, epoch 0's. + let next_epoch = clock.current_epoch().map_or(0, |epoch| epoch + 1); + let at = read_time(&clock, next_epoch * slots_per_epoch); + let wait = at.duration_since(now).unwrap_or_default(); + tokio::time::sleep(wait.max(Duration::from_millis(100))).await; + follower.apply(read(nodes.nodes()).await); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::beacon_node::mock::MockBeaconNode; + use ethlambda_types::beacon::config::{Config, GasLimitScheduleEntry}; + use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32}; + + fn schedule(gas_limit: u64) -> GasLimitSchedule { + vec![GasLimitScheduleEntry { + epoch: 0, + gas_limit, + }] + .into() + } + + fn serving(gas_limit: u64) -> MockBeaconNode { + let mut config = Config::mainnet(); + config.gas_limit_schedule = schedule(gas_limit); + MockBeaconNode::new().with_spec(config) + } + + fn down() -> MockBeaconNode { + let node = MockBeaconNode::new(); + node.failures + .lock() + .expect("lock") + .insert("spec", "down".to_string()); + node + } + + fn follower() -> (ScheduleFollower, Arc) { + let settings = Arc::new(ProposerSettings::new(Bytes32::ZERO, None)); + (ScheduleFollower::new(settings.clone(), true), settings) + } + + const KEY: BlsPubkey = BlsPubkey([1; 48]); + + /// The review's case: the first node serves no schedule (or is down), + /// a later one does, and the later one's is taken rather than leaving + /// every preference at 60M. + #[tokio::test] + async fn the_first_node_that_serves_a_schedule_is_taken() { + let nodes = [MockBeaconNode::new(), down(), serving(200_000_000)]; + let read = read(&nodes).await; + assert_eq!(read.answered, 2); + assert_eq!(read.served, Some((2, schedule(200_000_000)))); + + let (mut follower, settings) = follower(); + assert_eq!(settings.gas_limit(&KEY, 0), DEFAULT_GAS_LIMIT); + assert_eq!(follower.apply(read), Applied::Took); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + } + + /// Order decides between two nodes that both serve one. + #[tokio::test] + async fn the_earlier_node_wins_when_several_serve_one() { + let nodes = [serving(100_000_000), serving(200_000_000)]; + assert_eq!(read(&nodes).await.served, Some((0, schedule(100_000_000)))); + } + + /// A node that starts serving the schedule after startup is followed at + /// the next read; one held is kept when the nodes stop serving it, and + /// replaced by another non-empty one. + #[tokio::test] + async fn a_schedule_is_followed_kept_and_replaced() { + let node = MockBeaconNode::new(); + let nodes = std::slice::from_ref(&node); + let (mut follower, settings) = follower(); + + let none = Applied::NoneServed { warned: true }; + assert_eq!(follower.apply(read(nodes).await), none, "none served yet"); + assert_eq!(settings.gas_limit(&KEY, 0), DEFAULT_GAS_LIMIT); + + let mut config = Config::mainnet(); + config.gas_limit_schedule = schedule(200_000_000); + node.set_spec(config.clone()); + assert_eq!(follower.apply(read(nodes).await), Applied::Took); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + assert_eq!(follower.apply(read(nodes).await), Applied::Unchanged); + + node.set_spec(Config::mainnet()); + assert_eq!(follower.apply(read(nodes).await), none, "kept, and said so"); + assert_eq!(follower.held(), &schedule(200_000_000)); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + + config.gas_limit_schedule = schedule(300_000_000); + node.set_spec(config); + assert_eq!(follower.apply(read(nodes).await), Applied::Took, "replaced"); + assert_eq!(settings.gas_limit(&KEY, 0), 300_000_000); + } + + /// The review's other half: a missing schedule is warned about, once per + /// run of empty reads rather than every epoch, and only when it changes + /// what the client signs (gloas scheduled, no `--gas-limit`). + #[tokio::test] + async fn a_missing_schedule_is_warned_about_once_per_run_when_it_matters() { + let empty = [MockBeaconNode::new()]; + let (mut follower, _) = follower(); + let warned = Applied::NoneServed { warned: true }; + let quiet = Applied::NoneServed { warned: false }; + assert_eq!(follower.apply(read(&empty).await), warned); + assert_eq!(follower.apply(read(&empty).await), quiet, "once per run"); + follower.apply(read(&[serving(200_000_000)]).await); + assert_eq!(follower.apply(read(&empty).await), warned, "a new run"); + + let settings = Arc::new(ProposerSettings::new(Bytes32::ZERO, None)); + let mut irrelevant = ScheduleFollower::new(settings, false); + assert_eq!(irrelevant.apply(read(&empty).await), quiet); + } + + /// No node answering changes nothing. + #[tokio::test] + async fn no_answer_changes_nothing() { + let (mut follower, settings) = follower(); + follower.apply(read(&[serving(200_000_000)]).await); + assert_eq!( + follower.apply(read(&[down(), down()]).await), + Applied::NoAnswer + ); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + } +} diff --git a/crates/validator/src/http_api/proposer.rs b/crates/validator/src/http_api/proposer.rs index 2e292f818..fc297e821 100644 --- a/crates/validator/src/http_api/proposer.rs +++ b/crates/validator/src/http_api/proposer.rs @@ -382,7 +382,11 @@ pub async fn get_gas_limit( ) -> Result>, ApiError> { let pubkey = parse_path_key(&pubkey)?; require_held(&*context.store.read().await, &pubkey)?; - let gas_limit = context.settings.gas_limit(&pubkey); + // The one in force now, which without an override or `--gas-limit` is + // the schedule's for the current epoch (Lighthouse's answer too). Epoch 0 + // before genesis. + let epoch = context.clock.current_epoch().unwrap_or(0); + let gas_limit = context.settings.gas_limit(&pubkey, epoch); Ok(Json(Data { data: GasLimitEntry { pubkey: encode_hex(&pubkey.0), @@ -698,6 +702,41 @@ mod tests { assert_eq!(body["data"]["gas_limit"], DEFAULT_GAS_LIMIT.to_string()); } + /// Without an override, `GET` reports the gas limit in force now, which + /// the network's schedule names for the current epoch (the harness clock + /// started at the Unix epoch, so it is past epoch 1 and short of the last + /// one); an override still wins over it. + #[tokio::test] + async fn the_default_served_is_the_one_scheduled_for_the_current_epoch() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let harness = harness(None); + harness.settings.set_gas_limit_schedule( + vec![ + GasLimitScheduleEntry { + epoch: 1, + gas_limit: 200_000_000, + }, + GasLimitScheduleEntry { + epoch: u64::MAX, + gas_limit: 300_000_000, + }, + ] + .into(), + ); + let path = uri(&harness.pubkey, "gas_limit"); + + let (status, body) = send(&harness.app, request("GET", &path, None)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"]["gas_limit"], "200000000"); + + let set = serde_json::json!({ "gas_limit": "30000000" }); + let (status, _) = send(&harness.app, request("POST", &path, Some(set))).await; + assert_eq!(status, StatusCode::ACCEPTED); + let (_, body) = send(&harness.app, request("GET", &path, None)).await; + assert_eq!(body["data"]["gas_limit"], "30000000"); + } + /// The specification's `Uint64` is a decimal string with no sign and no /// leading zero; a JSON number is not one. #[tokio::test] @@ -717,7 +756,7 @@ mod tests { assert_eq!(status, StatusCode::BAD_REQUEST, "{gas_limit}"); } assert_eq!( - harness.settings.gas_limit(&harness.pubkey), + harness.settings.gas_limit(&harness.pubkey, 0), DEFAULT_GAS_LIMIT ); } @@ -735,7 +774,7 @@ mod tests { let zero = serde_json::json!({ "gas_limit": "0" }); let (status, _) = send(&harness.app, request("POST", &path, Some(zero))).await; assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(harness.settings.gas_limit(&harness.pubkey), 30_000_000); + assert_eq!(harness.settings.gas_limit(&harness.pubkey, 0), 30_000_000); } #[tokio::test] @@ -850,7 +889,7 @@ mod tests { restarted.graffiti(&harness.pubkey), graffiti_from_text("persisted").expect("fits") ); - assert_eq!(restarted.gas_limit(&harness.pubkey), DEFAULT_GAS_LIMIT); + assert_eq!(restarted.gas_limit(&harness.pubkey, 0), DEFAULT_GAS_LIMIT); } /// The file was replaced and only its directory's flush failed: the diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 495688b68..4df0c2d0b 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -32,6 +32,7 @@ pub mod doppelganger; pub mod duties; pub mod error; pub mod exit; +mod gas_limit_schedule; pub mod head_monitor; pub mod http_api; pub(crate) mod in_flight; @@ -149,8 +150,10 @@ pub struct ValidatorConfig { /// The gas limit every validator targets unless the keymanager API gives /// it its own: its builder registrations' before gloas, and its proposer /// preferences' from gloas, which is what the node's own payload is built - /// toward. - pub gas_limit: u64, + /// toward. `None` when `--gas-limit` was not given: the network's + /// `GAS_LIMIT_SCHEDULE` then names it per epoch, and + /// [`proposer_settings::DEFAULT_GAS_LIMIT`] where it names none. + pub gas_limit: Option, /// Builder proposals, or `None` when `--builder-proposals` is off. pub builder: Option, /// The smallest p2p bid, in gwei, a gloas block may be built on @@ -313,6 +316,16 @@ pub async fn run(config: ValidatorConfig, stop: impl Future PreferencesService { None => Before::Unsent, }; // One read for both, so a keymanager write between two reads - // cannot pair an old address with a new gas limit. + // cannot pair an old address with a new gas limit. The gas limit + // is the one for the proposal's epoch, `target`, which is the next + // epoch's for a preference signed ahead. let Some((fee_recipient, target_gas_limit)) = - self.settings.fee_recipient_and_gas_limit(&pubkey) + self.settings.fee_recipient_and_gas_limit(&pubkey, target) else { no_fee_recipient += 1; continue; @@ -574,8 +576,10 @@ impl PreferencesService { }) if done >= round => continue, Some(PqSent { signed, .. }) => (signed, false), None => { + // The gas limit for the proposal's epoch, `target`, as at + // a BLS epoch. let Some((fee_recipient, target_gas_limit)) = - self.settings.fee_recipient_and_gas_limit(&pubkey) + self.settings.fee_recipient_and_gas_limit(&pubkey, target) else { no_fee_recipient += 1; continue; @@ -996,6 +1000,52 @@ mod tests { } } + /// Without `--gas-limit` or an override, each preference carries the gas + /// limit the schedule names for its proposal's epoch, not the wall + /// clock's: the next epoch's preference is signed now, at its own + /// epoch's limit. + #[tokio::test] + async fn the_target_gas_limit_is_the_one_scheduled_for_the_proposal_epoch() { + use crate::proposer_settings::DEFAULT_GAS_LIMIT; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = Arc::new(RwLock::new(store)); + let settings = settings(Some(FEE_RECIPIENT)); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: GLOAS_EPOCH + 1, + gas_limit: 200_000_000, + }] + .into(), + ); + let node = MockBeaconNode::new() + .with_proposers_v2( + GLOAS_EPOCH, + Root::repeat_byte(0x11), + vec![duty(&pubkeys[0], 3, slot_in(GLOAS_EPOCH, 10))], + ) + .with_proposers_v2( + GLOAS_EPOCH + 1, + Root::repeat_byte(0x22), + vec![duty(&pubkeys[0], 3, slot_in(GLOAS_EPOCH + 1, 4))], + ); + let (service, node) = service(node, settings); + + service.poll(slot_in(GLOAS_EPOCH, 1), store).await; + + let mut entries: Vec<_> = submitted(&node) + .into_iter() + .flat_map(|(_, entries)| entries) + .collect(); + entries.sort_by_key(|entry| entry.message.proposal_slot); + let gas_limits: Vec<_> = entries + .iter() + .map(|entry| entry.message.target_gas_limit) + .collect(); + assert_eq!(gas_limits, [DEFAULT_GAS_LIMIT, 200_000_000]); + } + #[tokio::test] async fn a_second_poll_does_not_resubmit() { let (store, pubkeys) = store_with_keys(1); @@ -1104,6 +1154,49 @@ mod tests { assert_eq!(node.submitted_pq_preferences.lock().expect("lock").len(), 1); } + /// A PQ preference carries the gas limit the schedule names for its + /// proposal's epoch, as a BLS one does, rather than `DEFAULT_GAS_LIMIT`: + /// pq-devnet-1 schedules 200M from epoch 0, and a validator left on the + /// default pulled every proposal toward 60M. + #[tokio::test] + async fn a_pq_preference_carries_the_scheduled_gas_limit() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = Arc::new(RwLock::new(store)); + let slot = slot_in(GLOAS_EPOCH, 12); + let current = slot_in(GLOAS_EPOCH, 1); + // The other PQ test's key and secret, so the shared registry holds + // one key whichever runs first; another slot, so another leaf. + crate::pq::derive_and_register(pubkeys[0], &[21; 32], current, None); + let config = context() + .config + .clone() + .with_fork_epoch(ForkName::Eip8483, GLOAS_EPOCH) + .with_fork_epoch(ForkName::Pq, GLOAS_EPOCH); + let context = Arc::new(SigningContext::new(config, Root::repeat_byte(0x42))); + let node = Arc::new(MockBeaconNode::new().with_proposers_v2( + GLOAS_EPOCH, + Root::repeat_byte(0x11), + vec![duty(&pubkeys[0], 3, slot)], + )); + let settings = settings(Some(FEE_RECIPIENT)); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: GLOAS_EPOCH, + gas_limit: 200_000_000, + }] + .into(), + ); + let service = Arc::new(PreferencesService::new(node.clone(), context, settings)); + + service.poll(current, store).await; + + let sent = node.submitted_pq_preferences.lock().expect("lock").clone(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].message.target_gas_limit, 200_000_000); + } + /// A reorg that moves a slot from one of this client's validators to /// another leaves both preferences kept, and each validator's block may /// pay only the address it signed for itself. diff --git a/crates/validator/src/proposer_settings.rs b/crates/validator/src/proposer_settings.rs index 1abb2853c..7d3bb8756 100644 --- a/crates/validator/src/proposer_settings.rs +++ b/crates/validator/src/proposer_settings.rs @@ -1,7 +1,10 @@ //! What each validator proposes with: its fee recipient, graffiti and gas limit. //! //! Every validator starts on the process-wide defaults from the command line. -//! The keymanager API's `feerecipient`, `graffiti` and `gas_limit` endpoints +//! The gas limit's default without `--gas-limit` depends on the epoch: the +//! network's `GAS_LIMIT_SCHEDULE`, read off the beacon node, names one per +//! epoch, and [`DEFAULT_GAS_LIMIT`] covers every epoch it does not. The +//! keymanager API's `feerecipient`, `graffiti` and `gas_limit` endpoints //! override them per key, and `DELETE` puts a key back on the defaults. //! //! # The definitions file is the record; this is the cache @@ -44,7 +47,10 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{PoisonError, RwLock}; -use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32, ExecutionAddress, H160, H256}; +use ethlambda_types::beacon::config::{GasLimitSchedule, MAX_GAS_LIMIT_SCHEDULE_ENTRIES}; +use ethlambda_types::beacon::primitives::{ + BlsPubkey, Bytes32, Epoch, ExecutionAddress, H160, H256, +}; /// A block's graffiti field is exactly this wide. pub const GRAFFITI_BYTES: usize = 32; @@ -77,18 +83,39 @@ pub fn graffiti_to_text(graffiti: &Bytes32) -> String { String::from_utf8_lossy(&graffiti.0[..GRAFFITI_BYTES - padding]).into_owned() } -/// The gas limit a validator with no override reports, unless `--gas-limit` -/// names another. +/// The gas limit of last resort: what a validator with no override reports +/// when `--gas-limit` was not given and the network's `GAS_LIMIT_SCHEDULE` +/// schedules nothing for the epoch (the beacon node does not serve the key, +/// the schedule is empty, or its first entry is still ahead). /// -/// Lighthouse's and Nimbus's default (Lighthouse's when the network config -/// names no gas limit schedule, which this client does not read). Builder -/// registrations carry it as the gas limit the builder should target, from -/// gloas the proposer preferences carry it as the target the node's own -/// payload is built toward too, and the keymanager API serves it as the -/// specification requires. A network whose gas limit is elsewhere needs -/// `--gas-limit`, or every proposal pulls its limit toward this one. +/// Lighthouse's and Nimbus's default, and what Lighthouse falls back to when +/// its schedule names none. Builder registrations carry the resulting gas +/// limit as the one the builder should target, from gloas the proposer +/// preferences carry it as the target the node's own payload is built toward +/// too, and the keymanager API serves it as the specification requires. pub const DEFAULT_GAS_LIMIT: u64 = 60_000_000; +/// `[epoch: gas limit, ...]`, for the startup log line. +/// +/// Bounded like every other text a node sends that reaches a log line. A node +/// can serve a schedule of any length (only a beacon node's own config file is +/// held to [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`]), so at most that many entries +/// are written out and the rest are counted. +pub fn gas_limit_schedule_text(schedule: &GasLimitSchedule) -> String { + let entries = schedule.entries(); + let shown: Vec = entries + .iter() + .take(MAX_GAS_LIMIT_SCHEDULE_ENTRIES) + .map(|entry| format!("{}: {}", entry.epoch, entry.gas_limit)) + .collect(); + let rest = entries.len() - shown.len(); + if rest == 0 { + format!("[{}]", shown.join(", ")) + } else { + format!("[{}, ... and {rest} more]", shown.join(", ")) + } +} + /// `text` as a fee recipient: `0x` and forty hex digits, the keymanager /// specification's `EthAddress` pattern. The zero address is refused: the /// specification forbids it outright, since it would read as an address @@ -157,10 +184,32 @@ pub enum SettingChange { struct Inner { default_fee_recipient: Option, default_graffiti: Bytes32, - default_gas_limit: u64, + /// `--gas-limit`, or `None` when it was not given. + default_gas_limit: Option, + /// The network's `GAS_LIMIT_SCHEDULE`, from the beacon node's + /// `/eth/v1/config/spec`; empty until it is fetched, or when the node does + /// not serve the key. + gas_limit_schedule: GasLimitSchedule, overrides: HashMap, } +impl Inner { + /// The gas limit at `epoch` of a validator with no override of its own: + /// `--gas-limit`, else the one the schedule names for `epoch`, else + /// [`DEFAULT_GAS_LIMIT`]. Lighthouse's order. + fn default_gas_limit(&self, epoch: Epoch) -> u64 { + self.default_gas_limit + .or_else(|| self.gas_limit_schedule.gas_limit_at(epoch)) + .unwrap_or(DEFAULT_GAS_LIMIT) + } + + /// `pubkey`'s gas limit at `epoch`: its override, else the default. + fn gas_limit(&self, pubkey: &BlsPubkey, epoch: Epoch) -> u64 { + let overridden = self.overrides.get(pubkey).and_then(|o| o.gas_limit); + overridden.unwrap_or_else(|| self.default_gas_limit(epoch)) + } +} + /// The defaults and every per-key override, shared by the duty loop and the /// keymanager API. /// @@ -188,16 +237,18 @@ impl ProposerSettings { inner: RwLock::new(Inner { default_fee_recipient: fee_recipient, default_graffiti: graffiti, - default_gas_limit: DEFAULT_GAS_LIMIT, + default_gas_limit: None, + gas_limit_schedule: GasLimitSchedule::default(), overrides: HashMap::new(), }), generation: AtomicU64::new(0), } } - /// These settings with `gas_limit` as the gas limit of every validator - /// with no override of its own, in place of [`DEFAULT_GAS_LIMIT`]. - pub fn with_default_gas_limit(mut self, gas_limit: u64) -> Self { + /// These settings with `gas_limit` (`--gas-limit`) as the gas limit of + /// every validator with no override of its own, at every epoch, in place + /// of the schedule's and [`DEFAULT_GAS_LIMIT`]. `None` leaves those two. + pub fn with_default_gas_limit(mut self, gas_limit: Option) -> Self { self.inner .get_mut() .unwrap_or_else(PoisonError::into_inner) @@ -205,6 +256,22 @@ impl ProposerSettings { self } + /// Take the gas limit of a validator with neither an override nor + /// `--gas-limit` from `schedule` (the network's `GAS_LIMIT_SCHEDULE`), at + /// the epoch each reader names. + /// + /// Set by [`crate::gas_limit_schedule`]: at startup, after these settings + /// are built and before anything that signs reads them, and again whenever + /// its once-an-epoch read of every node finds another schedule. It leaves [`Self::generation`] alone: that counts override + /// writes, and the full registration send each epoch compares every gas + /// limit it signs anyway. + pub fn set_gas_limit_schedule(&self, schedule: GasLimitSchedule) { + self.inner + .write() + .unwrap_or_else(PoisonError::into_inner) + .gas_limit_schedule = schedule; + } + /// A counter that moves whenever a write or delete changes a fee /// recipient or gas limit override; one that leaves them as they were /// does not move it. Equal readings mean no per-key fee recipient or gas @@ -244,26 +311,29 @@ impl ProposerSettings { }) } - /// `pubkey`'s fee recipient and gas limit read together, under one lock, or - /// `None` when it has no fee recipient. + /// `pubkey`'s fee recipient and its gas limit at `epoch` read together, + /// under one lock, or `None` when it has no fee recipient. /// /// For a signed message that carries both (a builder registration, proposer /// preferences): two separate reads could straddle a keymanager write and /// pair an old address with a new gas limit, a combination the operator /// never configured, which the builder then keeps. + /// + /// `epoch` picks the schedule's entry when neither an override nor + /// `--gas-limit` names a gas limit: a preference's proposal epoch, a + /// registration's current one. pub fn fee_recipient_and_gas_limit( &self, pubkey: &BlsPubkey, + epoch: Epoch, ) -> Option<(ExecutionAddress, u64)> { self.read(|inner| { - let overrides = inner.overrides.get(pubkey); - let fee_recipient = overrides + let fee_recipient = inner + .overrides + .get(pubkey) .and_then(|o| o.fee_recipient) .or(inner.default_fee_recipient)?; - let gas_limit = overrides - .and_then(|o| o.gas_limit) - .unwrap_or(inner.default_gas_limit); - Some((fee_recipient, gas_limit)) + Some((fee_recipient, inner.gas_limit(pubkey, epoch))) }) } @@ -275,12 +345,11 @@ impl ProposerSettings { }) } - /// The gas limit `pubkey` reports. - pub fn gas_limit(&self, pubkey: &BlsPubkey) -> u64 { - self.read(|inner| { - let overridden = inner.overrides.get(pubkey).and_then(|o| o.gas_limit); - overridden.unwrap_or(inner.default_gas_limit) - }) + /// The gas limit `pubkey` targets at `epoch`: its override, else + /// `--gas-limit`, else the schedule's for `epoch`, else + /// [`DEFAULT_GAS_LIMIT`]. + pub fn gas_limit(&self, pubkey: &BlsPubkey, epoch: Epoch) -> u64 { + self.read(|inner| inner.gas_limit(pubkey, epoch)) } /// Every override `pubkey` holds, defaults left as `None`. @@ -349,6 +418,7 @@ impl ProposerSettings { #[cfg(test)] mod tests { use super::*; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; use ethlambda_types::beacon::primitives::H160; fn key(byte: u8) -> BlsPubkey { @@ -364,7 +434,7 @@ mod tests { let settings = settings(); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(1)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); } #[test] @@ -376,11 +446,11 @@ mod tests { assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xbb; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x22)); - assert_eq!(settings.gas_limit(&key(1)), 30_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 30_000_000); assert_eq!(settings.fee_recipient(&key(2)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(2)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(2)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(2), 0), DEFAULT_GAS_LIMIT); } /// `--gas-limit` replaces the default every key without an override gets, @@ -388,18 +458,121 @@ mod tests { /// clearing it falls back to the configured default, not the built-in one. #[test] fn a_configured_default_gas_limit_replaces_the_built_in_one() { - let settings = settings().with_default_gas_limit(200_000_000); - assert_eq!(settings.gas_limit(&key(1)), 200_000_000); + let settings = settings().with_default_gas_limit(Some(200_000_000)); + assert_eq!(settings.gas_limit(&key(1), 0), 200_000_000); assert_eq!( - settings.fee_recipient_and_gas_limit(&key(1)), + settings.fee_recipient_and_gas_limit(&key(1), 0), Some((H160([0xaa; 20]), 200_000_000)) ); settings.set_gas_limit(&key(1), 30_000_000); - assert_eq!(settings.gas_limit(&key(1)), 30_000_000); - assert_eq!(settings.gas_limit(&key(2)), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 30_000_000); + assert_eq!(settings.gas_limit(&key(2), 0), 200_000_000); settings.clear_gas_limit(&key(1)); - assert_eq!(settings.gas_limit(&key(1)), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 200_000_000); + } + + /// Two entries, at epochs 100 and 200. + fn schedule() -> GasLimitSchedule { + vec![ + GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }, + GasLimitScheduleEntry { + epoch: 200, + gas_limit: 300_000_000, + }, + ] + .into() + } + + /// Without `--gas-limit`, the schedule names the default per epoch, and + /// [`DEFAULT_GAS_LIMIT`] covers the epochs before its first entry. + #[test] + fn the_schedule_names_the_default_at_each_epoch() { + let settings = settings(); + settings.set_gas_limit_schedule(schedule()); + + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 99), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 100), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 199), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 200), 300_000_000); + assert_eq!( + settings.fee_recipient_and_gas_limit(&key(1), 150), + Some((H160([0xaa; 20]), 200_000_000)) + ); + } + + /// A node that does not serve `GAS_LIMIT_SCHEDULE` leaves the schedule + /// empty, and every epoch gets [`DEFAULT_GAS_LIMIT`]. + #[test] + fn without_a_schedule_every_epoch_gets_the_built_in_default() { + let settings = settings(); + settings.set_gas_limit_schedule(GasLimitSchedule::default()); + for epoch in [0, 100, Epoch::MAX] { + assert_eq!(settings.gas_limit(&key(1), epoch), DEFAULT_GAS_LIMIT); + } + } + + /// The order: a key's own override, then `--gas-limit`, then the + /// schedule, then [`DEFAULT_GAS_LIMIT`]. + #[test] + fn an_override_and_the_flag_both_win_over_the_schedule() { + let flagged = settings().with_default_gas_limit(Some(45_000_000)); + flagged.set_gas_limit_schedule(schedule()); + assert_eq!(flagged.gas_limit(&key(1), 0), 45_000_000); + assert_eq!(flagged.gas_limit(&key(1), 150), 45_000_000); + flagged.set_gas_limit(&key(1), 30_000_000); + assert_eq!(flagged.gas_limit(&key(1), 150), 30_000_000); + assert_eq!( + flagged.fee_recipient_and_gas_limit(&key(1), 150), + Some((H160([0xaa; 20]), 30_000_000)) + ); + + let scheduled = settings().with_default_gas_limit(None); + scheduled.set_gas_limit_schedule(schedule()); + scheduled.set_gas_limit(&key(1), 30_000_000); + assert_eq!(scheduled.gas_limit(&key(1), 150), 30_000_000); + assert_eq!(scheduled.gas_limit(&key(2), 150), 200_000_000); + // Clearing the override puts the key back on the schedule. + scheduled.clear_gas_limit(&key(1)); + assert_eq!(scheduled.gas_limit(&key(1), 150), 200_000_000); + } + + /// A node can serve a schedule of any length, and its text goes into the + /// startup line: at most `MAX_GAS_LIMIT_SCHEDULE_ENTRIES` entries are + /// written out, the rest counted. + #[test] + fn the_gas_limit_schedule_text_is_bounded() { + let schedule = |count: u64| -> GasLimitSchedule { + let entries = (0..count).map(|epoch| GasLimitScheduleEntry { + epoch, + gas_limit: 60_000_000, + }); + entries.collect::>().into() + }; + assert_eq!(gas_limit_schedule_text(&schedule(0)), "[]"); + assert_eq!( + gas_limit_schedule_text(&schedule(2)), + "[0: 60000000, 1: 60000000]" + ); + + let full = gas_limit_schedule_text(&schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES as u64)); + assert!(!full.contains("more"), "{full}"); + + let over = gas_limit_schedule_text(&schedule(100_000)); + let last_shown = format!("{}: 60000000", MAX_GAS_LIMIT_SCHEDULE_ENTRIES - 1); + let first_hidden = format!(" {MAX_GAS_LIMIT_SCHEDULE_ENTRIES}: 60000000"); + let hidden = 100_000 - MAX_GAS_LIMIT_SCHEDULE_ENTRIES; + assert!(over.contains(&last_shown), "{over}"); + assert!(!over.contains(&first_hidden), "{over}"); + assert!( + over.ends_with(&format!(", ... and {hidden} more]")), + "{over}" + ); + assert!(over.len() < full.len() + 64, "{} bytes", over.len()); } /// The pair a signed registration or preference carries agrees with the @@ -407,19 +580,19 @@ mod tests { #[test] fn the_fee_recipient_and_gas_limit_read_together_match_the_single_reads() { let settings = ProposerSettings::new(Bytes32::ZERO, None); - assert_eq!(settings.fee_recipient_and_gas_limit(&key(1)), None); + assert_eq!(settings.fee_recipient_and_gas_limit(&key(1), 0), None); settings.set_gas_limit(&key(1), 30_000_000); - assert_eq!(settings.fee_recipient_and_gas_limit(&key(1)), None); + assert_eq!(settings.fee_recipient_and_gas_limit(&key(1), 0), None); settings.set_fee_recipient(&key(1), H160([0xbb; 20])); assert_eq!( - settings.fee_recipient_and_gas_limit(&key(1)), + settings.fee_recipient_and_gas_limit(&key(1), 0), Some((H160([0xbb; 20]), 30_000_000)) ); let defaults = self::settings(); assert_eq!( - defaults.fee_recipient_and_gas_limit(&key(2)), + defaults.fee_recipient_and_gas_limit(&key(2), 0), Some((H160([0xaa; 20]), DEFAULT_GAS_LIMIT)) ); } @@ -456,7 +629,7 @@ mod tests { settings.forget(&key(1)); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(1)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); } #[test] @@ -491,7 +664,7 @@ mod tests { ); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xbb; 20]))); assert_eq!( - settings.gas_limit(&key(1)), + settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT, "an override the seed does not carry is gone" ); diff --git a/crates/validator/src/registration.rs b/crates/validator/src/registration.rs index b24689fcf..8d39fb2f4 100644 --- a/crates/validator/src/registration.rs +++ b/crates/validator/src/registration.rs @@ -107,7 +107,9 @@ //! //! # The per-slot check is one atomic read //! -//! Only a keymanager write changes what a registration says, so +//! Only a keymanager write changes what a registration says between two +//! epochs' full sends (the gas limit schedule moves a default only at an +//! epoch, and each full send compares every value it signs), so //! [`RegistrationService::register_changed`] compares //! [`ProposerSettings::generation`] with the one it last signed against and //! returns before touching the store when it has not moved. While something @@ -288,12 +290,16 @@ impl RegistrationService { /// per lookup, inside the signer), and the cache is written last, so a key /// is cached only once its chunk is signed in full. /// - /// `now_secs` is a parameter so a test can fix the timestamp. + /// `now_secs` is a parameter so a test can fix the timestamp. `epoch` is + /// the one the send is for, which picks the gas limit schedule's entry for + /// a validator with no gas limit of its own (see + /// [`ProposerSettings::fee_recipient_and_gas_limit`]). async fn current( &self, store: &RwLock, pubkeys: &[BlsPubkey], now_secs: u64, + epoch: Epoch, ) -> Current { /// Where a validator's registration comes from, in `pubkeys`' order. enum Source { @@ -318,7 +324,7 @@ impl RegistrationService { } let Some((fee_recipient, gas_limit)) = - self.settings.fee_recipient_and_gas_limit(pubkey) + self.settings.fee_recipient_and_gas_limit(pubkey, epoch) else { no_fee_recipient += 1; if signed.contains_key(pubkey) { @@ -443,6 +449,7 @@ impl RegistrationService { self: &Arc, store: &Arc>, pubkeys: &[BlsPubkey], + epoch: Epoch, ) -> Current { let now_secs = Self::now_secs(); let mut current = Current { @@ -457,7 +464,7 @@ impl RegistrationService { // thread is outside it, so it enters it to wait on them. let runtime = tokio::runtime::Handle::current(); let part = tokio::task::spawn_blocking(move || { - runtime.block_on(service.current(&store, &chunk, now_secs)) + runtime.block_on(service.current(&store, &chunk, now_secs, epoch)) }) .await; match part { @@ -532,7 +539,7 @@ impl RegistrationService { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = pubkeys.clone(); - let current = self.current_blocking(&store, &pubkeys).await; + let current = self.current_blocking(&store, &pubkeys, epoch).await; if current.no_fee_recipient > 0 { warn!( skipped = current.no_fee_recipient, @@ -591,7 +598,7 @@ impl RegistrationService { if known.is_empty() { return; } - let current = self.current_blocking(&store, &known).await; + let current = self.current_blocking(&store, &known, epoch).await; // What changed, and what an earlier slot could not get any node to // take. Both are read off `all`, the newest registration per key, so a // key that changed again since its failed send goes out once, as now. @@ -696,11 +703,11 @@ mod tests { let store = RwLock::new(store); let (service, _) = service(Config::mainnet(), settings(Some(H160([0xab; 20])))); - let first = service.current(&store, &pubkeys, 1_000).await; + let first = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(first.all.len(), 2); assert_eq!(first.changed.len(), 2); - let second = service.current(&store, &pubkeys, 2_000).await; + let second = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(second.all, first.all, "same timestamp and signature"); assert!(second.changed.is_empty()); assert_eq!(second.all[0].message.timestamp, 1_000); @@ -712,11 +719,11 @@ mod tests { let store = RwLock::new(store); let settings = settings(Some(H160([0xab; 20]))); let (service, _) = service(Config::mainnet(), settings.clone()); - let first = service.current(&store, &pubkeys, 1_000).await; + let first = service.current(&store, &pubkeys, 1_000, 0).await; settings.set_fee_recipient(&pubkeys[0], H160([0xcd; 20])); settings.set_gas_limit(&pubkeys[1], 30_000_000); - let second = service.current(&store, &pubkeys, 2_000).await; + let second = service.current(&store, &pubkeys, 2_000, 0).await; let changed: Vec<_> = second.changed.iter().map(|r| r.message.pubkey).collect(); assert_eq!(changed, vec![pubkeys[0], pubkeys[1]]); @@ -728,6 +735,34 @@ mod tests { assert_eq!(second.all[2], first.all[2], "the third is untouched"); } + /// A validator with no gas limit of its own registers the one the schedule + /// names for the send's epoch, and is re-signed when that moves, which + /// no keymanager write signals: the epoch's full send compares the values. + #[tokio::test] + async fn the_gas_limit_follows_the_schedule_at_the_sends_epoch() { + use crate::proposer_settings::DEFAULT_GAS_LIMIT; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = RwLock::new(store); + let settings = settings(Some(H160([0xab; 20]))); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: 5, + gas_limit: 200_000_000, + }] + .into(), + ); + let (service, _) = service(Config::mainnet(), settings); + + let before = service.current(&store, &pubkeys, 1_000, 4).await; + assert_eq!(before.all[0].message.gas_limit, DEFAULT_GAS_LIMIT); + + let from = service.current(&store, &pubkeys, 2_000, 5).await; + assert_eq!(from.changed.len(), 1, "re-signed for the new gas limit"); + assert_eq!(from.all[0].message.gas_limit, 200_000_000); + } + /// A relay drops a registration that is not newer than the one it holds, /// so a change signed within the same second, or after the clock stepped /// back, still gets a later timestamp than the registration it replaces. @@ -737,20 +772,20 @@ mod tests { let store = RwLock::new(store); let settings = settings(Some(H160([0xab; 20]))); let (service, _) = service(Config::mainnet(), settings.clone()); - let first = service.current(&store, &pubkeys, 2_000).await; + let first = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(first.all[0].message.timestamp, 2_000); settings.set_gas_limit(&pubkeys[0], 30_000_000); - let same_second = service.current(&store, &pubkeys, 2_000).await; + let same_second = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(same_second.changed[0].message.timestamp, 2_001); settings.set_gas_limit(&pubkeys[0], 31_000_000); - let stepped_back = service.current(&store, &pubkeys, 1_000).await; + let stepped_back = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(stepped_back.changed[0].message.timestamp, 2_002); // Once the clock is ahead again, its reading is used. settings.set_gas_limit(&pubkeys[0], 32_000_000); - let caught_up = service.current(&store, &pubkeys, 5_000).await; + let caught_up = service.current(&store, &pubkeys, 5_000, 0).await; assert_eq!(caught_up.changed[0].message.timestamp, 5_000); } @@ -762,7 +797,7 @@ mod tests { settings.set_fee_recipient(&pubkeys[1], H160([0xcd; 20])); let (service, _) = service(Config::mainnet(), settings); - let current = service.current(&store, &pubkeys, 1_000).await; + let current = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(current.no_fee_recipient, 1); assert_eq!(current.all.len(), 1); @@ -776,7 +811,7 @@ mod tests { store.remove(&pubkeys[0]); let store = RwLock::new(store); - let current = service.current(&store, &pubkeys, 1_000).await; + let current = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(current.all.len(), 1); assert_eq!(current.all[0].message.pubkey, pubkeys[1]); diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 8e5e40ce9..c4cefe75a 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -435,7 +435,10 @@ asks for again. - **Proposing**: the client sends its VRF proof for the slot (the RANDAO reveal) to `POST /eth/v1/validator/pq_blocks/{slot}`, signs the block and the envelope revealing its self-built payload at their leaves, and publishes - both. The block's attestations are packed a third of a slot ahead, when + both. The payload is built toward the gas target of the proposer's own PQ + preferences for the slot (the network's `GAS_LIMIT_SCHEDULE`, unless + `--gas-limit` or the keymanager says otherwise), else the parent's gas + limit, which would hold the chain's limit where it is. The block's attestations are packed a third of a slot ahead, when the chain actor starts the slot's payload build for a proposer a validator client registered here (`ethlambda_blockchain::pq_attestation_packing`): it picks, from the aggregates it validated, what `process_attestation` diff --git a/docs/cli.md b/docs/cli.md index 5d70b2a2e..d893a529e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -379,7 +379,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | `--metrics-port` | `5064` | Prometheus metrics port | | `--keymanager-port` | `5062` | Keymanager API port. Only bound with `--enable-keymanager` | | `--suggested-fee-recipient` | none | Execution address to receive block rewards, `0x`-prefixed, for every validator the keymanager API gives no address of its own. Optional, and startup warns when it is absent: without it the beacon node picks an address, and it will not be yours. The addresses reach each beacon node as one `prepare_beacon_proposer` request every slot, listing each validator that has an index on chain and an address, as Lighthouse's validator client sends it. The zero address is accepted, as every other client accepts it, but reported at error at startup: it burns the rewards, and builder registrations and proposer preferences sign it for the builder to pay | -| `--gas-limit` | `60000000` | The gas limit every validator targets, unless the keymanager API gives it its own. Before gloas it goes into builder registrations (with `--builder-proposals`). From gloas it goes into the proposer preferences, which are published for every proposal, and the beacon node builds this client's own payloads toward it as well, so a network whose gas limit is not 60M needs it set, or every proposal pulls the limit toward 60M. **Sepolia and Platåberget schedule `200000000`** (their `config.yaml`'s `GAS_LIMIT_SCHEDULE`, which this client does not read yet, [#795](https://github.com/lambdaclass/ethlambda/issues/795)), so on either pass `--gas-limit 200000000`. Must be positive | +| `--gas-limit` | the network's schedule, else `60000000` | The gas limit every validator targets, unless the keymanager API gives it its own. Before gloas it goes into builder registrations (with `--builder-proposals`). From gloas it goes into the proposer preferences, which are published for every proposal, and the beacon node builds this client's own payloads toward it as well. Without it, each validator targets the gas limit the network's `GAS_LIMIT_SCHEDULE` (served on the beacon nodes' `/eth/v1/config/spec`; every node is asked at startup and again every epoch, and the first in `--beacon-nodes` order that serves a non-empty schedule is followed, with a warning while none does and gloas is scheduled) names for the proposal's epoch, and `60000000` for an epoch the schedule names none or a node that does not serve it, as Lighthouse does; Sepolia's, Platåberget's and pq-devnet-1's schedules name `200000000`, so none needs the flag. Must be positive | | `--graffiti` | empty | Text for the graffiti field of proposed blocks, for every validator the keymanager API gives no graffiti of its own. At most 32 bytes as UTF-8, right-padded with zeros. Refused rather than truncated if longer. An ethlambda beacon node appends both clients' versions to it (see [`rpc.md`](rpc.md#validator-endpoints)) | | `--enable-keymanager` | off | Serve the keymanager API: keystores, remote keys, plus each validator's own fee recipient, graffiti and gas limit. Off by default because it mutates key material | | `--web3signer-url` | none | Base URL of a Web3Signer (`https://signer:9000`): the signer a remote key imported through `POST /eth/v1/remotekeys` without a `url` of its own is assigned to. Checked for shape at startup. Keys whose definitions entry names a signer need no default | @@ -825,7 +825,7 @@ give one validator its own value in place of the command line's default: |---|---|---| | `feerecipient` | `--suggested-fee-recipient` | Once the duties of the slot it is set in are done, when the fee recipients are sent to the beacon node again, as they are after every slot's duties (the next slot's while a slow beacon node still holds the last send). A validator imported since the last epoch boundary, or with no index on chain yet, is first sent once an epoch boundary resolves its index. A block proposed before then pays the address the node was last given, and the check before signing reports the mismatch. With `--builder-proposals`, the next builder registration carries it too, usually at the next slot (later while the epoch's full registration send is still running) and again every slot until a node accepts it or the epoch's full send carries it, and an ethlambda beacon node takes it from there. A `DELETE` that leaves a validator with no address at all (no `--suggested-fee-recipient` either) sends no fee recipient and no registration, so the beacon node and the builder keep paying the address they were last given. From gloas, the proposer preferences carry it, from the next dependent root on | | `graffiti` | `--graffiti` | The next proposal | -| `gas_limit` | `--gas-limit` | Before gloas, the next builder registration with `--builder-proposals` (usually at the next slot, later while the epoch's full registration send is still running, and again every slot until a node accepts it or the epoch's full send carries it), and stored and served only without it. From gloas, the proposer preferences' target gas limit, from the next dependent root on, flag or not | +| `gas_limit` | `--gas-limit`, else the network's schedule | Before gloas, the next builder registration with `--builder-proposals` (usually at the next slot, later while the epoch's full registration send is still running, and again every slot until a node accepts it or the epoch's full send carries it), and stored and served only without it. From gloas, the proposer preferences' target gas limit, from the next dependent root on, flag or not | **These persist.** Each is written onto the validator's entry in `validator_definitions.yml` (`suggested_fee_recipient`, `graffiti`, `gas_limit`, diff --git a/docs/data_storage.md b/docs/data_storage.md index 706056320..9bc070327 100644 --- a/docs/data_storage.md +++ b/docs/data_storage.md @@ -284,7 +284,8 @@ different checkpoints. | `chain` | raw byte | both | Which consensus protocol this directory holds (`Chain`) | | `preset` | raw byte | both | Which SSZ preset the writing build used (`Preset`) | | `time` | `u64` | both | The store clock, as a **UNIX timestamp in milliseconds** | -| `config` | `Config` | both | The node's runtime configuration | +| `config` | `Config` | both | The node's runtime configuration, except the keys below that have rows of their own | +| `config_gas_limit_schedule` | `List[GasLimitScheduleEntry, 32]` | both | `GAS_LIMIT_SCHEDULE` (gloas, EIP-8261); absent in a directory written before it | | `head` | `H256` | both | Current fork choice head | | `anchor_slot` | `u64` | both | The slot this directory's chain begins at | | `states_pruned_below` | `u64` | both | Exclusive upper bound of the `States`/`StateDiffs` slots already range-deleted; absent means 0 | @@ -298,6 +299,18 @@ Rows marked for one chain are never written on the other, so reaching one through the wrong chain's accessor panics naming the key rather than reading a zero. That is deliberate: a data directory holds one chain for its whole life. +`config` is a positional SSZ container, so a field added to it would leave +every row written before it undecodable. A `Config` key added since +`DB_VERSION` 10 therefore takes zero bytes there and gets a `config_*` row of its +own (`CONFIG_ROWS` in `store.rs`). An older directory just lacks the row: a +beacon resume reports the key as missing, adds the config file's value and +writes the row, instead of failing. An older build never reads the row. Every +`config*` row is written in one batch, at bootstrap and by `replace_config`. +A lean resume never rewrites `config`, so a lean directory that predates a row +goes on lacking it and runs on the field's zero-width default; each such key's +default must therefore be the value `Config::lean` holds, as +`GAS_LIMIT_SCHEDULE`'s empty schedule is. + #### One clock, three readings `time` is the only clock either chain keeps, and it is a UNIX millisecond. @@ -341,9 +354,10 @@ migration path. `config` and `chain` are the odd ones out among the mutable rows: written at bootstrap (`init_store` for lean, `init_beacon` for beacon) and not mutated as the chain progresses. `chain` is never rewritten (it has a getter, -`Store::chain`, and no setter). `config` is rewritten in one place, -`Store::replace_config`, by a beacon resume whose config file changed values -the directory does not contradict (see below), and that method panics unless +`Store::chain`, and no setter). `config` (with its `config_*` rows) is +rewritten in one place, `Store::replace_config`, by a beacon resume whose +config file changed values the directory does not contradict (see below) or +whose directory predates a `config_*` row, and that method panics unless its `Store` holds the only handle to the cached copy. Because neither changes once a `Store` is shared, the `Store` keeps a copy of each in memory, and reads of them never reach the backend. Every other `Metadata` key is mutated @@ -397,8 +411,8 @@ because a second row denominated in `slot ‖ root` would be a value that could drift from the first. `init_beacon` writes the two beacon-only keys plus `db_version`, `chain`, -`preset`, `config`, `time`, `head`, `anchor_slot`, `latest_justified` and -`latest_finalized` in one atomic batch. +`preset`, `config` and its `config_*` rows, `time`, `head`, `anchor_slot`, +`latest_justified` and `latest_finalized` in one atomic batch. `anchor_slot` is the odd one among these: every other row is either a format tag or something a later writer moves, while this one is written once at @@ -907,7 +921,8 @@ A `Store` is created through one of four constructors in The first two funnel into `init_store`, which writes the anchor in **one atomic batch**: the `Metadata` keys a lean directory needs (the format version -and the chain and preset tags, time, config, head = safe_target = anchor root, +and the chain and preset tags, time, config and its `config_*` rows, head = +safe_target = anchor root, justified = finalized = anchor checkpoint), the anchor header, its `BlockRoots` entry, the body if non-empty, a full snapshot into `States` keyed by the anchor's slot and root (the base of every future diff chain), and the anchor's `LiveChain` entry. `time` @@ -926,7 +941,8 @@ one row an import does not write is the anchor's `BlockRoots` entry, which `index_beacon_anchor` adds right after the block (see [BlockRoots](#blockroots)). `from_db_state` is the restore path: it reads `db_version`, `preset`, `chain`, -`config` and `anchor_slot` from `Metadata`, returning `None` for an empty DB. A format +`config` (with whichever `config_*` rows the directory has) and `anchor_slot` +from `Metadata`, returning `None` for an empty DB. A format mismatch is still fatal, failing with `Error::DbVersionMismatch` or `Error::PresetMismatch` rather than reading on, but `from_db_state` no longer judges the network or the chain, and it does not mutate anything either: it diff --git a/docs/rpc.md b/docs/rpc.md index 3bcc6ccd7..e53731e6c 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -344,7 +344,11 @@ the publish endpoints. The Beacon API has no PQ block production yet, so ethlambda's validator client asks `POST /eth/v1/validator/pq_blocks/{slot}` with `{"randao_reveal": [], "graffiti"?}`; the block's graffiti gets both clients' codes appended, as `produceBlockV3`'s -does (see its **Graffiti** note below). Attester duties at a PQ epoch add `is_aggregator`, the validator's seat in +does (see its **Graffiti** note below). The payload is built toward the gas +target of the proposer's own signed PQ preferences for the slot, when this +node holds them under the slot's dependent root, else the parent bid's gas +limit; its fee recipient is `prepare_beacon_proposer`'s, else the zero +address. Attester duties at a PQ epoch add `is_aggregator`, the validator's seat in its committee's aggregation committee, and `GET aggregate_attestation` at a PQ slot answers `{"aggregate", "proof"}`, the aggregate this node proved for its aggregators' committee (Lighthouse's PQ branch's `PqAggregate`), or 404. @@ -1025,6 +1029,13 @@ gloas's `MAX_*_SIZE` preset keys, which bound gossip message sizes the node does not run on. Domain types and withdrawal prefixes are `0x`-prefixed hex; `VERSIONED_HASH_VERSION_KZG` is a decimal, as lighthouse reports it. `GENESIS_TIME` is absent: `/eth/v1/beacon/genesis` reports it. +`GAS_LIMIT_SCHEDULE` (gloas, EIP-8261) is a list of `{"EPOCH", "GAS_LIMIT"}` +entries with quoted values, ascending by epoch, as `BLOB_SCHEDULE` is and as +lighthouse reports it, and `[]` on a network that schedules nothing (lighthouse +leaves the key out while gloas is unscheduled). Validator clients, this one's +included, take their default gas limit from it. The data directory stores it, +in a row of its own; a directory written before that row existed takes the +network `config.yaml`'s on its next start. The configuration keys come from the `Config` the data directory was initialized with. Some of them (the custody and subnet counts, the From 6f8a4e2a1b74f7b2e25564248f2fa0a55751620d Mon Sep 17 00:00:00 2001 From: ilitteri Date: Thu, 3 Dec 2026 22:39:54 -0300 Subject: [PATCH 24/25] Port the PQ measurement telemetry (eth.telemetry/0.5, registry 0.10.0) to pq-devnet-1 pq-devnet-1 exported no PQ measurement events: the telemetry only lived on pq-devnet-2, where it arrived in the same commit as the ERC-8517 keys and the X_COMMITTEE_COUNTS rotation (470cdfb8), then moved to wire 0.4 (fcbf6a87) and 0.5 (142f7fcd). pq-devnet-1 is live without those protocol changes, so this carries the telemetry alone: - ethlambda-telemetry's pq_events module and its lifecycle test, byte for byte pq-devnet-2's: OTLP Logs over grpc and http/protobuf configured through OTEL_*, the pq.* events of ethDreamer/pq-measurement-spec at wire 0.5, and the pq_measurement_* exporter-health counters. - --telemetry-events=pq on `beacon` and `validator`, and every hook site the pq-devnet-2 branch has: gossip receipt, admission, validation and pool result in p2p, publication results in the swarm adapter, committee and proposal duties and proving operations in rpc, merge calls in block packing, backend calls in ethlambda-crypto, proof verification timing in the PQ gossip rules, and the validator client's duty schedule, publication and abandonment. - The validator client now reads CONFIG_NAME from the node's spec, so its pq.context names the network rather than the default. Nothing of ERC-8517 or X_COMMITTEE_COUNTS is included; the telemetry crate is identical to pq-devnet-2's, and the lifecycle test's records pass the spec's schemas, tools/metadata.py and tools/otlp.py at efdd060. --- Cargo.lock | 19 + bin/ethlambda/src/cli.rs | 7 + bin/ethlambda/src/main.rs | 40 + bin/ethlambda/src/validator.rs | 20 + bin/ethlambda/src/version.rs | 3 + crates/blockchain/Cargo.toml | 1 + .../blockchain/src/pq_attestation_packing.rs | 84 +- crates/blockchain/state_transition/Cargo.toml | 1 + .../state_transition/src/beacon/gossip/pq.rs | 10 +- crates/common/crypto/Cargo.toml | 1 + crates/common/crypto/src/stark.rs | 62 +- crates/common/crypto/src/stark/leanvm.rs | 25 +- crates/common/telemetry/Cargo.toml | 21 +- crates/common/telemetry/src/lib.rs | 1 + crates/common/telemetry/src/pq_events/duty.rs | 348 ++++++ .../common/telemetry/src/pq_events/gossip.rs | 802 +++++++++++++ .../telemetry/src/pq_events/hardware.rs | 120 ++ .../common/telemetry/src/pq_events/health.rs | 220 ++++ crates/common/telemetry/src/pq_events/mod.rs | 1050 +++++++++++++++++ crates/common/telemetry/src/pq_events/otlp.rs | 1046 ++++++++++++++++ .../common/telemetry/src/pq_events/proof.rs | 280 +++++ .../telemetry/src/pq_events/settings.rs | 386 ++++++ .../common/telemetry/src/pq_events/traffic.rs | 508 ++++++++ crates/common/telemetry/tests/pq_lifecycle.rs | 503 ++++++++ crates/net/p2p/Cargo.toml | 1 + crates/net/p2p/src/beacon/engine_columns.rs | 4 +- crates/net/p2p/src/beacon/pq.rs | 213 +++- crates/net/p2p/src/beacon/verdict.rs | 15 + crates/net/p2p/src/gossipsub/handler.rs | 53 +- crates/net/p2p/src/lib.rs | 31 + crates/net/p2p/src/swarm_adapter.rs | 226 +++- crates/net/rpc/Cargo.toml | 1 + crates/net/rpc/src/beacon/pq_aggregation.rs | 241 +++- crates/net/rpc/src/beacon/pq_proposal.rs | 61 + crates/net/rpc/src/beacon/validator.rs | 65 +- crates/validator/Cargo.toml | 1 + crates/validator/src/aggregation.rs | 90 +- crates/validator/src/beacon_node/dto.rs | 5 + crates/validator/src/duties.rs | 54 + crates/validator/src/error.rs | 3 + crates/validator/src/lib.rs | 45 + crates/validator/src/proposal.rs | 20 +- crates/validator/src/slot_clock.rs | 7 + docs/beacon_pq.md | 24 + docs/cli.md | 2 + docs/metrics.md | 14 + 46 files changed, 6639 insertions(+), 95 deletions(-) create mode 100644 crates/common/telemetry/src/pq_events/duty.rs create mode 100644 crates/common/telemetry/src/pq_events/gossip.rs create mode 100644 crates/common/telemetry/src/pq_events/hardware.rs create mode 100644 crates/common/telemetry/src/pq_events/health.rs create mode 100644 crates/common/telemetry/src/pq_events/mod.rs create mode 100644 crates/common/telemetry/src/pq_events/otlp.rs create mode 100644 crates/common/telemetry/src/pq_events/proof.rs create mode 100644 crates/common/telemetry/src/pq_events/settings.rs create mode 100644 crates/common/telemetry/src/pq_events/traffic.rs create mode 100644 crates/common/telemetry/tests/pq_lifecycle.rs diff --git a/Cargo.lock b/Cargo.lock index 18bcc9fd6..e5f226dab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2085,6 +2085,7 @@ dependencies = [ "blst", "claims", "ethlambda-metrics", + "ethlambda-telemetry", "ethlambda-types", "hex", "keccak 0.1.6", @@ -2167,6 +2168,7 @@ dependencies = [ "lru", "rand 0.8.6", "secp256k1 0.30.0", + "serde_json", "sha2", "snap", "spawned-concurrency", @@ -2189,6 +2191,7 @@ dependencies = [ "ethlambda-network-api", "ethlambda-state-transition", "ethlambda-storage", + "ethlambda-telemetry", "ethlambda-test-fixtures", "ethlambda-types", "ethlambda-validator", @@ -2234,6 +2237,7 @@ dependencies = [ "ethlambda-crypto", "ethlambda-metrics", "ethlambda-storage", + "ethlambda-telemetry", "ethlambda-test-fixtures", "ethlambda-types", "foldhash 0.2.0", @@ -2281,13 +2285,27 @@ name = "ethlambda-telemetry" version = "1.0.0" dependencies = [ "axum", + "bytes", "ethlambda-metrics", + "flate2", "hex", + "http", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "prost", "reqwest", + "rustls", + "rustls-pki-types", "serde", "serde_json", + "sha2", "tokio", "tracing", + "url", + "uuid", + "webpki-roots", ] [[package]] @@ -2335,6 +2353,7 @@ dependencies = [ "ctr", "ethlambda-crypto", "ethlambda-metrics", + "ethlambda-telemetry", "ethlambda-types", "futures-util", "hex", diff --git a/bin/ethlambda/src/cli.rs b/bin/ethlambda/src/cli.rs index 5f86eec0e..55f8c3a20 100644 --- a/bin/ethlambda/src/cli.rs +++ b/bin/ethlambda/src/cli.rs @@ -470,6 +470,13 @@ pub(crate) struct MainnetOptions { /// finalized checkpoint. #[arg(long, default_value_t = ethlambda_rpc::FallbackThresholds::DEFAULT.epochs_since_finalization, requires = "builder")] pub(crate) builder_fallback_epochs_since_finalization: u64, + + /// Comma-separated telemetry event families to export over OTLP Logs + /// (`pq` in `eth.telemetry/0.5`). Configured via standard `OTEL_*` + /// environment variables (`OTEL_EXPORTER_OTLP_LOGS_*`, + /// `OTEL_RESOURCE_ATTRIBUTES` with `eth.node.id`, `OTEL_SERVICE_NAME`). + #[arg(long, value_parser = ethlambda_telemetry::pq_events::event_families)] + pub(crate) telemetry_events: Option, } /// `--builder`'s value, refused while the flags are parsed unless it is an diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index e8956b9e0..d4df086a1 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -795,6 +795,45 @@ async fn run_node(options: Options) -> eyre::Result<()> { } }; + if let Some(ref families) = mainnet.telemetry_events { + ethlambda_telemetry::pq_events::event_families(families) + .map_err(|e| eyre::eyre!(e))?; + ethlambda_telemetry::pq_events::ExportSettings::from_env("ethlambda-bn") + .map_err(|e| eyre::eyre!(e))?; + let cfg = store.config(); + if cfg.pq_fork_epoch != ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH { + use ethlambda_crypto::stark::{ + self, + leanvm::{LEANVM_REV, LeanVmConfig}, + }; + let cores = std::thread::available_parallelism().map_or(1, usize::from); + let effective_threads = if mainnet.pq_prover_threads == 0 { + cores + } else { + mainnet.pq_prover_threads.min(cores) + }; + ethlambda_telemetry::pq_events::start( + ethlambda_telemetry::pq_events::StartParams { + role: "bn", + network: cfg.config_name.as_str(), + genesis_root: format!( + "0x{}", + hex::encode(params.wire.genesis_validators_root.0) + ), + genesis_time: params.wire.genesis_time, + slot_duration: std::time::Duration::from_millis(cfg.slot_duration_ms), + client_commit: version::GIT_COMMIT, + prover_revision: Some(LEANVM_REV), + prover_backend: Some(stark::backend_name()), + log_inverse_rate: Some(u64::from(LeanVmConfig::default().log_inv_rate)), + effective_prover_threads: Some(effective_threads), + }, + ) + .map_err(|e| eyre::eyre!(e))?; + info!("Exporting eth.telemetry/0.5 PQ measurement events over OTLP Logs"); + } + } + ChainSetup { wire: WireConfig::Beacon(Box::new(params.wire)), discovery: DiscoveryWireEntries { @@ -1244,6 +1283,7 @@ async fn wait_for_shutdown(node: RunningNode) { let _ = node.http.await; // After the actors, which are the only emitters, have stopped. ethlambda_telemetry::shutdown(TELEMETRY_FLUSH_TIMEOUT).await; + ethlambda_telemetry::pq_events::shutdown(TELEMETRY_FLUSH_TIMEOUT).await; info!("Shutdown complete"); } diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index b1b0b8a42..df683f59a 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -211,6 +211,13 @@ pub(crate) struct ValidatorOptions { /// broken, or a proxy in front of it that holds events back. #[arg(long, default_value = "false")] pub(crate) disable_event_stream: bool, + + /// Comma-separated telemetry event families to export over OTLP Logs + /// (`pq` in `eth.telemetry/0.5`). Configured via standard `OTEL_*` + /// environment variables (`OTEL_EXPORTER_OTLP_LOGS_*`, + /// `OTEL_RESOURCE_ATTRIBUTES` with `eth.node.id`, `OTEL_SERVICE_NAME`). + #[arg(long, value_parser = ethlambda_telemetry::pq_events::event_families)] + pub(crate) telemetry_events: Option, } impl ValidatorOptions { @@ -332,6 +339,8 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { vrf_state_url: options.vrf_state_url, xmss_cache_url: options.xmss_cache_url, event_stream: !options.disable_event_stream, + telemetry_events: options.telemetry_events, + client_commit: crate::version::GIT_COMMIT.to_string(), }; ethlambda_validator::run(config, stop) .await @@ -364,6 +373,7 @@ mod tests { vrf_state_url: None, xmss_cache_url: None, disable_event_stream: false, + telemetry_events: None, } } @@ -604,4 +614,14 @@ mod tests { "the message must count bytes, not characters, got {err}" ); } + + #[test] + fn telemetry_events_accepts_pq_once_and_rejects_unknown_or_duplicate_flags() { + let ok = parse(&["--telemetry-events=pq"]).expect("pq is valid"); + assert_eq!(ok.telemetry_events.as_deref(), Some("pq")); + assert!(parse(&["--telemetry-events=pq,pq"]).is_ok()); + assert!(parse(&["--telemetry-events=unknown"]).is_err()); + assert!(parse(&["--telemetry-events="]).is_err()); + assert!(parse(&["--telemetry-events=pq", "--telemetry-events=pq"]).is_err()); + } } diff --git a/bin/ethlambda/src/version.rs b/bin/ethlambda/src/version.rs index 0f2927902..a5a1e8c51 100644 --- a/bin/ethlambda/src/version.rs +++ b/bin/ethlambda/src/version.rs @@ -11,6 +11,9 @@ use ethlambda_engine::types::ClientVersionV1; /// survived a change of hash function unchanged and so cannot stand in for it. pub const LEANVM_REV: &str = env!("ETHLAMBDA_LEANVM_REV"); +/// Full git commit hash baked at build time by `build.rs`. +pub const GIT_COMMIT: &str = env!("ETHLAMBDA_GIT_COMMIT"); + /// Environment variable that overrides the release channel baked at build time. /// /// Promoting a release candidate stamps `ETHLAMBDA_CHANNEL=stable` onto the diff --git a/crates/blockchain/Cargo.toml b/crates/blockchain/Cargo.toml index d19d963be..b95190125 100644 --- a/crates/blockchain/Cargo.toml +++ b/crates/blockchain/Cargo.toml @@ -30,6 +30,7 @@ tokio.workspace = true tokio-util = { version = "0.7", default-features = false, features = ["rt"] } serde.workspace = true +serde_json.workspace = true thiserror.workspace = true tracing.workspace = true diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index c5f23434a..b182c870d 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -210,8 +210,62 @@ pub async fn pack_attestations( return fall_back("no time left to merge"); }; let budget_ms = remaining.as_millis() as u64; + let state_for_plan = state.clone(); let job = tokio::task::spawn_blocking(move || { let _permit = permit; + let duty_key = ethlambda_telemetry::pq_events::duty::proposal_key(slot); + let duty_ref = ethlambda_telemetry::pq_events::duty::get(&duty_key); + let plan = if ethlambda_telemetry::pq_events::is_enabled() { + let recorder = ethlambda_telemetry::pq_events::global(); + let seq = ethlambda_telemetry::pq_events::duty::sequence(&duty_key) + .or_else(|| recorder.map(|r| r.reference())); + let mut vote_slots: Vec = + packed.attestations.iter().map(|a| a.data.slot).collect(); + vote_slots.sort_unstable(); + vote_slots.dedup(); + let mut workload = if duty_ref.is_some() { + serde_json::json!({ + "kind": "merge", + "purpose": "proposal_preparation", + "proposal_slot": slot, + "vote_slots": vote_slots, + }) + } else { + serde_json::json!({ + "kind": "merge", + "purpose": "reusable_preparation", + "vote_slots": vote_slots, + }) + }; + if let Some(seq) = seq { + workload["sequence"] = serde_json::json!(seq); + } + let plan = ethlambda_telemetry::pq_events::proof::Plan::new( + ethlambda_telemetry::pq_events::Mode::Production, + workload, + duty_ref.clone(), + ); + if let Some(ref p) = plan { + use ethlambda_state_transition::beacon::helpers::accessors::get_domain; + use ethlambda_types::{ + beacon::{constants::DOMAIN_BEACON_ATTESTER, signing::compute_signing_root}, + primitives::HashTreeRoot as _, + }; + let msg_slots = packed.attestations.iter().map(|att| { + let domain = get_domain( + &state_for_plan, + DOMAIN_BEACON_ATTESTER, + Some(att.data.target.epoch), + ); + let root = compute_signing_root(att.data.hash_tree_root(), domain); + (root.0, att.data.slot) + }); + p.messages(msg_slots); + } + plan + } else { + None + }; let started = Instant::now(); let proof = packed.merge().map_err(|err| err.to_string()); // Logged when it ends, deadline or not: what a merge costs here, how @@ -222,6 +276,27 @@ pub async fn pack_attestations( .flat_map(|(statements, _)| statements) .map(|statement| statement.pubkeys.len()) .sum(); + if let (Some(p), Ok(_)) = (&plan, &proof) { + let mut unique_claims: Vec<([u8; 32], [u8; 32])> = packed + .children + .iter() + .flat_map(|(statements, _)| statements) + .flat_map(|s| s.pubkeys.iter().map(move |pk| (*pk, s.message))) + .collect(); + let input_sum = unique_claims.len(); + unique_claims.sort_unstable(); + unique_claims.dedup(); + let unique_len = unique_claims.len(); + p.set_claims(serde_json::json!({ + "input_sum": input_sum, + "input_unique": unique_len, + "baseline_unique": 0, + "output_unique": unique_len, + "added_unique": unique_len, + })); + } + let completion = plan.as_ref().and_then(|p| p.take_completion()); + let has_duty = duty_ref.is_some(); info!( %slot, attestations = packed.attestations.len(), @@ -233,10 +308,15 @@ pub async fn pack_attestations( ok = proof.is_ok(), "Merged PQ attestation proofs" ); - proof.map(|proof| (packed, proof)) + proof.map(|proof| (packed, proof, completion, has_duty)) }); match tokio::time::timeout(remaining, job).await { - Ok(Ok(Ok((packed, proof)))) => { + Ok(Ok(Ok((packed, proof, completion, has_duty)))) => { + if let Some(completion) = completion + && let Some(op) = completion.ready(if has_duty { "proposal" } else { "reusable" }) + { + ethlambda_telemetry::pq_events::duty::remember_result(&proof, op); + } info!( %slot, attestations = packed.attestations.len(), diff --git a/crates/blockchain/state_transition/Cargo.toml b/crates/blockchain/state_transition/Cargo.toml index 6c07c6725..7b3c153b0 100644 --- a/crates/blockchain/state_transition/Cargo.toml +++ b/crates/blockchain/state_transition/Cargo.toml @@ -37,6 +37,7 @@ ethlambda-types.workspace = true ethlambda-crypto.workspace = true ethlambda-metrics.workspace = true ethlambda-storage.workspace = true +ethlambda-telemetry.workspace = true thiserror.workspace = true tracing.workspace = true diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index 968d64fb3..fd5b71bd0 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs @@ -320,6 +320,7 @@ pub fn aggregate_stateful_checks( let Ok(committee) = epoch_committees.committee(data.slot, committee_index) else { return Err(Outcome::Ignore(IgnoreReason::Internal)); }; + ethlambda_telemetry::pq_events::gossip::committee_members(committee.len(), None); // [REJECT] The number of aggregation bits matches the committee size. if aggregate.aggregation_bits.len() != committee.len() { return Err(Outcome::Reject(RejectReason::BitsLength)); @@ -334,7 +335,14 @@ pub fn aggregate_stateful_checks( // [Modified in PQ] [REJECT] The aggregate stark is valid. let statements = get_attestation_statements(&state, aggregate, &committees) .map_err(|_| Outcome::Reject(RejectReason::AggregateProof))?; - if !verify_aggregates(&statements, &aggregate_and_proof.proof) { + let verify_started = ethlambda_telemetry::pq_events::is_enabled().then(std::time::Instant::now); + let verified = verify_aggregates(&statements, &aggregate_and_proof.proof); + if let Some(started) = verify_started { + ethlambda_telemetry::pq_events::gossip::record_current_proof_verify_ns( + u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX), + ); + } + if !verified { return Err(Outcome::Reject(RejectReason::AggregateProof)); } let attesting_indices = get_attesting_indices(&state, aggregate, &committees) diff --git a/crates/common/crypto/Cargo.toml b/crates/common/crypto/Cargo.toml index 54c0d612c..191870dfa 100644 --- a/crates/common/crypto/Cargo.toml +++ b/crates/common/crypto/Cargo.toml @@ -12,6 +12,7 @@ version.workspace = true [dependencies] blst = "0.3.16" ethlambda-metrics.workspace = true +ethlambda-telemetry.workspace = true ethlambda-types.workspace = true rand.workspace = true rayon.workspace = true diff --git a/crates/common/crypto/src/stark.rs b/crates/common/crypto/src/stark.rs index 3d2b0d738..ca9443e46 100644 --- a/crates/common/crypto/src/stark.rs +++ b/crates/common/crypto/src/stark.rs @@ -109,12 +109,32 @@ pub fn prove_aggregates>( ) -> Result, ProveError> { check_shape(statements, signatures)?; match backend() { - Backend::Reference => Ok(signatures - .iter() - .flatten() - .flat_map(|signature| signature.as_ref()) - .copied() - .collect()), + Backend::Reference => { + let raw_sigs: usize = signatures.iter().map(Vec::len).sum(); + let mut call = if raw_sigs > 0 && ethlambda_telemetry::pq_events::is_enabled() { + let mut msgs: Vec<[u8; 32]> = statements + .iter() + .filter(|s| !s.pubkeys.is_empty()) + .map(|s| s.message) + .collect(); + msgs.sort_unstable(); + msgs.dedup(); + ethlambda_telemetry::pq_events::proof::Call::start(0, raw_sigs, &msgs) + } else { + None + }; + let out: Vec = signatures + .iter() + .flatten() + .flat_map(|signature| signature.as_ref()) + .copied() + .collect(); + if let Some(mut call) = call.take() { + call.backend_finished(); + call.returned(out.len()); + } + Ok(out) + } Backend::LeanVm(leanvm) => leanvm.prove(statements, signatures), } } @@ -126,11 +146,31 @@ pub fn merge_proofs, P: AsRef<[u8]>>( children: &[(S, P)], ) -> Result, ProveError> { match backend() { - Backend::Reference => Ok(children - .iter() - .flat_map(|(_, proof)| proof.as_ref()) - .copied() - .collect()), + Backend::Reference => { + let mut call = if children.len() > 1 && ethlambda_telemetry::pq_events::is_enabled() { + let mut msgs: Vec<[u8; 32]> = children + .iter() + .flat_map(|(stmts, _)| stmts.as_ref().iter()) + .filter(|s| !s.pubkeys.is_empty()) + .map(|s| s.message) + .collect(); + msgs.sort_unstable(); + msgs.dedup(); + ethlambda_telemetry::pq_events::proof::Call::start(children.len(), 0, &msgs) + } else { + None + }; + let out: Vec = children + .iter() + .flat_map(|(_, proof)| proof.as_ref()) + .copied() + .collect(); + if let Some(mut call) = call.take() { + call.backend_finished(); + call.returned(out.len()); + } + Ok(out) + } Backend::LeanVm(leanvm) => leanvm.merge(children), } } diff --git a/crates/common/crypto/src/stark/leanvm.rs b/crates/common/crypto/src/stark/leanvm.rs index 3d8f3aaa3..49a2a3020 100644 --- a/crates/common/crypto/src/stark/leanvm.rs +++ b/crates/common/crypto/src/stark/leanvm.rs @@ -348,9 +348,20 @@ impl LeanVmBackend { raw_signatures: Vec<(LeanXmssPublicKey, Message, LeanXmssSignature)>, expected: &AggregateClaims, ) -> Result { - let started = Instant::now(); let signatures = raw_signatures.len(); - let (claims, proof) = guarded("aggregate", || { + let mut call = if ethlambda_telemetry::pq_events::is_enabled() { + let mut msgs: Vec<[u8; 32]> = expected.lean_xmss.iter().map(|(_, msg)| *msg).collect(); + msgs.sort_unstable(); + msgs.dedup(); + ethlambda_telemetry::pq_events::proof::Call::start(children.len(), signatures, &msgs) + } else { + None + }; + if let Some(call) = &mut call { + call.starting(); + } + let started = Instant::now(); + let res = guarded("aggregate", || { leanvm_prover::aggregate( children, raw_signatures, @@ -359,14 +370,20 @@ impl LeanVmBackend { OutputClaims::All, self.log_inv_rate, ) - })? - .map_err(|err| Error::LeanVm(err.to_string()))?; + }); + if let Some(call) = &mut call { + call.backend_finished(); + } + let (claims, proof) = res?.map_err(|err| Error::LeanVm(err.to_string()))?; if claims != *expected { return Err(Error::ClaimsMismatch { expected: expected.num_signature_claims(), found: claims.num_signature_claims(), }); } + if let Some(call) = call { + call.returned(proof.to_bytes().len()); + } tracing::debug!( children = children.len(), signatures, diff --git a/crates/common/telemetry/Cargo.toml b/crates/common/telemetry/Cargo.toml index c543a2d96..736a82311 100644 --- a/crates/common/telemetry/Cargo.toml +++ b/crates/common/telemetry/Cargo.toml @@ -6,16 +6,31 @@ rust-version.workspace = true license.workspace = true [dependencies] +bytes = "1" ethlambda-metrics.workspace = true +flate2 = "1" hex.workspace = true +http = "1" +http-body-util = "0.1" +hyper = { version = "1", features = ["client", "http2"] } +hyper-rustls = { version = "0.27", default-features = false, features = ["ring", "webpki-tokio", "http2", "tls12"] } +hyper-util = { version = "0.1", features = ["client-legacy", "http2", "tokio"] } +prost = "0.14" reqwest.workspace = true +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +rustls-pki-types = "1" serde.workspace = true serde_json.workspace = true +sha2.workspace = true tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } tracing.workspace = true +url = "2" +uuid = { version = "1", features = ["v4"] } +webpki-roots = "1" [dev-dependencies] -# A stand-in ClickHouse HTTP endpoint for the writer tests. Already in the -# lockfile through ethlambda-rpc, so this adds no new crate. -axum = "0.8.1" +# Stand-in HTTP/1.1 + HTTP/2 endpoints for ClickHouse and OTLP writer tests. +# Already in the lockfile through ethlambda-rpc, so this adds no new crate. +axum = { version = "0.8.1", features = ["http2"] } +hyper-util = { version = "0.1", features = ["client-legacy", "http2", "server-auto", "tokio"] } tokio = { workspace = true, features = ["macros", "net", "rt", "sync", "time"] } diff --git a/crates/common/telemetry/src/lib.rs b/crates/common/telemetry/src/lib.rs index 14537154e..3f8806926 100644 --- a/crates/common/telemetry/src/lib.rs +++ b/crates/common/telemetry/src/lib.rs @@ -7,6 +7,7 @@ mod event; mod metrics; +pub mod pq_events; mod writer; use std::sync::{Arc, Mutex, OnceLock}; diff --git a/crates/common/telemetry/src/pq_events/duty.rs b/crates/common/telemetry/src/pq_events/duty.rs new file mode 100644 index 000000000..5745e6f74 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/duty.rs @@ -0,0 +1,348 @@ +//! Bounded duty and produced-proof correlation (`pq.duty_scheduled` and +//! `pq.duty_completed`, `eth.telemetry/0.5`). + +use std::{ + collections::BTreeMap, + sync::{Mutex, OnceLock}, +}; + +use serde_json::{Value, json}; +use sha2::{Digest as _, Sha256}; + +use super::{Mode, Point, Reference, global}; + +const LIMIT: usize = 4_096; + +#[derive(Clone)] +struct Duty { + reference: Reference, + revision: u64, + schedule: Value, + terminal: bool, + terminal_outcome: Option, + submitted: bool, + details: Value, + validator: Option, + sequence: Reference, +} + +#[derive(Default)] +struct Registry { + duties: BTreeMap, + results: BTreeMap<[u8; 32], Reference>, + messages: BTreeMap<[u8; 32], Value>, + sequence_attempts: BTreeMap<(String, String), u64>, +} + +static REGISTRY: OnceLock> = OnceLock::new(); + +fn lock() -> Option> { + match REGISTRY.get_or_init(Mutex::default).try_lock() { + Ok(guard) => Some(guard), + Err(_) => { + if let Some(recorder) = global() { + recorder.record_summary_eviction("pq.duty_completed"); + } + None + } + } +} + +pub fn committee_key(slot: u64, committee_index: u64, position: u64) -> String { + format!("committee:{slot}:{committee_index}:{position}") +} + +pub fn proposal_key(slot: u64) -> String { + format!("proposal:{slot}") +} + +/// Schedule or revise a local PQ duty (`pq.duty_scheduled`). Idempotent when +/// called again with identical schedule and validator while still active. +pub fn schedule(key: String, schedule: Value, validator: Option) -> Option<(Reference, u64)> { + let recorder = global()?; + let point = recorder.point(); + let mut registry = lock()?; + if let Some(old) = registry.duties.get(&key) + && old.schedule == schedule + && old.validator == validator + && !matches!( + old.terminal_outcome.as_deref(), + Some("superseded" | "cancelled") + ) + { + return Some((old.reference.clone(), old.revision)); + } + + let (reference, revision) = if let Some(old) = registry.duties.get_mut(&key) { + if !old.terminal && !old.submitted { + close(old, &point, "superseded", "reorg", None); + } + (old.reference.clone(), old.revision.saturating_add(1)) + } else { + (recorder.reference(), 0) + }; + + if registry.duties.len() >= LIMIT && !registry.duties.contains_key(&key) { + registry.duties.pop_first(); + recorder.record_summary_eviction("pq.duty_completed"); + } + + let mut data = schedule.clone(); + data["duty"] = json!(reference); + data["revision"] = json!(revision); + data["known"] = json!(point); + recorder.emit("pq.duty_scheduled", &point, Mode::Production, data); + + registry.duties.insert( + key, + Duty { + reference: reference.clone(), + revision, + schedule, + terminal: false, + terminal_outcome: None, + submitted: false, + details: json!({}), + validator, + sequence: recorder.reference(), + }, + ); + Some((reference, revision)) +} + +pub fn get(key: &str) -> Option<(Reference, u64)> { + global()?; + let registry = lock()?; + let duty = registry.duties.get(key)?; + (!duty.terminal).then(|| (duty.reference.clone(), duty.revision)) +} + +pub fn sequence(key: &str) -> Option { + global()?; + lock()?.duties.get(key).map(|d| d.sequence.clone()) +} + +pub fn next_attempt(sequence: &Reference) -> Option { + let mut registry = lock()?; + let key = (sequence.process_id.clone(), sequence.id.clone()); + if registry.sequence_attempts.len() >= LIMIT && !registry.sequence_attempts.contains_key(&key) { + registry.sequence_attempts.pop_first(); + if let Some(recorder) = global() { + recorder.record_summary_eviction("pq.operation_admitted"); + } + } + let attempts = registry.sequence_attempts.entry(key).or_default(); + *attempts = attempts.saturating_add(1); + Some(*attempts) +} + +pub fn details(key: &str, extra: Value) { + if global().is_none() { + return; + } + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.get_mut(key) + && let (Some(target), Some(obj)) = (duty.details.as_object_mut(), extra.as_object()) + { + target.extend(obj.clone()); + } +} + +/// Close a duty that ended without a publication, for any reason but its +/// cutoff: an abandoned duty goes through [`missed_deadline`], which records +/// the cutoff. +pub fn complete(key: &str, outcome: &'static str, reason: &'static str) { + debug_assert_ne!(outcome, "missed_deadline", "use missed_deadline()"); + finish(key, outcome, reason, None); +} + +/// Close a duty the client gave up on because its cutoff was reached +/// (`outcome=missed_deadline`, `reason=deadline`). +/// +/// `deadline_unix_ns` is the cutoff the abandoning code path ran against, in +/// UTC nanoseconds, taken from the same reading that path scheduled itself +/// from. It is not the duty's nominal publication target, though the two may +/// be equal. +/// +/// Nothing is recorded for a duty already handed to the publisher: its +/// publication may have happened, and an abandonment must not be made up. +pub fn missed_deadline(key: &str, deadline_unix_ns: u64) { + finish(key, "missed_deadline", "deadline", Some(deadline_unix_ns)); +} + +fn finish(key: &str, outcome: &str, reason: &str, deadline_unix_ns: Option) { + let Some(recorder) = global() else { return }; + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.get_mut(key) + && !duty.terminal + && !duty.submitted + { + close(duty, &recorder.point(), outcome, reason, deadline_unix_ns); + } +} + +pub fn committee_suppressed(slot: u64, committee_index: u64, validator: u64) { + let Some(recorder) = global() else { return }; + let point = recorder.point(); + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.values_mut().find(|d| { + !d.terminal + && d.schedule["kind"] == "committee" + && d.schedule["slot"] == slot + && d.schedule["committee_index"] == committee_index + && d.validator == Some(validator) + }) + { + close(duty, &point, "suppressed", "already_covered", None); + } +} + +fn close( + duty: &mut Duty, + point: &Point, + outcome: &str, + reason: &str, + deadline_unix_ns: Option, +) { + let Some(recorder) = global() else { return }; + let kind = duty.schedule["kind"].as_str().unwrap_or("proposal"); + let mut data = json!({ + "duty": duty.reference, + "revision": duty.revision, + "kind": kind, + "slot": duty.schedule["slot"], + "terminal": point, + "outcome": outcome, + "reason": reason, + }); + if kind == "committee" { + data["collection_closed"] = json!({ "missing": "not_reached" }); + } else { + data["selection_time"] = json!({ "missing": "not_reached" }); + data["selected_operations"] = json!([]); + data["reused_messages"] = json!([]); + } + if let (Some(target), Some(extra)) = (data.as_object_mut(), duty.details.as_object()) { + target.extend(extra.clone()); + } + // Wire 0.5: the cutoff is on abandoned duties and no others. + if let Some(deadline) = deadline_unix_ns { + data["deadline_unix_ns"] = json!(deadline.to_string()); + } + recorder.emit("pq.duty_completed", point, Mode::Production, data); + duty.terminal = true; + duty.terminal_outcome = Some(outcome.to_owned()); +} + +pub fn remember_result(proof: &[u8], operation: Reference) { + let Some(recorder) = global() else { return }; + let digest: [u8; 32] = Sha256::digest(proof).into(); + if let Some(mut registry) = lock() { + if registry.results.len() >= LIMIT && !registry.results.contains_key(&digest) { + registry.results.pop_first(); + recorder.record_summary_eviction("pq.operation_completed"); + } + registry.results.insert(digest, operation); + } +} + +pub fn result(proof: &[u8]) -> Option { + global()?; + let digest: [u8; 32] = Sha256::digest(proof).into(); + lock()?.results.get(&digest).cloned() +} + +pub fn remember_message(proof: &[u8], message: Value) { + let Some(recorder) = global() else { return }; + let digest: [u8; 32] = Sha256::digest(proof).into(); + if let Some(mut registry) = lock() { + if registry.messages.len() >= LIMIT && !registry.messages.contains_key(&digest) { + registry.messages.pop_first(); + recorder.record_summary_eviction("pq.aggregate_received"); + } + registry.messages.insert(digest, message); + } +} + +pub fn message(proof: &[u8]) -> Option { + global()?; + let digest: [u8; 32] = Sha256::digest(proof).into(); + lock()?.messages.get(&digest).cloned() +} + +pub fn publication_metadata(slot: u64, aggregator_index: Option, proof: &[u8]) -> Value { + if global().is_none() { + return json!({}); + } + let mut data = json!({}); + if let Some(op) = result(proof) { + data["operation"] = json!(op); + } + if let Some(registry) = lock() + && let Some(duty) = registry.duties.values().find(|d| { + !d.terminal + && d.schedule["slot"] == slot + && if let Some(index) = aggregator_index { + d.schedule["kind"] == "committee" && d.validator == Some(index) + } else { + d.schedule["kind"] == "proposal" + } + }) + { + data["duty"] = json!(duty.reference); + data["duty_revision"] = json!(duty.revision); + } + data +} + +pub fn published( + slot: u64, + aggregator_index: Option, + publication: &Reference, + requested: &Point, + returned: &Point, + accepted: bool, +) { + if global().is_none() || !accepted { + return; + } + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.values_mut().find(|d| { + !d.terminal + && d.schedule["slot"] == slot + && if let Some(index) = aggregator_index { + d.schedule["kind"] == "committee" && d.validator == Some(index) + } else { + d.schedule["kind"] == "proposal" + } + }) + { + duty.details["publication"] = json!(publication); + duty.details["published_at"] = json!(requested); + close(duty, returned, "published", "none", None); + } +} + +pub fn proposal_published(slot: u64, requested: &Point, returned: &Point, accepted: bool) { + if global().is_none() || !accepted { + return; + } + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.get_mut(&proposal_key(slot)) + && !duty.terminal + { + duty.details["published_at"] = json!(requested); + close(duty, returned, "published", "none", None); + } +} + +pub fn submitted(key: &str) { + if global().is_none() { + return; + } + if let Some(mut registry) = lock() + && let Some(duty) = registry.duties.get_mut(key) + { + duty.submitted = true; + } +} diff --git a/crates/common/telemetry/src/pq_events/gossip.rs b/crates/common/telemetry/src/pq_events/gossip.rs new file mode 100644 index 000000000..222101979 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/gossip.rs @@ -0,0 +1,802 @@ +//! Bounded non-blocking correlation for PQ aggregate gossip receipt, validation, +//! proposal-pool insertion, and publication (`eth.telemetry/0.5`). + +use std::{ + collections::{HashMap, VecDeque}, + fmt::Write as _, + sync::{ + Arc, Mutex, OnceLock, + atomic::{AtomicU64, Ordering}, + }, +}; + +use serde_json::{Value, json}; + +use super::{Mode, Point, Reference, global}; + +const CAPACITY: usize = 16_384; +pub const MAX_RECORDED_AGGREGATION_BITS: usize = 2_048; + +/// Decoded aggregate claims (`vote` and `sizes`) for `pq.aggregate_processed` +/// and `pq.aggregate_publication`. Never retains proof bytes. +#[derive(Clone, Debug, PartialEq)] +pub struct AggregateMetadata { + vote: Value, + sizes: Value, +} + +impl AggregateMetadata { + #[allow(clippy::too_many_arguments)] + pub fn decoded( + slot: u64, + committee_index: Option, + data_root: String, + signers: usize, + bit_length: usize, + bitlist_ssz: Option<&[u8]>, + ssz_bytes: usize, + compressed_bytes: Option, + proof_bytes: usize, + ) -> Self { + let bits = if bit_length > MAX_RECORDED_AGGREGATION_BITS { + json!({ "bit_length": bit_length, "missing": "limit_exceeded" }) + } else if let Some(bytes) = bitlist_ssz { + let mut encoded = String::with_capacity(2 + bytes.len() * 2); + encoded.push_str("0x"); + for byte in bytes { + let _ = write!(&mut encoded, "{byte:02x}"); + } + json!({ "bit_length": bit_length, "ssz": encoded }) + } else { + json!({ "missing": "not_exposed" }) + }; + let compressed = + compressed_bytes.map_or_else(|| json!({ "missing": "not_exposed" }), |n| json!(n)); + Self { + vote: json!({ + "slot": slot, + "committee_index": committee_index.map_or_else( + || json!({ "missing": "invalid_committee_bits" }), + |idx| json!(idx), + ), + "attestation_data_root": data_root, + "signers": signers, + "aggregation_bits": bits, + "committee": { "missing": "not_checked" }, + }), + sizes: json!({ + "ssz_bytes": ssz_bytes, + "compressed_payload_bytes": compressed, + "proof_bytes": proof_bytes, + }), + } + } + + pub fn unavailable(ssz_bytes: Option, compressed_bytes: Option) -> Self { + let missing = json!({ "missing": "not_exposed" }); + Self { + vote: json!({ + "slot": missing, + "committee_index": missing, + "attestation_data_root": missing, + "signers": missing, + "aggregation_bits": missing, + "committee": missing, + }), + sizes: json!({ + "ssz_bytes": ssz_bytes.map_or_else(|| missing.clone(), |n| json!(n)), + "proof_bytes": missing.clone(), + "compressed_payload_bytes": compressed_bytes.map_or(missing, |n| json!(n)), + }), + } + } + + pub fn set_compressed_bytes(&mut self, bytes: Option) { + if let Some(bytes) = bytes { + self.sizes["compressed_payload_bytes"] = json!(bytes); + } + } + + pub fn set_committee(&mut self, members: usize, state_root: Option<&str>) { + self.vote["committee"] = json!({ + "members": members, + "state_root": state_root.map_or_else(|| json!({ "missing": "not_exposed" }), |r| json!(r)), + }); + } + + fn add_to(&self, data: &mut Value, committee: Option<&Value>) { + data["metadata_status"] = json!("decoded"); + data["vote"] = self.vote.clone(); + data["sizes"] = self.sizes.clone(); + if let Some(committee) = committee { + data["vote"]["committee"] = committee.clone(); + } + } +} + +#[derive(Clone)] +struct Attempt { + reference: Reference, + submitted: Option, + admitted: Option, + started: Option, + finished: Option, + proof_verify_ns: Option, + closed: bool, + loss_epoch: u64, + committee: Value, +} + +#[derive(Clone)] +struct Receipt { + topic: String, + first: Reference, + current: Attempt, + metadata: Option>, + ssz_bytes: Option, + compressed_bytes: Option, +} + +#[derive(Default)] +struct State { + messages: HashMap, + order: VecDeque, +} + +static STATE: OnceLock> = OnceLock::new(); +static LOSS_EPOCH: AtomicU64 = AtomicU64::new(0); + +fn with_state_result(f: impl FnOnce(&mut State) -> R) -> Option { + let recorder = global()?; + match STATE + .get_or_init(|| Mutex::new(State::default())) + .try_lock() + { + Ok(mut state) => Some(f(&mut state)), + Err(_) => { + LOSS_EPOCH.fetch_add(1, Ordering::Relaxed); + recorder.record_summary_eviction("pq.aggregate_processed"); + None + } + } +} + +fn with_state(f: impl FnOnce(&mut State)) { + let _ = with_state_result(f); +} + +fn point_or_missing(value: &Option, missing: &str) -> Value { + value + .as_ref() + .map_or_else(|| json!({ "missing": missing }), |p| json!(p)) +} + +fn fresh_attempt(reference: Reference) -> Attempt { + Attempt { + reference, + submitted: None, + admitted: None, + started: None, + finished: None, + proof_verify_ns: None, + closed: false, + loss_epoch: LOSS_EPOCH.load(Ordering::Relaxed), + committee: json!({ "missing": "not_checked" }), + } +} + +/// Record first application receipt of an aggregate message (`pq.aggregate_received`). +pub fn received( + topic: &str, + gossip_id: &str, + ssz_bytes: Option, + compressed_bytes: Option, +) { + let Some(recorder) = global() else { return }; + let received_pt = recorder.point(); + received_at(topic, gossip_id, ssz_bytes, compressed_bytes, received_pt); +} + +pub fn received_at( + topic: &str, + gossip_id: &str, + ssz_bytes: Option, + compressed_bytes: Option, + received_pt: Point, +) { + let Some(recorder) = global() else { return }; + let captured = with_state_result(|state| { + if let Some(existing) = state.messages.get_mut(gossip_id) { + if existing.ssz_bytes.is_none() { + existing.ssz_bytes = ssz_bytes; + } + if existing.compressed_bytes.is_none() { + existing.compressed_bytes = compressed_bytes; + } + return None; + } + let evicted = if state.messages.len() >= CAPACITY { + state + .order + .pop_front() + .and_then(|old| state.messages.remove(&old)) + } else { + None + }; + let attempt = recorder.reference(); + state.order.push_back(gossip_id.to_owned()); + state.messages.insert( + gossip_id.to_owned(), + Receipt { + topic: topic.to_owned(), + first: attempt.clone(), + current: fresh_attempt(attempt.clone()), + metadata: None, + ssz_bytes, + compressed_bytes, + }, + ); + Some((attempt, evicted.is_some())) + }) + .flatten(); + + if let Some((attempt, evicted)) = captured { + if evicted { + recorder.record_summary_eviction("pq.aggregate_received"); + } + recorder.emit( + "pq.aggregate_received", + &received_pt, + Mode::Production, + json!({ + "message": { "topic": topic, "gossip_id": gossip_id }, + "attempt": attempt, + "received": received_pt, + }), + ); + } +} + +/// Attach decoded vote/bitlist/size metadata after receipt without delaying the +/// receipt timestamp. +pub fn annotate(gossip_id: &str, mut metadata: AggregateMetadata) { + let mut replacement = None; + let previous = with_state_result(|state| { + let receipt = state.messages.get_mut(gossip_id)?; + if let Some(compressed) = receipt.compressed_bytes { + metadata.set_compressed_bytes(Some(compressed)); + } + replacement = Some(Arc::new(metadata)); + std::mem::replace(&mut receipt.metadata, replacement.take()) + }); + drop(previous); +} + +/// Record presentation of `gossip_id` to the validation admission pool +/// (`pq.aggregate_processed.submitted`), before admission is decided. +pub fn submitted(gossip_id: &str) { + let Some(recorder) = global() else { return }; + let at = recorder.point(); + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) { + if receipt.current.closed { + receipt.current = fresh_attempt(recorder.reference()); + } + receipt.current.submitted = Some(at); + } + }); +} + +/// Record acceptance of `gossip_id` into the validation admission pool +/// (`pq.aggregate_processed.admission.at`). +pub fn admitted(gossip_id: &str) { + let Some(recorder) = global() else { return }; + let at = recorder.point(); + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) { + if receipt.current.closed { + receipt.current = fresh_attempt(recorder.reference()); + } + receipt.current.admitted = Some(at); + } + }); +} + +/// Record simultaneous queue submission and acceptance when a caller does not +/// separate pre-acquire presentation from permit acquisition. +pub fn queued(gossip_id: &str) { + let Some(recorder) = global() else { return }; + let at = recorder.point(); + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) { + if receipt.current.closed { + receipt.current = fresh_attempt(recorder.reference()); + } + if receipt.current.submitted.is_none() { + receipt.current.submitted = Some(at.clone()); + } + receipt.current.admitted = Some(at); + } + }); +} + +thread_local! { + static VALIDATION: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +pub struct ValidationScope { + previous: Option<(String, Reference)>, + _thread_bound: std::marker::PhantomData>, +} + +impl ValidationScope { + fn enter(id: &str, reference: Reference) -> Self { + let previous = VALIDATION.with(|v| v.replace(Some((id.to_owned(), reference)))); + Self { + previous, + _thread_bound: std::marker::PhantomData, + } + } +} + +impl Drop for ValidationScope { + fn drop(&mut self) { + VALIDATION.with(|v| *v.borrow_mut() = self.previous.take()); + } +} + +pub fn started(gossip_id: &str) -> Option { + let recorder = global()?; + let at = recorder.point(); + let reference = with_state_result(|state| { + let receipt = state.messages.get_mut(gossip_id)?; + if receipt.current.closed { + receipt.current = fresh_attempt(recorder.reference()); + } + receipt.current.started = Some(at); + if receipt.metadata.is_none() { + receipt.metadata = Some(Arc::new(AggregateMetadata::unavailable( + receipt.ssz_bytes, + receipt.compressed_bytes, + ))); + } + Some(receipt.current.reference.clone()) + })??; + Some(ValidationScope::enter(gossip_id, reference)) +} + +pub fn committee_members(members: usize, state_root: Option<&str>) { + if global().is_none() { + return; + } + VALIDATION.with(|v| { + if let Some((id, reference)) = v.borrow().as_ref() { + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(id) + && &receipt.current.reference == reference + && !receipt.current.closed + { + receipt.current.committee = json!({ + "members": members, + "state_root": state_root.map_or_else(|| json!({ "missing": "not_exposed" }), |r| json!(r)), + }); + } + }); + } + }); +} + +pub fn record_committee_for_id(gossip_id: &str, members: usize, state_root: Option<&str>) { + if global().is_none() { + return; + } + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) + && !receipt.current.closed + { + receipt.current.committee = json!({ + "members": members, + "state_root": state_root.map_or_else(|| json!({ "missing": "not_exposed" }), |r| json!(r)), + }); + } + }); +} + +pub fn record_proof_verify_ns(gossip_id: &str, elapsed_ns: u64) { + if global().is_none() { + return; + } + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) + && !receipt.current.closed + { + receipt.current.proof_verify_ns = Some(elapsed_ns); + } + }); +} + +pub fn record_current_proof_verify_ns(elapsed_ns: u64) { + if global().is_none() { + return; + } + VALIDATION.with(|v| { + if let Some((id, reference)) = v.borrow().as_ref() { + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(id) + && &receipt.current.reference == reference + && !receipt.current.closed + { + receipt.current.proof_verify_ns = Some(elapsed_ns); + } + }); + } + }); +} + +pub fn finished(gossip_id: &str) { + let Some(recorder) = global() else { return }; + let at = recorder.point(); + with_state(|state| { + if let Some(receipt) = state.messages.get_mut(gossip_id) { + receipt.current.finished = Some(at); + } + }); +} + +#[allow(clippy::too_many_arguments)] +fn complete_if( + gossip_id: &str, + outcome: &str, + pool: &str, + pool_reason: Option<&str>, + stage: Option<&'static str>, + reason: &str, + usable: Option, + rejected_admission: bool, + expected: Option<&Reference>, +) { + let Some(recorder) = global() else { return }; + let closed_pt = usable.clone().unwrap_or_else(|| recorder.point()); + let captured = with_state_result(|state| { + let receipt = state.messages.get_mut(gossip_id)?; + let attempt = &mut receipt.current; + if attempt.closed || expected.is_some_and(|r| r != &attempt.reference) { + return None; + } + let missing = if attempt.loss_epoch != LOSS_EPOCH.load(Ordering::Relaxed) { + "not_exposed" + } else { + "not_reached" + }; + attempt.closed = true; + if expected.is_some() && missing == "not_exposed" { + return Some(None); + } + Some(Some((receipt.clone(), missing))) + }) + .flatten(); + + let Some(maybe_snapshot) = captured else { + return; + }; + let Some((receipt, missing)) = maybe_snapshot else { + recorder.record_summary_eviction("pq.aggregate_processed"); + return; + }; + + let attempt = &receipt.current; + let observed_or_not_exposed = |pt: &Option| { + pt.as_ref() + .map_or_else(|| json!({ "missing": "not_exposed" }), |p| json!(p)) + }; + let (submitted, admission) = if stage == Some("decode") { + ( + json!({ "missing": "not_reached" }), + json!({ "outcome": "not_reached" }), + ) + } else if rejected_admission { + ( + observed_or_not_exposed(&attempt.submitted), + json!({ + "outcome": "rejected", + "at": &closed_pt, + "reason": "queue_full", + }), + ) + } else if attempt.admitted.is_some() || attempt.submitted.is_some() { + let reached_validation = stage == Some("validation") + || attempt.started.is_some() + || attempt.finished.is_some() + || usable.is_some(); + if attempt.admitted.is_some() || reached_validation { + ( + observed_or_not_exposed(&attempt.submitted), + json!({ + "outcome": "accepted", + "at": observed_or_not_exposed(&attempt.admitted), + }), + ) + } else { + ( + observed_or_not_exposed(&attempt.submitted), + json!({ "outcome": "unknown" }), + ) + } + } else if stage == Some("precheck") { + ( + json!({ "missing": missing }), + json!({ "outcome": if missing == "not_exposed" { "unknown" } else { "not_reached" } }), + ) + } else if missing == "not_exposed" { + ( + json!({ "missing": "not_exposed" }), + json!({ "outcome": "unknown" }), + ) + } else { + ( + json!({ "missing": "not_applicable" }), + json!({ "outcome": "not_applicable" }), + ) + }; + + let usable_val = if let Some(ref u) = usable { + json!(u) + } else if pool == "already_available" { + json!({ "missing": "not_applicable" }) + } else if pool == "unknown" { + json!({ "missing": "not_exposed" }) + } else { + json!({ "missing": "not_reached" }) + }; + + let mut data = json!({ + "message": { "topic": receipt.topic, "gossip_id": gossip_id }, + "attempt": attempt.reference, + "receipt_attempt": receipt.first, + "submitted": submitted, + "admission": admission, + "started": if rejected_admission { json!({ "missing": "not_reached" }) } else { point_or_missing(&attempt.started, missing) }, + "finished": if rejected_admission { json!({ "missing": "not_reached" }) } else { point_or_missing(&attempt.finished, missing) }, + "usable": usable_val, + "outcome": outcome, + "pool_outcome": pool, + "reason": reason, + "closed": { + "at": &closed_pt, + "cause": "resolved", + }, + }); + if let Some(decision_stage) = stage { + data["decision_stage"] = json!(decision_stage); + } + if let Some(pool_reason) = pool_reason { + data["pool_reason"] = json!(pool_reason); + } + if let Some(ns) = attempt.proof_verify_ns { + data["proof_verify_ns"] = json!(ns.to_string()); + data["proof_verify_scope"] = json!("backend"); + } + + if stage == Some("decode") { + data["metadata_status"] = json!("malformed"); + for boundary in ["started", "finished", "usable"] { + data[boundary] = json!({ "missing": "not_reached" }); + } + } else if let Some(metadata) = &receipt.metadata { + let committee = if missing == "not_exposed" + && attempt.committee == json!({ "missing": "not_checked" }) + { + json!({ "missing": "not_exposed" }) + } else { + attempt.committee.clone() + }; + metadata.add_to(&mut data, Some(&committee)); + } else if outcome == "accepted" || usable.is_some() || attempt.finished.is_some() { + AggregateMetadata::unavailable(receipt.ssz_bytes, receipt.compressed_bytes) + .add_to(&mut data, None); + } else { + data["metadata_status"] = json!(if missing == "not_exposed" { + "not_exposed" + } else { + "not_decoded" + }); + } + + recorder.emit("pq.aggregate_processed", &closed_pt, Mode::Production, data); +} + +pub fn decode_failed(gossip_id: &str) { + complete_if( + gossip_id, + "rejected", + "not_applicable", + None, + Some("decode"), + "decode_error", + None, + false, + None, + ); +} + +pub fn precheck_finished(gossip_id: &str, validation_outcome: &str, reason: &str) { + complete_if( + gossip_id, + validation_outcome, + "not_applicable", + None, + Some("precheck"), + reason, + None, + false, + None, + ); +} + +pub fn queue_dropped(gossip_id: &str) { + complete_if( + gossip_id, + "not_reached", + "not_applicable", + None, + None, + "none", + None, + true, + None, + ); +} + +pub fn validation_failed(gossip_id: &str, outcome: &str, reason: &str) { + complete_if( + gossip_id, + outcome, + "not_applicable", + None, + Some("validation"), + reason, + None, + false, + None, + ); +} + +/// Complete `pq.aggregate_processed` after proposal-pool insertion returns. +pub fn pool_result(gossip_id: &str, outcome: &str) { + let Some(recorder) = global() else { return }; + let inserted = outcome == "inserted"; + let usable = inserted.then(|| recorder.point()); + let (pool, pool_reason) = match outcome { + "inserted" => ("inserted", None), + "covered" => ("already_available", Some("already_covered")), + "error" => ("error", Some("pool_error")), + "expired" => ("not_inserted", Some("deadline")), + "capacity" => ("not_inserted", Some("queue_full")), + "invalid" => ("not_inserted", Some("invalid")), + _ => ("not_inserted", Some("other")), + }; + complete_if( + gossip_id, + "accepted", + pool, + pool_reason, + Some("validation"), + "none", + usable, + false, + None, + ); +} + +/// Deferred retry guard for parked PQ aggregates: opens a fresh attempt when +/// queued into a dependency wait, and closes it as `"cancelled"` if dropped +/// without executing. +pub struct RetryGuard { + id: String, + reference: Option, + armed: bool, +} + +impl RetryGuard { + pub fn new(id: String) -> Self { + let reference = global().and_then(|recorder| { + with_state_result(|state| { + let receipt = state.messages.get_mut(&id)?; + receipt.current = fresh_attempt(recorder.reference()); + Some(receipt.current.reference.clone()) + }) + .flatten() + }); + Self { + id, + reference, + armed: true, + } + } + + pub fn executing(mut self) { + self.armed = false; + } +} + +impl Drop for RetryGuard { + fn drop(&mut self) { + if self.armed + && let Some(reference) = &self.reference + { + complete_if( + &self.id, + "cancelled", + "not_applicable", + None, + Some("queue"), + "other", + None, + false, + Some(reference), + ); + } + } +} + +/// Emit `pq.aggregate_publication` after gossipsub publish returns. +#[allow(clippy::too_many_arguments)] +pub fn published( + topic: &str, + gossip_id: Option<&str>, + invoked: &Point, + returned: &Point, + outcome: &str, + reason: &str, + aggregate: AggregateMetadata, + extra: Value, +) -> Option { + let recorder = global()?; + let publication = recorder.reference(); + let (outcome, reason) = match (gossip_id.is_some(), outcome) { + (true, "accepted") => ( + "accepted", + if reason == "accepted_zero_recipients" { + "accepted_zero_recipients" + } else { + "none" + }, + ), + (true, "duplicate_suppressed") => ("duplicate_suppressed", "duplicate"), + (_, "cancelled") => ("cancelled", "cancelled"), + _ => { + let valid_reason = match reason { + "queue_full" | "encode_error" | "no_peers" | "invalid" | "timeout" | "shutdown" + | "other" => reason, + _ => "other", + }; + ("failed", valid_reason) + } + }; + let message = gossip_id.map_or_else( + || json!({ "topic": topic, "missing": "not_created" }), + |id| json!({ "topic": topic, "gossip_id": id }), + ); + let mut data = json!({ + "message": message, + "publication": publication, + "invoked": invoked, + "result": { + "stage": "network", + "outcome": outcome, + "at": returned, + "reason": reason, + }, + "closed": { + "at": returned, + "cause": "resolved", + }, + }); + if let (Some(target), Some(extra_obj)) = (data.as_object_mut(), extra.as_object()) { + target.extend(extra_obj.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + aggregate.add_to(&mut data, None); + recorder.emit("pq.aggregate_publication", returned, Mode::Production, data); + Some(publication) +} diff --git a/crates/common/telemetry/src/pq_events/hardware.rs b/crates/common/telemetry/src/pq_events/hardware.rs new file mode 100644 index 000000000..5c46b4288 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/hardware.rs @@ -0,0 +1,120 @@ +//! Host/container hardware summary for `pq.context`'s `hardware_ref`. +//! +//! Reads `/proc` and cgroup v2 limits on Linux and falls back cleanly on macOS +//! or other platforms when `PQ_MEASUREMENT_HARDWARE_REF` is unset. + +use std::fs; +use std::path::Path; + +/// Build `pq.context`'s `hardware_ref`: uses `PQ_MEASUREMENT_HARDWARE_REF` if +/// non-empty, otherwise inspects `/proc` and cgroup v2 to produce a compact +/// single-line hardware descriptor. +pub fn hardware_ref() -> String { + if let Ok(explicit) = std::env::var("PQ_MEASUREMENT_HARDWARE_REF") + && !explicit.trim().is_empty() + { + return explicit; + } + detected_summary() +} + +pub(crate) fn detected_summary() -> String { + let arch = std::env::consts::ARCH; + let os = std::env::consts::OS; + let cores = std::thread::available_parallelism() + .ok() + .map(usize::from) + .unwrap_or(1); + let cpu_model = field("/proc/cpuinfo", "model name") + .or_else(|| field("/proc/cpuinfo", "Hardware")) + .unwrap_or_else(|| "unknown".to_string()); + let affinity = + field("/proc/self/status", "Cpus_allowed_list").unwrap_or_else(|| "unrestricted".into()); + let visible_mem_mib = field("/proc/meminfo", "MemTotal") + .and_then(|value| value.split_whitespace().next()?.parse::().ok()) + .map(|kib| format!("{}MiB", kib / 1024)) + .unwrap_or_else(|| "unknown".into()); + let (cpu_quota, mem_limit) = cgroup_limits(Path::new("/sys/fs/cgroup"), &own_cgroup()); + let quota_str = cpu_quota + .map(|q| format!("{q:.2}")) + .unwrap_or_else(|| "max".into()); + let cgroup_mem_str = mem_limit + .map(|b| format!("{}MiB", b >> 20)) + .unwrap_or_else(|| "max".into()); + + format!( + "detected:{os}/{arch};cpu={cpu_model};parallelism={cores};affinity={affinity};cgroup_cpus={quota_str};mem={visible_mem_mib};cgroup_mem={cgroup_mem_str}" + ) +} + +fn field(file: &str, key: &str) -> Option { + let text = fs::read_to_string(file).ok()?; + value_of(&text, key) +} + +fn value_of(text: &str, key: &str) -> Option { + text.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + (name.trim() == key).then(|| value.trim().to_string()) + }) +} + +fn own_cgroup() -> String { + fs::read_to_string("/proc/self/cgroup") + .ok() + .and_then(|text| { + text.lines() + .find_map(|line| line.strip_prefix("0::/").map(str::to_owned)) + }) + .unwrap_or_default() +} + +fn cgroup_limits(root: &Path, group: &str) -> (Option, Option) { + let mut path = root.join(group); + if !path.is_dir() { + path = root.to_path_buf(); + } + let cpu = |p: &Path| { + let value = fs::read_to_string(p.join("cpu.max")).ok()?; + let (quota, period) = value.trim().split_once(' ')?; + let period = period.parse::().ok().filter(|&period| period > 0)?; + Some(quota.parse::().ok()? as f64 / period as f64) + }; + let memory = |p: &Path| { + fs::read_to_string(p.join("memory.max")) + .ok()? + .trim() + .parse::() + .ok() + }; + let levels = || { + path.ancestors() + .take_while(|ancestor| ancestor.starts_with(root)) + }; + ( + levels().filter_map(cpu).reduce(f64::min), + levels().filter_map(memory).min(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn summary_is_non_empty_and_names_arch() { + let summary = detected_summary(); + assert!(!summary.is_empty()); + assert!(summary.contains(std::env::consts::ARCH)); + } + + #[test] + fn proc_field_lookup_matches_exact_key() { + let cpuinfo = "processor\t: 0\nmodel name\t: AMD EPYC 9454P\n"; + assert_eq!( + value_of(cpuinfo, "model name").as_deref(), + Some("AMD EPYC 9454P") + ); + assert_eq!(value_of(cpuinfo, "model"), None); + } +} diff --git a/crates/common/telemetry/src/pq_events/health.rs b/crates/common/telemetry/src/pq_events/health.rs new file mode 100644 index 000000000..3e0ed55a1 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/health.rs @@ -0,0 +1,220 @@ +//! Prometheus exporter-health counters (`EXPORTER_HEALTH.md`) and per-recorder +//! atomic snapshots for unit tests. + +use std::sync::{ + LazyLock, + atomic::{AtomicU64, Ordering}, +}; + +use ethlambda_metrics::{ + IntCounter, IntCounterVec, register_int_counter, register_int_counter_vec, +}; + +use super::EVENT_NAMES; + +/// Bounded drop reason vocabulary per `EXPORTER_HEALTH.md`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropReason { + QueueFull, + RecordInvalid, + RecordTooLarge, + ExportRejected, + ExportFailed, + Shutdown, + Other, +} + +impl DropReason { + pub const ALL: [Self; 7] = [ + Self::QueueFull, + Self::RecordInvalid, + Self::RecordTooLarge, + Self::ExportRejected, + Self::ExportFailed, + Self::Shutdown, + Self::Other, + ]; + + pub const fn as_str(self) -> &'static str { + match self { + Self::QueueFull => "queue_full", + Self::RecordInvalid => "record_invalid", + Self::RecordTooLarge => "record_too_large", + Self::ExportRejected => "export_rejected", + Self::ExportFailed => "export_failed", + Self::Shutdown => "shutdown", + Self::Other => "other", + } + } +} + +static GENERATED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "pq_measurement_generated_total", + "Logical PQ records generated, excluding transport retries", + &["event"] + ) + .expect("pq_measurement_generated_total metric registration") +}); + +static DROPPED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "pq_measurement_dropped_total", + "Logical PQ records terminally discarded locally or rejected by the collector", + &["event", "reason"] + ) + .expect("pq_measurement_dropped_total metric registration") +}); + +static UNCONFIRMED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "pq_measurement_export_unconfirmed_total", + "PQ records acknowledged without rejection, with durable delivery unconfirmed", + &["event"] + ) + .expect("pq_measurement_export_unconfirmed_total metric registration") +}); + +static EVICTED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "pq_measurement_summary_evictions_total", + "PQ measurement correlation/summary observations lost before record generation", + &["event"] + ) + .expect("pq_measurement_summary_evictions_total metric registration") +}); + +static EXPORT_ERRORS: LazyLock = LazyLock::new(|| { + register_int_counter!( + "pq_measurement_export_errors_total", + "PQ export requests failing or exceeding their timeout" + ) + .expect("pq_measurement_export_errors_total metric registration") +}); + +static EXPORT_REJECTED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "pq_measurement_export_rejected_total", + "PQ record submissions rejected in valid OTLP partial-success responses", + &["event"] + ) + .expect("pq_measurement_export_rejected_total metric registration") +}); + +static EXPORT_WARNINGS: LazyLock = LazyLock::new(|| { + register_int_counter!( + "pq_measurement_export_warnings_total", + "PQ export requests acknowledged with a warning and zero rejected records" + ) + .expect("pq_measurement_export_warnings_total metric registration") +}); + +#[derive(Debug, Clone, Default)] +pub struct FamilyCounters { + pub generated: u64, + pub dropped: u64, + pub export_unconfirmed: u64, + pub summary_evictions: u64, + pub export_rejected: u64, +} + +#[derive(Debug, Clone)] +pub struct Counters { + pub families: Vec<(&'static str, FamilyCounters)>, + pub export_errors: u64, + pub export_warnings: u64, + pub queue_depth: usize, +} + +#[derive(Debug, Default)] +pub(crate) struct FamilyAtomic { + pub(crate) generated: AtomicU64, + pub(crate) dropped: AtomicU64, + pub(crate) unconfirmed: AtomicU64, + pub(crate) evicted: AtomicU64, + pub(crate) rejected: AtomicU64, +} + +#[derive(Debug, Default)] +pub(crate) struct Health { + pub(crate) families: [FamilyAtomic; 10], + pub(crate) export_errors: AtomicU64, + pub(crate) export_warnings: AtomicU64, +} + +impl Health { + /// Register and zero-initialize all supported counter series when PQ event + /// collection starts (`EXPORTER_HEALTH.md`). + pub(crate) fn initialize_metrics() { + for name in EVENT_NAMES { + let _ = GENERATED.with_label_values(&[name]); + for reason in DropReason::ALL { + let _ = DROPPED.with_label_values(&[name, reason.as_str()]); + } + let _ = UNCONFIRMED.with_label_values(&[name]); + let _ = EVICTED.with_label_values(&[name]); + let _ = EXPORT_REJECTED.with_label_values(&[name]); + } + let _ = LazyLock::force(&EXPORT_ERRORS); + let _ = LazyLock::force(&EXPORT_WARNINGS); + } + + pub(crate) fn generated(&self, index: usize) { + if let (Some(f), Some(&name)) = (self.families.get(index), EVENT_NAMES.get(index)) { + f.generated.fetch_add(1, Ordering::Relaxed); + GENERATED.with_label_values(&[name]).inc(); + } + } + + pub(crate) fn dropped(&self, index: usize, reason: DropReason, count: u64) { + if count == 0 { + return; + } + if let (Some(f), Some(&name)) = (self.families.get(index), EVENT_NAMES.get(index)) { + f.dropped.fetch_add(count, Ordering::Relaxed); + DROPPED + .with_label_values(&[name, reason.as_str()]) + .inc_by(count); + } + } + + pub(crate) fn unconfirmed(&self, index: usize, count: u64) { + if count == 0 { + return; + } + if let (Some(f), Some(&name)) = (self.families.get(index), EVENT_NAMES.get(index)) { + f.unconfirmed.fetch_add(count, Ordering::Relaxed); + UNCONFIRMED.with_label_values(&[name]).inc_by(count); + } + } + + pub(crate) fn evicted(&self, index: usize, count: u64) { + if count == 0 { + return; + } + if let (Some(f), Some(&name)) = (self.families.get(index), EVENT_NAMES.get(index)) { + f.evicted.fetch_add(count, Ordering::Relaxed); + EVICTED.with_label_values(&[name]).inc_by(count); + } + } + + pub(crate) fn export_error(&self) { + self.export_errors.fetch_add(1, Ordering::Relaxed); + EXPORT_ERRORS.inc(); + } + + pub(crate) fn export_rejected(&self, index: usize, count: u64) { + if count == 0 { + return; + } + if let (Some(f), Some(&name)) = (self.families.get(index), EVENT_NAMES.get(index)) { + f.rejected.fetch_add(count, Ordering::Relaxed); + EXPORT_REJECTED.with_label_values(&[name]).inc_by(count); + } + } + + pub(crate) fn export_warning(&self) { + self.export_warnings.fetch_add(1, Ordering::Relaxed); + EXPORT_WARNINGS.inc(); + } +} diff --git a/crates/common/telemetry/src/pq_events/mod.rs b/crates/common/telemetry/src/pq_events/mod.rs new file mode 100644 index 000000000..866f7563a --- /dev/null +++ b/crates/common/telemetry/src/pq_events/mod.rs @@ -0,0 +1,1050 @@ +//! Post-quantum measurement events (`eth.telemetry/0.5`) and operational +//! Prometheus exporter-health accounting (`EXPORTER_HEALTH.md`). +//! +//! Enabled solely via `--telemetry-events=pq` on `ethlambda beacon` and +//! `ethlambda validator`. Does not install a `tracing` subscriber or forward +//! application logs; hooks check an atomic fast path and enqueue onto a bounded +//! channel with `try_send` so collector connectivity never blocks validator +//! duties. + +pub mod duty; +pub mod gossip; +pub mod hardware; +pub mod health; +pub mod otlp; +pub mod proof; +pub mod settings; +pub mod traffic; + +pub use health::{Counters, DropReason, FamilyCounters}; +pub use settings::{ExportSettings, Protocol}; + +use std::sync::{ + Arc, OnceLock, + atomic::{AtomicBool, AtomicU64, Ordering}, +}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::sync::{Notify, mpsc}; + +use health::Health; +use otlp::{Exporter, QueuedEntry, build_resource, now_unix_ns, to_log_record}; + +pub const SCHEMA_VERSION: &str = "eth.telemetry/0.5"; +pub const MAX_COUNT: u64 = (1_u64 << 53) - 1; +pub const EVENT_NAMES: [&str; 10] = [ + "pq.context", + "pq.aggregate_received", + "pq.aggregate_processed", + "pq.aggregate_publication", + "pq.validation_batch", + "pq.operation_admitted", + "pq.operation_completed", + "pq.duty_scheduled", + "pq.duty_completed", + "pq.aggregate_traffic", +]; + +static GLOBAL: OnceLock> = OnceLock::new(); +static ENABLED: AtomicBool = AtomicBool::new(false); + +/// Validate `--telemetry-events` selector list (`pq` is the one family emitted). +pub fn event_families(value: &str) -> Result { + if value.split(',').all(|family| family == "pq") { + Ok("pq".to_owned()) + } else { + Err( + "--telemetry-events accepts pq (comma-separated, case-sensitive, no whitespace or empty selectors)" + .into(), + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + Production, + Experiment, + Replay, +} + +impl Mode { + pub const fn as_str(self) -> &'static str { + match self { + Self::Production => "production", + Self::Experiment => "experiment", + Self::Replay => "replay", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Point { + pub process_id: String, + pub unix_ns: String, + pub mono_ns: String, +} + +impl Point { + pub fn elapsed_ns_since(&self, earlier: &Self) -> Option { + if self.process_id != earlier.process_id { + return None; + } + self.mono_ns + .parse::() + .ok()? + .checked_sub(earlier.mono_ns.parse().ok()?) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Reference { + pub process_id: String, + pub id: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Record { + pub schema_version: String, + pub event_name: String, + pub node_id: String, + pub service_name: String, + pub process_id: String, + pub event_seq: u64, + pub context_id: String, + pub timestamp_unix_ns: String, + pub mode: Mode, + pub data: Value, +} + +#[derive(Debug, Clone)] +pub struct Config { + pub endpoint: String, + pub node_id: String, + pub service_name: String, + pub context_id: String, + pub context_data: Value, + pub settings: ExportSettings, + pub queue_capacity: usize, + pub batch_size: usize, + pub max_record_bytes: usize, + pub export_timeout: Duration, + pub flush_interval: Duration, +} + +impl Config { + pub fn from_env( + default_service_name: &str, + context_id: impl Into, + context_data: Value, + ) -> Result { + Self::from_settings( + ExportSettings::from_env(default_service_name)?, + context_id, + context_data, + ) + } + + pub fn from_settings( + settings: ExportSettings, + context_id: impl Into, + context_data: Value, + ) -> Result { + let config = Self { + endpoint: settings.endpoint.clone(), + node_id: settings.node_id.clone(), + service_name: settings.service_name.clone(), + context_id: context_id.into(), + context_data, + export_timeout: settings.timeout, + settings, + queue_capacity: 2_048, + batch_size: 32, + max_record_bytes: 65_536, + flush_interval: Duration::from_secs(1), + }; + config.validate()?; + Ok(config) + } + + pub fn new_for_test( + endpoint: impl Into, + protocol: Protocol, + node_id: impl Into, + context_id: impl Into, + context_data: Value, + ) -> Result { + let settings = ExportSettings { + endpoint: endpoint.into(), + protocol, + node_id: node_id.into(), + service_name: "ethlambda-test".into(), + resources: Default::default(), + headers: Default::default(), + gzip: false, + timeout: Duration::from_secs(2), + certificate: None, + client_certificate: None, + client_key: None, + ignored_instance_id: false, + }; + Self::from_settings(settings, context_id, context_data) + } + + fn validate(&self) -> Result<(), String> { + settings::validate_url(&self.endpoint, self.settings.protocol)?; + if self.node_id.is_empty() + || self.service_name.is_empty() + || self.context_id.is_empty() + || !self.context_data.is_object() + || self.queue_capacity == 0 + || self.queue_capacity > 65_536 + || self.batch_size == 0 + || self.batch_size > 256 + || self.max_record_bytes == 0 + || self.max_record_bytes > 1_048_576 + || self.export_timeout.is_zero() + || self.flush_interval.is_zero() + { + return Err("invalid measurement identity or bounded exporter configuration".into()); + } + Ok(()) + } +} + +pub struct Recorder { + process_id: String, + node_id: String, + service_name: String, + context_id: String, + origin: Instant, + next_seq: AtomicU64, + next_ref: AtomicU64, + max_record_bytes: usize, + sender: mpsc::Sender, + health: Arc, + stopped: AtomicBool, + stop: Arc, + finished: Arc, + done: Arc, +} + +impl Recorder { + pub fn start(config: Config) -> Result, String> { + config.validate()?; + tokio::runtime::Handle::try_current() + .map_err(|_| "PQ measurement exporter requires a Tokio runtime")?; + let process_id = uuid::Uuid::new_v4().to_string(); + let resource = build_resource(&config, &process_id); + let exporter = Exporter::new(&config, resource)?; + let (sender, receiver) = mpsc::channel(config.queue_capacity); + let health = Arc::new(Health::default()); + let stop = Arc::new(Notify::new()); + let finished = Arc::new(Notify::new()); + let done = Arc::new(AtomicBool::new(false)); + + let recorder = Arc::new(Self { + process_id, + node_id: config.node_id.clone(), + service_name: config.service_name.clone(), + context_id: config.context_id.clone(), + origin: Instant::now(), + next_seq: AtomicU64::new(1), + next_ref: AtomicU64::new(0), + max_record_bytes: config.max_record_bytes, + sender, + health: health.clone(), + stopped: AtomicBool::new(false), + stop: stop.clone(), + finished: finished.clone(), + done: done.clone(), + }); + + let context_record = recorder.build_record( + "pq.context", + 0, + &recorder.point(), + Mode::Production, + config.context_data.clone(), + ); + if validate_body(&context_record.data, config.max_record_bytes).is_err() { + return Err( + "PQ measurement context exceeds export limits or contains unsupported JSON values" + .into(), + ); + } + Health::initialize_metrics(); + health.generated(0); + let context_log = to_log_record(&context_record, now_unix_ns()); + tokio::spawn(otlp::run( + exporter, + config, + receiver, + context_log, + health, + stop, + finished, + done, + )); + Ok(recorder) + } + + pub fn process_id(&self) -> &str { + &self.process_id + } + + pub fn node_id(&self) -> &str { + &self.node_id + } + + pub fn service_name(&self) -> &str { + &self.service_name + } + + pub fn context_id(&self) -> &str { + &self.context_id + } + + pub fn point(&self) -> Point { + let wall = SystemTime::now(); + let mono = self.origin.elapsed(); + Point { + process_id: self.process_id.clone(), + unix_ns: unix_ns(wall).to_string(), + mono_ns: duration_ns(mono).to_string(), + } + } + + pub fn monotonic_ns(&self) -> u64 { + duration_ns(self.origin.elapsed()) + } + + pub fn new_id(&self) -> String { + match self + .next_ref + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) + { + Ok(n) => (n + 1).to_string(), + Err(_) => uuid::Uuid::new_v4().to_string(), + } + } + + pub fn reference(&self) -> Reference { + Reference { + process_id: self.process_id.clone(), + id: self.new_id(), + } + } + + pub fn emit(&self, event_name: &'static str, at: &Point, mode: Mode, data: Value) -> bool { + let Some(index) = EVENT_NAMES.iter().position(|n| *n == event_name) else { + return false; + }; + self.health.generated(index); + let sequence = self + .next_seq + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| { + (n < MAX_COUNT).then_some(n + 1) + }); + let Ok(prev_seq) = sequence else { + self.health.dropped(index, DropReason::Other, 1); + return false; + }; + let event_seq = prev_seq; + if self.stopped.load(Ordering::Relaxed) { + self.health.dropped(index, DropReason::Shutdown, 1); + return false; + } + if at.unix_ns.parse::().is_err() || at.process_id != self.process_id { + self.health.dropped(index, DropReason::RecordInvalid, 1); + return false; + } + if let Err(reason) = validate_body(&data, self.max_record_bytes) { + self.health.dropped(index, reason, 1); + return false; + } + let record = self.build_record(event_name, event_seq, at, mode, data); + let log = to_log_record(&record, now_unix_ns()); + match self.sender.try_send(QueuedEntry { + family_index: index, + log, + }) { + Ok(()) => true, + Err(_) => { + self.health.dropped(index, DropReason::QueueFull, 1); + false + } + } + } + + fn build_record( + &self, + event_name: &str, + event_seq: u64, + at: &Point, + mode: Mode, + data: Value, + ) -> Record { + Record { + schema_version: SCHEMA_VERSION.into(), + event_name: event_name.into(), + node_id: self.node_id.clone(), + service_name: self.service_name.clone(), + process_id: self.process_id.clone(), + event_seq, + context_id: self.context_id.clone(), + timestamp_unix_ns: at.unix_ns.clone(), + mode, + data, + } + } + + pub fn record_summary_eviction(&self, family: &'static str) { + self.record_summary_evictions(family, 1); + } + + pub fn record_summary_evictions(&self, family: &'static str, count: u64) { + if count == 0 { + return; + } + if let Some(index) = EVENT_NAMES.iter().position(|n| *n == family) { + self.health.evicted(index, count); + } + } + + pub fn snapshot(&self) -> Counters { + Counters { + families: EVENT_NAMES + .iter() + .zip(self.health.families.iter()) + .map(|(name, f)| { + ( + *name, + FamilyCounters { + generated: f.generated.load(Ordering::Relaxed), + dropped: f.dropped.load(Ordering::Relaxed), + export_unconfirmed: f.unconfirmed.load(Ordering::Relaxed), + summary_evictions: f.evicted.load(Ordering::Relaxed), + export_rejected: f.rejected.load(Ordering::Relaxed), + }, + ) + }) + .collect(), + export_errors: self.health.export_errors.load(Ordering::Relaxed), + export_warnings: self.health.export_warnings.load(Ordering::Relaxed), + queue_depth: self + .sender + .max_capacity() + .saturating_sub(self.sender.capacity()), + } + } + + pub async fn shutdown(&self, timeout: Duration) -> bool { + self.stopped.store(true, Ordering::Relaxed); + self.stop.notify_one(); + let completed = self.finished.notified(); + tokio::pin!(completed); + completed.as_mut().enable(); + self.done.load(Ordering::Acquire) || tokio::time::timeout(timeout, completed).await.is_ok() + } +} + +#[inline] +pub fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +pub fn install_global(recorder: Arc) -> Result<(), Arc> { + let res = GLOBAL.set(recorder); + if res.is_ok() { + ENABLED.store(true, Ordering::Release); + } + res +} + +#[inline] +pub fn global() -> Option<&'static Arc> { + if !is_enabled() { + return None; + } + GLOBAL.get() +} + +pub fn point() -> Option { + global().map(|r| r.point()) +} + +pub fn emit(event_name: &'static str, at: &Point, mode: Mode, data: Value) -> bool { + global().is_some_and(|r| r.emit(event_name, at, mode, data)) +} + +pub async fn shutdown(timeout: Duration) { + if let Some(recorder) = GLOBAL.get() { + ENABLED.store(false, Ordering::Release); + let _ = recorder.shutdown(timeout).await; + } +} + +/// Shared BN / VC startup helper: reads standard `OTEL_*` environment settings, +/// builds `pq.context` with ethlambda's exact hook declarations, and installs +/// the global non-blocking [`Recorder`]. +pub struct StartParams<'a> { + pub role: &'a str, + pub network: &'a str, + pub genesis_root: String, + pub genesis_time: u64, + pub slot_duration: Duration, + pub client_commit: &'a str, + pub prover_revision: Option<&'a str>, + pub prover_backend: Option<&'a str>, + pub log_inverse_rate: Option, + pub effective_prover_threads: Option, +} + +pub fn start(params: StartParams<'_>) -> Result<(), String> { + let default_service = format!("ethlambda-{}", params.role); + let settings = ExportSettings::from_env(&default_service)?; + if settings.ignored_instance_id { + tracing::warn!( + "Ignoring configured service.instance.id for telemetry events; a fresh process UUID is required" + ); + } + let data = context_data(¶ms, &settings.node_id); + let config = Config::from_settings(settings, default_service, data)?; + let recorder = Recorder::start(config)?; + install_global(recorder) + .map_err(|_| "PQ measurement recorder already initialized in this process".into()) +} + +/// The `pq.context` payload a process of `params.role` announces: chain +/// identity, prover parameters and ethlambda's hook declarations. +pub fn context_data(params: &StartParams<'_>, node_id: &str) -> Value { + let bn = params.role == "bn"; + let mut data = json!({ + "network": if params.network.is_empty() { "custom" } else { params.network }, + "genesis_root": params.genesis_root, + "genesis_unix_ns": Duration::from_secs(params.genesis_time).as_nanos().to_string(), + "slot_ns": params.slot_duration.as_nanos().to_string(), + "client_commit": if params.client_commit.is_empty() { "unavailable" } else { params.client_commit }, + "hardware_ref": hardware::hardware_ref(), + "metrics_node_ref": format!("deployment:{node_id}"), + "schedule_ref": "pq.duty_scheduled: collection_unix_ns and scheduled_publish_unix_ns from the network config's PQ aggregation offsets (staggered by seat); a proposal's target is its slot start", + "gossip_id_algorithm": "ethereum-altair:sha256(domain4||topic_len_le_u64||topic||uncompressed_ssz)[0..20]", + "instrumentation_revision": if bn { + "ethlambda-eth.telemetry/0.5; registry 0.10.0; decoded original vote/bitlist/proof sizes; actual ordered committee length at validation; compressed payload bytes on receipt and publish; traffic nominal UTC boundaries anchored to fixed observer-start paired reading; duty cutoff (deadline_unix_ns): a committee seat's broadcast time, at which the node stops proving the seat and discards a proof finished later" + } else { + "ethlambda-eth.telemetry/0.5; registry 0.10.0; duty cutoff (deadline_unix_ns): a proposal's slot attestation-due time, at which a block not yet handed to the beacon node is abandoned" + }, + "hooks": { + "receipt": { + "code_location": if bn { + "ethlambda_p2p::gossipsub::handler before application validation" + } else { + "not_exposed: validator client has no gossip stack" + }, + "decompression": "after", + "deduplication": "after", + }, + "validation_start": if bn { + "ethlambda_p2p::beacon::pq::triage_pq_aggregate" + } else { + "not_exposed" + }, + "validation_batching": if bn { "individual" } else { "not_applicable" }, + "validation_batch": if bn { + "Not applicable: ethlambda validates each PQ aggregate individually in ethlambda_p2p::beacon::pq and HTTP submission." + } else { + "Not applicable: validator client submits duties to the beacon node over HTTP." + }, + "validation_finish": if bn { + "ethlambda_p2p::beacon::pq::triage_pq_aggregate after STARK proof verification" + } else { + "not_exposed" + }, + "usable": if bn { + "ethlambda_storage::Store::insert_pq_aggregate after proposal-pool insertion" + } else { + "not_exposed" + }, + "publish": if bn { + "ethlambda_p2p::swarm_adapter around gossipsub::Behaviour::publish (Ok -> network accepted/none, Duplicate -> duplicate_suppressed/duplicate, NoPeersSubscribedToTopic -> failed/no_peers, AllQueuesFull -> failed/queue_full, MessageTooLarge|SigningError|TransformFailed -> failed/encode_error, other PublishError -> failed/other; API acceptance does not confirm peer receipt)" + } else { + "not_exposed: HTTP submission is not network gossipsub publication" + }, + "backend_start": if bn { + "ethlambda_crypto::stark immediately before leanvm_prover::aggregate" + } else { + "not_exposed: STARK aggregation backend runs in beacon node" + }, + "backend_finish": if bn { + "ethlambda_crypto::stark immediately after leanvm_prover::aggregate returns" + } else { + "not_exposed" + }, + "backend_scope": "One synchronous leanvm_prover::aggregate call; excludes caller candidate selection and SSZ wrapping.", + "caller_scope": if bn { + "Tokio spawn_blocking prover submission; aggregate traffic RX/TX copy hooks are internal to rust-libp2p gossipsub::Behaviour and declared unavailable." + } else { + "not_exposed; validator client has no gossip or STARK prover stack" + }, + "proof_verify_scope": if bn { + "Synchronous ethlambda_crypto::stark::verify_aggregated_signature wall elapsed" + } else { + "not_exposed" + }, + }, + "unavailable": [], + }); + + let mut unavailable = Vec::new(); + if let Some(rev) = params.prover_revision { + data["prover_revision"] = json!(rev); + } else { + unavailable.push("prover_revision"); + } + if let Some(log_inv_rate) = params.log_inverse_rate { + let mut proof_params = json!({ "log_inverse_rate": log_inv_rate }); + if let Some(backend) = params.prover_backend { + proof_params["backend"] = json!(backend); + } + data["proof_parameters"] = proof_params; + } else { + unavailable.push("proof_parameters"); + } + if let Some(threads) = params.effective_prover_threads.filter(|n| *n > 0) { + data["effective_prover_threads"] = json!(threads); + } else { + unavailable.push("effective_prover_threads"); + } + data["unavailable"] = json!(unavailable); + data +} + +fn unix_ns(time: SystemTime) -> u64 { + time.duration_since(UNIX_EPOCH) + .map(duration_ns) + .unwrap_or_default() +} + +fn duration_ns(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) +} + +fn validate_body(value: &Value, budget: usize) -> Result<(), DropReason> { + fn visit(value: &Value, remaining: &mut usize, depth: usize) -> Result<(), DropReason> { + if depth > 32 { + return Err(DropReason::RecordInvalid); + } + if *remaining < 128 { + return Err(DropReason::RecordTooLarge); + } + *remaining -= 128; + match value { + Value::Null => Err(DropReason::RecordInvalid), + Value::Bool(_) => Ok(()), + Value::Number(n) => { + if n.as_i64().is_some_and(|v| v.unsigned_abs() <= MAX_COUNT) { + Ok(()) + } else { + Err(DropReason::RecordInvalid) + } + } + Value::String(s) => { + let charge = s.len().saturating_mul(6); + if charge > *remaining { + return Err(DropReason::RecordTooLarge); + } + *remaining -= charge; + Ok(()) + } + Value::Array(items) => { + for item in items { + visit(item, remaining, depth + 1)?; + } + Ok(()) + } + Value::Object(map) => { + for (k, v) in map { + let charge = k.len().saturating_mul(6).saturating_add(128); + if charge > *remaining { + return Err(DropReason::RecordTooLarge); + } + *remaining -= charge; + visit(v, remaining, depth + 1)?; + } + Ok(()) + } + } + } + if !value.is_object() { + return Err(DropReason::RecordInvalid); + } + let mut remaining = budget; + visit(value, &mut remaining, 0) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, StatusCode, header::CONTENT_TYPE}, + response::IntoResponse, + routing::post, + }; + use prost::Message as _; + use std::sync::Mutex; + + fn sample_context_data() -> Value { + json!({ + "network": "pq-devnet-2", + "genesis_root": "0x1111111111111111111111111111111111111111111111111111111111111111", + "genesis_unix_ns": "1799988000000000000", + "slot_ns": "12000000000", + "client_commit": "deadbeef", + "hardware_ref": "test-host", + "metrics_node_ref": "node-a", + "schedule_ref": "test", + "gossip_id_algorithm": "ethereum-altair", + "instrumentation_revision": "test", + "hooks": { + "receipt": { + "code_location": "test", + "decompression": "after", + "deduplication": "after" + }, + "validation_start": "test", + "validation_finish": "test", + "usable": "test", + "publish": "test", + "backend_start": "test", + "backend_finish": "test", + "backend_scope": "test", + "caller_scope": "test", + "proof_verify_scope": "test", + "validation_batching": "individual", + "validation_batch": "Not applicable" + }, + "unavailable": ["prover_revision", "proof_parameters", "effective_prover_threads"] + }) + } + + #[test] + fn event_family_selector_accepts_only_pq() { + assert_eq!(event_families("pq").unwrap(), "pq"); + assert_eq!(event_families("pq,pq").unwrap(), "pq"); + for bad in ["", "pq,", ",pq", "PQ", " pq", "*", "eth.cl"] { + assert!(event_families(bad).is_err(), "{bad}"); + } + } + + #[test] + fn otlp_protobuf_round_trips_canonical_records_losslessly() { + let context = sample_context_data(); + let cfg = Config::new_for_test( + "http://localhost:4318/v1/logs", + Protocol::HttpProtobuf, + "node-a", + "ctx-a", + context.clone(), + ) + .unwrap(); + let pid = "11111111-1111-4111-8111-111111111111"; + let resource = otlp::build_resource(&cfg, pid); + + let rec1 = Record { + schema_version: SCHEMA_VERSION.into(), + event_name: "pq.context".into(), + node_id: "node-a".into(), + service_name: "ethlambda-test".into(), + process_id: pid.into(), + event_seq: 0, + context_id: "ctx-a".into(), + timestamp_unix_ns: "1800000000000000000".into(), + mode: Mode::Production, + data: context, + }; + let rec2 = Record { + schema_version: SCHEMA_VERSION.into(), + event_name: "pq.aggregate_processed".into(), + node_id: "node-a".into(), + service_name: "ethlambda-test".into(), + process_id: pid.into(), + event_seq: 1, + context_id: "ctx-a".into(), + timestamp_unix_ns: "1800000007640000000".into(), + mode: Mode::Production, + data: json!({ + "message": { + "topic": "/eth2/12345678/beacon_aggregate_and_proof/ssz_snappy", + "gossip_id": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + }, + "attempt": { "process_id": pid, "id": "1" }, + "receipt_attempt": { "process_id": pid, "id": "1" }, + "submitted": { "process_id": pid, "unix_ns": "1800000007610000000", "mono_ns": "90" }, + "admission": { + "outcome": "accepted", + "at": { "process_id": pid, "unix_ns": "1800000007610000000", "mono_ns": "90" } + }, + "started": { "process_id": pid, "unix_ns": "1800000007620000000", "mono_ns": "100" }, + "finished": { "process_id": pid, "unix_ns": "1800000007640000000", "mono_ns": "120" }, + "usable": { "missing": "not_reached" }, + "outcome": "rejected", + "pool_outcome": "not_applicable", + "reason": "invalid", + "decision_stage": "validation", + "closed": { + "at": { "process_id": pid, "unix_ns": "1800000007640000000", "mono_ns": "120" }, + "cause": "resolved" + }, + "metadata_status": "decoded", + "vote": { + "slot": 1000, + "committee_index": 0, + "attestation_data_root": "0x3333333333333333333333333333333333333333333333333333333333333333", + "signers": 8, + "aggregation_bits": { "bit_length": 8, "ssz": "0xff01" }, + "committee": { "members": 8, "state_root": { "missing": "not_exposed" } } + }, + "sizes": { + "ssz_bytes": 180800, + "compressed_payload_bytes": { "missing": "not_exposed" }, + "proof_bytes": 180000 + } + }), + }; + + let logs = [ + otlp::to_log_record(&rec1, 1_800_000_000_000_000_001), + otlp::to_log_record(&rec2, 1_800_000_007_640_000_001), + ]; + // Failure outcome sets `error.type = "invalid"`. + assert!(logs[1].attributes.iter().any(|kv| kv.key == "error.type")); + + let wire = otlp::encode_records_request(&resource, &logs).encode_to_vec(); + let decoded_req = otlp::ExportLogsServiceRequest::decode(wire.as_slice()).unwrap(); + let round_tripped = otlp::decode_records_request(&decoded_req).unwrap(); + assert_eq!(round_tripped, vec![rec1, rec2]); + } + + #[tokio::test] + async fn http_protobuf_exporter_handles_success_partial_rejection_and_queue_overflow() { + #[derive(Default)] + struct CollectorState { + received: Mutex>, + reject_next: AtomicU64, + } + + let state = Arc::new(CollectorState::default()); + let state_clone = state.clone(); + let app = Router::new() + .route( + "/v1/logs", + post( + |State(st): State>, body: Bytes| async move { + let req = otlp::ExportLogsServiceRequest::decode(body.as_ref()).unwrap(); + let recs = otlp::decode_records_request(&req).unwrap(); + st.received.lock().unwrap().extend(recs); + let rej = st.reject_next.swap(0, Ordering::AcqRel); + let resp = otlp::ExportLogsServiceResponse { + partial_success: (rej > 0).then(|| otlp::ExportLogsPartialSuccess { + rejected_log_records: rej as i64, + error_message: "rejected".into(), + }), + }; + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, "application/x-protobuf".parse().unwrap()); + (StatusCode::OK, headers, resp.encode_to_vec()).into_response() + }, + ), + ) + .with_state(state_clone); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let mut cfg = Config::new_for_test( + format!("http://{addr}/v1/logs"), + Protocol::HttpProtobuf, + "node-http", + "ctx-http", + sample_context_data(), + ) + .unwrap(); + cfg.queue_capacity = 2; + cfg.flush_interval = Duration::from_millis(50); + + let recorder = Recorder::start(cfg).unwrap(); + let pt = recorder.point(); + let rx_payload = json!({ + "message": { "topic": "/eth2/00000000/beacon_aggregate_and_proof/ssz_snappy", "gossip_id": "0xaa" }, + "attempt": recorder.reference(), + "received": pt, + }); + // Queue capacity is 2: 3 rapid emits before worker drains -> 2 admitted, 1 dropped. + assert!(recorder.emit( + "pq.aggregate_received", + &pt, + Mode::Production, + rx_payload.clone() + )); + assert!(recorder.emit( + "pq.aggregate_received", + &pt, + Mode::Production, + rx_payload.clone() + )); + let third = recorder.emit( + "pq.aggregate_received", + &pt, + Mode::Production, + rx_payload.clone(), + ); + if !third { + let snap = recorder.snapshot(); + let fam = snap + .families + .iter() + .find(|(n, _)| *n == "pq.aggregate_received") + .unwrap(); + assert_eq!(fam.1.generated, 3); + assert_eq!(fam.1.dropped, 1); + } + + tokio::time::sleep(Duration::from_millis(120)).await; + // Inject partial rejection of 1 record on the next batch. + state.reject_next.store(1, Ordering::Release); + assert!(recorder.emit("pq.aggregate_received", &pt, Mode::Production, rx_payload)); + assert!(recorder.shutdown(Duration::from_secs(2)).await); + + let snap = recorder.snapshot(); + let ctx_fam = &snap.families[0].1; + assert_eq!(ctx_fam.generated, 1); + assert_eq!(ctx_fam.export_unconfirmed, 1); + let rx_fam = snap + .families + .iter() + .find(|(n, _)| *n == "pq.aggregate_received") + .unwrap(); + assert_eq!(rx_fam.1.export_rejected, 1); + assert!(state.received.lock().unwrap().len() >= 3); + } + + #[tokio::test] + async fn grpc_http2_exporter_delivers_context_and_events_with_gzip() { + let received = Arc::new(Mutex::new(Vec::::new())); + let received_clone = received.clone(); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + break; + }; + let received_inner = received_clone.clone(); + tokio::spawn(async move { + let io = hyper_util::rt::TokioIo::new(stream); + let service = hyper::service::service_fn( + move |req: http::Request| { + let received_req = received_inner.clone(); + async move { + assert_eq!( + req.uri().path(), + "/opentelemetry.proto.collector.logs.v1.LogsService/Export" + ); + let is_gzip = req + .headers() + .get("grpc-encoding") + .and_then(|v| v.to_str().ok()) + == Some("gzip"); + let body = http_body_util::BodyExt::collect(req.into_body()) + .await + .unwrap() + .to_bytes(); + assert_eq!(body[0], u8::from(is_gzip)); + let len = u32::from_be_bytes([body[1], body[2], body[3], body[4]]) + as usize; + let payload = &body[5..5 + len]; + let raw = if is_gzip { + use std::io::Read as _; + let mut dec = flate2::read::GzDecoder::new(payload); + let mut out = Vec::new(); + dec.read_to_end(&mut out).unwrap(); + out + } else { + payload.to_vec() + }; + let proto = + otlp::ExportLogsServiceRequest::decode(raw.as_slice()).unwrap(); + let recs = otlp::decode_records_request(&proto).unwrap(); + received_req.lock().unwrap().extend(recs); + + let resp_proto = + otlp::ExportLogsServiceResponse::default().encode_to_vec(); + let mut frame = Vec::with_capacity(5 + resp_proto.len()); + frame.push(0); + frame.extend_from_slice(&(resp_proto.len() as u32).to_be_bytes()); + frame.extend_from_slice(&resp_proto); + + Ok::<_, std::convert::Infallible>( + http::Response::builder() + .status(200) + .header("content-type", "application/grpc+proto") + .header("grpc-status", "0") + .body(http_body_util::Full::new(Bytes::from(frame))) + .unwrap(), + ) + } + }, + ); + let _ = hyper::server::conn::http2::Builder::new( + hyper_util::rt::TokioExecutor::new(), + ) + .serve_connection(io, service) + .await; + }); + } + }); + + let mut cfg = Config::new_for_test( + format!("http://{addr}"), + Protocol::Grpc, + "node-grpc", + "ctx-grpc", + sample_context_data(), + ) + .unwrap(); + cfg.settings.gzip = true; + cfg.flush_interval = Duration::from_millis(50); + + let recorder = Recorder::start(cfg).unwrap(); + let pt = recorder.point(); + assert!(recorder.emit( + "pq.aggregate_received", + &pt, + Mode::Production, + json!({ + "message": { "topic": "/eth2/00000000/beacon_aggregate_and_proof/ssz_snappy", "gossip_id": "0xbb" }, + "attempt": recorder.reference(), + "received": pt, + }), + )); + assert!(recorder.shutdown(Duration::from_secs(2)).await); + + let recs = received.lock().unwrap(); + assert_eq!(recs.len(), 2); + assert_eq!(recs[0].event_name, "pq.context"); + assert_eq!(recs[1].event_name, "pq.aggregate_received"); + } +} diff --git a/crates/common/telemetry/src/pq_events/otlp.rs b/crates/common/telemetry/src/pq_events/otlp.rs new file mode 100644 index 000000000..f6bc941ad --- /dev/null +++ b/crates/common/telemetry/src/pq_events/otlp.rs @@ -0,0 +1,1046 @@ +//! OTLP Logs v1 protobuf codec, HTTP/protobuf + gRPC HTTP/2 exporters, and +//! bounded async batch worker (`eth.telemetry/0.5`, registry `0.10.0`). +//! +//! Built directly on `prost` + `reqwest` + `hyper`/`hyper-rustls` so that: +//! 1. No `opentelemetry-sdk` or `tonic` crate graph is added to `Cargo.lock`. +//! 2. `ExportLogsPartialSuccess.rejected_log_records` is observed directly for +//! `EXPORTER_HEALTH.md` accounting. + +use std::collections::BTreeMap; +use std::io::Write as _; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use bytes::Bytes; +use flate2::{Compression, write::GzEncoder}; +use http::{ + HeaderMap, HeaderName, HeaderValue, Method, Request, Uri, + header::{CONTENT_TYPE, TE}, +}; +use http_body_util::{BodyExt as _, Full}; +use hyper_rustls::HttpsConnector; +use hyper_util::{ + client::legacy::{Client as HyperClient, connect::HttpConnector}, + rt::TokioExecutor, +}; +use prost::Message; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject as _}; +use serde_json::Value; +use tokio::sync::{Notify, mpsc}; + +use super::{ + Config, EVENT_NAMES, Mode, Record, SCHEMA_VERSION, + health::{DropReason, Health}, + settings::Protocol, +}; + +const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024; +const PROTOBUF_CONTENT_TYPE: &str = "application/x-protobuf"; +const GRPC_CONTENT_TYPE: &str = "application/grpc+proto"; +const GRPC_EXPORT_PATH: &str = "/opentelemetry.proto.collector.logs.v1.LogsService/Export"; +const SEVERITY_NUMBER_INFO: i32 = 9; + +// --------------------------------------------------------------------------- +// OTLP Logs v1 Protobuf Wire Types (`opentelemetry.proto.*`) +// --------------------------------------------------------------------------- + +#[derive(Clone, PartialEq, Message)] +pub struct ExportLogsServiceRequest { + #[prost(message, repeated, tag = "1")] + pub resource_logs: Vec, +} + +#[derive(Clone, PartialEq, Message)] +pub struct ExportLogsServiceResponse { + #[prost(message, optional, tag = "1")] + pub partial_success: Option, +} + +#[derive(Clone, PartialEq, Message)] +pub struct ExportLogsPartialSuccess { + #[prost(int64, tag = "1")] + pub rejected_log_records: i64, + #[prost(string, tag = "2")] + pub error_message: String, +} + +#[derive(Clone, PartialEq, Message)] +pub struct ResourceLogs { + #[prost(message, optional, tag = "1")] + pub resource: Option, + #[prost(message, repeated, tag = "2")] + pub scope_logs: Vec, + #[prost(string, tag = "3")] + pub schema_url: String, +} + +#[derive(Clone, PartialEq, Message)] +pub struct Resource { + #[prost(message, repeated, tag = "1")] + pub attributes: Vec, + #[prost(uint32, tag = "2")] + pub dropped_attributes_count: u32, +} + +#[derive(Clone, PartialEq, Message)] +pub struct ScopeLogs { + #[prost(message, optional, tag = "1")] + pub scope: Option, + #[prost(message, repeated, tag = "2")] + pub log_records: Vec, + #[prost(string, tag = "3")] + pub schema_url: String, +} + +#[derive(Clone, PartialEq, Message)] +pub struct InstrumentationScope { + #[prost(string, tag = "1")] + pub name: String, + #[prost(string, tag = "2")] + pub version: String, + #[prost(message, repeated, tag = "3")] + pub attributes: Vec, + #[prost(uint32, tag = "4")] + pub dropped_attributes_count: u32, +} + +#[derive(Clone, PartialEq, Message)] +pub struct LogRecord { + #[prost(fixed64, tag = "1")] + pub time_unix_nano: u64, + #[prost(int32, tag = "2")] + pub severity_number: i32, + #[prost(string, tag = "3")] + pub severity_text: String, + #[prost(message, optional, tag = "5")] + pub body: Option, + #[prost(message, repeated, tag = "6")] + pub attributes: Vec, + #[prost(uint32, tag = "7")] + pub dropped_attributes_count: u32, + #[prost(fixed32, tag = "8")] + pub flags: u32, + #[prost(bytes = "vec", tag = "9")] + pub trace_id: Vec, + #[prost(bytes = "vec", tag = "10")] + pub span_id: Vec, + #[prost(fixed64, tag = "11")] + pub observed_time_unix_nano: u64, + #[prost(string, tag = "12")] + pub event_name: String, +} + +#[derive(Clone, PartialEq, Message)] +pub struct KeyValue { + #[prost(string, tag = "1")] + pub key: String, + #[prost(message, optional, tag = "2")] + pub value: Option, +} + +#[derive(Clone, PartialEq, Message)] +pub struct AnyValue { + #[prost(oneof = "any_value::Value", tags = "1, 2, 3, 4, 5, 6, 7")] + pub value: Option, +} + +pub mod any_value { + #[derive(Clone, PartialEq, prost::Oneof)] + pub enum Value { + #[prost(string, tag = "1")] + StringValue(String), + #[prost(bool, tag = "2")] + BoolValue(bool), + #[prost(int64, tag = "3")] + IntValue(i64), + #[prost(double, tag = "4")] + DoubleValue(f64), + #[prost(message, tag = "5")] + ArrayValue(super::ArrayValue), + #[prost(message, tag = "6")] + KvlistValue(super::KeyValueList), + #[prost(bytes, tag = "7")] + BytesValue(Vec), + } +} + +#[derive(Clone, PartialEq, Message)] +pub struct ArrayValue { + #[prost(message, repeated, tag = "1")] + pub values: Vec, +} + +#[derive(Clone, PartialEq, Message)] +pub struct KeyValueList { + #[prost(message, repeated, tag = "1")] + pub values: Vec, +} + +// --------------------------------------------------------------------------- +// Canonical Record <-> OTLP Mapping (`eth.telemetry/0.5`) +// --------------------------------------------------------------------------- + +fn string_kv(key: impl Into, value: impl Into) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + } +} + +fn int_kv(key: impl Into, value: i64) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(value)), + }), + } +} + +pub(crate) fn json_to_any_value(value: &Value) -> AnyValue { + let v = match value { + Value::String(s) => any_value::Value::StringValue(s.clone()), + Value::Bool(b) => any_value::Value::BoolValue(*b), + Value::Number(n) => any_value::Value::IntValue(n.as_i64().unwrap_or_default()), + Value::Array(items) => any_value::Value::ArrayValue(ArrayValue { + values: items.iter().map(json_to_any_value).collect(), + }), + Value::Object(map) => any_value::Value::KvlistValue(KeyValueList { + values: map + .iter() + .map(|(k, val)| KeyValue { + key: k.clone(), + value: Some(json_to_any_value(val)), + }) + .collect(), + }), + Value::Null => any_value::Value::StringValue("invalid-null".into()), + }; + AnyValue { value: Some(v) } +} + +pub(crate) fn any_value_to_json(any: &AnyValue) -> Result { + match any.value.as_ref().ok_or("empty AnyValue")? { + any_value::Value::StringValue(s) => Ok(Value::String(s.clone())), + any_value::Value::BoolValue(b) => Ok(Value::Bool(*b)), + any_value::Value::IntValue(i) => Ok(Value::Number((*i).into())), + any_value::Value::ArrayValue(arr) => { + let mut items = Vec::with_capacity(arr.values.len()); + for item in &arr.values { + items.push(any_value_to_json(item)?); + } + Ok(Value::Array(items)) + } + any_value::Value::KvlistValue(kvlist) => { + let mut map = serde_json::Map::with_capacity(kvlist.values.len()); + for kv in &kvlist.values { + let val = kv.value.as_ref().ok_or("missing map value")?; + if map + .insert(kv.key.clone(), any_value_to_json(val)?) + .is_some() + { + return Err(format!("duplicate nested key {}", kv.key)); + } + } + Ok(Value::Object(map)) + } + any_value::Value::DoubleValue(_) | any_value::Value::BytesValue(_) => { + Err("unsupported double/bytes AnyValue in canonical PQ event".into()) + } + } +} + +pub(crate) fn error_type(record: &Record) -> Option<&str> { + fn reason_or<'a>(obj: &'a Value, reason_key: &str, outcome: &'static str) -> &'a str { + obj.get(reason_key) + .and_then(Value::as_str) + .filter(|r| !r.is_empty() && *r != "none") + .unwrap_or(outcome) + } + const PROCESSING_FAILURES: &[&str] = &["rejected", "error", "dropped", "decode_error"]; + let data = &record.data; + match record.event_name.as_str() { + "pq.aggregate_publication" => { + let result = data.get("result")?; + (result.get("outcome").and_then(Value::as_str) == Some("failed")) + .then(|| reason_or(result, "reason", "failed")) + } + "pq.aggregate_processed" => { + if data.get("pool_outcome").and_then(Value::as_str) == Some("error") { + return Some(reason_or(data, "pool_reason", "error")); + } + if let Some(&outcome) = data + .get("outcome") + .and_then(Value::as_str) + .and_then(|o| PROCESSING_FAILURES.iter().find(|&&f| f == o)) + { + return Some(reason_or(data, "reason", outcome)); + } + let admission = data.get("admission")?; + (admission.get("outcome").and_then(Value::as_str) == Some("rejected")) + .then(|| reason_or(admission, "reason", "rejected")) + } + "pq.validation_batch" => (data.get("outcome").and_then(Value::as_str) == Some("failed")) + .then(|| reason_or(data, "reason", "failed")), + "pq.operation_completed" => { + let outcome = match data.get("outcome").and_then(Value::as_str) { + Some("failed") => "failed", + Some("expired") => "expired", + _ => return None, + }; + Some(reason_or(data, "reason", outcome)) + } + "pq.duty_completed" => { + let outcome = match data.get("outcome").and_then(Value::as_str) { + Some("failed") => "failed", + Some("unavailable") => "unavailable", + Some("missed_deadline") => "missed_deadline", + _ => return None, + }; + Some(reason_or(data, "reason", outcome)) + } + _ => None, + } +} + +pub(crate) fn build_resource(config: &Config, process_id: &str) -> Resource { + let mut attrs = config.settings.resources.clone(); + attrs.insert("eth.node.id".into(), config.node_id.clone()); + attrs.insert("service.name".into(), config.service_name.clone()); + attrs.insert("service.instance.id".into(), process_id.to_owned()); + Resource { + attributes: attrs.into_iter().map(|(k, v)| string_kv(k, v)).collect(), + dropped_attributes_count: 0, + } +} + +pub(crate) fn to_log_record(record: &Record, observed_unix_nano: u64) -> LogRecord { + let mut attributes = Vec::with_capacity( + record + .data + .as_object() + .map_or(5, |obj| obj.len().saturating_add(5)), + ); + attributes.push(string_kv( + "eth.telemetry.schema_version", + &record.schema_version, + )); + attributes.push(string_kv("eth.telemetry.context_id", &record.context_id)); + attributes.push(string_kv("eth.telemetry.mode", record.mode.as_str())); + attributes.push(int_kv( + "eth.telemetry.event_seq", + i64::try_from(record.event_seq).unwrap_or(i64::MAX), + )); + if let Some(data) = record.data.as_object() { + for (key, val) in data { + attributes.push(KeyValue { + key: format!("pq.{key}"), + value: Some(json_to_any_value(val)), + }); + } + } + if let Some(err) = error_type(record) { + attributes.push(string_kv("error.type", err)); + } + + LogRecord { + time_unix_nano: record.timestamp_unix_ns.parse::().unwrap_or_default(), + severity_number: SEVERITY_NUMBER_INFO, + severity_text: String::new(), + body: None, + attributes, + dropped_attributes_count: 0, + flags: 0, + trace_id: Vec::new(), + span_id: Vec::new(), + observed_time_unix_nano: observed_unix_nano, + event_name: record.event_name.clone(), + } +} + +pub fn encode_records_request( + resource: &Resource, + records: &[LogRecord], +) -> ExportLogsServiceRequest { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(resource.clone()), + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + name: "ethlambda.eth.telemetry".into(), + version: "0.10.0".into(), + attributes: Vec::new(), + dropped_attributes_count: 0, + }), + log_records: records.to_vec(), + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +/// Reconstruct canonical [`Record`]s from an OTLP `ExportLogsServiceRequest` per +/// `INGESTION.md` Section 2 (used by conformance and round-trip tests). +pub fn decode_records_request(request: &ExportLogsServiceRequest) -> Result, String> { + let mut out = Vec::new(); + for rl in &request.resource_logs { + let res = rl.resource.as_ref().ok_or("missing Resource")?; + let mut res_map = BTreeMap::new(); + for kv in &res.attributes { + let val = kv + .value + .as_ref() + .ok_or("missing resource attribute value")?; + let any_value::Value::StringValue(s) = + val.value.as_ref().ok_or("empty resource AnyValue")? + else { + continue; + }; + if res_map.insert(kv.key.clone(), s.clone()).is_some() { + return Err(format!("duplicate resource attribute {}", kv.key)); + } + } + let node_id = res_map + .get("eth.node.id") + .cloned() + .ok_or("missing eth.node.id")?; + let service_name = res_map + .get("service.name") + .cloned() + .ok_or("missing service.name")?; + let process_id = res_map + .get("service.instance.id") + .cloned() + .ok_or("missing service.instance.id")?; + + for sl in &rl.scope_logs { + for lr in &sl.log_records { + if let Some(body) = &lr.body + && !matches!(body.value, Some(any_value::Value::StringValue(_))) + { + return Err("structured LogRecord body is not valid in 0.5".into()); + } + if lr.event_name.is_empty() { + return Err("missing LogRecord event_name".into()); + } + let mut seen_keys = std::collections::HashSet::new(); + let mut schema_version = None; + let mut context_id = None; + let mut mode = None; + let mut event_seq = None; + let mut seen_error_type = None; + let mut data = serde_json::Map::new(); + for kv in &lr.attributes { + if !seen_keys.insert(kv.key.clone()) { + return Err(format!("duplicate attribute {}", kv.key)); + } + let val = kv.value.as_ref().ok_or("missing attribute value")?; + match kv.key.as_str() { + "eth.telemetry.schema_version" => { + let Value::String(s) = any_value_to_json(val)? else { + return Err("schema_version must be string".into()); + }; + schema_version = Some(s); + } + "eth.telemetry.context_id" => { + let Value::String(s) = any_value_to_json(val)? else { + return Err("context_id must be string".into()); + }; + context_id = Some(s); + } + "eth.telemetry.mode" => { + let Value::String(s) = any_value_to_json(val)? else { + return Err("mode must be string".into()); + }; + mode = Some(match s.as_str() { + "production" => Mode::Production, + "experiment" => Mode::Experiment, + "replay" => Mode::Replay, + _ => return Err(format!("invalid mode {s}")), + }); + } + "eth.telemetry.event_seq" => { + let Some(any_value::Value::IntValue(seq)) = val.value else { + return Err("event_seq must be int_value".into()); + }; + event_seq = Some(u64::try_from(seq).map_err(|_| "negative event_seq")?); + } + "error.type" => { + let Value::String(s) = any_value_to_json(val)? else { + return Err("error.type must be string".into()); + }; + seen_error_type = Some(s); + } + other => { + if let Some(field) = other.strip_prefix("pq.") { + data.insert(field.to_owned(), any_value_to_json(val)?); + } + } + } + } + let schema_version = schema_version.ok_or("missing schema_version")?; + if schema_version != SCHEMA_VERSION { + return Err(format!("unsupported schema_version {schema_version}")); + } + let record = Record { + schema_version, + event_name: lr.event_name.clone(), + node_id: node_id.clone(), + service_name: service_name.clone(), + process_id: process_id.clone(), + event_seq: event_seq.ok_or("missing event_seq")?, + context_id: context_id.ok_or("missing context_id")?, + timestamp_unix_ns: lr.time_unix_nano.to_string(), + mode: mode.ok_or("missing mode")?, + data: Value::Object(data), + }; + if seen_error_type.as_deref() != error_type(&record) { + return Err("error.type does not match failure outcome/reason".into()); + } + out.push(record); + } + } + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// OTLP Exporters (`grpc` over HTTP/2 + `http/protobuf`) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Outcome { + Full, + Warning, + Rejected(u64), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ExportError { + Unavailable, + Failed, +} + +type GrpcHttpClient = HyperClient, Full>; + +enum TransportClient { + Grpc { + client: Box, + uri: Uri, + headers: HeaderMap, + gzip: bool, + }, + Http { + client: reqwest::Client, + headers: reqwest::header::HeaderMap, + endpoint: String, + gzip: bool, + }, +} + +pub(crate) struct Exporter { + client: TransportClient, + resource: Resource, + timeout: Duration, +} + +impl Exporter { + pub(crate) fn new(config: &Config, resource: Resource) -> Result { + let settings = &config.settings; + let client = match settings.protocol { + Protocol::Grpc => { + let tls_config = build_rustls_config(settings)?; + let https = hyper_rustls::HttpsConnectorBuilder::new() + .with_tls_config(tls_config) + .https_or_http() + .enable_http2() + .build(); + let client = HyperClient::builder(TokioExecutor::new()) + .http2_only(true) + .build(https); + let base = config.endpoint.trim_end_matches('/'); + let uri: Uri = format!("{base}{GRPC_EXPORT_PATH}") + .parse() + .map_err(|_| "invalid OTLP gRPC URI")?; + let mut headers = HeaderMap::new(); + for (key, value) in &settings.headers { + headers.insert( + HeaderName::from_bytes(key.as_bytes()) + .map_err(|_| "invalid OTLP header name")?, + HeaderValue::from_str(value).map_err(|_| "invalid OTLP header value")?, + ); + } + headers.insert(CONTENT_TYPE, HeaderValue::from_static(GRPC_CONTENT_TYPE)); + headers.insert(TE, HeaderValue::from_static("trailers")); + if settings.gzip { + headers.insert( + HeaderName::from_static("grpc-encoding"), + HeaderValue::from_static("gzip"), + ); + } + TransportClient::Grpc { + client: Box::new(client), + uri, + headers, + gzip: settings.gzip, + } + } + Protocol::HttpProtobuf => { + let mut headers = reqwest::header::HeaderMap::new(); + for (key, value) in &settings.headers { + headers.insert( + reqwest::header::HeaderName::from_bytes(key.as_bytes()) + .map_err(|_| "invalid OTLP header name")?, + reqwest::header::HeaderValue::from_str(value) + .map_err(|_| "invalid OTLP header value")?, + ); + } + headers.insert( + reqwest::header::CONTENT_TYPE, + reqwest::header::HeaderValue::from_static(PROTOBUF_CONTENT_TYPE), + ); + if settings.gzip { + headers.insert( + reqwest::header::CONTENT_ENCODING, + reqwest::header::HeaderValue::from_static("gzip"), + ); + } + let mut builder = reqwest::Client::builder() + .timeout(config.export_timeout) + .redirect(reqwest::redirect::Policy::none()); + if let Some(cert) = &settings.certificate { + builder = builder.add_root_certificate( + reqwest::Certificate::from_pem(cert) + .map_err(|_| "invalid OTLP CA certificate")?, + ); + } + if let (Some(cert), Some(key)) = + (&settings.client_certificate, &settings.client_key) + { + let mut pem = cert.clone(); + pem.push(b'\n'); + pem.extend(key); + builder = builder.identity( + reqwest::Identity::from_pem(&pem) + .map_err(|_| "invalid OTLP client identity")?, + ); + } + TransportClient::Http { + client: builder + .build() + .map_err(|_| "failed to configure OTLP HTTP client")?, + headers, + endpoint: config.endpoint.clone(), + gzip: settings.gzip, + } + } + }; + Ok(Self { + client, + resource, + timeout: config.export_timeout, + }) + } + + pub(crate) async fn export(&mut self, records: &[LogRecord]) -> Result { + let request = encode_records_request(&self.resource, records); + let response = tokio::time::timeout(self.timeout, self.client.send(request)) + .await + .map_err(|_| ExportError::Unavailable)??; + let Some(partial) = response.partial_success else { + return Ok(Outcome::Full); + }; + let rejected = + u64::try_from(partial.rejected_log_records).map_err(|_| ExportError::Failed)?; + match rejected { + 0 if partial.error_message.is_empty() => Ok(Outcome::Full), + 0 => Ok(Outcome::Warning), + count if count <= records.len() as u64 => Ok(Outcome::Rejected(count)), + _ => Err(ExportError::Failed), + } + } +} + +fn build_rustls_config(settings: &super::ExportSettings) -> Result { + let mut roots = rustls::RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + if let Some(cert_pem) = &settings.certificate { + let certs = CertificateDer::pem_slice_iter(cert_pem) + .collect::, _>>() + .map_err(|_| "invalid OTLP CA certificate PEM")?; + if certs.is_empty() { + return Err("empty OTLP CA certificate PEM".into()); + } + for cert in certs { + roots + .add(cert) + .map_err(|_| "invalid OTLP CA certificate DER")?; + } + } + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let builder = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|_| "invalid TLS protocol configuration")? + .with_root_certificates(roots); + if let (Some(cert_pem), Some(key_pem)) = (&settings.client_certificate, &settings.client_key) { + let certs = CertificateDer::pem_slice_iter(cert_pem) + .collect::, _>>() + .map_err(|_| "invalid OTLP client certificate PEM")?; + let key = PrivateKeyDer::from_pem_slice(key_pem) + .map_err(|_| "invalid OTLP client private key PEM")?; + builder + .with_client_auth_cert(certs, key) + .map_err(|_| "invalid OTLP client mTLS certificate/key pair".into()) + } else { + Ok(builder.with_no_client_auth()) + } +} + +fn gzip_bytes(raw: &[u8]) -> Result, ExportError> { + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(raw).map_err(|_| ExportError::Failed)?; + encoder.finish().map_err(|_| ExportError::Failed) +} + +fn encode_grpc_frame(payload: &[u8], gzip: bool) -> Result { + let body = if gzip { + gzip_bytes(payload)? + } else { + payload.to_vec() + }; + let len = u32::try_from(body.len()).map_err(|_| ExportError::Failed)?; + let mut frame = Vec::with_capacity(5 + body.len()); + frame.push(u8::from(gzip)); + frame.extend_from_slice(&len.to_be_bytes()); + frame.extend_from_slice(&body); + Ok(Bytes::from(frame)) +} + +fn decode_grpc_response( + initial_headers: &HeaderMap, + trailers: Option<&HeaderMap>, + body: &[u8], +) -> Result { + let status_header = trailers + .and_then(|t| t.get("grpc-status")) + .or_else(|| initial_headers.get("grpc-status")); + let code = match status_header { + Some(val) => val + .to_str() + .ok() + .and_then(|s| s.trim().parse::().ok()) + .ok_or(ExportError::Failed)?, + // An explicit HTTP 200 gRPC response without grpc-status is malformed per gRPC spec. + None => return Err(ExportError::Failed), + }; + match code { + 0 => {} + // Cancelled (1), DeadlineExceeded (4), ResourceExhausted (8), Unavailable (14) + 1 | 4 | 8 | 14 => return Err(ExportError::Unavailable), + _ => return Err(ExportError::Failed), + } + if body.is_empty() { + return Ok(ExportLogsServiceResponse::default()); + } + if body.len() < 5 { + return Err(ExportError::Failed); + } + let compressed = body[0]; + if compressed != 0 { + // Request uses identity response encoding (`grpc-accept-encoding` not advertised as gzip). + return Err(ExportError::Failed); + } + let msg_len = u32::from_be_bytes([body[1], body[2], body[3], body[4]]) as usize; + if body.len() != 5 + msg_len || msg_len > MAX_RESPONSE_BYTES { + return Err(ExportError::Failed); + } + ExportLogsServiceResponse::decode(&body[5..]).map_err(|_| ExportError::Failed) +} + +impl TransportClient { + async fn send( + &mut self, + request: ExportLogsServiceRequest, + ) -> Result { + let encoded = request.encode_to_vec(); + match self { + Self::Grpc { + client, + uri, + headers, + gzip, + } => { + let frame = encode_grpc_frame(&encoded, *gzip)?; + let mut req = Request::builder() + .method(Method::POST) + .uri(uri.clone()) + .body(Full::new(frame)) + .map_err(|_| ExportError::Failed)?; + *req.headers_mut() = headers.clone(); + + let response = client + .request(req) + .await + .map_err(|_| ExportError::Unavailable)?; + match response.status() { + http::StatusCode::OK => {} + http::StatusCode::TOO_MANY_REQUESTS + | http::StatusCode::BAD_GATEWAY + | http::StatusCode::SERVICE_UNAVAILABLE + | http::StatusCode::GATEWAY_TIMEOUT => return Err(ExportError::Unavailable), + _ => return Err(ExportError::Failed), + } + let initial_headers = response.headers().clone(); + let collected = response + .into_body() + .collect() + .await + .map_err(|_| ExportError::Unavailable)?; + let trailers = collected.trailers().cloned(); + let bytes = collected.to_bytes(); + if bytes.len() > MAX_RESPONSE_BYTES + 5 { + return Err(ExportError::Failed); + } + decode_grpc_response(&initial_headers, trailers.as_ref(), &bytes) + } + Self::Http { + client, + headers, + endpoint, + gzip, + } => { + let body = if *gzip { + gzip_bytes(&encoded)? + } else { + encoded + }; + let mut response = client + .post(endpoint.as_str()) + .headers(headers.clone()) + .body(body) + .send() + .await + .map_err(|_| ExportError::Unavailable)?; + match response.status() { + reqwest::StatusCode::OK => {} + reqwest::StatusCode::TOO_MANY_REQUESTS + | reqwest::StatusCode::BAD_GATEWAY + | reqwest::StatusCode::SERVICE_UNAVAILABLE + | reqwest::StatusCode::GATEWAY_TIMEOUT => return Err(ExportError::Unavailable), + _ => return Err(ExportError::Failed), + } + if response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .is_some_and(|header| { + header + .to_str() + .ok() + .and_then(|value| value.split(';').next()) + .is_none_or(|media_type| { + !media_type + .trim() + .eq_ignore_ascii_case(PROTOBUF_CONTENT_TYPE) + }) + }) + { + return Err(ExportError::Failed); + } + let mut buf = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|error| { + if error.is_timeout() { + ExportError::Unavailable + } else { + ExportError::Failed + } + })? { + if chunk.len() > MAX_RESPONSE_BYTES.saturating_sub(buf.len()) { + return Err(ExportError::Failed); + } + buf.extend_from_slice(&chunk); + } + ExportLogsServiceResponse::decode(buf.as_slice()).map_err(|_| ExportError::Failed) + } + } + } +} + +// --------------------------------------------------------------------------- +// Bounded Async Batch Worker +// --------------------------------------------------------------------------- + +pub(crate) struct QueuedEntry { + pub(crate) family_index: usize, + pub(crate) log: LogRecord, +} + +#[derive(Default)] +enum ContextAttempt { + #[default] + Initial, + OnData, + Complete, +} + +#[derive(Default)] +struct ContextExport { + attempt: ContextAttempt, + acknowledged: bool, +} + +pub(crate) fn now_unix_ns() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)) + .unwrap_or_default() +} + +async fn flush( + exporter: &mut Exporter, + context: &LogRecord, + batch: &mut Vec, + health: &Health, + context_export: &mut ContextExport, +) { + if batch.is_empty() && !matches!(context_export.attempt, ContextAttempt::Initial) { + return; + } + let mut available = true; + if !matches!(context_export.attempt, ContextAttempt::Complete) { + match exporter.export(std::slice::from_ref(context)).await { + Ok(outcome @ (Outcome::Full | Outcome::Warning)) => { + if matches!(outcome, Outcome::Warning) { + health.export_warning(); + } + context_export.attempt = ContextAttempt::Complete; + if !context_export.acknowledged { + health.unconfirmed(0, 1); + context_export.acknowledged = true; + } + } + Ok(Outcome::Rejected(count)) => { + health.export_rejected(0, count); + context_export.attempt = ContextAttempt::OnData; + available = context_export.acknowledged; + } + Err(error) => { + health.export_error(); + if matches!(error, ExportError::Failed) { + context_export.attempt = ContextAttempt::OnData; + available = context_export.acknowledged; + } else { + available = false; + } + } + } + } + + let mut groups: [Vec; EVENT_NAMES.len()] = std::array::from_fn(|_| Vec::new()); + for entry in batch.drain(..) { + if let Some(group) = groups.get_mut(entry.family_index) { + group.push(entry.log); + } + } + + for (index, group) in groups + .iter() + .enumerate() + .filter(|(_, group)| !group.is_empty()) + { + let count = group.len() as u64; + if !available { + health.dropped(index, DropReason::ExportFailed, count); + continue; + } + match exporter.export(group).await { + Ok(Outcome::Full) => health.unconfirmed(index, count), + Ok(Outcome::Warning) => { + health.export_warning(); + health.unconfirmed(index, count); + } + Ok(Outcome::Rejected(rejected)) => { + health.export_rejected(index, rejected); + health.dropped(index, DropReason::ExportRejected, rejected); + health.unconfirmed(index, count.saturating_sub(rejected)); + } + Err(error) => { + health.export_error(); + health.dropped(index, DropReason::ExportFailed, count); + available = !matches!(error, ExportError::Unavailable); + context_export.attempt = ContextAttempt::OnData; + } + } + } +} + +#[allow(clippy::too_many_arguments)] +pub(crate) async fn run( + mut exporter: Exporter, + config: Config, + mut receiver: mpsc::Receiver, + context: LogRecord, + health: Arc, + stop: Arc, + finished: Arc, + done: Arc, +) { + let mut batch = Vec::with_capacity(config.batch_size); + let mut context_export = ContextExport::default(); + let mut interval = tokio::time::interval(config.flush_interval); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + + loop { + tokio::select! { + _ = stop.notified() => { + receiver.close(); + break; + } + entry = receiver.recv() => match entry { + Some(entry) => { + batch.push(entry); + if batch.len() >= config.batch_size { + flush(&mut exporter, &context, &mut batch, &health, &mut context_export).await; + } + } + None => break, + }, + _ = interval.tick() => { + flush(&mut exporter, &context, &mut batch, &health, &mut context_export).await; + } + } + } + + while let Some(entry) = receiver.recv().await { + batch.push(entry); + if batch.len() >= config.batch_size { + flush( + &mut exporter, + &context, + &mut batch, + &health, + &mut context_export, + ) + .await; + } + } + + // Attempt final flush (including initial pq.context if shutdown happened before first tick). + flush( + &mut exporter, + &context, + &mut batch, + &health, + &mut context_export, + ) + .await; + if !context_export.acknowledged { + health.dropped(0, DropReason::Shutdown, 1); + } + done.store(true, Ordering::Release); + finished.notify_waiters(); +} diff --git a/crates/common/telemetry/src/pq_events/proof.rs b/crates/common/telemetry/src/pq_events/proof.rs new file mode 100644 index 000000000..30761f486 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/proof.rs @@ -0,0 +1,280 @@ +//! Per-native-call STARK proving lifecycle (`pq.operation_admitted` and +//! `pq.operation_completed`, `eth.telemetry/0.5`). +//! +//! `Plan` is entered on the synchronous worker thread executing a committee or +//! merge proving plan; `Call` wraps each individual `leanvm_prover::aggregate` +//! invocation inside `ethlambda_crypto::stark`. + +use std::{ + cell::RefCell, + collections::{BTreeMap, BTreeSet}, + rc::Rc, +}; + +use serde_json::{Value, json}; + +use super::{Mode, Reference, duty, global}; + +thread_local! { + static CURRENT: RefCell>>> = const { RefCell::new(None) }; +} + +struct State { + mode: Mode, + workload: Value, + duty: Option<(Reference, u64)>, + plan: Reference, + calls: u64, + pending: Option, + last: Option, + messages: BTreeMap<[u8; 32], u64>, + drop_reason: &'static str, +} + +/// Scope for one fixed-input proving plan on its blocking worker thread. +pub struct Plan { + state: Rc>, + previous: Option>>, +} + +/// A finished prover call transferred across thread/await boundaries awaiting +/// consumer installation; dropping it records `discarded_late`. +pub struct Completion { + record: Option, + mode: Mode, + operation: Option, +} + +impl Completion { + pub fn ready(mut self, kind: &'static str) -> Option { + let recorder = global()?; + let point = recorder.point(); + if let Some(mut record) = self.record.take() { + record["ready"] = json!(point); + record["terminal"] = json!(point); + record["ready_kind"] = json!(kind); + record["outcome"] = json!("success"); + record["reason"] = json!("none"); + if record["workload"]["kind"] == "merge" { + record["plan_ready"] = json!(point); + } + recorder.emit("pq.operation_completed", &point, self.mode, record); + } + self.operation.take() + } +} + +impl Drop for Completion { + fn drop(&mut self) { + let Some(recorder) = global() else { return }; + if let Some(mut record) = self.record.take() { + let point = recorder.point(); + record["terminal"] = json!(point); + record["outcome"] = json!("discarded_late"); + record["reason"] = json!("deadline"); + if record["workload"]["kind"] == "merge" { + record["plan_ready"] = json!({ "missing": "not_reached" }); + } + recorder.emit("pq.operation_completed", &point, self.mode, record); + } + } +} + +impl Plan { + pub fn new(mode: Mode, workload: Value, duty: Option<(Reference, u64)>) -> Option { + let recorder = global()?; + let state = Rc::new(RefCell::new(State { + mode, + workload, + duty, + plan: recorder.reference(), + calls: 0, + pending: None, + last: None, + messages: BTreeMap::new(), + drop_reason: "other", + })); + let previous = CURRENT.with(|current| current.replace(Some(Rc::clone(&state)))); + Some(Self { state, previous }) + } + + pub fn messages(&self, messages: impl IntoIterator) { + self.state.borrow_mut().messages.extend(messages); + } + + pub fn unfinished_reason(&self, reason: &'static str) { + self.state.borrow_mut().drop_reason = reason; + } + + pub fn set_claims(&self, claims: Value) { + if let Some(record) = self.state.borrow_mut().pending.as_mut() { + record["claims"] = claims; + } + } + + pub fn take_completion(&self) -> Option { + let mut state = self.state.borrow_mut(); + Some(Completion { + record: Some(state.pending.take()?), + mode: state.mode, + operation: state.last.clone(), + }) + } + + pub fn ready(&self, kind: &'static str) -> Option { + let recorder = global()?; + let point = recorder.point(); + let mut state = self.state.borrow_mut(); + { + let mut record = state.pending.take()?; + record["ready"] = json!(point); + record["terminal"] = json!(point); + record["ready_kind"] = json!(kind); + record["outcome"] = json!("success"); + record["reason"] = json!("none"); + if record["workload"]["kind"] == "merge" { + record["plan_ready"] = json!(point); + } + recorder.emit("pq.operation_completed", &point, state.mode, record); + } + state.last.clone() + } + + pub fn discard(&self, outcome: &'static str, reason: &'static str) { + let Some(recorder) = global() else { return }; + let point = recorder.point(); + let mut state = self.state.borrow_mut(); + if let Some(mut record) = state.pending.take() { + record["terminal"] = json!(point); + record["outcome"] = json!(outcome); + record["reason"] = json!(reason); + if record["workload"]["kind"] == "merge" { + record["plan_ready"] = json!({ "missing": "not_reached" }); + } + recorder.emit("pq.operation_completed", &point, state.mode, record); + } + } +} + +impl Drop for Plan { + fn drop(&mut self) { + let reason = self.state.borrow().drop_reason; + self.discard("cancelled", reason); + CURRENT.with(|current| { + current.replace(self.previous.take()); + }); + } +} + +/// One synchronous native prover invocation (`leanvm_prover::aggregate`). +pub struct Call { + state: Rc>, + record: Option, +} + +impl Call { + pub fn start( + input_proofs: usize, + raw_signatures: usize, + messages: &[[u8; 32]], + ) -> Option { + let recorder = global()?; + let state = CURRENT.with(|current| current.borrow().as_ref().cloned())?; + let point = recorder.point(); + let mut plan = state.borrow_mut(); + if let Some(mut preceding) = plan.pending.take() { + preceding["ready"] = json!(point); + preceding["terminal"] = json!(point); + preceding["ready_kind"] = json!("intermediate"); + preceding["outcome"] = json!("success"); + preceding["reason"] = json!("none"); + recorder.emit("pq.operation_completed", &point, plan.mode, preceding); + } + plan.calls = plan.calls.saturating_add(1); + let mut workload = plan.workload.clone(); + if workload["kind"] == "merge" { + workload["input_proofs"] = json!(input_proofs); + workload["raw_signatures"] = json!(raw_signatures); + workload["input_messages"] = json!(messages.len().max(1)); + let slots = messages + .iter() + .filter_map(|m| plan.messages.get(m).copied()) + .collect::>(); + if !slots.is_empty() { + workload["vote_slots"] = json!(slots); + } else if !workload["vote_slots"].is_array() { + workload["vote_slots"] = json!([]); + } + workload["plan"] = json!(plan.plan); + workload["plan_call_index"] = json!(plan.calls); + let sequence = serde_json::from_value::(workload["sequence"].clone()).ok(); + workload["attempt_index"] = json!(sequence.as_ref().and_then(duty::next_attempt)?); + } + let operation = recorder.reference(); + plan.last = Some(operation.clone()); + let mut record = json!({ + "operation": operation, + "workload": workload, + "queued": point, + }); + if let Some((duty_ref, revision)) = &plan.duty { + record["duty"] = json!(duty_ref); + record["duty_revision"] = json!(revision); + } + recorder.emit("pq.operation_admitted", &point, plan.mode, record.clone()); + record["started"] = json!(point); + record["backend_finished"] = json!({ "missing": "not_reached" }); + record["ready"] = json!({ "missing": "not_reached" }); + record["timing_scope"] = json!("backend"); + drop(plan); + Some(Self { + state, + record: Some(record), + }) + } + + pub fn starting(&mut self) { + if let Some(recorder) = global() + && let Some(record) = &mut self.record + { + record["started"] = json!(recorder.point()); + } + } + + pub fn backend_finished(&mut self) { + if let Some(recorder) = global() + && let Some(record) = &mut self.record + { + record["backend_finished"] = json!(recorder.point()); + } + } + + pub fn returned(mut self, output_proof_bytes: usize) { + if let Some(mut record) = self.record.take() { + record["output_proof_bytes"] = json!(output_proof_bytes); + self.state.borrow_mut().pending = Some(record); + } + } +} + +impl Drop for Call { + fn drop(&mut self) { + let Some(recorder) = global() else { return }; + let Some(mut record) = self.record.take() else { + return; + }; + let terminal = recorder.point(); + record["terminal"] = json!(terminal); + record["outcome"] = json!("failed"); + record["reason"] = json!("backend_error"); + if record["workload"]["kind"] == "merge" { + record["plan_ready"] = json!({ "missing": "not_reached" }); + } + recorder.emit( + "pq.operation_completed", + &terminal, + self.state.borrow().mode, + record, + ); + } +} diff --git a/crates/common/telemetry/src/pq_events/settings.rs b/crates/common/telemetry/src/pq_events/settings.rs new file mode 100644 index 000000000..96d01bf7c --- /dev/null +++ b/crates/common/telemetry/src/pq_events/settings.rs @@ -0,0 +1,386 @@ +//! Validated standard OTLP Logs settings (`eth.telemetry/0.5`). +//! +//! Parsing is independent of process-global state so unit tests can exercise +//! precedence, percent-decoding, header validation, and TLS rules directly. + +use std::{collections::BTreeMap, time::Duration}; +use url::Url; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Protocol { + Grpc, + HttpProtobuf, +} + +#[derive(Clone)] +pub struct ExportSettings { + pub endpoint: String, + pub protocol: Protocol, + pub node_id: String, + pub service_name: String, + pub resources: BTreeMap, + pub headers: BTreeMap, + pub gzip: bool, + pub timeout: Duration, + pub certificate: Option>, + pub client_certificate: Option>, + pub client_key: Option>, + pub ignored_instance_id: bool, +} + +impl std::fmt::Debug for ExportSettings { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ExportSettings") + .field("endpoint", &self.endpoint) + .field("protocol", &self.protocol) + .field("node_id", &self.node_id) + .field("service_name", &self.service_name) + .field("gzip", &self.gzip) + .field("timeout", &self.timeout) + .field("headers", &"") + .field( + "client_key", + &self.client_key.as_ref().map(|_| ""), + ) + .finish_non_exhaustive() + } +} + +impl ExportSettings { + pub fn from_env(default_service_name: &str) -> Result { + let mut values = BTreeMap::new(); + for name in ["OTEL_RESOURCE_ATTRIBUTES", "OTEL_SERVICE_NAME"] + .into_iter() + .map(str::to_owned) + .chain( + [ + "ENDPOINT", + "PROTOCOL", + "HEADERS", + "COMPRESSION", + "TIMEOUT", + "CERTIFICATE", + "CLIENT_CERTIFICATE", + "CLIENT_KEY", + ] + .into_iter() + .flat_map(|suffix| { + [ + format!("OTEL_EXPORTER_OTLP_{suffix}"), + format!("OTEL_EXPORTER_OTLP_LOGS_{suffix}"), + ] + }), + ) + { + match std::env::var(&name) { + Ok(value) => { + values.insert(name, value); + } + Err(std::env::VarError::NotPresent) => {} + Err(std::env::VarError::NotUnicode(_)) => { + return Err(format!("{name} must be UTF-8")); + } + } + } + Self::parse(default_service_name, |name| values.get(name).cloned()) + } + + pub(crate) fn parse( + default_service_name: &str, + raw_get: impl Fn(&str) -> Option, + ) -> Result { + // OTel treats the empty string as unset. Whitespace is not an empty value. + let get = |name: &str| raw_get(name).filter(|value| !value.is_empty()); + let setting = |suffix: &str| { + get(&format!("OTEL_EXPORTER_OTLP_LOGS_{suffix}")) + .or_else(|| get(&format!("OTEL_EXPORTER_OTLP_{suffix}"))) + }; + + let protocol = match setting("PROTOCOL").as_deref().unwrap_or("grpc") { + "grpc" => Protocol::Grpc, + "http/protobuf" => Protocol::HttpProtobuf, + _ => return Err("OTLP Logs protocol must be grpc or http/protobuf".into()), + }; + + let endpoint = if let Some(endpoint) = get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT") { + endpoint + } else if let Some(base) = get("OTEL_EXPORTER_OTLP_ENDPOINT") { + validate_url(&base, protocol)?; + if protocol == Protocol::HttpProtobuf { + let mut url = Url::parse(&base).map_err(|_| "invalid OTLP endpoint")?; + url.set_path(&format!("{}/v1/logs", url.path().trim_end_matches('/'))); + url.to_string() + } else { + base + } + } else { + match protocol { + Protocol::Grpc => "http://localhost:4317", + Protocol::HttpProtobuf => "http://localhost:4318/v1/logs", + } + .into() + }; + validate_url(&endpoint, protocol)?; + + let mut resources = parse_pairs( + get("OTEL_RESOURCE_ATTRIBUTES").as_deref().unwrap_or(""), + "OTEL_RESOURCE_ATTRIBUTES", + )?; + let node_id = resources + .get("eth.node.id") + .cloned() + .ok_or("OTEL_RESOURCE_ATTRIBUTES must provide eth.node.id")?; + if node_id.trim().is_empty() || node_id.len() > 256 { + return Err("eth.node.id must contain 1 to 256 bytes".into()); + } + let service_name = get("OTEL_SERVICE_NAME") + .or_else(|| resources.get("service.name").cloned()) + .unwrap_or_else(|| default_service_name.into()); + if service_name.trim().is_empty() || service_name.len() > 256 { + return Err("service.name must contain 1 to 256 bytes".into()); + } + let ignored_instance_id = resources.remove("service.instance.id").is_some(); + resources.insert("service.name".into(), service_name.clone()); + + let headers = parse_pairs(setting("HEADERS").as_deref().unwrap_or(""), "OTLP headers")?; + for (key, value) in &headers { + http::header::HeaderName::from_bytes(key.as_bytes()) + .map_err(|_| "invalid OTLP header name")?; + let hv = http::header::HeaderValue::from_str(value) + .map_err(|_| "invalid OTLP header value")?; + if protocol == Protocol::Grpc { + if key.ends_with("-bin") || key.bytes().any(|b| b.is_ascii_uppercase()) { + return Err( + "OTLP gRPC headers require lowercase ASCII names; binary headers are unsupported" + .into(), + ); + } + if hv.as_bytes().iter().any(|&b| !(0x20..=0x7e).contains(&b)) { + return Err("invalid OTLP gRPC metadata value".into()); + } + } + } + + let gzip = match setting("COMPRESSION").as_deref() { + None => false, + Some("gzip") => true, + _ => return Err("OTLP Logs compression must be unset (uncompressed) or gzip".into()), + }; + + let timeout = match setting("TIMEOUT") { + None => Duration::from_secs(10), + Some(value) => Duration::from_millis( + value + .parse::() + .map_err(|_| "OTLP timeout must be positive integer milliseconds")?, + ), + }; + if timeout.is_zero() { + return Err("OTLP timeout must be positive".into()); + } + + let read = |name: &str| -> Result>, String> { + setting(name) + .map(|path| { + std::fs::read(path).map_err(|_| format!("cannot read OTLP {name} file")) + }) + .transpose() + }; + let certificate = read("CERTIFICATE")?; + let client_certificate = read("CLIENT_CERTIFICATE")?; + let client_key = read("CLIENT_KEY")?; + if client_certificate.is_some() != client_key.is_some() { + return Err("OTLP client certificate and key must be supplied together".into()); + } + if (certificate.is_some() || client_key.is_some()) && !endpoint.starts_with("https://") { + return Err("OTLP trust/mTLS settings require an https endpoint".into()); + } + if let Some(cert) = &certificate { + reqwest::Certificate::from_pem(cert).map_err(|_| "invalid OTLP CA certificate PEM")?; + } + if let (Some(cert), Some(key)) = (&client_certificate, &client_key) { + let mut pem = cert.clone(); + pem.push(b'\n'); + pem.extend(key); + reqwest::Identity::from_pem(&pem).map_err(|_| "invalid OTLP client identity PEM")?; + } + + Ok(Self { + endpoint, + protocol, + node_id, + service_name, + resources, + headers, + gzip, + timeout, + certificate, + client_certificate, + client_key, + ignored_instance_id, + }) + } +} + +pub(crate) fn validate_url(endpoint: &str, protocol: Protocol) -> Result { + let url = Url::parse(endpoint).map_err(|_| "invalid OTLP Logs endpoint URL")?; + if endpoint.trim() != endpoint + || !matches!(url.scheme(), "http" | "https") + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + || url.port() == Some(0) + { + return Err( + "OTLP Logs endpoint requires http/https host, no credentials or fragment, and a nonzero port" + .into(), + ); + } + if protocol == Protocol::Grpc && (!matches!(url.path(), "" | "/") || url.query().is_some()) { + return Err("OTLP gRPC endpoint paths and queries are unsupported".into()); + } + Ok(url) +} + +fn decode_percent(value: &str) -> Result { + let mut bytes = Vec::with_capacity(value.len()); + let mut iter = value.bytes(); + while let Some(byte) = iter.next() { + if byte == b'%' { + let digit = |b: u8| (b as char).to_digit(16).map(|v| v as u8); + let high = iter + .next() + .and_then(digit) + .ok_or("invalid percent encoding in OTel settings")?; + let low = iter + .next() + .and_then(digit) + .ok_or("invalid percent encoding in OTel settings")?; + bytes.push(high * 16 + low); + } else { + bytes.push(byte); + } + } + String::from_utf8(bytes).map_err(|_| "OTel settings must be UTF-8".into()) +} + +fn parse_pairs(value: &str, name: &str) -> Result, String> { + let mut result = BTreeMap::new(); + if value.is_empty() { + return Ok(result); + } + for pair in value.split(',') { + let (key, val) = pair + .split_once('=') + .ok_or_else(|| format!("malformed {name} key/value list"))?; + let key = decode_percent(key.trim())?; + let val = decode_percent(val.trim())?; + if key.is_empty() { + return Err(format!("empty key in {name}")); + } + if result.insert(key, val).is_some() { + return Err(format!("duplicate key in {name}")); + } + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(entries: &[(&str, &str)]) -> Result { + let mut values: BTreeMap = [( + "OTEL_RESOURCE_ATTRIBUTES".into(), + "eth.node.id=ethlambda-1".into(), + )] + .into(); + values.extend(entries.iter().map(|(k, v)| (k.to_string(), v.to_string()))); + ExportSettings::parse("ethlambda-bn", |key| values.get(key).cloned()) + } + + #[test] + fn standard_protocol_endpoint_precedence_and_signal_path() { + let defaults = parse(&[]).unwrap(); + assert_eq!(defaults.protocol, Protocol::Grpc); + assert_eq!(defaults.endpoint, "http://localhost:4317"); + + let specific = parse(&[ + ("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"), + ("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL", "http/protobuf"), + ("OTEL_EXPORTER_OTLP_ENDPOINT", "https://collector/base/"), + ( + "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", + "https://collector/custom/logs", + ), + ]) + .unwrap(); + assert_eq!(specific.protocol, Protocol::HttpProtobuf); + assert_eq!(specific.endpoint, "https://collector/custom/logs"); + + let general = parse(&[ + ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf"), + ("OTEL_EXPORTER_OTLP_ENDPOINT", "https://collector/base/"), + ]) + .unwrap(); + assert_eq!(general.endpoint, "https://collector/base/v1/logs"); + assert_eq!( + parse(&[("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")]) + .unwrap() + .endpoint, + "http://localhost:4318/v1/logs" + ); + assert_eq!( + parse(&[("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "")]) + .unwrap() + .endpoint, + "http://localhost:4317" + ); + assert!(parse(&[("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json")]).is_err()); + } + + #[test] + fn headers_identity_compression_and_timeout_are_validated() { + let parsed = parse(&[ + ("OTEL_EXPORTER_OTLP_HEADERS", "authorization=discarded"), + ( + "OTEL_EXPORTER_OTLP_LOGS_HEADERS", + "authorization=Bearer%20example%2Cvalue,x-test=a+b%3Dc", + ), + ("OTEL_EXPORTER_OTLP_LOGS_COMPRESSION", "gzip"), + ("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "1250"), + ( + "OTEL_RESOURCE_ATTRIBUTES", + "eth.node.id=node-a,service.instance.id=ignored,deployment.environment.name=devnet", + ), + ("OTEL_SERVICE_NAME", "custom-bn"), + ]) + .unwrap(); + assert_eq!(parsed.headers["authorization"], "Bearer example,value"); + assert_eq!(parsed.headers["x-test"], "a+b=c"); + assert!(parsed.gzip); + assert_eq!(parsed.timeout, Duration::from_millis(1250)); + assert_eq!(parsed.service_name, "custom-bn"); + assert!(parsed.ignored_instance_id); + assert!(!parsed.resources.contains_key("service.instance.id")); + assert!(!format!("{parsed:?}").contains("Bearer")); + + for (name, value) in [ + ("OTEL_RESOURCE_ATTRIBUTES", ""), + ("OTEL_RESOURCE_ATTRIBUTES", "eth.node.id="), + ("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "0"), + ("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "NaN"), + ("OTEL_EXPORTER_OTLP_LOGS_COMPRESSION", "zstd"), + ("OTEL_EXPORTER_OTLP_LOGS_COMPRESSION", "none"), + ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "broken"), + ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "authorization=%zz"), + ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "authorization=a%0Db"), + ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "x=a,x=b"), + ("OTEL_EXPORTER_OTLP_LOGS_HEADERS", "x-bin=raw"), + ] { + assert!(parse(&[(name, value)]).is_err(), "{name}={value}"); + } + assert!(parse(&[("OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE", "/definitely/missing")]).is_err()); + } +} diff --git a/crates/common/telemetry/src/pq_events/traffic.rs b/crates/common/telemetry/src/pq_events/traffic.rs new file mode 100644 index 000000000..4cfdcf88b --- /dev/null +++ b/crates/common/telemetry/src/pq_events/traffic.rs @@ -0,0 +1,508 @@ +//! Fixed-size 1-second traffic windows of ten 100 ms buckets (`pq.aggregate_traffic`, +//! `eth.telemetry/0.5`). +//! +//! Nominal window boundaries derive from a single paired `(unix_ns, mono_ns)` +//! anchor captured when the collector starts so wall-clock steps never shift +//! nominal bucket offsets. + +use std::{ + collections::VecDeque, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use super::{MAX_COUNT, Mode, Point, Recorder}; + +pub const BUCKET_NS: u64 = 100_000_000; +pub const WINDOW_NS: u64 = 1_000_000_000; +pub const MAX_TOPICS: usize = 32; +pub const MAX_RETAINED_WINDOWS: usize = 8; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Scope { + pub code_location: String, + pub payload_encoding: Encoding, + pub copy_basis: CopyBasis, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Encoding { + Compressed, + Uncompressed, + Unavailable, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CopyBasis { + AllReceivedCopies, + PerRecipient, + Unavailable, +} + +impl Scope { + pub fn unavailable(code_location: impl Into) -> Self { + Self { + code_location: code_location.into(), + payload_encoding: Encoding::Unavailable, + copy_basis: CopyBasis::Unavailable, + } + } +} + +#[derive(Clone, Copy, Debug)] +pub enum Direction { + Rx, + Tx, +} + +#[derive(Clone, Copy, Debug, Default)] +struct Counts { + payload_bytes: u64, + message_copies: u64, + lost: bool, +} + +impl Counts { + fn add(&mut self, bytes: u64) { + match ( + self.payload_bytes.checked_add(bytes), + self.message_copies.checked_add(1), + ) { + (Some(bytes), Some(copies)) if bytes <= MAX_COUNT && copies <= MAX_COUNT => { + self.payload_bytes = bytes; + self.message_copies = copies; + } + _ => self.lost = true, + } + } + + fn value(self, scope: &Scope) -> Value { + if scope.copy_basis == CopyBasis::Unavailable { + json!({ "missing": "not_exposed" }) + } else if self.lost { + json!({ "missing": "not_observed" }) + } else { + json!({ + "payload_bytes": self.payload_bytes, + "message_copies": self.message_copies, + }) + } + } +} + +pub struct Window { + topic: String, + start: Point, + rx_scope: Scope, + tx_scope: Scope, + rx: [Counts; 10], + tx: [Counts; 10], +} + +impl Window { + pub fn data(&self) -> Value { + json!({ + "topic": self.topic, + "window_start": self.start, + "bucket_ns": BUCKET_NS.to_string(), + "rx_scope": self.rx_scope, + "tx_scope": self.tx_scope, + "buckets": self.rx + .iter() + .zip(self.tx.iter()) + .map(|(rx, tx)| json!({ + "rx": rx.value(&self.rx_scope), + "tx": tx.value(&self.tx_scope), + })) + .collect::>(), + }) + } +} + +#[derive(Clone, Debug)] +pub struct Topic { + pub name: String, + pub rx_scope: Scope, + pub tx_scope: Scope, +} + +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub max_topics: usize, + pub retained_windows: usize, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_topics: MAX_TOPICS, + retained_windows: MAX_RETAINED_WINDOWS, + } + } +} + +#[derive(Clone, Copy, Debug, Default)] +struct TopicCounts { + rx: [Counts; 10], + tx: [Counts; 10], +} + +impl TopicCounts { + fn direction(&mut self, direction: Direction) -> &mut [Counts; 10] { + match direction { + Direction::Rx => &mut self.rx, + Direction::Tx => &mut self.tx, + } + } + + fn lose(&mut self, direction: Direction) { + for bucket in self.direction(direction) { + bucket.lost = true; + } + } +} + +struct Batch { + index: u64, + topics: [TopicCounts; MAX_TOPICS], +} + +impl Batch { + fn empty(index: u64) -> Self { + Self { + index, + topics: [TopicCounts::default(); MAX_TOPICS], + } + } +} + +struct Driver { + current: Batch, + completed: VecDeque, + capacity: usize, + topic_count: usize, +} + +impl Driver { + fn new(capacity: usize, topic_count: usize) -> Self { + Self { + current: Batch::empty(0), + completed: VecDeque::with_capacity(capacity), + capacity, + topic_count, + } + } + + fn advance(&mut self, elapsed: u64) -> u64 { + let target = elapsed / WINDOW_NS; + let delta = target.saturating_sub(self.current.index); + if delta == 0 { + return 0; + } + let mut evicted = 0_u64; + if delta > self.capacity as u64 { + evicted = (self.completed.len() as u64) + .saturating_add(delta.saturating_sub(self.capacity as u64)); + self.completed.clear(); + for index in target.saturating_sub(self.capacity as u64)..target { + self.completed.push_back(Batch::empty(index)); + } + self.current = Batch::empty(target); + } else { + for _ in 0..delta { + let next = self.current.index.saturating_add(1); + let completed = std::mem::replace(&mut self.current, Batch::empty(next)); + if self.completed.len() >= self.capacity { + self.completed.pop_front(); + evicted = evicted.saturating_add(1); + } + self.completed.push_back(completed); + } + } + evicted.saturating_mul(self.topic_count as u64) + } + + fn lose(&mut self, topic: usize, direction: Direction) { + if let Some(counts) = self.current.topics.get_mut(topic) { + counts.lose(direction); + } + for window in &mut self.completed { + if let Some(counts) = window.topics.get_mut(topic) { + counts.lose(direction); + } + } + } + + fn observe(&mut self, topic: usize, direction: Direction, elapsed: u64, bytes: u64) -> bool { + if elapsed / WINDOW_NS != self.current.index { + return false; + } + let bucket = ((elapsed % WINDOW_NS) / BUCKET_NS) as usize; + let Some(counts) = self + .current + .topics + .get_mut(topic) + .and_then(|c| c.direction(direction).get_mut(bucket)) + else { + return false; + }; + let was_lost = counts.lost; + counts.add(bytes); + !was_lost && counts.lost + } +} + +#[derive(Clone)] +struct Anchor { + process_id: String, + mono_ns: u64, + unix_ns: u64, +} + +impl Anchor { + fn new(point: Point) -> Result { + Ok(Self { + process_id: point.process_id, + mono_ns: point + .mono_ns + .parse() + .map_err(|_| "invalid traffic monotonic anchor")?, + unix_ns: point + .unix_ns + .parse() + .map_err(|_| "invalid traffic UTC anchor")?, + }) + } + + fn boundary(&self, index: u64) -> Option { + let offset = index.checked_mul(WINDOW_NS)?; + Some(Point { + process_id: self.process_id.clone(), + mono_ns: self.mono_ns.checked_add(offset)?.to_string(), + unix_ns: self.unix_ns.checked_add(offset)?.to_string(), + }) + } +} + +pub struct Collector { + recorder: Arc, + topics: Vec, + anchor: Anchor, + state: Mutex, + losses: [[AtomicU64; 2]; MAX_TOPICS], + pending_loss: AtomicBool, + stopped: AtomicBool, +} + +impl Collector { + pub fn new( + recorder: Arc, + topics: Vec, + limits: Limits, + ) -> Result, String> { + if limits.max_topics == 0 + || limits.max_topics > MAX_TOPICS + || limits.retained_windows == 0 + || limits.retained_windows > MAX_RETAINED_WINDOWS + || topics.is_empty() + || topics.len() > limits.max_topics + { + return Err( + "traffic collector requires 1..=32 topics and 1..=8 retained windows".into(), + ); + } + for (index, topic) in topics.iter().enumerate() { + if topic.name.is_empty() + || topic.name.len() > 512 + || topics.iter().take(index).any(|p| p.name == topic.name) + || !valid_scope(&topic.rx_scope, Direction::Rx) + || !valid_scope(&topic.tx_scope, Direction::Tx) + { + return Err("invalid or duplicate traffic topic/copy scope".into()); + } + } + let state = Driver::new(limits.retained_windows, topics.len()); + let anchor = Anchor::new(recorder.point())?; + Ok(Arc::new(Self { + recorder, + topics, + anchor, + state: Mutex::new(state), + losses: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))), + pending_loss: AtomicBool::new(false), + stopped: AtomicBool::new(false), + })) + } + + pub fn observe(&self, direction: Direction, topic: &str, payload_bytes: usize) { + if self.stopped.load(Ordering::Relaxed) { + return; + } + let Some(index) = self.topics.iter().position(|e| e.name == topic) else { + return; + }; + let now = self.recorder.monotonic_ns(); + self.observe_at(direction, index, payload_bytes as u64, now); + } + + pub(crate) fn observe_at( + &self, + direction: Direction, + topic: usize, + payload_bytes: u64, + now: u64, + ) { + let Ok(mut state) = self.state.try_lock() else { + self.note_loss(topic, direction); + return; + }; + let Some(elapsed) = now.checked_sub(self.anchor.mono_ns) else { + state.lose(topic, direction); + self.recorder + .record_summary_eviction("pq.aggregate_traffic"); + return; + }; + let evicted = state.advance(elapsed); + self.recorder + .record_summary_evictions("pq.aggregate_traffic", evicted); + self.apply_losses(&mut state); + if elapsed / WINDOW_NS != state.current.index { + state.lose(topic, direction); + self.recorder + .record_summary_eviction("pq.aggregate_traffic"); + } else if state.observe(topic, direction, elapsed, payload_bytes) { + self.recorder + .record_summary_eviction("pq.aggregate_traffic"); + } + } + + fn note_loss(&self, topic: usize, direction: Direction) { + if let Some(loss) = self + .losses + .get(topic) + .and_then(|pair| pair.get(direction_index(direction))) + { + loss.store(1, Ordering::Release); + self.pending_loss.store(true, Ordering::Release); + } + self.recorder + .record_summary_eviction("pq.aggregate_traffic"); + } + + fn apply_losses(&self, state: &mut Driver) { + if !self.pending_loss.swap(false, Ordering::AcqRel) { + return; + } + for (topic, directions) in self.losses.iter().take(self.topics.len()).enumerate() { + for (index, loss) in directions.iter().enumerate() { + if loss.swap(0, Ordering::AcqRel) != 0 { + state.lose( + topic, + if index == 0 { + Direction::Rx + } else { + Direction::Tx + }, + ); + } + } + } + } + + pub fn tick(&self) { + if !self.stopped.load(Ordering::Relaxed) { + self.flush_at(self.recorder.monotonic_ns()); + } + } + + pub fn shutdown(&self) { + self.shutdown_at(self.recorder.monotonic_ns()); + } + + pub(crate) fn shutdown_at(&self, now: u64) { + if !self.stopped.swap(true, Ordering::AcqRel) { + self.flush_at(now); + } + } + + pub(crate) fn flush_at(&self, now: u64) { + let Ok(mut state) = self.state.try_lock() else { + for index in 0..self.topics.len() { + self.note_loss(index, Direction::Rx); + self.note_loss(index, Direction::Tx); + } + return; + }; + let Some(elapsed) = now.checked_sub(self.anchor.mono_ns) else { + return; + }; + let evicted = state.advance(elapsed); + self.recorder + .record_summary_evictions("pq.aggregate_traffic", evicted); + self.apply_losses(&mut state); + let completed = state.completed.drain(..).collect::>(); + drop(state); + + for batch in completed { + let Some(start) = self.anchor.boundary(batch.index) else { + self.recorder + .record_summary_evictions("pq.aggregate_traffic", self.topics.len() as u64); + continue; + }; + let Some(close) = batch + .index + .checked_add(1) + .and_then(|idx| self.anchor.boundary(idx)) + else { + self.recorder + .record_summary_evictions("pq.aggregate_traffic", self.topics.len() as u64); + continue; + }; + for (topic, counts) in self.topics.iter().zip(batch.topics.iter()) { + let window = Window { + topic: topic.name.clone(), + start: start.clone(), + rx_scope: topic.rx_scope.clone(), + tx_scope: topic.tx_scope.clone(), + rx: counts.rx, + tx: counts.tx, + }; + self.recorder.emit( + "pq.aggregate_traffic", + &close, + Mode::Production, + window.data(), + ); + } + } + } +} + +fn direction_index(direction: Direction) -> usize { + match direction { + Direction::Rx => 0, + Direction::Tx => 1, + } +} + +fn valid_scope(scope: &Scope, direction: Direction) -> bool { + if scope.code_location.is_empty() { + return false; + } + match scope.copy_basis { + CopyBasis::Unavailable => scope.payload_encoding == Encoding::Unavailable, + CopyBasis::AllReceivedCopies => { + matches!(direction, Direction::Rx) && scope.payload_encoding != Encoding::Unavailable + } + CopyBasis::PerRecipient => { + matches!(direction, Direction::Tx) && scope.payload_encoding != Encoding::Unavailable + } + } +} diff --git a/crates/common/telemetry/tests/pq_lifecycle.rs b/crates/common/telemetry/tests/pq_lifecycle.rs new file mode 100644 index 000000000..4a447ddfd --- /dev/null +++ b/crates/common/telemetry/tests/pq_lifecycle.rs @@ -0,0 +1,503 @@ +//! End-to-end lifecycle test for `eth.telemetry/0.5` PQ events and Prometheus +//! exporter-health metrics (`EXPORTER_HEALTH.md`). +//! +//! The context is the one a beacon node announces (`pq_events::context_data`) +//! and every schedule and workload has the shape its production call site +//! builds, so the records collected here are what a node exports. Set +//! `PQ_EVENTS_DUMP=` to write them as normalized JSON, the form the +//! measurement spec's `schema.json` and `tools/` validate. + +use std::{ + sync::{Arc, Mutex}, + time::Duration, +}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, StatusCode, header::CONTENT_TYPE}, + response::IntoResponse, + routing::post, +}; +use ethlambda_telemetry::pq_events::{ + self, Config, Mode, Protocol, Record, Recorder, duty, + gossip::{self, AggregateMetadata}, + otlp, proof, traffic, +}; +use prost::Message as _; +use serde_json::json; + +#[derive(Clone, Default)] +struct CollectorState { + collected: Arc>>, + wire_batches: Arc>>>, +} + +#[tokio::test] +async fn full_pq_telemetry_lifecycle_delivers_all_active_event_families_and_health_metrics() { + let state = CollectorState::default(); + + let app = Router::new() + .route( + "/v1/logs", + post( + |State(sink): State, body: Bytes| async move { + sink.wire_batches.lock().unwrap().push(body.to_vec()); + let req = otlp::ExportLogsServiceRequest::decode(body.as_ref()).unwrap(); + let recs = otlp::decode_records_request(&req).unwrap(); + sink.collected.lock().unwrap().extend(recs); + let resp = otlp::ExportLogsServiceResponse::default().encode_to_vec(); + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, "application/x-protobuf".parse().unwrap()); + (StatusCode::OK, headers, resp).into_response() + }, + ), + ) + .with_state(state.clone()); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let context_data = pq_events::context_data( + &pq_events::StartParams { + role: "bn", + network: "pq-devnet-2", + genesis_root: format!("0x{}", "11".repeat(32)), + genesis_time: 1_799_988_000, + slot_duration: Duration::from_secs(12), + client_commit: "deadbeef", + prover_revision: Some("351f7ae4"), + prover_backend: Some("leanvm"), + log_inverse_rate: Some(2), + effective_prover_threads: Some(8), + }, + "ethlambda-0", + ); + + let mut cfg = Config::new_for_test( + format!("http://{addr}/v1/logs"), + Protocol::HttpProtobuf, + "ethlambda-0", + "ethlambda-bn", + context_data, + ) + .unwrap(); + cfg.flush_interval = Duration::from_millis(25); + + let recorder = Recorder::start(cfg).unwrap(); + assert!(pq_events::install_global(recorder.clone()).is_ok()); + + let topic = "/eth2/deadbeef/beacon_aggregate_and_proof/ssz_snappy"; + let traffic_collector = traffic::Collector::new( + recorder.clone(), + vec![traffic::Topic { + name: topic.to_owned(), + rx_scope: traffic::Scope::unavailable("rust-libp2p gossipsub internal"), + tx_scope: traffic::Scope::unavailable("rust-libp2p gossipsub internal"), + }], + traffic::Limits::default(), + ) + .unwrap(); + + // 1. Schedule a committee aggregation duty and prove its seat. + let c_key = duty::committee_key(10, 0, 0); + let c_duty = duty::schedule( + c_key.clone(), + json!({ + "kind": "committee", + "slot": 10, + "collection_unix_ns": "1799988124800000000", + "scheduled_publish_unix_ns": "1799988127200000000", + "aggregator_position": 0, + "committee_index": 0, + "committee_members": 8, + "committees_per_slot": 16, + }), + Some(42), + ) + .expect("committee duty scheduled"); + + let proof_bytes = b"leanvm-committee-proof-bytes"; + { + let plan = proof::Plan::new( + Mode::Production, + json!({ + "kind": "committee", + "purpose": "committee_duty", + "vote_slot": 10, + "committee_index": 0, + "committees_per_slot": 16, + "committee_members": 8, + "signatures": 8, + }), + Some(c_duty), + ) + .unwrap(); + let mut call = proof::Call::start(0, 8, &[]).unwrap(); + call.starting(); + call.backend_finished(); + call.returned(proof_bytes.len()); + plan.set_claims(json!({ "output_unique": 8 })); + duty::details( + &c_key, + json!({ + "collection_closed": recorder.point(), + "available_signers": 8, + "selected_signers": 8, + }), + ); + let op_ref = plan.ready("committee").unwrap(); + duty::remember_result(proof_bytes, op_ref); + } + + // 2. Receive, validate, and insert a gossip aggregate into the proposal pool. + let gossip_id = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + gossip::received(topic, gossip_id, Some(180_512), Some(179_900)); + let meta = AggregateMetadata::decoded( + 10, + Some(0), + "0x2222222222222222222222222222222222222222222222222222222222222222".into(), + 8, + 8, + Some(&[0xff, 0x01]), + 180_512, + Some(179_900), + proof_bytes.len(), + ); + gossip::annotate(gossip_id, meta.clone()); + gossip::submitted(gossip_id); + gossip::admitted(gossip_id); + { + let _scope = gossip::started(gossip_id); + gossip::committee_members(8, None); + gossip::record_current_proof_verify_ns(5_800_000); + gossip::finished(gossip_id); + } + gossip::pool_result(gossip_id, "inserted"); + duty::remember_message( + proof_bytes, + json!({ "topic": topic, "gossip_id": gossip_id }), + ); + + // 2b. Exercise 0.5 decode, precheck, queue-drop, validation-reject, and + // already-covered pool outcomes on distinct gossip messages. + let bad_decode_id = "0x1111111111111111111111111111111111111111"; + gossip::received(topic, bad_decode_id, Some(42), Some(40)); + gossip::decode_failed(bad_decode_id); + + let precheck_id = "0x2222222222222222222222222222222222222222"; + gossip::received(topic, precheck_id, Some(180_512), Some(179_900)); + gossip::annotate(precheck_id, meta.clone()); + gossip::precheck_finished(precheck_id, "ignored", "duplicate"); + + let dropped_id = "0x3333333333333333333333333333333333333333"; + gossip::received(topic, dropped_id, Some(180_512), Some(179_900)); + gossip::annotate(dropped_id, meta.clone()); + gossip::submitted(dropped_id); + gossip::queue_dropped(dropped_id); + + let unobserved_drop_id = "0x3434343434343434343434343434343434343434"; + gossip::received(topic, unobserved_drop_id, Some(180_512), Some(179_900)); + gossip::annotate(unobserved_drop_id, meta.clone()); + gossip::queue_dropped(unobserved_drop_id); + + let rejected_id = "0x4444444444444444444444444444444444444444"; + gossip::received(topic, rejected_id, Some(180_512), Some(179_900)); + gossip::annotate(rejected_id, meta.clone()); + gossip::queued(rejected_id); + { + let _scope = gossip::started(rejected_id); + gossip::committee_members(8, None); + gossip::finished(rejected_id); + } + gossip::validation_failed(rejected_id, "rejected", "invalid"); + + let covered_id = "0x5555555555555555555555555555555555555555"; + gossip::received(topic, covered_id, Some(180_512), Some(179_900)); + gossip::annotate(covered_id, meta.clone()); + gossip::queued(covered_id); + { + let _scope = gossip::started(covered_id); + gossip::committee_members(8, None); + gossip::finished(covered_id); + } + gossip::pool_result(covered_id, "covered"); + + // 3. Publish our local committee aggregate and complete the committee duty, + // plus exercise duplicate-suppressed and failed publication shapes. + let req_pt = recorder.point(); + let ret_pt = recorder.point(); + let pub_extra = duty::publication_metadata(10, Some(42), proof_bytes); + let pub_ref = gossip::published( + topic, + Some("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), + &req_pt, + &ret_pt, + "accepted", + "none", + meta.clone(), + pub_extra, + ) + .expect("publication reference"); + duty::published(10, Some(42), &pub_ref, &req_pt, &ret_pt, true); + + let _ = gossip::published( + topic, + Some("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), + &req_pt, + &ret_pt, + "duplicate_suppressed", + "duplicate", + meta.clone(), + json!({}), + ); + let _ = gossip::published( + topic, + Some("0xcccccccccccccccccccccccccccccccccccccccc"), + &req_pt, + &ret_pt, + "failed", + "queue_full", + meta.clone(), + json!({}), + ); + let _ = gossip::published( + topic, + None, + &req_pt, + &ret_pt, + "failed", + "no_peers", + meta, + json!({}), + ); + + // 4. Schedule a proposal duty, run a block-merge proving plan, and publish. + let p_key = duty::proposal_key(12); + let p_duty = duty::schedule( + p_key.clone(), + json!({ + "kind": "proposal", + "slot": 12, + "scheduled_publish_unix_ns": "1799988144000000000", + }), + Some(7), + ) + .expect("proposal duty scheduled"); + let seq = duty::sequence(&p_key).expect("proposal sequence"); + let merge_op = { + let msg_root = [0x22_u8; 32]; + let plan = proof::Plan::new( + Mode::Production, + json!({ + "kind": "merge", + "purpose": "proposal_preparation", + "proposal_slot": 12, + "vote_slots": [10], + "sequence": seq, + }), + Some(p_duty), + ) + .unwrap(); + plan.messages([(msg_root, 10)]); + let mut call = proof::Call::start(2, 0, &[msg_root]).unwrap(); + call.starting(); + call.backend_finished(); + call.returned(190_000); + plan.set_claims(json!({ + "input_sum": 16, + "input_unique": 16, + "baseline_unique": 0, + "output_unique": 16, + "added_unique": 16, + })); + plan.take_completion().unwrap().ready("proposal").unwrap() + }; + duty::details( + &p_key, + json!({ + "selection_time": recorder.point(), + "parent_root": format!("0x{}", "33".repeat(32)), + "selected_operations": [merge_op], + "reused_messages": [duty::message(proof_bytes).unwrap()], + "attestation_records": 1, + "claims_by_slot": [{ "slot": 10, "claims": 16 }], + }), + ); + let prop_req = recorder.point(); + let prop_ret = recorder.point(); + duty::proposal_published(12, &prop_req, &prop_ret, true); + + // 5. A committee duty abandoned at its cutoff, and one closed without a + // publication for another reason. + let late_key = duty::committee_key(11, 3, 1); + let no_inputs_key = duty::committee_key(11, 4, 1); + for (key, committee_index) in [(&late_key, 3), (&no_inputs_key, 4)] { + duty::schedule( + key.clone(), + json!({ + "kind": "committee", + "slot": 11, + "collection_unix_ns": "1799988137400000000", + "scheduled_publish_unix_ns": "1799988139800000000", + "aggregator_position": 1, + "committee_index": committee_index, + "committee_members": 8, + "committees_per_slot": 16, + }), + Some(43 + committee_index), + ) + .expect("committee duty scheduled"); + } + duty::missed_deadline(&late_key, 1_799_988_139_800_000_000); + duty::complete(&no_inputs_key, "no_inputs", "no_inputs"); + // A closed duty is not closed again, as an abandonment or otherwise. + duty::missed_deadline(&no_inputs_key, 1_799_988_139_800_000_000); + duty::missed_deadline(&c_key, 1_799_988_127_200_000_000); + + // 6. Wait slightly past 1s so at least one 1s `pq.aggregate_traffic` window closes. + tokio::time::sleep(Duration::from_millis(1_050)).await; + traffic_collector.shutdown(); + pq_events::shutdown(Duration::from_secs(2)).await; + + let mut recs = state.collected.lock().unwrap().clone(); + assert!(!recs.is_empty()); + assert_eq!(recs[0].event_name, "pq.context"); + recs.sort_by_key(|r| r.event_seq); + + // Verify monotonic contiguous event_seq starting at 0 with zero drops. + for (idx, rec) in recs.iter().enumerate() { + assert_eq!(rec.schema_version, "eth.telemetry/0.5"); + assert_eq!(rec.event_seq, idx as u64); + } + if let Ok(path) = std::env::var("PQ_EVENTS_DUMP") { + std::fs::write(path, serde_json::to_string_pretty(&recs).unwrap()).unwrap(); + } + if let Ok(path) = std::env::var("PQ_EVENTS_WIRE_DUMP") { + let hex_batches: Vec = state + .wire_batches + .lock() + .unwrap() + .iter() + .map(hex::encode) + .collect(); + std::fs::write(path, serde_json::to_string_pretty(&hex_batches).unwrap()).unwrap(); + } + + // Wire 0.5's duty fields: every schedule names its nominal publication + // target, and a cutoff is on abandoned duties and no others. + let scheduled: Vec<_> = named(&recs, "pq.duty_scheduled"); + assert_eq!(scheduled.len(), 4); + for data in &scheduled { + assert!(data["scheduled_publish_unix_ns"].is_string()); + for removed in ["broadcast_unix_ns", "proposal_unix_ns"] { + assert!(data.get(removed).is_none(), "0.3's {removed} on a schedule"); + } + } + let completed: Vec<_> = named(&recs, "pq.duty_completed"); + let outcomes: Vec<_> = completed + .iter() + .map(|data| data["outcome"].as_str().unwrap()) + .collect(); + assert_eq!( + outcomes, + ["published", "published", "missed_deadline", "no_inputs"] + ); + for data in &completed { + assert!( + data.get("late").is_none(), + "0.3's late flag on a completion" + ); + if data["outcome"] == "missed_deadline" { + assert_eq!(data["deadline_unix_ns"], "1799988139800000000"); + assert_eq!(data["reason"], "deadline"); + assert!(data.get("published_at").is_none() && data.get("publication").is_none()); + } else { + assert!(data.get("deadline_unix_ns").is_none()); + } + } + + let snap = recorder.snapshot(); + assert_eq!(snap.export_errors, 0); + for (family, counts) in &snap.families { + assert_eq!(counts.dropped, 0, "unexpected drops for {family}"); + } + + for expected_family in [ + "pq.context", + "pq.duty_scheduled", + "pq.operation_admitted", + "pq.operation_completed", + "pq.aggregate_received", + "pq.aggregate_processed", + "pq.aggregate_publication", + "pq.duty_completed", + "pq.aggregate_traffic", + ] { + assert!( + recs.iter().any(|r| r.event_name == expected_family), + "missing event family {expected_family}" + ); + } + + // Verify `submitted` and `admission` semantics on rejected queue admission: + // - when `gossip::submitted` ran before permit exhaustion, `submitted` carries + // that pre-admission point (`<= admission.at`); + // - when `queue_dropped` is reached without a captured `submitted` point, + // `submitted` is `{"missing": "not_exposed"}` rather than fabricated. + let processed: Vec<_> = named(&recs, "pq.aggregate_processed"); + let by_gossip_id = |gid: &str| { + processed + .iter() + .copied() + .find(|data| data["message"]["gossip_id"] == gid) + .unwrap_or_else(|| panic!("missing pq.aggregate_processed for {gid}")) + }; + let dropped = by_gossip_id(dropped_id); + assert_eq!(dropped["admission"]["outcome"], "rejected"); + assert_eq!(dropped["admission"]["reason"], "queue_full"); + let sub_mono: u64 = dropped["submitted"]["mono_ns"] + .as_str() + .expect("captured submitted point") + .parse() + .unwrap(); + let adm_mono: u64 = dropped["admission"]["at"]["mono_ns"] + .as_str() + .expect("captured admission refusal point") + .parse() + .unwrap(); + assert!(sub_mono <= adm_mono); + + let unobserved = by_gossip_id(unobserved_drop_id); + assert_eq!(unobserved["admission"]["outcome"], "rejected"); + assert_eq!(unobserved["admission"]["reason"], "queue_full"); + assert_eq!(unobserved["submitted"], json!({ "missing": "not_exposed" })); + + // Verify Prometheus exporter-health series are registered and populated. + let families = ethlambda_metrics::gather(); + for metric_name in [ + "pq_measurement_generated_total", + "pq_measurement_dropped_total", + "pq_measurement_export_unconfirmed_total", + "pq_measurement_summary_evictions_total", + "pq_measurement_export_errors_total", + ] { + assert!( + families.iter().any(|f| f.name() == metric_name), + "Prometheus scrape missing {metric_name}" + ); + } +} + +/// The payloads of the records named `event_name`, in emission order. +fn named<'a>(records: &'a [Record], event_name: &str) -> Vec<&'a serde_json::Value> { + records + .iter() + .filter(|record| record.event_name == event_name) + .map(|record| &record.data) + .collect() +} diff --git a/crates/net/p2p/Cargo.toml b/crates/net/p2p/Cargo.toml index e23778579..36379611c 100644 --- a/crates/net/p2p/Cargo.toml +++ b/crates/net/p2p/Cargo.toml @@ -86,6 +86,7 @@ libssz-types.workspace = true sha2 = "0.10" hex.workspace = true +serde_json.workspace = true [dev-dependencies] # `test-utils` for `helpers::test_state`: a test that needs a stored post-state diff --git a/crates/net/p2p/src/beacon/engine_columns.rs b/crates/net/p2p/src/beacon/engine_columns.rs index dcad42eab..922489f74 100644 --- a/crates/net/p2p/src/beacon/engine_columns.rs +++ b/crates/net/p2p/src/beacon/engine_columns.rs @@ -255,7 +255,7 @@ mod tests { let mut published = Vec::new(); while let Ok(command) = commands.try_recv() { - if let SwarmCommand::Publish { topic, data } = command { + if let SwarmCommand::Publish { topic, data, .. } = command { published.push((topic, data)); } } @@ -305,7 +305,7 @@ mod tests { publish_and_forward(&mut server, vec![sidecar(1)]); - let Ok(SwarmCommand::Publish { topic, data }) = commands.try_recv() else { + let Ok(SwarmCommand::Publish { topic, data, .. }) = commands.try_recv() else { panic!("column 1 is new and custodied, so it is published"); }; // The id gossipsub computes for a received copy of those bytes. diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index a16a037f4..b9b19e9cb 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -38,6 +38,8 @@ pub(crate) enum PqValidated { signed: Box, /// Filled in by [`Self::stateful_checks`] on `Accept`. attesting_indices: Vec, + topic: String, + pq_aggregate_id: Option, }, Attestation { attestation: Box, @@ -56,18 +58,53 @@ pub(crate) enum PqValidated { } impl PqValidated { + pub(crate) fn pq_aggregate_id(&self) -> Option<&str> { + match self { + Self::Aggregate { + pq_aggregate_id, .. + } => pq_aggregate_id.as_deref(), + _ => None, + } + } + + pub(crate) fn on_not_forwarded(&self, outcome: Outcome) { + if let Self::Aggregate { + pq_aggregate_id: Some(gid), + .. + } = self + { + let (validation_outcome, reason) = map_pq_outcome(outcome); + ethlambda_telemetry::pq_events::gossip::validation_failed( + gid, + validation_outcome, + reason, + ); + } + } + pub(crate) fn stateful_checks(&mut self, store: &Store) -> Outcome { match self { Self::Aggregate { signed, attesting_indices, - } => match gossip::pq::aggregate_stateful_checks(store, signed) { - Ok(indices) => { - *attesting_indices = indices; - Outcome::Accept + pq_aggregate_id, + .. + } => { + let _scope = pq_aggregate_id + .as_deref() + .and_then(ethlambda_telemetry::pq_events::gossip::started); + let result = gossip::pq::aggregate_stateful_checks(store, signed); + if let Some(gid) = pq_aggregate_id.as_deref() { + ethlambda_telemetry::pq_events::gossip::finished(gid); } - Err(outcome) => outcome, - }, + match result { + Ok(indices) => { + *attesting_indices = indices; + Outcome::Accept + } + Err(outcome) => outcome, + } + } Self::Attestation { attestation, subnet_id, @@ -148,10 +185,27 @@ impl PqValidated { if let Self::Aggregate { signed, attesting_indices, + topic, + pq_aggregate_id, } = &self - && outcome == Outcome::Accept { - pool_aggregate(&server.store, signed, attesting_indices); + if outcome == Outcome::Accept { + let inserted = pool_aggregate(&server.store, signed, attesting_indices); + if let Some(gid) = pq_aggregate_id { + ethlambda_telemetry::pq_events::duty::remember_message( + &signed.message.proof, + serde_json::json!({ "topic": topic, "gossip_id": gid }), + ); + ethlambda_telemetry::pq_events::gossip::pool_result( + gid, + if inserted { "inserted" } else { "covered" }, + ); + } + } else if outcome == Outcome::Ignore(IgnoreReason::Overloaded) + && let Some(gid) = pq_aggregate_id + { + ethlambda_telemetry::pq_events::gossip::queue_dropped(gid); + } } if let Self::Attestation { attestation, .. } = &self && outcome == Outcome::Accept @@ -167,6 +221,7 @@ impl PqValidated { Self::Aggregate { signed, attesting_indices, + .. } if outcome == Outcome::Accept => { let arrival = AggregateArrival { decode_start: received_at, @@ -227,12 +282,12 @@ fn pool_aggregate( store: &Store, signed: &pq::SignedAggregateAndProof, attesting_indices: &[ValidatorIndex], -) { +) -> bool { let aggregate = &signed.message.aggregate; let committees = get_committee_indices(&aggregate.committee_bits); // Gossip validation accepts single-committee aggregates only. let [committee_index] = committees[..] else { - return; + return false; }; store .pq_signature_pool() @@ -242,7 +297,64 @@ fn pool_aggregate( committee_index, attesting_indices: attesting_indices.to_vec(), proof: signed.message.proof.clone(), - }); + }) +} + +fn map_pq_outcome(outcome: Outcome) -> (&'static str, &'static str) { + match outcome { + Outcome::Accept => ("accepted", "none"), + Outcome::Reject(_) => ("rejected", "invalid"), + Outcome::Queue(_) => ("deferred", "missing_state"), + Outcome::Ignore(IgnoreReason::AlreadySeen | IgnoreReason::AlreadyStored) => { + ("ignored", "duplicate") + } + Outcome::Ignore(IgnoreReason::CoveredBits) => ("ignored", "already_covered"), + Outcome::Ignore( + IgnoreReason::UnknownBlock + | IgnoreReason::StateUnavailable + | IgnoreReason::PayloadEnvelopeUnseen + | IgnoreReason::PayloadOptimistic + | IgnoreReason::AncestryUnknown, + ) => ("ignored", "missing_state"), + Outcome::Ignore(IgnoreReason::Overloaded) => ("dropped", "queue_full"), + Outcome::Ignore(IgnoreReason::Internal) => ("error", "other"), + Outcome::Ignore(IgnoreReason::OutsideEpochWindow | IgnoreReason::Finalized) => { + ("ignored", "deadline") + } + Outcome::Ignore(_) => ("ignored", "early_gate"), + } +} + +fn build_aggregate_metadata( + signed: &pq::SignedAggregateAndProof, + ssz_bytes: usize, + compressed_bytes: Option, +) -> ethlambda_telemetry::pq_events::gossip::AggregateMetadata { + use ethlambda_types::primitives::HashTreeRoot as _; + use libssz::SszEncode as _; + + let agg = &signed.message.aggregate; + let committees = get_committee_indices(&agg.committee_bits); + let committee_index = (committees.len() == 1).then(|| committees[0]); + let data_root = format!("0x{}", hex::encode(agg.data.hash_tree_root().0)); + let bit_length = agg.aggregation_bits.len(); + let signers = (0..bit_length) + .filter(|&i| agg.aggregation_bits.get(i).unwrap_or(false)) + .count(); + let bitlist_ssz = (bit_length + <= ethlambda_telemetry::pq_events::gossip::MAX_RECORDED_AGGREGATION_BITS) + .then(|| agg.aggregation_bits.to_ssz()); + ethlambda_telemetry::pq_events::gossip::AggregateMetadata::decoded( + agg.data.slot, + committee_index, + data_root, + signers, + bit_length, + bitlist_ssz.as_deref(), + ssz_bytes, + compressed_bytes, + signed.message.proof.len(), + ) } /// Decode a message from a PQ digest's topic `kind` and run its cheap rules, @@ -255,17 +367,35 @@ fn pool_aggregate( /// scored down for this build's gap. pub(crate) fn triage( server: &P2PServer, + topic: &str, kind: &str, payload: &[u8], + compressed_len: usize, + message_id: Option<&libp2p::gossipsub::MessageId>, received_at: Instant, ) -> Option { if !beacon_decode::is_pq_reshaped(kind) { return None; } + let pq_agg_id = (kind == beacon_topics::BEACON_AGGREGATE_AND_PROOF + && ethlambda_telemetry::pq_events::is_enabled()) + .then(|| message_id.map(|id| format!("0x{}", hex::encode(&id.0)))) + .flatten(); + if let Some(ref gid) = pq_agg_id { + ethlambda_telemetry::pq_events::gossip::received( + topic, + gid, + Some(payload.len()), + Some(compressed_len), + ); + } let metric_kind = beacon_topics::metric_kind(kind).unwrap_or(kind); let decoded = match beacon_decode::decode_pq_gossip(kind, payload) { Ok(decoded) => decoded, Err(err) => { + if let Some(ref gid) = pq_agg_id { + ethlambda_telemetry::pq_events::gossip::decode_failed(gid); + } metrics::inc_beacon_gossip(metric_kind, "unsupported_fork"); debug!(kind, %err, bytes = payload.len(), "PQ gossip decode failed"); return Some(Dispatch::Report(Outcome::Ignore( @@ -273,6 +403,12 @@ pub(crate) fn triage( ))); } }; + if let (Some(gid), PqGossip::Aggregate(signed)) = (&pq_agg_id, &decoded) { + ethlambda_telemetry::pq_events::gossip::annotate( + gid, + build_aggregate_metadata(signed, payload.len(), Some(compressed_len)), + ); + } metrics::inc_beacon_gossip(metric_kind, "decoded"); trace!( kind, @@ -321,12 +457,22 @@ pub(crate) fn triage( } }; if let Err(outcome) = cheap { + if let Some(ref gid) = pq_agg_id { + let (validation_outcome, reason) = map_pq_outcome(outcome); + ethlambda_telemetry::pq_events::gossip::precheck_finished( + gid, + validation_outcome, + reason, + ); + } return Some(Dispatch::Report(outcome)); } let object = match decoded { PqGossip::Aggregate(signed) => PqValidated::Aggregate { signed, attesting_indices: Vec::new(), + topic: topic.to_owned(), + pq_aggregate_id: pq_agg_id, }, PqGossip::Attestation(attestation) => { let subnet_id = beacon_topics::attestation_subnet(kind) @@ -379,7 +525,7 @@ pub(crate) fn publish_pq_gossip( ); return; }; - let (topic, bytes) = match &object { + let (topic, bytes, is_aggregate) = match &object { PqGossipObject::Attestation { subnet_id, attestation, @@ -390,6 +536,7 @@ pub(crate) fn publish_pq_gossip( ( beacon_topics::attestation_topic_name(digest, *subnet_id), attestation.to_ssz(), + None, ) } PqGossipObject::Aggregate { @@ -397,7 +544,7 @@ pub(crate) fn publish_pq_gossip( attesting_indices, } => { // Gossip never hands a node its own aggregate back. - pool_aggregate(&server.store, aggregate, attesting_indices); + let _ = pool_aggregate(&server.store, aggregate, attesting_indices); if let Some(key) = gossip::pq::aggregate_key(aggregate) { let bits = gossip::pq::aggregation_bits(aggregate); server.seen_aggregates.record_parts(&key, &bits); @@ -405,6 +552,7 @@ pub(crate) fn publish_pq_gossip( ( beacon_topics::topic_name(digest, beacon_topics::BEACON_AGGREGATE_AND_PROOF), aggregate.to_ssz(), + Some(&**aggregate), ) } PqGossipObject::PayloadAttestation(message) => { @@ -414,6 +562,7 @@ pub(crate) fn publish_pq_gossip( ( beacon_topics::topic_name(digest, beacon_topics::PAYLOAD_ATTESTATION_MESSAGE), message.to_ssz(), + None, ) } // The Beacon API recorded it in the PQ builder market it shares with @@ -421,12 +570,31 @@ pub(crate) fn publish_pq_gossip( PqGossipObject::ProposerPreferences(preferences) => ( beacon_topics::topic_name(digest, beacon_topics::PROPOSER_PREFERENCES), preferences.to_ssz(), + None, ), }; - server.swarm_handle.publish( - IdentTopic::new(topic), - crate::gossipsub::compress_message(&bytes), - ); + let compressed = crate::gossipsub::compress_message(&bytes); + let pq_hook = if let Some(agg) = is_aggregate + && ethlambda_telemetry::pq_events::is_enabled() + { + let metadata = build_aggregate_metadata(agg, bytes.len(), Some(compressed.len())); + let extra = ethlambda_telemetry::pq_events::duty::publication_metadata( + slot, + Some(agg.message.aggregator_index), + &agg.message.proof, + ); + Some(Box::new(crate::swarm_adapter::PqPublishHook::Aggregate { + slot, + aggregator_index: agg.message.aggregator_index, + metadata, + extra, + })) + } else { + None + }; + server + .swarm_handle + .publish_with_pq(IdentTopic::new(topic), compressed, pq_hook); debug!(slot, "Published a validator client's PQ message"); let Some(blockchain) = server.blockchain.clone() else { @@ -477,7 +645,16 @@ mod tests { } fn triage_now(server: &P2PServer, kind: &str, payload: &[u8]) -> Option { - triage(server, kind, payload, Instant::now()) + let topic = format!("/eth2/00000000/{kind}/ssz_snappy"); + triage( + server, + &topic, + kind, + payload, + payload.len(), + None, + Instant::now(), + ) } /// A message this build cannot decode under a PQ digest is this build's diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index beedb9fd4..3fbc1077b 100644 --- a/crates/net/p2p/src/beacon/verdict.rs +++ b/crates/net/p2p/src/beacon/verdict.rs @@ -760,6 +760,8 @@ fn conclude(server: &mut P2PServer, id: GossipId, outcome: Outcome, object: Vali let received_at = id.received_at; if report(server, id, outcome) { object.forward(server, received_at, outcome); + } else if let Validated::Pq(pq) = &object { + pq.on_not_forwarded(outcome); } } @@ -987,7 +989,17 @@ pub(crate) fn spawn_stateful_checks( object: Validated, ) { let pool = pool_of(&object); + let pq_agg_id = match &object { + Validated::Pq(pq) => pq.pq_aggregate_id(), + _ => None, + }; + if let Some(gid) = pq_agg_id { + ethlambda_telemetry::pq_events::gossip::submitted(gid); + } let Ok(permit) = permits_for(server, &object).clone().try_acquire_owned() else { + if let Some(gid) = pq_agg_id { + ethlambda_telemetry::pq_events::gossip::queue_dropped(gid); + } metrics::inc_validation_permit_exhausted(pool); let received_at = id.received_at; let outcome = Outcome::Ignore(IgnoreReason::Overloaded); @@ -995,6 +1007,9 @@ pub(crate) fn spawn_stateful_checks( object.forward(server, received_at, outcome); return; }; + if let Some(gid) = pq_agg_id { + ethlambda_telemetry::pq_events::gossip::admitted(gid); + } let store = server.store.clone(); let actor = ctx.actor_ref(); let in_use = metrics::PoolInUse::new(pool); diff --git a/crates/net/p2p/src/gossipsub/handler.rs b/crates/net/p2p/src/gossipsub/handler.rs index 7eb04ceec..9192a1800 100644 --- a/crates/net/p2p/src/gossipsub/handler.rs +++ b/crates/net/p2p/src/gossipsub/handler.rs @@ -91,6 +91,23 @@ pub async fn handle_gossip_message( let compressed_len = message.data.len(); let Some(payload) = decompress(&message.data, kind) else { + if kind == beacon_topics::BEACON_AGGREGATE_AND_PROOF + && ethlambda_telemetry::pq_events::is_enabled() + && let Some(ref b_id) = beacon_id + && server.wire.beacon().and_then(|wire| { + beacon_topics::topic_digest(message.topic.as_str()) + .and_then(|d| wire.schedule.fork_for_digest(d)) + }) == Some(ForkName::Pq) + { + let gid = format!("0x{}", hex::encode(&b_id.message_id.0)); + ethlambda_telemetry::pq_events::gossip::received( + message.topic.as_str(), + &gid, + None, + Some(compressed_len), + ); + ethlambda_telemetry::pq_events::gossip::decode_failed(&gid); + } if let Some(id) = beacon_id { verdict::report(server, id, Outcome::Reject(RejectReason::Decompress)); } @@ -104,9 +121,15 @@ pub async fn handle_gossip_message( handle_lean_attestation(server, &payload, compressed_len).await } _ => match beacon_id { - Some(id) => { - handle_beacon_gossip(server, ctx, id, message.topic.as_str(), kind, &payload) - } + Some(id) => handle_beacon_gossip( + server, + ctx, + id, + message.topic.as_str(), + kind, + &payload, + compressed_len, + ), None => trace!(topic = %message.topic, "Gossip on an unhandled topic"), }, } @@ -234,6 +257,7 @@ fn handle_beacon_gossip( topic: &str, kind: &str, payload: &[u8], + compressed_len: usize, ) { let Some(wire) = server.wire.beacon() else { // Beacon topics are never subscribed on a lean node, whose gossipsub @@ -250,7 +274,17 @@ fn handle_beacon_gossip( // A PQ digest's reshaped topics decode as PQ's containers; its block and // column topics take the shared path below. let pq_dispatch = (topic_fork == ForkName::Pq) - .then(|| crate::beacon::pq::triage(server, kind, payload, id.received_at)) + .then(|| { + crate::beacon::pq::triage( + server, + topic, + kind, + payload, + compressed_len, + Some(&id.message_id), + id.received_at, + ) + }) .flatten(); let dispatch = if let Some(dispatch) = pq_dispatch { dispatch @@ -958,9 +992,18 @@ pub async fn publish_beacon_block( digest, beacon_topics::BEACON_BLOCK, )); + let pq_hook = if matches!(block, SignedBeaconBlock::Pq(_)) + && ethlambda_telemetry::pq_events::is_enabled() + { + Some(Box::new(crate::swarm_adapter::PqPublishHook::Proposal { + slot, + })) + } else { + None + }; server .swarm_handle - .publish(topic, compress_message(&block.to_ssz())); + .publish_with_pq(topic, compress_message(&block.to_ssz()), pq_hook); info!( slot, proposer = block.proposer_index(), diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index 81315a6f2..7ce5560ea 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -1586,6 +1586,37 @@ impl P2P { }; let (swarm_stream, swarm_handle) = swarm_adapter::start_swarm_adapter(built.swarm, node_names.clone()); + if let (Some(recorder), Some(beacon)) = ( + ethlambda_telemetry::pq_events::global(), + built.wire.beacon(), + ) { + let pq_epoch = beacon + .config + .fork_epoch(ethlambda_types::beacon::fork::ForkName::Pq); + if pq_epoch != u64::MAX { + use ethlambda_telemetry::pq_events::traffic::{Collector, Limits, Scope, Topic}; + let pq_digest = beacon.schedule.digest_at(pq_epoch); + let topic_name = beacon::topics::topic_name( + pq_digest, + beacon::topics::BEACON_AGGREGATE_AND_PROOF, + ); + if let Ok(collector) = Collector::new( + recorder.clone(), + vec![Topic { + name: topic_name, + rx_scope: Scope::unavailable( + "rust-libp2p gossipsub::Behaviour handles pre-dedup publish decoding internally", + ), + tx_scope: Scope::unavailable( + "rust-libp2p gossipsub::Behaviour::send_message enqueues per-peer RPCs privately", + ), + }], + Limits::default(), + ) { + swarm_handle.set_traffic_collector(collector); + } + } + } // Seeded from the anchor the store was bootstrapped at, so the first // range request starts where the chain does rather than at slot 0. diff --git a/crates/net/p2p/src/swarm_adapter.rs b/crates/net/p2p/src/swarm_adapter.rs index 65c24634f..8387ad069 100644 --- a/crates/net/p2p/src/swarm_adapter.rs +++ b/crates/net/p2p/src/swarm_adapter.rs @@ -42,11 +42,25 @@ const SLOW_PEER_REPORT_THRESHOLD: usize = 10; /// bandwidth that slow is not something the node can solve from its side. const MAX_SLOW_PEER_DISCONNECTS_PER_CHECK: usize = 10; +pub(crate) enum PqPublishHook { + Aggregate { + slot: u64, + aggregator_index: u64, + metadata: ethlambda_telemetry::pq_events::gossip::AggregateMetadata, + extra: serde_json::Value, + }, + Proposal { + slot: u64, + }, +} + pub enum SwarmCommand { Publish { topic: libp2p::gossipsub::IdentTopic, data: Vec, + pq_hook: Option>, }, + SetTrafficCollector(std::sync::Arc), /// Join a topic after startup: the aggregator subnets, which a validator /// client names slot by slot. Subscribe(libp2p::gossipsub::IdentTopic), @@ -137,12 +151,35 @@ pub struct SwarmHandle { impl SwarmHandle { pub fn publish(&self, topic: libp2p::gossipsub::IdentTopic, data: Vec) { + self.publish_with_pq(topic, data, None); + } + + pub(crate) fn publish_with_pq( + &self, + topic: libp2p::gossipsub::IdentTopic, + data: Vec, + pq_hook: Option>, + ) { let _ = self .cmd_tx - .send(SwarmCommand::Publish { topic, data }) + .send(SwarmCommand::Publish { + topic, + data, + pq_hook, + }) .inspect_err(|_| debug!("Swarm adapter closed, cannot publish")); } + pub(crate) fn set_traffic_collector( + &self, + collector: std::sync::Arc, + ) { + let _ = self + .cmd_tx + .send(SwarmCommand::SetTrafficCollector(collector)) + .inspect_err(|_| debug!("Swarm adapter closed, cannot install PQ traffic collector")); + } + pub fn subscribe(&self, topic: libp2p::gossipsub::IdentTopic) { let _ = self .cmd_tx @@ -291,6 +328,10 @@ async fn swarm_loop( ) { let mut mesh_metric_tick = tokio::time::interval(MESH_METRIC_REFRESH_INTERVAL); mesh_metric_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut pq_traffic_tick = tokio::time::interval(std::time::Duration::from_secs(1)); + pq_traffic_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut pq_traffic: Option> = + None; let mut slow_peers = SlowPeers::default(); let exit = loop { tokio::select! { @@ -306,7 +347,16 @@ async fn swarm_loop( } cmd = cmd_rx.recv() => { let Some(cmd) = cmd else { break LoopExit::ActorStopped }; - execute_command(&mut swarm, cmd); + if let SwarmCommand::SetTrafficCollector(collector) = cmd { + pq_traffic = Some(collector); + } else { + execute_command(&mut swarm, cmd); + } + } + _ = pq_traffic_tick.tick(), if pq_traffic.is_some() => { + if let Some(collector) = &pq_traffic { + collector.tick(); + } } _ = mesh_metric_tick.tick() => { metrics::update_gossip_mesh_peers( @@ -332,6 +382,9 @@ async fn swarm_loop( } } }; + if let Some(collector) = &pq_traffic { + collector.shutdown(); + } match exit { LoopExit::ActorStopped => info!("Swarm adapter loop stopped: the P2P actor shut down"), LoopExit::SwarmEnded => { @@ -537,14 +590,76 @@ fn disconnect_graylisted_peers(swarm: &mut libp2p::Swarm) { pub(crate) fn execute_command(swarm: &mut libp2p::Swarm, cmd: SwarmCommand) { match cmd { - SwarmCommand::Publish { topic, data } => { - swarm + SwarmCommand::Publish { + topic, + data, + pq_hook, + } => { + let topic_str = topic.hash().into_string(); + let computed_id = pq_hook.is_some().then(|| { + let msg = libp2p::gossipsub::Message { + source: None, + data: data.clone(), + sequence_number: None, + topic: topic.hash(), + }; + format!("0x{}", hex::encode(&crate::compute_message_id(&msg).0)) + }); + let requested = pq_hook + .is_some() + .then(ethlambda_telemetry::pq_events::point) + .flatten(); + let res = swarm .behaviour_mut() .gossipsub .publish(topic, data) - .inspect_err(|err| debug!(%err, "Swarm adapter: publish failed")) - .ok(); + .inspect_err(|err| debug!(%err, "Swarm adapter: publish failed")); + let returned = pq_hook + .is_some() + .then(ethlambda_telemetry::pq_events::point) + .flatten(); + if let (Some(hook), Some(requested), Some(returned)) = (pq_hook, requested, returned) { + match *hook { + PqPublishHook::Aggregate { + slot, + aggregator_index, + metadata, + extra, + } => { + let (accepted, outcome, reason, id_opt) = + pq_publish_telemetry_outcome(&res, computed_id); + if let Some(pub_ref) = ethlambda_telemetry::pq_events::gossip::published( + &topic_str, + id_opt.as_deref(), + &requested, + &returned, + outcome, + reason, + metadata, + extra, + ) { + ethlambda_telemetry::pq_events::duty::published( + slot, + Some(aggregator_index), + &pub_ref, + &requested, + &returned, + accepted, + ); + } + } + PqPublishHook::Proposal { slot } => { + ethlambda_telemetry::pq_events::duty::proposal_published( + slot, + &requested, + &returned, + res.is_ok(), + ); + } + } + } } + SwarmCommand::SetTrafficCollector(_) => {} SwarmCommand::Subscribe(topic) => { let _ = swarm .behaviour_mut() @@ -672,6 +787,31 @@ pub(crate) fn execute_command(swarm: &mut libp2p::Swarm, cmd: SwarmCo } } +fn pq_publish_telemetry_outcome( + res: &Result, + computed_id: Option, +) -> (bool, &'static str, &'static str, Option) { + use libp2p::gossipsub::PublishError; + match res { + Ok(id) => ( + true, + "accepted", + "none", + Some(format!("0x{}", hex::encode(&id.0))), + ), + Err(PublishError::Duplicate) => (false, "duplicate_suppressed", "duplicate", computed_id), + Err(PublishError::NoPeersSubscribedToTopic) => (false, "failed", "no_peers", computed_id), + Err(PublishError::AllQueuesFull(_)) => (false, "failed", "queue_full", computed_id), + Err( + PublishError::MessageTooLarge + | PublishError::SigningError(_) + | PublishError::TransformFailed(_), + ) => (false, "failed", "encode_error", None), + #[allow(unreachable_patterns)] + Err(_) => (false, "failed", "other", None), + } +} + #[cfg(test)] mod tests { use super::*; @@ -865,4 +1005,78 @@ mod tests { slow_peers.record(deferred_peer, &failed(non_priority)); assert_eq!(slow_peers.check(), nothing()); } + + #[test] + fn pq_publish_telemetry_maps_every_gossipsub_outcome_and_matches_context_hook() { + use libp2p::gossipsub::{MessageId, PublishError}; + + let computed = Some("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()); + assert_eq!( + pq_publish_telemetry_outcome(&Ok(MessageId(vec![0xbb; 20])), computed.clone()), + ( + true, + "accepted", + "none", + Some("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_string()), + ) + ); + assert_eq!( + pq_publish_telemetry_outcome(&Err(PublishError::Duplicate), computed.clone()), + (false, "duplicate_suppressed", "duplicate", computed.clone()) + ); + assert_eq!( + pq_publish_telemetry_outcome( + &Err(PublishError::NoPeersSubscribedToTopic), + computed.clone() + ), + (false, "failed", "no_peers", computed.clone()) + ); + assert_eq!( + pq_publish_telemetry_outcome(&Err(PublishError::AllQueuesFull(3)), computed.clone()), + (false, "failed", "queue_full", computed.clone()) + ); + assert_eq!( + pq_publish_telemetry_outcome(&Err(PublishError::MessageTooLarge), computed.clone()), + (false, "failed", "encode_error", None) + ); + assert_eq!( + pq_publish_telemetry_outcome( + &Err(PublishError::TransformFailed(std::io::Error::other( + "snappy" + ))), + computed, + ), + (false, "failed", "encode_error", None) + ); + + let ctx = ethlambda_telemetry::pq_events::context_data( + ðlambda_telemetry::pq_events::StartParams { + role: "bn", + network: "pq-devnet-2", + genesis_root: format!("0x{}", "11".repeat(32)), + genesis_time: 1_799_988_000, + slot_duration: std::time::Duration::from_secs(12), + client_commit: "deadbeef", + prover_revision: Some("351f7ae4"), + prover_backend: Some("leanvm"), + log_inverse_rate: Some(2), + effective_prover_threads: Some(8), + }, + "ethlambda-0", + ); + let publish_hook = ctx["hooks"]["publish"].as_str().unwrap(); + for expected in [ + "accepted/none", + "duplicate_suppressed/duplicate", + "failed/no_peers", + "failed/queue_full", + "failed/encode_error", + "failed/other", + ] { + assert!( + publish_hook.contains(expected), + "pq.context publish hook missing {expected}: {publish_hook}" + ); + } + } } diff --git a/crates/net/rpc/Cargo.toml b/crates/net/rpc/Cargo.toml index de9576f21..5dd33923b 100644 --- a/crates/net/rpc/Cargo.toml +++ b/crates/net/rpc/Cargo.toml @@ -23,6 +23,7 @@ ethlambda-metrics.workspace = true ethlambda-network-api.workspace = true ethlambda-state-transition.workspace = true ethlambda-storage.workspace = true +ethlambda-telemetry.workspace = true ethlambda-test-fixtures.workspace = true ethlambda-types.workspace = true libssz.workspace = true diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index b25b9cff6..20fe89283 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -81,22 +81,63 @@ pub(crate) fn spawn(store: Store, shutdown: CancellationToken) { /// The committees of `slot` in which one of this node's aggregators holds /// seat `position` of the aggregation committee, as `state` names them. -fn committees_at_seat(store: &Store, state: &BeaconState, slot: Slot, position: u64) -> Vec { +fn committees_at_seat( + store: &Store, + state: &BeaconState, + slot: Slot, + position: u64, +) -> Vec<(u64, u64)> { // Bound first, so the pool's lock is not held while committees are read. let aggregators = store.pq_signature_pool().aggregators(slot); aggregators .into_iter() - .filter(|(committee, validators)| { - get_aggregation_committee(state, slot, *committee).is_ok_and(|members| { - members - .get(position as usize) - .is_some_and(|member| validators.contains(member)) - }) + .filter_map(|(committee, validators)| { + let members = get_aggregation_committee(state, slot, committee).ok()?; + let member = *members.get(position as usize)?; + validators.contains(&member).then_some((committee, member)) }) - .map(|(committee, _)| committee) .collect() } +pub(crate) fn schedule_committee_duty( + config: &Config, + state: &BeaconState, + store: &Store, + slot: Slot, + committee_index: u64, + position: u64, + validator_index: u64, +) -> Option<(ethlambda_telemetry::pq_events::Reference, u64)> { + if !ethlambda_telemetry::pq_events::is_enabled() { + return None; + } + let epoch = compute_epoch_at_slot(slot); + let epoch_committees = store.committee_cache().committees(state, epoch); + let committee = epoch_committees.committee(slot, committee_index).ok()?; + let committees_per_slot = epoch_committees.committees_per_slot(); + let start_ms = slot_start_ms(config, slot); + let collection_ns = + u128::from(start_ms.saturating_add(get_aggregation_cutoff_ms(position, config))) + .saturating_mul(1_000_000); + let broadcast_ns = + u128::from(start_ms.saturating_add(get_pq_aggregate_due_ms(position, config))) + .saturating_mul(1_000_000); + ethlambda_telemetry::pq_events::duty::schedule( + ethlambda_telemetry::pq_events::duty::committee_key(slot, committee_index, position), + serde_json::json!({ + "kind": "committee", + "slot": slot, + "collection_unix_ns": collection_ns.to_string(), + "scheduled_publish_unix_ns": broadcast_ns.to_string(), + "aggregator_position": position, + "committee_index": committee_index, + "committee_members": committee.len(), + "committees_per_slot": committees_per_slot, + }), + Some(validator_index), + ) +} + /// Prove what `slot` collected for the committees whose aggregator at /// `position` is this node's, before that aggregator's broadcast time. async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { @@ -104,12 +145,27 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { return; } let deadline_ms = slot_start_ms(config, slot) + get_pq_aggregate_due_ms(position, config); + // The same cutoff for telemetry: a duty abandoned below was abandoned at it. + let deadline_ns = deadline_ms.saturating_mul(1_000_000); let Some(budget) = deadline_ms.checked_sub(now_ms()).filter(|&left| left > 0) else { warn!(%slot, position, "No time left to prove this seat's PQ aggregates"); + if ethlambda_telemetry::pq_events::is_enabled() + && let Ok((_, state)) = head(store) + { + for (committee, validator) in committees_at_seat(store, &state, slot, position) { + let _ = schedule_committee_duty( + config, &state, store, slot, committee, position, validator, + ); + let key = + ethlambda_telemetry::pq_events::duty::committee_key(slot, committee, position); + ethlambda_telemetry::pq_events::duty::missed_deadline(&key, deadline_ns); + } + } return; }; let deadline = Instant::now() + Duration::from_millis(budget); let store = store.clone(); + let cfg = config.clone(); let spawned = Instant::now(); let job = tokio::task::spawn_blocking(move || { // Time spent waiting for a blocking thread, which comes out of the @@ -123,16 +179,77 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { return; } }; - let committees = committees_at_seat(&store, &state, slot, position); - if committees.is_empty() { + let seated = committees_at_seat(&store, &state, slot, position); + if seated.is_empty() { return; } + let mut duty_by_committee = std::collections::HashMap::new(); + let closed_pt = ethlambda_telemetry::pq_events::point(); + if ethlambda_telemetry::pq_events::is_enabled() { + for &(committee, validator) in &seated { + if let Some(dref) = schedule_committee_duty( + &cfg, &state, &store, slot, committee, position, validator, + ) { + duty_by_committee.insert(committee, dref); + } + if let Some(ref pt) = closed_pt { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, committee, position, + ); + ethlambda_telemetry::pq_events::duty::details( + &key, + serde_json::json!({ "collection_closed": pt }), + ); + } + } + } + let committee_indices: Vec = seated.iter().map(|&(c, _)| c).collect(); let state_ms = started.elapsed().as_millis() as u64; - let mut groups = store.pq_signature_pool().collected(slot, &committees); - let committees = groups.len(); + let all_groups = store + .pq_signature_pool() + .collected(slot, &committee_indices); + if ethlambda_telemetry::pq_events::is_enabled() { + let seen_committees: std::collections::HashSet = + all_groups.iter().map(|g| g.committee_index).collect(); + for &(committee, _) in &seated { + if !seen_committees.contains(&committee) { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, committee, position, + ); + ethlambda_telemetry::pq_events::duty::details( + &key, + serde_json::json!({ "available_signers": 0, "selected_signers": 0 }), + ); + ethlambda_telemetry::pq_events::duty::complete(&key, "no_inputs", "no_inputs"); + } + } + } + let committees = all_groups.len(); + let mut groups = Vec::with_capacity(all_groups.len()); // What an earlier seat of this node already proved in full is not // proved again: see `PqSignaturePool::is_proven`. - groups.retain(|group| !store.pq_signature_pool().is_proven(group)); + for group in all_groups { + if store.pq_signature_pool().is_proven(&group) { + if ethlambda_telemetry::pq_events::is_enabled() { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + group.committee_index, + position, + ); + ethlambda_telemetry::pq_events::duty::details( + &key, + serde_json::json!({ "available_signers": group.signatures.len() }), + ); + ethlambda_telemetry::pq_events::duty::complete( + &key, + "suppressed", + "already_covered", + ); + } + } else { + groups.push(group); + } + } let already_proven = committees - groups.len(); let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the @@ -140,18 +257,35 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { groups.sort_by_key(|group| std::cmp::Reverse(group.signatures.len())); let (mut proved, mut failed, mut late) = (0usize, 0usize, 0usize); let mut prove_ms_total = 0u64; - for group in groups { + let mut group_iter = groups.into_iter(); + while let Some(group) = group_iter.next() { + let committee = group.committee_index; + let collected = group.signatures.len(); + let duty_key = + ethlambda_telemetry::pq_events::duty::committee_key(slot, committee, position); + ethlambda_telemetry::pq_events::duty::details( + &duty_key, + serde_json::json!({ "available_signers": collected }), + ); if Instant::now() >= deadline { warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); + ethlambda_telemetry::pq_events::duty::missed_deadline(&duty_key, deadline_ns); + for rem in group_iter { + let rem_key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + rem.committee_index, + position, + ); + ethlambda_telemetry::pq_events::duty::missed_deadline(&rem_key, deadline_ns); + } break; } - let committee = group.committee_index; - let collected = group.signatures.len(); + let duty_ref = duty_by_committee.get(&committee).cloned(); let committee_started = Instant::now(); - let result = prove_committee(&store, &state, group); + let result = prove_committee(&store, &state, group, duty_ref); let took_ms = committee_started.elapsed().as_millis() as u64; match result { - Ok((aggregate, prove_ms)) if Instant::now() < deadline => { + Ok((aggregate, prove_ms, plan)) if Instant::now() < deadline => { proved += 1; prove_ms_total += prove_ms; info!( @@ -165,11 +299,26 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { "Proved a PQ aggregate" ); store.pq_aggregate_pool().insert((*aggregate).clone()); - store.pq_signature_pool().insert_proven(aggregate); + store.pq_signature_pool().insert_proven(aggregate.clone()); + ethlambda_telemetry::pq_events::duty::details( + &duty_key, + serde_json::json!({ + "selected_signers": aggregate.attesting_indices.len(), + }), + ); + if let Some(plan) = plan + && let Some(op) = plan.ready("committee") + { + ethlambda_telemetry::pq_events::duty::remember_result(&aggregate.proof, op); + } } - Ok((aggregate, prove_ms)) => { + Ok((aggregate, prove_ms, plan)) => { late += 1; prove_ms_total += prove_ms; + if let Some(plan) = plan { + plan.discard("discarded_late", "deadline"); + } + ethlambda_telemetry::pq_events::duty::missed_deadline(&duty_key, deadline_ns); warn!( %slot, committee, @@ -179,10 +328,26 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { took_ms, "A PQ aggregate was proved after its deadline" ); + for rem in group_iter { + let rem_key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + rem.committee_index, + position, + ); + ethlambda_telemetry::pq_events::duty::missed_deadline( + &rem_key, + deadline_ns, + ); + } break; } Err(err) => { failed += 1; + ethlambda_telemetry::pq_events::duty::complete( + &duty_key, + "failed", + "backend_error", + ); debug!( %slot, committee, @@ -229,12 +394,21 @@ fn prove_committee( store: &Store, state: &BeaconState, group: CommitteeSignatures, -) -> Result<(Arc, u64), String> { + duty_ref: Option<(ethlambda_telemetry::pq_events::Reference, u64)>, +) -> Result< + ( + Arc, + u64, + Option, + ), + String, +> { let committees = store.committee_cache(); let epoch_committees = committees.committees(state, group.data.target.epoch); let committee = epoch_committees .committee(group.data.slot, group.committee_index) .map_err(|err| err.to_string())?; + let committees_per_slot = epoch_committees.committees_per_slot(); let mut aggregation_bits = pq::AggregationBits::with_length(committee.len()); let mut attesting_indices = Vec::new(); let mut signatures = Vec::new(); @@ -250,6 +424,7 @@ fn prove_committee( if signatures.is_empty() { return Err("no collected signature belongs to the committee".into()); } + let sig_count = signatures.len(); let mut committee_bits = pq::CommitteeBits::default(); committee_bits .set(group.committee_index as usize, true) @@ -261,6 +436,25 @@ fn prove_committee( }; let statements = get_attestation_statements(state, &attestation, &committees) .map_err(|err| err.to_string())?; + let plan = if let Some(dref) = duty_ref + && ethlambda_telemetry::pq_events::is_enabled() + { + ethlambda_telemetry::pq_events::proof::Plan::new( + ethlambda_telemetry::pq_events::Mode::Production, + serde_json::json!({ + "kind": "committee", + "purpose": "committee_duty", + "vote_slot": group.data.slot, + "committee_index": group.committee_index, + "committees_per_slot": committees_per_slot, + "committee_members": committee.len(), + "signatures": sig_count, + }), + Some(dref), + ) + } else { + None + }; let proving = Instant::now(); let proof = ethlambda_state_transition::beacon::helpers::pq::prove_aggregates( &statements, @@ -268,6 +462,9 @@ fn prove_committee( ) .map_err(|err| err.to_string())?; let prove_ms = proving.elapsed().as_millis() as u64; + if let Some(ref p) = plan { + p.set_claims(serde_json::json!({ "output_unique": sig_count })); + } attesting_indices.sort_unstable(); let aggregate = Arc::new(PooledPqAggregate { attestation, @@ -277,7 +474,7 @@ fn prove_committee( .try_into() .map_err(|_| "the proof exceeds MAX_STARK_PROOF_SIZE".to_string())?, }); - Ok((aggregate, prove_ms)) + Ok((aggregate, prove_ms, plan)) } fn now_ms() -> u64 { diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index d400d4181..56bc19389 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -228,6 +228,22 @@ async fn produce( if !is_valid_vrf_proof(&state, proposer, slot, &randao_reveal).unwrap_or(false) { return Err(ApiError::BadRequest("invalid randao_reveal")); } + if ethlambda_telemetry::pq_events::is_enabled() { + let proposal_ns = u128::from(config.genesis_time) + .saturating_mul(1_000_000_000) + .saturating_add( + u128::from(slot).saturating_mul(u128::from(config.slot_duration_ms) * 1_000_000), + ); + let _ = ethlambda_telemetry::pq_events::duty::schedule( + ethlambda_telemetry::pq_events::duty::proposal_key(slot), + serde_json::json!({ + "kind": "proposal", + "slot": slot, + "scheduled_publish_unix_ns": proposal_ns.to_string(), + }), + Some(proposer), + ); + } let fee_recipient = prepared_fee_recipient(fee_recipients, proposer).unwrap_or(ExecutionAddress::ZERO); // The execution client's version, for the graffiti, is asked alongside @@ -325,9 +341,54 @@ async fn attestations_for_block( proof_bytes = packed.proof.len(), "Collected the PQ attestations packed ahead of the slot" ); + record_proposal_selection(slot, head_root, &packed.attestations, &packed.proof); return (packed.attestations, packed.proof); } } let packed = pack_attestations(store, state, config, PermitWait::TryOnce).await; + record_proposal_selection(slot, head_root, &packed.attestations, &packed.proof); (packed.attestations, packed.proof) } + +fn record_proposal_selection( + slot: Slot, + parent_root: Root, + attestations: &[pq::Attestation], + proof: &[u8], +) { + let Some(selection_time) = ethlambda_telemetry::pq_events::point() else { + return; + }; + let mut selected_ops = Vec::new(); + let mut reused_msgs = Vec::new(); + if !proof.is_empty() { + if let Some(op) = ethlambda_telemetry::pq_events::duty::result(proof) { + selected_ops.push(op); + } else if let Some(msg) = ethlambda_telemetry::pq_events::duty::message(proof) { + reused_msgs.push(msg); + } + } + let mut by_slot = std::collections::BTreeMap::::new(); + for att in attestations { + let len = att.aggregation_bits.len(); + let signers = (0..len) + .filter(|&i| att.aggregation_bits.get(i).unwrap_or(false)) + .count(); + *by_slot.entry(att.data.slot).or_default() += signers; + } + let claims_by_slot: Vec<_> = by_slot + .into_iter() + .map(|(s, claims)| serde_json::json!({ "slot": s, "claims": claims })) + .collect(); + ethlambda_telemetry::pq_events::duty::details( + ðlambda_telemetry::pq_events::duty::proposal_key(slot), + serde_json::json!({ + "selection_time": selection_time, + "parent_root": format!("0x{}", hex::encode(parent_root.0)), + "selected_operations": selected_ops, + "reused_messages": reused_msgs, + "attestation_records": attestations.len(), + "claims_by_slot": claims_by_slot, + }), + ); +} diff --git a/crates/net/rpc/src/beacon/validator.rs b/crates/net/rpc/src/beacon/validator.rs index f8c4e8cc0..ecb6a5a26 100644 --- a/crates/net/rpc/src/beacon/validator.rs +++ b/crates/net/rpc/src/beacon/validator.rs @@ -366,6 +366,33 @@ async fn post_committee_subscriptions( (subnet_id, entry.slot) }) .collect(); + if ethlambda_telemetry::pq_events::is_enabled() + && let Ok((_, state)) = head(&store) + { + for entry in subscriptions + .iter() + .filter(|entry| entry.is_aggregator && is_pq_slot(entry.slot)) + { + if let Ok(members) = + ethlambda_state_transition::beacon::helpers::pq::get_aggregation_committee( + &state, + entry.slot, + entry.committee_index, + ) + && let Some(pos) = members.iter().position(|&v| v == entry.validator_index) + { + let _ = crate::beacon::pq_aggregation::schedule_committee_duty( + &config, + &state, + &store, + entry.slot, + entry.committee_index, + pos as u64, + entry.validator_index, + ); + } + } + } if !subnets.is_empty() && p2p.subscribe_attestation_subnets(subnets).is_err() { return ApiError::Internal("the network actor is not running").into_response(); } @@ -388,12 +415,44 @@ struct ProposerPreparation { /// `POST /eth/v1/validator/prepare_beacon_proposer`: record where each /// validator's block rewards should be paid. async fn post_prepare_beacon_proposer( + State(store): State, Extension(fee_recipients): Extension, Json(preparations): Json>, ) -> Response { - let mut map = fee_recipients.lock().expect("fee recipient lock poisoned"); - for preparation in preparations { - map.insert(preparation.validator_index, preparation.fee_recipient); + { + let mut map = fee_recipients.lock().expect("fee recipient lock poisoned"); + for preparation in &preparations { + map.insert(preparation.validator_index, preparation.fee_recipient); + } + } + if ethlambda_telemetry::pq_events::is_enabled() + && let Ok((_, state)) = head(&store) + && let BeaconState::Pq(inner) = state.as_ref() + { + let config = store.config(); + let start_slot = compute_start_slot_at_epoch(compute_epoch_at_slot(state.slot())); + let prepared: std::collections::HashSet = + preparations.iter().map(|p| p.validator_index).collect(); + for (offset, &proposer) in inner.proposer_lookahead.iter().enumerate() { + let slot = start_slot + offset as u64; + if slot > 0 && prepared.contains(&proposer) { + let proposal_ns = u128::from(config.genesis_time) + .saturating_mul(1_000_000_000) + .saturating_add( + u128::from(slot) + .saturating_mul(u128::from(config.slot_duration_ms) * 1_000_000), + ); + let _ = ethlambda_telemetry::pq_events::duty::schedule( + ethlambda_telemetry::pq_events::duty::proposal_key(slot), + serde_json::json!({ + "kind": "proposal", + "slot": slot, + "scheduled_publish_unix_ns": proposal_ns.to_string(), + }), + Some(proposer), + ); + } + } } axum::http::StatusCode::OK.into_response() } diff --git a/crates/validator/Cargo.toml b/crates/validator/Cargo.toml index c45e7d693..1ed2ec5af 100644 --- a/crates/validator/Cargo.toml +++ b/crates/validator/Cargo.toml @@ -12,6 +12,7 @@ version.workspace = true [dependencies] ethlambda-types.workspace = true ethlambda-metrics.workspace = true +ethlambda-telemetry.workspace = true # leanXMSS signing and VRF proofs for the PQ fork (`pq`). ethlambda-crypto.workspace = true # A pool of the VRF trees' own, so hashing one does not hold up the leanXMSS diff --git a/crates/validator/src/aggregation.rs b/crates/validator/src/aggregation.rs index d18ac2c49..6898dc81d 100644 --- a/crates/validator/src/aggregation.rs +++ b/crates/validator/src/aggregation.rs @@ -167,18 +167,57 @@ impl AggregationService { // A 404 also when another aggregator's broadcast already // covers every attester: nothing to publish, as the // specification has it. The node's message says which. - Err(Error::BeaconNodeStatus { status: 404, body }) => info!( - %slot, - committee = duty.committee_index, - reason = %body, - "No PQ aggregate to publish for this committee" - ), - Err(err) => warn!( - %slot, - committee = duty.committee_index, - %err, - "Could not fetch this committee's PQ aggregate" - ), + Err(Error::BeaconNodeStatus { status: 404, body }) => { + let suppressed = body.contains("covered"); + for d in selected + .iter() + .filter(|d| d.committee_index == duty.committee_index) + { + if suppressed { + ethlambda_telemetry::pq_events::duty::committee_suppressed( + slot, + d.committee_index, + d.validator_index, + ); + } else { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + d.committee_index, + d.aggregator_position.unwrap_or(0), + ); + ethlambda_telemetry::pq_events::duty::complete( + &key, + "no_inputs", + "no_inputs", + ); + } + } + info!( + %slot, + committee = duty.committee_index, + reason = %body, + "No PQ aggregate to publish for this committee" + ); + } + Err(err) => { + for d in selected + .iter() + .filter(|d| d.committee_index == duty.committee_index) + { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + d.committee_index, + d.aggregator_position.unwrap_or(0), + ); + ethlambda_telemetry::pq_events::duty::complete(&key, "failed", "other"); + } + warn!( + %slot, + committee = duty.committee_index, + %err, + "Could not fetch this committee's PQ aggregate" + ); + } } } @@ -190,6 +229,12 @@ impl AggregationService { let pubkey = match parse_pubkey(&duty.pubkey) { Ok(pubkey) => pubkey, Err(err) => { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + duty.committee_index, + duty.aggregator_position.unwrap_or(0), + ); + ethlambda_telemetry::pq_events::duty::complete(&key, "failed", "other"); warn!(%slot, validator = duty.validator_index, %err, "Duty carried an unreadable pubkey"); continue; } @@ -204,16 +249,26 @@ impl AggregationService { .aggregate_and_proof_signing_root(message.hash_tree_root(), slot); let leaf = crate::pq::slot_leaf(slot, LEAF_OFFSET_AGGREGATE_AND_PROOF); let request = crate::pq::SignRequest { pubkey, leaf, root }; - owed.push((message, request)); + owed.push((duty, message, request)); } // Signed together, in parallel off this task. - let requests = owed.iter().map(|(_, request)| *request).collect(); + let requests = owed.iter().map(|(_, _, request)| *request).collect(); let signatures = crate::pq::sign_all(requests).await; let mut signed = Vec::with_capacity(owed.len()); - for ((message, _), signature) in owed.into_iter().zip(signatures) { + let mut signed_keys = Vec::with_capacity(owed.len()); + for ((duty, message, _), signature) in owed.into_iter().zip(signatures) { + let key = ethlambda_telemetry::pq_events::duty::committee_key( + slot, + duty.committee_index, + duty.aggregator_position.unwrap_or(0), + ); match signature { - Ok(signature) => signed.push(pq::SignedAggregateAndProof { message, signature }), + Ok(signature) => { + signed.push(pq::SignedAggregateAndProof { message, signature }); + signed_keys.push(key); + } Err(err) => { + ethlambda_telemetry::pq_events::duty::complete(&key, "failed", "other"); let validator = message.aggregator_index; warn!(%slot, validator, %err, "Failed to sign a PQ aggregate"); } @@ -222,6 +277,9 @@ impl AggregationService { if signed.is_empty() { return Ok(0); } + for key in &signed_keys { + ethlambda_telemetry::pq_events::duty::submitted(key); + } let count = signed.len(); self.beacon_node.publish_pq_aggregates(&signed).await?; info!(%slot, count, "Published PQ aggregates"); diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index 662f3c771..d364b7629 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -695,6 +695,11 @@ pub fn config_from_spec_response(value: &serde_json::Value) -> Result { if let Some(epochs) = spec_u64(value, "SHARD_COMMITTEE_PERIOD")? { config.shard_committee_period = epochs; } + if let Some(name) = value.get("CONFIG_NAME").and_then(serde_json::Value::as_str) + && let Ok(parsed) = ethlambda_types::beacon::config::ConfigName::try_from(name) + { + config.config_name = parsed; + } if let Some(version) = spec_version(value, "GENESIS_FORK_VERSION")? { config = config.with_fork_version(ForkName::Phase0, version); } diff --git a/crates/validator/src/duties.rs b/crates/validator/src/duties.rs index 1012b8c46..1975b6711 100644 --- a/crates/validator/src/duties.rs +++ b/crates/validator/src/duties.rs @@ -150,6 +150,60 @@ impl DutiesService { Ok(changed) } + pub fn schedule_pq_telemetry(&self, epoch: Epoch, clock: &crate::slot_clock::SlotClock) { + if !ethlambda_telemetry::pq_events::is_enabled() { + return; + } + let sys_ns = |t: std::time::SystemTime| -> String { + t.duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + .to_string() + }; + for &ep in &[epoch, epoch.saturating_add(1)] { + if let Some(held) = self.by_epoch.get(&ep) { + for duty in &held.duties { + if duty.is_aggregator == Some(true) && clock.is_pq(duty.slot) { + let pos = duty.aggregator_position.unwrap_or(0); + let _ = ethlambda_telemetry::pq_events::duty::schedule( + ethlambda_telemetry::pq_events::duty::committee_key( + duty.slot, + duty.committee_index, + pos, + ), + serde_json::json!({ + "kind": "committee", + "slot": duty.slot, + "collection_unix_ns": sys_ns(clock.pq_aggregation_cutoff_time(duty.slot, pos)), + "scheduled_publish_unix_ns": sys_ns(clock.pq_aggregation_time(duty.slot, pos)), + "aggregator_position": pos, + "committee_index": duty.committee_index, + "committee_members": duty.committee_length, + "committees_per_slot": duty.committees_at_slot, + }), + Some(duty.validator_index), + ); + } + } + } + } + if let Some(held) = self.proposers.get(&epoch) { + for duty in &held.duties { + if clock.is_pq(duty.slot) { + let _ = ethlambda_telemetry::pq_events::duty::schedule( + ethlambda_telemetry::pq_events::duty::proposal_key(duty.slot), + serde_json::json!({ + "kind": "proposal", + "slot": duty.slot, + "scheduled_publish_unix_ns": sys_ns(clock.start_of(duty.slot)), + }), + Some(duty.validator_index), + ); + } + } + } + } + /// Fetch `epoch`'s proposer duties and keep only this client's, replacing /// anything held for that epoch if the `dependent_root` has changed. /// diff --git a/crates/validator/src/error.rs b/crates/validator/src/error.rs index 620eae1d2..020da3816 100644 --- a/crates/validator/src/error.rs +++ b/crates/validator/src/error.rs @@ -142,6 +142,8 @@ pub enum Error { /// values here, or a different one from what this process already runs. #[error("cannot run the beacon node's preset: {0}")] Preset(String), + #[error("telemetry configuration error: {0}")] + TelemetryConfig(String), #[error("keystore {path}: {reason}")] Keystore { path: String, reason: String }, @@ -285,6 +287,7 @@ impl Error { | Self::SlashingProtection { .. } | Self::SlashingProtectionUnusable { .. } | Self::Io { .. } + | Self::TelemetryConfig(_) | Self::Unflushed { .. } => false, } } diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 4df0c2d0b..9759177c8 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -186,6 +186,13 @@ pub struct ValidatorConfig { /// votes when its payload does, rather than only at their deadlines. See /// [`head_monitor`]. pub event_stream: bool, + + /// Optional comma-separated telemetry event families (`--telemetry-events`, + /// `pq` in `eth.telemetry/0.5`). + pub telemetry_events: Option, + + /// Client git commit reported in `pq.context`. + pub client_commit: String, } /// Builder proposals: register each validator with the beacon node's builder @@ -340,6 +347,30 @@ pub async fn run(config: ValidatorConfig, stop: impl Future { + duties.schedule_pq_telemetry(epoch, &clock); last_epoch = Some(epoch); resubscribe = moved; to_register = Some(registrable); @@ -927,6 +959,7 @@ pub async fn run(config: ValidatorConfig, stop: impl Future( "Block proposal ran past the point attesters stop waiting and was abandoned" ); metrics::inc_block_proposal_failures(); + // The cutoff the budget above runs to, in UTC: the slot's + // attestation time, not a fresh reading. Recorded only for a PQ + // duty not yet handed to the node: one that was may already be + // published. + let cutoff_ns = clock + .attestation_time(slot) + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_nanos() as u64); + ethlambda_telemetry::pq_events::duty::missed_deadline( + ðlambda_telemetry::pq_events::duty::proposal_key(slot), + cutoff_ns, + ); } Err(err) => { error!(%slot, validator = duty.validator_index, %err, "Failed to propose this slot's block"); diff --git a/crates/validator/src/proposal.rs b/crates/validator/src/proposal.rs index 4c0cbeaef..87b032cb2 100644 --- a/crates/validator/src/proposal.rs +++ b/crates/validator/src/proposal.rs @@ -477,13 +477,26 @@ impl ProposalService { }; let randao_reveal = crate::pq::vrf_proof(&pubkey, slot).map_err(pq_error)?; let graffiti = self.settings.graffiti(&pubkey); - let contents = before( + let contents = match before( deadline, slot, self.beacon_node .produce_pq_block(slot, &randao_reveal, Some(graffiti)), ) - .await?; + .await + { + Ok(contents) => contents, + Err(err) => { + // A deadline is closed by the caller, which holds the cutoff + // (`propose` in `lib.rs`); anything else left the node + // without a block to sign. + if !matches!(err, Error::ProposalDeadline { .. }) { + let key = ethlambda_telemetry::pq_events::duty::proposal_key(slot); + ethlambda_telemetry::pq_events::duty::complete(&key, "unavailable", "other"); + } + return Err(err); + } + }; if contents.block.slot != slot || contents.block.proposer_index != validator { return Err(Error::InconsistentResponse(format!( "asked for validator {validator}'s PQ block at slot {slot}, node built one for \ @@ -534,6 +547,9 @@ impl ProposalService { message: contents.block, signature, }; + ethlambda_telemetry::pq_events::duty::submitted( + ðlambda_telemetry::pq_events::duty::proposal_key(slot), + ); let published = before( deadline, slot, diff --git a/crates/validator/src/slot_clock.rs b/crates/validator/src/slot_clock.rs index a07443c59..11617ee3f 100644 --- a/crates/validator/src/slot_clock.rs +++ b/crates/validator/src/slot_clock.rs @@ -187,6 +187,13 @@ impl SlotClock { self.start_of(slot) + Duration::from_millis(offset_ms) } + pub fn pq_aggregation_cutoff_time(&self, slot: Slot, position: u64) -> SystemTime { + let component = |bps: u64| bps.saturating_mul(self.slot_duration_ms) / BASIS_POINTS; + let offset_ms = component(self.config.aggregation_cutoff_bps) + .saturating_add(position.saturating_mul(component(self.config.aggregator_delay_bps))); + self.start_of(slot) + Duration::from_millis(offset_ms) + } + /// When the sync committee message for `slot` is signed. /// /// The fork of `slot` picks the offset, as it does for attestations: diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index c4cefe75a..43338118f 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -69,6 +69,7 @@ changes. | Block production | `pq_block_production`, `rpc::beacon::pq_proposal` | self-build; attestations packed from validated aggregates, their proofs merged under a deadline; blobs, their columns gossiped with the envelope. Every block it built on the devnet was canonical on Lighthouse | | VRF tree | `ethlambda_crypto::vrf` | the specification's Keccak-256 tree over all `2^31` leaves, each `keccak256(vrf_seed \|\| le64(slot))`; known answers from ethereum-package's published state. Restorable from a compact state (root and leaf 0's branch), which the package publishes for its genesis validators and `ethlambda pq-keys` writes | | Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; aggregators staggered by seat; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | +| PQ telemetry | `ethlambda_telemetry::pq_events` | opt-in `--telemetry-events=pq` (`eth.telemetry/0.5` / registry `0.10.0` OTLP Logs over `grpc` and `http/protobuf` plus `pq_measurement_*` Prometheus exporter-health counters) on both `beacon` and `validator` | | Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead with leanVM, seat by seat | | Beacon API | `rpc::beacon::{pool, pq_proposal, ptc, proposal}` | PQ attestations, aggregates (in and out), payload attestations, blocks, envelopes and `POST /eth/v1/validator/pq_blocks/{slot}`; the other endpoints refuse PQ's signed containers | @@ -569,6 +570,29 @@ What the package does for ethlambda on a PQ network: --output-dir keys` writes the key file the generator reads (`xmss_pubkey_url`) and the VRF states (`vrf_state_url`); every root hashes a whole tree, minutes a validator, and the run is resumable. +- Both `ethlambda beacon` and `ethlambda validator` accept + `--telemetry-events=pq` to export `eth.telemetry/0.5` structured PQ + measurement events (`pq.context`, `pq.aggregate_received`, + `pq.aggregate_processed`, `pq.aggregate_publication`, `pq.operation_admitted`, + `pq.operation_completed`, `pq.duty_scheduled`, `pq.duty_completed`, + `pq.aggregate_traffic`) over OTLP Logs (`grpc` or `http/protobuf`) configured + via standard `OTEL_*` environment variables (`OTEL_EXPORTER_OTLP_LOGS_*`, + `OTEL_RESOURCE_ATTRIBUTES` with `eth.node.id`, `OTEL_SERVICE_NAME`), alongside + the `pq_measurement_*` Prometheus exporter-health counters. + The contract is [ethDreamer/pq-measurement-spec](https://github.com/ethDreamer/pq-measurement-spec) + at wire 0.5 (registry 0.10.0): a duty's schedule names its nominal + publication target (`scheduled_publish_unix_ns`), a completion carries no + `late` flag, a duty abandoned at its cutoff (`missed_deadline`) carries + that cutoff as `deadline_unix_ns`, and aggregate processing and publication + use the 0.5 `admission`, `decision_stage`, `result` and `closed` shapes. The + beacon node's cutoff for a committee seat is the seat's broadcast time, where + it stops proving and discards a proof finished later; the validator client's + for a proposal is the slot's attestation time, where a block not yet handed + to the node is abandoned. To check the records against the spec's own schema + and tools, run + `PQ_EVENTS_DUMP= cargo test -p ethlambda-telemetry --test pq_lifecycle`: + it writes every record that test exports as normalized JSON, the form + `schemas/pq.schema.json` validates. Before genesis, `docker run --rm --entrypoint ethlambda ethlambda:pq-local pq-prover-check` on a devnet host says whether its prover keeps up with a diff --git a/docs/cli.md b/docs/cli.md index d893a529e..5edcc4db1 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -166,6 +166,7 @@ something specific here. | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | | `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.19.0 (`351f7ae4`, the release pq-devnet-1 runs, and the only one it takes). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | +| `--telemetry-events` | off | Comma-separated telemetry event families to export over OTLP Logs (`pq` in `eth.telemetry/0.5`, registry `0.10.0`). Configured via standard `OTEL_EXPORTER_OTLP_LOGS_*` / `OTEL_EXPORTER_OTLP_*`, `OTEL_RESOURCE_ATTRIBUTES` (requiring `eth.node.id`), and `OTEL_SERVICE_NAME` environment variables | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, @@ -390,6 +391,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | `--init-slashing-protection` | off | Register every loaded key with no slashing-protection record as never having signed, instead of refusing to start. Dangerous: only for keys that have signed nothing anywhere for at least two epochs, and even then it rules out a double vote only, not a surround of an older vote; a key with a history should bring it instead. Never lowers an existing record; remove it once the keys are registered, and startup warns while it is set for nothing | | `--enable-doppelganger-protection` | off | Sign no attestation or block for a validator until the beacon node has seen it stay silent for a full epoch, and stop if it sees one act meanwhile. Applies at every start and to every key the keymanager API imports, and costs two to three epochs of attestations each time. See [Doppelganger protection](#doppelganger-protection) | | `--disable-event-stream` | off | Read no beacon node's event stream, so every attestation, sync committee message and payload timeliness committee vote waits for its offset into the slot. One flag for what Lighthouse splits between `--disable-beacon-head-monitor` and `--disable-payload-available-monitor`; Prysm's nearest is `--disable-attest-timely`. For a node whose stream is broken, or a proxy in front of it that holds events back. See [Duties start on the block](#duties-start-on-the-block) | +| `--telemetry-events` | off | Comma-separated telemetry event families to export over OTLP Logs (`pq` in `eth.telemetry/0.5`, registry `0.10.0`), configured via standard `OTEL_*` environment variables | ### What it does today diff --git a/docs/metrics.md b/docs/metrics.md index a0578e26a..887914c2f 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -899,6 +899,20 @@ Observability into how many validators/subnets are covered by the attestations t | `lean_attestation_aggregate_coverage_subnets` | Gauge | Number of covered subnets in attestation aggregate reports | Per round, per section (see note above) | section=timely,late,block,combined,agg_start_new,proposal_combined | | `lean_attestation_aggregate_coverage_diff_validators` | Gauge | Validators in the symmetric difference between block-included aggregates and locally-aggregated timely aggregates for the same slot | On block import, when the head carries the round's votes (see note above) | direction=block_only,timely_only | +### PQ Measurement Exporter Health (`--telemetry-events=pq`) + +When `ethlambda beacon` or `ethlambda validator` is started with `--telemetry-events=pq`, `ethlambda_telemetry::pq_events` registers and zero-initializes the `EXPORTER_HEALTH.md` operational counters on that process's Prometheus `/metrics` endpoint across all ten `pq.*` event families (`pq.context`, `pq.aggregate_received`, `pq.aggregate_processed`, `pq.aggregate_publication`, `pq.validation_batch`, `pq.operation_admitted`, `pq.operation_completed`, `pq.duty_scheduled`, `pq.duty_completed`, `pq.aggregate_traffic`): + +| Name | Type | Usage | Labels | +|------|------|-------|--------| +| `pq_measurement_generated_total` | Counter | Logical PQ telemetry records generated, excluding OTLP transport retries | `event` | +| `pq_measurement_dropped_total` | Counter | Logical PQ telemetry records terminally discarded locally or rejected by the collector | `event`, `reason=queue_full,record_invalid,record_too_large,export_rejected,export_failed,shutdown,other` | +| `pq_measurement_export_errors_total` | Counter | OTLP Logs export requests failing or exceeding their timeout | | +| `pq_measurement_export_unconfirmed_total` | Counter | PQ telemetry records acknowledged by the OTLP endpoint without rejection (durable collector storage unconfirmed) | `event` | +| `pq_measurement_summary_evictions_total` | Counter | Correlation or traffic-summary observations lost before record generation due to bounded state eviction or non-blocking lock contention | `event` | +| `pq_measurement_export_rejected_total` | Counter | Record submissions rejected in valid OTLP `partial_success` responses | `event` | +| `pq_measurement_export_warnings_total` | Counter | OTLP export requests acknowledged with a `partial_success` warning message and zero rejected records | | + --- ✅(*) **Partial support**: These metrics are implemented but not collected "on scrape" as the spec requires. They are updated on specific events (e.g., on tick, on block processing) rather than being computed fresh on each Prometheus scrape. From fd3d276aa8656886ab323db9fa18ce2d7854f92b Mon Sep 17 00:00:00 2001 From: ilitteri Date: Thu, 3 Dec 2026 22:59:25 -0300 Subject: [PATCH 25/25] Describe the telemetry crate's OTLP pq.* events in CLAUDE.md's crate map, as pq-devnet-2's does --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 557aaab35..5adcf5fa9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ crates/ ├─ crypto/ # XMSS sign/verify + aggregation (leanVM wrapper) ├─ ssz-tree/ # Persistent Merkle tree (List/Vector) behind the beacon registry and balances ├─ metrics/ # Prometheus re-exports, TimingGuard, gather utilities - ├─ telemetry/ # ClickHouse block_events rows (opt-in) + ├─ telemetry/ # ClickHouse block_events rows + OTLP pq.* telemetry events (opt-in) └─ test-fixtures/ # Spec-fixture loading (prod dep of rpc's Hive test driver) net/ ├─ api/ # Actor protocol traits wiring BlockChain ↔ P2P, plus the shared sync-gate thresholds (`sync.rs`)