diff --git a/CLAUDE.md b/CLAUDE.md index 96a434dc4..e6b54e153 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 @@ -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` 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) diff --git a/crates/net/p2p/src/discovery/dial.rs b/crates/net/p2p/src/discovery/dial.rs index c8270b387..f325a1dc1 100644 --- a/crates/net/p2p/src/discovery/dial.rs +++ b/crates/net/p2p/src/discovery/dial.rs @@ -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; @@ -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}; @@ -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, + /// 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, /// Our own peer ID, so the loop never dials itself. local_peer_id: PeerId, /// Connected-peer count above which the loop stops dialing. @@ -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, @@ -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 @@ -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(); diff --git a/crates/net/p2p/src/discovery/enr.rs b/crates/net/p2p/src/discovery/enr.rs index 80d187c77..6b239c754 100644 --- a/crates/net/p2p/src/discovery/enr.rs +++ b/crates/net/p2p/src/discovery/enr.rs @@ -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; @@ -233,12 +234,87 @@ pub(crate) fn dialable_port(port: u16) -> Option { 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::from_pairs(INITIAL_ENR_SEQ, ¶ms.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, +) -> Result { + let seq = starting_seq(previous_seq); + NodeRecord::from_pairs(seq, ¶ms.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 { + 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, + /// That record's `seq`, which the new record starts above. + pub(crate) seq: Option, +} + +/// 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 @@ -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(¶ms_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(¶ms_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(¶ms_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(¶ms_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(¶ms_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] diff --git a/crates/net/p2p/src/discovery/mod.rs b/crates/net/p2p/src/discovery/mod.rs index 9d4242bba..00e35b8e7 100644 --- a/crates/net/p2p/src/discovery/mod.rs +++ b/crates/net/p2p/src/discovery/mod.rs @@ -20,14 +20,14 @@ use std::time::Duration; use ethrex_p2p::discovery::{DiscoveryConfig, DiscoveryServer}; use ethrex_p2p::peer_table::{PeerTable, PeerTableServer}; -use ethrex_p2p::types::{LocalNode, Node, SharedLocalNode}; +use ethrex_p2p::types::{LocalNode, Node, NodeRecord, SharedLocalNode}; use tokio::net::UdpSocket; use tokio::sync::watch; use tracing::{info, warn}; use crate::Bootnode; use admission::LeanFilter; -use enr::{EnrForkId, LocalEnrParams, build_local_enr}; +use enr::{EnrForkId, LocalEnrParams, build_local_enr_after}; /// Dials per second the loop opens when this node has no peers at all. /// @@ -151,6 +151,37 @@ pub struct DiscoveryHandle { /// The configured [`DiscoverySpawnConfig::target_peers`], carried through to /// the dial loop, which is the only thing it governs. pub target_peers: usize, + /// The record discovery serves right now, for saving it; see [`ServedEnr`]. + pub(crate) served: ServedEnr, +} + +/// The record discovery serves right now. +/// +/// discv5's IP voting re-signs the record at runtime with a new address and a +/// higher `seq`, and ethrex writes every record it re-signs into the +/// [`SharedLocalNode`] it was started with. This reads through that, which is +/// how the dial loop notices the record has moved and saves it +/// ([`dial::save_served_enr`]). +#[derive(Clone)] +pub(crate) struct ServedEnr(SharedLocalNode); + +impl ServedEnr { + /// The `seq` of the served record, or `None` if the lock is poisoned. + pub(crate) fn seq(&self) -> Option { + Some(self.0.read().ok()?.record.seq) + } + + /// The served record itself, or `None` if the lock is poisoned. + pub(crate) fn record(&self) -> Option { + Some(self.0.read().ok()?.record.clone()) + } + + /// Put `record` where ethrex writes each record it re-signs, as discv5's + /// IP voting does. + #[cfg(test)] + pub(crate) fn replace_for_test(&self, record: NodeRecord) { + self.0.write().expect("local node lock").record = record; + } } /// Bind the discv5 socket, build the local ENR, and start ethrex's discovery @@ -164,8 +195,14 @@ pub struct DiscoveryHandle { /// separate question from whether `build_swarm` dials one statically, which /// turns on its `quic`/`tcp` entries: a bootnode can do both, either, or /// neither. +/// +/// `previous` is the record this node last served, kept in its data directory +/// (`Store::local_enr`), or `None` on a first start. A start that names no +/// address of its own takes that record's, and every start signs above its +/// `seq`: see [`resumes_address`] and [`enr::carried_over`]. pub async fn spawn_discovery( config: DiscoverySpawnConfig, + previous: Option, ) -> Result { let signer = secp256k1::SecretKey::from_slice(&config.node_key).map_err(DiscoveryError::NodeKey)?; @@ -179,7 +216,15 @@ pub async fn spawn_discovery( })?; let bound = socket.local_addr().map_err(DiscoveryError::SocketAddr)?; - let advertise_ip = config.advertise_ip.unwrap_or(config.bind_ip); + let configured_ip = config.advertise_ip.unwrap_or(config.bind_ip); + let carried = previous + .as_ref() + .map(|record| enr::carried_over(record, &signer)) + .unwrap_or_default(); + let resumed_ip = carried + .ip + .filter(|last| resumes_address(*last, configured_ip, config.bind_ip)); + let advertise_ip = resumed_ip.unwrap_or(configured_ip); let params = LocalEnrParams { signer, ip: advertise_ip, @@ -191,7 +236,7 @@ pub async fn spawn_discovery( custody_group_count: config.custody_group_count, }; let local_node = params.local_node(); - let local_record = build_local_enr(¶ms)?; + let local_record = build_local_enr_after(¶ms, carried.seq)?; // EIP-778's text form is URL-safe base64 *without* padding let local_enr = local_record .enr_url() @@ -234,14 +279,16 @@ pub async fn spawn_discovery( // number, keeping the extra entries. // // ethrex mirrors each re-signed record into the shared identity for its own - // RPC and shutdown; nothing here reads it back, so it is handed over and - // dropped. The fork id channel republishes an execution chain's EIP-2124 - // `eth` entry, which a consensus record does not carry: it starts at `None` - // and its sender is dropped at once, which ethrex reads as "never changes". + // RPC and shutdown. `ServedEnr` keeps a clone to read the served record + // back through, for saving it. The fork id channel republishes an execution + // chain's EIP-2124 `eth` entry, which a consensus record does not carry: it + // starts at `None` and its sender is dropped at once, which ethrex reads as + // "never changes". let shared_local_node: SharedLocalNode = Arc::new(RwLock::new(LocalNode { node: local_node.clone(), record: local_record.clone(), })); + let served = ServedEnr(shared_local_node.clone()); let (_, no_fork_id) = watch::channel(None); DiscoveryServer::spawn( local_node, @@ -269,7 +316,13 @@ pub async fn spawn_discovery( .map_err(|err| DiscoveryError::Server(err.to_string()))?; info!(enr = %local_enr, "Local ENR"); - if unspecified_as_published(advertise_ip) { + if let Some(ip) = resumed_ip { + info!( + %ip, + "Local ENR starts from the address this node's last record carried; \ + discv5 IP voting replaces it if it has changed" + ); + } else if unspecified_as_published(advertise_ip) { warn!( "Local ENR advertises an unspecified IP; peers can still reach us once \ discv5 IP voting resolves our external address, but this ENR is not \ @@ -283,6 +336,7 @@ pub async fn spawn_discovery( local_enr, filter, target_peers: config.target_peers, + served, }) } @@ -303,16 +357,37 @@ pub async fn spawn_discovery( /// `Status`, which does follow the switch) and the admission filter does move, /// but a peer that discovers this node after a boundary reads the stale digest /// and rejects the record, so a long-running node becomes harder to find until -/// it is restarted. +/// it is restarted. A restart signs a new record at a higher `seq` +/// ([`enr::build_local_enr`]), which is what makes peers holding the old one +/// fetch it. pub(crate) fn update_served_enr(fork_id: &EnrForkId) { warn!( fork_digest = %hex::encode(fork_id.fork_digest), next_fork_epoch = fork_id.next_fork_epoch, "The served ENR keeps its startup eth2 entry: the discovery server offers no way to \ - replace its record at runtime" + replace its record at runtime. Restart the node to publish the new fork digest" ); } +/// Whether a start takes `last`, the address its last record carried, as the +/// one to advertise. +/// +/// Only when this start names none. `configured` is `--discovery.advertise-ip` +/// or else the bind address, and an address the operator gave stands. Without +/// one the record would start at `0.0.0.0`, and since it is newer than the +/// record peers hold from the previous run, they would swap a record they can +/// dial for one they cannot until IP voting had settled again. Starting from +/// the last address avoids that, and costs nothing when the address has +/// changed: voting is on in this case and replaces it as it would at runtime. +/// +/// And only within the family the discovery socket is bound on, since a +/// record advertising the other one names an address this node cannot answer +/// from. +fn resumes_address(last: IpAddr, configured: IpAddr, bind: IpAddr) -> bool { + unspecified_as_published(configured) + && last.to_canonical().is_ipv4() == bind.to_canonical().is_ipv4() +} + /// Whether `ip` is the unspecified address once read the way the ENR /// publishes it, an IPv4-mapped IPv6 address as the IPv4 address it maps /// (`LocalEnrParams::local_pairs`): `0.0.0.0`, `::` and `::ffff:0.0.0.0` @@ -362,7 +437,7 @@ mod tests { async fn spawn_binds_the_socket_and_returns_the_local_enr() { // Port 0 asks the OS for a free port, so the test cannot collide with a // running node or a sibling test. - let handle = spawn_discovery(config(0, None)) + let handle = spawn_discovery(config(0, None), None) .await .expect("discovery spawns"); @@ -392,7 +467,7 @@ mod tests { // locally. The ENR must reflect the advertised address, not the bind // address. let advertised = Ipv4Addr::new(203, 0, 113, 7); - let handle = spawn_discovery(config(0, Some(IpAddr::from(advertised)))) + let handle = spawn_discovery(config(0, Some(IpAddr::from(advertised))), None) .await .expect("discovery spawns"); @@ -404,11 +479,86 @@ mod tests { let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); let busy = socket.local_addr().unwrap().port(); - let result = spawn_discovery(config(busy, None)).await; + let result = spawn_discovery(config(busy, None), None).await; assert!(result.is_err(), "a busy discovery port must not be silent"); } + #[tokio::test] + async fn a_restart_serves_the_address_its_last_record_carried() { + // No address of its own to advertise, as on a node started without + // `--discovery.advertise-ip` and bound to the wildcard. The last run's + // record had the address IP voting found. + let voted = IpAddr::from(Ipv4Addr::new(203, 0, 113, 7)); + let restart = config(0, Some(IpAddr::from(Ipv4Addr::UNSPECIFIED))); + let signer = secp256k1::SecretKey::from_slice(&restart.node_key).expect("a valid key"); + let last = enr::build_local_enr(&LocalEnrParams { + signer, + ip: voted, + discovery_port: 9000, + p2p_port: restart.p2p_port, + subscription_subnets: restart.subscription_subnets.clone(), + attestation_committee_count: restart.attestation_committee_count, + fork_id: restart.fork_id, + custody_group_count: None, + }) + .expect("the last record builds"); + + let handle = spawn_discovery(restart, Some(last.clone())) + .await + .expect("discovery spawns"); + + let served = decode_enr(&handle.local_enr); + assert_eq!(enr::read_ip(served.pairs()), Some(voted)); + assert!(served.seq > last.seq, "and peers take it over the last one"); + assert_eq!(handle.served.record(), Some(served)); + } + + #[tokio::test] + async fn an_address_the_operator_names_is_not_replaced_by_the_last_records() { + let named = IpAddr::from(Ipv4Addr::new(198, 51, 100, 9)); + let restart = config(0, Some(named)); + let signer = secp256k1::SecretKey::from_slice(&restart.node_key).expect("a valid key"); + let last = enr::build_local_enr(&LocalEnrParams { + signer, + ip: IpAddr::from(Ipv4Addr::new(203, 0, 113, 7)), + discovery_port: 9000, + p2p_port: restart.p2p_port, + subscription_subnets: restart.subscription_subnets.clone(), + attestation_committee_count: restart.attestation_committee_count, + fork_id: restart.fork_id, + custody_group_count: None, + }) + .expect("the last record builds"); + + let handle = spawn_discovery(restart, Some(last)) + .await + .expect("discovery spawns"); + + let served = decode_enr(&handle.local_enr); + assert_eq!(enr::read_ip(served.pairs()), Some(named)); + } + + #[test] + fn the_last_address_is_taken_only_within_the_bound_family() { + let ip = |text: &str| text.parse::().unwrap(); + + assert!(resumes_address( + ip("203.0.113.7"), + ip("0.0.0.0"), + ip("0.0.0.0") + )); + assert!(resumes_address(ip("2001:db8::7"), ip("::"), ip("::"))); + assert!( + !resumes_address(ip("2001:db8::7"), ip("0.0.0.0"), ip("0.0.0.0")), + "an IPv4 socket cannot answer at an IPv6 address" + ); + assert!( + !resumes_address(ip("203.0.113.7"), ip("198.51.100.9"), ip("0.0.0.0")), + "an address the operator named stands" + ); + } + /// The IPv4-mapped form of `0.0.0.0` is published as `0.0.0.0`, so it must /// leave IP voting on like the other two spellings, where the raw /// `is_unspecified` would have locked it. diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index b72b0003b..a89749f4d 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -97,7 +97,10 @@ use tracing::{debug, info, trace, warn}; use crate::{ discovery::{ DIAL_INTERVAL_AT_TARGET, DIAL_INTERVAL_AT_ZERO_PEERS, DiscoveryError, DiscoverySpawnConfig, - dial::{DiscoveryState, dial_interval, dial_progress, dial_tick, forget_discovered_peer}, + dial::{ + DiscoveryState, dial_interval, dial_progress, dial_tick, forget_discovered_peer, + save_served_enr, + }, enr::{dialable_port, read_ip, read_public_key, read_quic_port, read_tcp_port}, spawn_discovery, }, @@ -1648,7 +1651,14 @@ impl P2P { ) -> Result { let (discovery, local_enr) = match discovery { Some(config) => { - let discovery = spawn_discovery(config).await?; + // The record this node last served, which the new one starts + // from. One that does not decode is as good as none. + let previous = store.local_enr().and_then(|bytes| { + NodeRecord::decode(&bytes) + .inspect_err(|err| warn!(%err, "Ignoring the saved local ENR")) + .ok() + }); + let discovery = spawn_discovery(config, previous).await?; let local_enr = discovery.local_enr.clone(); (Some(discovery), Some(local_enr)) } @@ -2337,6 +2347,7 @@ impl P2PServer { let Some(target_peers) = self.discovery.as_ref().map(DiscoveryState::target_peers) else { return; }; + save_served_enr(self); let dialed = dial_tick(self, target_peers).await; // Rescheduled on every path out of the tick, so nothing above can stop // the loop. The gap is a function of how full the peer table is rather @@ -4234,21 +4245,24 @@ pub(crate) mod test_support { crate::swarm_adapter::start_swarm_adapter(built.swarm, HashMap::new()); drain_swarm_events(swarm_stream); - let discovery = crate::discovery::spawn_discovery(crate::discovery::DiscoverySpawnConfig { - node_key: secp256k1::SecretKey::new(&mut rand::rngs::OsRng) - .secret_bytes() - .to_vec(), - bind_ip: IpAddr::from(Ipv4Addr::LOCALHOST), - discovery_port: 0, - p2p_port: 0, - subscription_subnets: HashSet::new(), - attestation_committee_count: 1, - bootnodes: Vec::new(), - advertise_ip: None, - target_peers: 0, - fork_id: EnrForkId::local(), - custody_group_count: None, - }) + let discovery = crate::discovery::spawn_discovery( + crate::discovery::DiscoverySpawnConfig { + node_key: secp256k1::SecretKey::new(&mut rand::rngs::OsRng) + .secret_bytes() + .to_vec(), + bind_ip: IpAddr::from(Ipv4Addr::LOCALHOST), + discovery_port: 0, + p2p_port: 0, + subscription_subnets: HashSet::new(), + attestation_committee_count: 1, + bootnodes: Vec::new(), + advertise_ip: None, + target_peers: 0, + fork_id: EnrForkId::local(), + custody_group_count: None, + }, + None, + ) .await .expect("discovery spawns"); diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index 5e080f4b8..4df2d39be 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -3644,21 +3644,24 @@ pub(crate) mod tests { crate::swarm_adapter::start_swarm_adapter(built.swarm, HashMap::new()); crate::test_support::drain_swarm_events(swarm_stream); - let discovery = crate::discovery::spawn_discovery(crate::discovery::DiscoverySpawnConfig { - node_key: secp256k1::SecretKey::new(&mut rand::rngs::OsRng) - .secret_bytes() - .to_vec(), - bind_ip: IpAddr::from(Ipv4Addr::LOCALHOST), - discovery_port: 0, - p2p_port: 0, - subscription_subnets: HashSet::new(), - attestation_committee_count: 1, - bootnodes: Vec::new(), - advertise_ip: None, - target_peers: 0, - fork_id: EnrForkId::local(), - custody_group_count: None, - }) + let discovery = crate::discovery::spawn_discovery( + crate::discovery::DiscoverySpawnConfig { + node_key: secp256k1::SecretKey::new(&mut rand::rngs::OsRng) + .secret_bytes() + .to_vec(), + bind_ip: IpAddr::from(Ipv4Addr::LOCALHOST), + discovery_port: 0, + p2p_port: 0, + subscription_subnets: HashSet::new(), + attestation_committee_count: 1, + bootnodes: Vec::new(), + advertise_ip: None, + target_peers: 0, + fork_id: EnrForkId::local(), + custody_group_count: None, + }, + None, + ) .await .expect("discovery spawns"); diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 494cef0a4..8d5431a60 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -303,6 +303,12 @@ const KEY_CUSTODIED_GROUP_COUNT: &[u8] = b"custodied_group_count"; /// it's SSZ-encoded. Both rows are absent in a directory written before they /// existed, which did not bump [`DB_VERSION`] either. const KEY_CUSTODY_SINCE_SLOT: &[u8] = b"custody_since_slot"; +/// The ENR this node last served over discovery, RLP-encoded as on the wire. +/// Read at startup, so a restart's record starts from the address the last one +/// carried and above its `seq`; `ethlambda-p2p`'s `discovery` says why. Absent +/// until a node has run discovery from this directory, and in one written +/// before the row existed, which did not bump [`DB_VERSION`]. +const KEY_LOCAL_ENR: &[u8] = b"local_enr"; /// The on-disk format this build reads and writes. /// /// Bumped whenever a table's key or value layout changes. `from_db_state` @@ -5914,6 +5920,25 @@ impl Store { ]); } + /// The ENR this node last served over discovery, as the bytes + /// [`Self::set_local_enr`] was given. `None` until one was saved. + pub fn local_enr(&self) -> Option> { + let view = self.backend.begin_read().expect("read view"); + view.read_with(Table::Metadata, KEY_LOCAL_ENR, |bytes| bytes.to_vec()) + .expect("read") + } + + /// Save the ENR this node serves over discovery, replacing the last one. + /// The bytes are the caller's encoding and come back as given. + pub fn set_local_enr(&self, record: &[u8]) { + let mut batch = self.backend.begin_write().expect("write batch"); + let entries = vec![(KEY_LOCAL_ENR.to_vec(), record.to_vec())]; + batch + .put_batch(Table::Metadata, entries) + .expect("put metadata"); + batch.commit().expect("commit"); + } + /// An SSZ `u64` metadata row that may be absent. fn read_optional_metadata(&self, key: &[u8]) -> Option { let view = self.backend.begin_read().expect("read view"); @@ -6232,6 +6257,21 @@ mod tests { assert_eq!(reopened.custody_record(), Some(record)); } + /// The served ENR is on disk too: a restart reads back the bytes the last + /// run saved, and a later save replaces them. + #[test] + fn the_served_enr_survives_a_reopen() { + let backend: Arc = Arc::new(InMemoryBackend::new()); + let store = beacon_test_store(Arc::clone(&backend)); + assert_eq!(store.local_enr(), None); + + store.set_local_enr(b"first record"); + store.set_local_enr(b"the record after it"); + + let reopened = beacon_test_store(backend); + assert_eq!(reopened.local_enr(), Some(b"the record after it".to_vec())); + } + #[test] fn a_beacon_block_reads_back_as_the_fork_it_was_written_as() { // `get_signed_block` dispatches on the store's own chain tag, so this diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 13a2bb1dc..42b2b1b96 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -80,7 +80,10 @@ digest (or the next one, within clock skew of the boundary). One gap: the ENR this node serves over discv5 keeps the `eth2` entry it started with, because ethrex's `DiscoveryServer` offers no way to replace its record at runtime. Peers already connected are unaffected; peers discovering the node -after a boundary read the stale digest and reject the record. +after a boundary read the stale digest and reject the record. A restart after +the boundary publishes the new digest: the record is signed at a `seq` taken +from the clock, above the one peers hold, so they fetch it +(see [discovery.md](./discovery.md#the-enr)). ## Gossip diff --git a/docs/cli.md b/docs/cli.md index ea8ad8672..b490ee56c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -61,7 +61,7 @@ one `CommonOptions` struct flattened into each. | `--http-address` | `127.0.0.1` | Bind address for both HTTP servers | | `--api-port` | `5052` | API server port. `beacon` binds it too, off its own anchored store rather than an empty one; the lean-shaped `/lean/v0` routes still don't answer for it (see [`beacon` flags](#beacon-flags) below) | | `--metrics-port` | `5054` | Metrics and debug server port. Equal to `--api-port` merges the routers onto one listener | -| `--node-key` | `/node.key` | Hex file holding the secp256k1 key that is this node's libp2p and discv5 identity. When omitted, the key stored in `--data-dir` as `node.key` is used, generated and stored there (mode `0600`) on the directory's first start, so the PeerId and ENR stay the same across restarts until the directory is wiped | +| `--node-key` | `/node.key` | Hex file holding the secp256k1 key that is this node's libp2p and discv5 identity. When omitted, the key stored in `--data-dir` as `node.key` is used, generated and stored there (mode `0600`) on the directory's first start, so the PeerId and the discv5 node id stay the same across restarts until the directory is wiped. The ENR's text does not: the record is signed anew at every start, at a higher `seq` (see [Peer discovery](./discovery.md)) | | `--checkpoint-sync-url` | see below | API base URLs, tried in order until one answers. Supplies `node`'s starting state on the lean API, and `beacon`'s anchor on a standard Beacon API; required on a fresh `beacon` data directory only for a built-in network, since a loaded network anchors at its own `genesis.ssz` instead. See [`checkpoint_sync.md`](checkpoint_sync.md) | | `--discovery.port` | `9000` | discv5 UDP port; must differ from `--gossipsub-port`. See [Peer discovery](./discovery.md) | | `--discovery.advertise-ip` | bind address | IP published in the ENR | diff --git a/docs/data_storage.md b/docs/data_storage.md index ed80baa97..b96c77f3a 100644 --- a/docs/data_storage.md +++ b/docs/data_storage.md @@ -298,6 +298,7 @@ different checkpoints. | `validator_custody_count` | `u64` | beacon | Highest custody group count attached validators have required; only ever raised, absent until one has (see [Validator custody](beacon_wire.md#validator-custody)) | | `custodied_group_count` | `u64` | beacon | Custody groups whose columns the last start held (its sampling size); written with `custody_since_slot`, just before the chain actor spawns | | `custody_since_slot` | `u64` | beacon | First slot from which every column of `custodied_group_count` is held; `Status` reports it when later than the anchor | +| `local_enr` | RLP `NodeRecord` | both | The ENR this node last served over discovery; a restart starts its record from this one's address and above its `seq` (see [Peer discovery](discovery.md)). Absent until discovery has run | Rows marked for one chain are never written on the other, so reaching one through the wrong chain's accessor panics naming the key rather than reading a diff --git a/docs/discovery.md b/docs/discovery.md index 6e800aa7f..1118515c2 100644 --- a/docs/discovery.md +++ b/docs/discovery.md @@ -85,6 +85,31 @@ voting later changes our external address, ethrex edits and re-signs that record rather than rebuilding one, so the consensus entries survive the bump; only the sequence number and `ip` move, which the reported ENR then lags. +The record starts each boot at `seq` = the current time in milliseconds, not at +a constant. A peer identifies a record by (node id, seq) and takes a replacement +only at a strictly higher `seq`, and ethrex's WHOAREYOU responder does not even +send the record when the requester's `enr_seq` already matches. A restart that +began again from a constant would therefore serve a record at or behind the one +peers cached from the previous run (which IP voting may have bumped), and they +would keep the cached copy, stale `eth2`, address and all. The same goes for an +upgrade that changes which entries the record carries. The clock clears the +previous run in every ordinary case: that run would have had to edit its record +more than once per millisecond of uptime to pass it. The node also keeps the +record it last served (the `local_enr` row of its data directory, written +whenever the record's `seq` moves) and signs the next one above that record's +`seq`, so a clock that reads earlier than it did then does not put the new +record behind. + +The kept record is also where a node started without `--discovery.advertise-ip` +gets its first address from. Such a node does not know its address until IP +voting finds it, and a first record at the bind address (`0.0.0.0`), being +newer, would replace the voted record peers held from the previous run with one +they cannot dial. So the new record starts from the address the last one +carried. If the address has changed since, voting replaces it as it would at +runtime. A first start has no record to take one from and starts at the bind +address, and so does a start under another node key, or one whose discovery +socket is bound on the other address family. + ## Which peers get dialed A discovered peer is admitted only if: @@ -98,7 +123,9 @@ hardcoded dummy and `beacon` passes the digest it derived at startup and moves it at each fork-digest boundary, so one admission policy serves both chains. The record this node serves is not refreshed at a boundary (ethrex's `DiscoveryServer` cannot replace it at runtime), so its `eth2` entry keeps the -startup digest until a restart; see [beacon_wire.md](./beacon_wire.md#the-fork-digest). +startup digest until a restart, whose record peers take because it starts at a +higher `seq` (see [The ENR](#the-enr)); see +[beacon_wire.md](./beacon_wire.md#the-fork-digest). A differing `next_fork_version` or `next_fork_epoch` is *not* grounds for rejection: the spec permits connecting to a peer that is incompatible with an @@ -269,24 +296,6 @@ redial is what keeps a devnet's own bootnode reachable across its restarts. Splitting the flag into initial peers, dialed once, and bootnodes, seeded into discv5, is the real fix and is left to a follow-up. -### An upgrade's new ENR entries are invisible to peers that stayed up - -The record is signed at ethrex's `INITIAL_ENR_SEQ`, a constant. A peer -identifies a record by (node id, seq) and accepts a replacement only at a -strictly higher seq, and ethrex's WHOAREYOU responder does not even send the -record when the requester's `enr_seq` already matches. So when an ethlambda -release changes which entries it publishes, as adding `tcp` did, a peer holding -the previous record under the same seq keeps it: the new entries reach only -peers that meet this node for the first time. - -A fixed local floor above `INITIAL_ENR_SEQ` does not close this. ethrex re-signs -the record at `seq + 1` whenever discv5's IP voting moves the advertised -address, so a node behind NAT may already be serving a seq above any constant -the code could pick, which is exactly the case the floor was meant to cover. -Closing it needs a seq that grows without bound across restarts: a persisted -counter bumped on every content change, or one derived from the wall clock at -startup, which is what several beacon clients do. - ### One lean devnet is not separated from another The spec's `fork_digest` is derived from genesis, so it separates one chain from