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: 14 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<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
8 changes: 8 additions & 0 deletions crates/blockchain/state_transition/src/beacon/fork_choice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<ethlambda_storage::StorageEntry>, StorageError> {
self.inner.first_at_or_after(table, key)
}
}

/// The first head computation after a restart fills the payload links by
Expand Down
120 changes: 111 additions & 9 deletions crates/net/p2p/src/beacon/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<T>(
io: &mut T,
label: &'static str,
config: &Config,
genesis_validators_root: Root,
slot: u64,
encoded: Vec<u8>,
) -> 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<T>(
io: &mut T,
Expand All @@ -372,20 +402,63 @@ 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(),
"Skipping oversized execution payload envelope in response"
);
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<T, I>(
io: &mut T,
label: &'static str,
config: &Config,
genesis_validators_root: Root,
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(
io,
label,
config,
genesis_validators_root,
envelope.slot,
envelope.ssz,
)
.await?;
}
Ok(())
}
Expand All @@ -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<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
4 changes: 3 additions & 1 deletion crates/net/p2p/src/beacon/protocols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
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
32 changes: 23 additions & 9 deletions crates/net/p2p/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
/// 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,
},
}

Expand Down Expand Up @@ -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<u64>,
rest: Option<req_resp::UnansweredEnvelopes>,
) -> 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
Expand Down Expand Up @@ -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<Self>,
) {
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]
Expand Down
26 changes: 25 additions & 1 deletion crates/net/p2p/src/req_resp/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading