diff --git a/CLAUDE.md b/CLAUDE.md index 96a434dc4..ad4aedecf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -449,11 +449,23 @@ 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. 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 row of either answer 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) + until the envelope answer is forwarded (the actor keeps unmatched envelopes only briefly); + the span ends at the batch's highest delivered block, and an answer that stops short of it + 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/blockchain/state_transition/src/beacon/fork_choice.rs b/crates/blockchain/state_transition/src/beacon/fork_choice.rs index e24458ebd..1447cacff 100644 --- a/crates/blockchain/state_transition/src/beacon/fork_choice.rs +++ b/crates/blockchain/state_transition/src/beacon/fork_choice.rs @@ -11998,6 +11998,14 @@ mod tests { > { self.inner.prefix_iterator(table, prefix) } + + fn first_at_or_after( + &self, + table: ethlambda_storage::Table, + key: &[u8], + ) -> std::result::Result, StorageError> { + self.inner.first_at_or_after(table, key) + } } /// The first head computation after a restart fills the payload links by diff --git a/crates/net/p2p/src/beacon/encoding.rs b/crates/net/p2p/src/beacon/encoding.rs index 4f64825af..f68e9fe73 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::{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 @@ -208,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) @@ -304,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); @@ -351,13 +354,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 +402,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 +410,55 @@ 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 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 [`EnvelopeAnswer`]'s business. The +/// rows go out as stored, decoded as a check but never re-encoded. +/// +/// Each read and its decode run here, on the connection's task, as every +/// response's encoding and compression do (a block answer's blocks are +/// encoded and compressed the same way). The next read waits on the peer +/// taking this chunk, so the work is paced by this node's uplink, not by how +/// much peers ask for. Moving it to the blocking pool would only pay off with +/// the encoding and compression moved too, for every response type. +pub async fn write_stored_envelopes_response( + io: &mut T, + label: &'static str, + config: &Config, + genesis_validators_root: Root, + 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( + io, + label, + config, + genesis_validators_root, + envelope.slot, + envelope.ssz, + ) + .await?; } Ok(()) } @@ -406,18 +479,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/beacon/protocols.rs b/crates/net/p2p/src/beacon/protocols.rs index 7498420de..f7ebdbf7d 100644 --- a/crates/net/p2p/src/beacon/protocols.rs +++ b/crates/net/p2p/src/beacon/protocols.rs @@ -11,7 +11,9 @@ //! //! The two gloas execution payload envelope protocols are registered for the //! same reason the column ones are: the server side answers out of -//! `Table::ExecutionPayloadEnvelopes`. Nothing requests them yet. +//! `Table::ExecutionPayloadEnvelopes`. The client side asks for them too: by +//! range after a gloas span's blocks arrive, by root for a block held for its +//! parent's payload. //! //! Only version 2 of the two block protocols is registered. Version 1 is //! deprecated by the spec, which lets a client answer it with an empty list, 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/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..da3e1d0e6 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`: 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)) .await @@ -440,6 +442,28 @@ impl libp2p::request_response::Codec for Codec { ) .await } + ResponsePayload::ExecutionPayloadEnvelopesByRange(answer) => { + let context = self.beacon_context(protocol.as_ref())?; + 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, + context.genesis_validators_root, + answer, + ) + .await + } }, Response::Error { code, message } => { // Send error code 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/envelope_client.rs b/crates/net/p2p/src/req_resp/envelope_client.rs index 41b6f955a..da8a280ca 100644 --- a/crates/net/p2p/src/req_resp/envelope_client.rs +++ b/crates/net/p2p/src/req_resp/envelope_client.rs @@ -108,6 +108,182 @@ 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`]). A server following +/// the specification sends a prefix of the window ("MUST be sent in +/// consecutive order"), so what it left out starts right after its last +/// envelope. That is the only part asked for again; see [`unanswered_tail`] +/// for an answer that is not a prefix. +#[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. The +/// window ends at the batch's highest block (see the caller of +/// [`request_beacon_envelopes_by_range`]), so slots past it are never asked +/// about. Within it, whether the answer stopped at a limit or the remaining +/// blocks simply have no payload on the chain (one never revealed, or not +/// built on) cannot be told apart from here, so both are asked about; the +/// second costs one request that comes back empty. +/// +/// Only the tail, whatever the answer left out before its last envelope +/// ([`unlinked_neighbours`] sees some of that; an answer missing the window's +/// first envelopes looks like any other). The peer was asked for those slots +/// and sent the envelopes on both sides of them, so it does not hold what is +/// missing or will not send it, and asking it again would only keep range +/// sync's next batch waiting. A peer set on withholding can answer empty just +/// as well. What it left out comes from other peers, by root: the chain actor +/// asks as soon as the child of a block missing its payload is held, and every +/// slot after that. +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) +} + +/// The first two neighbouring envelopes of a range answer, in slot order, of +/// which the later does not build on the earlier: the slots of both. +/// +/// What a server answers with is the canonical chain's payloads, and each of +/// those builds on the one before it however many slots without a payload lie +/// between: its `parent_hash` is the earlier one's `block_hash`. Two +/// neighbours that do not link therefore have a payload missing between them, +/// or one of them is not the canonical chain's, which the envelope checks +/// decide. Either way the answer is not the prefix of the window the +/// specification asks for. +/// +/// Nothing is asked for again on the strength of this ([`unanswered_tail`] +/// says why); it is what tells a batch that fell back to by-root lookups from +/// one whose slots simply held no payload. +fn unlinked_neighbours(envelopes: &[SignedExecutionPayloadEnvelope]) -> Option<(u64, u64)> { + envelopes.windows(2).find_map(|pair| { + let (earlier, later) = (&pair[0].message.payload, &pair[1].message.payload); + (later.parent_hash != earlier.block_hash) + .then_some((earlier.slot_number, later.slot_number)) + }) +} + +/// 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. @@ -317,7 +493,8 @@ fn range_reaches_gloas(config: &Config, span: &std::ops::RangeInclusive) -> } /// Ask `peer` for the envelopes in `[start_slot, start_slot + count)`, the span -/// of a `BeaconBlocksByRange` answer that was just handed to the chain actor. +/// of a `BeaconBlocksByRange` answer that was just handed to the chain actor, +/// up to its highest block: no envelope lies past that. /// /// Sent after that answer rather than beside the blocks request, so the /// ordering the chain actor needs does not depend on which of two streams @@ -332,7 +509,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 +521,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 +571,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 +602,30 @@ 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. That +/// includes whatever the answer left out before its last envelope, which is +/// noticed where it shows ([`unlinked_neighbours`]) and not asked of this peer +/// again. 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 +639,31 @@ pub(super) async fn handle_envelopes_by_range_response( if dropped > 0 { debug!(%peer, start_slot, end_slot, dropped, "Dropping out-of-range envelopes"); } + if let Some((earlier_slot, later_slot)) = unlinked_neighbours(&envelopes) { + debug!( + %peer, + start_slot, + end_slot, + earlier_slot, + later_slot, + "ExecutionPayloadEnvelopesByRange answer is not a run of payloads built on one \ + another; what it left out is asked for by root" + ); + } + 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 +734,227 @@ 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)); + // Only the tail is asked about. The slots between two envelopes held + // no payload, or held one this peer did not send, and it is not asked + // for those again either way. + 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 range answer that leaves a payload out between two it carries is told + /// apart from one whose slots in between held none: every payload builds + /// on the one before it, so the envelopes on either side do not link. + #[test] + fn a_range_answer_missing_a_payload_between_two_it_carries_is_noticed() { + let root = H256::repeat_byte(1); + let hash = |slot: u64| H256::repeat_byte(slot as u8); + // The canonical payloads of slots 10, 15 and 20, each built on the one + // before; the slots between hold none. + let payload = |slot: u64, built_on: u64| { + let mut envelope = + crate::beacon::encoding::test_support::envelope(root, slot, hash(slot)); + envelope.message.payload.parent_hash = hash(built_on); + envelope + }; + let (first, second, third) = (payload(10, 9), payload(15, 10), payload(20, 15)); + + let whole = [first.clone(), second.clone(), third.clone()]; + assert_eq!(unlinked_neighbours(&whole), None); + assert_eq!(unlinked_neighbours(&whole[..1]), None); + assert_eq!(unlinked_neighbours(&[]), None); + + // Slot 15's payload left out: slot 20's does not build on slot 10's. + let holed = [first, third]; + assert_eq!(unlinked_neighbours(&holed), Some((10, 20))); + // The answer reached the end of the span, so the peer that left the + // payload out is not asked again: it comes by root. + assert_eq!(unanswered_tail(&holed, 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..04b063bc2 100644 --- a/crates/net/p2p/src/req_resp/envelopes.rs +++ b/crates/net/p2p/src/req_resp/envelopes.rs @@ -2,20 +2,162 @@ //! (`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_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; 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); + +/// 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 is under 26 MiB of SSZ. An answer from a node with +/// this serving budget is therefore read whole. +/// +/// The budget counts SSZ bytes, and the answer is held decoded, which can be +/// several times larger: an empty transaction is a 4-byte offset in SSZ and a +/// 24-byte `Vec` decoded, so envelopes packed with them hold about six times +/// what was counted. +/// +/// 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 +/// ([`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. +/// +/// `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 EnvelopeAnswer { + envelopes: I, + /// The bytes still to send before the answer stops; zero once it has. + budget: usize, +} + +/// 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 } + } + + /// 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.size_hint().1.unwrap_or(usize::MAX) + } + } + + /// 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 + /// 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.size_hint().1, + "Envelope 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 +167,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 +184,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 +203,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(EnvelopeAnswer::new(envelopes, budget)) } /// Answer `execution_payload_envelopes_by_root/1` with whichever of the named @@ -117,6 +281,10 @@ fn envelopes_by_range( /// 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, @@ -128,53 +296,65 @@ 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)] mod tests { use super::*; + use crate::beacon::BeaconContext; use crate::beacon::encoding::test_support; - use ethlambda_storage::{ForkCheckpoints, backend::InMemoryBackend}; + 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; + use futures::io::Cursor; + use libp2p::StreamProtocol; + use libp2p::request_response::Codec as _; + use libssz::{SszDecode as _, SszEncode as _}; use std::sync::Arc; /// A gloas block whose bid builds on the payload `parent_block_hash`. @@ -199,20 +379,103 @@ mod tests { } fn beacon_store() -> Store { + beacon_store_on(Arc::new(InMemoryBackend::new()), 0) + } + + /// Mainnet's configuration with gloas starting at `epoch`. Mainnet itself + /// schedules no gloas, and nothing is served from before the fork. + fn gloas_config_from(epoch: u64) -> Config { + Config { + gloas_fork_epoch: epoch, + ..Config::mainnet() + } + } + + /// A store on `backend`, on a chain that is gloas from genesis, whose + /// anchor block, of root zero, is at `anchor_slot`. + fn beacon_store_on(backend: Arc, anchor_slot: u64) -> Store { + beacon_store_with(backend, gloas_config_from(0), anchor_slot) + } + + /// [`beacon_store_on`] under a configuration of the caller's choosing. + fn beacon_store_with(backend: Arc, config: Config, anchor_slot: u64) -> Store { let mut store = Store::init_beacon( - Arc::new(InMemoryBackend::new()), + backend, 0, - Config::mainnet(), + config, 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: 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) + .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 +529,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 +542,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 +553,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 +595,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,56 +606,304 @@ 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] fn by_range_answers_empty_for_a_pre_gloas_window_that_has_blocks() { - let mut store = beacon_store(); + // Gloas from epoch 1: slots 1 and 2 are before the fork. + let first_gloas = preset::slots_per_epoch(); + let backend = Arc::new(InMemoryBackend::new()); + let mut store = beacon_store_with(backend, gloas_config_from(1), 0); let root_1 = extend_chain(&mut store, pre_gloas_block(1, H256::ZERO)); let root_2 = extend_chain(&mut store, pre_gloas_block(2, root_1)); - let root_3 = extend_chain(&mut store, gloas_block(3, root_2, hash(0))); - let envelope = reveal(&mut store, 3, root_3, hash(3)); + let root_3 = extend_chain(&mut store, gloas_block(first_gloas, root_2, hash(0))); + let envelope = reveal(&mut store, first_gloas, 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!(served(&store, 1, first_gloas - 1).is_empty()); + assert_eq!(served(&store, 1, first_gloas), vec![envelope]); + } + + /// A chain that never schedules gloas (mainnet today) answers every + /// window empty, whatever its store holds. + #[test] + fn by_range_answers_empty_where_gloas_is_not_scheduled() { + let backend = Arc::new(InMemoryBackend::new()); + let mut store = beacon_store_with(backend, Config::mainnet(), 0); + let root_1 = extend_chain(&mut store, pre_gloas_block(1, H256::ZERO)); + extend_chain(&mut store, pre_gloas_block(2, root_1)); + + assert!(served(&store, 0, MAX_REQUEST_PAYLOADS).is_empty()); + let answer = envelopes_by_range(&store, 0, MAX_REQUEST_PAYLOADS).expect("answered"); + assert_eq!(answer.remaining(), 0); } #[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); + } + + /// 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 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); + let codec = || { + Codec::beacon(BeaconContext { + config: config.clone(), + genesis_validators_root: H256::repeat_byte(0x4b), + }) + }; - assert!(envelopes_by_range(&store, 9, 1).is_err()); - assert!(envelopes_by_range(&store, 10, 1).is_ok()); + 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}"), + } + } + } + + /// 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] @@ -414,7 +915,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()]); } @@ -426,6 +927,143 @@ 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 by-root row is checked before it is sent, like a by-range one: a + /// row that does not decode ends the answer where it is, so the peer + /// keeps the envelopes it was sent instead of failing to read the lot. + #[test] + fn by_root_ends_the_answer_at_a_row_that_does_not_decode() { + 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 roots: Vec = envelopes + .iter() + .map(|envelope| envelope.message.beacon_block_root) + .collect(); + let corrupt = envelope_key(2, &roots[1]); + 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_root(&store, &roots); + 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: nothing is sent past the row that failed. + assert_eq!(answer.remaining(), 0); + assert_eq!(answer.next_envelope(), None); + + // Asked for alone, the corrupt row answers empty, not garbage. + assert!(drain(envelopes_by_root(&store, &roots[1..2])).is_empty()); + } + + /// 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 5e080f4b8..becb742d1 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,22 @@ pub async fn handle_req_resp_message( } } } + // 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::ExecutionPayloadEnvelopesByRoot(_) => { + 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 +565,7 @@ pub async fn handle_req_resp_message( start_slot, end_slot, session, + .. }) => { debug!( %peer, @@ -3522,13 +3545,16 @@ async fn handle_beacon_blocks_by_range_response( // envelopes of the same span only after that. On a gloas span the next // batch is then held back until the answer has been delivered (see // `RangeSyncState::envelopes_pending`). - let waiting_on_envelopes = request_beacon_envelopes_by_range( - server, - peer, - start_slot, - end_slot.saturating_sub(start_slot).saturating_add(1), - ) - .await; + // + // The span ends at the highest block handed over, not at the end asked + // for: past it there is no block, so no envelope, and a span reaching + // into those slots would have every answer that stops at that block + // followed up with a request that can only come back empty (the batch at + // the peer's head, a batch ending in missed slots). The server still + // judges that block's payload by its successor past the span. + let envelope_slots = highest.saturating_sub(start_slot).saturating_add(1); + let waiting_on_envelopes = + request_beacon_envelopes_by_range(server, peer, start_slot, envelope_slots).await; // Highest slot *handed to* the actor, not the highest imported: see // [`range_sync_target`] for why range sync reads this beside the store's @@ -3545,7 +3571,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 +5734,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..f6ffb9b92 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, EnvelopesByRoot}; use crate::beacon::messages::{ BeaconMetaData, BeaconStatus, DataColumnsByRangeRequest, ExecutionPayloadEnvelopesByRangeRequest, Goodbye, Ping, @@ -204,6 +205,20 @@ 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::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})") @@ -290,8 +305,22 @@ 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 answering either gloas envelope protocol. + /// 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 + /// 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), + /// 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/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/api/mod.rs b/crates/storage/src/api/mod.rs index 703ddfc53..493bfcce5 100644 --- a/crates/storage/src/api/mod.rs +++ b/crates/storage/src/api/mod.rs @@ -18,5 +18,6 @@ mod traits; pub use tables::{ALL_TABLES, Table}; pub use traits::{ - Error, PrefixResult, StorageBackend, StorageReadView, StorageReadViewExt, StorageWriteBatch, + Entry, Error, PrefixResult, StorageBackend, StorageReadView, StorageReadViewExt, + StorageWriteBatch, }; diff --git a/crates/storage/src/api/traits.rs b/crates/storage/src/api/traits.rs index 70332c2b3..e82948985 100644 --- a/crates/storage/src/api/traits.rs +++ b/crates/storage/src/api/traits.rs @@ -3,8 +3,11 @@ use super::Table; /// Storage error type. pub type Error = Box; +/// One table entry as a view hands it out: the key and the value, owned. +pub type Entry = (Box<[u8]>, Box<[u8]>); + /// Result type for prefix iterator operations. -pub type PrefixResult = Result<(Box<[u8]>, Box<[u8]>), Error>; +pub type PrefixResult = Result; /// A storage backend that can read and write data through views and batches. pub trait StorageBackend: Send + Sync { @@ -63,6 +66,14 @@ pub trait StorageReadView { table: Table, prefix: &[u8], ) -> Result + '_>, Error>; + + /// The first entry of a table whose key is at or after `key`, in the + /// table's byte-wise key order, or `None` when every key is before it. + /// + /// One seek, whatever the distance to that entry: over a table keyed by + /// big-endian slot this finds the next slot that has a row without + /// probing the empty slots in between. + fn first_at_or_after(&self, table: Table, key: &[u8]) -> Result, Error>; } /// Generic conveniences over [`StorageReadView::read`]. diff --git a/crates/storage/src/backend/in_memory.rs b/crates/storage/src/backend/in_memory.rs index 6c4d303f6..959f81e6f 100644 --- a/crates/storage/src/backend/in_memory.rs +++ b/crates/storage/src/backend/in_memory.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use std::sync::{Arc, RwLock}; use crate::api::{ - ALL_TABLES, Error, PrefixResult, StorageBackend, StorageReadView, StorageWriteBatch, Table, + ALL_TABLES, Entry, Error, PrefixResult, StorageBackend, StorageReadView, StorageWriteBatch, + Table, }; type TableData = HashMap, Vec>; @@ -102,6 +103,16 @@ impl StorageReadView for InMemoryReadView<'_> { Ok(Box::new(iter)) } + + fn first_at_or_after(&self, table: Table, key: &[u8]) -> Result, Error> { + let table_data = self.guard.get(&table).expect("table exists"); + let first = table_data + .iter() + .filter(|(k, _)| k.as_slice() >= key) + .min_by(|a, b| a.0.cmp(b.0)) + .map(|(k, v)| (k.clone().into_boxed_slice(), v.clone().into_boxed_slice())); + Ok(first) + } } /// Write batch that accumulates changes before committing. diff --git a/crates/storage/src/backend/rocksdb.rs b/crates/storage/src/backend/rocksdb.rs index d74ad860a..82af18796 100644 --- a/crates/storage/src/backend/rocksdb.rs +++ b/crates/storage/src/backend/rocksdb.rs @@ -1,11 +1,12 @@ //! RocksDB storage backend. use crate::api::{ - ALL_TABLES, Error, PrefixResult, StorageBackend, StorageReadView, StorageWriteBatch, Table, + ALL_TABLES, Entry, Error, PrefixResult, StorageBackend, StorageReadView, StorageWriteBatch, + Table, }; use rocksdb::{ BlockBasedOptions, Cache, ColumnFamilyDescriptor, DBCompressionType, DBWithThreadMode, - MultiThreaded, Options, WriteBatch, WriteOptions, + Direction, IteratorMode, MultiThreaded, Options, WriteBatch, WriteOptions, }; use std::path::Path; use std::sync::Arc; @@ -198,6 +199,19 @@ impl StorageReadView for RocksDBReadView { Ok(Box::new(iter)) } + + fn first_at_or_after(&self, table: Table, key: &[u8]) -> Result, Error> { + let cf = self + .db + .cf_handle(cf_name(table)) + .ok_or_else(|| format!("Column family {} not found", cf_name(table)))?; + + // No column family has a prefix extractor, so this seek is in total + // key order. + let mode = IteratorMode::From(key, Direction::Forward); + let first = self.db.iterator_cf(&cf, mode).next().transpose()?; + Ok(first) + } } /// Write batch for RocksDB. diff --git a/crates/storage/src/backend/tests.rs b/crates/storage/src/backend/tests.rs index 6367f19bc..d63bf0c1f 100644 --- a/crates/storage/src/backend/tests.rs +++ b/crates/storage/src/backend/tests.rs @@ -17,6 +17,7 @@ pub fn run_backend_tests(backend: &dyn StorageBackend) { test_put_from_borrowed_bytes(backend); test_delete(backend); test_prefix_iterator(backend); + test_first_at_or_after(backend); test_nonexistent_key(backend); test_contains(backend); test_read(backend); @@ -161,6 +162,45 @@ fn test_delete(backend: &dyn StorageBackend) { } } +/// Over big-endian slot keys, as `BlockRoots` has them: the seek lands on +/// the key itself when it is there, on the next one across any gap when it +/// is not, and on nothing past the last key. +fn test_first_at_or_after(backend: &dyn StorageBackend) { + let key = |slot: u64| slot.to_be_bytes().to_vec(); + // Slots chosen so that byte order and numeric order would differ under a + // little-endian or a prefix-bound seek: 255 and 256 share no prefix. + let slots = [3u64, 255, 256, 1_000_000]; + { + let mut batch = backend.begin_write().unwrap(); + let rows = slots + .iter() + .map(|&slot| (key(slot), vec![slot as u8])) + .collect(); + batch.put_batch(Table::BlockRoots, rows).unwrap(); + batch.commit().unwrap(); + } + + let view = backend.begin_read().unwrap(); + let found = |from: u64| { + view.first_at_or_after(Table::BlockRoots, &key(from)) + .unwrap() + .map(|(found, value)| { + let slot = u64::from_be_bytes(found.as_ref().try_into().unwrap()); + assert_eq!(&*value, &[slot as u8]); + slot + }) + }; + assert_eq!(found(0), Some(3)); + assert_eq!(found(3), Some(3)); + assert_eq!(found(4), Some(255)); + assert_eq!(found(255), Some(255)); + assert_eq!(found(256), Some(256)); + assert_eq!(found(257), Some(1_000_000)); + assert_eq!(found(1_000_000), Some(1_000_000)); + assert_eq!(found(1_000_001), None); + assert_eq!(found(u64::MAX), None); +} + fn test_prefix_iterator(backend: &dyn StorageBackend) { // Write data with common prefix { diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index fb4b6e7bf..5c421294f 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -18,7 +18,8 @@ mod target_balance_cache; pub use active_balance_cache::{ActiveBalanceCache, ActiveBalanceKey}; pub use api::{ - ALL_TABLES, StorageBackend, StorageReadView, StorageReadViewExt, StorageWriteBatch, Table, + ALL_TABLES, Entry as StorageEntry, StorageBackend, StorageReadView, StorageReadViewExt, + StorageWriteBatch, Table, }; pub use committee_cache::{CommitteeCache, Lookup, ShufflingKey}; /// Error type returned by the fallible [`Store`] operations, exported so @@ -33,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::{ - Chain, CustodyRecord, DB_VERSION, ForkCheckpoints, GetForkchoiceStoreError, HeadVoteWindow, - MAX_RESUMABLE_DB_STATE_AGE, NEW_PAYLOAD_CAP, Store, + 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 494cef0a4..20fe78631 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1208,28 +1208,224 @@ 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, +} + +/// Decodes the envelope row of the block `root` at `slot`, as a check on +/// bytes about to go on the wire as they are. +/// +/// A requester that cannot decode one chunk drops the whole answer, the +/// envelopes that came before it included. So a row is decoded before it is +/// handed over, whether or not anything is read out of it, and one that does +/// not decode is an error the answer can end at. +fn decode_stored_envelope( + slot: u64, + root: &H256, + ssz: &[u8], +) -> Result { + gloas::SignedExecutionPayloadEnvelope::from_ssz_bytes(ssz).map_err(|err| { + let root = ShortRoot(&root.0); + let reason = format!( + "the stored execution payload envelope of block {root} at slot {slot} does not decode: {err:?}" + ); + Error::Storage(reason.into()) + }) +} + +/// 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 the plan fixes the chain, and a row is judged only by its payload's +/// `block_hash`, which a later write cannot change: a block's `slot || root` +/// row only ever holds an envelope checked against that block's bid, which +/// names the hash. A row may be written again (an envelope delivered again is +/// recorded again), with the same payload. A row deleted since (a payload the +/// execution client found invalid, [`Store::remove_verified_payload`]) is +/// skipped, which leaves a gap in the answer. +/// +/// 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); + }; + // Every row is decoded, the head's too, though only a successor's bid + // needs a field out of it; see `decode_stored_envelope`. + let envelope = decode_stored_envelope(slot, &root, &ssz)?; + let on_chain = match link { + PayloadLink::FullHead => true, + PayloadLink::BuiltOnBy(parent_block_hash) => { + 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 + } + + 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 nothing is read out of a row. It is +/// decoded all the same, as a check on bytes that go on the wire as stored +/// ([`decode_stored_envelope`]). 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 or decode 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 Some(ssz) = view.get(Table::ExecutionPayloadEnvelopes, &key)? else { + return Ok(None); + }; + decode_stored_envelope(slot, root, &ssz)?; + Ok(Some(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 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CanonicalEnvelopes") + .field("remaining", &self.remaining()) + .finish_non_exhaustive() } } @@ -4408,6 +4604,44 @@ 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 { + self.config + .gloas_fork_epoch + .saturating_mul(slots_per_epoch()) + } + /// Gloas: the stored envelopes of payloads on the canonical chain, for the /// slots `start_slot..=end_slot`, in ascending slot order. /// @@ -4420,19 +4654,49 @@ 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. + /// + /// Slots before the gloas fork are cut off the front of the window before + /// anything is read. They hold no envelope, and planning them would decode + /// the block after each, which before gloas carries a whole execution + /// payload: a request costing megabytes a slot that the byte budget on + /// the answer never sees. A window that ends before gloas reads nothing. + /// + /// 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 sought + /// once for the next row after it, up to the head. A seek rather than a + /// read per slot: the gap to that block is the chain's, not the + /// request's, and can be any length. 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"); } + // No block before gloas has an envelope, and the plan decodes the + // block after each one it looks at. Before gloas that block carries + // its whole execution payload, so a window down there would cost a + // peer one request and this node megabytes of decoding per slot, to + // answer nothing. From gloas on a block holds a bid instead. + let start_slot = start_slot.max(self.first_gloas_slot()); + if start_slot > end_slot { + return CanonicalEnvelopes { + backend: self.backend.clone(), + candidates: VecDeque::new(), + }; + } let recorded_head = self.beacon.lock().unwrap().head_node_payload_status; let view = self.backend.begin_read().expect("read view"); let canonical_root = |slot: u64| -> Option { @@ -4441,14 +4705,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(); @@ -4463,50 +4719,53 @@ impl Store { // nothing about this one. let head_is_full = head_root.is_some() && recorded_head == head_root.map(|root| (root, PayloadStatus::Full)); - 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() - && let Some(head_slot) = head_slot - { - let successor = (end_slot.saturating_add(1)..=head_slot) - .find_map(|slot| canonical_root(slot).map(|root| (slot, root))); + // The head is decoded for its slot only once the window holds a + // block, which puts the head at a gloas slot as well. + if !window.is_empty() { + 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()); + // One seek for the next canonical block, however far it is: the + // index has no row for an empty slot, and probing them one by + // one would cost a read per slot of whatever gap the chain has + // after the window, which no request count bounds. + let successor = head_slot.and_then(|head_slot| { + let after = encode_block_root_key(end_slot.checked_add(1)?); + let (key, root) = view + .first_at_or_after(Table::BlockRoots, &after) + .expect("seek block root")?; + let slot = u64::from_be_bytes(key.as_ref().try_into().expect("slot key")); + let root = H256::from_ssz_bytes(&root).expect("valid block root"); + (slot <= head_slot).then_some((slot, root)) + }); 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 @@ -7585,6 +7844,7 @@ mod tests { struct ReadCounts { gets: Mutex>, contains: Mutex>, + seeks: Mutex>, } impl ReadCounts { @@ -7599,6 +7859,9 @@ mod tests { .copied() .unwrap_or(0) } + fn seeks(&self, table: Table) -> usize { + self.seeks.lock().unwrap().get(&table).copied().unwrap_or(0) + } } struct CountingBackend { @@ -7659,6 +7922,15 @@ mod tests { ) -> Result + '_>, BackendError> { self.inner.prefix_iterator(table, prefix) } + + fn first_at_or_after( + &self, + table: Table, + key: &[u8], + ) -> Result, BackendError> { + *self.counts.seeks.lock().unwrap().entry(table).or_default() += 1; + self.inner.first_at_or_after(table, key) + } } fn counting_store() -> (Store, Arc) { @@ -9784,6 +10056,32 @@ mod tests { }) } + /// Mainnet's configuration with gloas starting at `epoch`. Mainnet itself + /// does not schedule gloas, and the envelope planner serves nothing + /// before the fork. + fn gloas_config_from(epoch: u64) -> Config { + Config { + gloas_fork_epoch: epoch, + ..Config::mainnet() + } + } + + /// 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. @@ -9792,7 +10090,7 @@ mod tests { let mut store = Store::init_beacon( Arc::new(InMemoryBackend::new()), 0, - Config::mainnet(), + gloas_config_from(0), H256::ZERO, Store::beacon_checkpoint_as_stored(BeaconCheckpoint::default()), 0, @@ -9810,38 +10108,376 @@ 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!( + 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, + gloas_config_from(0), + 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 - .canonical_execution_payload_envelopes(1, 1) - .unwrap() - .is_empty() + .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!( + counts.contains(Table::ExecutionPayloadEnvelopes), + probes_before ); - store.set_head_payload_status(root, PayloadStatus::Full); + 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); + } + + /// 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!( - store.canonical_execution_payload_envelopes(1, 1).unwrap(), - vec![envelope] + 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()); + } + + /// A named block's row is decoded before it is handed over, though no + /// rule reads anything out of it: a row that does not decode is an error + /// at its own step, and the rows named after it are still there. + #[test] + fn a_corrupt_row_of_a_named_block_is_an_error() { + let backend = Arc::new(InMemoryBackend::new()); + 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"); + 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.insert_verified_payload(slot, &test_envelope(parent)); + roots.push(parent); + } + // 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"); + + let mut envelopes = store.execution_payload_envelopes_of(roots.clone()); + assert_eq!(envelopes.next().expect("slot 1").expect("reads").slot, 1); + assert!(envelopes.next().expect("slot 2").is_err()); + assert_eq!(envelopes.next().expect("slot 3").expect("reads").slot, 3); + 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. + #[test] + fn a_corrupt_row_at_the_full_head_is_an_error() { + let backend = Arc::new(InMemoryBackend::new()); + let mut store = Store::init_beacon( + backend.clone(), + 0, + gloas_config_from(0), + 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; + for slot in 1..=2 { + 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)); + } + store.set_head_payload_status(parent, PayloadStatus::Full); + let mut batch = backend.begin_write().expect("write batch"); + let rows = vec![(encode_slot_root_key(2, &parent), vec![0xff; 16])]; + batch + .put_batch(Table::ExecutionPayloadEnvelopes, rows) + .expect("put"); + batch.commit().expect("commit"); + + let mut envelopes = store.canonical_execution_payload_envelopes(1, 2); + assert_eq!(envelopes.next().expect("slot 1").expect("reads").slot, 1); + assert!(envelopes.next().expect("the head").is_err()); + assert!(envelopes.next().is_none()); + } + + /// The block after the window is found with one seek, whatever the run + /// of empty slots before it: planning costs the same reads when that + /// block is a hundred thousand slots on as when it is the next slot. + #[test] + fn the_successor_past_the_window_is_sought_not_scanned_for() { + const GAP: u64 = 100_000; + let counts = Arc::new(ReadCounts::default()); + let backend = Arc::new(CountingBackend { + inner: InMemoryBackend::new(), + counts: counts.clone(), + }); + let mut store = Store::init_beacon( + backend, + 0, + gloas_config_from(0), + 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"); + // Blocks at slots 1 and 2, then nothing until the head. + let mut parent = H256::ZERO; + let mut roots = Vec::new(); + for slot in [1, 2, 2 + GAP] { + 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); + } + + let gets_before = counts.gets(Table::BlockRoots); + let seeks_before = counts.seeks(Table::BlockRoots); + let envelopes = store.canonical_execution_payload_envelopes(1, 2); + // The window's own two slots, and nothing for the gap. + assert_eq!(counts.gets(Table::BlockRoots) - gets_before, 2); + assert_eq!(counts.seeks(Table::BlockRoots) - seeks_before, 1); + // Slot 2's payload is judged by the block across the gap. + let slots: Vec = envelopes + .map(|stored| stored.expect("reads").slot) + .collect(); + assert_eq!(slots, vec![1, 2]); + + // A window that ends at the head has no successor to find. + let envelopes = store.canonical_execution_payload_envelopes(2 + GAP, 2 + GAP); + assert_eq!(envelopes.remaining(), 0); + store.set_head_payload_status(roots[2], PayloadStatus::Full); + let envelopes = store.canonical_execution_payload_envelopes(2 + GAP, 2 + GAP); + assert_eq!(envelopes.remaining(), 1); + } + + /// A window before gloas is answered without reading the chain, and one + /// that straddles the fork is planned from the fork's first slot: the + /// blocks before it, which carry whole execution payloads, are never + /// loaded to look for a bid they do not have. + #[test] + fn slots_before_gloas_are_not_planned() { + let counts = Arc::new(ReadCounts::default()); + let backend = Arc::new(CountingBackend { + inner: InMemoryBackend::new(), + counts: counts.clone(), + }); + let first_gloas = slots_per_epoch(); + let mut store = Store::init_beacon( + backend, + 0, + gloas_config_from(1), + H256::ZERO, + Store::beacon_checkpoint_as_stored(BeaconCheckpoint::default()), + 0, + ); + store + .insert_signed_block(H256::ZERO, beacon_test_block(0, H256::ZERO)) + .expect("insert anchor"); + // A block in every slot: pre-gloas ones up to the fork, then three + // gloas blocks, each with an envelope the next one builds on. + let mut parent = H256::ZERO; + let mut gloas_roots = Vec::new(); + for slot in 1..first_gloas + 3 { + let block = if slot < first_gloas { + beacon_test_block(slot, parent) + } else { + 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"); + if slot >= first_gloas { + store.insert_verified_payload(slot, &test_envelope(parent)); + gloas_roots.push(parent); + } + } + store.set_head_payload_status(parent, PayloadStatus::Full); + let reads = || { + [Table::BlockRoots, Table::BlockHeaders, Table::Metadata] + .map(|table| counts.gets(table)) + }; + + // Entirely before the fork: nothing is read, nothing is planned. + let before = reads(); + let mut envelopes = store.canonical_execution_payload_envelopes(1, first_gloas - 1); + assert_eq!(envelopes.remaining(), 0); + assert!(envelopes.next().is_none()); + assert_eq!(reads(), before); + + // Across the fork: the plan starts at the fork's first slot, so the + // only blocks decoded are gloas ones (the successors of the first two + // gloas blocks, and the head for its slot). + let before = reads(); + let envelopes = store.canonical_execution_payload_envelopes(1, first_gloas + 2); + assert_eq!(envelopes.remaining(), 3); + let [_, headers_before, _] = before; + let [_, headers_after, _] = reads(); + assert_eq!(headers_after - headers_before, 3); + let slots: Vec = envelopes + .map(|stored| stored.expect("reads").slot) + .collect(); + assert_eq!(slots, vec![first_gloas, first_gloas + 1, first_gloas + 2]); + + // Mainnet schedules no gloas: every window is before the fork. + let unscheduled = Store::init_beacon( + Arc::new(InMemoryBackend::new()), + 0, + Config::mainnet(), + H256::ZERO, + Store::beacon_checkpoint_as_stored(BeaconCheckpoint::default()), + 0, ); + let envelopes = unscheduled.canonical_execution_payload_envelopes(0, u64::MAX); + assert_eq!(envelopes.remaining(), 0); } #[test] diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 13a2bb1dc..ffea88c54 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -769,12 +769,13 @@ 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 | | --- | --- | -| `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 @@ -783,6 +784,71 @@ 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 in slot order, and a prefix of the window +except where a row was deleted after the answer was planned (a payload the +execution client found invalid, `Store::remove_verified_payload`) or is too +large for one chunk: such a row is passed over and the answer goes on past it, +leaving a gap. + +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; +the block after the window's last is found with one seek of `BlockRoots`, not a +read per empty slot, since the gap to it is the chain's and has no bound), +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. The reads run on +the connection's task, as every response's encoding and compression do: each +waits on the peer taking the chunk before it, so the work is paced by this +node's uplink rather than by how much peers ask for. A row that fails to +read or to decode, the head's included, ends the answer where it is rather than +failing the stream, so the peer keeps what it was sent: every row is decoded +before it goes out, since a requester that cannot decode one chunk drops the +whole answer. + +The plan starts at the gloas fork's first slot, whatever the request names. +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 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 is +decoded before it goes out, as a by-range row is, and one that does not decode +ends the answer where it is. + +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 of SSZ an answer. That bounds bytes, not +memory: decoded, an empty transaction is a 24-byte `Vec` where its SSZ is a +4-byte offset, so envelopes packed with them hold about six times what was +counted. 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 a lookup with the block fetch's dedup, peer choice and retry ladder; a give-up @@ -792,7 +858,46 @@ 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. The span +runs from the batch's first slot to its highest block handed to the actor, not +to the end the batch asked for: past that block there is no envelope, and a +span reaching into those slots (the batch at the peer's head, one ending in +missed slots) would have an answer that stops at that block followed up for +nothing. Within the span, a last block whose payload is not on the chain (never +revealed, or not built on) looks the same from the requester's side as an +answer stopped at a limit, and costs one request that comes back empty. + +Only the tail is asked for again. An answer can also leave an envelope out +before its last one, which a server following the specification does not do +("MUST be sent in consecutive order"). Some of that shows: every canonical +payload builds on the one before it, so two neighbouring envelopes whose +`parent_hash` and `block_hash` do not link have one missing between them +(`unlinked_neighbours`, logged at `debug`). An answer that skips the window's +first envelopes looks like any other. Neither is asked of the same peer again: +it was asked for those slots and sent what lies on both sides of them, so it +does not hold the envelope or will not send it, and another request would only +keep the next batch waiting. A peer set on withholding can answer empty just as +well. What is left out comes by root from other peers, as soon as the chain +actor holds the child of a block missing its payload. + +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.