diff --git a/CLAUDE.md b/CLAUDE.md index 884e97e9e..1f1c62676 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -449,18 +449,22 @@ actual_slot = finalized_slot + 1 + relative_index mailbox) and the store's head (which gossip imports move and the watermark never sees). Fetched blocks reach the actor as `BlockSource::Sync`. - Gloas adds `execution_payload_envelopes_by_{range,root}/1`. Server: canonical FULL - envelopes only, and the head's envelope only when the head node is FULL. A by-range - answer stops once `ENVELOPES_BY_RANGE_BYTE_BUDGET` (16 MiB of SSZ) has gone out, always - carrying the first envelope, and is never in memory whole: the handler plans it and the - codec reads each row as it writes that chunk (`EnvelopesByRange`), decoding every one - before it goes out. The plan starts at gloas's first slot: planning decodes each next - block for its bid, and a pre-gloas block carries its whole payload. Client: by root + envelopes only, and the head's envelope only when the head node is FULL. Either answer + stops once its byte budget (`ENVELOPES_BY_RANGE_BYTE_BUDGET`, 16 MiB of SSZ, and + `ENVELOPES_BY_ROOT_BYTE_BUDGET`, the same) has gone out, always carrying the first + envelope, and is never in memory whole: the handler plans it and the codec reads each + row as it writes that chunk (`EnvelopeAnswer`). A by-range row is decoded before it + goes out, and the range plan starts at gloas's first slot: planning decodes each next + block for its bid, and a pre-gloas block carries its whole payload. A by-root request's + repeated root is answered once. Client: by root on `needs_envelope` (same dedup and retry ladder as block fetches) and on a gossip vote for a payload not verified here (at most once a slot per root), by range after a gloas span's blocks were handed to the actor, with range sync holding the next batch until the envelope answer is forwarded (the actor keeps unmatched envelopes only briefly); an answer that stops short of the span is followed by a request for the slots after its last envelope, the batch still held, for up to `ENVELOPE_FOLLOW_UP_WINDOW` (30 s). + The reader stops at `ENVELOPE_RESPONSE_BYTE_BUDGET` (16 MiB) too, so a peer's longer + answer reads as a short one rather than being held whole. Their chunks carry four `` (the block's own epoch's fork digest), which is why `BeaconWire` and the codec carry `genesis_validators_root`. See [`docs/beacon_wire.md`](docs/beacon_wire.md) diff --git a/crates/net/p2p/src/beacon/encoding.rs b/crates/net/p2p/src/beacon/encoding.rs index cbce0b35d..b6539ca41 100644 --- a/crates/net/p2p/src/beacon/encoding.rs +++ b/crates/net/p2p/src/beacon/encoding.rs @@ -55,7 +55,7 @@ use super::protocols::{self, MAX_REQUEST_BLOCKS_DENEB}; use super::size_bounds; use crate::req_resp::codec::write_success_chunk; use crate::req_resp::encoding::{ChunkLimits, MAX_PAYLOAD_SIZE, invalid, read_chunked_response}; -use crate::req_resp::envelopes::EnvelopesByRange; +use crate::req_resp::envelopes::{ENVELOPE_RESPONSE_BYTE_BUDGET, EnvelopeAnswer}; use crate::req_resp::messages::BlocksByRangeRequest; /// This chain's wire body for a slot window. Every field is shared, since this @@ -209,6 +209,7 @@ where // The deneb ceiling rather than the phase0 one, because it bounds what // *this* node asks for and nothing else opens one of these streams. max_chunks: MAX_REQUEST_BLOCKS_DENEB as usize, + max_bytes: None, }; read_chunked_response(io, protocol_label, limits, |context, payload| { let block = decode::decode_block(config, payload) @@ -305,6 +306,7 @@ where // The widest a single request can legitimately ask for, on either // column protocol; see `protocols::max_request_data_column_sidecars`. max_chunks: protocols::max_request_data_column_sidecars() as usize, + max_bytes: None, }; let schedule = ForkSchedule::new(config, genesis_validators_root); let gloas_bound = size_bounds::max_data_column_sidecar_size(config); @@ -421,23 +423,24 @@ where Ok(()) } -/// Write this node's own `ExecutionPayloadEnvelopesByRange` answer, reading -/// each envelope out of the store just before its chunk goes out. +/// Write one of this node's own envelope answers (by range or by root), +/// reading each envelope out of the store just before its chunk goes out. /// /// Same chunks as [`write_execution_payload_envelopes_response`], without the /// answer ever being in memory whole: one envelope is held at a time, and the /// next is read only once the peer has taken this one. Which envelopes there -/// are, and where the answer stops, is [`EnvelopesByRange`]'s business. The +/// are, and where the answer stops, is [`EnvelopeAnswer`]'s business. The /// rows go out as stored, with no decode and re-encode in between. -pub async fn write_envelopes_by_range_response( +pub async fn write_stored_envelopes_response( io: &mut T, label: &'static str, config: &Config, genesis_validators_root: Root, - answer: &mut EnvelopesByRange, + answer: &mut EnvelopeAnswer, ) -> io::Result<()> where T: AsyncWrite + Unpin + Send, + I: Iterator> + Send, { while let Some(envelope) = answer.next_envelope() { write_execution_payload_envelope_chunk( @@ -469,18 +472,47 @@ fn carries_envelopes(fork: ForkName) -> bool { /// refused too ([`carries_envelopes`]). /// The context is then checked against the digest the payload's own /// `slot_number` implies. +/// +/// Reading stops once [`ENVELOPE_RESPONSE_BYTE_BUDGET`] of envelopes has been +/// read: a peer may send `MAX_REQUEST_PAYLOADS` chunks of `MAX_PAYLOAD_SIZE`, +/// over a gigabyte held until the stream ends, whatever was asked for. What +/// was read is returned as the answer, and the rest of the peer's is left +/// unread. pub async fn decode_execution_payload_envelopes_response( io: &mut T, protocol_label: &str, config: &Config, genesis_validators_root: Root, ) -> io::Result> +where + T: AsyncRead + Unpin + Send, +{ + decode_execution_payload_envelopes_response_within( + io, + protocol_label, + config, + genesis_validators_root, + ENVELOPE_RESPONSE_BYTE_BUDGET, + ) + .await +} + +/// [`decode_execution_payload_envelopes_response`] under a byte budget of the +/// caller's choosing. +pub(crate) async fn decode_execution_payload_envelopes_response_within( + io: &mut T, + protocol_label: &str, + config: &Config, + genesis_validators_root: Root, + budget: usize, +) -> io::Result> where T: AsyncRead + Unpin + Send, { let limits = ChunkLimits { has_context: true, max_chunks: protocols::MAX_REQUEST_PAYLOADS as usize, + max_bytes: Some(budget), }; let schedule = ForkSchedule::new(config, genesis_validators_root); read_chunked_response(io, protocol_label, limits, |context, payload| { diff --git a/crates/net/p2p/src/lean/encoding.rs b/crates/net/p2p/src/lean/encoding.rs index abceb8eab..587a206c5 100644 --- a/crates/net/p2p/src/lean/encoding.rs +++ b/crates/net/p2p/src/lean/encoding.rs @@ -111,6 +111,7 @@ where // for: `blocks_by_range` is refused above it, and `blocks_by_root` // cannot name more roots than the request list holds. max_chunks: protocols::MAX_REQUEST_BLOCKS as usize, + max_bytes: None, }; let blocks = read_chunked_response(io, protocol_label, limits, |_, payload| { SignedBlock::from_ssz_bytes(payload) diff --git a/crates/net/p2p/src/req_resp/codec.rs b/crates/net/p2p/src/req_resp/codec.rs index 144fca25c..da3e1d0e6 100644 --- a/crates/net/p2p/src/req_resp/codec.rs +++ b/crates/net/p2p/src/req_resp/codec.rs @@ -383,8 +383,8 @@ impl libp2p::request_response::Codec for Codec { { let label = protocol_label(protocol.as_ref()); match resp { - // By `&mut`: the by-range envelope answer is consumed as it is - // written. Every other payload is only read. + // By `&mut`: this node's envelope answers are consumed as they + // are written. Every other payload is only read. Response::Success { mut payload } => match &mut payload { ResponsePayload::LeanStatus(status) => { write_success_chunk(io, label, NO_CONTEXT, lean_encoding::encode_status(status)) @@ -444,7 +444,18 @@ impl libp2p::request_response::Codec for Codec { } ResponsePayload::ExecutionPayloadEnvelopesByRange(answer) => { let context = self.beacon_context(protocol.as_ref())?; - beacon_encoding::write_envelopes_by_range_response( + beacon_encoding::write_stored_envelopes_response( + io, + label, + &context.config, + context.genesis_validators_root, + answer, + ) + .await + } + ResponsePayload::ExecutionPayloadEnvelopesByRoot(answer) => { + let context = self.beacon_context(protocol.as_ref())?; + beacon_encoding::write_stored_envelopes_response( io, label, &context.config, diff --git a/crates/net/p2p/src/req_resp/encoding.rs b/crates/net/p2p/src/req_resp/encoding.rs index 0ffde7e9a..75cbaaf7b 100644 --- a/crates/net/p2p/src/req_resp/encoding.rs +++ b/crates/net/p2p/src/req_resp/encoding.rs @@ -172,6 +172,16 @@ pub struct ChunkLimits { /// which is the request ceiling: a peer sending more than was ever askable /// for is not answering a request. pub max_chunks: usize, + /// The payload bytes, uncompressed, after which no further chunk is read, + /// or `None` to read until the peer closes or `max_chunks` is passed. + /// + /// Unlike `max_chunks` this is not a refusal: reading stops and what was + /// read is the answer, so the caller sees a short answer and can ask for + /// the rest. It is for a protocol whose chunks are large enough that + /// `max_chunks` of them is more than should be held at once. The chunk + /// that crosses the limit is kept, so the first chunk always is, and an + /// answer holds less than one chunk more than this. + pub max_bytes: Option, } /// Read a response that is one chunk per item, until the peer closes. @@ -188,7 +198,8 @@ pub struct ChunkLimits { /// /// A chunk with a non-success code is logged and skipped rather than ending the /// stream, so a peer that holds some of what was asked for can answer with that -/// much. The stream ends at EOF. `Err` only on an I/O error other than +/// much. The stream ends at EOF, or once `max_bytes` of payload have been read, +/// which leaves the rest of the peer's answer unread. `Err` only on an I/O error other than /// `UnexpectedEof`, on more than `max_chunks` chunks, or when `decode` refuses /// one, in which case nothing read so far is returned: a peer that mis-encodes /// one chunk has not shown itself trustworthy about the others. @@ -205,13 +216,23 @@ where let ChunkLimits { has_context, max_chunks, + max_bytes, } = limits; let mut items = Vec::new(); // Counts every chunk, not just the ones that decoded: a stream of error // chunks costs the same to read as a stream of blocks. let mut chunks = 0_usize; + // Likewise every chunk's payload, kept or not. + let mut payload_bytes = 0_usize; loop { + if chunks > 0 && max_bytes.is_some_and(|max_bytes| payload_bytes >= max_bytes) { + debug!( + chunks, + payload_bytes, "Stopped reading {protocol_label} response at its byte limit" + ); + break; + } let mut result_byte = 0_u8; if let Err(err) = io.read_exact(std::slice::from_mut(&mut result_byte)).await { if err.kind() == io::ErrorKind::UnexpectedEof { @@ -242,6 +263,7 @@ where let decoded = decode_payload(io).await?; let payload = decoded.uncompressed; + payload_bytes = payload_bytes.saturating_add(payload.len()); metrics::observe_reqresp_response_chunk_size( protocol_label, payload.len(), diff --git a/crates/net/p2p/src/req_resp/envelopes.rs b/crates/net/p2p/src/req_resp/envelopes.rs index 374c0b61d..d5a2294f2 100644 --- a/crates/net/p2p/src/req_resp/envelopes.rs +++ b/crates/net/p2p/src/req_resp/envelopes.rs @@ -2,8 +2,9 @@ //! (`execution_payload_envelopes_by_range/1` and `_by_root/1`): the server side, //! answering peers out of `Table::ExecutionPayloadEnvelopes`. -use ethlambda_storage::{CanonicalEnvelopes, Store, StoredEnvelope}; -use ethlambda_types::beacon::containers::gloas; +use std::collections::HashSet; + +use ethlambda_storage::{CanonicalEnvelopes, EnvelopesOfBlocks, Store, StoredEnvelope}; use ethlambda_types::primitives::H256; use libp2p::PeerId; use libp2p::request_response::ResponseChannel; @@ -41,7 +42,32 @@ pub(crate) const ENVELOPES_BY_RANGE_BYTE_BUDGET: usize = 16 * 1024 * 1024; // answer that is cut short still carries more than the one it must. const _: () = assert!(ENVELOPES_BY_RANGE_BYTE_BUDGET > MAX_PAYLOAD_SIZE); -/// An `ExecutionPayloadEnvelopesByRange` answer that is still in the store. +/// How many bytes of envelopes one `ExecutionPayloadEnvelopesByRoot` answer +/// sends before it stops: [`ENVELOPES_BY_RANGE_BYTE_BUDGET`], for the same +/// reasons. A request may name `MAX_REQUEST_PAYLOADS` roots, so by count +/// alone its answer is as large as a range's. The specification allows the +/// cut in the same words, and asks for "at least one payload envelope, if +/// they have it", which stopping only after the budget is spent gives. +pub(crate) const ENVELOPES_BY_ROOT_BYTE_BUDGET: usize = ENVELOPES_BY_RANGE_BYTE_BUDGET; + +/// How many bytes of envelopes this node reads out of one answer, to either +/// envelope protocol, before it stops reading. +/// +/// The serving budgets bound what this node sends; nothing bounds what a peer +/// sends back but `MAX_REQUEST_PAYLOADS` chunks of `MAX_PAYLOAD_SIZE`, which +/// is over a gigabyte decoded and held until the stream ends, whatever the +/// request asked for. The reader stops at the same 16 MiB the servers do, by +/// the same rule: the envelope that crosses the budget is kept, so the first +/// always is and one answer holds under 26 MiB. An answer from a node with +/// this serving budget is therefore read whole. +/// +/// A longer answer is cut, not refused, and reads as a short one. By range, +/// the requester asks again for the slots after the last envelope it read +/// ([`ENVELOPE_FOLLOW_UP_WINDOW`](super::envelope_client::ENVELOPE_FOLLOW_UP_WINDOW)). +/// By root this node names one root a request, so one envelope answers it. +pub(crate) const ENVELOPE_RESPONSE_BYTE_BUDGET: usize = ENVELOPES_BY_RANGE_BYTE_BUDGET; + +/// An envelope answer that is still in the store, sent under a byte budget. /// /// The handler decides which envelopes answer the request; the codec then /// takes them out one at a time as it writes each chunk @@ -49,18 +75,30 @@ const _: () = assert!(ENVELOPES_BY_RANGE_BYTE_BUDGET > MAX_PAYLOAD_SIZE); /// the P2P actor reads no envelope, and a peer that stops reading stops the /// reads too. /// -/// A [`ResponsePayload`] variant of its own -/// ([`ResponsePayload::ExecutionPayloadEnvelopesByRange`]), which only the -/// write side has: an answer read off the wire is the envelopes themselves. +/// `I` is where the envelopes come from: [`EnvelopesByRange`] or +/// [`EnvelopesByRoot`]. Each is a [`ResponsePayload`] variant of its own, +/// which only the write side has: an answer read off the wire is the +/// envelopes themselves ([`ResponsePayload::ExecutionPayloadEnvelopes`]). #[derive(Debug, Clone)] -pub struct EnvelopesByRange { - envelopes: CanonicalEnvelopes, +pub struct EnvelopeAnswer { + envelopes: I, /// The bytes still to send before the answer stops; zero once it has. budget: usize, } -impl EnvelopesByRange { - fn new(envelopes: CanonicalEnvelopes, budget: usize) -> Self { +/// This node's answer to `ExecutionPayloadEnvelopesByRange` +/// ([`ResponsePayload::ExecutionPayloadEnvelopesByRange`]). +pub type EnvelopesByRange = EnvelopeAnswer; + +/// This node's answer to `ExecutionPayloadEnvelopesByRoot` +/// ([`ResponsePayload::ExecutionPayloadEnvelopesByRoot`]). +pub type EnvelopesByRoot = EnvelopeAnswer; + +impl EnvelopeAnswer +where + I: Iterator>, +{ + fn new(envelopes: I, budget: usize) -> Self { Self { envelopes, budget } } @@ -70,12 +108,12 @@ impl EnvelopesByRange { if self.budget == 0 { 0 } else { - self.envelopes.remaining() + self.envelopes.size_hint().1.unwrap_or(usize::MAX) } } - /// The next envelope to send, or `None` when the answer is over: the - /// window is exhausted, the byte budget is spent, or the store failed. + /// The next envelope to send, or `None` when the answer is over: there + /// are no more, the byte budget is spent, or the store failed. /// /// Never panics and never fails the stream. A row that cannot be read /// ends the answer where it is, so the peer keeps the envelopes already @@ -106,8 +144,8 @@ impl EnvelopesByRange { if self.budget == 0 { debug!( last_slot = envelope.slot, - left = self.envelopes.remaining(), - "ExecutionPayloadEnvelopesByRange answer stopped at its byte budget" + left = self.envelopes.size_hint().1, + "Envelope answer stopped at its byte budget" ); } return Some(envelope); @@ -228,7 +266,7 @@ fn envelopes_by_range_within( // that slot, which answers it empty: no block is anywhere near there. let end_slot = start_slot.saturating_add(last_offset); let envelopes = store.canonical_execution_payload_envelopes(start_slot, end_slot); - Ok(EnvelopesByRange::new(envelopes, budget)) + Ok(EnvelopeAnswer::new(envelopes, budget)) } /// Answer `execution_payload_envelopes_by_root/1` with whichever of the named @@ -238,6 +276,10 @@ fn envelopes_by_range_within( /// stored envelope is left out rather than answered with an error, and the /// answer follows the order asked in. Roots past `MAX_REQUEST_PAYLOADS` are /// ignored (the wire list type already bounds a decoded request to it). +/// +/// As for a range, no envelope is read here, and the answer stops at a byte +/// budget ([`ENVELOPES_BY_ROOT_BYTE_BUDGET`]): the codec reads each envelope +/// as it writes it ([`EnvelopesByRoot`]). pub(super) async fn handle_execution_payload_envelopes_by_root_request( server: &mut P2PServer, peer: PeerId, @@ -249,42 +291,44 @@ pub(super) async fn handle_execution_payload_envelopes_by_root_request( }; let requested = roots.len(); - let envelopes = envelopes_by_root(&server.store, &roots); + let answer = envelopes_by_root(&server.store, &roots); trace!( %peer, requested, - found = envelopes.len(), + planned = answer.remaining(), "Responding to ExecutionPayloadEnvelopesByRoot request" ); respond( server, channel, - ResponsePayload::ExecutionPayloadEnvelopes(envelopes), + ResponsePayload::ExecutionPayloadEnvelopesByRoot(answer), ); } -/// The held envelopes among `roots`, in the order asked, looking at no more -/// than `MAX_REQUEST_PAYLOADS` of them. -fn envelopes_by_root(store: &Store, roots: &[H256]) -> Vec { - roots +/// The answer to `ExecutionPayloadEnvelopesByRoot`: the held envelopes among +/// `roots`, in the order asked, each once, looking at no more than +/// `MAX_REQUEST_PAYLOADS` roots, and cut off once +/// [`ENVELOPES_BY_ROOT_BYTE_BUDGET`] has been sent. +fn envelopes_by_root(store: &Store, roots: &[H256]) -> EnvelopesByRoot { + envelopes_by_root_within(store, roots, ENVELOPES_BY_ROOT_BYTE_BUDGET) +} + +/// [`envelopes_by_root`] under a byte budget of the caller's choosing. +/// +/// A root named again is answered once, at its first place. The answer is +/// "a list [...] whose length is less than or equal to the number of +/// requested" envelopes either way, and sending a block's envelope once per +/// mention would let one stored envelope fill a whole answer. +fn envelopes_by_root_within(store: &Store, roots: &[H256], budget: usize) -> EnvelopesByRoot { + let mut named = HashSet::new(); + let roots = roots .iter() .take(MAX_REQUEST_PAYLOADS as usize) - .filter_map(|root| { - store - .get_execution_payload_envelope(root) - .inspect_err(|err| { - error!( - root = %ethlambda_types::ShortRoot(&root.0), - %err, - "Stored execution payload envelope failed to read" - ) - }) - .ok() - .flatten() - }) - .collect() + .filter(|root| named.insert(**root)) + .copied(); + EnvelopeAnswer::new(store.execution_payload_envelopes_of(roots), budget) } #[cfg(test)] @@ -292,11 +336,13 @@ mod tests { use super::*; use crate::beacon::BeaconContext; use crate::beacon::encoding::test_support; - use crate::beacon::protocols::EXECUTION_PAYLOAD_ENVELOPES_BY_RANGE_V1; + use crate::beacon::protocols::{ + EXECUTION_PAYLOAD_ENVELOPES_BY_RANGE_V1, EXECUTION_PAYLOAD_ENVELOPES_BY_ROOT_V1, + }; use crate::req_resp::Codec; use ethlambda_storage::{ForkCheckpoints, StorageBackend, Table, backend::InMemoryBackend}; use ethlambda_types::beacon::config::Config; - use ethlambda_types::beacon::containers::SignedBeaconBlock; + use ethlambda_types::beacon::containers::{SignedBeaconBlock, gloas}; use ethlambda_types::beacon::fork_choice::PayloadStatus; use ethlambda_types::beacon::preset; use ethlambda_types::checkpoint::Checkpoint; @@ -364,7 +410,10 @@ mod tests { } /// Every envelope `answer` sends, decoded, in the order sent. - fn drain(mut answer: EnvelopesByRange) -> Vec { + fn drain(mut answer: EnvelopeAnswer) -> Vec + where + I: Iterator>, + { let mut sent = Vec::new(); while let Some(stored) = answer.next_envelope() { let envelope = gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(&stored.ssz) @@ -800,6 +849,58 @@ mod tests { } } + /// The requester's side of the budget: an answer longer than it is read + /// up to the envelope that crosses it, and the rest is left on the wire, + /// so what a peer chooses to send does not decide what this node holds. + #[tokio::test] + async fn an_envelope_answer_is_read_up_to_the_readers_byte_budget() { + let base = Config::mainnet(); + let config = Config { + gloas_fork_epoch: base.fulu_fork_epoch + 64, + ..base + }; + let genesis_validators_root = H256::repeat_byte(0x4b); + let first_slot = config.gloas_fork_epoch * preset::slots_per_epoch(); + let backend = Arc::new(InMemoryBackend::new()); + let mut store = beacon_store_with(backend, config.clone(), first_slot); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, first_slot + 1, 4); + let size = envelopes[0].to_ssz().len(); + let protocol = StreamProtocol::new(EXECUTION_PAYLOAD_ENVELOPES_BY_RANGE_V1); + // The peer sends all four, whatever this node would have sent. + let answer = envelopes_by_range(&store, first_slot + 1, 4).expect("answered"); + let response = Response::success(ResponsePayload::ExecutionPayloadEnvelopesByRange(answer)); + let mut wire = Cursor::new(Vec::new()); + Codec::beacon(BeaconContext { + config: config.clone(), + genesis_validators_root, + }) + .write_response(&protocol, &mut wire, response) + .await + .expect("writes"); + let wire = wire.into_inner(); + + for (budget, read_count) in [ + (usize::MAX, 4), + (2 * size + 1, 3), + (2 * size, 2), + (2 * size - 1, 2), + // The first envelope is read under any budget. + (1, 1), + (0, 1), + ] { + let read = crate::beacon::encoding::decode_execution_payload_envelopes_response_within( + &mut Cursor::new(wire.clone()), + "envelopes", + &config, + genesis_validators_root, + budget, + ) + .await + .expect("reads"); + assert_eq!(read, envelopes[..read_count], "budget {budget}"); + } + } + #[test] fn by_root_serves_known_envelopes_in_request_order_and_skips_unknown_roots() { let (store, envelopes) = chain_with_every_payload_built_on(); @@ -809,7 +910,7 @@ mod tests { .collect(); let asked = vec![roots[2], H256::repeat_byte(0xee), roots[0]]; - let served = envelopes_by_root(&store, &asked); + let served = drain(envelopes_by_root(&store, &asked)); assert_eq!(served, vec![envelopes[2].clone(), envelopes[0].clone()]); } @@ -821,6 +922,111 @@ mod tests { let mut asked = vec![H256::repeat_byte(0xee); MAX_REQUEST_PAYLOADS as usize]; asked.push(known); - assert!(envelopes_by_root(&store, &asked).is_empty()); + assert!(drain(envelopes_by_root(&store, &asked)).is_empty()); + } + + /// By root there is no chain rule: an envelope the canonical chain did + /// not build on is served when it is asked for by name. + #[test] + fn by_root_serves_an_envelope_the_chain_did_not_build_on() { + let mut store = beacon_store(); + let root_1 = extend_chain(&mut store, gloas_block(1, H256::ZERO, hash(0))); + // Slot 2 builds on slot 1's empty branch. + extend_chain(&mut store, gloas_block(2, root_1, hash(0))); + let envelope = reveal(&mut store, 1, root_1, hash(1)); + + assert!(served(&store, 1, 1).is_empty()); + assert_eq!(drain(envelopes_by_root(&store, &[root_1])), vec![envelope]); + } + + /// A root named over and over is answered once, so one stored envelope + /// cannot fill a whole answer. + #[test] + fn by_root_answers_a_repeated_root_once() { + let (store, envelopes) = chain_with_every_payload_built_on(); + let roots: Vec = envelopes + .iter() + .map(|e| e.message.beacon_block_root) + .collect(); + let repeated = vec![roots[1]; MAX_REQUEST_PAYLOADS as usize]; + assert_eq!(drain(envelopes_by_root(&store, &repeated)), envelopes[1..2]); + + // Each at its first place, whatever comes between. + let asked = [roots[2], roots[0], roots[2], roots[1], roots[0]]; + let once = vec![ + envelopes[2].clone(), + envelopes[0].clone(), + envelopes[1].clone(), + ]; + assert_eq!(drain(envelopes_by_root(&store, &asked)), once); + } + + /// The by-root answer stops once its budget has gone out, in the order + /// asked, and always carries the first envelope it has: "Clients MUST + /// respond with at least one payload envelope, if they have it." + #[test] + fn by_root_stops_once_the_byte_budget_is_spent() { + let mut store = beacon_store(); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, 1, 5); + let size = envelopes[0].to_ssz().len(); + // Newest first, with a root this node has nothing for in the lead. + let mut asked = vec![H256::repeat_byte(0xee)]; + asked.extend(envelopes.iter().rev().map(|e| e.message.beacon_block_root)); + let newest_first: Vec<_> = envelopes.iter().rev().cloned().collect(); + let within = |budget| drain(envelopes_by_root_within(&store, &asked, budget)); + + assert_eq!(within(2 * size), newest_first[..2]); + assert_eq!(within(2 * size + 1), newest_first[..3]); + // The unknown root costs nothing, and the first held one is sent + // however small the budget. + assert_eq!(within(1), newest_first[..1]); + assert_eq!(within(5 * size), newest_first); + assert_eq!(drain(envelopes_by_root(&store, &asked)), newest_first); + } + + /// The by-root answer goes through the codec's `write_response` and + /// reads back as the envelopes themselves, in the order asked. + #[tokio::test] + async fn a_by_root_answer_reads_back_as_its_envelopes() { + let base = Config::mainnet(); + let config = Config { + gloas_fork_epoch: base.fulu_fork_epoch + 64, + ..base + }; + let first_slot = config.gloas_fork_epoch * preset::slots_per_epoch(); + let mut store = beacon_store_on(Arc::new(InMemoryBackend::new()), first_slot); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, first_slot + 1, 3); + let asked: Vec = envelopes + .iter() + .rev() + .map(|e| e.message.beacon_block_root) + .collect(); + let newest_first: Vec<_> = envelopes.iter().rev().cloned().collect(); + let protocol = StreamProtocol::new(EXECUTION_PAYLOAD_ENVELOPES_BY_ROOT_V1); + let codec = || { + Codec::beacon(BeaconContext { + config: config.clone(), + genesis_validators_root: H256::repeat_byte(0x4b), + }) + }; + + let answer = envelopes_by_root(&store, &asked); + let response = Response::success(ResponsePayload::ExecutionPayloadEnvelopesByRoot(answer)); + let mut wire = Cursor::new(Vec::new()); + codec() + .write_response(&protocol, &mut wire, response) + .await + .expect("writes"); + + let read = codec() + .read_response(&protocol, &mut Cursor::new(wire.into_inner())) + .await + .expect("reads"); + match read { + Response::Success { + payload: ResponsePayload::ExecutionPayloadEnvelopes(read), + } => assert_eq!(read, newest_first), + other => panic!("read as {other}"), + } } } diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index 6e0db55cb..b44f07f2d 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -365,12 +365,13 @@ pub async fn handle_req_resp_message( } } } - // Unreachable by construction: this is the shape of an - // answer this node writes, and the codec reads a + // Unreachable by construction: these are the shapes of + // the answers this node writes, and the codec reads a // peer's envelopes as `ExecutionPayloadEnvelopes`. The // request is retired all the same, for the reason // `retire_unanswered` gives. - ResponsePayload::ExecutionPayloadEnvelopesByRange(_) => { + ResponsePayload::ExecutionPayloadEnvelopesByRange(_) + | ResponsePayload::ExecutionPayloadEnvelopesByRoot(_) => { error!( %peer, ?request_id, diff --git a/crates/net/p2p/src/req_resp/messages.rs b/crates/net/p2p/src/req_resp/messages.rs index 818ffc1aa..f6ffb9b92 100644 --- a/crates/net/p2p/src/req_resp/messages.rs +++ b/crates/net/p2p/src/req_resp/messages.rs @@ -6,7 +6,7 @@ use ethlambda_types::beacon::containers::gloas::SignedExecutionPayloadEnvelope; use ethlambda_types::beacon::primitives::Root; use libssz_types::SszList; -use super::envelopes::EnvelopesByRange; +use super::envelopes::{EnvelopesByRange, EnvelopesByRoot}; use crate::beacon::messages::{ BeaconMetaData, BeaconStatus, DataColumnsByRangeRequest, ExecutionPayloadEnvelopesByRangeRequest, Goodbye, Ping, @@ -212,6 +212,13 @@ impl std::fmt::Display for Response { "Success(ExecutionPayloadEnvelopesByRange remaining={})", answer.remaining() ), + Self::Success { + payload: ResponsePayload::ExecutionPayloadEnvelopesByRoot(answer), + } => write!( + f, + "Success(ExecutionPayloadEnvelopesByRoot remaining={})", + answer.remaining() + ), Self::Error { code, message } => { let message = String::from_utf8_lossy(message); write!(f, "Error({code:?}: {message})") @@ -298,9 +305,9 @@ pub enum ResponsePayload { /// protocols: which one produced the answer is known from the outbound /// request id, and the chunk framing is the same either way. DataColumnSidecars(Vec), - /// The envelopes of an answer read off the wire, from either gloas - /// envelope protocol, and this node's own answer to - /// `ExecutionPayloadEnvelopesByRoot`. + /// The envelopes answering either gloas envelope protocol, as a peer's + /// answer reads off the wire. This node's own answers are the two + /// variants below, which never hold the envelopes at once. ExecutionPayloadEnvelopes(Vec), /// This node's own answer to `ExecutionPayloadEnvelopesByRange`, still in /// the store: the codec reads each envelope as it writes it, and stops at @@ -310,6 +317,10 @@ pub enum ResponsePayload { /// [`Self::ExecutionPayloadEnvelopes`], so this never arrives as a /// response. ExecutionPayloadEnvelopesByRange(EnvelopesByRange), + /// This node's own answer to `ExecutionPayloadEnvelopesByRoot`, still in + /// the store and write-only, like + /// [`Self::ExecutionPayloadEnvelopesByRange`]. + ExecutionPayloadEnvelopesByRoot(EnvelopesByRoot), } /// Error message type for non-success responses. diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 536e474b1..5c421294f 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -34,6 +34,7 @@ pub use target_balance_cache::{TargetBalanceCache, TargetBalances}; // is unaffected by which module owns it. pub use state_writer::CacheKey; pub use store::{ - CanonicalEnvelopes, Chain, CustodyRecord, DB_VERSION, ForkCheckpoints, GetForkchoiceStoreError, - HeadVoteWindow, MAX_RESUMABLE_DB_STATE_AGE, NEW_PAYLOAD_CAP, Store, StoredEnvelope, + CanonicalEnvelopes, Chain, CustodyRecord, DB_VERSION, EnvelopesOfBlocks, ForkCheckpoints, + GetForkchoiceStoreError, HeadVoteWindow, MAX_RESUMABLE_DB_STATE_AGE, NEW_PAYLOAD_CAP, Store, + StoredEnvelope, }; diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 68eb6ad0f..37a0e7f5f 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1336,6 +1336,68 @@ impl Iterator for CanonicalEnvelopes { } None } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.remaining())) + } +} + +/// The stored envelopes of a list of blocks, in the order the blocks were +/// named, read from the store one at a time. +/// +/// What [`Store::execution_payload_envelopes_of`] returns, and +/// [`CanonicalEnvelopes`]' counterpart for a request that names its blocks: +/// there is no chain rule to apply, so a row is not even decoded. The same +/// holds otherwise: one row is read per [`Iterator::next`], a block with no +/// envelope is passed over, and a row that fails to read comes out as an +/// `Err` rather than a panic. +#[derive(Clone)] +pub struct EnvelopesOfBlocks { + backend: Arc, + /// Each block's slot and root: its row's key. + blocks: VecDeque<(u64, H256)>, +} + +impl EnvelopesOfBlocks { + /// How many blocks are still to be looked at: the most this can still + /// yield. + pub fn remaining(&self) -> usize { + self.blocks.len() + } + + fn read(&self, slot: u64, root: &H256) -> Result, Error> { + let view = self.backend.begin_read()?; + let key = encode_slot_root_key(slot, root); + let row = view.get(Table::ExecutionPayloadEnvelopes, &key)?; + Ok(row.map(|ssz| StoredEnvelope { slot, ssz })) + } +} + +impl Iterator for EnvelopesOfBlocks { + type Item = Result; + + fn next(&mut self) -> Option { + while let Some((slot, root)) = self.blocks.pop_front() { + match self.read(slot, &root) { + Ok(Some(envelope)) => return Some(Ok(envelope)), + Ok(None) => continue, + Err(err) => return Some(Err(err)), + } + } + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.remaining())) + } +} + +impl std::fmt::Debug for EnvelopesOfBlocks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EnvelopesOfBlocks") + .field("remaining", &self.remaining()) + .finish_non_exhaustive() + } } impl std::fmt::Debug for CanonicalEnvelopes { @@ -4521,6 +4583,36 @@ impl Store { })) } + /// Gloas: the stored envelopes of the blocks `roots` names, in that order. + /// + /// Serves `ExecutionPayloadEnvelopesByRoot`. Like + /// [`Self::canonical_execution_payload_envelopes`] this plans the answer + /// and does not touch `Table::ExecutionPayloadEnvelopes`: it resolves + /// each root to its block's slot, which is half of the row's key, and + /// leaves out the roots this node holds no block for. The envelopes come + /// out of the returned [`EnvelopesOfBlocks`], one row per step. A root + /// named twice is planned twice; a caller that wants each envelope once + /// passes each root once. + pub fn execution_payload_envelopes_of( + &self, + roots: impl IntoIterator, + ) -> EnvelopesOfBlocks { + if self.chain != Chain::Beacon { + Self::lean_only("execution_payload_envelopes_of"); + } + let view = self.backend.begin_read().expect("read view"); + let blocks = roots + .into_iter() + .filter_map(|root| { + block_slot_in(view.as_ref(), Chain::Beacon, &root).map(|slot| (slot, root)) + }) + .collect(); + EnvelopesOfBlocks { + backend: self.backend.clone(), + blocks, + } + } + /// The first slot of the gloas fork, `u64::MAX` when the configuration /// does not schedule it. fn first_gloas_slot(&self) -> u64 { @@ -10083,6 +10175,69 @@ mod tests { assert_eq!(envelope_reads(), reads_before + 3); } + /// Planning a by-root answer resolves slots and reads no envelope; each + /// step then reads one row, in the order the roots were named, and roots + /// with no block or no envelope are passed over. + #[test] + fn envelopes_of_named_blocks_are_read_one_per_step_in_the_order_named() { + let counts = Arc::new(ReadCounts::default()); + let backend = Arc::new(CountingBackend { + inner: InMemoryBackend::new(), + counts: counts.clone(), + }); + let envelope_reads = || counts.gets(Table::ExecutionPayloadEnvelopes); + let mut store = Store::init_beacon( + backend, + 0, + Config::mainnet(), + H256::ZERO, + Store::beacon_checkpoint_as_stored(BeaconCheckpoint::default()), + 0, + ); + store + .insert_signed_block(H256::ZERO, gloas_test_block(0, H256::ZERO)) + .expect("insert anchor"); + let mut parent = H256::ZERO; + let mut roots = Vec::new(); + for slot in 1..=3 { + let block = gloas_test_block(slot, parent); + parent = block.message_hash_tree_root(); + store.insert_signed_block(parent, block).expect("insert"); + roots.push(parent); + } + // Slots 1 and 3 have an envelope; slot 2's block has none. + store.insert_verified_payload(1, &test_envelope(roots[0])); + store.insert_verified_payload(3, &test_envelope(roots[2])); + let unknown = H256::repeat_byte(0xee); + + let reads_before = envelope_reads(); + let probes_before = counts.contains(Table::ExecutionPayloadEnvelopes); + let asked = [roots[2], unknown, roots[1], roots[0]]; + let mut envelopes = store.execution_payload_envelopes_of(asked); + // The unknown root has no block, so it is not planned at all. + assert_eq!(envelopes.remaining(), 3); + assert_eq!(envelope_reads(), reads_before); + assert_eq!( + counts.contains(Table::ExecutionPayloadEnvelopes), + probes_before + ); + + let first = envelopes.next().expect("slot 3").expect("reads"); + assert_eq!( + (first.slot, &first.ssz), + (3, &test_envelope(roots[2]).to_ssz()) + ); + assert_eq!(envelope_reads(), reads_before + 1); + + // Slot 2's missing row is passed over on the way to slot 1's. + let second = envelopes.next().expect("slot 1").expect("reads"); + assert_eq!( + (second.slot, &second.ssz), + (1, &test_envelope(roots[0]).to_ssz()) + ); + assert!(envelopes.next().is_none()); + } + /// The head's row is checked like any other before it is sent: its /// payload is compared with no successor's bid, but a requester that /// cannot decode it would drop the whole answer. diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 045e6d238..e05ce7de5 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -775,7 +775,7 @@ not the digest its slot implies, ends the stream. | Protocol | Served from | | --- | --- | -| `execution_payload_envelopes_by_root/1` | a point lookup per root in `Table::ExecutionPayloadEnvelopes`; unknown roots are left out, answers follow the order asked | +| `execution_payload_envelopes_by_root/1` | a point lookup per root in `Table::ExecutionPayloadEnvelopes`; unknown roots are left out, a repeated root is answered once, answers follow the order asked | | `execution_payload_envelopes_by_range/1` | the canonical blocks of the window (`BlockRoots`), each envelope kept only when the next canonical block builds on its payload; the head's own envelope only when the head node is FULL (`Store::head_payload_status`, which pairs the status with the head root it describes, so a stale status reads as unknown and the envelope is withheld) | Both are bounded by `MAX_REQUEST_PAYLOADS`: a by-root list over it fails to @@ -815,8 +815,28 @@ Planning a block decodes the block after it for its bid, and before gloas that block carries a whole execution payload, so a window down there would have the P2P actor decode megabytes a slot to answer nothing, outside the byte budget. A window that ends before gloas, and any window on a chain that does not -schedule gloas, reads nothing. The by-root answer is -still collected before it is sent. +schedule gloas, reads nothing. + +The by-root answer is read the same way (`EnvelopesByRoot`, +`Store::execution_payload_envelopes_of`): the handler resolves each root to its +block's slot and the codec reads each row as it writes it, under +`ENVELOPES_BY_ROOT_BYTE_BUDGET`, which is the range's 16 MiB. A request may +name `MAX_REQUEST_PAYLOADS` roots, so by count alone its answer is as large as +a range's. The specification's "Clients MUST respond with at least one payload +envelope, if they have it" is kept by stopping only once the budget is spent. +A root named more than once is answered once, at its first place: one stored +envelope must not be able to fill a whole answer. This node's own by-root +requests name a single root, so they are never cut short. A by-root row goes +out as stored, without the decode a by-range row gets. + +Reading an answer is bounded the same way. A peer may send +`MAX_REQUEST_PAYLOADS` chunks of `MAX_PAYLOAD_SIZE` to either protocol, +whatever was asked, and the reader holds every decoded envelope until the +stream ends. So it stops reading once `ENVELOPE_RESPONSE_BYTE_BUDGET` (the same +16 MiB) of envelopes has come in, keeping the one that crosses the budget, and +returns what it read: under 26 MiB an answer. An answer cut there reads as a +short one, and a by-range requester asks again for the slots after its last +envelope, as it does when the server stopped at its own budget. The client asks in two situations. By root: the chain actor's `FetchRequest.needs_envelope` (a block whose child waits on its payload) starts