Skip to content

fix(p2p): bound envelopes-by-range answers by bytes and read them as they are sent - #956

Merged
pablodeymo merged 10 commits into
mainfrom
fix/envelopes-by-range-byte-budget
Dec 2, 2026
Merged

pablodeymo merged 10 commits into
mainfrom
fix/envelopes-by-range-byte-budget

Conversation

@pablodeymo

@pablodeymo pablodeymo commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #895.

Motivation

execution_payload_envelopes_by_range answered with every canonical envelope in the window, up to MAX_REQUEST_PAYLOADS (128), and the P2P actor collected them all in memory before responding. Nothing bounded their total size.

  • An execution block may be 8 MiB of RLP (EIP-7934), so one request could make the node load and send about 1 GiB.
  • The requester has the request-response layer's 10 seconds for the whole exchange, so an answer that large could not arrive anyway, and one that misses the timeout is lost entirely.

What changed

A byte budget on the answer (req_resp/envelopes.rs)

  • The answer stops once ENVELOPES_BY_RANGE_BYTE_BUDGET (16 MiB of SSZ, before compression) has gone out. The specification allows it: "Clients MAY limit the number of payload envelopes in the response".
  • It always carries the first envelope the window has ("Clients MUST respond with at least the first [...] that exists in the range"), and overshoots by less than one envelope, so one answer sends under 26 MiB.
  • What it sends is a prefix of the window, in slot order.
  • The 16 MiB value is a judgement call, not from the issue: sending less and being asked again costs a round trip, where sending too much costs the whole answer.

Envelopes are read as they are sent (storage/src/store.rs, req_resp/codec.rs, beacon/encoding.rs)

  • Store::canonical_execution_payload_envelopes now returns a plan (CanonicalEnvelopes): the canonical blocks of the window and the parent_block_hash each successor builds on, from one view. It reads rows one at a time as an iterator.
  • The handler hands the codec that plan in a write-only ResponsePayload::ExecutionPayloadEnvelopesByRange, and the codec reads each row just before writing its chunk. The answer is never in memory whole, the P2P actor reads no envelope, and a peer that stops reading stops the reads.
  • Planning does not touch Table::ExecutionPayloadEnvelopes, not even for an existence check: on RocksDB contains is a pinned get, which loads the value. A block with no envelope is passed over at its turn, for one point read that misses.
  • The rows go on the wire as stored, with no re-encode. Each is decoded first, the head's included, so a corrupt row ends the answer instead of going out as a chunk the requester cannot decode (which would cost it the envelopes sent before).
  • The plan starts at the gloas fork's first slot. Planning decodes the block after each one for its bid, and a pre-gloas block carries its whole execution payload, so a pre-gloas window would have had the P2P actor decode up to 128 full blocks to answer nothing. A window that ends before gloas, or any window on a chain that does not schedule gloas (mainnet, Hoodi), reads nothing.
  • The canonical block after the window's last, whose bid decides that block's payload, is found with one seek of BlockRoots (StorageReadView::first_at_or_after, new on both backends). It was a read per slot up to the head, so a window ending before a run of empty slots cost a read per slot of the run on the P2P actor.
  • A row that fails to read or decode ends the answer where it is. It used to be an expect, and it now runs on the connection task, where a panic takes the swarm down.

The requester asks again after a short answer (req_resp/envelope_client.rs)

  • An answer that stops before the end of the span is followed by a request to the same peer for the slots after its last envelope, once the first answer has been checked and forwarded. Range sync's next batch stays held meanwhile.
  • Before, a short answer released the batch and left the rest to by-root lookups, one per held block.
  • Each follow-up starts past the last envelope received, so a span takes at most one request per slot.
  • 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 an envelope counts as progress before any check of it, so unbounded, a peer answering one envelope per request could hold a 128-slot batch for about 21 minutes.
  • A session's last batch is followed up too. That batch exhausts the session, so its envelope 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.

Docs. docs/beacon_wire.md and CLAUDE.md.

Behaviour preserved

  • With an unlimited budget, the set and order of envelopes served for a window is what main served: the successor's bid parent_block_hash must equal the payload's block_hash, the head's envelope is served only on the FULL node, and the successor of the window's last block is searched for past end_slot.
  • Refusals are unchanged: a zero count is INVALID_REQUEST, a start_slot below the anchor is RESOURCE_UNAVAILABLE, and a count over MAX_REQUEST_PAYLOADS is truncated.
  • The context epoch of a by-range chunk now comes from the row's key (the block's slot) instead of payload.slot_number. The two are equal for a stored envelope.

