Skip to content

feat(core): implement validatorapi voluntary_exit + validator_registrations handlers#460

Open
varex83agent wants to merge 11 commits into
mainfrom
bohdan/validatorapi-exit-registrations
Open

feat(core): implement validatorapi voluntary_exit + validator_registrations handlers#460
varex83agent wants to merge 11 commits into
mainfrom
bohdan/validatorapi-exit-registrations

Conversation

@varex83agent
Copy link
Copy Markdown
Collaborator

Summary

  • submit_voluntary_exit: implements validatorapi.go:752-795 — looks up
    the DV root pubkey via a new active_validators_fn hook, derives the
    duty slot as slots_per_epoch * epoch, builds the ParSignedData
    through signeddata::SignedVoluntaryExit::new_partial, verifies the
    partial signature against the DOMAIN_VOLUNTARY_EXIT domain at the
    exit's epoch, and fans the set out to every registered subscriber.
  • submit_validator_registrations: implements validatorapi.go:674-749
    — early-returns on empty input, swallows on disabled builder mode with
    a tracing::warn!, iterates entries through submit_one_registration
    which silently skips non-DV pubkeys (mirrors Go's swallowRegFilter),
    derives the slot from the registration timestamp + genesis time +
    slot duration, and verifies under DOMAIN_APPLICATION_BUILDER at
    epoch 0 (matches Go's VersionedSignedValidatorRegistration.Epoch).
  • Replaces the placeholder SignedVoluntaryExit and
    SignedValidatorRegistration unit structs in validatorapi/types.rs
    with real wrappers around phase0::SignedVoluntaryExit and
    versioned::VersionedSignedValidatorRegistration. The handler trait
    signatures are unchanged.
  • Adds one new ActiveValidatorsFn Component hook +
    register_active_validators method (same PR-1 pattern: Arc<…>,
    overwrite-on-re-register). Drops the now-stale #[allow(dead_code)]
    attributes on share_idx, builder_enabled, subs, and
    verify_partial_sig now that they're all consumed.

Go reference

Pluto Charon Go
Component::submit_voluntary_exit Component.SubmitVoluntaryExit (validatorapi.go:752-795)
Component::submit_validator_registrations Component.SubmitValidatorRegistrations (validatorapi.go:731-749)
Component::submit_one_registration (private) Component.submitRegistration (validatorapi.go:674-728)
slot_from_timestamp (private helper) SlotFromTimestamp (validatorapi.go:41-70)
ActiveValidatorsFn hook c.eth2Cl.ActiveValidators(ctx)
signeddata::SignedVoluntaryExit::new_partial core.NewPartialSignedVoluntaryExit
signeddata::VersionedSignedValidatorRegistration::new_partial core.NewPartialVersionedSignedValidatorRegistration

Test plan

  • cargo +nightly fmt --all --check
  • cargo clippy -p pluto-core --all-targets --all-features -- -D warnings
  • cargo test -p pluto-core --all-features — 383/383 passing (9 new):
    • submit_voluntary_exit_resolves_validator_and_fanouts (happy path),
    • submit_voluntary_exit_rejects_unknown_validator (400),
    • submit_voluntary_exit_returns_500_when_hook_unregistered,
    • submit_voluntary_exit_rejects_bad_signature (real BLS, 400),
    • submit_validator_registrations_swallows_when_builder_disabled,
    • submit_validator_registrations_no_op_on_empty_input,
    • submit_validator_registrations_swallows_non_dv_pubkey,
    • submit_validator_registrations_happy_path_fanouts,
    • submit_validator_registrations_rejects_bad_signature (real BLS, 400).

varex83 and others added 11 commits May 28, 2026 14:08
Threads the Handler through Axum state via AppState<H> + with_state,
wires the node_version route to the real handler, and adds a TestHandler
mock that future PRs will extend per-endpoint.
Re-uses the auto-generated pluto_eth2api envelopes
(GetProposerDutiesResponseResponse, GetVersionResponseResponse) as the
on-the-wire shape rather than hand-rolling parallel types. node_version
is migrated to the same pattern; the body.rs hand-rolled wrapper module
is removed.
Drops the per-handler generic parameter and routes through
Arc<dyn Handler> via AppState. The Handler trait is object-safe
(Send + Sync + 'static + async_trait-generated methods), so this
is a pure type change with no surface impact.
Adds the Handler impl that the router has been calling through.
node_version returns the obolnetwork/pluto/{version}-{commit}/{arch}-{os}
identity string; proposer_duties calls the upstream beacon node and
rewrites known DV root public keys to this node's public share so the
validator client sees keys matching its keystore. The remaining 17
trait methods are unimplemented!() stubs that land per-PR as their
router handlers are ported.
Wires POST /eth/v1/validator/duties/attester/{epoch}: dual-format
(numeric or string-encoded) validator index body, upstream call,
pubshare swap.
Wires POST /eth/v1/validator/duties/sync/{epoch}, reusing the
ValIndexes dual-format body extractor.
Wires GET /eth/v1/validator/attestation_data. The Component now
holds an Arc<MemDB> and awaits unsigned attestation data from the
local DutyDB rather than hitting upstream.
Bug fixes (must-fix per review):

- attestation_data: wrap MemDB::await_attestation in tokio::time::timeout
  (24s) so a request for a slot that never produces consensus output
  cannot hold a handler task indefinitely. delete_duty now records
  evicted keys per duty type and notifies waiters, so await_data returns
  Error::AwaitDutyExpired immediately when the awaited duty is gone
  instead of spinning until the timeout fires. Maps to 408 on the wire.
- Stop leaking upstream BlindedBlock400Response Debug output (incl.
  stacktraces) into the client-visible ApiError.message. The variant
  payload is now attached as `source` for debug logs; the message stays
  generic.

Hardening:

- new_insecure is gated behind #[cfg(test)] so the insecure_test flag
  cannot reach production builds.
- new_router applies DefaultBodyLimit::max(64 KiB) on the two
  POST /duties/{attester,sync}/{epoch} routes — defends against the
  Vec<u64> parse amplification on the ValIndexes deserializer.
- All upstream eth2_cl calls are wrapped in tokio::time::timeout(12s)
  so a hanging beacon node cannot stall handler tasks.
- proposer_duties / attester_duties / sync_committee_duties propagate
  upstream BadRequest as 400 and ServiceUnavailable as 503 instead of
  collapsing every non-Ok variant to 502 — the VC can now back off on
  upstream syncing instead of treating it as a gateway failure.
- swap_attester_pubshares / swap_sync_committee_pubshares now return
  500 (cluster misconfig) instead of 502 when a pubshare is missing —
  the upstream returned well-formed data, the failure is local.

ValIndexes:

- Replace #[serde(untagged)] with a streaming Visitor that validates
  each element via SeqAccess::next_element. Avoids the speculative
  Vec<u64> parse and the serde Content cache. Now accepts mixed
  numeric/string elements and rejects negative integers.
- Hard cap at 8192 indices per request.

ApiError:

- with_boxed_source for sources that aren't std::error::Error (e.g.
  anyhow::Error from auto-gen request builders).

Router:

- attestation_data uses Result<Query<...>, QueryRejection> so 4xx
  responses from missing/malformed query params share the same
  { code, message } envelope as the rest of the router.

Tests (+13):

- attestation_data: timeout when data never arrives; 408 when duty is
  evicted while a waiter is parked; cancellation cleanup when the
  handler future is dropped; negative lookup on wrong committee_index.
- Status-mapping helpers: confirm upstream Debug output is never
  serialized into the message.
- Router: ApiError envelope on bad query; oversized body rejection;
  ValIndexes empty/mixed/oversized/negative cases.

Co-Authored-By: Bohdan Ohorodnii <35969035+varex83@users.noreply.github.com>
Adds the plumbing every subsequent submit/await handler needs without
implementing any of the unimplemented!() arms. Mirrors Charon's
core/validatorapi/validatorapi.go:196-256 (subscriber list + six
Register* hooks) plus :1352 (verifyPartialSig).

- New Component fields: subs, await_proposal_fn, await_agg_attestation_fn,
  await_sync_contribution_fn, await_agg_sig_db_fn, duty_def_fn,
  pub_key_by_att_fn. All Option<Arc<…>> so registration before the
  Component is shared in an Arc, then read-only thereafter.
- subscribe() wraps the user closure with a set-clone step so each
  subscriber receives its own ParSignedDataSet — matches Go's
  Subscribe clone-before-fanout at validatorapi.go:249-256.
- register_* methods replace any prior registration, matching Go's
  single-function input semantics.
- verify_partial_sig() honours insecure_test, looks up this node's
  public share from pub_share_by_pubkey, then delegates to
  pluto_eth2util::signing::verify. Unlike Go — which projects domain /
  epoch / message-root through the core.Eth2SignedData interface — the
  Rust hook takes those three values directly so we don't have to port
  the Eth2SignedData trait in this plumbing PR; submit handlers in PRs
  3-6 will derive the triple from their concrete signed-data wrapper.

Tests: subscribe fanout clones per subscriber; the six register hooks
all overwrite on re-register; unregistered hooks default to None;
verify_partial_sig accepts a real BLS signature, rejects a tampered
one, rejects an unknown DV pubkey, and short-circuits in insecure_test
mode.

Co-Authored-By: Bohdan Ohorodnii <35969035+varex83@users.noreply.github.com>
…ations handlers

Replaces the two unimplemented!() arms on Component with the
real submit_voluntary_exit and submit_validator_registrations
handlers. Mirrors Charon's core/validatorapi/validatorapi.go:752-795
(SubmitVoluntaryExit), :674-728 (submitRegistration), and
:731-749 (SubmitValidatorRegistrations).

- types.rs: replace placeholder unit structs with real wrappers
  around phase0::SignedVoluntaryExit and
  versioned::VersionedSignedValidatorRegistration so handlers can
  read message-root, pubkey, timestamp, and signature.

- component.rs/submit_voluntary_exit:
  * Resolve the DV root pubkey via the new active_validators_fn
    hook (mirrors Go's c.eth2Cl.ActiveValidators). Unknown
    validator-index -> 400 ("validator not found") matching Go's
    errors.New branch.
  * Derive the duty slot as slots_per_epoch * exit_epoch via
    fetch_slots_config — same as Go's eth2wrap.FetchSlotsConfig
    path.
  * Build the ParSignedData through
    signeddata::SignedVoluntaryExit::new_partial, then call
    verify_partial_sig with DomainName::VoluntaryExit + exit.epoch
    + tree-hash of the unsigned message.
  * Fanout one set per subscriber via the existing subs vec.

- component.rs/submit_validator_registrations:
  * Empty-input early return + builder-mode gate (warn-and-swallow
    when builder_enabled = false) matching Go:732-739.
  * Per-entry submit_one_registration:
    - Group pubkey comes from v1.message.pubkey; if not a DV pubkey
      on this node, swallow with a tracing::debug and skip (mirrors
      Go's swallowRegFilter at :686-691).
    - SlotFromTimestamp inlined as slot_from_timestamp() — pure
      function over genesis_time + slot_duration.
    - ParSignedData built through
      signeddata::VersionedSignedValidatorRegistration::new_partial.
    - verify_partial_sig called with DomainName::ApplicationBuilder
      and epoch 0 — matches Go's
      VersionedSignedValidatorRegistration.Epoch returning 0.

- New ActiveValidatorsFn hook + register_active_validators method
  matches the existing PR-1 hook pattern (Arc<…> + overwrite-on-
  re-register). Dropped the dead_code allow attributes on
  share_idx, builder_enabled, subs, and verify_partial_sig now that
  they are all consumed by these handlers.

Tests (9 new):
- happy-path fanout for both endpoints (insecure_test mode),
- voluntary exit unknown-validator -> 400,
- voluntary exit unregistered hook -> 500,
- voluntary exit bad signature -> 400 (real BLS + BeaconMock),
- registrations empty-input no-op,
- registrations builder-disabled swallows without fanout,
- registrations non-DV pubkey swallowed (no fanout),
- registrations bad signature -> 400 (real BLS + BeaconMock).

cargo test -p pluto-core --all-features: 383/383 passing.

Co-Authored-By: Bohdan Ohorodnii <35969035+varex83@users.noreply.github.com>
@varex83agent varex83agent force-pushed the bohdan/validatorapi-plumbing branch from f5c3b49 to 8eedb3f Compare June 2, 2026 14:09
Base automatically changed from bohdan/validatorapi-plumbing to main June 3, 2026 20:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants