Skip to content

feat(p2p): refuse execution payloads whose block hash is not their header's - #770

Draft
MegaRedHand wants to merge 24 commits into
mainfrom
feat/gossip-payload-block-hash
Draft

MegaRedHand wants to merge 24 commits into
mainfrom
feat/gossip-payload-block-hash

Conversation

@MegaRedHand

@MegaRedHand MegaRedHand commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

What

Beacon p2p rebuilds the execution block header from a payload's own fields and compares
keccak256(rlp(header)) with the payload's block_hash:

  • pre-gloas beacon_block gossip (bellatrix to fulu), at the end of the stateful checks and
    only when they answered Accept, so the proposer signature has verified. A mismatch is
    IGNOREd (IgnoreReason::PayloadBlockHashMismatch, payload_block_hash_mismatch): not
    imported from gossip, not relayed, no peer scored.
  • gloas envelopes, from gossip and from by-root/by-range fetches, at the same point (after
    the builder signature). A mismatch is only counted and logged until the Amsterdam header
    is final.

Not checked: blocks fetched by range or root, and gossip blocks answered Queue or forwarded
under Overloaded. Counter lean_beacon_payload_block_hash_mismatch_total{kind} and a
warn! with slot and root. Code in crates/net/p2p/src/beacon/payload_hash.rs
(verify_block, verify_envelope, block_verdict, envelope_verdict), in p2p rather than
state_transition::gossip::* so the spec gossip fixtures (arbitrary payload hashes) are
unaffected. Header encoding with ethrex-rlp's Encoder (ethrex's BlockHeader holds
base_fee_per_gas as u64); trie roots from ethrex-common and ethrex-trie (v25.0.0,
already in the lockfile). bellatrix::ExecutionPayload gains a Default impl for the
pre-merge skip.

Why

The Engine API already requires the execution client to validate blockHash on every
newPayload, even while syncing (paris.md), so while an import waits for that answer this
catches nothing the EL would not. It exists for the early fork-choice import in #773, which
applies a payload before the EL answers and reverts it on INVALID: a gossip block caught here
saves that path a revert.

Deviation

