From 655a4d19b54dfe7000c6e38a6c7b0036e1ee2d60 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Mon, 14 Oct 2024 10:59:22 +0200 Subject: [PATCH] Enable recommended rule style/noUselessElse --- biome.jsonc | 2 - packages/api/src/utils/client/eventSource.ts | 3 +- packages/api/src/utils/client/httpClient.ts | 28 +++--- packages/api/src/utils/client/response.ts | 6 +- packages/api/src/utils/codecs.ts | 6 +- packages/api/src/utils/serdes.ts | 3 +- .../unit/client/httpClientFallback.test.ts | 8 +- packages/api/test/utils/checkAgainstSpec.ts | 4 +- .../src/api/impl/beacon/blocks/index.ts | 28 +++--- .../src/api/impl/beacon/state/index.ts | 4 +- .../src/api/impl/lodestar/index.ts | 3 +- .../beacon-node/src/api/impl/node/index.ts | 5 +- .../src/api/impl/validator/index.ts | 90 ++++++++++--------- .../beacon-node/src/chain/blocks/index.ts | 12 ++- .../chain/blocks/verifyBlocksSanityChecks.ts | 15 ++-- packages/beacon-node/src/chain/chain.ts | 69 +++++++------- .../beacon-node/src/chain/genesis/genesis.ts | 12 +-- .../src/chain/lightClient/index.ts | 4 +- .../opPools/aggregatedAttestationPool.ts | 76 ++++++++-------- .../src/chain/opPools/attestationPool.ts | 7 +- .../beacon-node/src/chain/opPools/opPool.ts | 5 +- .../chain/opPools/syncCommitteeMessagePool.ts | 8 +- .../opPools/syncContributionAndProofPool.ts | 5 +- .../chain/produceBlock/produceBlockBody.ts | 40 ++++----- .../src/chain/rewards/blockRewards.ts | 4 +- .../src/chain/rewards/syncCommitteeRewards.ts | 4 +- .../chain/seenCache/seenGossipBlockInput.ts | 60 ++++++------- .../beacon-node/src/chain/shufflingCache.ts | 5 +- .../src/chain/validation/attestation.ts | 53 ++++++----- packages/beacon-node/src/db/buckets.ts | 3 +- .../src/db/repositories/depositDataRoot.ts | 4 +- .../src/eth1/eth1DepositDataTracker.ts | 24 +++-- .../src/eth1/eth1MergeBlockTracker.ts | 89 +++++++++--------- packages/beacon-node/src/eth1/index.ts | 6 +- .../src/eth1/provider/jsonRpcHttpClient.ts | 12 ++- .../beacon-node/src/eth1/utils/deposits.ts | 4 +- .../beacon-node/src/eth1/utils/eth1Vote.ts | 10 +-- .../utils/optimizeNextBlockDiffForGenesis.ts | 3 +- .../beacon-node/src/execution/engine/http.ts | 6 +- .../beacon-node/src/execution/engine/mock.ts | 22 ++--- .../src/metrics/validatorMonitor.ts | 90 +++++++++---------- .../beacon-node/src/monitoring/properties.ts | 6 +- .../beacon-node/src/monitoring/service.ts | 6 +- .../src/network/gossip/encoding.ts | 3 +- .../src/network/gossip/gossipsub.ts | 3 +- .../beacon-node/src/network/peers/discover.ts | 15 ++-- .../network/processor/gossipQueues/index.ts | 3 +- .../network/processor/gossipQueues/indexed.ts | 3 +- .../network/processor/gossipQueues/linear.ts | 12 +-- .../reqresp/beaconBlocksMaybeBlobsByRange.ts | 6 +- .../reqresp/handlers/lightClientBootstrap.ts | 3 +- .../handlers/lightClientFinalityUpdate.ts | 14 +-- .../handlers/lightClientOptimisticUpdate.ts | 14 +-- .../handlers/lightClientUpdatesByRange.ts | 3 +- .../beacon-node/src/network/reqresp/types.ts | 7 +- packages/beacon-node/src/node/notifier.ts | 47 +++++----- packages/beacon-node/src/sync/range/range.ts | 6 +- .../src/sync/range/utils/batches.ts | 4 +- packages/beacon-node/src/sync/sync.ts | 50 +++++------ packages/beacon-node/src/sync/unknownBlock.ts | 7 +- .../src/sync/utils/remoteSyncType.ts | 55 ++++++------ packages/beacon-node/src/util/bitArray.ts | 2 +- packages/beacon-node/src/util/kzg.ts | 3 +- .../test/e2e/chain/lightclient.test.ts | 4 +- .../test/sim/electra-interop.test.ts | 10 +-- packages/beacon-node/test/spec/general/bls.ts | 3 +- .../test/spec/utils/runValidSszTest.ts | 3 +- ...hufflingForAttestationVerification.test.ts | 18 ++-- .../unit/eth1/eth1MergeBlockTracker.test.ts | 3 +- .../optimizeNextBlockDiffForGenesis.test.ts | 3 +- .../unit/executionEngine/httpRetry.test.ts | 6 +- .../test/unit/network/processorQueues.test.ts | 6 +- .../test/unit/util/dependentRoot.test.ts | 6 +- .../test/unit/util/wrapError.test.ts | 6 +- packages/beacon-node/test/utils/errors.ts | 8 +- .../cli/src/cmds/beacon/initBeaconState.ts | 38 ++++---- .../cli/src/cmds/beacon/initPeerIdAndEnr.ts | 7 +- .../cli/src/cmds/validator/keymanager/impl.ts | 3 +- .../src/cmds/validator/keymanager/server.ts | 3 +- .../signers/importExternalKeystores.ts | 20 ++--- .../cli/src/cmds/validator/signers/index.ts | 75 ++++++++-------- .../cli/src/cmds/validator/voluntaryExit.ts | 6 +- packages/cli/src/util/file.ts | 6 +- packages/cli/src/util/fs.ts | 6 +- packages/cli/test/e2e/voluntaryExit.test.ts | 3 +- .../cli/test/e2e/voluntaryExitFromApi.test.ts | 3 +- .../e2e/voluntaryExitRemoteSigner.test.ts | 3 +- .../cli/test/utils/crucible/tableReporter.ts | 3 +- .../cli/test/utils/crucible/utils/network.ts | 3 +- .../cli/test/utils/crucible/utils/syncing.ts | 3 +- packages/db/src/controller/level.ts | 10 +-- .../fork-choice/src/forkChoice/forkChoice.ts | 8 +- .../fork-choice/src/protoArray/protoArray.ts | 13 +-- packages/light-client/src/utils/clock.ts | 4 +- packages/logger/src/utils/json.ts | 10 +-- packages/prover/src/utils/process.ts | 3 +- .../sszSnappy/snappyFrames/uncompress.ts | 3 +- .../src/rate_limiter/ReqRespRateLimiter.ts | 4 +- packages/reqresp/src/request/index.ts | 9 +- packages/reqresp/src/response/index.ts | 8 +- packages/reqresp/src/utils/abortableSource.ts | 4 +- packages/reqresp/src/utils/bufferedSource.ts | 8 +- packages/reqresp/test/utils/errors.ts | 7 +- packages/spec-test-util/src/downloadTests.ts | 3 +- packages/spec-test-util/src/single.ts | 15 ++-- .../src/block/isValidIndexedAttestation.ts | 6 +- .../src/block/processAttestationPhase0.ts | 17 ++-- .../src/block/processEth1Data.ts | 3 +- .../src/block/processSyncCommittee.ts | 3 +- .../state-transition/src/cache/epochCache.ts | 33 ++++--- .../epoch/processPendingBalanceDeposits.ts | 13 ++- .../state-transition/src/util/blindedBlock.ts | 12 ++- packages/state-transition/src/util/deposit.ts | 6 +- .../state-transition/src/util/execution.ts | 20 +++-- .../src/util/loadState/loadValidator.ts | 3 +- .../src/util/shufflingDecisionRoot.ts | 9 +- .../state-transition/src/util/validator.ts | 6 +- .../test/perf/misc/proxy.test.ts | 3 +- .../test/utils/beforeValue.ts | 6 +- .../test/utils/beforeValueMocha.ts | 7 +- .../test/utils/testFileCache.ts | 62 ++++++------- packages/types/src/utils/validatorStatus.ts | 8 +- packages/utils/src/bytes.ts | 6 +- packages/utils/src/bytes/nodejs.ts | 6 +- packages/utils/src/retry.ts | 8 +- packages/utils/test/unit/promiserace.test.ts | 3 +- packages/utils/test/unit/retry.test.ts | 3 +- packages/validator/src/buckets.ts | 4 +- packages/validator/src/services/block.ts | 63 +++++++------ .../src/services/doppelgangerService.ts | 9 +- .../validator/src/services/validatorStore.ts | 27 +++--- .../slashingProtection/attestation/index.ts | 11 ++- .../src/slashingProtection/block/index.ts | 12 +-- packages/validator/src/util/clock.ts | 15 ++-- .../src/util/externalSignerClient.ts | 14 +-- 135 files changed, 900 insertions(+), 979 deletions(-) diff --git a/biome.jsonc b/biome.jsonc index 851c34e0497e..5ffc4449ee63 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -63,8 +63,6 @@ "deniedGlobals": ["fetch"] } }, - // There are a lot of places we use if/else pattern. Should be fixed in an independent PR. - "noUselessElse": "off", // We prefer to use `Math.pow` over `**` operator "useExponentiationOperator": "off", // In some cases the enums are initialized with values of other enums diff --git a/packages/api/src/utils/client/eventSource.ts b/packages/api/src/utils/client/eventSource.ts index 2e2cf0076068..f023a0ec5f0b 100644 --- a/packages/api/src/utils/client/eventSource.ts +++ b/packages/api/src/utils/client/eventSource.ts @@ -2,7 +2,6 @@ export async function getEventSource(): Promise { if (globalThis.EventSource) { return EventSource; - } else { - return (await import("eventsource")).default as unknown as typeof EventSource; } + return (await import("eventsource")).default as unknown as typeof EventSource; } diff --git a/packages/api/src/utils/client/httpClient.ts b/packages/api/src/utils/client/httpClient.ts index d36df36a35b0..721a150f7fcd 100644 --- a/packages/api/src/utils/client/httpClient.ts +++ b/packages/api/src/utils/client/httpClient.ts @@ -155,12 +155,10 @@ export class HttpClient implements IHttpClient { if (init.retries > 0) { return this.requestWithRetries(definition, args, init); - } else { - return this.getRequestMethod(init)(definition, args, init); } - } else { - return this.requestWithFallbacks(definition, args, localInit); + return this.getRequestMethod(init)(definition, args, init); } + return this.requestWithFallbacks(definition, args, localInit); } /** @@ -252,19 +250,16 @@ export class HttpClient implements IHttpClient { }); if (res.ok) { return res; - } else { - if (i >= this.urlsInits.length - 1) { - return res; - } else { - this.logger?.debug("Request error, retrying", {}, res.error() as Error); - } } + if (i >= this.urlsInits.length - 1) { + return res; + } + this.logger?.debug("Request error, retrying", {}, res.error() as Error); } catch (e) { if (i >= this.urlsInits.length - 1) { throw e; - } else { - this.logger?.debug("Request error, retrying", {}, e as Error); } + this.logger?.debug("Request error, retrying", {}, e as Error); } } @@ -391,14 +386,13 @@ export class HttpClient implements IHttpClient { if (isAbortedError(e)) { if (abortSignals.some((s) => s?.aborted)) { throw new ErrorAborted(`${routeId} request`); - } else if (controller.signal.aborted) { + } + if (controller.signal.aborted) { throw new TimeoutError(`${routeId} request`); - } else { - throw Error("Unknown aborted error"); } - } else { - throw e; + throw Error("Unknown aborted error"); } + throw e; } finally { timer?.(); diff --git a/packages/api/src/utils/client/response.ts b/packages/api/src/utils/client/response.ts index 7a4c4fb98ce4..626252b9aaca 100644 --- a/packages/api/src/utils/client/response.ts +++ b/packages/api/src/utils/client/response.ts @@ -35,9 +35,8 @@ export class ApiResponse extends Response { if (this.status === HttpStatusCode.NO_CONTENT) { this._wireFormat = null; return this._wireFormat; - } else { - throw Error("Content-Type header is required in response"); } + throw Error("Content-Type header is required in response"); } const mediaType = parseContentTypeHeader(contentType); @@ -197,9 +196,8 @@ export class ApiResponse extends Response { return `${errJson.message}\n` + errJson.failures.map((e) => e.message).join("\n"); } return errJson.message; - } else { - return errBody; } + return errBody; } catch (_e) { return errBody || this.statusText; } diff --git a/packages/api/src/utils/codecs.ts b/packages/api/src/utils/codecs.ts index 54214740f435..db96daf0ce50 100644 --- a/packages/api/src/utils/codecs.ts +++ b/packages/api/src/utils/codecs.ts @@ -68,11 +68,11 @@ export const EmptyResponseCodec: ResponseCodec = { export function ArrayOf(elementType: Type, limit = Infinity): ArrayType, unknown, unknown> { if (isCompositeType(elementType)) { return new ListCompositeType(elementType, limit) as unknown as ArrayType, unknown, unknown>; - } else if (isBasicType(elementType)) { + } + if (isBasicType(elementType)) { return new ListBasicType(elementType, limit) as unknown as ArrayType, unknown, unknown>; - } else { - throw Error(`Unknown type ${elementType.typeName}`); } + throw Error(`Unknown type ${elementType.typeName}`); } export function WithMeta(getType: (m: M) => Type): ResponseDataCodec { diff --git a/packages/api/src/utils/serdes.ts b/packages/api/src/utils/serdes.ts index d58b817b9099..9fb772a0bc63 100644 --- a/packages/api/src/utils/serdes.ts +++ b/packages/api/src/utils/serdes.ts @@ -18,9 +18,8 @@ export function querySerializeProofPathsArr(paths: JsonPath[]): string[] { export function queryParseProofPathsArr(pathStrs: string | string[]): JsonPath[] { if (Array.isArray(pathStrs)) { return pathStrs.map((pathStr) => queryParseProofPaths(pathStr)); - } else { - return [queryParseProofPaths(pathStrs)]; } + return [queryParseProofPaths(pathStrs)]; } /** diff --git a/packages/api/test/unit/client/httpClientFallback.test.ts b/packages/api/test/unit/client/httpClientFallback.test.ts index 244fcbe5bf23..9fcde27de072 100644 --- a/packages/api/test/unit/client/httpClientFallback.test.ts +++ b/packages/api/test/unit/client/httpClientFallback.test.ts @@ -56,12 +56,12 @@ describe("httpClient fallback", () => { // which is handled separately from network errors // but the fallback logic should be the same return new Response(null, {status: 500}); - } else { - throw Error(`test_error_server_${i}`); } - } else { - return new Response(null, {status: 200}); + + throw Error(`test_error_server_${i}`); } + + return new Response(null, {status: 200}); }); }); diff --git a/packages/api/test/utils/checkAgainstSpec.ts b/packages/api/test/utils/checkAgainstSpec.ts index 85e9711ae601..c8edde7e790e 100644 --- a/packages/api/test/utils/checkAgainstSpec.ts +++ b/packages/api/test/utils/checkAgainstSpec.ts @@ -218,7 +218,9 @@ type StringifiedProperty = string | StringifiedProperty[]; function stringifyProperty(value: unknown): StringifiedProperty { if (typeof value === "number") { return value.toString(10); - } else if (Array.isArray(value)) { + } + + if (Array.isArray(value)) { return value.map(stringifyProperty); } return String(value); diff --git a/packages/beacon-node/src/api/impl/beacon/blocks/index.ts b/packages/beacon-node/src/api/impl/beacon/blocks/index.ts index 240f391027a9..b54e8752a437 100644 --- a/packages/beacon-node/src/api/impl/beacon/blocks/index.ts +++ b/packages/beacon-node/src/api/impl/beacon/blocks/index.ts @@ -176,9 +176,8 @@ export function getBeaconBlockApi({ const message = `Equivocation checks not yet implemented for broadcastValidation=${broadcastValidation}`; if (chain.opts.broadcastValidationStrictness === "error") { throw Error(message); - } else { - chain.logger.warn(message, valLogMeta); } + chain.logger.warn(message, valLogMeta); } break; } @@ -193,9 +192,8 @@ export function getBeaconBlockApi({ const message = `Broadcast validation of ${broadcastValidation} type not implemented yet`; if (chain.opts.broadcastValidationStrictness === "error") { throw Error(message); - } else { - chain.logger.warn(message, valLogMeta); } + chain.logger.warn(message, valLogMeta); } } @@ -266,19 +264,19 @@ export function getBeaconBlockApi({ chain.logger.info("Publishing assembled block", {slot, blockRoot, source}); return publishBlock({signedBlockOrContents}, {...context, sszBytes: null}, opts); - } else { - const source = ProducedBlockSource.builder; - chain.logger.debug("Reconstructing signedBlockOrContents", {slot, blockRoot, source}); + } - const signedBlockOrContents = await reconstructBuilderBlockOrContents(chain, signedBlindedBlock); + const source = ProducedBlockSource.builder; + chain.logger.debug("Reconstructing signedBlockOrContents", {slot, blockRoot, source}); - // the full block is published by relay and it's possible that the block is already known to us - // by gossip - // - // see: https://github.com/ChainSafe/lodestar/issues/5404 - chain.logger.info("Publishing assembled block", {slot, blockRoot, source}); - return publishBlock({signedBlockOrContents}, {...context, sszBytes: null}, {...opts, ignoreIfKnown: true}); - } + const signedBlockOrContents = await reconstructBuilderBlockOrContents(chain, signedBlindedBlock); + + // the full block is published by relay and it's possible that the block is already known to us + // by gossip + // + // see: https://github.com/ChainSafe/lodestar/issues/5404 + chain.logger.info("Publishing assembled block", {slot, blockRoot, source}); + return publishBlock({signedBlockOrContents}, {...context, sszBytes: null}, {...opts, ignoreIfKnown: true}); }; return { diff --git a/packages/beacon-node/src/api/impl/beacon/state/index.ts b/packages/beacon-node/src/api/impl/beacon/state/index.ts index 2bf758a8e286..8cce896e1087 100644 --- a/packages/beacon-node/src/api/impl/beacon/state/index.ts +++ b/packages/beacon-node/src/api/impl/beacon/state/index.ts @@ -103,7 +103,9 @@ export function getBeaconStateApi({ data: validatorResponses, meta: {executionOptimistic, finalized}, }; - } else if (statuses.length) { + } + + if (statuses.length) { const validatorsByStatus = filterStateValidatorsByStatus(statuses, state, pubkey2index, currentEpoch); return { data: validatorsByStatus, diff --git a/packages/beacon-node/src/api/impl/lodestar/index.ts b/packages/beacon-node/src/api/impl/lodestar/index.ts index 0e8d2b1fa94b..34f0a722cacc 100644 --- a/packages/beacon-node/src/api/impl/lodestar/index.ts +++ b/packages/beacon-node/src/api/impl/lodestar/index.ts @@ -218,8 +218,7 @@ function stringifyKeys(keys: (Uint8Array | number | string)[]): string[] { return keys.map((key) => { if (key instanceof Uint8Array) { return toHex(key); - } else { - return `${key}`; } + return `${key}`; }); } diff --git a/packages/beacon-node/src/api/impl/node/index.ts b/packages/beacon-node/src/api/impl/node/index.ts index 370bba9b3c79..bd1fb85522de 100644 --- a/packages/beacon-node/src/api/impl/node/index.ts +++ b/packages/beacon-node/src/api/impl/node/index.ts @@ -76,10 +76,9 @@ export function getNodeApi( if (isSyncing || isOptimistic || elOffline) { // 206: Node is syncing but can serve incomplete data return {status: syncingStatus ?? routes.node.NodeHealth.SYNCING}; - } else { - // 200: Node is ready - return {status: routes.node.NodeHealth.READY}; } + // 200: Node is ready + return {status: routes.node.NodeHealth.READY}; // else { // 503: Node not initialized or having issues // NOTE: Lodestar does not start its API until fully initialized, so this status can never be served diff --git a/packages/beacon-node/src/api/impl/validator/index.ts b/packages/beacon-node/src/api/impl/validator/index.ts index 9c5e6c2987f1..bfed9e07b191 100644 --- a/packages/beacon-node/src/api/impl/validator/index.ts +++ b/packages/beacon-node/src/api/impl/validator/index.ts @@ -168,7 +168,9 @@ export function getValidatorApi( if (msToSlot > MAX_API_CLOCK_DISPARITY_MS) { throw Error(`Requested slot ${slot} is in the future`); - } else if (msToSlot > 0) { + } + + if (msToSlot > 0) { await chain.clock.waitForSlot(slot); } @@ -215,19 +217,19 @@ export function getValidatorApi( consensusBlockValue: prettyWeiToEth(consensusValue), blockTotalValue: prettyWeiToEth(totalValue), }; - } else if (source === ProducedBlockSource.builder) { + } + if (source === ProducedBlockSource.builder) { return { builderExecutionPayloadValue: prettyWeiToEth(executionValue), builderConsensusBlockValue: prettyWeiToEth(consensusValue), builderBlockTotalValue: prettyWeiToEth(totalValue), }; - } else { - return { - engineExecutionPayloadValue: prettyWeiToEth(executionValue), - engineConsensusBlockValue: prettyWeiToEth(consensusValue), - engineBlockTotalValue: prettyWeiToEth(totalValue), - }; } + return { + engineExecutionPayloadValue: prettyWeiToEth(executionValue), + engineConsensusBlockValue: prettyWeiToEth(consensusValue), + engineBlockTotalValue: prettyWeiToEth(totalValue), + }; } /** @@ -294,9 +296,9 @@ export function getValidatorApi( const headSlot = chain.forkChoice.getHead().slot; if (currentSlot - headSlot > SYNC_TOLERANCE_EPOCHS * SLOTS_PER_EPOCH) { throw new NodeIsSyncing(`headSlot ${headSlot} currentSlot ${currentSlot}`); - } else { - return; } + + return; } case SyncState.Synced: @@ -511,9 +513,9 @@ export function getValidatorApi( consensusBlockValue, shouldOverrideBuilder, }; - } else { - return {data: block, version, executionPayloadValue, consensusBlockValue, shouldOverrideBuilder}; } + + return {data: block, version, executionPayloadValue, consensusBlockValue, shouldOverrideBuilder}; } finally { if (timer) timer({source}); } @@ -726,13 +728,13 @@ export function getValidatorApi( executionPayloadBlinded: false, executionPayloadSource, }; - } else { - return { - ...builder.value, - executionPayloadBlinded: true, - executionPayloadSource, - }; } + + return { + ...builder.value, + executionPayloadBlinded: true, + executionPayloadSource, + }; } throw Error("Unreachable error occurred during the builder and execution block production"); @@ -757,25 +759,25 @@ export function getValidatorApi( if (opts.blindedLocal === true && ForkSeq[meta.version] >= ForkSeq.bellatrix) { if (meta.executionPayloadBlinded) { return {data, meta}; - } else { - if (isBlockContents(data)) { - const {block} = data; - const blindedBlock = beaconBlockToBlinded(config, block as BeaconBlock); - return { - data: blindedBlock, - meta: {...meta, executionPayloadBlinded: true}, - }; - } else { - const blindedBlock = beaconBlockToBlinded(config, data as BeaconBlock); - return { - data: blindedBlock, - meta: {...meta, executionPayloadBlinded: true}, - }; - } } - } else { - return {data, meta}; + + if (isBlockContents(data)) { + const {block} = data; + const blindedBlock = beaconBlockToBlinded(config, block as BeaconBlock); + return { + data: blindedBlock, + meta: {...meta, executionPayloadBlinded: true}, + }; + } + + const blindedBlock = beaconBlockToBlinded(config, data as BeaconBlock); + return { + data: blindedBlock, + meta: {...meta, executionPayloadBlinded: true}, + }; } + + return {data, meta}; }, async produceBlindedBlock({slot, randaoReveal, graffiti}) { @@ -788,12 +790,14 @@ export function getValidatorApi( const {block} = data; const blindedBlock = beaconBlockToBlinded(config, block as BeaconBlock); return {data: blindedBlock, meta: {version}}; - } else if (isBlindedBeaconBlock(data)) { + } + + if (isBlindedBeaconBlock(data)) { return {data, meta: {version}}; - } else { - const blindedBlock = beaconBlockToBlinded(config, data as BeaconBlock); - return {data: blindedBlock, meta: {version}}; } + + const blindedBlock = beaconBlockToBlinded(config, data as BeaconBlock); + return {data: blindedBlock, meta: {version}}; }, async produceAttestationData({committeeIndex, slot}) { @@ -1224,7 +1228,9 @@ export function getValidatorApi( if (errors.length > 1) { throw Error("Multiple errors on publishAggregateAndProofs\n" + errors.map((e) => e.message).join("\n")); - } else if (errors.length === 1) { + } + + if (errors.length === 1) { throw errors[0]; } }, @@ -1280,7 +1286,9 @@ export function getValidatorApi( if (errors.length > 1) { throw Error("Multiple errors on publishContributionAndProofs\n" + errors.map((e) => e.message).join("\n")); - } else if (errors.length === 1) { + } + + if (errors.length === 1) { throw errors[0]; } }, diff --git a/packages/beacon-node/src/chain/blocks/index.ts b/packages/beacon-node/src/chain/blocks/index.ts index a7a2ced2ad7a..f64e4b1f3813 100644 --- a/packages/beacon-node/src/chain/blocks/index.ts +++ b/packages/beacon-node/src/chain/blocks/index.ts @@ -53,7 +53,9 @@ export async function processBlocks( ): Promise { if (blocks.length === 0) { return; // TODO: or throw? - } else if (blocks.length > 1) { + } + + if (blocks.length > 1) { assertLinearChainSegment(this.config, blocks); } @@ -161,11 +163,13 @@ export async function processBlocks( function getBlockError(e: unknown, block: SignedBeaconBlock): BlockError { if (e instanceof BlockError) { return e; - } else if (e instanceof Error) { + } + + if (e instanceof Error) { const blockError = new BlockError(block, {code: BlockErrorCode.BEACON_CHAIN_ERROR, error: e}); blockError.stack = e.stack; return blockError; - } else { - return new BlockError(block, {code: BlockErrorCode.BEACON_CHAIN_ERROR, error: e as Error}); } + + return new BlockError(block, {code: BlockErrorCode.BEACON_CHAIN_ERROR, error: e as Error}); } diff --git a/packages/beacon-node/src/chain/blocks/verifyBlocksSanityChecks.ts b/packages/beacon-node/src/chain/blocks/verifyBlocksSanityChecks.ts index 573dfa52ce8b..22b20a55fb67 100644 --- a/packages/beacon-node/src/chain/blocks/verifyBlocksSanityChecks.ts +++ b/packages/beacon-node/src/chain/blocks/verifyBlocksSanityChecks.ts @@ -45,9 +45,8 @@ export function verifyBlocksSanityChecks( if (blockSlot === 0) { if (opts.ignoreIfKnown) { continue; - } else { - throw new BlockError(block, {code: BlockErrorCode.GENESIS_BLOCK}); } + throw new BlockError(block, {code: BlockErrorCode.GENESIS_BLOCK}); } // Not finalized slot @@ -56,9 +55,8 @@ export function verifyBlocksSanityChecks( if (blockSlot <= finalizedSlot) { if (opts.ignoreIfFinalized) { continue; - } else { - throw new BlockError(block, {code: BlockErrorCode.WOULD_REVERT_FINALIZED_SLOT, blockSlot, finalizedSlot}); } + throw new BlockError(block, {code: BlockErrorCode.WOULD_REVERT_FINALIZED_SLOT, blockSlot, finalizedSlot}); } let parentBlockSlot: Slot; @@ -71,10 +69,9 @@ export function verifyBlocksSanityChecks( parentBlock = chain.forkChoice.getBlockHex(parentRoot); if (!parentBlock) { throw new BlockError(block, {code: BlockErrorCode.PARENT_UNKNOWN, parentRoot}); - } else { - // Parent is known to the fork-choice - parentBlockSlot = parentBlock.slot; } + // Parent is known to the fork-choice + parentBlockSlot = parentBlock.slot; } // Block not in the future, also checks for infinity @@ -89,9 +86,9 @@ export function verifyBlocksSanityChecks( if (chain.forkChoice.hasBlockHex(blockHash)) { if (opts.ignoreIfKnown) { continue; - } else { - throw new BlockError(block, {code: BlockErrorCode.ALREADY_KNOWN, root: blockHash}); } + + throw new BlockError(block, {code: BlockErrorCode.ALREADY_KNOWN, root: blockHash}); } // Block is relevant diff --git a/packages/beacon-node/src/chain/chain.ts b/packages/beacon-node/src/chain/chain.ts index 4bd8cd2bea3d..195b8736b2c3 100644 --- a/packages/beacon-node/src/chain/chain.ts +++ b/packages/beacon-node/src/chain/chain.ts @@ -464,23 +464,23 @@ export class BeaconChain implements IBeaconChain { executionOptimistic: isOptimisticBlock(block), finalized: slot === finalizedBlock.slot && finalizedBlock.slot !== GENESIS_SLOT, }; - } else { - // Just check if state is already in the cache. If it's not dialed to the correct slot, - // do not bother in advancing the state. restApiCanTriggerRegen == false means do no work - const block = this.forkChoice.getCanonicalBlockAtSlot(slot); - if (!block) { - return null; - } + } - const state = this.regen.getStateSync(block.stateRoot); - return ( - state && { - state, - executionOptimistic: isOptimisticBlock(block), - finalized: slot === finalizedBlock.slot && finalizedBlock.slot !== GENESIS_SLOT, - } - ); + // Just check if state is already in the cache. If it's not dialed to the correct slot, + // do not bother in advancing the state. restApiCanTriggerRegen == false means do no work + const block = this.forkChoice.getCanonicalBlockAtSlot(slot); + if (!block) { + return null; } + + const state = this.regen.getStateSync(block.stateRoot); + return ( + state && { + state, + executionOptimistic: isOptimisticBlock(block), + finalized: slot === finalizedBlock.slot && finalizedBlock.slot !== GENESIS_SLOT, + } + ); } async getHistoricalStateBySlot( @@ -931,28 +931,27 @@ export class BeaconChain implements IBeaconChain { const effectiveBalances = this.checkpointBalancesCache.get(checkpoint); if (effectiveBalances) { return effectiveBalances; - } else { - // not expected, need metrics - this.metrics?.balancesCache.misses.inc(); - this.logger.debug("checkpointBalances cache miss", { - epoch: checkpoint.epoch, - root: checkpoint.rootHex, - }); - - const {state, stateId, shouldWarn} = this.closestJustifiedBalancesStateToCheckpoint(checkpoint, blockState); - this.metrics?.balancesCache.closestStateResult.inc({stateId}); - if (shouldWarn) { - this.logger.warn("currentJustifiedCheckpoint state not avail, using closest state", { - checkpointEpoch: checkpoint.epoch, - checkpointRoot: checkpoint.rootHex, - stateId, - stateSlot: state.slot, - stateRoot: toRootHex(state.hashTreeRoot()), - }); - } + } + // not expected, need metrics + this.metrics?.balancesCache.misses.inc(); + this.logger.debug("checkpointBalances cache miss", { + epoch: checkpoint.epoch, + root: checkpoint.rootHex, + }); - return getEffectiveBalanceIncrementsZeroInactive(state); + const {state, stateId, shouldWarn} = this.closestJustifiedBalancesStateToCheckpoint(checkpoint, blockState); + this.metrics?.balancesCache.closestStateResult.inc({stateId}); + if (shouldWarn) { + this.logger.warn("currentJustifiedCheckpoint state not avail, using closest state", { + checkpointEpoch: checkpoint.epoch, + checkpointRoot: checkpoint.rootHex, + stateId, + stateSlot: state.slot, + stateRoot: toRootHex(state.hashTreeRoot()), + }); } + + return getEffectiveBalanceIncrementsZeroInactive(state); } /** diff --git a/packages/beacon-node/src/chain/genesis/genesis.ts b/packages/beacon-node/src/chain/genesis/genesis.ts index 979476c69530..0c46f920d614 100644 --- a/packages/beacon-node/src/chain/genesis/genesis.ts +++ b/packages/beacon-node/src/chain/genesis/genesis.ts @@ -124,9 +124,9 @@ export class GenesisBuilder implements IGenesisBuilder { depositTree: this.depositTree, block, }; - } else { - this.throttledLog(`Waiting for min genesis time ${block.timestamp} / ${this.config.MIN_GENESIS_TIME}`); } + + this.throttledLog(`Waiting for min genesis time ${block.timestamp} / ${this.config.MIN_GENESIS_TIME}`); } throw Error("depositsStream stopped without a valid genesis state"); @@ -147,11 +147,11 @@ export class GenesisBuilder implements IGenesisBuilder { if (this.activatedValidatorCount >= this.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT) { this.logger.info("Found enough genesis validators", {blockNumber}); return blockNumber; - } else { - this.throttledLog( - `Found ${this.state.validators.length} / ${this.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT} validators to genesis` - ); } + + this.throttledLog( + `Found ${this.state.validators.length} / ${this.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT} validators to genesis` + ); } throw Error("depositsStream stopped without a valid genesis state"); diff --git a/packages/beacon-node/src/chain/lightClient/index.ts b/packages/beacon-node/src/chain/lightClient/index.ts index 7e2f7c16311d..5cdae8b31c5d 100644 --- a/packages/beacon-node/src/chain/lightClient/index.ts +++ b/packages/beacon-node/src/chain/lightClient/index.ts @@ -741,7 +741,7 @@ export function blockToLightClientHeader(fork: ForkName, block: BeaconBlock b.notSeenAttesterCount - a.notSeenAttesterCount).slice(0, maxAttestation); } + + return attestations.sort((a, b) => b.notSeenAttesterCount - a.notSeenAttesterCount).slice(0, maxAttestation); } /** Get attestations for API. */ @@ -636,45 +636,43 @@ export function getNotSeenValidatorsFn(state: CachedBeaconStateAllForks): GetNot } // altair and future forks - else { - // Get attestations to be included in an altair block. - // Attestations are sorted by inclusion distance then number of attesters. - // Attestations should pass the validation when processing attestations in state-transition. - // check for altair block already - const altairState = state as CachedBeaconStateAltair; - const previousParticipation = altairState.previousEpochParticipation.getAll(); - const currentParticipation = altairState.currentEpochParticipation.getAll(); - const stateEpoch = computeEpochAtSlot(state.slot); - // this function could be called multiple times with same slot + committeeIndex - const cachedNotSeenValidators = new Map>(); - - return (epoch: Epoch, slot: Slot, committeeIndex: number) => { - const participationStatus = - epoch === stateEpoch ? currentParticipation : epoch === stateEpoch - 1 ? previousParticipation : null; - - if (participationStatus === null) { - return null; - } - const cacheKey = slot + "_" + committeeIndex; - let notSeenAttestingIndices = cachedNotSeenValidators.get(cacheKey); - if (notSeenAttestingIndices != null) { - // if all validators are seen then return null, we don't need to check for any attestations of same committee again - return notSeenAttestingIndices.size === 0 ? null : notSeenAttestingIndices; - } - - const committee = state.epochCtx.getBeaconCommittee(slot, committeeIndex); - notSeenAttestingIndices = new Set(); - for (const [i, validatorIndex] of committee.entries()) { - // no need to check flagIsTimelySource as if validator is not seen, it's participation status is 0 - if (participationStatus[validatorIndex] === 0) { - notSeenAttestingIndices.add(i); - } - } - cachedNotSeenValidators.set(cacheKey, notSeenAttestingIndices); + // Get attestations to be included in an altair block. + // Attestations are sorted by inclusion distance then number of attesters. + // Attestations should pass the validation when processing attestations in state-transition. + // check for altair block already + const altairState = state as CachedBeaconStateAltair; + const previousParticipation = altairState.previousEpochParticipation.getAll(); + const currentParticipation = altairState.currentEpochParticipation.getAll(); + const stateEpoch = computeEpochAtSlot(state.slot); + // this function could be called multiple times with same slot + committeeIndex + const cachedNotSeenValidators = new Map>(); + + return (epoch: Epoch, slot: Slot, committeeIndex: number) => { + const participationStatus = + epoch === stateEpoch ? currentParticipation : epoch === stateEpoch - 1 ? previousParticipation : null; + + if (participationStatus === null) { + return null; + } + const cacheKey = slot + "_" + committeeIndex; + let notSeenAttestingIndices = cachedNotSeenValidators.get(cacheKey); + if (notSeenAttestingIndices != null) { // if all validators are seen then return null, we don't need to check for any attestations of same committee again return notSeenAttestingIndices.size === 0 ? null : notSeenAttestingIndices; - }; - } + } + + const committee = state.epochCtx.getBeaconCommittee(slot, committeeIndex); + notSeenAttestingIndices = new Set(); + for (const [i, validatorIndex] of committee.entries()) { + // no need to check flagIsTimelySource as if validator is not seen, it's participation status is 0 + if (participationStatus[validatorIndex] === 0) { + notSeenAttestingIndices.add(i); + } + } + cachedNotSeenValidators.set(cacheKey, notSeenAttestingIndices); + // if all validators are seen then return null, we don't need to check for any attestations of same committee again + return notSeenAttestingIndices.size === 0 ? null : notSeenAttestingIndices; + }; } export function extractParticipationPhase0( diff --git a/packages/beacon-node/src/chain/opPools/attestationPool.ts b/packages/beacon-node/src/chain/opPools/attestationPool.ts index 887448b1e553..8d8fbb92c0f1 100644 --- a/packages/beacon-node/src/chain/opPools/attestationPool.ts +++ b/packages/beacon-node/src/chain/opPools/attestationPool.ts @@ -145,11 +145,10 @@ export class AttestationPool { if (aggregate) { // Aggregate mutating return aggregateAttestationInto(aggregate, attestation); - } else { - // Create new aggregate - aggregateByIndex.set(committeeIndex, attestationToAggregate(attestation)); - return InsertOutcome.NewData; } + // Create new aggregate + aggregateByIndex.set(committeeIndex, attestationToAggregate(attestation)); + return InsertOutcome.NewData; } /** diff --git a/packages/beacon-node/src/chain/opPools/opPool.ts b/packages/beacon-node/src/chain/opPools/opPool.ts index ee66591e9aef..f71186c06d35 100644 --- a/packages/beacon-node/src/chain/opPools/opPool.ts +++ b/packages/beacon-node/src/chain/opPools/opPool.ts @@ -410,10 +410,9 @@ function isVoluntaryExitSignatureIncludable(stateFork: ForkSeq, voluntaryExitFor if (stateFork >= ForkSeq.deneb) { // Exists are perpetually valid https://eips.ethereum.org/EIPS/eip-7044 return true; - } else { - // Can only include exits from the current and previous fork - return voluntaryExitFork === stateFork || voluntaryExitFork === stateFork - 1; } + // Can only include exits from the current and previous fork + return voluntaryExitFork === stateFork || voluntaryExitFork === stateFork - 1; } function isSlashableAtEpoch(validator: phase0.Validator, epoch: Epoch): boolean { diff --git a/packages/beacon-node/src/chain/opPools/syncCommitteeMessagePool.ts b/packages/beacon-node/src/chain/opPools/syncCommitteeMessagePool.ts index bbaba1835dce..4de11e447231 100644 --- a/packages/beacon-node/src/chain/opPools/syncCommitteeMessagePool.ts +++ b/packages/beacon-node/src/chain/opPools/syncCommitteeMessagePool.ts @@ -88,11 +88,11 @@ export class SyncCommitteeMessagePool { if (contribution) { // Aggregate mutating return aggregateSignatureInto(contribution, signature, indexInSubcommittee); - } else { - // Create new aggregate - contributionsByRoot.set(rootHex, signatureToAggregate(subnet, signature, indexInSubcommittee)); - return InsertOutcome.NewData; } + + // Create new aggregate + contributionsByRoot.set(rootHex, signatureToAggregate(subnet, signature, indexInSubcommittee)); + return InsertOutcome.NewData; } /** diff --git a/packages/beacon-node/src/chain/opPools/syncContributionAndProofPool.ts b/packages/beacon-node/src/chain/opPools/syncContributionAndProofPool.ts index ff0feea891e1..81363be218d8 100644 --- a/packages/beacon-node/src/chain/opPools/syncContributionAndProofPool.ts +++ b/packages/beacon-node/src/chain/opPools/syncContributionAndProofPool.ts @@ -90,10 +90,9 @@ export class SyncContributionAndProofPool { const bestContribution = bestContributionBySubnet.get(subnet); if (bestContribution) { return replaceIfBetter(bestContribution, contribution, syncCommitteeParticipants); - } else { - bestContributionBySubnet.set(subnet, contributionToFast(contribution, syncCommitteeParticipants)); - return InsertOutcome.NewData; } + bestContributionBySubnet.set(subnet, contributionToFast(contribution, syncCommitteeParticipants)); + return InsertOutcome.NewData; } /** diff --git a/packages/beacon-node/src/chain/produceBlock/produceBlockBody.ts b/packages/beacon-node/src/chain/produceBlock/produceBlockBody.ts index ff8221a326e9..37670e4b8f82 100644 --- a/packages/beacon-node/src/chain/produceBlock/produceBlockBody.ts +++ b/packages/beacon-node/src/chain/produceBlock/produceBlockBody.ts @@ -481,26 +481,26 @@ export async function getExecutionPayloadParentHash( if (isMergeTransitionComplete(state)) { // Post-merge, normal payload return {isPremerge: false, parentHash: state.latestExecutionPayloadHeader.blockHash}; - } else { - if ( - !ssz.Root.equals(chain.config.TERMINAL_BLOCK_HASH, ZERO_HASH) && - getCurrentEpoch(state) < chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH - ) - throw new Error( - `InvalidMergeTBH epoch: expected >= ${ - chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH - }, actual: ${getCurrentEpoch(state)}` - ); + } - const terminalPowBlockHash = await chain.eth1.getTerminalPowBlock(); - if (terminalPowBlockHash === null) { - // Pre-merge, no prepare payload call is needed - return {isPremerge: true}; - } else { - // Signify merge via producing on top of the last PoW block - return {isPremerge: false, parentHash: terminalPowBlockHash}; - } + if ( + !ssz.Root.equals(chain.config.TERMINAL_BLOCK_HASH, ZERO_HASH) && + getCurrentEpoch(state) < chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH + ) { + throw new Error( + `InvalidMergeTBH epoch: expected >= ${ + chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH + }, actual: ${getCurrentEpoch(state)}` + ); } + + const terminalPowBlockHash = await chain.eth1.getTerminalPowBlock(); + if (terminalPowBlockHash === null) { + // Pre-merge, no prepare payload call is needed + return {isPremerge: true}; + } + // Signify merge via producing on top of the last PoW block + return {isPremerge: false, parentHash: terminalPowBlockHash}; } export async function getPayloadAttributesForSSE( @@ -536,9 +536,9 @@ export async function getPayloadAttributesForSSE( payloadAttributes, }; return ssePayloadAttributes; - } else { - throw Error("The execution is still pre-merge"); } + + throw Error("The execution is still pre-merge"); } function preparePayloadAttributes( diff --git a/packages/beacon-node/src/chain/rewards/blockRewards.ts b/packages/beacon-node/src/chain/rewards/blockRewards.ts index 65dc23496070..19a59aaa028e 100644 --- a/packages/beacon-node/src/chain/rewards/blockRewards.ts +++ b/packages/beacon-node/src/chain/rewards/blockRewards.ts @@ -90,9 +90,9 @@ function computeSyncAggregateReward(block: altair.BeaconBlock, preState: CachedB const {syncProposerReward} = preState.epochCtx; return syncCommitteeBits.getTrueBitIndexes().length * Math.floor(syncProposerReward); // syncProposerReward should already be integer - } else { - return 0; // phase0 block does not have syncAggregate } + + return 0; // phase0 block does not have syncAggregate } /** diff --git a/packages/beacon-node/src/chain/rewards/syncCommitteeRewards.ts b/packages/beacon-node/src/chain/rewards/syncCommitteeRewards.ts index 89ef84af43a2..71d345e32811 100644 --- a/packages/beacon-node/src/chain/rewards/syncCommitteeRewards.ts +++ b/packages/beacon-node/src/chain/rewards/syncCommitteeRewards.ts @@ -51,7 +51,7 @@ export async function computeSyncCommitteeRewards( return rewards.filter( (reward) => filtersSet.has(reward.validatorIndex) || filtersSet.has(index2pubkey[reward.validatorIndex].toHex()) ); - } else { - return rewards; } + + return rewards; } diff --git a/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts b/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts index 3806668436d8..e27fba54e7c6 100644 --- a/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts +++ b/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts @@ -149,42 +149,42 @@ export class SeenGossipBlockInput { blockInput, blockInputMeta: {pending: null, haveBlobs: allBlobs.blobs.length, expectedBlobs: blobKzgCommitments.length}, }; - } else { - const blockInput = getBlockInput.dataPromise( - config, - signedBlock, - BlockSource.gossip, - blockBytes ?? null, - cachedData - ); - - resolveBlockInput(blockInput); - return { - blockInput, - blockInputMeta: { - pending: GossipedInputType.blob, - haveBlobs: blobsCache.size, - expectedBlobs: blobKzgCommitments.length, - }, - }; - } - } else { - // will need to wait for the block to showup - if (cachedData === undefined) { - throw Error("Missing cachedData for deneb+ blobs"); } - const {blobsCache} = cachedData; + const blockInput = getBlockInput.dataPromise( + config, + signedBlock, + BlockSource.gossip, + blockBytes ?? null, + cachedData + ); + + resolveBlockInput(blockInput); return { - blockInput: { - block: null, - blockRootHex: blockHex, - cachedData, - blockInputPromise, + blockInput, + blockInputMeta: { + pending: GossipedInputType.blob, + haveBlobs: blobsCache.size, + expectedBlobs: blobKzgCommitments.length, }, - blockInputMeta: {pending: GossipedInputType.block, haveBlobs: blobsCache.size, expectedBlobs: null}, }; } + + // will need to wait for the block to showup + if (cachedData === undefined) { + throw Error("Missing cachedData for deneb+ blobs"); + } + const {blobsCache} = cachedData; + + return { + blockInput: { + block: null, + blockRootHex: blockHex, + cachedData, + blockInputPromise, + }, + blockInputMeta: {pending: GossipedInputType.block, haveBlobs: blobsCache.size, expectedBlobs: null}, + }; } } diff --git a/packages/beacon-node/src/chain/shufflingCache.ts b/packages/beacon-node/src/chain/shufflingCache.ts index 749fea1b82ff..bdedddacf6db 100644 --- a/packages/beacon-node/src/chain/shufflingCache.ts +++ b/packages/beacon-node/src/chain/shufflingCache.ts @@ -130,10 +130,9 @@ export class ShufflingCache implements IShufflingCache { if (isShufflingCacheItem(cacheItem)) { this.metrics?.shufflingCache.hit.inc(); return cacheItem.shuffling; - } else { - this.metrics?.shufflingCache.shufflingPromiseNotResolved.inc(); - return cacheItem.promise; } + this.metrics?.shufflingCache.shufflingPromiseNotResolved.inc(); + return cacheItem.promise; } /** diff --git a/packages/beacon-node/src/chain/validation/attestation.ts b/packages/beacon-node/src/chain/validation/attestation.ts index 119a8ee1a899..37687faffe00 100644 --- a/packages/beacon-node/src/chain/validation/attestation.ts +++ b/packages/beacon-node/src/chain/validation/attestation.ts @@ -208,19 +208,18 @@ export async function validateApiAttestation( const targetEpoch = attestation.data.target.epoch; chain.seenAttesters.add(targetEpoch, validatorIndex); return step0Result; - } else { - throw new AttestationError(GossipAction.IGNORE, { - code: AttestationErrorCode.INVALID_SIGNATURE, - }); } + + throw new AttestationError(GossipAction.IGNORE, { + code: AttestationErrorCode.INVALID_SIGNATURE, + }); } catch (err) { if (err instanceof EpochCacheError && err.type.code === EpochCacheErrorCode.COMMITTEE_INDEX_OUT_OF_RANGE) { throw new AttestationError(GossipAction.IGNORE, { code: AttestationErrorCode.BAD_TARGET_EPOCH, }); - } else { - throw err; } + throw err; } } @@ -715,27 +714,27 @@ function verifyAttestationTargetRoot(headBlock: ProtoBlock, targetRoot: Root, at targetRoot: toRootHex(targetRoot), expected: null, }); - } else { - const expectedTargetRoot = - headBlockEpoch === attestationEpoch - ? // If the block is in the same epoch as the attestation, then use the target root - // from the block. - headBlock.targetRoot - : // If the head block is from a previous epoch then skip slots will cause the head block - // root to become the target block root. - // - // We know the head block is from a previous epoch due to a previous check. - headBlock.blockRoot; - - // TODO: Do a fast comparision to convert and compare byte by byte - if (expectedTargetRoot !== toRootHex(targetRoot)) { - // Reject any attestation with an invalid target root. - throw new AttestationError(GossipAction.REJECT, { - code: AttestationErrorCode.INVALID_TARGET_ROOT, - targetRoot: toRootHex(targetRoot), - expected: expectedTargetRoot, - }); - } + } + + const expectedTargetRoot = + headBlockEpoch === attestationEpoch + ? // If the block is in the same epoch as the attestation, then use the target root + // from the block. + headBlock.targetRoot + : // If the head block is from a previous epoch then skip slots will cause the head block + // root to become the target block root. + // + // We know the head block is from a previous epoch due to a previous check. + headBlock.blockRoot; + + // TODO: Do a fast comparision to convert and compare byte by byte + if (expectedTargetRoot !== toRootHex(targetRoot)) { + // Reject any attestation with an invalid target root. + throw new AttestationError(GossipAction.REJECT, { + code: AttestationErrorCode.INVALID_TARGET_ROOT, + targetRoot: toRootHex(targetRoot), + expected: expectedTargetRoot, + }); } } diff --git a/packages/beacon-node/src/db/buckets.ts b/packages/beacon-node/src/db/buckets.ts index c361b4d60e7b..c35a5a18edf5 100644 --- a/packages/beacon-node/src/db/buckets.ts +++ b/packages/beacon-node/src/db/buckets.ts @@ -67,9 +67,8 @@ export function getBucketNameByValue(enumValue: T): keyof type const keys = Object.keys(Bucket).filter((x) => { if (Number.isNaN(parseInt(x))) { return Bucket[x as keyof typeof Bucket] === enumValue; - } else { - return false; } + return false; }) as (keyof typeof Bucket)[]; if (keys.length > 0) { return keys[0]; diff --git a/packages/beacon-node/src/db/repositories/depositDataRoot.ts b/packages/beacon-node/src/db/repositories/depositDataRoot.ts index 9b872c91bce4..97200ccd0f92 100644 --- a/packages/beacon-node/src/db/repositories/depositDataRoot.ts +++ b/packages/beacon-node/src/db/repositories/depositDataRoot.ts @@ -69,7 +69,9 @@ export class DepositDataRootRepository extends Repository { // TODO: Review and fix properly if (index > depositRootTree.length) { throw Error(`Error setting depositRootTree index ${index} > length ${depositRootTree.length}`); - } else if (index === depositRootTree.length) { + } + + if (index === depositRootTree.length) { depositRootTree.push(value); } else { depositRootTree.set(index, value); diff --git a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts index a38b3f9987d9..14ce2205331e 100644 --- a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts +++ b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts @@ -380,26 +380,24 @@ export class Eth1DepositDataTracker { this.eth1FollowDistance = Math.min(this.eth1FollowDistance + delta, this.config.ETH1_FOLLOW_DISTANCE); return true; - } else { - // Blocks are slower than expected, reduce eth1FollowDistance. Limit min CATCHUP_MIN_FOLLOW_DISTANCE - const delta = - this.eth1FollowDistance - - Math.max(this.eth1FollowDistance - ETH1_FOLLOW_DISTANCE_DELTA_IF_SLOW, ETH_MIN_FOLLOW_DISTANCE); - this.eth1FollowDistance = this.eth1FollowDistance - delta; - - // Even if the blocks are slow, when we are all caught up as there is no - // further possibility to reduce follow distance, we need to call it quits - // for now, else it leads to an incessant poll on the EL - return delta === 0; } + // Blocks are slower than expected, reduce eth1FollowDistance. Limit min CATCHUP_MIN_FOLLOW_DISTANCE + const delta = + this.eth1FollowDistance - + Math.max(this.eth1FollowDistance - ETH1_FOLLOW_DISTANCE_DELTA_IF_SLOW, ETH_MIN_FOLLOW_DISTANCE); + this.eth1FollowDistance = this.eth1FollowDistance - delta; + + // Even if the blocks are slow, when we are all caught up as there is no + // further possibility to reduce follow distance, we need to call it quits + // for now, else it leads to an incessant poll on the EL + return delta === 0; } private getFromBlockToFetch(lastCachedBlock: number | null): number { if (lastCachedBlock === null) { return this.eth1Provider.deployBlock ?? 0; - } else { - return lastCachedBlock + 1; } + return lastCachedBlock + 1; } private async getLastProcessedDepositBlockNumber(): Promise { diff --git a/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts b/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts index 6d9fd2ad7d11..5bf76625dfe8 100644 --- a/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts +++ b/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts @@ -126,11 +126,10 @@ export class Eth1MergeBlockTracker { td: this.latestEth1Block.totalDifficulty, timestamp: this.latestEth1Block.timestamp, }; - } else { - return { - ttdHit: true, - }; } + return { + ttdHit: true, + }; } /** @@ -242,60 +241,56 @@ export class Eth1MergeBlockTracker { const block = await this.getPowBlock(terminalBlockHash); if (block) { return block; - } else { - // if a TERMINAL_BLOCK_HASH other than ZERO_HASH is configured and we can't find it, return NONE - return null; } + // if a TERMINAL_BLOCK_HASH other than ZERO_HASH is configured and we can't find it, return NONE + return null; } // Search merge block by TTD - else { - const latestBlockRaw = await this.eth1Provider.getBlockByNumber("latest"); - if (!latestBlockRaw) { - throw Error("getBlockByNumber('latest') returned null"); - } - - let block = toPowBlock(latestBlockRaw); - this.latestEth1Block = {...block, timestamp: quantityToNum(latestBlockRaw.timestamp)}; - this.cacheBlock(block); + const latestBlockRaw = await this.eth1Provider.getBlockByNumber("latest"); + if (!latestBlockRaw) { + throw Error("getBlockByNumber('latest') returned null"); + } - // This code path to look backwards for the merge block is only necessary if: - // - The network has not yet found the merge block - // - There are descendants of the merge block in the eth1 chain - // For the search below to require more than a few hops, multiple block proposers in a row must fail to detect - // an existing merge block. Such situation is extremely unlikely, so this search is left un-optimized. Since - // this class can start eagerly looking for the merge block when not necessary, startPollingMergeBlock() should - // only be called when there is certainty that a mergeBlock search is necessary. - - while (true) { - if (block.totalDifficulty < this.config.TERMINAL_TOTAL_DIFFICULTY) { - // TTD not reached yet - return null; - } + let block = toPowBlock(latestBlockRaw); + this.latestEth1Block = {...block, timestamp: quantityToNum(latestBlockRaw.timestamp)}; + this.cacheBlock(block); + + // This code path to look backwards for the merge block is only necessary if: + // - The network has not yet found the merge block + // - There are descendants of the merge block in the eth1 chain + // For the search below to require more than a few hops, multiple block proposers in a row must fail to detect + // an existing merge block. Such situation is extremely unlikely, so this search is left un-optimized. Since + // this class can start eagerly looking for the merge block when not necessary, startPollingMergeBlock() should + // only be called when there is certainty that a mergeBlock search is necessary. + + while (true) { + if (block.totalDifficulty < this.config.TERMINAL_TOTAL_DIFFICULTY) { + // TTD not reached yet + return null; + } - // else block.totalDifficulty >= this.config.TERMINAL_TOTAL_DIFFICULTY - // Potential mergeBlock! Must find the first block that passes TTD + // else block.totalDifficulty >= this.config.TERMINAL_TOTAL_DIFFICULTY + // Potential mergeBlock! Must find the first block that passes TTD - // Allow genesis block to reach TTD https://github.com/ethereum/consensus-specs/pull/2719 - if (block.parentHash === ZERO_HASH_HEX) { - return block; - } + // Allow genesis block to reach TTD https://github.com/ethereum/consensus-specs/pull/2719 + if (block.parentHash === ZERO_HASH_HEX) { + return block; + } - const parent = await this.getPowBlock(block.parentHash); - if (!parent) { - throw Error(`Unknown parent of block with TD>TTD ${block.parentHash}`); - } + const parent = await this.getPowBlock(block.parentHash); + if (!parent) { + throw Error(`Unknown parent of block with TD>TTD ${block.parentHash}`); + } - this.metrics?.eth1.eth1ParentBlocksFetched.inc(); + this.metrics?.eth1.eth1ParentBlocksFetched.inc(); - // block.td > TTD && parent.td < TTD => block is mergeBlock - if (parent.totalDifficulty < this.config.TERMINAL_TOTAL_DIFFICULTY) { - // Is terminal total difficulty block AND has verified block -> parent relationship - return block; - } else { - block = parent; - } + // block.td > TTD && parent.td < TTD => block is mergeBlock + if (parent.totalDifficulty < this.config.TERMINAL_TOTAL_DIFFICULTY) { + // Is terminal total difficulty block AND has verified block -> parent relationship + return block; } + block = parent; } } diff --git a/packages/beacon-node/src/eth1/index.ts b/packages/beacon-node/src/eth1/index.ts index 059c9c6c6c4a..42b82d03a848 100644 --- a/packages/beacon-node/src/eth1/index.ts +++ b/packages/beacon-node/src/eth1/index.ts @@ -53,9 +53,8 @@ export function initializeEth1ForBlockProduction( logger: modules.logger, signal: modules.signal, }); - } else { - return new Eth1ForBlockProductionDisabled(); } + return new Eth1ForBlockProductionDisabled(); } export class Eth1ForBlockProduction implements IEth1ForBlockProduction { @@ -85,9 +84,8 @@ export class Eth1ForBlockProduction implements IEth1ForBlockProduction { async getEth1DataAndDeposits(state: CachedBeaconStateAllForks): Promise { if (this.eth1DepositDataTracker === null) { return {eth1Data: state.eth1Data, deposits: []}; - } else { - return this.eth1DepositDataTracker.getEth1DataAndDeposits(state); } + return this.eth1DepositDataTracker.getEth1DataAndDeposits(state); } async getTerminalPowBlock(): Promise { diff --git a/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts b/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts index e1a2a001c278..abd0dd20050e 100644 --- a/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts +++ b/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts @@ -296,12 +296,10 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient { // controller will abort on both parent signal abort + timeout of this specific request if (this.opts?.signal?.aborted) { throw new ErrorAborted("request"); - } else { - throw new TimeoutError("request"); } - } else { - throw e; + throw new TimeoutError("request"); } + throw e; } finally { timer?.(); this.metrics?.activeRequests.dec({routeId}, 1); @@ -315,11 +313,11 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient { function parseRpcResponse(res: RpcResponse, payload: RpcPayload

): R { if (res.result !== undefined) { return res.result; - } else if (res.error !== undefined) { + } + if (res.error !== undefined) { throw new ErrorJsonRpcResponse(res, payload.method); - } else { - throw Error(`Invalid JSON RPC response, no result or error property: ${jsonSerializeTry(res)}`); } + throw Error(`Invalid JSON RPC response, no result or error property: ${jsonSerializeTry(res)}`); } /** diff --git a/packages/beacon-node/src/eth1/utils/deposits.ts b/packages/beacon-node/src/eth1/utils/deposits.ts index 8d0331fc01d6..36f8c331ebc9 100644 --- a/packages/beacon-node/src/eth1/utils/deposits.ts +++ b/packages/beacon-node/src/eth1/utils/deposits.ts @@ -33,7 +33,9 @@ export async function getDeposits( if (deposits.length < depositsLen) { throw new Eth1Error({code: Eth1ErrorCode.NOT_ENOUGH_DEPOSITS, len: deposits.length, expectedLen: depositsLen}); - } else if (deposits.length > depositsLen) { + } + + if (deposits.length > depositsLen) { throw new Eth1Error({code: Eth1ErrorCode.TOO_MANY_DEPOSITS, len: deposits.length, expectedLen: depositsLen}); } diff --git a/packages/beacon-node/src/eth1/utils/eth1Vote.ts b/packages/beacon-node/src/eth1/utils/eth1Vote.ts index 7a4e3ddca9b6..84d35ae7d434 100644 --- a/packages/beacon-node/src/eth1/utils/eth1Vote.ts +++ b/packages/beacon-node/src/eth1/utils/eth1Vote.ts @@ -72,16 +72,14 @@ export function pickEth1Vote(state: BeaconStateAllForks, votesToConsider: phase0 } // If there's a single winning vote with a majority vote that one - else if (eth1DataRootsMaxVotes.length === 1) { + if (eth1DataRootsMaxVotes.length === 1) { return eth1DataHashToEth1Data.get(eth1DataRootsMaxVotes[0]) ?? state.eth1Data; } // If there are multiple winning votes, vote for the latest one - else { - const latestMostVotedRoot = - eth1DataVotesOrder[Math.max(...eth1DataRootsMaxVotes.map((root) => eth1DataVotesOrder.indexOf(root)))]; - return eth1DataHashToEth1Data.get(latestMostVotedRoot) ?? state.eth1Data; - } + const latestMostVotedRoot = + eth1DataVotesOrder[Math.max(...eth1DataRootsMaxVotes.map((root) => eth1DataVotesOrder.indexOf(root)))]; + return eth1DataHashToEth1Data.get(latestMostVotedRoot) ?? state.eth1Data; } /** diff --git a/packages/beacon-node/src/eth1/utils/optimizeNextBlockDiffForGenesis.ts b/packages/beacon-node/src/eth1/utils/optimizeNextBlockDiffForGenesis.ts index 4dc633693580..961d58680e47 100644 --- a/packages/beacon-node/src/eth1/utils/optimizeNextBlockDiffForGenesis.ts +++ b/packages/beacon-node/src/eth1/utils/optimizeNextBlockDiffForGenesis.ts @@ -13,7 +13,6 @@ export function optimizeNextBlockDiffForGenesis( const numBlocksToGenesis = Math.floor(timeToGenesis / params.SECONDS_PER_ETH1_BLOCK); if (numBlocksToGenesis <= 2) { return 1; - } else { - return Math.max(1, Math.floor(numBlocksToGenesis / 2)); } + return Math.max(1, Math.floor(numBlocksToGenesis / 2)); } diff --git a/packages/beacon-node/src/execution/engine/http.ts b/packages/beacon-node/src/execution/engine/http.ts index a8206a89250d..e5e65746d90f 100644 --- a/packages/beacon-node/src/execution/engine/http.ts +++ b/packages/beacon-node/src/execution/engine/http.ts @@ -258,9 +258,8 @@ export class ExecutionEngineHttp implements IExecutionEngine { ).catch((e: Error) => { if (e instanceof HttpRpcError || e instanceof ErrorJsonRpcResponse) { return {status: ExecutionPayloadStatus.ELERROR, latestValidHash: null, validationError: e.message}; - } else { - return {status: ExecutionPayloadStatus.UNAVAILABLE, latestValidHash: null, validationError: e.message}; } + return {status: ExecutionPayloadStatus.UNAVAILABLE, latestValidHash: null, validationError: e.message}; }); this.updateEngineState(getExecutionEngineState({payloadStatus: status, oldState: this.state})); @@ -379,9 +378,8 @@ export class ExecutionEngineHttp implements IExecutionEngine { // Throw error on syncing if requested to produce a block, else silently ignore if (payloadAttributes) { throw Error("Execution Layer Syncing"); - } else { - return null; } + return null; case ExecutionPayloadStatus.INVALID: throw Error( diff --git a/packages/beacon-node/src/execution/engine/mock.ts b/packages/beacon-node/src/execution/engine/mock.ts index bc3a130e604e..8062b68bf572 100644 --- a/packages/beacon-node/src/execution/engine/mock.ts +++ b/packages/beacon-node/src/execution/engine/mock.ts @@ -149,7 +149,9 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend { const predefinedResponse = this.predefinedPayloadStatuses.get(blockHash); if (predefinedResponse) { return predefinedResponse; - } else if (this.opts.onlyPredefinedResponses) { + } + + if (this.opts.onlyPredefinedResponses) { throw Error(`No predefined response for blockHash ${blockHash}`); } @@ -212,7 +214,9 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend { payloadStatus: predefinedResponse, payloadId: null, }; - } else if (this.opts.onlyPredefinedResponses) { + } + + if (this.opts.onlyPredefinedResponses) { throw Error(`No predefined response for headBlockHash ${headBlockHash}`); } @@ -344,14 +348,12 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend { } // Don't start build process - else { - // IF the payload is deemed VALID and a build process hasn't been started - // {payloadStatus: {status: VALID, latestValidHash: forkchoiceState.headBlockHash, validationError: null}, payloadId: null} - return { - payloadStatus: {status: ExecutionPayloadStatus.VALID, latestValidHash: null, validationError: null}, - payloadId: null, - }; - } + // IF the payload is deemed VALID and a build process hasn't been started + // {payloadStatus: {status: VALID, latestValidHash: forkchoiceState.headBlockHash, validationError: null}, payloadId: null} + return { + payloadStatus: {status: ExecutionPayloadStatus.VALID, latestValidHash: null, validationError: null}, + payloadId: null, + }; } /** diff --git a/packages/beacon-node/src/metrics/validatorMonitor.ts b/packages/beacon-node/src/metrics/validatorMonitor.ts index 34dfa6b72e03..14a210f62997 100644 --- a/packages/beacon-node/src/metrics/validatorMonitor.ts +++ b/packages/beacon-node/src/metrics/validatorMonitor.ts @@ -814,7 +814,7 @@ function renderAttestationSummary( } // - else if (flags.timelyTarget) { + if (flags.timelyTarget) { // timelyHead == false, means at least one is true // - attestation voted incorrect head // - attestation was included late @@ -870,57 +870,55 @@ function renderAttestationSummary( } // - else if (flags.timelySource) { + if (flags.timelySource) { // timelyTarget == false && timelySource == true means that // - attestation voted the wrong target but distance is <= integer_squareroot(SLOTS_PER_EPOCH) return "wrong_target_timely_source"; } // - else { - // timelySource == false, either: - // - attestation was not included in the block - // - included in block with wrong target (very unlikely) - // - included in block with distance > SLOTS_PER_EPOCH (very unlikely) - - // Validator failed to submit an attestation for this epoch, validator client is probably offline - if (!summary || summary.poolSubmitDelayMinSec === null) { - return "no_submission"; - } + // timelySource == false, either: + // - attestation was not included in the block + // - included in block with wrong target (very unlikely) + // - included in block with distance > SLOTS_PER_EPOCH (very unlikely) + + // Validator failed to submit an attestation for this epoch, validator client is probably offline + if (!summary || summary.poolSubmitDelayMinSec === null) { + return "no_submission"; + } - const canonicalBlockInclusion = summary.blockInclusions.find((block) => isCanonical(rootCache, block)); - if (canonicalBlockInclusion) { - // Canonical block inclusion with no participation flags set means wrong target + late source - return "wrong_target_late_source"; - } + const canonicalBlockInclusion = summary.blockInclusions.find((block) => isCanonical(rootCache, block)); + if (canonicalBlockInclusion) { + // Canonical block inclusion with no participation flags set means wrong target + late source + return "wrong_target_late_source"; + } - const submittedLate = - summary.poolSubmitDelayMinSec > - (INTERVALS_LATE_ATTESTATION_SUBMISSION * config.SECONDS_PER_SLOT) / INTERVALS_PER_SLOT; - - const aggregateInclusion = summary.aggregateInclusionDelaysSec.length > 0; - - if (submittedLate && aggregateInclusion) { - return "late_submit"; - } else if (submittedLate && !aggregateInclusion) { - return "late_submit_no_aggregate_inclusion"; - } else if (!submittedLate && aggregateInclusion) { - // TODO: Why was it missed then? - if (summary.blockInclusions.length) { - return "block_inclusion_but_orphan"; - } else { - return "aggregate_inclusion_but_missed"; - } - // } else if (!submittedLate && !aggregateInclusion) { - } else { - // Did the node had enough peers? - if (summary.poolSubmitSentPeers === 0) { - return "sent_to_zero_peers"; - } else { - return "no_aggregate_inclusion"; - } + const submittedLate = + summary.poolSubmitDelayMinSec > + (INTERVALS_LATE_ATTESTATION_SUBMISSION * config.SECONDS_PER_SLOT) / INTERVALS_PER_SLOT; + + const aggregateInclusion = summary.aggregateInclusionDelaysSec.length > 0; + + if (submittedLate && aggregateInclusion) { + return "late_submit"; + } + if (submittedLate && !aggregateInclusion) { + return "late_submit_no_aggregate_inclusion"; + } + + if (!submittedLate && aggregateInclusion) { + // TODO: Why was it missed then? + if (summary.blockInclusions.length) { + return "block_inclusion_but_orphan"; } + return "aggregate_inclusion_but_missed"; + // } else if (!submittedLate && !aggregateInclusion) { } + // Did the node had enough peers? + if (summary.poolSubmitSentPeers === 0) { + return "sent_to_zero_peers"; + } + return "no_aggregate_inclusion"; } function whyIsHeadVoteWrong(rootCache: RootHexCache, canonicalBlockInclusion: AttestationBlockInclusion): string { @@ -968,9 +966,7 @@ function whyIsHeadVoteWrong(rootCache: RootHexCache, canonicalBlockInclusion: At // \_(A)_(A) // // Vote for different heads on skipped slot - else { - return "wrong_head_vote"; - } + return "wrong_head_vote"; } function whyIsDistanceNotOk( @@ -989,9 +985,7 @@ function whyIsDistanceNotOk( } // - else { - return "late_unknown"; - } + return "late_unknown"; } /** Returns true if the state's root record includes `block` */ diff --git a/packages/beacon-node/src/monitoring/properties.ts b/packages/beacon-node/src/monitoring/properties.ts index 55b94dd159b7..2ab819179863 100644 --- a/packages/beacon-node/src/monitoring/properties.ts +++ b/packages/beacon-node/src/monitoring/properties.ts @@ -140,11 +140,11 @@ export class MetricProperty implements ClientStatsPropert case JsonType.Boolean: if (this.definition.rangeValue != null) { return value === this.definition.rangeValue; - } else if (this.definition.threshold != null) { + } + if (this.definition.threshold != null) { return value >= this.definition.threshold; - } else { - return value > 0; } + return value > 0; } } return value; diff --git a/packages/beacon-node/src/monitoring/service.ts b/packages/beacon-node/src/monitoring/service.ts index bd2388738d1f..f6a6a2352e02 100644 --- a/packages/beacon-node/src/monitoring/service.ts +++ b/packages/beacon-node/src/monitoring/service.ts @@ -191,11 +191,11 @@ export class MonitoringService { // error was thrown by abort signal if (signal.reason === FetchAbortReason.Close) { throw new ErrorAborted("request"); - } else if (signal.reason === FetchAbortReason.Timeout) { + } + if (signal.reason === FetchAbortReason.Timeout) { throw new TimeoutError("request"); - } else { - throw e; } + throw e; } finally { timer({status: res?.ok ? SendDataStatus.Success : SendDataStatus.Error}); clearTimeout(timeout); diff --git a/packages/beacon-node/src/network/gossip/encoding.ts b/packages/beacon-node/src/network/gossip/encoding.ts index 02c0df07b2f1..f7f733fcd915 100644 --- a/packages/beacon-node/src/network/gossip/encoding.ts +++ b/packages/beacon-node/src/network/gossip/encoding.ts @@ -25,9 +25,8 @@ const sharedMsgIdBuf = Buffer.alloc(20); export function fastMsgIdFn(rpcMsg: RPC.Message): string { if (rpcMsg.data) { return xxhash.h64Raw(rpcMsg.data, h64Seed).toString(16); - } else { - return "0000000000000000"; } + return "0000000000000000"; } export function msgIdToStrFn(msgId: Uint8Array): string { diff --git a/packages/beacon-node/src/network/gossip/gossipsub.ts b/packages/beacon-node/src/network/gossip/gossipsub.ts index 8e24a8fe9a7b..e8ccab6fc591 100644 --- a/packages/beacon-node/src/network/gossip/gossipsub.ts +++ b/packages/beacon-node/src/network/gossip/gossipsub.ts @@ -324,7 +324,8 @@ export class Eth2Gossipsub extends GossipSub { */ function attSubnetLabel(subnet: number): string { if (subnet > 9) return String(subnet); - else return `0${subnet}`; + + return `0${subnet}`; } function getMetricsTopicStrToLabel(config: BeaconConfig, opts: {disableLightClientServer: boolean}): TopicStrToLabel { diff --git a/packages/beacon-node/src/network/peers/discover.ts b/packages/beacon-node/src/network/peers/discover.ts index 25c32823bef6..0ca67caf74fa 100644 --- a/packages/beacon-node/src/network/peers/discover.ts +++ b/packages/beacon-node/src/network/peers/discover.ts @@ -278,9 +278,8 @@ export class PeerDiscovery { if (this.randomNodeQuery.code === QueryStatusCode.Active) { this.metrics?.discovery.findNodeQueryRequests.inc({action: "ignore"}); return; - } else { - this.metrics?.discovery.findNodeQueryRequests.inc({action: "start"}); } + this.metrics?.discovery.findNodeQueryRequests.inc({action: "start"}); // Use async version to prevent blocking the event loop // Time to completion of this function is not critical, in case this async call add extra lag @@ -389,13 +388,13 @@ export class PeerDiscovery { if (this.shouldDialPeer(cachedPeer)) { void this.dialPeer(cachedPeer); return DiscoveredPeerStatus.attempt_dial; - } else { - // Add to pending good peers with a last seen time - this.cachedENRs.set(peerId.toString(), cachedPeer); - const dropped = pruneSetToMax(this.cachedENRs, MAX_CACHED_ENRS); - // If the cache was already full, count the peer as dropped - return dropped > 0 ? DiscoveredPeerStatus.dropped : DiscoveredPeerStatus.cached; } + + // Add to pending good peers with a last seen time + this.cachedENRs.set(peerId.toString(), cachedPeer); + const dropped = pruneSetToMax(this.cachedENRs, MAX_CACHED_ENRS); + // If the cache was already full, count the peer as dropped + return dropped > 0 ? DiscoveredPeerStatus.dropped : DiscoveredPeerStatus.cached; } catch (e) { this.logger.error("Error onDiscovered", {}, e as Error); return DiscoveredPeerStatus.error; diff --git a/packages/beacon-node/src/network/processor/gossipQueues/index.ts b/packages/beacon-node/src/network/processor/gossipQueues/index.ts index 12596a42b7a1..dfa5b0dd1973 100644 --- a/packages/beacon-node/src/network/processor/gossipQueues/index.ts +++ b/packages/beacon-node/src/network/processor/gossipQueues/index.ts @@ -104,8 +104,7 @@ export function createGossipQueues(): { return mapValues(gossipQueueOpts, (opts) => { if (isIndexedGossipQueueMinSizeOpts(opts)) { return new IndexedGossipQueueMinSize(opts); - } else { - return new LinearGossipQueue(opts); } + return new LinearGossipQueue(opts); }); } diff --git a/packages/beacon-node/src/network/processor/gossipQueues/indexed.ts b/packages/beacon-node/src/network/processor/gossipQueues/indexed.ts index 8edba7dfaadb..a7b23b2ac929 100644 --- a/packages/beacon-node/src/network/processor/gossipQueues/indexed.ts +++ b/packages/beacon-node/src/network/processor/gossipQueues/indexed.ts @@ -123,9 +123,8 @@ export class IndexedGossipQueueMinSize implements GossipQueue { // overload, need to drop more items if (this.opts.dropOpts.type === DropType.count) { return this.dropByCount(this.opts.dropOpts.count); - } else { - this.recentDrop = true; - const droppedCount = this.dropByRatio(this._dropRatio); - // increase drop ratio the next time queue is full - this._dropRatio = Math.min(MAX_DROP_RATIO, this._dropRatio + this.opts.dropOpts.step); - return droppedCount; } + + this.recentDrop = true; + const droppedCount = this.dropByRatio(this._dropRatio); + // increase drop ratio the next time queue is full + this._dropRatio = Math.min(MAX_DROP_RATIO, this._dropRatio + this.opts.dropOpts.step); + return droppedCount; } next(): T | null { diff --git a/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts index 74b6d8f13b2e..8c69c21679ba 100644 --- a/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts +++ b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts @@ -37,7 +37,7 @@ export async function beaconBlocksMaybeBlobsByRange( } // Only request blobs if they are recent enough - else if (computeEpochAtSlot(startSlot) >= currentEpoch - config.MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS) { + if (computeEpochAtSlot(startSlot) >= currentEpoch - config.MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS) { const [allBlocks, allBlobSidecars] = await Promise.all([ network.sendBeaconBlocksByRange(peerId, request), network.sendBlobSidecarsByRange(peerId, request), @@ -47,9 +47,7 @@ export async function beaconBlocksMaybeBlobsByRange( } // Post Deneb but old blobs - else { - throw Error("Cannot sync blobs outside of blobs prune window"); - } + throw Error("Cannot sync blobs outside of blobs prune window"); } // Assumes that the blobs are in the same sequence as blocks, doesn't require block to be sorted diff --git a/packages/beacon-node/src/network/reqresp/handlers/lightClientBootstrap.ts b/packages/beacon-node/src/network/reqresp/handlers/lightClientBootstrap.ts index d14e0945e977..3b50304eb50c 100644 --- a/packages/beacon-node/src/network/reqresp/handlers/lightClientBootstrap.ts +++ b/packages/beacon-node/src/network/reqresp/handlers/lightClientBootstrap.ts @@ -24,8 +24,7 @@ export async function* onLightClientBootstrap(requestBody: Root, chain: IBeaconC } catch (e) { if ((e as LightClientServerError).type?.code === LightClientServerErrorCode.RESOURCE_UNAVAILABLE) { throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, (e as Error).message); - } else { - throw new ResponseError(RespStatus.SERVER_ERROR, (e as Error).message); } + throw new ResponseError(RespStatus.SERVER_ERROR, (e as Error).message); } } diff --git a/packages/beacon-node/src/network/reqresp/handlers/lightClientFinalityUpdate.ts b/packages/beacon-node/src/network/reqresp/handlers/lightClientFinalityUpdate.ts index 2468b0b64f4b..4764c6f198f7 100644 --- a/packages/beacon-node/src/network/reqresp/handlers/lightClientFinalityUpdate.ts +++ b/packages/beacon-node/src/network/reqresp/handlers/lightClientFinalityUpdate.ts @@ -9,12 +9,12 @@ export async function* onLightClientFinalityUpdate(chain: IBeaconChain): AsyncIt const update = chain.lightClientServer.getFinalityUpdate(); if (update === null) { throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, "No latest finality update available"); - } else { - const fork = chain.config.getForkName(update.signatureSlot); - const type = responseSszTypeByMethod[ReqRespMethod.LightClientFinalityUpdate](fork, 0); - yield { - data: type.serialize(update), - fork, - }; } + + const fork = chain.config.getForkName(update.signatureSlot); + const type = responseSszTypeByMethod[ReqRespMethod.LightClientFinalityUpdate](fork, 0); + yield { + data: type.serialize(update), + fork, + }; } diff --git a/packages/beacon-node/src/network/reqresp/handlers/lightClientOptimisticUpdate.ts b/packages/beacon-node/src/network/reqresp/handlers/lightClientOptimisticUpdate.ts index ba8371910c02..4c030a8e4174 100644 --- a/packages/beacon-node/src/network/reqresp/handlers/lightClientOptimisticUpdate.ts +++ b/packages/beacon-node/src/network/reqresp/handlers/lightClientOptimisticUpdate.ts @@ -9,12 +9,12 @@ export async function* onLightClientOptimisticUpdate(chain: IBeaconChain): Async const update = chain.lightClientServer.getOptimisticUpdate(); if (update === null) { throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, "No latest optimistic update available"); - } else { - const fork = chain.config.getForkName(update.signatureSlot); - const type = responseSszTypeByMethod[ReqRespMethod.LightClientOptimisticUpdate](fork, 0); - yield { - data: type.serialize(update), - fork, - }; } + + const fork = chain.config.getForkName(update.signatureSlot); + const type = responseSszTypeByMethod[ReqRespMethod.LightClientOptimisticUpdate](fork, 0); + yield { + data: type.serialize(update), + fork, + }; } diff --git a/packages/beacon-node/src/network/reqresp/handlers/lightClientUpdatesByRange.ts b/packages/beacon-node/src/network/reqresp/handlers/lightClientUpdatesByRange.ts index eb0e3c3d3f4e..89466eca6c21 100644 --- a/packages/beacon-node/src/network/reqresp/handlers/lightClientUpdatesByRange.ts +++ b/packages/beacon-node/src/network/reqresp/handlers/lightClientUpdatesByRange.ts @@ -31,9 +31,8 @@ export async function* onLightClientUpdatesByRange( } catch (e) { if ((e as LightClientServerError).type?.code === LightClientServerErrorCode.RESOURCE_UNAVAILABLE) { throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, (e as Error).message); - } else { - throw new ResponseError(RespStatus.SERVER_ERROR, (e as Error).message); } + throw new ResponseError(RespStatus.SERVER_ERROR, (e as Error).message); } } } diff --git a/packages/beacon-node/src/network/reqresp/types.ts b/packages/beacon-node/src/network/reqresp/types.ts index f4a95527ac5f..96ae1558ec07 100644 --- a/packages/beacon-node/src/network/reqresp/types.ts +++ b/packages/beacon-node/src/network/reqresp/types.ts @@ -90,9 +90,9 @@ export type ResponseTypeGetter = (fork: ForkName, version: number) => Type const blocksResponseType: ResponseTypeGetter = (fork, version) => { if (version === Version.V1) { return ssz.phase0.SignedBeaconBlock; - } else { - return ssz[fork].SignedBeaconBlock; } + + return ssz[fork].SignedBeaconBlock; }; export const responseSszTypeByMethod: {[K in ReqRespMethod]: ResponseTypeGetter} = { @@ -114,9 +114,8 @@ export const responseSszTypeByMethod: {[K in ReqRespMethod]: ResponseTypeGetter< function onlyLightclientFork(fork: ForkName): ForkLightClient { if (isForkLightClient(fork)) { return fork; - } else { - throw Error(`Not a lightclient fork ${fork}`); } + throw Error(`Not a lightclient fork ${fork}`); } export type RequestTypedContainer = { diff --git a/packages/beacon-node/src/node/notifier.ts b/packages/beacon-node/src/node/notifier.ts index a676d4137775..20a359a45c49 100644 --- a/packages/beacon-node/src/node/notifier.ts +++ b/packages/beacon-node/src/node/notifier.ts @@ -148,9 +148,8 @@ export async function runNodeNotifier(modules: NodeNotifierModules): Promise msPerHalfSlot ? msToNextSlot - msPerHalfSlot : msToNextSlot + msPerHalfSlot; - } else { - // after the 1st time always wait until middle of next clock slot - return msToNextSlot + msPerHalfSlot; } + // after the 1st time always wait until middle of next clock slot + return msToNextSlot + msPerHalfSlot; } function getHeadExecutionInfo( @@ -181,26 +179,25 @@ function getHeadExecutionInfo( ): string[] { if (clockEpoch < config.BELLATRIX_FORK_EPOCH) { return []; - } else { - const executionStatusStr = headInfo.executionStatus.toLowerCase(); - - // Add execution status to notifier only if head is on/post bellatrix - if (isExecutionCachedStateType(headState)) { - if (isMergeTransitionComplete(headState)) { - const executionPayloadHashInfo = - headInfo.executionStatus !== ExecutionStatus.PreMerge ? headInfo.executionPayloadBlockHash : "empty"; - const executionPayloadNumberInfo = - headInfo.executionStatus !== ExecutionStatus.PreMerge ? headInfo.executionPayloadNumber : NaN; - return [ - `exec-block: ${executionStatusStr}(${executionPayloadNumberInfo} ${prettyBytesShort( - executionPayloadHashInfo - )})`, - ]; - } else { - return [`exec-block: ${executionStatusStr}`]; - } - } else { - return []; + } + + const executionStatusStr = headInfo.executionStatus.toLowerCase(); + + // Add execution status to notifier only if head is on/post bellatrix + if (isExecutionCachedStateType(headState)) { + if (isMergeTransitionComplete(headState)) { + const executionPayloadHashInfo = + headInfo.executionStatus !== ExecutionStatus.PreMerge ? headInfo.executionPayloadBlockHash : "empty"; + const executionPayloadNumberInfo = + headInfo.executionStatus !== ExecutionStatus.PreMerge ? headInfo.executionPayloadNumber : NaN; + return [ + `exec-block: ${executionStatusStr}(${executionPayloadNumberInfo} ${prettyBytesShort( + executionPayloadHashInfo + )})`, + ]; } + return [`exec-block: ${executionStatusStr}`]; } + + return []; } diff --git a/packages/beacon-node/src/sync/range/range.ts b/packages/beacon-node/src/sync/range/range.ts index efdf84cf7af1..51e3a5d0f182 100644 --- a/packages/beacon-node/src/sync/range/range.ts +++ b/packages/beacon-node/src/sync/range/range.ts @@ -150,17 +150,15 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) { if (chain.isSyncing) { if (chain.syncType === RangeSyncType.Finalized) { return {status: RangeSyncStatus.Finalized, target: chain.target}; - } else { - syncingHeadTargets.push(chain.target); } + syncingHeadTargets.push(chain.target); } } if (syncingHeadTargets.length > 0) { return {status: RangeSyncStatus.Head, targets: syncingHeadTargets}; - } else { - return {status: RangeSyncStatus.Idle}; } + return {status: RangeSyncStatus.Idle}; } /** Full debug state for lodestar API */ diff --git a/packages/beacon-node/src/sync/range/utils/batches.ts b/packages/beacon-node/src/sync/range/utils/batches.ts index 734c84800b69..c8490ade6317 100644 --- a/packages/beacon-node/src/sync/range/utils/batches.ts +++ b/packages/beacon-node/src/sync/range/utils/batches.ts @@ -113,7 +113,7 @@ export function isSyncChainDone(batches: Batch[], lastEpochWithProcessBlocks: Ep if (lastAwaitingValidation) { return batchStartEpochIsAfterSlot(lastAwaitingValidation.startEpoch + EPOCHS_PER_BATCH, targetSlot); - } else { - return batchStartEpochIsAfterSlot(lastEpochWithProcessBlocks, targetSlot); } + + return batchStartEpochIsAfterSlot(lastEpochWithProcessBlocks, targetSlot); } diff --git a/packages/beacon-node/src/sync/sync.ts b/packages/beacon-node/src/sync/sync.ts index aa835322b9b4..1e03431adbbb 100644 --- a/packages/beacon-node/src/sync/sync.ts +++ b/packages/beacon-node/src/sync/sync.ts @@ -99,31 +99,31 @@ export class BeaconSync implements IBeaconSync { isOptimistic: false, elOffline, }; - } else { - const head = this.chain.forkChoice.getHead(); - - switch (this.state) { - case SyncState.SyncingFinalized: - case SyncState.SyncingHead: - case SyncState.Stalled: - return { - headSlot: head.slot, - syncDistance: currentSlot - head.slot, - isSyncing: true, - isOptimistic: isOptimisticBlock(head), - elOffline, - }; - case SyncState.Synced: - return { - headSlot: head.slot, - syncDistance: 0, - isSyncing: false, - isOptimistic: isOptimisticBlock(head), - elOffline, - }; - default: - throw new Error("Node is stopped, cannot get sync status"); - } + } + + const head = this.chain.forkChoice.getHead(); + + switch (this.state) { + case SyncState.SyncingFinalized: + case SyncState.SyncingHead: + case SyncState.Stalled: + return { + headSlot: head.slot, + syncDistance: currentSlot - head.slot, + isSyncing: true, + isOptimistic: isOptimisticBlock(head), + elOffline, + }; + case SyncState.Synced: + return { + headSlot: head.slot, + syncDistance: 0, + isSyncing: false, + isOptimistic: isOptimisticBlock(head), + elOffline, + }; + default: + throw new Error("Node is stopped, cannot get sync status"); } } diff --git a/packages/beacon-node/src/sync/unknownBlock.ts b/packages/beacon-node/src/sync/unknownBlock.ts index a172b5d723db..ff0f96dfa4da 100644 --- a/packages/beacon-node/src/sync/unknownBlock.ts +++ b/packages/beacon-node/src/sync/unknownBlock.ts @@ -493,9 +493,8 @@ export class UnknownBlockSync { if (lastError) { lastError.message = `Error fetching UnknownBlockRoot after ${MAX_ATTEMPTS_PER_BLOCK} attempts: ${lastError.message}`; throw lastError; - } else { - throw Error(`Error fetching UnknownBlockRoot after ${MAX_ATTEMPTS_PER_BLOCK}: unknown error`); } + throw Error(`Error fetching UnknownBlockRoot after ${MAX_ATTEMPTS_PER_BLOCK}: unknown error`); } /** @@ -569,9 +568,9 @@ export class UnknownBlockSync { if (lastError) { lastError.message = `Error fetching UnavailableBlockInput after ${MAX_ATTEMPTS_PER_BLOCK} attempts: ${lastError.message}`; throw lastError; - } else { - throw Error(`Error fetching UnavailableBlockInput after ${MAX_ATTEMPTS_PER_BLOCK}: unknown error`); } + + throw Error(`Error fetching UnavailableBlockInput after ${MAX_ATTEMPTS_PER_BLOCK}: unknown error`); } /** diff --git a/packages/beacon-node/src/sync/utils/remoteSyncType.ts b/packages/beacon-node/src/sync/utils/remoteSyncType.ts index ec53e0cd3d8d..247269ab409a 100644 --- a/packages/beacon-node/src/sync/utils/remoteSyncType.ts +++ b/packages/beacon-node/src/sync/utils/remoteSyncType.ts @@ -49,8 +49,7 @@ export function getPeerSyncType( return PeerSyncType.Behind; } - // - else if (remote.finalizedEpoch > local.finalizedEpoch) { + if (remote.finalizedEpoch > local.finalizedEpoch) { if ( // Peer is in next epoch, and head is within range => SYNCED (local.finalizedEpoch + 1 === remote.finalizedEpoch && @@ -59,26 +58,24 @@ export function getPeerSyncType( forkChoice.hasBlock(remote.headRoot) ) { return PeerSyncType.FullySynced; - } else { - return PeerSyncType.Advanced; } + return PeerSyncType.Advanced; } // remote.finalizedEpoch == local.finalizedEpoch - else { - // NOTE: if a peer has our same `finalizedEpoch` with a different `finalized_root` - // they are not considered relevant and won't be propagated to sync. - // Check if the peer is the peer is inside the tolerance range to be considered synced. - if (remote.headSlot < nearRangeStart) { - return PeerSyncType.Behind; - } else if (remote.headSlot > nearRangeEnd && !forkChoice.hasBlock(remote.headRoot)) { - // This peer has a head ahead enough of ours and we have no knowledge of their best block. - return PeerSyncType.Advanced; - } else { - // This peer is either in the tolerance range, or ahead us with an already rejected block. - return PeerSyncType.FullySynced; - } + // NOTE: if a peer has our same `finalizedEpoch` with a different `finalized_root` + // they are not considered relevant and won't be propagated to sync. + // Check if the peer is the peer is inside the tolerance range to be considered synced. + if (remote.headSlot < nearRangeStart) { + return PeerSyncType.Behind; + } + + if (remote.headSlot > nearRangeEnd && !forkChoice.hasBlock(remote.headRoot)) { + // This peer has a head ahead enough of ours and we have no knowledge of their best block. + return PeerSyncType.Advanced; } + // This peer is either in the tolerance range, or ahead us with an already rejected block. + return PeerSyncType.FullySynced; } export enum RangeSyncType { @@ -99,9 +96,8 @@ export const rangeSyncTypes = Object.keys(RangeSyncType) as RangeSyncType[]; export function getRangeSyncType(local: phase0.Status, remote: phase0.Status, forkChoice: IForkChoice): RangeSyncType { if (remote.finalizedEpoch > local.finalizedEpoch && !forkChoice.hasBlock(remote.finalizedRoot)) { return RangeSyncType.Finalized; - } else { - return RangeSyncType.Head; } + return RangeSyncType.Head; } export function getRangeSyncTarget( @@ -134,16 +130,15 @@ export function getRangeSyncTarget( root: remote.finalizedRoot, }, }; - } else { - return { - syncType: RangeSyncType.Head, - // The new peer has the same finalized (earlier filters should prevent a peer with an - // earlier finalized chain from reaching here). - startEpoch: Math.min(computeEpochAtSlot(local.headSlot), remote.finalizedEpoch), - target: { - slot: remote.headSlot, - root: remote.headRoot, - }, - }; } + return { + syncType: RangeSyncType.Head, + // The new peer has the same finalized (earlier filters should prevent a peer with an + // earlier finalized chain from reaching here). + startEpoch: Math.min(computeEpochAtSlot(local.headSlot), remote.finalizedEpoch), + target: { + slot: remote.headSlot, + root: remote.headRoot, + }, + }; } diff --git a/packages/beacon-node/src/util/bitArray.ts b/packages/beacon-node/src/util/bitArray.ts index 364110fe958f..3411886de3ca 100644 --- a/packages/beacon-node/src/util/bitArray.ts +++ b/packages/beacon-node/src/util/bitArray.ts @@ -72,7 +72,7 @@ export function intersectUint8Arrays(aUA: Uint8Array, bUA: Uint8Array): Intersec // subset = MUST subset MAYBE equal if (!someExcludes && !someSuperset && someSubset) return IntersectResult.Subset; // intersect = any other condition - else return IntersectResult.Intersect; + return IntersectResult.Intersect; } /** diff --git a/packages/beacon-node/src/util/kzg.ts b/packages/beacon-node/src/util/kzg.ts index efc6dd34ee1c..5b34065fad90 100644 --- a/packages/beacon-node/src/util/kzg.ts +++ b/packages/beacon-node/src/util/kzg.ts @@ -154,7 +154,6 @@ export function trustedSetupJsonToTxt(data: TrustedSetupJSON): TrustedSetupTXT { function strip0xPrefix(hex: string): string { if (hex.startsWith("0x")) { return hex.slice(2); - } else { - return hex; } + return hex; } diff --git a/packages/beacon-node/test/e2e/chain/lightclient.test.ts b/packages/beacon-node/test/e2e/chain/lightclient.test.ts index 5e7b7f36fff2..4d5f90a6d77c 100644 --- a/packages/beacon-node/test/e2e/chain/lightclient.test.ts +++ b/packages/beacon-node/test/e2e/chain/lightclient.test.ts @@ -152,7 +152,9 @@ describe("chain / lightclient", function () { const lcHeadSlot = lightclient.getHead().beacon.slot; if (head.slot - lcHeadSlot > maxLcHeadTrackingDiffSlots) { throw Error(`Lightclient head ${lcHeadSlot} is too far behind the beacon node ${head.slot}`); - } else if (head.slot > targetSlotToReach) { + } + + if (head.slot > targetSlotToReach) { resolve(); } } catch (e) { diff --git a/packages/beacon-node/test/sim/electra-interop.test.ts b/packages/beacon-node/test/sim/electra-interop.test.ts index 2d08428df558..480d959e52f4 100644 --- a/packages/beacon-node/test/sim/electra-interop.test.ts +++ b/packages/beacon-node/test/sim/electra-interop.test.ts @@ -211,12 +211,12 @@ describe("executionEngine / ExecutionEngineHttp", function () { if (payload.transactions.length !== 1) { throw Error(`Number of transactions mismatched. Expected: 1, actual: ${payload.transactions.length}`); - } else { - const actualTransaction = bytesToData(payload.transactions[0]); + } - if (actualTransaction !== depositTransactionB) { - throw Error(`Transaction mismatched. Expected: ${depositTransactionB}, actual: ${actualTransaction}`); - } + const actualTransaction = bytesToData(payload.transactions[0]); + + if (actualTransaction !== depositTransactionB) { + throw Error(`Transaction mismatched. Expected: ${depositTransactionB}, actual: ${actualTransaction}`); } if (depositRequests === undefined || depositRequests.length !== 1) { diff --git a/packages/beacon-node/test/spec/general/bls.ts b/packages/beacon-node/test/spec/general/bls.ts index fca8529e4e3b..dfebe945b069 100644 --- a/packages/beacon-node/test/spec/general/bls.ts +++ b/packages/beacon-node/test/spec/general/bls.ts @@ -41,9 +41,8 @@ export const blsTestRunner: TestRunnerFn = (_fork, testNam const {message} = e as Error; if (message.includes("BLST_ERROR") || message === "EMPTY_AGGREGATE_ARRAY" || message === "ZERO_SECRET_KEY") { return null; - } else { - throw e; } + throw e; } }, options: { diff --git a/packages/beacon-node/test/spec/utils/runValidSszTest.ts b/packages/beacon-node/test/spec/utils/runValidSszTest.ts index 7ca02cec2d1e..a8d3060af08d 100644 --- a/packages/beacon-node/test/spec/utils/runValidSszTest.ts +++ b/packages/beacon-node/test/spec/utils/runValidSszTest.ts @@ -168,9 +168,8 @@ function wrapErr(fn: () => T, prefix: string): T { export function toJsonOrString(value: unknown): unknown { if (typeof value === "number" || typeof value === "bigint") { return value.toString(10); - } else { - return value; } + return value; } function renderTree(node: Node): void { diff --git a/packages/beacon-node/test/unit/chain/validation/attestation/getShufflingForAttestationVerification.test.ts b/packages/beacon-node/test/unit/chain/validation/attestation/getShufflingForAttestationVerification.test.ts index 9aa7c29c7825..4ba65270e17a 100644 --- a/packages/beacon-node/test/unit/chain/validation/attestation/getShufflingForAttestationVerification.test.ts +++ b/packages/beacon-node/test/unit/chain/validation/attestation/getShufflingForAttestationVerification.test.ts @@ -40,17 +40,15 @@ describe("getShufflingForAttestationVerification", () => { forkchoiceStub.getDependentRoot.mockImplementationOnce((block, epochDiff) => { if (block === attHeadBlock && epochDiff === EpochDifference.previous) { return previousDependentRoot; - } else { - throw new Error("Unexpected input"); } + throw new Error("Unexpected input"); }); const expectedShuffling = {epoch: attEpoch} as EpochShuffling; shufflingCacheStub.get.mockImplementationOnce((epoch, root) => { if (epoch === attEpoch && root === previousDependentRoot) { return Promise.resolve(expectedShuffling); - } else { - return Promise.resolve(null); } + return Promise.resolve(null); }); const resultShuffling = await getShufflingForAttestationVerification( chain, @@ -72,17 +70,15 @@ describe("getShufflingForAttestationVerification", () => { forkchoiceStub.getDependentRoot.mockImplementationOnce((block, epochDiff) => { if (block === attHeadBlock && epochDiff === EpochDifference.current) { return currentDependentRoot; - } else { - throw new Error("Unexpected input"); } + throw new Error("Unexpected input"); }); const expectedShuffling = {epoch: attEpoch} as EpochShuffling; shufflingCacheStub.get.mockImplementationOnce((epoch, root) => { if (epoch === attEpoch && root === currentDependentRoot) { return Promise.resolve(expectedShuffling); - } else { - return Promise.resolve(null); } + return Promise.resolve(null); }); const resultShuffling = await getShufflingForAttestationVerification( chain, @@ -107,12 +103,10 @@ describe("getShufflingForAttestationVerification", () => { if (callCount === 0) { callCount++; return Promise.resolve(null); - } else { - return Promise.resolve(expectedShuffling); } - } else { - return Promise.resolve(null); + return Promise.resolve(expectedShuffling); } + return Promise.resolve(null); }); chain.regenStateForAttestationVerification.mockImplementationOnce(() => Promise.resolve(expectedShuffling)); diff --git a/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts b/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts index 37ad9420ade6..c7f4c8fb7aa4 100644 --- a/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts +++ b/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts @@ -115,9 +115,8 @@ describe("eth1 / Eth1MergeBlockTracker", () => { if (blockNumber === "latest") { if (latestBlockPointer >= blocks.length) { throw Error("Fetched too many blocks"); - } else { - return blocks[latestBlockPointer++]; } + return blocks[latestBlockPointer++]; } return blocks[blockNumber]; }, diff --git a/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts b/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts index 0521823d1283..ca11eab94984 100644 --- a/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts @@ -29,9 +29,8 @@ describe("eth1 / utils / optimizeNextBlockDiffForGenesis", function () { if (lastFetchedBlock.timestamp > params.MIN_GENESIS_TIME - params.GENESIS_DELAY) { break; - } else { - diffRecord.push({number: lastFetchedBlock.blockNumber, blockDiff}); } + diffRecord.push({number: lastFetchedBlock.blockNumber, blockDiff}); } // Make sure the returned diffs converge to genesis time fast diff --git a/packages/beacon-node/test/unit/executionEngine/httpRetry.test.ts b/packages/beacon-node/test/unit/executionEngine/httpRetry.test.ts index b75dc8048283..7c5531d3ace9 100644 --- a/packages/beacon-node/test/unit/executionEngine/httpRetry.test.ts +++ b/packages/beacon-node/test/unit/executionEngine/httpRetry.test.ts @@ -32,10 +32,10 @@ describe("ExecutionEngine / http ", () => { reqJsonRpcPayload = req.body; delete (reqJsonRpcPayload as {id?: number}).id; return returnValue; - } else { - --errorResponsesBeforeSuccess; - throw Error(`Will succeed after ${errorResponsesBeforeSuccess} more attempts`); } + + --errorResponsesBeforeSuccess; + throw Error(`Will succeed after ${errorResponsesBeforeSuccess} more attempts`); }); afterCallbacks.push(async () => { diff --git a/packages/beacon-node/test/unit/network/processorQueues.test.ts b/packages/beacon-node/test/unit/network/processorQueues.test.ts index 378d87ab7861..07a10591c0ad 100644 --- a/packages/beacon-node/test/unit/network/processorQueues.test.ts +++ b/packages/beacon-node/test/unit/network/processorQueues.test.ts @@ -21,10 +21,10 @@ async function validateTest(job: string, tracker: string[], opts: ValidateOpts): async function getStateFromCache(retrieveSync: boolean): Promise { if (retrieveSync) { return 1; - } else { - await sleep(0); - return 2; } + + await sleep(0); + return 2; } describe("event loop with branching async", () => { diff --git a/packages/beacon-node/test/unit/util/dependentRoot.test.ts b/packages/beacon-node/test/unit/util/dependentRoot.test.ts index e7923f111d0b..c8044f332e34 100644 --- a/packages/beacon-node/test/unit/util/dependentRoot.test.ts +++ b/packages/beacon-node/test/unit/util/dependentRoot.test.ts @@ -26,9 +26,8 @@ describe("util / getShufflingDependentRoot", () => { forkchoiceStub.getDependentRoot.mockImplementation((block, epochDiff) => { if (block === headBattHeadBlock && epochDiff === EpochDifference.previous) { return "current"; - } else { - throw new Error("should not be called"); } + throw new Error("should not be called"); }); expect(getShufflingDependentRoot(forkchoiceStub, attEpoch, blockEpoch, headBattHeadBlock)).toEqual("current"); }); @@ -39,9 +38,8 @@ describe("util / getShufflingDependentRoot", () => { forkchoiceStub.getDependentRoot.mockImplementation((block, epochDiff) => { if (block === headBattHeadBlock && epochDiff === EpochDifference.current) { return "0x000"; - } else { - throw new Error("should not be called"); } + throw new Error("should not be called"); }); expect(getShufflingDependentRoot(forkchoiceStub, attEpoch, blockEpoch, headBattHeadBlock)).toEqual("0x000"); }); diff --git a/packages/beacon-node/test/unit/util/wrapError.test.ts b/packages/beacon-node/test/unit/util/wrapError.test.ts index 19bff7321e3c..2a8e5ca15ceb 100644 --- a/packages/beacon-node/test/unit/util/wrapError.test.ts +++ b/packages/beacon-node/test/unit/util/wrapError.test.ts @@ -5,13 +5,15 @@ describe("util / wrapError", () => { const error = Error("test-error"); async function throwNoAwait(shouldThrow: boolean): Promise { if (shouldThrow) throw error; - else return true; + + return true; } async function throwAwait(shouldThrow: boolean): Promise { await new Promise((r) => setTimeout(r, 0)); if (shouldThrow) throw error; - else return true; + + return true; } it("Handle error and result with throwNoAwait", async () => { diff --git a/packages/beacon-node/test/utils/errors.ts b/packages/beacon-node/test/utils/errors.ts index c3d293e83c78..1bf31a2ce9af 100644 --- a/packages/beacon-node/test/utils/errors.ts +++ b/packages/beacon-node/test/utils/errors.ts @@ -53,9 +53,11 @@ export function expectLodestarError(err1: LodestarErro export function getErrorMetadata(err: LodestarError | Error | unknown): unknown { if (err instanceof LodestarError) { return mapValues(err.getMetadata(), (value) => getErrorMetadata(value as any)); - } else if (err instanceof Error) { + } + + if (err instanceof Error) { return err.message; - } else { - return err; } + + return err; } diff --git a/packages/cli/src/cmds/beacon/initBeaconState.ts b/packages/cli/src/cmds/beacon/initBeaconState.ts index 67b578e9fdb9..8dc9e9317c65 100644 --- a/packages/cli/src/cmds/beacon/initBeaconState.ts +++ b/packages/cli/src/cmds/beacon/initBeaconState.ts @@ -162,7 +162,9 @@ export async function initBeaconState( db, logger ); - } else if (args.checkpointSyncUrl) { + } + + if (args.checkpointSyncUrl) { return fetchWSStateFromBeaconApi( lastDbStateWithBytes, lastDbValidatorsBytes, @@ -175,24 +177,24 @@ export async function initBeaconState( db, logger ); - } else { - const genesisStateFile = args.genesisStateFile || getGenesisFileUrl(args.network || defaultNetwork); - if (genesisStateFile && !args.forceGenesis) { - const stateBytes = await downloadOrLoadFile(genesisStateFile); - const anchorState = getStateTypeFromBytes(chainForkConfig, stateBytes).deserializeToViewDU(stateBytes); - const config = createBeaconConfig(chainForkConfig, anchorState.genesisValidatorsRoot); - const wssCheck = isWithinWeakSubjectivityPeriod(config, anchorState, getCheckpointFromState(anchorState)); - await checkAndPersistAnchorState(config, db, logger, anchorState, stateBytes, { - isWithinWeakSubjectivityPeriod: wssCheck, - isCheckpointState: true, - }); - return {anchorState}; - } else { - // Only place we will not bother checking isWithinWeakSubjectivityPeriod as forceGenesis passed by user - const anchorState = await initStateFromEth1({config: chainForkConfig, db, logger, opts: options.eth1, signal}); - return {anchorState}; - } } + + const genesisStateFile = args.genesisStateFile || getGenesisFileUrl(args.network || defaultNetwork); + if (genesisStateFile && !args.forceGenesis) { + const stateBytes = await downloadOrLoadFile(genesisStateFile); + const anchorState = getStateTypeFromBytes(chainForkConfig, stateBytes).deserializeToViewDU(stateBytes); + const config = createBeaconConfig(chainForkConfig, anchorState.genesisValidatorsRoot); + const wssCheck = isWithinWeakSubjectivityPeriod(config, anchorState, getCheckpointFromState(anchorState)); + await checkAndPersistAnchorState(config, db, logger, anchorState, stateBytes, { + isWithinWeakSubjectivityPeriod: wssCheck, + isCheckpointState: true, + }); + return {anchorState}; + } + + // Only place we will not bother checking isWithinWeakSubjectivityPeriod as forceGenesis passed by user + const anchorState = await initStateFromEth1({config: chainForkConfig, db, logger, opts: options.eth1, signal}); + return {anchorState}; } async function readWSState( diff --git a/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts b/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts index 68a4cbed59af..2881b378069a 100644 --- a/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts +++ b/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts @@ -186,9 +186,8 @@ export async function initPrivateKeyAndEnr( writeFile600Perm(peerIdFile, exportToJSON(privateKey)); writeFile600Perm(enrFile, enr.encodeTxt()); return {privateKey, enr}; - } else { - const {privateKey, enr} = await newPrivateKeyAndENR(); - overwriteEnrWithCliArgs(enr, args, logger, {newEnr: true, bootnode}); - return {privateKey, enr}; } + const {privateKey, enr} = await newPrivateKeyAndENR(); + overwriteEnrWithCliArgs(enr, args, logger, {newEnr: true, bootnode}); + return {privateKey, enr}; } diff --git a/packages/cli/src/cmds/validator/keymanager/impl.ts b/packages/cli/src/cmds/validator/keymanager/impl.ts index d965b2af5075..b4233f3162cd 100644 --- a/packages/cli/src/cmds/validator/keymanager/impl.ts +++ b/packages/cli/src/cmds/validator/keymanager/impl.ts @@ -378,7 +378,6 @@ export class KeymanagerApi implements Api { function ensureJSON(strOrJson: string | T): T { if (typeof strOrJson === "string") { return JSON.parse(strOrJson) as T; - } else { - return strOrJson; } + return strOrJson; } diff --git a/packages/cli/src/cmds/validator/keymanager/server.ts b/packages/cli/src/cmds/validator/keymanager/server.ts index c4d3256c6151..e48c708c96a8 100644 --- a/packages/cli/src/cmds/validator/keymanager/server.ts +++ b/packages/cli/src/cmds/validator/keymanager/server.ts @@ -80,6 +80,7 @@ function readFileIfExists(filepath: string): string | null { return fs.readFileSync(filepath, "utf8").trim(); } catch (e) { if ((e as {code: string}).code === "ENOENT") return null; - else throw e; + + throw e; } } diff --git a/packages/cli/src/cmds/validator/signers/importExternalKeystores.ts b/packages/cli/src/cmds/validator/signers/importExternalKeystores.ts index 7b90d16d1d88..f86ea90ab1a8 100644 --- a/packages/cli/src/cmds/validator/signers/importExternalKeystores.ts +++ b/packages/cli/src/cmds/validator/signers/importExternalKeystores.ts @@ -28,17 +28,17 @@ export function importKeystoreDefinitionsFromExternalDir(args: { export async function readPassphraseOrPrompt(args: {importKeystoresPassword?: string}): Promise { if (args.importKeystoresPassword) { return readPassphraseFile(args.importKeystoresPassword); - } else { - const answers = await inquirer.prompt<{password: string}>([ - { - name: "password", - type: "password", - message: "Enter the keystore(s) password", - }, - ]); - - return answers.password; } + + const answers = await inquirer.prompt<{password: string}>([ + { + name: "password", + type: "password", + message: "Enter the keystore(s) password", + }, + ]); + + return answers.password; } /** diff --git a/packages/cli/src/cmds/validator/signers/index.ts b/packages/cli/src/cmds/validator/signers/index.ts index c155b52d186a..6a343d12e6b8 100644 --- a/packages/cli/src/cmds/validator/signers/index.ts +++ b/packages/cli/src/cmds/validator/signers/index.ts @@ -53,13 +53,12 @@ export async function getSignersFromArgs( // Using a remote signer with TESTNETS if (args["externalSigner.pubkeys"] || args["externalSigner.fetch"]) { return getRemoteSigners(args); - } else { - return indexes.map((index) => ({type: SignerType.Local, secretKey: interopSecretKey(index)})); } + return indexes.map((index) => ({type: SignerType.Local, secretKey: interopSecretKey(index)})); } // UNSAFE, ONLY USE FOR TESTNETS - Derive keys directly from a mnemonic - else if (args.fromMnemonic) { + if (args.fromMnemonic) { if (network === defaultNetwork) { throw new YargsError("fromMnemonic must only be used in testnets"); } @@ -76,7 +75,7 @@ export async function getSignersFromArgs( } // Import JSON keystores and run - else if (args.importKeystores) { + if (args.importKeystores) { const keystoreDefinitions = importKeystoreDefinitionsFromExternalDir({ keystoresPath: args.importKeystores, password: await readPassphraseOrPrompt(args), @@ -105,45 +104,43 @@ export async function getSignersFromArgs( } // Remote keys are declared manually or will be fetched from external signer - else if (args["externalSigner.pubkeys"] || args["externalSigner.fetch"]) { + if (args["externalSigner.pubkeys"] || args["externalSigner.fetch"]) { return getRemoteSigners(args); } // Read keys from local account manager - else { - const persistedKeysBackend = new PersistedKeysBackend(accountPaths); - - // Read and decrypt local keystores, imported via keymanager api or import cmd - const keystoreDefinitions = persistedKeysBackend.readAllKeystores(); - - const needle = showProgress({ - total: keystoreDefinitions.length, - frequencyMs: KEYSTORE_IMPORT_PROGRESS_MS, - signal, - progress: ({ratePerSec, percentage, current, total}) => { - logger.info( - `${percentage.toFixed(0)}% of local keystores imported. current=${current} total=${total} rate=${( - ratePerSec * 60 - ).toFixed(2)}keys/m` - ); - }, - }); - - const keystoreSigners = await decryptKeystoreDefinitions(keystoreDefinitions, { - ignoreLockFile: args.force, - onDecrypt: needle, - cacheFilePath: path.join(accountPaths.cacheDir, "local_keystores.cache"), - disableThreadPool: args["disableKeystoresThreadPool"], - logger, - signal, - }); - - // Read local remote keys, imported via keymanager api - const signerDefinitions = persistedKeysBackend.readAllRemoteKeys(); - const remoteSigners = signerDefinitions.map(({url, pubkey}): Signer => ({type: SignerType.Remote, url, pubkey})); - - return [...keystoreSigners, ...remoteSigners]; - } + const persistedKeysBackend = new PersistedKeysBackend(accountPaths); + + // Read and decrypt local keystores, imported via keymanager api or import cmd + const keystoreDefinitions = persistedKeysBackend.readAllKeystores(); + + const needle = showProgress({ + total: keystoreDefinitions.length, + frequencyMs: KEYSTORE_IMPORT_PROGRESS_MS, + signal, + progress: ({ratePerSec, percentage, current, total}) => { + logger.info( + `${percentage.toFixed(0)}% of local keystores imported. current=${current} total=${total} rate=${( + ratePerSec * 60 + ).toFixed(2)}keys/m` + ); + }, + }); + + const keystoreSigners = await decryptKeystoreDefinitions(keystoreDefinitions, { + ignoreLockFile: args.force, + onDecrypt: needle, + cacheFilePath: path.join(accountPaths.cacheDir, "local_keystores.cache"), + disableThreadPool: args["disableKeystoresThreadPool"], + logger, + signal, + }); + + // Read local remote keys, imported via keymanager api + const signerDefinitions = persistedKeysBackend.readAllRemoteKeys(); + const remoteSigners = signerDefinitions.map(({url, pubkey}): Signer => ({type: SignerType.Remote, url, pubkey})); + + return [...keystoreSigners, ...remoteSigners]; } export function getSignerPubkeyHex(signer: Signer): string { diff --git a/packages/cli/src/cmds/validator/voluntaryExit.ts b/packages/cli/src/cmds/validator/voluntaryExit.ts index b922b49852ee..6594ddd54daa 100644 --- a/packages/cli/src/cmds/validator/voluntaryExit.ts +++ b/packages/cli/src/cmds/validator/voluntaryExit.ts @@ -191,15 +191,13 @@ function selectSignersToExit(args: VoluntaryExitArgs, signers: Signer[]): Signer const signer = signersByPubkey.get(pubkey); if (!signer) { throw new YargsError(`Unknown pubkey ${pubkey}`); - } else { - selectedSigners.push({pubkey, signer}); } + selectedSigners.push({pubkey, signer}); } return selectedSigners; - } else { - return signersWithPubkey; } + return signersWithPubkey; } async function resolveValidatorIndexes(client: ApiClient, signersToExit: SignerPubkey[]) { diff --git a/packages/cli/src/util/file.ts b/packages/cli/src/util/file.ts index 5415cf2affa6..a18768d456b9 100644 --- a/packages/cli/src/util/file.ts +++ b/packages/cli/src/util/file.ts @@ -104,9 +104,8 @@ export function readFileIfExists(filepath: string, acceptedFormats?: string[] } catch (e) { if ((e as {code: string}).code === "ENOENT") { return null; - } else { - throw e; } + throw e; } } @@ -141,9 +140,8 @@ export async function downloadOrLoadFile(pathOrUrl: string): Promise if (isUrl(pathOrUrl)) { const res = await got.get(pathOrUrl, {encoding: "binary"}); return res.rawBody; - } else { - return fs.promises.readFile(pathOrUrl); } + return fs.promises.readFile(pathOrUrl); } /** diff --git a/packages/cli/src/util/fs.ts b/packages/cli/src/util/fs.ts index 37464c877b85..17501bea78c9 100644 --- a/packages/cli/src/util/fs.ts +++ b/packages/cli/src/util/fs.ts @@ -21,7 +21,8 @@ export function unlinkSyncMaybe(filepath: string): boolean { } catch (e) { const {code} = e as ErrorFs; if (code === "ENOENT") return false; - else throw e; + + throw e; } } @@ -37,7 +38,8 @@ export function rmdirSyncMaybe(dirpath: string): boolean { // about error codes https://nodejs.org/api/fs.html#fspromisesrmdirpath-options // ENOENT error on Windows and an ENOTDIR if (code === "ENOENT" || code === "ENOTDIR") return false; - else throw e; + + throw e; } } diff --git a/packages/cli/test/e2e/voluntaryExit.test.ts b/packages/cli/test/e2e/voluntaryExit.test.ts index 25d4ab345aa7..0dabdf835c5c 100644 --- a/packages/cli/test/e2e/voluntaryExit.test.ts +++ b/packages/cli/test/e2e/voluntaryExit.test.ts @@ -78,9 +78,8 @@ describe("voluntaryExit cmd", function () { const validator = (await client.beacon.getStateValidator({stateId: "head", validatorId: pubkey})).value(); if (validator.status !== "active_exiting") { throw Error("Validator not exiting"); - } else { - console.log(`Confirmed validator ${pubkey} = ${validator.status}`); } + console.log(`Confirmed validator ${pubkey} = ${validator.status}`); }, {retryDelay: 1000, retries: 20} ); diff --git a/packages/cli/test/e2e/voluntaryExitFromApi.test.ts b/packages/cli/test/e2e/voluntaryExitFromApi.test.ts index 21a9c0fc6872..eacc899ddbdc 100644 --- a/packages/cli/test/e2e/voluntaryExitFromApi.test.ts +++ b/packages/cli/test/e2e/voluntaryExitFromApi.test.ts @@ -85,9 +85,8 @@ describe("voluntary exit from api", function () { const validator = (await beaconClient.getStateValidator({stateId: "head", validatorId: pubkeyToExit})).value(); if (validator.status !== "active_exiting") { throw Error("Validator not exiting"); - } else { - console.log(`Confirmed validator ${pubkeyToExit} = ${validator.status}`); } + console.log(`Confirmed validator ${pubkeyToExit} = ${validator.status}`); }, {retryDelay: 1000, retries: 20} ); diff --git a/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts b/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts index 8cb5f0d44d95..6b154880d6d6 100644 --- a/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts +++ b/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts @@ -100,9 +100,8 @@ describe("voluntaryExit using remote signer", function () { const validator = (await client.beacon.getStateValidator({stateId: "head", validatorId: pubkey})).value(); if (validator.status !== "active_exiting") { throw Error("Validator not exiting"); - } else { - console.log(`Confirmed validator ${pubkey} = ${validator.status}`); } + console.log(`Confirmed validator ${pubkey} = ${validator.status}`); }, {retryDelay: 1000, retries: 20} ); diff --git a/packages/cli/test/utils/crucible/tableReporter.ts b/packages/cli/test/utils/crucible/tableReporter.ts index d11fc9ca3fbc..829f91304c9e 100644 --- a/packages/cli/test/utils/crucible/tableReporter.ts +++ b/packages/cli/test/utils/crucible/tableReporter.ts @@ -33,9 +33,8 @@ export class TableReporter extends SimulationReporter // Print slots once, may be called twice for missed block timer if (slot <= this.lastPrintedSlot) { return; - } else { - this.lastPrintedSlot = slot; } + this.lastPrintedSlot = slot; if (slot <= 0) { return; diff --git a/packages/cli/test/utils/crucible/utils/network.ts b/packages/cli/test/utils/crucible/utils/network.ts index 7f41b87aff04..a9a70b5561b4 100644 --- a/packages/cli/test/utils/crucible/utils/network.ts +++ b/packages/cli/test/utils/crucible/utils/network.ts @@ -78,9 +78,8 @@ export async function waitForNodeSyncStatus(env: Simulation, node: NodePair): Pr const result = (await node.beacon.api.node.getSyncingStatus()).value(); if (!result.isSyncing) { break; - } else { - await sleep(1000, env.options.controller.signal); } + await sleep(1000, env.options.controller.signal); } } diff --git a/packages/cli/test/utils/crucible/utils/syncing.ts b/packages/cli/test/utils/crucible/utils/syncing.ts index d31575e74e5d..b720c6bf6ccc 100644 --- a/packages/cli/test/utils/crucible/utils/syncing.ts +++ b/packages/cli/test/utils/crucible/utils/syncing.ts @@ -184,8 +184,7 @@ export async function waitForNodeSyncStatus(env: Simulation, node: NodePair): Pr const result = (await node.beacon.api.node.getSyncingStatus()).value(); if (!result.isSyncing) { break; - } else { - await sleep(1000, env.options.controller.signal); } + await sleep(1000, env.options.controller.signal); } } diff --git a/packages/db/src/controller/level.ts b/packages/db/src/controller/level.ts index 084b577b6a01..82fbf631f7ae 100644 --- a/packages/db/src/controller/level.ts +++ b/packages/db/src/controller/level.ts @@ -78,11 +78,11 @@ export class LevelDbController implements DatabaseController= ${config.TERMINAL_TOTAL_DIFFICULTY}, actual = ${powBlock.totalDifficulty}` ); - } else if (!isParentTotalDifficultyValid) { + } + + if (!isParentTotalDifficultyValid) { throw Error( `Invalid terminal POW block parent: expected < ${config.TERMINAL_TOTAL_DIFFICULTY}, actual = ${powBlockParent.totalDifficulty}` ); diff --git a/packages/fork-choice/src/protoArray/protoArray.ts b/packages/fork-choice/src/protoArray/protoArray.ts index b8bb63837e36..82a8b2620880 100644 --- a/packages/fork-choice/src/protoArray/protoArray.ts +++ b/packages/fork-choice/src/protoArray/protoArray.ts @@ -304,9 +304,9 @@ export class ProtoArray { * EL is lazy (or buggy) with its LVH response. */ throw Error(`Unable to find latestValidExecHash=${latestValidExecHash} in the forkchoice`); - } else { - this.propagateInValidExecutionStatusByIndex(invalidateFromParentIndex, latestValidHashIndex, currentSlot); } + + this.propagateInValidExecutionStatusByIndex(invalidateFromParentIndex, latestValidHashIndex, currentSlot); } } @@ -431,7 +431,9 @@ export class ProtoArray { code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE, ...this.lvhError, }); - } else if (validNode.executionStatus === ExecutionStatus.Syncing) { + } + + if (validNode.executionStatus === ExecutionStatus.Syncing) { validNode.executionStatus = ExecutionStatus.Valid; } return validNode; @@ -808,10 +810,9 @@ export class ProtoArray { descendantRoot: blockRoot, ancestorSlot, }); - } else { - // Root is older or equal than queried slot, thus a skip slot. Return most recent root prior to slot. - return blockRoot; } + // Root is older or equal than queried slot, thus a skip slot. Return most recent root prior to slot. + return blockRoot; } /** diff --git a/packages/light-client/src/utils/clock.ts b/packages/light-client/src/utils/clock.ts index 44b74b1b601b..efe210b620d8 100644 --- a/packages/light-client/src/utils/clock.ts +++ b/packages/light-client/src/utils/clock.ts @@ -39,7 +39,7 @@ export function timeUntilNextEpoch(config: Pick const msFromGenesis = Date.now() - genesisTime * 1000; if (msFromGenesis >= 0) { return milliSecondsPerEpoch - (msFromGenesis % milliSecondsPerEpoch); - } else { - return Math.abs(msFromGenesis % milliSecondsPerEpoch); } + + return Math.abs(msFromGenesis % milliSecondsPerEpoch); } diff --git a/packages/logger/src/utils/json.ts b/packages/logger/src/utils/json.ts index f1919a38da8b..bab060cc8187 100644 --- a/packages/logger/src/utils/json.ts +++ b/packages/logger/src/utils/json.ts @@ -44,10 +44,9 @@ export function logCtxToJson(arg: unknown, depth = 0, fromError = false): LogDat if (arg instanceof LodestarError) { if (fromError) { return "[LodestarErrorCircular]"; - } else { - // Allow one extra depth level for LodestarError - metadata = logCtxToJson(arg.getMetadata(), depth - 1, true) as Record; } + // Allow one extra depth level for LodestarError + metadata = logCtxToJson(arg.getMetadata(), depth - 1, true) as Record; } else { metadata = {message: arg.message}; } @@ -105,10 +104,9 @@ export function logCtxToString(arg: unknown, depth = 0, fromError = false): stri if (arg instanceof LodestarError) { if (fromError) { return "[LodestarErrorCircular]"; - } else { - // Allow one extra depth level for LodestarError - metadata = logCtxToString(arg.getMetadata(), depth - 1, true); } + // Allow one extra depth level for LodestarError + metadata = logCtxToString(arg.getMetadata(), depth - 1, true); } else { metadata = arg.message; } diff --git a/packages/prover/src/utils/process.ts b/packages/prover/src/utils/process.ts index 80748544302c..75bb79516609 100644 --- a/packages/prover/src/utils/process.ts +++ b/packages/prover/src/utils/process.ts @@ -106,7 +106,6 @@ export async function processAndVerifyRequest({ if (responses.length === 1) { return responses[0]; - } else { - return responses; } + return responses; } diff --git a/packages/reqresp/src/encodingStrategies/sszSnappy/snappyFrames/uncompress.ts b/packages/reqresp/src/encodingStrategies/sszSnappy/snappyFrames/uncompress.ts index 69d9ea44d834..8530bc7aeb88 100644 --- a/packages/reqresp/src/encodingStrategies/sszSnappy/snappyFrames/uncompress.ts +++ b/packages/reqresp/src/encodingStrategies/sszSnappy/snappyFrames/uncompress.ts @@ -51,9 +51,8 @@ export class SnappyFramesUncompress { } if (result.length === 0) { return null; - } else { - return result; } + return result; } reset(): void { diff --git a/packages/reqresp/src/rate_limiter/ReqRespRateLimiter.ts b/packages/reqresp/src/rate_limiter/ReqRespRateLimiter.ts index 66dfbd9f1cc7..7bb87cbd1fb2 100644 --- a/packages/reqresp/src/rate_limiter/ReqRespRateLimiter.ts +++ b/packages/reqresp/src/rate_limiter/ReqRespRateLimiter.ts @@ -68,9 +68,9 @@ export class ReqRespRateLimiter { if ((byPeer && !byPeer.allows(peerIdStr, requestCount)) || (total && !total.allows(null, requestCount))) { this.opts?.onRateLimit?.(peerId, protocolID); return false; - } else { - return true; } + + return true; } prune(peerId: PeerId): void { diff --git a/packages/reqresp/src/request/index.ts b/packages/reqresp/src/request/index.ts index b79df24e2adf..9a374db3b8be 100644 --- a/packages/reqresp/src/request/index.ts +++ b/packages/reqresp/src/request/index.ts @@ -106,9 +106,8 @@ export async function* sendRequest( ).catch((e: Error) => { if (e instanceof TimeoutError) { throw new RequestError({code: RequestErrorCode.DIAL_TIMEOUT}); - } else { - throw new RequestError({code: RequestErrorCode.DIAL_ERROR, error: e}); } + throw new RequestError({code: RequestErrorCode.DIAL_ERROR, error: e}); }); // TODO: Does the TTFB timer start on opening stream or after receiving request @@ -133,9 +132,8 @@ export async function* sendRequest( if (e instanceof TimeoutError) { throw new RequestError({code: RequestErrorCode.REQUEST_TIMEOUT}); - } else { - throw new RequestError({code: RequestErrorCode.REQUEST_ERROR, error: e as Error}); } + throw new RequestError({code: RequestErrorCode.REQUEST_ERROR, error: e as Error}); } ); @@ -209,8 +207,7 @@ export async function* sendRequest( if (e instanceof ResponseError) { throw new RequestError(responseStatusErrorToRequestError(e)); - } else { - throw e; } + throw e; } } diff --git a/packages/reqresp/src/response/index.ts b/packages/reqresp/src/response/index.ts index ad13ba8b9359..d9f0e1b1806a 100644 --- a/packages/reqresp/src/response/index.ts +++ b/packages/reqresp/src/response/index.ts @@ -77,9 +77,8 @@ export async function handleRequest({ ).catch((e: unknown) => { if (e instanceof TimeoutError) { throw e; // Let outter catch (_e) {} re-type the error as SERVER_ERROR - } else { - throw new ResponseError(RespStatus.INVALID_REQUEST, (e as Error).message); } + throw new ResponseError(RespStatus.INVALID_REQUEST, (e as Error).message); }); logger.debug("Req received", logCtx); @@ -134,8 +133,7 @@ export async function handleRequest({ if (responseError !== null) { logger.verbose("Resp error", logCtx, responseError); throw responseError; - } else { - // NOTE: Only log once per request to verbose, intermediate steps to debug - logger.verbose("Resp done", logCtx); } + // NOTE: Only log once per request to verbose, intermediate steps to debug + logger.verbose("Resp done", logCtx); } diff --git a/packages/reqresp/src/utils/abortableSource.ts b/packages/reqresp/src/utils/abortableSource.ts index 17ea836bcac3..127339bbd597 100644 --- a/packages/reqresp/src/utils/abortableSource.ts +++ b/packages/reqresp/src/utils/abortableSource.ts @@ -53,9 +53,9 @@ export function abortableSource( if (result.done) { return; - } else { - yield result.value; } + + yield result.value; } } catch (err) { // End the iterator if it is a generator diff --git a/packages/reqresp/src/utils/bufferedSource.ts b/packages/reqresp/src/utils/bufferedSource.ts index 569cc217ea23..e5daca1d2f67 100644 --- a/packages/reqresp/src/utils/bufferedSource.ts +++ b/packages/reqresp/src/utils/bufferedSource.ts @@ -35,11 +35,11 @@ export class BufferedSource { if (done === true) { that.isDone = true; return {done: true, value: undefined}; - } else { - // Concat new chunk and return a reference to its BufferList instance - that.buffer.append(chunk); - return {done: false, value: that.buffer}; } + + // Concat new chunk and return a reference to its BufferList instance + that.buffer.append(chunk); + return {done: false, value: that.buffer}; }, }; } diff --git a/packages/reqresp/test/utils/errors.ts b/packages/reqresp/test/utils/errors.ts index 16c098f2f57c..e4697a6d97d5 100644 --- a/packages/reqresp/test/utils/errors.ts +++ b/packages/reqresp/test/utils/errors.ts @@ -53,9 +53,10 @@ export function expectLodestarError(err1: LodestarErro export function getErrorMetadata(err: LodestarError | Error | unknown): unknown { if (err instanceof LodestarError) { return mapValues(err.getMetadata(), (value) => getErrorMetadata(value as any)); - } else if (err instanceof Error) { + } + + if (err instanceof Error) { return err.message; - } else { - return err; } + return err; } diff --git a/packages/spec-test-util/src/downloadTests.ts b/packages/spec-test-util/src/downloadTests.ts index e13478934927..bca6a8ac52c9 100644 --- a/packages/spec-test-util/src/downloadTests.ts +++ b/packages/spec-test-util/src/downloadTests.ts @@ -51,9 +51,8 @@ export async function downloadGenericSpecTests( if (existingVersion === specVersion) { return log(`version ${specVersion} already downloaded`); - } else { - log(`Downloading new version ${specVersion}`); } + log(`Downloading new version ${specVersion}`); if (fs.existsSync(outputDir)) { log(`Cleaning existing version ${existingVersion} at ${outputDir}`); diff --git a/packages/spec-test-util/src/single.ts b/packages/spec-test-util/src/single.ts index d4fe72b63bc8..888c87e3ffa8 100644 --- a/packages/spec-test-util/src/single.ts +++ b/packages/spec-test-util/src/single.ts @@ -195,9 +195,13 @@ function loadInputFiles( function getInputType(filename: string): InputType { if (filename.endsWith(InputType.YAML)) { return InputType.YAML; - } else if (filename.endsWith(InputType.SSZ_SNAPPY)) { + } + + if (filename.endsWith(InputType.SSZ_SNAPPY)) { return InputType.SSZ_SNAPPY; - } else if (filename.endsWith(InputType.SSZ)) { + } + + if (filename.endsWith(InputType.SSZ)) { return InputType.SSZ; } throw new Error(`Could not get InputType from ${filename}`); @@ -212,7 +216,9 @@ function deserializeInputFile( ): any { if (inputType === InputType.YAML) { return loadYaml(fs.readFileSync(file, "utf8")); - } else if (inputType === InputType.SSZ || inputType === InputType.SSZ_SNAPPY) { + } + + if (inputType === InputType.SSZ || inputType === InputType.SSZ_SNAPPY) { const sszTypes = options.getSszTypes ? options.getSszTypes(meta) : options.sszTypes; if (!sszTypes) throw Error("sszTypes is not defined"); let data = fs.readFileSync(file); @@ -240,9 +246,8 @@ function deserializeInputFile( throw Error("BeaconState type has no deserializeToViewDU method"); } return sszType.deserializeToViewDU(data); - } else { - return sszType.deserialize(data); } + return sszType.deserialize(data); } } diff --git a/packages/state-transition/src/block/isValidIndexedAttestation.ts b/packages/state-transition/src/block/isValidIndexedAttestation.ts index 33d92a208260..8c7502ceedb5 100644 --- a/packages/state-transition/src/block/isValidIndexedAttestation.ts +++ b/packages/state-transition/src/block/isValidIndexedAttestation.ts @@ -18,9 +18,8 @@ export function isValidIndexedAttestation( if (verifySignature) { return verifySignatureSet(getIndexedAttestationSignatureSet(state, indexedAttestation)); - } else { - return true; } + return true; } export function isValidIndexedAttestationBigint( @@ -34,9 +33,8 @@ export function isValidIndexedAttestationBigint( if (verifySignature) { return verifySignatureSet(getIndexedAttestationBigintSignatureSet(state, indexedAttestation)); - } else { - return true; } + return true; } /** diff --git a/packages/state-transition/src/block/processAttestationPhase0.ts b/packages/state-transition/src/block/processAttestationPhase0.ts index ba6bc9089693..e2b32bbbbee8 100644 --- a/packages/state-transition/src/block/processAttestationPhase0.ts +++ b/packages/state-transition/src/block/processAttestationPhase0.ts @@ -91,13 +91,13 @@ export function validateAttestation(fork: ForkSeq, state: CachedBeaconStateAllFo if (committeeIndices.length === 0) { throw Error("Attestation should have at least one committee bit set"); - } else { - const lastCommitteeIndex = committeeIndices[committeeIndices.length - 1]; - if (lastCommitteeIndex >= committeeCount) { - throw new Error( - `Attestation committee index exceeds committee count: lastCommitteeIndex=${lastCommitteeIndex} numCommittees=${committeeCount}` - ); - } + } + + const lastCommitteeIndex = committeeIndices[committeeIndices.length - 1]; + if (lastCommitteeIndex >= committeeCount) { + throw new Error( + `Attestation committee index exceeds committee count: lastCommitteeIndex=${lastCommitteeIndex} numCommittees=${committeeCount}` + ); } // Get total number of attestation participant of every committee specified @@ -133,9 +133,8 @@ export function isTimelyTarget(fork: ForkSeq, inclusionDistance: Slot): boolean // post deneb attestation is valid till end of next epoch for target if (fork >= ForkSeq.deneb) { return true; - } else { - return inclusionDistance <= SLOTS_PER_EPOCH; } + return inclusionDistance <= SLOTS_PER_EPOCH; } export function checkpointToStr(checkpoint: phase0.Checkpoint): string { diff --git a/packages/state-transition/src/block/processEth1Data.ts b/packages/state-transition/src/block/processEth1Data.ts index 3d1927744328..92ab147aa772 100644 --- a/packages/state-transition/src/block/processEth1Data.ts +++ b/packages/state-transition/src/block/processEth1Data.ts @@ -58,9 +58,8 @@ export function becomesNewEth1Data( // The +1 is to account for the `eth1Data` supplied to the function. if ((sameVotesCount + 1) * 2 > SLOTS_PER_ETH1_VOTING_PERIOD) { return true; - } else { - return false; } + return false; } function isEqualEth1DataView( diff --git a/packages/state-transition/src/block/processSyncCommittee.ts b/packages/state-transition/src/block/processSyncCommittee.ts index 70c918ed60bf..5f81a984b677 100644 --- a/packages/state-transition/src/block/processSyncCommittee.ts +++ b/packages/state-transition/src/block/processSyncCommittee.ts @@ -96,9 +96,8 @@ export function getSyncCommitteeSignatureSet( // https://github.com/ethereum/eth2.0-specs/blob/30f2a076377264677e27324a8c3c78c590ae5e20/specs/altair/bls.md#eth2_fast_aggregate_verify if (byteArrayEquals(signature, G2_POINT_AT_INFINITY)) { return null; - } else { - throw Error("Empty sync committee signature is not infinity"); } + throw Error("Empty sync committee signature is not infinity"); } const domain = state.config.getDomain(state.slot, DOMAIN_SYNC_COMMITTEE, previousSlot); diff --git a/packages/state-transition/src/cache/epochCache.ts b/packages/state-transition/src/cache/epochCache.ts index 4eb16fa49927..aa16f019f9bf 100644 --- a/packages/state-transition/src/cache/epochCache.ts +++ b/packages/state-transition/src/cache/epochCache.ts @@ -957,20 +957,19 @@ export class EpochCache { const validatorIndices = this.getBeaconCommittee(data.slot, data.index); return aggregationBits.intersectValues(validatorIndices); - } else { - const {aggregationBits, committeeBits, data} = attestation as electra.Attestation; + } + const {aggregationBits, committeeBits, data} = attestation as electra.Attestation; - // There is a naming conflict on the term `committeeIndices` - // In Lodestar it usually means a list of validator indices of participants in a committee - // In the spec it means a list of committee indices according to committeeBits - // This `committeeIndices` refers to the latter - // TODO Electra: resolve the naming conflicts - const committeeIndices = committeeBits.getTrueBitIndexes(); + // There is a naming conflict on the term `committeeIndices` + // In Lodestar it usually means a list of validator indices of participants in a committee + // In the spec it means a list of committee indices according to committeeBits + // This `committeeIndices` refers to the latter + // TODO Electra: resolve the naming conflicts + const committeeIndices = committeeBits.getTrueBitIndexes(); - const validatorIndices = this.getBeaconCommittees(data.slot, committeeIndices); + const validatorIndices = this.getBeaconCommittees(data.slot, committeeIndices); - return aggregationBits.intersectValues(validatorIndices); - } + return aggregationBits.intersectValues(validatorIndices); } getCommitteeAssignments( @@ -1030,9 +1029,8 @@ export class EpochCache { getValidatorIndex(pubkey: Uint8Array): ValidatorIndex | null { if (this.isPostElectra()) { return this.pubkey2index.get(pubkey) ?? this.unfinalizedPubkey2index.get(toMemoryEfficientHexStr(pubkey)) ?? null; - } else { - return this.pubkey2index.get(pubkey); } + return this.pubkey2index.get(pubkey); } /** @@ -1072,12 +1070,11 @@ export class EpochCache { // Repeated insert. metrics?.finalizedPubkeyDuplicateInsert.inc(); return; - } else { - // attempt to insert the same pubkey with different index, should never happen. - throw Error( - `inserted existing pubkey into finalizedPubkey2index cache with a different index, index=${index} priorIndex=${existingIndex}` - ); } + // attempt to insert the same pubkey with different index, should never happen. + throw Error( + `inserted existing pubkey into finalizedPubkey2index cache with a different index, index=${index} priorIndex=${existingIndex}` + ); } this.pubkey2index.set(pubkey, index); diff --git a/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts b/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts index bef3ec0b2724..1cd9e17efbad 100644 --- a/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts +++ b/packages/state-transition/src/epoch/processPendingBalanceDeposits.ts @@ -41,14 +41,13 @@ export function processPendingBalanceDeposits(state: CachedBeaconStateElectra, c if (processedAmount + amount > availableForProcessing) { // Deposit does not fit in the churn, no more deposit processing in this epoch. break; - } else { - // Deposit fits in the churn, process it. Increase balance and consume churn. - increaseBalance(state, depositIndex, Number(amount)); - if (cachedBalances) { - cachedBalances[depositIndex] += Number(amount); - } - processedAmount = processedAmount + amount; } + // Deposit fits in the churn, process it. Increase balance and consume churn. + increaseBalance(state, depositIndex, Number(amount)); + if (cachedBalances) { + cachedBalances[depositIndex] += Number(amount); + } + processedAmount = processedAmount + amount; } // Regardless of how the deposit was handled, we move on in the queue. nextDepositIndex++; diff --git a/packages/state-transition/src/util/blindedBlock.ts b/packages/state-transition/src/util/blindedBlock.ts index ceda91c94bb1..1793ff37255e 100644 --- a/packages/state-transition/src/util/blindedBlock.ts +++ b/packages/state-transition/src/util/blindedBlock.ts @@ -102,12 +102,11 @@ export function parseExecutionPayloadAndBlobsBundle(data: ExecutionPayload | Exe } { if (isExecutionPayloadAndBlobsBundle(data)) { return data; - } else { - return { - executionPayload: data, - blobsBundle: null, - }; } + return { + executionPayload: data, + blobsBundle: null, + }; } export function reconstructFullBlockOrContents( @@ -128,7 +127,6 @@ export function reconstructFullBlockOrContents( } return {signedBlock, ...contents} as SignedBeaconBlockOrContents; - } else { - return signedBlock as SignedBeaconBlockOrContents; } + return signedBlock as SignedBeaconBlockOrContents; } diff --git a/packages/state-transition/src/util/deposit.ts b/packages/state-transition/src/util/deposit.ts index e8ef93c515d2..4370a13c783c 100644 --- a/packages/state-transition/src/util/deposit.ts +++ b/packages/state-transition/src/util/deposit.ts @@ -15,10 +15,8 @@ export function getEth1DepositCount(state: CachedBeaconStateAllForks, eth1Data?: if (state.eth1DepositIndex < eth1DataIndexLimit) { return Math.min(MAX_DEPOSITS, eth1DataIndexLimit - state.eth1DepositIndex); - } else { - return 0; } - } else { - return Math.min(MAX_DEPOSITS, eth1DataToUse.depositCount - state.eth1DepositIndex); + return 0; } + return Math.min(MAX_DEPOSITS, eth1DataToUse.depositCount - state.eth1DepositIndex); } diff --git a/packages/state-transition/src/util/execution.ts b/packages/state-transition/src/util/execution.ts index b9243ebe7874..deed64bd6c51 100644 --- a/packages/state-transition/src/util/execution.ts +++ b/packages/state-transition/src/util/execution.ts @@ -71,13 +71,13 @@ export function isMergeTransitionComplete(state: BeaconStateExecutions): boolean // TODO: Performance ssz.bellatrix.ExecutionPayloadHeader.defaultValue() ); - } else { - return !ssz.capella.ExecutionPayloadHeader.equals( - state.latestExecutionPayloadHeader, - // TODO: Performance - ssz.capella.ExecutionPayloadHeader.defaultValue() - ); } + + return !ssz.capella.ExecutionPayloadHeader.equals( + state.latestExecutionPayloadHeader, + // TODO: Performance + ssz.capella.ExecutionPayloadHeader.defaultValue() + ); } /** Type guard for bellatrix.BeaconState */ @@ -112,11 +112,13 @@ export function getFullOrBlindedPayloadFromBody( ): ExecutionPayload | ExecutionPayloadHeader { if (isBlindedBeaconBlockBody(body)) { return body.executionPayloadHeader; - } else if ((body as bellatrix.BeaconBlockBody).executionPayload !== undefined) { + } + + if ((body as bellatrix.BeaconBlockBody).executionPayload !== undefined) { return (body as bellatrix.BeaconBlockBody).executionPayload; - } else { - throw Error("Not full or blinded beacon block"); } + + throw Error("Not full or blinded beacon block"); } export function isCapellaPayload( diff --git a/packages/state-transition/src/util/loadState/loadValidator.ts b/packages/state-transition/src/util/loadState/loadValidator.ts index dcf5051c9c6d..406c848ef089 100644 --- a/packages/state-transition/src/util/loadState/loadValidator.ts +++ b/packages/state-transition/src/util/loadState/loadValidator.ts @@ -17,9 +17,8 @@ export function loadValidator( newValidatorValue[field] = seedValidator[field]; } return ssz.phase0.Validator.toViewDU(newValidatorValue); - } else { - return ssz.phase0.Validator.deserializeToViewDU(newValidatorBytes); } + return ssz.phase0.Validator.deserializeToViewDU(newValidatorBytes); } /** diff --git a/packages/state-transition/src/util/shufflingDecisionRoot.ts b/packages/state-transition/src/util/shufflingDecisionRoot.ts index 3d28cbebf83d..5a6c500d3987 100644 --- a/packages/state-transition/src/util/shufflingDecisionRoot.ts +++ b/packages/state-transition/src/util/shufflingDecisionRoot.ts @@ -14,9 +14,8 @@ export function proposerShufflingDecisionRoot(state: CachedBeaconStateAllForks): const decisionSlot = proposerShufflingDecisionSlot(state); if (state.slot === decisionSlot) { return null; - } else { - return getBlockRootAtSlot(state, decisionSlot); } + return getBlockRootAtSlot(state, decisionSlot); } /** @@ -39,9 +38,8 @@ export function attesterShufflingDecisionRoot(state: CachedBeaconStateAllForks, const decisionSlot = attesterShufflingDecisionSlot(state, requestedEpoch); if (state.slot === decisionSlot) { return null; - } else { - return getBlockRootAtSlot(state, decisionSlot); } + return getBlockRootAtSlot(state, decisionSlot); } /** @@ -75,7 +73,6 @@ function attesterShufflingDecisionEpoch(state: CachedBeaconStateAllForks, reques if (requestedEpoch < currentEpoch) { throw Error(`EpochTooLow: current ${currentEpoch} requested ${requestedEpoch}`); - } else { - throw Error(`EpochTooHigh: current ${currentEpoch} requested ${requestedEpoch}`); } + throw Error(`EpochTooHigh: current ${currentEpoch} requested ${requestedEpoch}`); } diff --git a/packages/state-transition/src/util/validator.ts b/packages/state-transition/src/util/validator.ts index ebad21d9d25c..bf79f9264342 100644 --- a/packages/state-transition/src/util/validator.ts +++ b/packages/state-transition/src/util/validator.ts @@ -45,9 +45,8 @@ export function getActiveValidatorIndices(state: BeaconStateAllForks, epoch: Epo export function getActivationChurnLimit(config: ChainForkConfig, fork: ForkSeq, activeValidatorCount: number): number { if (fork >= ForkSeq.deneb) { return Math.min(config.MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT, getChurnLimit(config, activeValidatorCount)); - } else { - return getChurnLimit(config, activeValidatorCount); } + return getChurnLimit(config, activeValidatorCount); } export function getChurnLimit(config: ChainForkConfig, activeValidatorCount: number): number { @@ -79,9 +78,8 @@ export function getMaxEffectiveBalance(withdrawalCredentials: Uint8Array): numbe // Compounding withdrawal credential only available since Electra if (hasCompoundingWithdrawalCredential(withdrawalCredentials)) { return MAX_EFFECTIVE_BALANCE_ELECTRA; - } else { - return MIN_ACTIVATION_BALANCE; } + return MIN_ACTIVATION_BALANCE; } export function getActiveBalance(state: CachedBeaconStateElectra, validatorIndex: ValidatorIndex): number { diff --git a/packages/state-transition/test/perf/misc/proxy.test.ts b/packages/state-transition/test/perf/misc/proxy.test.ts index 6a3536a12de5..08618a1727e2 100644 --- a/packages/state-transition/test/perf/misc/proxy.test.ts +++ b/packages/state-transition/test/perf/misc/proxy.test.ts @@ -12,9 +12,8 @@ describe("Proxy cost", () => { get(target, p) { if (p === "length") { return target.length; - } else { - return target[p as unknown as number]; } + return target[p as unknown as number]; }, }); diff --git a/packages/state-transition/test/utils/beforeValue.ts b/packages/state-transition/test/utils/beforeValue.ts index 6a2f5ee86945..2ac79575ae5a 100644 --- a/packages/state-transition/test/utils/beforeValue.ts +++ b/packages/state-transition/test/utils/beforeValue.ts @@ -25,12 +25,10 @@ export function beforeValue(fn: () => T | Promise, timeout?: number): Lazy if (prop === "value") { if (value === null) { throw Error("beforeValue has not yet run the before() block"); - } else { - return value; } - } else { - return undefined; + return value; } + return undefined; }, } ); diff --git a/packages/state-transition/test/utils/beforeValueMocha.ts b/packages/state-transition/test/utils/beforeValueMocha.ts index d078357bd3b4..1389f182c188 100644 --- a/packages/state-transition/test/utils/beforeValueMocha.ts +++ b/packages/state-transition/test/utils/beforeValueMocha.ts @@ -24,12 +24,11 @@ export function beforeValue(fn: () => T | Promise, timeout?: number): Lazy if (prop === "value") { if (value === null) { throw Error("beforeValue has not yet run the before() block"); - } else { - return value; } - } else { - return undefined; + return value; } + + return undefined; }, } ); diff --git a/packages/state-transition/test/utils/testFileCache.ts b/packages/state-transition/test/utils/testFileCache.ts index 28741bf932c5..5283a6f87fa1 100644 --- a/packages/state-transition/test/utils/testFileCache.ts +++ b/packages/state-transition/test/utils/testFileCache.ts @@ -41,23 +41,23 @@ export async function getNetworkCachedState( if (fs.existsSync(filepath)) { const stateSsz = fs.readFileSync(filepath); return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config); - } else { - const stateSsz = await tryEach([ - () => downloadTestFile(fileId), - () => { - const client = getClient( - {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}}, - {config} - ); - return client.debug.getStateV2({stateId: slot}).then((r) => { - return r.ssz(); - }); - }, - ]); - - fs.writeFileSync(filepath, stateSsz); - return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config); } + + const stateSsz = await tryEach([ + () => downloadTestFile(fileId), + () => { + const client = getClient( + {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}}, + {config} + ); + return client.debug.getStateV2({stateId: slot}).then((r) => { + return r.ssz(); + }); + }, + ]); + + fs.writeFileSync(filepath, stateSsz); + return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config); } /** @@ -76,22 +76,22 @@ export async function getNetworkCachedBlock( if (fs.existsSync(filepath)) { const blockSsz = fs.readFileSync(filepath); return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz); - } else { - const blockSsz = await tryEach([ - () => downloadTestFile(fileId), - async () => { - const client = getClient( - {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}}, - {config} - ); - - return (await client.beacon.getBlockV2({blockId: slot})).ssz(); - }, - ]); - - fs.writeFileSync(filepath, blockSsz); - return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz); } + + const blockSsz = await tryEach([ + () => downloadTestFile(fileId), + async () => { + const client = getClient( + {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}}, + {config} + ); + + return (await client.beacon.getBlockV2({blockId: slot})).ssz(); + }, + ]); + + fs.writeFileSync(filepath, blockSsz); + return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz); } async function downloadTestFile(fileId: string): Promise { diff --git a/packages/types/src/utils/validatorStatus.ts b/packages/types/src/utils/validatorStatus.ts index aa8171fbbbd2..9e72c39d9df2 100644 --- a/packages/types/src/utils/validatorStatus.ts +++ b/packages/types/src/utils/validatorStatus.ts @@ -24,7 +24,9 @@ export function getValidatorStatus(validator: phase0.Validator, currentEpoch: Ep if (validator.activationEpoch > currentEpoch) { if (validator.activationEligibilityEpoch === FAR_FUTURE_EPOCH) { return "pending_initialized"; - } else if (validator.activationEligibilityEpoch < FAR_FUTURE_EPOCH) { + } + + if (validator.activationEligibilityEpoch < FAR_FUTURE_EPOCH) { return "pending_queued"; } } @@ -32,7 +34,9 @@ export function getValidatorStatus(validator: phase0.Validator, currentEpoch: Ep if (validator.activationEpoch <= currentEpoch && currentEpoch < validator.exitEpoch) { if (validator.exitEpoch === FAR_FUTURE_EPOCH) { return "active_ongoing"; - } else if (validator.exitEpoch < FAR_FUTURE_EPOCH) { + } + + if (validator.exitEpoch < FAR_FUTURE_EPOCH) { return validator.slashed ? "active_slashed" : "active_exiting"; } } diff --git a/packages/utils/src/bytes.ts b/packages/utils/src/bytes.ts index 95bb62ebd548..c290232ce8db 100644 --- a/packages/utils/src/bytes.ts +++ b/packages/utils/src/bytes.ts @@ -34,7 +34,8 @@ export function bytesToInt(value: Uint8Array, endianness: Endianness = "le"): nu export function bigIntToBytes(value: bigint, length: number, endianness: Endianness = "le"): Buffer { if (endianness === "le") { return toBufferLE(value, length); - } else if (endianness === "be") { + } + if (endianness === "be") { return toBufferBE(value, length); } throw new Error("endianness must be either 'le' or 'be'"); @@ -43,7 +44,8 @@ export function bigIntToBytes(value: bigint, length: number, endianness: Endiann export function bytesToBigInt(value: Uint8Array, endianness: Endianness = "le"): bigint { if (endianness === "le") { return toBigIntLE(value as Buffer); - } else if (endianness === "be") { + } + if (endianness === "be") { return toBigIntBE(value as Buffer); } throw new Error("endianness must be either 'le' or 'be'"); diff --git a/packages/utils/src/bytes/nodejs.ts b/packages/utils/src/bytes/nodejs.ts index 4cf8e78c67c6..efa7a585835f 100644 --- a/packages/utils/src/bytes/nodejs.ts +++ b/packages/utils/src/bytes/nodejs.ts @@ -1,11 +1,11 @@ export function toHex(buffer: Uint8Array | Parameters[0]): string { if (Buffer.isBuffer(buffer)) { return "0x" + buffer.toString("hex"); - } else if (buffer instanceof Uint8Array) { + } + if (buffer instanceof Uint8Array) { return "0x" + Buffer.from(buffer.buffer, buffer.byteOffset, buffer.length).toString("hex"); - } else { - return "0x" + Buffer.from(buffer).toString("hex"); } + return "0x" + Buffer.from(buffer).toString("hex"); } // Shared buffer to convert root to hex diff --git a/packages/utils/src/retry.ts b/packages/utils/src/retry.ts index 6c5e63deca42..bc759d62e9b2 100644 --- a/packages/utils/src/retry.ts +++ b/packages/utils/src/retry.ts @@ -60,9 +60,13 @@ export async function retry(fn: (attempt: number) => A | Promise, opts?: R if (i === maxAttempts) { // Reached maximum number of attempts, there's no need to check if we should retry break; - } else if (shouldRetry && !shouldRetry(lastError)) { + } + + if (shouldRetry && !shouldRetry(lastError)) { break; - } else if (opts?.retryDelay !== undefined) { + } + + if (opts?.retryDelay !== undefined) { await sleep(opts?.retryDelay, opts?.signal); } } diff --git a/packages/utils/test/unit/promiserace.test.ts b/packages/utils/test/unit/promiserace.test.ts index 1f31a55014a4..4b20f19f9fba 100644 --- a/packages/utils/test/unit/promiserace.test.ts +++ b/packages/utils/test/unit/promiserace.test.ts @@ -58,9 +58,8 @@ describe("resolveOrRacePromises", () => { const testPromises = timeouts.map((timeMs) => { if (timeMs > 0) { return resolveAfter(`${timeMs}`, timeMs); - } else { - return rejectAfter(`${timeMs}`, -timeMs); } + return rejectAfter(`${timeMs}`, -timeMs); }); const testResults = (await resolveOrRacePromises(testPromises as unknown as NonEmptyArray>, { resolveTimeoutMs: cutoffMs, diff --git a/packages/utils/test/unit/retry.test.ts b/packages/utils/test/unit/retry.test.ts index 12afb7597015..bd77c499a364 100644 --- a/packages/utils/test/unit/retry.test.ts +++ b/packages/utils/test/unit/retry.test.ts @@ -28,7 +28,8 @@ describe("retry", () => { id: "Succeed at the last attempt", fn: async (attempt) => { if (attempt < retries) throw sampleError; - else return sampleResult; + + return sampleResult; }, opts: {retries}, result: sampleResult, diff --git a/packages/validator/src/buckets.ts b/packages/validator/src/buckets.ts index bd361570a5a9..3313f7b5ae35 100644 --- a/packages/validator/src/buckets.ts +++ b/packages/validator/src/buckets.ts @@ -19,9 +19,9 @@ export function getBucketNameByValue(enumValue: T): keyof type const keys = Object.keys(Bucket).filter((x) => { if (Number.isNaN(parseInt(x))) { return Bucket[x as keyof typeof Bucket] === enumValue; - } else { - return false; } + + return false; }) as (keyof typeof Bucket)[]; if (keys.length > 0) { return keys[0]; diff --git a/packages/validator/src/services/block.ts b/packages/validator/src/services/block.ts index c3acf19c1669..cb295450e96b 100644 --- a/packages/validator/src/services/block.ts +++ b/packages/validator/src/services/block.ts @@ -265,18 +265,17 @@ export class BlockProposingService { debugLogCtx, builderSelection ); - } else { - Object.assign(debugLogCtx, {api: "produceBlindedBlock"}); - const res = await this.api.validator.produceBlindedBlock({slot, randaoReveal, graffiti}); - const {version} = res.meta(); - const executionPayloadSource = ProducedBlockSource.builder; - - return parseProduceBlockResponse( - {data: res.value(), executionPayloadBlinded: true, executionPayloadSource, version}, - debugLogCtx, - builderSelection - ); } + Object.assign(debugLogCtx, {api: "produceBlindedBlock"}); + const res = await this.api.validator.produceBlindedBlock({slot, randaoReveal, graffiti}); + const {version} = res.meta(); + const executionPayloadSource = ProducedBlockSource.builder; + + return parseProduceBlockResponse( + {data: res.value(), executionPayloadBlinded: true, executionPayloadSource, version}, + debugLogCtx, + builderSelection + ); }; } @@ -311,26 +310,26 @@ function parseProduceBlockResponse( executionPayloadSource, debugLogCtx, } as FullOrBlindedBlockWithContents & DebugLogCtx; - } else { - const data = response.data; - if (isBlockContents(data)) { - return { - block: data.block, - contents: {blobs: data.blobs, kzgProofs: data.kzgProofs}, - version: response.version, - executionPayloadBlinded: false, - executionPayloadSource, - debugLogCtx, - } as FullOrBlindedBlockWithContents & DebugLogCtx; - } else { - return { - block: response.data, - contents: null, - version: response.version, - executionPayloadBlinded: false, - executionPayloadSource, - debugLogCtx, - } as FullOrBlindedBlockWithContents & DebugLogCtx; - } } + + const data = response.data; + if (isBlockContents(data)) { + return { + block: data.block, + contents: {blobs: data.blobs, kzgProofs: data.kzgProofs}, + version: response.version, + executionPayloadBlinded: false, + executionPayloadSource, + debugLogCtx, + } as FullOrBlindedBlockWithContents & DebugLogCtx; + } + + return { + block: response.data, + contents: null, + version: response.version, + executionPayloadBlinded: false, + executionPayloadSource, + debugLogCtx, + } as FullOrBlindedBlockWithContents & DebugLogCtx; } diff --git a/packages/validator/src/services/doppelgangerService.ts b/packages/validator/src/services/doppelgangerService.ts index e167ee1d5028..aa43d7bba55b 100644 --- a/packages/validator/src/services/doppelgangerService.ts +++ b/packages/validator/src/services/doppelgangerService.ts @@ -275,11 +275,12 @@ export class DoppelgangerService { function getStatus(state: DoppelgangerState | undefined): DoppelgangerStatus { if (!state) { return DoppelgangerStatus.Unknown; - } else if (state.remainingEpochs <= 0) { + } + if (state.remainingEpochs <= 0) { return DoppelgangerStatus.VerifiedSafe; - } else if (state.remainingEpochs === REMAINING_EPOCHS_IF_DOPPELGANGER) { + } + if (state.remainingEpochs === REMAINING_EPOCHS_IF_DOPPELGANGER) { return DoppelgangerStatus.DoppelgangerDetected; - } else { - return DoppelgangerStatus.Unverified; } + return DoppelgangerStatus.Unverified; } diff --git a/packages/validator/src/services/validatorStore.ts b/packages/validator/src/services/validatorStore.ts index c15bfb6518b4..55b5adef23e1 100644 --- a/packages/validator/src/services/validatorStore.ts +++ b/packages/validator/src/services/validatorStore.ts @@ -538,13 +538,13 @@ export class ValidatorStore { signature: await this.getSignature(duty.pubkey, signingRoot, signingSlot, signableMessage), committeeBits: BitArray.fromSingleBit(MAX_COMMITTEES_PER_SLOT, duty.committeeIndex), }; - } else { - return { - aggregationBits: BitArray.fromSingleBit(duty.committeeLength, duty.validatorCommitteeIndex), - data: attestationData, - signature: await this.getSignature(duty.pubkey, signingRoot, signingSlot, signableMessage), - } as phase0.Attestation; } + + return { + aggregationBits: BitArray.fromSingleBit(duty.committeeLength, duty.validatorCommitteeIndex), + data: attestationData, + signature: await this.getSignature(duty.pubkey, signingRoot, signingSlot, signableMessage), + } as phase0.Attestation; } async signAggregateAndProof( @@ -731,15 +731,14 @@ export class ValidatorStore { const builderData = validatorData?.builderData; if (builderData?.regFullKey === regFullKey) { return builderData.validatorRegistration; - } else { - const validatorRegistration = await this.signValidatorRegistration(pubkeyMaybeHex, regAttributes, slot); - // If pubkeyHex was actually registered, then update the regData - if (validatorData !== undefined) { - validatorData.builderData = {validatorRegistration, regFullKey}; - this.validators.set(pubkeyHex, validatorData); - } - return validatorRegistration; } + const validatorRegistration = await this.signValidatorRegistration(pubkeyMaybeHex, regAttributes, slot); + // If pubkeyHex was actually registered, then update the regData + if (validatorData !== undefined) { + validatorData.builderData = {validatorRegistration, regFullKey}; + this.validators.set(pubkeyHex, validatorData); + } + return validatorRegistration; } private async getSignature( diff --git a/packages/validator/src/slashingProtection/attestation/index.ts b/packages/validator/src/slashingProtection/attestation/index.ts index 8dd86769202f..f0d3a0bca172 100644 --- a/packages/validator/src/slashingProtection/attestation/index.ts +++ b/packages/validator/src/slashingProtection/attestation/index.ts @@ -63,13 +63,12 @@ export class SlashingProtectionAttestationService { // Interchange format allows for attestations without signing_root, then assume root is equal if (isEqualNonZeroRoot(sameTargetAtt.signingRoot, attestation.signingRoot)) { return SafeStatus.SAME_DATA; - } else { - throw new InvalidAttestationError({ - code: InvalidAttestationErrorCode.DOUBLE_VOTE, - attestation: attestation, - prev: sameTargetAtt, - }); } + throw new InvalidAttestationError({ + code: InvalidAttestationErrorCode.DOUBLE_VOTE, + attestation: attestation, + prev: sameTargetAtt, + }); } // Check for a surround vote diff --git a/packages/validator/src/slashingProtection/block/index.ts b/packages/validator/src/slashingProtection/block/index.ts index 618fa61704be..385575e82a0a 100644 --- a/packages/validator/src/slashingProtection/block/index.ts +++ b/packages/validator/src/slashingProtection/block/index.ts @@ -41,13 +41,13 @@ export class SlashingProtectionBlockService { // Interchange format allows for blocks without signing_root, then assume root is equal if (isEqualNonZeroRoot(sameSlotBlock.signingRoot, block.signingRoot)) { return SafeStatus.SAME_DATA; - } else { - throw new InvalidBlockError({ - code: InvalidBlockErrorCode.DOUBLE_BLOCK_PROPOSAL, - block, - block2: sameSlotBlock, - }); } + + throw new InvalidBlockError({ + code: InvalidBlockErrorCode.DOUBLE_BLOCK_PROPOSAL, + block, + block2: sameSlotBlock, + }); } // Refuse to sign any block with slot <= min(b.slot for b in data.signed_blocks if b.pubkey == proposer_pubkey), diff --git a/packages/validator/src/util/clock.ts b/packages/validator/src/util/clock.ts index ca29eacd41c2..4b3fc45cd803 100644 --- a/packages/validator/src/util/clock.ts +++ b/packages/validator/src/util/clock.ts @@ -119,17 +119,14 @@ export class Clock implements IClock { if (timeItem === TimeItem.Slot) { if (msFromGenesis >= 0) { return milliSecondsPerSlot - (msFromGenesis % milliSecondsPerSlot); - } else { - return Math.abs(msFromGenesis % milliSecondsPerSlot); - } - } else { - const milliSecondsPerEpoch = SLOTS_PER_EPOCH * milliSecondsPerSlot; - if (msFromGenesis >= 0) { - return milliSecondsPerEpoch - (msFromGenesis % milliSecondsPerEpoch); - } else { - return Math.abs(msFromGenesis % milliSecondsPerEpoch); } + return Math.abs(msFromGenesis % milliSecondsPerSlot); + } + const milliSecondsPerEpoch = SLOTS_PER_EPOCH * milliSecondsPerSlot; + if (msFromGenesis >= 0) { + return milliSecondsPerEpoch - (msFromGenesis % milliSecondsPerEpoch); } + return Math.abs(msFromGenesis % milliSecondsPerEpoch); } } diff --git a/packages/validator/src/util/externalSignerClient.ts b/packages/validator/src/util/externalSignerClient.ts index 64d595452296..54c0c16946ad 100644 --- a/packages/validator/src/util/externalSignerClient.ts +++ b/packages/validator/src/util/externalSignerClient.ts @@ -241,14 +241,14 @@ function serializerSignableMessagePayload(config: BeaconConfig, payload: Signabl block_header: ssz.phase0.BeaconBlockHeader.toJson(blindedOrFullBlockToHeader(config, payload.data)), }, }; - } else { - return { - beacon_block: { - version, - block: config.getForkTypes(payload.data.slot).BeaconBlock.toJson(payload.data), - }, - }; } + + return { + beacon_block: { + version, + block: config.getForkTypes(payload.data.slot).BeaconBlock.toJson(payload.data), + }, + }; } case SignableMessageType.DEPOSIT: