diff --git a/.github/workflows/docker_publish.yaml b/.github/workflows/docker_publish.yaml index ac598b4ea..bf9f8e12d 100644 --- a/.github/workflows/docker_publish.yaml +++ b/.github/workflows/docker_publish.yaml @@ -13,10 +13,6 @@ on: tags: description: "Docker image tags, comma-separated (e.g., devnet5,devnet5-fix)" required: true - leanvm_rev: - description: "leanVM commit, tag or branch to build the PQ prover sidecar from (blank: the one in leanvm-revision)" - required: false - default: "" permissions: contents: read @@ -112,11 +108,9 @@ jobs: with: context: . file: ./Dockerfile - # An empty LEANVM_REV builds the sidecar from leanvm-revision. build-args: | GIT_COMMIT=${{ github.sha }} GIT_BRANCH=${{ github.ref_name }} - LEANVM_REV=${{ inputs.leanvm_rev }} ${{ matrix.variant.build_args }} push: true tags: ${{ steps.prep.outputs.tags }} diff --git a/CLAUDE.md b/CLAUDE.md index a632b0e11..557aaab35 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,7 +102,9 @@ make test # All tests + forkchoice spec tests `make test` is `test-consensus` plus `test-node`, two halves CI runs as separate jobs because together they no longer fit a runner's disk. `CONSENSUS_CRATES` in the Makefile names the first; `test-node` is the workspace minus it. Run one half -directly when iterating on it. +directly when iterating on it. `test-consensus` also runs the PQ fork's +end-to-end leanVM prover test by name (`leanvm_proofs_merge_and_verify`, ignored +by a plain `cargo test`, which spends minutes on it unoptimized). ### Docs-only changes skip CI @@ -300,18 +302,30 @@ actual_slot = finalized_slot + 1 + relative_index signatures, a port of leanVM `4af2cddd`'s Rust implementation pinned by consensus-specs' and leanVM's known answers), and proves many signatures at once through `ethlambda_crypto::stark`: the specification's reference (the - signatures concatenated) by default, or real leanVM proofs from a - `leanvm-sidecar` process (leanVM `c5ee9d239`, bindings v0.15.0, the - release pq-devnet-0 runs for its signer, prover, verifier and sidecar), - which is what the PQ devnet runs. The node only connects to a sidecar - (`--pq-prover-socket`); as for Lighthouse, something else starts it: the - image's `ethlambda-pq` supervisor (`bin/ethlambda/pq/`), run as - `ethlambda-pq beacon `. The image builds `leanvm-sidecar` from the - revision in the root `leanvm-revision` file (or `--build-arg LEANVM_REV`), - so which prover a devnet runs is chosen outside the node; the node's client - only refuses a sidecar with another protocol version or verifier tag. - The two encodings do not verify each other's proofs. Never pass one - scheme's key to the other + signatures concatenated), or real leanVM proofs made in process + (`stark::leanvm`, leanVM `351f7ae4`, bindings v0.19.0, the one release + pq-devnet-1 runs for signer, prover and verifier; `lean_vm` with its + experimental prover). `run_node` installs leanVM as soon + as `--network` resolves to a network that schedules PQ, on + `--pq-prover-threads` threads (0: one per core, never more than the + cores); the reference is then only what the spec tests run. Setup ends + with a self-check (one signature proved and verified) that fails startup, + and every call into leanVM is wrapped in `leanvm::guarded`, since a panic + there would otherwise unwind into the chain actor importing a block: it + reads as a proof that does not verify, or was not made. The image builds + the prover with leanVM's CPU tiers (`leanvm-cpu-tiers` feature plus + leanVM's `scripts/tier-rustc` as `RUSTC_WRAPPER`, fetched by the + Dockerfile at the pinned revision), picked at run time; a plain `cargo + build` has no tiers and proves on `.cargo/config.toml`'s baseline. + `ethlambda pq-prover-check` measures the prover on a host against a + seat's 2.4 s proving window. v0.17.0 removed pq-devnet-0's + `leanvm-sidecar`, so the image builds none, and `ethlambda-pq` + (`bin/ethlambda/pq/`) is now a shim that execs `ethlambda`, kept for + launchers that still call it. A proof from another leanVM revision does not + verify, and nothing on the wire says why; the root `leanvm-revision` file + names the pin (a test holds it equal to the manifest's `rev`s, and the + Dockerfile reads it). The two encodings do not verify each other's proofs. + Never pass one scheme's key to the other - Wire sizes: `PUBLIC_KEY_SIZE` (`common/types/src/state.rs`) and `SIGNATURE_SIZE` (`common/types/src/attestation.rs`), static-asserted against leanVM's scheme constants in `common/crypto/src/signature.rs` @@ -540,7 +554,15 @@ the next fork the node cannot follow: the first refuses such an anchor with `UnsupportedFork`, the second warns once per scheduled fork for which `ForkName::is_followed` answers no (the one place that says which forks the node follows). The ignored-keys warning only ever names heze's keys and -`GAS_LIMIT_SCHEDULE`/`INCLUSION_LIST_DUE_BPS`. +`INCLUSION_LIST_DUE_BPS`. `GAS_LIMIT_SCHEDULE` (EIP-8261) is a `Config` field +served on `/eth/v1/config/spec` and stored in a `Metadata` row of its own +(`config_gas_limit_schedule`), not in `Metadata["config"]`'s encoding, where it +takes zero bytes. That is the pattern for every `Config` key added after +`DB_VERSION` 10 (`CONFIG_ROWS` in `store.rs`): no version bump, and a directory +that predates the key resumes, with a beacon resume adding the config file's +value (`Store::fill_missing_config_keys`) instead of failing. `ConfigFile::parse` +refuses a schedule with an entry before `GLOAS_FORK_EPOCH`, two at one epoch, +or more than 32 entries. Platåberget (the Glamsterdam testnet) is already past its `GLOAS_FORK_EPOCH`, so its checkpoint anchor is a gloas state: it is accepted, starts with no payload known (head EMPTY), and its first FULL child is held until the anchor's @@ -879,8 +901,11 @@ transitions are in `ethlambda-types`, per the section above. Nothing above validation, deneb's and fulu's data availability, and gloas's payload-aware suites. - **EIP-8483 and PQ** (consensus-specs' `pq` branch feature forks, pinned at - `2f43bc0f`, the pq-devnet-0 spec; branch `pq-devnet-0-b5d422b2` follows - `b5d422b2`) are `ForkName::Eip8483` and `ForkName::Pq` after gloas, selectors + `4c296784`, pq-devnet-1's spec: staggered aggregators of `4595f0fc`, VRF + secrets of `b5d422b2`, `X_MAX_COMMITTEE_COUNT_PER_SLOT` of `af898d07` (one + per process, selected with the preset: absent it is the preset's + `MAX_COMMITTEES_PER_SLOT_PQ`, above that it is refused at startup), + keccak256 legacy keys of `4c296784`) are `ForkName::Eip8483` and `ForkName::Pq` after gloas, selectors 8 and 9, implemented in the state transition and fork choice (`stf/{eip8483,pq}.rs`, `stf/epoch/pq.rs`, `helpers/pq.rs`, `upgrade_to_*`) and PQ's gossip rules (`gossip/pq.rs`, `p2p/src/beacon/pq.rs`: a PQ digest's @@ -895,10 +920,12 @@ transitions are in `ethlambda-types`, per the section above. Nothing above `pq` branch, see `docs/beacon_pq.md`, "Running a devnet"), with its own validators: the validator client derives each validator's leanXMSS key and VRF seed from its BLS key - (`ethlambda_crypto::pq_keys`) and attests, aggregates, casts PTC votes and - proposes, each signature - at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all - `2^31` leaves, each `keccak256(vrf_seed || le64(slot))`) takes minutes of + (`ethlambda_crypto::pq_keys`) and attests (each vote published as soon as + it is signed, `pq::sign_each`, not once the batch is), aggregates (staggered by its seat + in the aggregation committee, each seat on its own; the node skips a seat's + proof when an earlier seat of its own already proved every vote collected), + casts PTC votes and proposes, each signature at its leaf. The VRF tree (`ethlambda_crypto::vrf`, Keccak-256 over all + `2^31` leaves, each committing to its slot's secret) takes about 100 s of every core per key, so a background thread hashes it after startup (in a rayon pool of its own: on the global one it starves every leanXMSS signature until done) and stores its upper nodes in @@ -916,8 +943,8 @@ transitions are in `ethlambda-types`, per the section above. Nothing above client survives a restart. The beacon node builds PQ blocks through `POST /eth/v1/validator/pq_blocks/{slot}` (`rpc/src/beacon/pq_proposal.rs`, `pq_block_production.rs`), packing attestations from the validated - aggregates in `Store::pq_aggregate_pool` with their proofs merged on the - sidecar under a deadline (one unmerged attestation when it misses), and + aggregates in `Store::pq_aggregate_pool` with their proofs merged by + leanVM under a deadline (one unmerged attestation when it misses), and proves its aggregators' committees ahead (`rpc/src/beacon/pq_aggregation.rs`, `Store::pq_signature_pool`). Blobs travel as in gloas: the node keeps the blobs of the payload it built and the envelope endpoint publishes their @@ -1014,7 +1041,14 @@ transitions are in `ethlambda-types`, per the section above. Nothing above client do), unconditionally, re-sending each kept one once an epoch (a node holds them in memory only), and `produceBlockV4` carries the boost factor and `--builder-min-bid`. `--gas-limit` sets the target gas limit the preferences - carry, which the node's own gloas payload is built toward. + carry, which the node's own gloas payload is built toward; without it, the + one the beacon node's `GAS_LIMIT_SCHEDULE` names for the proposal's epoch, + else 60M (`gas_limit_schedule`: every node's `/eth/v1/config/spec` is read + at startup and again every epoch, the first non-empty schedule in + `--beacon-nodes` order is handed to `ProposerSettings`, one held is kept + while no node serves one, and a missing one is warned about while gloas is + scheduled and `--gas-limit` unset; an unusable schedule reads as empty, with + a warning). It keeps EIP-3076 minimal-watermark slashing protection in `--validators-dir/slashing_protection.json` (`crate::slashing_protection`), durable before every block (blinded ones included) and attestation signature; @@ -1223,12 +1257,13 @@ behavior. in-memory map stays as a write-through cache in front of the table. Pruned on finalization to the same horizon as `LiveChain` (the finalized block's own slot, keeping that block's own entry). -- `DB_VERSION` is 9: `Config` lost PQ's aggregation timing keys - (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`, - consensus-specs `4595f0fc`) with the move back to `2f43bc0f`, so a version - 8 directory's stored config decodes into the wrong fields. (8 added the - EIP-8483 and PQ fork versions and epochs, - `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY` and +- `DB_VERSION` is 10 (pq-devnet-1): `Config` has PQ's aggregation timing + (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`) + again and `X_MAX_COMMITTEE_COUNT_PER_SLOT`, so a pq-devnet-0 (version 9, + without the timing keys) directory's stored config decodes into the wrong + fields. (9 dropped the timing keys for pq-devnet-0's `2f43bc0f`; 8 gave + `Config` the EIP-8483 and PQ fork versions and epochs, + `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, the timing keys and `ATTESTATION_SUBNET_COUNT_PQ`; 7 moved `States` and `StateDiffs` from root keys to slot||root keys, the block's slot looked up from `BlockHeaders` by readers, so `Store::prune_finalized_states` can diff --git a/Cargo.lock b/Cargo.lock index 145e5e236..18bcc9fd6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "aggregation" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "claims", + "fiat_shamir_prover", + "isa", + "keccak256", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", + "lean_sphincs", + "lean_xmss", + "stable_lean_vm_core", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", + "zkdsl_compiler", +] + [[package]] name = "ahash" version = "0.8.12" @@ -1092,7 +1112,7 @@ dependencies = [ [[package]] name = "claims" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "lean_sphincs", "lean_xmss", @@ -2068,6 +2088,7 @@ dependencies = [ "ethlambda-types", "hex", "keccak 0.1.6", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", "lean_xmss", "leanvm", "pbkdf2", @@ -2076,7 +2097,6 @@ dependencies = [ "rayon", "sha2", "sha3 0.10.9", - "sidecar", "thiserror 2.0.21", "tracing", "zk_alloc", @@ -2630,6 +2650,431 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "experimental_dispatch" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_lean_vm_core", + "experimental_lean_vm_core_armaes", + "experimental_lean_vm_core_armsha3", + "experimental_lean_vm_core_x86avx2", + "experimental_lean_vm_core_x86v3clmul", + "experimental_lean_vm_core_x86v3gfni", + "experimental_lean_vm_core_x86v4", + "experimental_lean_vm_core_x86v4gfni", + "isa", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs", + "experimental_primitives", + "fiat_shamir_prover", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_armaes", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_armsha3", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86avx2", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v3clmul", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v3gfni", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v4", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_keccak_gkr_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_pcs_x86v4gfni", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr", + "experimental_parallel", + "experimental_pcs", + "experimental_primitives", + "fiat_shamir_prover", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_armaes", + "experimental_parallel", + "experimental_pcs_armaes", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_armsha3", + "experimental_parallel", + "experimental_pcs_armsha3", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_x86avx2", + "experimental_parallel", + "experimental_pcs_x86avx2", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_x86v3clmul", + "experimental_parallel", + "experimental_pcs_x86v3clmul", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_x86v3gfni", + "experimental_parallel", + "experimental_pcs_x86v3gfni", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_x86v4", + "experimental_parallel", + "experimental_pcs_x86v4", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_lean_vm_core_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_keccak_gkr_x86v4gfni", + "experimental_parallel", + "experimental_pcs_x86v4gfni", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "isa", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_parallel" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "libc", +] + +[[package]] +name = "experimental_pcs" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives", + "fiat_shamir_prover", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_armaes", + "fiat_shamir_prover_armaes", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_armsha3", + "fiat_shamir_prover_armsha3", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86avx2", + "fiat_shamir_prover_x86avx2", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v3clmul", + "fiat_shamir_prover_x86v3clmul", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v3gfni", + "fiat_shamir_prover_x86v3gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v4", + "fiat_shamir_prover_x86v4", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_pcs_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "experimental_primitives_x86v4gfni", + "fiat_shamir_prover_x86v4gfni", + "tracing", + "verifier", +] + +[[package]] +name = "experimental_primitives" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover", + "keccak256", +] + +[[package]] +name = "experimental_primitives_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_armaes", + "keccak256_armaes", +] + +[[package]] +name = "experimental_primitives_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_armsha3", + "keccak256_armsha3", +] + +[[package]] +name = "experimental_primitives_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86avx2", + "keccak256_x86avx2", +] + +[[package]] +name = "experimental_primitives_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v3clmul", + "keccak256_x86v3clmul", +] + +[[package]] +name = "experimental_primitives_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v3gfni", + "keccak256_x86v3gfni", +] + +[[package]] +name = "experimental_primitives_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v4", + "keccak256_x86v4", +] + +[[package]] +name = "experimental_primitives_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "experimental_parallel", + "fiat_shamir_prover_x86v4gfni", + "keccak256_x86v4gfni", +] + [[package]] name = "eyre" version = "0.6.12" @@ -2717,6 +3162,78 @@ dependencies = [ "serde", ] +[[package]] +name = "fiat_shamir_prover" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_armaes", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_armsha3", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_x86avx2", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_x86v3clmul", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_x86v3gfni", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_x86v4", + "verifier", +] + +[[package]] +name = "fiat_shamir_prover_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256_x86v4gfni", + "verifier", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3662,6 +4179,14 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "isa" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "verifier", +] + [[package]] name = "itertools" version = "0.10.5" @@ -3833,7 +4358,42 @@ dependencies = [ [[package]] name = "keccak256" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_armaes" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_armsha3" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_x86avx2" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_x86v3clmul" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_x86v3gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_x86v4" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "keccak256_x86v4gfni" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "konst" @@ -3889,10 +4449,22 @@ name = "lean_compiler" version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad#48a904208d682848dac0e18ef8b01ebfc40df9ad" dependencies = [ - "lean_vm", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "primitives", ] +[[package]] +name = "lean_da" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + [[package]] name = "lean_da" version = "0.1.0" @@ -3909,11 +4481,28 @@ dependencies = [ [[package]] name = "lean_sphincs" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", ] +[[package]] +name = "lean_vm" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "aggregation", + "claims", + "experimental_dispatch", + "isa", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80)", + "lean_sphincs", + "lean_vrf", + "lean_xmss", + "stable_lean_vm_core", + "verifier", +] + [[package]] name = "lean_vm" version = "0.1.0" @@ -3928,10 +4517,18 @@ dependencies = [ "zk_alloc", ] +[[package]] +name = "lean_vrf" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "keccak256", +] + [[package]] name = "lean_xmss" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" dependencies = [ "keccak256", ] @@ -3942,8 +4539,8 @@ version = "0.1.0" source = "git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad#48a904208d682848dac0e18ef8b01ebfc40df9ad" dependencies = [ "clap", - "lean_da", - "lean_vm", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "primitives", "rand 0.9.4", "rec_aggregation", @@ -5780,8 +6377,8 @@ dependencies = [ "bincode", "flock", "lean_compiler", - "lean_da", - "lean_vm", + "lean_da 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", + "lean_vm 0.1.0 (git+https://github.com/leanEthereum/leanVM.git?rev=48a904208d682848dac0e18ef8b01ebfc40df9ad)", "parallel", "pcs", "primitives", @@ -6522,17 +7119,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "sidecar" -version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" -dependencies = [ - "claims", - "lean_sphincs", - "lean_xmss", - "verifier", -] - [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -6701,6 +7287,62 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stable_keccak_gkr" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "fiat_shamir_prover", + "stable_parallel", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_lean_vm_core" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "fiat_shamir_prover", + "isa", + "stable_keccak_gkr", + "stable_parallel", + "stable_pcs", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_parallel" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" + +[[package]] +name = "stable_pcs" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "fiat_shamir_prover", + "stable_parallel", + "stable_primitives", + "tracing", + "verifier", +] + +[[package]] +name = "stable_primitives" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "fiat_shamir_prover", + "isa", + "keccak256", + "stable_parallel", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -7412,7 +8054,7 @@ dependencies = [ [[package]] name = "verifier" version = "0.1.0" -source = "git+https://github.com/leanEthereum/leanVM.git?rev=c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764#c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" [[package]] name = "version_check" @@ -8315,6 +8957,16 @@ dependencies = [ "libc", ] +[[package]] +name = "zkdsl_compiler" +version = "0.1.0" +source = "git+https://github.com/leanEthereum/leanVM.git?rev=351f7ae421529ce164ed747eee1f78bdeaec3e80#351f7ae421529ce164ed747eee1f78bdeaec3e80" +dependencies = [ + "isa", + "keccak256", + "verifier", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index 4173f9e33..05a8eb9a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -129,21 +129,21 @@ sha3 = "0.10.9" # hashes pay for a streaming hasher's buffering. keccak = "0.1.6" -# The client of leanVM's `leanvm-sidecar` (`crates/sidecar` without its -# `server` feature, which builds no prover) and its claim encoding: the PQ -# fork's attestation proofs as the PQ devnet makes them, real leanVM STARKs -# over leanXMSS signatures rather than the specification's concatenation +# leanVM's in-process prover (`lean_vm`) and its claim encoding: the PQ fork's +# attestation proofs as the PQ devnet makes them, real leanVM STARKs over +# leanXMSS signatures rather than the specification's concatenation # (`ethlambda_crypto::stark`); and leanVM's leanXMSS, which signs and verifies. -# Pinned to bindings v0.15.0, the release pq-devnet-0 runs for its signer, -# prover, verifier and sidecar. The sidecar binary is built and started -# outside the node (the image's `leanvm-revision` file and `ethlambda-pq` -# supervisor), and the client refuses one whose hello names another protocol -# version or verifier tag; beyond that nothing on the wire detects a -# mismatch, a proof from an incompatible revision just fails to verify. Not -# the `leanvm` revision below, which lean consensus proves with. -leanvm_sidecar = { package = "sidecar", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } -leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } -leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764" } +# Pinned to bindings v0.19.0 (351f7ae4), the one release pq-devnet-1 runs for +# its signer, prover and verifier; the devnet takes no other revision. +# `experimental_prover` is the prover the pq-devnet-0 sidecar ran; it makes +# the same proofs as the stable one, faster. leanVM's `cpu_tiers` is behind +# `ethlambda-crypto`'s `leanvm-cpu-tiers` feature, off by default: it only +# does anything under leanVM's `scripts/tier-rustc` as `RUSTC_WRAPPER`, which +# the Dockerfile sets. +# Not the `leanvm` revision below, which lean consensus proves with. +leanvm_prover = { package = "lean_vm", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80", features = ["experimental_prover"] } +leanvm_claims = { package = "claims", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80" } +leanvm_lean_xmss = { package = "lean_xmss", git = "https://github.com/leanEthereum/leanVM.git", rev = "351f7ae421529ce164ed747eee1f78bdeaec3e80" } # XMSS signatures + recursive aggregation, through leanVM's own facade crate: # it re-exports the aggregation API, the `xmss` module (keys, signing, and the diff --git a/Dockerfile b/Dockerfile index 7adc984a7..1b2650b0e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,32 +1,5 @@ # syntax=docker.io/docker/dockerfile:1.7-labs -# leanVM's prover sidecar, which the `ethlambda-pq` supervisor starts beside -# the node on a network scheduling the PQ fork, as Lighthouse's image does. -# Built from the revision in `leanvm-revision` (bindings v0.15.0, the release -# pq-devnet-0 runs), or from `--build-arg LEANVM_REV=`: -# which prover a devnet runs is chosen here, not by the node, whose client -# only requires the sidecar's protocol version and verifier tag to be its own. -# The commit built is recorded at /usr/local/share/ethlambda/leanvm-revision. -# leanVM's own .cargo/config.toml builds with `-C target-cpu=native`, which on -# CI's arm64 runner (Neoverse, with SVE) gives a binary that dies with SIGILL -# on Apple silicon, and on an amd64 runner with AVX-512 one that dies on hosts -# without it. ethlambda's config replaces it, so the sidecar gets the node's -# own portable CPU baseline (and the carryless-multiply features leanVM needs). -FROM rust:1.97-bookworm AS sidecar -ARG LEANVM_REV="" -COPY leanvm-revision /leanvm-revision -COPY .cargo/config.toml /ethlambda-cargo-config.toml -RUN rev="${LEANVM_REV:-$(tr -d '[:space:]' < /leanvm-revision)}" \ - && test -n "$rev" \ - && git clone -q https://github.com/leanEthereum/leanVM.git /leanVM \ - && cd /leanVM \ - && git checkout -q "$rev" \ - && mkdir -p .cargo \ - && cp /ethlambda-cargo-config.toml .cargo/config.toml \ - && cargo build --release -p leanvm-sidecar --features experimental_prover \ - && cp target/release/leanvm-sidecar /leanvm-sidecar \ - && git rev-parse HEAD > /leanvm-revision-built - FROM rust:1.97-bookworm AS chef WORKDIR /app @@ -47,12 +20,32 @@ COPY --from=planner /app/recipe.json recipe.json # cached deps are compiled with default flags and cargo reuses them. COPY .cargo/ .cargo/ +# leanVM's PQ prover is compiled once more per CPU tier (AVX-512, GFNI and +# VPCLMULQDQ on x86-64, SHA3 on arm64), and picks the fastest one the host has +# at run time: one image for every host, as the other clients' leanVM builds +# are. A tier only gets its instructions when rustc is wrapped by leanVM's own +# `scripts/tier-rustc`, which adds a tier's target features to that tier's +# crates and leaves every other crate as asked, so the node itself keeps the +# portable baseline in `.cargo/config.toml`. Fetched at the pinned revision +# (`leanvm-revision`, which a test holds equal to the workspace's `rev`), so +# the wrapper is the one the prover's sources were written against. Set before +# `cargo chef cook`, which is what compiles the tiers. A build without the +# `leanvm-cpu-tiers` feature has no tier crates, and the wrapper changes +# nothing in it. +COPY leanvm-revision leanvm-revision +RUN rev="$(tr -d '[:space:]' < leanvm-revision)" \ + && test -n "$rev" \ + && curl -fsSL "https://raw.githubusercontent.com/leanEthereum/leanVM/${rev}/scripts/tier-rustc" \ + -o /usr/local/bin/leanvm-tier-rustc \ + && chmod +x /usr/local/bin/leanvm-tier-rustc +ENV RUSTC_WRAPPER=/usr/local/bin/leanvm-tier-rustc + # Build profile, release by default ARG BUILD_PROFILE=release ENV BUILD_PROFILE=$BUILD_PROFILE -# Extra Cargo features -ARG FEATURES="" +# Cargo features. `leanvm-cpu-tiers` by default: see the wrapper above. +ARG FEATURES="leanvm-cpu-tiers" ENV FEATURES=$FEATURES # Disable default features (e.g. for `shadow-integration`, which must drop the @@ -106,10 +99,12 @@ LABEL org.opencontainers.image.version=$VERSION # Copy ethlambda over from the build stage COPY --from=builder /app/ethlambda /usr/local/bin -# The PQ prover sidecar and its supervisor, `ethlambda-pq beacon ` -COPY --from=sidecar /leanvm-sidecar /usr/local/bin/leanvm-sidecar -COPY --from=sidecar /leanvm-revision-built /usr/local/share/ethlambda/leanvm-revision +# pq-devnet-0's launcher name, `ethlambda-pq beacon `, kept for +# launchers that still use it. Since bindings v0.17.0 leanVM proves in the node, so +# there is no sidecar to start: the script only runs `ethlambda`. The leanVM +# revision the node proves with is the one in `leanvm-revision`. COPY --chmod=755 bin/ethlambda/pq/ethlambda-pq /usr/local/bin/ethlambda-pq +COPY leanvm-revision /usr/local/share/ethlambda/leanvm-revision # Copy licenses COPY LICENSE ./ diff --git a/Makefile b/Makefile index 80430d0a7..c8fe497bc 100644 --- a/Makefile +++ b/Makefile @@ -41,6 +41,9 @@ test: test-consensus test-node ## 🧪 Run all tests test-consensus: leanSpec/fixtures ## 🧪 Run the consensus half of the workspace suite $(TEST) $(addprefix -p ,$(CONSENSUS_CRATES)) + # The PQ fork's leanVM prover, end to end: ignored by a plain `cargo test`, + # which spends minutes on it unoptimized. A second or two here. + $(TEST) -p ethlambda-crypto --lib -- --ignored leanvm_proofs_merge_and_verify test-node: leanSpec/fixtures slashing-protection-interchange-tests ## 🧪 Run the node half of the workspace suite $(TEST) --workspace $(addprefix --exclude ,$(CONSENSUS_CRATES)) diff --git a/README.md b/README.md index 3e8eae4cb..df56ce897 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ beacon node. | `--secrets-dir` | One password file per keystore, named after the validator's public key | | `--suggested-fee-recipient` | Execution address for block rewards, `0x`-prefixed. Optional, but without it the beacon node picks an address that is not yours | | `--graffiti` | Text for proposed blocks, at most 32 bytes | -| `--gas-limit` | The gas limit validators target (default `60000000`). From gloas the beacon node builds this client's own payloads toward it, so set it on a network whose limit is elsewhere. Sepolia and Platåberget schedule `200000000`: pass `--gas-limit 200000000` there (until [#795](https://github.com/lambdaclass/ethlambda/issues/795)) | +| `--gas-limit` | The gas limit validators target. From gloas the beacon node builds this client's own payloads toward it. Without it, the gas limit the network's `GAS_LIMIT_SCHEDULE` names for the proposal's epoch (Sepolia's and Platåberget's name `200000000`, pq-devnet-1's too), else `60000000` | | `--builder-proposals` | Propose builder blocks before gloas: register each validator with the beacon node's builder (`--builder` on an ethlambda node) and sign a blinded block when the builder's bid wins. Off by default. From gloas, with or without it, a node that cannot build the payload itself may build on a builder's p2p bid, and that block is signed | | `--enable-keymanager` | Serve the keymanager API on `--keymanager-port` (default `5062`). Off by default, since it mutates key material | | `--enable-doppelganger-protection` | Sign no attestation or block for a key until the beacon node has seen it stay silent for a full epoch, and stop if another client turns out to be running it. Costs two to three epochs of attestations per start. Off by default | diff --git a/bin/ethlambda/Cargo.toml b/bin/ethlambda/Cargo.toml index 852039a51..75ffb1d5d 100644 --- a/bin/ethlambda/Cargo.toml +++ b/bin/ethlambda/Cargo.toml @@ -17,6 +17,9 @@ jemalloc = ["dep:tikv-jemallocator"] # The quinn-udp UDP fallback is a Cargo `[patch]` (which cannot be feature-gated), # injected at build time by `shadow/build.sh` / `make shadow-build`. shadow-integration = ["ethlambda-crypto/shadow-integration"] +# The PQ prover's CPU tiers: see `ethlambda-crypto`'s feature of the same +# name. The Dockerfile builds with it, and with the wrapper it needs. +leanvm-cpu-tiers = ["ethlambda-crypto/leanvm-cpu-tiers"] [dependencies] ethlambda-blockchain.workspace = true diff --git a/bin/ethlambda/pq/ethlambda-pq b/bin/ethlambda/pq/ethlambda-pq index d5bd3dc2a..c29282897 100755 --- a/bin/ethlambda/pq/ethlambda-pq +++ b/bin/ethlambda/pq/ethlambda-pq @@ -1,120 +1,19 @@ #!/bin/bash -# Runs `ethlambda` with a leanVM prover sidecar beside it, for a network that -# schedules the PQ fork, adapted from Lighthouse's `lighthouse-pq-bn`: -# `ethlambda-pq beacon ` starts the sidecar on a private socket, waits -# for it to listen, then starts `ethlambda --pq-prover-socket `. +# Kept so a launcher written for pq-devnet-0's image (`ethlambda-pq beacon +# `, as ethereum-package's pq branch runs it) still starts the node. # -# The node exiting stops the sidecar, and the script exits with the node's -# status. The sidecar exiting does not stop the node: it is started again on -# the same socket, and the node's client reconnects on its next request. -# Meanwhile the node proves nothing, and a gossip aggregate it cannot verify -# is ignored rather than held against its sender. The pause before a restart -# starts at one second and doubles, up to 32, while the sidecar keeps exiting -# within a minute of starting. After LEANVM_MAX_RESTARTS (default 10) such -# exits in a row, the script stops the node too: a sidecar that cannot run -# (killed for memory at every warm-up, say) is then reported, not retried -# forever. +# pq-devnet-0 ran leanVM's prover as a separate `leanvm-sidecar`, which this +# script started and supervised. leanVM bindings v0.17.0 removed the sidecar: +# the node proves in process on a network that schedules the PQ fork +# (pq-devnet-1 runs bindings v0.19.0), so this script only runs +# `ethlambda `. # -# Which sidecar is this script's choice, not the node's: -# - LEANVM_SIDECAR: the executable (default: `leanvm-sidecar` on PATH, the one -# the image builds from the leanVM revision in `leanvm-revision`, recorded at -# /usr/local/share/ethlambda/leanvm-revision). -# - LEANVM_THREADS: how many threads it proves on (default 0: one per core). -# The node refuses a sidecar speaking another protocol version or proving for -# another verifier than its client. +# LEANVM_THREADS, the sidecar's thread count, is still honored: it becomes +# `--pq-prover-threads` (0, the default: one per core). LEANVM_SIDECAR and +# LEANVM_MAX_RESTARTS no longer mean anything and are ignored. set -eu -sidecar=${LEANVM_SIDECAR:-leanvm-sidecar} -threads=${LEANVM_THREADS:-0} -max_restarts=${LEANVM_MAX_RESTARTS:-10} -revision_file=/usr/local/share/ethlambda/leanvm-revision -if [[ -z ${LEANVM_SIDECAR:-} && -r $revision_file ]]; then - echo "ethlambda-pq: starting $sidecar (leanVM $(cat "$revision_file")) on $threads threads (0: one per core)" >&2 -else - echo "ethlambda-pq: starting $sidecar on $threads threads (0: one per core)" >&2 +if [[ -n ${LEANVM_THREADS:-} ]]; then + exec ethlambda "$@" --pq-prover-threads "$LEANVM_THREADS" fi - -socket_dir=$(mktemp -d "${TMPDIR:-/tmp}/leanvm.XXXXXXXX") -socket_path="$socket_dir/prover.sock" -prover_pid= -prover_started=0 -node_pid= - -cleanup() { - if [[ -n "$node_pid" ]]; then - kill "$node_pid" 2>/dev/null || true - wait "$node_pid" 2>/dev/null || true - fi - if [[ -n "$prover_pid" ]]; then - kill "$prover_pid" 2>/dev/null || true - wait "$prover_pid" 2>/dev/null || true - fi - rm -f -- "$socket_path" "$socket_path.lock" - rmdir -- "$socket_dir" 2>/dev/null || true -} - -trap cleanup EXIT -trap 'exit 143' TERM -trap 'exit 130' INT - -start_sidecar() { - # A sidecar killed outright leaves its socket and lock behind. - rm -f -- "$socket_path" "$socket_path.lock" - "$sidecar" --socket "$socket_path" --threads "$threads" & - prover_pid=$! - prover_started=$SECONDS -} - -start_sidecar -ready_deadline=$((SECONDS + 120)) -until [[ -S "$socket_path" ]]; do - if ! kill -0 "$prover_pid" 2>/dev/null; then - echo "ethlambda-pq: $sidecar exited before creating its socket" >&2 - exit 1 - fi - if (( SECONDS >= ready_deadline )); then - echo "ethlambda-pq: $sidecar did not create its socket within 120 seconds" >&2 - exit 1 - fi - sleep 0.1 -done - -ethlambda "$@" --pq-prover-socket "$socket_path" & -node_pid=$! - -# Short polls rather than one long sleep for the pause, so a TERM is handled -# within a fraction of a second whatever the script is waiting for. -delay=1 -failures=0 -restart_at=0 -while kill -0 "$node_pid" 2>/dev/null; do - if [[ -n "$prover_pid" ]] && ! kill -0 "$prover_pid" 2>/dev/null; then - prover_status=0 - wait "$prover_pid" || prover_status=$? - prover_pid= - lived=$((SECONDS - prover_started)) - if (( lived >= 60 )); then - delay=1 - failures=0 - else - failures=$((failures + 1)) - fi - if (( failures >= max_restarts )); then - echo "ethlambda-pq: $sidecar exited within a minute of starting $failures times in a row; stopping ethlambda" >&2 - exit 1 - fi - echo "ethlambda-pq: $sidecar exited (status $prover_status) after ${lived}s while ethlambda was running; restarting it in ${delay}s" >&2 - restart_at=$((SECONDS + delay)) - delay=$((delay * 2 > 32 ? 32 : delay * 2)) - fi - if [[ -z "$prover_pid" ]] && (( SECONDS >= restart_at )); then - start_sidecar - echo "ethlambda-pq: restarted $sidecar" >&2 - fi - sleep 0.2 -done - -status=0 -wait "$node_pid" || status=$? -node_pid= -exit "$status" +exec ethlambda "$@" diff --git a/bin/ethlambda/src/cli.rs b/bin/ethlambda/src/cli.rs index 96ae53c89..5f86eec0e 100644 --- a/bin/ethlambda/src/cli.rs +++ b/bin/ethlambda/src/cli.rs @@ -420,19 +420,12 @@ pub(crate) struct MainnetOptions { )] pub(crate) bootnodes: Vec, - /// The Unix socket of a running `leanvm-sidecar`, which makes and checks - /// the PQ fork's attestation proofs as leanVM STARKs, the encoding the PQ - /// devnet's clients use. Something else starts the sidecar, as for - /// Lighthouse: the image's `ethlambda-pq` supervisor does, and picks which - /// build. The node refuses one speaking another protocol version or - /// proving for another verifier than its client (leanVM - /// `c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764`, bindings v0.15.0). - /// - /// Without it, the node uses the specification's reference encoding (a - /// proof is the signatures concatenated), which only another node on the - /// reference accepts. - #[arg(long)] - pub(crate) pq_prover_socket: Option, + /// How many threads leanVM's in-process prover runs on, 0 for one per + /// core. Read only on a network that schedules the PQ fork, whose + /// attestation proofs this node makes and checks with leanVM (bindings + /// v0.19.0) in process. + #[arg(long, default_value_t = 0)] + pub(crate) pq_prover_threads: usize, /// Base URL of a builder API endpoint, normally MEV-Boost (for example /// `http://127.0.0.1:18550`) or a relay directly. Without it every block diff --git a/bin/ethlambda/src/command.rs b/bin/ethlambda/src/command.rs index c72109a90..8a26c4447 100644 --- a/bin/ethlambda/src/command.rs +++ b/bin/ethlambda/src/command.rs @@ -34,6 +34,7 @@ const EXPLICIT: &[&str] = &[ SLASHING_PROTECTION, KEYGEN, PQ_KEYS, + PQ_PROVER_CHECK, "help", "-h", "--help", @@ -50,6 +51,7 @@ const VOLUNTARY_EXIT: &str = "voluntary-exit"; const SLASHING_PROTECTION: &str = "slashing-protection"; const KEYGEN: &str = "keygen"; const PQ_KEYS: &str = "pq-keys"; +const PQ_PROVER_CHECK: &str = "pq-prover-check"; #[derive(Debug, clap::Parser)] #[command( @@ -103,6 +105,9 @@ pub(crate) enum Command { /// Write a Beacon Chain PQ-fork genesis's leanXMSS keys and VRF roots for /// a mnemonic's validators, in ethPandaOps' genesis tooling's file formats. PqKeys(crate::pq_keys::PqKeysOptions), + /// Prove and verify a PQ-fork aggregate with leanVM on this machine, and + /// report what it took against an aggregator seat's proving window. + PqProverCheck(crate::pq_prover_check::PqProverCheckOptions), } /// Parse the process arguments, exiting the way clap does on a parse error, @@ -473,6 +478,7 @@ mod tests { SLASHING_PROTECTION, KEYGEN, PQ_KEYS, + PQ_PROVER_CHECK, ] { let args = [OsString::from("ethlambda"), OsString::from(token)]; assert_eq!( diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 9c70b382a..e8956b9e0 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -9,6 +9,7 @@ mod fd_limit; mod keygen; mod network; mod pq_keys; +mod pq_prover_check; mod shutdown; mod slashing_protection; mod validator; @@ -138,6 +139,11 @@ fn main() -> eyre::Result<()> { init_info_stderr_logging()?; pq_keys::run(options) } + // Seconds of every core, for a report on stderr: as keygen. + Command::PqProverCheck(options) => { + init_info_stderr_logging()?; + pq_prover_check::run(options) + } } } @@ -399,17 +405,6 @@ async fn run_node(options: Options) -> eyre::Result<()> { ); ethlambda_crypto::init_leanvm(lean.prover_arena); } - // The PQ fork's attestation proofs: leanVM proofs from a sidecar this node - // starts, or one already listening, the specification's reference - // encoding otherwise. Before anything can verify a proof, since the first - // one used stays installed. - if let Network::Mainnet { mainnet, .. } = &network { - use ethlambda_crypto::stark::{self, sidecar::SidecarConfig}; - if let Some(socket) = &mainnet.pq_prover_socket { - stark::install_sidecar(SidecarConfig::new(socket.clone())) - .wrap_err("cannot use the leanVM prover sidecar")?; - } - } // Initialize metrics ethlambda_blockchain::metrics::init(); @@ -479,6 +474,26 @@ async fn run_node(options: Options) -> eyre::Result<()> { let spec = network::NetworkSpec::parse(&mainnet.network)?; let source = network::NetworkSource::resolve(&spec)?; let bootnodes = beacon_bootnodes(&mainnet.bootnodes, source.bootnodes(), discovery_ip)?; + // The PQ fork's attestation proofs: leanVM proofs, made and + // checked in this process, on a network that schedules PQ (the + // specification's reference encoding otherwise, which nothing + // there uses). Here, once the network says whether it does, and + // before anything can verify a proof, since the first backend + // used stays installed. + let pq_epoch = source.config().pq_fork_epoch; + if pq_epoch != ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH { + use ethlambda_crypto::stark::{self, leanvm::LeanVmConfig}; + let config = LeanVmConfig { + threads: mainnet.pq_prover_threads, + ..LeanVmConfig::default() + }; + info!( + pq_epoch, + threads = config.threads, + "Starting leanVM's prover for the PQ fork" + ); + stark::install_leanvm(config).wrap_err("cannot start leanVM's prover")?; + } (Some(source), bootnodes) } }; @@ -928,6 +943,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { let rpc_sync_status = sync_status.clone(); let rpc_events = events.clone(); let rpc_builder_market = builder_market.clone(); + let rpc_pq_builder_market = pq_builder_market.clone(); let rpc_fee_recipients = fee_recipients.clone(); // The payload builds the chain actor starts ahead of their slots, which // block production collects. @@ -978,7 +994,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { p2p: rpc_p2p, payload_attestation_pool: payload_attestation_pool.clone(), builder_market: rpc_builder_market, - pq_builder_market: pq_builder_market.clone(), + pq_builder_market: rpc_pq_builder_market, sync_committee_pool: sync_committee_pool.clone(), fee_recipients: rpc_fee_recipients, prepared_payloads: rpc_prepared_payloads, @@ -1036,6 +1052,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { ethlambda_blockchain::PayloadPreparation { fee_recipients, builder_market, + pq_builder_market, always_prepare: always_prepare_payload, prepared_payloads, prepared_pq_attestations, @@ -2088,6 +2105,11 @@ fn first_config_difference( // Compared below: when an unregistered validator becomes withdrawable // at the PQ fork is a state-transition rule. unregistered_validator_withdrawability_delay: _, + // PQ's aggregation timing: when an aggregator proves and broadcasts, + // which changes no block's validity. + aggregation_cutoff_bps: _, + aggregate_due_bps_pq: _, + aggregator_delay_bps: _, // Validator cycle: compared below. Churn and inactivity-leak // parameters change which exits, activations and inactivity scores a @@ -2102,6 +2124,9 @@ fn first_config_difference( max_per_epoch_activation_exit_churn_limit: _, churn_limit_quotient_gloas: _, max_per_epoch_activation_churn_limit_gloas: _, + // Compared below: PQ's committee cap decides every PQ committee, so + // which attestations and aggregates a block may carry. + x_max_committee_count_per_slot: _, // Fork choice: weighting/timing knobs a node applies to its own view // of the chain. They change which head a node *prefers*, not which @@ -2179,6 +2204,13 @@ fn first_config_difference( max_request_blob_sidecars_electra: _, max_request_data_column_sidecars: _, min_epochs_for_block_requests: _, + + // Advisory, a validator client's default gas limit: the specification + // says it adds no validity rule, so the file's always wins, through + // the caller's `replace_config`. In a directory that predates its + // row, `persisted` already holds the file's + // (`Store::fill_missing_config_keys`). + gas_limit_schedule: _, } = persisted; compare!(preset_base); @@ -2253,6 +2285,7 @@ fn first_config_difference( max_per_epoch_activation_exit_churn_limit, churn_limit_quotient_gloas, max_per_epoch_activation_churn_limit_gloas, + x_max_committee_count_per_slot, consolidation_churn_limit_quotient, max_blobs_per_block_deneb, max_blobs_per_block_electra, @@ -2372,13 +2405,23 @@ async fn fetch_initial_beacon_state( .max(state.slot()); let processed_through = compute_epoch_at_slot(processed_slot); - let persisted = store.config(); + // A config key this directory predates has no stored value to + // compare, so it is added from the config file rather than + // refused; `replace_config` below writes it. + let (persisted, added) = store.fill_missing_config_keys(&config); if let Some(difference) = first_config_difference(&persisted, &config, processed_through) { error!(%difference, "Persisted config disagrees with the network config"); return Err(checkpoint_sync::CheckpointSyncError::ConfigChanged { difference }); } + // Only once the resume is accepted: a refused one adds nothing. + for key in &added { + info!( + key, + "Config key this data directory predates; adding the config file's" + ); + } // Not a chain value, so not refused (see `first_config_difference`). if persisted.config_name != config.config_name { warn!( @@ -2406,11 +2449,9 @@ async fn fetch_initial_beacon_state( // Whatever differs now is a value this directory does not // contradict, so the config file wins: the node runs on the // persisted config, and keeping the stored one would leave it on - // the old fork schedule. `replace_config` needs the only handle - // to the cached config, hence the `drop`. - let config_changed = *persisted != config; - drop(persisted); - if config_changed { + // the old fork schedule. A key added above has no row yet, which + // `replace_config` writes too. + if persisted != config || !added.is_empty() { store.replace_config(config.clone()); } @@ -3656,6 +3697,127 @@ validators: ); } + /// `GAS_LIMIT_SCHEDULE` is stored in a `Metadata` row of its own: + /// - a fresh directory writes it, so a reopened one carries the schedule + /// with no config file involved; + /// - a directory that predates the row (written by an older build; + /// simulated here by deleting the row) still resumes, with the key added + /// from the config file and written, and the `config` row unchanged; + /// - a changed schedule in the file is followed and stored. + #[tokio::test] + async fn the_gas_limit_schedule_is_stored_and_added_to_a_directory_that_predates_it() { + use ethlambda_storage::Table; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + // The schedule's row, as `ethlambda_storage`'s `CONFIG_ROWS` names it. + const SCHEDULE_ROW: &[u8] = b"config_gas_limit_schedule"; + let row = |backend: &Arc, key: &[u8]| { + backend + .begin_read() + .unwrap() + .get(Table::Metadata, key) + .unwrap() + }; + + let dir = tempfile::tempdir().unwrap(); + std::fs::copy( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/networks/devnet/config.yaml"), + dir.path().join("config.yaml"), + ) + .unwrap(); + let state = beacon::mainnet_genesis_state().unwrap(); + std::fs::write(dir.path().join("genesis.ssz"), state.to_ssz()).unwrap(); + let backend: Arc = Arc::new(InMemoryBackend::new()); + + // The devnet's file carries an empty schedule; give the loaded config + // one, as a file that schedules a gas limit would. + let first = GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }; + let load = |entries: Vec| { + let mut loaded = network::dir::NetworkDir::load(dir.path()).unwrap(); + loaded.config.gas_limit_schedule = entries.into(); + network::NetworkSource::Loaded(Box::new(loaded)) + }; + + let Ok(fresh) = fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first])).await + else { + panic!("first run anchors"); + }; + assert_eq!(fresh.config().gas_limit_schedule.entries(), [first]); + drop(fresh); + + let stored = Store::from_db_state(backend.clone()) + .expect("reopen") + .expect("populated directory"); + assert_eq!( + stored.config().gas_limit_schedule.entries(), + [first], + "the schedule is read back from its row" + ); + drop(stored); + + // A directory written before the row existed. + assert!( + row(&backend, SCHEDULE_ROW).is_some(), + "the fresh run wrote it" + ); + let config_row = row(&backend, b"config").expect("config row"); + let mut batch = backend.begin_write().unwrap(); + batch + .delete_batch(Table::Metadata, vec![SCHEDULE_ROW.to_vec()]) + .unwrap(); + batch.commit().unwrap(); + let predating = Store::from_db_state(backend.clone()) + .expect("a directory without the row loads") + .expect("populated directory"); + assert!(predating.config().gas_limit_schedule.is_empty()); + drop(predating); + + let Ok(resumed) = + fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first])).await + else { + panic!("a directory that predates the key resumes"); + }; + assert_eq!(resumed.config().gas_limit_schedule.entries(), [first]); + drop(resumed); + assert!( + row(&backend, SCHEDULE_ROW).is_some(), + "the resume writes the key it added" + ); + assert_eq!( + row(&backend, b"config").expect("config row"), + config_row, + "the config row is left as it was" + ); + + // The file schedules another entry. + let second = GasLimitScheduleEntry { + epoch: 200, + gas_limit: 300_000_000, + }; + let Ok(followed) = + fetch_initial_beacon_state(&[], backend.clone(), &load(vec![first, second])).await + else { + panic!("a changed schedule resumes"); + }; + assert_eq!( + followed.config().gas_limit_schedule.entries(), + [first, second] + ); + drop(followed); + let reopened = Store::from_db_state(backend) + .expect("reopen") + .expect("populated directory"); + assert_eq!( + reopened.config().gas_limit_schedule.entries(), + [first, second], + "the changed schedule is stored" + ); + } + /// `churn_limit_quotient` is one of the state-transition fields the /// original field list omitted entirely: a directory with a different /// churn quotient from its config file accepted a different set of diff --git a/bin/ethlambda/src/network/built_in.rs b/bin/ethlambda/src/network/built_in.rs index 5e9dcad23..8f333874a 100644 --- a/bin/ethlambda/src/network/built_in.rs +++ b/bin/ethlambda/src/network/built_in.rs @@ -68,10 +68,11 @@ impl BuiltInNetwork { /// Build this network's configuration, genesis values and bootnode list. pub(crate) fn resolve(self) -> eyre::Result { let chain = self.chain(); - let parsed = ConfigFile::parse(chain.config_yaml) + let mut parsed = ConfigFile::parse(chain.config_yaml) .wrap_err_with(|| format!("the built-in {} config.yaml did not parse", self.name()))?; super::select_preset(parsed.config.preset_base.as_str())?; super::check_constants(&parsed.config)?; + super::select_committee_cap(&mut parsed)?; // A built-in config can carry a fork whose keys this build does not // even claim (heze), which the ignored-keys warning below says. A fork // whose keys it claims but whose rules it does not follow is diff --git a/bin/ethlambda/src/network/config_file.rs b/bin/ethlambda/src/network/config_file.rs index 3c5731509..8e642c331 100644 --- a/bin/ethlambda/src/network/config_file.rs +++ b/bin/ethlambda/src/network/config_file.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{Config, GasLimitScheduleError}; use serde::Deserialize; use serde::de::{IgnoredAny, Visitor}; @@ -27,6 +27,11 @@ pub(crate) struct ConfigFile { pub(crate) config: Config, /// Keys no field claimed: a typo, or a fork this build cannot process. pub(crate) ignored: Vec, + /// Whether the file carried `X_MAX_COMMITTEE_COUNT_PER_SLOT`. An absent + /// key parses as mainnet's value, like every other, and for this one + /// that is not what an absent key means: see + /// [`super::select_committee_cap`]. + pub(crate) committee_cap_declared: bool, } #[derive(Debug, thiserror::Error)] @@ -47,6 +52,11 @@ pub(crate) enum ConfigFileError { (SECONDS_PER_SLOT * 1000) to fit in a u64" )] SlotDurationOverflow { seconds: u64 }, + /// A schedule the specification forbids. Refused rather than read, as + /// Lighthouse refuses it: with two entries at one epoch there is no one + /// gas limit to report for it. + #[error("GAS_LIMIT_SCHEDULE is malformed: {0}")] + GasLimitSchedule(#[from] GasLimitScheduleError), } impl ConfigFile { @@ -60,14 +70,20 @@ impl ConfigFile { document.contains_key("SECONDS_PER_SLOT"), document.contains_key("SLOT_DURATION_MS"), )?; + config.gas_limit_schedule.check(config.gloas_fork_epoch)?; + let committee_cap_declared = document.contains_key("X_MAX_COMMITTEE_COUNT_PER_SLOT"); let claimed = config_field_names(); let ignored = document .into_keys() .filter(|key| !claimed.contains(&key.as_str())) .collect(); - Ok(Self { config, ignored }) + Ok(Self { + config, + ignored, + committee_cap_declared, + }) } /// Log what was ignored, as one line naming each key. @@ -250,7 +266,6 @@ mod tests { for key in [ "HEZE_FORK_VERSION", "HEZE_FORK_EPOCH", - "GAS_LIMIT_SCHEDULE", "INCLUSION_LIST_DUE_BPS", ] { assert!( @@ -260,6 +275,79 @@ mod tests { } } + #[test] + fn the_gas_limit_schedule_is_claimed_rather_than_ignored() { + // The devnet's is empty, Sepolia's and Platåberget's are not; none is + // reported as ignored any more. + for text in [ + DEVNET, + include_str!("../../assets/sepolia/config.yaml"), + include_str!("../../assets/plataberget/config.yaml"), + ] { + let parsed = ConfigFile::parse(text).unwrap(); + assert!( + !parsed.ignored.iter().any(|key| key == "GAS_LIMIT_SCHEDULE"), + "GAS_LIMIT_SCHEDULE reported as ignored" + ); + } + let sepolia = ConfigFile::parse(include_str!("../../assets/sepolia/config.yaml")).unwrap(); + assert_eq!( + sepolia.config.gas_limit_schedule.gas_limit_at(353_024), + Some(200_000_000) + ); + } + + #[test] + fn a_gas_limit_schedule_the_specification_forbids_is_refused() { + let before_gloas = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 9\n", + " GAS_LIMIT: 100000000\n", + ); + let err = ConfigFile::parse(before_gloas).unwrap_err(); + assert!( + matches!( + err, + ConfigFileError::GasLimitSchedule(GasLimitScheduleError::BeforeGloas { + epoch: 9, + gloas_fork_epoch: 10 + }) + ), + "got {err}" + ); + + let shared_epoch = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 100000000\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 200000000\n", + ); + let err = ConfigFile::parse(shared_epoch).unwrap_err(); + assert!( + matches!( + err, + ConfigFileError::GasLimitSchedule(GasLimitScheduleError::DuplicateEpoch { + epoch: 10 + }) + ), + "got {err}" + ); + + // Starting at the fork itself is allowed. + let from_gloas = concat!( + "GLOAS_FORK_EPOCH: 10\n", + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 10\n", + " GAS_LIMIT: 100000000\n", + " - EPOCH: 11\n", + " GAS_LIMIT: 200000000\n", + ); + ConfigFile::parse(from_gloas).unwrap(); + } + #[test] fn the_gloas_keys_are_claimed_rather_than_ignored() { // GLOAS_* and PAYLOAD_DUE_BPS used to be reported as ignored diff --git a/bin/ethlambda/src/network/dir.rs b/bin/ethlambda/src/network/dir.rs index 7bbe82aaa..54bb82d65 100644 --- a/bin/ethlambda/src/network/dir.rs +++ b/bin/ethlambda/src/network/dir.rs @@ -55,6 +55,12 @@ pub(crate) enum NetworkDirError { #[source] source: super::ConstantsMismatch, }, + #[error("{}: {source}", path.display())] + CommitteeCap { + path: PathBuf, + #[source] + source: ethlambda_types::beacon::config::CommitteeCapTooLarge, + }, // `{fork:?}` rather than `{fork}`: `ForkName` exposes `as_str` and does not // implement `Display`. #[error("{} did not decode as a {fork:?} BeaconState: {reason}", path.display())] @@ -77,7 +83,7 @@ impl NetworkDir { pub(crate) fn load(base: &Path) -> Result { let config_path = base.join(CONFIG_FILE); let text = read_required(&config_path)?; - let parsed = ConfigFile::parse(&text).map_err(|source| NetworkDirError::Config { + let mut parsed = ConfigFile::parse(&text).map_err(|source| NetworkDirError::Config { path: config_path.clone(), source, })?; @@ -97,6 +103,12 @@ impl NetworkDir { path: config_path.clone(), source, })?; + super::select_committee_cap(&mut parsed).map_err(|source| { + NetworkDirError::CommitteeCap { + path: config_path.clone(), + source, + } + })?; let genesis_path = base.join(GENESIS_STATE_FILE); let genesis_bytes = read_required_bytes(&genesis_path)?; diff --git a/bin/ethlambda/src/network/mod.rs b/bin/ethlambda/src/network/mod.rs index 5f9426157..4f0b2c635 100644 --- a/bin/ethlambda/src/network/mod.rs +++ b/bin/ethlambda/src/network/mod.rs @@ -11,7 +11,11 @@ pub(crate) mod dir; use std::path::PathBuf; -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{ + CommitteeCapTooLarge, Config, select_x_max_committee_count_per_slot, +}; + +use self::config_file::ConfigFile; use ethlambda_types::beacon::preset::{Preset, PresetAlreadyActive}; pub(crate) use built_in::BuiltInNetwork; @@ -107,6 +111,29 @@ pub(crate) fn select_preset(declared: &str) -> Result Ok(preset) } +/// Settles the network's `X_MAX_COMMITTEE_COUNT_PER_SLOT` and makes it the +/// cap every PQ committee count of this process uses (consensus-specs pq +/// `af898d07`). After [`select_preset`], whose `MAX_COMMITTEES_PER_SLOT_PQ` +/// it is read against: +/// +/// - A file that omits the key gets the preset's value, not the mainnet 16 +/// every other absent key falls back to. The specification's own configs +/// set the two equal, and a minimal network whose file predates the key +/// must not be given more committees than its `CommitteeBits` can name. +/// The value is written into the config, so the data directory and +/// `/eth/v1/config/spec` hold what the node runs on. +/// - A value above the preset's is refused, as the specification forbids it: +/// a client that ran it would name committees an attestation cannot, and +/// one that silently lowered it would shuffle another chain than its peers. +pub(crate) fn select_committee_cap(parsed: &mut ConfigFile) -> Result<(), CommitteeCapTooLarge> { + if !parsed.committee_cap_declared { + parsed.config.x_max_committee_count_per_slot = + ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64; + } + select_x_max_committee_count_per_slot(&parsed.config)?; + Ok(()) +} + /// One `config.yaml` key that the node runs on a compile-time constant for, /// set to another value. #[derive(Debug)] @@ -450,6 +477,32 @@ mod tests { /// The specification's own configs must pass, or every built-in network /// and every devnet derived from one would be refused. + /// A file that omits `X_MAX_COMMITTEE_COUNT_PER_SLOT` runs on its + /// preset's `MAX_COMMITTEES_PER_SLOT_PQ`, not on the mainnet value the key + /// parsed as, and its config says so afterwards. + #[test] + fn an_absent_committee_cap_is_the_presets() { + let mut parsed = ConfigFile::parse("CONFIG_NAME: devnet\n").unwrap(); + assert!(!parsed.committee_cap_declared); + // Whatever another preset's default would have left there. + parsed.config.x_max_committee_count_per_slot = u64::MAX; + select_committee_cap(&mut parsed).unwrap(); + assert_eq!( + parsed.config.x_max_committee_count_per_slot, + ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64 + ); + } + + #[test] + fn a_committee_cap_above_the_presets_is_refused() { + let above = ethlambda_types::beacon::preset::max_committees_per_slot_pq() as u64 + 1; + let yaml = format!("X_MAX_COMMITTEE_COUNT_PER_SLOT: {above}\n"); + let mut parsed = ConfigFile::parse(&yaml).unwrap(); + assert!(parsed.committee_cap_declared); + let err = select_committee_cap(&mut parsed).unwrap_err(); + assert_eq!((err.declared, err.max), (above, above - 1)); + } + #[test] fn the_shipped_configs_match_the_compiled_constants() { check_constants(&Config::mainnet()).unwrap(); diff --git a/bin/ethlambda/src/pq_prover_check.rs b/bin/ethlambda/src/pq_prover_check.rs new file mode 100644 index 000000000..651b6a893 --- /dev/null +++ b/bin/ethlambda/src/pq_prover_check.rs @@ -0,0 +1,121 @@ +//! What leanVM's prover does on this machine (`ethlambda pq-prover-check`). +//! +//! On a network that schedules the PQ fork, the node proves each of its +//! aggregators' committees between that seat's cutoff and its broadcast: the +//! difference of `AGGREGATE_DUE_BPS_PQ` and `AGGREGATION_CUTOFF_BPS`, 2.4 s of +//! a 12-second slot. leanVM makes one proof at a time, so a proof that does +//! not fit is an aggregate that is never broadcast. How long one takes +//! depends on the host: its cores, and which instructions its CPU has that +//! the build can use. +//! +//! This starts the prover as the node does, proves and verifies an aggregate +//! of as many signatures as asked, a few times over, and reports what each +//! round took against that budget. It touches no network and no data +//! directory, so it answers before a devnet's genesis rather than at its +//! first aggregation duty. + +use std::time::Duration; + +use ethlambda_crypto::stark::leanvm::{ + LEANVM_REV, LeanVmBackend, LeanVmConfig, MAX_SELF_CHECK_SIGNATURES, PROTOCOL_VERSION, +}; +use ethlambda_types::beacon::config::Config; +use eyre::WrapErr as _; +use tracing::{info, warn}; + +#[derive(Debug, clap::Args)] +pub(crate) struct PqProverCheckOptions { + /// How many signatures one aggregate proves: the attesters of one + /// committee. + #[arg( + long, + default_value_t = 128, + value_parser = clap::value_parser!(u32).range(1..=i64::from(MAX_SELF_CHECK_SIGNATURES)) + )] + signatures: u32, + + /// How many threads leanVM's prover runs on, 0 for one per core: the + /// node's `--pq-prover-threads`. + #[arg(long, default_value_t = 0)] + threads: usize, + + /// How many times to prove. The first round pays for whatever the prover + /// sets up on first use. + #[arg(long, default_value_t = 3, value_parser = clap::value_parser!(u32).range(1..))] + rounds: u32, +} + +pub(crate) fn run(options: PqProverCheckOptions) -> eyre::Result<()> { + let config = LeanVmConfig { + threads: options.threads, + ..LeanVmConfig::default() + }; + let backend = LeanVmBackend::setup(config).wrap_err("cannot start leanVM's prover")?; + let signatures = options.signatures as usize; + let rounds = backend + .measure(signatures, options.rounds as usize) + .wrap_err("leanVM's prover failed")?; + + let budget = seat_budget(&Config::mainnet()); + for (round, check) in rounds.iter().enumerate() { + info!( + round = round + 1, + signatures, + prove_ms = check.prove.as_millis() as u64, + verify_ms = check.verify.as_millis() as u64, + proof_bytes = check.proof_bytes, + "Proved and verified an aggregate" + ); + } + let slowest = rounds + .iter() + .map(|check| check.prove) + .max() + .unwrap_or_default(); + let (slowest_ms, budget_ms) = (slowest.as_millis() as u64, budget.as_millis() as u64); + if slowest < budget { + info!( + signatures, + slowest_ms, + budget_ms, + leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, + "One aggregate of this size fits a seat's proving window on a 12-second slot" + ); + } else { + warn!( + signatures, + slowest_ms, + budget_ms, + leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, + "One aggregate of this size does not fit a seat's proving window on a 12-second \ + slot: this host would miss its aggregates" + ); + } + Ok(()) +} + +/// How long a seat has to prove on `config`'s timing: from its cutoff to its +/// broadcast, the same for every seat. +fn seat_budget(config: &Config) -> Duration { + let bps = config + .aggregate_due_bps_pq + .saturating_sub(config.aggregation_cutoff_bps); + Duration::from_millis(bps.saturating_mul(config.slot_duration_ms) / 10_000) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// PQ `validator.md`'s 12-second example: a seat stops collecting at 4.8 s + /// and broadcasts at 7.2 s. + #[test] + fn a_seat_has_the_cutoff_to_broadcast_window_to_prove_in() { + assert_eq!( + seat_budget(&Config::mainnet()), + Duration::from_millis(2_400) + ); + } +} diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index d0651928f..b1b0b8a42 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -6,9 +6,7 @@ use std::path::PathBuf; use ethlambda_types::beacon::primitives::{Bytes32, ExecutionAddress, H160}; -use ethlambda_validator::proposer_settings::{ - DEFAULT_GAS_LIMIT, GRAFFITI_BYTES, graffiti_from_text, -}; +use ethlambda_validator::proposer_settings::{GRAFFITI_BYTES, graffiti_from_text}; use ethlambda_validator::{BuilderProposals, ValidatorConfig}; use eyre::WrapErr as _; @@ -81,17 +79,14 @@ pub(crate) struct ValidatorOptions { /// Before gloas it goes into builder registrations (with /// `--builder-proposals`). From gloas it goes into the proposer /// preferences, published for every proposal, and the beacon node builds - /// this client's own payloads toward it too, so on a network whose gas - /// limit is not the default, set it or every proposal pulls the limit - /// toward 60M. Sepolia and Platåberget schedule 200000000: pass - /// `--gas-limit 200000000` there. The network config's - /// `GAS_LIMIT_SCHEDULE` is not read yet (#795). - #[arg( - long, - default_value_t = DEFAULT_GAS_LIMIT, - value_parser = clap::value_parser!(u64).range(1..) - )] - pub(crate) gas_limit: u64, + /// this client's own payloads toward it too. + /// + /// Without it, the gas limit is the one the network's `GAS_LIMIT_SCHEDULE` + /// (read off the beacon node's `/eth/v1/config/spec`) names for the + /// proposal's epoch, and 60000000 for an epoch it names none, or when the + /// node does not serve the key. + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + pub(crate) gas_limit: Option, /// Serve the keymanager API: keystores, remote keys, plus each validator's /// own fee recipient, graffiti and gas limit. @@ -357,7 +352,7 @@ mod tests { metrics_port: 5064, graffiti: graffiti.to_string(), suggested_fee_recipient: None, - gas_limit: DEFAULT_GAS_LIMIT, + gas_limit: None, enable_keymanager: false, web3signer_url: None, builder_proposals: false, @@ -394,11 +389,12 @@ mod tests { Cli::try_parse_from(base.iter().chain(extra)).map(|cli| cli.options) } + /// Unset unless given, so the network's schedule can supply the default. #[test] - fn the_gas_limit_defaults_to_60m_and_takes_any_positive_value() { - assert_eq!(parse(&[]).expect("parses").gas_limit, DEFAULT_GAS_LIMIT); + fn the_gas_limit_is_unset_by_default_and_takes_any_positive_value() { + assert_eq!(parse(&[]).expect("parses").gas_limit, None); let options = parse(&["--gas-limit", "200000000"]).expect("parses"); - assert_eq!(options.gas_limit, 200_000_000); + assert_eq!(options.gas_limit, Some(200_000_000)); parse(&["--gas-limit", "0"]).expect_err("a zero gas limit is a mistake"); } diff --git a/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml b/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml index 5e491f0cb..8b89a197d 100644 --- a/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml +++ b/bin/ethlambda/tests/fixtures/networks/devnet/config.yaml @@ -203,8 +203,8 @@ BLOB_SCHEDULE: - EPOCH: 419072 # January 7, 2026, 01:01:11am UTC MAX_BLOBS_PER_BLOCK: 21 -# Keys a kurtosis-generated config carries that mainnet's does not. GLOAS_* and -# PAYLOAD_DUE_BPS are claimed by `Config` now; GAS_LIMIT_SCHEDULE, +# Keys a kurtosis-generated config carries that mainnet's does not. GLOAS_*, +# PAYLOAD_DUE_BPS and GAS_LIMIT_SCHEDULE are claimed by `Config` now; # HEZE_FORK_VERSION, HEZE_FORK_EPOCH, and INCLUSION_LIST_DUE_BPS are still # deliberately present: this build cannot process heze, so they must land in # the ignored-key warning rather than in Config. diff --git a/crates/blockchain/src/payload_attributes.rs b/crates/blockchain/src/payload_attributes.rs index c8a10af2f..be8e5b063 100644 --- a/crates/blockchain/src/payload_attributes.rs +++ b/crates/blockchain/src/payload_attributes.rs @@ -37,7 +37,9 @@ use ethlambda_engine::{CustodyColumns, EngineClient, ForkchoiceStateV1}; use ethlambda_state_transition::beacon::block_production::{ PayloadInputs, advance_to_slot, payload_inputs, }; -use ethlambda_state_transition::beacon::builder_market::SharedBuilderMarket; +use ethlambda_state_transition::beacon::builder_market::{ + PqBuilderMarket, SharedBuilderMarket, SharedPqBuilderMarket, +}; use ethlambda_state_transition::beacon::fork_choice::{ advance_to_epoch_start, get_head_node, should_build_on_full, }; @@ -105,6 +107,9 @@ pub fn prepared_fee_recipient( pub struct PayloadPreparation { pub fee_recipients: FeeRecipients, pub builder_market: SharedBuilderMarket, + /// The PQ fork's proposer preferences, which PQ block production reads + /// its gas target from (see [`prepare_pq_proposal`]). + pub pq_builder_market: SharedPqBuilderMarket, /// `--always-prepare-payload`. pub always_prepare: bool, /// The payload builds the actor started ahead of their slots, shared @@ -466,9 +471,11 @@ fn prepare_gloas_proposal_on( } /// Everything a PQ block at a slot builds on: [`GloasProposal`]'s -/// counterpart for PQ's own production endpoint (`pq_blocks/{slot}`). PQ has -/// no proposer preferences in production, so the fee recipient is -/// `prepare_beacon_proposer`'s, else the zero address. +/// counterpart for PQ's own production endpoint (`pq_blocks/{slot}`). The fee +/// recipient is `prepare_beacon_proposer`'s, else the zero address. The gas +/// target is the one the proposer's own signed PQ preferences for the slot +/// name, when this node holds them, else the parent's gas limit (see +/// [`pq_preferred_gas_limit`]). pub struct PqProposal { /// The head state advanced to the proposal slot. pub state: BeaconState, @@ -487,6 +494,7 @@ pub struct PqProposal { /// preparation ahead of the slot, so the two compute the same attributes. pub fn prepare_pq_proposal( store: &Store, + market: &PqBuilderMarket, head_root: H256, head_state: &BeaconState, slot: Slot, @@ -495,12 +503,13 @@ pub fn prepare_pq_proposal( return Err(ProposalError::NotAfterHead); } let build_on_full = parent_builds_on_full(store, head_root, slot)?; - prepare_pq_proposal_on(store, head_root, head_state, slot, build_on_full) + prepare_pq_proposal_on(store, market, head_root, head_state, slot, build_on_full) } /// [`prepare_pq_proposal`] with the parent payload branch already chosen. fn prepare_pq_proposal_on( store: &Store, + market: &PqBuilderMarket, head_root: H256, head_state: &BeaconState, slot: Slot, @@ -535,8 +544,14 @@ fn prepare_pq_proposal_on( })?; let proposer = get_beacon_proposer_index(&state) .map_err(|_| ProposalError::Internal("no proposer for the slot"))?; - let inputs = pq_payload_inputs(&state, build_on_full, &parent_requests, &config) + let mut inputs = pq_payload_inputs(&state, build_on_full, &parent_requests, &config) .map_err(|_| ProposalError::Internal("computing the payload attributes failed"))?; + // As gloas's self-build does: without this the payload is built toward + // the parent's gas limit, so the network's `GAS_LIMIT_SCHEDULE`, which + // the validator client signs into its preferences, never moved it. + if let Some(target) = pq_preferred_gas_limit(market, head_state, head_root, slot, proposer) { + inputs.target_gas_limit = target; + } Ok(PqProposal { state, inputs, @@ -546,6 +561,23 @@ fn prepare_pq_proposal_on( }) } +/// The target gas limit of `proposer`'s own signed PQ preferences for +/// `slot`, under the dependent root `head_root`'s chain gives the slot, when +/// this node holds them. Preferences another validator signed for the slot +/// (the slot moved to it in a reorg) do not count. +fn pq_preferred_gas_limit( + market: &PqBuilderMarket, + head_state: &BeaconState, + head_root: H256, + slot: Slot, + proposer: ValidatorIndex, +) -> Option { + dependent_root_at(head_state, head_root, slot) + .and_then(|dependent_root| market.preferences(slot, dependent_root)) + .filter(|signed| signed.message.validator_index == proposer) + .map(|signed| signed.message.target_gas_limit) +} + // --------------------------------------------------------------------------- // The event // --------------------------------------------------------------------------- @@ -690,9 +722,15 @@ pub(crate) fn next_payload( // whose preparation this is too ([`prepare_pq_proposal`]). ForkName::Pq => { let build_on_full = choose_build_on_full()?; - let proposal = - prepare_pq_proposal_on(store, head_root, head_state, proposal_slot, build_on_full) - .map_err(|err| format!("preparing the proposal failed: {err:?}"))?; + let proposal = prepare_pq_proposal_on( + store, + &preparation.pq_builder_market, + head_root, + head_state, + proposal_slot, + build_on_full, + ) + .map_err(|err| format!("preparing the proposal failed: {err:?}"))?; if !prepares_for(proposal.proposer) { return Ok(None); } @@ -761,8 +799,10 @@ pub(crate) struct AttributesKey { /// gloas, and while no status is recorded for the head, in which case the /// worker chooses. pub(crate) build_on_full: Option, - /// Gloas: the fee recipient and gas target of the proposer's signed - /// preferences for the slot, once this node holds them. + /// Gloas and PQ: the fee recipient and gas target of the proposer's + /// signed preferences for the slot, once this node holds them. PQ + /// production reads only the gas target, but a change to either starts + /// another build, which is harmless. pub(crate) preferences: Option<(ExecutionAddress, u64)>, } @@ -801,8 +841,23 @@ pub(crate) fn attributes_key( }); (build_on_full(), preferences) } - // PQ production takes no proposer preferences. - ForkName::Pq => (build_on_full(), None), + // PQ production takes the gas target from them + // ([`prepare_pq_proposal`]), so their arrival starts another build. + ForkName::Pq => { + let preferences = dependent_root_at(head_state, head_root, proposal_slot) + .and_then(|root| { + preparation + .pq_builder_market + .preferences(proposal_slot, root) + }) + .map(|signed| { + ( + signed.message.fee_recipient, + signed.message.target_gas_limit, + ) + }); + (build_on_full(), preferences) + } _ => (None, None), }; AttributesKey { @@ -1195,6 +1250,49 @@ mod tests { } } + /// PQ block production builds toward the gas target of the proposer's + /// own signed PQ preferences for the slot, under the dependent root the + /// head's chain gives it: the network's `GAS_LIMIT_SCHEDULE` reaches the + /// payload through them. Without them, another validator's, or ones + /// under another dependent root, it keeps the parent's gas limit. + #[test] + fn a_pq_proposal_takes_the_gas_target_of_its_proposers_own_preferences() { + use ethlambda_types::beacon::containers::gloas::ProposerPreferences; + + let (_, head_root, head_state) = fulu_store(); + let slot = head_state.slot() + 1; + let dependent_root = dependent_root_at(&head_state, head_root, slot).expect("in range"); + let proposer = 7; + let preferences = |validator_index, dependent_root| pq::SignedProposerPreferences { + message: ProposerPreferences { + dependent_root, + proposal_slot: slot, + validator_index, + fee_recipient: ExecutionAddress::ZERO, + target_gas_limit: 200_000_000, + }, + signature: Default::default(), + }; + let lookup = |market: &PqBuilderMarket| { + pq_preferred_gas_limit(market, &head_state, head_root, slot, proposer) + }; + + let market = PqBuilderMarket::default(); + assert_eq!(lookup(&market), None, "none held"); + assert!(market.record_preferences(preferences(proposer, dependent_root), slot - 1)); + assert_eq!(lookup(&market), Some(200_000_000)); + + let another_validators = PqBuilderMarket::default(); + let theirs = preferences(proposer + 1, dependent_root); + assert!(another_validators.record_preferences(theirs, slot - 1)); + assert_eq!(lookup(&another_validators), None, "another validator's"); + + let another_root = PqBuilderMarket::default(); + let stale = preferences(proposer, H256::repeat_byte(0x99)); + assert!(another_root.record_preferences(stale, slot - 1)); + assert_eq!(lookup(&another_root), None, "under another dependent root"); + } + #[test] fn a_registered_proposer_gets_the_attributes_block_production_would_send() { let (store, head_root, head_state) = fulu_store(); diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index 32e5d7e92..c5f23434a 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -3,12 +3,14 @@ //! //! # Why ahead of the slot //! -//! The merge folds the selected aggregates' proofs into one on the proving -//! sidecar: about 0.6 s for two children on pq-devnet-0. Block production used -//! to run it when the validator client asked for the block, at the slot's -//! start, so every block this node proposed waited for it. Its blocks reached -//! the network at about 1.0 to 1.2 s, against 0.15 to 0.4 s for Prysm's, -//! Teku's, Lighthouse's and Silver's, which carry the same merged proof. +//! The merge folds the selected aggregates' proofs into one, a leanVM proof +//! made in process: about 0.6 s for two children on pq-devnet-0's sidecar, +//! and up to about 2 s in pq-devnet-1's first hours. Block production used to +//! run it when the validator client asked for the block, at the slot's start, +//! so every block this node proposed waited for it. On pq-devnet-0 its blocks +//! reached the network at about 1.0 to 1.2 s, against 0.15 to 0.4 s for +//! Prysm's, Teku's, Lighthouse's and Silver's, which carry the same merged +//! proof; Prysm merges about 9.6 s into the slot before. //! //! Nothing the merge reads is new at the slot. A block at slot `S` packs //! aggregates from `S - MIN_ATTESTATION_INCLUSION_DELAY_PQ` (two slots) and @@ -29,12 +31,20 @@ //! //! # One merge at a time //! -//! The sidecar proves one request after another, so the merges share one -//! permit ([`MERGE_PERMIT`]). A packing replaced by another (the head moved) -//! is abandoned and does not start its merge; one already merging finishes, +//! leanVM proves one request after another, so the merges share one permit +//! ([`MERGE_PERMIT`]). A packing replaced by another (the head moved) is +//! abandoned and does not start its merge; one already merging finishes, //! unheard. A packing ahead of the slot waits for the permit, having seconds //! to spare; production tries it once and packs one committee's attestation //! when it is held, as it always has. +//! +//! The node's own aggregates prove on the same leanVM, at each aggregator +//! seat's cutoff (`rpc`'s `pq_aggregation`), and the last seat's cutoff is +//! before a third of a slot ahead. So the slot's aggregate proofs have +//! normally all started when a packing asks for leanVM: on pq-devnet-1 each +//! takes about 0.7 s, and the last ends about 8 s into the slot. One still +//! waiting for leanVM then may be proved after the packing's merge, since +//! nothing orders the two. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -110,7 +120,7 @@ fn same_aggregates(a: &[Arc], b: &[Arc]) - addresses(a) == addresses(b) } -/// One merge at a time: the sidecar proves one request after another, so a +/// One merge at a time: leanVM proves one request after another, so a /// second merge started while one runs would only push both past their /// deadlines. A merge that missed its deadline keeps the permit until it /// ends. Shared by the merge ahead of the slot and the one at production. diff --git a/crates/blockchain/state_transition/src/beacon/fork_choice.rs b/crates/blockchain/state_transition/src/beacon/fork_choice.rs index 5028ac87d..f47bc9010 100644 --- a/crates/blockchain/state_transition/src/beacon/fork_choice.rs +++ b/crates/blockchain/state_transition/src/beacon/fork_choice.rs @@ -4357,6 +4357,31 @@ pub fn get_payload_due_ms(config: &Config) -> u64 { get_slot_component_duration_ms(config.payload_due_bps, config) } +/// `get_aggregate_due_ms` as PQ modifies it (`pq/fork-choice.md`): how far +/// into a slot, in milliseconds, the aggregator at `position` in its +/// aggregation committee broadcasts its aggregate. +/// +/// The aggregators of a committee are staggered, `AGGREGATOR_DELAY_BPS` +/// apart in the committee's order, so a later one can skip an aggregate an +/// earlier one already covered. Named apart from the earlier forks' +/// `get_aggregate_due_ms`, which takes no position and which nothing in this +/// crate implements: its reader is the validator client's clock. +pub fn get_pq_aggregate_due_ms(position: u64, config: &Config) -> u64 { + let delay_ms = get_slot_component_duration_ms(config.aggregator_delay_bps, config); + get_slot_component_duration_ms(config.aggregate_due_bps_pq, config) + .saturating_add(position.saturating_mul(delay_ms)) +} + +/// `get_aggregation_cutoff_ms` (PQ `fork-choice.md`): how far into a slot, in +/// milliseconds, the aggregator at `position` in its aggregation committee +/// stops collecting attestations. From then until +/// [`get_pq_aggregate_due_ms`] it proves the ones it has. +pub fn get_aggregation_cutoff_ms(position: u64, config: &Config) -> u64 { + let delay_ms = get_slot_component_duration_ms(config.aggregator_delay_bps, config); + get_slot_component_duration_ms(config.aggregation_cutoff_bps, config) + .saturating_add(position.saturating_mul(delay_ms)) +} + // --------------------------------------------------------------------------- // Merge transition helpers (bellatrix) // --------------------------------------------------------------------------- @@ -6562,6 +6587,31 @@ mod tests { use crate::beacon::helpers::test_state; use crate::beacon::primitives::BlsSignature; + /// PQ `validator.md`'s table for a 12-second slot: each seat of an + /// aggregation committee stops collecting and broadcasts 0.6 s after the + /// one before it, with 2.4 s in between to prove. + #[test] + fn pq_aggregators_are_staggered_by_their_seat() { + let config = Config::mainnet(); + assert_eq!(config.slot_duration_ms, 12_000); + let expected = [ + (4_800, 7_200), + (5_400, 7_800), + (6_000, 8_400), + (6_600, 9_000), + ]; + for (position, (cutoff, due)) in (0..constants::AGGREGATORS_PER_COMMITTEE).zip(expected) { + assert_eq!(get_aggregation_cutoff_ms(position, &config), cutoff); + assert_eq!(get_pq_aggregate_due_ms(position, &config), due); + } + // The last seat still broadcasts within the slot, on both presets. + for config in [Config::mainnet(), Config::minimal()] { + let last = constants::AGGREGATORS_PER_COMMITTEE - 1; + assert!(get_pq_aggregate_due_ms(last, &config) <= config.slot_duration_ms); + assert!(get_aggregation_cutoff_ms(0, &config) > get_attestation_due_ms(0, &config)); + } + } + /// A store backed by a fresh in-memory backend, with every checkpoint at /// its default (genesis) value and no anchor block or state written. /// Tests populate only what the function under test actually reads. diff --git a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs index 18e723ea6..e48768438 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/mod.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/mod.rs @@ -211,10 +211,6 @@ pub enum IgnoreReason { AlreadyExiting, /// The head state's sync committees cannot answer for the message's period. SyncCommitteeUnavailable, - /// A PQ aggregate's proof could not be checked: the prover sidecar did not - /// answer, as while `ethlambda-pq` restarts it. Nothing is known about the - /// proof, so this is not the sender's fault. - ProverUnreachable, } impl IgnoreReason { @@ -258,7 +254,6 @@ impl IgnoreReason { Self::BeforeFork => "before_fork", Self::AlreadyExiting => "already_exiting", Self::SyncCommitteeUnavailable => "sync_committee_unavailable", - Self::ProverUnreachable => "prover_unreachable", } } } diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index 15d89ae3e..968d64fb3 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs @@ -1,6 +1,6 @@ //! Gossip validation for the PQ fork's topics //! (`specs/_features/pq/p2p-interface.md`, consensus-specs' `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Every topic whose message carries a validator's or builder's signature //! carries an XMSS one instead, at the leaf the fork assigns that message, and @@ -61,7 +61,7 @@ use crate::beacon::helpers::misc::{ use crate::beacon::helpers::pq::{ compute_xmss_attestation_leaf_index, compute_xmss_leaf_index, get_aggregation_committee, get_attestation_statements, get_attesting_indices, get_committee_indices, - is_valid_indexed_attestation, try_verify_aggregates, xmss_verify, + is_valid_indexed_attestation, verify_aggregates, xmss_verify, }; use crate::beacon::helpers::predicates::{is_slashable_attestation_data, is_slashable_validator}; use crate::beacon::lean_boundary::lean_block_unreachable; @@ -331,15 +331,11 @@ pub fn aggregate_stateful_checks( if !aggregators.contains(&aggregator_index) { return Err(Outcome::Reject(RejectReason::NotAggregator)); } - // [Modified in PQ] [REJECT] The aggregate stark is valid. A prover sidecar - // that did not answer (restarting, say) judged nothing, so the aggregate - // is IGNOREd rather than its sender penalized for it. + // [Modified in PQ] [REJECT] The aggregate stark is valid. let statements = get_attestation_statements(&state, aggregate, &committees) .map_err(|_| Outcome::Reject(RejectReason::AggregateProof))?; - match try_verify_aggregates(&statements, &aggregate_and_proof.proof) { - Ok(true) => {} - Ok(false) => return Err(Outcome::Reject(RejectReason::AggregateProof)), - Err(_) => return Err(Outcome::Ignore(IgnoreReason::ProverUnreachable)), + if !verify_aggregates(&statements, &aggregate_and_proof.proof) { + return Err(Outcome::Reject(RejectReason::AggregateProof)); } let attesting_indices = get_attesting_indices(&state, aggregate, &committees) .map_err(|_| Outcome::Ignore(IgnoreReason::Internal))?; diff --git a/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs index 7749dd19e..d11f8431c 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/accessors.rs @@ -142,7 +142,9 @@ pub fn committee_count_per_slot(active_count: u64) -> u64 { } /// The most committees a slot of `fork` has: `MAX_COMMITTEES_PER_SLOT`, or -/// the PQ fork's `MAX_COMMITTEES_PER_SLOT_PQ`. +/// the PQ fork's `X_MAX_COMMITTEE_COUNT_PER_SLOT` (consensus-specs pq +/// `af898d07`; at most `MAX_COMMITTEES_PER_SLOT_PQ`, and equal to it unless a +/// devnet lowers it). /// /// The PQ fork's cap applies to every epoch a PQ state is asked about, /// including a previous epoch that ran before the fork: the specification's @@ -150,7 +152,7 @@ pub fn committee_count_per_slot(active_count: u64) -> u64 { /// are recomputed under the new cap. pub fn max_committees_per_slot(fork: ForkName) -> u64 { if fork == ForkName::Pq { - preset::max_committees_per_slot_pq() as u64 + ethlambda_types::beacon::config::x_max_committee_count_per_slot() } else { preset::max_committees_per_slot() as u64 } diff --git a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs index 7396adc31..af6f25a23 100644 --- a/crates/blockchain/state_transition/src/beacon/helpers/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/helpers/pq.rs @@ -1,6 +1,6 @@ //! Helpers the PQ fork adds or modifies (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! # Keys //! @@ -105,19 +105,6 @@ pub fn verify_aggregates(statements: &[AggregateStatement], proof: &[u8]) -> boo stark::verify_aggregates(statements, proof) } -/// [`verify_aggregates`], with a prover sidecar that could not be reached -/// told apart from a proof that does not verify (`stark::try_verify_aggregates`), -/// for gossip, which IGNOREs what it could not judge. -pub fn try_verify_aggregates( - statements: &[AggregateStatement], - proof: &[u8], -) -> std::result::Result { - if !xmss_verification_enabled() { - return Ok(true); - } - stark::try_verify_aggregates(statements, proof) -} - // --------------------------------------------------------------------------- // Misc // --------------------------------------------------------------------------- @@ -134,11 +121,15 @@ pub fn compute_legacy_vrf_root(pubkey: &BlsPubkey) -> Root { legacy_digest(pubkey, constants::LEGACY_VRF_ROOT_DOMAIN) } +/// `keccak256(pubkey + domain)`. SHA-256 before consensus-specs pq +/// `4c296784`, which moved both legacy derivations to the hash the VRF tree +/// already uses; the RANDAO mix and the aggregation committee seeds stay on +/// SHA-256. fn legacy_digest(pubkey: &BlsPubkey, domain: u8) -> Bytes32 { let mut input = Vec::with_capacity(pubkey.0.len() + 1); input.extend_from_slice(&pubkey.0); input.push(domain); - hash(&input) + ethlambda_types::primitives::H256(ethlambda_crypto::keccak256(&input)) } /// `is_legacy_pubkey`: whether a 48-byte request key names a BLS key (made @@ -201,11 +192,14 @@ pub fn is_builder_bid_leaf_index(leaf_index: u64) -> bool { (start..start + constants::XMSS_BUILDER_BID_LEAVES).contains(&leaf_index) } -/// `is_valid_vrf_proof`: whether `proof` opens the leaf at index `slot` of the -/// tree under the VRF root of the validator at `validator_index`. +/// `is_valid_vrf_proof`: whether `proof` reveals the secret that the leaf at +/// index `slot` of the tree under the VRF root of the validator at +/// `validator_index` commits to. /// /// The tree is hashed with Keccak-256, not the SHA-256 of -/// `is_valid_merkle_branch`, and `proof[0]` is the leaf itself. +/// `is_valid_merkle_branch`, and its leaf is `compute_vrf_leaf` of the +/// revealed secret and the slot: the branch holds only commitments, so a +/// reveal gives away no other slot's secret. pub fn is_valid_vrf_proof( state: &BeaconState, validator_index: ValidatorIndex, @@ -609,6 +603,29 @@ mod tests { ); } + /// consensus-specs pq `4c296784`: `keccak256(pubkey + domain)`, the + /// domain one byte, not `sha256`. + #[test] + fn legacy_keys_are_keccak256_of_the_bls_key_and_domain() { + let bls = BlsPubkey([0xa5; 48]); + let digest = |domain: u8| { + let mut input = bls.0.to_vec(); + input.push(domain); + ethlambda_crypto::keccak256(&input) + }; + assert_eq!( + compute_legacy_xmss_pubkey(&bls).0, + digest(constants::LEGACY_XMSS_PUBKEY_DOMAIN) + ); + assert_eq!( + compute_legacy_vrf_root(&bls).0, + digest(constants::LEGACY_VRF_ROOT_DOMAIN) + ); + let mut sha_input = bls.0.to_vec(); + sha_input.push(constants::LEGACY_XMSS_PUBKEY_DOMAIN); + assert_ne!(compute_legacy_xmss_pubkey(&bls).0, hash(&sha_input).0); + } + /// A PQ state at `slot` whose block root at each earlier slot is /// `roots[slot]`: a skipped slot repeats the root before it. fn pq_state_with_roots(slot: Slot, roots: &[u8]) -> BeaconState { diff --git a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs index 95c7cb16d..f4a9bcf7b 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/eip8483.rs @@ -1,6 +1,6 @@ //! EIP-8483's block processing (consensus-specs //! `specs/_features/eip8483/beacon-chain.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's block processing, with two more execution-layer request lists in //! the parent payload: validators and builders register post-quantum material diff --git a/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs index 0750579b1..d49eb9696 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/epoch/pq.rs @@ -1,6 +1,6 @@ //! The PQ fork's epoch processing (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's driver without `process_sync_committee_updates` (sync committees are //! gone), with [`process_aggregation_committee_window`] and diff --git a/crates/blockchain/state_transition/src/beacon/stf/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/pq.rs index ad6f6644c..6172b444f 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/pq.rs @@ -1,6 +1,6 @@ //! The PQ fork's block processing (consensus-specs //! `specs/_features/pq/beacon-chain.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! Gloas's block processing with leanXMSS in place of BLS: //! @@ -9,7 +9,7 @@ //! (`compute_xmss_leaf_index`), a bid at any of the bid leaves; //! - attestations carry no signature: the block's `proof` covers all of them, //! checked once in [`process_stark`] after every attestation is processed; -//! - the RANDAO reveal is a VRF proof, the leaf the proposer's committed +//! - the RANDAO reveal is a VRF proof, the secret the proposer's committed //! tree holds for the slot ([`process_randao`]); //! - voluntary exits are execution-layer requests, and the body loses //! `voluntary_exits`, `sync_aggregate`, `bls_to_execution_changes` and @@ -135,8 +135,8 @@ pub fn verify_block_signature(state: &BeaconState, signed_block: &pq::SignedBeac } /// `process_randao` (modified in PQ): the reveal is the proposer's VRF proof -/// for the slot, and the leaf it reveals is mixed in. The proposer committed -/// to its leaves when it registered its VRF root, so it cannot grind the +/// for the slot, and the secret it reveals is mixed in. The proposer committed +/// to its secrets when it registered its VRF root, so it cannot grind the /// reveal and can only withhold its block, as with BLS. pub fn process_randao( state: &mut BeaconState, @@ -995,17 +995,17 @@ mod tests { ) } - /// A VRF proof for `slot` under a root it determines: the leaf and every - /// sibling chosen, the root folded up from the leaf, as - /// `is_valid_vrf_proof` folds. - fn vrf_proof_and_root(slot: Slot, leaf: Bytes32) -> (pq::VrfProof, Root) { + /// A VRF proof for `slot` under a root it determines: the secret and + /// every sibling chosen, the root folded up from the leaf committing to + /// the secret, as `is_valid_vrf_proof` folds. + fn vrf_proof_and_root(slot: Slot, secret: Bytes32) -> (pq::VrfProof, Root) { let siblings: Vec = (0..constants::VRF_TREE_DEPTH) // Distinct from any node a test folds, so no level's order is moot. .map(|level| Bytes32::repeat_byte(level as u8 + 0x40)) .collect(); let branch = siblings.iter().map(|sibling| &sibling.0); - let root = ethlambda_crypto::vrf::fold_vrf_branch(&leaf.0, branch, slot); - let mut proof = vec![leaf]; + let root = ethlambda_crypto::vrf::fold_vrf_branch(&secret.0, branch, slot); + let mut proof = vec![secret]; proof.extend(siblings); ( pq::VrfProof::try_from(proof).expect("VRF_TREE_DEPTH + 1 roots"), @@ -1026,44 +1026,50 @@ mod tests { } #[test] - fn a_valid_vrf_proof_mixes_its_leaf_in() { + fn a_valid_vrf_proof_mixes_its_secret_in() { let mut state = with_validators_at(ForkName::Pq, 64); let slot = state.slot(); let proposer = get_beacon_proposer_index(&state).unwrap(); - let leaf = Bytes32::repeat_byte(0xab); - let (proof, root) = vrf_proof_and_root(slot, leaf); + let secret = Bytes32::repeat_byte(0xab); + let (proof, root) = vrf_proof_and_root(slot, secret); set_key(&mut state, proposer, XmssPubkey::default(), root); let epoch = get_current_epoch(&state); let previous = get_randao_mix(&state, epoch); process_randao(&mut state, &proof, RandaoVerification::Verify).unwrap(); - let expected = hash(&[&previous.0[..], &leaf.0, &constants::DOMAIN_RANDAO].concat()); + let expected = hash(&[&previous.0[..], &secret.0, &constants::DOMAIN_RANDAO].concat()); assert_eq!(get_randao_mix(&state, epoch), expected); } #[test] - fn a_vrf_proof_for_another_slot_or_leaf_is_refused() { + fn a_vrf_proof_for_another_slot_or_secret_is_refused() { let mut state = with_validators_at(ForkName::Pq, 64); let slot = state.slot(); let proposer = get_beacon_proposer_index(&state).unwrap(); - // A root opening the leaf at the next slot: the same leaf and branch - // revealed at this slot fold to a different root. + // A root committing to the secret at the next slot: the same secret + // and branch revealed at this slot fold to a different root. let (proof, next_slot_root) = vrf_proof_and_root(slot + 1, Bytes32::repeat_byte(1)); set_key(&mut state, proposer, XmssPubkey::default(), next_slot_root); assert!(process_randao(&mut state.clone(), &proof, RandaoVerification::Verify).is_err()); let (_, root) = vrf_proof_and_root(slot, Bytes32::repeat_byte(1)); set_key(&mut state, proposer, XmssPubkey::default(), root); - let (wrong_leaf, _) = vrf_proof_and_root(slot, Bytes32::repeat_byte(2)); + let (wrong_secret, _) = vrf_proof_and_root(slot, Bytes32::repeat_byte(2)); assert!( - process_randao(&mut state.clone(), &wrong_leaf, RandaoVerification::Verify).is_err() + process_randao( + &mut state.clone(), + &wrong_secret, + RandaoVerification::Verify + ) + .is_err() ); // Block production's skip still mixes the reveal in, unchecked. - assert!(process_randao(&mut state, &wrong_leaf, RandaoVerification::Skip).is_ok()); + assert!(process_randao(&mut state, &wrong_secret, RandaoVerification::Skip).is_ok()); } - /// The tree is hashed with Keccak-256 (`2f43bc0f`). A proof whose root is - /// folded with SHA-256, the rule before it, is refused. + /// The tree is hashed with Keccak-256 and its leaf commits to the secret + /// and the slot. A proof whose root is folded with SHA-256 from the + /// secret itself, the rule before both changes, is refused. #[test] fn a_vrf_proof_under_the_earlier_sha256_tree_is_refused() { let mut state = with_validators_at(ForkName::Pq, 64); @@ -1085,6 +1091,20 @@ mod tests { assert!(process_randao(&mut state, &proof, RandaoVerification::Verify).is_err()); } + /// The leaf commits to the whole slot, while the branch reads only its + /// low `VRF_TREE_DEPTH` bits: a proof for `slot` does not also open + /// `slot + 2^31`, which walks the same path. + #[test] + fn a_vrf_leaf_commits_to_its_whole_slot() { + let mut state = with_validators_at(ForkName::Pq, 64); + let slot = state.slot(); + let (proof, root) = vrf_proof_and_root(slot, Bytes32::repeat_byte(0xab)); + set_key(&mut state, 0, XmssPubkey::default(), root); + assert!(is_valid_vrf_proof(&state, 0, slot, &proof).unwrap()); + let same_path = slot + (1 << constants::VRF_TREE_DEPTH); + assert!(!is_valid_vrf_proof(&state, 0, same_path, &proof).unwrap()); + } + #[test] fn the_block_signature_is_checked_at_the_slots_proposer_leaf() { let mut state = with_validators_at(ForkName::Pq, 64); diff --git a/crates/common/crypto/Cargo.toml b/crates/common/crypto/Cargo.toml index c55273174..54c0d612c 100644 --- a/crates/common/crypto/Cargo.toml +++ b/crates/common/crypto/Cargo.toml @@ -23,7 +23,7 @@ pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] } leanvm.workspace = true leanvm_claims.workspace = true leanvm_lean_xmss.workspace = true -leanvm_sidecar.workspace = true +leanvm_prover.workspace = true postcard.workspace = true thiserror.workspace = true @@ -31,6 +31,13 @@ tracing.workspace = true [features] shadow-integration = [] +# leanVM's PQ prover compiled once more per CPU tier (AVX-512, GFNI and +# VPCLMULQDQ on x86-64, SHA3 on arm64), the fastest tier the running CPU has +# picked at run time. Only a build with leanVM's `scripts/tier-rustc` as +# `RUSTC_WRAPPER` gives the tiers their instructions, which the Dockerfile +# does; without the wrapper the feature compiles the copies and uses none. +# Off by default so that an ordinary build does not compile them. +leanvm-cpu-tiers = ["leanvm_prover/cpu_tiers"] [dev-dependencies] hex.workspace = true diff --git a/crates/common/crypto/src/lib.rs b/crates/common/crypto/src/lib.rs index f25c7def1..2742eeddb 100644 --- a/crates/common/crypto/src/lib.rs +++ b/crates/common/crypto/src/lib.rs @@ -48,7 +48,7 @@ pub mod bls; /// The Beacon Chain PQ fork's leanXMSS signatures (the specification's `xmss` /// module), over Keccak-256. Not the XMSS of [`signature`]. pub mod lean_xmss; -/// leanVM's own leanXMSS (bindings v0.15.0): what a validator signs with and +/// leanVM's own leanXMSS (bindings v0.19.0): what a validator signs with and /// what [`lean_xmss::verify`] runs, re-exported so a signer depends on one pin. pub use leanvm_lean_xmss; mod metrics; @@ -57,7 +57,8 @@ mod metrics; pub mod pq_keys; pub mod signature; /// The Beacon Chain PQ fork's proofs of many leanXMSS signatures (the -/// specification's `stark` module), in its reference concatenation encoding. +/// specification's `stark` module): its reference concatenation encoding, or +/// leanVM proofs made in process. pub mod stark; /// The Beacon Chain PQ fork's VRF tree, whose openings are its RANDAO /// reveals: verification for the state transition, derivation for a @@ -67,6 +68,13 @@ pub mod vrf; #[cfg(feature = "shadow-integration")] pub mod shadow_cost; +/// The Beacon Chain PQ fork's `keccak256` (Ethereum's Keccak-256, with +/// Keccak's original padding, not SHA3-256's), over `data`. +pub fn keccak256(data: &[u8]) -> [u8; 32] { + use sha3::{Digest as _, Keccak256}; + Keccak256::digest(data).into() +} + /// log(1/rate) for the WHIR commitment scheme used inside the aggregation prover. const LOG_INV_RATE: usize = 2; diff --git a/crates/common/crypto/src/stark.rs b/crates/common/crypto/src/stark.rs index 4c8160c67..3d2b0d738 100644 --- a/crates/common/crypto/src/stark.rs +++ b/crates/common/crypto/src/stark.rs @@ -7,9 +7,9 @@ //! of every statement's public keys, in statement order and within a //! statement in public-key order, and verification checks each in turn. It //! is what the specification's fixtures use. -//! - **Sidecar** ([`install_sidecar`]): real leanVM proofs, made and checked -//! by a `leanvm-sidecar` process over a Unix socket, as the PQ devnet's -//! other clients make them. See [`sidecar`]. +//! - **leanVM** ([`install_leanvm`]): real leanVM proofs, made and checked +//! in this process (bindings v0.19.0), as the PQ devnet's other clients make +//! them. See [`leanvm`]. //! //! The two encodings are not interchangeable: a node verifies only the proofs //! its own backend makes, so every node of a network must run the same one. @@ -25,12 +25,12 @@ use rayon::prelude::*; use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; -pub mod sidecar; +pub mod leanvm; /// The backend every proof of this process goes through. enum Backend { Reference, - Sidecar(sidecar::SidecarBackend), + LeanVm(leanvm::LeanVmBackend), } static BACKEND: OnceLock = OnceLock::new(); @@ -39,22 +39,26 @@ fn backend() -> &'static Backend { BACKEND.get_or_init(|| Backend::Reference) } -/// Makes every proof of this process a leanVM proof from the sidecar at -/// `config.socket`, after checking it answers with this protocol and -/// verifier. Call once, at startup, before anything proves or verifies: -/// whichever backend is first used stays for the life of the process. -pub fn install_sidecar(config: sidecar::SidecarConfig) -> Result<(), sidecar::Error> { - let backend = sidecar::SidecarBackend::connect(config)?; +/// Makes every proof of this process a leanVM proof, made and checked in +/// process, after starting leanVM's prover pool and passing its self-check +/// (about a second). Call once, at startup, before anything proves or +/// verifies: whichever backend is first used stays for the life of the +/// process. +pub fn install_leanvm(config: leanvm::LeanVmConfig) -> Result<(), leanvm::Error> { + if BACKEND.get().is_some() { + return Err(leanvm::Error::AlreadyInstalled); + } + let backend = leanvm::LeanVmBackend::setup(config)?; BACKEND - .set(Backend::Sidecar(backend)) - .map_err(|_| sidecar::Error::AlreadyInstalled) + .set(Backend::LeanVm(backend)) + .map_err(|_| leanvm::Error::AlreadyInstalled) } -/// The installed backend's name, for logs: `reference` or `sidecar`. +/// The installed backend's name, for logs: `reference` or `leanvm`. pub fn backend_name() -> &'static str { match backend() { Backend::Reference => "reference", - Backend::Sidecar(_) => "sidecar", + Backend::LeanVm(_) => "leanvm", } } @@ -90,15 +94,15 @@ pub enum ProveError { expected: u64, found: u64, }, - #[error("the prover sidecar failed: {0}")] - Sidecar(String), + #[error("leanVM could not prove: {0}")] + LeanVm(String), } /// `stark.ProveAggregates(statements, signatures)`: `signatures[i][j]` is the /// signature of `statements[i].pubkeys[j]`. The reference verifies nothing -/// and only asserts the shapes line up; the sidecar refuses a signature that -/// does not verify. Blocks the calling thread for as long as the proof takes, -/// which under the sidecar is seconds. +/// and only asserts the shapes line up; leanVM refuses a signature that does +/// not verify. Blocks the calling thread for as long as the proof takes, +/// which under leanVM is seconds, and leanVM makes one proof at a time. pub fn prove_aggregates>( statements: &[AggregateStatement], signatures: &[Vec], @@ -111,7 +115,7 @@ pub fn prove_aggregates>( .flat_map(|signature| signature.as_ref()) .copied() .collect()), - Backend::Sidecar(sidecar) => sidecar.prove(statements, signatures), + Backend::LeanVm(leanvm) => leanvm.prove(statements, signatures), } } @@ -127,49 +131,20 @@ pub fn merge_proofs, P: AsRef<[u8]>>( .flat_map(|(_, proof)| proof.as_ref()) .copied() .collect()), - Backend::Sidecar(sidecar) => sidecar.merge(children), + Backend::LeanVm(leanvm) => leanvm.merge(children), } } /// `stark.VerifyAggregates(statements, proof)`. Under the reference, `true` /// only if `proof` holds, for each statement in turn and each of its public /// keys in order, a signature `xmss.Verify` accepts at the statement's leaf -/// index and message, and nothing else. Under the sidecar, whether the leanVM -/// proof proves every `(public key, message)` claim; it cannot check the leaf -/// indices, which leanVM proofs do not attest. A sidecar that cannot answer -/// reads as `false`, and is logged; [`try_verify_aggregates`] tells it apart. +/// index and message, and nothing else. Under leanVM, whether the proof +/// proves every `(public key, message)` claim; it cannot check the leaf +/// indices, which leanVM proofs do not attest. pub fn verify_aggregates(statements: &[AggregateStatement], proof: &[u8]) -> bool { - try_verify_aggregates(statements, proof).unwrap_or_else(|err| { - tracing::error!(%err, "The prover sidecar could not verify an attestation proof"); - false - }) -} - -/// The sidecar could not be asked: no connection, or one that failed or timed -/// out, as while `ethlambda-pq` restarts it. Says nothing about the proof. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("the prover sidecar could not be reached: {0}")] -pub struct SidecarUnreachable(pub String); - -/// [`verify_aggregates`], with a sidecar that could not be reached told apart -/// from a proof that does not verify, so gossip can IGNORE a message it could -/// not judge rather than penalize the peer that sent it. Only a connection -/// failure is [`SidecarUnreachable`]: a sidecar that answered and refused the -/// request is logged and reads as `false`, as an invalid proof does. -pub fn try_verify_aggregates( - statements: &[AggregateStatement], - proof: &[u8], -) -> Result { match backend() { - Backend::Reference => Ok(reference_verify(statements, proof)), - Backend::Sidecar(sidecar) => match sidecar.verify(statements, proof) { - Ok(valid) => Ok(valid), - Err(sidecar::Error::Io(err)) => Err(SidecarUnreachable(err.to_string())), - Err(err) => { - tracing::error!(%err, "The prover sidecar refused to verify an attestation proof"); - Ok(false) - } - }, + Backend::Reference => reference_verify(statements, proof), + Backend::LeanVm(leanvm) => leanvm.verify(statements, proof), } } diff --git a/crates/common/crypto/src/stark/leanvm.rs b/crates/common/crypto/src/stark/leanvm.rs new file mode 100644 index 000000000..3d8f3aaa3 --- /dev/null +++ b/crates/common/crypto/src/stark/leanvm.rs @@ -0,0 +1,641 @@ +//! Attestation proofs made and checked by leanVM in this process (bindings +//! v0.19.0, [`LEANVM_REV`]). +//! +//! The PQ devnet does not run the specification's reference concatenation: +//! its clients prove with leanVM. pq-devnet-0 did it through a separate +//! `leanvm-sidecar` process; v0.17.0 removed the sidecar, and every client now +//! proves in-process through `lean_vm`'s `setup`, `aggregate` and +//! `AggregateProof::{from_bytes, verify}`. Proofs only verify against a +//! verifier of the same release, and nothing on the wire says so: a proof from +//! another revision simply fails to verify. +//! +//! The mapping from the specification's statements is Lighthouse's, so the +//! two clients' proofs verify against each other: +//! +//! - A leanVM proof attests `(public key, message)` claims. A statement list +//! flattens to the sorted, deduplicated list of its pairs (the verifier only +//! accepts a claim list strictly sorted by the 64 bytes `pubkey || message`). +//! - **The leaf index is not part of a claim** (leanEthereum/leanVM#787), so +//! [`LeanVmBackend::verify`] shows each key signed the message at *some* +//! leaf, not at the statement's. [`LeanVmBackend::prove`] refuses +//! signatures made at another leaf, since it sees them. +//! - The empty proof stands for "nothing to prove" (leanVM refuses to prove +//! zero claims), and verifies only against no claims. +//! - A merge folds the children [`MAX_CHILDREN_PER_AGGREGATE`] at a time, +//! round after round, until one proof remains. +//! +//! leanVM runs one proof at a time per process ("a second waits for the +//! first"), on a thread pool of its own that [`LeanVmBackend::setup`] starts. +//! Verification takes no lock and runs on the calling thread, so it does not +//! wait for a proof in progress. +//! +//! Every call into leanVM goes through [`guarded`], which catches a panic +//! inside it: see there for why that matters more in process than it did +//! behind a socket. + +use std::time::{Duration, Instant}; + +use leanvm_claims::{AggregateClaims, OutputClaims}; +use leanvm_lean_xmss::{LeanXmssPublicKey, LeanXmssSignature}; +use leanvm_prover::AggregateProof; + +use super::{AggregateStatement, ProveError}; +use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; + +/// The most children one aggregate takes (leanVM's `MAX_RECURSIONS`). +pub const MAX_CHILDREN_PER_AGGREGATE: usize = leanvm_prover::MAX_RECURSIONS; + +/// leanVM's own count of its STARK-breaking changes: proofs and signatures +/// verify between two builds exactly when this is the same in both. What to +/// compare with another client's when a proof of theirs does not verify. +pub const PROTOCOL_VERSION: u32 = leanvm_prover::PROTOCOL_VERSION; + +/// The leanVM revision the workspace proves and verifies with (bindings +/// v0.19.0). Every node of a network must run the same one. +pub const LEANVM_REV: &str = "351f7ae421529ce164ed747eee1f78bdeaec3e80"; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("leanVM: {0}")] + LeanVm(String), + #[error("a proof backend is already installed")] + AlreadyInstalled, + #[error("leanVM proved {found} claims, {expected} were asked")] + ClaimsMismatch { expected: usize, found: usize }, + #[error("child {0} has claims and an empty proof, or a proof and no claims")] + MalformedChild(usize), + #[error("child {0}'s proof does not decode")] + UndecodableChild(usize), + #[error("log_inv_rate {0} is outside leanVM's {min}..={max}", min = leanvm_prover::MIN_LOG_INV_RATE, max = leanvm_prover::MAX_LOG_INV_RATE)] + LogInvRate(u8), + #[error("leanVM panicked in {call}: {reason}")] + Panicked { call: &'static str, reason: String }, + #[error("leanVM failed its self-check: {0}")] + SelfCheck(String), +} + +/// Runs one call into leanVM, catching a panic inside it. +/// +/// pq-devnet-0 ran leanVM in a sidecar, where an input that crashed it cost +/// a restart of that process. In process, the caller is the thread importing +/// a block or judging gossip, and the proof bytes come from peers: a panic +/// must fail the one proof, not unwind through the chain actor. Verification +/// shares no lock with proving, so it goes on whatever a panic left behind; +/// proving may not (leanVM's signer cache does not tolerate a poisoned lock), +/// and then every later proof fails here the same way, loudly. +fn guarded(call: &'static str, run: impl FnOnce() -> T) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).map_err(|panic| { + let reason = panic + .downcast_ref::<&str>() + .map(|reason| (*reason).to_string()) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_else(|| "no message".to_string()); + tracing::error!(call, %reason, "leanVM panicked"); + Error::Panicked { call, reason } + }) +} + +/// The seed of the throwaway key [`LeanVmBackend::self_check`] signs with. +/// Public, so the key protects nothing, and the rule that a seed backs one +/// key only ([`lean_xmss::range_key`]) costs it nothing: the check builds it +/// over as many leaves as it is asked to prove. +const SELF_CHECK_SEED: [u8; 32] = *b"ethlambda leanVM self-check key."; + +/// The most signatures [`LeanVmBackend::self_check`] proves at once: twice the +/// largest committee, and within the throwaway key's first bottom tree. +pub const MAX_SELF_CHECK_SIGNATURES: u32 = 4096; + +/// What [`LeanVmBackend::self_check`] measured. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SelfCheck { + pub signatures: usize, + pub prove: Duration, + pub verify: Duration, + pub proof_bytes: usize, +} + +impl From for ProveError { + fn from(error: Error) -> Self { + ProveError::LeanVm(error.to_string()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LeanVmConfig { + /// How many threads leanVM's prover pool runs, 0 for one per physical + /// core. + pub threads: usize, + /// `log_inv_rate` of the proofs made, within leanVM's bounds: a higher + /// rate gives smaller proofs that take longer to make. A proof verifies + /// whatever rate it was made at. + pub log_inv_rate: u8, +} + +impl Default for LeanVmConfig { + /// One thread per core, at the rate pq-devnet-0's sidecars proved at + /// (Lighthouse's default). + fn default() -> Self { + Self { + threads: 0, + log_inv_rate: 2, + } + } +} + +pub struct LeanVmBackend { + log_inv_rate: usize, +} + +impl LeanVmBackend { + /// Starts leanVM's prover pool and builds its aggregation program, which + /// verifying needs too, then proves and verifies one signature + /// ([`Self::self_check`]): a prover that cannot run on this machine is + /// reported here, at startup, rather than at the first aggregation duty. + /// Takes about a second; call once. + /// + /// More threads than the machine has cores are lowered to the cores, + /// with a warning: leanVM would oversubscribe them. Setup also picks the + /// prover's CPU tier (since bindings v0.18.0), so a build that leaves + /// some of this CPU unused says so on stderr here, not at the first + /// proof. + pub fn setup(config: LeanVmConfig) -> Result { + let rate = usize::from(config.log_inv_rate); + if !(leanvm_prover::MIN_LOG_INV_RATE..=leanvm_prover::MAX_LOG_INV_RATE).contains(&rate) { + return Err(Error::LogInvRate(config.log_inv_rate)); + } + let cores = std::thread::available_parallelism().map_or(1, usize::from); + let threads = threads_within(config.threads, cores); + if threads != config.threads { + tracing::warn!( + asked = config.threads, + cores, + "More leanVM prover threads than cores; using one per core" + ); + } + let started = Instant::now(); + guarded("setup", || leanvm_prover::setup(threads))?; + let backend = Self { log_inv_rate: rate }; + let setup_ms = started.elapsed().as_millis() as u64; + let check = backend.self_check(1)?; + tracing::info!( + threads, + log_inv_rate = config.log_inv_rate, + leanvm_rev = LEANVM_REV, + protocol_version = PROTOCOL_VERSION, + setup_ms, + self_check_prove_ms = check.prove.as_millis() as u64, + self_check_verify_ms = check.verify.as_millis() as u64, + "leanVM prover ready, in process" + ); + Ok(backend) + } + + /// Proves `signatures` leanXMSS signatures of a throwaway key, each over + /// its own message at its own leaf, and checks that the proof verifies + /// against those claims and against no others. The times are the prover's + /// and the verifier's alone, without the signing. + /// + /// As many claims as a committee of `signatures` attesters gives, so the + /// proving time is what one seat's aggregate of that size costs here. + pub fn self_check(&self, signatures: usize) -> Result { + let input = self_check_input(signatures)?; + self.prove_and_verify(input.statements, &input.signatures) + } + + /// [`Self::self_check`] `rounds` times over one input, signed once: what + /// proving costs on this machine round after round, the first paying for + /// whatever the prover sets up on first use. + pub fn measure(&self, signatures: usize, rounds: usize) -> Result, Error> { + let input = self_check_input(signatures)?; + (0..rounds) + .map(|_| self.prove_and_verify(input.statements.clone(), &input.signatures)) + .collect() + } + + fn prove_and_verify( + &self, + mut statements: Vec, + signed: &[Vec>], + ) -> Result { + let started = Instant::now(); + let proof = self + .prove(&statements, signed) + .map_err(|err| Error::SelfCheck(format!("proving: {err}")))?; + let prove = started.elapsed(); + let started = Instant::now(); + if !self.verify(&statements, &proof) { + return Err(Error::SelfCheck("the proof it made does not verify".into())); + } + let verify = started.elapsed(); + // And against nothing else: a verifier that accepts every proof is + // worse than one that accepts none. + statements[0].message[31] ^= 1; + if self.verify(&statements, &proof) { + return Err(Error::SelfCheck( + "the proof verifies against a claim it does not prove".into(), + )); + } + Ok(SelfCheck { + signatures: statements.len(), + prove, + verify, + proof_bytes: proof.len(), + }) + } + + pub(super) fn prove>( + &self, + statements: &[AggregateStatement], + signatures: &[Vec], + ) -> Result, ProveError> { + for (statement_index, (statement, group)) in statements.iter().zip(signatures).enumerate() { + for (signature_index, signature) in group.iter().enumerate() { + let found = lean_xmss::signature_index(signature.as_ref()).unwrap_or(u64::MAX); + if found != statement.leaf_index { + return Err(ProveError::LeafIndex { + statement: statement_index, + signature: signature_index, + expected: statement.leaf_index, + found, + }); + } + } + } + let expected = statements_to_claims(statements); + if expected.lean_xmss.is_empty() { + return Ok(Vec::new()); + } + let raw_signatures: Vec<_> = statements + .iter() + .zip(signatures) + .flat_map(|(statement, group)| { + statement + .pubkeys + .iter() + .zip(group) + .map(|(pubkey, signature)| { + let signature: &[u8; SIGNATURE_SIZE] = signature + .as_ref() + .try_into() + .expect("check_shape bounds every signature's length"); + ( + LeanXmssPublicKey::from_bytes(pubkey), + statement.message, + LeanXmssSignature::from_bytes(signature), + ) + }) + }) + .collect(); + let proof = self.aggregate(&[], raw_signatures, &expected)?; + Ok(proof.to_bytes()) + } + + pub(super) fn merge, P: AsRef<[u8]>>( + &self, + children: &[(S, P)], + ) -> Result, ProveError> { + let mut level: Vec<(AggregateClaims, AggregateProof)> = Vec::with_capacity(children.len()); + for (index, (statements, proof)) in children.iter().enumerate() { + let claims = statements_to_claims(statements.as_ref()); + match (claims.lean_xmss.is_empty(), proof.as_ref().is_empty()) { + (true, true) => {} + (false, false) => { + let proof = guarded("decode", || AggregateProof::from_bytes(proof.as_ref()))? + .ok_or(Error::UndecodableChild(index))?; + level.push((claims, proof)); + } + _ => return Err(Error::MalformedChild(index).into()), + } + } + while level.len() > 1 { + let mut next = Vec::with_capacity(level.len().div_ceil(MAX_CHILDREN_PER_AGGREGATE)); + let mut rest = level.into_iter().peekable(); + while rest.peek().is_some() { + let chunk: Vec<_> = rest.by_ref().take(MAX_CHILDREN_PER_AGGREGATE).collect(); + if chunk.len() == 1 { + next.extend(chunk); + continue; + } + let expected = union(&chunk); + let proof = self.aggregate(&chunk, Vec::new(), &expected)?; + next.push((expected, proof)); + } + level = next; + } + Ok(level + .pop() + .map(|(_, proof)| proof.to_bytes()) + .unwrap_or_default()) + } + + pub(super) fn verify(&self, statements: &[AggregateStatement], proof: &[u8]) -> bool { + let claims = statements_to_claims(statements); + if claims.lean_xmss.is_empty() || proof.is_empty() { + return claims.lean_xmss.is_empty() && proof.is_empty(); + } + // A panic reads as a proof that does not verify: the bytes are a + // peer's, and whatever they did to the verifier, they proved nothing. + guarded("verify", || { + AggregateProof::from_bytes(proof).is_some_and(|proof| proof.verify(&claims)) + }) + .unwrap_or(false) + } + + /// One aggregate. Checks leanVM proved exactly `expected`. + fn aggregate( + &self, + children: &[(AggregateClaims, AggregateProof)], + raw_signatures: Vec<(LeanXmssPublicKey, Message, LeanXmssSignature)>, + expected: &AggregateClaims, + ) -> Result { + let started = Instant::now(); + let signatures = raw_signatures.len(); + let (claims, proof) = guarded("aggregate", || { + leanvm_prover::aggregate( + children, + raw_signatures, + Vec::new(), + None, + OutputClaims::All, + self.log_inv_rate, + ) + })? + .map_err(|err| Error::LeanVm(err.to_string()))?; + if claims != *expected { + return Err(Error::ClaimsMismatch { + expected: expected.num_signature_claims(), + found: claims.num_signature_claims(), + }); + } + tracing::debug!( + children = children.len(), + signatures, + claims = claims.num_signature_claims(), + elapsed_ms = started.elapsed().as_millis() as u64, + "Proved an attestation aggregate" + ); + Ok(proof) + } +} + +/// What [`LeanVmBackend::self_check`] proves: statements of one public key +/// each, and each statement's one signature, in the same order. +struct SelfCheckInput { + statements: Vec, + signatures: Vec>>, +} + +/// `signatures` statements of one signature each, by one throwaway key over +/// its first leaves, with their signatures as [`LeanVmBackend::prove`] takes +/// them. +/// +/// One key rather than one per signature: a claim is a `(public key, +/// message)` pair, so the prover's work is the same, and a key's leaves share +/// a bottom tree that is built once. Its signatures are then independent and +/// made in parallel; the tree is built first, since a signature that had to +/// build it would do so with rayon from inside a rayon task. +fn self_check_input(signatures: usize) -> Result { + use rayon::prelude::*; + let count = u32::try_from(signatures) + .ok() + .filter(|count| (1..=MAX_SELF_CHECK_SIGNATURES).contains(count)) + .ok_or_else(|| { + Error::SelfCheck(format!( + "cannot prove {signatures} signatures: 1 to {MAX_SELF_CHECK_SIGNATURES}" + )) + })?; + let key = lean_xmss::range_key(&SELF_CHECK_SEED, 0, count - 1); + key.prepare(0) + .map_err(|err| Error::SelfCheck(format!("building the key: {err}")))?; + let pubkey = key.public_key().to_bytes(); + let signed: Vec<(AggregateStatement, Vec>)> = (0..count) + .into_par_iter() + .map(|leaf| { + let mut message: Message = [0x5c; 32]; + message[..4].copy_from_slice(&leaf.to_le_bytes()); + let signature = key + .sign(&message, leaf) + .map_err(|err| Error::SelfCheck(format!("signing: {err}")))?; + let statement = AggregateStatement { + pubkeys: vec![pubkey], + leaf_index: u64::from(leaf), + message, + }; + Ok((statement, vec![signature.to_bytes()])) + }) + .collect::>()?; + let (statements, signatures) = signed.into_iter().unzip(); + Ok(SelfCheckInput { + statements, + signatures, + }) +} + +/// `asked` prover threads on a machine of `cores`: 0 (one per core) as it is, +/// and never more than the cores. +fn threads_within(asked: usize, cores: usize) -> usize { + asked.min(cores) +} + +/// The claims a proof of `statements` attests: every `(pubkey, message)` +/// pair, strictly sorted by its bytes, without duplicates. No leanSPHINCS +/// claims and no DA commitment. +pub fn statements_to_claims(statements: &[AggregateStatement]) -> AggregateClaims { + let mut pairs: Vec<([u8; PUBKEY_SIZE], Message)> = statements + .iter() + .flat_map(|statement| { + statement + .pubkeys + .iter() + .map(|pubkey| (*pubkey, statement.message)) + }) + .collect(); + // Tuples of byte arrays order as their concatenation does. + pairs.sort_unstable(); + pairs.dedup(); + AggregateClaims { + lean_xmss: pairs + .into_iter() + .map(|(pubkey, message)| (LeanXmssPublicKey::from_bytes(&pubkey), message)) + .collect(), + lean_sphincs: Vec::new(), + da_commitment: None, + } +} + +/// The claims a proof of all of `children` attests: their union, strictly +/// sorted. +fn union(children: &[(AggregateClaims, AggregateProof)]) -> AggregateClaims { + let mut lean_xmss: Vec<_> = children + .iter() + .flat_map(|(claims, _)| claims.lean_xmss.iter().copied()) + .collect(); + lean_xmss.sort_unstable(); + lean_xmss.dedup(); + AggregateClaims { + lean_xmss, + lean_sphincs: Vec::new(), + da_commitment: None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn statement( + pubkeys: &[[u8; PUBKEY_SIZE]], + leaf_index: u64, + message: Message, + ) -> AggregateStatement { + AggregateStatement { + pubkeys: pubkeys.to_vec(), + leaf_index, + message, + } + } + + #[test] + fn no_claims_encode_as_empty_lists() { + let expected = [0u8; 8 + 8 + 1]; + assert_eq!(statements_to_claims(&[]).to_bytes(), expected); + assert_eq!( + statements_to_claims(&[statement(&[], 1, [7; 32])]).to_bytes(), + expected + ); + } + + /// Lighthouse's `claims_bytes_match_the_sidecar_format`: out of order within + /// and across statements, one repeated claim, one key signing two + /// messages, and no leaf index on the wire. + #[test] + fn claims_are_sorted_deduplicated_pairs() { + let mut low_key = [3; 32]; + low_key[31] = 2; + let statements = [ + statement(&[[9; 32], [3; 32], low_key], 40_000, [0xaa; 32]), + statement(&[[3; 32], [1; 32]], 50_000, [0x11; 32]), + statement(&[[9; 32]], 60_000, [0xaa; 32]), + ]; + let mut expected = Vec::new(); + expected.extend_from_slice(&5u64.to_le_bytes()); + for (key, message) in [ + ([1; 32], [0x11; 32]), + (low_key, [0xaa; 32]), + ([3; 32], [0x11; 32]), + ([3; 32], [0xaa; 32]), + ([9; 32], [0xaa; 32]), + ] { + expected.extend_from_slice(&key); + expected.extend_from_slice(&message); + } + expected.extend_from_slice(&0u64.to_le_bytes()); + expected.push(0); + assert_eq!(statements_to_claims(&statements).to_bytes(), expected); + } + + #[test] + fn a_rate_outside_leanvms_bounds_is_refused() { + let config = LeanVmConfig { + threads: 0, + log_inv_rate: 0, + }; + assert!(matches!( + LeanVmBackend::setup(config), + Err(Error::LogInvRate(0)) + )); + } + + #[test] + fn a_panic_inside_leanvm_is_an_error_not_an_unwind() { + let caught = guarded("test", || -> u8 { panic!("boom {}", 7) }); + assert!(matches!( + caught, + Err(Error::Panicked { call: "test", reason }) if reason == "boom 7" + )); + assert_eq!(guarded("test", || 3).unwrap(), 3); + } + + #[test] + fn prover_threads_never_exceed_the_cores() { + assert_eq!(threads_within(0, 8), 0); + assert_eq!(threads_within(2, 8), 2); + assert_eq!(threads_within(8, 8), 8); + assert_eq!(threads_within(64, 8), 8); + } + + /// The places that name the leanVM revision agree: this module's + /// constant, the workspace manifest's three `rev`s, and the root + /// `leanvm-revision` file, which the image build reads. + #[test] + fn the_leanvm_pin_is_the_same_everywhere() { + let file = include_str!("../../../../../leanvm-revision").trim(); + assert_eq!(file, LEANVM_REV, "leanvm-revision"); + let manifest = include_str!("../../../../../Cargo.toml"); + for package in ["lean_vm", "claims", "lean_xmss"] { + let named = format!("package = \"{package}\""); + let line = manifest + .lines() + .find(|line| line.contains(&named)) + .unwrap_or_else(|| panic!("no {package} dependency in the workspace manifest")); + assert!(line.contains(&format!("rev = \"{LEANVM_REV}\"")), "{line}"); + } + } + + /// End to end on leanVM itself: `setup` proves and verifies its + /// self-check, then two committees' proofs, merged, verify against their + /// concatenated statements and nothing else, and bytes that are no proof + /// verify against nothing. + /// + /// Ignored by a plain `cargo test`, which spends minutes on it + /// unoptimized; `make test-consensus`, and so CI, runs it by name under + /// `release-fast`, where it takes a second or two. + #[test] + #[ignore = "minutes unoptimized: `make test-consensus` runs it by name"] + fn leanvm_proofs_merge_and_verify() { + use crate::lean_xmss::range_key; + let backend = LeanVmBackend::setup(LeanVmConfig::default()).unwrap(); + let check = backend.self_check(4).unwrap(); + assert_eq!(check.signatures, 4); + assert!(check.proof_bytes > 0); + let signed = |seed: u8, leaf: u32, message: &Message| { + let key = range_key(&[seed; 32], leaf, leaf); + let signature = key.sign(message, leaf).unwrap().to_bytes(); + (key.public_key().to_bytes(), signature) + }; + let (m1, m2): (Message, Message) = ([1; 32], [2; 32]); + let (a, sig_a) = signed(10, 40, &m1); + let (b, sig_b) = signed(11, 40, &m1); + let (c, sig_c) = signed(12, 41, &m2); + let first = [statement(&[a, b], 40, m1)]; + let second = [statement(&[c], 41, m2)]; + let one = backend.prove(&first, &[vec![&sig_a, &sig_b]]).unwrap(); + let two = backend.prove(&second, &[vec![&sig_c]]).unwrap(); + assert!(backend.verify(&first, &one)); + assert!(!backend.verify(&second, &one)); + let merged = backend + .merge(&[(&first[..], &one[..]), (&second[..], &two[..])]) + .unwrap(); + let both = [first[0].clone(), second[0].clone()]; + assert!(backend.verify(&both, &merged)); + assert!(!backend.verify(&first, &merged)); + assert!(!backend.verify(&both, &merged[..merged.len() - 1])); + // What a peer can send in a proof's place. + assert!(!backend.verify(&both, &[0xff; 64])); + assert!(!backend.verify(&both, &u64::MAX.to_le_bytes())); + let mut flipped = merged.clone(); + *flipped.last_mut().unwrap() ^= 1; + assert!(!backend.verify(&both, &flipped)); + // A signature made at another leaf than the statement's is refused + // before leanVM sees it, since the proof would not attest the leaf. + let wrong_leaf = [statement(&[c], 42, m2)]; + assert!(matches!( + backend.prove(&wrong_leaf, &[vec![&sig_c]]), + Err(ProveError::LeafIndex { + expected: 42, + found: 41, + .. + }) + )); + } +} diff --git a/crates/common/crypto/src/stark/sidecar.rs b/crates/common/crypto/src/stark/sidecar.rs deleted file mode 100644 index 9228d03e3..000000000 --- a/crates/common/crypto/src/stark/sidecar.rs +++ /dev/null @@ -1,513 +0,0 @@ -//! Attestation proofs from a `leanvm-sidecar` process, over its Unix socket -//! (protocol version 1, `bins/leanvm-sidecar/README.md` in the leanVM -//! repository). -//! -//! The PQ devnet does not run the specification's reference concatenation: -//! its clients prove with leanVM, through this sidecar. The wire protocol is -//! leanVM's own client crate at the revision the workspace pins -//! ([`LEANVM_REV`]). The sidecar itself is started outside this process, as -//! for Lighthouse, and may be built from another revision: the hello is -//! checked for this client's protocol version and verifier tag, and nothing -//! else on the wire detects a mismatch. Proofs only have to verify with the -//! other clients' verifiers, so which revision a devnet proves with is the -//! devnet's choice, within that tag. -//! -//! The mapping from the specification's statements is Lighthouse's, so the -//! two clients' proofs verify against each other: -//! -//! - A leanVM proof attests `(public key, message)` claims. A statement list -//! flattens to the sorted, deduplicated list of its pairs (the verifier only -//! accepts a claim list strictly sorted by the 64 bytes `pubkey || message`). -//! - **The leaf index is not part of a claim** (leanEthereum/leanVM#787), so -//! [`SidecarBackend::verify`] shows each key signed the message at *some* -//! leaf, not at the statement's. [`SidecarBackend::prove`] refuses -//! signatures made at another leaf, since it sees them. -//! - The empty proof stands for "nothing to prove" (the sidecar refuses to -//! prove zero claims), and verifies only against no claims. -//! - A merge folds the children [`MAX_CHILDREN_PER_AGGREGATE`] at a time, -//! round after round, until one proof remains. -//! -//! Connections are reopened after a failure. One is for proving, where -//! requests queue in the sidecar. The others, [`SidecarConfig::verify_connections`] -//! of them, are for verifying, which the sidecar answers without waiting for -//! proofs in progress: it serves each connection on a thread of its own and -//! verifies there, so verifications on different connections run at once. -//! A verification takes a free connection and waits on one only when every -//! one is busy, so the node's gossip checks, imports and block production do -//! not queue behind each other's round trips. - -use std::path::PathBuf; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard, TryLockError}; -use std::time::{Duration, Instant}; - -use leanvm_claims::{AggregateClaims, OutputClaims}; -use leanvm_lean_xmss::{LeanXmssPublicKey, LeanXmssSignature}; -use leanvm_sidecar::{Client, SidecarError}; - -use super::{AggregateStatement, ProveError}; -use crate::lean_xmss::{self, Message, PUBKEY_SIZE, SIGNATURE_SIZE}; - -/// The most children one aggregate request takes. -pub const MAX_CHILDREN_PER_AGGREGATE: usize = 16; - -/// The leanVM revision the workspace's sidecar client is pinned to (bindings -/// v0.15.0). A sidecar from another revision is accepted when its hello -/// carries this client's protocol version and verifier tag. -pub const LEANVM_REV: &str = "c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764"; - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("sidecar connection: {0}")] - Io(#[from] std::io::Error), - #[error("sidecar: {0}")] - Sidecar(String), - #[error("a proof backend is already installed")] - AlreadyInstalled, - #[error("the sidecar proved {found} claims, {expected} were asked")] - ClaimsMismatch { expected: usize, found: usize }, - #[error("child {0} has claims and an empty proof, or a proof and no claims")] - MalformedChild(usize), -} - -impl From for Error { - fn from(error: SidecarError) -> Self { - match error { - SidecarError::Io(error) => Error::Io(error), - other => Error::Sidecar(format!("{other:?}")), - } - } -} - -impl From for ProveError { - fn from(error: Error) -> Self { - ProveError::Sidecar(error.to_string()) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SidecarConfig { - /// The Unix socket `leanvm-sidecar --socket` listens on. - pub socket: PathBuf, - /// `log_inv_rate` of the proofs requested, 1 to 4: a higher rate gives - /// smaller proofs that take longer to make. A proof verifies whatever rate - /// it was made at. - pub log_inv_rate: u8, - /// How long one prove or merge request may wait on the sidecar, queueing - /// behind others included. - pub prove_timeout: Duration, - /// How long one verify request may wait on the sidecar. - pub verify_timeout: Duration, - /// How many connections verify at once, at least one. The sidecar serves - /// at most 16 connections, the proving one among them. - pub verify_connections: usize, -} - -/// How many verifications run at once by default: enough that a burst of -/// gossip aggregates does not hold up a block's proof, few enough to leave -/// the prover its cores and the sidecar its connection limit. -pub const DEFAULT_VERIFY_CONNECTIONS: usize = 4; - -impl SidecarConfig { - /// Lighthouse's defaults, and [`DEFAULT_VERIFY_CONNECTIONS`]. - pub fn new(socket: impl Into) -> Self { - Self { - socket: socket.into(), - log_inv_rate: 2, - prove_timeout: Duration::from_secs(300), - verify_timeout: Duration::from_secs(30), - verify_connections: DEFAULT_VERIFY_CONNECTIONS, - } - } -} - -pub struct SidecarBackend { - config: SidecarConfig, - prove_connection: Mutex>, - /// Never empty. Each opened on first use, but for the first. - verify_connections: Vec>>, - /// Where the next verification starts looking for a free connection, so - /// the waits spread over all of them when every one is busy. - next_verify: AtomicUsize, -} - -impl SidecarBackend { - /// Opens the proving connection and the first verifying one now, checking - /// each hello (magic, protocol version, verifier tag), so a missing or - /// incompatible sidecar is reported at startup. The other verifying - /// connections open on first use. - pub fn connect(config: SidecarConfig) -> Result { - let prove_connection = open(&config, config.prove_timeout)?; - let first_verify = open(&config, config.verify_timeout)?; - tracing::info!( - socket = %config.socket.display(), - prover = prove_connection.prover(), - client_leanvm_rev = LEANVM_REV, - verify_connections = config.verify_connections.max(1), - "Connected to the leanVM prover sidecar" - ); - let verify_connections = std::iter::once(Some(first_verify)) - .chain(std::iter::repeat_with(|| None)) - .take(config.verify_connections.max(1)) - .map(Mutex::new) - .collect(); - Ok(Self { - config, - prove_connection: Mutex::new(Some(prove_connection)), - verify_connections, - next_verify: AtomicUsize::new(0), - }) - } - - /// A free verifying connection, or, when every one is busy, the next one - /// in turn once it frees. - fn verify_connection(&self) -> MutexGuard<'_, Option> { - let count = self.verify_connections.len(); - let start = self.next_verify.fetch_add(1, Ordering::Relaxed) % count; - let in_turn = (0..count).map(|offset| &self.verify_connections[(start + offset) % count]); - for connection in in_turn { - match connection.try_lock() { - Ok(guard) => return guard, - Err(TryLockError::Poisoned(poisoned)) => return poisoned.into_inner(), - Err(TryLockError::WouldBlock) => {} - } - } - lock(&self.verify_connections[start]) - } - - pub(super) fn prove>( - &self, - statements: &[AggregateStatement], - signatures: &[Vec], - ) -> Result, ProveError> { - for (statement_index, (statement, group)) in statements.iter().zip(signatures).enumerate() { - for (signature_index, signature) in group.iter().enumerate() { - let found = lean_xmss::signature_index(signature.as_ref()).unwrap_or(u64::MAX); - if found != statement.leaf_index { - return Err(ProveError::LeafIndex { - statement: statement_index, - signature: signature_index, - expected: statement.leaf_index, - found, - }); - } - } - } - let expected = statements_to_claims(statements); - if expected.lean_xmss.is_empty() { - return Ok(Vec::new()); - } - let raw_signatures: Vec<_> = statements - .iter() - .zip(signatures) - .flat_map(|(statement, group)| { - statement - .pubkeys - .iter() - .zip(group) - .map(|(pubkey, signature)| { - let signature: &[u8; SIGNATURE_SIZE] = signature - .as_ref() - .try_into() - .expect("check_shape bounds every signature's length"); - ( - LeanXmssPublicKey::from_bytes(pubkey), - statement.message, - LeanXmssSignature::from_bytes(signature), - ) - }) - }) - .collect(); - Ok(self.aggregate(&[], &raw_signatures, &expected)?) - } - - pub(super) fn merge, P: AsRef<[u8]>>( - &self, - children: &[(S, P)], - ) -> Result, ProveError> { - let mut level: Vec<(AggregateClaims, Vec)> = Vec::with_capacity(children.len()); - for (index, (statements, proof)) in children.iter().enumerate() { - let claims = statements_to_claims(statements.as_ref()); - match (claims.lean_xmss.is_empty(), proof.as_ref().is_empty()) { - (true, true) => {} - (false, false) => level.push((claims, proof.as_ref().to_vec())), - _ => return Err(Error::MalformedChild(index).into()), - } - } - while level.len() > 1 { - let mut next = Vec::with_capacity(level.len().div_ceil(MAX_CHILDREN_PER_AGGREGATE)); - for chunk in level.chunks(MAX_CHILDREN_PER_AGGREGATE) { - if let [only] = chunk { - next.push(only.clone()); - continue; - } - let expected = union(chunk); - let proof = self.aggregate(chunk, &[], &expected)?; - next.push((expected, proof)); - } - level = next; - } - Ok(level.pop().map(|(_, proof)| proof).unwrap_or_default()) - } - - pub(super) fn verify( - &self, - statements: &[AggregateStatement], - proof: &[u8], - ) -> Result { - let claims = statements_to_claims(statements); - if claims.lean_xmss.is_empty() || proof.is_empty() { - return Ok(claims.lean_xmss.is_empty() && proof.is_empty()); - } - with_connection( - &self.config, - self.verify_connection(), - self.config.verify_timeout, - |client| client.verify(&claims, proof), - ) - } - - /// One aggregate request on the proving connection. Checks the sidecar - /// proved exactly `expected`. - fn aggregate( - &self, - children: &[(AggregateClaims, Vec)], - raw_signatures: &[(LeanXmssPublicKey, Message, LeanXmssSignature)], - expected: &AggregateClaims, - ) -> Result, Error> { - let started = Instant::now(); - let (claims, proof) = with_connection( - &self.config, - lock(&self.prove_connection), - self.config.prove_timeout, - |client| { - client.aggregate( - children, - raw_signatures, - &[], - &[], - OutputClaims::All, - usize::from(self.config.log_inv_rate), - ) - }, - )?; - if claims != *expected { - return Err(Error::ClaimsMismatch { - expected: expected.num_signature_claims(), - found: claims.num_signature_claims(), - }); - } - tracing::debug!( - children = children.len(), - signatures = raw_signatures.len(), - claims = claims.num_signature_claims(), - proof_bytes = proof.len(), - elapsed_ms = started.elapsed().as_millis() as u64, - "Proved an attestation aggregate" - ); - Ok(proof) - } -} - -/// The claims a proof of `statements` attests: every `(pubkey, message)` -/// pair, strictly sorted by its bytes, without duplicates. No leanSPHINCS -/// claims and no DA commitment. -pub fn statements_to_claims(statements: &[AggregateStatement]) -> AggregateClaims { - let mut pairs: Vec<([u8; PUBKEY_SIZE], Message)> = statements - .iter() - .flat_map(|statement| { - statement - .pubkeys - .iter() - .map(|pubkey| (*pubkey, statement.message)) - }) - .collect(); - // Tuples of byte arrays order as their concatenation does. - pairs.sort_unstable(); - pairs.dedup(); - AggregateClaims { - lean_xmss: pairs - .into_iter() - .map(|(pubkey, message)| (LeanXmssPublicKey::from_bytes(&pubkey), message)) - .collect(), - lean_sphincs: Vec::new(), - da_commitment: None, - } -} - -/// The claims a proof of all of `children` attests: their union, strictly -/// sorted. -fn union(children: &[(AggregateClaims, Vec)]) -> AggregateClaims { - let mut lean_xmss: Vec<_> = children - .iter() - .flat_map(|(claims, _)| claims.lean_xmss.iter().copied()) - .collect(); - lean_xmss.sort_unstable(); - lean_xmss.dedup(); - AggregateClaims { - lean_xmss, - lean_sphincs: Vec::new(), - da_commitment: None, - } -} - -fn open(config: &SidecarConfig, timeout: Duration) -> Result { - let client = Client::connect(&config.socket)?; - client.set_timeout(Some(timeout))?; - Ok(client) -} - -/// `connection`'s lock. A panic while it was held leaves the connection as -/// it was, which the next call reuses or reopens like any other. -fn lock(connection: &Mutex>) -> MutexGuard<'_, Option> { - connection - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) -} - -/// Runs `call` on the connection in `slot`, held for the whole call, opening -/// it first if needed. A connection that fails is dropped, as the protocol -/// requires after anything but a rejection; if a reused one failed other than -/// by timing out, the sidecar may have restarted, so this reconnects and -/// tries once more. -fn with_connection( - config: &SidecarConfig, - mut slot: MutexGuard<'_, Option>, - timeout: Duration, - mut call: impl FnMut(&mut Client) -> Result, -) -> Result { - let mut reused = slot.is_some(); - loop { - let client = match slot.as_mut() { - Some(client) => client, - None => slot.insert(open(config, timeout)?), - }; - match call(client) { - Ok(value) => return Ok(value), - Err(SidecarError::Rejected(rejection, message)) => { - return Err(Error::Sidecar(format!("{rejection:?}: {message}"))); - } - Err(SidecarError::Io(error)) - if reused - && !matches!( - error.kind(), - std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock - ) => - { - *slot = None; - reused = false; - } - Err(error) => { - *slot = None; - return Err(error.into()); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A backend with `count` verifying connections, none opened. - fn unconnected(count: usize) -> SidecarBackend { - SidecarBackend { - config: SidecarConfig::new("/nonexistent"), - prove_connection: Mutex::new(None), - verify_connections: (0..count).map(|_| Mutex::new(None)).collect(), - next_verify: AtomicUsize::new(0), - } - } - - /// A verification takes a free connection rather than wait on a busy - /// one, so verifications run side by side. - #[test] - fn a_verification_takes_a_free_connection_past_busy_ones() { - let backend = unconnected(3); - let first = backend.verify_connection(); - let second = backend.verify_connection(); - let third = backend.verify_connection(); - // Three at once, none waiting: each took its own connection. - assert!( - backend - .verify_connections - .iter() - .all(|c| c.try_lock().is_err()) - ); - drop(second); - // With two busy, the next one finds the free one wherever the - // rotation starts. - let again = backend.verify_connection(); - assert!( - backend - .verify_connections - .iter() - .all(|c| c.try_lock().is_err()) - ); - drop((first, third, again)); - } - - #[test] - fn at_least_one_connection_verifies() { - let config = SidecarConfig { - verify_connections: 0, - ..SidecarConfig::new("/nonexistent") - }; - assert_eq!(config.verify_connections.max(1), 1); - assert_eq!( - SidecarConfig::new("/x").verify_connections, - DEFAULT_VERIFY_CONNECTIONS - ); - } - - fn statement( - pubkeys: &[[u8; PUBKEY_SIZE]], - leaf_index: u64, - message: Message, - ) -> AggregateStatement { - AggregateStatement { - pubkeys: pubkeys.to_vec(), - leaf_index, - message, - } - } - - #[test] - fn no_claims_encode_as_empty_lists() { - let expected = [0u8; 8 + 8 + 1]; - assert_eq!(statements_to_claims(&[]).to_bytes(), expected); - assert_eq!( - statements_to_claims(&[statement(&[], 1, [7; 32])]).to_bytes(), - expected - ); - } - - /// Lighthouse's `claims_bytes_match_the_sidecar_format`: out of order within - /// and across statements, one repeated claim, one key signing two - /// messages, and no leaf index on the wire. - #[test] - fn claims_are_sorted_deduplicated_pairs() { - let mut low_key = [3; 32]; - low_key[31] = 2; - let statements = [ - statement(&[[9; 32], [3; 32], low_key], 40_000, [0xaa; 32]), - statement(&[[3; 32], [1; 32]], 50_000, [0x11; 32]), - statement(&[[9; 32]], 60_000, [0xaa; 32]), - ]; - let mut expected = Vec::new(); - expected.extend_from_slice(&5u64.to_le_bytes()); - for (key, message) in [ - ([1; 32], [0x11; 32]), - (low_key, [0xaa; 32]), - ([3; 32], [0x11; 32]), - ([3; 32], [0xaa; 32]), - ([9; 32], [0xaa; 32]), - ] { - expected.extend_from_slice(&key); - expected.extend_from_slice(&message); - } - expected.extend_from_slice(&0u64.to_le_bytes()); - expected.push(0); - assert_eq!(statements_to_claims(&statements).to_bytes(), expected); - } -} diff --git a/crates/common/crypto/src/vrf.rs b/crates/common/crypto/src/vrf.rs index 9530a7335..feed42a8f 100644 --- a/crates/common/crypto/src/vrf.rs +++ b/crates/common/crypto/src/vrf.rs @@ -1,32 +1,37 @@ //! The Beacon Chain PQ fork's VRF tree (consensus-specs //! `specs/_features/pq/{beacon-chain,validator}.md`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`, the pq-devnet-0 spec). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! XMSS signatures are not unique, so a proposer could grind a signature-based -//! RANDAO reveal. A validator instead registers as its VRF root the root of a -//! Merkle tree of depth [`VRF_TREE_DEPTH`], hashed with Keccak-256, whose leaf -//! for a slot is `keccak256(vrf_seed || le64(slot))`. Its reveal is the leaf -//! followed by the leaf's branch (a `VRFProof`). +//! RANDAO reveal. A validator instead has a secret for each slot, derived from +//! its VRF seed, and registers as its VRF root the root of a Merkle tree of +//! depth [`VRF_TREE_DEPTH`], hashed with Keccak-256, whose leaf for a slot +//! commits to that slot's secret. Its reveal is the secret followed by the +//! leaf's branch (a `VRFProof`). The branch holds only commitments, so +//! proposing at one slot reveals no other slot's secret. //! -//! The verifying half ([`fold_vrf_branch`]) is the state transition's -//! `is_valid_vrf_proof`. The deriving half ([`compute_vrf_leaf`], -//! [`compute_vrf_node`], [`VrfTree`]) is the validator's. +//! The verifying half ([`compute_vrf_leaf`], [`fold_vrf_branch`]) is the +//! state transition's `is_valid_vrf_proof`. The deriving half +//! ([`compute_vrf_secret`], [`compute_vrf_node`], [`VrfTree`]) is the +//! validator's. //! //! # Cost //! -//! A leaf hashes its index with the seed, so no two leaves are equal and -//! nothing but hashing all `2^31` of them yields the root: about two -//! Keccak-256 calls a leaf, 4.3 billion a tree. [`VrfTree::build`] runs them -//! across cores and keeps the `2^15` nodes [`SUBTREE_DEPTH`] levels above the -//! leaves (1 MiB), from which a proof rebuilds one `2^16`-leaf subtree. -//! [`VrfTree::to_bytes`] and [`VrfTree::from_bytes`] carry those nodes, so a -//! tree is hashed once per seed, not once per start. ethereum-package -//! publishes each genesis validator's root and leaf 0's branch, from which -//! [`VrfTree::from_state_record`] proves without hashing the tree. - -use ethlambda_types::beacon::constants::VRF_TREE_DEPTH; +//! A leaf commits to its index as well as its secret, so no two leaves are +//! equal and nothing but hashing all `2^31` of them yields the root: three +//! Keccak-256 calls a leaf, about 6.4 billion a tree. [`VrfTree::build`] runs +//! them across cores and keeps the `2^15` nodes [`SUBTREE_DEPTH`] levels +//! above the leaves (1 MiB), from which a proof rebuilds one `2^16`-leaf +//! subtree. [`VrfTree::to_bytes`] and [`VrfTree::from_bytes`] carry those +//! nodes, so a tree is hashed once per seed, not once per start. On an Apple +//! M4 Max's 14 cores a tree takes about 100 seconds and a proof 30 ms. + +use ethlambda_types::beacon::constants::{VRF_LEAF_DOMAIN, VRF_TREE_DEPTH}; use rayon::prelude::*; +/// The specification's `VRF_SECRET_DOMAIN` (`validator.md`). +pub const VRF_SECRET_DOMAIN: &[u8] = b"VRF_SECRET"; + /// How many levels above the leaves the nodes a [`VrfTree`] keeps are: a /// proof rebuilds one subtree of this depth, about 200,000 hashes. const SUBTREE_DEPTH: usize = 16; @@ -36,7 +41,7 @@ const SUBTREE_DEPTH: usize = 16; /// [`VrfTree::from_state_record`]. pub const STATE_RECORD_SIZE: usize = 32 + 4 + 32 * VRF_TREE_DEPTH; -/// A node of the tree, or a seed. +/// A node of the tree, a secret, or a seed. pub type Node = [u8; 32]; /// Keccak-256's rate: the bytes one permutation absorbs. @@ -44,8 +49,8 @@ const KECCAK_RATE: usize = 136; /// The specification's `keccak256`, over the concatenation of `parts`. /// -/// Every input the tree hashes (a leaf's preimage, a pair of nodes) is at -/// most 64 bytes, under one block, so this pads it into a +/// Every input the tree hashes (a secret's preimage, a leaf's, a pair of +/// nodes) is at most 64 bytes, under one block, so this pads it into a /// single block and runs the permutation once rather than going through a /// streaming hasher, which the full tree's billions of calls notice. /// @@ -79,10 +84,16 @@ fn hash_pair(left: &Node, right: &Node) -> Node { keccak256(&[left, right]) } -/// `compute_vrf_leaf`: the leaf at `index` of the VRF tree derived from -/// `vrf_seed`, `keccak256(vrf_seed || uint_to_bytes(index))`. -pub fn compute_vrf_leaf(vrf_seed: &Node, index: u64) -> Node { - keccak256(&[vrf_seed, &index.to_le_bytes()]) +/// `compute_vrf_secret`: the secret for `index` of the VRF tree derived from +/// `vrf_seed`. +pub fn compute_vrf_secret(vrf_seed: &Node, index: u64) -> Node { + keccak256(&[VRF_SECRET_DOMAIN, vrf_seed, &index.to_le_bytes()]) +} + +/// `compute_vrf_leaf`: the leaf at `index` of a VRF tree, which commits to +/// `secret`. +pub fn compute_vrf_leaf(secret: &Node, index: u64) -> Node { + keccak256(&[VRF_LEAF_DOMAIN, secret, &index.to_le_bytes()]) } /// `compute_vrf_node`: the node at `index` among the nodes `height` levels @@ -104,7 +115,7 @@ pub fn compute_vrf_node(vrf_seed: &Node, height: usize, index: u64) -> Node { let mut finished: Vec = Vec::with_capacity(height + 1); for offset in 0..1u64 << height { let leaf_index = first_leaf + offset; - let mut node = compute_vrf_leaf(vrf_seed, leaf_index); + let mut node = compute_vrf_leaf(&compute_vrf_secret(vrf_seed, leaf_index), leaf_index); // Each trailing one bit of `offset` is a level whose left sibling is // already finished. for _ in 0..offset.trailing_ones() { @@ -116,16 +127,16 @@ pub fn compute_vrf_node(vrf_seed: &Node, height: usize, index: u64) -> Node { finished.pop().expect("the last leaf folds up to the node") } -/// The root a `VRFProof` folds to at `slot`: its revealed `leaf`, hashed up -/// through `branch` (siblings bottom-up) on the side each bit of `slot` -/// gives. `is_valid_vrf_proof` is this compared with the proposer's -/// registered VRF root. +/// The root a `VRFProof` folds to at `slot`: the leaf committing to `secret` +/// at index `slot`, hashed up through `branch` (siblings bottom-up) on the +/// side each bit of `slot` gives. `is_valid_vrf_proof` is this compared with +/// the proposer's registered VRF root. pub fn fold_vrf_branch<'a>( - leaf: &Node, + secret: &Node, branch: impl IntoIterator, slot: u64, ) -> Node { - let mut value = *leaf; + let mut value = compute_vrf_leaf(secret, slot); for (height, sibling) in branch.into_iter().enumerate() { value = if (slot >> height) & 1 == 1 { hash_pair(sibling, &value) @@ -220,7 +231,7 @@ impl VrfTree { actual: 32 * branch.len(), }); } - if fold_vrf_branch(&compute_vrf_leaf(&vrf_seed, 0), &branch, 0) != root { + if fold_vrf_branch(&compute_vrf_secret(&vrf_seed, 0), &branch, 0) != root { return Err(VrfTreeError::WrongSeed); } Ok(Self { @@ -303,9 +314,9 @@ impl VrfTree { } } - /// `compute_vrf_proof`: the leaf at index `slot`, then its branch, - /// siblings bottom-up. `None` for a slot past the tree's last leaf, which - /// no proof exists for. + /// `compute_vrf_proof`: the secret for `slot`, then the branch of the leaf + /// at index `slot`, siblings bottom-up. `None` for a slot past the tree's + /// last leaf, which no proof exists for. pub fn proof(&self, slot: u64) -> Option> { if slot >> self.depth != 0 { return None; @@ -314,9 +325,9 @@ impl VrfTree { let subtree = slot >> subtree_depth; let first_leaf = subtree << subtree_depth; let mut proof = Vec::with_capacity(self.depth + 1); - proof.push(compute_vrf_leaf(&self.seed, slot)); + proof.push(compute_vrf_secret(&self.seed, slot)); let mut nodes: Vec = (first_leaf..first_leaf + (1 << subtree_depth)) - .map(|index| compute_vrf_leaf(&self.seed, index)) + .map(|index| compute_vrf_leaf(&compute_vrf_secret(&self.seed, index), index)) .collect(); reduce(&mut nodes, (slot - first_leaf) as usize, &mut proof); match &self.kept { @@ -343,7 +354,8 @@ impl VrfTree { /// What the tree keeps, then its root: everything [`Self::from_bytes`] /// needs beside the seed. A tree hashed in full keeps its nodes /// [`SUBTREE_DEPTH`] levels up (1 MiB), one restored from a compact - /// state keeps leaf 0's branch (1 KiB). + /// state keeps leaf 0's branch (1 KiB). They are commitments, so the + /// bytes reveal no secret. pub fn to_bytes(&self) -> Vec { let mut bytes = match &self.kept { Kept::Subtrees(subtree_roots) => subtree_roots.concat(), @@ -412,6 +424,26 @@ fn reduce(nodes: &mut Vec, mut index: usize, branch: &mut Vec) { mod tests { use super::*; + /// The single-block permutation here and the streaming hasher behind + /// [`crate::keccak256`] agree, and both are Keccak-256 (the empty input's + /// digest), not SHA3-256. + #[test] + fn keccak256_is_keccak_and_agrees_with_the_streaming_hasher() { + assert_eq!( + hex::encode(keccak256(&[])), + "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" + ); + for len in [0usize, 1, 49, 64, 135] { + let input: Vec = (0..len as u8).collect(); + assert_eq!( + keccak256(&[&input]), + crate::keccak256(&input), + "{len} bytes" + ); + } + } + use sha2::Digest as _; + fn hex32(text: &str) -> Node { hex::decode(text).unwrap().try_into().unwrap() } @@ -424,7 +456,7 @@ mod tests { /// The specification's `compute_vrf_node`, as it is written. fn recursive_node(vrf_seed: &Node, height: usize, index: u64) -> Node { if height == 0 { - return compute_vrf_leaf(vrf_seed, index); + return compute_vrf_leaf(&compute_vrf_secret(vrf_seed, index), index); } let left = recursive_node(vrf_seed, height - 1, 2 * index); let right = recursive_node(vrf_seed, height - 1, 2 * index + 1); @@ -473,7 +505,7 @@ mod tests { } #[test] - fn a_proof_reveals_its_slots_leaf_and_folds_to_the_root() { + fn a_proof_reveals_its_slots_secret_and_folds_to_the_root() { let seed = seed(); let depth = SUBTREE_DEPTH + 2; let tree = VrfTree::with_depth(seed, depth); @@ -482,90 +514,88 @@ mod tests { for slot in [0, 1, 5, (1 << SUBTREE_DEPTH) - 1, 1 << SUBTREE_DEPTH, last] { let proof = tree.proof(slot).unwrap(); assert_eq!(proof.len(), depth + 1); - assert_eq!(proof[0], compute_vrf_leaf(&seed, slot), "slot {slot}"); + assert_eq!(proof[0], compute_vrf_secret(&seed, slot), "slot {slot}"); assert_eq!( fold_vrf_branch(&proof[0], &proof[1..], slot), root, "slot {slot}" ); - // The branch opens this leaf only: not at the neighbouring index, - // and not another leaf at this one. + // The leaf commits to its index: the same secret and branch do not + // open the neighbouring leaf, nor does another secret this one. assert_ne!(fold_vrf_branch(&proof[0], &proof[1..], slot ^ 1), root); assert_ne!(fold_vrf_branch(&[1; 32], &proof[1..], slot), root); } assert!(tree.proof(last + 1).is_none()); } - /// Validator 0 of ethereum-package's default mnemonic: its VRF root and - /// leaf 0's branch as the package publishes them - /// (`static_files/xmss-keys/b9dec4e1daa17dfe.vrf`, record 0, from - /// eth-beacon-genesis, an independent implementation), and the VRF seed - /// its signing key derives. - const PUBLISHED_ROOT: &str = "2c8d6a710d3a22803be6490fef9c9247e30ac68793bffb7cbc151d17f8313cb0"; - const PUBLISHED_BRANCH: [&str; VRF_TREE_DEPTH] = [ - "3b553e1e307ad6190a1c81579244b4cc5ef3689bb306e406c286df6f149f3385", - "bdff49fdadccf691e8463ad83c9144bb1f1dd3be2cc65d61cb65194a11d44778", - "b3188264c7dbdfc2097fef24d373f8f0fdde3700f1c7dda868d4d1dfff3ea735", - "bc747d9befb30d217afb5ef24b2130b3939a18cbb12e8ff9cad8ea43d666f328", - "2826365c053905094470eb39f801babe15bb56dfede5d3d89c60f94bec94c6cc", - "b054a7ce37d45e7dc9574b25815b33ef9d5d02dfba2c5867c15c6ce6ce4f87e0", - "8d48edeef8615159f8e9a5c3ff7d59dc13063cb5a246dec9caf01573514257d9", - "410a426beda2a00182b63294eac078460157987ce4f7c8d16008d6a82970b278", - "c01def0ca03beffc51029b7e13f50e39169df10c82f7130d5f7b9c5e8f876d28", - "5a29cca22a1043e0724dc105e1204f0c2f1956e4d634b7fda4f124f0f3dbe7ae", - "cd69bff80485b514887c3282ba6e7411e745928f4d253a12b1cc6b658b362a87", - "f79eb3ba9c7015ff12e965a793f36930aa667af852669424018c1e652742ec76", - "7b577ddefc00fab0447df555c5d59f76e4e49656fb0f6e565969cccae4ce7dcc", - "a82515f2a8c036495e924da314d087473d1d7d4acc6a97ec767bcf16e97292f2", - "36d25a6b0464f79c531d9338e6645fb0559816f66aa3ea7616c5194cc0da924a", - "438ab193ca00bdf0e5b75855f94bb32e778fbffe85d370284b878b8835968dd6", - "1305124c8db86859bcf9110c72a2231bce1bc2bf44443032775d90d1e76b3667", - "ece380acfc342142a937a48d3ea84e3397421f3db74a9122bcea245a4fceb43e", - "a8e932e0dd6ec363635fdb0b30ea60d24cc1a861904c879e236c0e77f9efa562", - "123e8cef55f55b0dd4f3d0758fd52aa270c53d3f230393112a404216fc10743f", - "760a6fcab9db4b616b94ad3882dea4d434a849f6d1a03fa507c648d904ec641d", - "32a9196616c33e77daecac4d5fbafd131b0968899e1a440cb4f05d868a0deb7f", - "0a9cf6b998c2736cc5c5a137b335261b1ee68671345b1c9a17f208026f4146a5", - "cb310e30dc647396390e107f0ec081689d9b84c965b340b7d6949b4be00fe461", - "fc097343ba9eed74f88793de989d6f250eb852eacb7d70a76f65ffbbbde906ee", - "1d7fd2ea64087c2a054a78558ed0e578047c06c2fa033dd0cbc3c2a33b88b06e", - "44d7360b2aacc44b9c969859104c1ecfa4d8da6c410fab927969d28bf6335e38", - "d8af842dfc83814f0291c4ad67ce2b74e83cefbddf870d1a7352793d027abc6f", - "6de1e6d637d9a2965eff8b036c0a8c37dcdd85f95f4327a87821b1c10f1eefeb", - "1b4c477849c185cb826bd541d5a31d83cc5d603b8d5b5d137de2babe4535705d", - "d1ed2b30f968fa3b5daac6544cf01bb549ad0c70b50a2f56057e89dbbf4e7d72", - ]; - - fn published_seed() -> Node { - crate::pq_keys::vrf_seed(&hex32( - "0dce41fa73ae9f6bdfd51df4d422d75eee174553dba5fd450c4437e4ed3fc903", - )) + /// A proof's branch holds commitments only: no node of it is a secret of + /// the tree, in particular not the neighbouring slot's, which the leaf + /// sibling was before leaves committed to secrets. + #[test] + fn a_proof_reveals_no_other_secret() { + let seed = seed(); + let tree = VrfTree::with_depth(seed, 4); + let proof = tree.proof(6).unwrap(); + let secrets: Vec = (0..16) + .map(|index| compute_vrf_secret(&seed, index)) + .collect(); + assert!(proof[1..].iter().all(|node| !secrets.contains(node))); + assert_eq!(proof[1], compute_vrf_leaf(&secrets[7], 7)); } - /// The leaf rule, the little-endian index and the fold's order, against - /// what ethPandaOps' genesis tooling registered: the branch's lower - /// levels are this seed's nodes, and leaf 0 folds through the whole - /// branch to the published root, so the published state restores. + /// Known answers from a transcription of the specification's functions + /// over an independent Keccak-256, for the seed `00 01 .. 1f`: the domain + /// tags, the little-endian index and the order of every concatenation. #[test] - fn matches_ethereum_packages_published_state() { - let seed = published_seed(); - let branch: Vec = PUBLISHED_BRANCH.iter().map(|node| hex32(node)).collect(); - for (height, sibling) in branch.iter().enumerate().take(11) { - assert_eq!( - compute_vrf_node(&seed, height, 1), - *sibling, - "height {height}" - ); - } - let root = hex32(PUBLISHED_ROOT); + fn known_answers() { + let seed = seed(); + let secret = compute_vrf_secret(&seed, 0); assert_eq!( - fold_vrf_branch(&compute_vrf_leaf(&seed, 0), &branch, 0), - root + secret, + hex32("568e22331e25e613a84a6a86df3f442e2f7f994ccce0b746088fb737c2bc0e20") ); - let tree = VrfTree::from_compact_state(seed, root, branch).unwrap(); - let proof = tree.proof(9).unwrap(); - assert_eq!(proof[0], compute_vrf_leaf(&seed, 9)); - assert_eq!(fold_vrf_branch(&proof[0], &proof[1..], 9), root); + assert_eq!( + compute_vrf_secret(&seed, (1 << 31) - 1), + hex32("7d65715bc75677b7ae70b0e3a287a883b6424dbdc7fe12476e14a2a28e5f4a72") + ); + assert_eq!( + compute_vrf_leaf(&secret, 0), + hex32("7858a2fe40f519a1db8508fba150a5d89a2f8e6e5c784eb6b5c36728a4364af2") + ); + assert_eq!( + compute_vrf_node(&seed, 4, 5), + hex32("e216d7728aa69ed5ff228641a373039fb56c1bdda676edf8e012443af726e8c6") + ); + assert_eq!( + compute_vrf_node(&seed, 3, (1 << 28) - 1), + hex32("c70649c366c4690b4d9977254f45cef88aa2cb4f0b0a0b08e8d42a6f95a5020e") + ); + + // A depth-10 tree's proofs are the first eleven nodes of the full + // tree's `compute_vrf_proof`. SHA-256 fingerprints their bytes. + let tree = VrfTree::with_depth(seed, 10); + assert_eq!( + tree.root(), + hex32("e2fd22f54650f9bb431288d5632b94b406024a411db4fef773eacec0fae253bb") + ); + for (slot, fingerprint) in [ + ( + 0, + "53b437b21a44e9def0f0a202bf515f0182f652a758a0446318262d9d612687db", + ), + ( + 5, + "f22b4ec50f24ae2754eddd04eefd08e52d63b1c13aa863f6b9c4df064afaf9f8", + ), + ( + 1023, + "dc21b0ac18f3119cc77117d501050a2c4fa90299aa285bb5e9cd8b90bd575d07", + ), + ] { + let proof = tree.proof(slot).unwrap().concat(); + let digest: Node = sha2::Sha256::digest(proof).into(); + assert_eq!(digest, hex32(fingerprint), "slot {slot}"); + } } #[test] @@ -665,7 +695,7 @@ mod tests { let seed = seed(); let mut branch = VrfTree::with_depth(seed, SUBTREE_DEPTH).compact_state().1; branch.extend((SUBTREE_DEPTH..VRF_TREE_DEPTH).map(|height| [height as u8; 32])); - let root = fold_vrf_branch(&compute_vrf_leaf(&seed, 0), &branch, 0); + let root = fold_vrf_branch(&compute_vrf_secret(&seed, 0), &branch, 0); let tree = VrfTree::from_compact_state(seed, root, branch).unwrap(); let record = tree.to_state_record(); diff --git a/crates/common/types/src/beacon/config.rs b/crates/common/types/src/beacon/config.rs index cdbe94253..4d053ba82 100644 --- a/crates/common/types/src/beacon/config.rs +++ b/crates/common/types/src/beacon/config.rs @@ -16,9 +16,8 @@ //! schedule) stay out for the same reason `GLOAS_*` used to: a fork version //! stored here would give [`Config::fork_at_epoch`] a fork //! [`crate::beacon::fork::ForkName`] has no variant for, so each is -//! reported as an unknown key instead. `GAS_LIMIT_SCHEDULE` (gloas-era) -//! stays out too, since it is a list rather than a scalar. The rest are -//! heze-era data keys, not gloas's, with no reader in this build at all: +//! reported as an unknown key instead. The rest are heze-era data keys, not +//! gloas's, with no reader in this build at all: //! `INCLUSION_LIST_DUE_BPS`, `MAX_REQUEST_INCLUSION_LIST`, //! `MIN_SLOTS_FOR_INCLUSION_LISTS_REQUESTS`, and //! `MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST` (EIP-7805's fork-choice-enforced @@ -31,6 +30,11 @@ //! value it reports from the one `Config` the store holds, rather than having //! the name threaded to it separately from startup. //! +//! `GAS_LIMIT_SCHEDULE` (gloas, EIP-8261) is a field for the same reason, but +//! one stored in a `Metadata` row of its own rather than in this struct's +//! encoding: see [`GasLimitSchedule`]. It is advisory, a validator client's +//! default gas limit, so nothing a node checks depends on it. +//! //! Networking values and the deposit contract identity used to be left out too, //! on the grounds that the state transition never reads them. They are here now //! because they have a second reader: `/eth/v1/config/spec` must echo every key @@ -52,7 +56,7 @@ use libssz_types::SszList; use crate::beacon::constants; use crate::beacon::fork::ForkName; use crate::beacon::lean_fork_unreachable; -use crate::beacon::preset::Preset; +use crate::beacon::preset::{self, Preset}; use crate::beacon::primitives::{Epoch, ExecutionBlockHash, Gwei, U256, Uint256, Version}; use crate::chain_config::ChainConfig; use crate::constants::INTERVALS_PER_SLOT; @@ -84,6 +88,235 @@ pub struct BlobScheduleEntry { /// version. pub const MAX_BLOB_SCHEDULE_ENTRIES: usize = 32; +/// How many gas-limit-schedule entries a [`GasLimitSchedule`] can carry. +/// +/// A storage bound, not a consensus one, like [`MAX_BLOB_SCHEDULE_ENTRIES`]: +/// the schedule's own row is a bounded SSZ list. A beacon node refuses a +/// config file naming more ([`GasLimitSchedule::check`]); a validator client, +/// which stores nothing, takes any length. +pub const MAX_GAS_LIMIT_SCHEDULE_ENTRIES: usize = 32; + +/// One entry in gloas's gas limit schedule (EIP-8261): from `epoch` onward, +/// until a later entry takes over, `gas_limit` is the network's default and +/// recommended maximum gas limit. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, SszEncode, SszDecode, serde::Deserialize, serde::Serialize, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub struct GasLimitScheduleEntry { + /// The first epoch this entry applies to. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub epoch: Epoch, + /// The gas limit from `epoch` onward. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub gas_limit: u64, +} + +/// `GAS_LIMIT_SCHEDULE`: the gas limit a validator targets by default, per +/// epoch (EIP-8261). Possibly empty. +/// +/// Advisory: the specification says it introduces no validity rules, so no +/// block, bid or preference is judged against it. Its reader is a validator +/// client, which targets [`Self::gas_limit_at`] its proposal's epoch when its +/// operator named no gas limit. +/// +/// Held ascending by epoch, whatever order the file lists it in: the +/// specification recommends that order, and `/eth/v1/config/spec` reports it +/// in it. +/// +/// A beacon node holds at most [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] entries, +/// since [`Self::check`] refuses more, so its schedule always fits the stored +/// row. Deserializing takes any length: a validator client reading a node's +/// schedule stores nothing. +/// +/// # Stored in a row of its own +/// +/// [`Config`] is persisted SSZ-encoded under `Metadata["config"]`, a positional +/// container: a new field there would leave every row written before it +/// undecodable, which is a `DB_VERSION` bump with no migration. So this field +/// takes zero bytes in that encoding (this type's `SszEncode`/`SszDecode` write +/// and read nothing, keeping the row byte for byte what it was), and the +/// storage crate keeps the schedule in a `Metadata` row of its own instead, +/// encoded by [`Self::to_row_ssz`]. A directory written before that row existed +/// simply has none: a beacon resume reports the key as missing and adds the +/// config file's, rather than failing. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +#[serde( + from = "Vec", + into = "Vec" +)] +pub struct GasLimitSchedule(Vec); + +/// The schedule's stored row: an SSZ list, ascending by epoch. +type GasLimitScheduleRow = SszList; + +impl GasLimitSchedule { + /// The entries, ascending by epoch. + pub fn entries(&self) -> &[GasLimitScheduleEntry] { + &self.0 + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The gas limit scheduled for `epoch`: that of the latest entry at or + /// before it, or `None` when every entry is later (or there is none). + /// + /// This is gloas's `get_scheduled_gas_limit`. + pub fn gas_limit_at(&self, epoch: Epoch) -> Option { + self.0 + .iter() + .rev() + .find(|entry| entry.epoch <= epoch) + .map(|entry| entry.gas_limit) + } + + /// Whether a beacon node can run on this schedule: it holds at most + /// [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] entries, which is what its stored + /// row can hold, and it keeps [`Self::check_rules`]. + pub fn check(&self, gloas_fork_epoch: Epoch) -> Result<(), GasLimitScheduleError> { + if self.0.len() > MAX_GAS_LIMIT_SCHEDULE_ENTRIES { + return Err(GasLimitScheduleError::TooManyEntries { + entries: self.0.len(), + }); + } + self.check_rules(gloas_fork_epoch) + } + + /// Whether the schedule keeps the specification's two rules (no two + /// entries share an epoch, and none is before `gloas_fork_epoch`), and + /// names no zero gas limit, which no validator could target (`--gas-limit` + /// and the keymanager refuse one too). + /// + /// Without [`Self::check`]'s bound on the entries: a validator client + /// reading a node's schedule stores none of it, and checks it with this. + pub fn check_rules(&self, gloas_fork_epoch: Epoch) -> Result<(), GasLimitScheduleError> { + if let Some(entry) = self.0.iter().find(|entry| entry.epoch < gloas_fork_epoch) { + return Err(GasLimitScheduleError::BeforeGloas { + epoch: entry.epoch, + gloas_fork_epoch, + }); + } + if let Some(pair) = self + .0 + .windows(2) + .find(|pair| pair[0].epoch == pair[1].epoch) + { + return Err(GasLimitScheduleError::DuplicateEpoch { + epoch: pair[0].epoch, + }); + } + if let Some(entry) = self.0.iter().find(|entry| entry.gas_limit == 0) { + return Err(GasLimitScheduleError::ZeroGasLimit { epoch: entry.epoch }); + } + Ok(()) + } + + /// The schedule as its own `Metadata` row stores it: an SSZ + /// `List[GasLimitScheduleEntry, MAX_GAS_LIMIT_SCHEDULE_ENTRIES]`. + /// + /// # Panics + /// + /// If the schedule holds more than [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`] + /// entries. A beacon node's config file is refused before that + /// ([`Self::check`]), so only a schedule built in code can. + pub fn to_row_ssz(&self) -> Vec { + let row = GasLimitScheduleRow::try_from(self.0.clone()).unwrap_or_else(|_| { + panic!( + "a gas limit schedule of {} entries is over the {MAX_GAS_LIMIT_SCHEDULE_ENTRIES} \ + its row can hold", + self.0.len() + ) + }); + libssz::SszEncode::to_ssz(&row) + } + + /// Decode the schedule's own `Metadata` row ([`Self::to_row_ssz`]). + pub fn from_row_ssz(bytes: &[u8]) -> Result { + let row = ::from_ssz_bytes(bytes)?; + Ok(Self::from(row.to_vec())) + } +} + +/// Sorted on the way in, stably, so entries the file lists out of order are +/// held in epoch order and two sharing an epoch keep the file's order. +impl From> for GasLimitSchedule { + fn from(mut entries: Vec) -> Self { + entries.sort_by_key(|entry| entry.epoch); + Self(entries) + } +} + +impl From for Vec { + fn from(schedule: GasLimitSchedule) -> Self { + schedule.0 + } +} + +/// A `GAS_LIMIT_SCHEDULE` a beacon node refuses: one too long for it to store, +/// or one that breaks the specification's rules. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum GasLimitScheduleError { + #[error( + "{entries} entries, more than the {MAX_GAS_LIMIT_SCHEDULE_ENTRIES} this node can store" + )] + TooManyEntries { entries: usize }, + #[error( + "an entry at epoch {epoch} is before GLOAS_FORK_EPOCH ({gloas_fork_epoch}), \ + which the schedule must not start before" + )] + BeforeGloas { + epoch: Epoch, + gloas_fork_epoch: Epoch, + }, + #[error("two entries share epoch {epoch}")] + DuplicateEpoch { epoch: Epoch }, + #[error("the entry at epoch {epoch} names a gas limit of zero")] + ZeroGasLimit { epoch: Epoch }, +} + +/// Zero bytes inside [`Config`]'s encoding: see "Stored in a row of its own" +/// on [`GasLimitSchedule`]. The row itself is [`GasLimitSchedule::to_row_ssz`]. +impl libssz::SszEncode for GasLimitSchedule { + fn is_fixed_size() -> bool { + true + } + + fn fixed_size() -> usize { + 0 + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn ssz_append(&self, _buf: &mut Vec) {} +} + +/// Zero bytes inside [`Config`]'s encoding, decoded as the empty schedule, +/// which the storage crate then fills from the schedule's own row: see +/// "Stored in a row of its own" on [`GasLimitSchedule`]. +impl libssz::SszDecode for GasLimitSchedule { + fn is_fixed_size() -> bool { + true + } + + fn fixed_size() -> usize { + 0 + } + + fn from_ssz_bytes(bytes: &[u8]) -> Result { + if !bytes.is_empty() { + return Err(libssz::DecodeError::InvalidFixedLength { + expected: 0, + got: bytes.len(), + }); + } + Ok(Self::default()) + } +} + /// How many bytes a [`ConfigName`] can hold. /// /// A storage bound, not a consensus one, for the same reason as @@ -434,6 +667,25 @@ pub struct Config { /// `compute_validators`). #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub unregistered_validator_withdrawability_delay: Epoch, + /// PQ: basis points of [`Self::slot_duration_ms`] by which the first + /// aggregator of an aggregation committee stops collecting attestations + /// and starts proving its aggregate; each later one stops + /// [`Self::aggregator_delay_bps`] after the one before it + /// (`get_aggregation_cutoff_ms`). + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregation_cutoff_bps: u64, + /// PQ: [`Self::aggregate_due_bps_gloas`]'s replacement, the basis points + /// by which the first aggregator of an aggregation committee broadcasts + /// its aggregate; later than gloas's, to leave time to prove one + /// (`get_aggregate_due_ms` modified in PQ). + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregate_due_bps_pq: u64, + /// PQ: basis points of [`Self::slot_duration_ms`] between the cutoffs, + /// and between the broadcasts, of two aggregators next to each other in + /// an aggregation committee. Staggering them lets a later aggregator + /// skip an aggregate an earlier one already covered. + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub aggregator_delay_bps: u64, // -- Validator cycle ----------------------------------------------------- /// Score points added to a validator's inactivity score for each epoch it @@ -489,6 +741,20 @@ pub struct Config { /// builder-registry value; see [`Self::churn_limit_quotient_gloas`]. #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub max_per_epoch_activation_churn_limit_gloas: Gwei, + /// PQ (consensus-specs pq `af898d07`): the most committees a PQ slot has, + /// `MAX_COMMITTEES_PER_SLOT_PQ` replaced in `get_committee_count_per_slot`. + /// Temporary and testing-only: a devnet lowers it to put its validators + /// into fewer, larger committees. It may not exceed the preset's + /// `MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`; the + /// state transition reads it through + /// [`x_max_committee_count_per_slot`], which the node sets from this. + /// + /// Like every key, absent from a file it parses as mainnet's value. For + /// this one that is wrong on a minimal network, so the node replaces an + /// absent key with its preset's `MAX_COMMITTEES_PER_SLOT_PQ` once the + /// preset is selected (`network::select_committee_cap` in the binary). + #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] + pub x_max_committee_count_per_slot: u64, // -- Fork choice --------------------------------------------------------- /// Percentage boost, relative to a single committee's weight, given to a @@ -650,6 +916,72 @@ pub struct Config { pub max_request_data_column_sidecars: u64, #[serde(with = "crate::beacon::serde_helpers::quoted_or_bare")] pub min_epochs_for_block_requests: u64, + + // -- Stored in rows of their own ---------------------------------------- + // Every key added after `DB_VERSION` 10 goes here: it takes zero bytes in + // `Metadata["config"]`, and the storage crate keeps it in a `Metadata` row + // of its own, so a directory that predates the key loads, and a resume + // adds the config file's value instead of failing. + /// Gloas (EIP-8261): the gas limit schedule, a validator client's default + /// gas limit per epoch. Empty when the file omits it, as mainnet's does. + /// See [`GasLimitSchedule`]. + pub gas_limit_schedule: GasLimitSchedule, +} + +/// The PQ committee cap this process runs on, `0` until +/// [`select_x_max_committee_count_per_slot`] sets one. +static X_MAX_COMMITTEE_COUNT_PER_SLOT: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + +/// An `X_MAX_COMMITTEE_COUNT_PER_SLOT` above the preset's +/// `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification says it must not +/// exceed: `CommitteeBits` has that many bits, so a slot with more committees +/// could not name them all in an attestation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error( + "X_MAX_COMMITTEE_COUNT_PER_SLOT is {declared}, above MAX_COMMITTEES_PER_SLOT_PQ ({max}), \ + the most committees an attestation's committee bits can name" +)] +pub struct CommitteeCapTooLarge { + pub declared: u64, + pub max: u64, +} + +/// Makes `config`'s `X_MAX_COMMITTEE_COUNT_PER_SLOT` the cap every PQ +/// committee count of this process uses, and returns it. +/// +/// One per process, like the preset (see `beacon::preset`), and selected +/// after it: the state transition counts committees from a state alone, which +/// carries no config. Refuses a value above the active preset's +/// `MAX_COMMITTEES_PER_SLOT_PQ` and stores nothing then. +pub fn select_x_max_committee_count_per_slot(config: &Config) -> Result { + let cap = committee_cap( + config.x_max_committee_count_per_slot, + preset::max_committees_per_slot_pq() as u64, + )?; + X_MAX_COMMITTEE_COUNT_PER_SLOT.store(cap, std::sync::atomic::Ordering::Relaxed); + Ok(cap) +} + +/// The cap a `declared` `X_MAX_COMMITTEE_COUNT_PER_SLOT` gives under a preset +/// of `max` committees per slot. A zero is one: `get_committee_count_per_slot` +/// never goes below one committee, whatever the cap. +fn committee_cap(declared: u64, max: u64) -> Result { + if declared > max { + return Err(CommitteeCapTooLarge { declared, max }); + } + Ok(declared.max(1)) +} + +/// `X_MAX_COMMITTEE_COUNT_PER_SLOT` as selected for this process, or the +/// preset's `MAX_COMMITTEES_PER_SLOT_PQ` when none was: the specification's +/// own configs set the two equal, so a process that never selects one (a +/// spec test, a lean node) runs on the specification's value. +pub fn x_max_committee_count_per_slot() -> u64 { + match X_MAX_COMMITTEE_COUNT_PER_SLOT.load(std::sync::atomic::Ordering::Relaxed) { + 0 => preset::max_committees_per_slot_pq() as u64, + cap => cap, + } } /// Mainnet's values, which is what an absent key in a `config.yaml` falls back @@ -774,6 +1106,9 @@ impl Config { payload_attestation_due_bps: 7_500, min_builder_withdrawability_delay: 64, unregistered_validator_withdrawability_delay: 16_384, + aggregation_cutoff_bps: 4_000, + aggregate_due_bps_pq: 6_000, + aggregator_delay_bps: 500, inactivity_score_bias: 4, inactivity_score_recovery_rate: 16, @@ -785,6 +1120,7 @@ impl Config { max_per_epoch_activation_exit_churn_limit: 256_000_000_000, churn_limit_quotient_gloas: 32_768, max_per_epoch_activation_churn_limit_gloas: 256_000_000_000, + x_max_committee_count_per_slot: 16, proposer_score_boost: 40, reorg_head_weight_threshold: 20, @@ -853,6 +1189,8 @@ impl Config { max_request_blob_sidecars_electra: 1_152, max_request_data_column_sidecars: 16_384, min_epochs_for_block_requests: 33_024, + + gas_limit_schedule: GasLimitSchedule::default(), } } @@ -914,6 +1252,9 @@ impl Config { payload_attestation_due_bps: 7_500, min_builder_withdrawability_delay: 2, unregistered_validator_withdrawability_delay: 16_384, + aggregation_cutoff_bps: 4_000, + aggregate_due_bps_pq: 6_000, + aggregator_delay_bps: 500, inactivity_score_bias: 4, inactivity_score_recovery_rate: 16, @@ -925,6 +1266,7 @@ impl Config { max_per_epoch_activation_exit_churn_limit: 128_000_000_000, churn_limit_quotient_gloas: 16, max_per_epoch_activation_churn_limit_gloas: 128_000_000_000, + x_max_committee_count_per_slot: 4, proposer_score_boost: 40, reorg_head_weight_threshold: 20, @@ -983,6 +1325,8 @@ impl Config { max_request_blob_sidecars_electra: 1_152, max_request_data_column_sidecars: 16_384, min_epochs_for_block_requests: 33_024, + + gas_limit_schedule: GasLimitSchedule::default(), } } @@ -1304,6 +1648,61 @@ mod tests { assert_eq!(config.max_request_payloads, 128); } + #[test] + fn the_pq_committee_cap_is_claimed_and_parses() { + assert_eq!(Config::mainnet().x_max_committee_count_per_slot, 16); + assert_eq!(Config::minimal().x_max_committee_count_per_slot, 4); + let config: Config = + serde_yaml_ng::from_str("X_MAX_COMMITTEE_COUNT_PER_SLOT: 1\n").unwrap(); + assert_eq!(config.x_max_committee_count_per_slot, 1); + // Absent, it parses as mainnet's, like every other key a file omits; + // the node then replaces it with its preset's value. + let config: Config = serde_yaml_ng::from_str("CONFIG_NAME: x\n").unwrap(); + assert_eq!(config.x_max_committee_count_per_slot, 16); + } + + #[test] + fn the_pq_committee_cap_may_not_exceed_committee_bits() { + assert_eq!(committee_cap(1, 16), Ok(1)); + assert_eq!(committee_cap(4, 16), Ok(4)); + assert_eq!(committee_cap(16, 16), Ok(16)); + // Mainnet's value on a minimal preset, and anything else above it. + let too_large = CommitteeCapTooLarge { + declared: 16, + max: 4, + }; + assert_eq!(committee_cap(16, 4), Err(too_large)); + assert!(too_large.to_string().contains("is 16, above")); + // `max(1, min(cap, ..))` in the specification: a zero cap is one + // committee, not none. + assert_eq!(committee_cap(0, 16), Ok(1)); + } + + #[test] + fn pq_timing_keys_are_claimed_and_parse() { + let yaml = "UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY: 8\n\ + AGGREGATION_CUTOFF_BPS: 3500\nAGGREGATE_DUE_BPS_PQ: 5500\n\ + AGGREGATOR_DELAY_BPS: 250\n"; + let config: Config = serde_yaml_ng::from_str(yaml).unwrap(); + assert_eq!(config.unregistered_validator_withdrawability_delay, 8); + assert_eq!(config.aggregation_cutoff_bps, 3_500); + assert_eq!(config.aggregate_due_bps_pq, 5_500); + assert_eq!(config.aggregator_delay_bps, 250); + } + + /// consensus-specs' `test_config_invariants` for PQ: an aggregator stops + /// collecting before it broadcasts, and the last aggregator of a full + /// aggregation committee still broadcasts within the slot. + #[test] + fn pq_aggregation_timing_fits_the_slot() { + for config in [Config::mainnet(), Config::minimal()] { + assert!(config.aggregation_cutoff_bps < config.aggregate_due_bps_pq); + let last_delay = + (constants::AGGREGATORS_PER_COMMITTEE - 1) * config.aggregator_delay_bps; + assert!(config.aggregate_due_bps_pq + last_delay <= constants::BASIS_POINTS); + } + } + #[test] fn max_blobs_per_block_selects_the_active_schedule_entry() { let config = Config::mainnet(); @@ -1678,6 +2077,214 @@ mod tests { assert!(json.get("GENESIS_TIME").is_none()); } + fn gas_limit_entry(epoch: Epoch, gas_limit: u64) -> GasLimitScheduleEntry { + GasLimitScheduleEntry { epoch, gas_limit } + } + + #[test] + fn the_gas_limit_schedule_parses_and_is_looked_up_by_epoch() { + // Listed out of order and with bare and quoted integers, both of + // which a `config.yaml` may carry. + let yaml = concat!( + "GAS_LIMIT_SCHEDULE:\n", + " - EPOCH: 200\n", + " GAS_LIMIT: 150000000\n", + " - EPOCH: '100'\n", + " GAS_LIMIT: '100000000'\n", + " - EPOCH: 300\n", + " GAS_LIMIT: 200000000\n", + ); + let config: Config = serde_yaml_ng::from_str(yaml).unwrap(); + let schedule = &config.gas_limit_schedule; + assert_eq!( + schedule.entries(), + [ + gas_limit_entry(100, 100_000_000), + gas_limit_entry(200, 150_000_000), + gas_limit_entry(300, 200_000_000), + ], + "held ascending by epoch" + ); + + // Before the first entry nothing is scheduled. + assert_eq!(schedule.gas_limit_at(0), None); + assert_eq!(schedule.gas_limit_at(99), None); + // Each entry from its own epoch until the next one's. + assert_eq!(schedule.gas_limit_at(100), Some(100_000_000)); + assert_eq!(schedule.gas_limit_at(199), Some(100_000_000)); + assert_eq!(schedule.gas_limit_at(200), Some(150_000_000)); + assert_eq!(schedule.gas_limit_at(299), Some(150_000_000)); + assert_eq!(schedule.gas_limit_at(300), Some(200_000_000)); + assert_eq!(schedule.gas_limit_at(Epoch::MAX), Some(200_000_000)); + } + + #[test] + fn an_absent_or_empty_gas_limit_schedule_schedules_nothing() { + let absent: Config = serde_yaml_ng::from_str("SECONDS_PER_SLOT: 12").unwrap(); + assert!(absent.gas_limit_schedule.is_empty()); + assert_eq!(absent.gas_limit_schedule.gas_limit_at(Epoch::MAX), None); + + let empty: Config = serde_yaml_ng::from_str("GAS_LIMIT_SCHEDULE: []").unwrap(); + assert!(empty.gas_limit_schedule.is_empty()); + assert!(Config::mainnet().gas_limit_schedule.is_empty()); + } + + #[test] + fn the_built_in_networks_schedules_parse_from_their_files() { + let sepolia: Config = serde_yaml_ng::from_str(include_str!( + "../../../../../bin/ethlambda/assets/sepolia/config.yaml" + )) + .unwrap(); + assert_eq!( + sepolia.gas_limit_schedule.entries(), + [gas_limit_entry(353_024, 200_000_000)] + ); + assert_eq!(sepolia.gas_limit_schedule.gas_limit_at(353_023), None); + assert_eq!( + sepolia.gas_limit_schedule.gas_limit_at(353_024), + Some(200_000_000) + ); + + let plataberget: Config = serde_yaml_ng::from_str(include_str!( + "../../../../../bin/ethlambda/assets/plataberget/config.yaml" + )) + .unwrap(); + assert_eq!( + plataberget.gas_limit_schedule.entries(), + [gas_limit_entry(1_566, 200_000_000)] + ); + // Platåberget's gloas starts at 1536, before its schedule does. + assert_eq!(plataberget.gas_limit_schedule.gas_limit_at(1_536), None); + assert_eq!( + plataberget.gas_limit_schedule.gas_limit_at(1_566), + Some(200_000_000) + ); + } + + #[test] + fn a_gas_limit_schedule_breaking_the_specifications_rules_is_named() { + let schedule = GasLimitSchedule::from(vec![gas_limit_entry(20, 1), gas_limit_entry(10, 2)]); + assert_eq!(schedule.check(10), Ok(())); + assert_eq!( + schedule.check(11), + Err(GasLimitScheduleError::BeforeGloas { + epoch: 10, + gloas_fork_epoch: 11 + }) + ); + + let duplicate = GasLimitSchedule::from(vec![ + gas_limit_entry(10, 1), + gas_limit_entry(20, 2), + gas_limit_entry(10, 3), + ]); + assert_eq!( + duplicate.check(0), + Err(GasLimitScheduleError::DuplicateEpoch { epoch: 10 }) + ); + + let zero = GasLimitSchedule::from(vec![gas_limit_entry(10, 1), gas_limit_entry(20, 0)]); + assert_eq!( + zero.check(0), + Err(GasLimitScheduleError::ZeroGasLimit { epoch: 20 }) + ); + assert_eq!(GasLimitSchedule::default().check(Epoch::MAX), Ok(())); + } + + /// The schedule must leave `Metadata["config"]`'s encoding alone: rows + /// written before the field existed decode unchanged, and no `DB_VERSION` + /// bump is needed. Decoding that row gives an empty schedule; the storage + /// crate fills it from the schedule's own row. + #[test] + fn the_config_row_leaves_the_gas_limit_schedule_to_its_own_row() { + let mut scheduled = Config::mainnet(); + scheduled.gas_limit_schedule = vec![gas_limit_entry(100, 200_000_000)].into(); + + let bytes = scheduled.to_ssz(); + assert_eq!(bytes, Config::mainnet().to_ssz()); + assert_eq!(scheduled.encoded_len(), Config::mainnet().encoded_len()); + + let decoded = Config::from_ssz_bytes(&bytes).expect("valid config"); + assert!(decoded.gas_limit_schedule.is_empty()); + assert_eq!(decoded, Config::mainnet()); + // `PartialEq` still compares the field, so a resume that finds the + // stored schedule (its row's) differing from the file's rewrites it. + assert_ne!(decoded, scheduled); + + assert_eq!(GasLimitSchedule::default().to_ssz(), Vec::::new()); + assert!(GasLimitSchedule::from_ssz_bytes(&[0]).is_err()); + } + + #[test] + fn the_gas_limit_schedule_row_round_trips() { + let schedule = GasLimitSchedule::from(vec![ + gas_limit_entry(1_566, 200_000_000), + gas_limit_entry(1_536, 60_000_000), + ]); + let decoded = GasLimitSchedule::from_row_ssz(&schedule.to_row_ssz()).expect("valid row"); + assert_eq!(decoded, schedule); + assert_eq!(decoded.gas_limit_at(1_566), Some(200_000_000)); + + let empty = GasLimitSchedule::default(); + assert_eq!( + GasLimitSchedule::from_row_ssz(&empty.to_row_ssz()), + Ok(empty) + ); + // One byte is not a whole 16-byte entry. + assert!(GasLimitSchedule::from_row_ssz(&[0]).is_err()); + } + + /// The stored row holds at most `MAX_GAS_LIMIT_SCHEDULE_ENTRIES`, so + /// `check` (a beacon node's config file) refuses a longer schedule rather + /// than the write failing. Deserializing alone does not: a validator + /// client reads a node's schedule and stores nothing. + #[test] + fn a_gas_limit_schedule_longer_than_its_row_is_refused_by_check_only() { + let schedule = |count: usize| { + let entries = (0..count as u64).map(|epoch| gas_limit_entry(epoch, 60_000_000)); + GasLimitSchedule::from(entries.collect::>()) + }; + assert_eq!(schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES).check(0), Ok(())); + assert_eq!( + schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1).check(0), + Err(GasLimitScheduleError::TooManyEntries { + entries: MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1 + }) + ); + + let entry = |epoch| format!(" - EPOCH: {epoch}\n GAS_LIMIT: 60000000\n"); + let over: String = (0..=MAX_GAS_LIMIT_SCHEDULE_ENTRIES).map(entry).collect(); + let parsed: Config = serde_yaml_ng::from_str(&format!("GAS_LIMIT_SCHEDULE:\n{over}")) + .expect("deserializing takes any length"); + assert_eq!( + parsed.gas_limit_schedule.entries().len(), + MAX_GAS_LIMIT_SCHEDULE_ENTRIES + 1 + ); + } + + #[test] + fn the_gas_limit_schedule_serializes_as_a_list_of_quoted_entries() { + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![ + gas_limit_entry(100, 75_000_000), + gas_limit_entry(42, 60_000_000), + ] + .into(); + + let json = serde_json::to_value(&config).expect("serializes"); + assert_eq!( + json["GAS_LIMIT_SCHEDULE"], + serde_json::json!([ + {"EPOCH": "42", "GAS_LIMIT": "60000000"}, + {"EPOCH": "100", "GAS_LIMIT": "75000000"}, + ]) + ); + + // An empty schedule is still reported, as the file may carry it. + let json = serde_json::to_value(Config::mainnet()).expect("serializes"); + assert_eq!(json["GAS_LIMIT_SCHEDULE"], serde_json::json!([])); + } + #[test] fn the_blob_schedule_serializes_as_a_list_of_quoted_entries() { let mut config = Config::mainnet(); diff --git a/crates/common/types/src/beacon/constants.rs b/crates/common/types/src/beacon/constants.rs index 3888c5bd5..e0d1607bc 100644 --- a/crates/common/types/src/beacon/constants.rs +++ b/crates/common/types/src/beacon/constants.rs @@ -465,6 +465,9 @@ pub const XMSS_LEAVES_PER_SLOT: u64 = 1 << 3; /// The depth of the tree under a validator's VRF root: a leaf per slot. pub const VRF_TREE_DEPTH: usize = 31; +/// Prefixed to a secret and its index to derive the leaf of a VRF tree that +/// commits to the secret (`compute_vrf_leaf`). +pub const VRF_LEAF_DOMAIN: &[u8] = b"VRF_LEAF"; /// The slot leaf a beacon block (and so a proposer slashing's headers) is /// signed at. diff --git a/crates/common/types/src/beacon/containers/eip8483.rs b/crates/common/types/src/beacon/containers/eip8483.rs index 712ac2ca4..e3b078801 100644 --- a/crates/common/types/src/beacon/containers/eip8483.rs +++ b/crates/common/types/src/beacon/containers/eip8483.rs @@ -1,6 +1,6 @@ //! Containers whose shape is specific to EIP-8483 (consensus-specs //! `specs/_features/eip8483`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! EIP-8483 adds two execution-layer requests with which validators and //! builders register opaque post-quantum material: 64 bytes for a validator diff --git a/crates/common/types/src/beacon/containers/pq.rs b/crates/common/types/src/beacon/containers/pq.rs index 043bfd7a1..d787013d2 100644 --- a/crates/common/types/src/beacon/containers/pq.rs +++ b/crates/common/types/src/beacon/containers/pq.rs @@ -1,6 +1,6 @@ //! Containers whose shape is specific to the PQ fork (consensus-specs //! `specs/_features/pq`, on the `pq` branch at -//! `2f43bc0f989f47af81df390a90bc1f78e2436323`). +//! `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`). //! //! The fork replaces BLS with leanXMSS. Every signed container trades its //! `BLSSignature` for an [`XmssSignature`]; [`Attestation`] loses its signature diff --git a/crates/common/types/src/beacon/fork.rs b/crates/common/types/src/beacon/fork.rs index 89c064185..0fc4160c7 100644 --- a/crates/common/types/src/beacon/fork.rs +++ b/crates/common/types/src/beacon/fork.rs @@ -45,7 +45,7 @@ fn beacon_snapshot_interval() -> u64 { /// /// [`ForkName::Eip8483`] and [`ForkName::Pq`] are consensus-specs feature /// forks (`specs/_features/{eip8483,pq}` on the `pq` branch, pinned at -/// `2f43bc0f989f47af81df390a90bc1f78e2436323`), not mainnet upgrades: the +/// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`), not mainnet upgrades: the /// PQ fork replaces BLS with leanXMSS, and needs the EIP-8483 registrations /// made before it, so the two are scheduled in that order after gloas. Other /// forks after gloas exist upstream but are out of scope for this crate. diff --git a/crates/common/types/src/beacon/preset.rs b/crates/common/types/src/beacon/preset.rs index 3154c3ff0..3a4668d35 100644 --- a/crates/common/types/src/beacon/preset.rs +++ b/crates/common/types/src/beacon/preset.rs @@ -2262,7 +2262,7 @@ mod tests { /// The PQ preset's values, pinned from `presets/{mainnet,minimal}/pq.yaml`, /// `eip8483.yaml` and `eip8205.yaml` at consensus-specs' `pq` pin - /// `2f43bc0f989f47af81df390a90bc1f78e2436323`. + /// `4c296784bb6ff54cbdcf72ebdda2a1057cce8893`. #[test] fn pq_pinned_values() { assert_eq!(mainnet::MAX_COMMITTEES_PER_SLOT_PQ, 16); diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index 6c29c0437..a16a037f4 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -218,7 +218,11 @@ impl PqValidated { } /// Hold an accepted aggregate for block production, which merges the proofs -/// of the ones it packs (PQ `validator.md`, "Proof"). +/// of the ones it packs (PQ `validator.md`, "Proof"), and record its +/// attesters as broadcast, which this node's own aggregators compare theirs +/// against before broadcasting (`should_broadcast_aggregate`). Both the +/// aggregates gossip accepted and the ones this node published come through +/// here. fn pool_aggregate( store: &Store, signed: &pq::SignedAggregateAndProof, @@ -230,6 +234,9 @@ fn pool_aggregate( let [committee_index] = committees[..] else { return; }; + store + .pq_signature_pool() + .note_broadcast(&aggregate.data, committee_index, attesting_indices); store.pq_aggregate_pool().insert(PooledPqAggregate { attestation: aggregate.clone(), committee_index, diff --git a/crates/net/rpc/src/beacon/config.rs b/crates/net/rpc/src/beacon/config.rs index e4316ccdb..c9c8fb1f2 100644 --- a/crates/net/rpc/src/beacon/config.rs +++ b/crates/net/rpc/src/beacon/config.rs @@ -18,7 +18,13 @@ //! //! The configuration keys include gloas's (`GLOAS_*` and the other gloas //! timing and churn keys), since `Config` holds them and this serializes the -//! whole of it. The preset and constant keys are the ones lighthouse reports +//! whole of it. That includes `GAS_LIMIT_SCHEDULE` (EIP-8261), a list of +//! `{"EPOCH", "GAS_LIMIT"}` entries with quoted values, ascending by epoch, as +//! `BLOB_SCHEDULE` is reported and as lighthouse reports it. It is reported +//! empty when the network schedules nothing, where lighthouse leaves the key +//! out while gloas is unscheduled: the specification's own `config.yaml`s +//! carry it empty, and this endpoint echoes every key a `config.yaml` carries. +//! A validator client takes its default gas limit from it. The preset and constant keys are the ones lighthouse reports //! plus gloas's own, from `presets/*/gloas.yaml` and `beacon-chain.md`'s //! constants (`PTC_SIZE`, `DOMAIN_BEACON_BUILDER`, ...), less keys the //! specification does not define at all (`GAS_LIMIT_ADJUSTMENT_FACTOR`, @@ -496,6 +502,43 @@ mod tests { assert!(data["MIN_BUILDER_WITHDRAWABILITY_DELAY"].is_string()); } + /// The fixture's `Config::mainnet()` schedules no gas limit, which is + /// reported as an empty list rather than left out. + #[tokio::test] + async fn the_spec_reports_an_empty_gas_limit_schedule() { + let json = get_spec_json().await; + assert_eq!(json["data"]["GAS_LIMIT_SCHEDULE"], serde_json::json!([])); + } + + /// The shape lighthouse reports and validator clients read: quoted + /// values, ascending by epoch. + #[test] + fn the_spec_reports_the_gas_limit_schedule_as_quoted_entries() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![ + GasLimitScheduleEntry { + epoch: 400_000, + gas_limit: 300_000_000, + }, + GasLimitScheduleEntry { + epoch: 353_024, + gas_limit: 200_000_000, + }, + ] + .into(); + + let data = spec(&config); + assert_eq!( + data["GAS_LIMIT_SCHEDULE"], + serde_json::json!([ + {"EPOCH": "353024", "GAS_LIMIT": "200000000"}, + {"EPOCH": "400000", "GAS_LIMIT": "300000000"}, + ]) + ); + } + #[tokio::test] async fn the_fork_schedule_lists_scheduled_forks_with_quoted_epochs() { let fixture = beacon_fixture(64); diff --git a/crates/net/rpc/src/beacon/pool.rs b/crates/net/rpc/src/beacon/pool.rs index 3f51d7bb6..614bf7046 100644 --- a/crates/net/rpc/src/beacon/pool.rs +++ b/crates/net/rpc/src/beacon/pool.rs @@ -701,11 +701,23 @@ async fn get_aggregate_attestation( crate::shared::content::with_consensus_version(response, fork) } +/// The 404 [`get_pq_aggregate`] answers for an aggregate it will not hand +/// out to be broadcast. The validator client reads any 404 here as nothing +/// to publish. +const PQ_AGGREGATE_ALREADY_COVERED: &str = + "an aggregate already broadcast for this committee covers every attester of this one"; + /// [`get_aggregate_attestation`] at a PQ slot: the committee's aggregate /// this node proved from the votes it collected for its aggregators (see /// [`crate::beacon::pq_aggregation`]), with its proof. A request racing the -/// proof waits for it until the slot's signatures are sealed and proved, for -/// at most a few seconds; a 404 when there is none. +/// proof waits for it, for at most a few seconds; a 404 when there is none. +/// +/// Also a 404 when an aggregate already broadcast for the same vote and +/// committee, by another aggregator or an earlier one of this node, includes +/// every attester of this one: PQ `validator.md`'s +/// `should_broadcast_aggregate` answers no, since gossip would ignore it. The +/// validator client asks at its aggregator's own broadcast time, so the +/// answer is the one that time calls for. async fn get_pq_aggregate(store: &Store, query: &AggregateQuery, headers: &HeaderMap) -> Response { use ethlambda_types::beacon::containers::pq; use libssz::SszEncode as _; @@ -732,6 +744,15 @@ async fn get_pq_aggregate(store: &Store, query: &AggregateQuery, headers: &Heade if let Err(err) = require_validated(store, aggregate.attestation.data.beacon_block_root) { return err.into_response(); } + let covered = store.pq_signature_pool().is_covered( + query.slot, + query.attestation_data_root, + query.committee_index, + &aggregate.attesting_indices, + ); + if covered { + return ApiError::NotFound(PQ_AGGREGATE_ALREADY_COVERED).into_response(); + } let answer = pq::ProvenAggregate { aggregate: aggregate.attestation.clone(), proof: aggregate.proof.clone(), diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index be738b792..b25b9cff6 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -1,15 +1,22 @@ //! PQ aggregation for this node's validator client. //! //! A PQ aggregator proves its committee's signatures instead of aggregating -//! them (PQ `validator.md`, "Aggregate stark"), and proving takes the -//! sidecar seconds, too long to run inside the `aggregate_attestation` -//! request. So, as Lighthouse's PQ branch does, the node proves ahead: the -//! validator client names the committees it aggregates for through +//! them (PQ `validator.md`, "Aggregate stark"), and proving takes leanVM +//! seconds, too long to run inside the `aggregate_attestation` request. So, +//! as Lighthouse's PQ branch does, the node proves ahead: the validator +//! client names the committees it aggregates for through //! `beacon_committee_subscriptions`, the node collects their validated votes' -//! signatures ([`ethlambda_storage::pools::PqSignaturePool`]), and once a slot -//! the task here seals that slot's signatures halfway between the -//! attestation and aggregate deadlines and proves each committee's before the -//! aggregate deadline, largest first. The endpoint then answers with what was +//! signatures ([`ethlambda_storage::pools::PqSignaturePool`]), and proves +//! each committee's at its aggregator's cutoff. +//! +//! The aggregators of a committee are staggered by their seat in its +//! aggregation committee (PQ `validator.md`, "Construct aggregate"): the one +//! at `position` stops collecting at `get_aggregation_cutoff_ms(position)` and +//! broadcasts at `get_aggregate_due_ms(position)`. The task here wakes at +//! each seat's cutoff in turn, proves what was collected for the committees +//! one of this node's validators holds that seat in (unless an earlier seat +//! of this node already proved every vote collected), and ends the slot's +//! collection after the last seat's. The endpoint then answers with what was //! proved, and the aggregate also goes into the pool block production packs //! from, since gossip never hands a node its own messages. @@ -17,8 +24,11 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use ethlambda_state_transition::beacon::{ - fork_choice::{get_attestation_due_ms, get_slot_component_duration_ms}, - helpers::{accessors::CommitteeCacheExt as _, pq::get_attestation_statements}, + fork_choice::{get_aggregation_cutoff_ms, get_pq_aggregate_due_ms}, + helpers::{ + accessors::CommitteeCacheExt as _, + pq::{get_aggregation_committee, get_attestation_statements}, + }, }; use ethlambda_storage::{ Store, @@ -26,6 +36,7 @@ use ethlambda_storage::{ }; use ethlambda_types::beacon::{ config::Config, + constants::AGGREGATORS_PER_COMMITTEE, containers::{BeaconState, pq}, fork::ForkName, primitives::Slot, @@ -36,8 +47,8 @@ use tracing::{debug, info, warn}; use crate::beacon::validator::head; -/// Start proving PQ aggregates once a slot, if the network schedules PQ. -/// Stops with `shutdown`. +/// Start proving PQ aggregates at every aggregator's cutoff, if the network +/// schedules PQ. Stops with `shutdown`. pub(crate) fn spawn(store: Store, shutdown: CancellationToken) { let config = store.config(); if config.fork_epoch(ForkName::Pq) == u64::MAX { @@ -50,35 +61,54 @@ pub(crate) fn spawn(store: Store, shutdown: CancellationToken) { loop { let slot = next_slot_to_seal(&config, now_ms()).max(next); next = slot + 1; - let cutoff = collection_cutoff_ms(&config, slot); - let wait = Duration::from_millis(cutoff.saturating_sub(now_ms())); - tokio::select! { - () = shutdown.cancelled() => return, - () = tokio::time::sleep(wait) => {} - } - if config.fork_at_epoch(compute_epoch_at_slot(slot)) != ForkName::Pq { - continue; + for position in 0..AGGREGATORS_PER_COMMITTEE { + let cutoff = + slot_start_ms(&config, slot) + get_aggregation_cutoff_ms(position, &config); + let wait = Duration::from_millis(cutoff.saturating_sub(now_ms())); + tokio::select! { + () = shutdown.cancelled() => return, + () = tokio::time::sleep(wait) => {} + } + if config.fork_at_epoch(compute_epoch_at_slot(slot)) == ForkName::Pq { + prove_seat(&store, &config, slot, position).await; + } } - prove_slot(&store, &config, slot).await; + // The last seat's cutoff has passed: nothing more is collected. + store.pq_signature_pool().seal(slot); } }); } -/// Seal `slot`'s collected signatures and prove what the time to its -/// aggregate deadline allows. -async fn prove_slot(store: &Store, config: &Config, slot: Slot) { - let groups = store.pq_signature_pool().seal(slot); - if groups.is_empty() { +/// The committees of `slot` in which one of this node's aggregators holds +/// seat `position` of the aggregation committee, as `state` names them. +fn committees_at_seat(store: &Store, state: &BeaconState, slot: Slot, position: u64) -> Vec { + // Bound first, so the pool's lock is not held while committees are read. + let aggregators = store.pq_signature_pool().aggregators(slot); + aggregators + .into_iter() + .filter(|(committee, validators)| { + get_aggregation_committee(state, slot, *committee).is_ok_and(|members| { + members + .get(position as usize) + .is_some_and(|member| validators.contains(member)) + }) + }) + .map(|(committee, _)| committee) + .collect() +} + +/// Prove what `slot` collected for the committees whose aggregator at +/// `position` is this node's, before that aggregator's broadcast time. +async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { + if store.pq_signature_pool().aggregators(slot).is_empty() { return; } - let deadline_ms = slot_start_ms(config, slot) + aggregate_due_ms(config, slot); + let deadline_ms = slot_start_ms(config, slot) + get_pq_aggregate_due_ms(position, config); let Some(budget) = deadline_ms.checked_sub(now_ms()).filter(|&left| left > 0) else { - warn!(%slot, "No time left to prove this slot's PQ aggregates"); + warn!(%slot, position, "No time left to prove this seat's PQ aggregates"); return; }; let deadline = Instant::now() + Duration::from_millis(budget); - let committees = groups.len(); - let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); let store = store.clone(); let spawned = Instant::now(); let job = tokio::task::spawn_blocking(move || { @@ -89,12 +119,22 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { let state = match head(&store) { Ok((_, state)) => state, Err(err) => { - warn!(%slot, ?err, "Could not read the head state to prove this slot's PQ aggregates"); + warn!(%slot, position, ?err, "Could not read the head state to prove this seat's PQ aggregates"); return; } }; + let committees = committees_at_seat(&store, &state, slot, position); + if committees.is_empty() { + return; + } let state_ms = started.elapsed().as_millis() as u64; - let mut groups = groups; + let mut groups = store.pq_signature_pool().collected(slot, &committees); + let committees = groups.len(); + // What an earlier seat of this node already proved in full is not + // proved again: see `PqSignaturePool::is_proven`. + groups.retain(|group| !store.pq_signature_pool().is_proven(group)); + let already_proven = committees - groups.len(); + let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the // deadline. groups.sort_by_key(|group| std::cmp::Reverse(group.signatures.len())); @@ -102,7 +142,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { let mut prove_ms_total = 0u64; for group in groups { if Instant::now() >= deadline { - warn!(%slot, "The PQ aggregate deadline passed with committees left to prove"); + warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); break; } let committee = group.committee_index; @@ -117,6 +157,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { info!( %slot, committee, + position, attesters = aggregate.attesting_indices.len(), proof_bytes = aggregate.proof.len(), prove_ms, @@ -132,6 +173,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { warn!( %slot, committee, + position, attesters = aggregate.attesting_indices.len(), prove_ms, took_ms, @@ -144,6 +186,7 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { debug!( %slot, committee, + position, signatures = collected, took_ms, %err, @@ -152,22 +195,24 @@ async fn prove_slot(store: &Store, config: &Config, slot: Slot) { } } } - // One line for the slot's whole proving pass: what the sidecar was - // asked for, what it cost, and what the budget left undone. + // One line for the seat's whole proving pass: what leanVM was asked + // for, what it cost, and what the budget left undone. info!( %slot, + position, committees, signatures, proved, + already_proven, failed, late, - unproved = committees - proved - failed - late, + unproved = committees - already_proven - proved - failed - late, queued_ms, state_ms, prove_ms = prove_ms_total, took_ms = started.elapsed().as_millis() as u64, budget_ms = budget, - "Finished proving this slot's PQ aggregates" + "Finished proving this seat's PQ aggregates" ); }); let _ = job.await; @@ -249,41 +294,19 @@ fn slot_start_ms(config: &Config, slot: Slot) -> u64 { } /// The first slot whose signatures are still being collected at `now_ms`: -/// slot 0 before genesis, then the wall clock's slot until its collection -/// cutoff and the next one after it. Taking the wall clock's slot plus one -/// skipped slot 0 on a node started before genesis, whose aggregators' votes -/// were then never proved. +/// slot 0 before genesis, then the wall clock's slot until its last seat's +/// collection cutoff and the next one after it. Taking the wall clock's slot +/// plus one skipped slot 0 on a node started before genesis, whose +/// aggregators' votes were then never proved. fn next_slot_to_seal(config: &Config, now_ms: u64) -> Slot { let genesis_ms = config.genesis_time.saturating_mul(1000); let Some(elapsed) = now_ms.checked_sub(genesis_ms) else { return 0; }; let slot = elapsed / config.slot_duration_ms.max(1); - if now_ms < collection_cutoff_ms(config, slot) { - slot - } else { - slot + 1 - } -} - -/// How far into `slot` its aggregates are due. -fn aggregate_due_ms(config: &Config, slot: Slot) -> u64 { - let gloas_on = config.fork_at_epoch(compute_epoch_at_slot(slot)) >= ForkName::Gloas; - let basis_points = if gloas_on { - config.aggregate_due_bps_gloas - } else { - config.aggregate_due_bps - }; - get_slot_component_duration_ms(basis_points, config) -} - -/// When `slot`'s signatures stop being collected: halfway from the -/// attestation deadline to the aggregate deadline. -fn collection_cutoff_ms(config: &Config, slot: Slot) -> u64 { - let attestation_due = get_attestation_due_ms(compute_epoch_at_slot(slot), config); - let aggregate_due = aggregate_due_ms(config, slot); - let window = aggregate_due.saturating_sub(attestation_due); - slot_start_ms(config, slot) + attestation_due + window / 2 + let last_cutoff = slot_start_ms(config, slot) + + get_aggregation_cutoff_ms(AGGREGATORS_PER_COMMITTEE - 1, config); + if now_ms < last_cutoff { slot } else { slot + 1 } } #[cfg(test)] @@ -291,30 +314,32 @@ mod tests { use super::*; #[test] - fn signatures_are_collected_until_halfway_to_the_aggregate_deadline() { + fn each_seat_proves_between_its_cutoff_and_its_broadcast() { let mut config = Config::mainnet(); config.genesis_time = 100; - config.gloas_fork_epoch = 0; - // Gloas timing: attestations at 25% of 12 s, aggregates at 50%. assert_eq!(slot_start_ms(&config, 2), 100_000 + 24_000); - assert_eq!(aggregate_due_ms(&config, 2), 6_000); - assert_eq!(collection_cutoff_ms(&config, 2), 124_000 + 3_000 + 1_500); + for position in 0..AGGREGATORS_PER_COMMITTEE { + let cutoff = get_aggregation_cutoff_ms(position, &config); + let due = get_pq_aggregate_due_ms(position, &config); + // 2.4 s to prove on a 12 s slot, whatever the seat. + assert_eq!(due - cutoff, 2_400); + } } #[test] fn the_next_slot_to_seal_starts_at_genesis() { let mut config = Config::mainnet(); config.genesis_time = 100; - config.gloas_fork_epoch = 0; - // Before genesis: slot 0, whose cutoff is 4.5 s into it. + // Before genesis: slot 0, whose last seat (3) stops collecting + // 40% + 3 * 5% of 12 s in, at 6.6 s. assert_eq!(next_slot_to_seal(&config, 0), 0); assert_eq!(next_slot_to_seal(&config, 99_999), 0); - assert_eq!(next_slot_to_seal(&config, 104_499), 0); - assert_eq!(next_slot_to_seal(&config, 104_500), 1); - // Mid-slot: that slot until its cutoff, the next one from then on. + assert_eq!(next_slot_to_seal(&config, 106_599), 0); + assert_eq!(next_slot_to_seal(&config, 106_600), 1); + // Mid-slot: that slot until its last cutoff, the next one from then on. assert_eq!(next_slot_to_seal(&config, 124_000), 2); - assert_eq!(next_slot_to_seal(&config, 128_499), 2); - assert_eq!(next_slot_to_seal(&config, 128_500), 3); + assert_eq!(next_slot_to_seal(&config, 130_599), 2); + assert_eq!(next_slot_to_seal(&config, 130_600), 3); assert_eq!(next_slot_to_seal(&config, 135_999), 3); } } diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index ea943e0e3..d400d4181 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -19,14 +19,14 @@ //! that ahead of the slot, alongside the payload build, for the slots this //! node's proposers hold, and production collects it when it was for the head //! it builds on (`ethlambda_blockchain::pq_attestation_packing`); otherwise -//! it merges here while the execution client builds the payload. A merge runs -//! on the proving sidecar and costs about 0.6 s with two children, so it is -//! bounded by a deadline three quarters of the way to the slot's attestation -//! deadline (Lighthouse's PQ branch uses the same one). A merge that misses -//! it or fails is dropped for the most valuable single-committee attestation -//! alone, whose proof needs no merging; a block `process_stark` refuses is -//! built again without attestations, so the block goes out rather than not -//! at all. +//! it merges here while the execution client builds the payload. A merge is a +//! leanVM proof, in process, and costs from under a second to seconds when +//! there is more than one child, so it is bounded by a deadline three quarters +//! of the way to the slot's attestation deadline (Lighthouse's PQ branch uses +//! the same one). A merge that misses it or fails is dropped for the most +//! valuable single-committee attestation alone, whose proof needs no merging; +//! a block `process_stark` refuses is built again without attestations, so the +//! block goes out rather than not at all. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; @@ -45,6 +45,7 @@ use ethlambda_blockchain::{ }; use ethlambda_engine::{EngineClient, types::ClientVersionV1}; use ethlambda_state_transition::beacon::{ + builder_market::SharedPqBuilderMarket, helpers::pq::is_valid_vrf_proof, pq_block_production::{PqBlockInputs, assemble_pq_block, parse_pq_execution_requests}, }; @@ -116,7 +117,8 @@ impl PqBlobs { #[derive(Debug, Deserialize)] struct ProducePqBlock { - /// The proposer's VRF proof for the slot: the leaf, then its branch. + /// The proposer's VRF proof for the slot: the secret, then its leaf's + /// branch. randao_reveal: Vec, #[serde(default)] graffiti: Option, @@ -131,6 +133,7 @@ async fn post_produce_pq_block( Extension(custody): Extension, Extension(OwnVersion(own_version)): Extension, Extension(sync_status): Extension, + Extension(pq_market): Extension, blob_cache: Option>, ahead: Option>, ahead_attestations: Option>, @@ -162,6 +165,7 @@ async fn post_produce_pq_block( &store, &engine, &fee_recipients, + &pq_market, &custody, ahead.as_ref().map(|Extension(ahead)| ahead), ahead_attestations.as_ref().map(|Extension(ahead)| ahead), @@ -193,6 +197,7 @@ async fn produce( store: &Store, engine: &EngineClient, fee_recipients: &FeeRecipients, + pq_market: &SharedPqBuilderMarket, custody: &NodeCustodyColumns, ahead: Option<&PreparedPayloads>, ahead_attestations: Option<&PreparedPqAttestations>, @@ -211,13 +216,15 @@ async fn produce( proposer, build_on_full, parent_requests, - } = prepare_pq_proposal(store, head_root, &head_state, slot).map_err(|err| match err { - ProposalError::NotAfterHead => ApiError::BadRequest("slot is not after the head block"), - ProposalError::ParentEnvelopeMissing => { - ApiError::ServiceUnavailable("the parent's payload envelope is not held to build on") - } - ProposalError::Internal(message) => ApiError::Internal(message), - })?; + } = prepare_pq_proposal(store, pq_market, head_root, &head_state, slot).map_err( + |err| match err { + ProposalError::NotAfterHead => ApiError::BadRequest("slot is not after the head block"), + ProposalError::ParentEnvelopeMissing => ApiError::ServiceUnavailable( + "the parent's payload envelope is not held to build on", + ), + ProposalError::Internal(message) => ApiError::Internal(message), + }, + )?; if !is_valid_vrf_proof(&state, proposer, slot, &randao_reveal).unwrap_or(false) { return Err(ApiError::BadRequest("invalid randao_reveal")); } diff --git a/crates/net/rpc/src/beacon/validator.rs b/crates/net/rpc/src/beacon/validator.rs index f65d893bb..f8c4e8cc0 100644 --- a/crates/net/rpc/src/beacon/validator.rs +++ b/crates/net/rpc/src/beacon/validator.rs @@ -295,11 +295,11 @@ fn liveness(store: &Store, epoch: &str, indices: &[String]) -> Result, + /// A PQ aggregator's index in its aggregation committee, which staggers + /// it: the `position` of `get_aggregation_cutoff_ms` and + /// `get_aggregate_due_ms` (PQ `validator.md`, "Construct aggregate"). + /// Absent for a validator that is not one. + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "quoted_position" + )] + aggregator_position: Option, +} + +/// An aggregator's position as the Beacon API writes an integer: a decimal +/// string. Only called for `Some`, since `None` is skipped. +fn quoted_position( + position: &Option, + serializer: S, +) -> Result { + serializer.collect_str(&position.unwrap_or_default()) } /// `POST /eth/v1/validator/duties/attester/{epoch}`, with the validator @@ -765,10 +786,14 @@ fn attester_duties( .map_err(|_| ApiError::Internal("committee names an unknown validator"))?; // A state not yet at PQ (the fork's first epoch, asked // early) names no aggregation committee: not an aggregator. - let is_aggregator = is_pq.then(|| { + let aggregator_position = if is_pq { get_aggregation_committee(&state, slot, committee_index) - .is_ok_and(|members| members.contains(&validator_index)) - }); + .ok() + .and_then(|members| members.iter().position(|&m| m == validator_index)) + .map(|seat| seat as u64) + } else { + None + }; duties.push(AttesterDuty { pubkey: ApiPubkey::of(&state, validator.pubkey), validator_index, @@ -777,7 +802,8 @@ fn attester_duties( committees_at_slot, validator_committee_index: position as u64, slot, - is_aggregator, + is_aggregator: is_pq.then_some(aggregator_position.is_some()), + aggregator_position, }); } } diff --git a/crates/storage/src/pools/pq_signature.rs b/crates/storage/src/pools/pq_signature.rs index a81d0a37c..de095995d 100644 --- a/crates/storage/src/pools/pq_signature.rs +++ b/crates/storage/src/pools/pq_signature.rs @@ -5,9 +5,16 @@ //! signatures with an `AttestationProof` instead of aggregating them. The //! validator client names the committees it aggregates for through //! `beacon_committee_subscriptions`; this pool keeps the signatures of -//! validated single attestations for those committees only, seals each slot's -//! once its collection window closes, and holds what the node proved from -//! them for the aggregate endpoint to answer with. +//! validated single attestations for those committees only, hands what it +//! has collected to the prover at each of its aggregators' cutoffs, and holds +//! what the node proved from them for the aggregate endpoint to answer with. +//! +//! The aggregators of a committee are staggered (`get_aggregation_cutoff_ms`), +//! so a slot's signatures are read more than once and its collection ends at +//! the last cutoff ([`PqSignaturePool::seal`]). The pool also records the +//! attesters of every aggregate broadcast for those committees, gossip's and +//! this node's own, which is what `should_broadcast_aggregate` compares an +//! aggregate against before it is broadcast. //! //! In memory only, and a few slots deep: an aggregate is published within its //! own slot. @@ -36,6 +43,13 @@ fn max_groups_per_slot() -> usize { preset::max_committees_per_slot_pq() * 4 } +/// How many broadcast aggregates' attester sets the pool keeps per +/// `(AttestationData, committee)`. Gossip accepts one aggregate per +/// aggregator and epoch, and only one no earlier aggregate covers, so a +/// committee's `AGGREGATORS_PER_COMMITTEE` aggregators fill at most that +/// many; twice that leaves room without letting a peer grow the record. +const MAX_BROADCAST_SETS: usize = 8; + /// `(slot, data root, committee index)`. type Key = (Slot, Root, u64); @@ -52,12 +66,16 @@ pub struct CommitteeSignatures { /// Signatures awaiting proof and the aggregates proved from them. #[derive(Debug, Default)] pub struct PqSignaturePool { - /// `(slot, committee)` this node's validators aggregate for. - subscriptions: BTreeSet<(Slot, u64)>, + /// The validators of this node that aggregate for each `(slot, + /// committee)`. + subscriptions: BTreeMap<(Slot, u64), BTreeSet>, raw: BTreeMap, proven: BTreeMap>, - /// The latest slot whose signatures were handed to the prover: later - /// signatures for it are not collected. + /// The attesters, sorted, of each aggregate broadcast for a subscribed + /// committee: the ones gossip accepted and the ones this node published. + broadcast: BTreeMap>>, + /// The latest slot whose collection ended: later signatures for it are + /// not collected. sealed_slot: Option, } @@ -66,26 +84,48 @@ impl PqSignaturePool { let earliest = now.saturating_sub(RETAINED_SLOTS - 1); self.raw.retain(|(slot, _, _), _| *slot >= earliest); self.proven.retain(|(slot, _, _), _| *slot >= earliest); - self.subscriptions.retain(|(slot, _)| *slot >= now); + self.broadcast.retain(|(slot, _, _), _| *slot >= earliest); + self.subscriptions.retain(|(slot, _), _| *slot >= now); } - /// Collect `committee`'s signatures at `slot`, which one of this node's - /// validators aggregates for. Refused for a past slot, one more than two + /// Collect `committee`'s signatures at `slot`, which `validator`, one of + /// this node's, aggregates for. Refused for a past slot, one more than two /// epochs ahead, or a committee index PQ cannot have. - pub fn subscribe(&mut self, now: Slot, slot: Slot, committee: u64) -> bool { + pub fn subscribe( + &mut self, + now: Slot, + slot: Slot, + committee: u64, + validator: ValidatorIndex, + ) -> bool { self.prune(now); let accepted = slot >= now && slot <= now.saturating_add(2 * preset::slots_per_epoch()) && committee < preset::max_committees_per_slot_pq() as u64; if accepted { - self.subscriptions.insert((slot, committee)); + let aggregators = self.subscriptions.entry((slot, committee)).or_default(); + // A committee has `AGGREGATORS_PER_COMMITTEE` aggregators; more + // names than a committee has members is a caller's mistake, and + // the bound keeps the record from growing with it. + if aggregators.len() < preset::MAX_VALIDATORS_PER_COMMITTEE { + aggregators.insert(validator); + } } accepted } /// Whether this node collects `committee`'s signatures at `slot`. pub fn is_subscribed(&self, slot: Slot, committee: u64) -> bool { - self.subscriptions.contains(&(slot, committee)) + self.subscriptions.contains_key(&(slot, committee)) + } + + /// The committees of `slot` this node aggregates for, each with its + /// aggregators among this node's validators. + pub fn aggregators(&self, slot: Slot) -> Vec<(u64, Vec)> { + self.subscriptions + .range((slot, 0)..=(slot, u64::MAX)) + .map(|(&(_, committee), validators)| (committee, validators.iter().copied().collect())) + .collect() } /// Keep a validated attestation's signature, if its committee is one this @@ -97,7 +137,7 @@ impl PqSignaturePool { let committee = attestation.committee_index; if slot < now || self.sealed_slot.is_some_and(|sealed| slot <= sealed) - || !self.subscriptions.contains(&(slot, committee)) + || !self.subscriptions.contains_key(&(slot, committee)) { return false; } @@ -128,27 +168,43 @@ impl PqSignaturePool { kept } - /// Hand `slot`'s collected signatures to the prover, at most once per - /// slot. Signatures arriving for it afterwards are not collected. - pub fn seal(&mut self, slot: Slot) -> Vec { + /// What `slot` has collected so far for `committees`, for an aggregator + /// whose cutoff has come. Collection goes on for the aggregators after + /// it, until [`Self::seal`]. + pub fn collected(&self, slot: Slot, committees: &[u64]) -> Vec { + self.raw + .range((slot, Root::ZERO, 0)..) + .take_while(|((held, _, _), _)| *held == slot) + .filter(|((_, _, committee), _)| committees.contains(committee)) + .map(|(_, group)| group.clone()) + .collect() + } + + /// End `slot`'s collection, once its last aggregator's cutoff has passed: + /// its signatures are dropped and none arriving afterwards is kept. + pub fn seal(&mut self, slot: Slot) { self.prune(slot); if self.sealed_slot.is_some_and(|sealed| slot <= sealed) { - return Vec::new(); + return; } self.sealed_slot = Some(slot); - let later = self.raw.split_off(&(slot + 1, Root::ZERO, 0)); - std::mem::replace(&mut self.raw, later) - .into_iter() - .filter(|((held, _, _), _)| *held == slot) - .map(|(_, group)| group) - .collect() + self.raw = self.raw.split_off(&(slot + 1, Root::ZERO, 0)); } /// Hold an aggregate this node proved, for the aggregate endpoint. + /// + /// A later seat proves from more signatures than an earlier one, so the + /// aggregate covering more attesters is the one kept. pub fn insert_proven(&mut self, aggregate: Arc) { let data = &aggregate.attestation.data; let key = (data.slot, data.hash_tree_root(), aggregate.committee_index); - self.proven.insert(key, aggregate); + let better = self + .proven + .get(&key) + .is_none_or(|held| aggregate.attesting_indices.len() > held.attesting_indices.len()); + if better { + self.proven.insert(key, aggregate); + } } /// The aggregate this node proved for `committee`'s vote on the data @@ -162,10 +218,89 @@ impl PqSignaturePool { self.proven.get(&(slot, data_root, committee)).cloned() } - /// Whether `slot`'s signatures were already handed to the prover. + /// Whether the aggregate this node holds for `group`'s vote already + /// proves every signature `group` has. + /// + /// A committee's seats are staggered, and one node can hold several of + /// them. Unless a vote arrived between two of their cutoffs, the later + /// seat collected what the earlier one proved: proving it again takes the + /// prover seconds, one proof at a time, for an aggregate the endpoint + /// would not even keep ([`Self::insert_proven`] keeps the larger one) and + /// that `should_broadcast_aggregate` rules out once the earlier seat has + /// broadcast. The held aggregate still answers the later seat's request. + pub fn is_proven(&self, group: &CommitteeSignatures) -> bool { + let key = ( + group.data.slot, + group.data.hash_tree_root(), + group.committee_index, + ); + self.proven.get(&key).is_some_and(|held| { + group + .signatures + .keys() + .all(|signer| held.attesting_indices.binary_search(signer).is_ok()) + }) + } + + /// Whether `slot`'s collection has ended. pub fn is_sealed(&self, slot: Slot) -> bool { self.sealed_slot.is_some_and(|sealed| slot <= sealed) } + + /// Record an aggregate broadcast for `committee`'s vote on `data`, with + /// the attesters it covers: one gossip accepted, or one this node + /// published. Kept only for committees this node aggregates for. + pub fn note_broadcast( + &mut self, + data: &AttestationData, + committee: u64, + attesting_indices: &[ValidatorIndex], + ) { + if !self.subscriptions.contains_key(&(data.slot, committee)) { + return; + } + let mut attesters = attesting_indices.to_vec(); + attesters.sort_unstable(); + attesters.dedup(); + let sets = self + .broadcast + .entry((data.slot, data.hash_tree_root(), committee)) + .or_default(); + if sets.iter().any(|held| is_superset(held, &attesters)) { + return; + } + sets.retain(|held| !is_superset(&attesters, held)); + if sets.len() < MAX_BROADCAST_SETS { + sets.push(attesters); + } + } + + /// Whether an aggregate already broadcast for the same data and committee + /// includes all of `attesting_indices`: the negation of PQ + /// `validator.md`'s `should_broadcast_aggregate`. Each broadcast + /// aggregate is compared on its own, since a proposer includes one per + /// committee: two that only together cover the attesters do not make an + /// aggregate redundant. An identical one does. + pub fn is_covered( + &self, + slot: Slot, + data_root: Root, + committee: u64, + attesting_indices: &[ValidatorIndex], + ) -> bool { + let mut attesters = attesting_indices.to_vec(); + attesters.sort_unstable(); + self.broadcast + .get(&(slot, data_root, committee)) + .is_some_and(|sets| sets.iter().any(|held| is_superset(held, &attesters))) + } +} + +/// Whether sorted `held` includes every element of `wanted`. +fn is_superset(held: &[ValidatorIndex], wanted: &[ValidatorIndex]) -> bool { + wanted + .iter() + .all(|validator| held.binary_search(validator).is_ok()) } #[cfg(test)] @@ -186,47 +321,175 @@ mod tests { } #[test] - fn signatures_need_a_subscription_and_a_slot_seals_once() { + fn signatures_need_a_subscription_and_are_read_until_the_slot_seals() { let mut pool = PqSignaturePool::default(); assert!(!pool.insert(3, &vote(3, 0, 7, 1))); - assert!(pool.subscribe(3, 3, 0)); + assert!(pool.subscribe(3, 3, 0, 7)); assert!(pool.insert(3, &vote(3, 0, 7, 1))); // The first signature per attester wins. assert!(!pool.insert(3, &vote(3, 0, 7, 1))); - assert!(pool.insert(3, &vote(3, 0, 8, 1))); // Another committee of the slot is not subscribed. assert!(!pool.insert(3, &vote(3, 1, 9, 1))); - let sealed = pool.seal(3); - let [group] = sealed.as_slice() else { - panic!("one group to prove"); + // The first aggregator's cutoff reads what there is, and collection + // goes on for the next one. + let attesters = |pool: &PqSignaturePool| -> Vec> { + pool.collected(3, &[0]) + .iter() + .map(|group| group.signatures.keys().copied().collect()) + .collect() }; - assert_eq!( - group.signatures.keys().copied().collect::>(), - vec![7, 8] - ); - // Nothing more is collected for a sealed slot, nor sealed twice. + assert_eq!(attesters(&pool), vec![vec![7]]); + assert!(pool.insert(3, &vote(3, 0, 8, 1))); + assert_eq!(attesters(&pool), vec![vec![7, 8]]); + // Only the committees asked for are read. + assert!(pool.collected(3, &[1]).is_empty()); + assert!(pool.collected(4, &[0]).is_empty()); + + // Nothing more is collected for a sealed slot. + pool.seal(3); + assert!(pool.is_sealed(3)); + assert!(pool.collected(3, &[0]).is_empty()); assert!(!pool.insert(3, &vote(3, 0, 10, 1))); - assert!(pool.seal(3).is_empty()); + } + + #[test] + fn sealing_a_slot_keeps_the_next_ones_signatures() { + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 7); + pool.subscribe(3, 4, 0, 7); + pool.insert(3, &vote(3, 0, 7, 1)); + pool.insert(3, &vote(4, 0, 7, 1)); + pool.seal(3); + assert_eq!(pool.collected(4, &[0]).len(), 1); } #[test] fn a_slot_holds_a_bounded_number_of_groups() { let mut pool = PqSignaturePool::default(); - pool.subscribe(3, 3, 0); + pool.subscribe(3, 3, 0, 7); for root in 0..=max_groups_per_slot() as u8 { pool.insert(3, &vote(3, 0, root as u64, root)); } - assert_eq!(pool.seal(3).len(), max_groups_per_slot()); + assert_eq!(pool.collected(3, &[0]).len(), max_groups_per_slot()); } #[test] fn subscriptions_are_bounded_in_time_and_committee() { let mut pool = PqSignaturePool::default(); - assert!(!pool.subscribe(10, 9, 0)); - assert!(!pool.subscribe(10, 10 + 2 * preset::slots_per_epoch() + 1, 0)); - assert!(!pool.subscribe(10, 10, preset::max_committees_per_slot_pq() as u64)); - assert!(pool.subscribe(10, 12, 1)); + assert!(!pool.subscribe(10, 9, 0, 1)); + assert!(!pool.subscribe(10, 10 + 2 * preset::slots_per_epoch() + 1, 0, 1)); + assert!(!pool.subscribe(10, 10, preset::max_committees_per_slot_pq() as u64, 1)); + assert!(pool.subscribe(10, 12, 1, 1)); assert!(pool.is_subscribed(12, 1)); } + + #[test] + fn a_committees_aggregators_are_the_validators_that_subscribed() { + let mut pool = PqSignaturePool::default(); + pool.subscribe(10, 12, 1, 40); + pool.subscribe(10, 12, 1, 30); + pool.subscribe(10, 12, 1, 40); + pool.subscribe(10, 12, 3, 50); + pool.subscribe(10, 13, 0, 60); + assert_eq!(pool.aggregators(12), vec![(1, vec![30, 40]), (3, vec![50])]); + assert!(pool.aggregators(11).is_empty()); + } + + /// PQ `validator.md`'s table for `should_broadcast_aggregate`: whether an + /// aggregator in a committee of four broadcasts an aggregate with + /// attesters 0 and 1, given the aggregates already broadcast. + #[test] + fn an_aggregate_is_redundant_only_when_one_broadcast_covers_it() { + let data = vote(3, 0, 0, 1).data; + let root = data.hash_tree_root(); + let covered_given = |broadcast: &[&[ValidatorIndex]]| { + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 0); + for attesters in broadcast { + pool.note_broadcast(&data, 0, attesters); + } + pool.is_covered(3, root, 0, &[0, 1]) + }; + // Nothing to compare against. + assert!(!covered_given(&[])); + // `1000` lacks attester 1. + assert!(!covered_given(&[&[0]])); + // `1110` has attesters 0 and 1. + assert!(covered_given(&[&[0, 1, 2]])); + // `1100`: an identical aggregate counts as a superset. + assert!(covered_given(&[&[1, 0]])); + // `1000` and `0100`: neither has both. + assert!(!covered_given(&[&[0], &[1]])); + // `0011` has neither. + assert!(!covered_given(&[&[2, 3]])); + } + + /// A later seat has something to prove only when it collected a vote the + /// held aggregate lacks. + #[test] + fn a_group_is_proven_once_the_held_aggregate_has_all_its_signers() { + use ethlambda_types::beacon::containers::pq::Attestation; + let mut pool = PqSignaturePool::default(); + pool.subscribe(3, 3, 0, 7); + pool.insert(3, &vote(3, 0, 10, 1)); + pool.insert(3, &vote(3, 0, 11, 1)); + let collected = |pool: &PqSignaturePool| pool.collected(3, &[0]).remove(0); + assert!(!pool.is_proven(&collected(&pool)), "nothing held yet"); + + // The first seat proves the two votes it collected. + let group = collected(&pool); + pool.insert_proven(Arc::new(PooledPqAggregate { + attestation: Attestation { + aggregation_bits: Default::default(), + data: group.data, + committee_bits: Default::default(), + }, + committee_index: 0, + attesting_indices: vec![10, 11], + proof: Default::default(), + })); + assert!(pool.is_proven(&collected(&pool))); + + // A third vote reaches the next seat before its cutoff. + pool.insert(3, &vote(3, 0, 12, 1)); + assert!(!pool.is_proven(&collected(&pool))); + + // Another vote on other data is its own group, with nothing held. + pool.insert(3, &vote(3, 0, 13, 2)); + let groups = pool.collected(3, &[0]); + assert_eq!(groups.len(), 2); + assert!(groups.iter().all(|group| !pool.is_proven(group))); + } + + #[test] + fn broadcasts_are_kept_per_vote_and_committee_and_only_when_subscribed() { + let data = vote(3, 0, 0, 1).data; + let other = vote(3, 0, 0, 2).data; + let mut pool = PqSignaturePool::default(); + // Not a committee this node aggregates for: nothing is kept. + pool.note_broadcast(&data, 0, &[0, 1]); + assert!(!pool.is_covered(3, data.hash_tree_root(), 0, &[0])); + + pool.subscribe(3, 3, 0, 0); + pool.subscribe(3, 3, 1, 0); + pool.note_broadcast(&data, 0, &[0, 1]); + assert!(pool.is_covered(3, data.hash_tree_root(), 0, &[0])); + // Another vote of the committee, and another committee's same vote. + assert!(!pool.is_covered(3, other.hash_tree_root(), 0, &[0])); + assert!(!pool.is_covered(3, data.hash_tree_root(), 1, &[0])); + + // A set a later one covers is dropped, so the record stays small. + for extra in 2..40 { + let attesters: Vec = (0..=extra).collect(); + pool.note_broadcast(&data, 0, &attesters); + } + let key = (3, data.hash_tree_root(), 0); + assert_eq!(pool.broadcast[&key].len(), 1); + // Disjoint sets are capped. + for attester in 100..140 { + pool.note_broadcast(&data, 0, &[attester]); + } + assert_eq!(pool.broadcast[&key].len(), MAX_BROADCAST_SETS); + } } diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 1b7d49f84..3013d660c 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -25,7 +25,7 @@ use ethlambda_types::{ bits_is_subset, validator_indices, }, beacon::{ - config::Config, + config::{Config, GasLimitSchedule}, constants::NUM_BLOCK_TIMELINESS_DEADLINES, containers::{ BeaconState, Checkpoint as BeaconCheckpoint, DataColumnSidecar, SignedBeaconBlock, @@ -126,7 +126,65 @@ impl ForkCheckpoints { /// configuration can still compare it against a wall clock. const KEY_TIME: &[u8] = b"time"; /// Key for "config" field of the Store. Its value has type [`Config`] and it's SSZ-encoded. +/// +/// Every key added to `Config` after [`DB_VERSION`] 10 takes zero bytes in this +/// row's encoding and lives in a row of its own instead: see [`CONFIG_ROWS`]. const KEY_CONFIG: &[u8] = b"config"; + +/// A `Config` key stored in a `Metadata` row of its own, outside +/// [`KEY_CONFIG`]'s encoding. +/// +/// `KEY_CONFIG` holds a positional SSZ container, which has no notion of a +/// missing key: a field added to it leaves every row written before it +/// undecodable, so each one used to cost a [`DB_VERSION`] bump and a resync of +/// every data directory. A key with a row of its own does not: +/// - **an older directory** has no row, which [`Store::fill_missing_config_keys`] +/// reports and a beacon resume fills from the config file, then writes, instead +/// of failing; +/// - **an older build** never looks for the row, and still decodes `KEY_CONFIG`, +/// since the key's field takes zero bytes there. +/// +/// So a new `Config` key gets an entry in [`CONFIG_ROWS`], a zero-width field +/// encoding inside `Config`, and a row codec of its own. Its zero-width decode +/// must give the value `Config::lean` holds: a lean resume never fills a +/// missing row, so a lean directory that predates the key runs on that decode. +struct ConfigRow { + /// The key's name in a `config.yaml`, for logs. + name: &'static str, + /// Its `Metadata` key. + key: &'static [u8], + /// The field's value, as its row stores it. + encode: fn(&Config) -> Vec, + /// Decode a row into the field. + decode: fn(&[u8], &mut Config) -> Result<(), libssz::DecodeError>, + /// Copy the field from the first config into the second. + copy: fn(&Config, &mut Config), +} + +/// Every [`ConfigRow`], in no particular order. +const CONFIG_ROWS: &[ConfigRow] = &[ConfigRow { + name: "GAS_LIMIT_SCHEDULE", + key: b"config_gas_limit_schedule", + encode: |config| config.gas_limit_schedule.to_row_ssz(), + decode: |bytes, config| { + config.gas_limit_schedule = GasLimitSchedule::from_row_ssz(bytes)?; + Ok(()) + }, + copy: |from, into| into.gas_limit_schedule = from.gas_limit_schedule.clone(), +}]; + +/// The `Metadata` entries that store `config`: [`KEY_CONFIG`] and every +/// [`CONFIG_ROWS`] row. Written together, so the rows can never describe two +/// different configs. +fn config_entries(config: &Config) -> Vec<(Vec, Vec)> { + let rows = CONFIG_ROWS + .iter() + .map(|row| (row.key.to_vec(), (row.encode)(config))); + std::iter::once((KEY_CONFIG.to_vec(), config.to_ssz())) + .chain(rows) + .collect() +} + /// Key for "head" field of the Store. Its value has type [`H256`] and it's SSZ-encoded. const KEY_HEAD: &[u8] = b"head"; /// Key for "safe_target" field of the Store. Its value has type [`H256`] and it's SSZ-encoded. @@ -226,16 +284,23 @@ const KEY_STATES_PRUNED_BELOW: &[u8] = b"states_pruned_below"; /// same policy every previous change followed. /// /// 8 widened `Config` with the EIP-8483 and PQ fork versions and epochs, -/// `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY` and -/// `ATTESTATION_SUBNET_COUNT_PQ`, so a directory written by +/// `UNREGISTERED_VALIDATOR_WITHDRAWABILITY_DELAY`, PQ's aggregation timing +/// (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, `AGGREGATOR_DELAY_BPS`) +/// and `ATTESTATION_SUBNET_COUNT_PQ`, so a directory written by /// version 7 decodes into the wrong fields, the same consequence as 3, 4 and /// 6. /// -/// 9 narrowed `Config` again: the PQ aggregation timing keys of consensus-specs -/// `4595f0fc` (`AGGREGATION_CUTOFF_BPS`, `AGGREGATE_DUE_BPS_PQ`, -/// `AGGREGATOR_DELAY_BPS`) left with the move back to `2f43bc0f`, so a -/// directory a version 8 build wrote with them decodes into the wrong fields. -pub const DB_VERSION: u64 = 9; +/// 9 (pq-devnet-0) narrowed `Config` again: the PQ aggregation timing keys of +/// consensus-specs `4595f0fc` left with the move back to `2f43bc0f`. +/// +/// 10 (pq-devnet-1) puts them back, so a directory version 9 wrote decodes +/// into the wrong fields. Not 8 again, although the layout is 8's: a number +/// stands for one history, and nothing should read a version 9 directory as +/// the version before it. +/// +/// A `Config` key added since 10 needs no bump: it gets a row of its own (see +/// `ConfigRow`), which a directory written before it simply lacks. +pub const DB_VERSION: u64 = 10; /// The consensus protocol a data directory holds. /// @@ -1520,11 +1585,20 @@ impl Store { .expect("read anchor slot") .expect("a versioned directory always carries an anchor slot"); - ( - Config::from_ssz_bytes(&bytes).expect("valid config"), - chain, - anchor_slot, - ) + let mut config = Config::from_ssz_bytes(&bytes).expect("valid config"); + // A key whose row is absent stays as `KEY_CONFIG` decoded it + // (empty): the directory predates it, and a resume fills it from + // the config file (`fill_missing_config_keys`). + for row in CONFIG_ROWS { + let Some(bytes) = view.get(Table::Metadata, row.key).expect("get config row") + else { + continue; + }; + (row.decode)(&bytes, &mut config) + .unwrap_or_else(|err| panic!("invalid {} row: {err:?}", row.name)); + } + + (config, chain, anchor_slot) }; info!(?chain, anchor_slot, "Loaded store from persisted DB state"); @@ -1817,7 +1891,7 @@ impl Store { let mut batch = backend.begin_write().expect("write batch"); // Metadata - let metadata_entries = vec![ + let mut metadata_entries = vec![ (KEY_DB_VERSION.to_vec(), DB_VERSION.to_ssz()), (KEY_CHAIN.to_vec(), vec![Chain::Lean.selector()]), (KEY_PRESET.to_vec(), vec![Preset::active().selector()]), @@ -1825,13 +1899,13 @@ impl Store { // millisecond, so the value that means "the clock has not // advanced past genesis" is genesis itself. (KEY_TIME.to_vec(), runtime_config.genesis_time_ms().to_ssz()), - (KEY_CONFIG.to_vec(), runtime_config.to_ssz()), (KEY_HEAD.to_vec(), anchor_block_root.to_ssz()), (KEY_SAFE_TARGET.to_vec(), anchor_block_root.to_ssz()), (KEY_LATEST_JUSTIFIED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_LATEST_FINALIZED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_ANCHOR_SLOT.to_vec(), anchor_slot.to_ssz()), ]; + metadata_entries.extend(config_entries(&runtime_config)); batch .put_batch(Table::Metadata, metadata_entries) .expect("put metadata"); @@ -1931,7 +2005,7 @@ impl Store { // and the finalized slot it is advancing *past*, so both chains have // to start with those rows present rather than have that one writer // grow an absent-key branch. - let metadata_entries = vec![ + let mut metadata_entries = vec![ (KEY_DB_VERSION.to_vec(), DB_VERSION.to_ssz()), (KEY_CHAIN.to_vec(), vec![Chain::Beacon.selector()]), (KEY_PRESET.to_vec(), vec![Preset::active().selector()]), @@ -1940,7 +2014,6 @@ impl Store { // anchor's own time; the seed matters only for the window before // it does. (KEY_TIME.to_vec(), runtime_config.genesis_time_ms().to_ssz()), - (KEY_CONFIG.to_vec(), runtime_config.to_ssz()), (KEY_HEAD.to_vec(), anchor_block_root.to_ssz()), (KEY_LATEST_JUSTIFIED.to_vec(), anchor_checkpoint.to_ssz()), (KEY_LATEST_FINALIZED.to_vec(), anchor_checkpoint.to_ssz()), @@ -1954,6 +2027,7 @@ impl Store { ), (KEY_ANCHOR_SLOT.to_vec(), anchor_slot.to_ssz()), ]; + metadata_entries.extend(config_entries(&runtime_config)); let mut batch = backend.begin_write().expect("write batch"); batch @@ -2212,10 +2286,42 @@ impl Store { Arc::get_mut(&mut self.config).is_some(), "replace_config needs the only handle to the cached config" ); - self.set_metadata(KEY_CONFIG, &config); + // `KEY_CONFIG` and every `CONFIG_ROWS` row, in one commit; this is also + // what adds a row the directory predates. + let mut batch = self.backend.begin_write().expect("write batch"); + batch + .put_batch(Table::Metadata, config_entries(&config)) + .expect("put config"); + batch.commit().expect("commit"); self.config = Arc::new(config); } + /// This store's config with every key the directory predates taken from + /// `supplied`, plus those keys' names. + /// + /// A predated key is a `ConfigRow` with no row in this directory. Its + /// field holds whatever [`Store::from_db_state`] left there (empty), which + /// is not a value this directory ever recorded. So the caller should + /// compare the returned config, not [`Store::config`], against the config + /// file, then hand the file's to [`Store::replace_config`] to write the + /// missing rows. Reads only. + pub fn fill_missing_config_keys(&self, supplied: &Config) -> (Config, Vec<&'static str>) { + let view = self.backend.begin_read().expect("read view"); + let mut config = (*self.config).clone(); + let mut missing = Vec::new(); + for row in CONFIG_ROWS { + if view + .get(Table::Metadata, row.key) + .expect("get config row") + .is_none() + { + (row.copy)(supplied, &mut config); + missing.push(row.name); + } + } + (config, missing) + } + /// Which consensus protocol this data directory holds. /// /// Infallible for the same reason [`Store::config`] is: fixed at bootstrap @@ -9263,6 +9369,106 @@ mod tests { assert_eq!(store.head().expect("head"), anchor.root); } + /// A beacon directory over `config`, as `init_beacon` writes one. + fn beacon_directory(config: Config) -> Arc { + let backend = Arc::new(InMemoryBackend::new()); + let anchor = BeaconCheckpoint { + epoch: 0, + root: H256::from([1u8; 32]), + }; + Store::init_beacon( + backend.clone(), + 1_606_824_023, + config, + anchor.root, + Store::beacon_checkpoint_as_stored(anchor), + 0, + ); + backend + } + + fn scheduled_config() -> Config { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + let mut config = Config::mainnet(); + config.gas_limit_schedule = vec![GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }] + .into(); + config + } + + /// Every `CONFIG_ROWS` key is written at bootstrap and read back on a + /// resume, and none is reported missing. + #[test] + fn a_config_key_stored_in_its_own_row_is_read_back() { + let scheduled = scheduled_config(); + let backend = beacon_directory(scheduled.clone()); + + let store = Store::from_db_state(backend).unwrap().unwrap(); + + assert_eq!( + store.config().gas_limit_schedule, + scheduled.gas_limit_schedule + ); + let (filled, missing) = store.fill_missing_config_keys(&Config::mainnet()); + assert!(missing.is_empty(), "{missing:?}"); + assert_eq!(filled.gas_limit_schedule, scheduled.gas_limit_schedule); + + // An empty schedule (mainnet's, Hoodi's) is written as a row too, so + // every later resume finds it rather than adding it again. + let unscheduled = Store::from_db_state(beacon_directory(Config::mainnet())) + .unwrap() + .unwrap(); + let (filled, missing) = unscheduled.fill_missing_config_keys(&scheduled); + assert!(missing.is_empty(), "{missing:?}"); + assert!(filled.gas_limit_schedule.is_empty()); + } + + /// A directory written before a key's row existed loads, reports the key + /// missing, and takes its value from the supplied config. Its `config` + /// row is the same bytes an older build wrote and reads. + #[test] + fn a_directory_that_predates_a_config_row_reports_the_key_missing() { + let scheduled = scheduled_config(); + let backend = beacon_directory(scheduled.clone()); + let config_row = backend + .begin_read() + .unwrap() + .get(Table::Metadata, KEY_CONFIG) + .unwrap() + .expect("config row"); + assert_eq!( + config_row, + Config::mainnet().to_ssz(), + "the config row does not carry the schedule" + ); + let mut batch = backend.begin_write().unwrap(); + let keys = CONFIG_ROWS.iter().map(|row| row.key.to_vec()).collect(); + batch.delete_batch(Table::Metadata, keys).unwrap(); + batch.commit().unwrap(); + + let mut store = Store::from_db_state(backend.clone()).unwrap().unwrap(); + assert!(store.config().gas_limit_schedule.is_empty()); + let (filled, missing) = store.fill_missing_config_keys(&scheduled); + assert_eq!(missing, ["GAS_LIMIT_SCHEDULE"]); + assert_eq!(filled, scheduled); + + // What a resume does next: the file's config, rows included. + store.replace_config(scheduled.clone()); + let reopened = Store::from_db_state(backend).unwrap().unwrap(); + assert_eq!( + reopened.config().gas_limit_schedule, + scheduled.gas_limit_schedule + ); + assert!( + reopened + .fill_missing_config_keys(&Config::mainnet()) + .1 + .is_empty() + ); + } + #[test] fn a_store_hands_back_the_runtime_config_it_persisted() { let backend = Arc::new(InMemoryBackend::new()); diff --git a/crates/validator/src/aggregation.rs b/crates/validator/src/aggregation.rs index e9a66dc78..d18ac2c49 100644 --- a/crates/validator/src/aggregation.rs +++ b/crates/validator/src/aggregation.rs @@ -34,6 +34,7 @@ use std::collections::BTreeMap; use std::sync::Arc; +use std::time::SystemTime; use ethlambda_types::beacon::containers::electra; use ethlambda_types::beacon::containers::gloas; @@ -49,6 +50,7 @@ use crate::beacon_node::{AggregateKind, BeaconNodeApi, SignedAggregates}; use crate::error::{Error, Result}; use crate::keys::ValidatorStore; use crate::signing::{AggregateAndProofRef, SigningContext, sign_all}; +use crate::slot_clock::SlotClock; /// An `AggregateAndProof` of either fork, held between building it and /// signing it. @@ -94,27 +96,63 @@ impl AggregationService { /// "Broadcast aggregate"). There is no selection proof, and the proof of /// the attesters' signatures is the node's: it collects them and proves /// ahead, since proving takes seconds. + /// + /// The aggregators are staggered by seat: the one at `position` publishes + /// at `get_aggregate_due_ms(position)`. Each seat waits for its own time + /// and then runs on its own, beside the others: the node may hold a + /// seat's request for seconds while a proof is still being made, and a + /// seat served in turn behind it would publish that much late, into the + /// seats after it. The node answers 404 for an aggregate one already + /// broadcast covers (`should_broadcast_aggregate`), which skips it here. pub async fn aggregate_pq( &self, + clock: &SlotClock, slot: Slot, data: &AttestationData, duties: &[AttesterDutyDto], ) -> Result { - use ethlambda_types::beacon::constants::LEAF_OFFSET_AGGREGATE_AND_PROOF; - use ethlambda_types::beacon::containers::pq; - - let selected: Vec<&AttesterDutyDto> = duties + let mut by_seat: BTreeMap> = BTreeMap::new(); + for duty in duties .iter() .filter(|duty| duty.is_aggregator == Some(true)) - .collect(); - if selected.is_empty() { - return Ok(0); + { + by_seat + .entry(duty.aggregator_position.unwrap_or(0)) + .or_default() + .push(duty); } + let seats = by_seat.into_iter().map(|(position, seated)| async move { + let due = clock.pq_aggregation_time(slot, position); + let wait = due.duration_since(SystemTime::now()).unwrap_or_default(); + tokio::time::sleep(wait).await; + self.publish_pq_seat(slot, data, &seated) + .await + .inspect_err(|err| { + warn!(%slot, position, %err, "Failed to publish this seat's PQ aggregates") + }) + .unwrap_or(0) + }); + Ok(futures_util::future::join_all(seats) + .await + .into_iter() + .sum()) + } + + /// Fetch, sign and publish the aggregates of the aggregators `selected`, + /// all at one seat of their committees' aggregation committees. + async fn publish_pq_seat( + &self, + slot: Slot, + data: &AttestationData, + selected: &[&AttesterDutyDto], + ) -> Result { + use ethlambda_types::beacon::constants::LEAF_OFFSET_AGGREGATE_AND_PROOF; + use ethlambda_types::beacon::containers::pq; // One fetch per committee, as for the other forks. let data_root = data.hash_tree_root(); let mut aggregates = BTreeMap::new(); - for duty in &selected { + for duty in selected { if aggregates.contains_key(&duty.committee_index) { continue; } @@ -126,13 +164,14 @@ impl AggregationService { Ok(aggregate) => { aggregates.insert(duty.committee_index, aggregate); } - // The node proved nothing for the committee: no votes reached - // it, or the proof missed the aggregate deadline. - Err(Error::BeaconNodeStatus { status: 404, body }) => warn!( + // A 404 also when another aggregator's broadcast already + // covers every attester: nothing to publish, as the + // specification has it. The node's message says which. + Err(Error::BeaconNodeStatus { status: 404, body }) => info!( %slot, committee = duty.committee_index, reason = %body, - "No PQ aggregate available for this committee" + "No PQ aggregate to publish for this committee" ), Err(err) => warn!( %slot, @@ -144,7 +183,7 @@ impl AggregationService { } let mut owed = Vec::new(); - for duty in &selected { + for duty in selected { let Some(proven) = aggregates.get(&duty.committee_index) else { continue; }; @@ -457,6 +496,52 @@ mod tests { } } + /// Each PQ seat asks for its aggregate at its own time. The node holds a + /// request while a proof is still being made, here for three seconds: + /// the next seat, due 0.6 s after the first, must not wait behind it. + #[tokio::test(start_paused = true)] + async fn a_slow_answer_for_one_pq_seat_does_not_delay_the_next() { + use std::time::{Duration, UNIX_EPOCH}; + + let held = Duration::from_secs(3); + let node = Arc::new(MockBeaconNode::new().with_pq_aggregate_delay(held)); + let service = AggregationService::new(node.clone(), context()); + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 0); + // Slot 64 began within the last second. + let slot = 64; + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + let clock = SlotClock::from_config(now.as_secs() - slot * 12, &config); + let (_, pubkey) = store(); + let seat = |position: u64| AttesterDutyDto { + is_aggregator: Some(true), + aggregator_position: Some(position), + // A committee each, so each seat has its own request. + ..duty(&pubkey, position, slot, position) + }; + + let started = tokio::time::Instant::now(); + let published = service + .aggregate_pq(&clock, slot, &data(slot), &[seat(0), seat(1)]) + .await + .expect("a 404 is no error"); + assert_eq!(published, 0, "the mock proves no aggregate"); + + let calls = node.pq_aggregate_calls(); + assert_eq!(calls.len(), 2); + let (first, second) = (calls[0].0 - started, calls[1].0 - started); + // 7.2 s and 7.8 s into the slot, less the fraction of a second the + // slot is already old. + assert!(first > Duration::from_millis(6_200) && first <= Duration::from_millis(7_200)); + let apart = second - first; + assert!( + apart > Duration::from_millis(550) && apart < Duration::from_millis(650), + "the second seat asked {apart:?} after the first" + ); + // Both answers were held three seconds, side by side. + let took = started.elapsed(); + assert!(took < first + held + Duration::from_secs(1), "{took:?}"); + } + fn duty( pubkey: &BlsPubkey, validator_index: u64, @@ -472,6 +557,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/attestation.rs b/crates/validator/src/attestation.rs index 39f59b89f..382826e80 100644 --- a/crates/validator/src/attestation.rs +++ b/crates/validator/src/attestation.rs @@ -283,23 +283,6 @@ impl AttestationService { to_sign.push((duty, pubkey)); } - // From PQ a leanXMSS signature at the target epoch's leaf, over the - // same signing root: the slashing protection record above already - // guards that leaf (one per target epoch). Those keys are derived from - // local keystores at startup and sign here, with no round trip, in - // parallel off this task, and each vote goes out as soon as it is - // signed rather than with the batch (see `publish_pq_as_signed`). - if is_pq { - let published = self - .publish_pq_as_signed(slot, &to_sign, &data, &data_dto, fork_name) - .await?; - return Ok(Attested { - published, - refused, - data: Some(data), - }); - } - // Signed concurrently rather than one after another. A local key // signs in microseconds either way; a remote signer costs a round // trip per signature, and a hundred validators behind one signer @@ -318,6 +301,14 @@ impl AttestationService { // a signer hangs every vote in it, a local key's too, is published // the full budget after the attestation offset (see // `SIGNING_BUDGET` for what that leaves before aggregation). + // + // From PQ the keys are leanXMSS ones derived from local keystores, + // and nothing is published whole: see `publish_pq_as_signed`. + if is_pq { + return self + .publish_pq_as_signed(slot, &to_sign, data, &data_dto, fork_name, refused) + .await; + } let signatures: Vec> = { let _timing = crate::metrics::time_signing(); @@ -384,30 +375,34 @@ impl AttestationService { }) } - /// Signs `to_sign`'s PQ votes over `data` and submits each as soon as it - /// is signed, rather than the batch once its slowest signature is done. - /// Returns how many the beacon node accepted. + /// The PQ fork's half of [`Self::attest_with`]: signs `to_sign`'s + /// attestations with leanXMSS at the target epoch's leaf, which the + /// slashing protection record already guards (one per target epoch), and + /// publishes each as soon as its signature exists. /// - /// A leanXMSS signature costs about 0.3 s of a core and varies several - /// fold from one to the next (see `pq::sign_batch`), so twenty of them - /// keep a host's cores busy for a second or more. Published whole, every - /// vote waited for the slowest; published as signed, the median vote goes - /// out about halfway through, as other clients' do. + /// Not once the batch is signed. The keys sign in parallel, so a batch + /// is normally a few signatures' time away, but a key that has to build a + /// bottom tree first takes seconds, and a vote held for it misses the + /// aggregators' cutoff with it: pq-devnet-0's clients published five to + /// ten seconds into the slot that way. A signature goes out with whatever + /// else was signed by the time it is picked up, so the requests are as + /// few as the signing is fast, and none waits for a slower key or for an + /// earlier request's answer. /// - /// A submission carries whatever was signed by the time the previous one - /// answered: the first vote alone, then the ones that came in meanwhile, - /// so a slow node costs fewer, larger requests rather than a queue of - /// small ones. A failed submission costs its own votes only; the slot's - /// error is returned only when none was accepted at all. + /// Failing every request is the error the batch's one request used to + /// be; failing some is logged, and the rest count as published. async fn publish_pq_as_signed( &self, slot: Slot, to_sign: &[(&AttesterDutyDto, BlsPubkey)], - data: &AttestationData, + data: AttestationData, data_dto: &AttestationDataOutDto, fork_name: &str, - ) -> Result { - let root = self.context.attestation_signing_root(data); + refused: usize, + ) -> Result { + use futures_util::stream::{FuturesUnordered, StreamExt as _}; + + let root = self.context.attestation_signing_root(&data); let leaf = crate::pq::attestation_leaf(data.target.epoch); let requests = to_sign .iter() @@ -417,81 +412,100 @@ impl AttestationService { root, }) .collect(); - // Until the last signature exists, not the last submission, so the - // histogram still reads as the time the duty's signing took. + // Observed when the last signature is in, as the batch's timing was. let mut timing = Some(crate::metrics::time_signing()); - let mut signed = crate::pq::sign_streamed(requests); - - let mut ready = Vec::with_capacity(to_sign.len()); - let mut answered = 0; - let mut published = 0; + let mut signed = crate::pq::sign_each(requests); + let mut requests_out = FuturesUnordered::new(); + let (mut answered, mut submitted, mut published) = (0usize, 0usize, 0usize); let mut failure = None; - while signed.recv_many(&mut ready, to_sign.len()).await > 0 { - answered += ready.len(); - if answered >= to_sign.len() { - timing.take(); - } - let mut attestations = Vec::with_capacity(ready.len()); - for (position, signature) in ready.drain(..) { - let (duty, _) = &to_sign[position]; - match signature { - Ok(signature) => attestations.push(SingleAttestationDto { - committee_index: duty.committee_index, - attester_index: duty.validator_index, - data: data_dto.clone(), - signature: encode_hex(&signature.0), - }), - // One validator failing must not cost the others their - // attestation. - Err(err) => { - error!(%slot, validator = duty.validator_index, %err, "Failed to sign attestation"); - crate::metrics::inc_signing_failures(); + loop { + tokio::select! { + next = signed.recv(), if timing.is_some() => { + let Some(first) = next else { + timing = None; + continue; + }; + let mut ready = vec![first]; + while let Ok(more) = signed.try_recv() { + ready.push(more); } - } - } - if attestations.is_empty() { - continue; - } - - let submitted = attestations.len(); - let pending = to_sign.len() - answered; - match self - .beacon_node - .submit_attestations(&attestations, fork_name) - .await - { - Ok(accepted) => { - if accepted < submitted { - warn!( - %slot, - published = accepted, - submitted, - "Some attestations in this slot's batch were rejected by the beacon node" - ); + answered += ready.len(); + let attestations: Vec = ready + .into_iter() + .filter_map(|(position, signature)| { + let (duty, _) = to_sign[position]; + // One validator failing must not cost the others + // their attestation. + let signature = signature + .inspect_err(|err| { + error!(%slot, validator = duty.validator_index, %err, "Failed to sign attestation"); + crate::metrics::inc_signing_failures(); + }) + .ok()?; + Some(SingleAttestationDto { + committee_index: duty.committee_index, + attester_index: duty.validator_index, + data: data_dto.clone(), + signature: encode_hex(&signature.0), + }) + }) + .collect(); + if attestations.is_empty() { + continue; } - info!(%slot, count = accepted, pending, "Published attestations"); - crate::metrics::inc_attestations_published(accepted as u64); - self.observe_vote_delays(slot, accepted); - published += accepted; - } - Err(err) => { - warn!(%slot, count = submitted, pending, %err, "Failed to submit some of this slot's attestations"); - failure = Some(err); + submitted += attestations.len(); + requests_out.push(async move { + self.beacon_node + .submit_attestations(&attestations, fork_name) + .await + }); } + Some(answer) = requests_out.next(), if !requests_out.is_empty() => match answer { + Ok(count) => { + published += count; + self.observe_vote_delays(slot, count); + } + Err(err) => { + warn!(%slot, %err, "Failed to publish some of this slot's attestations"); + failure = Some(err); + } + }, + else => break, } } - if answered < to_sign.len() { - let missing = to_sign.len() - answered; - error!(%slot, missing, "The PQ signing task stopped before every attestation was signed"); - for _ in 0..missing { - crate::metrics::inc_signing_failures(); - } + // The signing task died before answering for these. + let unsigned = to_sign.len() - answered; + error!(%slot, unsigned, "The PQ signing task ended before signing every attestation"); + crate::metrics::inc_signing_failures_by(unsigned as u64); } - match failure { - Some(err) if published == 0 => Err(err), - _ => Ok(published), + if submitted == 0 { + return Ok(Attested { + published: 0, + refused, + data: Some(data), + }); } + if published == 0 + && let Some(err) = failure + { + return Err(err); + } + if published < submitted { + warn!( + %slot, + published, + submitted, + "Some attestations in this slot's batch were rejected by the beacon node" + ); + } + info!(%slot, count = published, "Published attestations"); + crate::metrics::inc_attestations_published(published as u64); + Ok(Attested { + published, + refused, + data: Some(data), + }) } /// One delay observation per vote the node accepted just now, from the @@ -562,6 +576,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } @@ -861,6 +876,58 @@ mod tests { assert_eq!(data.target.epoch, 3); } + /// At a PQ slot each attestation is published as soon as it is signed: + /// every one exactly once, however many requests that took, with a + /// leanXMSS signature, and a validator whose signature fails costs only + /// its own vote. + #[tokio::test] + async fn pq_attestations_are_each_published_once_and_a_failure_costs_one_vote() { + use ethlambda_types::beacon::fork::ForkName; + + let mut keyless_secret = secret(); + keyless_secret[31] ^= 0x02; + let mut store = ValidatorStore::new(); + let first = store.insert_secret("first", &secret()).expect("inserts"); + let second = store + .insert_secret("second", &other_secret()) + .expect("inserts"); + let keyless = store + .insert_secret("keyless", &keyless_secret) + .expect("inserts"); + // A PQ client derives a leanXMSS key for each local key at startup. + // The third never got one, so its signature fails. + crate::pq::derive_and_register(first, &secret(), 0, None); + crate::pq::derive_and_register(second, &other_secret(), 0, None); + let store = RwLock::new(store); + + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 0); + let context = Arc::new(SigningContext::new(config, Root::ZERO)); + let node = Arc::new(MockBeaconNode::new().with_attestation_data(96)); + let service = + AttestationService::new(node.clone(), context, SlashingProtection::in_memory()); + let duties = [ + duty(&encode_hex(&first.0), 11, 96, 3), + duty(&encode_hex(&second.0), 12, 96, 3), + duty(&encode_hex(&keyless.0), 13, 96, 3), + ]; + + let attested = service.attest(96, &duties, &store).await.expect("attests"); + + assert_eq!(attested.published, 2); + assert_eq!(attested.data.expect("data").slot, 96); + let submitted = node.submitted(); + let mut attesters: Vec = submitted.iter().map(|vote| vote.attester_index).collect(); + attesters.sort_unstable(); + assert_eq!( + attesters, + vec![11, 12], + "each signed vote once, the unsigned one never" + ); + let hex_len = 2 + 2 * ethlambda_crypto::lean_xmss::SIGNATURE_SIZE; + assert!(submitted.iter().all(|vote| vote.signature.len() == hex_len)); + assert_eq!(node.last_submitted_fork_name().as_deref(), Some("pq")); + } + /// With no duty there is nothing to fetch, so there is no data either. /// A zeroed default here would have the aggregation duty ask for the /// aggregate of an attestation nobody made. diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index bbdd19f6b..662f3c771 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -28,7 +28,7 @@ //! two of the endpoints used here, but no implementation exercises it: see the //! design document's "Wire format" section for the evidence. -use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::config::{Config, GasLimitSchedule}; use ethlambda_types::beacon::containers::electra::{ AggregationBits, Attestation, CommitteeBits, SignedAggregateAndProof, }; @@ -41,6 +41,8 @@ use ethlambda_types::beacon::primitives::{ }; use libssz::SszDecode as _; use serde::{Deserialize, Serialize}; +use std::sync::atomic::{AtomicBool, Ordering}; +use tracing::{debug, warn}; use crate::error::{Error, Result}; @@ -59,6 +61,20 @@ pub mod quoted_u64 { } } +/// An optional quoted 64-bit integer: absent (or `null`) is `None`. Used with +/// `#[serde(default)]` so a field older nodes do not send is simply missing. +pub mod quoted_u64_option { + use serde::{Deserialize as _, Deserializer}; + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|text| text.parse().map_err(serde::de::Error::custom)) + .transpose() + } +} + /// A list of 64-bit integers, each quoted, as `validator_sync_committee_indices` /// and `sync_committee_indices` carry them. pub mod quoted_u64_vec { @@ -218,6 +234,12 @@ pub struct AttesterDutyDto { /// before PQ, where aggregators select themselves with a BLS proof. #[serde(default)] pub is_aggregator: Option, + /// A PQ aggregator's index in its aggregation committee, which staggers + /// its broadcast (`get_aggregate_due_ms(position)`, PQ `validator.md`). + /// Absent from a node that does not send it, which is read as the first + /// seat: the earliest time, and the one gloas-style nodes assume. + #[serde(default, with = "quoted_u64_option")] + pub aggregator_position: Option, } /// One proposer duty, from `GET /eth/v1/validator/duties/proposer/{epoch}`. @@ -550,7 +572,10 @@ fn spec_u64(value: &serde_json::Value, key: &str) -> Result> { /// separately, by [`crate::adopt_preset`]. /// /// Only the keys read below are overridden: the slot length, the duty -/// offsets, `SHARD_COMMITTEE_PERIOD` and the fork schedule. Every other +/// offsets, `SHARD_COMMITTEE_PERIOD`, the fork schedule and +/// `GAS_LIMIT_SCHEDULE`. An absent or unusable `GAS_LIMIT_SCHEDULE` is an +/// empty schedule, which leaves the default gas limit to `DEFAULT_GAS_LIMIT`, +/// rather than an error (see [`gas_limit_schedule_of`]). Every other /// `Config` field is mainnet's whatever the node reports, so code in this /// crate that starts reading one has to read its key here first. /// @@ -653,6 +678,11 @@ pub fn config_from_spec_response(value: &serde_json::Value) -> Result { "PAYLOAD_ATTESTATION_DUE_BPS", &mut config.payload_attestation_due_bps, ), + // PQ's staggered aggregators. Absent keeps the specification's + // defaults (4000, 6000, 500). + ("AGGREGATION_CUTOFF_BPS", &mut config.aggregation_cutoff_bps), + ("AGGREGATE_DUE_BPS_PQ", &mut config.aggregate_due_bps_pq), + ("AGGREGATOR_DELAY_BPS", &mut config.aggregator_delay_bps), ] { if let Some(bps) = spec_u64(value, key)? { *field = bps; @@ -681,10 +711,53 @@ pub fn config_from_spec_response(value: &serde_json::Value) -> Result { config = config.with_fork_version(fork, version); } } + // After the loop: the schedule's rules read the gloas epoch. + config.gas_limit_schedule = gas_limit_schedule_of(value, config.gloas_fork_epoch); Ok(config) } +/// `GAS_LIMIT_SCHEDULE`: the default gas limit, per epoch, when `--gas-limit` +/// names none. +/// +/// Empty when the node does not serve it, or serves `null` (how Go's JSON +/// encoder writes a nil slice), which falls back to `DEFAULT_GAS_LIMIT`. Also +/// empty, with a warning, when the node serves one this client cannot decode +/// or that breaks [`GasLimitSchedule::check_rules`]: the schedule only names +/// a default and identifies no chain, so it is no reason to stop using the +/// node. +/// +/// The warning is given once per process; any later one is at `debug`. +fn gas_limit_schedule_of(value: &serde_json::Value, gloas_fork_epoch: Epoch) -> GasLimitSchedule { + static WARNED: AtomicBool = AtomicBool::new(false); + let Some(field) = value + .get("GAS_LIMIT_SCHEDULE") + .filter(|field| !field.is_null()) + else { + return GasLimitSchedule::default(); + }; + // serde's message can quote the node's own text, so it is written out + // and bounded like every other JSON decode error from a node. + let schedule = serde_json::from_value::(field.clone()) + .map_err(|err| super::http::decode_text(&err)) + .and_then(|schedule| { + let checked = schedule.check_rules(gloas_fork_epoch); + checked.map(|()| schedule).map_err(|err| err.to_string()) + }); + schedule.unwrap_or_else(|detail| { + if WARNED.swap(true, Ordering::Relaxed) { + debug!(%detail, "Ignoring a GAS_LIMIT_SCHEDULE a beacon node serves"); + } else { + warn!( + %detail, + "A beacon node serves a GAS_LIMIT_SCHEDULE this client cannot use; ignoring it, \ + so the default gas limit comes from another node or DEFAULT_GAS_LIMIT" + ); + } + GasLimitSchedule::default() + }) +} + impl TryFrom<&AttestationDto> for Attestation { type Error = Error; @@ -1140,6 +1213,44 @@ mod tests { assert_eq!(config.payload_attestation_due_bps, 7_500); } + #[test] + fn the_pq_aggregation_offsets_are_read_and_default_to_the_specification() { + let response = serde_json::json!({ + "AGGREGATION_CUTOFF_BPS": "3000", + "AGGREGATE_DUE_BPS_PQ": "5500", + "AGGREGATOR_DELAY_BPS": "400", + }); + let config = config_from_spec_response(&response).expect("builds"); + assert_eq!(config.aggregation_cutoff_bps, 3_000); + assert_eq!(config.aggregate_due_bps_pq, 5_500); + assert_eq!(config.aggregator_delay_bps, 400); + + let config = config_from_spec_response(&serde_json::json!({})).expect("builds"); + assert_eq!(config.aggregation_cutoff_bps, 4_000); + assert_eq!(config.aggregate_due_bps_pq, 6_000); + assert_eq!(config.aggregator_delay_bps, 500); + } + + #[test] + fn an_attester_dutys_aggregator_position_is_optional() { + let duty = |extra: serde_json::Value| { + let mut value = serde_json::json!({ + "pubkey": "0x00", "validator_index": "1", "committee_index": "2", + "committee_length": "3", "committees_at_slot": "4", + "validator_committee_index": "0", "slot": "5", + }); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value::(value).unwrap() + }; + assert_eq!(duty(serde_json::json!({})).aggregator_position, None); + let seated = duty(serde_json::json!({"is_aggregator": true, "aggregator_position": "2"})); + assert_eq!(seated.is_aggregator, Some(true)); + assert_eq!(seated.aggregator_position, Some(2)); + } + /// A node that has not moved to the basis-point form keeps the defaults, /// which are the right answer for every network that predates it. #[test] @@ -1233,6 +1344,91 @@ mod tests { assert!(matches!(err, Error::Decode(_)), "got {err:?}"); } + /// A spec response holding only `keys`, as quoted strings: on this + /// branch an absent key keeps its default. + fn spec_with(keys: &[(&str, &str)]) -> serde_json::Value { + let mut spec = serde_json::json!({}); + for (key, value) in keys { + spec[*key] = serde_json::Value::String((*value).to_string()); + } + spec + } + + /// The schedule in the shape a beacon node serves it (this one's and + /// lighthouse's), looked up at the proposal's epoch; a node that does not + /// serve the key, or serves it empty, schedules nothing. + #[test] + fn the_gas_limit_schedule_is_read_and_defaults_to_empty() { + // A complete response with `GAS_LIMIT_SCHEDULE` set to `schedule`, + // gloas at Sepolia's epoch so the entries are not before it. + let serving = |schedule: serde_json::Value| { + let mut response = spec_with(&[ + ("GLOAS_FORK_EPOCH", "353024"), + ("GLOAS_FORK_VERSION", "0x90000075"), + ]); + response["GAS_LIMIT_SCHEDULE"] = schedule; + response + }; + + let response = serving(serde_json::json!([ + {"EPOCH": "353024", "GAS_LIMIT": "200000000"}, + {"EPOCH": "400000", "GAS_LIMIT": "300000000"}, + ])); + let config = config_from_spec_response(&response).expect("builds"); + let schedule = &config.gas_limit_schedule; + assert_eq!(schedule.entries().len(), 2); + assert_eq!(schedule.gas_limit_at(353_023), None); + assert_eq!(schedule.gas_limit_at(353_024), Some(200_000_000)); + assert_eq!(schedule.gas_limit_at(400_000), Some(300_000_000)); + + let config = config_from_spec_response(&spec_with(&[])).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + let response = serving(serde_json::json!([])); + let config = config_from_spec_response(&response).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + // Go's encoder writes a nil slice as `null`. + let response = serving(serde_json::Value::Null); + let config = config_from_spec_response(&response).expect("builds"); + assert!(config.gas_limit_schedule.is_empty()); + } + + /// A schedule the client cannot use is ignored, not an error: it only + /// names a default gas limit, so it must not cost the client the node. + /// That covers one that does not decode and one that breaks the rules a + /// beacon node holds its own to (gloas at epoch 100 here). + #[test] + fn an_unusable_gas_limit_schedule_is_ignored() { + let serving = |schedule: serde_json::Value| { + let mut response = spec_with(&[]); + response["GLOAS_FORK_EPOCH"] = serde_json::json!("100"); + response["GLOAS_FORK_VERSION"] = serde_json::json!("0x07000000"); + response["GAS_LIMIT_SCHEDULE"] = schedule; + response + }; + let unusable = [ + serde_json::json!("200000000"), + serde_json::json!([{"EPOCH": "100", "LIMIT": "200000000"}]), + serde_json::json!([ + {"EPOCH": "100", "GAS_LIMIT": "100000000"}, + {"EPOCH": "100", "GAS_LIMIT": "200000000"}, + ]), + serde_json::json!([{"EPOCH": "99", "GAS_LIMIT": "200000000"}]), + serde_json::json!([{"EPOCH": "100", "GAS_LIMIT": "0"}]), + ]; + for schedule in unusable { + let config = config_from_spec_response(&serving(schedule.clone())) + .unwrap_or_else(|err| panic!("{schedule}: {err:?}")); + assert!(config.gas_limit_schedule.is_empty(), "{schedule}"); + } + + let usable = serving(serde_json::json!([{"EPOCH": "100", "GAS_LIMIT": "200000000"}])); + let config = config_from_spec_response(&usable).expect("builds"); + assert_eq!( + config.gas_limit_schedule.gas_limit_at(100), + Some(200_000_000) + ); + } + #[test] fn a_sync_duty_parses_its_quoted_indices() { let duty: SyncDutyDto = serde_json::from_value(serde_json::json!({ diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 47db70f05..ce0e67da8 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -50,9 +50,10 @@ impl FallbackBeaconNode { Self { nodes } } - /// The nodes, in order, for a test outside this module that drives a + /// The nodes, in `--beacon-nodes` order: for a caller that must hear + /// every node rather than the first that answers (the gas limit schedule, + /// see [`crate::gas_limit_schedule`]), and for a test that drives a /// service through the fallback and then inspects each mock. - #[cfg(test)] pub(crate) fn nodes(&self) -> &[B] { &self.nodes } @@ -635,14 +636,15 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } - /// A 404 is a node that proved nothing for this committee: no votes for it - /// reached the node, or its proof missed the deadline. Another node may - /// still hold votes, so the walk goes on past it, but when every node - /// answered 404 that is the committee's answer, which comes back as the - /// last node's [`Error::BeaconNodeStatus`] for the caller to report with - /// the node's reason, rather than as every node failing. Any other failure - /// among them still warns here, since the node that failed may have held - /// the votes. + /// A 404 is a node with nothing to publish for this committee: it holds + /// no votes for it, or (the aggregators' later seats, every slot with two + /// of them) an aggregate already broadcast covers every attester this one + /// would. Another node may still hold votes, so the walk goes on past it, + /// but when every node answered 404 that is the committee's answer, which + /// comes back as the last node's [`Error::BeaconNodeStatus`] without the + /// missed-duty warning: the specification has the aggregator publish + /// nothing then. Any other failure among them still warns, since the node + /// that failed may have held the votes. async fn pq_aggregate( &self, slot: Slot, @@ -971,9 +973,10 @@ mod tests { assert_eq!(genesis.genesis_time, 1_606_824_023); } - /// Every node having no PQ aggregate is the committee's answer, so it comes - /// back as the 404 itself; a node that failed outright among them may have - /// held the votes, which is a failure. + /// Every node having no PQ aggregate is the committee's answer (a later + /// aggregator seat whose committee is already covered), so it comes back + /// as the 404 itself; a node that failed outright among them may have held + /// the votes, which is a failure. #[tokio::test] async fn a_pq_aggregate_no_node_holds_is_the_404_not_a_failure() { let fallback = FallbackBeaconNode::new(vec![MockBeaconNode::new(), MockBeaconNode::new()]); diff --git a/crates/validator/src/beacon_node/http.rs b/crates/validator/src/beacon_node/http.rs index e4bc57263..6dc2f87bb 100644 --- a/crates/validator/src/beacon_node/http.rs +++ b/crates/validator/src/beacon_node/http.rs @@ -119,6 +119,14 @@ fn error_text(text: &str) -> String { ethlambda_types::text::one_line(text, ERROR_TEXT_LIMIT) } +/// A JSON answer's decode error as [`error_text`] writes it. serde's message +/// can quote the node's own text, the whole of an unexpected string among +/// it, so it is bounded and written out like a failed answer's body before +/// it reaches an error and the log line that prints it. +pub(crate) fn decode_text(err: &serde_json::Error) -> String { + error_text(&err.to_string()) +} + /// [`read_error_body`] as [`error_text`] shows it. async fn error_body(response: reqwest::Response) -> String { error_text(&read_error_body(response).await) @@ -633,10 +641,11 @@ impl BeaconNodeApi for HttpBeaconNode { /// Fetches the network's configuration, as far as this client reads it. /// - /// The spec endpoint returns every configuration value as a quoted - /// string. Only the keys [`config_from_spec_response`] names are read - /// (the fork schedule, the slot duration, the duty offsets and - /// `SHARD_COMMITTEE_PERIOD`); the rest of `Config` keeps its mainnet + /// The spec endpoint returns every scalar configuration value as a quoted + /// string, and a schedule as a list of objects. Only the keys + /// [`config_from_spec_response`] names are read (the fork schedule, the + /// slot duration, the duty offsets, `SHARD_COMMITTEE_PERIOD` and + /// `GAS_LIMIT_SCHEDULE`); the rest of `Config` keeps its mainnet /// defaults, so nothing in this client may rely on those. async fn spec(&self) -> Result { let response: DataResponse = self.get("/eth/v1/config/spec").await?; diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index ac678bc68..e37545691 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -59,6 +59,8 @@ pub struct MockBeaconNode { /// When set, every method fails with this message, regardless of `failures`. pub fail_everything: Option, pub genesis: Option, + /// What `spec` answers; `Config::mainnet()` while unset. + pub spec: Mutex>, pub syncing: bool, /// Tracking a head its execution client has not validated. Separate from /// `syncing`, because the pair a real node can report and this client must @@ -196,6 +198,12 @@ pub struct MockBeaconNode { /// What `payload_attestation_data` answers with. `None` is the 204. pub payload_attestation_data: Option, pub payload_attestation_data_calls: Mutex, + /// How long `pq_aggregate` holds a request before answering, as a node + /// does while the proof asked for is still being made. + pub pq_aggregate_delay: std::time::Duration, + /// When each `pq_aggregate` call arrived and for which committee, in + /// arrival order. + pub pq_aggregate_calls: Mutex>, pub submitted_payload_attestations: Mutex>, /// The fork each `attestation_data` call named, in call order. pub attestation_data_forks: Mutex>, @@ -453,6 +461,17 @@ impl MockBeaconNode { *self.proposer_duties_v2_calls.lock().expect("lock") } + /// Answers `spec` with `config` rather than `Config::mainnet()`. + pub fn with_spec(self, config: Config) -> Self { + self.set_spec(config); + self + } + + /// What `spec` answers from now on. + pub fn set_spec(&self, config: Config) { + *self.spec.lock().expect("lock") = Some(config); + } + pub fn with_attestation_data(mut self, slot: Slot) -> Self { self.attestation_data = Some(AttestationData { slot, @@ -470,6 +489,17 @@ impl MockBeaconNode { self } + /// Hold every `pq_aggregate` request for `delay` before answering it. + pub fn with_pq_aggregate_delay(mut self, delay: std::time::Duration) -> Self { + self.pq_aggregate_delay = delay; + self + } + + /// When each `pq_aggregate` call arrived and for which committee. + pub fn pq_aggregate_calls(&self) -> Vec<(tokio::time::Instant, u64)> { + self.pq_aggregate_calls.lock().expect("lock").clone() + } + /// Answer `attestation_data` naming `root` as the head block. Over /// [`Self::with_attestation_data`], which names the zero root. pub fn with_attestation_block_root(mut self, root: Root) -> Self { @@ -945,7 +975,8 @@ impl BeaconNodeApi for MockBeaconNode { async fn spec(&self) -> Result { self.guard("spec")?; - Ok(Config::mainnet()) + let spec = self.spec.lock().expect("lock").clone(); + Ok(spec.unwrap_or_else(Config::mainnet)) } async fn is_optimistic_or_syncing(&self) -> Result { @@ -1286,8 +1317,13 @@ impl BeaconNodeApi for MockBeaconNode { &self, _slot: Slot, _attestation_data_root: Root, - _committee_index: u64, + committee_index: u64, ) -> Result { + self.pq_aggregate_calls + .lock() + .expect("lock") + .push((tokio::time::Instant::now(), committee_index)); + tokio::time::sleep(self.pq_aggregate_delay).await; self.guard("pq_aggregate")?; // What a node with nothing to publish for the committee answers. Err(Error::BeaconNodeStatus { diff --git a/crates/validator/src/duties.rs b/crates/validator/src/duties.rs index c2ff2ed61..1012b8c46 100644 --- a/crates/validator/src/duties.rs +++ b/crates/validator/src/duties.rs @@ -442,6 +442,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/gas_limit_schedule.rs b/crates/validator/src/gas_limit_schedule.rs new file mode 100644 index 000000000..be09b8087 --- /dev/null +++ b/crates/validator/src/gas_limit_schedule.rs @@ -0,0 +1,297 @@ +//! The network's `GAS_LIMIT_SCHEDULE` (EIP-8261), read off every beacon node. +//! +//! The schedule names the default gas limit of a validator with neither its +//! own override nor `--gas-limit` ([`ProposerSettings`]). It identifies no +//! chain, so no node is trusted over another for it, and a node that serves +//! none must not cost the client the schedule another node serves: the first +//! node in `--beacon-nodes` order that serves a non-empty one is taken. An +//! unusable schedule (one that does not decode, or breaks the rules a beacon +//! node holds its own config to) reads as empty, with a warning, in +//! [`crate::beacon_node::dto::config_from_spec_response`]. +//! +//! Read at startup, then again every epoch by [`run`], so a node that comes +//! up, or starts serving the key, after the client started is followed +//! without a restart. Without that, a client whose first node served no +//! schedule would sign the built-in 60M into every proposer preference until +//! restarted, pulling the gas limit away from the network's. +//! +//! A schedule once held is kept while the nodes that answer serve none: a node +//! restarted on a build that predates the key, or on a broken config, is far +//! likelier than a network dropping its schedule, and falling back to 60M is +//! exactly what this module exists to avoid. A node serving another non-empty +//! schedule replaces it. Preferences already signed keep the gas limit they +//! were signed with; each one signed after a change carries the new one. + +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use ethlambda_types::beacon::config::GasLimitSchedule; +use futures_util::future::join_all; +use tracing::{info, warn}; + +use crate::beacon_node::BeaconNodeApi; +use crate::beacon_node::fallback::FallbackBeaconNode; +use crate::proposer_settings::{DEFAULT_GAS_LIMIT, ProposerSettings, gas_limit_schedule_text}; +use crate::slot_clock::SlotClock; + +/// One round of asking every node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ScheduleRead { + /// How many nodes answered `/eth/v1/config/spec` at all. + pub answered: usize, + /// The first non-empty schedule in `--beacon-nodes` order, with that + /// node's position, or `None` when no node that answered serves one. + pub served: Option<(usize, GasLimitSchedule)>, +} + +/// Asks every node for its spec at once, so a node that hangs until its +/// request timeout delays the round by that timeout only, and takes the first +/// non-empty schedule in `nodes`' order. +pub(crate) async fn read(nodes: &[B]) -> ScheduleRead { + let answers = join_all(nodes.iter().map(|node| node.spec())).await; + let answered = answers.iter().filter(|answer| answer.is_ok()).count(); + let served = answers.into_iter().enumerate().find_map(|(node, answer)| { + let schedule = answer.ok()?.gas_limit_schedule; + (!schedule.is_empty()).then_some((node, schedule)) + }); + ScheduleRead { answered, served } +} + +/// What one [`ScheduleFollower::apply`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Applied { + /// No node answered: nothing changed. + NoAnswer, + /// A node served the schedule already held. + Unchanged, + /// A node served another schedule, now held and in the settings. + Took, + /// Nodes answered but none serves a schedule; whatever was held is kept. + /// `warned` when this read gave the warning, which is once per run of + /// such reads, and only while the schedule matters. + NoneServed { warned: bool }, +} + +/// The schedule the client holds, and what it has said about it. +pub(crate) struct ScheduleFollower { + settings: Arc, + held: GasLimitSchedule, + /// Whether an empty schedule changes what this client signs: gloas is + /// scheduled (the schedule applies only from it) and `--gas-limit` was + /// not given (which would override it). Only then is a missing schedule + /// worth a warning. + matters: bool, + /// Whether the warning for the current run of empty reads was given, so + /// it is given once per run rather than every epoch. + warned_empty: bool, +} + +impl ScheduleFollower { + pub(crate) fn new(settings: Arc, matters: bool) -> Self { + Self { + settings, + held: GasLimitSchedule::default(), + matters, + warned_empty: false, + } + } + + pub(crate) fn held(&self) -> &GasLimitSchedule { + &self.held + } + + /// Takes `read` into the proposer settings, logging a change, and warning + /// once when no node serves a schedule while one matters. + pub(crate) fn apply(&mut self, read: ScheduleRead) -> Applied { + let Some((node, schedule)) = read.served else { + // Nothing to go on when no node answered; when some did, none + // serves a schedule, and one held is kept (see the module doc). + if read.answered == 0 { + return Applied::NoAnswer; + } + let warn_now = self.matters && !self.warned_empty; + if warn_now { + self.warned_empty = true; + if self.held.is_empty() { + warn!( + answered = read.answered, + default_gas_limit = DEFAULT_GAS_LIMIT, + "No beacon node serves a usable GAS_LIMIT_SCHEDULE while gloas is \ + scheduled; validators without --gas-limit or their own gas limit \ + target the default until one does" + ); + } else { + warn!( + answered = read.answered, + kept = %gas_limit_schedule_text(&self.held), + "No beacon node serves a GAS_LIMIT_SCHEDULE any more; keeping the one \ + held" + ); + } + } + return Applied::NoneServed { warned: warn_now }; + }; + self.warned_empty = false; + if schedule == self.held { + return Applied::Unchanged; + } + info!( + node, + previous = %gas_limit_schedule_text(&self.held), + schedule = %gas_limit_schedule_text(&schedule), + "Took the gas limit schedule a beacon node serves; validators without --gas-limit \ + or their own gas limit target it" + ); + self.settings.set_gas_limit_schedule(schedule.clone()); + self.held = schedule; + Applied::Took + } +} + +/// How far into an epoch's first slot the schedule is read again: half a +/// slot, clear of the boundary's duties. +fn read_time(clock: &SlotClock, epoch_start_slot: u64) -> SystemTime { + clock.start_of(epoch_start_slot) + clock.slot_duration() / 2 +} + +/// Reads the schedule off every node once an epoch, for as long as the client +/// runs. Spawned by [`crate::run`] and aborted when it returns. +pub(crate) async fn run( + nodes: Arc>, + clock: SlotClock, + mut follower: ScheduleFollower, +) { + let slots_per_epoch = ethlambda_types::beacon::preset::slots_per_epoch(); + loop { + let now = SystemTime::now(); + // The next epoch's read; before genesis, epoch 0's. + let next_epoch = clock.current_epoch().map_or(0, |epoch| epoch + 1); + let at = read_time(&clock, next_epoch * slots_per_epoch); + let wait = at.duration_since(now).unwrap_or_default(); + tokio::time::sleep(wait.max(Duration::from_millis(100))).await; + follower.apply(read(nodes.nodes()).await); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::beacon_node::mock::MockBeaconNode; + use ethlambda_types::beacon::config::{Config, GasLimitScheduleEntry}; + use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32}; + + fn schedule(gas_limit: u64) -> GasLimitSchedule { + vec![GasLimitScheduleEntry { + epoch: 0, + gas_limit, + }] + .into() + } + + fn serving(gas_limit: u64) -> MockBeaconNode { + let mut config = Config::mainnet(); + config.gas_limit_schedule = schedule(gas_limit); + MockBeaconNode::new().with_spec(config) + } + + fn down() -> MockBeaconNode { + let node = MockBeaconNode::new(); + node.failures + .lock() + .expect("lock") + .insert("spec", "down".to_string()); + node + } + + fn follower() -> (ScheduleFollower, Arc) { + let settings = Arc::new(ProposerSettings::new(Bytes32::ZERO, None)); + (ScheduleFollower::new(settings.clone(), true), settings) + } + + const KEY: BlsPubkey = BlsPubkey([1; 48]); + + /// The review's case: the first node serves no schedule (or is down), + /// a later one does, and the later one's is taken rather than leaving + /// every preference at 60M. + #[tokio::test] + async fn the_first_node_that_serves_a_schedule_is_taken() { + let nodes = [MockBeaconNode::new(), down(), serving(200_000_000)]; + let read = read(&nodes).await; + assert_eq!(read.answered, 2); + assert_eq!(read.served, Some((2, schedule(200_000_000)))); + + let (mut follower, settings) = follower(); + assert_eq!(settings.gas_limit(&KEY, 0), DEFAULT_GAS_LIMIT); + assert_eq!(follower.apply(read), Applied::Took); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + } + + /// Order decides between two nodes that both serve one. + #[tokio::test] + async fn the_earlier_node_wins_when_several_serve_one() { + let nodes = [serving(100_000_000), serving(200_000_000)]; + assert_eq!(read(&nodes).await.served, Some((0, schedule(100_000_000)))); + } + + /// A node that starts serving the schedule after startup is followed at + /// the next read; one held is kept when the nodes stop serving it, and + /// replaced by another non-empty one. + #[tokio::test] + async fn a_schedule_is_followed_kept_and_replaced() { + let node = MockBeaconNode::new(); + let nodes = std::slice::from_ref(&node); + let (mut follower, settings) = follower(); + + let none = Applied::NoneServed { warned: true }; + assert_eq!(follower.apply(read(nodes).await), none, "none served yet"); + assert_eq!(settings.gas_limit(&KEY, 0), DEFAULT_GAS_LIMIT); + + let mut config = Config::mainnet(); + config.gas_limit_schedule = schedule(200_000_000); + node.set_spec(config.clone()); + assert_eq!(follower.apply(read(nodes).await), Applied::Took); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + assert_eq!(follower.apply(read(nodes).await), Applied::Unchanged); + + node.set_spec(Config::mainnet()); + assert_eq!(follower.apply(read(nodes).await), none, "kept, and said so"); + assert_eq!(follower.held(), &schedule(200_000_000)); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + + config.gas_limit_schedule = schedule(300_000_000); + node.set_spec(config); + assert_eq!(follower.apply(read(nodes).await), Applied::Took, "replaced"); + assert_eq!(settings.gas_limit(&KEY, 0), 300_000_000); + } + + /// The review's other half: a missing schedule is warned about, once per + /// run of empty reads rather than every epoch, and only when it changes + /// what the client signs (gloas scheduled, no `--gas-limit`). + #[tokio::test] + async fn a_missing_schedule_is_warned_about_once_per_run_when_it_matters() { + let empty = [MockBeaconNode::new()]; + let (mut follower, _) = follower(); + let warned = Applied::NoneServed { warned: true }; + let quiet = Applied::NoneServed { warned: false }; + assert_eq!(follower.apply(read(&empty).await), warned); + assert_eq!(follower.apply(read(&empty).await), quiet, "once per run"); + follower.apply(read(&[serving(200_000_000)]).await); + assert_eq!(follower.apply(read(&empty).await), warned, "a new run"); + + let settings = Arc::new(ProposerSettings::new(Bytes32::ZERO, None)); + let mut irrelevant = ScheduleFollower::new(settings, false); + assert_eq!(irrelevant.apply(read(&empty).await), quiet); + } + + /// No node answering changes nothing. + #[tokio::test] + async fn no_answer_changes_nothing() { + let (mut follower, settings) = follower(); + follower.apply(read(&[serving(200_000_000)]).await); + assert_eq!( + follower.apply(read(&[down(), down()]).await), + Applied::NoAnswer + ); + assert_eq!(settings.gas_limit(&KEY, 0), 200_000_000); + } +} diff --git a/crates/validator/src/head_monitor.rs b/crates/validator/src/head_monitor.rs index 3340e2a67..7e9905f4e 100644 --- a/crates/validator/src/head_monitor.rs +++ b/crates/validator/src/head_monitor.rs @@ -819,6 +819,7 @@ mod tests { validator_committee_index: 0, slot: SLOT, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/http_api/proposer.rs b/crates/validator/src/http_api/proposer.rs index 2e292f818..fc297e821 100644 --- a/crates/validator/src/http_api/proposer.rs +++ b/crates/validator/src/http_api/proposer.rs @@ -382,7 +382,11 @@ pub async fn get_gas_limit( ) -> Result>, ApiError> { let pubkey = parse_path_key(&pubkey)?; require_held(&*context.store.read().await, &pubkey)?; - let gas_limit = context.settings.gas_limit(&pubkey); + // The one in force now, which without an override or `--gas-limit` is + // the schedule's for the current epoch (Lighthouse's answer too). Epoch 0 + // before genesis. + let epoch = context.clock.current_epoch().unwrap_or(0); + let gas_limit = context.settings.gas_limit(&pubkey, epoch); Ok(Json(Data { data: GasLimitEntry { pubkey: encode_hex(&pubkey.0), @@ -698,6 +702,41 @@ mod tests { assert_eq!(body["data"]["gas_limit"], DEFAULT_GAS_LIMIT.to_string()); } + /// Without an override, `GET` reports the gas limit in force now, which + /// the network's schedule names for the current epoch (the harness clock + /// started at the Unix epoch, so it is past epoch 1 and short of the last + /// one); an override still wins over it. + #[tokio::test] + async fn the_default_served_is_the_one_scheduled_for_the_current_epoch() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let harness = harness(None); + harness.settings.set_gas_limit_schedule( + vec![ + GasLimitScheduleEntry { + epoch: 1, + gas_limit: 200_000_000, + }, + GasLimitScheduleEntry { + epoch: u64::MAX, + gas_limit: 300_000_000, + }, + ] + .into(), + ); + let path = uri(&harness.pubkey, "gas_limit"); + + let (status, body) = send(&harness.app, request("GET", &path, None)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"]["gas_limit"], "200000000"); + + let set = serde_json::json!({ "gas_limit": "30000000" }); + let (status, _) = send(&harness.app, request("POST", &path, Some(set))).await; + assert_eq!(status, StatusCode::ACCEPTED); + let (_, body) = send(&harness.app, request("GET", &path, None)).await; + assert_eq!(body["data"]["gas_limit"], "30000000"); + } + /// The specification's `Uint64` is a decimal string with no sign and no /// leading zero; a JSON number is not one. #[tokio::test] @@ -717,7 +756,7 @@ mod tests { assert_eq!(status, StatusCode::BAD_REQUEST, "{gas_limit}"); } assert_eq!( - harness.settings.gas_limit(&harness.pubkey), + harness.settings.gas_limit(&harness.pubkey, 0), DEFAULT_GAS_LIMIT ); } @@ -735,7 +774,7 @@ mod tests { let zero = serde_json::json!({ "gas_limit": "0" }); let (status, _) = send(&harness.app, request("POST", &path, Some(zero))).await; assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(harness.settings.gas_limit(&harness.pubkey), 30_000_000); + assert_eq!(harness.settings.gas_limit(&harness.pubkey, 0), 30_000_000); } #[tokio::test] @@ -850,7 +889,7 @@ mod tests { restarted.graffiti(&harness.pubkey), graffiti_from_text("persisted").expect("fits") ); - assert_eq!(restarted.gas_limit(&harness.pubkey), DEFAULT_GAS_LIMIT); + assert_eq!(restarted.gas_limit(&harness.pubkey, 0), DEFAULT_GAS_LIMIT); } /// The file was replaced and only its directory's flush failed: the diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index d038859ac..4df0c2d0b 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -32,6 +32,7 @@ pub mod doppelganger; pub mod duties; pub mod error; pub mod exit; +mod gas_limit_schedule; pub mod head_monitor; pub mod http_api; pub(crate) mod in_flight; @@ -149,8 +150,10 @@ pub struct ValidatorConfig { /// The gas limit every validator targets unless the keymanager API gives /// it its own: its builder registrations' before gloas, and its proposer /// preferences' from gloas, which is what the node's own payload is built - /// toward. - pub gas_limit: u64, + /// toward. `None` when `--gas-limit` was not given: the network's + /// `GAS_LIMIT_SCHEDULE` then names it per epoch, and + /// [`proposer_settings::DEFAULT_GAS_LIMIT`] where it names none. + pub gas_limit: Option, /// Builder proposals, or `None` when `--builder-proposals` is off. pub builder: Option, /// The smallest p2p bid, in gwei, a gloas block may be built on @@ -313,6 +316,16 @@ pub async fn run(config: ValidatorConfig, stop: impl Future( // PQ aggregators are the aggregation committee and publish what the node // proved; see `AggregationService::aggregate_pq`. let outcome = if data.target.epoch >= aggregation.pq_fork_epoch() { - tokio::time::timeout(budget, aggregation.aggregate_pq(slot, data, duties)).await + tokio::time::timeout(budget, aggregation.aggregate_pq(clock, slot, data, duties)).await } else { tokio::time::timeout(budget, aggregation.aggregate(slot, data, duties, store)).await }; @@ -3533,6 +3556,7 @@ mod tests { validator_committee_index: 0, slot: 3200, is_aggregator: None, + aggregator_position: None, } } diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index 7aca3fd42..097ad24aa 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -573,6 +573,10 @@ pub fn inc_signing_failures() { SIGNING_FAILURES_TOTAL.inc(); } +pub fn inc_signing_failures_by(count: u64) { + SIGNING_FAILURES_TOTAL.inc_by(count); +} + pub fn inc_attestations_refused() { ATTESTATIONS_REFUSED_TOTAL.inc(); } diff --git a/crates/validator/src/pq.rs b/crates/validator/src/pq.rs index 195e29bd0..87a5f7b09 100644 --- a/crates/validator/src/pq.rs +++ b/crates/validator/src/pq.rs @@ -85,7 +85,8 @@ pub const VRF_TREE_DIRECTORY: &str = "pq_vrf_trees"; /// leanXMSS trees, one file per validator, named by its BLS public key: /// [`TREE_FILE_MAGIC`], the key's public key, leanVM's `cache_to_bytes` (the /// top tree's cached level and that of every bottom tree the key holds, at -/// most `MAX_CACHED_BOTTOM_TREES`; about 25 KB), then an HMAC-SHA256 tag over +/// most `DEFAULT_BOTTOM_TREE_CACHE_SIZE`, eight since leanVM bindings v0.19.0; +/// about 46 KB), then an HMAC-SHA256 tag over /// all of it under a key derived from the XMSS seed ([`tree_mac_key`]), so /// only a file this client wrote for this seed loads. Lighthouse's and /// Teku's PQ branches keep the same thing the same way. Written whenever a @@ -985,38 +986,11 @@ pub fn sign_batch(requests: &[SignRequest]) -> Vec) + Sync, -) { - use rayon::prelude::*; - let mut signable = Vec::with_capacity(requests.len()); - for (position, checked) in claim_batch(requests).into_iter().enumerate() { - match checked { - Ok(claimed) => signable.push((position, claimed)), - Err(err) => signed(position, Err(err)), - } - } - signable - .into_par_iter() - .for_each(|(position, (key, leaf_index))| { - let signature = sign_claimed(&requests[position], &key, leaf_index); - signed(position, Ok(signature)); - }); -} - -/// Each request's key and leaf index once its leaf is recorded, or why it -/// cannot be signed: an unknown key, a leaf out of range, or one already -/// spent on another root. All the batch's leaves are recorded with one write -/// and one flush. +/// Each request's key and leaf, with the leaf claimed for its root in the +/// durable record: what happens before any signature of a batch exists, one +/// write and one flush for all of it. A request whose key is unknown, whose +/// leaf is out of range or already spent on another root is an error at its +/// position, and claims nothing. fn claim_batch(requests: &[SignRequest]) -> Vec, u32), PqSignError>> { let mut checked: Vec, u32), PqSignError>> = requests .iter() @@ -1047,28 +1021,6 @@ fn claim_batch(requests: &[SignRequest]) -> Vec, u32), PqSign checked } -/// One answer of [`sign_streamed`]: the request's position in the batch, and -/// its signature or why there is none. -pub type Signed = (usize, Result); - -/// [`sign_each`] on tokio's blocking pool, started at once: each answer comes -/// out of the receiver as soon as it exists. The channel closes after the -/// last one, or early if the signing task dies, in which case the requests -/// that never answered have no signature. -pub fn sign_streamed(requests: Vec) -> tokio::sync::mpsc::UnboundedReceiver { - let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); - if !requests.is_empty() { - tokio::task::spawn_blocking(move || { - sign_each(&requests, |position, signature| { - // A receiver gone means the duty was abandoned; the leaf is - // spent either way. - let _ = sender.send((position, signature)); - }); - }); - } - receiver -} - /// [`sign_batch`] on tokio's blocking pool, so neither the flush nor the /// hashing holds the task that awaits it. pub async fn sign_all(requests: Vec) -> Vec> { @@ -1086,6 +1038,41 @@ pub async fn sign_all(requests: Vec) -> Vec, +) -> tokio::sync::mpsc::UnboundedReceiver<(usize, Result)> { + let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); + if requests.is_empty() { + return receiver; + } + tokio::task::spawn_blocking(move || { + use rayon::prelude::*; + let checked = claim_batch(&requests); + requests + .par_iter() + .zip(checked) + .enumerate() + .for_each(|(position, (request, checked))| { + let signed = + checked.map(|(key, leaf_index)| sign_claimed(request, &key, leaf_index)); + // A receiver that is gone abandoned the duty, as when its + // slot ended: the leaf is spent either way. + let _ = sender.send((position, signed)); + }); + }); + receiver +} + /// One [`sign_all`] signature. pub async fn sign(pubkey: &BlsPubkey, leaf: u64, root: Root) -> Result { let request = SignRequest { @@ -1167,6 +1154,44 @@ mod tests { assert_ne!(attestation_leaf(0) >> 16, slot_leaf(0, 0) >> 16); } + /// `sign_each` answers every request once, at its position, with the + /// signature the batch signer makes, and an unsignable request is an + /// error at its own position only. + #[tokio::test] + async fn each_signature_is_handed_over_once_at_its_position() { + let pubkey = BlsPubkey([41; 48]); + derive_and_register(pubkey, &[41; 32], 0, None); + let leaf = attestation_leaf(3); + let root = Root::from([5; 32]); + let known = SignRequest { pubkey, leaf, root }; + let unknown = SignRequest { + pubkey: BlsPubkey([42; 48]), + leaf, + root, + }; + + let mut signed = sign_each(vec![unknown, known]); + let mut answers = Vec::new(); + while let Some(answer) = signed.recv().await { + answers.push(answer); + } + answers.sort_by_key(|(position, _)| *position); + + assert_eq!(answers.len(), 2); + assert!(matches!( + answers[0], + (0, Err(PqSignError::UnknownValidator)) + )); + let (1, Ok(signature)) = &answers[1] else { + panic!("the known key signs at position 1"); + }; + // Signing is deterministic: the batch signer gives the same bytes. + let batch = sign_batch(&[known]); + assert_eq!(batch[0].as_ref().expect("signs").0, signature.0); + // No requests, no answers. + assert!(sign_each(Vec::new()).recv().await.is_none()); + } + #[test] fn a_request_key_maps_back_and_a_leaf_signs_once() { let secret = [7u8; 32]; @@ -1239,68 +1264,6 @@ mod tests { ); } - /// Signing one by one answers every request exactly once, at its - /// position, with what the batch would have given: the refusals as - /// refusals, and the same bytes for each signature. - #[test] - fn signing_one_by_one_answers_each_request_once_in_its_place() { - let pubkey = BlsPubkey([25; 48]); - let unknown = BlsPubkey([26; 48]); - derive_and_register(pubkey, &[25; 32], 0, None); - let spent = slot_leaf(1, LEAF_OFFSET_PTC_ATTESTER); - let free = slot_leaf(2, LEAF_OFFSET_PTC_ATTESTER); - let other = slot_leaf(3, LEAF_OFFSET_AGGREGATE_AND_PROOF); - sign_now(&pubkey, spent, Root::from([1; 32])).unwrap(); - - let requests = [ - request(pubkey, free, 1), - request(pubkey, spent, 2), - request(unknown, free, 1), - request(pubkey, other, 3), - ]; - let answers = Mutex::new(Vec::new()); - sign_each(&requests, |position, signature| { - answers.lock().unwrap().push((position, signature)); - }); - let mut answers = answers.into_inner().unwrap(); - answers.sort_by_key(|(position, _)| *position); - let positions: Vec = answers.iter().map(|(position, _)| *position).collect(); - assert_eq!(positions, vec![0, 1, 2, 3]); - assert!(matches!(answers[1].1, Err(PqSignError::LeafUsed(_)))); - assert!(matches!(answers[2].1, Err(PqSignError::UnknownValidator))); - - // Signing is deterministic, so the batch path re-signs the same - // leaves for the same roots and must give the same bytes. - let again = sign_batch(&[requests[0], requests[3]]); - for (answer, batch) in [(&answers[0].1, &again[0]), (&answers[3].1, &again[1])] { - assert_eq!( - answer.as_ref().unwrap().0.to_vec(), - batch.as_ref().unwrap().0.to_vec() - ); - } - } - - /// The async wrapper starts signing at once and closes its channel after - /// the last answer. - #[tokio::test] - async fn a_streamed_batch_answers_every_request_and_then_closes() { - let pubkey = BlsPubkey([27; 48]); - derive_and_register(pubkey, &[27; 32], 0, None); - let requests = vec![ - request(pubkey, slot_leaf(4, LEAF_OFFSET_PTC_ATTESTER), 1), - request(pubkey, slot_leaf(5, LEAF_OFFSET_PTC_ATTESTER), 2), - ]; - let mut signed = sign_streamed(requests); - let mut positions = Vec::new(); - while let Some((position, signature)) = signed.recv().await { - assert!(signature.is_ok()); - positions.push(position); - } - positions.sort_unstable(); - assert_eq!(positions, vec![0, 1]); - assert!(sign_streamed(Vec::new()).recv().await.is_none()); - } - /// A batch cannot spend one leaf on two roots, and what it claims is /// written once and found again after a restart. #[test] @@ -1594,7 +1557,7 @@ mod tests { let proof = vrf_proof(&pubkey, 5).unwrap(); assert_eq!(proof.len(), 32); - assert_eq!(proof[0].0, vrf::compute_vrf_leaf(&vrf_seed, 5)); + assert_eq!(proof[0].0, vrf::compute_vrf_secret(&vrf_seed, 5)); let branch = proof[1..].iter().map(|node| &node.0); let root: [u8; 32] = bytes[bytes.len() - 32..].try_into().unwrap(); assert_eq!(vrf::fold_vrf_branch(&proof[0].0, branch, 5), root); @@ -1614,7 +1577,7 @@ mod tests { fn stand_in_state_record(vrf_seed: vrf::Node) -> Vec { let mut branch = vrf::VrfTree::with_depth(vrf_seed, 16).compact_state().1; branch.extend((16..31).map(|height| [height as u8; 32])); - let root = vrf::fold_vrf_branch(&vrf::compute_vrf_leaf(&vrf_seed, 0), &branch, 0); + let root = vrf::fold_vrf_branch(&vrf::compute_vrf_secret(&vrf_seed, 0), &branch, 0); vrf::VrfTree::from_compact_state(vrf_seed, root, branch) .unwrap() .to_state_record() diff --git a/crates/validator/src/preferences.rs b/crates/validator/src/preferences.rs index 2ad90f25b..da40bd7a4 100644 --- a/crates/validator/src/preferences.rs +++ b/crates/validator/src/preferences.rs @@ -491,9 +491,11 @@ impl PreferencesService { None => Before::Unsent, }; // One read for both, so a keymanager write between two reads - // cannot pair an old address with a new gas limit. + // cannot pair an old address with a new gas limit. The gas limit + // is the one for the proposal's epoch, `target`, which is the next + // epoch's for a preference signed ahead. let Some((fee_recipient, target_gas_limit)) = - self.settings.fee_recipient_and_gas_limit(&pubkey) + self.settings.fee_recipient_and_gas_limit(&pubkey, target) else { no_fee_recipient += 1; continue; @@ -574,8 +576,10 @@ impl PreferencesService { }) if done >= round => continue, Some(PqSent { signed, .. }) => (signed, false), None => { + // The gas limit for the proposal's epoch, `target`, as at + // a BLS epoch. let Some((fee_recipient, target_gas_limit)) = - self.settings.fee_recipient_and_gas_limit(&pubkey) + self.settings.fee_recipient_and_gas_limit(&pubkey, target) else { no_fee_recipient += 1; continue; @@ -996,6 +1000,52 @@ mod tests { } } + /// Without `--gas-limit` or an override, each preference carries the gas + /// limit the schedule names for its proposal's epoch, not the wall + /// clock's: the next epoch's preference is signed now, at its own + /// epoch's limit. + #[tokio::test] + async fn the_target_gas_limit_is_the_one_scheduled_for_the_proposal_epoch() { + use crate::proposer_settings::DEFAULT_GAS_LIMIT; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = Arc::new(RwLock::new(store)); + let settings = settings(Some(FEE_RECIPIENT)); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: GLOAS_EPOCH + 1, + gas_limit: 200_000_000, + }] + .into(), + ); + let node = MockBeaconNode::new() + .with_proposers_v2( + GLOAS_EPOCH, + Root::repeat_byte(0x11), + vec![duty(&pubkeys[0], 3, slot_in(GLOAS_EPOCH, 10))], + ) + .with_proposers_v2( + GLOAS_EPOCH + 1, + Root::repeat_byte(0x22), + vec![duty(&pubkeys[0], 3, slot_in(GLOAS_EPOCH + 1, 4))], + ); + let (service, node) = service(node, settings); + + service.poll(slot_in(GLOAS_EPOCH, 1), store).await; + + let mut entries: Vec<_> = submitted(&node) + .into_iter() + .flat_map(|(_, entries)| entries) + .collect(); + entries.sort_by_key(|entry| entry.message.proposal_slot); + let gas_limits: Vec<_> = entries + .iter() + .map(|entry| entry.message.target_gas_limit) + .collect(); + assert_eq!(gas_limits, [DEFAULT_GAS_LIMIT, 200_000_000]); + } + #[tokio::test] async fn a_second_poll_does_not_resubmit() { let (store, pubkeys) = store_with_keys(1); @@ -1104,6 +1154,49 @@ mod tests { assert_eq!(node.submitted_pq_preferences.lock().expect("lock").len(), 1); } + /// A PQ preference carries the gas limit the schedule names for its + /// proposal's epoch, as a BLS one does, rather than `DEFAULT_GAS_LIMIT`: + /// pq-devnet-1 schedules 200M from epoch 0, and a validator left on the + /// default pulled every proposal toward 60M. + #[tokio::test] + async fn a_pq_preference_carries_the_scheduled_gas_limit() { + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = Arc::new(RwLock::new(store)); + let slot = slot_in(GLOAS_EPOCH, 12); + let current = slot_in(GLOAS_EPOCH, 1); + // The other PQ test's key and secret, so the shared registry holds + // one key whichever runs first; another slot, so another leaf. + crate::pq::derive_and_register(pubkeys[0], &[21; 32], current, None); + let config = context() + .config + .clone() + .with_fork_epoch(ForkName::Eip8483, GLOAS_EPOCH) + .with_fork_epoch(ForkName::Pq, GLOAS_EPOCH); + let context = Arc::new(SigningContext::new(config, Root::repeat_byte(0x42))); + let node = Arc::new(MockBeaconNode::new().with_proposers_v2( + GLOAS_EPOCH, + Root::repeat_byte(0x11), + vec![duty(&pubkeys[0], 3, slot)], + )); + let settings = settings(Some(FEE_RECIPIENT)); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: GLOAS_EPOCH, + gas_limit: 200_000_000, + }] + .into(), + ); + let service = Arc::new(PreferencesService::new(node.clone(), context, settings)); + + service.poll(current, store).await; + + let sent = node.submitted_pq_preferences.lock().expect("lock").clone(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].message.target_gas_limit, 200_000_000); + } + /// A reorg that moves a slot from one of this client's validators to /// another leaves both preferences kept, and each validator's block may /// pay only the address it signed for itself. diff --git a/crates/validator/src/proposer_settings.rs b/crates/validator/src/proposer_settings.rs index 1abb2853c..7d3bb8756 100644 --- a/crates/validator/src/proposer_settings.rs +++ b/crates/validator/src/proposer_settings.rs @@ -1,7 +1,10 @@ //! What each validator proposes with: its fee recipient, graffiti and gas limit. //! //! Every validator starts on the process-wide defaults from the command line. -//! The keymanager API's `feerecipient`, `graffiti` and `gas_limit` endpoints +//! The gas limit's default without `--gas-limit` depends on the epoch: the +//! network's `GAS_LIMIT_SCHEDULE`, read off the beacon node, names one per +//! epoch, and [`DEFAULT_GAS_LIMIT`] covers every epoch it does not. The +//! keymanager API's `feerecipient`, `graffiti` and `gas_limit` endpoints //! override them per key, and `DELETE` puts a key back on the defaults. //! //! # The definitions file is the record; this is the cache @@ -44,7 +47,10 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{PoisonError, RwLock}; -use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32, ExecutionAddress, H160, H256}; +use ethlambda_types::beacon::config::{GasLimitSchedule, MAX_GAS_LIMIT_SCHEDULE_ENTRIES}; +use ethlambda_types::beacon::primitives::{ + BlsPubkey, Bytes32, Epoch, ExecutionAddress, H160, H256, +}; /// A block's graffiti field is exactly this wide. pub const GRAFFITI_BYTES: usize = 32; @@ -77,18 +83,39 @@ pub fn graffiti_to_text(graffiti: &Bytes32) -> String { String::from_utf8_lossy(&graffiti.0[..GRAFFITI_BYTES - padding]).into_owned() } -/// The gas limit a validator with no override reports, unless `--gas-limit` -/// names another. +/// The gas limit of last resort: what a validator with no override reports +/// when `--gas-limit` was not given and the network's `GAS_LIMIT_SCHEDULE` +/// schedules nothing for the epoch (the beacon node does not serve the key, +/// the schedule is empty, or its first entry is still ahead). /// -/// Lighthouse's and Nimbus's default (Lighthouse's when the network config -/// names no gas limit schedule, which this client does not read). Builder -/// registrations carry it as the gas limit the builder should target, from -/// gloas the proposer preferences carry it as the target the node's own -/// payload is built toward too, and the keymanager API serves it as the -/// specification requires. A network whose gas limit is elsewhere needs -/// `--gas-limit`, or every proposal pulls its limit toward this one. +/// Lighthouse's and Nimbus's default, and what Lighthouse falls back to when +/// its schedule names none. Builder registrations carry the resulting gas +/// limit as the one the builder should target, from gloas the proposer +/// preferences carry it as the target the node's own payload is built toward +/// too, and the keymanager API serves it as the specification requires. pub const DEFAULT_GAS_LIMIT: u64 = 60_000_000; +/// `[epoch: gas limit, ...]`, for the startup log line. +/// +/// Bounded like every other text a node sends that reaches a log line. A node +/// can serve a schedule of any length (only a beacon node's own config file is +/// held to [`MAX_GAS_LIMIT_SCHEDULE_ENTRIES`]), so at most that many entries +/// are written out and the rest are counted. +pub fn gas_limit_schedule_text(schedule: &GasLimitSchedule) -> String { + let entries = schedule.entries(); + let shown: Vec = entries + .iter() + .take(MAX_GAS_LIMIT_SCHEDULE_ENTRIES) + .map(|entry| format!("{}: {}", entry.epoch, entry.gas_limit)) + .collect(); + let rest = entries.len() - shown.len(); + if rest == 0 { + format!("[{}]", shown.join(", ")) + } else { + format!("[{}, ... and {rest} more]", shown.join(", ")) + } +} + /// `text` as a fee recipient: `0x` and forty hex digits, the keymanager /// specification's `EthAddress` pattern. The zero address is refused: the /// specification forbids it outright, since it would read as an address @@ -157,10 +184,32 @@ pub enum SettingChange { struct Inner { default_fee_recipient: Option, default_graffiti: Bytes32, - default_gas_limit: u64, + /// `--gas-limit`, or `None` when it was not given. + default_gas_limit: Option, + /// The network's `GAS_LIMIT_SCHEDULE`, from the beacon node's + /// `/eth/v1/config/spec`; empty until it is fetched, or when the node does + /// not serve the key. + gas_limit_schedule: GasLimitSchedule, overrides: HashMap, } +impl Inner { + /// The gas limit at `epoch` of a validator with no override of its own: + /// `--gas-limit`, else the one the schedule names for `epoch`, else + /// [`DEFAULT_GAS_LIMIT`]. Lighthouse's order. + fn default_gas_limit(&self, epoch: Epoch) -> u64 { + self.default_gas_limit + .or_else(|| self.gas_limit_schedule.gas_limit_at(epoch)) + .unwrap_or(DEFAULT_GAS_LIMIT) + } + + /// `pubkey`'s gas limit at `epoch`: its override, else the default. + fn gas_limit(&self, pubkey: &BlsPubkey, epoch: Epoch) -> u64 { + let overridden = self.overrides.get(pubkey).and_then(|o| o.gas_limit); + overridden.unwrap_or_else(|| self.default_gas_limit(epoch)) + } +} + /// The defaults and every per-key override, shared by the duty loop and the /// keymanager API. /// @@ -188,16 +237,18 @@ impl ProposerSettings { inner: RwLock::new(Inner { default_fee_recipient: fee_recipient, default_graffiti: graffiti, - default_gas_limit: DEFAULT_GAS_LIMIT, + default_gas_limit: None, + gas_limit_schedule: GasLimitSchedule::default(), overrides: HashMap::new(), }), generation: AtomicU64::new(0), } } - /// These settings with `gas_limit` as the gas limit of every validator - /// with no override of its own, in place of [`DEFAULT_GAS_LIMIT`]. - pub fn with_default_gas_limit(mut self, gas_limit: u64) -> Self { + /// These settings with `gas_limit` (`--gas-limit`) as the gas limit of + /// every validator with no override of its own, at every epoch, in place + /// of the schedule's and [`DEFAULT_GAS_LIMIT`]. `None` leaves those two. + pub fn with_default_gas_limit(mut self, gas_limit: Option) -> Self { self.inner .get_mut() .unwrap_or_else(PoisonError::into_inner) @@ -205,6 +256,22 @@ impl ProposerSettings { self } + /// Take the gas limit of a validator with neither an override nor + /// `--gas-limit` from `schedule` (the network's `GAS_LIMIT_SCHEDULE`), at + /// the epoch each reader names. + /// + /// Set by [`crate::gas_limit_schedule`]: at startup, after these settings + /// are built and before anything that signs reads them, and again whenever + /// its once-an-epoch read of every node finds another schedule. It leaves [`Self::generation`] alone: that counts override + /// writes, and the full registration send each epoch compares every gas + /// limit it signs anyway. + pub fn set_gas_limit_schedule(&self, schedule: GasLimitSchedule) { + self.inner + .write() + .unwrap_or_else(PoisonError::into_inner) + .gas_limit_schedule = schedule; + } + /// A counter that moves whenever a write or delete changes a fee /// recipient or gas limit override; one that leaves them as they were /// does not move it. Equal readings mean no per-key fee recipient or gas @@ -244,26 +311,29 @@ impl ProposerSettings { }) } - /// `pubkey`'s fee recipient and gas limit read together, under one lock, or - /// `None` when it has no fee recipient. + /// `pubkey`'s fee recipient and its gas limit at `epoch` read together, + /// under one lock, or `None` when it has no fee recipient. /// /// For a signed message that carries both (a builder registration, proposer /// preferences): two separate reads could straddle a keymanager write and /// pair an old address with a new gas limit, a combination the operator /// never configured, which the builder then keeps. + /// + /// `epoch` picks the schedule's entry when neither an override nor + /// `--gas-limit` names a gas limit: a preference's proposal epoch, a + /// registration's current one. pub fn fee_recipient_and_gas_limit( &self, pubkey: &BlsPubkey, + epoch: Epoch, ) -> Option<(ExecutionAddress, u64)> { self.read(|inner| { - let overrides = inner.overrides.get(pubkey); - let fee_recipient = overrides + let fee_recipient = inner + .overrides + .get(pubkey) .and_then(|o| o.fee_recipient) .or(inner.default_fee_recipient)?; - let gas_limit = overrides - .and_then(|o| o.gas_limit) - .unwrap_or(inner.default_gas_limit); - Some((fee_recipient, gas_limit)) + Some((fee_recipient, inner.gas_limit(pubkey, epoch))) }) } @@ -275,12 +345,11 @@ impl ProposerSettings { }) } - /// The gas limit `pubkey` reports. - pub fn gas_limit(&self, pubkey: &BlsPubkey) -> u64 { - self.read(|inner| { - let overridden = inner.overrides.get(pubkey).and_then(|o| o.gas_limit); - overridden.unwrap_or(inner.default_gas_limit) - }) + /// The gas limit `pubkey` targets at `epoch`: its override, else + /// `--gas-limit`, else the schedule's for `epoch`, else + /// [`DEFAULT_GAS_LIMIT`]. + pub fn gas_limit(&self, pubkey: &BlsPubkey, epoch: Epoch) -> u64 { + self.read(|inner| inner.gas_limit(pubkey, epoch)) } /// Every override `pubkey` holds, defaults left as `None`. @@ -349,6 +418,7 @@ impl ProposerSettings { #[cfg(test)] mod tests { use super::*; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; use ethlambda_types::beacon::primitives::H160; fn key(byte: u8) -> BlsPubkey { @@ -364,7 +434,7 @@ mod tests { let settings = settings(); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(1)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); } #[test] @@ -376,11 +446,11 @@ mod tests { assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xbb; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x22)); - assert_eq!(settings.gas_limit(&key(1)), 30_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 30_000_000); assert_eq!(settings.fee_recipient(&key(2)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(2)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(2)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(2), 0), DEFAULT_GAS_LIMIT); } /// `--gas-limit` replaces the default every key without an override gets, @@ -388,18 +458,121 @@ mod tests { /// clearing it falls back to the configured default, not the built-in one. #[test] fn a_configured_default_gas_limit_replaces_the_built_in_one() { - let settings = settings().with_default_gas_limit(200_000_000); - assert_eq!(settings.gas_limit(&key(1)), 200_000_000); + let settings = settings().with_default_gas_limit(Some(200_000_000)); + assert_eq!(settings.gas_limit(&key(1), 0), 200_000_000); assert_eq!( - settings.fee_recipient_and_gas_limit(&key(1)), + settings.fee_recipient_and_gas_limit(&key(1), 0), Some((H160([0xaa; 20]), 200_000_000)) ); settings.set_gas_limit(&key(1), 30_000_000); - assert_eq!(settings.gas_limit(&key(1)), 30_000_000); - assert_eq!(settings.gas_limit(&key(2)), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 30_000_000); + assert_eq!(settings.gas_limit(&key(2), 0), 200_000_000); settings.clear_gas_limit(&key(1)); - assert_eq!(settings.gas_limit(&key(1)), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 0), 200_000_000); + } + + /// Two entries, at epochs 100 and 200. + fn schedule() -> GasLimitSchedule { + vec![ + GasLimitScheduleEntry { + epoch: 100, + gas_limit: 200_000_000, + }, + GasLimitScheduleEntry { + epoch: 200, + gas_limit: 300_000_000, + }, + ] + .into() + } + + /// Without `--gas-limit`, the schedule names the default per epoch, and + /// [`DEFAULT_GAS_LIMIT`] covers the epochs before its first entry. + #[test] + fn the_schedule_names_the_default_at_each_epoch() { + let settings = settings(); + settings.set_gas_limit_schedule(schedule()); + + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 99), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 100), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 199), 200_000_000); + assert_eq!(settings.gas_limit(&key(1), 200), 300_000_000); + assert_eq!( + settings.fee_recipient_and_gas_limit(&key(1), 150), + Some((H160([0xaa; 20]), 200_000_000)) + ); + } + + /// A node that does not serve `GAS_LIMIT_SCHEDULE` leaves the schedule + /// empty, and every epoch gets [`DEFAULT_GAS_LIMIT`]. + #[test] + fn without_a_schedule_every_epoch_gets_the_built_in_default() { + let settings = settings(); + settings.set_gas_limit_schedule(GasLimitSchedule::default()); + for epoch in [0, 100, Epoch::MAX] { + assert_eq!(settings.gas_limit(&key(1), epoch), DEFAULT_GAS_LIMIT); + } + } + + /// The order: a key's own override, then `--gas-limit`, then the + /// schedule, then [`DEFAULT_GAS_LIMIT`]. + #[test] + fn an_override_and_the_flag_both_win_over_the_schedule() { + let flagged = settings().with_default_gas_limit(Some(45_000_000)); + flagged.set_gas_limit_schedule(schedule()); + assert_eq!(flagged.gas_limit(&key(1), 0), 45_000_000); + assert_eq!(flagged.gas_limit(&key(1), 150), 45_000_000); + flagged.set_gas_limit(&key(1), 30_000_000); + assert_eq!(flagged.gas_limit(&key(1), 150), 30_000_000); + assert_eq!( + flagged.fee_recipient_and_gas_limit(&key(1), 150), + Some((H160([0xaa; 20]), 30_000_000)) + ); + + let scheduled = settings().with_default_gas_limit(None); + scheduled.set_gas_limit_schedule(schedule()); + scheduled.set_gas_limit(&key(1), 30_000_000); + assert_eq!(scheduled.gas_limit(&key(1), 150), 30_000_000); + assert_eq!(scheduled.gas_limit(&key(2), 150), 200_000_000); + // Clearing the override puts the key back on the schedule. + scheduled.clear_gas_limit(&key(1)); + assert_eq!(scheduled.gas_limit(&key(1), 150), 200_000_000); + } + + /// A node can serve a schedule of any length, and its text goes into the + /// startup line: at most `MAX_GAS_LIMIT_SCHEDULE_ENTRIES` entries are + /// written out, the rest counted. + #[test] + fn the_gas_limit_schedule_text_is_bounded() { + let schedule = |count: u64| -> GasLimitSchedule { + let entries = (0..count).map(|epoch| GasLimitScheduleEntry { + epoch, + gas_limit: 60_000_000, + }); + entries.collect::>().into() + }; + assert_eq!(gas_limit_schedule_text(&schedule(0)), "[]"); + assert_eq!( + gas_limit_schedule_text(&schedule(2)), + "[0: 60000000, 1: 60000000]" + ); + + let full = gas_limit_schedule_text(&schedule(MAX_GAS_LIMIT_SCHEDULE_ENTRIES as u64)); + assert!(!full.contains("more"), "{full}"); + + let over = gas_limit_schedule_text(&schedule(100_000)); + let last_shown = format!("{}: 60000000", MAX_GAS_LIMIT_SCHEDULE_ENTRIES - 1); + let first_hidden = format!(" {MAX_GAS_LIMIT_SCHEDULE_ENTRIES}: 60000000"); + let hidden = 100_000 - MAX_GAS_LIMIT_SCHEDULE_ENTRIES; + assert!(over.contains(&last_shown), "{over}"); + assert!(!over.contains(&first_hidden), "{over}"); + assert!( + over.ends_with(&format!(", ... and {hidden} more]")), + "{over}" + ); + assert!(over.len() < full.len() + 64, "{} bytes", over.len()); } /// The pair a signed registration or preference carries agrees with the @@ -407,19 +580,19 @@ mod tests { #[test] fn the_fee_recipient_and_gas_limit_read_together_match_the_single_reads() { let settings = ProposerSettings::new(Bytes32::ZERO, None); - assert_eq!(settings.fee_recipient_and_gas_limit(&key(1)), None); + assert_eq!(settings.fee_recipient_and_gas_limit(&key(1), 0), None); settings.set_gas_limit(&key(1), 30_000_000); - assert_eq!(settings.fee_recipient_and_gas_limit(&key(1)), None); + assert_eq!(settings.fee_recipient_and_gas_limit(&key(1), 0), None); settings.set_fee_recipient(&key(1), H160([0xbb; 20])); assert_eq!( - settings.fee_recipient_and_gas_limit(&key(1)), + settings.fee_recipient_and_gas_limit(&key(1), 0), Some((H160([0xbb; 20]), 30_000_000)) ); let defaults = self::settings(); assert_eq!( - defaults.fee_recipient_and_gas_limit(&key(2)), + defaults.fee_recipient_and_gas_limit(&key(2), 0), Some((H160([0xaa; 20]), DEFAULT_GAS_LIMIT)) ); } @@ -456,7 +629,7 @@ mod tests { settings.forget(&key(1)); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xaa; 20]))); assert_eq!(settings.graffiti(&key(1)), Bytes32::repeat_byte(0x11)); - assert_eq!(settings.gas_limit(&key(1)), DEFAULT_GAS_LIMIT); + assert_eq!(settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT); } #[test] @@ -491,7 +664,7 @@ mod tests { ); assert_eq!(settings.fee_recipient(&key(1)), Some(H160([0xbb; 20]))); assert_eq!( - settings.gas_limit(&key(1)), + settings.gas_limit(&key(1), 0), DEFAULT_GAS_LIMIT, "an override the seed does not carry is gone" ); diff --git a/crates/validator/src/registration.rs b/crates/validator/src/registration.rs index b24689fcf..8d39fb2f4 100644 --- a/crates/validator/src/registration.rs +++ b/crates/validator/src/registration.rs @@ -107,7 +107,9 @@ //! //! # The per-slot check is one atomic read //! -//! Only a keymanager write changes what a registration says, so +//! Only a keymanager write changes what a registration says between two +//! epochs' full sends (the gas limit schedule moves a default only at an +//! epoch, and each full send compares every value it signs), so //! [`RegistrationService::register_changed`] compares //! [`ProposerSettings::generation`] with the one it last signed against and //! returns before touching the store when it has not moved. While something @@ -288,12 +290,16 @@ impl RegistrationService { /// per lookup, inside the signer), and the cache is written last, so a key /// is cached only once its chunk is signed in full. /// - /// `now_secs` is a parameter so a test can fix the timestamp. + /// `now_secs` is a parameter so a test can fix the timestamp. `epoch` is + /// the one the send is for, which picks the gas limit schedule's entry for + /// a validator with no gas limit of its own (see + /// [`ProposerSettings::fee_recipient_and_gas_limit`]). async fn current( &self, store: &RwLock, pubkeys: &[BlsPubkey], now_secs: u64, + epoch: Epoch, ) -> Current { /// Where a validator's registration comes from, in `pubkeys`' order. enum Source { @@ -318,7 +324,7 @@ impl RegistrationService { } let Some((fee_recipient, gas_limit)) = - self.settings.fee_recipient_and_gas_limit(pubkey) + self.settings.fee_recipient_and_gas_limit(pubkey, epoch) else { no_fee_recipient += 1; if signed.contains_key(pubkey) { @@ -443,6 +449,7 @@ impl RegistrationService { self: &Arc, store: &Arc>, pubkeys: &[BlsPubkey], + epoch: Epoch, ) -> Current { let now_secs = Self::now_secs(); let mut current = Current { @@ -457,7 +464,7 @@ impl RegistrationService { // thread is outside it, so it enters it to wait on them. let runtime = tokio::runtime::Handle::current(); let part = tokio::task::spawn_blocking(move || { - runtime.block_on(service.current(&store, &chunk, now_secs)) + runtime.block_on(service.current(&store, &chunk, now_secs, epoch)) }) .await; match part { @@ -532,7 +539,7 @@ impl RegistrationService { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = pubkeys.clone(); - let current = self.current_blocking(&store, &pubkeys).await; + let current = self.current_blocking(&store, &pubkeys, epoch).await; if current.no_fee_recipient > 0 { warn!( skipped = current.no_fee_recipient, @@ -591,7 +598,7 @@ impl RegistrationService { if known.is_empty() { return; } - let current = self.current_blocking(&store, &known).await; + let current = self.current_blocking(&store, &known, epoch).await; // What changed, and what an earlier slot could not get any node to // take. Both are read off `all`, the newest registration per key, so a // key that changed again since its failed send goes out once, as now. @@ -696,11 +703,11 @@ mod tests { let store = RwLock::new(store); let (service, _) = service(Config::mainnet(), settings(Some(H160([0xab; 20])))); - let first = service.current(&store, &pubkeys, 1_000).await; + let first = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(first.all.len(), 2); assert_eq!(first.changed.len(), 2); - let second = service.current(&store, &pubkeys, 2_000).await; + let second = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(second.all, first.all, "same timestamp and signature"); assert!(second.changed.is_empty()); assert_eq!(second.all[0].message.timestamp, 1_000); @@ -712,11 +719,11 @@ mod tests { let store = RwLock::new(store); let settings = settings(Some(H160([0xab; 20]))); let (service, _) = service(Config::mainnet(), settings.clone()); - let first = service.current(&store, &pubkeys, 1_000).await; + let first = service.current(&store, &pubkeys, 1_000, 0).await; settings.set_fee_recipient(&pubkeys[0], H160([0xcd; 20])); settings.set_gas_limit(&pubkeys[1], 30_000_000); - let second = service.current(&store, &pubkeys, 2_000).await; + let second = service.current(&store, &pubkeys, 2_000, 0).await; let changed: Vec<_> = second.changed.iter().map(|r| r.message.pubkey).collect(); assert_eq!(changed, vec![pubkeys[0], pubkeys[1]]); @@ -728,6 +735,34 @@ mod tests { assert_eq!(second.all[2], first.all[2], "the third is untouched"); } + /// A validator with no gas limit of its own registers the one the schedule + /// names for the send's epoch, and is re-signed when that moves, which + /// no keymanager write signals: the epoch's full send compares the values. + #[tokio::test] + async fn the_gas_limit_follows_the_schedule_at_the_sends_epoch() { + use crate::proposer_settings::DEFAULT_GAS_LIMIT; + use ethlambda_types::beacon::config::GasLimitScheduleEntry; + + let (store, pubkeys) = store_with_keys(1); + let store = RwLock::new(store); + let settings = settings(Some(H160([0xab; 20]))); + settings.set_gas_limit_schedule( + vec![GasLimitScheduleEntry { + epoch: 5, + gas_limit: 200_000_000, + }] + .into(), + ); + let (service, _) = service(Config::mainnet(), settings); + + let before = service.current(&store, &pubkeys, 1_000, 4).await; + assert_eq!(before.all[0].message.gas_limit, DEFAULT_GAS_LIMIT); + + let from = service.current(&store, &pubkeys, 2_000, 5).await; + assert_eq!(from.changed.len(), 1, "re-signed for the new gas limit"); + assert_eq!(from.all[0].message.gas_limit, 200_000_000); + } + /// A relay drops a registration that is not newer than the one it holds, /// so a change signed within the same second, or after the clock stepped /// back, still gets a later timestamp than the registration it replaces. @@ -737,20 +772,20 @@ mod tests { let store = RwLock::new(store); let settings = settings(Some(H160([0xab; 20]))); let (service, _) = service(Config::mainnet(), settings.clone()); - let first = service.current(&store, &pubkeys, 2_000).await; + let first = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(first.all[0].message.timestamp, 2_000); settings.set_gas_limit(&pubkeys[0], 30_000_000); - let same_second = service.current(&store, &pubkeys, 2_000).await; + let same_second = service.current(&store, &pubkeys, 2_000, 0).await; assert_eq!(same_second.changed[0].message.timestamp, 2_001); settings.set_gas_limit(&pubkeys[0], 31_000_000); - let stepped_back = service.current(&store, &pubkeys, 1_000).await; + let stepped_back = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(stepped_back.changed[0].message.timestamp, 2_002); // Once the clock is ahead again, its reading is used. settings.set_gas_limit(&pubkeys[0], 32_000_000); - let caught_up = service.current(&store, &pubkeys, 5_000).await; + let caught_up = service.current(&store, &pubkeys, 5_000, 0).await; assert_eq!(caught_up.changed[0].message.timestamp, 5_000); } @@ -762,7 +797,7 @@ mod tests { settings.set_fee_recipient(&pubkeys[1], H160([0xcd; 20])); let (service, _) = service(Config::mainnet(), settings); - let current = service.current(&store, &pubkeys, 1_000).await; + let current = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(current.no_fee_recipient, 1); assert_eq!(current.all.len(), 1); @@ -776,7 +811,7 @@ mod tests { store.remove(&pubkeys[0]); let store = RwLock::new(store); - let current = service.current(&store, &pubkeys, 1_000).await; + let current = service.current(&store, &pubkeys, 1_000, 0).await; assert_eq!(current.all.len(), 1); assert_eq!(current.all[0].message.pubkey, pubkeys[1]); diff --git a/crates/validator/src/slot_clock.rs b/crates/validator/src/slot_clock.rs index a067d1956..a07443c59 100644 --- a/crates/validator/src/slot_clock.rs +++ b/crates/validator/src/slot_clock.rs @@ -161,7 +161,13 @@ impl SlotClock { /// After the attester offset on every network the specification ships, /// necessarily: an aggregator folds together votes its beacon node has /// collected, and before the attesters have voted there is nothing to fold. + /// + /// At a PQ slot this is the first aggregator seat's time; a later seat + /// waits further, until [`Self::pq_aggregation_time`] for its position. pub fn aggregation_time(&self, slot: Slot) -> SystemTime { + if self.is_pq(slot) { + return self.pq_aggregation_time(slot, 0); + } let bps = if self.is_gloas(slot) { self.config.aggregate_due_bps_gloas } else { @@ -170,6 +176,17 @@ impl SlotClock { self.offset_into(slot, bps) } + /// When the PQ aggregator at `position` in its aggregation committee + /// broadcasts for `slot`: PQ's `get_aggregate_due_ms(position)`, the first + /// seat's offset plus `position` aggregator delays, each rounded down to + /// a millisecond on its own as the specification rounds them. + pub fn pq_aggregation_time(&self, slot: Slot, position: u64) -> SystemTime { + let component = |bps: u64| bps.saturating_mul(self.slot_duration_ms) / BASIS_POINTS; + let offset_ms = component(self.config.aggregate_due_bps_pq) + .saturating_add(position.saturating_mul(component(self.config.aggregator_delay_bps))); + self.start_of(slot) + Duration::from_millis(offset_ms) + } + /// When the sync committee message for `slot` is signed. /// /// The fork of `slot` picks the offset, as it does for attestations: @@ -382,6 +399,27 @@ mod tests { UNIX_EPOCH + Duration::from_secs(GENESIS + offset_secs) } + /// PQ `validator.md`'s 12-second example: the seats broadcast at 7.2, + /// 7.8, 8.4 and 9.0 s, and a PQ slot's aggregation duty wakes for the + /// first. + #[test] + fn pq_aggregators_broadcast_staggered_by_their_seat() { + let config = Config::mainnet().with_fork_epoch(ForkName::Pq, 1); + let clock = SlotClock::from_config(GENESIS, &config); + let slot = slots_per_epoch() + 2; + assert!(clock.is_pq(slot) && !clock.is_pq(slot - slots_per_epoch())); + for (position, offset_ms) in [(0, 7_200), (1, 7_800), (2, 8_400), (3, 9_000)] { + assert_eq!( + clock.pq_aggregation_time(slot, position), + clock.start_of(slot) + Duration::from_millis(offset_ms) + ); + } + assert_eq!( + clock.aggregation_time(slot), + clock.pq_aggregation_time(slot, 0) + ); + } + #[test] fn a_slot_ends_where_the_next_begins() { let clock = clock(); diff --git a/crates/validator/src/subscriptions.rs b/crates/validator/src/subscriptions.rs index 69997dcd5..68b445c29 100644 --- a/crates/validator/src/subscriptions.rs +++ b/crates/validator/src/subscriptions.rs @@ -221,6 +221,7 @@ mod tests { validator_committee_index: 7, slot, is_aggregator: None, + aggregator_position: None, } } diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 14d1a6d3f..c4cefe75a 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -1,7 +1,7 @@ # The PQ fork -consensus-specs' `pq` branch (pinned here at the pq-devnet-0 spec, -`2f43bc0f989f47af81df390a90bc1f78e2436323`) specifies an emergency fork that +consensus-specs' `pq` branch (pinned here at +`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`, pq-devnet-1's spec) specifies an emergency fork that replaces BLS with leanXMSS, a hash-based signature scheme believed secure against a quantum adversary. It comes as two feature forks after gloas: @@ -14,7 +14,11 @@ against a quantum adversary. It comes as two feature forks after gloas: client protocol go, RANDAO reveals become VRF proofs, attestations lose their signatures to a block-wide STARK proof, voluntary exits move to the execution layer, and deposits carry a VRF root instead of a signature, guarded by - preregistrations (EIP-8205). + preregistrations (EIP-8205). A validator or builder that registered + nothing takes `keccak256(pubkey + domain)` of its BLS key as its XMSS key + (and, a validator, as its VRF root), against which nothing verifies, and + is exited (`compute_legacy_xmss_pubkey`, `compute_legacy_vrf_root`; SHA-256 + before `4c296784`). Both are `ForkName`s (`Eip8483`, `Pq`), between `Gloas` and `Lean`, on-disk selectors 8 and 9. Neither is scheduled on a public network. **The node @@ -50,7 +54,7 @@ changes. | Layer | Where | Status | | --- | --- | --- | | leanXMSS sign/verify | `ethlambda_crypto::lean_xmss` | KAT-pinned against consensus-specs and leanVM | -| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs through a running `leanvm-sidecar` (`--pq-prover-socket`), which the image's `ethlambda-pq` supervisor starts (see [Proofs](#proofs)) | +| Attestation proofs | `ethlambda_crypto::stark` | the specification's reference concatenation by default; leanVM proofs made in process (bindings v0.19.0) on a network that schedules PQ (see [Proofs](#proofs)) | | Containers | `ethlambda_types::beacon::containers::{eip8483, pq}` | SSZ round trips, gaps per the spec; the maximal aggregate, attester slashing and bid encode to `pq.yaml`'s size bounds | | Fork upgrades | `upgrade::{upgrade_to_eip8483, upgrade_to_pq}` | unit-tested | | Block processing | `stf::{eip8483, pq}` | unit-tested with real XMSS keys | @@ -64,8 +68,8 @@ changes. | EIP-8483 gossip | `gossip`, `ethlambda_p2p::beacon::decode` | attestations, aggregates and attester slashings decode and validate as gloas's; blocks, envelopes and columns are ignored | | Block production | `pq_block_production`, `rpc::beacon::pq_proposal` | self-build; attestations packed from validated aggregates, their proofs merged under a deadline; blobs, their columns gossiped with the envelope. Every block it built on the devnet was canonical on Lighthouse | | VRF tree | `ethlambda_crypto::vrf` | the specification's Keccak-256 tree over all `2^31` leaves, each `keccak256(vrf_seed \|\| le64(slot))`; known answers from ethereum-package's published state. Restorable from a compact state (root and leaf 0's branch), which the package publishes for its genesis validators and `ethlambda pq-keys` writes | -| Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | -| Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead on the sidecar | +| Validator client | `ethlambda_validator::pq` and the duty services | seeds derived from each BLS key as ethereum-package's generator and Lighthouse derive them; attestations, aggregates, PTC votes, proposals and envelopes, each at its leaf; aggregators staggered by seat; run on devnets next to other clients' (see [Running a devnet](#running-a-devnet)) | +| Aggregation | `rpc::beacon::pq_aggregation`, `pools::{PqSignaturePool, PqAggregatePool}` | the node collects its aggregators' committees' signatures and proves ahead with leanVM, seat by seat | | Beacon API | `rpc::beacon::{pool, pq_proposal, ptc, proposal}` | PQ attestations, aggregates (in and out), payload attestations, blocks, envelopes and `POST /eth/v1/validator/pq_blocks/{slot}`; the other endpoints refuse PQ's signed containers | ## Gossip @@ -139,57 +143,69 @@ over a few leaves only, for tests. `ethlambda_crypto::stark` proves, merges and verifies the fork's attestation proofs through one of two backends, chosen once per process: -- **Reference** (the default): the specification's stand-in for a recursive - STARK. A proof is the signatures concatenated in statement order, and - verification checks each, plus the exact length. It is capped by - `MAX_STARK_PROOF_SIZE` (1 MiB), about 436 signatures per block. The - specification's fixtures use it. -- **Sidecar** (`--pq-prover-socket`, `stark::install_sidecar`): real leanVM - proofs, made and checked by a `leanvm-sidecar` process over a Unix socket, - through leanVM's own client crate at `c5ee9d239` (bindings v0.15.0, - `sidecar::LEANVM_REV`), the release pq-devnet-0 runs for its signer, - prover, verifier and sidecar. A statement list maps to leanVM - claims as Lighthouse maps it: the sorted, deduplicated - `(public key, message)` pairs, the empty proof for no claims, and merges - folded sixteen children at a time. -- **Who starts the sidecar**: not the node, as for Lighthouse. The image's - `ethlambda-pq` supervisor (`bin/ethlambda/pq/ethlambda-pq`, Lighthouse's - `lighthouse-pq-bn` adapted) starts it on a private socket, waits for it to - listen, and runs `ethlambda --pq-prover-socket `. The node - exiting stops the sidecar. The sidecar exiting does not stop the node - (Lighthouse's script stops it): the sidecar is started again on the same - socket after a pause (one second, doubling to 32 while it keeps dying - within a minute), and the node's client reconnects on its next request. - Until then the node proves nothing, gossip aggregates it cannot verify are - IGNOREd (`prover_unreachable`) rather than held against their senders, and - a block whose proof it could not check fails import and is fetched again - later (there is no bad-block cache). The gap is the sidecar's warm-up, not - the pause: on the local devnet, a sidecar on 2 threads killed mid-run - served again 50 s later (12 s at the container's start, on an idle - machine). Its node's head stood still meanwhile, so the two blocks it - proposed were built on a stale head and orphaned, and it imported the - block it had missed 8 s after the sidecar came back. After - `LEANVM_MAX_RESTARTS` (10) quick exits in a row the supervisor stops the - node too. `LEANVM_THREADS` sets the - sidecar's proving threads, `LEANVM_SIDECAR` another executable. The image - builds `leanvm-sidecar` from the commit in the root `leanvm-revision` file, - or from - `--build-arg LEANVM_REV` (the publish workflow's `leanvm_rev` input), and - records the commit at `/usr/local/share/ethlambda/leanvm-revision`. The - node's client refuses a sidecar whose hello names another protocol version - or verifier tag; any other revision is accepted, and its proofs only have - to verify with the other clients' verifiers (Teku's v0.16.0 sidecar and - ethlambda's v0.15.0 one verified each other's on the interop devnet). A - verifier-tag change needs `sidecar::LEANVM_REV` and the client crates - moved with it. +- **Reference**: the specification's stand-in for a recursive STARK. A proof + is the signatures concatenated in statement order, and verification checks + each, plus the exact length. It is capped by `MAX_STARK_PROOF_SIZE` (1 MiB), + about 436 signatures per block. The specification's fixtures use it, and so + does any process that never installs leanVM. +- **leanVM** (`stark::install_leanvm`, `stark::leanvm`): real leanVM proofs, + made and checked in this process by `lean_vm` at `351f7ae4` (bindings + v0.19.0, `leanvm::LEANVM_REV`), the one release pq-devnet-1 runs for its + signer, prover and verifier. A statement list maps to leanVM claims as + Lighthouse maps it: the sorted, deduplicated `(public key, message)` pairs, + the empty proof for no claims, and merges folded sixteen children + (`MAX_RECURSIONS`) at a time. The node installs it itself, as soon as + `--network` resolves to a network that schedules PQ, after + `lean_vm::setup` starts the prover's pool (`--pq-prover-threads`, 0 for + one thread per core, and never more than the cores) and builds its + aggregation program. leanVM proves one proof at a time per process; + verifying takes no lock and runs on the calling thread, so it does not + wait for a proof. +- **The self-check.** Setup ends by proving and verifying one throwaway + signature, and checking the proof does not verify against another claim. + A prover that cannot run on the machine stops the node at startup rather + than missing every aggregation duty, and the `leanVM prover ready` line + carries what the proof and its check took. +- **Panics stay inside.** In a sidecar, an input that crashed leanVM cost + that process a restart. In the node, the caller is the thread importing a + block or judging gossip, and the proof bytes are a peer's. Every call into + leanVM is wrapped (`leanvm::guarded`): a panic in the verifier reads as a + proof that does not verify, one in the prover as a proof that was not + made, and both are logged as `leanVM panicked`. +- **The build.** leanVM's experimental prover (the one pq-devnet-0's sidecar + ran; the same proofs as the stable one, faster). The image builds with the + `leanvm-cpu-tiers` feature and leanVM's `scripts/tier-rustc` as + `RUSTC_WRAPPER` (the Dockerfile fetches it at the pinned revision): the + prover is compiled once more per CPU tier (AVX-512, GFNI and VPCLMULQDQ + on x86-64, SHA3 on arm64) and picks the fastest one the host has at run + time, as the other clients' leanVM builds do. Every other crate keeps the + portable baseline in `.cargo/config.toml`. A build without the feature, + which is what `cargo build` gives, proves on that baseline alone, and + leanVM says so on stderr at the first proof when the CPU has more. +- **What it costs.** `ethlambda pq-prover-check` proves and verifies an + aggregate of `--signatures` claims (128 by default) on the machine it runs + on and reports each round against a seat's proving window, 2.4 s of a + 12-second slot. On 14 cores of an Apple M4 Max, a `release-fast` build + proves 128 signatures in about 0.28 s and 512 in about 0.86 s; verifying + takes about 6 ms either way, and the proofs are 160 to 200 KB. + +pq-devnet-0 ran the prover as a separate `leanvm-sidecar` (bindings v0.15.0), +which the image built and its `ethlambda-pq` supervisor started and +restarted; while it restarted, gossip aggregates were IGNOREd +(`prover_unreachable`). v0.17.0 removed the sidecar and its client API, so +the image builds none, nothing can be unreachable, and `ethlambda-pq` is a +shim that execs `ethlambda` (`LEANVM_THREADS` becomes `--pq-prover-threads`) +for launchers that still call it. A proof from another leanVM revision does +not verify, and nothing on the wire says why: the root `leanvm-revision` +file names the pin, and the image records it at +`/usr/local/share/ethlambda/leanvm-revision`. The encodings are not interchangeable, so every node of a network must use -the same backend; the PQ devnet's Lighthouse accepts only the sidecar. A -leanVM proof does not attest the leaf a signature was made at, so the sidecar -backend checks that each key signed the message at *some* leaf -(`docs/spec_deviations.md`). Lighthouse's blocks replay through ethlambda's -state transition with every proof verified this way, state root for state -root. +the same backend; the PQ devnet runs leanVM. A leanVM proof does not attest +the leaf a signature was made at, so the leanVM backend checks that each key +signed the message at *some* leaf (`docs/spec_deviations.md`). On +pq-devnet-0, Lighthouse's blocks replayed through ethlambda's state +transition with every proof verified this way, state root for state root. ### Leaves @@ -251,9 +267,22 @@ fork too, and those are not applied to any fork yet, the PQ forks included. See ## Committees -The PQ fork caps a slot's committees at `MAX_COMMITTEES_PER_SLOT_PQ` (16 on -mainnet, 4 on minimal), for every epoch a PQ state is asked about, including a -previous epoch that ran before the fork. The committee cache's `ShufflingKey` +The PQ fork caps a slot's committees at `X_MAX_COMMITTEE_COUNT_PER_SLOT` (16 +on mainnet, 4 on minimal), for every epoch a PQ state is asked about, +including a previous epoch that ran before the fork. The key is a temporary, +testing-only config value (`af898d07`): a devnet lowers it to put its +validators into fewer, larger committees. It may not exceed the preset's +`MAX_COMMITTEES_PER_SLOT_PQ`, the length of `CommitteeBits`. The state +transition counts committees from a state alone, so the node selects the cap +once per process from the network's `config.yaml`, beside the preset +(`network::select_committee_cap`). A file that omits the key runs on its +preset's `MAX_COMMITTEES_PER_SLOT_PQ`, which the specification's own +configs set it to, not on the mainnet 16 an absent key otherwise parses as: +a minimal network whose file predates the key keeps its four committees. A +value above the preset's is refused at startup, as the specification +forbids it; a zero is one committee, as `get_committee_count_per_slot` has +it. A process that selects no cap (the spec tests) runs on the preset's +value, and a resume refuses a changed cap. The committee cache's `ShufflingKey` carries the cap, since a state either side of the fork names the same epoch and deciding block but a different shuffling. @@ -265,26 +294,27 @@ previous, current and lookahead epochs. ## The VRF tree XMSS signatures are not unique, so a RANDAO reveal signed with one could be -ground. A validator instead registers as its VRF root the root of a Merkle -tree of depth `VRF_TREE_DEPTH` (31), hashed with Keccak-256, whose leaf for a -slot is `compute_vrf_leaf(vrf_seed, slot) = keccak256(vrf_seed || le64(slot))` -(consensus-specs `pq` at `2f43bc0f`, the pq-devnet-0 spec). The reveal is the -leaf followed by its branch, and `process_randao` mixes the leaf in. - -The root costs the whole tree: a leaf hashes its index, so no two leaves are -equal and no subtree can be reused, about two Keccak-256 calls for each of -`2^31` leaves (`vrf::tests::the_whole_tree_...`, `--ignored`). -ethereum-package publishes each genesis validator's root and leaf 0's branch, -which `ethlambda_crypto::vrf::tests::matches_ethereum_packages_published_state` -checks validator 0's against. +ground. A validator instead has a secret for each slot, +`compute_vrf_secret(vrf_seed, slot)`, and registers as its VRF root the root +of a Merkle tree of depth `VRF_TREE_DEPTH` (31), hashed with Keccak-256, +whose leaf for a slot is `compute_vrf_leaf(secret, slot)`: a hash of +`VRF_LEAF_DOMAIN`, the secret and the slot. The reveal is the secret followed +by the leaf's branch, and `process_randao` mixes the secret in. + +Two consequences, both deliberate in the specification: + +- **A reveal discloses only its own slot's secret.** The branch holds + commitments, never secrets. (Before `b5d422b2` the leaf was the secret + itself, so the sibling leaf in a branch was the neighbouring slot's reveal.) +- **The root costs the whole tree.** A leaf commits to its index, so no two + leaves are equal and no subtree can be reused: the root takes three + Keccak-256 calls for each of `2^31` leaves, about 100 seconds of all 14 + cores of an Apple M4 Max (`vrf::tests::the_whole_tree_...`, `--ignored`). `is_valid_vrf_proof` folds the branch itself (`vrf::fold_vrf_branch`), not -through the SHA-256 `is_valid_merkle_branch`. It reads the slot's low 31 bits -only, so a proof for `slot` also opens `slot + 2^31`, as the specification -has it. - -consensus-specs' later `b5d422b2` makes each leaf commit to a per-slot secret -and reveals the secret instead; branch `pq-devnet-0-b5d422b2` follows it. +through the SHA-256 `is_valid_merkle_branch`. The leaf commits to the whole +slot while the branch reads only its low 31 bits, so a proof for `slot` does +not open `slot + 2^31`. ## Inclusion delay @@ -358,14 +388,13 @@ it: 2. With `--vrf-state-url` (a URL or a path), the key's record in a file of precomputed states, read at its validator index: ethereum-package's `vrf_state_url` format, 1028 bytes a validator (the root, four zero - bytes, then leaf 0's branch), which ethereum-package publishes for its - genesis validators and `ethlambda pq-keys` writes. The record must fold - the key's own leaf 0 to its root, so a record of another validator's, or - of another VRF rule's, falls through to the next source. + bytes, then leaf 0's branch), which `ethlambda pq-keys` writes. The + record must fold the key's own leaf 0 to its root, so a record of another + validator's, or of another VRF rule's, falls through to the next source. A proof then hashes only the leaves below the slot's highest bit, a few milliseconds on a young chain. 3. The whole tree, hashed. It keeps the `2^15` nodes 16 levels above the - leaves (1 MiB), and a proof rebuilds one + leaves (1 MiB, commitments only, so no secret), and a proof rebuilds one `2^16`-leaf subtree, about 30 ms. The hashing runs in a rayon pool of its own, one thread short of the cores: leanXMSS signing parallelizes on rayon's global pool, which runs a job from outside it only once a @@ -389,7 +418,12 @@ A start drops the leaves of slots more than two epochs back, which nothing asks for again. - **Attesting**: a `SingleAttestation` signed at the target epoch's leaf, - published on one of PQ's 16 subnets. The client votes once a beacon node + published on one of PQ's 16 subnets. Each one is published as soon as its + signature exists (`AttestationService::publish_pq_as_signed`, + `pq::sign_each`), with whatever else was signed by then, not once the + slot's batch is signed: a key that has to build a bottom tree first takes + seconds, and held for it, every other key's vote would miss the + aggregators' cutoff too. The client votes once a beacon node reports a non-optimistic `head` at the slot whose block the attestation data names, or at the attestation deadline otherwise (`head_monitor`, as at every fork); it used to wait for the deadline every slot, which put its @@ -401,22 +435,27 @@ asks for again. - **Proposing**: the client sends its VRF proof for the slot (the RANDAO reveal) to `POST /eth/v1/validator/pq_blocks/{slot}`, signs the block and the envelope revealing its self-built payload at their leaves, and publishes - both. The block's attestations are packed a third of a slot ahead, when + both. The payload is built toward the gas target of the proposer's own PQ + preferences for the slot (the network's `GAS_LIMIT_SCHEDULE`, unless + `--gas-limit` or the keymanager says otherwise), else the parent's gas + limit, which would hold the chain's limit where it is. The block's attestations are packed a third of a slot ahead, when the chain actor starts the slot's payload build for a proposer a validator client registered here (`ethlambda_blockchain::pq_attestation_packing`): it picks, from the aggregates it validated, what `process_attestation` accepts at the slot and credits someone new, as `compute_on_chain_aggregate` - shapes them, and merges their proofs in `process_stark`'s order on the - sidecar. A block at `N` packs aggregates from `N - 2` and earlier, all held + shapes them, and merges their proofs in `process_stark`'s order with + leanVM. A block at `N` packs aggregates from `N - 2` and earlier, all held by then. Production takes that result when it is for the head it builds on and the pool still holds what it was packed from, and otherwise packs while the execution client builds the payload, as it always did. A merge must end three quarters of the way to the attestation deadline (Lighthouse's bound). One child needs no merge; when more do not finish in time, the block packs the most valuable single-committee attestation - alone, whose proof is the block's as it is. A two-child merge takes about - 0.6 s on pq-devnet-0's hosts (about four seconds on the local devnet's VM), - which is what packing ahead takes off every block's path. + alone, whose proof is the block's as it is. A two-child merge took about + 0.6 s on pq-devnet-0's sidecar and up to about 2 s in process in + pq-devnet-1's first hours (about four seconds on the local devnet's VM, + for Lighthouse too), which is what packing ahead takes off every block's + path. A payload with blobs keeps them on the node that built it, and the envelope's publication builds the data columns from them and gossips them with it (PQ keeps gloas's sidecar). @@ -429,28 +468,40 @@ asks for again. two, as `pq/p2p-interface.md` asks. - **Aggregating**: a PQ aggregator is a member of its committee's aggregation committee, which the attester duties report as - `is_aggregator`. Every aggregator broadcasts at gloas's aggregate deadline - (`AGGREGATE_DUE_BPS_GLOAS`, 6 s into a 12-second slot); `2f43bc0f` neither - staggers them nor has them skip a covered aggregate (consensus-specs' - later `4595f0fc` does both; branch `pq-devnet-0-b5d422b2` follows it). - Proving takes seconds, so the node proves ahead, as Lighthouse's PQ branch - does: the client's committee subscriptions join the committee's subnet and - register it, the node keeps the validated votes' signatures for registered - committees, and halfway between the attestation and aggregate deadlines - seals the slot and proves each committee before the aggregate deadline. - `GET aggregate_attestation` then answers the proved aggregate and its - proof, or a 404 when the node proved none, and the client signs the - `AggregateAndProof` at the slot's aggregate leaf. + `is_aggregator`, with its seat in it as `aggregator_position`. The seats + are staggered (PQ `validator.md`, "Construct aggregate"): the one at + `position` stops collecting at `get_aggregation_cutoff_ms(position)` + (`AGGREGATION_CUTOFF_BPS` plus `position` times `AGGREGATOR_DELAY_BPS`) and + broadcasts at `get_aggregate_due_ms(position)` (`AGGREGATE_DUE_BPS_PQ` plus + the same delay); on a 12-second slot that is 4.8 s and 7.2 s for the first + seat, each later one 0.6 s after. Proving takes seconds, so the node proves + ahead, as Lighthouse's PQ branch does: the client's committee subscriptions + join the committee's subnet and register it with the aggregating validator, + the node keeps the validated votes' signatures for registered committees, + and at each seat's cutoff proves what it has for the committees one of its + validators holds that seat in. A node holding two seats of one committee + proves at the later one only if a vote arrived since the earlier one's + proof (`PqSignaturePool::is_proven`): otherwise the aggregate would be the + same, for as long again on a prover that makes one proof at a time. The + client asks for each aggregate at its seat's broadcast time, every seat on + its own, so a request the node holds while a proof is still being made + does not delay the seats after it; `GET aggregate_attestation` answers the proved + aggregate and its proof, or a 404 when an aggregate already broadcast for + the committee, gossip's or this node's, covers every attester of it + (`should_broadcast_aggregate`). The client signs the `AggregateAndProof` at + the slot's aggregate leaf. ## Running a devnet ethpandaops/ethereum-package's `pq` branch runs PQ-at-genesis devnets with -ethlambda as beacon node, validator client or both (its -`.github/tests/cl-pq.yaml` names every client's `pq-devnet-0` image; the -pq-devnet-0 notes, `notes.ethereum.org/@ethpandaops/pq-devnet-0`, pin the -rest). Build the image from the repository root (`docker build -t -ethlambda:pq-local .`: it ships `leanvm-sidecar`, built from the commit in -`leanvm-revision`, and the `ethlambda-pq` supervisor), then `kurtosis run +ethlambda as beacon node, validator client or both. This branch targets +pq-devnet-1 (`notes.ethereum.org/@ethpandaops/pq-devnet-1`): consensus-specs +`pq` at `4c296784` and leanVM bindings v0.19.0, which every client must run, +since proofs from another revision do not verify. The example below names +pq-devnet-0's images for the other clients; swap in their pq-devnet-1 images +once published (the notes list them as TBD). Build the image from the +repository root (`docker build -t ethlambda:pq-local .`: the node proves in +process, so there is no sidecar to ship), then `kurtosis run --enclave pq --args-file params.yaml` with, for example, ethlambda next to Teku and Lodestar, and Silver's beacon node behind ethlambda's validator client (Silver has no client of its own): @@ -461,8 +512,8 @@ participants: el_image: ethpandaops/geth:glamsterdam-devnet-8 cl_type: ethlambda cl_image: ethlambda:pq-local - cl_extra_env_vars: - LEANVM_THREADS: "2" + cl_extra_params: + - --pq-prover-threads=2 vc_type: ethlambda vc_image: ethlambda:pq-local validator_count: 16 @@ -499,32 +550,44 @@ package runs `ethereum/client-go:latest`. What the package does for ethlambda on a PQ network: -- It runs the beacon node as `ethlambda-pq beacon `: the supervisor - starts the sidecar on a private socket, waits for it to listen, and runs - the node on it, restarting the sidecar if it exits (see [Proofs](#proofs)). - `LEANVM_THREADS` (through `cl_extra_env_vars`) caps the sidecar's threads. +- It runs the beacon node as `ethlambda-pq beacon `, pq-devnet-0's + sidecar supervisor, which is now a shim that execs `ethlambda` (see + [Proofs](#proofs)); `LEANVM_THREADS`, if set, becomes + `--pq-prover-threads`. - It passes the validator client `--init-slashing-protection` and, for its default mnemonic, the leanXMSS tree caches and VRF tree states it publishes for that mnemonic's first 10000 validators (`--xmss-cache-url`, `--vrf-state-url`). The client refuses a flag given twice, so `vc_extra_params` must not repeat them. - Its genesis generator gives each validator the leanXMSS key and VRF seed - the validator client derives from the BLS key. For another mnemonic, or + the validator client derives from the BLS key. pq-devnet-1's VRF rule is + `b5d422b2`'s (leaves commit to revealed secrets), and its legacy keys are + keccak256 (`4c296784`): tree states and keys published for pq-devnet-0's + rule fail their check against the seed, and the validator client then + hashes the tree itself (minutes a key) rather than use them. For another mnemonic, or past the published 10000, `ethlambda pq-keys --mnemonic ... --count N --output-dir keys` writes the key file the generator reads (`xmss_pubkey_url`) and the VRF states (`vrf_state_url`); every root hashes a whole tree, minutes a validator, and the run is resumable. +Before genesis, `docker run --rm --entrypoint ethlambda ethlambda:pq-local +pq-prover-check` on a devnet host says whether its prover keeps up with a +committee of 128 (see [Proofs](#proofs)). + Limits worth knowing: - **At least 32 validators** on the mainnet preset: gloas's `compute_ptc` asserts every slot has an attester, so with fewer, epoch processing fails at the first epoch boundary (`compute_balance_weighted_selection: total > 0`) and the chain stops. The specification does the same. -- **Memory.** Every `leanvm-sidecar` warms up by proving twice and stays - large. In Docker Desktop's default 8 GB VM a second sidecar next to - Lighthouse's has had the kernel kill Lighthouse's. Set `LEANVM_THREADS` on - nodes that only verify. +- **Memory.** A proof's buffers are now the node's own allocations, on top + of everything else it holds, where they were a sidecar's. The node's + jemalloc returns them to the kernel some seconds after the proof, as it + does any freed memory. leanVM's own builds instead keep them + (`dirty_decay_ms:-1`), so the next proof does not fault each page in + again, at the price of the process holding its peak; the image's + jemalloc reads `MALLOC_CONF`, so `MALLOC_CONF=dirty_decay_ms:-1` trades + the same way, for the whole node. Not measured here. - **Lighthouse's envelopes over req/resp.** Its `pq-devnet-0` image (last checked at `sha256:f571048f`) answered `execution_payload_envelopes_by_{range,root}` with a gloas-shaped envelope @@ -534,7 +597,7 @@ Limits worth knowing: What shows interop working: the beacon APIs agree on the head and finality; ethlambda's `lean_beacon_gossip_validation_total` is all `accept` (blocks, -envelopes, aggregates with their proofs checked through the sidecar, +envelopes, aggregates with their proofs checked by leanVM, attestations, payload attestations, proposer preferences); `lean_beacon_aggregate_total{outcome="applied"}` rises; every envelope is `VALID` (`Execution payload envelope verified ... status=Valid`); every block @@ -548,7 +611,10 @@ each ethlambda validator client logs `Derived the validators' PQ keys ... stored=0 cached=N built=0 refused=0 trees_built=0` and `Every validator's VRF tree is ready ... loaded=N hashed=0`, about a second each. A restart on the same `--validators-dir` reads both from disk instead (`stored=N`), since the -first start writes every key's trees and VRF state there. +first start writes every key's trees and VRF state there. VRF states +published for pq-devnet-0's rule (leaves revealed, before `b5d422b2`) fail +their check against the seed instead, and show as `loaded=0 hashed=N` after +minutes per key: the package has to publish states for pq-devnet-1's rule. To check ethlambda alone, give two participants `cl_type: ethlambda` and `vc_type: ethlambda` with 16 validators each (the 32 minimum), and no other @@ -567,7 +633,7 @@ No consensus-specs release ships fixtures for either fork. The pyspec on the ```sh git clone https://github.com/ethereum/consensus-specs && cd consensus-specs -git checkout 2f43bc0f989f47af81df390a90bc1f78e2436323 +git checkout 4c296784bb6ff54cbdcf72ebdda2a1057cce8893 make test reftests=true fork=eip8483 preset=minimal make test reftests=true fork=pq preset=minimal ``` @@ -604,6 +670,11 @@ generated. - The ENR's `attnets` keeps the pre-PQ backbone across the PQ boundary: ethrex's `DiscoveryServer` cannot replace the served record at runtime (the same gap as its `eth2` entry, see `CLAUDE.md`). +- Interop at pq-devnet-1's spec (`4c296784`): its genesis and key + derivation are still TBD in the devnet notes, and until ethPandaOps' + generator and the other clients follow `b5d422b2`'s VRF rule and + `4c296784`'s keccak256 legacy keys, a mixed network cannot run. An + ethlambda-only network runs on files `ethlambda pq-keys` writes. - PQ block production does not weigh builder bids: it self-builds, and the PQ builder market it would read is filled but unused. - The pubkey index cache keys a pubkey by bytes 1 to 9, all zero for a PQ diff --git a/docs/cli.md b/docs/cli.md index eaad50d01..d893a529e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -165,7 +165,7 @@ something specific here. |---|---|---| | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | -| `--pq-prover-socket` | none | The Unix socket of a running `leanvm-sidecar`, which makes and checks the PQ fork's attestation proofs as leanVM STARKs, the encoding the PQ devnet's clients use. The node refuses a sidecar whose protocol version or verifier tag differs from its client's (leanVM `c5ee9d239`, bindings v0.15.0). Without it the node uses the specification's reference encoding (the signatures concatenated), which only another node on the reference accepts. Read only on a network scheduling PQ. The image's `ethlambda-pq` supervisor (`bin/ethlambda/pq/`, as Lighthouse's `lighthouse-pq-bn`) starts a sidecar and passes this flag: `ethlambda-pq beacon `, with `LEANVM_THREADS` for its proving threads (0, the default: one per core) and `LEANVM_SIDECAR` for another executable than the image's `leanvm-sidecar` | +| `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.19.0 (`351f7ae4`, the release pq-devnet-1 runs, and the only one it takes). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, @@ -379,7 +379,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | `--metrics-port` | `5064` | Prometheus metrics port | | `--keymanager-port` | `5062` | Keymanager API port. Only bound with `--enable-keymanager` | | `--suggested-fee-recipient` | none | Execution address to receive block rewards, `0x`-prefixed, for every validator the keymanager API gives no address of its own. Optional, and startup warns when it is absent: without it the beacon node picks an address, and it will not be yours. The addresses reach each beacon node as one `prepare_beacon_proposer` request every slot, listing each validator that has an index on chain and an address, as Lighthouse's validator client sends it. The zero address is accepted, as every other client accepts it, but reported at error at startup: it burns the rewards, and builder registrations and proposer preferences sign it for the builder to pay | -| `--gas-limit` | `60000000` | The gas limit every validator targets, unless the keymanager API gives it its own. Before gloas it goes into builder registrations (with `--builder-proposals`). From gloas it goes into the proposer preferences, which are published for every proposal, and the beacon node builds this client's own payloads toward it as well, so a network whose gas limit is not 60M needs it set, or every proposal pulls the limit toward 60M. **Sepolia and Platåberget schedule `200000000`** (their `config.yaml`'s `GAS_LIMIT_SCHEDULE`, which this client does not read yet, [#795](https://github.com/lambdaclass/ethlambda/issues/795)), so on either pass `--gas-limit 200000000`. Must be positive | +| `--gas-limit` | the network's schedule, else `60000000` | The gas limit every validator targets, unless the keymanager API gives it its own. Before gloas it goes into builder registrations (with `--builder-proposals`). From gloas it goes into the proposer preferences, which are published for every proposal, and the beacon node builds this client's own payloads toward it as well. Without it, each validator targets the gas limit the network's `GAS_LIMIT_SCHEDULE` (served on the beacon nodes' `/eth/v1/config/spec`; every node is asked at startup and again every epoch, and the first in `--beacon-nodes` order that serves a non-empty schedule is followed, with a warning while none does and gloas is scheduled) names for the proposal's epoch, and `60000000` for an epoch the schedule names none or a node that does not serve it, as Lighthouse does; Sepolia's, Platåberget's and pq-devnet-1's schedules name `200000000`, so none needs the flag. Must be positive | | `--graffiti` | empty | Text for the graffiti field of proposed blocks, for every validator the keymanager API gives no graffiti of its own. At most 32 bytes as UTF-8, right-padded with zeros. Refused rather than truncated if longer. An ethlambda beacon node appends both clients' versions to it (see [`rpc.md`](rpc.md#validator-endpoints)) | | `--enable-keymanager` | off | Serve the keymanager API: keystores, remote keys, plus each validator's own fee recipient, graffiti and gas limit. Off by default because it mutates key material | | `--web3signer-url` | none | Base URL of a Web3Signer (`https://signer:9000`): the signer a remote key imported through `POST /eth/v1/remotekeys` without a `url` of its own is assigned to. Checked for shape at startup. Keys whose definitions entry names a signer need no default | @@ -825,7 +825,7 @@ give one validator its own value in place of the command line's default: |---|---|---| | `feerecipient` | `--suggested-fee-recipient` | Once the duties of the slot it is set in are done, when the fee recipients are sent to the beacon node again, as they are after every slot's duties (the next slot's while a slow beacon node still holds the last send). A validator imported since the last epoch boundary, or with no index on chain yet, is first sent once an epoch boundary resolves its index. A block proposed before then pays the address the node was last given, and the check before signing reports the mismatch. With `--builder-proposals`, the next builder registration carries it too, usually at the next slot (later while the epoch's full registration send is still running) and again every slot until a node accepts it or the epoch's full send carries it, and an ethlambda beacon node takes it from there. A `DELETE` that leaves a validator with no address at all (no `--suggested-fee-recipient` either) sends no fee recipient and no registration, so the beacon node and the builder keep paying the address they were last given. From gloas, the proposer preferences carry it, from the next dependent root on | | `graffiti` | `--graffiti` | The next proposal | -| `gas_limit` | `--gas-limit` | Before gloas, the next builder registration with `--builder-proposals` (usually at the next slot, later while the epoch's full registration send is still running, and again every slot until a node accepts it or the epoch's full send carries it), and stored and served only without it. From gloas, the proposer preferences' target gas limit, from the next dependent root on, flag or not | +| `gas_limit` | `--gas-limit`, else the network's schedule | Before gloas, the next builder registration with `--builder-proposals` (usually at the next slot, later while the epoch's full registration send is still running, and again every slot until a node accepts it or the epoch's full send carries it), and stored and served only without it. From gloas, the proposer preferences' target gas limit, from the next dependent root on, flag or not | **These persist.** Each is written onto the validator's entry in `validator_definitions.yml` (`suggested_fee_recipient`, `graffiti`, `gas_limit`, @@ -970,6 +970,23 @@ names (EIP-7044), an epoch from before deneb included, so a pre-signed exit stays valid across every fork to come. The command signs that way, and the [keymanager API](#the-keymanager-api)'s `voluntary_exit` route does too. +## `pq-prover-check` + +Proves and verifies one PQ-fork aggregate with leanVM on the machine it runs +on, and reports what it took against an aggregator seat's proving window +(2.4 s of a 12-second slot). No network and no data directory: it answers +whether a host keeps up before a devnet's genesis. + +| Flag | Default | Description | +|------|---------|-------------| +| `--signatures` | `128` | How many signatures the aggregate proves, 1 to 4096: one committee's attesters | +| `--threads` | `0` | leanVM prover threads, 0 for one per core: the node's `--pq-prover-threads` | +| `--rounds` | `3` | How many times to prove; the first round pays for whatever the prover sets up on first use | + +Each round logs `prove_ms`, `verify_ms` and `proof_bytes`, and the last line +says whether the slowest round fits the window (a warning when it does not). +See [`beacon_pq.md`](beacon_pq.md#proofs) for what the prover is built with. + ## `slashing-protection` Moves the validator client's EIP-3076 history in and out of its diff --git a/docs/data_storage.md b/docs/data_storage.md index 706056320..9bc070327 100644 --- a/docs/data_storage.md +++ b/docs/data_storage.md @@ -284,7 +284,8 @@ different checkpoints. | `chain` | raw byte | both | Which consensus protocol this directory holds (`Chain`) | | `preset` | raw byte | both | Which SSZ preset the writing build used (`Preset`) | | `time` | `u64` | both | The store clock, as a **UNIX timestamp in milliseconds** | -| `config` | `Config` | both | The node's runtime configuration | +| `config` | `Config` | both | The node's runtime configuration, except the keys below that have rows of their own | +| `config_gas_limit_schedule` | `List[GasLimitScheduleEntry, 32]` | both | `GAS_LIMIT_SCHEDULE` (gloas, EIP-8261); absent in a directory written before it | | `head` | `H256` | both | Current fork choice head | | `anchor_slot` | `u64` | both | The slot this directory's chain begins at | | `states_pruned_below` | `u64` | both | Exclusive upper bound of the `States`/`StateDiffs` slots already range-deleted; absent means 0 | @@ -298,6 +299,18 @@ Rows marked for one chain are never written on the other, so reaching one through the wrong chain's accessor panics naming the key rather than reading a zero. That is deliberate: a data directory holds one chain for its whole life. +`config` is a positional SSZ container, so a field added to it would leave +every row written before it undecodable. A `Config` key added since +`DB_VERSION` 10 therefore takes zero bytes there and gets a `config_*` row of its +own (`CONFIG_ROWS` in `store.rs`). An older directory just lacks the row: a +beacon resume reports the key as missing, adds the config file's value and +writes the row, instead of failing. An older build never reads the row. Every +`config*` row is written in one batch, at bootstrap and by `replace_config`. +A lean resume never rewrites `config`, so a lean directory that predates a row +goes on lacking it and runs on the field's zero-width default; each such key's +default must therefore be the value `Config::lean` holds, as +`GAS_LIMIT_SCHEDULE`'s empty schedule is. + #### One clock, three readings `time` is the only clock either chain keeps, and it is a UNIX millisecond. @@ -341,9 +354,10 @@ migration path. `config` and `chain` are the odd ones out among the mutable rows: written at bootstrap (`init_store` for lean, `init_beacon` for beacon) and not mutated as the chain progresses. `chain` is never rewritten (it has a getter, -`Store::chain`, and no setter). `config` is rewritten in one place, -`Store::replace_config`, by a beacon resume whose config file changed values -the directory does not contradict (see below), and that method panics unless +`Store::chain`, and no setter). `config` (with its `config_*` rows) is +rewritten in one place, `Store::replace_config`, by a beacon resume whose +config file changed values the directory does not contradict (see below) or +whose directory predates a `config_*` row, and that method panics unless its `Store` holds the only handle to the cached copy. Because neither changes once a `Store` is shared, the `Store` keeps a copy of each in memory, and reads of them never reach the backend. Every other `Metadata` key is mutated @@ -397,8 +411,8 @@ because a second row denominated in `slot ‖ root` would be a value that could drift from the first. `init_beacon` writes the two beacon-only keys plus `db_version`, `chain`, -`preset`, `config`, `time`, `head`, `anchor_slot`, `latest_justified` and -`latest_finalized` in one atomic batch. +`preset`, `config` and its `config_*` rows, `time`, `head`, `anchor_slot`, +`latest_justified` and `latest_finalized` in one atomic batch. `anchor_slot` is the odd one among these: every other row is either a format tag or something a later writer moves, while this one is written once at @@ -907,7 +921,8 @@ A `Store` is created through one of four constructors in The first two funnel into `init_store`, which writes the anchor in **one atomic batch**: the `Metadata` keys a lean directory needs (the format version -and the chain and preset tags, time, config, head = safe_target = anchor root, +and the chain and preset tags, time, config and its `config_*` rows, head = +safe_target = anchor root, justified = finalized = anchor checkpoint), the anchor header, its `BlockRoots` entry, the body if non-empty, a full snapshot into `States` keyed by the anchor's slot and root (the base of every future diff chain), and the anchor's `LiveChain` entry. `time` @@ -926,7 +941,8 @@ one row an import does not write is the anchor's `BlockRoots` entry, which `index_beacon_anchor` adds right after the block (see [BlockRoots](#blockroots)). `from_db_state` is the restore path: it reads `db_version`, `preset`, `chain`, -`config` and `anchor_slot` from `Metadata`, returning `None` for an empty DB. A format +`config` (with whichever `config_*` rows the directory has) and `anchor_slot` +from `Metadata`, returning `None` for an empty DB. A format mismatch is still fatal, failing with `Error::DbVersionMismatch` or `Error::PresetMismatch` rather than reading on, but `from_db_state` no longer judges the network or the chain, and it does not mutate anything either: it diff --git a/docs/metrics.md b/docs/metrics.md index 29cbf29ea..a0578e26a 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -460,9 +460,7 @@ The two topics add reasons the others do not, all `reason` label values on `lean_beacon_gossip_validation_total`: `outside_epoch_window`, `covered_bits` (aggregate only), `unknown_block`, `state_unavailable`, `finalized_not_ancestor`, `ancestry_unknown`, `payload_envelope_unseen` and -`payload_optimistic` (gloas only), and `prover_unreachable` (PQ aggregate -only: the prover sidecar did not answer, so the proof was not judged) on the -ignore side; +`payload_optimistic` (gloas only) on the ignore side; `epoch_mismatch`, `no_participants` (aggregate only), `non_zero_data_index`, `committee_bits` (aggregate only), `committee_index`, `bits_length` (aggregate only), `not_aggregator` (aggregate only), `not_in_committee`, diff --git a/docs/rpc.md b/docs/rpc.md index 3bcc6ccd7..e53731e6c 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -344,7 +344,11 @@ the publish endpoints. The Beacon API has no PQ block production yet, so ethlambda's validator client asks `POST /eth/v1/validator/pq_blocks/{slot}` with `{"randao_reveal": [], "graffiti"?}`; the block's graffiti gets both clients' codes appended, as `produceBlockV3`'s -does (see its **Graffiti** note below). Attester duties at a PQ epoch add `is_aggregator`, the validator's seat in +does (see its **Graffiti** note below). The payload is built toward the gas +target of the proposer's own signed PQ preferences for the slot, when this +node holds them under the slot's dependent root, else the parent bid's gas +limit; its fee recipient is `prepare_beacon_proposer`'s, else the zero +address. Attester duties at a PQ epoch add `is_aggregator`, the validator's seat in its committee's aggregation committee, and `GET aggregate_attestation` at a PQ slot answers `{"aggregate", "proof"}`, the aggregate this node proved for its aggregators' committee (Lighthouse's PQ branch's `PqAggregate`), or 404. @@ -1025,6 +1029,13 @@ gloas's `MAX_*_SIZE` preset keys, which bound gossip message sizes the node does not run on. Domain types and withdrawal prefixes are `0x`-prefixed hex; `VERSIONED_HASH_VERSION_KZG` is a decimal, as lighthouse reports it. `GENESIS_TIME` is absent: `/eth/v1/beacon/genesis` reports it. +`GAS_LIMIT_SCHEDULE` (gloas, EIP-8261) is a list of `{"EPOCH", "GAS_LIMIT"}` +entries with quoted values, ascending by epoch, as `BLOB_SCHEDULE` is and as +lighthouse reports it, and `[]` on a network that schedules nothing (lighthouse +leaves the key out while gloas is unscheduled). Validator clients, this one's +included, take their default gas limit from it. The data directory stores it, +in a row of its own; a directory written before that row existed takes the +network `config.yaml`'s on its next start. The configuration keys come from the `Config` the data directory was initialized with. Some of them (the custody and subnet counts, the diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index c8ad82a25..18d1ca234 100644 --- a/docs/spec_deviations.md +++ b/docs/spec_deviations.md @@ -1005,7 +1005,7 @@ signature, whichever way the node answered. Three departures: ## EIP-8483 and PQ run on a newer gloas than the gloas fork does -consensus-specs' `pq` branch (`2f43bc0f989f47af81df390a90bc1f78e2436323`) is +consensus-specs' `pq` branch (`4c296784bb6ff54cbdcf72ebdda2a1057cce8893`) is based on a `master` newer than this repository's pin (`v1.7.0-beta.2`). Across every fork's `beacon-chain.md`, `fork.md` and `fork-choice.md`, the rules that changed in between are the three state-transition rules below, the four @@ -1125,15 +1125,15 @@ Two more: The specification's `stark.VerifyAggregates` checks each signature at its statement's leaf index, and its reference implementation does (a proof is the signatures concatenated). The PQ devnet's clients prove with leanVM -instead, through a `leanvm-sidecar` (`--pq-prover-socket`, -`ethlambda_crypto::stark::sidecar`), and a leanVM proof attests only +instead, in process from bindings v0.19.0 (`ethlambda_crypto::stark::leanvm`, +installed on any network that schedules PQ), and a leanVM proof attests only `(public key, message)` claims (leanEthereum/leanVM#787). So under the -sidecar backend a proof shows each key signed the message at *some* leaf, +leanVM backend a proof shows each key signed the message at *some* leaf, not at the statement's. Proving still refuses a signature made at another leaf, since it sees the signatures, which is Lighthouse's behavior too. The two encodings are not interchangeable: a node verifies only the backend it -runs, so a network picks one, and the reference stays the default for the -specification's fixtures. +runs, so a network picks one, and the reference stays what the +specification's fixtures run. ## The genesis block's body carries the state's bid from gloas on diff --git a/leanvm-revision b/leanvm-revision index a4c800f4e..75f098b90 100644 --- a/leanvm-revision +++ b/leanvm-revision @@ -1 +1 @@ -c5ee9d239e42d0bc8113eb4aee3e2cae5faf1764 +351f7ae421529ce164ed747eee1f78bdeaec3e80