Limits

  • execution_payload_envelopes_by_root still collects up to 128 envelopes with no byte bound, and does not deduplicate roots, so a request naming one large block's root 128 times loads about 1 GiB. Out of this issue's scope; fix(p2p): bound envelopes-by-root answers by bytes and read them as they are sent #958, stacked on this PR, fixes it.
  • The requester's reader still accepts up to 128 chunks of MAX_PAYLOAD_SIZE with no total cap. Unchanged here.
  • No test drives the full path from a received short answer through the completion callback to the follow-up request, because that needs a live actor Context. The pieces on either side are tested.
  • Not run against a live peer or a devnet. Whether a full-budget answer fits the 10 s exchange on a slow uplink is not measured.

Testing

  • make fmt, make lint and make test-node pass (2,846 passed, 0 failed, 9 ignored). make test-consensus and make test-ethrex were not run locally; the changed crates (ethlambda-storage, ethlambda-p2p) are in the test-node half. CI runs all three.
  • New storage test: planning makes no read or existence check on the envelope table (counted through CountingBackend), each step reads one row, and a corrupt row is an error rather than a panic.
  • New serving tests: the budget boundary (one byte under, exactly, one byte over), the first envelope under any budget, a row rewritten after planning is read at send time, a corrupt row ends the answer, an oversized envelope is skipped without being charged, and the answer round-trips through Codec::write_response and read_response.
  • New requester tests: the unanswered tail of an answer, the follow-up request and its deadline, the last batch of a session, a session ended for cause, and a span meeting another session.
  • Review follow-up (48d959b8), both findings of the automated review: a window before gloas reads no block (read counts through CountingBackend; the test fails without the clamp), a chain with no gloas scheduled answers empty, and a corrupt row at a FULL head is an error.
  • Second review follow-up (fa8aa614, f496f53d): planning a window whose next block is 100,000 slots on makes one seek and no read for the gap (counted through CountingBackend), and the shared backend suite runs first_at_or_after on RocksDB and in memory.

…they are sent

`execution_payload_envelopes_by_range` answered with every canonical
envelope in the window, up to `MAX_REQUEST_PAYLOADS` (128), collected in
memory by the P2P actor before responding. An execution block may be
8 MiB, so one request could make the node load and send about 1 GiB.

Server:
- The answer stops once `ENVELOPES_BY_RANGE_BYTE_BUDGET` (16 MiB of SSZ)
  has gone out. It always carries the first envelope the window has and
  overshoots by less than one envelope.
- The handler only plans the answer. The codec reads each envelope row as
  it writes that chunk (`EnvelopesByRange`, `CanonicalEnvelopes`), so the
  answer is never in memory whole and the P2P actor reads no envelope.
  Planning does not touch the envelope table: on RocksDB an existence
  check loads the value it finds.
- A row that fails to read ends the answer where it is, instead of a
  panic.

Requester:
- An answer that stops short of the span is followed by a request to the
  same peer for the slots after its last envelope, with range sync's next
  batch still held, for up to `ENVELOPE_FOLLOW_UP_WINDOW` (30 s).
- A session's last batch is followed up too; a session ended for cause is
  not, and neither is a span once another session runs.

Closes #895
@pablodeymo

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

AI security review: 2 finding(s) to check

Reviewed by Opus, GPT, Kimi, GLM, DeepSeek. A judge model checked every one of the findings against the code.

# Finding Severity Status Found by Where
M3 Pre-Gloas requests decode whole blocks before the byte budget applies medium Bug Opus, GPT (2/5) crates/storage/src/store.rs:4599
M4 Corrupt FULL-head rows are transmitted instead of ending the answer low Bug DeepSeek, GLM, GPT (3/5) crates/storage/src/store.rs:1306
Details

