Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -449,18 +449,22 @@ actual_slot = finalized_slot + 1 + relative_index
mailbox) and the store's head (which gossip imports move and the watermark never sees).
Fetched blocks reach the actor as `BlockSource::Sync`.
- Gloas adds `execution_payload_envelopes_by_{range,root}/1`. Server: canonical FULL
envelopes only, and the head's envelope only when the head node is FULL. A by-range
answer stops once `ENVELOPES_BY_RANGE_BYTE_BUDGET` (16 MiB of SSZ) has gone out, always
carrying the first envelope, and is never in memory whole: the handler plans it and the
codec reads each row as it writes that chunk (`EnvelopesByRange`), decoding every one
before it goes out. The plan starts at gloas's first slot: planning decodes each next
block for its bid, and a pre-gloas block carries its whole payload. Client: by root
envelopes only, and the head's envelope only when the head node is FULL. Either answer
stops once its byte budget (`ENVELOPES_BY_RANGE_BYTE_BUDGET`, 16 MiB of SSZ, and
`ENVELOPES_BY_ROOT_BYTE_BUDGET`, the same) has gone out, always carrying the first
envelope, and is never in memory whole: the handler plans it and the codec reads each
row as it writes that chunk (`EnvelopeAnswer`). A by-range row is decoded before it
goes out, and the range plan starts at gloas's first slot: planning decodes each next
block for its bid, and a pre-gloas block carries its whole payload. A by-root request's
repeated root is answered once. Client: by root
on `needs_envelope` (same dedup and retry ladder as block fetches) and on a gossip vote
for a payload not verified here (at most once a slot per root), by range after a
gloas span's blocks were handed to the actor, with range sync holding the next batch
until the envelope answer is forwarded (the actor keeps unmatched envelopes only briefly);
an answer that stops short of the span is followed by a request for the slots after its
last envelope, the batch still held, for up to `ENVELOPE_FOLLOW_UP_WINDOW` (30 s).
The reader stops at `ENVELOPE_RESPONSE_BYTE_BUDGET` (16 MiB) too, so a peer's longer
answer reads as a short one rather than being held whole.
Their chunks carry four `<context-bytes>` (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)

Expand Down
44 changes: 38 additions & 6 deletions crates/net/p2p/src/beacon/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ use super::protocols::{self, MAX_REQUEST_BLOCKS_DENEB};
use super::size_bounds;
use crate::req_resp::codec::write_success_chunk;
use crate::req_resp::encoding::{ChunkLimits, MAX_PAYLOAD_SIZE, invalid, read_chunked_response};
use crate::req_resp::envelopes::EnvelopesByRange;
use crate::req_resp::envelopes::{ENVELOPE_RESPONSE_BYTE_BUDGET, EnvelopeAnswer};
use crate::req_resp::messages::BlocksByRangeRequest;

/// This chain's wire body for a slot window. Every field is shared, since this
Expand Down Expand Up @@ -209,6 +209,7 @@ where
// The deneb ceiling rather than the phase0 one, because it bounds what
// *this* node asks for and nothing else opens one of these streams.
max_chunks: MAX_REQUEST_BLOCKS_DENEB as usize,
max_bytes: None,
};
read_chunked_response(io, protocol_label, limits, |context, payload| {
let block = decode::decode_block(config, payload)
Expand Down Expand Up @@ -305,6 +306,7 @@ where
// The widest a single request can legitimately ask for, on either
// column protocol; see `protocols::max_request_data_column_sidecars`.
max_chunks: protocols::max_request_data_column_sidecars() as usize,
max_bytes: None,
};
let schedule = ForkSchedule::new(config, genesis_validators_root);
let gloas_bound = size_bounds::max_data_column_sidecar_size(config);
Expand Down Expand Up @@ -421,23 +423,24 @@ where
Ok(())
}

