From 445e707679122a62da5e903b3ab00165768c727a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:36:56 -0300 Subject: [PATCH 1/4] feat(validator): --network, to hold every beacon node to a named network --- CLAUDE.md | 9 +- README.md | 1 + bin/ethlambda/src/validator.rs | 101 +++++- crates/validator/src/beacon_node/fallback.rs | 75 +++-- crates/validator/src/chain_check.rs | 317 ++++++++++++++++++- crates/validator/src/lib.rs | 21 +- docs/cli.md | 19 +- 7 files changed, 497 insertions(+), 46 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f621ef5f4..44cdc1e93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -967,7 +967,14 @@ transitions are in `ethlambda-types`, per the section above. Nothing above unguarded. The client checks every beacon node against the chain it runs on (`chain_check`, `FallbackBeaconNode::establish`/`check_nodes`): the reference is the first node that answers at startup (startup waits, retrying every 2 s, - while none does), and a node whose genesis, preset, slot + while none does). Optional `--network` (resolved by the binary's `network` + module, as `beacon --network` is, into a `chain_check::ExpectedNetwork`) + narrows that to the first node on the named network by + `first_identity_difference` (preset, genesis, slot duration, genesis fork + version; `establish_on`), failing when every node answered off it; the fork + schedule is never held to it, only compared once an epoch + (`warn_if_schedule_differs`), so a stale binary cannot go offline at a fork. + A node whose genesis, preset, slot duration or any active fork's epoch and version differs is skipped by every call until a later check finds it compatible again. A background task re-asks every node every slot, judging and merging each answer as it arrives, at the diff --git a/README.md b/README.md index c57b41e14..44c210479 100644 --- a/README.md +++ b/README.md @@ -359,6 +359,7 @@ beacon node. | Flag | Meaning | |---|---| | `--beacon-nodes` | Base URLs of the beacon nodes to use, comma-separated or repeated. Each is asked whether it is syncing once a slot; the ones that said synced are tried first, then the rest, each in the order given, so the order is a preference. A slot in which every node that answered is syncing or on an optimistic head signs nothing | +| `--network` | Optional. The network every beacon node must be on (`mainnet`, `sepolia`, `hoodi`, `plataberget`, or a network directory). A node on another network is not used; the fork schedule still comes from the beacon nodes, with a warning when it differs from the network's. Without it the client runs on the first answering node's chain | | `--validators-dir` | Directory of EIP-2335 keystores and `validator_definitions.yml`. Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`) are discovered and the file is written | | `--secrets-dir` | One password file per keystore, named after the validator's public key | | `--suggested-fee-recipient` | Execution address for block rewards, `0x`-prefixed. Optional, but without it the beacon node picks an address that is not yours | diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index f3801e563..bf6d31f94 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -1,17 +1,23 @@ //! `ethlambda validator`: the beacon-chain validator client. //! -//! It talks to a beacon node over the standard REST Beacon API and depends on -//! nothing else in this binary, so it runs against any conformant node. +//! It talks to a beacon node over the standard REST Beacon API, so it runs +//! against any conformant node. The one thing it takes from the rest of this +//! binary is `--network`'s resolution, the same `network` module `ethlambda +//! beacon` resolves its own `--network` with. use std::path::PathBuf; use ethlambda_types::beacon::primitives::{Bytes32, ExecutionAddress, H160}; +use ethlambda_validator::beacon_node::Genesis; +use ethlambda_validator::chain_check::{ChainId, ExpectedNetwork}; use ethlambda_validator::proposer_settings::{ DEFAULT_GAS_LIMIT, GRAFFITI_BYTES, graffiti_from_text, }; use ethlambda_validator::{BuilderProposals, ValidatorConfig}; use eyre::WrapErr as _; +use crate::network::{NetworkSource, NetworkSpec}; + /// An execution address is exactly this wide. const ADDRESS_BYTES: usize = 20; @@ -27,6 +33,23 @@ pub(crate) struct ValidatorOptions { #[arg(long, value_delimiter = ',', required = true)] pub(crate) beacon_nodes: Vec, + /// The network every beacon node must be on: a built-in name (`mainnet`, + /// `sepolia`, `hoodi`, `plataberget`) or a path to a directory of + /// published network files, as `ethlambda beacon --network` takes. + /// + /// Optional, with no default. Without it the client runs on the chain of + /// the first beacon node that answers. With it, a node whose preset, + /// genesis, slot duration or genesis fork version differs from the + /// network's is never used, and startup fails when every node that + /// answered is on another network. + /// + /// The fork schedule still comes from the beacon nodes. One that differs + /// from this network's config is warned about once an epoch, never + /// refused, so a fork the network schedules or moves needs the beacon + /// nodes upgraded, not this client. + #[arg(long)] + pub(crate) network: Option, + /// Directory holding the EIP-2335 keystores and `validator_definitions.yml`. /// Without that file, keystores in the Lighthouse layout /// (`<0xpubkey>/voting-keystore.json`, password in @@ -249,6 +272,32 @@ impl ValidatorOptions { }) } + /// Resolve `--network`, or `None` when it is absent. + /// + /// Must run before anything reads a preset value: resolving selects the + /// network's preset, as it does for `ethlambda beacon`, and the client + /// later refuses to start if a read froze one first + /// (`require_unread_preset`). + pub(crate) fn network(&self) -> eyre::Result> { + let Some(value) = &self.network else { + return Ok(None); + }; + let spec = NetworkSpec::parse(value)?; + let source = NetworkSource::resolve(&spec) + .wrap_err_with(|| format!("failed to resolve --network {value}"))?; + let genesis = source.genesis(); + Ok(Some(ExpectedNetwork { + name: source.name().to_string(), + chain: ChainId { + genesis: Genesis { + genesis_time: genesis.genesis_time, + genesis_validators_root: genesis.genesis_validators_root, + }, + config: source.config().clone(), + }, + })) + } + /// Reject a port clash before anything binds, the way the node's own /// options do. pub(crate) fn validate_ports(&self) -> eyre::Result<()> { @@ -277,6 +326,7 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { // with `EMFILE` once several signers are busy at once, and every // signature those requests were for fails with it. crate::fd_limit::raise_fd_limit().wrap_err("failed to raise RLIMIT_NOFILE")?; + let network = options.network()?; let graffiti = options.graffiti()?; let suggested_fee_recipient = options.suggested_fee_recipient()?; let builder = options.builder(); @@ -297,6 +347,7 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { builder_min_bid: options.builder_min_bid, init_slashing_protection: options.init_slashing_protection, doppelganger_protection: options.enable_doppelganger_protection, + network, }) .await .map_err(Into::into) @@ -309,6 +360,7 @@ mod tests { fn options(graffiti: &str) -> ValidatorOptions { ValidatorOptions { beacon_nodes: vec!["http://localhost:5052".to_string()], + network: None, validators_dir: PathBuf::from("/tmp/validators"), secrets_dir: PathBuf::from("/tmp/secrets"), http_address: "127.0.0.1".parse().expect("valid address"), @@ -366,6 +418,51 @@ mod tests { parse(&["--gas-limit", "30000000"]).expect("parses alone"); } + /// Absent, the client takes its chain from the beacon nodes alone, as it + /// did before the flag existed. + #[test] + fn the_network_is_optional() { + let options = parse(&[]).expect("parses"); + assert_eq!(options.network, None); + assert_eq!(options.network().expect("nothing to resolve"), None); + + let options = parse(&["--network", "hoodi"]).expect("parses"); + assert_eq!(options.network.as_deref(), Some("hoodi")); + } + + /// A built-in network resolves to the genesis values and config the + /// beacon node runs it on, so the two are compared like for like. + #[test] + fn a_built_in_network_resolves_to_its_genesis_and_config() { + let mut options = options(""); + options.network = Some("hoodi".to_string()); + let network = options + .network() + .expect("hoodi resolves") + .expect("a network was named"); + + assert_eq!(network.name, "hoodi"); + assert_eq!(network.chain.genesis.genesis_time, 1_742_213_400); + assert_eq!( + hex::encode(network.chain.genesis.genesis_validators_root.0), + "212f13fc4df078b6cb7db228f1c8307566dcecf900867401a92023d7ba99cb5f" + ); + assert_eq!(network.chain.config.preset_base.as_str(), "mainnet"); + assert_eq!(network.chain.config.slot_duration_ms, 12_000); + assert_eq!( + network.chain.config.genesis_fork_version, + [0x10, 0, 0x09, 0x10] + ); + } + + #[test] + fn an_unknown_network_name_is_refused_at_startup() { + let mut options = options(""); + options.network = Some("hodi".to_string()); + let err = options.network().expect_err("no such network"); + assert!(err.to_string().contains("unknown network"), "{err}"); + } + /// Without the flag the token stays in `--validators-dir`. With it the path /// is taken as given, and, like `--keymanager-port`, accepted without /// `--enable-keymanager`, which is what decides whether it is read. diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 495347b7c..97bb5e9fd 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -46,7 +46,9 @@ use crate::beacon_node::{ AggregateAttestation, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, ValidatorEntry, }; -use crate::chain_check::{ChainId, Served, first_chain_difference}; +use crate::chain_check::{ + ChainId, ExpectedNetwork, Served, first_chain_difference, first_identity_difference, +}; use crate::error::{Error, Result}; /// The boxed future `#[async_trait]` desugars a trait method call into, @@ -408,39 +410,76 @@ impl FallbackBeaconNode { &self, with_reference: impl FnOnce(&ChainId) -> Result, ) -> Result { + self.establish_on(None, with_reference).await + } + + /// [`Self::establish`], with the chain held to the `network` the operator + /// named (`--network`) when there is one. + /// + /// The reference is then the first node that answers *on that network*: + /// no [`first_identity_difference`] from it (preset, genesis, slot + /// duration, genesis fork version). A node that answers on another one is + /// never the reference, so `with_reference` never sees its chain or + /// adopts its preset, and is judged against the reference like any other + /// node, which leaves it unusable. Its answer is as final as an + /// unreadable spec: when every node has answered with one or the other, + /// startup fails naming each, rather than waiting for a node that will + /// not move to another network on its own. + /// + /// The fork schedule is not held to the network's: it may differ while a + /// change rolls out, and is followed from the nodes as without a network + /// (see [`crate::chain_check::warn_if_schedule_differs`]). + pub async fn establish_on( + &self, + network: Option<&ExpectedNetwork>, + with_reference: impl FnOnce(&ChainId) -> Result, + ) -> Result { + // Why an answer cannot be the reference: `None` when it can. + let off_network = |chain: &ChainId| { + let network = network?; + first_identity_difference(&network.chain, chain) + .map(|difference| format!("not on {}: {difference}", network.name)) + }; let (reference_at, asked) = loop { let asked = futures_util::future::join_all(self.nodes.iter().map(ask)).await; - if let Some(reference_at) = asked.iter().position(|answer| answer.is_ok()) { + if let Some(reference_at) = asked.iter().position(|answer| { + answer + .as_ref() + .is_ok_and(|chain| off_network(chain).is_none()) + }) { break (reference_at, asked); } let detail = asked .iter() .enumerate() - .filter_map(|(position, answer)| { - answer - .as_ref() - .err() - .map(|err| format!("node {position}: {err}")) + .filter_map(|(position, answer)| match answer { + Ok(chain) => off_network(chain).map(|why| format!("node {position}: {why}")), + Err(err) => Some(format!("node {position}: {err}")), }) .collect::>() .join("; "); - // A node that answered with a preset this client cannot run on, or - // a spec it cannot read (a required key absent, say), answered: - // asking it again gives the same answer. Waiting is for a node - // that has not answered yet, and for one whose answer was not the - // node's at all: a body that is not JSON (`Error::Decode`), such - // as a proxy's maintenance page while the node boots. - if asked - .iter() - .all(|answer| matches!(answer, Err(Error::Preset(_) | Error::UnreadableSpec(_)))) - { + // A node that answered with a preset this client cannot run on, a + // spec it cannot read (a required key absent, say), or a chain + // off the named network, answered: asking it again gives the + // same answer. Waiting is for a node that has not answered yet, + // and for one whose answer was not the node's at all: a body that + // is not JSON (`Error::Decode`), such as a proxy's maintenance + // page while the node boots. Every `Ok` here is off the network, + // or it would have been the reference. + if asked.iter().all(|answer| { + matches!( + answer, + Ok(_) | Err(Error::Preset(_) | Error::UnreadableSpec(_)) + ) + }) { warn!(%detail, "No configured beacon node serves a chain this client can run on"); return Err(Error::AllBeaconNodesFailed(detail)); } warn!( %detail, retry_in_secs = STARTUP_RETRY.as_secs(), - "No configured beacon node answered; waiting for one" + "No configured beacon node answered on a chain this client can run on; waiting \ + for one" ); tokio::time::sleep(STARTUP_RETRY).await; }; diff --git a/crates/validator/src/chain_check.rs b/crates/validator/src/chain_check.rs index 6f037236d..e5cc315fb 100644 --- a/crates/validator/src/chain_check.rs +++ b/crates/validator/src/chain_check.rs @@ -8,6 +8,11 @@ //! ([`first_chain_difference`]). A node on another chain is skipped by every //! fallback call until a later check finds it compatible again (see //! [`crate::beacon_node::fallback::FallbackBeaconNode::check_nodes`]). +//! - With `--network`, the chain the client starts on must also be the one the +//! operator named ([`ExpectedNetwork`]): its identity +//! ([`first_identity_difference`]) decides which node may be the reference, +//! and its fork schedule is compared with the one the client follows +//! ([`schedule_differences`]), with a warning but never a refusal. //! - A fork the network schedules after startup is taken from the compatible //! nodes once every one of them still answering schedules it alike //! ([`merge_schedule`]), and swapped into the configuration the slot clock @@ -44,6 +49,22 @@ pub struct ChainId { pub config: Config, } +/// The network `--network` names, resolved from the binary's built-in +/// networks or a directory of published network files. +/// +/// Only ever compared against, never run on: the client's configuration is +/// still the reference node's, and its schedule is still followed from the +/// beacon nodes. What this adds is which node may be the reference (one whose +/// identity matches, see [`first_identity_difference`]) and a warning when +/// the schedule the client follows differs from this one +/// ([`warn_if_schedule_differs`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExpectedNetwork { + /// The network's name, for logs and errors. + pub name: String, + pub chain: ChainId, +} + fn epoch_text(epoch: Epoch) -> String { if epoch == FAR_FUTURE_EPOCH { "unscheduled".to_string() @@ -82,11 +103,57 @@ fn forks_in_order(config: &Config) -> bool { /// SSZ bounds and another epoch length, which every later field would be read /// against. A node whose spec cannot be parsed under its own preset's values /// at all (`Error::Preset`) is incompatible for the same reason. +/// +/// Everything up to the forks is [`first_identity_difference`]. pub fn first_chain_difference( ours: &ChainId, theirs: &ChainId, current_epoch: Epoch, ) -> Option { + if let Some(difference) = first_identity_difference(ours, theirs) { + return Some(difference); + } + let (ours, theirs) = (&ours.config, &theirs.config); + for fork in ForkName::ALL { + if fork == ForkName::Phase0 { + continue; + } + let (our_epoch, their_epoch) = (ours.fork_epoch(fork), theirs.fork_epoch(fork)); + if our_epoch > current_epoch && their_epoch > current_epoch { + continue; + } + if our_epoch != their_epoch { + return Some(format!( + "{} (ours {}, theirs {})", + fork_epoch_key(fork), + epoch_text(our_epoch), + epoch_text(their_epoch) + )); + } + if ours.fork_version(fork) != theirs.fork_version(fork) { + return Some(format!( + "{} (ours {}, theirs {})", + fork_version_key(fork), + version_text(ours.fork_version(fork)), + version_text(theirs.fork_version(fork)) + )); + } + } + None +} + +/// The first field that makes `theirs` a different network from `ours` +/// whatever either schedules: `PRESET_BASE`, the genesis time and validators +/// root, the slot duration, then `GENESIS_FORK_VERSION`, named with both +/// values. `None` when the two are one network. +/// +/// What `--network` is checked with ([`ExpectedNetwork`]). None of these moves +/// over a network's life, so a node that differs in one is on another network +/// and never will be on this one, where a fork that differs may only mean +/// that the node or this binary predates a schedule change. Those are left to +/// [`first_chain_difference`] (between nodes) and [`schedule_differences`] +/// (against the named network). +pub fn first_identity_difference(ours: &ChainId, theirs: &ChainId) -> Option { if ours.config.preset_base != theirs.config.preset_base { return Some(format!( "PRESET_BASE (ours {}, theirs {})", @@ -120,32 +187,64 @@ pub fn first_chain_difference( version_text(theirs.fork_version(genesis_version)) )); } + None +} + +/// Every fork from altair on whose epoch, or version while scheduled, differs +/// between the schedule the client `follows` and the `network` config's, one +/// line each naming both values. +/// +/// The version of a fork both leave unscheduled is a placeholder, so it is +/// not compared. +pub fn schedule_differences(follows: &Config, network: &Config) -> Vec { + let mut differences = Vec::new(); for fork in ForkName::ALL { if fork == ForkName::Phase0 { continue; } - let (our_epoch, their_epoch) = (ours.fork_epoch(fork), theirs.fork_epoch(fork)); - if our_epoch > current_epoch && their_epoch > current_epoch { - continue; - } - if our_epoch != their_epoch { - return Some(format!( - "{} (ours {}, theirs {})", + let (followed_epoch, network_epoch) = (follows.fork_epoch(fork), network.fork_epoch(fork)); + if followed_epoch != network_epoch { + differences.push(format!( + "{} (beacon nodes {}, network config {})", fork_epoch_key(fork), - epoch_text(our_epoch), - epoch_text(their_epoch) + epoch_text(followed_epoch), + epoch_text(network_epoch) )); - } - if ours.fork_version(fork) != theirs.fork_version(fork) { - return Some(format!( - "{} (ours {}, theirs {})", + } else if followed_epoch != FAR_FUTURE_EPOCH + && follows.fork_version(fork) != network.fork_version(fork) + { + differences.push(format!( + "{} (beacon nodes {}, network config {})", fork_version_key(fork), - version_text(ours.fork_version(fork)), - version_text(theirs.fork_version(fork)) + version_text(follows.fork_version(fork)), + version_text(network.fork_version(fork)) )); } } - None + differences +} + +/// Warn when the schedule the client `follows` differs from the named +/// `network`'s ([`schedule_differences`]). +/// +/// A warning and never a refusal: the client keeps following the beacon +/// nodes. Either side can be the stale one, the nodes not yet upgraded for a +/// fork the network scheduled, or this binary built before the network moved +/// one, and refusing on the second would stop every validator of an +/// operator who upgraded the nodes but not the client once the fork came. +pub fn warn_if_schedule_differs(network: &ExpectedNetwork, follows: &Config, epoch: Epoch) { + let differences = schedule_differences(follows, &network.chain.config); + if differences.is_empty() { + return; + } + warn!( + %epoch, + network = %network.name, + differences = %differences.join("; "), + "The fork schedule the beacon nodes serve differs from --network's config; the client \ + follows the beacon nodes. One of them is out of date: upgrade the beacon nodes or \ + this client, whichever predates the network's schedule" + ); } /// What the schedule is followed from: see @@ -511,12 +610,17 @@ pub fn follow_schedule( /// the upgraded node refused for it. Two small requests per node per slot is /// the price of that. /// -/// Disagreements are warned about once per epoch, at the epoch's first round. +/// Disagreements are warned about once per epoch, at the epoch's first round, +/// and so, with `--network`, is a schedule that differs from the network's +/// ([`warn_if_schedule_differs`]), compared once that round's merge is done. +/// The first round is a slot after startup, so a difference the reference +/// node already had is said then. pub async fn run( nodes: Arc>, genesis: Genesis, clock: SlotClock, context: Arc, + network: Option, shutdown: CancellationToken, ) { let mut warned_epoch = None; @@ -540,6 +644,9 @@ pub async fn run( () = shutdown.cancelled() => return, () = check_once(&nodes, genesis, &context, epoch_now, warn_disagreements) => {} } + if warn_disagreements && let Some(network) = &network { + warn_if_schedule_differs(network, &context.config(), epoch); + } } } @@ -874,6 +981,64 @@ mod tests { ); } + /// The identity is what `--network` refuses on, so it must not include a + /// fork: a moved fork is a schedule change the nodes may be ahead of. + #[test] + fn the_identity_leaves_the_forks_out() { + let epoch = Config::mainnet().fork_epoch(ForkName::Electra); + let moved = Config::mainnet().with_fork_epoch(ForkName::Electra, epoch + 1); + assert_eq!(first_identity_difference(&mainnet(), &chain(moved)), None); + + let mut other = mainnet(); + other.genesis.genesis_validators_root = Root::repeat_byte(0xbb); + let difference = first_identity_difference(&mainnet(), &other).expect("differs"); + assert!( + difference.starts_with("genesis_validators_root"), + "got {difference}" + ); + + let config = Config::mainnet().with_fork_version(ForkName::Phase0, [9, 9, 9, 9]); + let difference = first_identity_difference(&mainnet(), &chain(config)).expect("differs"); + assert!( + difference.starts_with("GENESIS_FORK_VERSION"), + "got {difference}" + ); + } + + #[test] + fn a_schedule_differs_from_the_network_by_epoch_or_scheduled_version() { + let network = with_gloas(NOW + 100, [8, 0, 0, 0]); + assert!(schedule_differences(&network, &network).is_empty()); + + // The nodes not upgraded yet, or this binary older than the network's + // schedule: either way both values are named. + let differences = schedule_differences(&Config::mainnet(), &network); + assert_eq!(differences.len(), 1, "got {differences:?}"); + assert!( + differences[0].starts_with("GLOAS_FORK_EPOCH") + && differences[0].contains("beacon nodes unscheduled") + && differences[0].contains(&format!("network config {}", NOW + 100)), + "got {differences:?}" + ); + + let reversioned = with_gloas(NOW + 100, [9, 0, 0, 0]); + let differences = schedule_differences(&reversioned, &network); + assert_eq!(differences.len(), 1, "got {differences:?}"); + assert!( + differences[0].starts_with("GLOAS_FORK_VERSION"), + "got {differences:?}" + ); + } + + /// An unscheduled fork's version is a placeholder, so two schedules that + /// both leave the fork out agree whatever it holds. + #[test] + fn an_unscheduled_forks_version_is_no_schedule_difference() { + let mut placeholder = Config::mainnet(); + placeholder.gloas_fork_version = [9, 9, 9, 9]; + assert!(schedule_differences(&placeholder, &Config::mainnet()).is_empty()); + } + // The checks through the fallback, against scripted mock nodes. use crate::beacon_node::fallback::NodeAnswer; @@ -956,6 +1121,124 @@ mod tests { ); } + /// `--network` on `genesis()`'s chain, on mainnet's config. + fn named_network() -> ExpectedNetwork { + ExpectedNetwork { + name: "testnet".to_string(), + chain: ChainId { + genesis: genesis(), + config: Config::mainnet(), + }, + } + } + + /// The first node answers, but on another network: the second, on the + /// named one, is the reference, and the first never gets a duty call. + #[tokio::test] + async fn a_node_off_the_named_network_is_never_the_reference() { + let first = node() + .with_genesis_root(Root::repeat_byte(0xbb)) + .with_duties(3, Root::repeat_byte(7), vec![]); + let second = node().failing_call("attester_duties", "down"); + let fallback = FallbackBeaconNode::new(vec![first, second]); + + let network = named_network(); + let mut seen = None; + let chain = fallback + .establish_on(Some(&network), |reference| { + seen = Some(reference.clone()); + Ok(NOW) + }) + .await + .expect("the second node is on the network"); + + assert_eq!(chain.genesis, genesis()); + assert_eq!( + seen, + Some(chain), + "with_reference saw the named network's chain" + ); + fallback + .attester_duties(3, &[]) + .await + .expect_err("only the second node is usable, and it fails"); + assert_eq!(*fallback.nodes()[0].duties_calls.lock().expect("lock"), 0); + } + + /// Without a network named, the same first node is the reference, as it + /// always was. + #[tokio::test] + async fn without_a_named_network_the_first_answer_is_the_reference() { + let first = node().with_genesis_root(Root::repeat_byte(0xbb)); + let fallback = FallbackBeaconNode::new(vec![first, node()]); + let chain = fallback + .establish_on(None, |_| Ok(NOW)) + .await + .expect("a node answers"); + assert_eq!( + chain.genesis.genesis_validators_root, + Root::repeat_byte(0xbb) + ); + } + + /// Every node answered, each on another network or preset: waiting would + /// change nothing, so startup fails at once, naming the network and why + /// each node is off it, and never adopts a node's chain. + #[tokio::test(start_paused = true)] + async fn every_node_off_the_named_network_fails_at_once() { + use std::time::Duration; + + let fallback = FallbackBeaconNode::new(vec![ + node().with_genesis_root(Root::repeat_byte(0xbb)), + node().with_spec(Config::minimal()), + ]); + let network = named_network(); + let establish = fallback.establish_on(Some(&network), |reference| { + panic!("no node is on the network, yet {reference:?} was adopted") + }); + // Shorter than one startup retry, so a wait fails here. + let err = tokio::time::timeout(Duration::from_secs(1), establish) + .await + .expect("fails without waiting") + .expect_err("no node is on the network"); + + assert!(matches!(err, Error::AllBeaconNodesFailed(_)), "got {err:?}"); + let text = err.to_string(); + assert!( + text.contains("node 0: not on testnet: genesis_validators_root") + && text.contains("node 1: not on testnet: PRESET_BASE"), + "got {text}" + ); + } + + /// A node off the network beside one that has not answered yet: startup + /// waits for the second, which comes up on the network and is the + /// reference. + #[tokio::test(start_paused = true)] + async fn startup_waits_for_a_node_on_the_named_network() { + use std::time::Duration; + + let fallback = FallbackBeaconNode::new(vec![ + node().with_genesis_root(Root::repeat_byte(0xbb)), + node().failing_call("genesis", "down"), + ]); + let comes_up = async { + tokio::time::sleep(Duration::from_secs(5)).await; + fallback.nodes()[1].stop_failing("genesis"); + }; + let network = named_network(); + let waited = async { + let (chain, ()) = + tokio::join!(fallback.establish_on(Some(&network), |_| Ok(NOW)), comes_up); + chain + }; + let chain = tokio::time::timeout(Duration::from_secs(60), waited) + .await + .expect("startup ends once the node on the network answers") + .expect("the second node is on the network"); + assert_eq!(chain.genesis, genesis()); + } + /// A node on the minimal preset while the reference is mainnet is marked /// incompatible and never asked for a duty. #[tokio::test] diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 74f6f3eb6..0516565c4 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -59,9 +59,11 @@ pub use error::{Error, Result}; /// Run this process on the preset the beacon node reports, before anything /// reads one. /// -/// A validator client has no network config of its own: the node's -/// `/eth/v1/config/spec` is where it learns the chain, `PRESET_BASE` -/// included. Every container this client decodes, builds or signs is bounded +/// A validator client runs on the node's `/eth/v1/config/spec`, `PRESET_BASE` +/// included, even with `--network`: the network it names is only compared +/// against (see [`chain_check::ExpectedNetwork`]). Resolving that network +/// selects its preset first, and the reference node is then one on it, so +/// this selects the same preset again. Every container this client decodes, builds or signs is bounded /// by that preset (a sync committee's bits, an attestation's committee bits, /// the slots in an epoch), so it is selected here, right after the spec is /// fetched and before any duty runs. @@ -171,6 +173,9 @@ pub struct ValidatorConfig { /// has seen it stay silent for a full epoch, and stop if it does not. See /// [`doppelganger`]. pub doppelganger_protection: bool, + /// The network `--network` names, or `None` to run on whichever chain the + /// first beacon node to answer is on. See [`chain_check::ExpectedNetwork`]. + pub network: Option, } /// Builder proposals: register each validator with the beacon node's builder @@ -291,14 +296,15 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { // The chain the client runs on is the first node's that answers, waiting // for one while none does; every other node is checked against it, and a - // node on another chain is not used. The schedule is the reference's: a - // fork another node schedules is taken by the background check once every + // node on another chain is not used. With `--network`, only a node on + // that network can be the first. The schedule is the reference's: a fork + // another node schedules is taken by the background check once every // node answering schedules it alike. See `chain_check`. let ChainId { genesis, config: spec, } = beacon_node - .establish(|reference| { + .establish_on(config.network.as_ref(), |reference| { // Right after the reference is chosen and before anything reads a // preset value, which the epoch below does. require_unread_preset()?; @@ -306,7 +312,9 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { Ok(chain_check::current_epoch_of(reference)) }) .await?; + let network = config.network.as_ref().map(|network| network.name.as_str()); info!( + network = network.unwrap_or("any, taken from the beacon nodes"), preset = spec.preset_base.as_str(), genesis_time = genesis.genesis_time, slot_duration_ms = spec.slot_duration_ms, @@ -435,6 +443,7 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { genesis, clock.clone(), context.clone(), + config.network.clone(), shutdown.clone(), )); let mut keymanager = None; diff --git a/docs/cli.md b/docs/cli.md index b223e4258..af97ca659 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -380,8 +380,22 @@ said, and asks them all again every 2 seconds, as Lighthouse's validator client does, rather than exiting: a client started beside its beacon node otherwise exits before the node's API is up. Only when every node answered, each with a preset this client cannot run on or a spec it cannot read, does startup fail; a -body that is not JSON at all (a proxy's page while the node boots) is waited out. A -response without the slot +body that is not JSON at all (a proxy's page while the node boots) is waited out. + +With `--network`, the reference must also be on the network it names, compared +on the fields that never move over a network's life: `PRESET_BASE`, +`genesis_time`, `genesis_validators_root`, the slot duration and +`GENESIS_FORK_VERSION`. A node that differs in one is never the reference and is +not used, and a node on another network counts as a final answer: when every +node answered, each on another network, on a preset this client cannot run on, +or with a spec it cannot read, startup fails naming why each is off; otherwise it +waits for one on the network. The fork schedule is not held to the network's, +since the beacon nodes or this binary may predate a change to it: the client +still follows the nodes' schedule (below), and warns once an epoch, naming both +values, when it differs from the network's config. Without `--network` the first +node to answer sets the chain, whatever it is. + +A response without the slot duration, `GENESIS_FORK_VERSION`, or the epoch and version of any fork from altair to fulu is refused rather than filled in from mainnet; only gloas may be absent, meaning unscheduled. @@ -444,6 +458,7 @@ slot's end, so a node serving a wrong one cannot park a duty past its slot. | Flag | Default | Meaning | |---|---|---| | `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node on this client's chain is asked `/eth/v1/node/syncing` once a slot; the ones that answered synced and not optimistic are tried first, in list order, then the rest in list order. The first that answers serves the request, so the order is a preference, not load balancing. A node on another chain, or not checked yet, is skipped: see [the chain check](#several-beacon-nodes-the-chain-check) and [The per-slot sync check](#the-per-slot-sync-check) | +| `--network` | none | The network every beacon node must be on: a built-in name (`mainnet`, `sepolia`, `hoodi`, `plataberget`) or a directory of published network files, resolved as `beacon --network` resolves it. A node on another network (preset, genesis, slot duration or genesis fork version) is not used, and startup fails if every node that answered is on one. The fork schedule still comes from the beacon nodes and is only warned about when it differs from the network's, so a rescheduled fork needs the beacon nodes upgraded, not this client. Without it the client runs on the first answering node's chain. See [the chain check](#several-beacon-nodes-the-chain-check) | | `--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 | | `--http-address` | `127.0.0.1` | Bind address for the metrics and keymanager servers | From 06d8b7c09c69404b6f1482e67b574a4be02765a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:46:39 -0300 Subject: [PATCH 2/4] fix(validator): name a network directory without CONFIG_NAME by its --network value --- bin/ethlambda/src/validator.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index bf6d31f94..3ca97bec0 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -286,8 +286,14 @@ impl ValidatorOptions { let source = NetworkSource::resolve(&spec) .wrap_err_with(|| format!("failed to resolve --network {value}"))?; let genesis = source.genesis(); + // A directory's `config.yaml` may omit `CONFIG_NAME`; the flag's value + // then names the network in logs and errors instead of nothing. + let name = match source.name() { + "" => value.clone(), + name => name.to_string(), + }; Ok(Some(ExpectedNetwork { - name: source.name().to_string(), + name, chain: ChainId { genesis: Genesis { genesis_time: genesis.genesis_time, From 93cd61238297c36b584def96a76a27b73e197fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:28:09 -0300 Subject: [PATCH 3/4] fix(validator): let --network's schedule pick the reference among disagreeing nodes Review round 1 on #902: - With --network, the reference was the first node on the network whatever schedule it served, so with one node stale on a rescheduled fork listed ahead of an upgraded one, the client followed the stale schedule and later dropped the node that agreed with the network. The first node on the network that also serves the network's schedule is now the reference, and the first on the network when none does. - The help text and the flag row said startup fails when every node that answered is off the network. It fails once every configured node has answered and none is on it, and waits while one has not answered. - The schedule warning told the operator to upgrade the beacon nodes or this client. For a directory the stale side can be its config.yaml, so the warning now names --network's config (this binary's for a built-in network, the directory's config.yaml otherwise), and the help text agrees with it. - The help text and docs/cli.md say a directory is resolved whole, as for beacon: its genesis.ssz decoded and its bootnodes file read. - Tests: the reference preference, a network directory resolving to its genesis and config, and a directory without CONFIG_NAME named by the flag's value. network::dir's complete_dir fixture is now reachable from the crate's other tests. --- bin/ethlambda/src/network/dir.rs | 4 +- bin/ethlambda/src/validator.rs | 56 ++++++++++++++++++-- crates/validator/src/beacon_node/fallback.rs | 30 ++++++++--- crates/validator/src/chain_check.rs | 35 +++++++++++- docs/cli.md | 12 +++-- 5 files changed, 120 insertions(+), 17 deletions(-) diff --git a/bin/ethlambda/src/network/dir.rs b/bin/ethlambda/src/network/dir.rs index 7bbe82aaa..4951a7b9a 100644 --- a/bin/ethlambda/src/network/dir.rs +++ b/bin/ethlambda/src/network/dir.rs @@ -185,7 +185,7 @@ fn read_required_bytes(path: &Path) -> Result, NetworkDirError> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; fn fixture(name: &str) -> std::path::PathBuf { @@ -196,7 +196,7 @@ mod tests { /// Build a complete directory in a temp dir: the devnet fixture plus a /// genesis state, which is too large to check in. - fn complete_dir() -> tempfile::TempDir { + pub(crate) fn complete_dir() -> tempfile::TempDir { let dir = tempfile::tempdir().unwrap(); std::fs::copy( fixture("devnet").join("config.yaml"), diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index 51eeb8377..4ed942946 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -45,13 +45,16 @@ pub(crate) struct ValidatorOptions { /// Optional, with no default. Without it the client runs on the chain of /// the first beacon node that answers. With it, a node whose preset, /// genesis, slot duration or genesis fork version differs from the - /// network's is never used, and startup fails when every node that - /// answered is on another network. + /// network's is never used. Startup fails once every configured node has + /// answered and none is on the network, and waits while one has not + /// answered. A directory is resolved whole, as for `beacon`: its + /// `genesis.ssz` is decoded and its bootnodes file read. /// /// The fork schedule still comes from the beacon nodes. One that differs /// from this network's config is warned about once an epoch, never /// refused, so a fork the network schedules or moves needs the beacon - /// nodes upgraded, not this client. + /// nodes upgraded for the client to follow it. The network's schedule + /// only picks the reference among nodes that disagree. #[arg(long)] pub(crate) network: Option, @@ -708,6 +711,53 @@ mod tests { ); } + /// A network directory resolves to its own genesis state and config, and + /// is named by its `CONFIG_NAME`. + #[test] + fn a_network_directory_resolves_to_its_genesis_and_config() { + let dir = crate::network::dir::tests::complete_dir(); + let mut options = options(""); + options.network = Some(dir.path().display().to_string()); + let network = options + .network() + .expect("the directory resolves") + .expect("a network was named"); + + let state = crate::beacon::mainnet_genesis_state().expect("fixture state"); + assert_eq!(network.name, "ethlambda-devnet"); + assert_eq!(network.chain.genesis.genesis_time, state.genesis_time()); + assert_eq!( + network.chain.genesis.genesis_validators_root, + state.genesis_validators_root() + ); + assert_eq!(network.chain.config.preset_base.as_str(), "mainnet"); + } + + /// A directory whose `config.yaml` has no `CONFIG_NAME` is named by the + /// flag's value, so logs and errors still say which network it is. + #[test] + fn a_network_directory_without_a_config_name_is_named_by_its_path() { + let dir = crate::network::dir::tests::complete_dir(); + let config = dir.path().join("config.yaml"); + let text = std::fs::read_to_string(&config).expect("fixture config"); + let unnamed: String = text + .lines() + .filter(|line| !line.starts_with("CONFIG_NAME:")) + .map(|line| format!("{line}\n")) + .collect(); + assert_ne!(unnamed.len(), text.len(), "the fixture names itself"); + std::fs::write(&config, unnamed).expect("rewrite config"); + + let value = dir.path().display().to_string(); + let mut options = options(""); + options.network = Some(value.clone()); + let network = options + .network() + .expect("the directory resolves") + .expect("a network was named"); + assert_eq!(network.name, value); + } + #[test] fn an_unknown_network_name_is_refused_at_startup() { let mut options = options(""); diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 43fbcb473..73bb7de40 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -74,6 +74,7 @@ use crate::beacon_node::{ }; use crate::chain_check::{ ChainId, ExpectedNetwork, Served, first_chain_difference, first_identity_difference, + schedule_differences, }; use crate::error::{Error, Result}; @@ -594,7 +595,12 @@ impl FallbackBeaconNode { /// /// The fork schedule is not held to the network's: it may differ while a /// change rolls out, and is followed from the nodes as without a network - /// (see [`crate::chain_check::warn_if_schedule_differs`]). + /// (see [`crate::chain_check::warn_if_schedule_differs`]). It only breaks + /// a tie: among the nodes on the network, the first that also serves the + /// network's schedule is the reference, and the first on the network + /// when none does. With the nodes disagreeing on a fork, the named + /// network's config is the third opinion, rather than list order alone + /// picking the schedule a stale node serves. pub async fn establish_on( &self, network: Option<&ExpectedNetwork>, @@ -606,13 +612,25 @@ impl FallbackBeaconNode { first_identity_difference(&network.chain, chain) .map(|difference| format!("not on {}: {difference}", network.name)) }; + // Whether an answer serves the named network's fork schedule; every + // answer does without a network. + let on_schedule = |chain: &ChainId| { + network.is_none_or(|network| { + schedule_differences(&chain.config, &network.chain.config).is_empty() + }) + }; + let on_network = |answer: &Result| { + answer + .as_ref() + .is_ok_and(|chain| off_network(chain).is_none()) + }; let (reference_at, asked) = loop { let asked = futures_util::future::join_all(self.nodes.iter().map(ask)).await; - if let Some(reference_at) = asked.iter().position(|answer| { - answer - .as_ref() - .is_ok_and(|chain| off_network(chain).is_none()) - }) { + let reference_at = asked + .iter() + .position(|answer| on_network(answer) && answer.as_ref().is_ok_and(&on_schedule)) + .or_else(|| asked.iter().position(on_network)); + if let Some(reference_at) = reference_at { break (reference_at, asked); } let detail = asked diff --git a/crates/validator/src/chain_check.rs b/crates/validator/src/chain_check.rs index e5cc315fb..92d5ba11e 100644 --- a/crates/validator/src/chain_check.rs +++ b/crates/validator/src/chain_check.rs @@ -242,8 +242,9 @@ pub fn warn_if_schedule_differs(network: &ExpectedNetwork, follows: &Config, epo network = %network.name, differences = %differences.join("; "), "The fork schedule the beacon nodes serve differs from --network's config; the client \ - follows the beacon nodes. One of them is out of date: upgrade the beacon nodes or \ - this client, whichever predates the network's schedule" + follows the beacon nodes. One side is out of date: the beacon nodes, or --network's \ + config (this binary's for a built-in network, the directory's config.yaml \ + otherwise), whichever predates the network's schedule" ); } @@ -1181,6 +1182,36 @@ mod tests { ); } + /// Two nodes on the named network that disagree on a fork: the second, + /// whose schedule is the network's, is the reference, though the first is + /// listed ahead of it. With neither on the network's schedule, list order + /// decides, as without a network. + #[tokio::test] + async fn a_node_on_the_named_network_and_its_schedule_is_the_preferred_reference() { + let network = named_network(); + let gloas_at = network.chain.config.fork_epoch(ForkName::Gloas); + let stale = Config::mainnet().with_fork_epoch(ForkName::Gloas, NOW + 10); + assert_ne!(stale.fork_epoch(ForkName::Gloas), gloas_at); + + let fallback = FallbackBeaconNode::new(vec![node().with_spec(stale.clone()), node()]); + let chain = fallback + .establish_on(Some(&network), |_| Ok(NOW)) + .await + .expect("both nodes are on the network"); + assert_eq!(chain.config.fork_epoch(ForkName::Gloas), gloas_at); + + let other = Config::mainnet().with_fork_epoch(ForkName::Gloas, NOW + 20); + let fallback = FallbackBeaconNode::new(vec![ + node().with_spec(stale.clone()), + node().with_spec(other), + ]); + let chain = fallback + .establish_on(Some(&network), |_| Ok(NOW)) + .await + .expect("both nodes are on the network"); + assert_eq!(chain.config.fork_epoch(ForkName::Gloas), NOW + 10); + } + /// Every node answered, each on another network or preset: waiting would /// change nothing, so startup fails at once, naming the network and why /// each node is off it, and never adopts a node's chain. diff --git a/docs/cli.md b/docs/cli.md index f884c99e6..8c42125bd 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -390,9 +390,13 @@ not used, and a node on another network counts as a final answer: when every node answered, each on another network, on a preset this client cannot run on, or with a spec it cannot read, startup fails naming why each is off; otherwise it waits for one on the network. The fork schedule is not held to the network's, -since the beacon nodes or this binary may predate a change to it: the client -still follows the nodes' schedule (below), and warns once an epoch, naming both -values, when it differs from the network's config. Without `--network` the first +since the beacon nodes or the network's config (this binary's, for a built-in +network; the directory's `config.yaml` otherwise) may predate a change to it: +the client still follows the nodes' schedule (below), and warns once an epoch, +naming both values, when it differs from the network's config. The network's +schedule only breaks a tie: among the nodes on the network, the first whose +schedule is the network's is the reference, and the first on the network when +none is. Without `--network` the first node to answer sets the chain, whatever it is. A response without the slot @@ -458,7 +462,7 @@ slot's end, so a node serving a wrong one cannot park a duty past its slot. | Flag | Default | Meaning | |---|---|---| | `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node on this client's chain is asked `/eth/v1/node/syncing` once a slot and ranked by the answer, list order breaking ties. The first that answers serves the request, so the order is a preference, not load balancing. A node on another chain, or not checked yet, is skipped: see [the chain check](#several-beacon-nodes-the-chain-check), [The per-slot sync check](#the-per-slot-sync-check) and [Ranking and broadcast](#ranking-and-broadcast) | -| `--network` | none | The network every beacon node must be on: a built-in name (`mainnet`, `sepolia`, `hoodi`, `plataberget`) or a directory of published network files, resolved as `beacon --network` resolves it. A node on another network (preset, genesis, slot duration or genesis fork version) is not used, and startup fails if every node that answered is on one. The fork schedule still comes from the beacon nodes and is only warned about when it differs from the network's, so a rescheduled fork needs the beacon nodes upgraded, not this client. Without it the client runs on the first answering node's chain. See [the chain check](#several-beacon-nodes-the-chain-check) | +| `--network` | none | The network every beacon node must be on: a built-in name (`mainnet`, `sepolia`, `hoodi`, `plataberget`) or a directory of published network files, resolved as `beacon --network` resolves it (a directory's `genesis.ssz` is decoded and its bootnodes file read, at startup). A node on another network (preset, genesis, slot duration or genesis fork version) is not used. Startup fails once every configured node has answered and none is on it, and waits while one has not answered. The fork schedule still comes from the beacon nodes and is only warned about when it differs from the network's, so a rescheduled fork needs the beacon nodes upgraded for the client to follow it; the network's schedule only picks the reference among nodes that disagree. Without it the client runs on the first answering node's chain. See [the chain check](#several-beacon-nodes-the-chain-check) | | `--broadcast` | none | Signed messages to send to every beacon node on this client's chain at once instead of the first that accepts them, comma-separated: `attestations` (attestations, aggregates, payload attestations), `blocks` (blocks and envelopes, never a blinded block), `sync-committee` (messages and contributions). `subscriptions` and `none` are accepted, as Lighthouse takes them, and change nothing, since subscriptions, fee recipients, builder registrations and proposer preferences always go to every node. See [Ranking and broadcast](#ranking-and-broadcast) | | `--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 | From 1a7fe813908f2404645f91d37366dd521f1257b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:58:28 -0300 Subject: [PATCH 4/4] fix(validator): keep the reference in list order whatever --network's schedule says Review round 2 on #902 found round 1's tie-break wrong in the other half of the case it was for. When the validator binary is the stale side (a fork postponed from X to Y, the binary still at X), preferring the node that matches --network's schedule made the stale node the reference: the client followed X, the upgraded node was dropped at X, and the schedule warning stayed quiet since the followed schedule equalled the network's. That is the outage the PR's design rules out by only ever comparing against the network's config. The reference is the first node on the network again, as without --network. The test now pins that a later node matching the network's schedule does not take its place, and the docs and help text say why: the network's config may be the stale side, and the once-an-epoch warning names the difference in either case. --- bin/ethlambda/src/validator.rs | 5 +-- crates/validator/src/beacon_node/fallback.rs | 35 ++++++-------------- crates/validator/src/chain_check.rs | 28 +++++----------- docs/cli.md | 11 +++--- 4 files changed, 29 insertions(+), 50 deletions(-) diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index 4ed942946..8339f7f1a 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -53,8 +53,9 @@ pub(crate) struct ValidatorOptions { /// The fork schedule still comes from the beacon nodes. One that differs /// from this network's config is warned about once an epoch, never /// refused, so a fork the network schedules or moves needs the beacon - /// nodes upgraded for the client to follow it. The network's schedule - /// only picks the reference among nodes that disagree. + /// nodes upgraded for the client to follow it. Nor does it pick which + /// node the client starts from: this binary's copy of the network's + /// config may be the stale side. #[arg(long)] pub(crate) network: Option, diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 73bb7de40..e0e2ab4fa 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -74,7 +74,6 @@ use crate::beacon_node::{ }; use crate::chain_check::{ ChainId, ExpectedNetwork, Served, first_chain_difference, first_identity_difference, - schedule_differences, }; use crate::error::{Error, Result}; @@ -595,12 +594,12 @@ impl FallbackBeaconNode { /// /// The fork schedule is not held to the network's: it may differ while a /// change rolls out, and is followed from the nodes as without a network - /// (see [`crate::chain_check::warn_if_schedule_differs`]). It only breaks - /// a tie: among the nodes on the network, the first that also serves the - /// network's schedule is the reference, and the first on the network - /// when none does. With the nodes disagreeing on a fork, the named - /// network's config is the third opinion, rather than list order alone - /// picking the schedule a stale node serves. + /// (see [`crate::chain_check::warn_if_schedule_differs`]). Nor does it + /// pick the reference among nodes on the network that disagree on a fork: + /// the network's config may be the stale side (a binary built before a + /// reschedule), and preferring the node that matches it would follow the + /// stale schedule and drop the upgraded node at the old epoch. List order + /// decides, as without a network, and the warning names the difference. pub async fn establish_on( &self, network: Option<&ExpectedNetwork>, @@ -612,25 +611,13 @@ impl FallbackBeaconNode { first_identity_difference(&network.chain, chain) .map(|difference| format!("not on {}: {difference}", network.name)) }; - // Whether an answer serves the named network's fork schedule; every - // answer does without a network. - let on_schedule = |chain: &ChainId| { - network.is_none_or(|network| { - schedule_differences(&chain.config, &network.chain.config).is_empty() - }) - }; - let on_network = |answer: &Result| { - answer - .as_ref() - .is_ok_and(|chain| off_network(chain).is_none()) - }; let (reference_at, asked) = loop { let asked = futures_util::future::join_all(self.nodes.iter().map(ask)).await; - let reference_at = asked - .iter() - .position(|answer| on_network(answer) && answer.as_ref().is_ok_and(&on_schedule)) - .or_else(|| asked.iter().position(on_network)); - if let Some(reference_at) = reference_at { + if let Some(reference_at) = asked.iter().position(|answer| { + answer + .as_ref() + .is_ok_and(|chain| off_network(chain).is_none()) + }) { break (reference_at, asked); } let detail = asked diff --git a/crates/validator/src/chain_check.rs b/crates/validator/src/chain_check.rs index 92d5ba11e..653875fbf 100644 --- a/crates/validator/src/chain_check.rs +++ b/crates/validator/src/chain_check.rs @@ -1182,29 +1182,19 @@ mod tests { ); } - /// Two nodes on the named network that disagree on a fork: the second, - /// whose schedule is the network's, is the reference, though the first is - /// listed ahead of it. With neither on the network's schedule, list order - /// decides, as without a network. + /// Two nodes on the named network that disagree on a fork: the first + /// listed is the reference, though the second's schedule is the + /// network's. The network's config may be the stale side (a binary built + /// before a reschedule), so it never picks the schedule the client starts + /// from; the warning names the difference instead. #[tokio::test] - async fn a_node_on_the_named_network_and_its_schedule_is_the_preferred_reference() { + async fn the_named_networks_schedule_does_not_pick_the_reference() { let network = named_network(); let gloas_at = network.chain.config.fork_epoch(ForkName::Gloas); - let stale = Config::mainnet().with_fork_epoch(ForkName::Gloas, NOW + 10); - assert_ne!(stale.fork_epoch(ForkName::Gloas), gloas_at); + let moved = Config::mainnet().with_fork_epoch(ForkName::Gloas, NOW + 10); + assert_ne!(moved.fork_epoch(ForkName::Gloas), gloas_at); - let fallback = FallbackBeaconNode::new(vec![node().with_spec(stale.clone()), node()]); - let chain = fallback - .establish_on(Some(&network), |_| Ok(NOW)) - .await - .expect("both nodes are on the network"); - assert_eq!(chain.config.fork_epoch(ForkName::Gloas), gloas_at); - - let other = Config::mainnet().with_fork_epoch(ForkName::Gloas, NOW + 20); - let fallback = FallbackBeaconNode::new(vec![ - node().with_spec(stale.clone()), - node().with_spec(other), - ]); + let fallback = FallbackBeaconNode::new(vec![node().with_spec(moved), node()]); let chain = fallback .establish_on(Some(&network), |_| Ok(NOW)) .await diff --git a/docs/cli.md b/docs/cli.md index 8c42125bd..17c5b21bb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -393,10 +393,11 @@ waits for one on the network. The fork schedule is not held to the network's, since the beacon nodes or the network's config (this binary's, for a built-in network; the directory's `config.yaml` otherwise) may predate a change to it: the client still follows the nodes' schedule (below), and warns once an epoch, -naming both values, when it differs from the network's config. The network's -schedule only breaks a tie: among the nodes on the network, the first whose -schedule is the network's is the reference, and the first on the network when -none is. Without `--network` the first +naming both values, when it differs from the network's config. Nor does the +network's schedule pick the reference among nodes on the network that disagree +on a fork: list order does, as without `--network`, since preferring the node +that matches a stale config would follow the stale schedule and drop the +upgraded node at the old epoch. Without `--network` the first node to answer sets the chain, whatever it is. A response without the slot @@ -462,7 +463,7 @@ slot's end, so a node serving a wrong one cannot park a duty past its slot. | Flag | Default | Meaning | |---|---|---| | `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node on this client's chain is asked `/eth/v1/node/syncing` once a slot and ranked by the answer, list order breaking ties. The first that answers serves the request, so the order is a preference, not load balancing. A node on another chain, or not checked yet, is skipped: see [the chain check](#several-beacon-nodes-the-chain-check), [The per-slot sync check](#the-per-slot-sync-check) and [Ranking and broadcast](#ranking-and-broadcast) | -| `--network` | none | The network every beacon node must be on: a built-in name (`mainnet`, `sepolia`, `hoodi`, `plataberget`) or a directory of published network files, resolved as `beacon --network` resolves it (a directory's `genesis.ssz` is decoded and its bootnodes file read, at startup). A node on another network (preset, genesis, slot duration or genesis fork version) is not used. Startup fails once every configured node has answered and none is on it, and waits while one has not answered. The fork schedule still comes from the beacon nodes and is only warned about when it differs from the network's, so a rescheduled fork needs the beacon nodes upgraded for the client to follow it; the network's schedule only picks the reference among nodes that disagree. Without it the client runs on the first answering node's chain. See [the chain check](#several-beacon-nodes-the-chain-check) | +| `--network` | none | The network every beacon node must be on: a built-in name (`mainnet`, `sepolia`, `hoodi`, `plataberget`) or a directory of published network files, resolved as `beacon --network` resolves it (a directory's `genesis.ssz` is decoded and its bootnodes file read, at startup). A node on another network (preset, genesis, slot duration or genesis fork version) is not used. Startup fails once every configured node has answered and none is on it, and waits while one has not answered. The fork schedule still comes from the beacon nodes and is only warned about when it differs from the network's, so a rescheduled fork needs the beacon nodes upgraded for the client to follow it. Nor does it pick which node the client starts from, since the network's config may be the stale side. Without it the client runs on the first answering node's chain. See [the chain check](#several-beacon-nodes-the-chain-check) | | `--broadcast` | none | Signed messages to send to every beacon node on this client's chain at once instead of the first that accepts them, comma-separated: `attestations` (attestations, aggregates, payload attestations), `blocks` (blocks and envelopes, never a blinded block), `sync-committee` (messages and contributions). `subscriptions` and `none` are accepted, as Lighthouse takes them, and change nothing, since subscriptions, fee recipients, builder registrations and proposer preferences always go to every node. See [Ranking and broadcast](#ranking-and-broadcast) | | `--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 |