M3. Pre-Gloas requests decode whole blocks before the byte budget applies (medium, DoS/resource)

  • Trigger: A connected peer repeatedly sends ExecutionPayloadEnvelopesByRange requests for retained pre-Gloas slots, with count 128 and start_slot at or above the anchor. The protocol is registered on beacon nodes without requiring the requested window to reach Gloas.
  • Mechanism: Planning now reads and fully decodes every successor before discovering that pre-Gloas blocks have no bid. Despite its name, BlockHeaders stores the entire signed beacon block, including its execution payload before Gloas. The handler performs this work synchronously on the P2P actor, before constructing the byte-budgeted answer. Count truncation limits the number of blocks but not their aggregate bytes, and neither the beacon-store guard nor request handling rejects pre-Gloas windows. Previously, missing envelope rows caused these blocks to be skipped before successor decoding.
  • Impact: An answer containing no envelopes can require reading and decoding hundreds of megabytes, approaching a gigabyte for 128 large blocks. Repeated small requests can monopolize disk/CPU and stall the P2P actor, entirely outside the new 16 MiB response budget.
  • Judge: Confirmed regression. Planning synchronously reads and fully decodes each canonical successor before checking its fork, including pre-Gloas blocks containing execution payloads. This work occurs before the response byte budget applies. Base skipped successor decoding when the current block had no envelope row, although its separate head decode already existed. Both reports describe this same added

M4. Corrupt FULL-head rows are transmitted instead of ending the answer (low, logic)

  • Trigger: Local storage corruption leaves an invalid SSZ envelope row smaller than the chunk limit for the head while its recorded payload status remains Full. A peer requests a range containing that head, potentially after valid earlier envelopes.
  • Mechanism: Only BuiltOnBy candidates are decoded. FullHead returns the stored bytes unchecked, EnvelopesByRange::next_envelope checks only their size, and write_envelopes_by_range_response sends them verbatim. Consequently, this case never reaches the error handling intended to terminate the response cleanly at a corrupt row. The receiving decode_execution_payload_envelopes_response rejects the malformed SSZ, and read_chunked_response propagates that error without returning previously decoded envelopes.
  • Impact: The node emits a malformed response and causes the requester to lose the valid prefix already transmitted, rather than preserving it and stopping before the damaged row. Requests reaching the damaged head continue to fail until the row is repaired or removed.
  • Judge: Confirmed under the stated local-corruption assumption. FullHead bypasses SSZ validation, so a malformed row within the chunk-size limit is emitted as a success chunk instead of cleanly ending the answer. The receiving decoder then returns an error and loses the valid prefix. All reports describe the same new unchecked raw-byte path; base decoded the row before serving it.
Pre-existing (real, but already on the base branch): 2
# Finding Category Severity (reported → judged) Found by Where Judge's reason
M1 Envelope responses can collect about 1.28 GiB in memory DoS/resource high GLM (1/5) crates/net/p2p/src/beacon/encoding.rs:483 Confirmed on both base and head. Both envelope protocols accept up to 128 chunks of 10 MiB each and retain decoded envelopes before request-specific validation, allowing roughly 1.25 GiB plus decoding overhead. The PR's outbound by-range budget does not constrain inbound responses.
M2 By-root envelope service still loads and sends up to 128 large envelopes without a byte budget or root deduplication DoS/resource medium DeepSeek (1/5) crates/net/p2p/src/req_resp/envelopes.rs:270 Confirmed; the by-root implementation is unchanged from base. Duplicate roots each cause a separate envelope read and decode, and all results are collected before transmission. Only individual chunks have a size limit, so one request can materialize and attempt to transmit around a gigabyte when sufficiently large stored envelopes exist.
Housekeeping (not security): 1

Stale docs, missing tests, leftovers and inconsistencies, from a separate cheap model. Not checked by the judge.

Kind Item Where Fix
stale-docs protocols.rs says 'Nothing requests them yet' but the PR adds client-side envelope requests crates/net/p2p/src/beacon/protocols.rs:14 Update the comment to say something like: '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, and the client requests them after a gloas span's blocks arrive (by range) and on d

Cost of this review: ~$3.85 of a $30 budget (estimated from token counts).

…ery row sent

Two findings from the review of this branch.

Planning an answer decodes the block after each one it looks at, for its
bid. Before gloas that block carries a whole execution payload, and nothing
kept a window out of those slots, so a peer asking for 128 pre-gloas slots
had the P2P actor decode 128 full blocks to answer nothing, outside the byte
budget. The envelope-table existence check this branch removed used to skip
them. The plan now starts at the gloas fork's first slot; a window that ends
before it, or any window on a chain that does not schedule gloas, reads
nothing.

The head's envelope was sent without being decoded, since no successor's bid
needs a field out of it. A corrupt row there went out as a chunk, and the
requester, failing to decode it, dropped the envelopes before it too. Every
row is now decoded before it is sent, so a corrupt one ends the answer.

