diff --git a/packages/api/src/beacon/routes/beacon/pool.ts b/packages/api/src/beacon/routes/beacon/pool.ts index aa2c36d3bc..42880b2767 100644 --- a/packages/api/src/beacon/routes/beacon/pool.ts +++ b/packages/api/src/beacon/routes/beacon/pool.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import {ValueOf} from "@chainsafe/ssz"; import {ChainForkConfig} from "@lodestar/config"; -import {isForkElectra} from "@lodestar/params"; +import {isForkPostElectra} from "@lodestar/params"; import {phase0, capella, CommitteeIndex, Slot, ssz, electra, AttesterSlashing} from "@lodestar/types"; import {Schema, Endpoint, RouteDefinitions} from "../../../utils/index.js"; import { @@ -262,7 +262,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions (isForkElectra(fork) ? AttestationListTypeElectra : AttestationListTypePhase0)), + data: WithVersion((fork) => (isForkPostElectra(fork) ? AttestationListTypeElectra : AttestationListTypePhase0)), meta: VersionCodec, }, }, @@ -281,7 +281,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions - isForkElectra(fork) ? AttesterSlashingListTypeElectra : AttesterSlashingListTypePhase0 + isForkPostElectra(fork) ? AttesterSlashingListTypeElectra : AttesterSlashingListTypePhase0 ), meta: VersionCodec, }, @@ -336,7 +336,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(signedAttestations[0]?.data.slot ?? 0); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? AttestationListTypeElectra.toJson(signedAttestations as AttestationListElectra) : AttestationListTypePhase0.toJson(signedAttestations as AttestationListPhase0), headers: {[MetaHeader.Version]: fork}, @@ -345,7 +345,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - signedAttestations: isForkElectra(fork) + signedAttestations: isForkPostElectra(fork) ? AttestationListTypeElectra.fromJson(body) : AttestationListTypePhase0.fromJson(body), }; @@ -353,7 +353,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(signedAttestations[0]?.data.slot ?? 0); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? AttestationListTypeElectra.serialize(signedAttestations as AttestationListElectra) : AttestationListTypePhase0.serialize(signedAttestations as AttestationListPhase0), headers: {[MetaHeader.Version]: fork}, @@ -362,7 +362,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - signedAttestations: isForkElectra(fork) + signedAttestations: isForkPostElectra(fork) ? AttestationListTypeElectra.deserialize(body) : AttestationListTypePhase0.deserialize(body), }; @@ -395,7 +395,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(Number(attesterSlashing.attestation1.data.slot)); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? ssz.electra.AttesterSlashing.toJson(attesterSlashing) : ssz.phase0.AttesterSlashing.toJson(attesterSlashing), headers: {[MetaHeader.Version]: fork}, @@ -404,7 +404,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - attesterSlashing: isForkElectra(fork) + attesterSlashing: isForkPostElectra(fork) ? ssz.electra.AttesterSlashing.fromJson(body) : ssz.phase0.AttesterSlashing.fromJson(body), }; @@ -412,7 +412,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(Number(attesterSlashing.attestation1.data.slot)); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? ssz.electra.AttesterSlashing.serialize(attesterSlashing as electra.AttesterSlashing) : ssz.electra.AttesterSlashing.serialize(attesterSlashing as phase0.AttesterSlashing), headers: {[MetaHeader.Version]: fork}, @@ -421,7 +421,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - attesterSlashing: isForkElectra(fork) + attesterSlashing: isForkPostElectra(fork) ? ssz.electra.AttesterSlashing.deserialize(body) : ssz.phase0.AttesterSlashing.deserialize(body), }; diff --git a/packages/api/src/beacon/routes/validator.ts b/packages/api/src/beacon/routes/validator.ts index ed7c0fd9ba..5bc5c17c09 100644 --- a/packages/api/src/beacon/routes/validator.ts +++ b/packages/api/src/beacon/routes/validator.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import {ContainerType, fromHexString, toHexString, Type, ValueOf} from "@chainsafe/ssz"; import {ChainForkConfig} from "@lodestar/config"; -import {isForkBlobs, isForkElectra} from "@lodestar/params"; +import {isForkBlobs, isForkPostElectra} from "@lodestar/params"; import { altair, BLSSignature, @@ -869,7 +869,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions (isForkElectra(fork) ? ssz.electra.Attestation : ssz.phase0.Attestation)), + data: WithVersion((fork) => (isForkPostElectra(fork) ? ssz.electra.Attestation : ssz.phase0.Attestation)), meta: VersionCodec, }, }, @@ -898,7 +898,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(signedAggregateAndProofs[0]?.message.aggregate.data.slot ?? 0); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? SignedAggregateAndProofListElectraType.toJson( signedAggregateAndProofs as SignedAggregateAndProofListElectra ) @@ -911,7 +911,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - signedAggregateAndProofs: isForkElectra(fork) + signedAggregateAndProofs: isForkPostElectra(fork) ? SignedAggregateAndProofListElectraType.fromJson(body) : SignedAggregateAndProofListPhase0Type.fromJson(body), }; @@ -919,7 +919,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = config.getForkName(signedAggregateAndProofs[0]?.message.aggregate.data.slot ?? 0); return { - body: isForkElectra(fork) + body: isForkPostElectra(fork) ? SignedAggregateAndProofListElectraType.serialize( signedAggregateAndProofs as SignedAggregateAndProofListElectra ) @@ -932,7 +932,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions { const fork = toForkName(fromHeaders(headers, MetaHeader.Version)); return { - signedAggregateAndProofs: isForkElectra(fork) + signedAggregateAndProofs: isForkPostElectra(fork) ? SignedAggregateAndProofListElectraType.deserialize(body) : SignedAggregateAndProofListPhase0Type.deserialize(body), }; diff --git a/packages/beacon-node/src/chain/chain.ts b/packages/beacon-node/src/chain/chain.ts index 9f30936305..598b26d706 100644 --- a/packages/beacon-node/src/chain/chain.ts +++ b/packages/beacon-node/src/chain/chain.ts @@ -1120,11 +1120,10 @@ export class BeaconChain implements IBeaconChain { } const cpEpoch = cp.epoch; - const electraEpoch = headState?.config.ELECTRA_FORK_EPOCH ?? Infinity; if (headState === null) { this.logger.verbose("Head state is null"); - } else if (cpEpoch >= electraEpoch) { + } else if (cpEpoch >= this.config.ELECTRA_FORK_EPOCH) { // Get the validator.length from the state at cpEpoch // We are confident the last element in the list is from headEpoch // Thus we query from the end of the list. (cpEpoch - headEpoch - 1) is negative number diff --git a/packages/beacon-node/src/chain/genesis/genesis.ts b/packages/beacon-node/src/chain/genesis/genesis.ts index 5efd352357..979476c695 100644 --- a/packages/beacon-node/src/chain/genesis/genesis.ts +++ b/packages/beacon-node/src/chain/genesis/genesis.ts @@ -174,13 +174,7 @@ export class GenesisBuilder implements IGenesisBuilder { }; }); - const {activatedValidatorCount} = applyDeposits( - this.config.getForkSeq(this.state.slot), - this.config, - this.state, - newDeposits, - this.depositTree - ); + const {activatedValidatorCount} = applyDeposits(this.config, this.state, newDeposits, this.depositTree); this.activatedValidatorCount += activatedValidatorCount; // TODO: If necessary persist deposits here to this.db.depositData, this.db.depositDataRoot diff --git a/packages/beacon-node/src/chain/stateCache/fifoBlockStateCache.ts b/packages/beacon-node/src/chain/stateCache/fifoBlockStateCache.ts index f115806874..d38fc32317 100644 --- a/packages/beacon-node/src/chain/stateCache/fifoBlockStateCache.ts +++ b/packages/beacon-node/src/chain/stateCache/fifoBlockStateCache.ts @@ -191,7 +191,7 @@ export class FIFOBlockStateCache implements BlockStateCache { } getStates(): IterableIterator { - throw new Error("Method not implemented."); + return this.cache.values(); } /** diff --git a/packages/beacon-node/src/chain/stateCache/persistentCheckpointsCache.ts b/packages/beacon-node/src/chain/stateCache/persistentCheckpointsCache.ts index c59c15de61..b315beba46 100644 --- a/packages/beacon-node/src/chain/stateCache/persistentCheckpointsCache.ts +++ b/packages/beacon-node/src/chain/stateCache/persistentCheckpointsCache.ts @@ -595,7 +595,11 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache { } getStates(): IterableIterator { - throw new Error("Method not implemented."); + const items = Array.from(this.cache.values()) + .filter(isInMemoryCacheItem) + .map((item) => item.state); + + return items.values(); } /** ONLY FOR DEBUGGING PURPOSES. For spec tests on error */ diff --git a/packages/beacon-node/src/chain/validation/aggregateAndProof.ts b/packages/beacon-node/src/chain/validation/aggregateAndProof.ts index 8034b998fd..02c6613b17 100644 --- a/packages/beacon-node/src/chain/validation/aggregateAndProof.ts +++ b/packages/beacon-node/src/chain/validation/aggregateAndProof.ts @@ -180,7 +180,7 @@ async function validateAggregateAndProof( } const attestingIndices = aggregate.aggregationBits.intersectValues(committeeIndices); - const indexedAttestationContent = { + const indexedAttestationContent: IndexedAttestation = { attestingIndices, data: attData, signature: aggregate.signature, diff --git a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts index d0578718f2..a38b3f9987 100644 --- a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts +++ b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts @@ -128,7 +128,7 @@ export class Eth1DepositDataTracker { */ async getEth1DataAndDeposits(state: CachedBeaconStateAllForks): Promise { if ( - state.epochCtx.isAfterElectra() && + state.epochCtx.isPostElectra() && state.eth1DepositIndex >= (state as CachedBeaconStateElectra).depositRequestsStartIndex ) { // No need to poll eth1Data since Electra deprecates the mechanism after depositRequestsStartIndex is reached diff --git a/packages/beacon-node/src/metrics/metrics/lodestar.ts b/packages/beacon-node/src/metrics/metrics/lodestar.ts index 595e4a7a45..6b4bdb111f 100644 --- a/packages/beacon-node/src/metrics/metrics/lodestar.ts +++ b/packages/beacon-node/src/metrics/metrics/lodestar.ts @@ -1397,7 +1397,7 @@ export function createLodestarMetrics( regenFnDeletePubkeyTime: register.histogram({ name: "lodestar_regen_fn_delete_pubkey_time_seconds", help: "Histrogram of time spent on deleting pubkeys from all state cache items in seconds", - buckets: [0.01, 0.1, 0.5, 1, 2, 5], + buckets: [0.01, 0.1, 0.5, 1], }), regenFnNumStatesUpdated: register.histogram({ name: "lodestar_regen_state_cache_state_updated_count", diff --git a/packages/beacon-node/src/network/gossip/topic.ts b/packages/beacon-node/src/network/gossip/topic.ts index dfca0eaf3d..f3968b8e65 100644 --- a/packages/beacon-node/src/network/gossip/topic.ts +++ b/packages/beacon-node/src/network/gossip/topic.ts @@ -129,9 +129,8 @@ export function sszDeserialize(topic: T, serializedData: * Deserialize a gossip serialized data into an Attestation object. */ export function sszDeserializeAttestation(fork: ForkName, serializedData: Uint8Array): Attestation { - const sszType = sszTypesFor(fork).Attestation; try { - return sszType.deserialize(serializedData); + return sszTypesFor(fork).Attestation.deserialize(serializedData); } catch (e) { throw new GossipActionError(GossipAction.REJECT, {code: GossipErrorCode.INVALID_SERIALIZED_BYTES_ERROR_CODE}); } diff --git a/packages/cli/src/options/beaconNodeOptions/network.ts b/packages/cli/src/options/beaconNodeOptions/network.ts index 25ba036a5d..6c6f1ed70c 100644 --- a/packages/cli/src/options/beaconNodeOptions/network.ts +++ b/packages/cli/src/options/beaconNodeOptions/network.ts @@ -63,13 +63,13 @@ export function parseListenArgs(args: NetworkArgs) { // If listenAddress is explicitly set, use it // If listenAddress6 is not set, use defaultListenAddress const listenAddress = args.listenAddress ?? (args.listenAddress6 ? undefined : defaultListenAddress); - const port = listenAddress ? args.port ?? defaultP2pPort : undefined; - const discoveryPort = listenAddress ? args.discoveryPort ?? args.port ?? defaultP2pPort : undefined; + const port = listenAddress ? (args.port ?? defaultP2pPort) : undefined; + const discoveryPort = listenAddress ? (args.discoveryPort ?? args.port ?? defaultP2pPort) : undefined; // Only use listenAddress6 if it is explicitly set const listenAddress6 = args.listenAddress6; - const port6 = listenAddress6 ? args.port6 ?? defaultP2pPort6 : undefined; - const discoveryPort6 = listenAddress6 ? args.discoveryPort6 ?? args.port6 ?? defaultP2pPort6 : undefined; + const port6 = listenAddress6 ? (args.port6 ?? defaultP2pPort6) : undefined; + const discoveryPort6 = listenAddress6 ? (args.discoveryPort6 ?? args.port6 ?? defaultP2pPort6) : undefined; return {listenAddress, port, discoveryPort, listenAddress6, port6, discoveryPort6}; } diff --git a/packages/cli/src/util/gitData/index.ts b/packages/cli/src/util/gitData/index.ts index 96c5e4bbae..93b748d420 100644 --- a/packages/cli/src/util/gitData/index.ts +++ b/packages/cli/src/util/gitData/index.ts @@ -23,11 +23,11 @@ export function readAndGetGitData(): GitData { branch: currentGitData.branch && currentGitData.branch.length > 0 ? currentGitData.branch - : persistedGitData.branch ?? "", + : (persistedGitData.branch ?? ""), commit: currentGitData.commit && currentGitData.commit.length > 0 ? currentGitData.commit - : persistedGitData.commit ?? "", + : (persistedGitData.commit ?? ""), }; } catch (e) { return { diff --git a/packages/config/src/forkConfig/index.ts b/packages/config/src/forkConfig/index.ts index dd2a1773c3..513cd7559e 100644 --- a/packages/config/src/forkConfig/index.ts +++ b/packages/config/src/forkConfig/index.ts @@ -84,9 +84,9 @@ export function createForkConfig(config: ChainConfig): ForkConfig { // Fork convenience methods getForkInfo(slot: Slot): ForkInfo { const epoch = Math.floor(Math.max(slot, 0) / SLOTS_PER_EPOCH); - return this.getForkInfoFromEpoch(epoch); + return this.getForkInfoAtEpoch(epoch); }, - getForkInfoFromEpoch(epoch: Epoch): ForkInfo { + getForkInfoAtEpoch(epoch: Epoch): ForkInfo { // NOTE: forks must be sorted by descending epoch, latest fork first for (const fork of forksDescendingEpochOrder) { if (epoch >= fork.epoch) return fork; @@ -99,8 +99,8 @@ export function createForkConfig(config: ChainConfig): ForkConfig { getForkSeq(slot: Slot): ForkSeq { return this.getForkInfo(slot).seq; }, - getForkSeqFromEpoch(epoch: Epoch): ForkSeq { - return this.getForkInfoFromEpoch(epoch).seq; + getForkSeqAtEpoch(epoch: Epoch): ForkSeq { + return this.getForkInfoAtEpoch(epoch).seq; }, getForkVersion(slot: Slot): Version { return this.getForkInfo(slot).version; diff --git a/packages/config/src/forkConfig/types.ts b/packages/config/src/forkConfig/types.ts index dd0381f4e9..ebb2899a2a 100644 --- a/packages/config/src/forkConfig/types.ts +++ b/packages/config/src/forkConfig/types.ts @@ -22,13 +22,13 @@ export type ForkConfig = { /** Get the hard-fork info for the active fork at `slot` */ getForkInfo(slot: Slot): ForkInfo; /** Get the hard-fork info for the active fork at `epoch` */ - getForkInfoFromEpoch(epoch: Epoch): ForkInfo; + getForkInfoAtEpoch(epoch: Epoch): ForkInfo; /** Get the hard-fork name at a given slot */ getForkName(slot: Slot): ForkName; /** Get the hard-fork sequence number at a given slot */ getForkSeq(slot: Slot): ForkSeq; /** Get the hard-fork sequence number at a given epoch */ - getForkSeqFromEpoch(epoch: Epoch): ForkSeq; + getForkSeqAtEpoch(epoch: Epoch): ForkSeq; /** Get the hard-fork version at a given slot */ getForkVersion(slot: Slot): Version; /** Get SSZ types by hard-fork */ diff --git a/packages/params/src/forkName.ts b/packages/params/src/forkName.ts index 4a41f06373..42e8917942 100644 --- a/packages/params/src/forkName.ts +++ b/packages/params/src/forkName.ts @@ -82,14 +82,14 @@ export function isForkBlobs(fork: ForkName): fork is ForkBlobs { } export type ForkPreElectra = ForkPreBlobs | ForkName.deneb; -export type ForkElectra = Exclude; -export const forkElectra = exclude(forkAll, [ +export type ForkPostElectra = Exclude; +export const forkPostElectra = exclude(forkAll, [ ForkName.phase0, ForkName.altair, ForkName.bellatrix, ForkName.capella, ForkName.deneb, ]); -export function isForkElectra(fork: ForkName): fork is ForkElectra { +export function isForkPostElectra(fork: ForkName): fork is ForkPostElectra { return isForkBlobs(fork) && fork !== ForkName.deneb; } diff --git a/packages/prover/src/utils/gitData/index.ts b/packages/prover/src/utils/gitData/index.ts index 96c5e4bbae..93b748d420 100644 --- a/packages/prover/src/utils/gitData/index.ts +++ b/packages/prover/src/utils/gitData/index.ts @@ -23,11 +23,11 @@ export function readAndGetGitData(): GitData { branch: currentGitData.branch && currentGitData.branch.length > 0 ? currentGitData.branch - : persistedGitData.branch ?? "", + : (persistedGitData.branch ?? ""), commit: currentGitData.commit && currentGitData.commit.length > 0 ? currentGitData.commit - : persistedGitData.commit ?? "", + : (persistedGitData.commit ?? ""), }; } catch (e) { return { diff --git a/packages/state-transition/package.json b/packages/state-transition/package.json index c9551195e8..480f804785 100644 --- a/packages/state-transition/package.json +++ b/packages/state-transition/package.json @@ -69,12 +69,8 @@ "@lodestar/types": "^1.21.0", "@lodestar/utils": "^1.21.0", "bigint-buffer": "^1.1.5", - "buffer-xor": "^2.0.2", "immutable": "^4.3.2" }, - "devDependencies": { - "@types/buffer-xor": "^2.0.0" - }, "keywords": [ "ethereum", "eth-consensus", diff --git a/packages/state-transition/src/block/processConsolidationRequest.ts b/packages/state-transition/src/block/processConsolidationRequest.ts index 2f12065fde..71b85e9273 100644 --- a/packages/state-transition/src/block/processConsolidationRequest.ts +++ b/packages/state-transition/src/block/processConsolidationRequest.ts @@ -16,7 +16,7 @@ export function processConsolidationRequest( } // If there is too little available consolidation churn limit, consolidation requests are ignored - if (getConsolidationChurnLimit(state) <= MIN_ACTIVATION_BALANCE) { + if (getConsolidationChurnLimit(state.epochCtx) <= MIN_ACTIVATION_BALANCE) { return; } diff --git a/packages/state-transition/src/cache/epochCache.ts b/packages/state-transition/src/cache/epochCache.ts index cf463a93a9..af6e976e90 100644 --- a/packages/state-transition/src/cache/epochCache.ts +++ b/packages/state-transition/src/cache/epochCache.ts @@ -400,7 +400,7 @@ export class EpochCache { const proposers = currentShuffling.activeIndices.length > 0 ? computeProposers( - config.getForkSeqFromEpoch(currentEpoch), + config.getForkSeqAtEpoch(currentEpoch), currentProposerSeed, currentShuffling, effectiveBalanceIncrements @@ -584,7 +584,7 @@ export class EpochCache { const currentProposerSeed = getSeed(state, this.currentShuffling.epoch, DOMAIN_BEACON_PROPOSER); this.proposers = computeProposers( - this.config.getForkSeqFromEpoch(currEpoch), + this.config.getForkSeqAtEpoch(currEpoch), currentProposerSeed, this.currentShuffling, this.effectiveBalanceIncrements @@ -785,7 +785,7 @@ export class EpochCache { getBeaconProposersNextEpoch(): ValidatorIndex[] { if (!this.proposersNextEpoch.computed) { const indexes = computeProposers( - this.config.getForkSeqFromEpoch(this.epoch + 1), + this.config.getForkSeqAtEpoch(this.epoch + 1), this.proposersNextEpoch.seed, this.nextShuffling, this.effectiveBalanceIncrements @@ -914,7 +914,7 @@ export class EpochCache { } getValidatorIndex(pubkey: Uint8Array | PubkeyHex): ValidatorIndex | undefined { - if (this.isAfterElectra()) { + if (this.isPostElectra()) { return this.pubkey2index.get(pubkey) ?? this.unfinalizedPubkey2index.get(toMemoryEfficientHexStr(pubkey)); } else { return this.pubkey2index.get(pubkey); @@ -927,7 +927,7 @@ export class EpochCache { * */ addPubkey(index: ValidatorIndex, pubkey: Uint8Array): void { - if (this.isAfterElectra()) { + if (this.isPostElectra()) { this.addUnFinalizedPubkey(index, pubkey); } else { // deposit mechanism pre ELECTRA follows a safe distance with assumption @@ -1049,7 +1049,7 @@ export class EpochCache { } effectiveBalanceIncrementsSet(index: number, effectiveBalance: number): void { - if (this.isAfterElectra()) { + if (this.isPostElectra()) { // TODO: electra // getting length and setting getEffectiveBalanceIncrementsByteLen is not fork safe // so each time we add an index, we should new the Uint8Array to keep it forksafe @@ -1074,8 +1074,8 @@ export class EpochCache { this.effectiveBalanceIncrements[index] = Math.floor(effectiveBalance / EFFECTIVE_BALANCE_INCREMENT); } - isAfterElectra(): boolean { - return this.epoch >= (this.config.ELECTRA_FORK_EPOCH ?? Infinity); + isPostElectra(): boolean { + return this.epoch >= this.config.ELECTRA_FORK_EPOCH; } getValidatorCountAtEpoch(targetEpoch: Epoch): number | undefined { diff --git a/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts b/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts index e6e43bbaa0..f89e938cc7 100644 --- a/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts +++ b/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts @@ -14,7 +14,7 @@ import {getCurrentEpoch} from "../util/epoch.js"; * TODO Electra: Update ssz library to support batch push to `pendingBalanceDeposits` */ export function processPendingBalanceDeposits(state: CachedBeaconStateElectra): void { - const availableForProcessing = state.depositBalanceToConsume + BigInt(getActivationExitChurnLimit(state)); + const availableForProcessing = state.depositBalanceToConsume + BigInt(getActivationExitChurnLimit(state.epochCtx)); const currentEpoch = getCurrentEpoch(state); let processedAmount = 0n; let nextDepositIndex = 0; diff --git a/packages/state-transition/src/slot/upgradeStateToElectra.ts b/packages/state-transition/src/slot/upgradeStateToElectra.ts index 974f0d6a60..ef7b0bd661 100644 --- a/packages/state-transition/src/slot/upgradeStateToElectra.ts +++ b/packages/state-transition/src/slot/upgradeStateToElectra.ts @@ -92,8 +92,8 @@ export function upgradeStateToElectra(stateDeneb: CachedBeaconStateDeneb): Cache // TODO-electra: can we improve this? stateElectraView.commit(); const tmpElectraState = getCachedBeaconState(stateElectraView, stateDeneb); - stateElectraView.exitBalanceToConsume = BigInt(getActivationExitChurnLimit(tmpElectraState)); - stateElectraView.consolidationBalanceToConsume = BigInt(getConsolidationChurnLimit(tmpElectraState)); + stateElectraView.exitBalanceToConsume = BigInt(getActivationExitChurnLimit(tmpElectraState.epochCtx)); + stateElectraView.consolidationBalanceToConsume = BigInt(getConsolidationChurnLimit(tmpElectraState.epochCtx)); preActivation.sort((i0, i1) => { const res = validatorsArr[i0].activationEligibilityEpoch - validatorsArr[i1].activationEligibilityEpoch; diff --git a/packages/state-transition/src/util/epoch.ts b/packages/state-transition/src/util/epoch.ts index 66bd2ad76b..7fed5e53f1 100644 --- a/packages/state-transition/src/util/epoch.ts +++ b/packages/state-transition/src/util/epoch.ts @@ -43,7 +43,7 @@ export function computeActivationExitEpoch(epoch: Epoch): Epoch { export function computeExitEpochAndUpdateChurn(state: CachedBeaconStateElectra, exitBalance: Gwei): number { let earliestExitEpoch = Math.max(state.earliestExitEpoch, computeActivationExitEpoch(state.epochCtx.epoch)); - const perEpochChurn = getActivationExitChurnLimit(state); + const perEpochChurn = getActivationExitChurnLimit(state.epochCtx); // New epoch for exits. let exitBalanceToConsume = @@ -72,7 +72,7 @@ export function computeConsolidationEpochAndUpdateChurn( state.earliestConsolidationEpoch, computeActivationExitEpoch(state.epochCtx.epoch) ); - const perEpochConsolidationChurn = getConsolidationChurnLimit(state); + const perEpochConsolidationChurn = getConsolidationChurnLimit(state.epochCtx); // New epoch for consolidations let consolidationBalanceToConsume = diff --git a/packages/state-transition/src/util/genesis.ts b/packages/state-transition/src/util/genesis.ts index 7bdc420d64..02bcef00bb 100644 --- a/packages/state-transition/src/util/genesis.ts +++ b/packages/state-transition/src/util/genesis.ts @@ -129,12 +129,12 @@ export function applyTimestamp(config: ChainForkConfig, state: CachedBeaconState * @returns active validator indices */ export function applyDeposits( - fork: ForkSeq, config: ChainForkConfig, state: CachedBeaconStateAllForks, newDeposits: phase0.Deposit[], fullDepositDataRootList?: DepositDataRootViewDU ): {activatedValidatorCount: number} { + const fork = config.getForkSeq(state.slot); const depositDataRootList: Root[] = []; const fullDepositDataRootArr = fullDepositDataRootList ? fullDepositDataRootList.getAllReadonlyValues() : null; @@ -258,7 +258,7 @@ export function initializeBeaconStateFromEth1( applyEth1BlockHash(state, eth1BlockHash); // Process deposits - applyDeposits(fork, config, state, deposits, fullDepositDataRootList); + applyDeposits(config, state, deposits, fullDepositDataRootList); // Commit before reading all validators in `getActiveValidatorIndices()` state.commit(); diff --git a/packages/state-transition/src/util/validator.ts b/packages/state-transition/src/util/validator.ts index 0c8c74b2cb..728f14587f 100644 --- a/packages/state-transition/src/util/validator.ts +++ b/packages/state-transition/src/util/validator.ts @@ -7,7 +7,7 @@ import { MAX_EFFECTIVE_BALANCE_ELECTRA, MIN_ACTIVATION_BALANCE, } from "@lodestar/params"; -import {BeaconStateAllForks, CachedBeaconStateElectra} from "../types.js"; +import {BeaconStateAllForks, CachedBeaconStateElectra, EpochCache} from "../types.js"; import {hasCompoundingWithdrawalCredential} from "./electra.js"; /** @@ -57,22 +57,22 @@ export function getChurnLimit(config: ChainForkConfig, activeValidatorCount: num /** * Get combined churn limit of activation-exit and consolidation */ -export function getBalanceChurnLimit(state: CachedBeaconStateElectra): number { +export function getBalanceChurnLimit(epochCtx: EpochCache): number { const churnLimitByTotalActiveBalance = Math.floor( - (state.epochCtx.totalActiveBalanceIncrements / state.config.CHURN_LIMIT_QUOTIENT) * EFFECTIVE_BALANCE_INCREMENT + (epochCtx.totalActiveBalanceIncrements / epochCtx.config.CHURN_LIMIT_QUOTIENT) * EFFECTIVE_BALANCE_INCREMENT ); // TODO Electra: verify calculation - const churn = Math.max(churnLimitByTotalActiveBalance, state.config.MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA); + const churn = Math.max(churnLimitByTotalActiveBalance, epochCtx.config.MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA); return churn - (churn % EFFECTIVE_BALANCE_INCREMENT); } -export function getActivationExitChurnLimit(state: CachedBeaconStateElectra): number { - return Math.min(state.config.MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT, getBalanceChurnLimit(state)); +export function getActivationExitChurnLimit(epochCtx: EpochCache): number { + return Math.min(epochCtx.config.MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT, getBalanceChurnLimit(epochCtx)); } -export function getConsolidationChurnLimit(state: CachedBeaconStateElectra): number { - return getBalanceChurnLimit(state) - getActivationExitChurnLimit(state); +export function getConsolidationChurnLimit(epochCtx: EpochCache): number { + return getBalanceChurnLimit(epochCtx) - getActivationExitChurnLimit(epochCtx); } export function getValidatorMaxEffectiveBalance(withdrawalCredentials: Uint8Array): number { diff --git a/packages/state-transition/test/unit/util/deposit.test.ts b/packages/state-transition/test/unit/util/deposit.test.ts index 677a15724e..b108de502a 100644 --- a/packages/state-transition/test/unit/util/deposit.test.ts +++ b/packages/state-transition/test/unit/util/deposit.test.ts @@ -10,7 +10,7 @@ describe("getEth1DepositCount", () => { const stateView = ssz.altair.BeaconState.defaultViewDU(); const preElectraState = createCachedBeaconStateTest(stateView); - if (preElectraState.epochCtx.isAfterElectra()) { + if (preElectraState.epochCtx.isPostElectra()) { throw Error("Not a pre-Electra state"); } @@ -39,7 +39,7 @@ describe("getEth1DepositCount", () => { {skipSyncCommitteeCache: true, skipSyncPubkeys: true} ) as CachedBeaconStateElectra; - if (!postElectraState.epochCtx.isAfterElectra()) { + if (!postElectraState.epochCtx.isPostElectra()) { throw Error("Not a post-Electra state"); } @@ -73,7 +73,7 @@ describe("getEth1DepositCount", () => { {skipSyncCommitteeCache: true, skipSyncPubkeys: true} ) as CachedBeaconStateElectra; - if (!postElectraState.epochCtx.isAfterElectra()) { + if (!postElectraState.epochCtx.isPostElectra()) { throw Error("Not a post-Electra state"); } diff --git a/packages/types/src/utils/typeguards.ts b/packages/types/src/utils/typeguards.ts index 2af1115987..72910645f6 100644 --- a/packages/types/src/utils/typeguards.ts +++ b/packages/types/src/utils/typeguards.ts @@ -1,4 +1,4 @@ -import {ForkBlobs, ForkExecution, ForkElectra} from "@lodestar/params"; +import {ForkBlobs, ForkExecution, ForkPostElectra} from "@lodestar/params"; import { BlockContents, SignedBeaconBlock, @@ -68,6 +68,6 @@ export function isSignedBlockContents( return (data as SignedBlockContents).kzgProofs !== undefined; } -export function isElectraAttestation(attestation: Attestation): attestation is Attestation { - return (attestation as Attestation).committeeBits !== undefined; +export function isElectraAttestation(attestation: Attestation): attestation is Attestation { + return (attestation as Attestation).committeeBits !== undefined; } diff --git a/packages/utils/src/promise.ts b/packages/utils/src/promise.ts index 2be7467bff..81fa72e7d5 100644 --- a/packages/utils/src/promise.ts +++ b/packages/utils/src/promise.ts @@ -109,7 +109,7 @@ export async function resolveOrRacePromises wrapPromise(p)) as ReturnPromiseWithTuple; // We intentionally want an array of promises here - // eslint-disable-next-line @typescript-eslint/no-floating-promises + promises = (promiseResults as PromiseResult[]).map((p) => p.promise) as unknown as T; try { diff --git a/packages/validator/src/services/attestation.ts b/packages/validator/src/services/attestation.ts index 4226bd572b..d6f48aeb3d 100644 --- a/packages/validator/src/services/attestation.ts +++ b/packages/validator/src/services/attestation.ts @@ -159,13 +159,13 @@ export class AttestationService { this.metrics?.attesterStepCallProduceAggregate.observe(this.clock.secFromSlot(slot + 2 / 3)); const dutiesByCommitteeIndex = groupAttDutiesByCommitteeIndex(dutiesAll); - const isAfterElectra = computeEpochAtSlot(slot) >= this.config.ELECTRA_FORK_EPOCH; + const isPostElectra = computeEpochAtSlot(slot) >= this.config.ELECTRA_FORK_EPOCH; // Then download, sign and publish a `SignedAggregateAndProof` for each // validator that is elected to aggregate for this `slot` and `committeeIndex`. await Promise.all( Array.from(dutiesByCommitteeIndex.entries()).map(([index, dutiesSameCommittee]) => { - const attestationData: phase0.AttestationData = {...attestationNoCommittee, index: isAfterElectra ? 0 : index}; + const attestationData: phase0.AttestationData = {...attestationNoCommittee, index: isPostElectra ? 0 : index}; return this.produceAndPublishAggregates(attestationData, index, dutiesSameCommittee); }) ); @@ -196,11 +196,11 @@ export class AttestationService { const signedAttestations: Attestation[] = []; const headRootHex = toHexString(attestationNoCommittee.beaconBlockRoot); const currentEpoch = computeEpochAtSlot(slot); - const isAfterElectra = currentEpoch >= this.config.ELECTRA_FORK_EPOCH; + const isPostElectra = currentEpoch >= this.config.ELECTRA_FORK_EPOCH; await Promise.all( duties.map(async ({duty}) => { - const index = isAfterElectra ? 0 : duty.committeeIndex; + const index = isPostElectra ? 0 : duty.committeeIndex; const attestationData: phase0.AttestationData = {...attestationNoCommittee, index}; const logCtxValidator = {slot, index, head: headRootHex, validatorIndex: duty.validatorIndex}; diff --git a/packages/validator/src/services/validatorStore.ts b/packages/validator/src/services/validatorStore.ts index cea281f0d1..252d0886cc 100644 --- a/packages/validator/src/services/validatorStore.ts +++ b/packages/validator/src/services/validatorStore.ts @@ -801,13 +801,13 @@ export class ValidatorStore { throw Error(`Inconsistent duties during signing: duty.slot ${duty.slot} != att.slot ${data.slot}`); } - const isAfterElectra = computeEpochAtSlot(duty.slot) >= this.config.ELECTRA_FORK_EPOCH; - if (!isAfterElectra && duty.committeeIndex != data.index) { + const isPostElectra = computeEpochAtSlot(duty.slot) >= this.config.ELECTRA_FORK_EPOCH; + if (!isPostElectra && duty.committeeIndex != data.index) { throw Error( `Inconsistent duties during signing: duty.committeeIndex ${duty.committeeIndex} != att.committeeIndex ${data.index}` ); } - if (isAfterElectra && data.index !== 0) { + if (isPostElectra && data.index !== 0) { throw Error(`Non-zero committee index post-electra during signing: att.committeeIndex ${data.index}`); } if (this.config.getForkSeq(duty.slot) >= ForkSeq.electra && data.index !== 0) {