datahaven/test/tools/validator-set-submitter/main.ts
Ahmad Kaouk 401f646286
feat: automated validator set submission with era targeting (#433)
## Era-targeted validator set submission with dedicated submitter role

> **Note:** This PR includes a detailed specification at
[`specs/validator-set-submission/validator-set-submission.md`](https://github.com/datahaven-xyz/datahaven/blob/feat/validator-set-submitter/specs/validator-set-submission/validator-set-submission.md)
that covers the design rationale, submission lifecycle, era-targeting
rules, and failure modes. Reading the spec first will make the contract,
pallet, and daemon changes easier to follow.

### Summary

- Introduce a dedicated `validatorSetSubmitter` role on
`DataHavenServiceManager`, separating validator set submission authority
from the contract owner
- Replace the unscoped `sendNewValidatorSet` with
`sendNewValidatorSetForEra`, which encodes a `targetEra` into the
Snowbridge message payload
- Add server-side era validation in the `external-validators` pallet to
reject stale, duplicate, or out-of-range submissions
- Add a long-running TypeScript daemon that watches session changes and
automatically submits each era's validator set at the right time

### Contract changes (`contracts/`)

- **New `validatorSetSubmitter` storage slot** — set during `initialize`
and rotatable via `setValidatorSetSubmitter` (owner-only). The storage
gap is decremented accordingly.
- **`sendNewValidatorSet` → `sendNewValidatorSetForEra`** — accepts a
`uint64 targetEra` parameter and is restricted to
`onlyValidatorSetSubmitter` instead of `onlyOwner`.
- **`buildNewValidatorSetMessageForEra`** — the
`NewValidatorSetPayload.externalIndex` is now caller-supplied instead of
hardcoded to `0`.
- **New events** — `ValidatorSetSubmitterUpdated`,
`ValidatorSetMessageSubmitted`.
- **New error** — `OnlyValidatorSetSubmitter`.
- **New test suite** — `ValidatorSetSubmitter.t.sol` covering submitter
set/rotate, access control, era encoding, and legacy function removal.

### Pallet changes (`operator/`)

- **`validate_target_era`** in `external-validators` — enforces
`activeEra < targetEra <= activeEra + 1` and `targetEra > ExternalIndex`
(dedup guard).
- **New errors** — `TargetEraTooOld`, `TargetEraTooNew`,
`DuplicateOrStaleTargetEra`.
- **Tests** — five new test cases for era boundary conditions (next-era
acceptance, old-era rejection, too-new rejection, duplicate rejection,
genesis behavior). Existing `era_hooks_with_external_index` test updated
to use valid target eras.
- **Runtime test fixes** — `external_index: 0` → `1` in
mainnet/stagenet/testnet EigenLayer message processor tests to satisfy
the new validation.

### Validator set submitter daemon
(`test/tools/validator-set-submitter/`)

- Event-driven service that subscribes to finalized
`Session.CurrentIndex` via Polkadot-API `watchValue`.
- Submits once per era during the last session, targeting `ActiveEra +
1`.
- Tracks submitted eras to avoid duplicates; skips if `ExternalIndex`
already covers the target.
- Startup self-checks: Ethereum connectivity, DataHaven connectivity,
on-chain submitter authorization.
- Supports `--dry-run` mode and YAML configuration.
- Graceful shutdown on `SIGINT`/`SIGTERM`.

### Test & tooling updates

- **E2E test** (`validator-set-update.test.ts`) — calls
`sendNewValidatorSetForEra` with a computed `targetEra` and filters the
substrate event by `external_index`.
- **`update-validator-set.ts` script** — accepts `--target-era` flag;
defaults to era 1 for fresh networks.
- **CLI launch** — wires validator set update as an interactive step
after relayer launch.
- **`package.json`** — new `submitter` and `submitter:dry-run` scripts.
- Regenerated contract bindings, PAPI metadata, state-diff, and storage
layout snapshots.

### Test plan

- [x] `forge test` — passes, including new `ValidatorSetSubmitter.t.sol`
- [x] `cargo test` — passes, including new era-validation tests in
`external-validators`
- [x] `bun test:e2e` — validator-set-update suite passes with
era-targeted flow
- [x] Manual: run submitter daemon against local network (`bun
submitter`), verify it submits once per era at the correct session

## ⚠️ Breaking Changes ⚠️

- **`sendNewValidatorSet` removed** — replaced by
`sendNewValidatorSetForEra(uint64 targetEra, ...)`. Callers must now
supply a `targetEra` parameter.
- **Access control changed** — validator set submission is now
restricted to the `validatorSetSubmitter` role instead of the contract
`owner`. The submitter address is set during `initialize` and rotatable
via `setValidatorSetSubmitter` (owner-only).
- **`external-validators` pallet now validates `targetEra`** — messages
with a stale, duplicate, or out-of-range `external_index` are rejected
on-chain. Existing integrations sending `external_index: 0` will fail
validation.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-20 10:31:44 +01:00

92 lines
3 KiB
TypeScript

import { Command } from "@commander-js/extra-typings";
import { logger } from "utils/logger";
import { privateKeyToAccount } from "viem/accounts";
import { getOnChainSubmitter } from "./chain";
import { loadConfig } from "./config";
import { createClients, startSubmitter } from "./submitter";
const program = new Command()
.name("validator-set-submitter")
.description("Automatically submits validator-set updates from Ethereum to DataHaven each era");
program
.command("run")
.description("Start the submitter daemon")
.option(
"--config <path>",
"Path to YAML config file",
"./tools/validator-set-submitter/config.yml"
)
.option(
"--submitter-private-key <key>",
"Override submitter private key (or use SUBMITTER_PRIVATE_KEY env var)"
)
.option("--dry-run", "Log what would be submitted without sending transactions", false)
.action(async (opts) => {
const config = await loadConfig(opts.config, {
dryRun: opts.dryRun,
submitterPrivateKey: opts.submitterPrivateKey
});
logger.info("Validator Set Submitter starting...");
logger.info(`Ethereum RPC: ${config.ethereumRpcUrl}`);
logger.info(`DataHaven WS: ${config.datahavenWsUrl}`);
logger.info(`ServiceManager: ${config.serviceManagerAddress}`);
logger.info(`Dry run: ${config.dryRun}`);
const clients = createClients(config);
// Startup self-checks
try {
const blockNumber = await clients.publicClient.getBlockNumber();
logger.info(`Ethereum connected — block #${blockNumber}`);
} catch (err) {
logger.error(`Cannot connect to Ethereum RPC: ${err}`);
process.exit(1);
}
try {
const header = await clients.papiClient.getBlockHeader();
logger.info(`DataHaven connected — block #${header.number}`);
} catch (err) {
logger.error(`Cannot connect to DataHaven WS: ${err}`);
process.exit(1);
}
// Verify our account is authorized on-chain
try {
const account = privateKeyToAccount(config.submitterPrivateKey);
const onChainSubmitter = await getOnChainSubmitter(
clients.publicClient,
config.serviceManagerAddress
);
if (onChainSubmitter.toLowerCase() !== account.address.toLowerCase()) {
logger.error(
`Account ${account.address} is not the authorized submitter (on-chain: ${onChainSubmitter})`
);
process.exit(1);
}
logger.info(`Authorized submitter verified: ${account.address}`);
} catch (err) {
logger.error(`Failed to verify submitter authorization: ${err}`);
process.exit(1);
}
// Graceful shutdown
const ac = new AbortController();
const shutdown = () => {
logger.info("Shutdown signal received, stopping...");
ac.abort();
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
try {
await startSubmitter(clients, config, ac.signal);
} finally {
clients.papiClient.destroy();
logger.info("Submitter stopped, PAPI client destroyed");
}
});
program.parse();