Skip to content
Merged
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
5 changes: 4 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,9 @@ actual_slot = finalized_slot + 1 + relative_index
one's left `UNSUBSCRIBE_LAG_EPOCHS` after, blob-parameter (BPO) boundaries included.
**Known gap**: ethrex's `DiscoveryServer` cannot replace the served ENR at runtime, so its
`eth2` entry keeps the startup digest until a restart; peers discovering the node after a
boundary reject the record
boundary reject the record. A restart publishes the new one because the record's `seq`
starts at the clock in milliseconds (`discovery::enr::starting_seq`), above the copy peers
hold; at a fixed starting `seq` they would keep that copy
- Validator custody (fulu `validator.md`; `p2p/src/beacon/validator_custody.rs`): the Beacon
API records every validator index named to `beacon_committee_subscriptions` and
`prepare_beacon_proposer` in `AttachedValidators` (`net/api`; expires after two silent
Expand Down Expand Up @@ -461,6 +463,7 @@ actual_slot = finalized_slot + 1 + relative_index
- Always on for `beacon` (mainnet bootnode ENRs are not statically dialable, so a crawl is its only way to find a peer); opt-in for `node` behind the lean-only `--discovery.enable`, off by default, so a lean node peers from `--bootnodes` alone and binds no discovery socket. `Network::discovery_enabled` is the one answer; `P2P::spawn` takes `Option<DiscoverySpawnConfig>` and `P2PServer.discovery` is an `Option`, `None` leaving the dial loop unscheduled
- Where it runs: `DEFAULT_DISCOVERY_PORT` (9000) unless `--discovery.port` says otherwise (own UDP socket, must differ from `--gossipsub-port`; checked once by `Options::validate_ports`, which skips the discovery rules when it is off). Co-located nodes that run discovery must each pass `--discovery.port`
- Reuses ethrex's `DiscoveryServer` + `PeerTable` with discv4 disabled; `spawn` takes the prepared lean ENR, so the record ethrex serves is the one we report
- The served record is saved to `Metadata["local_enr"]` on the dial tick whenever its `seq` moves (`dial::save_served_enr`, read through `discovery::ServedEnr`), and a start reads it back: the new record is signed above its `seq`, and starts at its address when the node names none (`discovery::resumes_address`), so a restart does not replace the voted record peers hold with one at `0.0.0.0`. A record under another node key carries nothing over
- ENR follows the beacon phase0 spec: `ip`/`udp`/`quic`/`tcp`/`secp256k1`/`eth2`/`attnets`
- Admission mirrors lighthouse: `eth2.fork_digest` must match, `next_fork_*` may differ, a `quic` or `tcp` entry required. Handed to the peer table as `LeanFilter: PeerFilter`, so records are judged on arrival, not at dial time; a reject is re-judged on a higher-`seq` ENR
- Candidates ranked by uncovered attestation subnets. See [`docs/discovery.md`](docs/discovery.md)
Expand Down
87 changes: 86 additions & 1 deletion crates/net/p2p/src/discovery/dial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::time::Duration;

use ethrex_p2p::discovery::lookup_interval_function;
use ethrex_p2p::peer_table::{PeerTable, PeerTableServerProtocol as _};
use ethrex_rlp::encode::RLPEncode;
use libp2p::PeerId;
use libp2p::swarm::dial_opts::DialOpts;
use tokio::sync::mpsc;
Expand All @@ -17,7 +18,7 @@ use tracing::trace;
use super::admission::{DiscoveredPeer, LeanFilter, rank_candidates};
use super::{
DIAL_INTERVAL_AT_TARGET, DIAL_INTERVAL_AT_ZERO_PEERS, DISCOVERY_CANDIDATE_BATCH,
DiscoveryHandle,
DiscoveryHandle, ServedEnr,
};
use crate::swarm_adapter::DialOutcome;
use crate::{ConnectionDirection, P2PServer, metrics};
Expand All @@ -40,6 +41,11 @@ pub(crate) struct DiscoveryState {
/// ends or its dial fails. Read once, when the connection is established,
/// for the Beacon API's peer list.
peer_enrs: HashMap<PeerId, String>,
/// The record discovery serves, read live, and the `seq` it had when it
/// was last saved to the data directory (`None` before the first save).
/// See [`save_served_enr`].
served: ServedEnr,
saved_enr_seq: Option<u64>,
/// Our own peer ID, so the loop never dials itself.
local_peer_id: PeerId,
/// Connected-peer count above which the loop stops dialing.
Expand All @@ -58,6 +64,8 @@ impl DiscoveryState {
candidates: VecDeque::new(),
peer_attnets: HashMap::new(),
peer_enrs: HashMap::new(),
served: handle.served,
saved_enr_seq: None,
local_peer_id,
target_peers: handle.target_peers,
filter: handle.filter,
Expand Down Expand Up @@ -94,6 +102,31 @@ impl DiscoveryState {
/// thing asking at all.
const CONTACT_POLL_IDLE: Duration = Duration::from_millis(250);

/// Save the record discovery serves to the data directory, if it is not the
/// one last saved.
///
/// Called on every dial tick, which runs for as long as discovery does. The
/// record moves without this actor's doing whenever discv5's IP voting
/// re-signs it, so there is no event to save it on: a tick reads the served
/// `seq` and writes only when it has moved, a handful of times in a process's
/// life. What is saved is what the next start takes its address and its `seq`
/// floor from ([`enr::carried_over`](super::enr::carried_over)), so a restart
/// does not put a record at `0.0.0.0` in place of the one peers hold.
pub(crate) fn save_served_enr(server: &mut P2PServer) {
let Some(discovery) = server.discovery.as_mut() else {
return;
};
let served_seq = discovery.served.seq();
if served_seq.is_none() || served_seq == discovery.saved_enr_seq {
return;
}
let Some(record) = discovery.served.record() else {
return;
};
server.store.set_local_enr(&record.encode_to_vec());
discovery.saved_enr_seq = Some(record.seq);
}

/// Drop a peer's discovery bookkeeping.
///
/// Called from both teardown paths — a connection that closed and a dial that
Expand Down Expand Up @@ -527,6 +560,58 @@ mod tests {
PeerId::from_public_key(&Keypair::generate_ed25519().public())
}

#[tokio::test]
async fn the_served_record_is_saved_once_and_again_when_it_moves() {
use super::super::enr::{EnrForkId, LocalEnrParams, build_local_enr_after};
use ethrex_p2p::types::NodeRecord;
use ethrex_rlp::decode::RLPDecode;

let config = ethlambda_types::beacon::config::Config::mainnet();
let mut server = crate::test_support::unconnected_beacon_server(config, 0).await;
let saved = |server: &P2PServer| {
let bytes = server.store.local_enr()?;
Some(NodeRecord::decode(&bytes).expect("what was saved decodes"))
};
let served = |server: &P2PServer| {
let discovery = server.discovery.as_ref().expect("discovery runs");
discovery.served.record().expect("the served record reads")
};
assert_eq!(saved(&server), None);

save_served_enr(&mut server);
let first = saved(&server).expect("the startup record is saved");
assert_eq!(first, served(&server));

// discv5's IP voting re-signs the record at a higher `seq` and writes
// it where this node reads it: the next tick saves that one over the
// first.
let voted = build_local_enr_after(
&LocalEnrParams {
signer: secp256k1::SecretKey::new(&mut rand::rngs::OsRng),
ip: std::net::Ipv4Addr::new(203, 0, 113, 7).into(),
discovery_port: 9000,
p2p_port: 9001,
subscription_subnets: HashSet::new(),
attestation_committee_count: 1,
fork_id: EnrForkId::local(),
custody_group_count: None,
},
Some(first.seq),
)
.expect("a record builds");
assert!(voted.seq > first.seq);
let discovery = server.discovery.as_ref().expect("discovery runs");
discovery.served.replace_for_test(voted.clone());

save_served_enr(&mut server);
assert_eq!(saved(&server), Some(voted));

// Nothing moved: the tick after that writes nothing, and the saved
// record is still the served one.
save_served_enr(&mut server);
assert_eq!(saved(&server), Some(served(&server)));
}

#[test]
fn covered_subnets_unions_only_connected_peers() {
let connected = random_peer();
Expand Down
170 changes: 163 additions & 7 deletions crates/net/p2p/src/discovery/enr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use std::collections::HashSet;
use std::net::IpAddr;

use ethlambda_types::time::unix_now_ms;
use ethrex_p2p::types::{INITIAL_ENR_SEQ, Node, NodeRecord, NodeRecordPairs};
use ethrex_p2p::utils::{node_id, public_key_from_signing_key};
use libssz::SszEncode;
Expand Down Expand Up @@ -233,12 +234,87 @@ pub(crate) fn dialable_port(port: u16) -> Option<u16> {
Some(port).filter(|port| *port != 0)
}

/// Build and sign this node's ENR.
/// Build and sign this node's ENR with no earlier record of its own to
/// follow, as on a first start. For tests, which build peers' records this
/// way; discovery itself goes through [`build_local_enr_after`].
#[cfg(test)]
pub(crate) fn build_local_enr(params: &LocalEnrParams) -> Result<NodeRecord, DiscoveryError> {
NodeRecord::from_pairs(INITIAL_ENR_SEQ, &params.signer, params.local_pairs())
build_local_enr_after(params, None)
}

/// Build and sign this node's ENR, at [`starting_seq`]. `previous_seq` is the
/// `seq` of the record this node last served, when it kept one.
pub(crate) fn build_local_enr_after(
params: &LocalEnrParams,
previous_seq: Option<u64>,
) -> Result<NodeRecord, DiscoveryError> {
let seq = starting_seq(previous_seq);
NodeRecord::from_pairs(seq, &params.signer, params.local_pairs())
.map_err(DiscoveryError::BuildEnr)
}

/// The `seq` this node's record starts at: the current time in milliseconds,
/// or one past `previous_seq`, the `seq` of the record it last served, where
/// the clock has not got that far.
///
/// A peer fetches a record again only once its `seq` grows. Starting every boot
/// from [`INITIAL_ENR_SEQ`] would serve a record at or behind the copy peers
/// cached from the previous run, and they would keep that one. That is what
/// makes a restart publish what the running node cannot: the served `eth2`
/// entry keeps its startup fork digest across a boundary
/// ([`update_served_enr`](super::update_served_enr)), and only a restart whose
/// record peers take replaces it. An upgrade that changes which entries the
/// record carries depends on it the same way.
///
/// The clock alone clears the previous run in every ordinary case: the only
/// edits to a running record are discv5 IP voting's, one `seq` each, so that
/// run would have had to edit its record more than once per millisecond of
/// uptime to pass it. `previous_seq` is for the other case, a clock that reads
/// earlier than it did while the previous run was serving. It is known when
/// the node kept its last record ([`carried_over`]); a first start, or one
/// under a new key, has the clock alone. geth does the same with the counter
/// it stores, falling back to the clock for a node it has none for.
fn starting_seq(previous_seq: Option<u64>) -> u64 {
let above_previous = previous_seq.map_or(INITIAL_ENR_SEQ, |seq| seq.saturating_add(1));
unix_now_ms().max(above_previous)
}

/// What a start takes over from the record this node last served.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct CarriedOver {
/// The address that record advertised, if it names a host.
pub(crate) ip: Option<IpAddr>,
/// That record's `seq`, which the new record starts above.
pub(crate) seq: Option<u64>,
}

/// What this start may take over from `previous`, the record the last run
/// served: nothing, unless the record is this node's own, signed by the key
/// `signer` holds.
///
/// The record comes out of the node's own data directory, but a directory can
/// be given another node key, and the record in it then describes another
/// identity: its address is not this node's to advertise, and its `seq` counts
/// another node's records.
pub(crate) fn carried_over(previous: &NodeRecord, signer: &SecretKey) -> CarriedOver {
let key = signer.public_key(secp256k1::SECP256K1).serialize();
if !record_is_keyed_by(previous, &key) || !previous.verify_signature() {
return CarriedOver::default();
}
CarriedOver {
ip: read_ip(previous.pairs()).filter(|ip| !ip.to_canonical().is_unspecified()),
seq: Some(previous.seq),
}
}

/// Whether `record` belongs to the node whose compressed public key is `key`.
fn record_is_keyed_by(record: &NodeRecord, key: &[u8; 33]) -> bool {
record
.pairs()
.secp256k1
.is_some_and(|entry| entry.as_bytes() == key)
}

/// The address a record advertises, preferring IPv4 when it carries both.
///
/// `None` for a record with neither `ip` nor `ip6`, which names no host to
Expand Down Expand Up @@ -296,17 +372,97 @@ mod tests {
use std::net::Ipv4Addr;

fn build() -> NodeRecord {
build_local_enr(&LocalEnrParams {
signer: secp256k1::SecretKey::new(&mut rand::rngs::OsRng),
ip: IpAddr::from(Ipv4Addr::LOCALHOST),
let signer = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);
build_local_enr(&params_of(signer, Ipv4Addr::LOCALHOST)).expect("ENR builds")
}

/// What `signer`'s node publishes when it advertises `ip`.
fn params_of(signer: SecretKey, ip: Ipv4Addr) -> LocalEnrParams {
LocalEnrParams {
signer,
ip: IpAddr::from(ip),
discovery_port: 9010,
p2p_port: 9001,
subscription_subnets: HashSet::from([1u64, 4]),
attestation_committee_count: 8,
fork_id: EnrForkId::local(),
custody_group_count: None,
})
.expect("ENR builds")
}
}

/// An address discv5's IP voting could have settled on.
const VOTED: Ipv4Addr = Ipv4Addr::new(203, 0, 113, 7);

#[test]
fn a_start_takes_over_the_address_and_seq_of_this_nodes_last_record() {
// The record the last run was serving when it stopped, after IP voting
// had found the address. A start that began again at `0.0.0.0` would,
// being newer, take that address away from every peer that held it.
let signer = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);
let last = build_local_enr(&params_of(signer, VOTED)).expect("ENR builds");

let carried = carried_over(&last, &signer);

assert_eq!(carried.ip, Some(IpAddr::from(VOTED)));
assert_eq!(carried.seq, Some(last.seq));
}

#[test]
fn a_last_record_that_never_found_its_address_carries_only_its_seq() {
let signer = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);
let last = build_local_enr(&params_of(signer, Ipv4Addr::UNSPECIFIED)).expect("builds");

let carried = carried_over(&last, &signer);

assert_eq!(carried.ip, None);
assert_eq!(carried.seq, Some(last.seq));
}

#[test]
fn a_record_under_another_key_carries_nothing_over() {
// A data directory given a new node key still holds the old
// identity's record. Its address and its `seq` are not this node's.
let previous_key = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);
let last = build_local_enr(&params_of(previous_key, VOTED)).expect("ENR builds");
let signer = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);

assert_eq!(carried_over(&last, &signer), CarriedOver::default());
}