Stricter than the consensus-specs gossip rules; IGNORE rather than REJECT because other
clients relay such blocks. Documented in docs/spec_deviations.md ("A payload's block hash
must be its header's") and docs/beacon_wire.md.

Header per fork

bellatrix: London fields; capella: withdrawals_root; deneb: blob_gas_used, excess_blob_gas, parent_beacon_block_root (the block's parent_root); electra/fulu: requests_hash (from the Engine API request list); gloas: block_access_list_hash (keccak of the payload's BAL bytes, EIP-7928) and slot_number (EIP-7843), parent root from the envelope. A bellatrix block with the empty default payload (pre-merge) is skipped.

Real-chain vectors (SSZ, crates/net/p2p/src/beacon/testdata/payload_hash/)

Fork Chain Object Source
bellatrix Sepolia block, slot 500000 lodestar-sepolia.chainsafe.io
capella Sepolia block, slot 1900000 (withdrawals) lodestar-sepolia.chainsafe.io
deneb Hoodi block, slot 2003 lodestar-hoodi.chainsafe.io
electra Hoodi block, slot 70001 lodestar-hoodi.chainsafe.io
fulu mainnet block, slot 15684701 (238 txs, 1 withdrawal + 2 consolidation requests) ethlambda-4 beacon API, byte-identical to lodestar-mainnet.chainsafe.io
gloas Platåberget envelope, slot 593101 ethlambda-3 beacon API

Each vector must match, and per fork a changed field must be refused. Also checked locally
(not committed): 200 consecutive finalized mainnet blocks (15684600-15684799), all match.

Cost

payload_hash::tests::verify_block_cost (ignored): ~0.24 ms on the fulu vector; at the
10 MiB gossip limit 11 ms (one tx), 19 ms (~15k mainnet-sized txs), 0.6 s (1,048,576
five-byte txs, worst case). M3 Pro, release-fast, shared machine at load ~20.

Testing

cargo fmt --all, cargo clippy --workspace --all-targets -- -D warnings,
cargo test --profile release-fast -p ethlambda-p2p -p ethlambda-types -p ethlambda-state-transition.
No leanSpec or consensus-spec fixtures were run.

…ader's

Rebuild the execution block header from a payload's own fields and reject
the message when keccak256(rlp(header)) differs from the claimed
block_hash. Runs on pre-gloas beacon_block gossip (bellatrix to fulu), on
gloas execution_payload gossip, and on every envelope fetched by root or
range.

Since engine_newPayloadV2 the Engine API answers a block-hash mismatch
with INVALID and a null latestValidHash, indistinguishable from an
executed-invalid payload whose last valid ancestor is unknown. Catching
the structural case on the consensus side keeps such payloads from being
applied to fork choice ahead of the execution client's answer.

The header is encoded in ethlambda-p2p rather than through ethrex's
BlockHeader, which holds base_fee_per_gas as a u64 where the payload has
256 bits. Each fork is tested against a real block or envelope (Sepolia,
Hoodi, mainnet, Plataberget) plus a one-field-changed refusal.

This is stricter than the consensus specs' gossip rules, documented in
docs/spec_deviations.md and docs/beacon_wire.md.
MegaRedHand added a commit that referenced this pull request Nov 5, 2026
…ader's (#770)

Rebuild the execution block header from a payload's own fields and reject
the message when keccak256(rlp(header)) differs from the claimed
block_hash. Runs on pre-gloas beacon_block gossip (bellatrix to fulu), on
gloas execution_payload gossip, and on every envelope fetched by root or
range.

Since engine_newPayloadV2 the Engine API answers a block-hash mismatch
with INVALID and a null latestValidHash, indistinguishable from an
executed-invalid payload whose last valid ancestor is unknown. Catching
the structural case on the consensus side keeps such payloads from being
applied to fork choice ahead of the execution client's answer.

The header is encoded in ethlambda-p2p rather than through ethrex's
BlockHeader, which holds base_fee_per_gas as a u64 where the payload has
256 bits. Each fork is tested against a real block or envelope (Sepolia,
Hoodi, mainnet, Plataberget) plus a one-field-changed refusal.

This is stricter than the consensus specs' gossip rules, documented in
docs/spec_deviations.md and docs/beacon_wire.md.

Cherry-picked from feat/gossip-payload-block-hash at 686b481.

Claude-Session: https://claude.ai/code/session_011vghNmndKPkZinHRkVTwVB
@MegaRedHand
MegaRedHand marked this pull request as ready for review November 17, 2026 18:52
@github-actions

Copy link
Copy Markdown

🤖 Codex Code Review

  • [P1] Move payload hashing off the P2P actor — handler.rs:538, also line 329. These calls synchronously build the transaction trie before entering the semaphore-bounded validation workers. An unauthenticated peer can send distinct envelopes containing many small transactions within the 10 MiB limit; the cheap checks only enforce duplicates, finality, and withdrawal/request counts. Each message forces trie allocation and hashing on the actor handling network events, delaying attestations, requests, and gossip verdicts. Run this check in a bounded blocking worker before forwarding or accepting the message.

The fork-specific header reconstruction otherwise looks consistent on inspection. Tests could not run because Rustup attempted to write to its read-only installation directory.


Automated review by OpenAI Codex · gpt-6.1-sol · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Claude Code Review

Review: execution payload block-hash check in p2p (PR 770)

The approach is sound. Rebuilding the header from the payload and comparing it to block_hash is cheap compared with an EL round-trip. The real-chain vectors for every fork are the right way to pin the RLP layout. Header field order, the post-merge constants, little-endian base_fee_per_gas and parent_root → parent_beacon_block_root all look correct. My concerns are mostly about gossip-scoring semantics and coverage.

Correctness / consensus safety

  1. REJECT penalizes honest relayers (gossipsub/handler.rs, triage_block).

    • Other clients do not run this rule at gossip time. Their EL check happens at import and may be optimistic.
    • So a validly signed block with a bad block_hash will be forwarded to us by honest Lighthouse or Prysm peers. Returning Reject charges each of them an invalid-message-delivery penalty.
    • A malicious proposer can therefore make ethlambda nodes downscore honest peers, once per slot per proposer slot it controls.
    • Consider Outcome::Ignore (or REJECT only once the signature is verified). This keeps the "don't propagate, don't import" effect without the scoring side effect.
    • Since this is a deliberate deviation, spec_deviations.md should at least discuss the scoring consequence.
  2. The stated safety rationale doesn't hold for sync.

    • spec_deviations.md says applying payloads to fork choice early "is only safe if the structural case cannot get that far". It then notes that blocks from beacon_blocks_by_range/root are not checked.
    • If the invariant matters, req/resp blocks are exactly the path that breaks it.
    • Either run verify_block in the block-fetch path, as you already do for envelopes in envelope_checks::judge, or weaken the rationale.
  3. Liveness risk from a stale header shape (payload_hash.rs, computed_hash).

    • Any drift in the header encoding makes this node reject every block or envelope of that fork. That is a self-partition, not a soft failure.
    • The gloas/Amsterdam header is still moving on devnets (BAL hash, slot number, possibly more).
    • Consider a config kill-switch, or a "log + metric but don't reject" mode, at least for gloas until the EIPs are final.
  4. Pre-merge detection is looser than the spec (verify_block, the Bellatrix arm).

    • block_hash == 0 && parent_hash == 0 is not is_execution_enabled, which compares the whole payload to ExecutionPayload::default().
    • A non-default payload with two zero hashes skips the check.
    • The STF parent-hash check will catch it in practice, but *payload == Default::default() states the intent exactly and costs nothing.

Performance

  1. Hashing runs synchronously in triage.
    • A gossip block can carry ~10 MB of transactions. On top of the trie hash, tx.to_vec() copies every transaction, and requests, extra_data and the withdrawals are copied too.
    • If triage_* runs on the swarm or event-loop task, this stalls it. Consider moving the check into the validation stage, or a spawn_blocking.
    • If Trie::compute_hash_from_unsorted_iter accepts borrowed values, avoid the per-transaction copy.

Readability

  1. The Deneb/Electra/Fulu arm matches on block three times.

    • It does this with two unreachable!() arms.
    • A single inner match returning (parent_root, payload, requests) removes the unreachable branches.
    • Alternatively, a small fn deneb_fields(payload, parent_root, requests) -> Fields helper would collapse the four nearly identical Fields { … } literals in verify_block and verify_envelope.
  2. Minor items in payload_hash.rs:

    • ethrex_crypto_keccak is a misleading name for a wrapper around ethrex_common::utils::keccak; keccak256 would be clearer.
    • Bloom::from_slice panics on length ≠ 256. That is fine given the SSZ ByteVector[256], but a debug_assert/comment would document the invariant.

Tests

  • The vectors plus per-field mutation tests are good.
  • Please add a test that a req/resp-fetched envelope with a bad hash is refused through envelope_checks::judge. Currently only the sealed happy path is exercised there.

Automated review by Claude · claude-opus-5-5 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Gemini Code Review

Solid PR — the header reconstruction across all forks (Bellatrix through Gloas/Amsterdam) is clean, well-documented, and well-tested against real chain vectors.

A few suggestions:

  1. Pre-merge Bellatrix empty payload check (crates/net/p2p/src/beacon/payload_hash.rs:178-180)

    if payload.block_hash.0 == [0; 32] && payload.parent_hash.0 == [0; 32] {
        return Ok(());
    }

    In the Bellatrix spec, is_execution_enabled checks body.execution_payload != ExecutionPayload() (full equality against the default container, not just block_hash and parent_hash). If a payload has zero block_hash and parent_hash but non-default values in other fields (e.g. gas_limit, timestamp, or transactions), the STF treats execution as enabled and forwards it to the EL, which will return INVALID with latestValidHash: null. Checking full default equality avoids letting such payloads slip through:

    if *payload == Default::default() {
        return Ok(());
    }

    (And in crates/net/p2p/src/beacon/payload_hash/tests.rs:217-224, *bellatrix_payload(&mut empty) = Default::default();.)

  2. Use the validated envelope slot when logging refusals (crates/net/p2p/src/beacon/payload_hash.rs:341-346)
    In reject_envelope_on_mismatch, refuse is passed envelope.message.payload.slot_number. At this stage cheap_checks has validated envelope.message.slot against the clock, whereas payload.slot_number has not yet been checked against envelope.message.slot (and may itself be the corrupted field causing the hash mismatch). Logging envelope.message.slot is more reliable here.

  3. Combine the duplicate match block in verify_block (crates/net/p2p/src/beacon/payload_hash.rs:236-252)
    Nit: parent_root, payload, and requests can be extracted in a single match block rather than two back-to-back matches with separate unreachable! arms.


Automated review by Gemini · gemini-4-argon · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Grok Code Review

I'll inspect the hash check against the surrounding gossip path and the header-encoding details that real vectors might not cover.


Automated review by Grok (xAI) · grok-4.7 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Kimi Code Review

Findings

  1. Medium: expensive payload reconstruction runs before signature validation, enabling unauthenticated CPU/memory DoS.
    crates/net/p2p/src/gossipsub/handler.rs:327-331 and :538-540 rebuild the header before Dispatch::Validate, meaning the proposer/builder signature has not yet been verified. An attacker can send unique, maximum-size payloads with invalid signatures and force transaction copying, trie construction, and repeated hashing. The fetched-envelope path has the same ordering in envelope_checks.rs:52-61. Run this check after proposer/builder signature verification, or otherwise gate and rate-limit the work.

  2. Medium: the Bellatrix pre-merge exemption can be bypassed by non-default payloads.
    crates/net/p2p/src/beacon/payload_hash.rs:197-202 skips verification whenever only block_hash and parent_hash are zero. A payload with arbitrary transactions or other nonzero fields can therefore avoid the new structural check while remaining execution-invalid. Compare the entire payload against ExecutionPayload::default() (or an equivalent is_default helper). The test a_pre_merge_bellatrix_payload_has_nothing_to_check should also assign a fully default payload; it currently zeroes only those two fields and consequently codifies the overly broad exemption.

The fork-specific header construction and real-chain test coverage otherwise look solid.


Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 DeepSeek Code Review

The PR is well-structured and the real-chain SSZ vectors give strong evidence the header reconstruction is correct. A few issues worth addressing:

  • DoS / placement: in gossipsub/handler.rs triage_block and triage_envelope, the new payload-hash check runs before Dispatch::Validate, which is where BLS signature verification normally happens. Fields::computed_hash builds a trie over all transactions, so any peer that can produce SSZ-valid but unsigned messages can force that CPU cost. Move the check after signature verification or into the stateful validation stage.

  • Coverage gap: beacon_wire.md explicitly notes blocks fetched by beacon_blocks_by_range/root are not checked here. Those blocks can still reach fork choice through sync, so the stated protection is incomplete. Add verify_block to the by-range/root block fetch handler as well.

  • Bellatrix pre-merge skip is too coarse: in verify_block (payload_hash.rs, Bellatrix arm), returning Ok(()) when block_hash == 0 && parent_hash == 0 also skips post-merge malformed payloads that happen to have those two fields zero but other fields non-zero. Compare the entire payload against ExecutionPayload::default() or verify the fork is actually before merge.

  • Minor test inconsistency: in payload_hash/tests.rs, a_changed_gloas_field_is_refused uses push(consolidation()) without .expect(...) for "execution_requests", unlike the electra/fulu test. If the bounded list is full and push returns Result, the error is discarded and the test fails confusingly. Use .expect("room for one more request").

  • Maintainability: the deneb/electra/fulu arm of verify_block has two nested matches with unreachable!("narrowed by the outer match"). Destructuring the block once would be clearer and less error-prone when adding future forks.

No other correctness issues found; the RLP field ordering and trie-root construction match the included real-chain vectors.


Automated review by DeepSeek · deepseek-v4-pro · custom prompt

@pablodeymo pablodeymo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at a01c0f6. The header reconstruction looks right to me: field order and the post-merge constants are correct, the transaction trie uses the same keys and routine as ethrex's own compute_transactions_root, and the requests list is the one newPayloadV4 already sends. My concerns are about where the check runs and what it answers.

Before merge

  1. REJECT penalizes honest peers (handler.rs:329). The spec has no such gossip rule, so other clients forward a validly signed block whose block_hash is wrong. Gossipsub then counts an invalid delivery for the sender and for every peer that already forwarded it. With our parameters (scoring.rs:487) one such block costs each of those peers 107.5 × count², and the count decays over 50 epochs. By my arithmetic (not a simulation), a proposer set with about 1.6% of slots that publishes such blocks keeps every relaying peer below the gossip threshold, and about 3.4% keeps them below the graylist, where we disconnect them. It costs the attacker those proposals, but it isolates only us. IGNORE keeps "don't import, don't forward" without the scoring effect. The execution_payload topic has no score parameters today, so this is about beacon_block.

  2. The check runs on the P2P actor, before the signature check (handler.rs:329, :538). Any peer can make the actor build a transaction trie for an unsigned message of up to the gossip size limit, on top of the decode and root it already pays. It is also outside guarded(), so a panic in the trie code would stop the actor, where the stateful half would answer Ignore(Internal). I read ethrex's insert path and found no panic reachable from these inputs, so that part is defense in depth.

    Suggestion for 1 and 2 together: run the check in the stateful half, after the proposer (or builder) signature verifies, and answer IGNORE. An unsigned message is then rejected by the signature rule as it is today, and only a proposer can reach the warn!. A message forwarded under Overloaded would skip the check, which is fine given point 3.

  3. The rationale in spec_deviations.md overclaims. "Applying payloads to fork choice before the execution client answers is only safe if the structural case cannot get that far" does not hold as written. Blocks fetched by range or root are not checked. #773 has its own path for a mismatch (it reverts the applied payload) and describes this PR as a complement that makes that path rare. And the Engine API requires the execution client to validate blockHash in all cases, even while syncing (paris.md), so today, with the import waiting for newPayload, this catches nothing the execution client does not. I'd describe the rule as what it is: it saves #773 a revert for gossip blocks.

  4. Two encodings have no real-chain vector (payload_hash/tests.rs). The electra and fulu vectors both carry empty execution_requests, and the largest block vector has 116 transactions, below the 128 where the trie key becomes two bytes. I expect both paths to be right, since they go through ethrex's routines, but a false mismatch on gossip would penalize honest peers on every such block. A mainnet block with 128 or more transactions and at least one request would pin it, with an assertion for both in the_vectors_exercise_what_each_fork_adds. Has this run on a live node? lean_beacon_payload_block_hash_mismatch_total staying at zero on mainnet for a few days would be good evidence.

Should fix

  1. Gloas has no fallback. Envelopes are checked on gossip and on fetch, so if the Amsterdam header changes on a later devnet, the node refuses every payload and cannot follow the chain. A pre-gloas block refused in error still comes back by root. Consider counting and logging without refusing for gloas until the header is final, or a flag that turns the rule off.

  2. Bellatrix pre-merge skip (payload_hash.rs:180). It tests two zero hashes; the spec's predicate is the whole payload being the default. *payload == Default::default() states that exactly, and a_pre_merge_bellatrix_payload_has_nothing_to_check should use a default payload too.

  3. Cost. "One trie over the transactions" has no number. Could you time verify_block on the fulu vector and on a block at the size limit?

Nits

  • The deneb/electra/fulu arm matches on block three times with two unreachable!() arms. One inner match returning (parent_root, payload, requests) removes them.
  • ethrex_crypto_keccak reads as a crate name; keccak256 is clearer.

The pre-merge skip tested two zero hashes, where the specification's
is_execution_enabled asks whether the whole payload is the default
ExecutionPayload(). bellatrix::ExecutionPayload now implements Default
(the all-zero value BeaconBlockBody::empty already built by hand), and
verify_block compares against it. A payload with zero hashes over real
fields is now checked, and the pre-merge test uses a default payload.
The deneb/electra/fulu arm of verify_block matched on the block three
times, two of them with unreachable!() arms. Deneb and electra/fulu are
now their own arms of the one match, sharing a Fields::deneb helper for
the payload container they have in common, so nothing is unreachable.
ethrex_crypto_keccak read like a crate name; it is keccak256 now.
…E it

The rule ran in triage on the P2P actor, before the signature check and
outside guarded(), and answered REJECT. Any peer could make the actor
build a transaction trie for an unsigned message, and since other
clients have no such rule and relay a validly signed block whatever its
block_hash, a REJECT scored every honest peer that forwarded one.

It now runs at the end of the stateful half, on the blocking thread
inside guarded(), and only on a message the topic's rules accepted, so
the proposer's (or builder's) signature has verified. A pre-gloas block
whose hash does not match is IGNOREd (new IgnoreReason
PayloadBlockHashMismatch, replacing the RejectReason): not imported, not
relayed, nobody scored. A Queue or Overloaded block is not hashed.