Also corrects protocols.rs, which still said nothing requests the envelope
protocols.
@pablodeymo

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

AI security review: 1 finding(s) to check

Reviewed by Opus, GPT, Kimi, GLM, DeepSeek. A judge model checked every one of the findings against the code.

# Finding Severity Status Found by Where
M4 Unbounded BlockRoots successor scan on crafted by-range window medium Bug DeepSeek (1/5) crates/storage/src/store.rs:4614
Details

M4. Unbounded BlockRoots successor scan on crafted by-range window (medium, DoS/resource)

  • Trigger: A connected peer sends an inbound ExecutionPayloadEnvelopesByRange request whose 128-slot window includes a canonical block but ends just before a stretch of empty slots, so the next canonical root is far later (or the head is far ahead).
  • Mechanism: BlockRoots only stores entries for slots that actually have canonical blocks. canonical_root performs a blocking view.get per slot, so find_map issues one DB point read for every skipped slot from end_slot+1 up to head_slot. The scan has no request-count/byte bound and runs synchronously in the handler before responding. The old code skipped this scan when the last window block had no stored envelope row; the new planner deliberately avoids touching the envelope table and therefore always runs it for any non-empty window.
  • Impact: A crafted request can force thousands or more BlockRoots point reads on the swarm actor, causing CPU/DB-I/O DoS. Up to 32 concurrent streams per connection and many peer connections amplify the effect.
  • Judge: Confirmed for the newly enabled missing-envelope case. The base required the last window block to have a stored envelope before scanning; this PR removes that guard and scans for every nonempty post-Gloas window. Across a long empty-slot gap, it performs synchronous point reads beyond the 128-slot request limit. The same scan was already vulnerable for envelope-bearing windows, but the missing-row
Duplicates folded into another finding: 1
# Same as Finding Found by Where
M3 M2 Skipped empty-branch envelopes bypass the storage-work budget GPT crates/storage/src/store.rs:1330
Pre-existing (real, but already on the base branch): 2
# Finding Category Severity (reported → judged) Found by Where Judge's reason
M1 By-range envelope responses have no aggregate memory bound DoS/resource high GLM (1/5) crates/net/p2p/src/beacon/encoding.rs:483 Confirmed: up to 128 independently bounded 10 MiB chunks are decoded and retained until EOF, without an aggregate-byte budget or envelope verification before accumulation. The base has the same decoder and accumulation loop; the new budget restricts outbound answers only.
M2 Byte budget does not bound reading and decoding non-canonical envelopes DoS/resource medium GPT, DeepSeek (2/5) crates/storage/src/store.rs:1309 Confirmed for canonical blocks whose successors chose their empty payload branches: entire rows are loaded and decoded before rejection, and rejected rows do not consume the response budget. Arbitrary orphaned-block rows are not candidates because planning uses canonical BlockRoots. The base already loaded and decoded rows before applying the same branch test.

Cost of this review: ~$4.69 of a $30 budget (estimated from token counts).

Planning a by-range answer needs the canonical block after the window's
last, to judge that block's payload by the bid built on it. It looked for
it with one BlockRoots read per slot from the window's end to the head. The
index has no row for an empty slot, so a window ending before a run of them
cost a read per slot of the run, on the P2P actor, bounded by nothing in the
request. Before this branch the scan ran only when the window's last block
had an envelope row; without the envelope-table check it ran for every
window that held a block.

StorageReadView gains first_at_or_after, the first entry at or after a key
in the table's key order (a RocksDB iterator seek; a minimum over the map
in memory), and the planner asks it once. The backend test suite covers it
on both backends.
…choice test view

The previous commit did not pass lint: clippy rejects first_at_or_after's
return type as too complex, and the read view the fork-choice tests wrap a
backend in did not implement the new method, so the state-transition test
target did not compile. The key and value pair is now `Entry` (exported as
`StorageEntry`), and that view forwards the seek.
@pablodeymo

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

AI security review: 1 finding(s) to check

Reviewed by Opus, GPT, Kimi, GLM, DeepSeek. A judge model checked every one of the findings against the code.
Malicious-code check (tests, build and install scripts, hooks, editor tasks, dependency sources): nothing found.

# Finding Severity Status Found by Where
M3 A high-slot envelope suppresses follow-ups for earlier omissions low Bug Kimi (1/5) crates/net/p2p/src/req_resp/envelope_client.rs:160
Details

