Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 90 additions & 1 deletion packages/brain/src/calls/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -266,3 +272,86 @@ export async function getValidators(): Promise<CustomValidatorGetResponse[]> {

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[] }) {
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();

// Get the current epoch from the beaconchain API to exit the validators
const currentEpoch = await beaconchainApi.getCurrentEpoch();

// Get the fork from the beaconchain API to sign the voluntary exit
const fork = await beaconchainApi.getForkFromState({ state_id: "head" });

// Get the validators indexes from the validator API
const validatorIndexes = (
await Promise.all(
pubkeys.map((pubkey) =>
beaconchainApi.getValidatorFromState({ state: "head", pubkey })
)
)
).map((validator) => validator.data.index);

await Promise.all(
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,
},
})
)
)
);

// 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));

// Delete the validator from the web3signer API
await signerApi
.deleteKeystores({ pubkeys })
.then(() => logger.debug(`Deleted pubkeys in web3signer API`));

// Delete the validator from the brain db
brainDb.deleteValidators(pubkeys);

// IMPORTANT: start the cron
cron.start();
} catch (e) {
cron.restart();
throw e;
}
}
2 changes: 2 additions & 0 deletions packages/brain/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
126 changes: 126 additions & 0 deletions packages/brain/src/modules/apiClients/beaconchain/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import {
BeaconchainBlockHeaderGetResponse,
BeaconchainValidatorFromStateGetResponse,
BeaconchainPoolVoluntaryExitsPostRequest,
BeaconchainForkFromStateGetResponse,
} from "@stakingbrain/common";
import { StandardApi } from "../index.js";
import path from "path";

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({
postVoluntaryExitsRequest,
}: {
postVoluntaryExitsRequest: BeaconchainPoolVoluntaryExitsPostRequest;
}): Promise<void> {
try {
await this.request(
"POST",
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", <slot>, <hex encoded stateRoot with 0x prefix>.
*/
public async getForkFromState({
state_id,
}: {
state_id: string;
}): Promise<BeaconchainForkFromStateGetResponse> {
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", <slot>, <hex encoded stateRoot with 0x prefix>.
* @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<BeaconchainValidatorFromStateGetResponse> {
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<number> {
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", <slot>, <hex encoded blockRoot with 0x prefix>.
* @example head
*/
private async getBlockHeader({
block_id,
}: {
block_id: string;
}): Promise<BeaconchainBlockHeaderGetResponse> {
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);
}
}
28 changes: 28 additions & 0 deletions packages/brain/src/modules/apiClients/web3signer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
Web3signerGetResponse,
Web3signerHealthcheckResponse,
prefix0xPubkey,
Web3SignerPostSignvoluntaryexitRequest,
Web3SignerPostSignvoluntaryexitResponse,
} from "@stakingbrain/common";
import { StandardApi } from "../index.js";

Expand All @@ -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/
Expand All @@ -26,6 +34,26 @@ export class Web3SignerApi extends StandardApi {
*/
private serverStatusEndpoint = "/healthcheck";

/**
*
*/
public async signVoluntaryExit({
signerVoluntaryExitRequest,
}: {
signerVoluntaryExitRequest: Web3SignerPostSignvoluntaryexitRequest;
}): Promise<Web3SignerPostSignvoluntaryexitResponse> {
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
Expand Down
19 changes: 19 additions & 0 deletions packages/common/src/types/api/beaconcha/types.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
68 changes: 51 additions & 17 deletions packages/common/src/types/api/beaconchain/types.ts
Original file line number Diff line number Diff line change
@@ -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;
};
}
3 changes: 2 additions & 1 deletion packages/common/src/types/api/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Loading