Repository navigation
perf(beacon): verify a block's signatures in one random-weight batch - #738
Conversation
… addition A committee's key sum is the largest cost left in verifying an attestation once its keys are cached. Folding the keys one by one through AggregatePublicKey::aggregate pays a projective addition per key; blst_p1s_add (reached through the safe MultiPoint::add) shares one field inversion across the batch and runs 1.6-2.3x faster in a single-threaded measurement. From 384 points up blst also spreads the work over its own thread pool. fast_aggregate_verify and eth_aggregate_pubkeys now sum through one private helper, sum_validated_points, which guards the empty slice (MultiPoint::add indexes the first element). The helper returns the same group element as the sequential sum, including for repeated keys (sync committees are drawn with replacement, so P + P occurs), which the new tests check at sizes around the 384-point threshold. Accepted and rejected inputs are unchanged.
Block import paid one pairing per signature: the proposer's, the RANDAO reveal, every attestation, the sync aggregate and each slashing, exit and BLS change. A pairing is dominated by its final exponentiation, which a batch pays once, so a block with a dozen signature sets checks in a fraction of the time. ethlambda-crypto gains SignatureSet and verify_signature_sets: resolved checks combined with unpredictable non-zero 64-bit weights from the OS-seeded CSPRNG (without them two invalid signatures can cancel). The state transition builds each set where the specification verifies it and pushes it into a SignatureBatch that the block driver verifies once processing ends. A failing batch re-checks sets one by one so the error still names the first bad signature with its usual label. Signatures whose failure rejects the block are deferred; deposit signatures, whose failure only skips the deposit, stay immediate, as does epoch processing. process_block keeps its meaning and signature, apply_block adds the proposer's signature to the same batch. The operation packer in block production uses an immediate batch so a rejected candidate still writes nothing. The attestation validity helpers are split into a set builder plus the existing bool function, so gossip and fork choice are untouched.
SignatureSet::fast_aggregate now sums its keys with part a's batched sum_validated_points instead of a sequential AggregatePublicKey::aggregate, and the identity-key check in verify_signature_sets documents that blst rejects the same input.
…738) perf(beacon): verify a block's signatures in one random-weight batch Block import paid one pairing per signature: the proposer's, the RANDAO reveal, every attestation, the sync aggregate and each slashing, exit and BLS change. A pairing is dominated by its final exponentiation, which a batch pays once, so a block with a dozen signature sets checks in a fraction of the time. ethlambda-crypto gains SignatureSet and verify_signature_sets: resolved checks combined with unpredictable non-zero 64-bit weights from the OS-seeded CSPRNG (without them two invalid signatures can cancel). The state transition builds each set where the specification verifies it and pushes it into a SignatureBatch that the block driver verifies once processing ends. A failing batch re-checks sets one by one so the error still names the first bad signature with its usual label. Signatures whose failure rejects the block are deferred; deposit signatures, whose failure only skips the deposit, stay immediate, as does epoch processing. process_block keeps its meaning and signature, apply_block adds the proposer's signature to the same batch. The operation packer in block production uses an immediate batch so a rejected candidate still writes nothing. The attestation validity helpers are split into a set builder plus the existing bool function, so gossip and fork choice are untouched. Cherry-picked from perf/block-signature-batch at 7736808.
A key and its negation are both valid, so a registry can hold both and an aggregate can name both. Pin that the batched sum still matches the sequential one when keys cancel, that such a pair aggregates to the identity, and that the identity never verifies. Also state the CPU-count condition on blst's pool.
…tch unverified A block fetched by request reaches the state transition without gossip's precheck, and with the proposer's signature in the body's batch a block its proposer never signed was only rejected after the whole body ran. Check that one signature on its own again, before the body, as before the batch existed. A deferring SignatureBatch could also be built and dropped without its sets ever being checked, turning any function that takes one into "valid except for its signatures". Outside the crate, a deferring batch now only comes from SignatureBatch::deferred, which verifies once its closure returns. Also cover an infinity signature inside a batch and keys that cancel.
🤖 Codex Code ReviewLooks good overall. The PR is a sensible refactor toward reusable signature batching, and I did not spot a consensus-breaking issue in the changed paths.
No requested changes from me. If you want, I can also do a second pass specifically on whether PR 738 needs new regression tests around gloas block production and attestation batching. Automated review by OpenAI Codex · gpt-5.4 · custom prompt |
🤖 Claude Code ReviewReview: PR 738, per-block BLS signature batchI read the new Overall: the design is sound and I found no blocking issues. Soundness of the batch
Deferral semantics
Minor points (non-blocking)
LGTM, pending CI on the spec fixtures for both presets. Automated review by Claude (Anthropic) · sonnet · custom prompt |
🤖 Kimi Code ReviewI'll review this PR which implements BLS signature batching for block processing. This is a significant optimization and correctness change for consensus-layer signature verification. High-Level AssessmentThe PR introduces deferred signature batching across all beacon state transition forks, replacing individual pairing checks with a single random-linear-combination batch verification. This is a well-known optimization (2-3x faster for typical blocks), but requires careful handling because:
Detailed Review1. Core Batching Logic (
|
| Operation | Deferred? | Immediate fallback? | Correct? |
|---|---|---|---|
| Block proposer | No | N/A | Yes (early reject) |
| RANDAO | Yes | process_randao |
Yes |
| Attestation (all forks) | Yes | indexed_attestation_signature_set → verify |
Yes |
| Sync aggregate (non-empty) | Yes | SignatureSet::verify |
Yes |
| Sync aggregate (empty) | No (infinity check) | N/A | Yes |
| Proposer slashing | Yes | SignatureSet::verify |
Yes |
| Attester slashing | Yes | indexed_attestation_signature_set → verify |
Yes |
| Voluntary exit | Yes | SignatureSet::verify |
Yes |
| BLS to execution change | Yes | SignatureSet::verify |
Yes |
| Deposit | No | N/A | Yes (bad deposit skipped, not rejected) |
| Execution payload bid (gloas) | Yes | SignatureSet::verify |
Yes |
| Payload attestation (gloas) | Yes | SignatureSet::verify |
Yes |
All correct. Deposits remain immediate because a bad signature deposit is skipped (not rejected), which changes state transition behavior.
Performance Assessment
The batch verification uses blst's verify_multiple_aggregate_signatures with:
- One Miller loop per signature set
- One final exponentiation total
- Random 64-bit weights
For a typical block with ~16 attestations + RANDAO + sync aggregate + exits:
- Before: ~19 full pairings = ~19 final exponentiations
- After: ~19 Miller loops + 1 final exponentiation ≈ 3-4x faster
The SignatureSet construction validates keys/signatures once, avoiding re-validation in the batch. Good.
Final Verdict
Approve with minor suggestions.
The PR is correct, well-tested, and implements a significant optimization safely. The deferred batch pattern with immediate fallback for block production is sound.
Suggested changes:
-
Document
INFINITY_FLAGsource (crates/common/crypto/src/bls/batch.rs:75):/// The bit of a compressed G1 point's first byte that marks the point at /// infinity (Zcash BLS12-381 §1.2: "The most significant three bits of /// u[0] are used to unambiguously represent the underlying element"). const INFINITY_FLAG: u8 = 0b0100_0000;
-
Add safety comment (
crates/blockchain/state_transition/src/beacon/stf/signatures.rs:142):// Unreachable with correct BLS batch verification: if the batch failed, // at least one individual set must fail. This is a defense-in-depth panic. verify(false, last)
-
Clarify test wrapper (
crates/blockchain/state_transition/tests/beacon_spec/operations.rs:174-192):
Add comment explaining theunhandledpattern for operation-name errors vs. state-transition errors. -
Consider whether
process_block_and_verifyshould be the pattern for all forks, not just gloas
Automated review by Kimi (Moonshot AI) · kimi-k2.6 · custom prompt
…738): review fixes fix(beacon): check the proposer's signature first and never drop a batch unverified A block fetched by request reaches the state transition without gossip's precheck, and with the proposer's signature in the body's batch a block its proposer never signed was only rejected after the whole body ran. Check that one signature on its own again, before the body, as before the batch existed. A deferring SignatureBatch could also be built and dropped without its sets ever being checked, turning any function that takes one into "valid except for its signatures". Outside the crate, a deferring batch now only comes from SignatureBatch::deferred, which verifies once its closure returns. Also cover an infinity signature inside a batch and keys that cancel. Updates nightly's #738 from perf/block-signature-batch at 7736808 to e6eeb5b.
…and resources (#756) The import replay reported `stf` as one number, which is most of a mainnet block's import but does not say which step of the transition to attack, nor whether an epoch-crossing block, a block after skipped slots and an ordinary block differ. The beacon STF had no internal timing at all. lean_beacon_stf_phase_seconds{context,phase} is observed around the steps of the transition: process_slots (excluding epoch work), process_epoch, the block signature, header (including the body hash it commits to), randao, eth1 data, execution payload (gloas: parent payload, withdrawals, bid), each operation list, the sync aggregate and the post-state root check. One Instant pair per step, none per attestation; an empty list observes nothing. The phase list is generated with the enum that the code observes through, so the two cannot disagree. The epoch precompute worker runs process_epoch on another thread while an import runs, and the replay reads the histogram before and after each block, so one series would charge the worker to whichever block was importing. The series is split by a context label instead: only fork_choice's transition_block sets `import` (a thread-local guard, since the steps are observed deep inside the per-fork block processing), and every other caller writes `other`. The replay reads only `import`. The replay report (schema_version 2) gains per block: the STF steps, the stf time outside any step, a class (epoch_boundary, after_skip, ordinary), process CPU seconds and RSS; and per run: p95 and p99, a per-class summary and the deltas of the cache lookup counters, so precompute hit rates appear in it. Consensus behavior is unchanged. Adapted onto nightly: block processing now defers every signature but the proposer's into one `SignatureBatch` (#738), so the old inline checks the timers wrapped no longer exist. Every call site keeps nightly's `signatures` argument and order, with the timers wrapped around the same steps as before; the proposer signature stays immediate and is still timed as `block_signature`. A new phase `batch_signatures` times `SignatureBatch::verify`, the one random-weight check of everything the steps deferred, so the verify cost that used to sit inside `randao`, the operation lists and `sync_aggregate` is now its own series. Those phases now cover building the signature sets and the state changes, not verification, and docs/metrics.md and docs/benchmarking.md say so. The phase is declared in the `StfPhase` enum, so the label list stays generated from it. replay.rs keeps both `--warm-committee-sums` (warm-up before the timers start) and the report changes; the report test for warm_committee_sums gets the new `Caches` argument. Verdicts, order and errors are nightly's. docs/benchmarking.md keeps #755's paragraph on the overlapped transition ahead of this section. Cherry-picked from perf/beacon-stf-phase-timing at c891134, adapted in 5c385e084.
Block import benchmark (offline replay of mainnet blocks, steady state)
Method
|
pablodeymo
left a comment
There was a problem hiding this comment.
Review notes on the deferred batch signature verification. The first two inline comments (DoS cost of forged blocks, state mutated by unverified operations) are the ones worth resolving before merge.
One more that falls outside the diff: crates/common/crypto/src/bls.rs (~L329), bls::verify and bls::fast_aggregate_verify still implement the full validate/sum/pair sequence themselves instead of SignatureSet::single(..).is_some_and(|s| s.verify()). Only tests keep the two copies in sync, and a drift would make gossip/fork choice (bls::*) disagree with block import (SignatureSet).
| /// | ||
| /// The re-checks run on rayon's pool, so a failing batch costs the batch | ||
| /// plus one round of single checks spread over the cores. That stays | ||
| /// bounded: only a block that is rejected pays it, the block's operation |
There was a problem hiding this comment.
Forged blocks now cost ~100x more CPU on import. Deferring every body signature to the end means a block with forged attestation/slashing/exit signatures runs every operation, then a ~130-set multi-pairing, then a par_iter single re-check of every set, where before it was rejected after one or two pairings at the first attestation. Only one valid proposer signature is needed, and one proposer key can sign any number of equivocating blocks for its slot; by-root/by-range sync skips gossip's per-proposer-slot dedup. The doc's "bounded because it takes the slot proposer's key" doesn't hold. Suggestion: verify the attestation sets first, or bail to per-set checks as soon as the first operation's signature fails.
There was a problem hiding this comment.
Two changes in 477ca69, and one place where I'd push back on the framing.
A failed batch no longer re-checks every set on its own. first_failing in stf/signatures.rs bisects: it checks the first half of the range that holds the first failing set and keeps the half that answers. The halves shrink by half each step, so it checks fewer sets than the batch had, at one final exponentiation per step: about 8 for a ~130-set block, instead of 130 pairings. The label is still the first failing set in push order (bisection_finds_the_first_bad_set_at_every_position).
Slashings, exits and BLS-to-execution changes now call SignatureBatch::verify_pending before they write, which checks their sets together with everything pending. A forged one stops the block at that operation, as before. (That is also the fix for the next thread.)
On "before it was rejected after one or two pairings": that was the cheapest forged block, not the costliest. With immediate checks a forger who wants us to do the work puts the bad signature on the sync aggregate, the last signature a block carries (process_operations then process_sync_aggregate, stf/electra.rs:1884-1885 on main). main then runs every operation and n standalone checks before rejecting. So the worst case was already a whole body.
In blst units, a standalone check is two Miller loops (key and message, then the signature in PAIRING_FinalVerify) and one final exponentiation. A batch of n is n+1 Miller loops and one final exponentiation, plus a 64-bit scalar multiplication in G1 and in G2 per set for the weights.
main's worst case, forn= 130: ~260 Miller loops, 130 final exponentiations, 130 hash-to-curves.- 63ba4aa added the batch and a full re-check on top of that, so you're right that it was strictly worse.
- Now it is the batch plus the bisection: ~270 Miller loops, ~10 final exponentiations, up to ~260 hash-to-curves, and the weights' scalar multiplications.
So about main's Miller loops, far fewer final exponentiations, more hashing. I haven't measured the net in wall time. The doc's "bounded because it takes the slot proposer's key" is gone; the module doc has a "What a forged block costs" section saying the above.
I didn't add a separate up-front pass over the attestations. Their sets come out of get_indexed_attestation and the key sums, which are most of what processing an attestation costs. A second pass would do that work twice for honest blocks and still not lower the worst case, which sits in the sync aggregate. The many-equivocating-blocks-through-sync point holds on main too; capping how many blocks per (proposer, slot) sync imports would be a separate change.
| //! observed. What must stay immediate is a signature whose failure does *not* | ||
| //! reject the block but changes what happens next: a deposit with a bad | ||
| //! signature is skipped and the block carries on, so that check cannot wait. | ||
| //! |
There was a problem hiding this comment.
With signatures deferred, operations whose signatures are forged mutate the state before later operations run. "Reaches no state a valid block could not" holds only if every key holder colludes; one attacker can now combine forged slashings + exits + BLS changes into a state no honest set of signers produces, making any unwrap/unreachable!/overflow that assumes those combinations impossible reachable. Also, transition_block returns the partly mutated state alongside the Err, so correctness now relies on an undocumented "never read the state after Err" rule.
There was a problem hiding this comment.
Agreed, the "reaches no state a valid block could not" argument assumed every key holder signs, which a forger doesn't need. Fixed in 477ca69: every operation that changes a validator's record checks its own sets, and everything pending, through SignatureBatch::verify_pending before it writes. That covers proposer and attester slashings, voluntary exits and BLS-to-execution changes. The RANDAO reveal does the same before the mix (next thread). So none of them writes on a forged signature, and none runs on a state an earlier forged signature wrote to. A block can no longer stack forged slashings, exits and credential changes.
What stays deferred is vote accounting: attestations (participation flags and the proposer's inclusion reward, what honest votes for the same data write), the sync aggregate (the last step of a block, so nothing runs after it), and gloas payload attestations (no writes). One write still precedes its check. The gloas bid records the builder's payment and the bid before its signature is verified. It is verified right after, together with the RANDAO reveal, before any operation runs, so nothing reads that record unverified. That holds whenever the reveal is verified, which import always does. I didn't give the bid a check of its own, which would cost another final exponentiation per gloas block for a write nothing reads in between. The module doc's "What may be deferred" section lists all four (af1671d). a_credential_change_checks_its_signature_and_every_pending_one_before_it_writes (147d418) pins it: through a deferring batch, a forged change is refused by the operation itself, and a genuine one is refused under the earlier set's label while a forged set is pending, with the credentials untouched both times. Before the change, the first call returned Ok and rewrote them.
transition_block now returns Result<BeaconState> instead of (BeaconState, Result<()>), and SpeculativeTransition holds that Result (93b4566). A failed transition has no state to read, so the rule is in the type, not in a doc.
| @@ -295,8 +354,8 @@ pub fn process_randao( | |||
|
|
|||
| let proposer = state.validator(proposer_index)?; | |||
| if verification == RandaoVerification::Verify { | |||
There was a problem hiding this comment.
The RANDAO reveal is XORed into randao_mixes before its signature is verified, so anything later in the same block reading the current mix (gloas get_seed/get_randao_mix) sees an attacker-chosen value until the batch fails at the end. This inverts the spec's verify-then-mix order.
There was a problem hiding this comment.
Fixed in 477ca69. process_randao pushes the reveal's set and calls verify_pending before it touches randao_mixes, so it is verify-then-mix again. In gloas, the builder's bid is pushed just before and is checked in the same batch, so nothing reads the bid's write unverified either. Tests in stf/block.rs: a_bad_randao_reveal_is_rejected_before_it_is_mixed_in checks the mix is unchanged after the rejection. a_bad_set_pending_before_the_reveal_is_rejected_with_it is the bid's case.
Cost: one more final exponentiation per block than 63ba4aa, since the reveal no longer shares the body's batch. The alternative was to fold it into apply_block's up-front proposer check as a 2-set batch. I didn't, because that would make an unsigned block cost more than the one pairing you asked to keep in the next thread.
| /// The proposer's signature check [`verify_block_signature`] makes, resolved | ||
| /// but not yet run. `None` is a proposer index outside the registry, or a key | ||
| /// or signature that does not validate. | ||
| pub fn block_signature_set( |
There was a problem hiding this comment.
block_signature_set is new public API whose only caller is verify_block_signature. It's left over from when the proposer signature was batched, and keeping it public invites someone to batch it again, undoing the "reject an unsigned block after one pairing" property apply_block relies on. Suggest inlining it or making it private.
There was a problem hiding this comment.
Removed in fa8c70f. verify_block_signature calls verify_proposer_signature directly, and its doc says it is checked on its own, never batched, so an unsigned block costs one pairing.
|
|
||
| /// [`indexed_attestation_signature_set`] under a signing domain the caller | ||
| /// chose. | ||
| pub fn indexed_attestation_signature_set_with_domain( |
There was a problem hiding this comment.
Each of helpers/{attestation,electra,gloas}.rs now has four near-identical functions (is_valid_*, is_valid_*_with_domain, *_signature_set, *_signature_set_with_domain). The bool versions are just .is_some_and(|s| s.verify()), so 12 functions could be 6, and *_signature_set_with_domain is pub with only same-module callers. Fixes to the structural checks still have to be made in three places.
There was a problem hiding this comment.
Done in b22918d. The rules live once, in helpers::attestation::attesters_signature_set: non-empty, at most MAX_VALIDATORS_PER_SLOT, sorted and unique, every index in the registry, then the set. It takes the attester list, data and signature of any fork's container and an optional domain. Phase0, electra and gloas each keep is_valid_indexed_attestation and indexed_attestation_signature_set, one line each over it. Both _with_domain variants are gone; gossip's aggregate validation, their only caller, calls the shared builder with the schedule's domain. The length bound is gloas's, and the earlier forks' list types are bounded at or below it, so it changes none of their answers. New test: only_a_sorted_unique_list_of_known_validators_builds_a_set.
| &sync_aggregate.sync_committee_signature, | ||
| ), | ||
| eth_fast_aggregate_verify, | ||
| )?; |
There was a problem hiding this comment.
This re-implements bls::eth_fast_aggregate_verify's empty-participants rule (must be G2_POINT_AT_INFINITY) inline, while block production's sync-aggregate precheck (block_production.rs:153) still uses the helper. If the two drift, the node packs aggregates its own STF rejects. A SignatureSet constructor returning trivially-valid / set / invalid would keep one definition.
There was a problem hiding this comment.
Done in 01e0024. SignatureSet::eth_fast_aggregate holds the rule and answers EthFastAggregate::{Valid, Invalid, Pairing(set)}. bls::eth_fast_aggregate_verify is SignatureSet::eth_fast_aggregate(..).verify(), which is what block production's verified_sync_aggregate calls. process_sync_aggregate matches on the same value: Valid passes, Invalid rejects, Pairing is pushed. Tests: no_participants_is_decided_without_a_pairing, participants_are_checked_by_their_pairing (the second compares against bls::eth_fast_aggregate_verify).
| } | ||
|
|
||
| /// Whether every set verifies, in one random-linear-combination check: | ||
| /// `verify_multiple_aggregate_signatures` with 64-bit scalars from the |
There was a problem hiding this comment.
The key_is_identity pre-check is redundant by its own doc (blst already rejects identity keys, "changes no behavior"), and the [only] => only.verify() arm returns before it, so it doesn't apply to single-set batches. Either drop it or apply it uniformly as a real guard, including in SignatureSet::verify.
There was a problem hiding this comment.
Dropped in 619e202. blst refuses an infinite public key wherever it adds one to a pairing (BLST_PK_IS_INFINITY, blst/src/aggregate.c in the min_pk path), and both the single check and verify_multiple_aggregate_signatures go through it. verify_signature_sets' doc now says that instead of claiming a check. keys_that_cancel_never_verify_alone_or_in_a_batch stays: [P, -P] fails alone and inside a batch, with the identity signature and with a real one, now with nothing of ours in the way.
| //! The weights must be unpredictable to whoever chose the signatures: with | ||
| //! independent uniform 64-bit weights, a forged batch passes with probability | ||
| //! about 2^-64, which is the soundness level every consensus client accepts. | ||
| //! They are drawn from `rand`'s thread-local CSPRNG, which is seeded from the |
There was a problem hiding this comment.
Nit: the soundness argument says rand::rng() is "reseeded periodically", but rand 0.10's ThreadRng dropped the periodic-reseeding wrapper. It's still an OS-seeded CSPRNG, so this isn't exploitable, but the documented guarantee is inaccurate.
There was a problem hiding this comment.
I looked, and the locked version still reseeds. rand 0.10.0 removed the public ReseedingRng type, but ThreadRng in rand 0.10.1 (what Cargo.lock pins) wraps its ChaCha12 core in an internal ReseedingCore that reseeds from SysRng every 64 KiB (rand-0.10.1/src/rngs/thread.rs, RESEED_BLOCK_THRESHOLD; its doc says "Automatic seeding via SysRng and after every 64 kB of output"). Your underlying point stands, though: the argument shouldn't lean on that. The doc now says soundness rests only on the OS-seeded CSPRNG being unpredictable, and mentions the reseeding as something nothing depends on (619e202).
| /// A block's signature batch failed while every set in it verified alone, | ||
| /// which only a bug in the batch check can cause. The block is rejected all | ||
| /// the same, so a non-zero value means this node may be refusing valid blocks. | ||
| pub fn inc_signature_batch_disagreements() { |
There was a problem hiding this comment.
Nit: CLAUDE.md prefers module-scoped LazyLock statics for state_transition metrics; this one is function-scoped, unlike LEAN_BEACON_COMMITTEE_CACHE_LOOKUPS_TOTAL just below.
There was a problem hiding this comment.
Moved to a module-scoped LazyLock like LEAN_BEACON_COMMITTEE_CACHE_LOOKUPS_TOTAL (0521d9d). The help text and the docs/metrics.md row now describe what it counts with the bisection: a failed batch whose narrowed-to set verifies on its own.
…e RANDAO mix changes A deferred signature let its operation write before the signature was known to be good, and every later operation ran on that write. That is now confined to votes: 1. Proposer and attester slashings, voluntary exits and BLS-to-execution changes call SignatureBatch::verify_pending before they write, so their own sets and every set still pending are checked first. No operation that slashes, exits or redirects a validator writes on a forged signature or runs on a state an earlier forged signature wrote to. A forged one is refused at its own operation. 2. The RANDAO reveal is checked the same way before it is mixed in, the specification's order. In gloas the builder's bid, pushed just before it, is checked in the same batch. 3. A failed batch is bisected to its first failing set instead of re-checking every set on its own: fewer set checks than the batch had, at one final exponentiation per halving, rather than a full pairing per set on top of the batch. Attestations, the sync aggregate and gloas's payload attestations still go into one batch, checked at the next of those points or at the end.
transition_block returned the partly applied copy alongside the error, so nothing but convention kept a caller from reading a state that a rejected block had written to. It now returns Result<BeaconState>, and SpeculativeTransition holds that Result, so a failed transition has no state to read.
Its one caller was verify_block_signature, and as public API it invited batching the proposer's signature again, which would undo the one-pairing rejection of an unsigned block apply_block relies on. verify_block_signature now calls verify_proposer_signature directly.
…ecks Phase0, electra and gloas each had four functions for one check: is_valid_indexed_attestation, its _with_domain variant, and the two matching signature-set builders, with the structural rules copied into each fork's file. The rules now live once, in attestation::attesters_signature_set, which takes the attester list, data and signature of any fork's container and an optional domain. Each fork keeps is_valid_indexed_attestation and indexed_attestation_signature_set, both thin over it: six functions where there were twelve. The _with_domain pair is gone; gossip's aggregate validation, its only caller, calls attesters_signature_set with the schedule's domain. The shared check includes gloas's MAX_VALIDATORS_PER_SLOT bound. Every earlier fork's attester list is bounded at or below it by its own type, so the check changes no earlier fork's answer.
key_is_identity changed no behavior, by its own documentation: blst refuses an infinite public key wherever it adds one to a pairing (BLST_PK_IS_INFINITY in blst/src/aggregate.c), on the batch path and the single path alike, and the single-set arm returned before the check anyway. The tests that pin it stay: [P, -P] fails alone and inside a batch, with the identity signature and with a real one. Also states what the random weights' soundness rests on. rand::rng() is a ChaCha12 generator seeded from the operating system; rand 0.10.1, the locked version, still reseeds it every 64 KiB, but the argument does not need that.
bls::verify and bls::fast_aggregate_verify each repeated the validate, sum and pair sequence SignatureSet holds, so only tests kept gossip and fork choice deciding a signature the way block import does. They are now SignatureSet::single and SignatureSet::fast_aggregate followed by its verify. eth_fast_aggregate_verify's empty-participants rule (valid exactly with G2_POINT_AT_INFINITY) was written twice: in bls, which block production's sync-aggregate check calls, and inline in altair's process_sync_aggregate. It now lives in SignatureSet::eth_fast_aggregate, which answers Valid, Invalid, or the set whose pairing decides. bls::eth_fast_aggregate_verify is that answer checked now, and the sync aggregate pushes the set or rejects from it.
…t module scope The state transition's metrics are module-scoped LazyLock statics, as CLAUDE.md prefers; this was the one function-scoped. Its help text and docs/metrics.md now say what it counts since the failing set is found by bisection: a failed batch whose narrowed-to set verifies alone.
… writes Pins the ordering for one of the operations that change a validator's record: through a batch that defers, a forged BLS-to-execution change is refused by the operation itself, and a genuine one is refused under the earlier set's label while a forged set is pending, with the credentials untouched both times. With the signature deferred to the end of the block, the first call returned Ok and rewrote them.
…check The signatures module doc said deferral was confined to votes, but process_execution_payload_bid records the builder's payment and the bid before its signature is checked. It is checked right after, with the RANDAO reveal, before any operation runs, whenever the reveal is verified (always on import; block production skips it for its own block). The doc now says so. Also corrects the cost wording: a bisection costs about what the batch did, not less, and a lone check is a pairing with a Miller loop of its own for the signature, which is what a batch saves along with the final exponentiation.
Done in 01e0024. I also replied on each inline thread. In short: slashings, exits, BLS changes and the RANDAO reveal are now checked, with everything pending, before they write, and only vote accounting is deferred. A failed batch is bisected instead of re-checked set by set. |
|
/review |
🤖 Codex Code ReviewNo actionable findings. The BLS batching preserves input validation, checks sensitive operations before mutation, and discards failed transition states. 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 |
🤖 Gemini Code ReviewThis PR looks great. The batch verification design and safety boundaries are well thought out:
No issues found — LGTM. Automated review by Gemini · gemini-4-argon · custom prompt |
🤖 Claude Code ReviewReview: batched BLS signature verification (PR 738)Verdict: the design is sound and the PR is mergeable. Items 1–3 are worth addressing; the rest are nits. What checks outSoundness of the batch
Deferral boundaries
Issues and suggestions
Performance
Automated review by Claude · claude-opus-5-5 · custom prompt |
🤖 DeepSeek Code ReviewA few concerns before merge:
The Automated review by DeepSeek · deepseek-v4-pro · custom prompt |
🤖 Kimi Code ReviewNo blocking correctness or security issues found. The deferred-verification design remains fail-closed:
Automated review by Kimi (Moonshot AI) · kimi-k3.1-pro · custom prompt |
🤖 Grok Code ReviewThe batching design is careful: invalid blocks still fail closed, state-changing operations call
I did not see a signature whose failure must not reject the block (deposits) get deferred, and the payload-attestation duplicate rule ( Automated review by Grok (xAI) · grok-4.7 · custom prompt |
Main's one-batch signature verification (#738) and this branch both appended a parameter to the same block-processing functions. Each keeps both, `target_delta` before `signatures`; the three `process_operations` that reach eight arguments allow clippy's too_many_arguments, like their siblings. `transition_block` takes main's `Result<BeaconState>` shape and calls the `*_with_options` entry points. `SpeculativeTransition` holds main's `transition` beside this branch's `target_delta`, and `assert_agrees_with` compares both. The delta test wraps `process_attestation` in `checked`, as main's single-operation tests do.
Stack 2/4 of the BLS verification work: (a) batched key sums -> (b) per-block signature batch -> (c) committee key sums -> (d) index-keyed pubkey cache. Based on (a), which has merged (#737), so this now targets main.
What changed and why
Block import checked every signature with its own pairing: the proposer's, the RANDAO reveal, each attestation, the sync aggregate and any slashings, exits and BLS changes. A pairing check is dominated by its final exponentiation, which a batch pays once for all sets.
ethlambda-crypto: newbls/batch.rswithSignatureSet(single,fast_aggregate,eth_fast_aggregate,verify) andverify_signature_sets. A set is the resolved inputs of a check (validated and summed key, message, validated signature); a batch isverify_multiple_aggregate_signatureswith 64-bit non-zero weights fromrand::rng(), a ChaCha12 generator seeded from the operating system. Random weights are required: without them two invalid signatures can be crafted to cancel; with unpredictable 64-bit weights a forger succeeds with probability about 2^-64. A single set skips the weights. An identity key (keys summing to it) fails alone and in a batch because blst refuses infinite public keys on both paths.bls::verify,bls::fast_aggregate_verifyandbls::eth_fast_aggregate_verifyare built onSignatureSet, so gossip, fork choice and block import decide a signature with one piece of code.SignatureSet::eth_fast_aggregateholds the empty-participants rule (valid exactly withG2_POINT_AT_INFINITY) once, answeringValid,Invalid, or the set whose pairing decides.ethlambda-state-transition: newstf/signatures.rswithSignatureBatch. Operations build their set where the specification verifies it and push it with the same label the immediate check used. Outside the crate there are only two ways to get a batch, and both check every set:SignatureBatch::deferred(|batch| ...)verifies what is pending once the closure returns, andimmediate()checks at push time (see below).stf::block::process_blockkeeps its signature and still means "the block is valid": it runs the body insideSignatureBatch::deferred.apply_blockchecks the proposer's block signature on its own first, as before this PR: a block fetched by request reaches the STF without gossip'sprecheck_block, so a block its proposer never signed is still rejected after one pairing rather than after the whole body.helpers::attestation::attesters_signature_set(non-empty, at mostMAX_VALIDATORS_PER_SLOT, sorted and unique, in the registry). Phase0, electra and gloas each keepis_valid_indexed_attestationandindexed_attestation_signature_setover it; gossip's aggregate validation calls it with the schedule's domain.Deferred, and checked before writing
A deferred signature lets its operation write before the signature is known to be good, so deferral is confined to votes, and to one write nothing reads before its check:
altair.rs, the last step of a block; no participants is decided without a pairing), gloas payload attestations (no writes).SignatureBatch::verify_pending): the RANDAO reveal, before the mix; proposer slashing headers (operations.rs, shared by gloas); attester slashings (phase0, electra, gloas); voluntary exits (phase0, deneb, electra); BLS to execution changes (capella.rs).No operation that slashes, exits or redirects a validator writes on a forged signature or runs on a state an earlier forged signature wrote to. A block of ordinary votes still checks all of its attestations and its sync aggregate in one batch.
Immediate, unchanged (failure changes state but does not reject): every deposit signature (
operations.rs,electra.rs,epoch/electra.rs) and the gloas builder deposit signature. The gloas envelope signature is not reachable fromprocess_block. Immediate, as onmain: the proposer's block signature (apply_block).Behavior notes
Errfromprocess_blockleaves the state partly applied, as any mid-block failure did, now including an attestation or sync aggregate whose signature turns out bad at the end.transition_block(fork_choice.rs) returnsResult<BeaconState>, so no caller can read a failed transition's state.SignatureBatch::immediate(), which checks at push time.gloas::process_block_and_verifyis the helper for the direct gloas drivers in block production.Cost of a forged block
Rejecting a block whose body carries a bad signature costs the processing up to the check that catches it, that batch, and the bisection.
With immediate checks a forger already got a whole body processed, by putting the bad signature on the sync aggregate, the last one checked. That cost every operation plus
nstandalone checks, each two Miller loops and a final exponentiation.Now a forged slashing, exit or credential change stops at its own operation. A forged vote costs every operation, the batch (
n+1 Miller loops, one final exponentiation), and the bisection (sets totalling fewer thann, about log2nfinal exponentiations). Both pay the weights' 64-bit scalar multiplications. Forn= 130 that is about the same Miller loops as before this PR, about 10 final exponentiations instead of 130, and up to twice the hash-to-curve. Not measured in wall time.Measured
On a loaded M3, the pairing per block took 2.7-4x less wall time with one batch. That ratio mixes two effects: fewer final exponentiations, and blst's
verify_multiple_aggregate_signaturesspreading the Miller loops over its own pool where the old per-set check used one worker. CPU time drops too: profiling a Hoodi block replay on a Ryzen 9700X (the whole stack, warm caches) puts pairing and hash-to-curve at 7.9 ms CPU per block before and 2.4 ms after. That run predates the review fixes that take the proposer's signature and the RANDAO reveal out of the body's batch, so a block now pays two more final exponentiations than profiled: three for a block with no slashing, exit or credential change (proposer; RANDAO; body), against one per signature set before this PR.Tests
ethlambda-crypto: the batch tests cover a valid batch of ten, one bad among ten, swapped signatures, empty batch, single set, repeated messages, mixed single and aggregate, an invalid aggregate inside a batch, agreement withbls::verifyandbls::fast_aggregate_verify,Nonefor invalid inputs, weights never zero, an infinity signature among valid sets, keys that cancel ([P, -P]never verifies, alone or in a batch;[P, P, -P]verifies underP's signature), andeth_fast_aggregatewith and without participants (agreeing withbls::eth_fast_aggregate_verify).ethlambda-state-transition --lib: bisection lands on the first bad set at every position for several batch sizes;verify_pendingclears what it checked; a bad RANDAO reveal is rejected before the mix changes, and so is a bad set pending before it; a valid reveal is checked, not deferred; a forged BLS-to-execution change is refused by the operation itself and a genuine one while a forged set is pending, credentials untouched; the shared attester-list rules; deferred and immediate failures carry the same label.beacon_spec_tests: the operation runner builds a batch around each operation and treats anErrfrom the operation or from the batch as the rejection.Before the second review round: crypto
--lib32 passed; state-transition--lib655 passed;beacon_spec_testsunfiltered (mainnet preset) 7493 passed, 977 ignored, 0 failed; on the stack's tip, storage 213, blockchain 291, p2p 362, rpc 335 passed.After the second review round:
make fmt,make lintandcargo clippy -p ethlambda-state-transition --all-targets --features beacon-spec-tests -D warningsare clean; the test suites were not rerun locally and are left to CI.