#[test]
fn a_record_starts_above_the_last_one_whatever_the_clock_says() {
// The last run served under a clock a day ahead of this one. The
// clock alone would put the new record behind it, and peers would keep
// the old one.
let signer = secp256k1::SecretKey::new(&mut rand::rngs::OsRng);
let ahead_of_the_clock = unix_now_ms() + 24 * 60 * 60 * 1_000;

let record =
build_local_enr_after(&params_of(signer, VOTED), Some(ahead_of_the_clock)).unwrap();

assert_eq!(record.seq, ahead_of_the_clock + 1);
assert!(record.verify_signature());
}

/// A restart must not serve a `seq` at or below what the previous run
/// reached: peers would keep their cached copy, stale `eth2` included. A
/// record that started at a fixed `seq` went back there on every boot.
#[test]
fn the_record_starts_at_the_clock_not_at_a_fixed_seq() {
let before = unix_now_ms();
let first = build();
let second = build();

// At least the clock when it was built, which a run's edits, one `seq`
// each, do not reach: that is what puts the next start's record ahead.
assert!(
first.seq >= before,
"seq {} is behind the clock, {before}",
first.seq
);
// And a later start is not behind an earlier one.
assert!(second.seq >= first.seq);
assert!(first.verify_signature());
}

#[test]
Expand Down
Loading