M3. A high-slot envelope suppresses follow-ups for earlier omissions (low, logic)

  • Trigger: A remote peer answering ExecutionPayloadEnvelopesByRange omits envelopes from earlier requested slots but includes an envelope at or near end_slot; this enters through handle_envelopes_by_range_response.
  • Mechanism: retain_envelopes_in_range filters and sorts the peer's chunks but does not verify that they form a consecutive prefix. Consequently, envelopes.last() is the highest returned slot, not evidence that every earlier envelope was delivered. An answer containing only slot end_slot, or one containing slots 10 and 20 in a 10..=20 request, produces rest == None; neither the per-envelope gossip checks nor any later response-completeness check detects the omissions.
  • Impact: The client releases the range envelope gate without requesting the omitted tail, defeating the new short-answer recovery for those slots. The missing envelopes fall back to slower per-root fetches and may arrive after subsequent batch delivery rather than under the intended ordering gate.
  • Judge: Confirmed for actual omissions, as distinct from legitimate slots without envelopes. Filtering and sorting leave the highest returned slot last, and follow-up selection considers only that slot. Returning end_slot suppresses follow-ups for all earlier omissions; returning near it requests only later slots. Per-envelope checks do not establish response completeness. By-root recovery limits the impa
Pre-existing (real, but already on the base branch): 2
# Finding Category Severity (reported → judged) Found by Where Judge's reason
M1 Inbound envelope responses have no aggregate memory cap DoS/resource high GLM (1/5) crates/net/p2p/src/beacon/encoding.rs:481 Confirmed: the reader retains up to 128 decoded envelopes, each allowing a 10 MiB SSZ payload, without an aggregate-byte limit. Fork-context checks do not prevent large, structurally valid chunks. The decoder and accumulation loop are unchanged from the base; the new outbound response budget does not protect this path.
M2 By-root envelope requests can force a roughly 1 GiB response collection DoS/resource high GLM (1/5) crates/net/p2p/src/req_resp/envelopes.rs:270 Confirmed: a decoded root list preserves duplicates, and each of its 128 entries causes a separate owned envelope decode that is collected before transmission. Repeating a known large envelope root therefore creates gigabyte-scale retention. The by-root handler, collection function, and storage decoding behavior already exist on the base.
Housekeeping (not security): 1

Stale docs, missing tests, leftovers and inconsistencies, from a separate cheap model. Not checked by the judge.

Kind Item Where Fix
stale-docs ExecutionPayloadEnvelopes variant doc says it answers either envelope protocol crates/net/p2p/src/req_resp/messages.rs:301 Change to something like '/// The envelopes answering the by-root protocol (and, when read off the wire, either envelope protocol).' or '/// The envelopes answering execution_payload_envelopes_by_root.' to match the new split.

Cost of this review: ~$3.88 of a $30 budget (estimated from token counts).

…why it is not asked for again

A short `ExecutionPayloadEnvelopesByRange` answer is followed by a request for
the slots after its last envelope. The code took the answer for a prefix of
the window without checking, so a peer that left an envelope out before its
last one was not noticed, and the comments said the answer is a prefix.

Every canonical payload builds on the one before it (`payload.parent_hash` is
`state.latest_block_hash`), so two neighbouring envelopes that do not link
have one missing between them. `unlinked_neighbours` finds that and the
handler logs it at `debug`.

The follow-up is unchanged, on purpose: only the tail is asked for again. The
peer was asked for those slots and sent what lies on both sides of them, so
another request to it would only keep range sync's next batch waiting, and 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. An answer that skips the window's first envelopes
cannot be told from any other. The comments and `docs/beacon_wire.md` now say
all of this.

Also corrects the doc of `ResponsePayload::ExecutionPayloadEnvelopes`, which
no longer answers the by-range protocol on the sending side.
@pablodeymo

Copy link
Copy Markdown
Collaborator Author

On M3 (a high-slot envelope suppresses follow-ups for earlier omissions)

The mechanism is right: the follow-up is computed from the answer's last envelope, and nothing checked that the answer is a prefix of the window. cb0db296 addresses it, but not by asking again for what was left out. That is deliberate.

