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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 and ranked by the answer (synced, then optimistic or with its execution client offline, then syncing or more than 8 slots behind, then failing), the order given breaking ties, so the order is a preference. A slot in which every node that answered is syncing or on an optimistic head signs nothing. `--broadcast` sends chosen signed messages to every node |
| `--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 |
Expand Down
4 changes: 2 additions & 2 deletions bin/ethlambda/src/network/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ fn read_required_bytes(path: &Path) -> Result<Vec<u8>, NetworkDirError> {
}

#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;

fn fixture(name: &str) -> std::path::PathBuf {
Expand All @@ -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"),
Expand Down
157 changes: 155 additions & 2 deletions bin/ethlambda/src/validator.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
//! `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::beacon_node::fallback::BroadcastTopic;
use ethlambda_validator::chain_check::{ChainId, ExpectedNetwork};
use ethlambda_validator::proposer_settings::{
DEFAULT_GAS_LIMIT, GRAFFITI_BYTES, graffiti_from_text,
};
Expand All @@ -15,6 +19,7 @@ use eyre::WrapErr as _;
use tokio::sync::oneshot;
use tracing::info;

use crate::network::{NetworkSource, NetworkSpec};
use crate::shutdown::ShutdownSignals;

/// An execution address is exactly this wide.
Expand All @@ -33,6 +38,27 @@ pub(crate) struct ValidatorOptions {
#[arg(long, value_delimiter = ',', required = true)]
pub(crate) beacon_nodes: Vec<String>,

/// 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. 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 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<String>,

/// Signed messages to send to every beacon node at once rather than to
/// the first that accepts them, comma-separated: `attestations`
/// (attestations, aggregates, payload attestations), `blocks` (blocks
Expand Down Expand Up @@ -298,6 +324,38 @@ 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<Option<ExpectedNetwork>> {
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();
// 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,
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<()> {
Expand Down Expand Up @@ -362,6 +420,7 @@ async fn run_client(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();
Expand All @@ -385,6 +444,7 @@ async fn run_client(options: ValidatorOptions) -> eyre::Result<()> {
self_build_only: options.self_build_only,
init_slashing_protection: options.init_slashing_protection,
doppelganger_protection: options.enable_doppelganger_protection,
network,
broadcast: options.broadcast.into_iter().collect(),
event_stream: !options.disable_event_stream,
};
Expand Down Expand Up @@ -515,6 +575,7 @@ mod tests {
fn options(graffiti: &str) -> ValidatorOptions {
ValidatorOptions {
beacon_nodes: vec!["http://localhost:5052".to_string()],
network: None,
broadcast: Vec::new(),
validators_dir: PathBuf::from("/tmp/validators"),
secrets_dir: PathBuf::from("/tmp/secrets"),
Expand Down Expand Up @@ -614,6 +675,98 @@ 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]
);
}

/// 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("");
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.
Expand Down
80 changes: 62 additions & 18 deletions crates/validator/src/beacon_node/fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,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,
Expand Down Expand Up @@ -574,39 +576,81 @@ impl<B: BeaconNodeApi> FallbackBeaconNode<B> {
&self,
with_reference: impl FnOnce(&ChainId) -> Result<u64>,
) -> Result<ChainId> {
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`]). 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>,
with_reference: impl FnOnce(&ChainId) -> Result<u64>,
) -> Result<ChainId> {
// 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::<Vec<_>>()
.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;
};
Expand Down
Loading
Loading