diff --git a/CLAUDE.md b/CLAUDE.md index 5d9d9dcde..7ef39486c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -361,7 +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) + - 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 still held at the startup digest's first epoch (`held_at`) and every later 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 at startup. The rollover adds a digest to it before joining one that is not listed (`Allowlist::list`), which only a clock stepped back makes it do: the filter gates this node's own joins too, and a refused join would leave the node deaf while it recorded the digest as held. 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 count limit, per peer or per RPC (`MaxCountSubscriptionFilter`): a refused join is never resent, a peer's held digests depend on its own client's join and leave timing, and gossipsub logs every over-limit RPC at `ERROR` with no penalty, which a peer could repeat at will; gossipsub does not export the `Subscription` type a quieter filter of our own would need. 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 467f65fce..6a6f166dd 100644 --- a/crates/net/p2p/src/beacon/scoring.rs +++ b/crates/net/p2p/src/beacon/scoring.rs @@ -1354,11 +1354,11 @@ mod tests { }; peer.swarm.dial(node_addr).expect("dial is accepted"); - // 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); + // The control topic is under the digest before the one `node` starts + // on (electra's): one the subscription filter lists, as it does the + // start digest's predecessor, and outside the window the rollover + // below opens, so nothing but this test joins it. + let control_digest = schedule.digest_at(FULU - 1); 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] { @@ -1382,12 +1382,9 @@ mod tests { // The control: joined first, so the join grafts the peer before the // topic has parameters. let settings = ScoreSettings::new(&config, crate::MESH_N); + let inputs = ScoreInputs::placeholder(); let control_params = settings - .digest_topic_params( - control_digest, - DigestRole::Upcoming, - ScoreInputs::placeholder(), - ) + .digest_topic_params(control_digest, DigestRole::Upcoming, inputs) .into_iter() .find(|(topic, _)| topic.hash() == control.hash()) .expect("the block topic is scored") diff --git a/crates/net/p2p/src/beacon/transition.rs b/crates/net/p2p/src/beacon/transition.rs index 12eec2dc7..1d7b72b2a 100644 --- a/crates/net/p2p/src/beacon/transition.rs +++ b/crates/net/p2p/src/beacon/transition.rs @@ -18,7 +18,7 @@ use ethlambda_types::beacon::preset; use ethlambda_types::beacon::primitives::{Epoch, ForkDigest}; use ethlambda_types::time::unix_now_ms; use libp2p::gossipsub::IdentTopic; -use tracing::{error, info}; +use tracing::{error, info, warn}; use super::BeaconWire; use super::topics::{self, BeaconTopics}; @@ -160,6 +160,30 @@ pub(crate) fn apply(server: &mut P2PServer, epoch: Epoch) -> Changes { kept.push(existing.swap_remove(index)); continue; } + // The subscription filter gates this node's own joins, and its list + // is built at startup for a clock that only moves forward: a digest + // the clock has stepped back to may not be on it. Joining it unlisted + // would be refused by gossipsub while everything below records it as + // held and leaves the digests the node was on, so it is listed first. + let every_topic = topics::every_topic( + entry.fork, + entry.digest, + wire.config.attestation_subnet_count, + ); + let listed = server.subscription_allowlist.list(every_topic); + if listed > 0 { + warn!( + fork_digest = %hex::encode(entry.digest), + fork = entry.fork.as_str(), + activation_epoch = entry.activation_epoch, + epoch, + listed, + "Joining a fork digest that was not on the subscription allowlist: the clock \ + has moved back to before the digests listed at startup. Listed it; peers' \ + earlier subscriptions under it were dropped, so its meshes fill as peers \ + connect or subscribe again" + ); + } let joined = BeaconTopics::for_fork( entry.fork, entry.digest, @@ -326,6 +350,57 @@ mod tests { ); } + /// A clock stepped back to before the digests listed at startup has the + /// rollover join one the subscription filter does not list. It is listed + /// first: gossipsub would refuse the joins otherwise, while the node + /// recorded them as held and left the topics it was on. + #[tokio::test] + async fn a_digest_the_clock_steps_back_to_is_listed_before_it_is_joined() { + use crate::subscription_filter::Allowlist; + + let config = config(); + let mut server = unconnected_beacon_server(config.clone(), 0).await; + let schedule = server.wire.beacon().expect("beacon").schedule.clone(); + let gloas = schedule.current_at(GLOAS + 10); + let bpo = schedule.current_at(BPO + 10); + let subnets = config.attestation_subnet_count; + // What a node started well into gloas lists, cut down to gloas's own + // digest: the one before it is not what this test steps back to. + server.subscription_allowlist = + Allowlist::of(topics::every_topic(gloas.fork, gloas.digest, subnets)); + apply(&mut server, GLOAS + 10); + assert_eq!(digests(&server), (gloas.digest, vec![])); + let block_under = |digest| topics::topic_name(digest, "beacon_block"); + assert!( + !server + .subscription_allowlist + .contains(&block_under(bpo.digest)) + ); + + // Back across two boundaries, to an epoch only the BPO digest holds. + apply(&mut server, BPO + 10); + assert_eq!(digests(&server), (bpo.digest, vec![])); + let wire = server.wire.beacon().expect("beacon"); + assert!(!wire.topics.topics.is_empty()); + for topic in &wire.topics.topics { + assert!( + server + .subscription_allowlist + .contains(topic.hash().as_str()), + "{topic} was joined unlisted" + ); + } + // The subnets joined on demand under that digest are listed with it. + let last_attnet = topics::attestation_topic_name(bpo.digest, subnets - 1); + assert!(server.subscription_allowlist.contains(&last_attnet)); + // Nothing is taken off the list: gloas's digest comes back. + assert!( + server + .subscription_allowlist + .contains(&block_under(gloas.digest)) + ); + } + #[tokio::test] async fn a_live_crossing_joins_switches_and_leaves_in_order() { let config = config(); diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index 2e9a50b69..6869e9545 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -1044,10 +1044,10 @@ pub(crate) struct Behaviour { /// 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. +/// to, which bounds what one peer holds, with no count limit of its own. pub(crate) type Gossipsub = libp2p::gossipsub::Behaviour< libp2p::gossipsub::IdentityTransform, - subscription_filter::SubscriptionFilter, + subscription_filter::Allowlist, >; /// No connection limits, which is what the lean network has always run with: a @@ -1210,6 +1210,10 @@ pub struct BuiltSwarm { /// Every dial target per bootnode; see [`dial_addrs`]. Empty entries are never /// inserted; see [`bootnode_dial_addrs`]. pub(crate) bootnode_addrs: HashMap>, + /// A handle on the list the swarm's gossipsub filters subscriptions by, + /// which the fork rollover adds a digest to before joining one that is + /// not on it. + pub(crate) subscription_allowlist: subscription_filter::Allowlist, } /// Why [`build_swarm`] could not produce a usable swarm. @@ -1350,7 +1354,7 @@ 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(); + let filter = subscription_filter::Allowlist::for_wire(&config.wire); build_swarm_with_filter(config, filter) } @@ -1360,7 +1364,7 @@ pub fn build_swarm(config: SwarmConfig) -> Result { /// as peers running other clients do. fn build_swarm_with_filter( config: SwarmConfig, - subscription_filter: subscription_filter::SubscriptionFilter, + subscription_filter: subscription_filter::Allowlist, ) -> Result { let SwarmConfig { node_key, @@ -1398,7 +1402,7 @@ fn build_swarm_with_filter( let mut gossipsub = Gossipsub::new_with_subscription_filter( MessageAuthenticity::Anonymous, gossipsub_config(seen_ttl, validate_messages), - subscription_filter, + subscription_filter.clone(), ) .expect("failed to initiate behaviour"); // Beacon only: the parameters are sized from the beacon chain's topics @@ -1630,6 +1634,7 @@ fn build_swarm_with_filter( swarm, wire, bootnode_addrs, + subscription_allowlist: subscription_filter, }) } @@ -1722,6 +1727,7 @@ impl P2P { store, blockchain: None, wire: built.wire, + subscription_allowlist: built.subscription_allowlist, connected_peers: HashMap::new(), peer_table: peer_table.clone(), peer_custody: HashMap::new(), @@ -1881,6 +1887,12 @@ pub struct P2PServer { pub(crate) wire: Wire, + /// A handle on the list the swarm's gossipsub filters subscriptions by. + /// The fork rollover lists a digest here before it joins one that is not + /// listed, which only a clock stepped back makes it do; see + /// [`subscription_filter::Allowlist`]. + pub(crate) subscription_allowlist: subscription_filter::Allowlist, + /// Every peer holding at least one established connection, and which side /// opened the first one. /// @@ -4328,6 +4340,7 @@ pub(crate) mod test_support { store, blockchain: None, wire: built.wire, + subscription_allowlist: built.subscription_allowlist, connected_peers: HashMap::new(), peer_table: ethlambda_network_api::PeerTableController::default(), peer_custody: HashMap::new(), @@ -4806,11 +4819,22 @@ mod tests { config.with_fork_epoch(ForkName::Gloas, last_boundary + 1_000) } + /// A wire on a digest of the test's own making, which is on no schedule: + /// the allowlist then lists every scheduled digest. fn subscription_test_wire() -> WireConfig { + let fork = subscription_test_config().fork_at_epoch(0); + subscription_test_wire_on([0u8; 4], fork) + } + + /// [`subscription_test_config`]'s wire for a node started on `fork_digest`. + fn subscription_test_wire_on( + fork_digest: [u8; 4], + fork: ethlambda_types::beacon::fork::ForkName, + ) -> WireConfig { let config = subscription_test_config(); WireConfig::Beacon(Box::new(crate::beacon::swarm::BeaconWireConfig { - fork_digest: [0u8; 4], - fork: config.fork_at_epoch(0), + fork_digest, + fork, genesis_time: config.genesis_time, config, genesis_validators_root: ethlambda_types::beacon::primitives::Root::ZERO, @@ -4833,11 +4857,6 @@ mod tests { } } - /// 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() - } - /// 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. @@ -4847,16 +4866,11 @@ mod tests { &config, ethlambda_types::beacon::primitives::Root::ZERO, ); + let subnets = config.attestation_subnet_count; let entries = schedule.entries(); entries[entries.len() - count..] .iter() - .map(|entry| { - beacon::topics::every_topic( - entry.fork, - entry.digest, - config.attestation_subnet_count, - ) - }) + .map(|entry| beacon::topics::every_topic(entry.fork, entry.digest, subnets)) .collect() } @@ -4899,29 +4913,26 @@ mod tests { 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, + recorded_subscriptions_by(subscription_test_wire(), hello, afterwards, awaited).await + } + + /// [`recorded_subscriptions`] with the node on `node_wire`. + async fn recorded_subscriptions_by( + node_wire: WireConfig, + hello: &[libp2p::gossipsub::IdentTopic], + afterwards: &[libp2p::gossipsub::IdentTopic], + awaited: &[libp2p::gossipsub::IdentTopic], + ) -> Option> { + let node_config = SwarmConfig { + wire: node_wire, + ..subscription_test_swarm_config(1) }; + let mut node = build_swarm(node_config).expect("the node's swarm builds"); + // The topics the swarm joins by itself as it is built. + let fork = subscription_test_config().fork_at_epoch(0); + let joined_by_itself = beacon::topics::every_topic(fork, [0u8; 4], 0); + let accepted = hello.iter().chain(afterwards).chain(&joined_by_itself); + let accepts_what_it_is_told = subscription_filter::Allowlist::of(accepted.cloned()); let mut peer = build_swarm_with_filter(subscription_test_swarm_config(2), accepts_what_it_is_told) .expect("the peer's swarm builds"); @@ -5069,6 +5080,44 @@ mod tests { assert_eq!(recorded, HashSet::from([listed.hash()])); } + /// The tests around this one start the node on a digest of their own + /// making, for which every scheduled digest is listed. A node on the + /// chain's current digest lists that one, the one before it and the ones + /// to come, and keeps no subscription under a digest the chain left + /// before: here the last blob-parameter digest of mainnet's schedule, with + /// gloas scheduled after it. Building the node's swarm is half the test, + /// since its own subscriptions go through the same filter. + #[tokio::test] + async fn a_node_on_a_scheduled_digest_keeps_nothing_under_one_the_chain_left() { + let config = subscription_test_config(); + let schedule = beacon::fork_schedule::ForkSchedule::new( + &config, + ethlambda_types::beacon::primitives::Root::ZERO, + ); + let [.., left, previous, start, next] = schedule.entries() else { + panic!("mainnet's schedule with gloas added has more than four digests"); + }; + assert_eq!( + [left.fork, previous.fork, start.fork], + [ethlambda_types::beacon::fork::ForkName::Fulu; 3], + "fulu's own digest and its two blob-parameter ones" + ); + let block = |entry: &beacon::fork_schedule::ScheduledDigest| { + let name = beacon::topics::topic_name(entry.digest, "beacon_block"); + libp2p::gossipsub::IdentTopic::new(name) + }; + + let listed = [block(previous), block(start), block(next)]; + let mut hello = vec![block(left)]; + hello.extend(listed.iter().cloned()); + let node_wire = subscription_test_wire_on(start.digest, start.fork); + let recorded = recorded_subscriptions_by(node_wire, &hello, &[], &listed) + .await + .expect("the topics of the listed digests are heard"); + let expected: HashSet<_> = listed.iter().map(|topic| topic.hash()).collect(); + assert_eq!(recorded, expected, "nothing under the digest left is kept"); + } + /// 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 @@ -5089,40 +5138,24 @@ mod tests { 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. + /// No count limits a hello. One padded with far more unlisted topics than + /// any client's hello cap (500, Prysm's and Teku's) or the whole allowlist + /// is read like any other: its listed topic is kept and the rest dropped. + /// Gossipsub's own per-RPC limit would refuse it whole instead, logging an + /// `ERROR` line for every such RPC a peer cared to send. #[tokio::test] - async fn a_hello_over_the_per_rpc_limit_is_ignored_whole() { - let filter = subscription_test_filter(); + async fn a_hello_padded_with_unlisted_topics_keeps_its_listed_one() { let listed = every_topic_of_the_last_digests(1).concat(); - let later = &listed[..1]; - let in_hello = listed[1].clone(); + let in_hello = listed[0].clone(); - // Exactly at the limit: read, so the listed topic in it is kept. - let mut hello: Vec<_> = (1..filter.max_subscriptions_per_request) + let mut hello: Vec<_> = (0..10_000) .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) + let recorded = recorded_subscriptions(&hello, &[], std::slice::from_ref(&in_hello)) .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"); + .expect("the listed topic is heard"); + assert_eq!(recorded, HashSet::from([in_hello.hash()])); } /// How many times [`concurrent_beacon_requests_on_different_protocols_never_cross`] diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index a3cc51679..5ab8421b4 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -3713,6 +3713,7 @@ pub(crate) mod tests { store, blockchain: None, wire: built.wire, + subscription_allowlist: built.subscription_allowlist, connected_peers: HashMap::new(), peer_table: ethlambda_network_api::PeerTableController::default(), peer_custody: HashMap::new(), diff --git a/crates/net/p2p/src/subscription_filter.rs b/crates/net/p2p/src/subscription_filter.rs index 967236d51..d3ee04b99 100644 --- a/crates/net/p2p/src/subscription_filter.rs +++ b/crates/net/p2p/src/subscription_filter.rs @@ -1,41 +1,55 @@ -//! Which gossipsub topics a peer may be recorded as subscribed to, and how -//! many. +//! Which gossipsub topics a peer may be recorded as subscribed to. //! //! 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. +//! megabyte-long names. An allowlist ([`Allowlist`]) of the topics this node +//! could subscribe or publish to closes that. 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. //! //! 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. +//! There is no count limit beside it, per peer or per RPC, as gossipsub's +//! `MaxCountSubscriptionFilter` would add: +//! +//! - A per-peer limit could only refuse an honest peer. The allowlist already +//! bounds what a peer holds, and how many digests' topics an honest peer +//! holds at once depends on its own client's join and leave timing, with a +//! join counted before the leaves that follow it in later RPCs. A refused +//! join is never resent, so such a peer would stay out of that digest's +//! meshes and fanout until it reconnected. +//! - A per-RPC limit bounds how long one RPC holds the swarm task, not the +//! work a peer can cause, and costs a log flood. Before the allowlist sees +//! an RPC's subscriptions, gossipsub copies every topic name in it into a +//! map (the default `filter_incoming_subscriptions`), on the swarm task +//! rather than the connection's. That is about 0.15 µs an entry: some +//! 0.2 s for an RPC filled to `max_control_message_size` (12 MB here) with +//! a million short names, measured on a copy of that pass and not in a +//! running node. A limit would refuse such an RPC after one length check. +//! The same names split over RPCs under the limit cost the same in total, +//! though, so what a peer can make the swarm task spend is bounded by the +//! bytes it sends either way. And an RPC over the limit is refused with an +//! error gossipsub logs at `ERROR`, with no score penalty and no +//! disconnect, so any connected peer could write error lines at will. A +//! filter of our own cannot turn that refusal into a silent one: the +//! method it would override takes gossipsub's `Subscription`, which the +//! crate does not export. What does shorten the stall is a lower +//! `max_control_message_size`, which is sized in `gossipsub_config`. use std::collections::HashSet; +use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard}; use ethlambda_types::state::VALIDATOR_REGISTRY_LIMIT; -use libp2p::gossipsub::{ - IdentTopic, MaxCountSubscriptionFilter, TopicHash, WhitelistSubscriptionFilter, -}; +use libp2p::gossipsub::{IdentTopic, TopicHash, TopicSubscriptionFilter}; +use tracing::warn; use crate::beacon::fork_schedule::ForkSchedule; use crate::beacon::swarm::BeaconWireConfig; @@ -43,23 +57,26 @@ 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. +/// The topics a peer may be recorded as subscribed to, and the subscription +/// filter both wires run. /// -/// 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. +/// A handle on one shared list: gossipsub owns a clone as its filter, and the +/// `P2PServer` keeps another, so the node can list a digest before it joins +/// one that is not listed ([`Self::list`]). The list is built for a clock that +/// only moves forward, and the same filter gates this node's own joins, so +/// without that a clock stepped back past the listed digests would have the +/// rollover join topics gossipsub refuses, while recording them as held and +/// leaving the ones it was on: a node that hears and publishes nothing until +/// it is restarted. +#[derive(Clone)] pub(crate) struct Allowlist { - topics: HashSet, + topics: Arc>>, +} + +impl TopicSubscriptionFilter for Allowlist { + fn can_subscribe(&mut self, topic_hash: &TopicHash) -> bool { + self.read().contains(topic_hash) + } } impl Allowlist { @@ -70,27 +87,59 @@ impl Allowlist { } } - /// Every topic under every digest the chain's schedule can produce, fork - /// and blob-parameter boundaries alike. + /// Every topic under each digest still held at the first epoch of the + /// digest the node starts on, and under every later one in the chain's + /// schedule, 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. + /// Those are every digest this node can hold for the rest of the process. + /// It starts on `fork_digest`, the one current at the wall clock, so at an + /// epoch at or past that digest's activation, and an earlier digest is + /// held until `UNSUBSCRIBE_LAG_EPOCHS` after its successor activates. That + /// is always the previous digest, and on a schedule with boundaries closer + /// together than the lag (a devnet forking at consecutive epochs) older + /// ones too. From there the schedule only moves forward, as long as the + /// clock does. A clock that stepped back to before those digests has the + /// rollover (`beacon::transition`) join one that is not listed, so it + /// lists the digest first ([`Self::list`]); gossipsub would refuse the + /// join otherwise. A digest the + /// chain left before that is one this node never subscribes or publishes + /// under, so a peer's subscriptions to it are of no use here and are + /// dropped. The range is taken from the start digest's first epoch, not + /// from the epoch the node starts at, which this function is not told: so + /// the previous digest stays listed however long ago the chain left it. Built once, at startup, so the next digest's topics are already + /// listed when peers start subscribing to them ahead of its boundary, and + /// the earlier ones' 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 + /// The start digest is listed by name 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. + /// on a digest it made up. Such a digest cannot be placed on the schedule, + /// so every scheduled digest is listed then, with a warning: outside a + /// test it means the digest and the schedule were derived from different + /// configurations. fn beacon(beacon: &BeaconWireConfig) -> Self { let schedule = ForkSchedule::new(&beacon.config, beacon.genesis_validators_root); - let topics = schedule - .entries() + let entries = schedule.entries(); + let start = entries + .iter() + .find(|entry| entry.digest == beacon.fork_digest); + if start.is_none() { + warn!( + fork_digest = %hex::encode(beacon.fork_digest), + "The fork digest this node starts on is not on its fork schedule; \ + keeping peers' subscriptions under every scheduled digest" + ); + } + let first_held = start + .and_then(|start| schedule.held_at(start.activation_epoch).first().copied()) + .and_then(|first| entries.iter().position(|entry| *entry == first)) + .unwrap_or(0); + let attestation_subnet_count = beacon.config.attestation_subnet_count; + let topics = entries[first_held..] .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) - }); + .flat_map(|(fork, digest)| topics::every_topic(fork, digest, attestation_subnet_count)); Self::of(topics) } @@ -117,54 +166,42 @@ impl Allowlist { Self::of(topics) } - fn of(topics: impl IntoIterator) -> Self { + /// An allowlist of exactly `topics`. + pub(crate) 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)) + Self { + topics: Arc::new(RwLock::new(topics)), + } } - /// The most listed topics one peer may hold: all of them. + /// Add `topics` to the list, for every handle on it. Returns how many + /// were not listed already. /// - /// 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() + /// For the topics this node is about to join, called before the join is + /// sent to the swarm: the list is what bounds a peer's stored + /// subscriptions, so it grows only by what the node itself holds, which + /// the fork schedule bounds. A topic listed late starts with no peer + /// recorded on it. Subscriptions peers sent while it was unlisted were + /// dropped, and gossipsub sends a subscription once, so its mesh fills as + /// peers connect or subscribe again. + pub(crate) fn list(&self, topics: impl IntoIterator) -> usize { + let mut listed = self.topics.write().unwrap_or_else(PoisonError::into_inner); + topics + .into_iter() + .filter(|topic| listed.insert(topic.hash())) + .count() } - /// 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) + /// Every critical section is one set call, so a poisoned lock holds a set + /// that is still whole and is read, not propagated: the filter runs on + /// the swarm task. + fn read(&self) -> RwLockReadGuard<'_, HashSet> { + self.topics.read().unwrap_or_else(PoisonError::into_inner) } - 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)] + pub(crate) fn contains(&self, topic: &str) -> bool { + self.read().contains(&TopicHash::from_raw(topic)) } } @@ -178,7 +215,6 @@ mod tests { }; 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, @@ -201,10 +237,11 @@ mod tests { config } - fn beacon_wire(config: Config) -> BeaconWireConfig { + /// A wire started at `epoch`, on the digest current then. + fn beacon_wire_at(config: Config, epoch: u64) -> BeaconWireConfig { let genesis_validators_root = Root::repeat_byte(7); let schedule = ForkSchedule::new(&config, genesis_validators_root); - let current = schedule.current_at(0); + let current = schedule.current_at(epoch); BeaconWireConfig { fork_digest: current.digest, fork: current.fork, @@ -219,6 +256,12 @@ mod tests { } } + /// A wire started at genesis, so on the first digest: every digest of the + /// schedule is listed. + fn beacon_wire(config: Config) -> BeaconWireConfig { + beacon_wire_at(config, 0) + } + fn lean_wire(attestation_committee_count: u64, subscription_subnets: &[u64]) -> LeanWireConfig { LeanWireConfig { validator_ids: Vec::new(), @@ -317,11 +360,121 @@ mod tests { assert!(allowlist.contains(&topic_name([0u8; 4], "beacon_block"))); } + /// Whatever epoch the node starts at, every digest it holds from then on + /// is listed: its own `subscribe` goes through the filter, so a digest + /// missing here is one it could not join. Checked over the dense start of + /// the schedule, where boundaries one epoch apart keep two earlier digests + /// held at once, and around the two sparse boundaries. + #[test] + fn every_digest_held_from_startup_on_is_listed() { + let config = scheduled_gloas(); + let start_epochs = (0..12).chain(995..1_005).chain(4_995..5_005); + for start in start_epochs { + let wire = beacon_wire_at(config.clone(), start); + let allowlist = Allowlist::beacon(&wire); + let schedule = ForkSchedule::new(&wire.config, wire.genesis_validators_root); + for epoch in (start..start + 12).chain([1_000, 1_003, 5_000, 5_003]) { + let held = schedule.held_at(epoch.max(start)); + for entry in held { + let block = topic_name(entry.digest, "beacon_block"); + let fork = entry.fork; + assert!( + allowlist.contains(&block), + "{fork:?} at {epoch}, from {start}" + ); + } + } + } + } + + /// A node started after several boundaries lists no digest the chain left + /// before it started: it never subscribes or publishes under those again. + /// Started at electra's first epoch, with capella, deneb and electra one + /// epoch apart, it still holds capella and deneb, and so lists them. + #[test] + fn a_digest_left_before_startup_is_not_listed() { + let wire = beacon_wire_at(scheduled_gloas(), 5); + let allowlist = Allowlist::beacon(&wire); + let schedule = ForkSchedule::new(&wire.config, wire.genesis_validators_root); + assert_eq!(wire.fork_digest, digest_of(&schedule, ForkName::Electra)); + + let listed = [ + ForkName::Capella, + ForkName::Deneb, + ForkName::Electra, + ForkName::Fulu, + ForkName::Gloas, + ]; + let left = [ForkName::Phase0, ForkName::Altair, ForkName::Bellatrix]; + for (forks, expected) in [(&listed[..], true), (&left[..], false)] { + for &fork in forks { + let block = topic_name(digest_of(&schedule, fork), "beacon_block"); + assert_eq!(allowlist.contains(&block), expected, "{fork:?}"); + } + } + + // Past the sparse fulu boundary, only electra is still held of the + // earlier digests. + let wire = beacon_wire_at(scheduled_gloas(), 1_000); + let allowlist = Allowlist::beacon(&wire); + let electra = topic_name(digest_of(&schedule, ForkName::Electra), "beacon_block"); + let deneb = topic_name(digest_of(&schedule, ForkName::Deneb), "beacon_block"); + assert!(allowlist.contains(&electra)); + assert!(!allowlist.contains(&deneb)); + } + + /// Mainnet's own schedule ends in three digests under one fork: fulu's and + /// its two blob-parameter ones. A node started today is on the last and + /// lists it and the one before; fulu's own digest and electra's were left + /// long before. Started on the first blob-parameter digest's second epoch, + /// it lists fulu's own too, which is held until two epochs after that + /// boundary. The epochs are mainnet's, written out here, and the + /// expectations follow from them rather than from `held_at`. + #[test] + fn a_start_on_a_blob_parameter_digest_lists_it_and_the_one_before() { + const ELECTRA: u64 = 364_032; + const FULU: u64 = 411_392; + const FIRST_BLOB_PARAMETERS: u64 = 412_672; + const SECOND_BLOB_PARAMETERS: u64 = 419_072; + + let config = Config::mainnet(); + let schedule = ForkSchedule::new(&config, Root::repeat_byte(7)); + let digest_from = |epoch: u64| { + let entry = schedule + .entries() + .iter() + .find(|entry| entry.activation_epoch == epoch); + entry.expect("mainnet has a boundary at this epoch").digest + }; + let block = |epoch: u64| topic_name(digest_from(epoch), "beacon_block"); + let digests: HashSet<_> = [FULU, FIRST_BLOB_PARAMETERS, SECOND_BLOB_PARAMETERS] + .map(digest_from) + .into(); + assert_eq!(digests.len(), 3, "one fork, three digests"); + + let wire = beacon_wire_at(config.clone(), SECOND_BLOB_PARAMETERS + 10_000); + assert_eq!(wire.fork_digest, digest_from(SECOND_BLOB_PARAMETERS)); + assert_eq!(wire.fork, ForkName::Fulu); + let allowlist = Allowlist::beacon(&wire); + assert!(allowlist.contains(&block(SECOND_BLOB_PARAMETERS))); + assert!(allowlist.contains(&block(FIRST_BLOB_PARAMETERS))); + assert!(!allowlist.contains(&block(FULU))); + assert!(!allowlist.contains(&block(ELECTRA))); + + let wire = beacon_wire_at(config, FIRST_BLOB_PARAMETERS + 1); + assert_eq!(wire.fork_digest, digest_from(FIRST_BLOB_PARAMETERS)); + let allowlist = Allowlist::beacon(&wire); + assert!(allowlist.contains(&block(SECOND_BLOB_PARAMETERS))); + assert!(allowlist.contains(&block(FIRST_BLOB_PARAMETERS))); + assert!(allowlist.contains(&block(FULU))); + assert!(!allowlist.contains(&block(ELECTRA))); + } + #[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 mut filter = Allowlist::beacon(&wire); let listed = IdentTopic::new(topic_name(digest, "beacon_block")).hash(); let unlisted = IdentTopic::new(topic_name(digest, "light_client_finality_update")).hash(); @@ -329,20 +482,6 @@ mod tests { 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])); @@ -354,7 +493,7 @@ mod tests { } 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); + assert_eq!(allowlist.read().len(), 6); } /// An aggregation subnet named past the committee count is still one this @@ -374,7 +513,7 @@ mod tests { 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_eq!(allowlist.read().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())); } @@ -387,15 +526,36 @@ mod tests { 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. + /// The list is shared with the filter gossipsub owns: a topic listed + /// through one handle is one the behaviour holding another will join. A + /// join of an unlisted topic is refused, which is what the fork rollover + /// lists a digest to avoid. #[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 - ); + fn a_topic_listed_later_can_be_joined_by_the_behaviour_holding_the_filter() { + use libp2p::gossipsub::{ + Behaviour, IdentityTransform, MessageAuthenticity, SubscriptionError, + }; + + let listed_at_start = IdentTopic::new("/eth2/aaaaaaaa/beacon_block/ssz_snappy"); + let listed_later = IdentTopic::new("/eth2/bbbbbbbb/beacon_block/ssz_snappy"); + let allowlist = Allowlist::of([listed_at_start.clone()]); + let mut gossipsub: Behaviour = + Behaviour::new_with_subscription_filter( + MessageAuthenticity::Anonymous, + crate::gossipsub_config(std::time::Duration::from_secs(60), false), + allowlist.clone(), + ) + .expect("the node's own gossipsub configuration"); + + assert!(matches!(gossipsub.subscribe(&listed_at_start), Ok(true))); + assert!(matches!( + gossipsub.subscribe(&listed_later), + Err(SubscriptionError::NotAllowed) + )); + + assert_eq!(allowlist.list([listed_later.clone()]), 1); + assert!(matches!(gossipsub.subscribe(&listed_later), Ok(true))); + // Listing what is listed already adds nothing. + assert_eq!(allowlist.list([listed_later, listed_at_start]), 0); } } diff --git a/crates/net/p2p/src/swarm_adapter.rs b/crates/net/p2p/src/swarm_adapter.rs index 7e80c238c..af7a66eb7 100644 --- a/crates/net/p2p/src/swarm_adapter.rs +++ b/crates/net/p2p/src/swarm_adapter.rs @@ -4,7 +4,9 @@ use std::time::Duration; use libp2p::{ PeerId, futures::StreamExt, - gossipsub::{FailedMessages, IdentTopic, MessageId, PublishError, TopicScoreParams}, + gossipsub::{ + FailedMessages, IdentTopic, MessageId, PublishError, SubscriptionError, TopicScoreParams, + }, request_response, swarm::{SwarmEvent, dial_opts::DialOpts}, }; @@ -650,11 +652,20 @@ pub(crate) fn execute_command(swarm: &mut libp2p::Swarm, cmd: SwarmCo } } SwarmCommand::Subscribe(topic) => { - let _ = swarm - .behaviour_mut() - .gossipsub - .subscribe(&topic) - .inspect_err(|err| warn!(%topic, %err, "Swarm adapter: subscribe failed")); + match swarm.behaviour_mut().gossipsub.subscribe(&topic) { + Ok(_) => {} + // The subscription filter gates this node's own joins too. A + // topic it refuses is one the node goes without, and nothing + // retries the join. The fork rollover lists a digest before + // joining it, so this is a topic kind missing from + // `beacon::topics::every_topic`. + Err(SubscriptionError::NotAllowed) => error!( + %topic, + "Swarm adapter: subscribe refused, the topic is not on the subscription \ + allowlist; this node hears nothing on it" + ), + Err(err) => warn!(%topic, %err, "Swarm adapter: subscribe failed"), + } } SwarmCommand::Unsubscribe(topic) => { swarm.behaviour_mut().gossipsub.unsubscribe(&topic); diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 71ebc9b42..5c50230e0 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -377,40 +377,70 @@ 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. +(`p2p/src/subscription_filter.rs`): 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 digest still held at the first epoch of the digest the +node starts on, and every later digest of the chain's schedule (fork and +blob-parameter boundaries alike; gloas's four kinds under gloas digests only). +Those are every digest the node can hold for the rest of the process: an +earlier digest is still held for a couple of epochs after its successor's +boundary (always the previous one, and older ones too on a devnet forking at +consecutive epochs), and the schedule only moves forward. That holds while the +clock does. A clock stepped back to before those digests has the rollover join +one that is not listed, and the same filter gates this node's own joins, so the +rollover lists the digest first (`Allowlist::list`, on a handle the `P2PServer` +keeps to the list gossipsub filters by) and logs a warning. Unlisted, gossipsub +would refuse those joins while the rollover recorded them as held and left the +topics the node was on, and the node would hear and publish nothing until a +restart. A digest listed that late starts with no peer recorded on it: the +subscriptions peers sent while it was unlisted were dropped and are not sent +again, so its meshes fill as peers connect or subscribe again. The range is +taken from the start digest's first epoch, not the epoch the node starts at, so +the previous digest stays listed however long ago the chain left it. +The list is built at startup, so the next digest's topics are listed +before peers join them, and grows only by a digest the node itself joins. 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, a digest the chain left before the node started, another chain's +digest, a made-up name) is dropped and costs the peer nothing. 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. +topic, two digests' worth on mainnet today. No count limit is set beside it, +per peer or per RPC, because neither is worth its cost: + +- **Per peer**, 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 would leave a + peer that holds one digest more out of that digest's meshes and fanout until + it reconnected. +- **Per RPC**, gossipsub's `MaxCountSubscriptionFilter` refuses an RPC over + the limit whole, with an error it logs at `ERROR`, naming the peer, and no + score penalty or disconnect, so any connected peer could write error lines + at will. What it saves is the length of one stall, not the work. Before the + allowlist sees an RPC's subscriptions, gossipsub copies every topic name in + it into a map, on the swarm task: about 0.15 µs an entry, so some 0.2 s for + an RPC filled to `max_control_message_size` (12 MB here) with a million + short names (measured on a copy of that pass, not in a running node). A + limit would refuse that RPC after one length check, but the same names split + over RPCs under the limit cost the same in total, so what a peer can make + the swarm task spend is bounded by the bytes it sends either way. A lower + `max_control_message_size` is what would shorten the stall; it is set to the + frame bound, since an honest hello around a boundary and a large IHAVE both + pass gossipsub's 16 KiB default (`gossipsub_config`). A filter of our own + that drops an over-limit RPC quietly is not possible, since the method it + would override takes gossipsub's `Subscription`, which the crate does not + export. + +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