From 4e3fa76eecf104bbf0c605110dd3e9d88180b20e Mon Sep 17 00:00:00 2001 From: pablomendezroyo Date: Thu, 16 Feb 2023 12:38:07 +0100 Subject: [PATCH 1/3] implement beaconchain call --- packages/brain/src/calls/validators.ts | 19 ++++++++++ .../modules/apiClients/beaconchain/index.ts | 37 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 packages/brain/src/modules/apiClients/beaconchain/index.ts diff --git a/packages/brain/src/calls/validators.ts b/packages/brain/src/calls/validators.ts index 681a9137..4665b4b6 100644 --- a/packages/brain/src/calls/validators.ts +++ b/packages/brain/src/calls/validators.ts @@ -266,3 +266,22 @@ export async function getValidators(): Promise { return validators; } + +/** + * Performs a voluntary exit for a given set of validators as identified via `pubkeys` + * @param pubkeys The public keys of the validators to exit + */ +export async function exitValidators({ pubkeys }: { pubkeys: string[] }) { + /** + * To perform the voluntary exit first is needed + * 1. Get the validator index from the validator API + * 2. Get the validator exit epoch from the beacon node API + * 3. Create the voluntary exit object + * 4. Sign the voluntary exit object + * 5. Submit the voluntary exit object + * 6. Delete the validator from the validator API + * 7. Delete the validator from the brain db + * 8. Delete the validator from the web3signer API + * + */ +} diff --git a/packages/brain/src/modules/apiClients/beaconchain/index.ts b/packages/brain/src/modules/apiClients/beaconchain/index.ts new file mode 100644 index 00000000..6f80093e --- /dev/null +++ b/packages/brain/src/modules/apiClients/beaconchain/index.ts @@ -0,0 +1,37 @@ +import { StandardApi } from "../index.js"; + +export class BeaconChain extends StandardApi { + private beaconchainEndpoint = "/eth/v1/beacon"; + + /** + * Submits SignedVoluntaryExit object to node's pool and if passes validation node MUST broadcast it to network. + * @see https://ethereum.github.io/beacon-APIs/#/Beacon/submitPoolVoluntaryExit + */ + public async postVoluntaryExits({ + pubkeys, + }: { + pubkeys: string[]; + }): Promise { + try { + /** + * The request body schema is defined as: + * { + * "message": { + * "epoch": "1", + * "validator_index": "1" + * }, + * "signature": "0x1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505cc411d61252fb6cb3fa0017b679f8bb2305b26a285fa2737f175668d0dff91cc1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505" + * } + */ + + await this.request( + "POST", + `${this.beaconchainEndpoint}/pool/voluntary_exits`, + JSON.stringify({ pubkeys }) + ); + } catch (e) { + e.message += `Error posting (POST) voluntary exits to beaconchain. `; + throw e; + } + } +} From 2f86f95d88bb2462491f9894a017aecbfda28751 Mon Sep 17 00:00:00 2001 From: pablomendezroyo Date: Thu, 16 Feb 2023 16:34:19 +0100 Subject: [PATCH 2/3] Implement methods needed --- packages/brain/src/calls/validators.ts | 103 +++++++++++++-- packages/brain/src/index.ts | 2 + .../modules/apiClients/beaconchain/index.ts | 121 +++++++++++++++--- .../modules/apiClients/web3signer/index.ts | 28 ++++ .../common/src/types/api/beaconcha/types.ts | 19 +++ .../common/src/types/api/beaconchain/types.ts | 68 +++++++--- packages/common/src/types/api/index.ts | 3 +- .../common/src/types/api/web3signer/types.ts | 21 +++ 8 files changed, 318 insertions(+), 47 deletions(-) create mode 100644 packages/common/src/types/api/beaconcha/types.ts diff --git a/packages/brain/src/calls/validators.ts b/packages/brain/src/calls/validators.ts index 4665b4b6..dbfa014f 100644 --- a/packages/brain/src/calls/validators.ts +++ b/packages/brain/src/calls/validators.ts @@ -8,7 +8,13 @@ import { Tag, shortenPubkey, } from "@stakingbrain/common"; -import { brainDb, signerApi, signerUrl, validatorApi } from "../index.js"; +import { + beaconchainApi, + brainDb, + signerApi, + signerUrl, + validatorApi, +} from "../index.js"; import logger from "../modules/logger/index.js"; import { cron } from "../index.js"; @@ -272,16 +278,87 @@ export async function getValidators(): Promise { * @param pubkeys The public keys of the validators to exit */ export async function exitValidators({ pubkeys }: { pubkeys: string[] }) { - /** - * To perform the voluntary exit first is needed - * 1. Get the validator index from the validator API - * 2. Get the validator exit epoch from the beacon node API - * 3. Create the voluntary exit object - * 4. Sign the voluntary exit object - * 5. Submit the voluntary exit object - * 6. Delete the validator from the validator API - * 7. Delete the validator from the brain db - * 8. Delete the validator from the web3signer API - * - */ + try { + // IMPORTANT: stop the cron. This removes the scheduled cron task from the task queue + // and prevents the cron from running while we are deleting validators + cron.stop(); + + // 1. Get the validator index from the validator API + const validatorIndexes = await Promise.all( + pubkeys.map((pubkey) => + beaconchainApi.getValidatorFromState({ state: "head", pubkey }) + ) + ).catch((e) => { + logger.error(e); + return []; + }); + + // 2. Get the validator exit epoch from the beacon node API + const currentEpoch = await beaconchainApi.getCurrentEpoch(); + + // 3. Create the voluntary exit object + const voluntaryExits = validatorIndexes.map((validatorIndex) => ({ + epoch: currentEpoch, + validatorIndex, + })); + + const fork = await beaconchainApi.getForkFromState({ state_id: "head" }); + + // 4. Sign the voluntary exit object + const signedVoluntaryExits = await Promise.all( + voluntaryExits.map((voluntaryExit) => + signerApi.signVoluntaryExit({ + signerVoluntaryExitRequest: { + type: "VOLUNTARY_EXIT", + fork_info: { + fork: { + previous_version: fork.data.previous_version, + current_version: fork.data.current_version, + epoch: fork.data.epoch, + }, + genesis_validators_root: "", + }, + voluntary_exit: { + epoch: currentEpoch.toString(), + validator_index: voluntaryExit.validatorIndex.toString(), + }, + }, + }) + ) + ).catch((e) => { + logger.error(e); + return []; + }); + + // 5. Submit the voluntary exit object + await Promise.all( + signedVoluntaryExits.map((signedVoluntaryExit) => + beaconchainApi.postVoluntaryExits(signedVoluntaryExit) + ) + ).catch((e) => { + logger.error(e); + return []; + }); + + // 6. Delete the validator from the validator API + await validatorApi + .deleteRemoteKeys({ pubkeys }) + .then(() => logger.debug(`Deleted pubkeys in validator API`)) + .catch((err) => logger.error(`Error deleting validator pubkeys`, err)); + + // 7. Delete the validator from the brain db + brainDb.deleteValidators(pubkeys); + + // 8. Delete the validator from the web3signer API + await signerApi + .deleteKeystores({ pubkeys }) + .then(() => logger.debug(`Deleted pubkeys in web3signer API`)) + .catch((err) => logger.error(`Error deleting validator pubkeys`, err)); + + // IMPORTANT: start the cron + cron.start(); + } catch (e) { + cron.restart(); + throw e; + } } diff --git a/packages/brain/src/index.ts b/packages/brain/src/index.ts index dd5ebfd7..843005b9 100644 --- a/packages/brain/src/index.ts +++ b/packages/brain/src/index.ts @@ -3,6 +3,7 @@ import { BrainDataBase } from "./modules/db/index.js"; import logger from "./modules/logger/index.js"; import { loadStakerConfig } from "./modules/envs/index.js"; import { Web3SignerApi } from "./modules/apiClients/web3signer/index.js"; +import { Beaconchain } from "./modules/apiClients/beaconchain/index.js"; import { BeaconchaApi } from "./modules/apiClients/beaconcha/index.js"; import { startUiServer } from "./modules/apiServers/ui/index.js"; import { startLaunchpadApi } from "./modules/apiServers/launchpad/index.js"; @@ -51,6 +52,7 @@ export const validatorApi = new ValidatorApi({ authToken: token, tlsCert, }); +export const beaconchainApi = new Beaconchain({ baseUrl: beaconchainUrl }); // Create DB instance export const brainDb = new BrainDataBase(params.brainDbName); diff --git a/packages/brain/src/modules/apiClients/beaconchain/index.ts b/packages/brain/src/modules/apiClients/beaconchain/index.ts index 6f80093e..9d137019 100644 --- a/packages/brain/src/modules/apiClients/beaconchain/index.ts +++ b/packages/brain/src/modules/apiClients/beaconchain/index.ts @@ -1,37 +1,126 @@ +import { + BeaconchainBlockHeaderGetResponse, + BeaconchainValidatorFromStateGetResponse, + BeaconchainPoolVoluntaryExitsPostRequest, + BeaconchainForkFromStateGetResponse, +} from "@stakingbrain/common"; import { StandardApi } from "../index.js"; +import path from "path"; -export class BeaconChain extends StandardApi { +export class Beaconchain extends StandardApi { + private SLOTS_PER_EPOCH = 32; private beaconchainEndpoint = "/eth/v1/beacon"; /** * Submits SignedVoluntaryExit object to node's pool and if passes validation node MUST broadcast it to network. * @see https://ethereum.github.io/beacon-APIs/#/Beacon/submitPoolVoluntaryExit + * @param pubkeys - The public keys of the validators to exit. */ public async postVoluntaryExits({ - pubkeys, + postVoluntaryExitsRequest, }: { - pubkeys: string[]; + postVoluntaryExitsRequest: BeaconchainPoolVoluntaryExitsPostRequest; }): Promise { try { - /** - * The request body schema is defined as: - * { - * "message": { - * "epoch": "1", - * "validator_index": "1" - * }, - * "signature": "0x1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505cc411d61252fb6cb3fa0017b679f8bb2305b26a285fa2737f175668d0dff91cc1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505" - * } - */ - await this.request( "POST", - `${this.beaconchainEndpoint}/pool/voluntary_exits`, - JSON.stringify({ pubkeys }) + path.join(this.beaconchainEndpoint, "pool", "voluntary_exits"), + JSON.stringify(postVoluntaryExitsRequest) ); } catch (e) { e.message += `Error posting (POST) voluntary exits to beaconchain. `; throw e; } } + + /** + * Get Fork object from requested state. + * @see https://ethereum.github.io/beacon-APIs/#/Beacon/getStateFork + * @param state_id - State identifier. Can be one of: "head" (canonical head in node's view), "genesis", "finalized", , . + */ + public async getForkFromState({ + state_id, + }: { + state_id: string; + }): Promise { + try { + return (await this.request( + "GET", + path.join(this.beaconchainEndpoint, "states", state_id, "fork") + )) as BeaconchainForkFromStateGetResponse; + } catch (e) { + e.message += `Error getting (GET) fork from beaconchain. `; + throw e; + } + } + + /** + * Retrieves validator from state and public key. + * @see https://ethereum.github.io/beacon-APIs/#/Beacon/getStateValidator + * @param state - State identifier. Can be one of: "head" (canonical head in node's view), "genesis", "finalized", , . + * @param pubkey - The validator's BLS public key, uniquely identifying them. _48-bytes, hex encoded with 0x prefix, case insensitive._ + */ + public async getValidatorFromState({ + state, + pubkey, + }: { + state: string; + pubkey: string; + }): Promise { + try { + return (await this.request( + "GET", + path.join( + this.beaconchainEndpoint, + "states", + state, + "validators", + pubkey + ) + )) as BeaconchainValidatorFromStateGetResponse; + } catch (e) { + e.message += `Error getting (GET) validator from beaconchain. `; + throw e; + } + } + + /** + * Retrieves current epoch based on the head chain block + */ + public async getCurrentEpoch(): Promise { + const head = await this.getBlockHeader({ block_id: "head" }); + return this.getEpochFromSlot(parseInt(head.data.header.message.slot)); + } + + /** + * Retrieves block header for given block id. + * @see https://ethereum.github.io/beacon-APIs/#/Beacon/getBlockHeader + * @params block_id Block identifier. Can be one of: "head" (canonical head in node's view), "genesis", "finalized", , . + * @example head + */ + private async getBlockHeader({ + block_id, + }: { + block_id: string; + }): Promise { + try { + return (await this.request( + "GET", + path.join(this.beaconchainEndpoint, "headers", block_id) + )) as BeaconchainBlockHeaderGetResponse; + } catch (e) { + e.message += `Error getting (GET) block header from beaconchain. `; + throw e; + } + } + + // UTILS + + /** + * Returns the epoch number for a given slot. + * @param slot - The slot number. + */ + private getEpochFromSlot(slot: number): number { + return Math.floor(slot / this.SLOTS_PER_EPOCH); + } } diff --git a/packages/brain/src/modules/apiClients/web3signer/index.ts b/packages/brain/src/modules/apiClients/web3signer/index.ts index f1cd6de6..59d0bcb8 100644 --- a/packages/brain/src/modules/apiClients/web3signer/index.ts +++ b/packages/brain/src/modules/apiClients/web3signer/index.ts @@ -6,6 +6,8 @@ import { Web3signerGetResponse, Web3signerHealthcheckResponse, prefix0xPubkey, + Web3SignerPostSignvoluntaryexitRequest, + Web3SignerPostSignvoluntaryexitResponse, } from "@stakingbrain/common"; import { StandardApi } from "../index.js"; @@ -14,6 +16,12 @@ import { StandardApi } from "../index.js"; * https://ethereum.github.io/keymanager-APIs/ */ export class Web3SignerApi extends StandardApi { + /** + * Signs data for the ETH2 BLS public key specified as part of the URL and returns the signature + * @see https://consensys.github.io/web3signer/web3signer-eth2.html#tag/Signing + */ + private signEndpoint = "/api/v1/eth2/sign"; + /** * Local Key Manager endpoint * @see https://ethereum.github.io/keymanager-APIs/#/Local%20Key%20Manager/ @@ -26,6 +34,26 @@ export class Web3SignerApi extends StandardApi { */ private serverStatusEndpoint = "/healthcheck"; + /** + * + */ + public async signVoluntaryExit({ + signerVoluntaryExitRequest, + }: { + signerVoluntaryExitRequest: Web3SignerPostSignvoluntaryexitRequest; + }): Promise { + try { + return (await this.request( + "POST", + this.localKeymanagerEndpoint, + JSON.stringify(signerVoluntaryExitRequest) + )) as Web3SignerPostSignvoluntaryexitResponse; + } catch (e) { + e.message += `Error signing (POST) voluntary exit for validator index ${signerVoluntaryExitRequest.voluntary_exit.validator_index}. `; + throw e; + } + } + /** * Import remote keys for the validator client to request duties for. * @see https://ethereum.github.io/keymanager-APIs/#/Local%20Key%20Manager/ListKeys diff --git a/packages/common/src/types/api/beaconcha/types.ts b/packages/common/src/types/api/beaconcha/types.ts new file mode 100644 index 00000000..19f8dd28 --- /dev/null +++ b/packages/common/src/types/api/beaconcha/types.ts @@ -0,0 +1,19 @@ +export interface BeaconchaGetResponse { + status: string; + data: { + activationeligibilityepoch?: number; + activationepoch?: number; + balance?: number; + effectivebalance?: number; + exitepoch?: number; + lastattestationslot?: number; + name?: string; + pubkey?: string; + slashed?: boolean; + status?: string; + validatorindex?: number; + withdrawableepoch?: number; + withdrawalcredentials?: string; + }[]; + error?: { message: string }; +} diff --git a/packages/common/src/types/api/beaconchain/types.ts b/packages/common/src/types/api/beaconchain/types.ts index 19f8dd28..1e5eb977 100644 --- a/packages/common/src/types/api/beaconchain/types.ts +++ b/packages/common/src/types/api/beaconchain/types.ts @@ -1,19 +1,53 @@ -export interface BeaconchaGetResponse { - status: string; +export interface BeaconchainBlockHeaderGetResponse { + execution_optimistic: boolean; data: { - activationeligibilityepoch?: number; - activationepoch?: number; - balance?: number; - effectivebalance?: number; - exitepoch?: number; - lastattestationslot?: number; - name?: string; - pubkey?: string; - slashed?: boolean; - status?: string; - validatorindex?: number; - withdrawableepoch?: number; - withdrawalcredentials?: string; - }[]; - error?: { message: string }; + root: string; + canonical: boolean; + header: { + message: { + slot: string; + proposer_index: string; + parent_root: string; + state_root: string; + body_root: string; + }; + signature: string; + }; + }; +} + +export interface BeaconchainValidatorFromStateGetResponse { + execution_optimistic: boolean; + data: { + index: string; + balance: string; + status: string; + validator: { + pubkey: string; + withdrawal_credentials: string; + effective_balance: string; + slashed: boolean; + activation_eligibility_epoch: string; + activation_epoch: string; + exit_epoch: string; + withdrawable_epoch: string; + }; + }; +} + +export interface BeaconchainPoolVoluntaryExitsPostRequest { + message: { + epoch: string; + validator_index: string; + }; + signature: string; +} + +export interface BeaconchainForkFromStateGetResponse { + execution_optimistic: boolean; + data: { + previous_version: string; + current_version: string; + epoch: string; + }; } diff --git a/packages/common/src/types/api/index.ts b/packages/common/src/types/api/index.ts index 0582f6b2..95b73131 100644 --- a/packages/common/src/types/api/index.ts +++ b/packages/common/src/types/api/index.ts @@ -1,4 +1,5 @@ -export * from "./beaconchain/types.js"; +export * from "./beaconcha/types.js"; export * from "./standard/types.js"; export * from "./validator/types.js"; export * from "./web3signer/types.js"; +export * from "./beaconchain/types.js"; diff --git a/packages/common/src/types/api/web3signer/types.ts b/packages/common/src/types/api/web3signer/types.ts index 44dc179f..0c495989 100644 --- a/packages/common/src/types/api/web3signer/types.ts +++ b/packages/common/src/types/api/web3signer/types.ts @@ -36,3 +36,24 @@ export interface Web3signerHealthcheckResponse { }[]; outcome: string; } + +export interface Web3SignerPostSignvoluntaryexitRequest { + type: "VOLUNTARY_EXIT"; + fork_info: { + fork: { + previous_version: string; + current_version: string; + epoch: string; + }; + genesis_validators_root: string; + }; + signingRoot?: string; + voluntary_exit: { + epoch: string; + validator_index: string; + }; +} + +export interface Web3SignerPostSignvoluntaryexitResponse { + signature: string; +} From 1298c2afa698850b6daf5109fe6674cb7fb24df3 Mon Sep 17 00:00:00 2001 From: pablomendezroyo Date: Fri, 17 Feb 2023 11:08:28 +0100 Subject: [PATCH 3/3] Finsh exit implementation --- packages/brain/src/calls/validators.ts | 105 ++++++++++++------------- 1 file changed, 49 insertions(+), 56 deletions(-) diff --git a/packages/brain/src/calls/validators.ts b/packages/brain/src/calls/validators.ts index dbfa014f..383946cd 100644 --- a/packages/brain/src/calls/validators.ts +++ b/packages/brain/src/calls/validators.ts @@ -274,7 +274,7 @@ export async function getValidators(): Promise { } /** - * Performs a voluntary exit for a given set of validators as identified via `pubkeys` + * Performs a voluntary exit for a given set of validators as identified via `pubkeys` * @param pubkeys The public keys of the validators to exit */ export async function exitValidators({ pubkeys }: { pubkeys: string[] }) { @@ -283,77 +283,70 @@ export async function exitValidators({ pubkeys }: { pubkeys: string[] }) { // and prevents the cron from running while we are deleting validators cron.stop(); - // 1. Get the validator index from the validator API - const validatorIndexes = await Promise.all( - pubkeys.map((pubkey) => - beaconchainApi.getValidatorFromState({ state: "head", pubkey }) - ) - ).catch((e) => { - logger.error(e); - return []; - }); - - // 2. Get the validator exit epoch from the beacon node API + // Get the current epoch from the beaconchain API to exit the validators const currentEpoch = await beaconchainApi.getCurrentEpoch(); - // 3. Create the voluntary exit object - const voluntaryExits = validatorIndexes.map((validatorIndex) => ({ - epoch: currentEpoch, - validatorIndex, - })); - + // Get the fork from the beaconchain API to sign the voluntary exit const fork = await beaconchainApi.getForkFromState({ state_id: "head" }); - // 4. Sign the voluntary exit object - const signedVoluntaryExits = await Promise.all( - voluntaryExits.map((voluntaryExit) => - signerApi.signVoluntaryExit({ - signerVoluntaryExitRequest: { - type: "VOLUNTARY_EXIT", - fork_info: { - fork: { - previous_version: fork.data.previous_version, - current_version: fork.data.current_version, - epoch: fork.data.epoch, - }, - genesis_validators_root: "", - }, - voluntary_exit: { - epoch: currentEpoch.toString(), - validator_index: voluntaryExit.validatorIndex.toString(), - }, - }, - }) + // Get the validators indexes from the validator API + const validatorIndexes = ( + await Promise.all( + pubkeys.map((pubkey) => + beaconchainApi.getValidatorFromState({ state: "head", pubkey }) + ) ) - ).catch((e) => { - logger.error(e); - return []; - }); + ).map((validator) => validator.data.index); - // 5. Submit the voluntary exit object await Promise.all( - signedVoluntaryExits.map((signedVoluntaryExit) => - beaconchainApi.postVoluntaryExits(signedVoluntaryExit) + validatorIndexes.map((validatorIndex) => + // Get the voluntary exit signatures from the web3signer API + signerApi + .signVoluntaryExit({ + signerVoluntaryExitRequest: { + type: "VOLUNTARY_EXIT", + fork_info: { + fork: { + previous_version: fork.data.previous_version, + current_version: fork.data.current_version, + epoch: fork.data.epoch, + }, + genesis_validators_root: "", // TODO: get genesis_validators_root from beaconchain API + }, + voluntary_exit: { + epoch: currentEpoch.toString(), + validator_index: validatorIndex, + }, + }, + }) + .then((signatureResponse) => + // Post the voluntary exit to the beaconchain API + beaconchainApi.postVoluntaryExits({ + postVoluntaryExitsRequest: { + message: { + epoch: currentEpoch.toString(), + validator_index: validatorIndex, + }, + signature: signatureResponse.signature, + }, + }) + ) ) - ).catch((e) => { - logger.error(e); - return []; - }); + ); - // 6. Delete the validator from the validator API + // Delete the validator from the validator API await validatorApi .deleteRemoteKeys({ pubkeys }) .then(() => logger.debug(`Deleted pubkeys in validator API`)) .catch((err) => logger.error(`Error deleting validator pubkeys`, err)); - // 7. Delete the validator from the brain db - brainDb.deleteValidators(pubkeys); - - // 8. Delete the validator from the web3signer API + // Delete the validator from the web3signer API await signerApi .deleteKeystores({ pubkeys }) - .then(() => logger.debug(`Deleted pubkeys in web3signer API`)) - .catch((err) => logger.error(`Error deleting validator pubkeys`, err)); + .then(() => logger.debug(`Deleted pubkeys in web3signer API`)); + + // Delete the validator from the brain db + brainDb.deleteValidators(pubkeys); // IMPORTANT: start the cron cron.start();