/// Write this node's own `ExecutionPayloadEnvelopesByRange` answer, reading
/// each envelope out of the store just before its chunk goes out.
/// Write one of this node's own envelope answers (by range or by root),
/// reading each envelope out of the store just before its chunk goes out.
///
/// Same chunks as [`write_execution_payload_envelopes_response`], without the
/// answer ever being in memory whole: one envelope is held at a time, and the
/// next is read only once the peer has taken this one. Which envelopes there
/// are, and where the answer stops, is [`EnvelopesByRange`]'s business. The
/// are, and where the answer stops, is [`EnvelopeAnswer`]'s business. The
/// rows go out as stored, with no decode and re-encode in between.
pub async fn write_envelopes_by_range_response<T>(
pub async fn write_stored_envelopes_response<T, I>(
io: &mut T,
label: &'static str,
config: &Config,
genesis_validators_root: Root,
answer: &mut EnvelopesByRange,
answer: &mut EnvelopeAnswer<I>,
) -> io::Result<()>
where
T: AsyncWrite + Unpin + Send,
I: Iterator<Item = Result<ethlambda_storage::StoredEnvelope, ethlambda_storage::Error>> + Send,
{
while let Some(envelope) = answer.next_envelope() {
write_execution_payload_envelope_chunk(
Expand Down Expand Up @@ -469,18 +472,47 @@ fn carries_envelopes(fork: ForkName) -> bool {
/// refused too ([`carries_envelopes`]).
/// The context is then checked against the digest the payload's own
/// `slot_number` implies.
///
/// Reading stops once [`ENVELOPE_RESPONSE_BYTE_BUDGET`] of envelopes has been
/// read: a peer may send `MAX_REQUEST_PAYLOADS` chunks of `MAX_PAYLOAD_SIZE`,
/// over a gigabyte held until the stream ends, whatever was asked for. What
/// was read is returned as the answer, and the rest of the peer's is left
/// unread.
pub async fn decode_execution_payload_envelopes_response<T>(
io: &mut T,
protocol_label: &str,
config: &Config,
genesis_validators_root: Root,
) -> io::Result<Vec<SignedExecutionPayloadEnvelope>>
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<T>(
io: &mut T,
protocol_label: &str,
config: &Config,
genesis_validators_root: Root,
budget: usize,
) -> io::Result<Vec<SignedExecutionPayloadEnvelope>>
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| {
Expand Down
1 change: 1 addition & 0 deletions crates/net/p2p/src/lean/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 14 additions & 3 deletions crates/net/p2p/src/req_resp/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,8 +383,8 @@ impl libp2p::request_response::Codec for Codec {
{
let label = protocol_label(protocol.as_ref());
match resp {
// By `&mut`: the by-range envelope answer is consumed as it is
// written. Every other payload is only read.
// By `&mut`: this node's envelope answers are consumed as they
// are written. Every other payload is only read.
Response::Success { mut payload } => match &mut payload {
ResponsePayload::LeanStatus(status) => {
write_success_chunk(io, label, NO_CONTEXT, lean_encoding::encode_status(status))
Expand Down Expand Up @@ -444,7 +444,18 @@ impl libp2p::request_response::Codec for Codec {
}
ResponsePayload::ExecutionPayloadEnvelopesByRange(answer) => {
let context = self.beacon_context(protocol.as_ref())?;
beacon_encoding::write_envelopes_by_range_response(
beacon_encoding::write_stored_envelopes_response(
io,
label,
&context.config,
context.genesis_validators_root,
answer,
)
.await
}
ResponsePayload::ExecutionPayloadEnvelopesByRoot(answer) => {
let context = self.beacon_context(protocol.as_ref())?;
beacon_encoding::write_stored_envelopes_response(
io,
label,
&context.config,
Expand Down
24 changes: 23 additions & 1 deletion crates/net/p2p/src/req_resp/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
}

/// Read a response that is one chunk per item, until the peer closes.
Expand All @@ -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.
Expand All @@ -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 {
Expand Down Expand Up @@ -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(),
Expand Down
Loading
Loading