Gloas envelopes, from gossip and from fetches, are hashed the same way
once accepted but only counted and logged, never refused: the Amsterdam
header may still change between devnets, and a wrong encoding would
otherwise refuse every payload and stop the node following the chain.
The test helpers that sealed envelopes for the old rule are gone again.
No real-chain vector reached a transactions trie key of two bytes
(index 128 and up) or carried any execution request: the electra and
fulu blocks had empty requests and the largest had 116 transactions.

The fulu vector is now mainnet slot 15684701 (finalized, canonical;
the same SSZ bytes from an ethlambda node's Beacon API and from
lodestar-mainnet.chainsafe.io): 238 transactions, one withdrawal request
and two consolidation requests, and its hash matches.
the_vectors_exercise_what_each_fork_adds asserts more than 128
transactions, rlp(128) being 0x81 0x80, and requests of two types; a
changed field inside one of its consolidation requests must be refused.
The "one more request" mutation pushes a withdrawal request now, since
the consolidation list (two at most) is already full in this block. The
old fulu vector (slot 15576000, 116 transactions, no requests) covered
nothing this one does not, so it is dropped.
An ignored test that prints how long verify_block takes, copies
included: on the real fulu vector, and on that block refilled to the
10 MiB gossip limit three ways (the most transactions the list allows,
transactions of the vector's mean size, and one transaction). Run with

  cargo test -p ethlambda-p2p --profile release-fast --lib \
      payload_hash::tests::verify_block_cost -- --ignored --nocapture --test-threads=1
spec_deviations.md said applying payloads to fork choice early "is only
safe if the structural case cannot get that far", which does not hold:
blocks fetched by range or root are not checked, the early import has
its own revert path, and the Engine API already requires the execution
client to validate blockHash on every newPayload, even while syncing.
The section now says that, and that the rule saves the early import a
revert for gossip blocks. It also covers where the rule now runs (after
the signature, IGNORE, gloas counted only), what is not covered, and the
measured cost. beacon_wire.md (both passages and the metric row) and
the reason list in metrics.md follow.
@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

Thanks. Going through it in order.

  1. IGNORE instead of REJECT. A mismatch is now Ignore(PayloadBlockHashMismatch) (payload_block_hash_mismatch); the reject reason is gone. a_block_mismatch_is_ignored_once_its_checks_accept pins the labels. (5211db6)
  2. After the signature, inside guarded(). Both triage calls are gone. The check runs in Validated::stateful_checks on the blocking thread, and only when the topic's own checks answered Accept, the one outcome that says the proposer's (or builder's) signature verified. Queue, Overloaded and Reject pass through unhashed (a_block_that_was_not_accepted_keeps_its_verdict), and triage never hashes (a_wrong_payload_block_hash_is_not_judged_in_triage, which got Report(Reject) before). Fetched envelopes had the same order in envelope_checks::judge; they are hashed after stateful_checks now too. (5211db6)
  3. Rationale. spec_deviations.md now says what you wrote: the Engine API already requires the EL to validate blockHash, so while the import waits for newPayload this catches nothing the EL wouldn't, and it exists to save perf(blockchain): import blocks and envelopes before the engine answers #773 a revert for gossip blocks. It also lists what is not covered (by-range/by-root blocks, Queue/Overloaded gossip blocks) and why IGNORE. The module doc in payload_hash.rs said the same thing and is fixed too, as are beacon_wire.md and metrics.md. (063105b)
  4. Vectors. The fulu vector is now mainnet slot 15684701 (finalized): 238 transactions, one withdrawal request and two consolidation requests. The SSZ is byte-identical from our node and from Lodestar's public API, and the hash matches. It replaces the old fulu vector, which had nothing this one lacks. the_vectors_exercise_what_each_fork_adds asserts more than 128 transactions (and that rlp(128) is 0x81 0x80) and requests of two types; the mutation test also flips a byte inside one of its consolidation requests. (e6abca5) Live node: not measured, I haven't looked at the counter on any node. What I did run locally (not committed): verify_block over the 200 consecutive finalized mainnet blocks 15684600 to 15684799. All match; 183 have more than 128 transactions (up to 786), 99 carry requests (deposits in 10, withdrawal requests in 1, consolidations in 93).
  5. Gloas fallback. I took the first option: an accepted envelope whose hash does not match is counted (kind="envelope") and logged, never refused, on gossip and on fetch, until the Amsterdam header is final. a_gloas_mismatch_is_counted_but_not_refused. (5211db6)
  6. Pre-merge skip. bellatrix::ExecutionPayload had no Default (logs_bloom is an SszVector), so I gave it one in types (the value BeaconBlockBody::empty() built by hand, which now uses it), and the skip compares with it. The pre-merge test uses a default payload, and a_payload_with_zero_hashes_but_other_fields_is_checked fails with the old predicate. (10a506e)
  7. Cost. There's an ignored payload_hash::tests::verify_block_cost now (926a6cd). On an M3 Pro (release-fast, load average around 20): about 0.22 ms on a 179-transaction mainnet block and 0.24 ms on the new 238-transaction vector; at the 10 MiB gossip limit, 11 ms for one transaction, 19 ms for 14,882 transactions of about 700 bytes, and 0.6 s for the worst case, 1,048,576 five-byte transactions. The machine was shared, and reruns under a load near 100 were up to five times slower, so take these as rough. Only a block whose proposer signature verified can ask for the 0.6 s now.

Nits: both in f24dde2. I split deneb and electra/fulu into their own arms sharing a Fields::deneb helper rather than one inner match, since an inner match under the or-pattern still needs one unreachable!().

The description is rewritten to match: its What/Why were about REJECT in triage.

@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

Copy link
Copy Markdown

🤖 Claude Code Review

Review: PR 770, payload block-hash check on gossip

The PR is well-scoped and well-documented. Gating the check on Accept (signature verified) and using IGNORE instead of REJECT are the right calls, and the real-chain vectors give good confidence in the RLP layout. A few points below.

Correctness / consensus

  1. Is Ignore(PayloadBlockHashMismatch) excluded from forwarding? verdict.rs around L124 turns Accept into this new Ignore reason. The docs say a block under Ignore(Overloaded) still reaches the chain actor.

    • Please confirm the dispatch code matches on Overloaded specifically, not on Ignore(_). Otherwise the mismatched block is still imported and the rule does nothing.
    • A test asserting the block is neither forwarded nor relayed would lock this in. The current tests only check the Outcome value.
  2. The rule is easy to get around via by-root fetch. As the envelope_verdict doc admits, "a pre-gloas block refused on gossip still comes back by root". A child block that references the ignored block triggers a parent-unknown fetch, and beacon_blocks_by_root is unhashed. So the block reaches import anyway, just one round trip later.

    • For the motivating use case (the early fork-choice import in ethlambda#773), this means a revert is delayed, not avoided.
    • Options: run verify_block on by-root/by-range results before forwarding them, or state this limitation explicitly in spec_deviations.md under "Not covered". The current text there only says fetched blocks are unhashed, not that ignored gossip blocks come back that way.
  3. Empty-list edge cases are not covered by the vectors. If the encoding is wrong for an empty transactions list, the node silently IGNOREs every block of that shape on gossip.

    • No vector has zero transactions. Trie::compute_hash_from_unsorted_iter over an empty iterator must yield EMPTY_TRIE_HASH (0x56e8…b421).
    • Electra/Fulu with no requests: compute_requests_hash must equal sha256("") with the empty-list filtering EIP-7685 specifies. The Hoodi electra vector may cover this, since its "carries" column is blank. If so, say so in the table.
    • A cheap guard: unit-assert that an empty trie root equals the known constant. If possible, also add a real empty-tx block (common on testnets).
  4. "Equivalence" claim in spec_deviations.md. "Every block it ignores carries a payload the execution client would call INVALID" holds only if this encoder is exact. Suggest softening to "…assuming the header encoding matches the EL's", since the gloas branch is deliberately non-refusing for exactly this reason.

Performance

  1. Avoidable copies in computed_hash. It copies every transaction (tx.to_vec(), up to ~10 MiB at the gossip limit) and collects a Vec<&[u8]> in Fields first.

    • If Trie::compute_hash_from_unsorted_iter accepts AsRef<[u8]>, pass slices directly.
    • Otherwise this is acceptable. The worst case is bounded to one signed block per proposer/slot, because equivocations hit the seen cache before signature verification.
  2. 0.6 s worst case inside a gossip validation permit. This is acceptable given the signature gate. It is worth noting in beacon_wire.md that this permit is held for the duration.

Maintainability

  1. Repeated Fields { … } literals. The 14 shared payload fields are written out three times (bellatrix, capella, gloas) plus once in Fields::deneb, all with the same fields.

    • A small macro or a Fields::base(payload) constructor would remove ~60 lines.
    • It would also remove the risk of one fork silently mis-wiring a field, e.g. swapping gas_used/gas_limit in only one arm.
  2. Pre-merge check allocates. *payload == bellatrix::ExecutionPayload::default() builds a 256-byte bloom each call. That is negligible, but payload.block_hash == ZERO && payload.parent_hash == ZERO && … is not what you want either, per the test. Keeping the full-equality check is fine; a static/LazyLock default would avoid the allocation.

  3. Minor: Bloom::from_slice panics on wrong length. It is safe here because LogsBloom is a fixed-length SszVector. A one-line comment would save a future reader the check.

Tests

The fork-by-fork mutation tests, the >128 transactions two-byte key coverage, and the block_verdict/envelope_verdict pass-through tests are good. Adding the forwarding test from item 1 and the empty-list cases from item 3 would close the remaining gaps.

The Default for ExecutionPayload refactor in bellatrix.rs looks good.


Automated review by Claude · claude-opus-5-5 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Codex Code Review

No actionable findings. The fork-specific header reconstruction, signature-gated hashing, and IGNORE handling look correct. Real-chain vectors and mutation tests provide good coverage.

Tests could not run: rustup attempted to update the pinned toolchain in a read-only directory.


Automated review by OpenAI Codex · gpt-6.1-sol · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Gemini Code Review

This PR is well-structured, thoroughly documented, and well-tested with real chain vectors across all execution-enabled forks (Bellatrix through Gloas). Gating the trie computation behind Outcome::Accept (after proposer/builder signature verification) and returning IGNORE rather than REJECT to avoid penalizing honest relaying peers are both sound design choices.

A couple of minor suggestions:

  1. Avoid intermediate Vec<&[u8]> allocation in Fields (crates/net/p2p/src/beacon/payload_hash.rs:92)
    Every fork from Bellatrix through Gloas uses bellatrix::Transactions (which derefs to &[bellatrix::Transaction]). Holding transactions: &'a [bellatrix::Transaction] in Fields<'a> instead of Vec<&'a [u8]> avoids collecting an intermediate vector of slice references (up to MAX_TRANSACTIONS_PER_PAYLOAD = 1,048,576 entries in the worst case) before building the trie.

  2. Log the consensus slot in envelope_verdict (crates/net/p2p/src/beacon/payload_hash.rs:380)
    let slot = envelope.message.payload.slot_number; reads the slot from the untrusted execution payload field (which could itself be the corrupted field causing the hash mismatch) rather than the validated consensus slot envelope.message.slot. Using envelope.message.slot ensures the logged slot always matches the beacon block at beacon_block_root.


Automated review by Gemini · gemini-4-argon · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Grok Code Review

I'll inspect the hash-check call sites and the header-encoding assumptions against the surrounding validation path.


Automated review by Grok (xAI) · grok-4.7 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Kimi Code Review

No blocking correctness or security issues found in the diff. The header field ordering and post-merge constants look correct, the check is appropriately gated on Accept so unsigned messages cannot trigger trie construction, and the real-chain vectors provide good per-fork coverage. Using IGNORE rather than REJECT also avoids penalizing honest relaying peers.

One non-blocking performance concern:

  • crates/net/p2p/src/beacon/payload_hash.rs:145-176 copies transaction data and constructs the full trie on the blocking validation path. The documented worst case—about 0.6 seconds for a maximally transaction-heavy gossip block, with substantial allocation overhead—could stall validation longer on slower or loaded nodes. The signature gate and concurrency permit bound exposure, but this deserves monitoring once deployed; consider caching successful verification by the payload’s SSZ root if profiling shows repeated work.

The uncovered paths (Queue, Overloaded, and blocks fetched by range/root) are explicitly documented and remain protected by execution-client validation. The metric-only gloas behavior is also a reasonable safeguard while that header format remains unstable.


Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 DeepSeek Code Review

Overall this is a well-reasoned, well-tested change. Running only after Accept, using IGNORE rather than REJECT, and the real-chain SSZ vectors all look right.

A few issues/concerns:

  1. crates/net/p2p/src/beacon/payload_hash/tests.rs — verify_block_cost
    The ignored benchmark case filled(1, room - 4) builds a transaction of roughly MAX_PAYLOAD_SIZE bytes. Transaction::try_from is bounded by MAX_BYTES_PER_TRANSACTION; in the usual preset that is 1 MiB, not 10 MiB, so the benchmark will panic when run as documented. Cap this case to preset::MAX_BYTES_PER_TRANSACTION or adjust the scenario.

  2. crates/net/p2p/src/beacon/payload_hash/tests.rs — missing degenerate-root coverage
    The real vectors all exercise non-empty payloads. There is no test for:

    • a non-default Bellatrix payload with zero transactions,
    • empty withdrawals in Capella,
    • empty requests in Electra/Fulu.

    These are the cases where Trie::compute_hash_from_unsorted_iter, compute_withdrawals_root, and compute_requests_hash must return the standard empty roots. Adding unit tests for these would guard against a regression that would cause valid empty blocks to be IGNOREd.

  3. crates/net/p2p/src/beacon/payload_hash.rs — Bellatrix default check is slightly heavier than necessary
    verify_block compares *payload == bellatrix::ExecutionPayload::default() on every accepted Bellatrix block. This constructs a default payload and does a full container comparison. In practice the first differing field usually short-circuits it, but a cheap is_default_execution_payload helper would avoid the allocation/comparison and make the pre-merge skip cheaper.

No production-blocking bug found in the payload hash computation or verdict integration itself.


Automated review by DeepSeek · deepseek-v4-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Codex Code Review

No actionable findings. Header reconstruction, fork-specific fields, signature gating, and mismatch verdict handling look correct. Real-chain vectors provide useful coverage across forks.

Tests could not run because rustup attempted to write to a read-only directory while resolving the pinned toolchain.


Automated review by OpenAI Codex · gpt-6.1-sol · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Kimi Code Review

No correctness issues found in the header reconstruction or verdict handling. The fork-specific field ordering, little-endian base_fee_per_gas, pre-merge Bellatrix exemption, and IGNORE-rather-than-REJECT behavior look sound. The real-chain vectors and mutation tests provide strong coverage.

One non-blocking concern:

  • Validation-time DoS amplification — payload_hash.rs, Fields::computed_hash around lines 151–161, and verdict.rs, settle around lines 554–565. The expensive transaction-trie construction happens before the seen cache is settled. Consequently, several distinct, validly signed equivocations for the same slot/proposer can arrive concurrently, all pass the cheap checks, and each perform the full hash before the first verdict marks that slot/proposer seen. With the documented worst case of roughly 0.6 seconds per block, a malicious proposer could occupy the validation permits and delay attestations or other gossip. Consider tracking in-flight validations by slot/proposer, or otherwise deduplicating before spawning stateful validation; reservations must be released for outcomes that should not mark the proposer seen. A concurrency test showing that simultaneous mismatched equivocations trigger only one payload-hash computation would cover this.

A smaller performance consideration: envelope_checks.rs:52–58 uses a fresh seen cache for fetched envelopes, so every accepted refetch repeats the full trie/header computation even though envelope_verdict never changes the outcome. If duplicate envelope fetches are common, caching the verification result by envelope/root identity would avoid repeated work.

Otherwise, the change is well documented, appropriately signature-gated, and careful about consensus and peer-scoring compatibility.


Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 DeepSeek Code Review

Overall this is a thorough, well-tested PR. The use of real-chain SSZ vectors per fork and the tests around seen-cache handling for mismatches are especially good.

A few issues worth addressing:

  • DoS/cost on the validation permit: Fields::computed_hash builds the full transaction trie on the blocking validation thread (crates/net/p2p/src/beacon/payload_hash.rs, around L160-178). The included benchmark shows worst case ~0.6s for a maxed payload, and docs note up to 5x slower under load. A block whose proposer signature verifies can force that cost. Consider whether that should run on a separate threadpool, have a stricter budget/timeout, or skip/limit trie construction for extreme transaction counts.

  • Bellatrix pre-merge skip is based only on payload shape: verify_block returns Ok whenever the Bellatrix payload equals ExecutionPayload::default() (payload_hash.rs, around L237-243). This is not actually is_execution_enabled; a post-merge Bellatrix block carrying the all-zero/default payload would also be skipped, so the new hash check would miss it. It is invalid anyway and the execution client should reject it, but if this rule is intended to protect the early fork-choice import path from post-merge-invalid payloads, confirm gossip::block::stateful_checks already rejects such a block before Accept, or pass fork-state information into verify_block.

  • Release builds lose the optional-field ordering check: computed_hash uses debug_assert! to verify that optional header fields are contiguous from the tail (payload_hash.rs, around L188-195). A future fork that accidentally makes an earlier field None while a later field is Some would silently produce the wrong header in release builds. Since this would likely cause false mismatches and self-DoS on gossip, consider a normal assert! or a compile-time/static check.

  • Per-block allocation in the Bellatrix pre-merge check: ExecutionPayload::default() allocates a 256-byte Vec on every call (crates/common/types/src/beacon/containers/bellatrix.rs, around L127-135), and verify_block calls it for every Bellatrix gossip block solely to decide whether to skip. Minor, but this is on the gossip hot path; a direct field check or is_default() method would avoid the allocation.

  • Minor API surface: verify_block and verify_envelope are pub while only used internally by p2p validation. pub(crate) would keep the module from exposing ethrex internals as public API.

  • Duplicate mismatch settling: in settle, the PayloadBlockHashMismatch branch calls object.record_seen(server) but ignores the returned bool (crates/net/p2p/src/beacon/verdict.rs, around L548-553). That is likely intentional, but concurrent copies of the same mismatching block can both be reported before the first one marks the seen cache. Not a correctness problem, just a duplicate-work/logging edge.


Automated review by DeepSeek · deepseek-v4-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Grok Code Review

The header rebuild is carefully pinned to real blocks and the IGNORE-vs-REJECT choice is right. A few gaps are still worth fixing before this is treated as protection for early fork-choice import.

  1. Trie build can stall or OOM validation. computed_hash copies every transaction and builds a full unsorted trie (payload_hash.rs around the Trie::compute_hash_from_unsorted_iter call). Your own benchmark is ~0.6s and a large node allocation for MAX_TRANSACTIONS_PER_PAYLOAD (1,048,576) five-byte txs. That runs while a gossip_validation_permits slot is held, and only after Outcome::Accept. Seen-cache update happens later in settle (verdict.rs), so a proposer can pre-sign many equivocations, pass cheap checks concurrently, and pile up trie builds before any of them is recorded. Cap in-flight hashes per (slot, proposer) (shared claim before the trie, not only in settle), and skip or bail out above a tx-count/memory budget so the EL still judges the monster block.

  2. record_seen is too late for the DoS case, and its effect on mismatch should stay a pure equivocation bit. Recording PayloadBlockHashMismatch in settle is the right spec reading (first valid signature). Confirm record_seen only marks slot+proposer and does not retain or rebroadcast the payload. It does not stop the burst in point 1.

  3. By-root/range import still skips the check. verify_block is only applied to gossip Accept. As spec_deviations.md says, a child that names an ignored block fetches it by root and imports it unhashed. That is exactly the path that still pays the revert this rule is meant to avoid once early fork-choice import lands. Hook the same verify_block into that import before relying on it.

  4. Pre-merge skip is not merge-aware. verify_block treats payload == ExecutionPayload::default() as nothing to check (payload_hash.rs, bellatrix arm). That is required so real pre-merge blocks are not ignored, but a post-merge proposer can sign that same empty payload and this rule will Accept it. Harmless while the EL is the gate; it will not save an early-import revert. Only skip when the store still has the empty execution header (spec is_execution_enabled), or hash the default payload whenever merge is done.

  5. debug_assert on header tail order is stripped in release (computed_hash). A future fork that sets a later optional field without the earlier ones would silently hash every block wrong and IGNORE all gossip, which is a liveness failure. Use assert! (or an enum of header versions) so a bad combination cannot ship.

The per-fork vectors (especially mainnet fulu with >128 txs and two request types) are the right way to pin RLP order, tx-trie keys, withdrawals root, and EIP-7685 requests hash. Keeping gloas count-only until the Amsterdam header is frozen is the correct call. I would not refuse on that path until a vector from a frozen devnet is required for the release.


Automated review by Grok (xAI) · grok-4.7 · custom prompt

@MegaRedHand
MegaRedHand marked this pull request as draft November 19, 2026 19:07
settle() recorded a block ignored for its payload hash but dropped
record_seen's answer, so a second such block for a slot and proposer
already recorded (two checked at once) was still reported as
payload_block_hash_mismatch. It is now AlreadySeen, the same as a second
Accept, and a_payload_hash_mismatch_marks_its_slot_and_proposer_seen
covers it.
verify_block, verify_envelope and HashMismatch were pub, though only the
p2p crate's own verdict code calls them.
The seen cache stops another block for a slot and proposer once the
first verdict reaches the p2p actor, not while blocks are still being
checked. A proposer publishing several signed equivocations at once has
each one hashed until then, up to the 128 validation permits. The cost
bullet now says so, and that the signature check has the same window.
@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

Round five (the automated review of adc00e2). Fixed in d38e786, a726ddd and e1f1b2c. make fmt and make lint pass; the tests are left to CI.

Fixed

  • Claude 2 / DeepSeek 6, the label of a mismatch that lost the seen race. settle recorded a mismatched block but dropped record_seen's answer. A second such block for a key already recorded (two checked at once) was therefore still reported as payload_block_hash_mismatch. It is now AlreadySeen, the same as a second Accept, and a_payload_hash_mismatch_marks_its_slot_and_proposer_seen covers it. d38e786
  • DeepSeek 5, visibility. verify_block, verify_envelope and HashMismatch are pub(crate). a726ddd
  • Claude 1 / Kimi 1, concurrent equivocations. True. The seen cache only stops another block for the key once the first verdict reaches the actor, so signed equivocations published together are each hashed until then, up to the 128 gossip_validation_permits. A message arriving with none free is forwarded unhashed under Overloaded. The signature check has the same window on main; this PR raises its per-block cost. The cost bullet in spec_deviations.md now says so. e1f1b2c Claiming the slot and proposer before the stateful checks would close the window for both, and belongs in its own change: Claim a gossip block's slot and proposer before its stateful checks #840.

Not changed

  • DeepSeek 1 / Grok 1, a separate pool, budget or transaction-count cap: in the same issue.
  • Grok 2: record_seen only puts (slot, proposer) -> root in an LRU that the cheap checks read. Nothing is kept or rebroadcast.
  • DeepSeek 2 / Grok 4, merge-aware pre-merge skip: a post-merge bellatrix block with the default payload is REJECTed by the gossip timestamp rule (its timestamp is 0) before it could reach Accept, the only outcome that is hashed.
  • DeepSeek 3 / Grok 5 / Claude 6, a release assert! or a typed tail: every fork's real vector runs through computed_hash with debug assertions on in CI. In release, an assert! would only turn every block into Ignore(Internal) instead of a wrong hash.
  • Claude 7: the variant's doc already says the rule runs in p2p.
  • Kimi 2, refetched envelopes: an envelope is refetched only while the chain actor still lacks it, and each judge already verifies a BLS signature.
  • Settled in earlier rounds: Claude 3 and 5, DeepSeek 4 (round three); Claude 4 and the idle-machine benchmark (round four); Grok 3, hashing fetched blocks (round three).

Gemini and Codex had no findings (Codex's tests did not run).

@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

Copy link
Copy Markdown

🤖 Claude Code Review

Review: payload block hash check (PR 770)

This is a careful, well-scoped change. The rule only fires after the signature verifies. It answers IGNORE, not REJECT. Gloas is count-only. The encoding is pinned per fork by real-chain vectors, including the two-byte trie key case and multi-type requests. The settle change, which records a mismatched block as seen, correctly matches the spec's "first block with a valid signature" and closes the equivocation amplification. I found no correctness bugs in the header encoding. My comments are mostly about operational risk and maintainability.

Operational risk

  1. No escape hatch if the encoding is wrong for a pre-gloas fork (payload_hash.rs, verify_block / block_verdict).

    • A mismatch now does three things:
      • IGNOREs the block.
      • Marks its (slot, proposer) as seen (verdict.rs settle).
      • Withholds it from the chain actor.
    • If the encoding is ever wrong for a live fork (for example, a fork reusing the Fulu variant but changing the EL header), the node silently drops every gossip block. It then follows the chain only through by-root fetches triggered by children or attestations.
    • The exhaustive match is good, because a new variant forces a decision. Still, consider:
      • a config flag (or reuse of a debug toggle) that downgrades block_verdict to count-only, like envelope_verdict, or
      • an error! when the mismatch rate is high.
    • This would give operators a mitigation without needing a release.
  2. Warn spam on fetched envelopes (envelope_checks.rs judge → envelope_verdict).

    • The doc says the gloas header "is still moving between devnets". If it moves, every fetched envelope during range sync emits a warn!, potentially thousands per batch.
    • Suggestions:
      • Log fetched mismatches at debug! and keep warn! for gossip, or
      • Rate-limit and rely on the counter, which already distinguishes kind. You could add a source label (gossip/fetch) to make this clearer.
  3. Permit starvation under equivocation (spec_deviations.md cost section).

    • The 0.6 s worst case × 128 gossip_validation_permits is documented.
    • If those permits are shared with attestation and aggregate validation, a single equivocating proposer can push other topics into Overloaded for roughly a second per burst.
    • This is bounded (it needs a real proposer signature and is slashable), so it is acceptable. It's worth stating explicitly in the doc whether the permit pool is shared, since that determines the blast radius.

Code quality

  1. Duplicated Fields literals (payload_hash.rs, the Bellatrix, Capella, and gloas verify_envelope arms).

    • Three near-identical 19-field struct literals exist beside Fields::deneb.
    • A macro or per-container constructors (Fields::bellatrix, Fields::capella, Fields::gloas) would mirror Fields::deneb. This would also make it harder to mis-set an optional field in a future fork. The debug_assert catches ordering, but not a forgotten field.
  2. Copying transactions (computed_hash, tx.to_vec()).

    • This doubles the transaction memory, up to about 10 MiB, per verification.
    • It's fine given the trie API takes owned values. A one-line note on the peak memory alongside the timing numbers would complete the cost analysis.
  3. Log context (block_verdict).

    • Add proposer_index to the warn!. A mismatch is attributable to a specific signed proposer, and that is the most actionable field.
  4. Public ExecutionPayload::default() (bellatrix.rs).

    • It is semantically the spec's ExecutionPayload(), so it's justified.
    • Note that ..Default::default() on a consensus container now compiles silently. Consider a doc line warning against using it outside the pre-merge comparison and the empty-body case.

Minor

  1. Layering of IgnoreReason::PayloadBlockHashMismatch.

    • This p2p-only policy now lives in state_transition::beacon::gossip. That is acceptable since IgnoreReason already lives there.
    • Keep the doc comment pointing at ethlambda-p2p as the only producer, as it already does.
  2. Unbacked ordering claim.

    • The gloas header ordering (block_access_list_hash then slot_number) is pinned only by the Plataberget vector.
    • Add a comment there citing the EIP or execution-specs revision it was checked against, so the next devnet bump knows what to re-verify.
  3. Tests.

    • Coverage is strong: real vectors per fork, field-mutation refusals, the pre-merge skip, the verdict passthrough, and the seen-cache interaction.
    • Nothing further needed.

Overall this looks good to merge. I'd prioritize item 1 (a kill switch for the enforcing path) and item 2 (fetch-path log volume).


Automated review by Claude · claude-opus-5-5 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Gemini Code Review

The implementation looks solid and well-tested against real chain vectors across all forks (Bellatrix through Gloas). Deferring the hash computation until stateful_checks returns Outcome::Accept (after proposer/builder signature verification) and recording PayloadBlockHashMismatch in seen_blocks in settle properly bounds the hashing work to at most one signed block per (slot, proposer) once settled.

One minor optional suggestion:

  • crates/net/p2p/src/beacon/payload_hash.rs:95: Since every fork's payload uses bellatrix::Transactions, Fields::transactions could hold &'a [bellatrix::Transaction] instead of allocating an intermediate Vec<&'a [u8]> before building the trie in computed_hash.

Automated review by Gemini · gemini-4-argon · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Codex Code Review

  • [P1] Bound concurrent trie construction — payload_hash.rs:149. A malicious proposer can send many signed equivocations before the first verdict updates seen_blocks, causing up to 128 concurrent trie builds. Each block can contain 1,048,576 tiny transactions; the documented benchmark already takes about 0.6 seconds per block, with additional allocations for trie keys, values, and nodes. This can exhaust memory or starve validation of honest gossip. Reserve (slot, proposer) atomically after signature verification and before hashing, and bound trie construction with a separate, smaller resource budget.

The header encoding and fork-specific handling otherwise look sound. Tests could not run because rustup attempted to write to a read-only directory.


Automated review by OpenAI Codex · gpt-6.1-sol · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Grok Code Review

The header reconstruction is in good shape: real-chain vectors pin bellatrix through fulu, IGNORE-not-REJECT is the right gossip scoring choice, and hashing only after Accept keeps unsigned gossip from building a transactions trie. Gloas staying count-only until the Amsterdam header is frozen is the correct caution.

  1. Pathological but in-spec payloads can stall validation. In payload_hash.rs computed_hash copies every transaction and builds a trie on the blocking validation thread, inside the gossip permit. Your own benchmark is about 0.6 s and a large trie for MAX_TRANSACTIONS_PER_PAYLOAD five-byte txs, and up to gossip_validation_permits equivocations can run before the first verdict records the slot and proposer. A single proposer key is enough. Skip the local check above a tx-count threshold (the execution client still validates), or give this check a much smaller semaphore than general gossip validation.

  2. The check is not on the import boundary, so it does not actually close the revert window this is aimed at. Queue, Ignore(Overloaded), and beacon_blocks_by_range / by_root still reach the chain actor unhashed (payload_hash.rs module comment and spec_deviations.md). A block dropped here is fetched unhashed as soon as a child names it. Before early fork-choice apply lands, run verify_block / verify_envelope at that apply site too, or the gossip filter is optional for an attacker.

  3. A systematic false positive does not self-heal via that by-root path. Children are ignored the same way, so no child arrives to trigger a fetch. Range sync still works; gossip head-following does not. PayloadBlockHashMismatch also marks the slot and proposer seen (verdict.rs settle), so a later gossip copy of a good block for that slot becomes AlreadySeen. That matches the spec’s first-valid-signature rule for a truly bad hash, but an encoder drift on a stable fork isolates this node. Alert on lean_beacon_payload_block_hash_mismatch_total{kind="block"} and keep a count-only switch.

Smaller notes:

  • Bloom::from_slice in computed_hash panics if logs_bloom is not 256 bytes. SSZ ByteVector[256] should make that unreachable; a length check returning HashMismatch would avoid a validation-thread panic if a constructor ever slips.
  • Bellatrix pre-merge skip is full equality with ExecutionPayload::default(), not a hash check (verify_block). A post-merge all-zero payload therefore bypasses the new filter. Narrow, and the execution client still rejects it.
  • The hand-rolled RLP tail is only safe while forks append fields. The debug_assert on tail is stripped in release and does not catch “middle field present, later field absent” (blob gas without parent_beacon_block_root). Fine today because each fork arm sets fields together; a new fork arm needs a vector before it may IGNORE, same as gloas.

Automated review by Grok (xAI) · grok-4.7 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Kimi Code Review

  • Medium – bound concurrent payload-hash work separately (crates/net/p2p/src/beacon/payload_hash.rs:158-174, crates/net/p2p/src/beacon/verdict.rs:548-556). The proposer/slot is marked seen only after hashing reaches the actor. Consequently, a proposer can submit many distinct, validly signed equivocations before the first verdict and occupy all 128 validation permits with transaction-trie construction. With the documented 0.6-second worst case, 10 MiB of transaction copies per block, and additional trie memory, this can saturate CPU/memory and delay unrelated gossip. Consider a small dedicated concurrency budget with a bounded queue, or an in-flight proposer/slot reservation immediately after signature verification and before trie construction.

  • Low – the Bellatrix exemption is not specifically pre-merge (payload_hash.rs:238-244). Returning Ok(()) whenever the payload equals ExecutionPayload::default() also exempts a default payload in a post-merge block. Post-merge, the specification’s is_execution_enabled remains true even for that payload; pre-merge classification requires state, not just payload equality. This is fail-open—subsequent state-transition/execution validation still catches it—but it is another bypass of the new early check. If intentional, document it alongside the other coverage gaps; otherwise, pass merge-completion information into the check.

Otherwise, the implementation looks careful: header field ordering and optional-field handling are consistent across forks, the real-chain vectors provide strong encoding coverage, and converting only an accepted gossip block to IGNORE avoids penalizing honest relaying peers.


Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 DeepSeek Code Review

⚠️ Review failed: DeepSeek returned an empty content field (finish_reason=length, reasoning_content present=yes). Raise max_tokens or lower reasoning_effort ('none' disables thinking).


Automated review by DeepSeek

envelope_verdict warned on every mismatch, fetched envelopes included,
so if the Amsterdam header moved, range sync would warn once per
envelope of every batch. It now takes the envelope's source: a gossip
envelope still warns and a fetched one logs at debug, and the counter
counts both as before.

A block's mismatch warning also names its proposer, the one party a
signed mismatch is attributable to. A comment at the gloas header fields
says what pins their order (a real Platåberget envelope) and that it
needs re-checking against the final EIPs before a mismatch is refused.
The cost bullet gave the 128 gossip_validation_permits as the bound on
concurrent hashing without saying what else draws from them. It is data
columns and envelopes only; the attestation, sync committee and builder
topics have pools of their own. The bullet also says what each log line
names, and that fetched envelopes log at debug.
@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

Round six (the automated review of e1f1b2c). Fixed in 8e0d90d and 17b4e41. make fmt and make lint pass; the tests are left to CI.

Fixed

  • Claude 2, warning volume on fetched envelopes. A mismatch on an envelope fetched by range or root now logs at debug, and a gossip one still warns. If the Amsterdam header moved, range sync would otherwise warn once per envelope of every batch. The counter counts both as before. envelope_verdict takes the source, and a_gloas_mismatch_is_counted_but_not_refused runs both. 8e0d90d
  • Claude 6, the proposer in the block warning. Added. 8e0d90d
  • Claude 9, what pins the gloas field order. A comment at the two Amsterdam fields says they are pinned only by the real Platåberget envelope, and must be re-checked against the final EIP-7928 and EIP-7843 header before a mismatch is refused (Check the payload block hash rule on live nodes before gloas refuses #818). 8e0d90d
  • Claude 3, the permit pool. The cost bullet now says the pool is shared with data columns and envelopes only. The attestation, sync committee and builder topics have pools of their own. 17b4e41

Not changed

DeepSeek's review failed (empty content).

@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

Copy link
Copy Markdown

🤖 Gemini Code Review

This PR looks great. The execution header reconstruction across Bellatrix through Gloas is clean, well-isolated in crates/net/p2p/src/beacon/payload_hash.rs, and properly gated behind Outcome::Accept so unsigned gossip messages never trigger trie computation.

A few highlights:

  • DoS & equivocation protection (crates/net/p2p/src/beacon/verdict.rs:557-566): Recording (slot, proposer) in seen_blocks on Ignore(PayloadBlockHashMismatch) matches the P2P spec's "first block with a valid signature" rule and prevents a proposer from forcing repeated signature and trie checks within the same slot.
  • Peer scoring safety: Returning IGNORE rather than REJECT on pre-Gloas blocks avoids penalizing honest peers that do not run this rule, and counting-only on Gloas envelopes avoids bricking sync while Amsterdam header fields are not yet final.
  • Test coverage: Testing against real SSZ blocks/envelopes across all six execution-enabled forks (including >128 transactions for 2-byte RLP trie keys and multi-type EIP-7685 requests) gives strong confidence in the RLP header encoding.

LGTM!


Automated review by Gemini · gemini-4-argon · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Claude Code Review

Review: PR 770, payload block-hash check on gossip

The design is sound: the check is opt-in, gated on a verified signature, and returns IGNORE rather than REJECT. Wiring settle() into the seen cache closes the equivocation amplification hole. The real-chain vectors per fork are the right way to pin an RLP header encoding, and the deviation is well documented. I found no blocking issues; the items below are risks and nits.

Correctness / consensus

  1. Liveness risk if the encoding drifts (payload_hash.rs, block_verdict).

    • For bellatrix to fulu, a wrong encoding would IGNORE every gossip block. Their children would be IGNOREd too, so the "comes back by root" fallback never triggers. The node would only follow via range sync.
    • The vectors make this unlikely for the existing forks. The exposure is a future ethrex bump that changes encoding (e.g. [u8; 8] nonce or Address RLP).
    • Suggestions:
      • Add a circuit breaker: if the last N accepted-signature blocks all mismatched, log error! and stop refusing.
      • At minimum, make sure every_real_payload_matches_its_hash runs in CI on every ethrex tag bump.
  2. settle() seen-recording (verdict.rs ~L557). Treating Ignore(PayloadBlockHashMismatch) as a seen candidate is correct per "first block with a valid signature". One consequence is worth stating in the doc: if a proposer's bad block lands first, this node IGNOREs that proposer's honest block for the slot, while other clients will have accepted the bad one. The node then diverges from gossip for that slot until by-root/range sync. This is acceptable since the bad block is INVALID anyway, but it should be spelled out.

  3. verify_block Bellatrix pre-merge check (L~283). *payload == bellatrix::ExecutionPayload::default() allocates a fresh default, including a 256-byte bloom, on every call. Short-circuit on payload.block_hash == ExecutionBlockHash::ZERO && … before the full comparison, or cache the default in a LazyLock.

  4. computed_hash tail invariant (L~195). This is only a debug_assert!. Because Fields is constructed entirely in this module, that is fine. Making the shape unrepresentable would be cleaner, e.g. a nested Option<(withdrawals, Option<(blob, pbbr, Option<(requests, Option<amsterdam>)>)>)>. This is a nit.

Performance / DoS

  1. Worst case of 0.6 s per block inside the shared gossip_validation_permits pool.

    • An equivocating proposer can push up to 128 such blocks concurrently.
    • That pool also serves data columns and envelopes, so a single malicious proposer can stall column validation for its slot.
    • Consider capping transaction count or total bytes hashed before building the trie. MAX_TRANSACTIONS_PER_PAYLOAD is 2^20, but no real EL block approaches that. Alternatively, run the hash in a dedicated, smaller pool.
  2. Fetched envelopes (envelope_checks.rs, judge). Every envelope in range sync now builds a full transactions trie, only to increment a counter. That is pure overhead during sync. Consider sampling, or gossip-only checking until gloas refusal is enabled.

  3. Double copy of transactions (computed_hash). Fields::transactions collects Vec<&[u8]>, then tx.to_vec() copies each one again for the trie. This is unavoidable given ethrex's API, but the intermediate Vec<&[u8]> could be dropped by passing the iterator through. This is minor.

Rust idioms / maintainability

  1. Duplicated field mapping. Bellatrix, capella, deneb, and gloas each hand-write the same 14-field mapping into Fields. A small macro_rules! (or a common(payload) helper per payload type) would remove about 60 lines and reduce the chance of a copy-paste field swap.

  2. envelope_verdict. let _ = verify_envelope(envelope).inspect_err(|m| …) reads awkwardly. Prefer if let Err(mismatch) = verify_envelope(envelope) { … }.

  3. Default for bellatrix::ExecutionPayload. The value matches the spec's ExecutionPayload(), which is correct. A public Default on a consensus container makes it easy to build placeholder payloads accidentally elsewhere. Consider a named constructor (ExecutionPayload::empty(), mirroring BeaconBlockBody::empty()) instead of the trait.

Tests

The mutation tests per field and per fork are good. Two additions would strengthen them:

  • Electra encode-path ordering. Add a test asserting requests_hash is the SHA-256 of the empty list for the electra vector. Today this is implicit through the passing hash, but an explicit test would make a regression easier to locate.
  • verify_block for Gloas and Lean. Add a test that these variants return Ok(()) without inspecting anything, so a future change routing gloas blocks here gets noticed.

Overall this looks good to merge once Item 1 (circuit breaker or at least a documented guard) and Item 5 (a cost cap) are considered.


Automated review by Claude · claude-opus-5-5 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Codex Code Review

  • [P1] Bound concurrent trie construction before hashing — payload_hash.rs:149. A malicious proposer can burst signed equivocations containing 1,048,576 tiny transactions each. All can pass the seen check before the first hash finishes, allowing up to 128 concurrent trie builds. The documented benchmark puts each at roughly 0.6 seconds, creating substantial CPU and allocation pressure and starving block, column, and envelope validation. After signature verification, atomically reserve (slot, proposer) before constructing the trie, or give this optional check a separate, tightly bounded budget with an execution-client fallback.

The fork-specific header encoding otherwise looks consistent. Tests could not run because rustup attempted to write to a read-only directory.


Automated review by OpenAI Codex · gpt-6.1-sol · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Kimi Code Review

  • Blocking: the gloas mutation test should fail to compile. In crates/net/p2p/src/beacon/payload_hash/tests.rs, a_changed_gloas_field_is_refused mixes match arms returning () with bounded-SSZ push arms returning Result. This affects block_access_list.push(0), consolidations.push(consolidation()), and withdrawals.push(withdrawal()). Wrap those arms in braces and handle the result, as the electra test does:

    "withdrawal" => {
        message.payload.withdrawals.push(withdrawal())
            .expect("room for one more withdrawal");
    }

    Besides fixing the match’s type, this prevents a failed insertion from silently leaving the test vector unchanged.

  • Non-blocking security/performance concern: payload_hash.rs::Fields::computed_hash adds substantial attacker-controlled work after signature verification. The documented worst case is approximately 0.6 seconds per block, with up to 128 concurrent validations sharing the block/column/envelope pool—about 77 CPU-seconds per burst, plus large temporary transaction allocations. The seen-cache update in verdict.rs::settle only helps after the first verdict arrives. Consider a follow-up that deduplicates or throttles in-flight payload-hash checks by (slot, proposer) after signature verification, while preserving the existing first-valid-signature semantics.

Otherwise, the production logic looks careful: post-Accept gating limits unsigned-message DoS, the header field ordering and absent-option assertion are sound, the mismatch is correctly IGNOREd rather than REJECTed, and the real-chain vectors provide good fork-specific coverage.


Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 Grok Code Review

The header reconstruction is in good shape. Real-chain vectors for every fork, the IGNORE-vs-REJECT choice, and recording a hash mismatch as the first valid signature are the right calls. A few gaps are worth fixing before this is the thing standing in front of early fork-choice import.

  1. debug_assert! on header-tail order is the wrong severity. In Fields::computed_hash (payload_hash.rs, the tail check just before Encoder::new) a present field after an absent one shifts every later RLP item. That is compiled out of release builds, so a future fork edit would not panic: it would IGNORE every bellatrix–fulu gossip block (and increment the envelope counter for every gloas payload) while range/root sync still imports them. The node would then attest a stale head and the warns would look like bad proposers, not a local encoding bug. This should be assert!, or a hard error that fails the task loudly. Same class of footgun as a wrong Amsterdam field order, which you already refused to enforce for gloas.

  2. One signed block can occupy a shared validation permit for a long time. Trie::compute_hash_from_unsorted_iter in computed_hash copies every transaction and builds the trie on the blocking pool. Your own numbers are about 0.6 s for MAX_TRANSACTIONS_PER_PAYLOAD five-byte txs, several times that under load, and that pool is also columns and envelopes (gossip_validation_permits, 128). A proposer does not need equivocations for the slow case: one valid signature over a max-count payload is enough. Equivocations already in flight each pay that cost until the first verdict hits settle in verdict.rs. Consider a single-flight on (slot, proposer_index) after the signature check and before the trie, so only one in-flight block is hashed and the rest become AlreadySeen without the trie. That matches the spec's first-valid-signature rule and keeps column validation from stalling.

  3. The pre-merge skip is wider than is_execution_enabled. In verify_block, any bellatrix payload that compares equal to ExecutionPayload::default() returns Ok(()) without hashing. That is required before the merge (claimed hash is zero, the empty header hash is not). After the merge it is also a bypass: an all-zero payload is exactly the shape whose block_hash does not match, and it is the shape this check exists to keep off the early-import path. Accept means the store was available for the stateful checks, so this can be tightened to "skip only when execution is not yet enabled." A post-merge default payload should fall through to the hash compare and IGNORE.

Smaller notes, not blockers. Bloom::from_slice panics if logs_bloom is ever not 256 bytes; SSZ makes that unreachable today, but a fallible check would match the "do not panic the validation thread" bar better than the tail debug_assert!. The hand-rolled header (nonce as eight zero bytes, full-width base_fee_per_gas, rlp(index) trie keys) matches the vectors, including the two-byte key past index 127; keep a new execution-layer header field on the fork checklist, because a miss becomes Item 1 in production. Gloas count-only until the Amsterdam header is frozen is the correct call.


Automated review by Grok (xAI) · grok-4.7 · custom prompt

@github-actions

Copy link
Copy Markdown

🤖 DeepSeek Code Review

⚠️ Review failed: DeepSeek returned an empty content field (finish_reason=length, reasoning_content present=yes). Raise max_tokens or lower reasoning_effort ('none' disables thinking).


Automated review by DeepSeek

@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

Round seven (the automated review of 17b4e41). No changes. make fmt and make lint pass on this head.

Not changed

  • Kimi, the gloas mutation test "should not compile": the gloas lists are libssz ProgressiveLists, whose push returns (), so every arm is (). The test compiles (it is linted with all targets) and passed when the suite last ran.
  • Claude 2, an honest block IGNOREd after a bad first one: that second block is an equivocation, which every client IGNOREs under the first-valid-signature rule. The bad block fails at the other clients' execution clients, so nothing diverges.
  • Claude 10, a named constructor instead of Default: Default is the spec's ExecutionPayload(), as asked for in the first round, and its doc says so.
  • Claude, a test that gloas and lean blocks return Ok: an explicit arm of an exhaustive match; a test would only restate it.
  • Codex P1, Kimi, Claude 5, Grok 2, bounding hashing per (slot, proposer): Claim a gossip block's slot and proposer before its stateful checks #840.
  • Settled earlier: Claude 1 and Grok 3's switch (round six), Grok 1's assert! and the pre-merge skip (round five), Claude 3, 7, 8 and the empty requests hash (round three), Claude 6 and 9 (round four), Claude 4 (rounds five and six), and the Bloom length (rounds three and six).

Gemini said LGTM, and DeepSeek's review failed (empty content).

@MegaRedHand

Copy link
Copy Markdown
Collaborator Author

The review loop for this PR stops here: the last round raised nothing left to address. It only re-raised points settled in earlier rounds, plus a compile claim that does not hold. Follow-ups still open from this PR's rounds:

This branch has not been deployed

No deployments
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.

2 participants