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`) diff --git a/Cargo.lock b/Cargo.lock index 18bcc9fd6..918ffa025 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2085,8 +2085,11 @@ dependencies = [ "blst", "claims", "ethlambda-metrics", + "ethlambda-telemetry", "ethlambda-types", "hex", + "hkdf", + "hmac", "keccak 0.1.6", "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", "lean_xmss", @@ -2099,6 +2102,7 @@ dependencies = [ "sha3 0.10.9", "thiserror 2.0.21", "tracing", + "unicode-normalization", "zk_alloc", ] @@ -2167,6 +2171,7 @@ dependencies = [ "lru", "rand 0.8.6", "secp256k1 0.30.0", + "serde_json", "sha2", "snap", "spawned-concurrency", @@ -2189,6 +2194,7 @@ dependencies = [ "ethlambda-network-api", "ethlambda-state-transition", "ethlambda-storage", + "ethlambda-telemetry", "ethlambda-test-fixtures", "ethlambda-types", "ethlambda-validator", @@ -2234,6 +2240,7 @@ dependencies = [ "ethlambda-crypto", "ethlambda-metrics", "ethlambda-storage", + "ethlambda-telemetry", "ethlambda-test-fixtures", "ethlambda-types", "foldhash 0.2.0", @@ -2281,13 +2288,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 +2356,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..b43db771d 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.4`). 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..ecf0fb441 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.4 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"); } @@ -2211,6 +2251,9 @@ fn first_config_difference( // row, `persisted` already holds the file's // (`Store::fill_missing_config_keys`). gas_limit_schedule: _, + // Compared below: PR-5879 requires never reusing a database under a + // different `X_COMMITTEE_COUNTS` rotation configuration. + x_committee_counts: _, } = persisted; compare!(preset_base); @@ -2286,6 +2329,7 @@ fn first_config_difference( churn_limit_quotient_gloas, max_per_epoch_activation_churn_limit_gloas, x_max_committee_count_per_slot, + x_committee_counts, consolidation_churn_limit_quotient, max_blobs_per_block_deneb, max_blobs_per_block_electra, diff --git a/bin/ethlambda/src/network/dir.rs b/bin/ethlambda/src/network/dir.rs index 54bb82d65..e4207ca8c 100644 --- a/bin/ethlambda/src/network/dir.rs +++ b/bin/ethlambda/src/network/dir.rs @@ -59,7 +59,7 @@ pub(crate) enum NetworkDirError { CommitteeCap { path: PathBuf, #[source] - source: ethlambda_types::beacon::config::CommitteeCapTooLarge, + source: ethlambda_types::beacon::config::PqCommitteeConfigError, }, // `{fork:?}` rather than `{fork}`: `ForkName` exposes `as_str` and does not // implement `Display`. @@ -120,11 +120,19 @@ impl NetworkDir { let fork = parsed.config.fork_at_epoch(0); let genesis_state = BeaconState::from_ssz(fork, &genesis_bytes).map_err(|err| { NetworkDirError::Genesis { - path: genesis_path, + path: genesis_path.clone(), fork, reason: format!("{err:?}"), } })?; + ethlambda_state_transition::beacon::helpers::pq::validate_pq_rotation_genesis( + &parsed.config, + &genesis_state, + ) + .map_err(|source| NetworkDirError::CommitteeCap { + path: config_path.clone(), + source, + })?; let bootnodes = read_bootnodes(base)?; diff --git a/bin/ethlambda/src/network/mod.rs b/bin/ethlambda/src/network/mod.rs index 4f0b2c635..f4b7e4fca 100644 --- a/bin/ethlambda/src/network/mod.rs +++ b/bin/ethlambda/src/network/mod.rs @@ -11,9 +11,7 @@ pub(crate) mod dir; use std::path::PathBuf; -use ethlambda_types::beacon::config::{ - CommitteeCapTooLarge, Config, select_x_max_committee_count_per_slot, -}; +use ethlambda_types::beacon::config::{Config, PqCommitteeConfigError, select_pq_committee_config}; use self::config_file::ConfigFile; use ethlambda_types::beacon::preset::{Preset, PresetAlreadyActive}; @@ -125,12 +123,12 @@ pub(crate) fn select_preset(declared: &str) -> Result /// - 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> { +pub(crate) fn select_committee_cap(parsed: &mut ConfigFile) -> Result<(), PqCommitteeConfigError> { 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)?; + select_pq_committee_config(&parsed.config)?; Ok(()) } @@ -500,7 +498,13 @@ mod tests { 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)); + assert_eq!( + err, + PqCommitteeConfigError::CapTooLarge { + declared: above, + max: above - 1, + } + ); } #[test] diff --git a/bin/ethlambda/src/pq_keys.rs b/bin/ethlambda/src/pq_keys.rs index 2d71cc904..b4dcf1f95 100644 --- a/bin/ethlambda/src/pq_keys.rs +++ b/bin/ethlambda/src/pq_keys.rs @@ -1,32 +1,19 @@ -//! PQ genesis key material (`ethlambda pq-keys`). +//! PQ genesis key material (`ethlambda pq-keys`, ERC-8517). //! //! A network on consensus-specs' `pq` fork registers, for every genesis //! validator, a leanXMSS public key and the root of a VRF tree over all -//! `2^31` slots. The root costs the whole tree (minutes of every core per -//! validator, see `ethlambda_crypto::vrf`), so genesis tooling reads them -//! from precomputed files rather than deriving them at genesis time. This -//! writes those files for a mnemonic's validators, in the two formats -//! ethPandaOps' tooling reads: +//! `2^31` slots. On `pq-devnet-2` and later, both derive from each account's +//! ERC-8517 account seed at `m/5326/3600///` +//! (`ethlambda_crypto::pq_keys`), binding every key file to one mnemonic, +//! network `chain_id`, and role. //! -//! - `.bin`, 64 bytes per validator index (the leanXMSS key, then the -//! VRF root), which eth-beacon-genesis reads through `--xmss-pubkey-cache` -//! or `--xmss-pubkey-url` (ethereum-package's `xmss_pubkey_url`), `` -//! being [`genesis_key_file_name`] of the mnemonic; -//! - `.vrf`, [`STATE_RECORD_SIZE`] bytes per index (the root, then -//! leaf 0's branch), which validator clients read through -//! ethereum-package's `vrf_state_url` instead of hashing their trees. -//! -//! The keys come from each validator's EIP-2333 signing key at -//! `m/12381/3600//0/0`, as the generator and every PQ client derive -//! them (`ethlambda_crypto::pq_keys`), and the VRF tree is the one the -//! specification defines at this repository's pin. That is the reason to -//! generate them here: the files ethereum-package publishes follow whatever -//! rule its generator implements, and a genesis whose roots follow another -//! rule than the client's fails every proposal. -//! -//! Records are written one validator at a time, at their index's offset, so -//! an interrupted run resumes where it stopped: a validator whose records are -//! present and whose state folds to its root is skipped. +//! Writes: +//! - `.bin`, 64 bytes per index (`xmss_pubkey || vrf_root`, with +//! `vrf_root` all zeros for `--role builder`, which has no VRF tree); +//! - `.vrf`, [`STATE_RECORD_SIZE`] bytes per index (validators only); +//! - `.xmss`, [`XMSS_CACHE_RECORD_SIZE`] bytes per index when +//! `--write-xmss-cache` is passed (top tree plus genesis attestation and +//! per-slot bottom trees). use std::fs::{File, OpenOptions}; use std::os::unix::fs::FileExt as _; @@ -34,9 +21,11 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use ethlambda_crypto::pq_keys::{ - bip39_seed, genesis_key_file_name, signing_key, vrf_seed, xmss_key, + HARDENED_OFFSET, PqRole, account_seed, bip39_seed_with_passphrase, genesis_key_file_name, + seeds_for_role, xmss_key, }; use ethlambda_crypto::vrf::{STATE_RECORD_SIZE, VrfTree}; +use ethlambda_validator::pq::{XMSS_CACHE_RECORD_SIZE, attestation_leaf, slot_leaf}; use eyre::{Context as _, OptionExt as _, bail}; use tracing::info; @@ -45,62 +34,136 @@ const KEY_RECORD_SIZE: usize = 64; #[derive(Debug, clap::Args)] pub(crate) struct PqKeysOptions { - /// The BIP-39 mnemonic the validators' keystores were derived from. + /// The BIP-39 mnemonic to derive ERC-8517 seeds from. #[arg(long, env = "ETHLAMBDA_PQ_KEYS_MNEMONIC", hide_env_values = true)] mnemonic: String, - /// The first validator index to write. + /// Optional BIP-39 passphrase of `--mnemonic`. + #[arg( + long, + default_value = "", + env = "ETHLAMBDA_PQ_KEYS_PASSPHRASE", + hide_env_values = true + )] + passphrase: String, + + /// EIP-155 / `DEPOSIT_CHAIN_ID` of the target network (`1 <= chain_id < 2^31`). + #[arg(long, value_parser = clap::value_parser!(u64).range(1..HARDENED_OFFSET))] + chain_id: u64, + + /// ERC-8517 role (`validator` or `builder`). Builders derive no VRF tree. + #[arg(long, default_value = "validator")] + role: PqRole, + + /// The first account index to write. #[arg(long, default_value_t = 0)] start: u32, - /// How many validators to write, from `--start`. + /// How many accounts to write, starting from `--start`. #[arg(long, value_parser = clap::value_parser!(u32).range(1..))] count: u32, - /// Directory to write `.bin` and `.vrf` into. Created if - /// absent; existing records are kept and skipped. + /// Directory to write `.bin`, `.vrf`, and optional + /// `.xmss` into. Created if absent; existing valid records are kept. #[arg(long)] output_dir: PathBuf, + + /// Override the base file name `` (without extension). Defaults to + /// [`genesis_key_file_name`] of `(mnemonic_seed, chain_id)`. + #[arg(long)] + name: Option, + + /// Also write `.xmss` (`14696` bytes per index: top tree + genesis + /// attestation and slot bottom trees). + #[arg(long, default_value_t = false)] + write_xmss_cache: bool, } pub(crate) fn run(options: PqKeysOptions) -> eyre::Result<()> { - let seed = bip39_seed(&options.mnemonic) - .ok_or_eyre("the mnemonic must be ASCII (BIP-39's NFKD form is not applied)")?; - let name = genesis_key_file_name(&seed); + let end = u64::from(options.start) + .checked_add(u64::from(options.count)) + .ok_or_eyre("--start plus --count overflows")?; + if end > HARDENED_OFFSET { + bail!( + "--start ({}) + --count ({}) exceeds ERC-8517's account bound ({HARDENED_OFFSET})", + options.start, + options.count + ); + } + + let seed = bip39_seed_with_passphrase(&options.mnemonic, &options.passphrase); + let default_name = genesis_key_file_name(&seed, options.chain_id)?; + let name = options.name.as_deref().unwrap_or(&default_name); + if name.is_empty() || name.contains(['/', '\\']) { + bail!("--name must be a non-empty file stem without path separators"); + } + std::fs::create_dir_all(&options.output_dir) .wrap_err_with(|| format!("creating {}", options.output_dir.display()))?; let keys_path = options.output_dir.join(format!("{name}.bin")); - let states_path = options.output_dir.join(format!("{name}.vrf")); let keys = open(&keys_path)?; - let states = open(&states_path)?; + let states_path = options.output_dir.join(format!("{name}.vrf")); + let states = (options.role == PqRole::Validator) + .then(|| open(&states_path)) + .transpose()?; + let cache_path = options.output_dir.join(format!("{name}.xmss")); + let xmss_cache = options + .write_xmss_cache + .then(|| open(&cache_path)) + .transpose()?; + info!( keys = %keys_path.display(), - states = %states_path.display(), + chain_id = options.chain_id, + role = %options.role, start = options.start, count = options.count, - "Writing PQ genesis keys" + write_xmss_cache = options.write_xmss_cache, + "Writing ERC-8517 PQ genesis keys" ); let started = Instant::now(); - let end = options - .start - .checked_add(options.count) - .ok_or_eyre("--start plus --count overflows a validator index")?; - for index in options.start..end { - let sk = signing_key(&seed, index); - let vrf_seed = vrf_seed(&sk); - if let Some(root) = existing(&keys, &states, index, vrf_seed)? { + for index in options.start..(end as u32) { + let acc_seed = account_seed(&seed, options.chain_id, options.role, u64::from(index))?; + let (_, maybe_vrf_seed) = seeds_for_role(&acc_seed, options.role); + if let Some(root) = existing( + &keys, + states.as_ref(), + xmss_cache.as_ref(), + index, + maybe_vrf_seed, + )? { info!(index, root = %hex::encode(root), "Already written"); continue; } + let key_started = Instant::now(); - let xmss_pubkey = xmss_key(&sk).public_key().to_bytes(); - let tree = VrfTree::build(vrf_seed); - let root = tree.root(); + let xmss = xmss_key(&acc_seed); + let xmss_pubkey = xmss.public_key().to_bytes(); + if let Some(cache_file) = &xmss_cache { + xmss.prepare(attestation_leaf(0) as u32); + xmss.prepare(slot_leaf(0, 0) as u32); + let cache_bytes = xmss.cache_to_bytes(); + write_at( + cache_file, + &cache_bytes, + index, + XMSS_CACHE_RECORD_SIZE, + &cache_path, + )?; + } + + let root = match (maybe_vrf_seed, states.as_ref()) { + (Some(vrf_seed), Some(states_file)) => { + let tree = VrfTree::build(vrf_seed); + let root = tree.root(); + let state = tree.to_state_record(); + write_at(states_file, &state, index, STATE_RECORD_SIZE, &states_path)?; + root + } + _ => [0u8; 32], + }; - // The state first: a key record is what marks the index done. - let state = tree.to_state_record(); - write_at(&states, &state, index, STATE_RECORD_SIZE, &states_path)?; let mut record = Vec::with_capacity(KEY_RECORD_SIZE); record.extend_from_slice(&xmss_pubkey); record.extend_from_slice(&root); @@ -110,13 +173,13 @@ pub(crate) fn run(options: PqKeysOptions) -> eyre::Result<()> { xmss_pubkey = %hex::encode(xmss_pubkey), vrf_root = %hex::encode(root), elapsed_s = key_started.elapsed().as_secs(), - "Wrote validator" + "Wrote account" ); } info!( count = options.count, elapsed_s = started.elapsed().as_secs(), - "PQ genesis keys written" + "ERC-8517 PQ genesis keys written" ); Ok(()) } @@ -131,33 +194,39 @@ fn open(path: &Path) -> eyre::Result { .wrap_err_with(|| format!("opening {}", path.display())) } -/// The root of `index`'s records when both are written and its state folds -/// this seed's leaf 0 to the root its key record names; `None` when it is to -/// be (re)written. fn existing( keys: &File, - states: &File, + states: Option<&File>, + xmss_cache: Option<&File>, index: u32, - vrf_seed: [u8; 32], + vrf_seed: Option<[u8; 32]>, ) -> eyre::Result> { let Some(key_record) = read_at(keys, index, KEY_RECORD_SIZE)? else { return Ok(None); }; - let Some(state) = read_at(states, index, STATE_RECORD_SIZE)? else { - return Ok(None); - }; - let Ok(tree) = VrfTree::from_state_record(vrf_seed, &state) else { - return Ok(None); - }; - let root = tree.root(); - if key_record[32..] != root { + if let Some(cache_file) = xmss_cache + && read_at(cache_file, index, XMSS_CACHE_RECORD_SIZE)?.is_none() + { return Ok(None); } - Ok(Some(root)) + match (vrf_seed, states) { + (Some(vrf_seed), Some(states_file)) => { + let Some(state) = read_at(states_file, index, STATE_RECORD_SIZE)? else { + return Ok(None); + }; + let Ok(tree) = VrfTree::from_state_record(vrf_seed, &state) else { + return Ok(None); + }; + let root = tree.root(); + if key_record[32..] != root { + return Ok(None); + } + Ok(Some(root)) + } + _ => Ok(Some(key_record[32..].try_into().expect("32 bytes"))), + } } -/// The record at `index`, or `None` when the file does not reach it or it -/// is all zeros (an index skipped by an earlier, later-starting run). fn read_at(file: &File, index: u32, size: usize) -> eyre::Result>> { let offset = u64::from(index) * size as u64; if file.metadata()?.len() < offset + size as u64 { @@ -177,5 +246,65 @@ fn write_at(file: &File, record: &[u8], index: u32, size: usize, path: &Path) -> } file.write_all_at(record, u64::from(index) * size as u64) .and_then(|()| file.sync_data()) - .wrap_err_with(|| format!("writing validator {index} to {}", path.display())) + .wrap_err_with(|| format!("writing account {index} to {}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser as _; + + #[derive(clap::Parser)] + struct Cli { + #[command(flatten)] + options: PqKeysOptions, + } + + #[test] + fn requires_valid_chain_id_and_accepts_role() { + assert!( + Cli::try_parse_from([ + "pq-keys", + "--mnemonic", + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + "--count", + "1", + "--output-dir", + "/tmp/out", + ]) + .is_err(), + "--chain-id is required" + ); + assert!( + Cli::try_parse_from([ + "pq-keys", + "--mnemonic", + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + "--chain-id", + "0", + "--count", + "1", + "--output-dir", + "/tmp/out", + ]) + .is_err(), + "chain_id 0 is refused" + ); + let parsed = Cli::try_parse_from([ + "pq-keys", + "--mnemonic", + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + "--chain-id", + "3151908", + "--role", + "builder", + "--count", + "2", + "--output-dir", + "/tmp/out", + ]) + .expect("valid pq-keys args"); + assert_eq!(parsed.options.chain_id, 3_151_908); + assert_eq!(parsed.options.role, PqRole::Builder); + } } diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index b1b0b8a42..9c96640ef 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -5,9 +5,10 @@ use std::path::PathBuf; +use ethlambda_crypto::pq_keys::PqRole; use ethlambda_types::beacon::primitives::{Bytes32, ExecutionAddress, H160}; use ethlambda_validator::proposer_settings::{GRAFFITI_BYTES, graffiti_from_text}; -use ethlambda_validator::{BuilderProposals, ValidatorConfig}; +use ethlambda_validator::{BuilderProposals, PqMnemonicConfig, ValidatorConfig}; use eyre::WrapErr as _; use crate::shutdown::ShutdownSignals; @@ -32,9 +33,11 @@ pub(crate) struct ValidatorOptions { #[arg(long)] pub(crate) validators_dir: PathBuf, - /// Directory holding one password file per keystore. + /// Directory holding one password file per keystore. Defaults to + /// `/secrets` when omitted (e.g. when PQ seeds come from + /// `--pq-mnemonic` or `--pq-seeds-file`). #[arg(long)] - pub(crate) secrets_dir: PathBuf, + pub(crate) secrets_dir: Option, /// Bind address for the metrics and keymanager servers. #[arg(long, default_value = "127.0.0.1")] @@ -211,6 +214,69 @@ 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, + + /// BIP-39 mnemonic to derive ERC-8517 post-quantum account seeds from on + /// a PQ network (`m/5326/3600///`). Requires + /// `--pq-account-max`. + #[arg( + long, + env = "ETHLAMBDA_PQ_MNEMONIC", + hide_env_values = true, + requires = "pq_account_max" + )] + pub(crate) pq_mnemonic: Option, + + /// Optional BIP-39 passphrase for `--pq-mnemonic`. + #[arg( + long, + default_value = "", + env = "ETHLAMBDA_PQ_PASSPHRASE", + hide_env_values = true, + requires = "pq_mnemonic" + )] + pub(crate) pq_passphrase: String, + + /// Explicit ERC-8517 `chain_id` (`1 <= chain_id < 2^31`) for + /// `--pq-mnemonic`. Defaults to the beacon node's `DEPOSIT_CHAIN_ID`. + #[arg( + long, + requires = "pq_mnemonic", + value_parser = clap::value_parser!(u64).range(1..(1 << 31)) + )] + pub(crate) pq_chain_id: Option, + + /// ERC-8517 role for `--pq-mnemonic`: `validator` (`0`) or `builder` (`1`). + #[arg(long, default_value = "validator", requires = "pq_mnemonic")] + pub(crate) pq_role: PqRole, + + /// Minimum ERC-8517 account index (inclusive) for `--pq-mnemonic`. + #[arg( + long, + default_value_t = 0, + requires = "pq_mnemonic", + value_parser = clap::value_parser!(u64).range(0..(1 << 31)) + )] + pub(crate) pq_account_min: u64, + + /// Maximum ERC-8517 account index (exclusive) for `--pq-mnemonic`. + #[arg( + long, + requires = "pq_mnemonic", + value_parser = clap::value_parser!(u64).range(0..=(1 << 31)) + )] + pub(crate) pq_account_max: Option, + + /// File of ERC-8517 post-quantum account seeds (`eth2-val-tools pq-seeds` + /// JSON lines / JSON list, or one `0x`-prefixed 32-byte hex seed per line). + #[arg(long)] + pub(crate) pq_seeds_file: Option, + + /// Comma-separated telemetry event families to export over OTLP Logs + /// (`pq` in `eth.telemetry/0.4`). 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 { @@ -313,12 +379,34 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { signals.force_exit_on_repeats(); signal }; + let pq_mnemonic = match (&options.pq_mnemonic, options.pq_account_max) { + (Some(mnemonic), Some(account_max)) => { + if options.pq_account_min > account_max { + eyre::bail!( + "--pq-account-min ({}) must not exceed --pq-account-max ({account_max})", + options.pq_account_min + ); + } + Some(PqMnemonicConfig::new( + mnemonic.clone(), + options.pq_passphrase, + options.pq_chain_id, + options.pq_role, + options.pq_account_min, + account_max, + )) + } + _ => None, + }; + let secrets_dir = options + .secrets_dir + .unwrap_or_else(|| options.validators_dir.join("secrets")); let config = ValidatorConfig { beacon_nodes: options.beacon_nodes, graffiti, suggested_fee_recipient, validators_dir: options.validators_dir, - secrets_dir: options.secrets_dir, + secrets_dir, metrics: std::net::SocketAddr::new(options.http_address, options.metrics_port), keymanager: options .enable_keymanager @@ -332,6 +420,10 @@ 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, + pq_mnemonic, + pq_seeds_file: options.pq_seeds_file, + telemetry_events: options.telemetry_events, + client_commit: crate::version::GIT_COMMIT.to_string(), }; ethlambda_validator::run(config, stop) .await @@ -346,7 +438,7 @@ mod tests { ValidatorOptions { beacon_nodes: vec!["http://localhost:5052".to_string()], validators_dir: PathBuf::from("/tmp/validators"), - secrets_dir: PathBuf::from("/tmp/secrets"), + secrets_dir: Some(PathBuf::from("/tmp/secrets")), http_address: "127.0.0.1".parse().expect("valid address"), keymanager_port: 5062, metrics_port: 5064, @@ -364,6 +456,14 @@ mod tests { vrf_state_url: None, xmss_cache_url: None, disable_event_stream: false, + pq_mnemonic: None, + pq_passphrase: String::new(), + pq_chain_id: None, + pq_role: PqRole::Validator, + pq_account_min: 0, + pq_account_max: None, + pq_seeds_file: None, + telemetry_events: None, } } @@ -604,4 +704,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/blockchain/state_transition/src/beacon/helpers/accessors.rs b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs index d11f8431c..2785da5c3 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs @@ -158,17 +158,36 @@ pub fn max_committees_per_slot(fork: ForkName) -> u64 { } } -/// [`committee_count_per_slot`] under `fork`'s cap. +/// [`committee_count_per_slot`] under `fork`'s static cap. pub fn committee_count_per_slot_for(fork: ForkName, active_count: u64) -> u64 { let ideal = active_count / preset::slots_per_epoch() / preset::target_committee_size(); ideal.clamp(1, max_committees_per_slot(fork)) } +/// Committee count per slot for `epoch` on `fork` (PR-5879): when `fork` is +/// [`ForkName::Pq`] and `X_COMMITTEE_COUNTS` rotation is enabled, returns the +/// stage entry `X_COMMITTEE_COUNTS[(epoch / 8) % len]`; otherwise uses the +/// static cap rule. +pub fn committee_count_per_slot_at_epoch(fork: ForkName, epoch: Epoch, active_count: u64) -> u64 { + if fork == ForkName::Pq + && let Some(rotated) = ethlambda_types::beacon::config::x_committee_count_at_epoch(epoch) + { + return rotated; + } + committee_count_per_slot_for(fork, active_count) +} + /// How many committees each slot of `epoch` has. /// /// At least one, so a small chain still produces committees, and at most -/// `MAX_COMMITTEES_PER_SLOT` (`MAX_COMMITTEES_PER_SLOT_PQ` on a PQ state). +/// `MAX_COMMITTEES_PER_SLOT` (`X_COMMITTEE_COUNTS` stage or +/// `X_MAX_COMMITTEE_COUNT_PER_SLOT` on a PQ state). pub fn get_committee_count_per_slot(state: &BeaconState, epoch: Epoch) -> u64 { + if state.fork_name() == ForkName::Pq + && let Some(rotated) = ethlambda_types::beacon::config::x_committee_count_at_epoch(epoch) + { + return rotated; + } committee_count_per_slot_for( state.fork_name(), get_active_validator_indices(state, epoch).len() as u64, @@ -215,7 +234,7 @@ pub fn get_committee_count_per_slot(state: &BeaconState, epoch: Epoch) -> u64 { pub fn build_epoch_committees(state: &BeaconState, epoch: Epoch) -> EpochCommittees { let active_indices = get_active_validator_indices(state, epoch); let committees_per_slot = - committee_count_per_slot_for(state.fork_name(), active_indices.len() as u64); + committee_count_per_slot_at_epoch(state.fork_name(), epoch, active_indices.len() as u64); let seed = get_seed(state, epoch, constants::DOMAIN_BEACON_ATTESTER); // The active set's own buffer becomes the shuffled set, so a build holds // one validator-sized list at a time, not a permutation and a gathered @@ -267,10 +286,17 @@ fn shuffling_key(state: &BeaconState, epoch: Epoch) -> Option { // see this function's documentation for why that is sound. let decision_slot = compute_start_slot_at_epoch(epoch.saturating_sub(1)).saturating_sub(1); let decision_root = get_block_root_at_slot(state, decision_slot).ok()?; + let fork = state.fork_name(); + let max_committees_per_slot = if fork == ForkName::Pq { + ethlambda_types::beacon::config::x_committee_count_at_epoch(epoch) + .unwrap_or_else(|| max_committees_per_slot(fork)) + } else { + max_committees_per_slot(fork) + }; Some(ShufflingKey { epoch, decision_root, - max_committees_per_slot: max_committees_per_slot(state.fork_name()), + max_committees_per_slot, }) } @@ -683,7 +709,7 @@ pub fn get_beacon_committee( let epoch = compute_epoch_at_slot(slot); let active_indices = get_active_validator_indices(state, epoch); let committees_per_slot = - committee_count_per_slot_for(state.fork_name(), active_indices.len() as u64); + committee_count_per_slot_at_epoch(state.fork_name(), epoch, active_indices.len() as u64); compute_committee( &active_indices, get_seed(state, epoch, constants::DOMAIN_BEACON_ATTESTER), diff --git a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index af6f25a23..2c620a99f 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs @@ -324,6 +324,54 @@ pub fn initialize_aggregation_committee_window( .expect("one empty epoch and MIN_SEED_LOOKAHEAD + 1 computed ones fill the window")) } +/// Setup-only validation of an `X_COMMITTEE_COUNTS` experiment genesis state +/// against `config` (consensus-specs PR-5879). +pub fn validate_pq_rotation_genesis( + config: ðlambda_types::beacon::config::Config, + state: &BeaconState, +) -> std::result::Result<(), ethlambda_types::beacon::config::PqCommitteeConfigError> { + use ethlambda_types::beacon::config::PqCommitteeConfigError; + + let cap = ethlambda_types::beacon::config::select_pq_committee_config(config)?; + if config.x_committee_counts.is_empty() { + return Ok(()); + } + let BeaconState::Pq(inner) = state else { + return Err(PqCommitteeConfigError::GenesisNotPq); + }; + if state.slot() != 0 { + return Err(PqCommitteeConfigError::GenesisNotPq); + } + let active = + crate::beacon::helpers::accessors::get_active_validator_indices(state, 0).len() as u64; + let ordinary = + (active / preset::slots_per_epoch() / preset::target_committee_size()).clamp(1, cap); + let max_per_committee = preset::MAX_VALIDATORS_PER_COMMITTEE as u64; + for &count in config.x_committee_counts.entries() { + let Some(committees) = preset::slots_per_epoch().checked_mul(count) else { + return Err(PqCommitteeConfigError::InfeasibleStage { + count, + active_validators: active, + }); + }; + if count > ordinary + || active < committees + || active.div_ceil(committees) > max_per_committee + { + return Err(PqCommitteeConfigError::InfeasibleStage { + count, + active_validators: active, + }); + } + } + let expected_window = initialize_aggregation_committee_window(state) + .map_err(|_| PqCommitteeConfigError::GenesisWindowMismatch)?; + if inner.aggregation_committee_window != expected_window { + return Err(PqCommitteeConfigError::GenesisWindowMismatch); + } + Ok(()) +} + // --------------------------------------------------------------------------- // Attestations // --------------------------------------------------------------------------- @@ -670,4 +718,57 @@ mod tests { assert_eq!(min_attestation_inclusion_delay(&pq), 2); assert_eq!(min_attestation_inclusion_delay(&gloas), 1); } + + #[test] + fn rotating_committee_geometry_rotates_every_eight_epochs_and_validates_genesis() { + use crate::beacon::helpers::accessors::{ + build_epoch_committees, get_beacon_committee, get_committee_count_per_slot, + }; + use ethlambda_types::beacon::config::{ + CommitteeCounts, Config, PqCommitteeConfigError, set_x_committee_counts_for_test, + }; + + let spe = preset::slots_per_epoch(); + let target = preset::target_committee_size(); + // 2 * spe * target active validators gives ordinary count = 2, allowing stages [2, 1]. + let n = (2 * spe * target) as usize; + let mut state = crate::beacon::helpers::test_state::with_validators_at(ForkName::Pq, n); + + let mut config = Config::active(); + config.pq_fork_epoch = 0; + config.x_committee_counts = CommitteeCounts::try_new(vec![2, 1]).unwrap(); + set_x_committee_counts_for_test(&[2, 1]); + + if let BeaconState::Pq(inner) = &mut state { + inner.slot = 0; + } + let window = initialize_aggregation_committee_window(&state).unwrap(); + if let BeaconState::Pq(inner) = &mut state { + inner.aggregation_committee_window = window; + } + validate_pq_rotation_genesis(&config, &state).expect("valid rotating genesis"); + + for (epoch, expected) in [(0, 2), (7, 2), (8, 1), (15, 1), (16, 2)] { + assert_eq!(get_committee_count_per_slot(&state, epoch), expected); + let epoch_committees = build_epoch_committees(&state, epoch); + assert_eq!(epoch_committees.committees_per_slot(), expected); + let slot = compute_start_slot_at_epoch(epoch); + for idx in 0..expected { + assert_eq!( + epoch_committees.committee(slot, idx).unwrap(), + get_beacon_committee(&state, slot, idx).unwrap().as_slice() + ); + } + } + + // Stage [4] exceeds ordinary count 2 for this validator count -> refused. + let mut infeasible = config.clone(); + infeasible.x_committee_counts = CommitteeCounts::try_new(vec![4]).unwrap(); + assert!(matches!( + validate_pq_rotation_genesis(&infeasible, &state), + Err(PqCommitteeConfigError::InfeasibleStage { count: 4, .. }) + )); + + set_x_committee_counts_for_test(&[]); + } } 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 d49eb9696..0c722994c 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs @@ -50,6 +50,22 @@ pub fn process_epoch(state: &mut BeaconState, config: &Config) -> Result<()> { process_aggregation_committee_window(state)?; // [New in PQ:EIP8205] process_preregistration_expiry(state)?; + if ethlambda_types::beacon::config::x_committee_counts_enabled() { + let current = get_current_epoch(state); + let now_active = + crate::beacon::helpers::accessors::get_active_validator_indices(state, current).len(); + let next_active = + crate::beacon::helpers::accessors::get_active_validator_indices(state, current + 1) + .len(); + if now_active != next_active { + tracing::warn!( + next_epoch = current + 1, + previous_active_validators = now_active, + active_validators = next_active, + "PQ rotating geometry active validator set changed; configured schedule stays unchanged, measurements are outside the fixed-size experiment" + ); + } + } Ok(()) } diff --git a/crates/common/crypto/Cargo.toml b/crates/common/crypto/Cargo.toml index 54c0d612c..b1fb14c6d 100644 --- a/crates/common/crypto/Cargo.toml +++ b/crates/common/crypto/Cargo.toml @@ -12,13 +12,17 @@ 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 sha2.workspace = true sha3.workspace = true keccak.workspace = true +hmac.workspace = true +hkdf = "0.12" pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] } +unicode-normalization = "0.1" leanvm.workspace = true leanvm_claims.workspace = true diff --git a/crates/common/crypto/src/pq_keys.rs b/crates/common/crypto/src/pq_keys.rs index 525b25b94..4602d9648 100644 --- a/crates/common/crypto/src/pq_keys.rs +++ b/crates/common/crypto/src/pq_keys.rs @@ -1,99 +1,403 @@ -//! A validator's PQ-fork key material, derived from its BLS signing key the -//! way ethPandaOps' PQ genesis tooling (eth-beacon-genesis) and Lighthouse's -//! PQ branch derive it, so a validator's keystore is all it needs on a -//! network whose genesis that tooling built: +//! Post-quantum validator and builder seed derivation (ERC-8517). //! -//! - the leanXMSS key grows from `sha256("leanxmss-seed" || sk)`; -//! - the VRF seed is `sha256("vrf-seed" || sk)`. +//! On `pq-devnet-2` and later PQ networks, post-quantum secrets derive from a +//! seed (normally a BIP-39 mnemonic's 64-byte seed) through ERC-8517's +//! hardened HMAC-SHA512 tree rather than from a BLS signing key: //! -//! `sk` is the 32-byte big-endian BLS secret key a keystore holds. The -//! specification leaves both seeds to the validator (`pq/validator.md`, -//! "XMSS public key" and "VRF tree"), asking only that they be independent -//! secrets; deriving them from the signing key is the devnet's convention, -//! not the specification's. +//! - Master extended key `(key, chain_code) = HMAC-SHA512("Ethereum PQ seed", seed)`. +//! - Account seed: the `key` at `m/5326/3600///`, +//! every step hardened (`0x00 || key || u32_be(index + 2^31)`). +//! - `xmss_seed = HKDF-Expand-SHA256(account_seed, "leanXMSS key", 32)`. +//! - `vrf_seed = HKDF-Expand-SHA256(account_seed, "VRF key", 32)` (validators +//! only; builders have no VRF tree). //! -//! What grows from the VRF seed is the specification's own: the tree -//! `compute_vrf_root` defines, in [`crate::vrf`]. +//! Out-of-range seeds (`len` outside `16..=64`), `chain_id` outside `[1, 2^31)`, +//! unsupported roles, and child/account indices `>= 2^31` are refused rather +//! than reduced or hashed into range. -use sha2::{Digest, Sha256}; +use std::fmt; +use std::str::FromStr; + +use hkdf::Hkdf; +use hmac::{Hmac, Mac as _}; +use sha2::{Digest, Sha256, Sha512}; +use unicode_normalization::UnicodeNormalization as _; use crate::{lean_xmss, vrf}; -fn sha256_concat(prefix: &[u8], body: &[u8]) -> [u8; 32] { - let mut hasher = Sha256::new(); - hasher.update(prefix); - hasher.update(body); - hasher.finalize().into() +type HmacSha512 = Hmac; + +/// Domain key for the ERC-8517 master node (`"Ethereum PQ seed"`). +pub const MASTER_KEY_DOMAIN: &[u8] = b"Ethereum PQ seed"; + +/// ERC-8517 purpose level (`"lean"` on a phone keypad). +pub const PQ_PURPOSE: u64 = 5326; + +/// Consensus coin type shared with ERC-2334. +pub const COIN_TYPE: u64 = 3600; + +/// Width of an encoded child index in octets. +pub const INDEX_OCTETS: usize = 4; + +/// Hardened child offset (`2^31`). Every valid ERC-8517 index lies below it. +pub const HARDENED_OFFSET: u64 = 1 << 31; + +/// Validator role (`0`): derives both a leanXMSS seed and a VRF seed. +pub const ROLE_VALIDATOR: u64 = 0; + +/// Builder role (`1`): derives a leanXMSS seed only (builders have no VRF tree). +pub const ROLE_BUILDER: u64 = 1; + +/// HKDF-Expand `info` string for the leanXMSS key seed. +pub const XMSS_SEED_INFO: &[u8] = b"leanXMSS key"; + +/// HKDF-Expand `info` string for the VRF tree seed. +pub const VRF_SEED_INFO: &[u8] = b"VRF key"; + +/// Minimum root seed length accepted by ERC-8517 (16 octets). +pub const MIN_SEED_BYTES: usize = 16; + +/// Maximum root seed length accepted by ERC-8517 (64 octets). +pub const MAX_SEED_BYTES: usize = 64; + +/// Role level in an ERC-8517 path (`m/5326/3600///`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PqRole { + Validator, + Builder, } -/// The seed a validator's leanXMSS key grows from. -pub fn xmss_seed(bls_secret_key: &[u8; 32]) -> lean_xmss::Seed { - sha256_concat(b"leanxmss-seed", bls_secret_key) +impl PqRole { + /// Numeric value placed in the derivation path (`0` or `1`). + pub const fn as_u64(self) -> u64 { + match self { + Self::Validator => ROLE_VALIDATOR, + Self::Builder => ROLE_BUILDER, + } + } + + /// Canonical CLI / configuration name (`"validator"` or `"builder"`). + pub const fn as_str(self) -> &'static str { + match self { + Self::Validator => "validator", + Self::Builder => "builder", + } + } } -/// A validator's VRF seed, the specification's `vrf_seed`. -pub fn vrf_seed(bls_secret_key: &[u8; 32]) -> vrf::Node { - sha256_concat(b"vrf-seed", bls_secret_key) +impl TryFrom for PqRole { + type Error = PqSeedError; + + fn try_from(value: u64) -> Result { + match value { + ROLE_VALIDATOR => Ok(Self::Validator), + ROLE_BUILDER => Ok(Self::Builder), + other => Err(PqSeedError::UnsupportedRole(other)), + } + } } -/// A validator's leanXMSS key, grown by leanVM's own `lean_xmss` (bindings -/// v0.15.0), the implementation pq-devnet-0 signs with. Generating it builds -/// the key's whole top tree on the calling thread: about 2.4 s, single-threaded, -/// so a caller with many keys spreads them across cores. -pub fn xmss_key(bls_secret_key: &[u8; 32]) -> leanvm_lean_xmss::LeanXmssExpandedSecretKey { - leanvm_lean_xmss::key_gen(&xmss_seed(bls_secret_key)).0 +impl FromStr for PqRole { + type Err = String; + + fn from_str(s: &str) -> Result { + match s { + "validator" => Ok(Self::Validator), + "builder" => Ok(Self::Builder), + other => Err(format!( + "unknown PQ role {other:?}, expected \"validator\" or \"builder\"" + )), + } + } } -/// The public parameter of a validator's leanXMSS key: the last 16 bytes of -/// its public key, derived from the seed by two hashes, without building a -/// tree. What a validator finds its own registry entry by before it has its -/// key (the root, the other 16 bytes, needs the whole top tree). -pub fn xmss_public_param(bls_secret_key: &[u8; 32]) -> [u8; 16] { - use leanvm_lean_xmss::internals::{public_param, scheme_seed}; - public_param(&scheme_seed(&xmss_seed(bls_secret_key))) +impl fmt::Display for PqRole { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Refusals required by ERC-8517 for out-of-range inputs. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PqSeedError { + #[error("seed must be {MIN_SEED_BYTES} to {MAX_SEED_BYTES} bytes, got {0}")] + SeedLength(usize), + #[error("chain_id {0} is outside [1, {HARDENED_OFFSET})")] + ChainIdOutOfRange(u64), + #[error("unsupported role {0}, expected 0 (validator) or 1 (builder)")] + UnsupportedRole(u64), + #[error("derivation index {0} is outside [0, {HARDENED_OFFSET})")] + IndexOutOfRange(u64), + #[error("invalid ERC-8517 path {path:?}: {reason}")] + InvalidPath { path: String, reason: String }, +} + +/// An ERC-8517 extended key `(key, chain_code)`. +#[derive(Clone, PartialEq, Eq)] +pub struct ExtendedKey { + pub key: [u8; 32], + pub chain_code: [u8; 32], +} + +impl fmt::Debug for ExtendedKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ExtendedKey(..)") + } +} + +/// Parsed ERC-8517 account path `m/5326/3600///`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PqAccountPath { + pub chain_id: u64, + pub role: PqRole, + pub account: u64, +} + +impl PqAccountPath { + /// Construct and validate an ERC-8517 account path. + pub fn new(chain_id: u64, role: PqRole, account: u64) -> Result { + validate_chain_id(chain_id)?; + validate_index(account)?; + Ok(Self { + chain_id, + role, + account, + }) + } + + /// Parse and validate an ERC-8517 account path string. + pub fn parse(path: &str) -> Result { + let bad = |reason: String| PqSeedError::InvalidPath { + path: path.to_string(), + reason, + }; + let parts: Vec<&str> = path.split('/').collect(); + if parts.len() != 6 || parts[0] != "m" { + return Err(bad( + "expected m/5326/3600///".to_string() + )); + } + let parse_seg = |segment: &str, name: &str| -> Result { + if segment.is_empty() + || (segment.len() > 1 && segment.starts_with('0')) + || !segment.bytes().all(|b| b.is_ascii_digit()) + { + return Err(bad(format!("invalid {name} segment {segment:?}"))); + } + segment + .parse::() + .map_err(|_| bad(format!("{name} overflows u64"))) + }; + let purpose = parse_seg(parts[1], "purpose")?; + if purpose != PQ_PURPOSE { + return Err(bad(format!("purpose is {purpose}, expected {PQ_PURPOSE}"))); + } + let coin_type = parse_seg(parts[2], "coin_type")?; + if coin_type != COIN_TYPE { + return Err(bad(format!( + "coin_type is {coin_type}, expected {COIN_TYPE}" + ))); + } + let chain_id = parse_seg(parts[3], "chain_id")?; + let role_raw = parse_seg(parts[4], "role")?; + let account = parse_seg(parts[5], "account")?; + validate_chain_id(chain_id)?; + let role = PqRole::try_from(role_raw)?; + validate_index(account)?; + Ok(Self { + chain_id, + role, + account, + }) + } } -/// The BIP-39 seed of `mnemonic` with no passphrase: PBKDF2-HMAC-SHA512 over -/// 2048 rounds, salted with `"mnemonic"`. What genesis generators and -/// deposit tools derive validator keys from. +impl fmt::Display for PqAccountPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "m/{PQ_PURPOSE}/{COIN_TYPE}/{}/{}/{}", + self.chain_id, + self.role.as_u64(), + self.account + ) + } +} + +fn validate_chain_id(chain_id: u64) -> Result<(), PqSeedError> { + if !(1..HARDENED_OFFSET).contains(&chain_id) { + return Err(PqSeedError::ChainIdOutOfRange(chain_id)); + } + Ok(()) +} + +fn validate_index(index: u64) -> Result<(), PqSeedError> { + if index >= HARDENED_OFFSET { + return Err(PqSeedError::IndexOutOfRange(index)); + } + Ok(()) +} + +fn ext_key_from_hmac(hmac_key: &[u8], data: &[u8]) -> ExtendedKey { + let mut mac = HmacSha512::new_from_slice(hmac_key).expect("HMAC takes any key length"); + mac.update(data); + let digest = mac.finalize().into_bytes(); + let mut key = [0u8; 32]; + let mut chain_code = [0u8; 32]; + key.copy_from_slice(&digest[..32]); + chain_code.copy_from_slice(&digest[32..]); + ExtendedKey { key, chain_code } +} + +/// ERC-8517 master extended key `master(seed)`. +/// +/// Refuses a seed outside `16..=64` bytes. +pub fn master_ext_key(seed: &[u8]) -> Result { + if !(MIN_SEED_BYTES..=MAX_SEED_BYTES).contains(&seed.len()) { + return Err(PqSeedError::SeedLength(seed.len())); + } + Ok(ext_key_from_hmac(MASTER_KEY_DOMAIN, seed)) +} + +/// Hardened child extended key `child((key, chain_code), index)` for +/// `0 <= index < 2^31`. +pub fn child_ext_key(parent: &ExtendedKey, index: u64) -> Result { + validate_index(index)?; + let hardened = u32::try_from(index + HARDENED_OFFSET).expect("index < 2^31 fits u32"); + let mut data = [0u8; 1 + 32 + INDEX_OCTETS]; + data[0] = 0x00; + data[1..33].copy_from_slice(&parent.key); + data[33..].copy_from_slice(&hardened.to_be_bytes()); + Ok(ext_key_from_hmac(&parent.chain_code, &data)) +} + +/// Format and validate an ERC-8517 account path +/// `m/5326/3600///`. +pub fn account_path(chain_id: u64, role: PqRole, account: u64) -> Result { + Ok(PqAccountPath::new(chain_id, role, account)?.to_string()) +} + +/// Derive the 32-byte ERC-8517 account seed at +/// `m/5326/3600///`. +pub fn account_seed( + seed: &[u8], + chain_id: u64, + role: PqRole, + account: u64, +) -> Result<[u8; 32], PqSeedError> { + validate_chain_id(chain_id)?; + validate_index(account)?; + let mut node = master_ext_key(seed)?; + for step in [PQ_PURPOSE, COIN_TYPE, chain_id, role.as_u64(), account] { + node = child_ext_key(&node, step)?; + } + Ok(node.key) +} + +/// Derive an account seed taking a raw numeric role, refusing unsupported +/// role values (`role > 1`). +pub fn account_seed_for_role( + seed: &[u8], + chain_id: u64, + role: u64, + account: u64, +) -> Result<[u8; 32], PqSeedError> { + account_seed(seed, chain_id, PqRole::try_from(role)?, account) +} + +fn hkdf_expand_32(account_seed: &[u8; 32], info: &[u8]) -> [u8; 32] { + let hkdf = Hkdf::::from_prk(account_seed).expect("32-byte PRK is valid for SHA-256"); + let mut out = [0u8; 32]; + hkdf.expand(info, &mut out) + .expect("32-byte output fits HKDF-SHA256"); + out +} + +/// Expand the leanXMSS signing key seed from an ERC-8517 `account_seed`: +/// `HKDF-Expand(account_seed, "leanXMSS key", 32)`. +pub fn xmss_seed(account_seed: &[u8; 32]) -> lean_xmss::Seed { + hkdf_expand_32(account_seed, XMSS_SEED_INFO) +} + +/// Expand a validator's VRF seed from an ERC-8517 `account_seed`: +/// `HKDF-Expand(account_seed, "VRF key", 32)`. /// -/// BIP-39 normalizes the mnemonic to NFKD first, which leaves ASCII as it is: -/// a mnemonic with any other character is refused rather than hashed -/// unnormalized into a different seed. -pub fn bip39_seed(mnemonic: &str) -> Option<[u8; 64]> { - if !mnemonic.is_ascii() { - return None; - } - let words: Vec<&str> = mnemonic.split_whitespace().collect(); +/// Builders have no VRF tree and do not derive a VRF seed. +pub fn vrf_seed(account_seed: &[u8; 32]) -> vrf::Node { + hkdf_expand_32(account_seed, VRF_SEED_INFO) +} + +/// Expand the seed(s) appropriate to `role`: `(xmss_seed, Some(vrf_seed))` for +/// a validator, `(xmss_seed, None)` for a builder. +pub fn seeds_for_role( + account_seed: &[u8; 32], + role: PqRole, +) -> (lean_xmss::Seed, Option) { + let xmss = xmss_seed(account_seed); + let vrf = match role { + PqRole::Validator => Some(vrf_seed(account_seed)), + PqRole::Builder => None, + }; + (xmss, vrf) +} + +/// Generate a validator's or builder's leanXMSS key from its `account_seed`. +/// +/// Builds the key's whole top tree on the calling thread (~2.4 s +/// single-threaded); a caller with many keys spreads them across cores. +pub fn xmss_key(account_seed: &[u8; 32]) -> leanvm_lean_xmss::LeanXmssExpandedSecretKey { + leanvm_lean_xmss::key_gen(&xmss_seed(account_seed)).0 +} + +/// The public parameter of an account's leanXMSS key: the last 16 bytes of +/// its 32-byte public key, derived from `account_seed` in microseconds without +/// building a tree. +pub fn xmss_public_param(account_seed: &[u8; 32]) -> [u8; 16] { + use leanvm_lean_xmss::internals::{public_param, scheme_seed}; + public_param(&scheme_seed(&xmss_seed(account_seed))) +} + +/// The 64-byte BIP-39 seed of `mnemonic` with `passphrase`: PBKDF2-HMAC-SHA512 +/// over 2048 iterations, password NFKD-normalized `mnemonic` (whitespace +/// collapsed to single ASCII spaces), salt `"mnemonic"` followed by +/// NFKD-normalized `passphrase`. +pub fn bip39_seed_with_passphrase(mnemonic: &str, passphrase: &str) -> [u8; 64] { + let normalized_mnemonic: String = mnemonic.nfkd().collect(); + let words: Vec<&str> = normalized_mnemonic.split_whitespace().collect(); + let password = words.join(" "); + + let normalized_passphrase: String = passphrase.nfkd().collect(); + let mut salt = String::with_capacity("mnemonic".len() + normalized_passphrase.len()); + salt.push_str("mnemonic"); + salt.push_str(&normalized_passphrase); + let mut seed = [0u8; 64]; - pbkdf2::pbkdf2_hmac::(words.join(" ").as_bytes(), b"mnemonic", 2048, &mut seed); - Some(seed) -} - -/// The name ethPandaOps' genesis generator (eth-beacon-genesis, `pq` branch -/// from `ff42fce0`) gives the file of a mnemonic's leanXMSS keys and VRF -/// roots, without its `.bin` extension: the first 8 bytes of -/// `sha256("leanxmss-full-keccak-vrf-keys" || seed)`, in hex. Its -/// `--xmss-pubkey-cache` directory and `--xmss-pubkey-url` both name the file -/// this way. The domain is the generator's, and changes with its VRF rule. -pub fn genesis_key_file_name(seed: &[u8; 64]) -> String { - let digest = sha256_concat(b"leanxmss-full-keccak-vrf-keys", seed); - digest[..8] - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() + pbkdf2::pbkdf2_hmac::(password.as_bytes(), salt.as_bytes(), 2048, &mut seed); + seed } -/// The signing key of validator `index` under `seed`: EIP-2333's key at -/// EIP-2334's path `m/12381/3600//0/0`, as 32 big-endian bytes (what a -/// keystore holds, and what [`xmss_seed`] and [`vrf_seed`] take). -pub fn signing_key(seed: &[u8; 64], index: u32) -> [u8; 32] { - let master = blst::min_pk::SecretKey::derive_master_eip2333(seed) - .expect("a 64-byte seed is long enough for EIP-2333"); - [12381, 3600, index, 0, 0] - .into_iter() - .fold(master, |key, child| key.derive_child_eip2333(child)) - .to_bytes() +/// The 64-byte BIP-39 seed of `mnemonic` with an empty passphrase. +pub fn bip39_seed(mnemonic: &str) -> [u8; 64] { + bip39_seed_with_passphrase(mnemonic, "") +} + +/// Network-scoped fingerprint naming a mnemonic's precomputed `.bin` / `.vrf` +/// key files on `chain_id`, without extension: the first 8 bytes of +/// `sha256("leanxmss-erc8517-keys" || chain_id_be8 || seed)` in hex. +/// +/// Including `chain_id` ensures two networks never share a precomputed key +/// file name for the same mnemonic. +pub fn genesis_key_file_name(seed: &[u8; 64], chain_id: u64) -> Result { + validate_chain_id(chain_id)?; + let mut hasher = Sha256::new(); + hasher.update(b"leanxmss-erc8517-keys"); + hasher.update(chain_id.to_be_bytes()); + hasher.update(seed); + let digest = hasher.finalize(); + Ok(digest[..8] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) } #[cfg(test)] @@ -107,51 +411,262 @@ mod tests { .unwrap() } - /// Validator 0 of ethereum-package's default mnemonic. The digests are - /// `hashlib`'s for the two tagged preimages. + const ERC_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + const KURTOSIS_MNEMONIC: &str = "giant issue aisle success illegal bike spike question tent \ + bar rely arctic volcano long crawl hungry vocal artwork \ + sniff fantasy very lucky have athlete"; + + /// Reproduces all five ERC-8517 test vectors, including master extended + /// keys, builder role (no VRF seed), Hoodi chain ID, and the largest + /// admissible chain ID and account (`2^31 - 1`). #[test] - fn seeds_are_tagged_hashes_of_the_signing_key() { - let sk = hex32("0dce41fa73ae9f6bdfd51df4d422d75eee174553dba5fd450c4437e4ed3fc903"); + fn erc8517_test_vectors() { + let seed = bip39_seed_with_passphrase(ERC_MNEMONIC, "TREZOR"); assert_eq!( - vrf_seed(&sk), - hex32("543fc5a4d86e79a434e9741770f7ee17c25bdc31be8d61436d7f9836538b03df") + hex::encode(seed), + "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e5349553\ + 1f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" ); + let master = master_ext_key(&seed).unwrap(); assert_eq!( - xmss_seed(&sk), - hex32("6d78e7072bfcbde1a75261f6e16772ea352de90462819cdc53e05f10d4700ad1") + master.key, + hex32("677bd6e9a2326115c3ab6bba3b781135e055220703b4049b3a68f3b44e3bc6ce") + ); + assert_eq!( + master.chain_code, + hex32("608452b43eb5cffb4c40cad053235bd7daae1dcab03c53ccdfea69a7e92982ce") + ); + + // Test Case 0: Mainnet, validator, account 0. + assert_eq!( + account_path(1, PqRole::Validator, 0).unwrap(), + "m/5326/3600/1/0/0" + ); + let acc0 = account_seed(&seed, 1, PqRole::Validator, 0).unwrap(); + assert_eq!( + acc0, + hex32("78897286a417216b2c8fed7023496767bff03e25ce194c3c8123ab1a93feaed1") + ); + assert_eq!( + xmss_seed(&acc0), + hex32("aa81fb7ad2abaadad451a643181480e0c96b3edbfd71a09aea5fe5032072227e") + ); + assert_eq!( + vrf_seed(&acc0), + hex32("e5048c4e07939596458c5b78ce63143c8ba44d228254ab5d8e8325349d740b42") + ); + + // Test Case 1: Mainnet, validator, account 1. + assert_eq!( + account_path(1, PqRole::Validator, 1).unwrap(), + "m/5326/3600/1/0/1" + ); + let acc1 = account_seed(&seed, 1, PqRole::Validator, 1).unwrap(); + assert_eq!( + acc1, + hex32("6f2f82f43e691d722ec3b2c3c6acd4e27e171089c32147e5b9287d18be9c34c1") + ); + assert_eq!( + xmss_seed(&acc1), + hex32("635f163bd9e56ed4bfd6728a222848d9b165dc239f14addaa92f0831549555bb") + ); + assert_eq!( + vrf_seed(&acc1), + hex32("8d3511f06d95a8e1a6ec04693bb5ad23c6315981472872529f70ef95795f528b") + ); + + // Test Case 2: Mainnet, builder, account 0 (no VRF seed). + assert_eq!( + account_path(1, PqRole::Builder, 0).unwrap(), + "m/5326/3600/1/1/0" + ); + let builder0 = account_seed(&seed, 1, PqRole::Builder, 0).unwrap(); + assert_eq!( + builder0, + hex32("c7e588290de2bacb01c12a2fdab2e5cb7d92d3eaa0ca7dd4964cc5dadc0004c6") + ); + let (builder_xmss, builder_vrf) = seeds_for_role(&builder0, PqRole::Builder); + assert_eq!( + builder_xmss, + hex32("00d635c0a0c0ff0790158dde24c629ccfdf0e91ee5d3d871fc902a470b68c203") + ); + assert!(builder_vrf.is_none()); + + // Test Case 3: Hoodi (chain_id 560048), validator, account 0. + assert_eq!( + account_path(560_048, PqRole::Validator, 0).unwrap(), + "m/5326/3600/560048/0/0" + ); + let hoodi0 = account_seed(&seed, 560_048, PqRole::Validator, 0).unwrap(); + assert_eq!( + hoodi0, + hex32("0c605f1757ec93579bd21b36fc405485831805b12c83f7192a6d8e2e2288f029") + ); + assert_eq!( + xmss_seed(&hoodi0), + hex32("0e3230b57757ab5f11b934431ddf1e487ef36d66bbd334b00aec0e70f95345ea") + ); + assert_eq!( + vrf_seed(&hoodi0), + hex32("170aed89e7a5927d5d51f4879f26c35f20fc09fdc4d921bae4e9decd336b8e53") + ); + + // Test Case 4: 32-byte raw seed, largest chain ID and account (2^31 - 1). + let raw_seed = hex32("3141592653589793238462643383279502884197169399375105820974944592"); + let raw_master = master_ext_key(&raw_seed).unwrap(); + assert_eq!( + raw_master.key, + hex32("4c6871abf495324e1cc4cf7822d24dcfca7e268cd86fb81c79447a3bfe33d433") + ); + assert_eq!( + raw_master.chain_code, + hex32("3f1a9d39e9ecb890cc8f41786055e60eef457d02d00c3f330379057556eb5965") + ); + let max_id = 2_147_483_647; + assert_eq!( + account_path(max_id, PqRole::Validator, max_id).unwrap(), + "m/5326/3600/2147483647/0/2147483647" + ); + let max_acc = account_seed(&raw_seed, max_id, PqRole::Validator, max_id).unwrap(); + assert_eq!( + max_acc, + hex32("467efb6bfc0ee03abf8895395464b3b44600de04dd19d1454ca105ddccc3d0c6") + ); + assert_eq!( + xmss_seed(&max_acc), + hex32("3379ba16de185155bdb07f291453a6bd7892c2ec2bd18ee4133d849a38b29ca6") + ); + assert_eq!( + vrf_seed(&max_acc), + hex32("44c79c2244df1d8e6b4b30393e223681ed1e6f60c8d74640a63dcd7841b49ca6") ); } - /// ethereum-package's default mnemonic derives the signing key the - /// seeds test above starts from, and its genesis tooling's published - /// leanXMSS key for validator 0 (`static_files/xmss-keys`). + /// Reproduces the `pq-devnet-2` spec check values: default ethereum-package + /// mnemonic, empty passphrase, chain ID `3151908`, validator role, accounts + /// `0` and `1` — including full leanXMSS public keys. #[test] - fn the_default_mnemonic_derives_validator_zero() { - let mnemonic = "giant issue aisle success illegal bike spike question tent bar rely \ - arctic volcano long crawl hungry vocal artwork sniff fantasy very lucky \ - have athlete"; - let seed = bip39_seed(mnemonic).unwrap(); - // The package publishes the mnemonic's keys as `b9dec4e1daa17dfe.bin`. - assert_eq!(genesis_key_file_name(&seed), "b9dec4e1daa17dfe"); - let sk = signing_key(&seed, 0); + fn pq_devnet_2_check_values() { + let seed = bip39_seed(KURTOSIS_MNEMONIC); + let chain_id = 3_151_908; + + let acc0 = account_seed(&seed, chain_id, PqRole::Validator, 0).unwrap(); + assert_eq!( + account_path(chain_id, PqRole::Validator, 0).unwrap(), + "m/5326/3600/3151908/0/0" + ); + assert_eq!( + acc0, + hex32("55fbb215782cdb01ef92bcbdea7b437a5515b505513175c63c89155c75204f8e") + ); assert_eq!( - sk, - hex32("0dce41fa73ae9f6bdfd51df4d422d75eee174553dba5fd450c4437e4ed3fc903") + xmss_seed(&acc0), + hex32("b4d657dc50d99079133fae51fcc31fad26ec6b0c015fa5935996a3cebe3f92ce") ); assert_eq!( - xmss_key(&sk).public_key().to_bytes(), - hex32("d7792e263b94cf0b7a9f70d8374c6d34a600b4247057d4079f810caff711c632") + vrf_seed(&acc0), + hex32("8f08bcd86f555c7254b14cb2f9b35afaea02a09eb79e7c60b59d11ec9f5ca9fa") ); - assert!(bip39_seed("caf\u{e9}").is_none()); + let pub0 = hex32("7af1834ab2c0d654f5f7a262e1c7d1422a57718cb03a1a437072a22087d08da1"); + assert_eq!(xmss_public_param(&acc0), pub0[16..]); + assert_eq!(xmss_key(&acc0).public_key().to_bytes(), pub0); + + let acc1 = account_seed(&seed, chain_id, PqRole::Validator, 1).unwrap(); + assert_eq!( + account_path(chain_id, PqRole::Validator, 1).unwrap(), + "m/5326/3600/3151908/0/1" + ); + assert_eq!( + acc1, + hex32("fd3783c0cad0af04cbca453c255fae510bb581569e125798d321be01fb45de13") + ); + assert_eq!( + xmss_seed(&acc1), + hex32("b6903608efa51df64db66792d6000d31fc2d5b95e1f7ed53a8dc203bc1838cb1") + ); + assert_eq!( + vrf_seed(&acc1), + hex32("7982f43ebd688c15a05996ac701abbf8968821a2753ec5d66f30b68971d2292d") + ); + let pub1 = hex32("dbd6d5a5e0ac91de2d96f48d3b0a4811dc549e671386e6854f6d8ca73e912ba4"); + assert_eq!(xmss_public_param(&acc1), pub1[16..]); + assert_eq!(xmss_key(&acc1).public_key().to_bytes(), pub1); } - /// The leanXMSS key of Lighthouse's - /// `pq_ethpandaops_keys_and_vrf_tree_boundaries`. #[test] - fn lighthouse_known_xmss_key() { - let sk = hex32("2892f3ba475c3640a67fe730798ad9c4eed3a6d934db85f91c41cfc837ce8834"); - let public = hex32("155a29b971da2b771fdf52c768af63fa03f78f25487e3e0ed03d012b7039d88b"); - assert_eq!(xmss_key(&sk).public_key().to_bytes(), public); - assert_eq!(xmss_public_param(&sk), public[16..]); + fn refuses_out_of_range_inputs() { + assert_eq!( + master_ext_key(&[0u8; 15]).unwrap_err(), + PqSeedError::SeedLength(15) + ); + assert!(master_ext_key(&[0u8; 16]).is_ok()); + assert!(master_ext_key(&[0u8; 64]).is_ok()); + assert_eq!( + master_ext_key(&[0u8; 65]).unwrap_err(), + PqSeedError::SeedLength(65) + ); + + let seed = [0u8; 32]; + assert_eq!( + account_seed(&seed, 0, PqRole::Validator, 0).unwrap_err(), + PqSeedError::ChainIdOutOfRange(0) + ); + assert_eq!( + account_seed(&seed, HARDENED_OFFSET, PqRole::Validator, 0).unwrap_err(), + PqSeedError::ChainIdOutOfRange(HARDENED_OFFSET) + ); + assert_eq!( + account_seed(&seed, u64::MAX, PqRole::Validator, 0).unwrap_err(), + PqSeedError::ChainIdOutOfRange(u64::MAX) + ); + assert_eq!( + account_seed_for_role(&seed, 1, 2, 0).unwrap_err(), + PqSeedError::UnsupportedRole(2) + ); + assert_eq!( + account_seed(&seed, 1, PqRole::Validator, HARDENED_OFFSET).unwrap_err(), + PqSeedError::IndexOutOfRange(HARDENED_OFFSET) + ); + let master = master_ext_key(&seed).unwrap(); + assert_eq!( + child_ext_key(&master, HARDENED_OFFSET).unwrap_err(), + PqSeedError::IndexOutOfRange(HARDENED_OFFSET) + ); + } + + #[test] + fn parses_and_separates_paths_and_key_file_names_by_chain_id() { + let parsed = PqAccountPath::parse("m/5326/3600/3151908/0/42").unwrap(); + assert_eq!( + parsed, + PqAccountPath { + chain_id: 3_151_908, + role: PqRole::Validator, + account: 42, + } + ); + assert_eq!(parsed.to_string(), "m/5326/3600/3151908/0/42"); + for bad in [ + "", + "m/12381/3600/0/0/0", + "m/5326/3600/0/0/0", + "m/5326/3600/2147483648/0/0", + "m/5326/3600/1/2/0", + "m/5326/3600/1/0/2147483648", + "m/5326/3600/01/0/0", + "m/5326/3600/1/0/0'", + ] { + assert!(PqAccountPath::parse(bad).is_err(), "{bad}"); + } + + let seed = bip39_seed(KURTOSIS_MNEMONIC); + let mainnet_name = genesis_key_file_name(&seed, 1).unwrap(); + let devnet_name = genesis_key_file_name(&seed, 3_151_908).unwrap(); + assert_eq!(mainnet_name.len(), 16); + assert_eq!(devnet_name.len(), 16); + assert_ne!(mainnet_name, devnet_name); + assert!(genesis_key_file_name(&seed, 0).is_err()); + assert!(genesis_key_file_name(&seed, HARDENED_OFFSET).is_err()); } } 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..d040f4bc9 --- /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.4`). + +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.4: 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..f3487ade7 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/gossip.rs @@ -0,0 +1,667 @@ +//! Bounded non-blocking correlation for PQ aggregate gossip receipt, validation, +//! proposal-pool insertion, and publication (`eth.telemetry/0.4`). + +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_published`. 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, + queued: 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, + queued: 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); +} + +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()); + } + receipt.current.queued = 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, + validation: &str, + pool: &str, + stage: &'static str, + reason: &str, + usable: Option, + rejected_admission: bool, + expected: Option<&Reference>, +) { + let Some(recorder) = global() else { return }; + let terminal = 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; + } + if rejected_admission { + attempt.queued = 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 queued_missing = if attempt.started.is_some() && attempt.queued.is_none() { + "not_exposed" + } else { + missing + }; + let mut data = json!({ + "message": { "topic": receipt.topic, "gossip_id": gossip_id }, + "attempt": attempt.reference, + "receipt_attempt": receipt.first, + "queued": point_or_missing(&attempt.queued, queued_missing), + "started": point_or_missing(&attempt.started, missing), + "finished": point_or_missing(&attempt.finished, missing), + "usable": point_or_missing(&usable, if pool == "already_available" { "not_applicable" } else { missing }), + "validation_outcome": validation, + "pool_outcome": pool, + "terminal_stage": stage, + "reason": 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 == "decode" { + data["metadata_status"] = json!("malformed"); + for boundary in ["queued", "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 validation == "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", &terminal, Mode::Production, data); +} + +pub fn decode_failed(gossip_id: &str) { + complete_if( + gossip_id, + "rejected", + "not_applicable", + "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", + "precheck", + reason, + None, + false, + None, + ); +} + +pub fn queue_dropped(gossip_id: &str) { + complete_if( + gossip_id, + "dropped", + "not_applicable", + "queue", + "queue_full", + None, + true, + None, + ); +} + +pub fn validation_failed(gossip_id: &str, outcome: &str, reason: &str) { + complete_if( + gossip_id, + outcome, + "not_applicable", + "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 = if inserted { + "inserted" + } else if outcome == "covered" { + "already_available" + } else { + "not_inserted" + }; + let reason = if inserted { + "none" + } else { + match outcome { + "covered" => "already_covered", + "expired" => "deadline", + "capacity" => "queue_full", + "invalid" => "invalid", + _ => "other", + } + }; + complete_if( + gossip_id, "accepted", pool, "pool", reason, 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", + "queue", + "other", + None, + false, + Some(reference), + ); + } + } +} + +/// Emit `pq.aggregate_published` after gossipsub publish returns. +#[allow(clippy::too_many_arguments)] +pub fn published( + topic: &str, + gossip_id: Option<&str>, + requested: &Point, + returned: &Point, + accepted: bool, + reason: &str, + aggregate: AggregateMetadata, + extra: Value, +) -> Option { + let recorder = global()?; + let publication = recorder.reference(); + 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, + "requested": requested, + "returned": returned, + "outcome": if accepted { "accepted" } else { "failed" }, + "reason": reason, + }); + 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_published", 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..83671ab4d --- /dev/null +++ b/crates/common/telemetry/src/pq_events/mod.rs @@ -0,0 +1,1042 @@ +//! Post-quantum measurement events (`eth.telemetry/0.4`) 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.4"; +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_published", + "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.4; 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.4; 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::P2PServer::publish_beacon_aggregate_pq around gossipsub publish" + } 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" }, + "queued": { "missing": "not_reached" }, + "started": { "process_id": pid, "unix_ns": "1800000007620000000", "mono_ns": "100" }, + "finished": { "process_id": pid, "unix_ns": "1800000007640000000", "mono_ns": "120" }, + "usable": { "missing": "not_reached" }, + "validation_outcome": "rejected", + "pool_outcome": "not_applicable", + "reason": "invalid", + "terminal_stage": "validation", + "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..25dccb414 --- /dev/null +++ b/crates/common/telemetry/src/pq_events/otlp.rs @@ -0,0 +1,1017 @@ +//! OTLP Logs v1 protobuf codec, HTTP/protobuf + gRPC HTTP/2 exporters, and +//! bounded async batch worker (`eth.telemetry/0.4`). +//! +//! 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.4`) +// --------------------------------------------------------------------------- + +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> { + let data = &record.data; + let outcome = match record.event_name.as_str() { + "pq.aggregate_processed" => { + let validation = data["validation_outcome"].as_str().unwrap_or(""); + if matches!( + validation, + "rejected" | "error" | "dropped" | "expired" | "cancelled" + ) { + Some(validation) + } else if data["pool_outcome"] == "error" { + Some("pool_error") + } else { + None + } + } + "pq.aggregate_published" => data["outcome"].as_str().filter(|v| *v == "failed"), + "pq.validation_batch" => data["outcome"] + .as_str() + .filter(|v| matches!(*v, "failed" | "cancelled")), + "pq.operation_completed" => data["outcome"] + .as_str() + .filter(|v| matches!(*v, "failed" | "expired" | "cancelled" | "discarded_late")), + "pq.duty_completed" => data["outcome"] + .as_str() + .filter(|v| matches!(*v, "failed" | "unavailable" | "missed_deadline")), + _ => None, + }?; + Some( + data["reason"] + .as_str() + .filter(|v| *v != "none") + .unwrap_or(outcome), + ) +} + +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: env!("CARGO_PKG_VERSION").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 lr.body.is_some() { + return Err("LogRecord body must be omitted".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 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" => {} + 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}")); + } + out.push(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), + }); + } + } + } + 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..52b31edc1 --- /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.4`). +//! +//! `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..604bf2f8f --- /dev/null +++ b/crates/common/telemetry/src/pq_events/settings.rs @@ -0,0 +1,386 @@ +//! Validated standard OTLP Logs settings (`eth.telemetry/0.4`). +//! +//! 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..8d321e02f --- /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.4`). +//! +//! 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..773a98e23 --- /dev/null +++ b/crates/common/telemetry/tests/pq_lifecycle.rs @@ -0,0 +1,376 @@ +//! End-to-end lifecycle test for `eth.telemetry/0.4` 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; + +#[tokio::test] +async fn full_pq_telemetry_lifecycle_delivers_all_active_event_families_and_health_metrics() { + let collected: Arc>> = Arc::new(Mutex::new(Vec::new())); + let collected_clone = collected.clone(); + + let app = Router::new() + .route( + "/v1/logs", + post( + |State(sink): State>>>, body: Bytes| async move { + let req = otlp::ExportLogsServiceRequest::decode(body.as_ref()).unwrap(); + let recs = otlp::decode_records_request(&req).unwrap(); + sink.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(collected_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()); + { + 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 }), + ); + + // 3. Publish our local committee aggregate and complete the committee duty. + 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, + true, + "none", + meta, + pub_extra, + ) + .expect("publication reference"); + duty::published(10, Some(42), &pub_ref, &req_pt, &ret_pt, true); + + // 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 = 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.4"); + 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(); + } + + // Wire 0.4'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_published", + "pq.duty_completed", + "pq.aggregate_traffic", + ] { + assert!( + recs.iter().any(|r| r.event_name == expected_family), + "missing event family {expected_family}" + ); + } + + // 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/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index 4d053ba82..240e48230 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -317,6 +317,186 @@ impl libssz::SszDecode for GasLimitSchedule { } } +/// Maximum entries in [`CommitteeCounts`] (`X_COMMITTEE_COUNTS`, PR-5879). +/// Every entry is a distinct positive `u64` power of two, so at most 64 can +/// ever exist. +pub const MAX_COMMITTEE_COUNTS_ENTRIES: usize = 64; + +/// Epochs each stage of `X_COMMITTEE_COUNTS` holds before advancing (PR-5879). +pub const PQ_ROTATION_EPOCHS_PER_STAGE: u64 = 8; + +type CommitteeCountsRow = SszList; + +/// Experimental PQ rotating committee schedule (`X_COMMITTEE_COUNTS`, PR-5879). +/// +/// Preserves exact entry order (never sorted, clamped, or filtered). Empty `[]` +/// disables rotation and uses the static `X_MAX_COMMITTEE_COUNT_PER_SLOT` cap. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CommitteeCounts(Vec); + +impl CommitteeCounts { + pub fn entries(&self) -> &[u64] { + &self.0 + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + /// Committee count per slot at `epoch` (`X_COMMITTEE_COUNTS[(epoch / 8) % len]`), + /// or `None` when rotation is disabled (`[]`). + pub fn count_at(&self, epoch: Epoch) -> Option { + if self.0.is_empty() { + return None; + } + let stage = ((epoch / PQ_ROTATION_EPOCHS_PER_STAGE) % self.0.len() as u64) as usize; + Some(self.0[stage]) + } + + /// Construct and validate an ordered list of distinct positive powers of two. + pub fn try_new(entries: Vec) -> Result { + if entries.len() > MAX_COMMITTEE_COUNTS_ENTRIES { + return Err(PqCommitteeConfigError::TooManyEntries(entries.len())); + } + let mut seen = Vec::with_capacity(entries.len()); + for &count in &entries { + if count == 0 || !count.is_power_of_two() { + return Err(PqCommitteeConfigError::NotPowerOfTwo(count)); + } + if seen.contains(&count) { + return Err(PqCommitteeConfigError::DuplicateCount(count)); + } + seen.push(count); + } + Ok(Self(entries)) + } + + pub fn to_row_ssz(&self) -> Vec { + let row = CommitteeCountsRow::try_from(self.0.clone()).expect("bounded by try_new"); + libssz::SszEncode::to_ssz(&row) + } + + pub fn from_row_ssz(bytes: &[u8]) -> Result { + let row = ::from_ssz_bytes(bytes)?; + Self::try_new(row.to_vec()).map_err(|_| libssz::DecodeError::InvalidByteLength { + expected: 0, + got: bytes.len(), + }) + } +} + +impl TryFrom> for CommitteeCounts { + type Error = PqCommitteeConfigError; + + fn try_from(entries: Vec) -> Result { + Self::try_new(entries) + } +} + +impl serde::Serialize for CommitteeCounts { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeSeq as _; + let mut seq = serializer.serialize_seq(Some(self.0.len()))?; + for count in &self.0 { + seq.serialize_element(&count.to_string())?; + } + seq.end() + } +} + +impl<'de> serde::Deserialize<'de> for CommitteeCounts { + fn deserialize>(deserializer: D) -> Result { + struct SeqVisitor; + + impl<'de> serde::de::Visitor<'de> for SeqVisitor { + type Value = CommitteeCounts; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a sequence of distinct positive power-of-two uint64 integers or decimal strings") + } + + fn visit_seq>( + self, + mut seq: A, + ) -> Result { + struct ScalarOrDecimal; + impl<'de> serde::de::Visitor<'de> for ScalarOrDecimal { + type Value = u64; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a uint64 integer or decimal string") + } + fn visit_u64(self, v: u64) -> Result { + Ok(v) + } + fn visit_i64(self, v: i64) -> Result { + u64::try_from(v).map_err(|_| E::custom("negative X_COMMITTEE_COUNTS entry")) + } + fn visit_str(self, v: &str) -> Result { + if v.is_empty() + || (v.len() > 1 && v.starts_with('0')) + || !v.bytes().all(|b| b.is_ascii_digit()) + { + return Err(E::custom(format!( + "invalid X_COMMITTEE_COUNTS decimal string {v:?}" + ))); + } + v.parse::().map_err(E::custom) + } + } + struct Entry(u64); + impl<'de> serde::Deserialize<'de> for Entry { + fn deserialize>(d: D2) -> Result { + d.deserialize_any(ScalarOrDecimal).map(Entry) + } + } + + let mut entries = Vec::new(); + while let Some(Entry(value)) = seq.next_element()? { + entries.push(value); + } + CommitteeCounts::try_new(entries).map_err(serde::de::Error::custom) + } + } + + deserializer.deserialize_seq(SeqVisitor) + } +} + +impl libssz::SszEncode for CommitteeCounts { + fn is_fixed_size() -> bool { + true + } + fn fixed_size() -> usize { + 0 + } + fn encoded_len(&self) -> usize { + 0 + } + fn ssz_append(&self, _buf: &mut Vec) {} +} + +impl libssz::SszDecode for CommitteeCounts { + 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 @@ -926,13 +1106,58 @@ pub struct Config { /// gas limit per epoch. Empty when the file omits it, as mainnet's does. /// See [`GasLimitSchedule`]. pub gas_limit_schedule: GasLimitSchedule, + + /// PQ (consensus-specs PR-5879): ordered rotating committee counts per + /// slot, eight epochs per stage from PQ genesis (`[]` disables rotation). + pub x_committee_counts: CommitteeCounts, } /// The PQ committee cap this process runs on, `0` until -/// [`select_x_max_committee_count_per_slot`] sets one. +/// [`select_x_max_committee_count_per_slot`] or [`select_pq_committee_config`] +/// sets one. static X_MAX_COMMITTEE_COUNT_PER_SLOT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static X_COMMITTEE_COUNTS_LEN: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +static X_COMMITTEE_COUNTS_STAGES: [std::sync::atomic::AtomicU64; MAX_COMMITTEE_COUNTS_ENTRIES] = + [const { std::sync::atomic::AtomicU64::new(0) }; MAX_COMMITTEE_COUNTS_ENTRIES]; + +/// Errors validating PQ static cap and `X_COMMITTEE_COUNTS` rotation (PR-5879). +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum PqCommitteeConfigError { + #[error("X_MAX_COMMITTEE_COUNT_PER_SLOT must be at least 1, got 0")] + CapZero, + #[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" + )] + CapTooLarge { declared: u64, max: u64 }, + #[error( + "X_COMMITTEE_COUNTS has {0} entries, exceeding MAX_COMMITTEE_COUNTS_ENTRIES ({MAX_COMMITTEE_COUNTS_ENTRIES})" + )] + TooManyEntries(usize), + #[error("X_COMMITTEE_COUNTS entry {0} must be a positive power of two")] + NotPowerOfTwo(u64), + #[error("X_COMMITTEE_COUNTS contains duplicate entry {0}")] + DuplicateCount(u64), + #[error("X_COMMITTEE_COUNTS entry {count} exceeds X_MAX_COMMITTEE_COUNT_PER_SLOT ({cap})")] + CountExceedsCap { count: u64, cap: u64 }, + #[error( + "X_COMMITTEE_COUNTS requires PQ_FORK_EPOCH == 0 (PQ from genesis), got {pq_fork_epoch}" + )] + RotationRequiresPqFromGenesis { pq_fork_epoch: Epoch }, + #[error("X_COMMITTEE_COUNTS requires a PQ genesis state at slot 0")] + GenesisNotPq, + #[error( + "X_COMMITTEE_COUNTS stage {count} is infeasible for {active_validators} genesis active validators" + )] + InfeasibleStage { count: u64, active_validators: u64 }, + #[error("genesis aggregation_committee_window does not match X_COMMITTEE_COUNTS")] + GenesisWindowMismatch, +} + /// 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 @@ -947,13 +1172,70 @@ pub struct CommitteeCapTooLarge { pub max: u64, } +/// Validate `config`'s `X_MAX_COMMITTEE_COUNT_PER_SLOT` and +/// `X_COMMITTEE_COUNTS`, and install both for this process (PR-5879). +pub fn select_pq_committee_config(config: &Config) -> Result { + let max = preset::max_committees_per_slot_pq() as u64; + let declared = config.x_max_committee_count_per_slot; + if declared == 0 { + return Err(PqCommitteeConfigError::CapZero); + } + if declared > max { + return Err(PqCommitteeConfigError::CapTooLarge { declared, max }); + } + if !config.x_committee_counts.is_empty() && config.pq_fork_epoch != 0 { + return Err(PqCommitteeConfigError::RotationRequiresPqFromGenesis { + pq_fork_epoch: config.pq_fork_epoch, + }); + } + for &count in config.x_committee_counts.entries() { + if count > declared { + return Err(PqCommitteeConfigError::CountExceedsCap { + count, + cap: declared, + }); + } + } + X_MAX_COMMITTEE_COUNT_PER_SLOT.store(declared, std::sync::atomic::Ordering::Relaxed); + store_x_committee_counts(config.x_committee_counts.entries()); + Ok(declared) +} + +fn store_x_committee_counts(entries: &[u64]) { + X_COMMITTEE_COUNTS_LEN.store(0, std::sync::atomic::Ordering::Release); + for (slot, &value) in X_COMMITTEE_COUNTS_STAGES.iter().zip(entries.iter()) { + slot.store(value, std::sync::atomic::Ordering::Relaxed); + } + X_COMMITTEE_COUNTS_LEN.store(entries.len(), std::sync::atomic::Ordering::Release); +} + +/// Install an explicit `X_COMMITTEE_COUNTS` stage list in tests; pass `&[]` to +/// restore static cap behavior. +pub fn set_x_committee_counts_for_test(entries: &[u64]) { + let validated = CommitteeCounts::try_new(entries.to_vec()) + .expect("test X_COMMITTEE_COUNTS must be distinct positive powers of two"); + store_x_committee_counts(validated.entries()); +} + +/// Whether experimental PQ committee rotation (`X_COMMITTEE_COUNTS`) is active +/// in this process. +pub fn x_committee_counts_enabled() -> bool { + X_COMMITTEE_COUNTS_LEN.load(std::sync::atomic::Ordering::Acquire) > 0 +} + +/// `X_COMMITTEE_COUNTS[(epoch / 8) % len]` when rotation is active, or `None` +/// when `X_COMMITTEE_COUNTS` is empty. +pub fn x_committee_count_at_epoch(epoch: Epoch) -> Option { + let len = X_COMMITTEE_COUNTS_LEN.load(std::sync::atomic::Ordering::Acquire); + if len == 0 { + return None; + } + let stage = ((epoch / PQ_ROTATION_EPOCHS_PER_STAGE) % len as u64) as usize; + Some(X_COMMITTEE_COUNTS_STAGES[stage].load(std::sync::atomic::Ordering::Relaxed)) +} + /// 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`), 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, @@ -1191,6 +1473,7 @@ impl Config { min_epochs_for_block_requests: 33_024, gas_limit_schedule: GasLimitSchedule::default(), + x_committee_counts: CommitteeCounts::default(), } } @@ -1327,6 +1610,7 @@ impl Config { min_epochs_for_block_requests: 33_024, gas_limit_schedule: GasLimitSchedule::default(), + x_committee_counts: CommitteeCounts::default(), } } @@ -2299,4 +2583,75 @@ mod tests { assert_eq!(entry["EPOCH"], "100"); assert_eq!(entry["MAX_BLOBS_PER_BLOCK"], "9"); } + + #[test] + fn x_committee_counts_parses_preserves_order_rotates_and_rejects_invalid() { + let yaml = "PQ_FORK_EPOCH: 0\nX_MAX_COMMITTEE_COUNT_PER_SLOT: 16\nX_COMMITTEE_COUNTS: [16, 1, 8, 2, 4]\n"; + let config: Config = serde_yaml_ng::from_str(yaml).expect("valid yaml"); + assert_eq!(config.x_committee_counts.entries(), &[16, 1, 8, 2, 4]); + assert_eq!(config.x_committee_counts.count_at(0), Some(16)); + assert_eq!(config.x_committee_counts.count_at(7), Some(16)); + assert_eq!(config.x_committee_counts.count_at(8), Some(1)); + assert_eq!(config.x_committee_counts.count_at(15), Some(1)); + assert_eq!(config.x_committee_counts.count_at(16), Some(8)); + assert_eq!(config.x_committee_counts.count_at(24), Some(2)); + assert_eq!(config.x_committee_counts.count_at(32), Some(4)); + assert_eq!(config.x_committee_counts.count_at(40), Some(16)); + + let json = serde_json::to_value(&config).expect("serializes"); + assert_eq!( + json["X_COMMITTEE_COUNTS"], + serde_json::json!(["16", "1", "8", "2", "4"]) + ); + let roundtrip: Config = serde_json::from_value(json).expect("deserializes strings"); + assert_eq!(roundtrip.x_committee_counts, config.x_committee_counts); + + let row = config.x_committee_counts.to_row_ssz(); + assert_eq!( + CommitteeCounts::from_row_ssz(&row).unwrap(), + config.x_committee_counts + ); + + for bad in [ + "X_COMMITTEE_COUNTS: [0]\n", + "X_COMMITTEE_COUNTS: [3]\n", + "X_COMMITTEE_COUNTS: [4, 4]\n", + "X_COMMITTEE_COUNTS: [-1]\n", + "X_COMMITTEE_COUNTS: [\"01\"]\n", + "X_COMMITTEE_COUNTS: [\"abc\"]\n", + ] { + assert!(serde_yaml_ng::from_str::(bad).is_err(), "{bad}"); + } + + // Requires cap <= MAX_COMMITTEES_PER_SLOT_PQ, PQ from genesis, and stages <= cap. + // Use stages within minimal's `MAX_COMMITTEES_PER_SLOT_PQ` (4) so both presets + // reach each check. + let preset_valid: Config = serde_yaml_ng::from_str( + "PQ_FORK_EPOCH: 0\nX_MAX_COMMITTEE_COUNT_PER_SLOT: 4\nX_COMMITTEE_COUNTS: [4, 1, 2]\n", + ) + .expect("valid yaml"); + let max = preset::max_committees_per_slot_pq() as u64; + let mut over_preset = preset_valid.clone(); + over_preset.x_max_committee_count_per_slot = max + 1; + assert_eq!( + select_pq_committee_config(&over_preset).unwrap_err(), + PqCommitteeConfigError::CapTooLarge { + declared: max + 1, + max, + } + ); + let mut not_genesis = preset_valid.clone(); + not_genesis.pq_fork_epoch = 1; + assert_eq!( + select_pq_committee_config(¬_genesis).unwrap_err(), + PqCommitteeConfigError::RotationRequiresPqFromGenesis { pq_fork_epoch: 1 } + ); + let mut over_cap = preset_valid; + over_cap.x_max_committee_count_per_slot = 2; + assert_eq!( + select_pq_committee_config(&over_cap).unwrap_err(), + PqCommitteeConfigError::CountExceedsCap { count: 4, cap: 2 } + ); + set_x_committee_counts_for_test(&[]); + } } 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..582f4ee49 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) => { + ("expired", "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/scoring.rs b/crates/net/p2p/src/beacon/scoring.rs index a42f73e91..8696efe78 100644 --- a/crates/net/p2p/src/beacon/scoring.rs +++ b/crates/net/p2p/src/beacon/scoring.rs @@ -78,7 +78,7 @@ use std::collections::HashSet; use std::time::Duration; use ethlambda_state_transition::beacon::helpers::accessors::{ - committee_count_per_slot, committee_count_per_slot_for, + committee_count_per_slot, committee_count_per_slot_at_epoch, }; use ethlambda_types::beacon::config::Config; use ethlambda_types::beacon::constants::{ @@ -360,7 +360,9 @@ impl ScoreSettings { let active = inputs .active_validators .max(placeholder_active_validators()); - let (aggregators_per_slot, committees_per_slot) = expected_pq_aggregators_per_slot(active); + let epoch = inputs.current_slot / slots_per_epoch(); + let (aggregators_per_slot, committees_per_slot) = + expected_pq_aggregators_per_slot(active, epoch); topics.extend(self.dynamic_topic_params_with( fork_digest, inputs, @@ -625,8 +627,8 @@ fn expected_aggregators_per_slot(active: u64) -> (f64, u64) { /// [`expected_aggregators_per_slot`] at PQ: every committee, under PQ's cap, /// has an aggregation committee of up to `AGGREGATORS_PER_COMMITTEE` members, /// fewer only when the committee itself is smaller. -fn expected_pq_aggregators_per_slot(active: u64) -> (f64, u64) { - let committees_per_slot = committee_count_per_slot_for(ForkName::Pq, active); +fn expected_pq_aggregators_per_slot(active: u64, epoch: u64) -> (f64, u64) { + let committees_per_slot = committee_count_per_slot_at_epoch(ForkName::Pq, epoch, active); let committee_size = active / (committees_per_slot * slots_per_epoch()).max(1); let per_committee = AGGREGATORS_PER_COMMITTEE.min(committee_size.max(1)); ( @@ -1611,4 +1613,23 @@ mod tests { assert!(SCORE_BANDS.contains(&score_band(score))); } } + + #[test] + fn pq_expected_aggregators_rotate_with_x_committee_counts() { + ethlambda_types::beacon::config::set_x_committee_counts_for_test(&[16, 8, 4, 2, 1]); + let active = 32_768; + let per = AGGREGATORS_PER_COMMITTEE as f64; + assert_eq!( + expected_pq_aggregators_per_slot(active, 0), + (16.0 * per, 16) + ); + assert_eq!(expected_pq_aggregators_per_slot(active, 8), (8.0 * per, 8)); + assert_eq!(expected_pq_aggregators_per_slot(active, 16), (4.0 * per, 4)); + assert_eq!(expected_pq_aggregators_per_slot(active, 24), (2.0 * per, 2)); + assert_eq!(expected_pq_aggregators_per_slot(active, 32), (1.0 * per, 1)); + assert_eq!( + expected_pq_aggregators_per_slot(active, 40), + (16.0 * per, 16) + ); + } } diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index beedb9fd4..7457fb2bd 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); } } @@ -999,6 +1001,11 @@ pub(crate) fn spawn_stateful_checks( let actor = ctx.actor_ref(); let in_use = metrics::PoolInUse::new(pool); let task = metrics::BlockingTask::new(id.kind); + if let Validated::Pq(pq) = &object + && let Some(gid) = pq.pq_aggregate_id() + { + ethlambda_telemetry::pq_events::gossip::queued(gid); + } tokio::task::spawn_blocking(move || { let _permit = permit; let _in_use = in_use; 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..37c7ed98e 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,85 @@ 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) { + use libp2p::gossipsub::PublishError; + match *hook { + PqPublishHook::Aggregate { + slot, + aggregator_index, + metadata, + extra, + } => { + let (accepted, reason, id_opt) = match &res { + Ok(id) => (true, "none", Some(format!("0x{}", hex::encode(&id.0)))), + Err(PublishError::Duplicate) => { + (false, "duplicate_suppressed", computed_id) + } + Err(PublishError::NoPeersSubscribedToTopic) => { + (false, "no_inputs", computed_id) + } + Err(_) => (false, "other", None), + }; + if let Some(pub_ref) = ethlambda_telemetry::pq_events::gossip::published( + &topic_str, + id_opt.as_deref(), + &requested, + &returned, + accepted, + 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() 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/config.rs b/crates/net/rpc/src/beacon/config.rs index c9c8fb1f2..c1178eaf1 100644 --- a/crates/net/rpc/src/beacon/config.rs +++ b/crates/net/rpc/src/beacon/config.rs @@ -539,6 +539,22 @@ mod tests { ); } + #[test] + fn the_spec_reports_x_committee_counts_as_ordered_quoted_strings() { + use ethlambda_types::beacon::config::CommitteeCounts; + + let default_data = spec(&Config::mainnet()); + assert_eq!(default_data["X_COMMITTEE_COUNTS"], serde_json::json!([])); + + let mut config = Config::mainnet(); + config.x_committee_counts = CommitteeCounts::try_new(vec![16, 8, 4, 2, 1]).unwrap(); + let data = spec(&config); + assert_eq!( + data["X_COMMITTEE_COUNTS"], + serde_json::json!(["16", "8", "4", "2", "1"]) + ); + } + #[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_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/storage/src/store.rs b/crates/storage/src/store.rs index 3013d660c..2defdb501 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -162,16 +162,29 @@ struct ConfigRow { } /// 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(()) +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(), + }, + ConfigRow { + name: "X_COMMITTEE_COUNTS", + key: b"config_x_committee_counts", + encode: |config| config.x_committee_counts.to_row_ssz(), + decode: |bytes, config| { + config.x_committee_counts = + ethlambda_types::beacon::config::CommitteeCounts::from_row_ssz(bytes)?; + Ok(()) + }, + copy: |from, into| into.x_committee_counts = from.x_committee_counts.clone(), }, - 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 @@ -9395,6 +9408,9 @@ mod tests { gas_limit: 200_000_000, }] .into(); + config.x_committee_counts = + ethlambda_types::beacon::config::CommitteeCounts::try_new(vec![16, 8, 4, 2, 1]) + .unwrap(); config } @@ -9450,8 +9466,9 @@ mod tests { let mut store = Store::from_db_state(backend.clone()).unwrap().unwrap(); assert!(store.config().gas_limit_schedule.is_empty()); + assert!(store.config().x_committee_counts.is_empty()); let (filled, missing) = store.fill_missing_config_keys(&scheduled); - assert_eq!(missing, ["GAS_LIMIT_SCHEDULE"]); + assert_eq!(missing, ["GAS_LIMIT_SCHEDULE", "X_COMMITTEE_COUNTS"]); assert_eq!(filled, scheduled); // What a resume does next: the file's config, rows included. @@ -9461,6 +9478,10 @@ mod tests { reopened.config().gas_limit_schedule, scheduled.gas_limit_schedule ); + assert_eq!( + reopened.config().x_committee_counts, + scheduled.x_committee_counts + ); assert!( reopened .fill_missing_config_keys(&Config::mainnet()) 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..78f3174ce 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -695,6 +695,14 @@ 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(chain_id) = spec_u64(value, "DEPOSIT_CHAIN_ID")? { + config.deposit_chain_id = chain_id; + } + 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..5c7ed0d4e 100644 --- a/crates/validator/src/error.rs +++ b/crates/validator/src/error.rs @@ -12,9 +12,12 @@ use ethlambda_types::beacon::primitives::{BlsPubkey, ValidatorIndex}; -/// The EIP-2335 keystore schema version this client understands. +/// The EIP-2335 BLS keystore schema version this client understands. pub const EIP2335_KEYSTORE_VERSION: u64 = 4; +/// The ERC-8519 post-quantum (`"leanxmss"`) keystore schema version. +pub const ERC8519_KEYSTORE_VERSION: u64 = 5; + /// Why a beacon node request failed, classified at construction. /// /// Failover and the duty loop need to tell a node that is down from one that @@ -142,10 +145,14 @@ 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 }, - #[error("unsupported keystore version {0}, expected {EIP2335_KEYSTORE_VERSION}")] + #[error( + "unsupported keystore version {0}, expected {EIP2335_KEYSTORE_VERSION} or {ERC8519_KEYSTORE_VERSION}" + )] KeystoreVersion(u64), #[error("keystore password did not match the checksum")] KeystoreBadPassword, @@ -285,6 +292,7 @@ impl Error { | Self::SlashingProtection { .. } | Self::SlashingProtectionUnusable { .. } | Self::Io { .. } + | Self::TelemetryConfig(_) | Self::Unflushed { .. } => false, } } diff --git a/crates/validator/src/http_api/keystores.rs b/crates/validator/src/http_api/keystores.rs index a19b169b8..13307c8cc 100644 --- a/crates/validator/src/http_api/keystores.rs +++ b/crates/validator/src/http_api/keystores.rs @@ -458,9 +458,9 @@ pub async fn import( let data = prepared .into_iter() .map(|result| match (result, ®istration) { - (Ok((pubkey, secret, _, overrides)), Ok(_)) => { + (Ok((pubkey, decrypted, _, overrides)), Ok(_)) => { let held = store.contains(&pubkey); - let status = finish_import(&mut store, &secret); + let status = finish_import(&mut store, pubkey, decrypted); // The file holds this key's entry, enabled, with these // overrides, so the settings must hold them too. For a key // already loaded this changes nothing. For an entry this @@ -701,10 +701,15 @@ fn remove_if_present(path: &Path) -> crate::Result<()> { } } -/// One key of an import that reached the disk: the key, its secret, what its -/// keystore and password files replaced, and the overrides its definitions -/// entry carries, which are seeded once the key is in the store. -type Persisted = (BlsPubkey, Zeroizing<[u8; 32]>, Overwritten, Overrides); +/// One key of an import that reached the disk: the key, its decrypted +/// material, what its keystore and password files replaced, and the overrides +/// its definitions entry carries, which are seeded once the key is in the store. +type Persisted = ( + BlsPubkey, + crate::keys::keystore::DecryptedKeystore, + Overwritten, + Overrides, +); /// Decrypt one keystore and persist it to disk: everything an import can do /// before it needs the store's write lock and its slashing-protection record. @@ -720,28 +725,53 @@ fn prepare_import( }; let keystore = Keystore::from_json(json).map_err(KeyStatus::error)?; - let secret = keystore.decrypt(password).map_err(KeyStatus::error)?; - let pubkey = ValidatorStore::derive_pubkey(&secret).map_err(KeyStatus::error)?; - - // A key a remote signer holds, by the file or by the store, is - // `duplicate` here, the mirror of what `/eth/v1/remotekeys` answers for a - // local one: neither route silently replaces the other's entry. Judged - // before anything is written, so a `duplicate` never leaves files behind. - // Re-importing a key this route already holds is still `imported`, since - // that is how a password is rotated. + let decrypted = keystore.decrypt_any(password).map_err(KeyStatus::error)?; + let pubkey = match &decrypted { + crate::keys::keystore::DecryptedKeystore::Bls(secret) => { + ValidatorStore::derive_pubkey(secret).map_err(KeyStatus::error)? + } + crate::keys::keystore::DecryptedKeystore::PqAccount { + account_seed, + pubkey, + path, + } => { + if let Some(parsed) = path + && parsed.chain_id != context.signing.config.deposit_chain_id + { + return Err(KeyStatus::error(format!( + "keystore path is for chain_id {}, but this network's DEPOSIT_CHAIN_ID is {}", + parsed.chain_id, context.signing.config.deposit_chain_id + ))); + } + let current_slot = context.clock.now().unwrap_or(0); + let role = Keystore::pq_role(*path); + let handle = BlsPubkey( + ethlambda_types::beacon::primitives::XmssPubkey(*pubkey) + .to_request_key() + .0, + ); + crate::pq::derive_and_register_account( + account_seed, + role, + Some(*pubkey), + Some(handle), + None, + current_slot, + None, + ) + .map_err(KeyStatus::error)?; + handle + } + }; + if held_remotely.contains(&pubkey) { return Err(KeyStatus::duplicate()); } - // Persisted before the key is reachable through the store: a validator - // this process is willing to sign with must already be durable, or a - // crash right after "imported" is reported silently loses it, with - // nothing about a live, signing validator hinting that it is about to - // vanish on the next restart. let (overwritten, overrides) = persist_import(context, definitions, &pubkey, json, password).map_err(KeyStatus::error)?; - Ok((pubkey, secret, overwritten, overrides)) + Ok((pubkey, decrypted, overwritten, overrides)) } /// What `persist_import` found at the two paths it writes, so an undone @@ -778,8 +808,22 @@ fn regular_file_bytes(path: &Path) -> crate::Result>> { /// scalar validation and hashmap insert, never an await. Nothing is judged /// again here: `prepare_import` judged the file and the store under /// `definitions_lock`, which is still held. -fn finish_import(store: &mut ValidatorStore, secret: &[u8; 32]) -> KeyStatus { - match store.insert_secret("keymanager import", secret) { +fn finish_import( + store: &mut ValidatorStore, + pubkey: BlsPubkey, + decrypted: crate::keys::keystore::DecryptedKeystore, +) -> KeyStatus { + let inserted = match decrypted { + crate::keys::keystore::DecryptedKeystore::Bls(secret) => { + store.insert_secret("keymanager import", &secret) + } + crate::keys::keystore::DecryptedKeystore::PqAccount { + account_seed, + pubkey: xmss_pubkey, + path, + } => Ok(store.insert_pq_account(pubkey, account_seed, Some(xmss_pubkey), path)), + }; + match inserted { Ok(pubkey) => { info!(pubkey = %encode_hex(&pubkey.0), "Imported validator key"); KeyStatus { diff --git a/crates/validator/src/http_api/remotekeys.rs b/crates/validator/src/http_api/remotekeys.rs index 561de2bfd..4cc55938e 100644 --- a/crates/validator/src/http_api/remotekeys.rs +++ b/crates/validator/src/http_api/remotekeys.rs @@ -784,7 +784,8 @@ mod tests { let pubkey = parse_pubkey(&pubkey_hex(byte)).expect("pubkey"); match store.signer(&pubkey).expect("held") { crate::keys::SigningMethod::Web3Signer { signer } => signer, - crate::keys::SigningMethod::LocalKeystore { .. } => panic!("a remote key"), + crate::keys::SigningMethod::LocalKeystore { .. } + | crate::keys::SigningMethod::PqAccount { .. } => panic!("a remote key"), } }) .collect(); diff --git a/crates/validator/src/keys/definitions.rs b/crates/validator/src/keys/definitions.rs index 70a5cd5fb..0fe515d4c 100644 --- a/crates/validator/src/keys/definitions.rs +++ b/crates/validator/src/keys/definitions.rs @@ -411,19 +411,29 @@ impl ValidatorDefinitions { path: keystore_path.display().to_string(), source, })?; - let pubkey = crate::keys::keystore::Keystore::from_json(&json) + let raw_pubkey = crate::keys::keystore::Keystore::from_json(&json) .ok() .and_then(|keystore| keystore.pubkey) .ok_or_else(|| Error::Keystore { path: keystore_path.display().to_string(), reason: "a discovered keystore must name its public key".to_string(), })?; - let pubkey = format!("0x{}", pubkey.trim_start_matches("0x")); + let bare = raw_pubkey.trim_start_matches("0x"); + let pubkey = format!("0x{bare}"); + let dir_name = entry.file_name(); + let voting_keystore_password_path = [ + secrets_dir.join(&pubkey), + secrets_dir.join(bare), + secrets_dir.join(dir_name), + ] + .into_iter() + .find(|candidate| candidate.is_file()) + .unwrap_or_else(|| secrets_dir.join(&pubkey)); definitions.push(ValidatorDefinition { enabled: true, signing: SigningDefinition::LocalKeystore { voting_keystore_path: keystore_path, - voting_keystore_password_path: secrets_dir.join(&pubkey), + voting_keystore_password_path, }, voting_public_key: pubkey, suggested_fee_recipient: None, diff --git a/crates/validator/src/keys/keystore.rs b/crates/validator/src/keys/keystore.rs index 80a9121aa..56b965516 100644 --- a/crates/validator/src/keys/keystore.rs +++ b/crates/validator/src/keys/keystore.rs @@ -1,37 +1,67 @@ -//! EIP-2335 keystore decryption. +//! EIP-2335 (BLS, v4) and ERC-8519 (`leanxmss`, v5) keystore decryption. //! -//! The format every staking tool emits: a JSON document holding a key-derivation -//! function (scrypt or pbkdf2), a checksum that verifies the password before any -//! decryption is attempted, and the secret under aes-128-ctr. +//! Version 4 encrypts a 32-byte BLS secret key under `aes-128-ctr` with a +//! 32-byte KDF output (`derived[0..16]` for the cipher, `derived[16..32]` for +//! the SHA-256 checksum). +//! +//! Version 5 (ERC-8519) encrypts a 32-byte ERC-8517 account seed under +//! `aes-256-ctr` with a 64-byte KDF output (`derived[0..32]` for the cipher, +//! `derived[32..64]` for the SHA-256 checksum), records `scheme: "leanxmss"` +//! and the 32-byte leanXMSS `pubkey` in clear, and records the ERC-8517 +//! derivation `path` (or `""` when unknown). +use ethlambda_crypto::pq_keys::{self, PqAccountPath, PqRole}; use serde::Deserialize; use zeroize::Zeroizing; -use crate::error::{EIP2335_KEYSTORE_VERSION, Error, Result}; +use crate::error::{EIP2335_KEYSTORE_VERSION, ERC8519_KEYSTORE_VERSION, Error, Result}; + +/// The `scheme` field required by ERC-8519 v5 post-quantum keystores. +pub const LEANXMSS_KEYSTORE_SCHEME: &str = "leanxmss"; + +/// Decrypted contents of either an EIP-2335 (v4) or ERC-8519 (v5) keystore. +pub enum DecryptedKeystore { + /// EIP-2335 v4: 32-byte big-endian BLS secret key. + Bls(Zeroizing<[u8; 32]>), + /// ERC-8519 v5: 32-byte ERC-8517 account seed, its declared 32-byte + /// leanXMSS public key, and its optional parsed ERC-8517 path. + PqAccount { + account_seed: Zeroizing<[u8; 32]>, + pubkey: [u8; 32], + path: Option, + }, +} + +impl std::fmt::Debug for DecryptedKeystore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Bls(_) => f.write_str("DecryptedKeystore::Bls(..)"), + Self::PqAccount { pubkey, path, .. } => f + .debug_struct("DecryptedKeystore::PqAccount") + .field("pubkey", &hex::encode(pubkey)) + .field("path", path) + .finish_non_exhaustive(), + } + } +} #[derive(Debug, Deserialize)] pub struct Keystore { /// The key-derivation, checksum and cipher parameters, plus the /// encrypted secret. pub crypto: Crypto, - /// The validator's BLS public key, hex-encoded. + /// Scheme identifier (`"leanxmss"` on ERC-8519 v5 keystores; absent on v4). + pub scheme: Option, + /// Public key in hex (48-byte BLS pubkey on v4; 32-byte leanXMSS pubkey on v5). pub pubkey: Option, - /// The keystore's HD derivation path (e.g. `m/12381/60/0/0`). - /// - /// ERC-2335 marks this required, but `decrypt` never reads it: refusing - /// a keystore that would otherwise decrypt correctly would reject real - /// operator key material over metadata this client has no use for. + /// HD derivation path (`m/12381/...` on v4, `m/5326/3600/...` or `""` on v5). pub path: Option, /// A UUID identifying this keystore. - /// - /// ERC-2335 marks this required too, but `decrypt` never reads it - /// either, for the same reason `path` stays optional. pub uuid: Option, - /// The ERC-2335 schema version; only [`EIP2335_KEYSTORE_VERSION`] decrypts. + /// Schema version: `4` (EIP-2335) or `5` (ERC-8519). pub version: u64, /// Where this keystore's JSON came from, used only to build error - /// messages. Not part of the ERC-2335 schema: set by the constructor, - /// never deserialized. + /// messages. #[serde(skip)] source: String, } @@ -64,7 +94,7 @@ pub struct Checksum { #[derive(Debug, Deserialize)] pub struct Cipher { - /// The cipher function; only `aes-128-ctr` is supported. + /// The cipher function: `aes-128-ctr` (v4) or `aes-256-ctr` (v5). pub function: String, /// The cipher's parameters. pub params: CipherParams, @@ -78,6 +108,9 @@ pub struct CipherParams { pub iv: String, } +/// Verified ERC-8519 v5 keystore material: `(account_seed, xmss_pubkey, path)`. +pub type DecryptedPqKeystore = (Zeroizing<[u8; 32]>, [u8; 32], Option); + impl Keystore { /// Parse a keystore from its JSON form. pub fn from_json(json: &str) -> Result { @@ -89,9 +122,6 @@ impl Keystore { Ok(keystore) } - /// Build a keystore error pointing at wherever this keystore's JSON came - /// from, so a later file-loading constructor only has to change what it - /// sets `source` to, not every call site that raises an error. fn keystore_error(&self, reason: impl Into) -> Error { Error::Keystore { path: self.source.clone(), @@ -99,25 +129,68 @@ impl Keystore { } } - /// Recover the 32-byte secret key, verifying the password first. + /// Recover the 32-byte BLS secret key of an EIP-2335 (v4) keystore, + /// verifying the password first. /// - /// The password check is deliberately a separate step ahead of decryption: - /// the checksum tells us the password is right without the cipher ever - /// running, which is what lets a wrong password be reported as such rather - /// than as 32 bytes of garbage that only fail later at signing time. - /// - /// The result is wrapped in [`Zeroizing`] so the secret is scrubbed from - /// memory on drop rather than lingering for the rest of the process. + /// Refuses an ERC-8519 (v5) keystore so a caller expecting a BLS scalar + /// never mistakes an account seed for one. Call [`Self::decrypt_any`] where + /// both v4 and v5 keystores are accepted. pub fn decrypt(&self, password: &str) -> Result> { if self.version != EIP2335_KEYSTORE_VERSION { return Err(Error::KeystoreVersion(self.version)); } + self.decrypt_v4(password) + } + /// Decrypt either an EIP-2335 (v4) or an ERC-8519 (v5) keystore. + /// + /// On v5, checks `scheme == "leanxmss"`, validates `pubkey` (64 lowercase + /// hex chars) and `path` (empty or a valid ERC-8517 path), verifies the + /// password checksum over `derived[32..64]`, decrypts under `aes-256-ctr`, + /// and verifies the fast 16-byte leanXMSS public parameter against + /// `pubkey[16..32]` immediately. Full 32-byte public-key verification runs + /// when the leanXMSS tree is loaded or built (see [`Self::decrypt_pq_verified`] + /// and `pq::derive_and_register`). + pub fn decrypt_any(&self, password: &str) -> Result { + match self.version { + EIP2335_KEYSTORE_VERSION => self.decrypt_v4(password).map(DecryptedKeystore::Bls), + ERC8519_KEYSTORE_VERSION => self.decrypt_v5_unchecked_root(password), + other => Err(Error::KeystoreVersion(other)), + } + } + + /// Decrypt an ERC-8519 (v5) keystore and immediately build the full + /// leanXMSS top tree to verify all 32 bytes of `pubkey` against the + /// decrypted account seed, as ERC-8519 requires. + pub fn decrypt_pq_verified(&self, password: &str) -> Result { + if self.version != ERC8519_KEYSTORE_VERSION { + return Err(Error::KeystoreVersion(self.version)); + } + let DecryptedKeystore::PqAccount { + account_seed, + pubkey, + path, + } = self.decrypt_v5_unchecked_root(password)? + else { + unreachable!("decrypt_v5_unchecked_root always returns PqAccount"); + }; + let derived_pubkey = pq_keys::xmss_key(&account_seed).public_key().to_bytes(); + if derived_pubkey != pubkey { + return Err(self.keystore_error(format!( + "keystore pubkey {} does not match leanXMSS key {} derived from its account seed", + hex::encode(pubkey), + hex::encode(derived_pubkey) + ))); + } + Ok((account_seed, pubkey, path)) + } + + fn decrypt_v4(&self, password: &str) -> Result> { let password = normalize_password(password); - let derived = self.derive_key(&password)?; + let derived = self.derive_key::<32>(&password)?; let cipher_message = self.decode_hex(&self.crypto.cipher.message)?; - if !self.checksum_matches(&derived, &cipher_message)? { + if !self.checksum_matches(&derived[16..32], &cipher_message)? { return Err(Error::KeystoreBadPassword); } @@ -129,8 +202,6 @@ impl Keystore { } let iv = self.decode_hex(&self.crypto.cipher.params.iv)?; - // Wrapped as soon as it holds the plaintext (post-decryption), so the - // buffer is scrubbed on drop rather than left as an ordinary `Vec`. let mut secret = Zeroizing::new(cipher_message); self.apply_aes_128_ctr(&derived[..16], &iv, &mut secret)?; @@ -139,36 +210,123 @@ impl Keystore { self.keystore_error(format!("secret is {} bytes, expected 32", secret.len())) ); } - // Constructed before the copy rather than after: the secret is never - // briefly held in a bare, unwrapped `[u8; 32]` on the stack between - // being copied out of `secret` and getting a `Zeroizing` guarantee of - // its own. let mut out = Zeroizing::new([0u8; 32]); out.copy_from_slice(&secret); Ok(out) } - /// Run the keystore's KDF over the password, producing the 32-byte - /// decryption key whose halves serve two different purposes: the first for - /// the cipher, the second for the checksum. - fn derive_key(&self, password: &[u8]) -> Result> { + fn decrypt_v5_unchecked_root(&self, password: &str) -> Result { + match self.scheme.as_deref() { + Some(LEANXMSS_KEYSTORE_SCHEME) => {} + Some(other) => { + return Err(self.keystore_error(format!( + "unsupported PQ keystore scheme {other:?}, expected {LEANXMSS_KEYSTORE_SCHEME:?}" + ))); + } + None => { + return Err(self.keystore_error("missing required field `scheme` on v5 keystore")); + } + } + let pubkey_text = self + .pubkey + .as_deref() + .ok_or_else(|| self.keystore_error("missing required field `pubkey` on v5 keystore"))?; + let pubkey = self.parse_v5_pubkey(pubkey_text)?; + let raw_path = self + .path + .as_deref() + .ok_or_else(|| self.keystore_error("missing required field `path` on v5 keystore"))?; + let parsed_path = if raw_path.is_empty() { + None + } else { + Some( + PqAccountPath::parse(raw_path) + .map_err(|err| self.keystore_error(err.to_string()))?, + ) + }; + if self.uuid.is_none() { + return Err(self.keystore_error("missing required field `uuid` on v5 keystore")); + } + + let password = normalize_password(password); + let derived = self.derive_key::<64>(&password)?; + + let cipher_message = self.decode_hex(&self.crypto.cipher.message)?; + if !self.checksum_matches(&derived[32..64], &cipher_message)? { + return Err(Error::KeystoreBadPassword); + } + + if self.crypto.cipher.function != "aes-256-ctr" { + return Err(self.keystore_error(format!( + "unsupported cipher {} on v5 keystore, expected aes-256-ctr", + self.crypto.cipher.function + ))); + } + + let iv = self.decode_hex(&self.crypto.cipher.params.iv)?; + let mut secret = Zeroizing::new(cipher_message); + self.apply_aes_256_ctr(&derived[..32], &iv, &mut secret)?; + + if secret.len() != 32 { + return Err( + self.keystore_error(format!("secret is {} bytes, expected 32", secret.len())) + ); + } + let mut account_seed = Zeroizing::new([0u8; 32]); + account_seed.copy_from_slice(&secret); + + let expected_param = pq_keys::xmss_public_param(&account_seed); + if pubkey[16..] != expected_param { + return Err(self.keystore_error(format!( + "keystore pubkey {} does not match the leanXMSS public parameter of its account seed", + hex::encode(pubkey) + ))); + } + + Ok(DecryptedKeystore::PqAccount { + account_seed, + pubkey, + path: parsed_path, + }) + } + + fn parse_v5_pubkey(&self, text: &str) -> Result<[u8; 32]> { + let stripped = text.strip_prefix("0x").unwrap_or(text); + if stripped.len() != 64 + || !stripped + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(self + .keystore_error("v5 keystore pubkey must be 64 lowercase hexadecimal characters")); + } + let bytes = hex::decode(stripped) + .map_err(|err| self.keystore_error(format!("bad pubkey hex: {err}")))?; + bytes + .try_into() + .map_err(|_| self.keystore_error("v5 keystore pubkey must be 32 bytes")) + } + + /// Role recorded in `path`, defaulting to [`PqRole::Validator`] when `path` + /// is empty. + pub fn pq_role(path: Option) -> PqRole { + path.map_or(PqRole::Validator, |parsed| parsed.role) + } + + /// Run the keystore's KDF over the password, producing an `N`-byte + /// decryption key (`32` for EIP-2335 v4, `64` for ERC-8519 v5). + fn derive_key(&self, password: &[u8]) -> Result> { let params = &self.crypto.kdf.params; let salt = self.decode_hex(self.string_param(params, "salt")?)?; let dklen = self.u64_param(params, "dklen")? as usize; - if dklen != 32 { - return Err(self.keystore_error(format!("dklen is {dklen}, expected 32"))); + if dklen != N { + return Err(self.keystore_error(format!("dklen is {dklen}, expected {N}"))); } - let mut out = Zeroizing::new([0u8; 32]); + let mut out = Zeroizing::new([0u8; N]); match self.crypto.kdf.function.as_str() { "scrypt" => { let n = self.u64_param(params, "n")?; - // RFC 7914 (which ERC-2335 references normatively) requires N - // to be a power of two: it is scrypt's cost parameter, - // expressed to the cipher as log2(N). A value that is not an - // exact power of two would silently truncate through - // `trailing_zeros`, deriving the wrong key and surfacing as a - // bad-password error instead of the corrupt file it is. if n < 2 || !n.is_power_of_two() { return Err(self .keystore_error(format!("scrypt n must be a power of two >= 2, got {n}"))); @@ -179,10 +337,8 @@ impl Keystore { let p = self.u64_param(params, "p")?; let p = u32::try_from(p) .map_err(|_| self.keystore_error(format!("scrypt p={p} out of range")))?; - // n was just verified to be an exact power of two, so this - // recovers its exponent rather than truncating it. let log_n = n.trailing_zeros() as u8; - let scrypt_params = scrypt::Params::new(log_n, r, p, 32) + let scrypt_params = scrypt::Params::new(log_n, r, p, N) .map_err(|err| self.keystore_error(format!("bad scrypt params: {err}")))?; scrypt::scrypt(password, &salt, &scrypt_params, out.as_mut()) .map_err(|err| self.keystore_error(format!("scrypt failed: {err}")))?; @@ -205,8 +361,7 @@ impl Keystore { Ok(out) } - /// `sha256(derived_key[16..32] | cipher_message) == checksum.message`. - fn checksum_matches(&self, derived: &[u8; 32], cipher_message: &[u8]) -> Result { + fn checksum_matches(&self, dk_slice: &[u8], cipher_message: &[u8]) -> Result { if self.crypto.checksum.function != "sha256" { return Err(self.keystore_error(format!( "unsupported checksum {}", @@ -215,7 +370,7 @@ impl Keystore { } use sha2::Digest as _; let mut hasher = sha2::Sha256::new(); - hasher.update(&derived[16..32]); + hasher.update(dk_slice); hasher.update(cipher_message); let expected = self.decode_hex(&self.crypto.checksum.message)?; Ok(hasher.finalize().as_slice() == expected.as_slice()) @@ -230,6 +385,15 @@ impl Keystore { Ok(()) } + fn apply_aes_256_ctr(&self, key: &[u8], iv: &[u8], data: &mut [u8]) -> Result<()> { + use aes::cipher::{KeyIvInit as _, StreamCipher as _}; + type Aes256Ctr = ctr::Ctr128BE; + let mut cipher = Aes256Ctr::new_from_slices(key, iv) + .map_err(|err| self.keystore_error(format!("bad aes key or iv: {err}")))?; + cipher.apply_keystream(data); + Ok(()) + } + fn decode_hex(&self, value: &str) -> Result> { hex::decode(value.trim_start_matches("0x")) .map_err(|err| self.keystore_error(format!("bad hex: {err}"))) @@ -250,16 +414,9 @@ impl Keystore { } } -/// EIP-2335 requires NFKD normalization, then stripping the C0/C1 control -/// codes, then UTF-8 encoding, in that order. The control-code strip must -/// happen on Unicode scalar values, not on already-encoded bytes: a C1 code -/// point (U+0080-U+009F) is two bytes in UTF-8, and so is every other -/// character above U+007F, so a byte in that same numeric range can be an -/// unrelated character's continuation byte. Filtering post-encoding would -/// corrupt any such character instead of leaving it alone. -/// -/// Wrapped in [`Zeroizing`] since this buffer holds the operator's password -/// in a form directly usable by the KDF. +/// EIP-2335 / ERC-8519 password normalization: NFKD normalization, then +/// stripping the C0, Delete and C1 control codes on Unicode scalar values, +/// then UTF-8 encoding. fn normalize_password(password: &str) -> Zeroizing> { use unicode_normalization::UnicodeNormalization as _; Zeroizing::new( @@ -275,12 +432,17 @@ fn normalize_password(password: &str) -> Zeroizing> { mod tests { use super::*; - /// The password from the EIP-2335 test vectors. Both keystores use it. + /// The password from the EIP-2335 and ERC-8519 test vectors. const PASSWORD: &str = "\u{1d531}\u{1d522}\u{1d530}\u{1d531}\u{1d52d}\u{1d51e}\u{1d530}\u{1d530}\u{1d534}\u{1d52c}\u{1d52f}\u{1d521}\u{1f511}"; - /// The secret both test keystores encrypt. + /// The secret both v4 test keystores encrypt. const SECRET: &str = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"; + /// The account seed both ERC-8519 v5 test keystores encrypt (ERC-8517 Test Case 0). + const PQ_ACCOUNT_SEED: &str = + "78897286a417216b2c8fed7023496767bff03e25ce194c3c8123ab1a93feaed1"; + const PQ_PUBKEY: &str = "9023e9124c4c6a0af5f47af8c4d042dcb93c2341654d727c3d8ec48199d05b04"; + const SCRYPT: &str = r#"{ "crypto": { "kdf": { @@ -335,6 +497,73 @@ mod tests { "version": 4 }"#; + const ERC8519_SCRYPT: &str = r#"{ + "crypto": { + "kdf": { + "function": "scrypt", + "params": { + "dklen": 64, + "n": 262144, + "p": 1, + "r": 8, + "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" + }, + "message": "" + }, + "checksum": { + "function": "sha256", + "params": {}, + "message": "beacf7fc11c7cc9d51031d749e111ba5fcbd0d7afc7e4bac9d071b4deb3a1003" + }, + "cipher": { + "function": "aes-256-ctr", + "params": { + "iv": "264daa3f303d7259501c93d997d84fe6" + }, + "message": "418939abcc4966a0a8e8a9963704429ba647c66579fe594b08964fa5dbce5fb2" + } + }, + "description": "This is a test keystore that uses scrypt to secure the secret.", + "scheme": "leanxmss", + "pubkey": "9023e9124c4c6a0af5f47af8c4d042dcb93c2341654d727c3d8ec48199d05b04", + "path": "m/5326/3600/1/0/0", + "uuid": "8c5b9f4a-2f0e-4b6d-9a3c-1e7d5f2b8a60", + "version": 5 + }"#; + + const ERC8519_PBKDF2: &str = r#"{ + "crypto": { + "kdf": { + "function": "pbkdf2", + "params": { + "dklen": 64, + "c": 262144, + "prf": "hmac-sha256", + "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" + }, + "message": "" + }, + "checksum": { + "function": "sha256", + "params": {}, + "message": "a205b2c54f55e442302f1b9757abdb17e218c19ec0c507c15bcaea08022c0168" + }, + "cipher": { + "function": "aes-256-ctr", + "params": { + "iv": "264daa3f303d7259501c93d997d84fe6" + }, + "message": "8e4864769eed6c16d233a8f0a3ae8b273d0369f9acc79a562d171ab1b132e1b8" + } + }, + "description": "This is a test keystore that uses PBKDF2 to secure the secret.", + "scheme": "leanxmss", + "pubkey": "9023e9124c4c6a0af5f47af8c4d042dcb93c2341654d727c3d8ec48199d05b04", + "path": "m/5326/3600/1/0/0", + "uuid": "3e1f7a92-6c4d-4b8e-b5a1-9d2c0f6e7b34", + "version": 5 + }"#; + #[test] fn decrypts_the_scrypt_vector() { let keystore = Keystore::from_json(SCRYPT).expect("parses"); @@ -349,6 +578,57 @@ mod tests { assert_eq!(hex::encode(*secret), SECRET); } + #[test] + fn decrypts_and_verifies_erc8519_scrypt_and_pbkdf2_vectors() { + let scrypt = Keystore::from_json(ERC8519_SCRYPT).expect("parses"); + // v4-only `decrypt` refuses v5 so an account seed is never treated as a BLS key. + assert!(matches!( + scrypt.decrypt(PASSWORD), + Err(Error::KeystoreVersion(5)) + )); + let (seed, pubkey, path) = scrypt.decrypt_pq_verified(PASSWORD).expect("decrypts v5"); + assert_eq!(hex::encode(*seed), PQ_ACCOUNT_SEED); + assert_eq!(hex::encode(pubkey), PQ_PUBKEY); + assert_eq!( + path, + Some(PqAccountPath { + chain_id: 1, + role: PqRole::Validator, + account: 0, + }) + ); + + let pbkdf2 = Keystore::from_json(ERC8519_PBKDF2).expect("parses"); + let DecryptedKeystore::PqAccount { + account_seed, + pubkey: pbkdf2_pubkey, + path: pbkdf2_path, + } = pbkdf2.decrypt_any(PASSWORD).expect("decrypts v5") + else { + panic!("expected PqAccount"); + }; + assert_eq!(hex::encode(*account_seed), PQ_ACCOUNT_SEED); + assert_eq!(hex::encode(pbkdf2_pubkey), PQ_PUBKEY); + assert_eq!(pbkdf2_path, path); + + // Wrong password, unknown scheme, and tampered pubkey are refused. + assert!(matches!( + pbkdf2.decrypt_any("wrong"), + Err(Error::KeystoreBadPassword) + )); + let bad_scheme = Keystore::from_json( + &ERC8519_PBKDF2.replace("\"scheme\": \"leanxmss\"", "\"scheme\": \"unknown\""), + ) + .unwrap(); + assert!(bad_scheme.decrypt_any(PASSWORD).is_err()); + let bad_pubkey = Keystore::from_json(&ERC8519_PBKDF2.replace( + PQ_PUBKEY, + "9023e9124c4c6a0af5f47af8c4d042dcb93c2341654d727c3d8ec48199d05b05", + )) + .unwrap(); + assert!(bad_pubkey.decrypt_any(PASSWORD).is_err()); + } + #[test] fn rejects_a_wrong_password_before_decrypting() { let keystore = Keystore::from_json(SCRYPT).expect("parses"); @@ -362,7 +642,7 @@ mod tests { fn rejects_an_unsupported_version() { let json = SCRYPT.replace("\"version\": 4", "\"version\": 3"); let keystore = Keystore::from_json(&json).expect("parses"); - let err = keystore.decrypt(PASSWORD).expect_err("must reject"); + let err = keystore.decrypt_any(PASSWORD).expect_err("must reject"); assert!(matches!(err, Error::KeystoreVersion(3)), "got {err:?}"); } diff --git a/crates/validator/src/keys/store.rs b/crates/validator/src/keys/store.rs index 0e232bca9..fdf754379 100644 --- a/crates/validator/src/keys/store.rs +++ b/crates/validator/src/keys/store.rs @@ -5,19 +5,20 @@ use std::path::Path; use std::sync::{Arc, Weak}; use blst::min_pk::SecretKey; -use ethlambda_types::beacon::primitives::{BLS_PUBKEY_SIZE, BlsPubkey}; +use ethlambda_crypto::pq_keys::PqAccountPath; +use ethlambda_types::beacon::primitives::{BLS_PUBKEY_SIZE, BlsPubkey, XmssPubkey}; use tracing::info; use zeroize::Zeroizing; use crate::beacon_node::dto::{encode_hex, parse_pubkey}; use crate::error::{Error, Result}; use crate::keys::definitions::{DEFINITIONS_FILE, SigningDefinition, ValidatorDefinitions}; -use crate::keys::keystore::Keystore; +use crate::keys::keystore::{DecryptedKeystore, Keystore}; use crate::keys::web3signer::Web3Signer; /// How one validator produces a signature. /// -/// Cheap to clone: both arms are an `Arc`, so a signing path can take a copy +/// Cheap to clone: every arm is an `Arc`, so a signing path can take a copy /// out of the store under a short read guard and sign after releasing it, /// which matters for the remote arm, whose signature is an HTTP round trip. /// @@ -29,8 +30,19 @@ use crate::keys::web3signer::Web3Signer; /// controls the key's lifetime in memory, not whether it can be printed. #[derive(Clone)] pub enum SigningMethod { - /// The secret key is held in this process, decrypted from a local keystore. + /// An EIP-2335 (v4) BLS secret key held in this process. LocalKeystore { secret_key: Arc }, + /// An ERC-8517 / ERC-8519 post-quantum account seed held in this process. + PqAccount { + account_seed: Arc>, + /// Declared 32-byte leanXMSS public key when decrypted from an + /// ERC-8519 keystore (verified in full when the leanXMSS key is loaded + /// or built), or `None` when derived directly from a mnemonic or + /// account-seed input. + declared_pubkey: Option<[u8; 32]>, + /// ERC-8517 path when known (`m/5326/3600///`). + path: Option, + }, /// The key is held by a Web3Signer, which signs on this client's behalf. Web3Signer { signer: Arc }, } @@ -204,13 +216,47 @@ impl ValidatorStore { // // `decrypt` yields a `Zeroizing<[u8; 32]>`, scrubbed on drop. Deref // it at the call below rather than copying it out. - let secret = keystore - .decrypt(password.trim_end_matches(['\n', '\r'])) + let decrypted = keystore + .decrypt_any(password.trim_end_matches(['\n', '\r'])) .map_err(|err| Error::Keystore { path: keystore_path.display().to_string(), reason: err.to_string(), })?; - self.insert_secret(&keystore_path.display().to_string(), &secret) + match decrypted { + DecryptedKeystore::Bls(secret) => { + self.insert_secret(&keystore_path.display().to_string(), &secret) + } + DecryptedKeystore::PqAccount { + account_seed, + pubkey, + path, + } => Ok(self.insert_pq_account( + BlsPubkey(XmssPubkey(pubkey).to_request_key().0), + account_seed, + Some(pubkey), + path, + )), + } + } + + /// Add one ERC-8517 / ERC-8519 post-quantum account seed under its + /// 48-byte request-key handle (`[0u8; 16] ++ xmss_pubkey_32`). + pub fn insert_pq_account( + &mut self, + pubkey: BlsPubkey, + account_seed: Zeroizing<[u8; 32]>, + declared_pubkey: Option<[u8; 32]>, + path: Option, + ) -> BlsPubkey { + self.validators.insert( + pubkey, + SigningMethod::PqAccount { + account_seed: Arc::new(account_seed), + declared_pubkey, + path, + }, + ); + pubkey } /// Add one secret key, deriving its public key. @@ -319,7 +365,7 @@ impl ValidatorStore { pub fn remote_url(&self, pubkey: &BlsPubkey) -> Option { match self.validators.get(pubkey)? { SigningMethod::Web3Signer { signer } => Some(signer.url().to_string()), - SigningMethod::LocalKeystore { .. } => None, + SigningMethod::LocalKeystore { .. } | SigningMethod::PqAccount { .. } => None, } } @@ -342,7 +388,7 @@ impl ValidatorStore { .iter() .filter_map(|(pubkey, method)| match method { SigningMethod::Web3Signer { signer } => Some((*pubkey, signer.url().to_string())), - SigningMethod::LocalKeystore { .. } => None, + SigningMethod::LocalKeystore { .. } | SigningMethod::PqAccount { .. } => None, }) .collect() } diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 4df0c2d0b..2cc1f54e3 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -186,6 +186,66 @@ pub struct ValidatorConfig { /// votes when its payload does, rather than only at their deadlines. See /// [`head_monitor`]. pub event_stream: bool, + + /// Optional ERC-8517 mnemonic + account-range derivation for PQ validators + /// or builders (`--pq-mnemonic`). + pub pq_mnemonic: Option, + + /// Optional file of ERC-8517 account seeds (`eth2-val-tools pq-seeds` JSON + /// lines / JSON list, or `0x`-hex lines) for PQ validators or builders + /// (`--pq-seeds-file`). + pub pq_seeds_file: Option, + + /// Optional comma-separated telemetry event families (`--telemetry-events`, + /// `pq` in `eth.telemetry/0.4`). + pub telemetry_events: Option, + + /// Client git commit reported in `pq.context`. + pub client_commit: String, +} + +/// ERC-8517 mnemonic derivation parameters for `ethlambda validator`. +#[derive(Clone)] +pub struct PqMnemonicConfig { + pub mnemonic: zeroize::Zeroizing, + pub passphrase: zeroize::Zeroizing, + /// Explicit `chain_id`, or `None` to use the beacon node's + /// `DEPOSIT_CHAIN_ID`. + pub chain_id: Option, + pub role: ethlambda_crypto::pq_keys::PqRole, + pub account_min: u64, + pub account_max: u64, +} + +impl PqMnemonicConfig { + pub fn new( + mnemonic: String, + passphrase: String, + chain_id: Option, + role: ethlambda_crypto::pq_keys::PqRole, + account_min: u64, + account_max: u64, + ) -> Self { + Self { + mnemonic: zeroize::Zeroizing::new(mnemonic), + passphrase: zeroize::Zeroizing::new(passphrase), + chain_id, + role, + account_min, + account_max, + } + } +} + +impl std::fmt::Debug for PqMnemonicConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PqMnemonicConfig") + .field("chain_id", &self.chain_id) + .field("role", &self.role) + .field("account_min", &self.account_min) + .field("account_max", &self.account_max) + .finish_non_exhaustive() + } } /// Builder proposals: register each validator with the beacon node's builder @@ -279,7 +339,7 @@ pub async fn run(config: ValidatorConfig, stop: impl Future> = None; + let current_slot = clock.now().unwrap_or(0); + if pq_epoch != ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH { + let candidates = collect_pq_candidates(&store, &config, spec.deposit_chain_id).await?; + if !candidates.is_empty() { + let count = candidates.len(); + let started = std::time::Instant::now(); + pq::use_tree_store(&config.validators_dir); + let stored_by_param = pq::stored_tree_paths_by_param(&config.validators_dir); + let mut unstored: Vec<(usize, [u8; 32])> = Vec::new(); + let mut stored_count = 0usize; + for (idx, candidate) in candidates.iter().enumerate() { + let has_stored = match candidate.existing_handle { + Some(handle) => pq::has_stored_trees(&config.validators_dir, &handle), + None => stored_by_param.contains_key( + ðlambda_crypto::pq_keys::xmss_public_param(&candidate.seed), + ), + }; + if has_stored { + stored_count += 1; + } else { + unstored.push((idx, *candidate.seed)); + } + } + let cache = match &config.xmss_cache_url { + Some(source) if !unstored.is_empty() => { + load_xmss_cache(beacon_node.as_ref(), &unstored, source.clone()).await + } + _ => HashMap::new(), + }; + info!( + count, + pq_epoch, + stored_trees = stored_count, + cache_records = cache.len(), + "Deriving the validators' PQ keys (ERC-8517)" + ); + let outcomes = tokio::task::spawn_blocking(move || { + use rayon::prelude::*; + candidates + .into_par_iter() + .enumerate() + .map(|(idx, candidate)| { + let stored_hint = candidate + .existing_handle + .is_none() + .then(|| { + let param = + ethlambda_crypto::pq_keys::xmss_public_param(&candidate.seed); + stored_by_param.get(¶m).map(PathBuf::as_path) + }) + .flatten(); + let (handle, derived) = pq::derive_and_register_account( + &candidate.seed, + candidate.role, + candidate.declared_pubkey, + candidate.existing_handle, + stored_hint, + current_slot, + cache.get(&idx), + ) + .map_err(|reason| Error::Keystore { + path: candidate.origin.clone(), + reason, + })?; + if derived.source == pq::KeySource::CacheRefused { + warn!( + pubkey = %crate::beacon_node::dto::encode_hex(&handle.0), + "The leanXMSS cache record is not this key's; built it instead" + ); + } + Ok((handle, candidate, derived)) + }) + .collect::>>() + }) + .await + .map_err(|err| Error::Io { + path: "PQ key derivation".into(), + source: std::io::Error::other(err.to_string()), + })??; + + let mut validator_pubkeys = Vec::with_capacity(outcomes.len()); + { + let mut store_guard = store.write().await; + for (handle, candidate, _) in &outcomes { + if candidate.existing_handle.is_none() { + store_guard.insert_pq_account( + *handle, + candidate.seed.clone(), + candidate.declared_pubkey, + candidate.path, + ); + } + if candidate.role == ethlambda_crypto::pq_keys::PqRole::Validator { + validator_pubkeys.push(*handle); + } + } + metrics::set_validators_loaded(store_guard.len() as u64); + } + let tally = |wanted| { + outcomes + .iter() + .filter(|(_, _, derived)| derived.source == wanted) + .count() + }; + let slowest = |time: fn(&pq::Derived) -> std::time::Duration| { + outcomes + .iter() + .map(|(_, _, derived)| time(derived)) + .max() + .unwrap_or_default() + .as_millis() as u64 + }; + info!( + count, + stored = tally(pq::KeySource::Stored), + cached = tally(pq::KeySource::Cached), + built = tally(pq::KeySource::Built) + tally(pq::KeySource::CacheRefused), + refused = tally(pq::KeySource::CacheRefused), + trees_built = outcomes + .iter() + .map(|(_, _, derived)| derived.trees_built) + .sum::(), + slowest_key_ms = slowest(|derived| derived.key_time), + slowest_trees_ms = slowest(|derived| derived.tree_time), + elapsed_ms = started.elapsed().as_millis() as u64, + "Derived the validators' PQ keys" + ); + let kept = + pq::open_leaf_record(&config.validators_dir, current_slot).map_err(|source| { + Error::Io { + path: config + .validators_dir + .join(pq::LEAF_RECORD_FILE) + .display() + .to_string(), + source, + } + })?; + info!(leaves = kept, "Opened the PQ leaf record"); + vrf_startup = Some(validator_pubkeys); + } else if config.pq_mnemonic.is_some() || config.pq_seeds_file.is_some() { + warn!("PQ seed source yielded zero accounts; the client will idle"); + } + } else if config.pq_mnemonic.is_some() || config.pq_seeds_file.is_some() { + return Err(Error::Keystore { + path: "--pq-mnemonic / --pq-seeds-file".to_string(), + reason: "post-quantum seed flags were given, but the beacon node's network does not schedule the PQ fork" + .to_string(), + }); + } + // After the beacon node names the chain, which the record must belong to, // and before any service that signs exists. Every loaded key must already // have a record, unless the operator said otherwise. That includes a key @@ -392,127 +633,16 @@ pub async fn run(config: ValidatorConfig, stop: impl Future = { - let store = store.read().await; - store - .pubkeys() - .into_iter() - .filter_map(|pubkey| match store.signer(&pubkey)? { - keys::store::SigningMethod::LocalKeystore { secret_key } => { - Some((pubkey, secret_key.to_bytes())) - } - // The PQ keys derive from the BLS secret, which a remote - // signer never hands over: such a validator has no PQ key. - keys::store::SigningMethod::Web3Signer { .. } => None, - }) - .collect() - }; - let count = secrets.len(); - let pubkeys: Vec = secrets.iter().map(|(pubkey, _)| *pubkey).collect(); - let current_slot = clock.now().unwrap_or(0); - let started = std::time::Instant::now(); - // The trees an earlier start built are read back first; only the keys - // with none stored need `xmss_cache_url`, and so the registry wait. - pq::use_tree_store(&config.validators_dir); - let (stored, unstored): (Vec<_>, Vec<_>) = secrets - .iter() - .partition(|(pubkey, _)| pq::has_stored_trees(&config.validators_dir, pubkey)); - let unstored: Vec<(BlsPubkey, [u8; 32])> = unstored.into_iter().copied().collect(); - let cache = match &config.xmss_cache_url { - Some(source) if !unstored.is_empty() => { - load_xmss_cache(beacon_node.as_ref(), &unstored, source.clone()).await - } - _ => HashMap::new(), - }; - info!( - count, - pq_epoch, - stored_trees = stored.len(), - cache_records = cache.len(), - "Deriving the validators' PQ keys" - ); - // leanVM derives a key on one thread, so the keys go across rayon's - // pool: one per core, not one OS thread per validator. - let derived = tokio::task::spawn_blocking(move || { - use rayon::prelude::*; - secrets - .par_iter() - .map(|(pubkey, secret)| { - let derived = - pq::derive_and_register(*pubkey, secret, current_slot, cache.get(pubkey)); - if derived.source == pq::KeySource::CacheRefused { - warn!( - pubkey = %crate::beacon_node::dto::encode_hex(&pubkey.0), - "The leanXMSS cache record is not this key's; built it instead" - ); - } - derived - }) - .collect::>() - }) - .await - .map_err(|err| Error::Io { - path: "PQ key derivation".into(), - source: std::io::Error::other(err.to_string()), - })?; - let tally = |wanted| { - derived - .iter() - .filter(|derived| derived.source == wanted) - .count() - }; - let slowest = |time: fn(&pq::Derived) -> std::time::Duration| { - derived - .iter() - .map(time) - .max() - .unwrap_or_default() - .as_millis() as u64 - }; - info!( - count, - stored = tally(pq::KeySource::Stored), - cached = tally(pq::KeySource::Cached), - built = tally(pq::KeySource::Built) + tally(pq::KeySource::CacheRefused), - refused = tally(pq::KeySource::CacheRefused), - trees_built = derived - .iter() - .map(|derived| derived.trees_built) - .sum::(), - slowest_key_ms = slowest(|derived| derived.key_time), - slowest_trees_ms = slowest(|derived| derived.tree_time), - elapsed_ms = started.elapsed().as_millis() as u64, - "Derived the validators' PQ keys" - ); - // Before any duty signs: the leaves a previous run signed stay spent. - let kept = - pq::open_leaf_record(&config.validators_dir, current_slot).map_err(|source| { - Error::Io { - path: config - .validators_dir - .join(pq::LEAF_RECORD_FILE) - .display() - .to_string(), - source, - } - })?; - info!(leaves = kept, "Opened the PQ leaf record"); + if let Some(validator_pubkeys) = vrf_startup { prepare_bottom_trees(clock.clone(), current_slot); - prepare_vrf_trees( - pubkeys, - config.validators_dir.clone(), - config.vrf_state_url.clone(), - beacon_node.clone(), - ); + if !validator_pubkeys.is_empty() { + prepare_vrf_trees( + validator_pubkeys, + config.validators_dir.clone(), + config.vrf_state_url.clone(), + beacon_node.clone(), + ); + } } // Every node's stream, read until `run` returns and `_monitor` with it. @@ -704,6 +834,7 @@ 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 +1058,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"); @@ -1990,11 +2134,260 @@ const RECORD_FETCHES: usize = 16; /// source that fails leaves those keys out, and [`pq::derive_and_register`] /// builds them. A record is only offered here; it is checked against the /// seed and the registered key when loaded. -async fn load_xmss_cache( +struct PqSeedCandidate { + origin: String, + seed: zeroize::Zeroizing<[u8; 32]>, + role: ethlambda_crypto::pq_keys::PqRole, + path: Option, + declared_pubkey: Option<[u8; 32]>, + existing_handle: Option, +} + +/// Gather and validate every ERC-8517 account seed from ERC-8519 keystores, +/// `--pq-mnemonic`, and `--pq-seeds-file`, refusing any seed, `chain_id`, +/// role or account index outside ERC-8517's bounds or belonging to a +/// different network (`deposit_chain_id`). +async fn collect_pq_candidates( + store: &RwLock, + config: &ValidatorConfig, + deposit_chain_id: u64, +) -> Result> { + use ethlambda_crypto::pq_keys::{ + HARDENED_OFFSET, PqAccountPath, account_seed, bip39_seed_with_passphrase, + }; + + let mut candidates = Vec::new(); + let mut bls_only_count = 0usize; + { + let store = store.read().await; + for pubkey in store.pubkeys() { + match store.signer(&pubkey) { + Some(keys::store::SigningMethod::PqAccount { + account_seed, + declared_pubkey, + path, + }) => { + if let Some(parsed) = path + && parsed.chain_id != deposit_chain_id + { + return Err(Error::Keystore { + path: crate::beacon_node::dto::encode_hex(&pubkey.0), + reason: format!( + "ERC-8519 keystore path is for chain_id {}, but the beacon node's DEPOSIT_CHAIN_ID is {deposit_chain_id}", + parsed.chain_id + ), + }); + } + candidates.push(PqSeedCandidate { + origin: crate::beacon_node::dto::encode_hex(&pubkey.0), + seed: (*account_seed).clone(), + role: keys::keystore::Keystore::pq_role(path), + path, + declared_pubkey, + existing_handle: Some(pubkey), + }); + } + Some(keys::store::SigningMethod::LocalKeystore { .. }) => { + bls_only_count += 1; + } + Some(keys::store::SigningMethod::Web3Signer { .. }) | None => {} + } + } + } + if bls_only_count > 0 { + warn!( + bls_keystores = bls_only_count, + "Loaded EIP-2335 (v4) BLS keystores on a network scheduling the PQ fork: \ + PQ keys derive from ERC-8517 account seeds (ERC-8519 v5 keystores, --pq-mnemonic, \ + or --pq-seeds-file), never from BLS secret keys" + ); + } + + if let Some(mnemonic_cfg) = &config.pq_mnemonic { + let chain_id = mnemonic_cfg.chain_id.unwrap_or(deposit_chain_id); + if !(1..HARDENED_OFFSET).contains(&chain_id) { + return Err(Error::Keystore { + path: "--pq-chain-id".to_string(), + reason: format!("chain_id {chain_id} is outside [1, {HARDENED_OFFSET})"), + }); + } + if chain_id != deposit_chain_id { + return Err(Error::Keystore { + path: "--pq-chain-id".to_string(), + reason: format!( + "configured PQ chain_id {chain_id} disagrees with the beacon node's DEPOSIT_CHAIN_ID ({deposit_chain_id})" + ), + }); + } + if mnemonic_cfg.account_min > mnemonic_cfg.account_max { + return Err(Error::Keystore { + path: "--pq-account-min / --pq-account-max".to_string(), + reason: format!( + "account_min ({}) exceeds account_max ({})", + mnemonic_cfg.account_min, mnemonic_cfg.account_max + ), + }); + } + if mnemonic_cfg.account_max > HARDENED_OFFSET { + return Err(Error::Keystore { + path: "--pq-account-max".to_string(), + reason: format!( + "account_max ({}) exceeds ERC-8517's limit ({HARDENED_OFFSET})", + mnemonic_cfg.account_max + ), + }); + } + let root_seed = zeroize::Zeroizing::new(bip39_seed_with_passphrase( + &mnemonic_cfg.mnemonic, + &mnemonic_cfg.passphrase, + )); + for account in mnemonic_cfg.account_min..mnemonic_cfg.account_max { + let path = PqAccountPath::new(chain_id, mnemonic_cfg.role, account).map_err(|err| { + Error::Keystore { + path: "--pq-mnemonic".to_string(), + reason: err.to_string(), + } + })?; + let derived = + account_seed(&*root_seed, chain_id, mnemonic_cfg.role, account).map_err(|err| { + Error::Keystore { + path: path.to_string(), + reason: err.to_string(), + } + })?; + candidates.push(PqSeedCandidate { + origin: path.to_string(), + seed: zeroize::Zeroizing::new(derived), + role: mnemonic_cfg.role, + path: Some(path), + declared_pubkey: None, + existing_handle: None, + }); + } + } + + if let Some(seeds_path) = &config.pq_seeds_file { + let parsed = parse_pq_seeds_file(seeds_path, deposit_chain_id)?; + candidates.extend(parsed); + } + + Ok(candidates) +} + +#[derive(serde::Deserialize)] +struct RawSeedEntry { + #[serde(default)] + path: Option, + account_seed: String, +} + +fn parse_pq_seeds_file( + path: &std::path::Path, + deposit_chain_id: u64, +) -> Result> { + use ethlambda_crypto::pq_keys::{PqAccountPath, PqRole}; + + let display = path.display().to_string(); + let contents = + zeroize::Zeroizing::new(std::fs::read_to_string(path).map_err(|source| Error::Io { + path: display.clone(), + source, + })?); + let trimmed = contents.trim(); + if trimmed.is_empty() { + return Ok(Vec::new()); + } + let decode_seed = |hex_str: &str, entry_origin: &str| -> Result> { + let bytes = hex::decode(hex_str.trim().trim_start_matches("0x")).map_err(|err| { + Error::Keystore { + path: entry_origin.to_string(), + reason: format!("account_seed is not valid hex: {err}"), + } + })?; + let array: [u8; 32] = bytes.try_into().map_err(|got: Vec| Error::Keystore { + path: entry_origin.to_string(), + reason: format!("account_seed must be 32 bytes, got {} bytes", got.len()), + })?; + Ok(zeroize::Zeroizing::new(array)) + }; + let build_candidate = |raw_path: Option, + raw_seed: &str, + index: usize| + -> Result { + let origin = format!("{display}#{index}"); + let parsed_path = match raw_path.as_deref() { + None | Some("") => None, + Some(text) => { + let parsed = PqAccountPath::parse(text).map_err(|err| Error::Keystore { + path: origin.clone(), + reason: err.to_string(), + })?; + if parsed.chain_id != deposit_chain_id { + return Err(Error::Keystore { + path: origin, + reason: format!( + "seed path {parsed} is for chain_id {}, expected DEPOSIT_CHAIN_ID {deposit_chain_id}", + parsed.chain_id + ), + }); + } + Some(parsed) + } + }; + let role = parsed_path.map_or(PqRole::Validator, |p| p.role); + let seed = decode_seed(raw_seed, &origin)?; + Ok(PqSeedCandidate { + origin, + seed, + role, + path: parsed_path, + declared_pubkey: None, + existing_handle: None, + }) + }; + + if trimmed.starts_with('[') { + let entries: Vec = + serde_json::from_str(trimmed).map_err(|err| Error::Keystore { + path: display.clone(), + reason: format!("invalid pq-seeds JSON list: {err}"), + })?; + return entries + .into_iter() + .enumerate() + .map(|(idx, entry)| build_candidate(entry.path, &entry.account_seed, idx)) + .collect(); + } + + let mut out = Vec::new(); + for (line_no, line) in contents.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if line.starts_with('{') { + let entry: RawSeedEntry = + serde_json::from_str(line).map_err(|err| Error::Keystore { + path: format!("{display}:{}", line_no + 1), + reason: format!("invalid pq-seeds JSON line: {err}"), + })?; + out.push(build_candidate( + entry.path, + &entry.account_seed, + line_no + 1, + )?); + } else { + out.push(build_candidate(None, line, line_no + 1)?); + } + } + Ok(out) +} + +async fn load_xmss_cache( beacon_node: &B, - keys: &[(BlsPubkey, [u8; 32])], + keys: &[(K, [u8; 32])], source: String, -) -> HashMap { +) -> HashMap { use futures_util::StreamExt as _; let mut registry = None; @@ -2026,9 +2419,9 @@ async fn load_xmss_cache( ); } let file = pq::RecordFile::new(reqwest::Client::new(), source, pq::XMSS_CACHE_RECORD_SIZE); - let fetch = |(pubkey, (index, registered)): (BlsPubkey, (u64, [u8; 32]))| { + let fetch = |(handle, (index, registered)): (K, (u64, [u8; 32]))| { let file = &file; - async move { (pubkey, index, registered, file.fetch(index).await) } + async move { (handle, index, registered, file.fetch(index).await) } }; let mut wanted = indices.into_iter(); // One record first, alone: a server that ignores the range sends the @@ -3620,4 +4013,78 @@ mod tests { ); assert_eq!(before.elapsed(), std::time::Duration::ZERO); } + + #[tokio::test] + async fn collect_pq_candidates_derives_erc8517_and_refuses_bls_or_wrong_network() { + use ethlambda_crypto::pq_keys::PqRole; + + let dir = tempfile::tempdir().unwrap(); + let seeds_path = dir.path().join("seeds.jsonl"); + std::fs::write( + &seeds_path, + r#"{"path":"m/5326/3600/3151908/1/0","account_seed":"0x1111111111111111111111111111111111111111111111111111111111111111"}"#, + ) + .unwrap(); + + let mut store = ValidatorStore::new(); + // A BLS v4 key in the store must never be hashed into a PQ seed. + store + .insert_secret("bls-test", &[1u8; 32]) + .expect("valid bls scalar"); + let store = RwLock::new(store); + + let mnemonic = "giant issue aisle success illegal bike spike question tent bar rely \ + arctic volcano long crawl hungry vocal artwork sniff fantasy very lucky \ + have athlete"; + let config = ValidatorConfig { + beacon_nodes: vec!["http://localhost:5052".into()], + validators_dir: dir.path().to_path_buf(), + secrets_dir: dir.path().join("secrets"), + metrics: "127.0.0.1:0".parse().unwrap(), + graffiti: Bytes32::ZERO, + suggested_fee_recipient: None, + keymanager: None, + web3signer_url: None, + gas_limit: None, + builder: None, + builder_min_bid: 0, + init_slashing_protection: false, + vrf_state_url: None, + doppelganger_protection: false, + xmss_cache_url: None, + event_stream: false, + pq_mnemonic: Some(PqMnemonicConfig::new( + mnemonic.into(), + String::new(), + None, + PqRole::Validator, + 0, + 2, + )), + pq_seeds_file: Some(seeds_path), + telemetry_events: None, + client_commit: String::new(), + }; + + let candidates = collect_pq_candidates(&store, &config, 3_151_908) + .await + .expect("valid ERC-8517 candidates"); + assert_eq!( + candidates.len(), + 3, + "2 mnemonic validators + 1 builder seed" + ); + assert_eq!( + hex::encode(*candidates[0].seed), + "55fbb215782cdb01ef92bcbdea7b437a5515b505513175c63c89155c75204f8e" + ); + assert_eq!( + hex::encode(*candidates[1].seed), + "fd3783c0cad0af04cbca453c255fae510bb581569e125798d321be01fb45de13" + ); + assert_eq!(candidates[2].role, PqRole::Builder); + + // Wrong network chain_id is refused rather than reused across networks. + assert!(collect_pq_candidates(&store, &config, 1).await.is_err()); + } } diff --git a/crates/validator/src/pq.rs b/crates/validator/src/pq.rs index 87a5f7b09..c08313feb 100644 --- a/crates/validator/src/pq.rs +++ b/crates/validator/src/pq.rs @@ -1,11 +1,10 @@ //! The validator client on the PQ fork (`specs/_features/pq/validator.md`). //! -//! At PQ a validator signs with leanXMSS and reveals RANDAO with a VRF proof, -//! both derived from its BLS signing key the way the PQ devnet's genesis -//! tooling registered them (`ethlambda_crypto::pq_keys`), so a keystore is -//! still all a validator needs. This module holds that material per key, -//! translates between a validator's BLS key and the form the PQ registry names -//! it by, and signs at the leaf each message is assigned. +//! At PQ (`pq-devnet-2` and later) a validator signs with leanXMSS and reveals +//! RANDAO with a VRF proof, both expanded from an ERC-8517 account seed +//! (`ethlambda_crypto::pq_keys`) loaded from an ERC-8519 (v5) keystore, a +//! mnemonic + chain ID + account range, or an account-seed file — never from a +//! BLS secret key. Builders derive at role `1` and hold no VRF seed. //! //! **The VRF tree.** The specification's tree has a leaf for each of `2^31` //! slots, and every one must be hashed to reach the root a validator @@ -124,6 +123,44 @@ pub fn has_stored_trees(validators_dir: &Path, pubkey: &BlsPubkey) -> bool { xmss_tree_path(validators_dir, pubkey).is_file() } +/// Index every stored tree file under `validators_dir` by the last 16 bytes +/// of the 48-byte hex pubkey in its filename (`0x<96-hex>.bin`), which equals +/// the key's `xmss_public_param` for request-form keys (`[0u8; 16] ++ pubkey`). +/// Lets mnemonic- and seed-derived accounts find their stored trees before +/// their top-tree root is known. +pub fn stored_tree_paths_by_param(validators_dir: &Path) -> HashMap<[u8; 16], PathBuf> { + let Ok(entries) = std::fs::read_dir(validators_dir.join(XMSS_TREE_DIRECTORY)) else { + return HashMap::new(); + }; + let mut by_param = HashMap::new(); + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_file() { + continue; + } + let Some(stem) = path + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| name.strip_prefix("0x")) + .and_then(|name| name.strip_suffix(".bin")) + else { + continue; + }; + if stem.len() != 96 { + continue; + } + let Ok(bytes) = hex::decode(stem) else { + continue; + }; + if bytes[..16] == [0u8; 16] + && let Ok(param) = <[u8; 16]>::try_from(&bytes[32..48]) + { + by_param.insert(param, path); + } + } + by_param +} + fn xmss_tree_path(validators_dir: &Path, pubkey: &BlsPubkey) -> PathBuf { validators_dir .join(XMSS_TREE_DIRECTORY) @@ -249,11 +286,12 @@ fn store_trees_at(path: &Path, key: &PqKey) { } } -/// A validator's PQ key material. +/// A validator's or builder's PQ key material. pub struct PqKey { /// leanVM's key: it caches the last few bottom trees it signed in. xmss: LeanXmssExpandedSecretKey, - vrf_seed: vrf::Node, + /// `Some` for a validator (`PqRole::Validator`), `None` for a builder. + vrf_seed: Option, /// Empty until [`prepare_vrf_tree`] has read or hashed the tree. vrf: OnceLock, /// The 48-byte form the PQ registry names the validator by. @@ -465,52 +503,93 @@ pub struct Derived { pub tree_time: Duration, } -/// Derives and registers the PQ key of the validator whose BLS key is -/// `pubkey` and secret key `secret` (32 bytes, big-endian, as a keystore -/// holds it). -/// -/// With trees an earlier start stored ([`use_tree_store`]), or a `cached` -/// record that is this key's, the key loads in milliseconds; stored trees -/// come first, since they hold the bottom trees the key built since genesis. -/// Otherwise it is built: slow, and on the calling thread alone, leanVM's key -/// generation (about 2.4 s). Either way the bottom trees its next attestation -/// and per-slot signatures fall in are then built if the key lacks them -/// (about 2.5 s each), and the key's trees are stored when anything was -/// loaded from elsewhere or built. Run it off the async runtime, and spread -/// many keys across cores. -/// -/// The key signs from here on. Its VRF tree, which only a proposal reads, is -/// [`prepare_vrf_tree`]'s to supply. +/// Derives and registers a validator's PQ key from its 32-byte ERC-8517 +/// `account_seed` under handle `pubkey`. pub fn derive_and_register( pubkey: BlsPubkey, - secret: &[u8; 32], + account_seed: &[u8; 32], current_slot: Slot, cached: Option<&XmssCacheRecord>, ) -> Derived { + derive_and_register_account( + account_seed, + pq_keys::PqRole::Validator, + None, + Some(pubkey), + None, + current_slot, + cached, + ) + .expect("unchecked declared_pubkey cannot fail") + .1 +} + +/// Derives and registers an ERC-8517 account's PQ key, verifying +/// `declared_pubkey` (when supplied by an ERC-8519 keystore) against all 32 +/// bytes of the derived leanXMSS public key, and returning `(handle, Derived)` +/// where `handle` is `pubkey_override` or `BlsPubkey([0u8; 16] ++ xmss_pubkey)`. +pub fn derive_and_register_account( + account_seed: &[u8; 32], + role: pq_keys::PqRole, + declared_pubkey: Option<[u8; 32]>, + pubkey_override: Option, + stored_path_hint: Option<&Path>, + current_slot: Slot, + cached: Option<&XmssCacheRecord>, +) -> Result<(BlsPubkey, Derived), String> { let started = Instant::now(); + let expected_pubkey = declared_pubkey + .as_ref() + .or_else(|| cached.map(|record| &record.registered)); let stored = tree_store().and_then(|validators_dir| { - let registered = cached.map(|record| &record.registered); - stored_key(&xmss_tree_path(validators_dir, &pubkey), secret, registered) + if let Some(pubkey) = pubkey_override { + stored_key( + &xmss_tree_path(validators_dir, &pubkey), + account_seed, + expected_pubkey, + ) + } else if let Some(path) = stored_path_hint { + stored_key(path, account_seed, expected_pubkey) + } else { + None + } }); + let usable_cache = cached + .filter(|record| declared_pubkey.is_none_or(|declared| declared == record.registered)); + let cache_rejected_by_declaration = cached.is_some() && usable_cache.is_none(); let (xmss, source) = match stored { Some(xmss) => (xmss, KeySource::Stored), None => { - let loaded = cached.map(|record| { + let loaded = usable_cache.map(|record| { let registered = leanvm_lean_xmss::LeanXmssPublicKey::from_bytes(&record.registered); - let seed = pq_keys::xmss_seed(secret); + let seed = pq_keys::xmss_seed(account_seed); LeanXmssExpandedSecretKey::from_cache_bytes(&seed, ®istered, &record.bytes) }); match loaded { Some(Some(xmss)) => (xmss, KeySource::Cached), - Some(None) => (pq_keys::xmss_key(secret), KeySource::CacheRefused), - None => (pq_keys::xmss_key(secret), KeySource::Built), + Some(None) => (pq_keys::xmss_key(account_seed), KeySource::CacheRefused), + None if cache_rejected_by_declaration => { + (pq_keys::xmss_key(account_seed), KeySource::CacheRefused) + } + None => (pq_keys::xmss_key(account_seed), KeySource::Built), } } }; + let actual_pubkey = xmss.public_key().to_bytes(); + if let Some(declared) = declared_pubkey + && actual_pubkey != declared + { + return Err(format!( + "keystore declares leanXMSS pubkey 0x{} but its decrypted account seed derives 0x{}", + hex::encode(declared), + hex::encode(actual_pubkey) + )); + } let key_time = started.elapsed(); let mut request_key = [0u8; 48]; - request_key[16..].copy_from_slice(&xmss.public_key().to_bytes()); + request_key[16..].copy_from_slice(&actual_pubkey); + let pubkey = pubkey_override.unwrap_or(BlsPubkey(request_key)); // Warm the two bottom trees duties sign in, so the first signature of each // kind does not pay for one at its deadline. Later ones are // `prepare_bottom_tree`'s. @@ -535,17 +614,19 @@ pub fn derive_and_register( debug!( pubkey = %encode_pubkey(&pubkey), ?source, + role = %role, key_ms = key_time.as_millis() as u64, trees_built, tree_ms = tree_time.as_millis() as u64, "Derived a validator's PQ key" ); + let (_, vrf_seed) = pq_keys::seeds_for_role(account_seed, role); let key = Arc::new(PqKey { xmss, - vrf_seed: pq_keys::vrf_seed(secret), + vrf_seed, vrf: OnceLock::new(), request_key, - storing: Mutex::new(tree_mac_key(secret)), + storing: Mutex::new(tree_mac_key(account_seed)), }); if source != KeySource::Stored || trees_built > 0 { store_trees(&pubkey, &key); @@ -553,12 +634,15 @@ pub fn derive_and_register( let mut registry = registry().write().expect("PQ key registry poisoned"); registry.by_request.insert(request_key, pubkey); registry.by_bls.insert(pubkey, key); - Derived { - source, - key_time, - trees_built, - tree_time, - } + Ok(( + pubkey, + Derived { + source, + key_time, + trees_built, + tree_time, + }, + )) } /// The longest [`prepare_tree`] can take and still have found the tree in @@ -585,22 +669,22 @@ fn encode_pubkey(pubkey: &BlsPubkey) -> String { /// public parameter (its request form's last 16 bytes) is the one the key's /// seed gives. What the leanXMSS cache is looked up by, before any key is /// built. A key with no such entry is left out. -pub fn indices_by_public_param( - keys: &[(BlsPubkey, [u8; 32])], +pub fn indices_by_public_param( + keys: &[(K, [u8; 32])], registry: &[(u64, [u8; 48])], -) -> HashMap { - let wanted: HashMap<[u8; 16], BlsPubkey> = keys +) -> HashMap { + let wanted: HashMap<[u8; 16], K> = keys .iter() - .map(|(pubkey, secret)| (pq_keys::xmss_public_param(secret), *pubkey)) + .map(|(handle, account_seed)| (pq_keys::xmss_public_param(account_seed), *handle)) .collect(); registry .iter() .filter(|(_, request)| request[..16] == [0; 16]) .filter_map(|(index, request)| { let param: [u8; 16] = request[32..].try_into().expect("16 bytes"); - let pubkey = wanted.get(¶m)?; + let handle = wanted.get(¶m)?; let registered = request[16..].try_into().expect("32 bytes"); - Some((*pubkey, (*index, registered))) + Some((*handle, (*index, registered))) }) .collect() } @@ -807,10 +891,11 @@ fn store_vrf_tree(path: &Path, tree: &vrf::VrfTree) { /// Blocking: checking a stored tree hashes one `2^16`-leaf subtree. pub fn restore_vrf_tree(pubkey: &BlsPubkey, validators_dir: &Path) -> Option { let key = key(pubkey)?; + let vrf_seed = key.vrf_seed?; if key.vrf.get().is_some() { return Some(VrfTreeSource::Held); } - let tree = stored_vrf_tree(&vrf_tree_path(validators_dir, pubkey), key.vrf_seed)?; + let tree = stored_vrf_tree(&vrf_tree_path(validators_dir, pubkey), vrf_seed)?; let _ = key.vrf.set(tree); Some(VrfTreeSource::Stored) } @@ -827,8 +912,8 @@ pub fn adopt_vrf_state( validators_dir: &Path, ) -> Result<(), VrfStateError> { let key = key(pubkey).ok_or(VrfStateError::UnknownValidator)?; - let tree = - vrf::VrfTree::from_state_record(key.vrf_seed, record).map_err(VrfStateError::Invalid)?; + let vrf_seed = key.vrf_seed.ok_or(VrfStateError::UnknownValidator)?; + let tree = vrf::VrfTree::from_state_record(vrf_seed, record).map_err(VrfStateError::Invalid)?; store_vrf_tree(&vrf_tree_path(validators_dir, pubkey), &tree); let _ = key.vrf.set(tree); Ok(()) @@ -932,7 +1017,8 @@ pub fn prepare_vrf_tree(pubkey: &BlsPubkey, validators_dir: &Path) -> Option 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/signing.rs b/crates/validator/src/signing.rs index c220f5df1..5df75b047 100644 --- a/crates/validator/src/signing.rs +++ b/crates/validator/src/signing.rs @@ -535,6 +535,11 @@ impl SigningContext { let bytes: [u8; BLS_SIGNATURE_SIZE] = signature.to_bytes(); Ok(BlsSignature(bytes)) } + SigningMethod::PqAccount { .. } => Err(Error::Signing { + pubkey: *pubkey, + reason: "a post-quantum (ERC-8517 / ERC-8519) account holds no BLS signing key" + .to_string(), + }), SigningMethod::Web3Signer { signer } => { // Web3Signer's `BLOCK_V2` takes the full block before // bellatrix and the header only from bellatrix on, and this 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..0536e9424 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -68,7 +68,8 @@ 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; aggregators staggered by seat; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | +| Validator client | `ethlambda_validator::pq` and the duty services | ERC-8517 account seeds (`m/5326/3600///`) loaded from ERC-8519 v5 `"leanxmss"` keystores, `--pq-mnemonic`, or `--pq-seeds-file`; 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.4` 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 | @@ -268,23 +269,22 @@ 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 `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 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. +on mainnet, 4 on minimal), unless the network's `config.yaml` defines +`X_COMMITTEE_COUNTS` (`ethereum/consensus-specs#5879`, pq-devnet-2): a non-empty +list of positive committee-count caps, each at most `MAX_COMMITTEES_PER_SLOT_PQ`, +cycled across 8-epoch stages (`X_COMMITTEE_COUNTS[(epoch // 8) % len]`) so a +single devnet exercises multiple committee geometries (`[16, 8, 4, 2, 1]`). +When `X_COMMITTEE_COUNTS` is empty or omitted, the node falls back to +`X_MAX_COMMITTEE_COUNT_PER_SLOT` (`network::select_committee_cap`). For a +PQ-from-genesis network (`PQ_FORK_EPOCH == 0`), startup verifies that active +validators at genesis can sustain every configured cap +(`active_validators // SLOTS_PER_EPOCH // TARGET_COMMITTEE_SIZE >= max_cap`) +and that `genesis.ssz`'s `aggregation_committee_window` matches epoch 0..=2's +committee counts; resuming a data directory refuses any change to either +`X_MAX_COMMITTEE_COUNT_PER_SLOT` or `X_COMMITTEE_COUNTS`. Gossipsub peer scoring +updates expected aggregators per epoch from the active stage's committee count, +and `GET /eth/v1/config/spec` serializes `X_COMMITTEE_COUNTS` as decimal strings +when non-empty. Aggregators are no longer self-selected: each beacon committee has an aggregation committee of up to `AGGREGATORS_PER_COMMITTEE` validators sampled @@ -330,28 +330,38 @@ PQ, and take the delay from the state's fork ## Validator duties -The validator client keeps its BLS keystores and derives each validator's PQ -seeds from the BLS signing key at startup, the way ethereum-package's genesis -generator and Lighthouse's PQ branch do: the leanXMSS key grows from -`sha256("leanxmss-seed" || sk)` and the VRF tree from the VRF seed -`sha256("vrf-seed" || sk)` (`ethlambda_crypto::pq_keys`). The specification -asks only that both seeds be secret; deriving them from the signing key is -the devnet's convention. The registry names a validator by its XMSS key, -which the Beacon API carries as its 32 bytes (a node from before that switch -sends the 48-byte request form instead; the client reads either). The client -looks its validators up by that key and maps it back to the BLS key it holds, -so a validator whose derived key is not the registered one resolves to no -index and gets no duties. It asks in two requests, the 48-byte ids (BLS keys -and request forms) and the 32-byte ones, since a node may refuse a whole -request holding the width it does not read: Lighthouse's PQ node refuses any -48-byte id. Key generation builds two bottom -trees per key, which takes under a minute for 16 validators. +From `pq-devnet-2` on, PQ keys no longer derive from BLS signing keys. Instead, +each account's 32-byte PQ seed derives via **ERC-8517** (`ethlambda_crypto::pq_keys`) +from a BIP-39 seed at the all-hardened path +`m/5326/3600///` (`HMAC-SHA512("Ethereum PQ seed", seed)`, +hardened child steps, then `HKDF-Expand-SHA256` with info `"leanXMSS key"` and, +for validator role `0`, `"VRF key"`; builder role `1` derives no VRF seed). +Out-of-range inputs (`seed` outside `16..=64` bytes, `chain_id` outside +`[1, 2^31)`, unsupported `role`, or `account >= 2^31`) are refused rather than +wrapped. + +`ethlambda validator` loads PQ validator seeds from three sources, refusing any +entry whose `chain_id` disagrees with the beacon node's `DEPOSIT_CHAIN_ID`: + +1. **ERC-8519 v5 `"leanxmss"` keystores** (`version: 5`, `scheme: "leanxmss"`, + 32-byte `secret` = ERC-8517 account seed, 64-byte `pubkey` = 32-byte + `XMSSPubkey` || 32-byte `vrf_root` or zeros) discovered in `--validators-dir` + or imported via `POST /eth/v1/keystores` (reported with their 48-byte + zero-padded request pubkey). +2. **`--pq-mnemonic` + `--pq-account-min`..`--pq-account-max`** (with optional + `--pq-passphrase`, `--pq-chain-id`, and `--pq-role`). +3. **`--pq-seeds-file`**, reading `eth2-val-tools pq-seeds` JSON / JSON-lines + entries or `0x`-prefixed 32-byte hex seeds. + +The registry names a validator by its XMSS key, which the Beacon API carries as +its 32 bytes (or 48-byte request form; the client reads either). Key generation +builds two bottom trees per key, which takes under a minute for 16 validators. A key's leanXMSS trees come from the first source that has them, and no duty starts until every key has the bottom trees its current duties sign in: 1. The trees a previous start stored in - `/pq_xmss_trees/0x.bin`: a format header, + `/pq_xmss_trees/0x.bin`: a format header, the key's public key, leanVM's `cache_to_bytes` (the top tree's cached level and those of the bottom trees it last used, at most four; about 25 KB), and an HMAC-SHA256 tag under a key derived from the XMSS seed, so @@ -560,15 +570,33 @@ What the package does for ethlambda on a PQ network: `--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. 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 + derived via ERC-8517 (`m/5326/3600//0/`). For another + mnemonic, or past the published 10000, `ethlambda pq-keys --mnemonic ... + --chain-id --count N --write-xmss-cache --output-dir keys` + writes the key file the generator reads (`xmss_pubkey_url`), the VRF states + (`vrf_state_url`), and the leanXMSS tree caches (`xmss_cache_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.4` structured PQ + measurement events (`pq.context`, `pq.aggregate_received`, + `pq.aggregate_processed`, `pq.aggregate_published`, `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.4 (registry 0.9.0): a duty's schedule names its nominal + publication target (`scheduled_publish_unix_ns`), a completion carries no + `late` flag, and a duty abandoned at its cutoff (`missed_deadline`) carries + that cutoff as `deadline_unix_ns`. 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 + `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..2fcffe113 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -165,7 +165,8 @@ 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 | +| `--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/pq-devnet-2 run, 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.4`). 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, @@ -374,7 +375,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. |---|---|---| | `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Tried in list order; the first that answers serves the request, so the order is a preference, not load balancing | | `--validators-dir` | required | Directory holding the EIP-2335 keystores and `validator_definitions.yml`, which also lists the keys a remote signer holds (see [Remote signing](#remote-signing-web3signer)). Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`, password in `--secrets-dir/<0xpubkey>`) are discovered and the file is written | -| `--secrets-dir` | required | Directory holding one password file per keystore, named after the validator's public key | +| `--secrets-dir` | `/secrets` | Directory holding one password file per keystore, named after the validator's public key. Optional when PQ keys come solely from `--pq-mnemonic` or `--pq-seeds-file` | | `--http-address` | `127.0.0.1` | Bind address for the metrics and keymanager servers | | `--metrics-port` | `5064` | Prometheus metrics port | | `--keymanager-port` | `5062` | Keymanager API port. Only bound with `--enable-keymanager` | @@ -390,6 +391,16 @@ 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) | +| `--vrf-state-url` | none | URL or path of precomputed 1028-byte VRF tree state records (`vrf_state_url`), indexed by validator index on a PQ network | +| `--xmss-cache-url` | none | URL or path of precomputed 14696-byte leanXMSS tree cache records (`xmss_cache_url`), indexed by validator index on a PQ network | +| `--pq-mnemonic` | none | BIP-39 mnemonic (or `ETHLAMBDA_PQ_MNEMONIC`) to derive ERC-8517 PQ account seeds at `m/5326/3600///`. Requires `--pq-account-max` | +| `--pq-passphrase` | empty | Optional BIP-39 passphrase (or `ETHLAMBDA_PQ_PASSPHRASE`) for `--pq-mnemonic` | +| `--pq-chain-id` | beacon node's `DEPOSIT_CHAIN_ID` | Explicit ERC-8517 `chain_id` (`1 <= chain_id < 2^31`) for `--pq-mnemonic`; refused if it disagrees with `DEPOSIT_CHAIN_ID` | +| `--pq-role` | `validator` | ERC-8517 role (`validator` or `builder`) for `--pq-mnemonic` | +| `--pq-account-min` | `0` | First ERC-8517 account index (inclusive, `< 2^31`) for `--pq-mnemonic` | +| `--pq-account-max` | none | Last ERC-8517 account index (exclusive, `<= 2^31`) for `--pq-mnemonic` | +| `--pq-seeds-file` | none | File of ERC-8517 account seeds (`eth2-val-tools pq-seeds` JSON / JSON lines, or one `0x`-prefixed 32-byte hex seed per line) | +| `--telemetry-events` | off | Comma-separated telemetry event families to export over OTLP Logs (`pq` in `eth.telemetry/0.4`), configured via standard `OTEL_*` environment variables | ### What it does today @@ -970,6 +981,25 @@ 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-keys` + +Generates ERC-8517 post-quantum genesis key files (`.bin`, `.vrf`, +and optionally `.xmss`) at `m/5326/3600///` for +a PQ-from-genesis devnet. Existing valid records in `--output-dir` are verified +and reused so interrupted runs resume cleanly. + +| Flag | Default | Description | +|------|---------|-------------| +| `--mnemonic` | required | BIP-39 mnemonic (or `ETHLAMBDA_PQ_KEYS_MNEMONIC`) | +| `--passphrase` | empty | Optional BIP-39 passphrase (or `ETHLAMBDA_PQ_KEYS_PASSPHRASE`) | +| `--chain-id` | required | Target network's EIP-155 / `DEPOSIT_CHAIN_ID` (`1 <= chain_id < 2^31`) | +| `--role` | `validator` | ERC-8517 role (`validator` or `builder`; builders write zeroed VRF roots and no `.vrf` file) | +| `--start` | `0` | First account index to generate (`--start + --count <= 2^31`) | +| `--count` | required | Number of accounts to generate (`>= 1`) | +| `--output-dir` | required | Output directory for `.bin`, `.vrf`, and `.xmss` | +| `--name` | `sha256("leanxmss-erc8517-keys" \|\| chain_id_be8 \|\| seed)[..8]` | Override base file stem `` | +| `--write-xmss-cache` | `false` | Also write `.xmss` (`14696` bytes per index: top tree plus genesis attestation and per-slot bottom trees) | + ## `pq-prover-check` Proves and verifies one PQ-fork aggregate with leanVM on the machine it runs diff --git a/docs/metrics.md b/docs/metrics.md index a0578e26a..3eeb71579 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_published`, `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.