What changed

  • An answer that leaves a payload out between two it carries is now detected. Every canonical payload builds on the one before it (payload.parent_hash == state.latest_block_hash, verify_execution_payload_envelope), so two neighbouring envelopes that do not link have one missing between them. unlinked_neighbours finds that and the handler logs it at debug with the peer and both slots.
  • The comments and docs/beacon_wire.md no longer say the answer is a prefix. They say only the tail is asked for again, and why.
  • Test: a_range_answer_missing_a_payload_between_two_it_carries_is_noticed (a linked run with empty slots between is not flagged; a run missing a payload is flagged, and still not asked for again).

Why the same peer is not asked again for the gap

  • It was asked for those slots and sent the envelopes on both sides of them. It does not hold the missing one, or will not send it. Our own server produces such an answer when a canonical block has no envelope row: it passes over the block and goes on.
  • A peer set on withholding can answer empty, which gets no follow-up either. A re-ask closes nothing for that case.
  • Follow-ups keep range sync's next batch waiting, so a request that cannot succeed has a cost.
  • The envelope is recovered from other peers already: the chain actor asks by root as soon as the child of a block missing its payload is held, and again every slot. That is what every short answer got before this PR.

What is not covered

An answer that skips the window's first envelopes (for example, only the last slot's) cannot be told from an honest one this way: there is no earlier envelope in the answer to link to. It falls back to the same by-root path.

Asking a different peer by range for just the gap would be a real recovery, but it needs more than one outstanding request under the gate that holds the next batch. Not done here.

