diff --git a/CLAUDE.md b/CLAUDE.md index 96a434dc4..501bc64f6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -449,11 +449,16 @@ 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. Client: by root + 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`). 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) + 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). 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 4f64825af..cbce0b35d 100644 --- a/crates/net/p2p/src/beacon/encoding.rs +++ b/crates/net/p2p/src/beacon/encoding.rs @@ -55,6 +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::messages::BlocksByRangeRequest; /// This chain's wire body for a slot window. Every field is shared, since this @@ -351,13 +352,40 @@ where .await } +/// Whether an SSZ payload of `size` bytes is one this node sends as a response +/// chunk: `MAX_PAYLOAD_SIZE` less a margin, the cut the block and sidecar +/// writers use too. +pub(crate) fn fits_one_chunk(size: usize) -> bool { + size <= MAX_PAYLOAD_SIZE - 1024 +} + +/// Write one envelope chunk: the result code, the `ForkDigest` of the epoch +/// `slot` is in, and the envelope's SSZ. +/// +/// The spec keys the context epoch off the block the envelope fulfills, so +/// `slot` is that block's. +async fn write_execution_payload_envelope_chunk( + io: &mut T, + label: &'static str, + config: &Config, + genesis_validators_root: Root, + slot: u64, + encoded: Vec, +) -> io::Result<()> +where + T: AsyncWrite + Unpin + Send, +{ + let epoch = slot / preset::slots_per_epoch(); + let digest = compute_fork_digest(config, genesis_validators_root, epoch); + write_success_chunk(io, label, &digest, encoded).await +} + /// Write an envelope response: one result code, one `ForkDigest` and one /// payload per envelope. /// -/// The counterpart of [`write_blocks_response`]. The spec keys the context -/// epoch off the block the envelope fulfills; an envelope carries no slot of -/// its own, but `verify_execution_payload_envelope` pins -/// `payload.slot_number` to that block's slot, so a stored envelope's +/// The counterpart of [`write_blocks_response`]. An envelope carries no slot +/// of its own for the context epoch, but `verify_execution_payload_envelope` +/// pins `payload.slot_number` to its block's slot, so a stored envelope's /// `slot_number` is the block's slot. pub async fn write_execution_payload_envelopes_response( io: &mut T, @@ -372,7 +400,7 @@ where for envelope in envelopes { let encoded = envelope.to_ssz(); let slot = envelope.message.payload.slot_number; - if encoded.len() > MAX_PAYLOAD_SIZE - 1024 { + if !fits_one_chunk(encoded.len()) { warn!( slot, size = encoded.len(), @@ -380,12 +408,47 @@ where ); continue; } - let digest = compute_fork_digest( + write_execution_payload_envelope_chunk( + io, + label, config, genesis_validators_root, - slot / preset::slots_per_epoch(), - ); - write_success_chunk(io, label, &digest, encoded).await?; + slot, + encoded, + ) + .await?; + } + Ok(()) +} + +/// Write this node's own `ExecutionPayloadEnvelopesByRange` answer, 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 +/// rows go out as stored, with no decode and re-encode in between. +pub async fn write_envelopes_by_range_response( + io: &mut T, + label: &'static str, + config: &Config, + genesis_validators_root: Root, + answer: &mut EnvelopesByRange, +) -> io::Result<()> +where + T: AsyncWrite + Unpin + Send, +{ + while let Some(envelope) = answer.next_envelope() { + write_execution_payload_envelope_chunk( + io, + label, + config, + genesis_validators_root, + envelope.slot, + envelope.ssz, + ) + .await?; } Ok(()) } diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index b72b0003b..9a050419e 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -525,14 +525,22 @@ pub(crate) enum PendingRequestKind { /// asked for the slots a `BeaconBlocksByRange` answer just delivered. /// /// Like [`Self::ColumnRange`] it carries no per-root bookkeeping: a short - /// or empty answer is not a failure to retry, since the chain actor asks - /// again by root for every parent still missing its envelope. + /// or empty answer is not a failure to retry. An answer that stops short + /// of `end_slot` is followed by another of these for the slots after its + /// last envelope, and the chain actor asks by root for every parent + /// still missing its envelope after that. EnvelopeRange { start_slot: u64, end_slot: u64, /// The range session that asked, whose gate the answer (or its - /// failure) releases; see [`RangeSyncState::id`]. + /// failure) releases; see [`RangeSyncState::id`]. `None` when no + /// session waits on the answer: there was none, or it ran out of + /// range with this request still out + /// (`release_envelope_requests_of`). session: Option, + /// Until when a short answer is still followed by a request for the + /// rest of the span; see `ENVELOPE_FOLLOW_UP_WINDOW`. + follow_ups_until: Instant, }, } @@ -2138,7 +2146,11 @@ pub(crate) trait P2PProtocol: Send + Sync { #[allow(dead_code)] // invoked via send_after, not called directly fn retry_envelope_fetch(&self, block_root: H256) -> Result<(), ActorError>; #[allow(dead_code)] // invoked via send_after, not called directly - fn resume_range_after_envelopes(&self, session: u64) -> Result<(), ActorError>; + fn resume_range_after_envelopes( + &self, + session: Option, + rest: Option, + ) -> Result<(), ActorError>; #[allow(dead_code)] // invoked via send_after, not called directly fn retry_peer_redial(&self, peer_id: PeerId) -> Result<(), ActorError>; #[allow(dead_code)] // invoked via send_after, not called directly @@ -2199,17 +2211,19 @@ impl P2PServer { } } - /// A range answer's envelopes are checked and forwarded. The check runs - /// on its own task, so the session that asked for them may have ended - /// meanwhile (`end_range_session`), and a later one may be waiting on - /// envelopes of its own, which this must not release. + /// A range answer's envelopes are checked and forwarded: ask for the + /// slots the answer stopped short of, or let range sync go on. The check + /// runs on its own task, so the session that asked for them may have + /// ended meanwhile (`end_range_session`), and a later one may be waiting + /// on envelopes of its own, which this must neither release nor ask on + /// behalf of. #[send_handler] async fn handle_resume_range_after_envelopes( &mut self, msg: p2p_protocol::ResumeRangeAfterEnvelopes, ctx: &Context, ) { - req_resp::handlers::release_envelope_gate(self, ctx, Some(msg.session)).await; + req_resp::resume_range_after_envelopes(self, ctx, msg.session, msg.rest).await; } #[send_handler] diff --git a/crates/net/p2p/src/req_resp/codec.rs b/crates/net/p2p/src/req_resp/codec.rs index 9d110e8ec..144fca25c 100644 --- a/crates/net/p2p/src/req_resp/codec.rs +++ b/crates/net/p2p/src/req_resp/codec.rs @@ -383,7 +383,9 @@ impl libp2p::request_response::Codec for Codec { { let label = protocol_label(protocol.as_ref()); match resp { - Response::Success { payload } => match &payload { + // By `&mut`: the by-range envelope answer is consumed as it is + // 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)) .await @@ -440,6 +442,17 @@ impl libp2p::request_response::Codec for Codec { ) .await } + ResponsePayload::ExecutionPayloadEnvelopesByRange(answer) => { + let context = self.beacon_context(protocol.as_ref())?; + beacon_encoding::write_envelopes_by_range_response( + io, + label, + &context.config, + context.genesis_validators_root, + answer, + ) + .await + } }, Response::Error { code, message } => { // Send error code diff --git a/crates/net/p2p/src/req_resp/envelope_client.rs b/crates/net/p2p/src/req_resp/envelope_client.rs index 41b6f955a..abcd12a3e 100644 --- a/crates/net/p2p/src/req_resp/envelope_client.rs +++ b/crates/net/p2p/src/req_resp/envelope_client.rs @@ -108,6 +108,145 @@ pub(crate) fn take_envelope_gate(server: &mut P2PServer, session: Option) - } } +/// How long after a batch's envelopes were first asked for a short answer is +/// still followed by a request for the rest of the span. +/// +/// The follow-ups hold range sync's next batch back, and what counts as +/// progress is an envelope in the span, before any check of it. Unbounded, a +/// peer answering one envelope per request, each just inside the request +/// timeout, would hold a 128-slot batch for as long as the chain takes to +/// produce one, and range sync would never catch up. Bounded by this, the +/// worst a peer can do is a batch a minute, many times the chain's pace. +/// A server that answers promptly gets through a span of ordinary payloads in +/// a fraction of it, and what is not fetched by then is asked for by root. +/// The same patience a batch held for custody gets +/// (`RANGE_BATCH_CUSTODY_WAIT`). +pub(crate) const ENVELOPE_FOLLOW_UP_WINDOW: Duration = Duration::from_secs(30); + +/// The span one `ExecutionPayloadEnvelopesByRange` request asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct EnvelopeSpan { + pub(crate) start_slot: u64, + pub(crate) end_slot: u64, + /// Until when a short answer is followed up; see + /// [`ENVELOPE_FOLLOW_UP_WINDOW`]. Set by the batch's first request and + /// carried unchanged by every follow-up. + pub(crate) follow_ups_until: Instant, +} + +/// The slots of a batch's envelope window that an answer stopped short of, and +/// the peer that gave it. +/// +/// A server may end its answer anywhere after the first envelope: the +/// specification's "Clients MAY limit the number of payload envelopes in the +/// response", which this node's own server uses to stop at a byte budget +/// ([`super::envelopes::ENVELOPES_BY_RANGE_BYTE_BUDGET`]). The answer is a +/// prefix of the window either way ("MUST be sent in consecutive order"), so +/// what it left out starts right after its last envelope. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct UnansweredEnvelopes { + pub(crate) peer: PeerId, + pub(crate) span: EnvelopeSpan, +} + +/// The part of `[.., end_slot]` a range answer did not reach, given the +/// envelopes it carried, in range and in slot order. +/// +/// `None` when the answer reached the end of the window, and when it carried +/// nothing: a peer with nothing for the window has nothing for its tail. +/// Whether the answer stopped at a limit or the remaining slots simply hold no +/// payload cannot be told apart from here, so both are asked about; the second +/// costs one request that comes back empty. +fn unanswered_tail(envelopes: &[SignedExecutionPayloadEnvelope], end_slot: u64) -> Option { + let last_slot = envelopes.last()?.message.payload.slot_number; + (last_slot < end_slot).then(|| last_slot + 1) +} + +/// Whether the rest of a span may be asked for on behalf of `session`, the +/// range session waiting on the span (`None` when none is). +/// +/// A session still waiting on these envelopes: yes. A span nothing waits on, +/// while no range session runs: yes. That is the ordinary end of a sync, +/// where the session's last batch exhausts it and its envelope request is +/// handed on ([`release_envelope_requests_of`]); those envelopes are the ones +/// nearest the head. Anything else is a span whose session is gone (ended +/// for cause, by `end_range_session`, or replaced) or one meeting a session +/// that is not its own, and neither is asked for again: the blocks of the +/// first were given up on, and the second has its own gate and pacing. +fn may_follow_up(server: &P2PServer, session: Option) -> bool { + match (&server.range_sync_state, session) { + (Some(state), Some(session)) => state.id == session && state.envelopes_pending, + (None, None) => true, + (Some(_), None) | (None, Some(_)) => false, + } +} + +/// A range session ran out of range with its last batch's envelopes still +/// being asked for: nothing waits on that answer any more, so the request +/// stops naming the session. Its short answers are then followed up as +/// [`may_follow_up`] allows, where a request still naming a session that no +/// longer runs is one whose session was ended for cause. +pub(crate) fn release_envelope_requests_of(server: &mut P2PServer, ended: u64) { + for kind in server.outbound_requests.values_mut() { + if let PendingRequestKind::EnvelopeRange { session, .. } = kind + && *session == Some(ended) + { + *session = None; + } + } +} + +/// Ask for the envelopes a short range answer left out. Returns whether a +/// request went out; when a range session is waiting on the span, its +/// envelope gate then stays shut until that answer has been forwarded too. +/// +/// Only once the first answer has been checked and handed to the chain actor, +/// so that the actor sees a batch's envelopes in slot order across the +/// requests as well as within each. Every such request starts past the last +/// envelope received, so a batch takes at most one request per slot it spans, +/// however little each answer carries, and none goes out once the span's +/// [`ENVELOPE_FOLLOW_UP_WINDOW`] has passed. +async fn follow_up_envelope_range( + server: &mut P2PServer, + session: Option, + rest: UnansweredEnvelopes, +) -> bool { + let UnansweredEnvelopes { peer, span } = rest; + let EnvelopeSpan { + start_slot, + end_slot, + follow_ups_until, + } = span; + if Instant::now() >= follow_ups_until { + debug!(%peer, start_slot, end_slot, "Envelope range answers took too long, leaving the rest to the by-root path"); + return false; + } + if !may_follow_up(server, session) { + return false; + } + let count = end_slot.saturating_sub(start_slot).saturating_add(1); + debug!(%peer, start_slot, end_slot, "Envelope range answer stopped short, asking for the rest"); + send_envelopes_by_range_request(server, peer, start_slot, count, follow_ups_until).await +} + +/// A range answer's envelopes have been forwarded: ask for the slots it +/// stopped short of (`rest`), or let range sync go on when there are none or +/// they cannot be asked for. What is still missing after that is asked for by +/// root, once its block is a parent missing its payload. +pub(crate) async fn resume_range_after_envelopes( + server: &mut P2PServer, + ctx: &Context, + session: Option, + rest: Option, +) { + if let Some(rest) = rest + && follow_up_envelope_range(server, session, rest).await + { + return; + } + release_envelope_gate(server, ctx, session).await; +} + /// How many block roots [`PayloadVoteFetches`] remembers. A vote for a /// payload names a recent block, so a handful of slots' worth is plenty; a /// root evicted early is only asked for again. @@ -332,7 +471,9 @@ fn range_reaches_gloas(config: &Config, span: &std::ops::RangeInclusive) -> /// next batch's blocks do, and the next request is held back until the answer /// has been checked and forwarded: this sets /// `RangeSyncState::envelopes_pending`, and [`release_envelope_gate`] clears -/// it. An envelope the answer lacks is asked for by root once its block is a +/// it. An answer that stops short of the span is followed by a request for +/// the rest, with the gate still shut ([`resume_range_after_envelopes`]); an +/// envelope still missing after that is asked for by root once its block is a /// parent missing one. /// /// Returns whether a request went out, which is also whether range sync is now @@ -342,6 +483,20 @@ pub(crate) async fn request_beacon_envelopes_by_range( peer: PeerId, start_slot: u64, count: u64, +) -> bool { + let follow_ups_until = Instant::now() + ENVELOPE_FOLLOW_UP_WINDOW; + send_envelopes_by_range_request(server, peer, start_slot, count, follow_ups_until).await +} + +/// [`request_beacon_envelopes_by_range`] for a span whose follow-up deadline +/// is already running: the batch's first request starts it, and a follow-up +/// keeps the one it was given. +async fn send_envelopes_by_range_request( + server: &mut P2PServer, + peer: PeerId, + start_slot: u64, + count: u64, + follow_ups_until: Instant, ) -> bool { let Some(wire) = server.wire.beacon() else { return false; @@ -378,6 +533,7 @@ pub(crate) async fn request_beacon_envelopes_by_range( start_slot, end_slot, session, + follow_ups_until, }, ); if let Some(state) = &mut server.range_sync_state { @@ -408,19 +564,27 @@ fn retain_envelopes_in_range( /// Take delivery of an `ExecutionPayloadEnvelopesByRange` answer. /// -/// No retry, unlike the by-root path: a short or empty answer is not an -/// attempt spent, and the envelopes it lacks are asked for by root, since the -/// chain actor re-asks every slot for each parent still missing one. Range -/// sync is released once the answer has been forwarded, or at once when there -/// is nothing to forward. +/// No retry ladder, unlike the by-root path: a short or empty answer is not +/// an attempt spent. An answer that stops before the end of the span is a +/// server limiting its response, which this node's own does at a byte budget, +/// so once it has been forwarded the same peer is asked for the slots after +/// its last envelope ([`resume_range_after_envelopes`]), and range sync stays +/// held meanwhile. An empty answer, or one that reaches the end, releases +/// range sync; the envelopes still missing then are asked for by root, since +/// the chain actor re-asks every slot for each parent still missing one. pub(super) async fn handle_envelopes_by_range_response( server: &mut P2PServer, peer: PeerId, - (start_slot, end_slot): (u64, u64), + span: EnvelopeSpan, session: Option, envelopes: Vec, ctx: &Context, ) { + let EnvelopeSpan { + start_slot, + end_slot, + .. + } = span; let received = envelopes.len(); trace!(%peer, start_slot, end_slot, received, "Received ExecutionPayloadEnvelopesByRange response"); @@ -434,15 +598,20 @@ pub(super) async fn handle_envelopes_by_range_response( if dropped > 0 { debug!(%peer, start_slot, end_slot, dropped, "Dropping out-of-range envelopes"); } + let rest = unanswered_tail(&envelopes, end_slot).map(|start_slot| UnansweredEnvelopes { + peer, + span: EnvelopeSpan { start_slot, ..span }, + }); // The release names the session that asked: the check runs on its own - // task, and that session may have ended by the time it finishes. + // task, and that session may have ended by the time it finishes. With no + // session and nothing left to ask for there is nothing to resume. let resume = ctx.clone(); let done: envelope_checks::Done = Box::new(move || { - if let Some(session) = session { + if session.is_some() || rest.is_some() { send_after( Duration::ZERO, resume, - p2p_protocol::ResumeRangeAfterEnvelopes { session }, + p2p_protocol::ResumeRangeAfterEnvelopes { session, rest }, ); } }); @@ -513,6 +682,196 @@ mod tests { assert_eq!(dropped, 2); } + /// What a range answer left out starts after its last envelope; an answer + /// that reached the end of the span, or carried nothing, left nothing to + /// ask this peer for. + #[test] + fn a_range_answer_that_stops_short_leaves_the_slots_after_its_last_envelope() { + let root = H256::repeat_byte(1); + let answer = |slots: &[u64]| -> Vec<_> { + slots.iter().map(|slot| envelope_for(*slot, root)).collect() + }; + + assert_eq!(unanswered_tail(&answer(&[10, 11, 12]), 20), Some(13)); + // The slots it skipped on the way are slots without a payload, not + // slots left out: only the tail is asked about. + assert_eq!(unanswered_tail(&answer(&[10, 15]), 20), Some(16)); + assert_eq!(unanswered_tail(&answer(&[19]), 20), Some(20)); + assert_eq!(unanswered_tail(&answer(&[10, 20]), 20), None); + assert_eq!(unanswered_tail(&[], 20), None); + } + + /// A beacon server on a chain that is gloas from genesis, with one + /// connected peer. + async fn gloas_server_with_a_peer() -> (P2PServer, PeerId) { + let config = Config::mainnet().with_fork_epoch(ForkName::Gloas, 0); + let mut server = crate::test_support::unconnected_beacon_server(config, 0).await; + let peer = PeerId::random(); + server + .connected_peers + .insert(peer, ConnectionDirection::Outbound); + (server, peer) + } + + /// The slots `start_slot..=63` of a span, still inside its follow-up + /// window. + fn rest_from(peer: PeerId, start_slot: u64) -> UnansweredEnvelopes { + UnansweredEnvelopes { + peer, + span: EnvelopeSpan { + start_slot, + end_slot: 63, + follow_ups_until: Instant::now() + ENVELOPE_FOLLOW_UP_WINDOW, + }, + } + } + + fn start_session(server: &mut P2PServer, peer: PeerId, range: std::ops::Range) -> u64 { + let peer_head = range.end - 1; + server.range_sync_state = Some(crate::RangeSyncState::new(range, peer, peer_head)); + server.range_sync_state.as_ref().unwrap().id + } + + /// The one envelope range request outstanding. + fn the_envelope_range_request(server: &P2PServer) -> (u64, u64, Option, Instant) { + let mut asked = server.outbound_requests.iter(); + let (id, kind) = asked.next().expect("a request went out"); + assert!(asked.next().is_none(), "one request, not several"); + assert_eq!( + id.protocol, + ReqRespProtocol::ExecutionPayloadEnvelopesByRange + ); + match kind { + PendingRequestKind::EnvelopeRange { + start_slot, + end_slot, + session, + follow_ups_until, + } => (*start_slot, *end_slot, *session, *follow_ups_until), + _ => panic!("not an envelope range request"), + } + } + + /// A short answer is followed by a request to the same peer for the rest + /// of the span, under the deadline the span already had, and the next + /// batch stays held back until that one is answered too. + #[tokio::test] + async fn a_short_range_answer_is_followed_by_a_request_for_the_rest() { + let (mut server, peer) = gloas_server_with_a_peer().await; + let session = start_session(&mut server, peer, 0..100_000); + + // The batch's own request, answered up to slot 40 of 0..=63. + assert!(request_beacon_envelopes_by_range(&mut server, peer, 0, 64).await); + let (_, _, _, deadline) = the_envelope_range_request(&server); + server.outbound_requests.clear(); + let rest = UnansweredEnvelopes { + peer, + span: EnvelopeSpan { + start_slot: 41, + end_slot: 63, + follow_ups_until: deadline, + }, + }; + + assert!(follow_up_envelope_range(&mut server, Some(session), rest).await); + + assert_eq!( + the_envelope_range_request(&server), + (41, 63, Some(session), deadline), + "the follow-up asks for the rest and does not restart the window" + ); + let state = server.range_sync_state.as_ref().unwrap(); + assert!(state.envelopes_pending); + assert!(state.next_batch().is_none()); + } + + /// Follow-ups hold the next batch back, so they stop when the span's + /// window is over, however much of the span is still unanswered. + #[tokio::test] + async fn a_span_is_not_followed_up_past_its_window() { + let (mut server, peer) = gloas_server_with_a_peer().await; + let session = start_session(&mut server, peer, 0..100_000); + assert!(request_beacon_envelopes_by_range(&mut server, peer, 0, 64).await); + server.outbound_requests.clear(); + let mut rest = rest_from(peer, 41); + rest.span.follow_ups_until = Instant::now(); + + assert!(!follow_up_envelope_range(&mut server, Some(session), rest).await); + + assert!(server.outbound_requests.is_empty()); + } + + /// A session's last batch exhausts it, so the session is gone before that + /// batch's envelope answer arrives. Its request is handed on, and the + /// rest of the span is still asked for, for as long as answers keep + /// stopping short. + #[tokio::test] + async fn the_last_batch_of_a_session_is_followed_up_after_the_session_ran_out() { + let (mut server, peer) = gloas_server_with_a_peer().await; + let session = start_session(&mut server, peer, 0..64); + assert!(request_beacon_envelopes_by_range(&mut server, peer, 0, 64).await); + assert_eq!(the_envelope_range_request(&server).2, Some(session)); + + // What `handle_beacon_blocks_by_range_response` does once the batch + // that exhausts the session is delivered. + server.range_sync_state = None; + release_envelope_requests_of(&mut server, session); + + // The request no longer names the session, so that is what its + // answer is handled under. + assert_eq!(the_envelope_range_request(&server).2, None); + server.outbound_requests.clear(); + assert!(follow_up_envelope_range(&mut server, None, rest_from(peer, 41)).await); + // That follow-up names no session either, and its own short answer + // is followed up the same way. + let (start_slot, end_slot, asked_by, _) = the_envelope_range_request(&server); + assert_eq!((start_slot, end_slot, asked_by), (41, 63, None)); + server.outbound_requests.clear(); + assert!(follow_up_envelope_range(&mut server, None, rest_from(peer, 50)).await); + assert_eq!(the_envelope_range_request(&server).0, 50); + } + + /// A session ended for cause (`end_range_session`: its peers gone, its + /// watermark expired) gave its blocks up, and an answer of its that was + /// already being checked asks for nothing more. + #[tokio::test] + async fn a_session_ended_for_cause_is_not_followed_up() { + let (mut server, peer) = gloas_server_with_a_peer().await; + let session = start_session(&mut server, peer, 0..100_000); + assert!(request_beacon_envelopes_by_range(&mut server, peer, 0, 64).await); + + server.end_range_session(); + + assert!(server.outbound_requests.is_empty()); + assert!(!follow_up_envelope_range(&mut server, Some(session), rest_from(peer, 41)).await); + assert!(server.outbound_requests.is_empty()); + } + + /// The rest of a span is never asked for across another session: not for + /// a session that ended once a later one runs, not for a span nothing + /// waits on, and not once the asking session's own gate is open. + #[tokio::test] + async fn the_rest_of_a_span_is_not_asked_for_across_another_session() { + let (mut server, peer) = gloas_server_with_a_peer().await; + let rest = rest_from(peer, 41); + + // A session that ended, with a later one waiting on its own envelopes. + let ended = start_session(&mut server, peer, 0..100_000); + let running = start_session(&mut server, peer, 0..100_000); + assert_ne!(ended, running); + server.range_sync_state.as_mut().unwrap().envelopes_pending = true; + assert!(!follow_up_envelope_range(&mut server, Some(ended), rest).await); + // Nor for a span nothing waits on. + assert!(!follow_up_envelope_range(&mut server, None, rest).await); + + // The running session, once its gate is open. + server.range_sync_state.as_mut().unwrap().envelopes_pending = false; + assert!(!follow_up_envelope_range(&mut server, Some(running), rest).await); + assert!(server.outbound_requests.is_empty()); + // The later session's gate was never touched. + assert!(!server.range_sync_state.as_ref().unwrap().envelopes_pending); + } + #[test] fn only_a_span_reaching_gloas_asks_for_envelopes() { let config = Config::mainnet().with_fork_epoch(ForkName::Gloas, 10); diff --git a/crates/net/p2p/src/req_resp/envelopes.rs b/crates/net/p2p/src/req_resp/envelopes.rs index c7f2249c9..a5694ff69 100644 --- a/crates/net/p2p/src/req_resp/envelopes.rs +++ b/crates/net/p2p/src/req_resp/envelopes.rs @@ -2,20 +2,119 @@ //! (`execution_payload_envelopes_by_range/1` and `_by_root/1`): the server side, //! answering peers out of `Table::ExecutionPayloadEnvelopes`. -use ethlambda_storage::Store; +use ethlambda_storage::{CanonicalEnvelopes, Store, StoredEnvelope}; use ethlambda_types::beacon::containers::gloas; use ethlambda_types::primitives::H256; use libp2p::PeerId; use libp2p::request_response::ResponseChannel; use tracing::{debug, error, trace, warn}; +use super::encoding::MAX_PAYLOAD_SIZE; use super::handlers::{beacon_block_store_or_refuse, refuse, respond}; use super::messages::ResponseCode; use super::{Response, ResponsePayload}; use crate::P2PServer; +use crate::beacon::encoding::fits_one_chunk; use crate::beacon::messages::ExecutionPayloadEnvelopesByRangeRequest; use crate::beacon::protocols::MAX_REQUEST_PAYLOADS; +/// How many bytes of envelopes one `ExecutionPayloadEnvelopesByRange` answer +/// sends before it stops, counted as SSZ, before compression. +/// +/// `MAX_REQUEST_PAYLOADS` bounds an answer by count alone, and an execution +/// block may be 8 MiB of RLP (EIP-7934), so a full window can be over a +/// gigabyte. The requester's whole exchange has the request-response layer's +/// timeout to finish in (ten seconds, libp2p's default, which this node does +/// not change), and an answer that does not make it is lost entire, so +/// sending less per answer and being asked again costs a round trip where +/// sending too much costs the answer. "Clients MAY limit the number of +/// payload envelopes in the response." +/// +/// The answer stops once this much has gone out, so it overshoots by less +/// than one envelope and always carries the first one, which the +/// specification requires ("Clients MUST respond with at least the first +/// [...] that exists in the range"). The most one answer can send is +/// therefore below `ENVELOPES_BY_RANGE_BYTE_BUDGET + MAX_PAYLOAD_SIZE`. +pub(crate) const ENVELOPES_BY_RANGE_BYTE_BUDGET: usize = 16 * 1024 * 1024; + +// The largest envelope a chunk can carry leaves budget for another, so an +// 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. +/// +/// The handler decides which envelopes answer the request; the codec then +/// takes them out one at a time as it writes each chunk +/// ([`Self::next_envelope`]). So the answer is never in memory as a whole, +/// 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. +#[derive(Debug, Clone)] +pub struct EnvelopesByRange { + envelopes: CanonicalEnvelopes, + /// The bytes still to send before the answer stops; zero once it has. + budget: usize, +} + +impl EnvelopesByRange { + fn new(envelopes: CanonicalEnvelopes, budget: usize) -> Self { + Self { envelopes, budget } + } + + /// How many envelopes the answer may still carry: the blocks left to + /// read, or none once the byte budget is spent. + pub(crate) fn remaining(&self) -> usize { + if self.budget == 0 { + 0 + } else { + self.envelopes.remaining() + } + } + + /// 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. + /// + /// 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 + /// sent and asks again for the rest, where an aborted stream would cost + /// it all of them. + pub(crate) fn next_envelope(&mut self) -> Option { + if self.budget == 0 { + return None; + } + loop { + let envelope = match self.envelopes.next()? { + Ok(envelope) => envelope, + Err(err) => { + error!(%err, "Stored execution payload envelope failed to read; ending the answer"); + self.budget = 0; + return None; + } + }; + let size = envelope.ssz.len(); + if !fits_one_chunk(size) { + warn!( + slot = envelope.slot, + size, "Skipping oversized execution payload envelope in response" + ); + continue; + } + self.budget = self.budget.saturating_sub(size); + if self.budget == 0 { + debug!( + last_slot = envelope.slot, + left = self.envelopes.remaining(), + "ExecutionPayloadEnvelopesByRange answer stopped at its byte budget" + ); + } + return Some(envelope); + } + } +} + /// Answer `execution_payload_envelopes_by_range/1` off the canonical chain. /// /// The spec makes it equivalent to `BeaconBlocksByRange` v2 with another @@ -25,8 +124,13 @@ use crate::beacon::protocols::MAX_REQUEST_PAYLOADS; /// specification's "Clients MAY limit the number of payload envelopes in the /// response" allows; the block handler refuses a `count` past its phase0 /// ceiling instead, because a request that wide is a protocol violation there. -/// A window before gloas simply holds no envelopes, so it is an empty answer. Which envelopes count as -/// canonical is [`Store::canonical_execution_payload_envelopes`]'s business. +/// The same sentence is what lets the answer stop at +/// [`ENVELOPES_BY_RANGE_BYTE_BUDGET`]. A window before gloas simply holds no +/// envelopes, so it is an empty answer. Which envelopes count as canonical is +/// [`Store::canonical_execution_payload_envelopes`]'s business. +/// +/// No envelope is read here: the answer handed to the codec is a plan, and +/// the codec reads each envelope as it writes it ([`EnvelopesByRange`]). pub(super) async fn handle_execution_payload_envelopes_by_range_request( server: &mut P2PServer, peer: PeerId, @@ -37,24 +141,17 @@ pub(super) async fn handle_execution_payload_envelopes_by_range_request( return; }; - if request.count == 0 { - refuse( - server, - channel, - ResponseCode::INVALID_REQUEST, - "invalid ExecutionPayloadEnvelopesByRange request", - ); - return; - } - let envelopes = match envelopes_by_range(&server.store, request.start_slot, request.count) { - Ok(envelopes) => envelopes, - Err(reason) => { + let answer = match envelopes_by_range(&server.store, request.start_slot, request.count) { + Ok(answer) => answer, + Err(refusal) => { debug!( %peer, start_slot = request.start_slot, - "ExecutionPayloadEnvelopesByRange request starts before this node's chain" + count = request.count, + reason = refusal.reason(), + "Refusing an ExecutionPayloadEnvelopesByRange request" ); - refuse(server, channel, ResponseCode::RESOURCE_UNAVAILABLE, reason); + refuse(server, channel, refusal.code(), refusal.reason()); return; } }; @@ -63,51 +160,75 @@ pub(super) async fn handle_execution_payload_envelopes_by_range_request( %peer, start_slot = request.start_slot, count = request.count, - found = envelopes.len(), + planned = answer.remaining(), "Responding to ExecutionPayloadEnvelopesByRange request" ); respond( server, channel, - ResponsePayload::ExecutionPayloadEnvelopes(envelopes), + ResponsePayload::ExecutionPayloadEnvelopesByRange(answer), ); } -/// The envelopes `ExecutionPayloadEnvelopesByRange` answers a non-empty window -/// with: the canonical ones in `[start_slot, start_slot + count)`, truncated -/// to `MAX_REQUEST_PAYLOADS` slots. -/// -/// `Err` carries the `RESOURCE_UNAVAILABLE` reason for a `start_slot` below -/// the store's anchor, which this chain does not reach back to. +/// Why an `ExecutionPayloadEnvelopesByRange` request gets an error rather +/// than an answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RangeRefusal { + /// A `count` of zero asks for nothing. + EmptyWindow, + /// The `start_slot` is below the store's anchor, which this chain does + /// not reach back to. + BeforeAnchor, +} + +impl RangeRefusal { + fn code(self) -> ResponseCode { + match self { + Self::EmptyWindow => ResponseCode::INVALID_REQUEST, + Self::BeforeAnchor => ResponseCode::RESOURCE_UNAVAILABLE, + } + } + + fn reason(self) -> &'static str { + match self { + Self::EmptyWindow => "invalid ExecutionPayloadEnvelopesByRange request", + Self::BeforeAnchor => { + "requested range starts before this node's earliest available slot" + } + } + } +} + +/// The answer to `ExecutionPayloadEnvelopesByRange`: the canonical envelopes +/// in `[start_slot, start_slot + count)`, truncated to `MAX_REQUEST_PAYLOADS` +/// slots, and cut off once [`ENVELOPES_BY_RANGE_BYTE_BUDGET`] has been sent. fn envelopes_by_range( store: &Store, start_slot: u64, count: u64, -) -> Result, &'static str> { - if start_slot < store.anchor_slot() { - return Err("requested range starts before this node's earliest available slot"); - } - let count = count.min(MAX_REQUEST_PAYLOADS); - // An overflowing window is attacker-supplied and answered empty, as is a - // zero `count`, which has no last offset to add. - let Some(end_slot) = count - .checked_sub(1) - .and_then(|last_offset| start_slot.checked_add(last_offset)) - else { - return Ok(Vec::new()); +) -> Result { + envelopes_by_range_within(store, start_slot, count, ENVELOPES_BY_RANGE_BYTE_BUDGET) +} + +/// [`envelopes_by_range`] under a byte budget of the caller's choosing. +fn envelopes_by_range_within( + store: &Store, + start_slot: u64, + count: u64, + budget: usize, +) -> Result { + let Some(last_offset) = count.min(MAX_REQUEST_PAYLOADS).checked_sub(1) else { + return Err(RangeRefusal::EmptyWindow); }; - Ok(store - .canonical_execution_payload_envelopes(start_slot, end_slot) - .inspect_err(|err| { - warn!( - start_slot, - end_slot, - ?err, - "Failed to get execution payload envelopes by slot range" - ) - }) - .unwrap_or_default()) + if start_slot < store.anchor_slot() { + return Err(RangeRefusal::BeforeAnchor); + } + // A window running past the last slot is attacker-supplied. It is cut at + // 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)) } /// Answer `execution_payload_envelopes_by_root/1` with whichever of the named @@ -169,12 +290,20 @@ fn envelopes_by_root(store: &Store, roots: &[H256]) -> Vec Store { + beacon_store_on(Arc::new(InMemoryBackend::new()), 0) + } + + /// A store on `backend` whose anchor block, of root zero, is at + /// `anchor_slot`. + fn beacon_store_on(backend: Arc, anchor_slot: u64) -> Store { let mut store = Store::init_beacon( - Arc::new(InMemoryBackend::new()), + backend, 0, Config::mainnet(), H256::ZERO, Checkpoint::default(), - 0, + anchor_slot, ); + let anchor = gloas_block(anchor_slot, H256::ZERO, H256::ZERO); store - .insert_signed_block(H256::ZERO, gloas_block(0, H256::ZERO, H256::ZERO)) + .insert_signed_block(H256::ZERO, anchor) .expect("insert anchor"); store } + /// Every envelope `answer` sends, decoded, in the order sent. + fn drain(mut answer: EnvelopesByRange) -> Vec { + let mut sent = Vec::new(); + while let Some(stored) = answer.next_envelope() { + let envelope = gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(&stored.ssz) + .expect("a served envelope decodes"); + assert_eq!(stored.slot, envelope.message.payload.slot_number); + sent.push(envelope); + } + sent + } + + /// What `ExecutionPayloadEnvelopesByRange` sends for the window. + fn served( + store: &Store, + start_slot: u64, + count: u64, + ) -> Vec { + drain(envelopes_by_range(store, start_slot, count).expect("answered")) + } + + /// The same, under a byte budget of `budget`. + fn served_within( + store: &Store, + start_slot: u64, + count: u64, + budget: usize, + ) -> Vec { + drain(envelopes_by_range_within(store, start_slot, count, budget).expect("answered")) + } + + /// Canonical slots `first..first + total` above `parent`, every payload + /// revealed and built on by the next block. Returns the envelopes; the + /// head's is served because the head is FULL. + fn extend_with_full_slots( + store: &mut Store, + mut parent: H256, + first: u64, + total: u64, + ) -> Vec { + // A payload hash per slot, distinct from the anchor's zero. + let payload_hash = |slot: u64| { + let mut bytes = [0u8; 32]; + bytes[24..].copy_from_slice(&(slot + 1).to_be_bytes()); + H256::from_slice(&bytes) + }; + let mut envelopes = Vec::new(); + for slot in first..first + total { + let builds_on = if slot == first { + H256::ZERO + } else { + payload_hash(slot - 1) + }; + parent = extend_chain(store, gloas_block(slot, parent, builds_on)); + envelopes.push(reveal(store, slot, parent, payload_hash(slot))); + } + envelopes + } + /// Inserts `block` and moves the head to it; returns its root. fn extend_chain(store: &mut Store, block: SignedBeaconBlock) -> H256 { let root = block.message_hash_tree_root(); @@ -266,13 +461,8 @@ mod tests { fn by_range_serves_only_canonical_envelopes_in_slot_order() { let (store, envelopes) = chain_with_every_payload_built_on(); - let served = envelopes_by_range(&store, 1, 3).expect("in window"); - - assert_eq!(served, envelopes); - assert_eq!( - envelopes_by_range(&store, 2, 1).expect("in window"), - envelopes[1..2] - ); + assert_eq!(served(&store, 1, 3), envelopes); + assert_eq!(served(&store, 2, 1), envelopes[1..2]); } #[test] @@ -284,9 +474,7 @@ mod tests { reveal(&mut store, 1, root_1, hash(1)); let head_envelope = reveal(&mut store, 2, root_2, hash(2)); - let served = envelopes_by_range(&store, 1, 2).expect("in window"); - - assert_eq!(served, vec![head_envelope]); + assert_eq!(served(&store, 1, 2), vec![head_envelope]); } #[test] @@ -297,10 +485,7 @@ mod tests { extend_chain(&mut store, gloas_block(3, root_1, hash(1))); let envelope = reveal(&mut store, 1, root_1, hash(1)); - assert_eq!( - envelopes_by_range(&store, 1, 1).expect("in window"), - vec![envelope] - ); + assert_eq!(served(&store, 1, 1), vec![envelope]); } /// A phase0 block, standing in for any block before gloas. @@ -342,10 +527,10 @@ mod tests { reveal(&mut store, slot, parent, payload_hash(slot)); } - let served = envelopes_by_range(&store, 1, total).expect("in window"); + let capped = served(&store, 1, total); - assert_eq!(served.len() as u64, MAX_REQUEST_PAYLOADS); - let last_slot = served + assert_eq!(capped.len() as u64, MAX_REQUEST_PAYLOADS); + let last_slot = capped .last() .expect("non-empty") .message @@ -353,8 +538,7 @@ mod tests { .slot_number; assert_eq!(last_slot, MAX_REQUEST_PAYLOADS); // A count past the cap is cut to it, not refused. - let wide = envelopes_by_range(&store, 1, u64::MAX).expect("in window"); - assert_eq!(wide, served); + assert_eq!(served(&store, 1, u64::MAX), capped); } #[test] @@ -365,44 +549,222 @@ mod tests { let root_3 = extend_chain(&mut store, gloas_block(3, root_2, hash(0))); let envelope = reveal(&mut store, 3, root_3, hash(3)); - assert!( - envelopes_by_range(&store, 1, 2) - .expect("in window") - .is_empty() - ); - assert_eq!( - envelopes_by_range(&store, 1, 3).expect("in window"), - vec![envelope] - ); + assert!(served(&store, 1, 2).is_empty()); + assert_eq!(served(&store, 1, 3), vec![envelope]); } #[test] fn by_range_answers_empty_for_an_overflowing_window() { let (store, _) = chain_with_every_payload_built_on(); - assert!( - envelopes_by_range(&store, u64::MAX, 5) - .expect("in window") - .is_empty() - ); + assert!(served(&store, u64::MAX, 5).is_empty()); + assert!(served(&store, u64::MAX - 2, 5).is_empty()); } #[test] - fn by_range_refuses_a_start_below_the_anchor() { - let mut store = Store::init_beacon( - Arc::new(InMemoryBackend::new()), - 0, - Config::mainnet(), - H256::ZERO, - Checkpoint::default(), - 10, + fn by_range_refuses_a_start_below_the_anchor_and_an_empty_window() { + let store = beacon_store_on(Arc::new(InMemoryBackend::new()), 10); + + let refusal = |start_slot, count| envelopes_by_range(&store, start_slot, count).err(); + assert_eq!(refusal(9, 1), Some(RangeRefusal::BeforeAnchor)); + assert_eq!(refusal(10, 1), None); + // An empty window is refused wherever it starts. + assert_eq!(refusal(10, 0), Some(RangeRefusal::EmptyWindow)); + assert_eq!(refusal(9, 0), Some(RangeRefusal::EmptyWindow)); + assert_eq!( + RangeRefusal::BeforeAnchor.code(), + ResponseCode::RESOURCE_UNAVAILABLE ); - store - .insert_signed_block(H256::ZERO, gloas_block(10, H256::ZERO, H256::ZERO)) - .expect("insert anchor"); + assert_eq!( + RangeRefusal::EmptyWindow.code(), + ResponseCode::INVALID_REQUEST + ); + } + + /// The answer stops once the budget has gone out: it overshoots by less + /// than one envelope, and what it sends is a prefix of the window. + #[test] + fn by_range_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(); + assert!(envelopes.iter().all(|e| e.to_ssz().len() == size)); + + // Two envelopes spend a budget of exactly two. + assert_eq!(served_within(&store, 1, 5, 2 * size), envelopes[..2]); + // One byte short of that is still two; one byte over takes a third. + assert_eq!(served_within(&store, 1, 5, 2 * size - 1), envelopes[..2]); + assert_eq!(served_within(&store, 1, 5, 2 * size + 1), envelopes[..3]); + // A budget the window fits under changes nothing. + assert_eq!(served_within(&store, 1, 5, 5 * size), envelopes); + assert_eq!(served(&store, 1, 5), envelopes); + } + + /// "Clients MUST respond with at least the first [...] that exists in the + /// range": however small the budget, an answer is never cut to nothing. + #[test] + fn by_range_sends_the_first_envelope_whatever_the_budget() { + let mut store = beacon_store(); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, 1, 3); + + assert_eq!(served_within(&store, 1, 3, 1), envelopes[..1]); + // The first that exists, which need not be at the first slot asked. + assert_eq!(served_within(&store, 2, 2, 1), envelopes[1..2]); + } + + /// A requester that asks again from the slot after the last envelope it + /// got collects the whole window, whatever the budget cut each answer to. + #[test] + fn asking_again_after_each_short_answer_collects_the_window() { + let mut store = beacon_store(); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, 1, 7); + let size = envelopes[0].to_ssz().len(); + let end_slot = 7; + + let mut collected = Vec::new(); + let mut requests = 0; + let mut start_slot = 1; + while start_slot <= end_slot { + let answer = served_within(&store, start_slot, end_slot - start_slot + 1, 2 * size); + requests += 1; + let Some(last) = answer.last() else { + break; + }; + start_slot = last.message.payload.slot_number + 1; + collected.extend(answer); + } + + assert_eq!(collected, envelopes); + // Two per answer: three full answers and the last envelope alone. + assert_eq!(requests, 4); + } - assert!(envelopes_by_range(&store, 9, 1).is_err()); - assert!(envelopes_by_range(&store, 10, 1).is_ok()); + /// The answer is a plan until it is sent: an envelope is read when its + /// chunk is due, not when the request was answered. + #[test] + fn by_range_reads_each_envelope_as_it_is_sent() { + let mut store = beacon_store(); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, 1, 3); + let mut answer = envelopes_by_range(&store, 1, 3).expect("answered"); + assert_eq!(answer.remaining(), 3); + + let first = answer.next_envelope().expect("the first envelope"); + assert_eq!(first.ssz, envelopes[0].to_ssz()); + assert_eq!(answer.remaining(), 2); + + // Slot 2's row is rewritten after the request was answered and before + // its chunk is due. Same payload, so the chain still builds on it. + let mut rewritten = envelopes[1].clone(); + rewritten.message.builder_index = 7; + store.insert_verified_payload(2, &rewritten); + + let second = answer.next_envelope().expect("the second envelope"); + assert_eq!(second.ssz, rewritten.to_ssz()); + } + + fn envelope_key(slot: u64, root: &H256) -> Vec { + let mut key = slot.to_be_bytes().to_vec(); + key.extend_from_slice(&root.0); + key + } + + /// A row that does not read ends the answer where it is, without a panic + /// and without failing the stream: the peer keeps what it was sent. + #[test] + fn by_range_ends_the_answer_at_a_row_that_fails_to_read() { + let backend = Arc::new(InMemoryBackend::new()); + let mut store = beacon_store_on(backend.clone(), 0); + let envelopes = extend_with_full_slots(&mut store, H256::ZERO, 1, 3); + let corrupt = envelope_key(2, &envelopes[1].message.beacon_block_root); + let mut batch = backend.begin_write().expect("write batch"); + let rows = vec![(corrupt, vec![0xff; 16])]; + batch + .put_batch(Table::ExecutionPayloadEnvelopes, rows) + .expect("put"); + batch.commit().expect("commit"); + + let mut answer = envelopes_by_range(&store, 1, 3).expect("answered"); + let first = answer.next_envelope().expect("the first envelope"); + assert_eq!(first.ssz, envelopes[0].to_ssz()); + assert_eq!(answer.next_envelope(), None); + // Over for good: slot 3's envelope is not sent past the gap. + assert_eq!(answer.remaining(), 0); + assert_eq!(answer.next_envelope(), None); + } + + /// An envelope no chunk can carry is left out, and the budget is spent + /// only on what is sent. + #[test] + fn by_range_skips_an_envelope_too_large_for_a_chunk_without_charging_it() { + let mut store = beacon_store(); + let root_1 = extend_chain(&mut store, gloas_block(1, H256::ZERO, hash(0))); + let root_2 = extend_chain(&mut store, gloas_block(2, root_1, hash(1))); + let root_3 = extend_chain(&mut store, gloas_block(3, root_2, hash(2))); + let mut oversized = test_support::envelope(root_1, 1, hash(1)); + oversized.message.payload.transactions = vec![vec![0u8; MAX_PAYLOAD_SIZE].into()].into(); + assert!(!fits_one_chunk(oversized.to_ssz().len())); + store.insert_verified_payload(1, &oversized); + let sendable = vec![ + reveal(&mut store, 2, root_2, hash(2)), + reveal(&mut store, 3, root_3, hash(3)), + ]; + let size = sendable[0].to_ssz().len(); + + assert_eq!(served(&store, 1, 3), sendable); + // One byte more than an envelope: had the oversized one been charged, + // the budget would be gone before the second. + assert_eq!(served_within(&store, 1, 3, size + 1), sendable); + assert_eq!(served_within(&store, 1, 3, size), sendable[..1]); + } + + /// The whole path a peer sees: the answer goes through the codec's + /// `write_response`, and reads back as the envelopes themselves. + #[tokio::test] + async fn a_by_range_answer_reads_back_as_its_envelopes() { + // Gloas scheduled after mainnet's fulu, so the chunks carry a digest + // only a gloas slot has. + 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, 4); + let size = envelopes[0].to_ssz().len(); + let protocol = StreamProtocol::new(EXECUTION_PAYLOAD_ENVELOPES_BY_RANGE_V1); + let codec = || { + Codec::beacon(BeaconContext { + config: config.clone(), + genesis_validators_root: H256::repeat_byte(0x4b), + }) + }; + + for (budget, expected) in [ + (ENVELOPES_BY_RANGE_BYTE_BUDGET, &envelopes[..]), + (2 * size, &envelopes[..2]), + ] { + let answer = + envelopes_by_range_within(&store, first_slot + 1, 4, budget).expect("answered"); + let response = + Response::success(ResponsePayload::ExecutionPayloadEnvelopesByRange(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, expected), + other => panic!("read as {other}"), + } + } } #[test] diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index 5e080f4b8..6e0db55cb 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -33,8 +33,9 @@ use ethlambda_types::{block::SignedBlock, primitives::H256}; pub(crate) use super::envelope_client::release_envelope_gate; use super::envelope_client::{ - handle_envelope_fetch_failure, handle_envelopes_by_range_response, - handle_envelopes_by_root_response, request_beacon_envelopes_by_range, + EnvelopeSpan, handle_envelope_fetch_failure, handle_envelopes_by_range_response, + handle_envelopes_by_root_response, release_envelope_requests_of, + request_beacon_envelopes_by_range, }; use super::{ Request, Response, ResponsePayload, envelopes, @@ -325,8 +326,13 @@ pub async fn handle_req_resp_message( start_slot, end_slot, session, + follow_ups_until, }) => { - let span = (start_slot, end_slot); + let span = EnvelopeSpan { + start_slot, + end_slot, + follow_ups_until, + }; handle_envelopes_by_range_response( server, peer, span, session, envelopes, ctx, ) @@ -359,6 +365,21 @@ 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 + // peer's envelopes as `ExecutionPayloadEnvelopes`. The + // request is retired all the same, for the reason + // `retire_unanswered` gives. + ResponsePayload::ExecutionPayloadEnvelopesByRange(_) => { + error!( + %peer, + ?request_id, + "A stored envelope answer arrived as a response" + ); + if let Some(kind) = server.outbound_requests.remove(&request_id) { + retire_unanswered(server, kind, peer, ctx).await; + } + } ResponsePayload::Blocks(blocks) => { trace!(kind = "blocks_response", peer_count, "P2P message received"); // Dispatched on what was asked for first and on the @@ -543,6 +564,7 @@ pub async fn handle_req_resp_message( start_slot, end_slot, session, + .. }) => { debug!( %peer, @@ -3545,7 +3567,11 @@ async fn handle_beacon_blocks_by_range_response( if let Some(state) = &mut server.range_sync_state { state.complete_batch(end_slot); if range_session_exhausted(state) { + // The session is over, but its last batch's envelopes are still + // being asked for, and nothing waits on them any more. + let ended = state.id; server.range_sync_state = None; + release_envelope_requests_of(server, ended); return; } } @@ -5704,6 +5730,7 @@ pub(crate) mod tests { start_slot: 1, end_slot: 10, session, + follow_ups_until: Instant::now(), }; server .outbound_requests diff --git a/crates/net/p2p/src/req_resp/messages.rs b/crates/net/p2p/src/req_resp/messages.rs index a94f6dac6..5673394e3 100644 --- a/crates/net/p2p/src/req_resp/messages.rs +++ b/crates/net/p2p/src/req_resp/messages.rs @@ -6,6 +6,7 @@ use ethlambda_types::beacon::containers::gloas::SignedExecutionPayloadEnvelope; use ethlambda_types::beacon::primitives::Root; use libssz_types::SszList; +use super::envelopes::EnvelopesByRange; use crate::beacon::messages::{ BeaconMetaData, BeaconStatus, DataColumnsByRangeRequest, ExecutionPayloadEnvelopesByRangeRequest, Goodbye, Ping, @@ -204,6 +205,13 @@ impl std::fmt::Display for Response { "Success(ExecutionPayloadEnvelopes count={})", envelopes.len() ), + Self::Success { + payload: ResponsePayload::ExecutionPayloadEnvelopesByRange(answer), + } => write!( + f, + "Success(ExecutionPayloadEnvelopesByRange remaining={})", + answer.remaining() + ), Self::Error { code, message } => { let message = String::from_utf8_lossy(message); write!(f, "Error({code:?}: {message})") @@ -292,6 +300,14 @@ pub enum ResponsePayload { DataColumnSidecars(Vec), /// The envelopes answering either gloas envelope protocol. 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 + /// the answer's byte budget. + /// + /// Write-only. Reading a peer's answer off the wire yields + /// [`Self::ExecutionPayloadEnvelopes`], so this never arrives as a + /// response. + ExecutionPayloadEnvelopesByRange(EnvelopesByRange), } /// Error message type for non-success responses. diff --git a/crates/net/p2p/src/req_resp/mod.rs b/crates/net/p2p/src/req_resp/mod.rs index e3a5f176c..7a341ddb6 100644 --- a/crates/net/p2p/src/req_resp/mod.rs +++ b/crates/net/p2p/src/req_resp/mod.rs @@ -2,7 +2,7 @@ pub(crate) mod behaviour; pub(crate) mod codec; pub(crate) mod encoding; mod envelope_client; -mod envelopes; +pub(crate) mod envelopes; pub mod handlers; pub(crate) mod messages; @@ -10,7 +10,10 @@ pub(crate) use behaviour::{ReqResp, ReqRespEvent}; pub use codec::Codec; pub use encoding::{MAX_COMPRESSED_PAYLOAD_SIZE, MAX_PAYLOAD_SIZE}; pub use envelope_client::fetch_envelope_from_peer; -pub(crate) use envelope_client::{PayloadVoteFetches, fetch_envelope_for_payload_vote}; +pub(crate) use envelope_client::{ + PayloadVoteFetches, UnansweredEnvelopes, fetch_envelope_for_payload_vote, + resume_range_after_envelopes, +}; pub use handlers::{ build_status, fetch_block_from_peer, fetch_data_columns_from_peer, handle_req_resp_message, request_beacon_block_by_root, request_beacon_blocks_by_range, diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index fb4b6e7bf..5c46dd944 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -33,6 +33,6 @@ pub use target_balance_cache::{TargetBalanceCache, TargetBalances}; // is unaffected by which module owns it. pub use state_writer::CacheKey; pub use store::{ - Chain, CustodyRecord, DB_VERSION, ForkCheckpoints, GetForkchoiceStoreError, HeadVoteWindow, - MAX_RESUMABLE_DB_STATE_AGE, NEW_PAYLOAD_CAP, Store, + CanonicalEnvelopes, Chain, CustodyRecord, DB_VERSION, 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 494cef0a4..8be431dab 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1208,28 +1208,137 @@ fn decode_beacon_block_value(bytes: &[u8]) -> SignedBeaconBlock { SignedBeaconBlock::from_ssz(fork, ssz).expect("valid signed block") } -/// Whether `block` builds on the payload whose hash is `payload_block_hash`: -/// gloas's bid `parent_block_hash` rule for a payload being part of the chain. -fn builds_on_payload(block: &SignedBeaconBlock, payload_block_hash: &ExecutionBlockHash) -> bool { +/// The payload a block builds on: its bid's `parent_block_hash`, which gloas +/// compares with a payload's `block_hash` to decide whether that payload is +/// part of the chain. `None` before gloas, where no block follows a gloas one. +fn bid_parent_block_hash(block: &SignedBeaconBlock) -> Option { match block { - SignedBeaconBlock::Gloas(block) => { + SignedBeaconBlock::Gloas(block) => Some( block .message .body .signed_execution_payload_bid .message - .parent_block_hash - == *payload_block_hash - } - // A pre-gloas block cannot follow a gloas one. + .parent_block_hash, + ), SignedBeaconBlock::Phase0(_) | SignedBeaconBlock::Altair(_) | SignedBeaconBlock::Bellatrix(_) | SignedBeaconBlock::Capella(_) | SignedBeaconBlock::Deneb(_) | SignedBeaconBlock::Electra(_) - | SignedBeaconBlock::Fulu(_) => false, - SignedBeaconBlock::Lean(_) => Store::lean_only("builds_on_payload"), + | SignedBeaconBlock::Fulu(_) => None, + SignedBeaconBlock::Lean(_) => Store::lean_only("bid_parent_block_hash"), + } +} + +/// What makes a stored envelope's payload part of the canonical chain. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PayloadLink { + /// The next canonical block's bid builds on this `parent_block_hash`: the + /// payload is on the chain when its own `block_hash` equals it. + BuiltOnBy(ExecutionBlockHash), + /// The block is the head and fork choice picked its FULL node. + FullHead, +} + +/// A block whose envelope [`CanonicalEnvelopes`] has yet to read. +#[derive(Debug, Clone, Copy)] +struct EnvelopeCandidate { + slot: u64, + root: H256, + link: PayloadLink, +} + +/// One envelope out of [`CanonicalEnvelopes`], as it goes on the wire. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredEnvelope { + /// The slot of the block the envelope fulfills, which is also its + /// payload's `slot_number`. + pub slot: u64, + /// The `SignedExecutionPayloadEnvelope`'s SSZ encoding, exactly as stored. + pub ssz: Vec, +} + +/// The canonical chain's envelopes for a slot window, in ascending slot order, +/// read from the store one at a time. +/// +/// [`Store::canonical_execution_payload_envelopes`] decides which blocks are +/// on the chain and what each payload must be built on, from a single view, +/// without touching the envelope table; this then reads envelope rows as +/// [`Iterator::next`] is called, stopping at the first that is on the chain. +/// An execution payload can be megabytes, so a caller that stops early (a +/// response byte budget, a closed stream) never loads the rows it does not +/// send, and holds one envelope at a time rather than the window. +/// +/// The rows are read after the view that planned them is gone. That is sound +/// because an envelope row is written once under its block's `slot || root` +/// and never rewritten: the plan fixes the chain, and a row read later is the +/// one the plan saw. A row that has gone since is skipped. +/// +/// Reading never panics, unlike the plan: an answer is read on the stream's +/// own task, where a panic takes the swarm down. A row that fails to read or +/// decode comes out as an `Err`. +#[derive(Clone)] +pub struct CanonicalEnvelopes { + backend: Arc, + candidates: VecDeque, +} + +impl CanonicalEnvelopes { + /// How many blocks are still to be looked at: the most this can still + /// yield, since a block may turn out to hold no envelope, or one the + /// chain did not build on. + pub fn remaining(&self) -> usize { + self.candidates.len() + } + + /// Reads `candidate`'s envelope: `None` when the row is gone, or when the + /// payload it carries is not the one the chain went on to build on. + fn read(&self, candidate: EnvelopeCandidate) -> Result, Error> { + let EnvelopeCandidate { slot, root, link } = candidate; + let key = encode_slot_root_key(slot, &root); + let view = self.backend.begin_read()?; + let Some(ssz) = view.get(Table::ExecutionPayloadEnvelopes, &key)? else { + return Ok(None); + }; + let on_chain = match link { + PayloadLink::FullHead => true, + PayloadLink::BuiltOnBy(parent_block_hash) => { + let envelope = gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(&ssz) + .map_err(|err| { + let reason = format!( + "the stored execution payload envelope of block {root} at slot {slot} does not decode: {err:?}" + ); + Error::Storage(reason.into()) + })?; + envelope.message.payload.block_hash == parent_block_hash + } + }; + Ok(on_chain.then_some(StoredEnvelope { slot, ssz })) + } +} + +impl Iterator for CanonicalEnvelopes { + type Item = Result; + + fn next(&mut self) -> Option { + while let Some(candidate) = self.candidates.pop_front() { + match self.read(candidate) { + Ok(Some(envelope)) => return Some(Ok(envelope)), + Ok(None) => continue, + Err(err) => return Some(Err(err)), + } + } + None + } +} + +impl std::fmt::Debug for CanonicalEnvelopes { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CanonicalEnvelopes") + .field("remaining", &self.remaining()) + .finish_non_exhaustive() } } @@ -4420,16 +4529,26 @@ impl Store { /// ([`Self::head_payload_status`]); before this process has computed a head /// the status is unknown and the head's envelope is withheld. /// - /// Canonical blocks come from `BlockRoots` and the whole answer is read - /// from one view, like [`get_signed_blocks_by_slot_range`](Self::get_signed_blocks_by_slot_range). - /// The successor of the last block in the window may lie past `end_slot`, - /// so the index is read on beyond it, up to the head, until one is found; - /// that search is skipped when the last block holds no envelope to judge. + /// This plans the answer and does not touch + /// `Table::ExecutionPayloadEnvelopes`: the envelopes come out of the + /// returned [`CanonicalEnvelopes`], one row per step, so the caller + /// decides how many to load. Not even to ask whether a block has one: on + /// RocksDB an existence check loads the value it finds, and the rows are + /// megabytes. So every canonical block whose payload could be on the + /// chain is planned, and a block with no envelope is passed over when its + /// turn comes, at the cost of one point read that misses. + /// + /// The plan itself is made from one view, like + /// [`get_signed_blocks_by_slot_range`](Self::get_signed_blocks_by_slot_range): + /// canonical blocks come from `BlockRoots`, each paired with the + /// `parent_block_hash` its successor builds on. The successor of the last + /// block in the window may lie past `end_slot`, so the index is read on + /// beyond it, up to the head, until one is found. pub fn canonical_execution_payload_envelopes( &self, start_slot: u64, end_slot: u64, - ) -> Result, Error> { + ) -> CanonicalEnvelopes { if self.chain != Chain::Beacon { Self::lean_only("canonical_execution_payload_envelopes"); } @@ -4441,14 +4560,6 @@ impl Store { .map(|bytes| H256::from_ssz_bytes(&bytes).expect("valid block root")) }; - let envelope_row = |slot: u64, root: &H256| { - view.get( - Table::ExecutionPayloadEnvelopes, - &encode_slot_root_key(slot, root), - ) - .expect("get") - }; - let mut window: Vec<(u64, H256)> = (start_slot..=end_slot) .filter_map(|slot| canonical_root(slot).map(|root| (slot, root))) .collect(); @@ -4466,8 +4577,7 @@ impl Store { let head_slot = head_root .and_then(|head| view.get(Table::BlockHeaders, &head.to_ssz()).expect("get")) .map(|bytes| decode_beacon_block_value(&bytes).slot()); - if let Some(&(last_slot, last_root)) = window.last() - && envelope_row(last_slot, &last_root).is_some() + if !window.is_empty() && let Some(head_slot) = head_slot { let successor = (end_slot.saturating_add(1)..=head_slot) @@ -4475,38 +4585,31 @@ impl Store { window.extend(successor); } - let mut envelopes = Vec::new(); + let mut candidates = VecDeque::new(); for (index, &(slot, root)) in window.iter().enumerate() { if slot > end_slot { break; } - let Some(bytes) = envelope_row(slot, &root) else { - continue; - }; - let envelope = gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(&bytes) - .expect("a stored envelope decodes"); - let builds_on_it = match window.get(index + 1) { + let link = match window.get(index + 1) { // No successor: this is the head, whose envelope is part of // the chain only on the FULL node. - None => head_is_full, - Some((_, next_root)) => { - let next = view - .get(Table::BlockHeaders, &next_root.to_ssz()) - .expect("get") - .map(|bytes| decode_beacon_block_value(&bytes)); - match next { - Some(next) => { - builds_on_payload(&next, &envelope.message.payload.block_hash) - } - None => false, - } - } + None => head_is_full.then_some(PayloadLink::FullHead), + // A successor that is missing, or from before gloas, builds + // on no payload. + Some((_, next_root)) => view + .get(Table::BlockHeaders, &next_root.to_ssz()) + .expect("get") + .and_then(|bytes| bid_parent_block_hash(&decode_beacon_block_value(&bytes))) + .map(PayloadLink::BuiltOnBy), }; - if builds_on_it { - envelopes.push(envelope); + if let Some(link) = link { + candidates.push_back(EnvelopeCandidate { slot, root, link }); } } - Ok(envelopes) + CanonicalEnvelopes { + backend: self.backend.clone(), + candidates, + } } /// Rebuilds the in-memory `verified_payloads` and `block_timeliness` from @@ -9784,6 +9887,22 @@ mod tests { }) } + /// Every envelope [`Store::canonical_execution_payload_envelopes`] yields + /// for the window, decoded. + fn canonical_envelopes( + store: &Store, + start_slot: u64, + end_slot: u64, + ) -> Vec { + store + .canonical_execution_payload_envelopes(start_slot, end_slot) + .map(|stored| { + let stored = stored.expect("read"); + gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(&stored.ssz).expect("decode") + }) + .collect() + } + /// The head's envelope belongs to the served chain only on the FULL node: /// an EMPTY head, or a head whose status this process has not computed, /// withholds it. @@ -9810,38 +9929,92 @@ mod tests { store.insert_verified_payload(1, &envelope); assert_eq!(store.head_payload_status(), None); - assert!( - store - .canonical_execution_payload_envelopes(1, 1) - .unwrap() - .is_empty() - ); + assert!(canonical_envelopes(&store, 1, 1).is_empty()); store.set_head_payload_status(root, PayloadStatus::Empty); assert_eq!(store.head_payload_status(), Some(PayloadStatus::Empty)); - assert!( - store - .canonical_execution_payload_envelopes(1, 1) - .unwrap() - .is_empty() - ); + assert!(canonical_envelopes(&store, 1, 1).is_empty()); // A FULL status recorded for another root (the previous head, say) // must not release this head's envelope. store.set_head_payload_status(H256::repeat_byte(0xee), PayloadStatus::Full); assert_eq!(store.head_payload_status(), None); - assert!( - store - .canonical_execution_payload_envelopes(1, 1) - .unwrap() - .is_empty() - ); + assert!(canonical_envelopes(&store, 1, 1).is_empty()); store.set_head_payload_status(root, PayloadStatus::Full); + assert_eq!(canonical_envelopes(&store, 1, 1), vec![envelope]); + } + + /// Planning an answer reads no envelope, and each step reads one: a row + /// that does not decode surfaces at its own step, as an error rather + /// than a panic, and the rows after it are still there to read. + #[test] + fn canonical_envelopes_are_read_one_per_step_and_a_corrupt_row_is_an_error() { + 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.clone(), + 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"); + // Slots 1 to 3, each bid building on a zero `parent_block_hash`, which + // is the `block_hash` every `test_envelope` reveals. + 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"); + store + .update_checkpoints(ForkCheckpoints::head_only(parent)) + .expect("advance head"); + store.insert_verified_payload(slot, &test_envelope(parent)); + roots.push(parent); + } + store.set_head_payload_status(parent, PayloadStatus::Full); + // Slot 2's row is garbage. + let mut batch = backend.begin_write().expect("write batch"); + let rows = vec![(encode_slot_root_key(2, &roots[1]), vec![0xff; 16])]; + batch + .put_batch(Table::ExecutionPayloadEnvelopes, rows) + .expect("put"); + batch.commit().expect("commit"); + + // The plan is made without going near the envelope table, not even + // to ask whether a row exists: on RocksDB that loads the value. + let reads_before = envelope_reads(); + let probes_before = counts.contains(Table::ExecutionPayloadEnvelopes); + let mut envelopes = store.canonical_execution_payload_envelopes(1, 3); + assert_eq!(envelopes.remaining(), 3); + assert_eq!(envelope_reads(), reads_before); assert_eq!( - store.canonical_execution_payload_envelopes(1, 1).unwrap(), - vec![envelope] + counts.contains(Table::ExecutionPayloadEnvelopes), + probes_before ); + + let first = envelopes.next().expect("slot 1").expect("reads"); + assert_eq!(first.slot, 1); + assert_eq!(first.ssz, test_envelope(roots[0]).to_ssz()); + assert_eq!(envelopes.remaining(), 2); + // One step, one row. + assert_eq!(envelope_reads(), reads_before + 1); + + assert!(envelopes.next().expect("slot 2").is_err()); + + let third = envelopes.next().expect("slot 3").expect("reads"); + assert_eq!(third.slot, 3); + assert!(envelopes.next().is_none()); + assert_eq!(envelope_reads(), reads_before + 3); } #[test] diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 13a2bb1dc..b04e0a7e6 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -769,7 +769,8 @@ the client (`req_resp/envelope_client.rs`) asks. A chunk carries one `SignedExecutionPayloadEnvelope` under the fork digest of its block's epoch. The envelope has no slot of its own, so the epoch comes from `payload.slot_number`, which `verify_execution_payload_envelope` pins to the -block's slot. A chunk whose digest names no gloas-or-later scheduled fork, or +block's slot (a by-range answer takes it from the row's key, which is that +block's slot). A chunk whose digest names no gloas-or-later scheduled fork, or not the digest its slot implies, ends the stream. | Protocol | Served from | @@ -783,6 +784,28 @@ decode, and a by-range `count` over it is truncated, which the specification's A by-range request starting below `Store::anchor_slot` gets `RESOURCE_UNAVAILABLE`, and a window before gloas is simply empty. +A by-range answer is also bounded by bytes, under the same sentence of the +specification. An execution block may be 8 MiB of RLP (EIP-7934), so 128 +envelopes can be over a gigabyte, and the requester has the request-response +layer's ten seconds for the whole exchange. The answer stops once +`ENVELOPES_BY_RANGE_BYTE_BUDGET` (16 MiB of SSZ, before compression) has gone +out. It always carries the first envelope the window has, as the specification +requires, and overshoots the budget by less than one envelope, so one answer +sends under 26 MiB. What it sends is a prefix of the window, in slot order. + +Nor is the answer ever in memory whole. The handler only plans it +(`Store::canonical_execution_payload_envelopes`: the canonical blocks of the +window and the `parent_block_hash` each successor builds on, from one view), +and the codec reads each envelope row as it writes that chunk +(`EnvelopesByRange`, `ResponsePayload::ExecutionPayloadEnvelopesByRange`). +Planning does not touch `Table::ExecutionPayloadEnvelopes` at all, not even to +ask whether a block has a row: on RocksDB an existence check loads the value it +finds. A block without an envelope is passed over when its turn comes, for one +point read that misses. The P2P actor reads no envelope, one envelope is held +per stream, and a peer that stops reading stops the reads. A row that fails to read ends the answer where it is rather than +failing the stream, so the peer keeps what it was sent. The by-root answer is +still collected before it is sent. + The client asks in two situations. By root: the chain actor's `FetchRequest.needs_envelope` (a block whose child waits on its payload) starts a lookup with the block fetch's dedup, peer choice and retry ladder; a give-up @@ -792,7 +815,28 @@ to the actor, the same peer is asked for that span's envelopes, and range sync holds the next block request until that answer is checked and forwarded (or has failed). The pause exists because the actor keeps an envelope whose block has not imported only briefly and in small numbers, so a batch's envelopes must -arrive before the next batch's blocks do. Everything fetched goes through the +arrive before the next batch's blocks do. An answer that stops before the end +of the span is a server limiting its response (ours does, at the byte budget +above), so once it is forwarded the same peer is asked for the slots after its +last envelope, with range sync still held; that repeats until an answer +reaches the end of the span or comes back empty. Each request starts past the +last envelope received, so a span takes at most one request per slot. A tail of +slots with no payload looks the same from the requester's side and costs one +request that comes back empty. + +The follow-ups stop `ENVELOPE_FOLLOW_UP_WINDOW` (30 s) after the batch's +envelopes were first asked for. They hold the next batch back, and what counts +as progress is an envelope in the span before any check of it, so without the +bound a peer answering one envelope per request, each just inside the request +timeout, would hold a 128-slot batch for as long as the chain takes to produce +one. With it the worst a peer can do is about a batch a minute. + +A session's last batch is followed up too. That batch exhausts the session, so +no session is running when its envelopes arrive, and they are the ones nearest +the head: the request is handed on (`release_envelope_requests_of`) and names +no session from then. A session ended for cause (`end_range_session`) is not +followed up, and neither is any span once another session is running. What is +still missing after all that is asked for by root. Everything fetched goes through the same rules as an `execution_payload` gossip message (`beacon/envelope_checks.rs`) before the actor sees it; a `Queue` verdict is forwarded too.