diff --git a/CLAUDE.md b/CLAUDE.md index 96a434dc4..22dc06d46 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -361,6 +361,7 @@ actual_slot = finalized_slot + 1 + relative_index - Topic: `/leanconsensus/{fork_digest}/{block|aggregation|attestation_N}/ssz_snappy` - `fork_digest` is a 4-byte hex string (no `0x` prefix); currently the dummy `12345678` agreed across clients - Mesh size: 8 (6-12 bounds), heartbeat: 700ms + - Subscription filter (`p2p/src/subscription_filter.rs`): gossipsub stores a peer's subscription only for a topic on the allowlist, which bounds what one peer holds, so a peer cannot grow this node's memory with topics of its own. The allowlist is every kind and every column, attestation and sync committee subnet under every digest of the `ForkSchedule` (`beacon::topics::every_topic`; lean: its three kinds and every committee subnet below `VALIDATOR_REGISTRY_LIMIT`, plus the ones it was told to join), built once at startup. Every subnet is on it, joined or not, because fanout publishing picks its peers from the stored subscriptions. The same filter gates this node's own `subscribe`, so a new subnet family has to be added to `every_topic` or the node cannot join it (a new global kind comes through `BeaconTopics::for_fork`). There is no per-peer count below the whole allowlist: a refused join is never resent, and a peer's held digests depend on its own client's join and leave timing (each join counted before the leaves that follow it). A hello over the per-RPC limit (twice the allowlist, at least 500) is ignored whole. See [`docs/beacon_wire.md`](docs/beacon_wire.md#which-subscriptions-are-kept) - Beacon wire: `validate_messages()` is on, so every beacon message waits for a verdict (~4.2s before gossipsub's cache evicts it). Rules in `state_transition::beacon::gossip` (cheap half inline, stateful half on a bounded `spawn_blocking` task); plumbing in `p2p/src/beacon/verdict.rs`. Lean gossip still auto-forwards - A subnet attestation or aggregate whose vote block is not imported yet (`UnknownBlock`/`StateUnavailable`) is parked with its verdict withheld (`p2p/src/beacon/parked_votes.rs`, lighthouse's reprocess queue) and checked once more when the chain actor's import sends `block_state_ready`; past 2.5 s, or with 16,384 held (parked, or released and not checked again yet; 2,048 of them aggregates; votes for a block not stored yet, whose root any peer can make up, at most half of each), it gets its first verdict instead. Rechecks run on their own permit pool (`recheck_permits`), not the attestation pool - Beacon peer scoring: lighthouse's parameters ported in `p2p/src/beacon/scoring.rs` (block, aggregate, 64 attestation subnets, exits, slashings; columns and sync contributions unscored), refreshed every slot from the head's active validator count. Mesh-delivery scoring (P3) is gated off while the head lags more than 4 slots and for an epoch after, because a catching-up node `Ignore`s every aggregate and would otherwise graylist its own mesh. Every held fork digest is parametrized before `transition::apply` joins it (gossipsub never scores a mesh grafted before its topic had parameters); the previous digest's weights are zeroed at the switch, and the switch restarts the P3 warmup. The swarm disconnects peers below the graylist (-16000) every 10 s, and peers gossipsub reported as `SlowPeer` in every check for a minute (a disabled gossipsub handler never drains its send queue, so the queue's message copies stay in memory until the connection closes). Gossipsub reports an expired forward like a full queue, so our own saturated uplink makes every peer look slow: a report counts only above `SLOW_PEER_REPORT_THRESHOLD` failures (Lighthouse's cut), and one check disconnects at most `MAX_SLOW_PEER_DISCONNECTS_PER_CHECK` peers. Lean runs unscored. See [`docs/beacon_wire.md`](docs/beacon_wire.md#peer-scoring) diff --git a/crates/net/p2p/src/beacon/scoring.rs b/crates/net/p2p/src/beacon/scoring.rs index 269d57d7d..467f65fce 100644 --- a/crates/net/p2p/src/beacon/scoring.rs +++ b/crates/net/p2p/src/beacon/scoring.rs @@ -1354,7 +1354,12 @@ mod tests { }; peer.swarm.dial(node_addr).expect("dial is accepted"); - let control = IdentTopic::new(topic_name([0xAB; 4], BEACON_BLOCK)); + // The control topic is under the genesis digest: one the subscription + // filter lists, as it does every digest of the schedule, and far + // outside the window the rollover below opens, so nothing but this + // test joins it. + let control_digest = schedule.digest_at(0); + let control = IdentTopic::new(topic_name(control_digest, BEACON_BLOCK)); let upcoming = IdentTopic::new(topic_name(schedule.digest_at(BPO), BEACON_BLOCK)); for topic in [&control, &upcoming] { let gossipsub = &mut peer.swarm.behaviour_mut().gossipsub; @@ -1378,7 +1383,11 @@ mod tests { // topic has parameters. let settings = ScoreSettings::new(&config, crate::MESH_N); let control_params = settings - .digest_topic_params([0xAB; 4], DigestRole::Upcoming, ScoreInputs::placeholder()) + .digest_topic_params( + control_digest, + DigestRole::Upcoming, + ScoreInputs::placeholder(), + ) .into_iter() .find(|(topic, _)| topic.hash() == control.hash()) .expect("the block topic is scored") diff --git a/crates/net/p2p/src/beacon/topics.rs b/crates/net/p2p/src/beacon/topics.rs index 67a99a423..21e8cab41 100644 --- a/crates/net/p2p/src/beacon/topics.rs +++ b/crates/net/p2p/src/beacon/topics.rs @@ -236,6 +236,40 @@ pub fn data_column_subnet(kind: &str) -> Option { suffix.parse().ok() } +/// Every topic that exists under `fork_digest`, for the fork that digest +/// names: the global kinds, and every data column, attestation and sync +/// committee subnet. +/// +/// This is what a peer on every subnet subscribes to, and so the widest this +/// node can subscribe or publish under one digest: a custody set grown by +/// validator custody, an aggregator duty and a sync committee duty each join +/// subnets inside these families, and the Beacon API publishes on subnets this +/// node never joins. The subscription allowlist +/// ([`crate::subscription_filter`]) is built from it. +/// +/// The global kinds come from [`BeaconTopics::for_fork`], which stays the one +/// place a fork changes which kinds exist. `sync_committee_{n}` is listed +/// under every digest, phase0's included, where no peer uses it. +pub fn every_topic( + fork: ForkName, + fork_digest: ForkDigest, + attestation_subnet_count: u64, +) -> Vec { + use ethlambda_types::beacon::constants::{ + DATA_COLUMN_SIDECAR_SUBNET_COUNT, SYNC_COMMITTEE_SUBNET_COUNT, + }; + + let column_subnets: Vec = (0..DATA_COLUMN_SIDECAR_SUBNET_COUNT).collect(); + let attestation_subnets: Vec = (0..attestation_subnet_count).collect(); + let mut topics = + BeaconTopics::for_fork(fork, fork_digest, &column_subnets, &attestation_subnets).topics; + topics.extend( + (0..SYNC_COMMITTEE_SUBNET_COUNT as u64) + .map(|subnet_id| IdentTopic::new(sync_committee_topic_name(fork_digest, subnet_id))), + ); + topics +} + /// The subscribed topics for one fork digest, built once at startup. #[derive(Debug, Clone)] pub struct BeaconTopics { diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index b72b0003b..3d172a53f 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -122,6 +122,7 @@ pub mod lean; pub mod metrics; mod peer_heads; mod req_resp; +mod subscription_filter; pub(crate) mod swarm_adapter; pub use libp2p::PeerId; @@ -1019,7 +1020,7 @@ pub(crate) struct Behaviour { req_resp: ReqResp, } -/// Gossipsub with no cap on how many topics a peer may subscribe to. +/// Gossipsub with this node's subscription filter in place of the default. /// /// libp2p-gossipsub 0.50 made `MaxCountSubscriptionFilter` the default, with /// upstream limits of 100 topics per peer and per RPC, and a peer over either @@ -1027,11 +1028,15 @@ pub(crate) struct Behaviour { /// custodying every column subscribes to all `DATA_COLUMN_SIDECAR_SUBNET_COUNT` /// column subnets alone, and every peer doubles its topic set around a /// fork-digest rollover, so that default would leave such peers out of every -/// mesh. Naming `AllowAllSubscriptionFilter` keeps the behaviour this node had -/// before the default changed. +/// mesh. +/// +/// Accepting everything instead, as this node did before, let one connected +/// peer grow its stored topic set without limit. [`subscription_filter`] is +/// the middle: an allowlist of the topics this node could subscribe or publish +/// to, which bounds what one peer holds, inside a limit on one RPC's entries. pub(crate) type Gossipsub = libp2p::gossipsub::Behaviour< libp2p::gossipsub::IdentityTransform, - libp2p::gossipsub::AllowAllSubscriptionFilter, + subscription_filter::SubscriptionFilter, >; /// No connection limits, which is what the lean network has always run with: a @@ -1334,6 +1339,18 @@ pub(crate) fn gossipsub_config( /// between, the transport, the QUIC and TCP listeners and the static bootnode /// dialing, is the same on either wire. pub fn build_swarm(config: SwarmConfig) -> Result { + let filter = subscription_filter::Allowlist::for_wire(&config.wire).into_filter(); + build_swarm_with_filter(config, filter) +} + +/// [`build_swarm`] with the subscription filter handed in rather than derived +/// from the wire, which is the only thing a caller can vary here. A test uses +/// it to stand up a peer that subscribes to topics this node does not list, +/// as peers running other clients do. +fn build_swarm_with_filter( + config: SwarmConfig, + subscription_filter: subscription_filter::SubscriptionFilter, +) -> Result { let SwarmConfig { node_key, bootnodes, @@ -1367,9 +1384,10 @@ pub fn build_swarm(config: SwarmConfig) -> Result { }; let validate_messages = matches!(wire, WireConfig::Beacon(_)); - let mut gossipsub = Gossipsub::new( + let mut gossipsub = Gossipsub::new_with_subscription_filter( MessageAuthenticity::Anonymous, gossipsub_config(seen_ttl, validate_messages), + subscription_filter, ) .expect("failed to initiate behaviour"); // Beacon only: the parameters are sized from the beacon chain's topics @@ -4742,79 +4760,153 @@ mod tests { assert!(config.max_control_messages_sent() <= config.max_publish_messages()); } - /// Every beacon topic under `fork_digest` for a node on every subnet: the - /// global topics, gloas's four, and every column, attestation and sync - /// committee subnet. - fn every_beacon_topic(fork_digest: [u8; 4]) -> Vec { - use crate::beacon::topics::{ - GLOAS_TOPIC_KINDS, SUBSCRIBED_TOPIC_KINDS, attestation_topic_name, - data_column_topic_name, sync_committee_topic_name, topic_name, - }; - use ethlambda_types::beacon::constants::{ - DATA_COLUMN_SIDECAR_SUBNET_COUNT, SYNC_COMMITTEE_SUBNET_COUNT, - }; + /// Mainnet's schedule with gloas added after its last blob-parameter + /// boundary, so the last two digests are a fulu one and the gloas one: the + /// two a peer holds around the gloas boundary. + fn subscription_test_config() -> ethlambda_types::beacon::config::Config { + use ethlambda_types::beacon::fork::ForkName; - let attestation_subnets = - ethlambda_types::beacon::config::Config::mainnet().attestation_subnet_count; - let globals = SUBSCRIBED_TOPIC_KINDS - .iter() - .chain(&GLOAS_TOPIC_KINDS) - .map(|kind| topic_name(fork_digest, kind)); - let columns = (0..DATA_COLUMN_SIDECAR_SUBNET_COUNT) - .map(|subnet| data_column_topic_name(fork_digest, subnet)); - let attestations = - (0..attestation_subnets).map(|subnet| attestation_topic_name(fork_digest, subnet)); - let sync_committees = (0..SYNC_COMMITTEE_SUBNET_COUNT as u64) - .map(|subnet| sync_committee_topic_name(fork_digest, subnet)); - globals - .chain(columns) - .chain(attestations) - .chain(sync_committees) - .map(libp2p::gossipsub::IdentTopic::new) - .collect() + let config = ethlambda_types::beacon::config::Config::mainnet(); + let last_boundary = beacon::fork_schedule::ForkSchedule::new( + &config, + ethlambda_types::beacon::primitives::Root::ZERO, + ) + .entries() + .last() + .expect("a schedule is never empty") + .activation_epoch; + config.with_fork_epoch(ForkName::Gloas, last_boundary + 1_000) + } + + fn subscription_test_wire() -> WireConfig { + let config = subscription_test_config(); + WireConfig::Beacon(Box::new(crate::beacon::swarm::BeaconWireConfig { + fork_digest: [0u8; 4], + fork: config.fork_at_epoch(0), + genesis_time: config.genesis_time, + config, + genesis_validators_root: ethlambda_types::beacon::primitives::Root::ZERO, + custody_columns: Vec::new(), + custody_group_count: ethlambda_types::beacon::constants::CUSTODY_REQUIREMENT, + custody_since_slot: 0, + attached_validators: Default::default(), + attestation_subnets: Vec::new(), + })) + } + + fn subscription_test_swarm_config(node_key_byte: u8) -> SwarmConfig { + SwarmConfig { + node_key: vec![node_key_byte; 32], + bootnodes: Vec::new(), + listening_socket: "127.0.0.1:0".parse().expect("valid socket"), + target_peers: crate::discovery::DEFAULT_DISCOVERY_TARGET_PEERS, + agent_version: "ethlambda/test", + wire: subscription_test_wire(), + } } - /// Connects a fresh peer subscribed to `topics` to a fresh node, both - /// beacon swarms, and answers whether the node learns every one of them. - /// - /// The peer subscribes before it dials, so its subscriptions reach the - /// node the way a connecting peer's do: all at once, in the one hello RPC - /// gossipsub sends a new connection (rust-libp2p since gossipsub 0.50, - /// go-libp2p-pubsub always; Teku's jvm-libp2p splits it into RPCs of at - /// most 200). That RPC is never resent. - async fn node_learns_every_subscription(topics: &[libp2p::gossipsub::IdentTopic]) -> bool { - use ethlambda_types::beacon::config::Config; - use ethlambda_types::beacon::primitives::Root; + /// The filter a node on [`subscription_test_wire`] runs, for its limits. + fn subscription_test_filter() -> subscription_filter::SubscriptionFilter { + subscription_filter::Allowlist::for_wire(&subscription_test_wire()).into_filter() + } - fn build(node_key_byte: u8) -> BuiltSwarm { - let config = Config::mainnet(); - build_swarm(SwarmConfig { - node_key: vec![node_key_byte; 32], - bootnodes: Vec::new(), - listening_socket: "127.0.0.1:0".parse().expect("valid socket"), - target_peers: crate::discovery::DEFAULT_DISCOVERY_TARGET_PEERS, - agent_version: "ethlambda/test", - wire: WireConfig::Beacon(Box::new(crate::beacon::swarm::BeaconWireConfig { - fork_digest: [0u8; 4], - fork: config.fork_at_epoch(0), - config: config.clone(), - genesis_time: config.genesis_time, - genesis_validators_root: Root::ZERO, - custody_columns: Vec::new(), - custody_group_count: ethlambda_types::beacon::constants::CUSTODY_REQUIREMENT, - custody_since_slot: 0, - attached_validators: Default::default(), - attestation_subnets: Vec::new(), - })), + /// Every topic of the last `count` digests of [`subscription_test_config`]'s + /// schedule, one list per digest, oldest first: what a peer on every + /// subnet subscribes to under each. + fn every_topic_of_the_last_digests(count: usize) -> Vec> { + let config = subscription_test_config(); + let schedule = beacon::fork_schedule::ForkSchedule::new( + &config, + ethlambda_types::beacon::primitives::Root::ZERO, + ); + let entries = schedule.entries(); + entries[entries.len() - count..] + .iter() + .map(|entry| { + beacon::topics::every_topic( + entry.fork, + entry.digest, + config.attestation_subnet_count, + ) }) - .expect("beacon swarm builds") - } + .collect() + } - let mut node = build(1); - let mut peer = build(2); + /// Topics another client subscribes to under `fork_digest` and this node + /// does not list: light client updates, and the kinds of proposals this + /// node does not follow. + fn foreign_topics(fork_digest: [u8; 4]) -> Vec { + [ + "light_client_finality_update", + "light_client_optimistic_update", + "execution_proof", + "inclusion_list", + "blob_sidecar_0", + "blob_sidecar_1", + ] + .into_iter() + .map(|kind| beacon::topics::topic_name(fork_digest, kind)) + .map(libp2p::gossipsub::IdentTopic::new) + .collect() + } + + /// Connects a fresh peer subscribed to `hello` to a fresh node, has the + /// peer subscribe to `afterwards` once they are connected, and answers + /// with the peer's topics as the node recorded them once it has heard + /// every topic of `awaited`. `None` if that does not happen in time. + /// + /// The peer subscribes to `hello` before it dials, so those subscriptions + /// reach the node the way a connecting peer's do: all at once, in the one + /// hello RPC gossipsub sends a new connection (rust-libp2p since gossipsub + /// 0.50, go-libp2p-pubsub always; Teku's jvm-libp2p splits it into RPCs of + /// at most 200). That RPC is never resent. `afterwards` travels in a later + /// RPC on the same stream, so a node that has heard it has already dealt + /// with the hello, whatever it did with it. + /// + /// The node runs the filter [`build_swarm`] gives it. The peer accepts + /// exactly the topics it is told to subscribe to, with no limit on their + /// number, so it can stand in for a peer running another client. + async fn recorded_subscriptions( + hello: &[libp2p::gossipsub::IdentTopic], + afterwards: &[libp2p::gossipsub::IdentTopic], + awaited: &[libp2p::gossipsub::IdentTopic], + ) -> Option> { + let mut node = + build_swarm(subscription_test_swarm_config(1)).expect("the node's swarm builds"); + let accepts_what_it_is_told = libp2p::gossipsub::MaxCountSubscriptionFilter { + filter: libp2p::gossipsub::WhitelistSubscriptionFilter( + hello + .iter() + .chain(afterwards) + .map(|topic| topic.hash()) + // The topics the swarm joins by itself as it is built. + .chain( + beacon::topics::every_topic( + subscription_test_config().fork_at_epoch(0), + [0u8; 4], + 0, + ) + .iter() + .map(|topic| topic.hash()), + ) + .collect(), + ), + max_subscribed_topics: usize::MAX, + max_subscriptions_per_request: usize::MAX, + }; + let mut peer = + build_swarm_with_filter(subscription_test_swarm_config(2), accepts_what_it_is_told) + .expect("the peer's swarm builds"); let peer_id = peer.local_peer_id; - for topic in topics { - let gossipsub = &mut peer.swarm.behaviour_mut().gossipsub; + // Leave the topics the swarm joined as it was built, so the hello + // carries `hello` and nothing else. Nothing is connected yet, so + // leaving them sends nothing. + let gossipsub = &mut peer.swarm.behaviour_mut().gossipsub; + let joined_at_build: Vec<_> = gossipsub.topics().cloned().collect(); + for topic in joined_at_build { + gossipsub.unsubscribe(&libp2p::gossipsub::IdentTopic::new(topic.into_string())); + } + for topic in hello { gossipsub.subscribe(topic).expect("peer subscribes"); } @@ -4827,16 +4919,26 @@ mod tests { }; peer.swarm.dial(node_addr).expect("dial is accepted"); - let hears_all = |gossipsub: &Gossipsub| { - gossipsub.all_peers().any(|(id, subscribed)| { - *id == peer_id - && topics - .iter() - .all(|topic| subscribed.contains(&&topic.hash())) - }) + let recorded = |gossipsub: &Gossipsub| -> Option> { + let (_, topics) = gossipsub.all_peers().find(|(id, _)| **id == peer_id)?; + Some(topics.into_iter().cloned().collect()) }; let heard = async { - while !hears_all(&node.swarm.behaviour().gossipsub) { + let mut sent_afterwards = false; + loop { + let connected = peer.swarm.is_connected(&node.local_peer_id); + if connected && !sent_afterwards { + for topic in afterwards { + let gossipsub = &mut peer.swarm.behaviour_mut().gossipsub; + gossipsub.subscribe(topic).expect("peer subscribes"); + } + sent_afterwards = true; + } + if let Some(topics) = recorded(&node.swarm.behaviour().gossipsub) + && awaited.iter().all(|topic| topics.contains(&topic.hash())) + { + return topics; + } tokio::select! { _ = node.swarm.select_next_some() => {} _ = peer.swarm.select_next_some() => {} @@ -4845,7 +4947,7 @@ mod tests { }; tokio::time::timeout(Duration::from_secs(10), heard) .await - .is_ok() + .ok() } /// A peer on every subnet sends a hello of well over 16 KiB once it holds @@ -4858,25 +4960,141 @@ mod tests { /// /// One digest's topics fit under that default, which is the control: a /// failure on two digests is the size and nothing else. + /// + /// The subscription filter must not refuse that hello either, and a peer + /// running another client adds topics this node does not list to it. With + /// those, every listed topic is still heard and none of the others is + /// kept. #[tokio::test] async fn a_peer_on_every_subnet_of_two_digests_is_heard_subscribing() { - let one_digest = every_beacon_topic([0xAA; 4]); + let digests = every_topic_of_the_last_digests(2); + let one_digest = digests[1].clone(); assert!( - node_learns_every_subscription(&one_digest).await, + recorded_subscriptions(&one_digest, &[], &one_digest) + .await + .is_some(), "a peer on every subnet of one digest is heard" ); - let mut two_digests = one_digest; - two_digests.extend(every_beacon_topic([0xBB; 4])); + let two_digests: Vec<_> = digests.concat(); let topic_bytes: usize = two_digests .iter() .map(|topic| topic.hash().as_str().len()) .sum(); assert!(topic_bytes > 16 * 1024, "the names alone pass 16 KiB"); assert!( - node_learns_every_subscription(&two_digests).await, + recorded_subscriptions(&two_digests, &[], &two_digests) + .await + .is_some(), "a peer on every subnet of two digests is heard" ); + + let foreign: Vec<_> = digests + .iter() + .flat_map(|topics| { + let digest = beacon::topics::topic_digest(topics[0].hash().as_str()) + .expect("a beacon topic names its digest"); + foreign_topics(digest) + }) + .collect(); + let mut hello = two_digests.clone(); + hello.extend(foreign.iter().cloned()); + let recorded = recorded_subscriptions(&hello, &[], &two_digests) + .await + .expect("the listed topics of a hello that carries others too are heard"); + let listed: HashSet<_> = two_digests.iter().map(|topic| topic.hash()).collect(); + assert_eq!(recorded, listed, "only the listed topics are kept"); + } + + /// A subscription to a topic outside the allowlist is dropped before it is + /// stored, which is what keeps a peer from growing this node's memory with + /// topics of its own invention, however long their names. The listed topic + /// in the same hello is the control: it is kept, so the hello was read. + #[tokio::test] + async fn a_subscription_to_an_unlisted_topic_is_not_stored() { + use ethlambda_types::beacon::constants::DATA_COLUMN_SIDECAR_SUBNET_COUNT; + + let digests = every_topic_of_the_last_digests(1); + let listed = digests[0][0].clone(); + let digest = beacon::topics::topic_digest(listed.hash().as_str()) + .expect("a beacon topic names its digest"); + + let unlisted = [ + // A kind this node has no use for. + beacon::topics::topic_name(digest, "light_client_finality_update"), + // A digest the schedule never produces. + beacon::topics::topic_name([0xde, 0xad, 0xbe, 0xef], "beacon_block"), + // The first subnet past a family. + beacon::topics::data_column_topic_name(digest, DATA_COLUMN_SIDECAR_SUBNET_COUNT), + // A name far longer than any real topic's. + beacon::topics::topic_name(digest, &"x".repeat(64 * 1024)), + // Not shaped like a topic at all. + "anything".to_owned(), + ] + .map(libp2p::gossipsub::IdentTopic::new); + + let mut hello = unlisted.to_vec(); + hello.push(listed.clone()); + let recorded = recorded_subscriptions(&hello, &[], std::slice::from_ref(&listed)) + .await + .expect("the listed topic is heard"); + assert_eq!(recorded, HashSet::from([listed.hash()])); + } + + /// A peer that joins a digest while it still holds every topic of four + /// others is heard joining. Four is the most this node's own join and + /// leave rules ever hold at once (a boundary at every epoch), and both a + /// join counted before the leaves that follow it and another client that + /// holds digests longer than this node go past it. A refused join is never + /// resent, so a per-peer limit sized from this node's own window would + /// leave such a peer out of the new digest for good. + #[tokio::test] + async fn a_peer_joining_a_digest_while_holding_four_others_is_heard() { + let digests = every_topic_of_the_last_digests(5); + let (joined, held) = digests.split_last().expect("five digests"); + let held = held.concat(); + let every: Vec<_> = held.iter().chain(joined).cloned().collect(); + + let recorded = recorded_subscriptions(&held, joined, &every) + .await + .expect("every topic of the fifth digest is heard"); + assert_eq!(recorded.len(), every.len()); + } + + /// Past the per-RPC limit gossipsub ignores the whole RPC, listed topics + /// included. That is the bound on a peer that sends more than an honest + /// one could, and the reason the limit has to clear every honest hello. + /// + /// Each case sends a hello of one listed topic padded with unlisted ones, + /// then, in a later RPC, another listed topic. Hearing that one shows the + /// hello was dealt with, and that a peer whose hello was refused is not + /// cut off from then on. + #[tokio::test] + async fn a_hello_over_the_per_rpc_limit_is_ignored_whole() { + let filter = subscription_test_filter(); + let listed = every_topic_of_the_last_digests(1).concat(); + let later = &listed[..1]; + let in_hello = listed[1].clone(); + + // Exactly at the limit: read, so the listed topic in it is kept. + let mut hello: Vec<_> = (1..filter.max_subscriptions_per_request) + .map(|n| libp2p::gossipsub::IdentTopic::new(format!("unlisted_{n}"))) + .collect(); + hello.push(in_hello.clone()); + assert_eq!(hello.len(), filter.max_subscriptions_per_request); + let recorded = recorded_subscriptions(&hello, later, later) + .await + .expect("the later topic is heard"); + let both = HashSet::from([in_hello.hash(), later[0].hash()]); + assert_eq!(recorded, both, "a hello at the limit"); + + // One entry more, unlisted: the whole hello is ignored. + hello.push(libp2p::gossipsub::IdentTopic::new("unlisted_0")); + let recorded = recorded_subscriptions(&hello, later, later) + .await + .expect("the later topic is heard"); + let only_later = HashSet::from([later[0].hash()]); + assert_eq!(recorded, only_later, "a hello one entry over the limit"); } /// How many times [`concurrent_beacon_requests_on_different_protocols_never_cross`] diff --git a/crates/net/p2p/src/subscription_filter.rs b/crates/net/p2p/src/subscription_filter.rs new file mode 100644 index 000000000..967236d51 --- /dev/null +++ b/crates/net/p2p/src/subscription_filter.rs @@ -0,0 +1,401 @@ +//! Which gossipsub topics a peer may be recorded as subscribed to, and how +//! many. +//! +//! Gossipsub keeps every topic a peer subscribes to in that peer's topic set +//! until the peer disconnects, and a topic's hash is its name. With every +//! subscription accepted, one connected peer could grow this node's memory +//! without limit, by subscribing to ever more topics or to ones with +//! megabyte-long names. Two bounds close that: +//! +//! - **An allowlist** ([`Allowlist`]) of the topics this node could subscribe +//! or publish to. A subscription to anything else is dropped before it is +//! stored, which bounds both a stored name's length and how many names one +//! peer can hold: at most the whole list. It covers the publish side because +//! gossipsub picks fanout and flood-publish peers from the stored sets: +//! without a subnet this node never joins on the list, publishing to it (a +//! gloas column sidecar, an attestation a validator client submitted) would +//! find no peer. +//! - **A count limit** around it (`MaxCountSubscriptionFilter`) on the +//! entries one RPC carries, counted before the allowlist drops any, which +//! keeps the filter's own pass over one RPC short. +//! +//! The same filter also gates this node's own `subscribe`, so a topic missing +//! from the allowlist is one this node cannot join: the list is built from +//! what the topic code itself produces, not written out beside it. +//! +//! A limit hit loses the whole RPC: gossipsub ignores every subscription in +//! it, and neither a peer's hello nor a join is ever sent again, so that peer +//! would be left out of those meshes for good. No limit is therefore sized +//! from how many digests a peer is expected to hold at once: that depends on +//! the peer's own join and leave timing, which other clients choose for +//! themselves, and gossipsub sees a join before the leave that follows it. + +use std::collections::HashSet; + +use ethlambda_types::state::VALIDATOR_REGISTRY_LIMIT; +use libp2p::gossipsub::{ + IdentTopic, MaxCountSubscriptionFilter, TopicHash, WhitelistSubscriptionFilter, +}; + +use crate::beacon::fork_schedule::ForkSchedule; +use crate::beacon::swarm::BeaconWireConfig; +use crate::beacon::topics; +use crate::gossipsub::{aggregation_topic, attestation_subnet_topic, block_topic}; +use crate::{LeanWireConfig, WireConfig}; + +/// The subscription filter both wires run: the allowlist inside the count +/// limit. +pub(crate) type SubscriptionFilter = MaxCountSubscriptionFilter; + +/// The fewest subscription entries one RPC is allowed, whatever the allowlist's +/// size. +/// +/// 500 is the largest per-RPC cap the other clients enforce (Prysm's and +/// Teku's), so no peer that talks to all of them sends more in one RPC. +/// Never going below it means a hello they accept is one this node accepts. +/// Only a lean network, whose whole topic set is a handful, is small enough +/// for this floor to be the limit. +const MIN_SUBSCRIPTIONS_PER_REQUEST: usize = 500; + +/// The topics a peer may be recorded as subscribed to. +pub(crate) struct Allowlist { + topics: HashSet, +} + +impl Allowlist { + pub(crate) fn for_wire(wire: &WireConfig) -> Self { + match wire { + WireConfig::Lean(lean) => Self::lean(lean), + WireConfig::Beacon(beacon) => Self::beacon(beacon), + } + } + + /// Every topic under every digest the chain's schedule can produce, fork + /// and blob-parameter boundaries alike. + /// + /// Built from the whole schedule, at startup, so the next digest's topics + /// are already listed when peers start subscribing to them ahead of its + /// boundary and the previous one's still are until they leave. A schedule + /// change needs a restart anyway. + /// + /// The digest the node starts on is listed as well. It is one of the + /// schedule's, so that adds nothing, except in a test that starts a swarm + /// on a digest it made up. + fn beacon(beacon: &BeaconWireConfig) -> Self { + let schedule = ForkSchedule::new(&beacon.config, beacon.genesis_validators_root); + let topics = schedule + .entries() + .iter() + .map(|entry| (entry.fork, entry.digest)) + .chain([(beacon.fork, beacon.fork_digest)]) + .flat_map(|(fork, digest)| { + topics::every_topic(fork, digest, beacon.config.attestation_subnet_count) + }); + Self::of(topics) + } + + /// The block and aggregation topics and every attestation subnet a + /// validator can publish on, under lean's one fork digest. + /// + /// A validator publishes on `validator_id % attestation_committee_count`, + /// and a validator id is below [`VALIDATOR_REGISTRY_LIMIT`], so the + /// subnets anyone publishes on are below the smaller of the two. The + /// committee count is operator input with no upper bound of its own; the + /// registry limit keeps a huge one from costing a topic per committee at + /// startup. The subnets this node was told to subscribe to are added on + /// their own, since its own `subscribe` goes through the filter. + fn lean(lean: &LeanWireConfig) -> Self { + let published_on = lean + .attestation_committee_count + .min(VALIDATOR_REGISTRY_LIMIT as u64); + let subnets: HashSet = (0..published_on) + .chain(lean.subscription_subnets.iter().copied()) + .collect(); + let topics = [block_topic(), aggregation_topic()] + .into_iter() + .chain(subnets.into_iter().map(attestation_subnet_topic)); + Self::of(topics) + } + + fn of(topics: impl IntoIterator) -> Self { + let topics = topics.into_iter().map(|topic| topic.hash()).collect(); + Self { topics } + } + + #[cfg(test)] + fn contains(&self, topic: &str) -> bool { + self.topics.contains(&TopicHash::from_raw(topic)) + } + + /// The most listed topics one peer may hold: all of them. + /// + /// The allowlist already bounds what a peer holds, so this limit never + /// refuses anything. Any lower one could refuse an honest peer: it holds + /// as many digests' topics at once as its own client's join and leave + /// rules say, and gossipsub counts a join to a new digest before the + /// leaves from an old one that follow it in later RPCs. A refused join is + /// never resent, so the peer would stay out of the new digest's meshes and + /// fanout until it reconnected. + /// + /// On mainnet's schedule that is about ten digests' topics, a couple of + /// thousand short names per peer. + fn max_subscribed_topics(&self) -> usize { + self.topics.len() + } + + /// The most subscription entries one RPC may carry. + /// + /// Counted before the allowlist drops anything, so it has to cover a whole + /// hello from another client, topics this node does not list included + /// (light client updates, execution proofs, inclusion lists). Twice the + /// whole allowlist leaves as much room for those again, and for a peer + /// that leaves and joins topics in one RPC. The frame size already bounds + /// what one RPC costs to parse; this only keeps the filter's own pass + /// short. + fn max_subscriptions_per_request(&self) -> usize { + self.topics + .len() + .saturating_mul(2) + .max(MIN_SUBSCRIPTIONS_PER_REQUEST) + } + + pub(crate) fn into_filter(self) -> SubscriptionFilter { + MaxCountSubscriptionFilter { + max_subscribed_topics: self.max_subscribed_topics(), + max_subscriptions_per_request: self.max_subscriptions_per_request(), + filter: WhitelistSubscriptionFilter(self.topics), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use ethlambda_types::beacon::config::Config; + use ethlambda_types::beacon::constants::{ + CUSTODY_REQUIREMENT, DATA_COLUMN_SIDECAR_SUBNET_COUNT, SYNC_COMMITTEE_SUBNET_COUNT, + }; + use ethlambda_types::beacon::fork::ForkName; + use ethlambda_types::beacon::primitives::{ForkDigest, Root}; + use libp2p::gossipsub::TopicSubscriptionFilter; + + use crate::beacon::topics::{ + GLOAS_TOPIC_KINDS, SUBSCRIBED_TOPIC_KINDS, attestation_topic_name, data_column_topic_name, + sync_committee_topic_name, topic_name, + }; + + /// A schedule with gloas on it, which mainnet's does not have yet: every + /// fork through gloas, and no blob schedule, so the only boundaries are + /// the forks. + fn scheduled_gloas() -> Config { + let mut config = Config::mainnet() + .with_fork_epoch(ForkName::Altair, 1) + .with_fork_epoch(ForkName::Bellatrix, 2) + .with_fork_epoch(ForkName::Capella, 3) + .with_fork_epoch(ForkName::Deneb, 4) + .with_fork_epoch(ForkName::Electra, 5) + .with_fork_epoch(ForkName::Fulu, 1_000) + .with_fork_epoch(ForkName::Gloas, 5_000); + config.blob_schedule = libssz_types::SszList::new(); + config + } + + fn beacon_wire(config: Config) -> BeaconWireConfig { + let genesis_validators_root = Root::repeat_byte(7); + let schedule = ForkSchedule::new(&config, genesis_validators_root); + let current = schedule.current_at(0); + BeaconWireConfig { + fork_digest: current.digest, + fork: current.fork, + genesis_time: config.genesis_time, + config, + genesis_validators_root, + custody_columns: Vec::new(), + custody_group_count: CUSTODY_REQUIREMENT, + custody_since_slot: 0, + attached_validators: Default::default(), + attestation_subnets: Vec::new(), + } + } + + fn lean_wire(attestation_committee_count: u64, subscription_subnets: &[u64]) -> LeanWireConfig { + LeanWireConfig { + validator_ids: Vec::new(), + attestation_committee_count, + subscription_subnets: subscription_subnets.iter().copied().collect(), + milliseconds_per_slot: 4_000, + } + } + + fn digest_of(schedule: &ForkSchedule, fork: ForkName) -> ForkDigest { + schedule + .entries() + .iter() + .find(|entry| entry.fork == fork) + .expect("the fork is scheduled") + .digest + } + + /// Every topic this node can subscribe or publish to, under every digest + /// of the schedule: the global kinds and every subnet of the three + /// families. Written out here rather than taken from `every_topic`, which + /// is what the allowlist is built from. + #[test] + fn every_topic_of_every_scheduled_digest_is_listed() { + let wire = beacon_wire(scheduled_gloas()); + let allowlist = Allowlist::beacon(&wire); + let schedule = ForkSchedule::new(&wire.config, wire.genesis_validators_root); + + assert!(schedule.entries().len() > 2, "several digests are checked"); + for entry in schedule.entries() { + let digest = entry.digest; + for kind in SUBSCRIBED_TOPIC_KINDS { + assert!(allowlist.contains(&topic_name(digest, kind)), "{kind}"); + } + for subnet in 0..DATA_COLUMN_SIDECAR_SUBNET_COUNT { + assert!(allowlist.contains(&data_column_topic_name(digest, subnet))); + } + for subnet in 0..wire.config.attestation_subnet_count { + assert!(allowlist.contains(&attestation_topic_name(digest, subnet))); + } + for subnet in 0..SYNC_COMMITTEE_SUBNET_COUNT as u64 { + assert!(allowlist.contains(&sync_committee_topic_name(digest, subnet))); + } + } + } + + #[test] + fn gloas_kinds_are_listed_under_a_gloas_digest_only() { + let wire = beacon_wire(scheduled_gloas()); + let allowlist = Allowlist::beacon(&wire); + let schedule = ForkSchedule::new(&wire.config, wire.genesis_validators_root); + let gloas = digest_of(&schedule, ForkName::Gloas); + let fulu = digest_of(&schedule, ForkName::Fulu); + + for kind in GLOAS_TOPIC_KINDS { + assert!(allowlist.contains(&topic_name(gloas, kind)), "{kind}"); + assert!(!allowlist.contains(&topic_name(fulu, kind)), "{kind}"); + } + } + + #[test] + fn a_topic_this_node_has_no_use_for_is_not_listed() { + let wire = beacon_wire(scheduled_gloas()); + let allowlist = Allowlist::beacon(&wire); + let digest = wire.fork_digest; + let attestation_subnets = wire.config.attestation_subnet_count; + + // A kind another client subscribes to and this node does not. + assert!(!allowlist.contains(&topic_name(digest, "light_client_finality_update"))); + // The first subnet past each family. + assert!(!allowlist.contains(&data_column_topic_name( + digest, + DATA_COLUMN_SIDECAR_SUBNET_COUNT + ))); + assert!(!allowlist.contains(&attestation_topic_name(digest, attestation_subnets))); + assert!(!allowlist.contains(&sync_committee_topic_name( + digest, + SYNC_COMMITTEE_SUBNET_COUNT as u64 + ))); + // A digest the schedule never produces. + assert!(!allowlist.contains(&topic_name([0xde, 0xad, 0xbe, 0xef], "beacon_block"))); + // A listed name with something appended, and another encoding. + let block = topic_name(digest, "beacon_block"); + assert!(allowlist.contains(&block)); + assert!(!allowlist.contains(&format!("{block}/"))); + assert!(!allowlist.contains(&block.replace("ssz_snappy", "ssz"))); + } + + /// The node subscribes through the same filter, so a start digest outside + /// the schedule has to be listed or the swarm could not be built on it. + #[test] + fn the_digest_the_node_starts_on_is_listed() { + let mut wire = beacon_wire(scheduled_gloas()); + wire.fork_digest = [0u8; 4]; + let allowlist = Allowlist::beacon(&wire); + assert!(allowlist.contains(&topic_name([0u8; 4], "beacon_block"))); + } + + #[test] + fn the_filter_gates_this_nodes_own_subscriptions_by_the_allowlist() { + let wire = beacon_wire(scheduled_gloas()); + let digest = wire.fork_digest; + let mut filter = Allowlist::beacon(&wire).into_filter(); + + let listed = IdentTopic::new(topic_name(digest, "beacon_block")).hash(); + let unlisted = IdentTopic::new(topic_name(digest, "light_client_finality_update")).hash(); + assert!(filter.can_subscribe(&listed)); + assert!(!filter.can_subscribe(&unlisted)); + } + + /// No set of listed topics is over the per-peer limit, however many + /// digests it spans, and an RPC may carry every listed topic with as many + /// unlisted ones again. + #[test] + fn no_set_of_listed_topics_is_over_a_limit() { + let wire = beacon_wire(scheduled_gloas()); + let allowlist = Allowlist::beacon(&wire); + let listed = allowlist.topics.len(); + + assert_eq!(allowlist.max_subscribed_topics(), listed); + assert!(allowlist.max_subscriptions_per_request() >= 2 * listed); + assert!(allowlist.max_subscriptions_per_request() >= MIN_SUBSCRIPTIONS_PER_REQUEST); + } + + #[test] + fn a_lean_node_lists_its_three_kinds_and_every_committee_subnet() { + let allowlist = Allowlist::lean(&lean_wire(4, &[1])); + + assert!(allowlist.contains(block_topic().hash().as_str())); + assert!(allowlist.contains(aggregation_topic().hash().as_str())); + for subnet in 0..4 { + assert!(allowlist.contains(attestation_subnet_topic(subnet).hash().as_str())); + } + assert!(!allowlist.contains(attestation_subnet_topic(4).hash().as_str())); + assert!(!allowlist.contains("/leanconsensus/12345678/something_else/ssz_snappy")); + assert_eq!(allowlist.topics.len(), 6); + } + + /// An aggregation subnet named past the committee count is still one this + /// node is asked to join, and its own `subscribe` goes through the filter. + #[test] + fn a_lean_subnet_the_node_was_told_to_join_is_listed() { + let allowlist = Allowlist::lean(&lean_wire(2, &[9])); + assert!(allowlist.contains(attestation_subnet_topic(9).hash().as_str())); + } + + /// The committee count has no upper bound of its own, but no validator id + /// reaches the registry limit, so no subnet past it is published on and + /// none is listed. A count of `u64::MAX` must not cost a topic per + /// committee. + #[test] + fn a_lean_committee_count_past_the_registry_lists_only_subnets_published_on() { + let allowlist = Allowlist::lean(&lean_wire(u64::MAX, &[])); + let registry = VALIDATOR_REGISTRY_LIMIT as u64; + + assert_eq!(allowlist.topics.len(), 2 + VALIDATOR_REGISTRY_LIMIT); + assert!(allowlist.contains(attestation_subnet_topic(registry - 1).hash().as_str())); + assert!(!allowlist.contains(attestation_subnet_topic(registry).hash().as_str())); + } + + /// A subnet this node was told to join is listed even past the registry + /// limit, since its own `subscribe` goes through the filter. + #[test] + fn a_lean_subnet_the_node_was_told_to_join_past_the_registry_is_listed() { + let past_registry = VALIDATOR_REGISTRY_LIMIT as u64 + 5; + let allowlist = Allowlist::lean(&lean_wire(u64::MAX, &[past_registry])); + assert!(allowlist.contains(attestation_subnet_topic(past_registry).hash().as_str())); + } + + /// A lean network's topic set is far smaller than any hello cap another + /// client enforces, so the floor is what limits one RPC there. + #[test] + fn a_lean_rpc_is_allowed_the_floor() { + let allowlist = Allowlist::lean(&lean_wire(1, &[0])); + assert_eq!( + allowlist.max_subscriptions_per_request(), + MIN_SUBSCRIPTIONS_PER_REQUEST + ); + } +} diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 13a2bb1dc..366cbf456 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -368,6 +368,47 @@ goes through fanout), all under the digest the block's slot falls in. Operations posted to the `pool/*` routes are published on their topics the same way, under the digest of the wall-clock slot. +### Which subscriptions are kept + +Gossipsub records every topic a peer subscribes to until the peer disconnects, +and a topic is stored under its name. Accepting every subscription would let +one connected peer grow that record without limit, with ever more topics or +with names megabytes long, so the node runs a subscription filter +(`p2p/src/subscription_filter.rs`) with two bounds: + +- **An allowlist.** A subscription is kept only for a topic this node could + subscribe or publish to: the global kinds, and every data column, + attestation and sync committee subnet, under every fork digest the chain's + schedule produces (fork and blob-parameter boundaries alike; gloas's four + kinds under gloas digests only). It is built once at startup from the whole + schedule, so the next digest's topics are listed before peers join them. + Every subnet is listed, not only the ones this node joins, because fanout + and flood publishing pick their peers from this record: publishing a column + or an attestation on a subnet this node has not joined needs to know who is + on it. A subscription to anything else (light client updates, another + chain's digest, a made-up name) is dropped and costs the peer nothing. +- **A count limit.** One RPC may carry twice as many entries as the allowlist + holds, counted before the allowlist drops any, and never fewer than 500, the + largest per-RPC cap the other clients enforce. + +The allowlist is also the bound on what one peer holds: at most every listed +topic, about ten digests' worth on mainnet's schedule. No lower per-peer limit +is set, because none is safe. A subscription refused for a count is never sent +again, and how many digests a peer holds at once depends on its own client's +join and leave timing, with each join counted before the leaves that follow it +in later RPCs. A limit sized from this node's own window (four digests, on a +schedule with a boundary at every epoch) would leave a peer that joins a fifth +out of that digest's meshes and fanout until it reconnected. + +A hello over the per-RPC limit is ignored whole, listed topics included, and a +hello is never sent again, so that limit is sized from the most an honest peer +can send rather than from what is typical. The same filter gates this node's +own `subscribe`, which is why the allowlist is built from what the topic code +produces (`topics::every_topic`) rather than listed beside it. Lean runs the +same filter over its three kinds and every attestation subnet a validator can +publish on: below the committee count and below `VALIDATOR_REGISTRY_LIMIT`, +since no validator id reaches it, plus the subnets the node was told to join. + ### Peer scoring Gossipsub peer scoring is on for this wire only