…hey are sent (#958)

Stacked on #956. Review and merge that one first; this PR's diff is only
the by-root part.

## Motivation

#956 bounds `execution_payload_envelopes_by_range` (#895).
`execution_payload_envelopes_by_root` has the same shape and was left
open there:

- It collected up to `MAX_REQUEST_PAYLOADS` (128) decoded envelopes in
the P2P actor, with no bound on their total size.
- It answered a root once per mention. A request naming one large
block's root 128 times loaded about 1 GiB from a single stored envelope.

## What changed

**The by-root answer uses the by-range mechanism**
(`req_resp/envelopes.rs`, `storage/src/store.rs`)

- The answer stops once `ENVELOPES_BY_ROOT_BYTE_BUDGET` has gone out. It
is the range's 16 MiB of SSZ, for the same reasons. The specification
allows it ("Clients MAY limit the number of payload envelopes in the
response") and asks for "at least one payload envelope, if they have
it", which stopping only once the budget is spent gives.
- The handler only resolves each root to its block's slot
(`Store::execution_payload_envelopes_of`). The codec reads each envelope
row as it writes that chunk (`EnvelopesByRoot`), so the answer is never
in memory whole and the P2P actor reads no envelope.
- `EnvelopeAnswer<I>` is the budgeted answer both protocols now share.
`EnvelopesByRange` and `EnvelopesByRoot` are aliases over where the
envelopes come from. The budget, the oversized-envelope skip and the
end-on-read-failure rule are written once.
- A row is not decoded on the by-root path, since there is no chain rule
to apply. It goes on the wire as stored.

**A repeated root 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.

**The requester stops reading an answer at a byte budget**
(`req_resp/encoding.rs`, `beacon/encoding.rs`)

- A peer may send `MAX_REQUEST_PAYLOADS` chunks of `MAX_PAYLOAD_SIZE` to
either envelope protocol, whatever was asked, and the reader held every
decoded envelope until the stream ended: about 1.25 GiB for one request.
The automated review listed this as present on `main`.
- `ChunkLimits` gains `max_bytes`. Envelope answers are read under
`ENVELOPE_RESPONSE_BYTE_BUDGET`, the servers' 16 MiB: the envelope that
crosses it is kept, so the first always is, and one answer holds under
26 MiB.
- A longer answer is cut, not refused, and reads as a short one. By
range the requester already asks again for the slots after its last
envelope (#956); by root this node names one root a request.

**Docs.** `docs/beacon_wire.md` and `CLAUDE.md`.

## Behaviour preserved

- Unknown roots are left out, the answer follows the order asked, and no
more than `MAX_REQUEST_PAYLOADS` roots are looked at.
- By root there is still no chain rule: an envelope the canonical chain
did not build on is served when asked for by name.
- This node's own by-root requests name a single root, so its requester
is never cut short and needs no change.

## Limits

- Another client that asks for many large envelopes by root in one
request now gets a short answer and has to ask again for the rest. The
specification allows the short answer; how each client handles it was
not checked.
- A by-root row goes out as stored, without the decode a by-range row
gets in #956, so a corrupt row would be sent as a chunk the requester
cannot decode.
- The block and data-column readers still read to their chunk limits
with no byte cap; only the envelope reader is bounded here.
- Not run against a live peer or a devnet.

## Testing

- `make fmt`, `make lint` and `make test-node` pass (2,853 passed, 0
failed, 9 ignored). `make test-consensus` and `make test-ethrex` were
not run locally; the changed crates (`ethlambda-storage`,
`ethlambda-p2p`) are in the `test-node` half.
- New storage test: planning a by-root answer makes no read or existence
check on the envelope table, each step reads one row in the order named,
and roots with no block or no envelope are passed over.
- New serving tests: a repeated root is answered once, the budget
boundary and the first envelope under any budget, an envelope the chain
did not build on is still served by name, and the answer round-trips
through `Codec::write_response` and `read_response`.
- New reader test: a four-envelope answer read under a budget exactly on
an envelope boundary, one byte under, one byte over, and near zero; the
first envelope is always read.
@pablodeymo

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

AI security review: 1 finding(s) to check

Reviewed by Opus, GPT, Kimi. A judge model checked every one of the findings against the code.
DeepSeek (unreadable answer), GLM (error, see the run log) did not finish; Opus, GPT, Kimi reviewed the whole PR. Comment /review continue to retry, with a new budget; reviewers that finished are reused.
Malicious-code check (tests, build and install scripts, hooks, editor tasks, dependency sources): nothing found.

# Finding Severity Status Found by Where
M2 By-root answers send stored envelope rows without decoding them, so one corrupt row makes the requester throw away the w low Bug Opus (1/3) crates/storage/src/store.rs:1349
Details

M2. By-root answers send stored envelope rows without decoding them, so one corrupt row makes the requester throw away the whole answer (low, logic)

  • Trigger: Only local storage corruption: a row in Table::ExecutionPayloadEnvelopes that no longer decodes. A peer then sends an execution_payload_envelopes_by_root request that names that block among other roots. The request goes through handle_execution_payload_envelopes_by_root_request → envelopes_by_root_within → Store::execution_payload_envelopes_of.
  • Mechanism: EnvelopesOfBlocks::read puts the raw row into a StoredEnvelope without decoding it. EnvelopeAnswer::next_envelope checks only its size, and write_stored_envelopes_response writes it as a SUCCESS chunk. On the requester's side, read_chunked_response stops at the first chunk whose decode fails (items.push(decode(context, &payload)?)) and returns Err, so the valid envelopes already received are lost too. The by-range path, CanonicalEnvelopes::read, decodes every row first for exactly this reason (its comment: "a requester that cannot decode one chunk drops the envelopes that came before it as well"). The by-root path has no such check.
  • Impact: A peer that asks for several roots in one request (other clients do; this node asks for one) loses every envelope in the answer, not just the corrupt one. It will keep losing them every time it asks this node, until the row is repaired. Before this PR the same corrupt row panicked the P2P actor (expect("a stored envelope decodes")), so this is milder, but it is not the clean end-of-answer that the by-range path gives.
  • Judge: Confirmed for corruption that returns readable bytes containing malformed SSZ, rather than a storage-read error. By-root iteration wraps those bytes without decoding, the answer checks only chunk size, and the writer sends them as SUCCESS. A requester using this decoder returns Err and loses previously collected envelopes. The range-only validation does not protect this path. The base path panicke
Pre-existing (real, but already on the base branch): 1
# Finding Category Severity (reported → judged) Found by Where Judge's reason
M1 Pin range-planning reads and seeks to one RocksDB snapshot logic medium GPT (1/3) crates/storage/src/backend/rocksdb.rs:212 The race is real, but already exists on the base branch. RocksDB read views hold no snapshot, and the base implementation also collected canonical roots through separate point reads before checking successor bids. A concurrent checkpoint commit can therefore mix branches in either version. The new seek retains this problem rather than introducing it; payload-link and head-status checks do not esta
Housekeeping (not security): 1

Stale docs, missing tests, leftovers and inconsistencies, from a separate cheap model. Not checked by the judge.

Kind Item Where Fix
missing-test No test exercises the full short-answer -> follow-up request path crates/net/p2p/src/req_resp/envelope_client.rs:271 Add a test that drives an actual ExecutionPayloadEnvelopesByRange response through handle_envelopes_by_range_response and the check-and-forward completion callback to a follow-up EnvelopeRange request on the same peer (including the deadline and session-gate checks). If that needs a live actor Conte

Cost of this review: ~$4.81 of a $30 budget (estimated from token counts).

pablodeymo and others added 3 commits December 2, 2026 01:30
`EnvelopesOfBlocks` handed a stored row over as it was: a by-root answer
applies no chain rule, so nothing is read out of the envelope. The bytes go
on the wire as stored, and a requester that cannot decode one chunk drops
the whole answer, so a corrupt row cost a peer asking for several roots
every envelope sent before it. The by-range reader already decodes each row
for this reason.

Both readers now go through `decode_stored_envelope`, and a by-root row
that does not decode is an error its answer ends at.
The envelopes of a range batch were asked for over the whole span the
batch requested, so an answer that stopped at the batch's last block was
followed up for slots holding no block, and so no envelope: the batch at
the peer's head, or one ending in missed slots, cost a request that could
only come back empty, with range sync held meanwhile. The span now ends at
the highest block handed to the chain actor. The server still judges that
block's payload by its successor past the span, so nothing is lost.

Also:
- `decode_stored_envelope` names the block with `ShortRoot`, as the log
  rule asks, where it formatted the full root.
- `write_stored_envelopes_response` says why the reads stay on the
  connection's task: they are paced by the peer taking each chunk, like
  every response's encoding and compression, and moving them alone to the
  blocking pool would not pay off.
- The repeated-root test gets its doc comment back from the test placed
  between them.
- A by-range answer passes over a row deleted after it was planned, or one
  too large for a chunk, and goes on: it is a prefix of the window only
  without those.
- An envelope row can be written again (a re-delivered envelope is recorded
  again). Reading rows after the plan is still sound because a row's payload
  hash is pinned by its block's bid.
- The reader's 16 MiB budget counts SSZ bytes, not memory: decoded, envelopes
  packed with empty transactions take about six times as much.
@pablodeymo
pablodeymo enabled auto-merge December 2, 2026 18:00
@pablodeymo
pablodeymo added this pull request to the merge queue Dec 2, 2026
Merged via the queue into main with commit acdc46b Dec 2, 2026
14 checks passed
@pablodeymo
pablodeymo deleted the fix/envelopes-by-range-byte-budget branch December 2, 2026 18:54
pablodeymo added a commit that referenced this pull request Dec 2, 2026
…they are sent (#968)

## 🗒️ Description / Motivation

Backport of #956 to `release/v2.0.0`, for `v2.0.0-rc.2`.

#956 is approved and not merged on `main` yet, so this is taken from its
head (`36232dcf`) and not from a squash commit on `main`. If #956
changes before it merges, this branch has to be refreshed from the new
head.

## What Changed

The ten commits of #956 as one commit on top of `release/v2.0.0`
(`3ed99c86`): the diff from its branch point on `main` (`e48246f8`) to
its head (`36232dcf`), applied with `git apply --3way`. It applied
without conflicts and nothing was edited by hand. That includes #958,
the by-root counterpart, which was merged into #956's branch.

What it does, from #956:

- An `execution_payload_envelopes_by_range` answer stops once 16 MiB of
SSZ has gone out, always carrying the first envelope its window has.
Before, one request could make the node load and send about 1 GiB.
- Envelopes are read as they are sent: the codec reads each row just
before writing its chunk, and a row that fails to read or decode ends
the answer where it is.
- The requester asks the same peer again after an answer that stops
short, for up to 30 s.
- `execution_payload_envelopes_by_root` answers are bounded and read the
same way (#958).

## Tests Added / Run

On this branch:

- `cargo fmt --all -- --check` and `make lint`: clean.
- `cargo test -p ethlambda-p2p --profile release-fast --lib`: 587
passed, 0 failed, 1 ignored.
- `cargo test -p ethlambda-storage --profile release-fast --features
rocksdb`: 256 passed, 0 failed, 2 ignored.

Not run locally: the rest of `make test`.

## Related Issues / PRs

- Original: #956 (closes #895 on `main`), with #958.
- The other PRs open against the release branch: #954, #962 (backport of
#950) and #965 (backport of #952). This one merges with each of them
without conflicts (checked with `git merge-tree`), though it shares
`crates/net/p2p/src/lib.rs`, `CLAUDE.md` and `docs/beacon_wire.md` with
some of them.
- Release checklist: #943.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Envelopes by range: bound the response by bytes, not only by count

2 participants