diff --git a/biome.jsonc b/biome.jsonc index b49fc601600c..62d67fb7575f 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -24,27 +24,8 @@ "enabled": true, "rules": { "recommended": true, - "complexity": { - "noForEach": "off", - "noStaticOnlyClass": "off", - "noThisInStatic": "off", - "noUselessEmptyExport": "off", - "noUselessTypeConstraint": "error", - "useArrowFunction": "off", - "useFlatMap": "off", - "useLiteralKeys": "off", - "useOptionalChain": "off", - "useRegexLiterals": "off", - "noBannedTypes": "error", - "noUselessThisAlias": "error" - }, "correctness": { - "noInvalidConstructorSuper": "off", - "noInvalidUseBeforeDeclaration": "off", - "noPrecisionLoss": "error", "noUnusedVariables": "error", - "noVoidTypeReturn": "off", - "useYield": "off", "useImportExtensions": { "level": "error", "options": { @@ -57,17 +38,16 @@ } }, "useArrayLiterals": "error", - "noUndeclaredDependencies": "off", // TODO: Need to see why this rule is not detecting monorepo packages "noUndeclaredVariables": "error" }, "performance": { - "noAccumulatingSpread": "off", + // This rule should be enabled but with considerations and careful review "noDelete": "off" }, "style": { + // The code usage looks suspicious so it should be enabled in a separate PR "noCommaOperator": "off", - "noInferrableTypes": "off", - "noNonNullAssertion": "error", + // There are a lot of places we mutate params, should be fixed in an independent PR. "noParameterAssign": "off", "noRestrictedGlobals": { "level": "error", @@ -75,15 +55,24 @@ "deniedGlobals": ["fetch"] } }, - "noUnusedTemplateLiteral": "off", - "noUselessElse": "off", - "noVar": "error", - "useConst": "error", - "useEnumInitializers": "off", + // We prefer to use `Math.pow` over `**` operator "useExponentiationOperator": "off", + // In some cases the enums are initialized with values of other enums + "useLiteralEnumMembers": "off", + // We prefer to have multiple declarations lines + "useSingleVarDeclarator": "off", + // We use `+` operator for string concatenation a lot + "useTemplate": "off", + // We use to export types and object without differentiating "useExportType": "off", + // We use to import types and object without differentiating "useImportType": "off", - "useLiteralEnumMembers": "off", + // It's nice to use `Number` namespace but should be done in a separate PR + "useNumberNamespace": "off", + // We prefer to auto-initialize enums + "useEnumInitializers": "off", + "noVar": "error", + "useConst": "error", "useNamingConvention": { "level": "error", "options": { @@ -194,34 +183,14 @@ ] } }, - "useNumberNamespace": "off", - "useSingleVarDeclarator": "off", - "useTemplate": "off", - "noNamespace": "error", - "useAsConstAssertion": "error" + "noNamespace": "error" }, "suspicious": { - "noAssignInExpressions": "error", - "noAsyncPromiseExecutor": "off", + // `void` as type is useful in our case when used as generic constraint e.g. K extends number | void "noConfusingVoidType": "off", - "noConsoleLog": "error", - "noDoubleEquals": "off", - "noDuplicateTestHooks": "off", - "noExplicitAny": "error", - "noExportsInTest": "off", - "noFallthroughSwitchClause": "off", - "noGlobalIsFinite": "off", - "noGlobalIsNan": "off", - "noImplicitAnyLet": "off", - "noPrototypeBuiltins": "off", - "noRedundantUseStrict": "off", - "noShadowRestrictedNames": "off", - "useDefaultSwitchClauseLast": "off", - "useGetterReturn": "off", - "noExtraNonNullAssertion": "error", - "noMisleadingInstantiator": "error", - "noUnsafeDeclarationMerging": "error", - "noEmptyBlockStatements": "off" // There is a lot of empty code blocks, should be enabled and clean up separately. + // There is a lot of empty code blocks, should be enabled and clean up separately. + "noEmptyBlockStatements": "off", + "noConsoleLog": "error" }, "nursery": { "useConsistentMemberAccessibility": { @@ -369,7 +338,16 @@ { "include": ["**/test/**/*.test.ts"], "linter": { - "rules": {} + "rules": { + "complexity": { + // During tests we often need to use private/protected attributes, which is only possible with literal keys + "useLiteralKeys": "off" + }, + "suspicious": { + // During tests it's quicker to define variables with `let` without specifying types + "noImplicitAnyLet": "off" + } + } } } ] diff --git a/packages/api/src/beacon/server/events.ts b/packages/api/src/beacon/server/events.ts index 96212f006d8f..b9027ab1879d 100644 --- a/packages/api/src/beacon/server/events.ts +++ b/packages/api/src/beacon/server/events.ts @@ -23,9 +23,9 @@ export function getRoutes(config: ChainForkConfig, methods: ApplicationMethods { + for (const [key, value] of Object.entries(res.getHeaders())) { if (value !== undefined) res.raw.setHeader(key, value); - }); + } res.raw.setHeader("Content-Type", "text/event-stream"); res.raw.setHeader("Cache-Control", "no-cache,no-transform"); 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 eec86725fcaa..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); } } @@ -352,7 +347,9 @@ export class HttpClient implements IHttpClient { // Attach global/local signal to this request's controller const onSignalAbort = (): void => controller.abort(); - abortSignals.forEach((s) => s?.addEventListener("abort", onSignalAbort)); + for (const s of abortSignals) { + s?.addEventListener("abort", onSignalAbort); + } const routeId = definition.operationId; const {printableUrl, requestWireFormat, responseWireFormat} = init; @@ -389,19 +386,20 @@ 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?.(); clearTimeout(timeout); - abortSignals.forEach((s) => s?.removeEventListener("abort", onSignalAbort)); + for (const s of abortSignals) { + s?.removeEventListener("abort", onSignalAbort); + } } } 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/headers.ts b/packages/api/src/utils/headers.ts index 5f3c6e3e1dfc..7547ac022a7a 100644 --- a/packages/api/src/utils/headers.ts +++ b/packages/api/src/utils/headers.ts @@ -70,7 +70,7 @@ export function parseAcceptHeader(accept?: string, supported = SUPPORTED_MEDIA_T } const qvalue = +weight.replace("q=", ""); - if (isNaN(qvalue) || qvalue > 1 || qvalue <= 0) { + if (Number.isNaN(qvalue) || qvalue > 1 || qvalue <= 0) { // If we can't convert the qvalue to a valid number, move on return best; } diff --git a/packages/api/src/utils/httpStatusCode.ts b/packages/api/src/utils/httpStatusCode.ts index 572562e7da3d..2316f3d1db87 100644 --- a/packages/api/src/utils/httpStatusCode.ts +++ b/packages/api/src/utils/httpStatusCode.ts @@ -1,5 +1,3 @@ -"use strict"; - /** * Hypertext Transfer Protocol (HTTP) response status codes. * @see {@link https://www.rfc-editor.org/rfc/rfc7231#section-6} diff --git a/packages/api/src/utils/serdes.ts b/packages/api/src/utils/serdes.ts index c2080ad2d020..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)]; } /** @@ -50,7 +49,7 @@ export type U64Str = string; export function fromU64Str(u64Str: U64Str): number { const u64 = parseInt(u64Str, 10); - if (!isFinite(u64)) { + if (!Number.isFinite(u64)) { throw Error(`Invalid uin64 ${u64Str}`); } return u64; diff --git a/packages/api/test/unit/client/fetch.test.ts b/packages/api/test/unit/client/fetch.test.ts index 0c08c5bbf5a3..1faf7d979a02 100644 --- a/packages/api/test/unit/client/fetch.test.ts +++ b/packages/api/test/unit/client/fetch.test.ts @@ -3,7 +3,7 @@ import http from "node:http"; import {describe, it, expect, afterEach} from "vitest"; import {FetchError, FetchErrorType, fetch} from "../../../src/utils/client/fetch.js"; -describe("FetchError", function () { +describe("FetchError", () => { const port = 37421; const randomHex = crypto.randomBytes(32).toString("hex"); @@ -87,7 +87,7 @@ describe("FetchError", function () { const afterHooks: (() => Promise)[] = []; - afterEach(async function () { + afterEach(async () => { while (afterHooks.length) { const afterHook = afterHooks.pop(); if (afterHook) @@ -100,7 +100,7 @@ describe("FetchError", function () { for (const testCase of testCases) { const {id, url = `http://localhost:${port}`, requestListener, signalHandler} = testCase; - it(id, async function () { + it(id, async () => { if (requestListener) { const server = http.createServer(requestListener); await new Promise((resolve) => server.listen(port, resolve)); 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..a3f943ad4816 100644 --- a/packages/api/test/utils/checkAgainstSpec.ts +++ b/packages/api/test/utils/checkAgainstSpec.ts @@ -93,13 +93,13 @@ export function runTestCheckAgainstSpec>( } }); - it(`${operationId}_route`, function () { + it(`${operationId}_route`, () => { expect(routeDef.method.toLowerCase()).toBe(routeSpec.method.toLowerCase()); expect(routeDef.url).toBe(routeSpec.url); }); if (requestSchema != null) { - it(`${operationId}_request`, function () { + it(`${operationId}_request`, () => { const reqJson = isRequestWithoutBody(routeDef) ? routeDef.req.writeReq(testData.args) : (routeDef.req as RequestWithBodyCodec).writeReqJson(testData.args); @@ -135,7 +135,7 @@ export function runTestCheckAgainstSpec>( } if (responseOkSchema) { - it(`${operationId}_response`, function () { + it(`${operationId}_response`, () => { const data = routeDef.resp.data.toJson(testData.res?.data, testData.res?.meta); const metaJson = routeDef.resp.meta.toJson(testData.res?.meta); const headers = parseHeaders(routeDef.resp.meta.toHeadersObject(testData.res?.meta)); @@ -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/api/test/utils/parseOpenApiSpec.ts b/packages/api/test/utils/parseOpenApiSpec.ts index e6e75014312b..d04827fd2011 100644 --- a/packages/api/test/utils/parseOpenApiSpec.ts +++ b/packages/api/test/utils/parseOpenApiSpec.ts @@ -151,7 +151,7 @@ function preprocessSchema(schema: JsonSchema): void { // Remove non-intersecting allOf enum applyRecursively(schema, (obj) => { - if (obj.allOf && obj.allOf.every((s) => s.enum)) { + if (obj.allOf?.every((s) => s.enum)) { obj.allOf = [obj.allOf[0]]; } }); diff --git a/packages/api/test/utils/utils.ts b/packages/api/test/utils/utils.ts index 32a4db6162c6..d3ecbc964435 100644 --- a/packages/api/test/utils/utils.ts +++ b/packages/api/test/utils/utils.ts @@ -20,8 +20,8 @@ export function getTestServer(): {server: FastifyInstance; start: () => Promise< const start = (): Promise => new Promise((resolve, reject) => { - server.listen({port: 0}, function (err, address) { - if (err !== null && err != undefined) { + server.listen({port: 0}, (err, address) => { + if (err != null) { reject(err); } else { resolve(address); 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/blocks/utils.ts b/packages/beacon-node/src/api/impl/beacon/blocks/utils.ts index fe4fc5ca3dc0..44152ff4b8a9 100644 --- a/packages/beacon-node/src/api/impl/beacon/blocks/utils.ts +++ b/packages/beacon-node/src/api/impl/beacon/blocks/utils.ts @@ -50,7 +50,7 @@ export function resolveBlockId(forkChoice: IForkChoice, blockId: routes.beacon.B // block id must be slot const blockSlot = parseInt(blockId, 10); - if (isNaN(blockSlot) && isNaN(blockSlot - 0)) { + if (Number.isNaN(blockSlot) && Number.isNaN(blockSlot - 0)) { throw new ValidationError(`Invalid block id '${blockId}'`, "blockId"); } return blockSlot; 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/beacon/state/utils.ts b/packages/beacon-node/src/api/impl/beacon/state/utils.ts index 15e8bdf73176..392262a563be 100644 --- a/packages/beacon-node/src/api/impl/beacon/state/utils.ts +++ b/packages/beacon-node/src/api/impl/beacon/state/utils.ts @@ -34,7 +34,7 @@ export function resolveStateId( // id must be slot const blockSlot = parseInt(String(stateId), 10); - if (isNaN(blockSlot) && isNaN(blockSlot - 0)) { + if (Number.isNaN(blockSlot) && Number.isNaN(blockSlot - 0)) { throw new ValidationError(`Invalid block id '${stateId}'`, "blockId"); } diff --git a/packages/beacon-node/src/api/impl/lodestar/index.ts b/packages/beacon-node/src/api/impl/lodestar/index.ts index 0e8d2b1fa94b..f89959ad9da6 100644 --- a/packages/beacon-node/src/api/impl/lodestar/index.ts +++ b/packages/beacon-node/src/api/impl/lodestar/index.ts @@ -109,6 +109,7 @@ export function getLodestarApi({ async getBlockProcessorQueueItems() { return { + // biome-ignore lint/complexity/useLiteralKeys: The `blockProcessor` is a protected attribute data: (chain as BeaconChain)["blockProcessor"].jobQueue.getItems().map((item) => { const [blockInputs, opts] = item.args; return { @@ -173,6 +174,7 @@ export function getLodestarApi({ async dumpDbBucketKeys({bucket}) { for (const repo of Object.values(db) as IBeaconDb[keyof IBeaconDb][]) { if (repo instanceof Repository) { + // biome-ignore lint/complexity/useLiteralKeys: `bucket` is protected and `bucketId` is private if (String(repo["bucket"]) === bucket || repo["bucketId"] === bucket) { return {data: stringifyKeys(await repo.keys())}; } @@ -218,8 +220,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..5642f47aeceb 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: @@ -399,7 +401,7 @@ export function getValidatorApi( } notOnOutOfRangeData(parentBlockRoot); - let timer; + let timer: undefined | ((opts: {source: ProducedBlockSource}) => number); try { timer = metrics?.blockProductionTime.startTimer(); const {block, executionPayloadValue, consensusBlockValue} = await chain.produceBlindedBlock({ @@ -465,7 +467,7 @@ export function getValidatorApi( } notOnOutOfRangeData(parentBlockRoot); - let timer; + let timer: undefined | ((opts: {source: ProducedBlockSource}) => number); try { timer = metrics?.blockProductionTime.startTimer(); const {block, executionPayloadValue, consensusBlockValue, shouldOverrideBuilder} = await chain.produceBlock({ @@ -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/balancesCache.ts b/packages/beacon-node/src/chain/balancesCache.ts index 50a86b31b6c8..d29a6998f600 100644 --- a/packages/beacon-node/src/chain/balancesCache.ts +++ b/packages/beacon-node/src/chain/balancesCache.ts @@ -35,7 +35,7 @@ export class CheckpointBalancesCache { const epochBoundaryRoot = epochBoundarySlot === state.slot ? blockRootHex : toRootHex(getBlockRootAtSlot(state, epochBoundarySlot)); - const index = this.items.findIndex((item) => item.epoch === epoch && item.rootHex == epochBoundaryRoot); + const index = this.items.findIndex((item) => item.epoch === epoch && item.rootHex === epochBoundaryRoot); if (index === -1) { if (this.items.length === MAX_BALANCE_CACHE_SIZE) { this.items.shift(); 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/verifyBlocksDataAvailability.ts b/packages/beacon-node/src/chain/blocks/verifyBlocksDataAvailability.ts index accd3df31ab0..98bfae2c1ce3 100644 --- a/packages/beacon-node/src/chain/blocks/verifyBlocksDataAvailability.ts +++ b/packages/beacon-node/src/chain/blocks/verifyBlocksDataAvailability.ts @@ -78,6 +78,7 @@ async function maybeValidateBlobs( case BlockInputType.outOfRangeData: return {dataAvailabilityStatus: DataAvailabilityStatus.OutOfRange, availableBlockInput: blockInput}; + // biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here case BlockInputType.availableData: if (opts.validBlobSidecars === BlobSidecarValidation.Full) { return {dataAvailabilityStatus: DataAvailabilityStatus.Available, availableBlockInput: blockInput}; 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/blocks/writeBlockInputToDb.ts b/packages/beacon-node/src/chain/blocks/writeBlockInputToDb.ts index 89cf7ddc7556..010c6a1fabc1 100644 --- a/packages/beacon-node/src/chain/blocks/writeBlockInputToDb.ts +++ b/packages/beacon-node/src/chain/blocks/writeBlockInputToDb.ts @@ -31,7 +31,7 @@ export async function writeBlockInputToDb(this: BeaconChain, blocksInput: BlockI if (blockInput.type === BlockInputType.availableData || blockInput.type === BlockInputType.dataPromise) { const blobSidecars = - blockInput.type == BlockInputType.availableData + blockInput.type === BlockInputType.availableData ? blockInput.blockData.blobs : // At this point of import blobs are available and can be safely awaited (await blockInput.cachedData.availabilityPromise).blobs; diff --git a/packages/beacon-node/src/chain/bls/multithread/index.ts b/packages/beacon-node/src/chain/bls/multithread/index.ts index ce9b726c7693..cb18ca86e42f 100644 --- a/packages/beacon-node/src/chain/bls/multithread/index.ts +++ b/packages/beacon-node/src/chain/bls/multithread/index.ts @@ -313,7 +313,8 @@ export class BlsMultiThreadWorkerPool implements IBlsVerifier { this.workers[0].status.code === WorkerStatusCode.initializationError && this.workers.every((worker) => worker.status.code === WorkerStatusCode.initializationError) ) { - return job.reject(this.workers[0].status.error); + job.reject(this.workers[0].status.error); + return; } // Append batchable sets to `bufferedJobs`, starting a timeout to push them into `jobs`. 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 30567b5d79b8..0a41ea059e73 100644 --- a/packages/beacon-node/src/chain/lightClient/index.ts +++ b/packages/beacon-node/src/chain/lightClient/index.ts @@ -225,7 +225,7 @@ export class LightClientServer { this.zero = { // Assign the hightest fork's default value because it can always be typecasted down to correct fork finalizedHeader: sszTypesFor(highestFork(forkLightClient)).LightClientHeader.defaultValue(), - finalityBranch: ssz.altair.LightClientUpdate.fields["finalityBranch"].defaultValue(), + finalityBranch: ssz.altair.LightClientUpdate.fields.finalityBranch.defaultValue(), }; if (metrics) { @@ -630,12 +630,12 @@ export class LightClientServer { ? await this.getFinalizedHeader(attestedData.finalizedCheckpoint.root) : null; - let isFinalized, finalityBranch, finalizedHeader; + let isFinalized: boolean, finalityBranch: Uint8Array[], finalizedHeader: LightClientHeader; if ( attestedData.isFinalized && finalizedHeaderAttested && - computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) == syncPeriod + computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) === syncPeriod ) { isFinalized = true; finalityBranch = attestedData.finalityBranch; @@ -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( @@ -716,7 +714,7 @@ export function getValidateAttestationDataFn( const stateEpoch = state.epochCtx.epoch; return (attData: phase0.AttestationData) => { const targetEpoch = attData.target.epoch; - let justifiedCheckpoint; + let justifiedCheckpoint: phase0.Checkpoint; // simple check first if (targetEpoch === stateEpoch) { justifiedCheckpoint = currentJustifiedCheckpoint; @@ -761,7 +759,7 @@ export function isValidAttestationData( data: phase0.AttestationData ): boolean { const {previousJustifiedCheckpoint, currentJustifiedCheckpoint} = state; - let justifiedCheckpoint; + let justifiedCheckpoint: phase0.Checkpoint; const stateEpoch = state.epochCtx.epoch; const targetEpoch = data.target.epoch; 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/regen/queued.ts b/packages/beacon-node/src/chain/regen/queued.ts index 57e64bd364ea..694e8635a3b7 100644 --- a/packages/beacon-node/src/chain/regen/queued.ts +++ b/packages/beacon-node/src/chain/regen/queued.ts @@ -336,7 +336,7 @@ export class QueuedStateRegenerator implements IStateRegenerator { caller: regenRequest.args[regenRequest.args.length - 1] as RegenCaller, entrypoint: regenRequest.key as RegenFnName, }; - let timer; + let timer: (() => number) | undefined; try { timer = this.metrics?.regenFnCallDuration.startTimer(metricsLabels); switch (regenRequest.key) { diff --git a/packages/beacon-node/src/chain/rewards/attestationsRewards.ts b/packages/beacon-node/src/chain/rewards/attestationsRewards.ts index 0c74b8610f93..588b310f87ea 100644 --- a/packages/beacon-node/src/chain/rewards/attestationsRewards.ts +++ b/packages/beacon-node/src/chain/rewards/attestationsRewards.ts @@ -85,7 +85,7 @@ function computeIdealAttestationsRewardsAndPenaltiesAltair( for (let i = 0; i < PARTICIPATION_FLAG_WEIGHTS.length; i++) { const weight = PARTICIPATION_FLAG_WEIGHTS[i]; - let unslashedStakeByIncrement; + let unslashedStakeByIncrement: number; let flagName: keyof IdealAttestationsReward; switch (i) { 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..1c03979b7d77 100644 --- a/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts +++ b/packages/beacon-node/src/chain/seenCache/seenGossipBlockInput.ts @@ -72,9 +72,9 @@ export class SeenGossipBlockInput { blockInput: NullBlockInput; blockInputMeta: {pending: GossipedInputType.block; haveBlobs: number; expectedBlobs: null}; } { - let blockHex; - let blockCache; - let fork; + let blockHex: RootHex; + let blockCache: BlockInputCacheType; + let fork: ForkName; if (gossipedInput.type === GossipedInputType.block) { const {signedBlock, blockBytes} = gossipedInput; @@ -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/stateCache/datastore/file.ts b/packages/beacon-node/src/chain/stateCache/datastore/file.ts index f487079ae443..3c978c2355d6 100644 --- a/packages/beacon-node/src/chain/stateCache/datastore/file.ts +++ b/packages/beacon-node/src/chain/stateCache/datastore/file.ts @@ -13,7 +13,7 @@ const CHECKPOINT_FILE_NAME_LENGTH = 82; export class FileCPStateDatastore implements CPStateDatastore { private readonly folderPath: string; - constructor(parentDir: string = ".") { + constructor(parentDir = ".") { // by default use the beacon folder `/beacon/checkpoint_states` this.folderPath = path.join(parentDir, CHECKPOINT_STATES_FOLDER); } diff --git a/packages/beacon-node/src/chain/validation/aggregateAndProof.ts b/packages/beacon-node/src/chain/validation/aggregateAndProof.ts index de5f40372c9f..6d6eab6ec15a 100644 --- a/packages/beacon-node/src/chain/validation/aggregateAndProof.ts +++ b/packages/beacon-node/src/chain/validation/aggregateAndProof.ts @@ -74,7 +74,7 @@ async function validateAggregateAndProof( const seenAttDataKey = serializedData ? getSeenAttDataKeyFromSignedAggregateAndProof(fork, serializedData) : null; const cachedAttData = seenAttDataKey ? chain.seenAttestationDatas.get(attSlot, seenAttDataKey) : null; - let attIndex; + let attIndex: number | null; if (ForkSeq[fork] >= ForkSeq.electra) { attIndex = (aggregate as electra.Attestation).committeeBits.getSingleTrueBit(); // [REJECT] len(committee_indices) == 1, where committee_indices = get_committee_indices(aggregate) diff --git a/packages/beacon-node/src/chain/validation/attestation.ts b/packages/beacon-node/src/chain/validation/attestation.ts index 119a8ee1a899..0b3f490e4129 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; } } @@ -274,7 +273,7 @@ async function validateAttestationNoSignatureCheck( const attEpoch = computeEpochAtSlot(attSlot); const attTarget = attData.target; const targetEpoch = attTarget.epoch; - let committeeIndex; + let committeeIndex: number | null; if (attestationOrCache.attestation) { if (isElectraAttestation(attestationOrCache.attestation)) { // api or first time validation of a gossip attestation @@ -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/chain/validation/lightClientFinalityUpdate.ts b/packages/beacon-node/src/chain/validation/lightClientFinalityUpdate.ts index f4865c73f8e4..0b19495abde6 100644 --- a/packages/beacon-node/src/chain/validation/lightClientFinalityUpdate.ts +++ b/packages/beacon-node/src/chain/validation/lightClientFinalityUpdate.ts @@ -34,9 +34,9 @@ export function validateLightClientFinalityUpdate( } // [IGNORE] The received finality_update matches the locally computed one exactly - const sszType = config.getLightClientForkTypes(gossipedFinalityUpdate.attestedHeader.beacon.slot)[ - "LightClientFinalityUpdate" - ]; + const sszType = config.getLightClientForkTypes( + gossipedFinalityUpdate.attestedHeader.beacon.slot + ).LightClientFinalityUpdate; if (localFinalityUpdate === null || !sszType.equals(gossipedFinalityUpdate, localFinalityUpdate)) { throw new LightClientError(GossipAction.IGNORE, { code: LightClientErrorCode.FINALITY_UPDATE_NOT_MATCHING_LOCAL, diff --git a/packages/beacon-node/src/chain/validation/lightClientOptimisticUpdate.ts b/packages/beacon-node/src/chain/validation/lightClientOptimisticUpdate.ts index 182321984af5..7a7dd7f34a91 100644 --- a/packages/beacon-node/src/chain/validation/lightClientOptimisticUpdate.ts +++ b/packages/beacon-node/src/chain/validation/lightClientOptimisticUpdate.ts @@ -35,9 +35,9 @@ export function validateLightClientOptimisticUpdate( } // [IGNORE] The received optimistic_update matches the locally computed one exactly - const sszType = config.getLightClientForkTypes(gossipedOptimisticUpdate.attestedHeader.beacon.slot)[ - "LightClientOptimisticUpdate" - ]; + const sszType = config.getLightClientForkTypes( + gossipedOptimisticUpdate.attestedHeader.beacon.slot + ).LightClientOptimisticUpdate; if (localOptimisticUpdate === null || !sszType.equals(gossipedOptimisticUpdate, localOptimisticUpdate)) { throw new LightClientError(GossipAction.IGNORE, { code: LightClientErrorCode.OPTIMISTIC_UPDATE_NOT_MATCHING_LOCAL, diff --git a/packages/beacon-node/src/db/buckets.ts b/packages/beacon-node/src/db/buckets.ts index eff123879037..c35a5a18edf5 100644 --- a/packages/beacon-node/src/db/buckets.ts +++ b/packages/beacon-node/src/db/buckets.ts @@ -65,11 +65,10 @@ export enum Bucket { export function getBucketNameByValue(enumValue: T): keyof typeof Bucket { const keys = Object.keys(Bucket).filter((x) => { - if (isNaN(parseInt(x))) { - return Bucket[x as keyof typeof Bucket] == enumValue; - } else { - return false; + if (Number.isNaN(parseInt(x))) { + return Bucket[x as keyof typeof Bucket] === enumValue; } + return false; }) as (keyof typeof Bucket)[]; if (keys.length > 0) { return keys[0]; diff --git a/packages/beacon-node/src/db/repositories/blockArchive.ts b/packages/beacon-node/src/db/repositories/blockArchive.ts index 15c07f552b21..427650a37bc3 100644 --- a/packages/beacon-node/src/db/repositories/blockArchive.ts +++ b/packages/beacon-node/src/db/repositories/blockArchive.ts @@ -105,7 +105,7 @@ export class BlockArchiveRepository extends Repository async *valuesStream(opts?: BlockFilterOptions): AsyncIterable { const firstSlot = this.getFirstSlot(opts); const valuesStream = super.valuesStream(opts); - const step = (opts && opts.step) ?? 1; + const step = opts?.step ?? 1; for await (const value of valuesStream) { if ((value.message.slot - firstSlot) % step === 0) { diff --git a/packages/beacon-node/src/db/repositories/blockArchiveIndex.ts b/packages/beacon-node/src/db/repositories/blockArchiveIndex.ts index 797142d09db7..8c2785dbe67c 100644 --- a/packages/beacon-node/src/db/repositories/blockArchiveIndex.ts +++ b/packages/beacon-node/src/db/repositories/blockArchiveIndex.ts @@ -17,7 +17,7 @@ export async function deleteRootIndex( signedBeaconBlockType: SSZTypesFor, block: SignedBeaconBlock ): Promise { - const beaconBlockType = (signedBeaconBlockType as typeof ssz.phase0.SignedBeaconBlock).fields["message"]; + const beaconBlockType = (signedBeaconBlockType as typeof ssz.phase0.SignedBeaconBlock).fields.message; return db.delete(getRootIndexKey(beaconBlockType.hashTreeRoot(block.message))); } 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/eth1DataCache.ts b/packages/beacon-node/src/eth1/eth1DataCache.ts index 91b8537d1cc4..7f9bb99a2f16 100644 --- a/packages/beacon-node/src/eth1/eth1DataCache.ts +++ b/packages/beacon-node/src/eth1/eth1DataCache.ts @@ -21,6 +21,6 @@ export class Eth1DataCache { async getHighestCachedBlockNumber(): Promise { const highestEth1Data = await this.db.eth1Data.lastValue(); - return highestEth1Data && highestEth1Data.blockNumber; + return highestEth1Data?.blockNumber ?? null; } } diff --git a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts index a38b3f9987d9..674b6b600f31 100644 --- a/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts +++ b/packages/beacon-node/src/eth1/eth1DepositDataTracker.ts @@ -14,7 +14,7 @@ import {Eth1DepositsCache} from "./eth1DepositsCache.js"; import {Eth1DataCache} from "./eth1DataCache.js"; import {getEth1VotesToConsider, pickEth1Vote} from "./utils/eth1Vote.js"; import {getDeposits} from "./utils/deposits.js"; -import {Eth1DataAndDeposits, IEth1Provider} from "./interface.js"; +import {Eth1DataAndDeposits, EthJsonRpcBlockRaw, IEth1Provider} from "./interface.js"; import {Eth1Options} from "./options.js"; import {HttpRpcError} from "./provider/jsonRpcHttpClient.js"; import {parseEth1Block} from "./provider/eth1Provider.js"; @@ -243,7 +243,7 @@ export class Eth1DepositDataTracker { const fromBlock = Math.min(remoteFollowBlock, this.getFromBlockToFetch(lastProcessedDepositBlockNumber)); const toBlock = Math.min(remoteFollowBlock, fromBlock + this.eth1GetLogsBatchSizeDynamic - 1); - let depositEvents; + let depositEvents: phase0.DepositEvent[]; try { depositEvents = await this.eth1Provider.getDepositEvents(fromBlock, toBlock); // Increase the batch size linearly even if we scale down exponentially (half each time) @@ -313,7 +313,7 @@ export class Eth1DepositDataTracker { lastProcessedDepositBlockNumber ); - let blocksRaw; + let blocksRaw: EthJsonRpcBlockRaw[]; try { blocksRaw = await this.eth1Provider.getBlocksByNumber(fromBlock, toBlock); // Increase the batch size linearly even if we scale down exponentially (half each time) @@ -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/eth1DepositsCache.ts b/packages/beacon-node/src/eth1/eth1DepositsCache.ts index 2fb187d02cf7..13dd29013124 100644 --- a/packages/beacon-node/src/eth1/eth1DepositsCache.ts +++ b/packages/beacon-node/src/eth1/eth1DepositsCache.ts @@ -129,7 +129,7 @@ export class Eth1DepositsCache { */ async getHighestDepositEventBlockNumber(): Promise { const latestEvent = await this.db.depositEvent.lastValue(); - return latestEvent && latestEvent.blockNumber; + return latestEvent?.blockNumber || null; } /** @@ -137,6 +137,6 @@ export class Eth1DepositsCache { */ async getLowestDepositEventBlockNumber(): Promise { const firstEvent = await this.db.depositEvent.firstValue(); - return firstEvent && firstEvent.blockNumber; + return firstEvent?.blockNumber || null; } } diff --git a/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts b/packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts index f2ce0a8bb2f5..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, + }; } /** @@ -193,7 +192,7 @@ export class Eth1MergeBlockTracker { // Persist found merge block here to affect both caller paths: // - internal searcher // - external caller if STOPPED - if (mergeBlock && this.status.code != StatusCode.FOUND) { + if (mergeBlock && this.status.code !== StatusCode.FOUND) { if (this.status.code === StatusCode.SEARCHING) { this.close(); } @@ -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 7b2ec17496d3..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 { @@ -104,11 +102,11 @@ export class Eth1ForBlockProduction implements IEth1ForBlockProduction { } startPollingMergeBlock(): void { - return this.eth1MergeBlockTracker.startPollingMergeBlock(); + this.eth1MergeBlockTracker.startPollingMergeBlock(); } stopPollingEth1Data(): void { - return this.eth1DepositDataTracker?.stopPollingEth1Data(); + this.eth1DepositDataTracker?.stopPollingEth1Data(); } } diff --git a/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts b/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts index e1a2a001c278..f2ceae0d8c19 100644 --- a/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts +++ b/packages/beacon-node/src/eth1/provider/jsonRpcHttpClient.ts @@ -268,7 +268,7 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient { }; const token = encodeJwtToken(jwtClaim, this.jwtSecret); - headers["Authorization"] = `Bearer ${token}`; + headers.Authorization = `Bearer ${token}`; } const res = await fetch(url, { @@ -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/provider/utils.ts b/packages/beacon-node/src/eth1/provider/utils.ts index 096f1d7233c8..7010e1377ca6 100644 --- a/packages/beacon-node/src/eth1/provider/utils.ts +++ b/packages/beacon-node/src/eth1/provider/utils.ts @@ -53,7 +53,7 @@ export function numToQuantity(num: number | bigint): QUANTITY { */ export function quantityToNum(hex: QUANTITY, id = ""): number { const num = parseInt(hex, 16); - if (isNaN(num) || num < 0) throw Error(`Invalid hex decimal ${id} '${hex}'`); + if (Number.isNaN(num) || num < 0) throw Error(`Invalid hex decimal ${id} '${hex}'`); return num; } 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/core/networkCore.ts b/packages/beacon-node/src/network/core/networkCore.ts index 9d075c730558..b000d184e0eb 100644 --- a/packages/beacon-node/src/network/core/networkCore.ts +++ b/packages/beacon-node/src/network/core/networkCore.ts @@ -224,6 +224,7 @@ export class NetworkCore implements INetworkCore { reqResp.registerProtocolsAtFork(forkCurrentSlot); // Bind discv5's ENR to local metadata + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute discv5 = peerManager["discovery"]?.discv5; // Initialize ENR with clock's fork @@ -277,6 +278,7 @@ export class NetworkCore implements INetworkCore { async scrapeMetrics(): Promise { return [ (await this.metrics?.register.metrics()) ?? "", + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute (await this.peerManager["discovery"]?.discv5.scrapeMetrics()) ?? "", ] .filter((str) => str.length > 0) @@ -344,6 +346,7 @@ export class NetworkCore implements INetworkCore { // REST API queries async getNetworkIdentity(): Promise { + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute const enr = await this.peerManager["discovery"]?.discv5.enr(); const discoveryAddresses = [ enr?.getLocationMultiaddr("tcp")?.toString() ?? null, @@ -410,6 +413,7 @@ export class NetworkCore implements INetworkCore { } async dumpDiscv5KadValues(): Promise { + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute return (await this.peerManager["discovery"]?.discv5?.kadValues())?.map((enr) => enr.encodeTxt()) ?? []; } @@ -426,6 +430,7 @@ export class NetworkCore implements INetworkCore { } async writeDiscv5Profile(durationMs: number, dirpath: string): Promise { + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute return this.peerManager["discovery"]?.discv5.writeProfile(durationMs, dirpath) ?? "no discv5"; } @@ -434,6 +439,7 @@ export class NetworkCore implements INetworkCore { } writeDiscv5HeapSnapshot(prefix: string, dirpath: string): Promise { + // biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute return this.peerManager["discovery"]?.discv5.writeHeapSnapshot(prefix, dirpath) ?? Promise.resolve("no discv5"); } 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 debcbaf89854..83bb913325bf 100644 --- a/packages/beacon-node/src/network/gossip/gossipsub.ts +++ b/packages/beacon-node/src/network/gossip/gossipsub.ts @@ -121,7 +121,7 @@ export class Eth2Gossipsub extends GossipSub { // TODO: figure out a way to dynamically transition to the size dataTransform: new DataTransformSnappy( gossipTopicCache, - isFinite(config.BELLATRIX_FORK_EPOCH) ? GOSSIP_MAX_SIZE_BELLATRIX : GOSSIP_MAX_SIZE + Number.isFinite(config.BELLATRIX_FORK_EPOCH) ? GOSSIP_MAX_SIZE_BELLATRIX : GOSSIP_MAX_SIZE ), metricsRegister: metricsRegister as MetricsRegister | null, metricsTopicStrToLabel: metricsRegister @@ -184,10 +184,11 @@ export class Eth2Gossipsub extends GossipSub { } private onScrapeLodestarMetrics(metrics: Eth2GossipsubMetrics): void { - const mesh = this["mesh"]; + const mesh = this.mesh; + // biome-ignore lint/complexity/useLiteralKeys: `topics` is a private attribute const topics = this["topics"] as Map>; - const peers = this["peers"]; - const score = this["score"]; + const peers = this.peers; + const score = this.score; const meshPeersByClient = new Map(); const meshPeerIdStrs = new Set(); @@ -324,7 +325,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/gossip/topic.ts b/packages/beacon-node/src/network/gossip/topic.ts index c44e29274bca..ed44c8314425 100644 --- a/packages/beacon-node/src/network/gossip/topic.ts +++ b/packages/beacon-node/src/network/gossip/topic.ts @@ -137,7 +137,7 @@ export function sszDeserializeAttestation(fork: ForkName, serializedData: Uint8A // Parsing -const gossipTopicRegex = new RegExp("^/eth2/(\\w+)/(\\w+)/(\\w+)"); +const gossipTopicRegex = /^\/eth2\/(\w+)\/(\w+)\/(\w+)/; /** * Parse a `GossipTopic` object from its stringified form. diff --git a/packages/beacon-node/src/network/peers/discover.ts b/packages/beacon-node/src/network/peers/discover.ts index d3bfd2d2aab4..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 @@ -372,7 +371,7 @@ export class PeerDiscovery { if ( this.libp2p.services.components.connectionManager .getDialQueue() - .find((pendingDial) => pendingDial.peerId && pendingDial.peerId.equals(peerId)) + .find((pendingDial) => pendingDial.peerId?.equals(peerId)) ) { return DiscoveredPeerStatus.already_dialing; } @@ -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; @@ -473,7 +472,7 @@ export class PeerDiscovery { /** Check if there is 1+ open connection with this peer */ private isPeerConnected(peerIdStr: PeerIdStr): boolean { const connections = getConnectionsMap(this.libp2p).get(peerIdStr); - return Boolean(connections && connections.value.some((connection) => connection.status === "open")); + return Boolean(connections?.value.some((connection) => connection.status === "open")); } } diff --git a/packages/beacon-node/src/network/peers/peerManager.ts b/packages/beacon-node/src/network/peers/peerManager.ts index 7894b63e0be2..b076285b0d21 100644 --- a/packages/beacon-node/src/network/peers/peerManager.ts +++ b/packages/beacon-node/src/network/peers/peerManager.ts @@ -277,11 +277,14 @@ export class PeerManager { switch (request.method) { case ReqRespMethod.Ping: - return this.onPing(peer, request.body); + this.onPing(peer, request.body); + return; case ReqRespMethod.Goodbye: - return this.onGoodbye(peer, request.body); + this.onGoodbye(peer, request.body); + return; case ReqRespMethod.Status: - return this.onStatus(peer, request.body); + this.onStatus(peer, request.body); + return; } } catch (e) { this.logger.error("Error onRequest handler", {}, e as 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/beaconBlocksMaybeBlobsByRoot.ts b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRoot.ts index b53addab9b43..3d121156d8e6 100644 --- a/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRoot.ts +++ b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRoot.ts @@ -1,5 +1,5 @@ import {ChainForkConfig} from "@lodestar/config"; -import {phase0, deneb} from "@lodestar/types"; +import {phase0, deneb, SignedBeaconBlock} from "@lodestar/types"; import {ForkSeq} from "@lodestar/params"; import {fromHex} from "@lodestar/utils"; import { @@ -64,7 +64,11 @@ export async function unavailableBeaconBlobsByRoot( } // resolve the block if thats unavailable - let block, blobsCache, blockBytes, resolveAvailability, cachedData; + let block: SignedBeaconBlock, + blobsCache: NullBlockInput["cachedData"]["blobsCache"], + blockBytes: Uint8Array | null, + resolveAvailability: NullBlockInput["cachedData"]["resolveAvailability"], + cachedData: NullBlockInput["cachedData"]; if (unavailableBlockInput.block === null) { const allBlocks = await network.sendBeaconBlocksByRoot(peerId, [fromHex(unavailableBlockInput.blockRootHex)]); block = allBlocks[0].data; 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 02d99dd86933..96ae1558ec07 100644 --- a/packages/beacon-node/src/network/reqresp/types.ts +++ b/packages/beacon-node/src/network/reqresp/types.ts @@ -90,16 +90,16 @@ 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} = { [ReqRespMethod.Status]: () => ssz.phase0.Status, [ReqRespMethod.Goodbye]: () => ssz.phase0.Goodbye, [ReqRespMethod.Ping]: () => ssz.phase0.Ping, - [ReqRespMethod.Metadata]: (_, version) => (version == Version.V1 ? ssz.phase0.Metadata : ssz.altair.Metadata), + [ReqRespMethod.Metadata]: (_, version) => (version === Version.V1 ? ssz.phase0.Metadata : ssz.altair.Metadata), [ReqRespMethod.BeaconBlocksByRange]: blocksResponseType, [ReqRespMethod.BeaconBlocksByRoot]: blocksResponseType, [ReqRespMethod.BlobSidecarsByRange]: () => ssz.deneb.BlobSidecar, @@ -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/network/util.ts b/packages/beacon-node/src/network/util.ts index 2be4756fe693..f1d6b917b5e4 100644 --- a/packages/beacon-node/src/network/util.ts +++ b/packages/beacon-node/src/network/util.ts @@ -15,6 +15,7 @@ export function prettyPrintPeerIdStr(id: PeerIdStr): string { */ // Compat function for efficiency reasons export function getConnectionsMap(libp2p: Libp2p): Map { + // biome-ignore lint/complexity/useLiteralKeys: `map` is a private attribute return libp2p.services.components.connectionManager.getConnectionsMap()["map"]; } diff --git a/packages/beacon-node/src/node/nodejs.ts b/packages/beacon-node/src/node/nodejs.ts index 7b42f0daceb2..0e51b15e514b 100644 --- a/packages/beacon-node/src/node/nodejs.ts +++ b/packages/beacon-node/src/node/nodejs.ts @@ -305,7 +305,7 @@ export class BeaconNode { void runNodeNotifier({network, chain, sync, config, logger, signal}); - return new this({ + return new BeaconNode({ opts, config, db, diff --git a/packages/beacon-node/src/node/notifier.ts b/packages/beacon-node/src/node/notifier.ts index 6b9a29817158..20a359a45c49 100644 --- a/packages/beacon-node/src/node/notifier.ts +++ b/packages/beacon-node/src/node/notifier.ts @@ -92,7 +92,7 @@ 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/backfill/backfill.ts b/packages/beacon-node/src/sync/backfill/backfill.ts index f60e28a19e1d..9612cf23b615 100644 --- a/packages/beacon-node/src/sync/backfill/backfill.ts +++ b/packages/beacon-node/src/sync/backfill/backfill.ts @@ -262,7 +262,7 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} // Load a previous finalized or wsCheckpoint slot from DB below anchorSlot const prevFinalizedCheckpointBlock = await extractPreviousFinOrWsCheckpoint(config, db, anchorSlot, logger); - return new this(opts, { + return new BackfillSync(opts, { syncAnchor, backfillStartFromSlot, backfillRangeWrittenSlot, @@ -457,6 +457,7 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} this.status = BackfillSyncStatus.aborted; break; case BackfillSyncErrorCode.NOT_ANCHORED: + // biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here case BackfillSyncErrorCode.NOT_LINEAR: // Lets try to jump directly to the parent of this anchorBlock as previous // (segment) of blocks could be orphaned/missed @@ -674,7 +675,7 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} ); // If possible, read back till anchorBlock > this.prevFinalizedCheckpointBlock - let parentBlock, + let parentBlock: SignedBeaconBlock | null, backCount = 1; let isPrevFinWsConfirmedAnchorParent = false; 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 cc8ddc6eb499..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"); } } @@ -163,6 +163,8 @@ export class BeaconSync implements IBeaconSync { return SyncState.SyncingHead; case RangeSyncStatus.Idle: return SyncState.Stalled; + default: + throw new Error("Unreachable code"); } } diff --git a/packages/beacon-node/src/sync/unknownBlock.ts b/packages/beacon-node/src/sync/unknownBlock.ts index a172b5d723db..003b035a898d 100644 --- a/packages/beacon-node/src/sync/unknownBlock.ts +++ b/packages/beacon-node/src/sync/unknownBlock.ts @@ -15,7 +15,7 @@ import { beaconBlocksMaybeBlobsByRoot, unavailableBeaconBlobsByRoot, } from "../network/reqresp/beaconBlocksMaybeBlobsByRoot.js"; -import {wrapError} from "../util/wrapError.js"; +import {Result, wrapError} from "../util/wrapError.js"; import {PendingBlock, PendingBlockStatus, PendingBlockType} from "./interface.js"; import {getDescendantBlocks, getAllDescendantBlocks, getUnknownAndAncestorBlocks} from "./utils/pendingBlocksTree.js"; import {SyncOptions} from "./options.js"; @@ -168,7 +168,7 @@ export class UnknownBlockSync { blockInputOrRootHex: RootHex | BlockInput | NullBlockInput, peerIdStr?: string ): Exclude { - let blockRootHex; + let blockRootHex: RootHex; let blockInput: BlockInput | NullBlockInput | null; let unknownBlockType: Exclude; @@ -285,7 +285,7 @@ export class UnknownBlockSync { block.status = PendingBlockStatus.fetching; - let res; + let res: Result<{blockInput: BlockInput; peerIdStr: string}>; if (block.blockInput === null) { res = await wrapError(this.fetchUnknownBlockRoot(fromHex(block.blockRootHex), connectedPeers)); } else { @@ -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`); } /** @@ -511,10 +510,10 @@ export class UnknownBlockSync { } const shuffledPeers = shuffle(connectedPeers); - let blockRootHex; - let pendingBlobs; - let blobKzgCommitmentsLen; - let blockRoot; + let blockRootHex: RootHex; + let pendingBlobs: number | undefined; + let blobKzgCommitmentsLen: number | undefined; + let blockRoot: Uint8Array; if (unavailableBlockInput.block === null) { blockRootHex = unavailableBlockInput.blockRootHex; @@ -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 87cca86375f0..247269ab409a 100644 --- a/packages/beacon-node/src/sync/utils/remoteSyncType.ts +++ b/packages/beacon-node/src/sync/utils/remoteSyncType.ts @@ -49,36 +49,33 @@ 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 && + (local.finalizedEpoch + 1 === remote.finalizedEpoch && withinRangeOf(remote.headSlot, local.headSlot, slotImportTolerance)) || // Peer's head is known => SYNCED 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/binarySearch.ts b/packages/beacon-node/src/util/binarySearch.ts index db7c03af50b7..459154eb0427 100644 --- a/packages/beacon-node/src/util/binarySearch.ts +++ b/packages/beacon-node/src/util/binarySearch.ts @@ -1,5 +1,5 @@ export function binarySearchLte(items: T[], value: number, getter: (item: T) => number): T { - if (items.length == 0) { + if (items.length === 0) { throw new ErrorNoValues(); } 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..e89d4e0dfc99 100644 --- a/packages/beacon-node/src/util/kzg.ts +++ b/packages/beacon-node/src/util/kzg.ts @@ -59,7 +59,7 @@ export enum TrustedFileMode { */ export function loadEthereumTrustedSetup(mode: TrustedFileMode = TrustedFileMode.Txt, filePath?: string): void { try { - let setupFilePath; + let setupFilePath: string; if (mode === TrustedFileMode.Bin) { const binPath = filePath ?? TRUSTED_SETUP_BIN_FILEPATH; const bytes = fs.readFileSync(binPath); @@ -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/api/impl/beacon/block/endpoint.test.ts b/packages/beacon-node/test/e2e/api/impl/beacon/block/endpoint.test.ts index ee0b17348099..b8939b54c294 100644 --- a/packages/beacon-node/test/e2e/api/impl/beacon/block/endpoint.test.ts +++ b/packages/beacon-node/test/e2e/api/impl/beacon/block/endpoint.test.ts @@ -14,7 +14,7 @@ import {getDevBeaconNode} from "../../../../../utils/node/beacon.js"; import {BeaconNode} from "../../../../../../src/node/nodejs.js"; import {getConfig} from "../../../../../utils/config.js"; -describe("beacon block api", function () { +describe("beacon block api", () => { vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000}); const restPort = 9596; diff --git a/packages/beacon-node/test/e2e/api/impl/beacon/node/endpoints.test.ts b/packages/beacon-node/test/e2e/api/impl/beacon/node/endpoints.test.ts index 0789932e61e4..6dc01870a844 100644 --- a/packages/beacon-node/test/e2e/api/impl/beacon/node/endpoints.test.ts +++ b/packages/beacon-node/test/e2e/api/impl/beacon/node/endpoints.test.ts @@ -9,7 +9,7 @@ import {getDevBeaconNode} from "../../../../../utils/node/beacon.js"; import {BeaconNode} from "../../../../../../src/node/nodejs.js"; import {getAndInitDevValidators} from "../../../../../utils/node/validator.js"; -describe("beacon node api", function () { +describe("beacon node api", () => { vi.setConfig({testTimeout: 60_000}); const restPort = 9596; diff --git a/packages/beacon-node/test/e2e/api/impl/beacon/state/endpoint.test.ts b/packages/beacon-node/test/e2e/api/impl/beacon/state/endpoint.test.ts index 01423d72341f..d8c87a3ba6b8 100644 --- a/packages/beacon-node/test/e2e/api/impl/beacon/state/endpoint.test.ts +++ b/packages/beacon-node/test/e2e/api/impl/beacon/state/endpoint.test.ts @@ -8,7 +8,7 @@ import {LogLevel, testLogger} from "../../../../../utils/logger.js"; import {getDevBeaconNode} from "../../../../../utils/node/beacon.js"; import {BeaconNode} from "../../../../../../src/node/nodejs.js"; -describe("beacon state api", function () { +describe("beacon state api", () => { const restPort = 9596; const config = createBeaconConfig(chainConfigDef, Buffer.alloc(32, 0xaa)); const validatorCount = 512; diff --git a/packages/beacon-node/test/e2e/api/impl/config.test.ts b/packages/beacon-node/test/e2e/api/impl/config.test.ts index 4bdedfa16391..3ffdbc4beb21 100644 --- a/packages/beacon-node/test/e2e/api/impl/config.test.ts +++ b/packages/beacon-node/test/e2e/api/impl/config.test.ts @@ -14,7 +14,7 @@ const CONSTANT_NAMES_SKIP_LIST = new Set([ "BLOB_SIDECAR_SUBNET_COUNT", ]); -describe("api / impl / config", function () { +describe("api / impl / config", () => { it("Ensure all constants are exposed", async () => { const constantNames = await downloadRemoteConstants(ethereumConsensusSpecsTests.specVersion); diff --git a/packages/beacon-node/test/e2e/api/impl/lightclient/endpoint.test.ts b/packages/beacon-node/test/e2e/api/impl/lightclient/endpoint.test.ts index 8f05ae41c468..effbed19fc2c 100644 --- a/packages/beacon-node/test/e2e/api/impl/lightclient/endpoint.test.ts +++ b/packages/beacon-node/test/e2e/api/impl/lightclient/endpoint.test.ts @@ -13,7 +13,7 @@ import {getAndInitDevValidators} from "../../../../utils/node/validator.js"; import {BeaconNode} from "../../../../../src/node/nodejs.js"; import {waitForEvent} from "../../../../utils/events/resolver.js"; -describe("lightclient api", function () { +describe("lightclient api", () => { const SECONDS_PER_SLOT = 1; const ALTAIR_FORK_EPOCH = 0; const restPort = 9596; @@ -80,7 +80,7 @@ describe("lightclient api", function () { await sleep(2 * SECONDS_PER_SLOT * 1000); }; - it("getLightClientUpdatesByRange()", async function () { + it("getLightClientUpdatesByRange()", async () => { const client = getClient({baseUrl: `http://127.0.0.1:${restPort}`}, {config}).lightclient; await waitForBestUpdate(); const res = await client.getLightClientUpdatesByRange({startPeriod: 0, count: 1}); @@ -91,7 +91,7 @@ describe("lightclient api", function () { expect(res.meta().versions[0]).toBe(ForkName.altair); }); - it("getLightClientOptimisticUpdate()", async function () { + it("getLightClientOptimisticUpdate()", async () => { await waitForBestUpdate(); const client = getClient({baseUrl: `http://127.0.0.1:${restPort}`}, {config}).lightclient; const res = await client.getLightClientOptimisticUpdate(); @@ -105,7 +105,7 @@ describe("lightclient api", function () { expect(res.headers.get(HttpHeader.ExposeHeaders)?.includes("Eth-Consensus-Version")).toBe(true); }); - it.skip("getLightClientFinalityUpdate()", async function () { + it.skip("getLightClientFinalityUpdate()", async () => { // TODO: not sure how this causes subsequent tests failed await waitForEvent(bn.chain.emitter, routes.events.EventType.finalizedCheckpoint, 240000); await sleep(SECONDS_PER_SLOT * 1000); @@ -114,7 +114,7 @@ describe("lightclient api", function () { expect(finalityUpdate).toBeDefined(); }); - it("getLightClientCommitteeRoot() for the 1st period", async function () { + it("getLightClientCommitteeRoot() for the 1st period", async () => { await waitForBestUpdate(); const lightclient = getClient({baseUrl: `http://127.0.0.1:${restPort}`}, {config}).lightclient; diff --git a/packages/beacon-node/test/e2e/api/lodestar/lodestar.test.ts b/packages/beacon-node/test/e2e/api/lodestar/lodestar.test.ts index d505e38b3f9a..bc847b47e9a9 100644 --- a/packages/beacon-node/test/e2e/api/lodestar/lodestar.test.ts +++ b/packages/beacon-node/test/e2e/api/lodestar/lodestar.test.ts @@ -10,10 +10,10 @@ import {waitForEvent} from "../../../utils/events/resolver.js"; import {ClockEvent} from "../../../../src/util/clock.js"; import {BeaconNode} from "../../../../src/index.js"; -describe("api / impl / validator", function () { +describe("api / impl / validator", () => { vi.setConfig({testTimeout: 60_000}); - describe("getLiveness endpoint", function () { + describe("getLiveness endpoint", () => { let bn: BeaconNode | undefined; const SECONDS_PER_SLOT = 2; const ALTAIR_FORK_EPOCH = 0; @@ -30,7 +30,7 @@ describe("api / impl / validator", function () { if (bn) await bn.close(); }); - it("Should return validator indices that are live", async function () { + it("Should return validator indices that are live", async () => { const chainConfig: ChainConfig = {...chainConfigDef, SECONDS_PER_SLOT, ALTAIR_FORK_EPOCH}; const genesisValidatorsRoot = Buffer.alloc(32, 0xaa); const config = createBeaconConfig(chainConfig, genesisValidatorsRoot); @@ -71,7 +71,7 @@ describe("api / impl / validator", function () { ]); }); - it("Should return only for previous, current and next epoch", async function () { + it("Should return only for previous, current and next epoch", async () => { const chainConfig: ChainConfig = {...chainConfigDef, SECONDS_PER_SLOT, ALTAIR_FORK_EPOCH}; const genesisValidatorsRoot = Buffer.alloc(32, 0xaa); const config = createBeaconConfig(chainConfig, genesisValidatorsRoot); diff --git a/packages/beacon-node/test/e2e/chain/bls/multithread.test.ts b/packages/beacon-node/test/e2e/chain/bls/multithread.test.ts index 25f0d5133bcd..a544b3231e87 100644 --- a/packages/beacon-node/test/e2e/chain/bls/multithread.test.ts +++ b/packages/beacon-node/test/e2e/chain/bls/multithread.test.ts @@ -5,23 +5,11 @@ import {BlsMultiThreadWorkerPool} from "../../../../src/chain/bls/multithread/in import {testLogger} from "../../../utils/logger.js"; import {VerifySignatureOpts} from "../../../../src/chain/bls/interface.js"; -describe("chain / bls / multithread queue", function () { +describe("chain / bls / multithread queue", () => { const logger = testLogger(); let controller: AbortController; - beforeEach(() => { - controller = new AbortController(); - }); - afterEach(() => controller.abort()); - const afterEachCallbacks: (() => Promise | void)[] = []; - afterEach(async () => { - while (afterEachCallbacks.length > 0) { - const callback = afterEachCallbacks.pop(); - if (callback) await callback(); - } - }); - const sets: ISignatureSet[] = []; const sameMessageSets: {publicKey: PublicKey; signature: Uint8Array}[] = []; const sameMessage = Buffer.alloc(32, 100); @@ -45,6 +33,19 @@ describe("chain / bls / multithread queue", function () { } }); + beforeEach(() => { + controller = new AbortController(); + }); + + afterEach(async () => { + controller.abort(); + + while (afterEachCallbacks.length > 0) { + const callback = afterEachCallbacks.pop(); + if (callback) await callback(); + } + }); + async function initializePool(): Promise { const pool = new BlsMultiThreadWorkerPool({}, {logger, metrics: null}); // await terminating all workers diff --git a/packages/beacon-node/test/e2e/chain/lightclient.test.ts b/packages/beacon-node/test/e2e/chain/lightclient.test.ts index 5e7b7f36fff2..ed698f2844a1 100644 --- a/packages/beacon-node/test/e2e/chain/lightclient.test.ts +++ b/packages/beacon-node/test/e2e/chain/lightclient.test.ts @@ -14,7 +14,7 @@ import {getDevBeaconNode} from "../../utils/node/beacon.js"; import {getAndInitDevValidators} from "../../utils/node/validator.js"; import {HeadEventData} from "../../../src/chain/index.js"; -describe("chain / lightclient", function () { +describe("chain / lightclient", () => { vi.setConfig({testTimeout: 600_000}); /** @@ -46,7 +46,7 @@ describe("chain / lightclient", function () { } }); - it("Lightclient track head on server configuration", async function () { + it("Lightclient track head on server configuration", async () => { // delay a bit so regular sync sees it's up to date and sync is completed from the beginning // also delay to allow bls workers to be transpiled/initialized const genesisSlotsDelay = 7; @@ -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/e2e/chain/proposerBoostReorg.test.ts b/packages/beacon-node/test/e2e/chain/proposerBoostReorg.test.ts index ad32e2d5b270..fd6af72ad6cb 100644 --- a/packages/beacon-node/test/e2e/chain/proposerBoostReorg.test.ts +++ b/packages/beacon-node/test/e2e/chain/proposerBoostReorg.test.ts @@ -12,7 +12,7 @@ import {getAndInitDevValidators} from "../../utils/node/validator.js"; import {waitForEvent} from "../../utils/events/resolver.js"; import {ReorgEventData} from "../../../src/chain/emitter.js"; -describe("proposer boost reorg", function () { +describe("proposer boost reorg", () => { vi.setConfig({testTimeout: 60000}); const validatorCount = 8; diff --git a/packages/beacon-node/test/e2e/chain/stateCache/nHistoricalStates.test.ts b/packages/beacon-node/test/e2e/chain/stateCache/nHistoricalStates.test.ts index b6c5c30dace4..fcac715e1719 100644 --- a/packages/beacon-node/test/e2e/chain/stateCache/nHistoricalStates.test.ts +++ b/packages/beacon-node/test/e2e/chain/stateCache/nHistoricalStates.test.ts @@ -19,7 +19,7 @@ import {ReorgedForkChoice} from "../../../mocks/fork-choice/reorg.js"; * This includes several tests which make >6 min to pass in CI, so let's only run 1 of them and leave remaining ones * for local investigation. */ -describe("regen/reload states with n-historical states configuration", function () { +describe("regen/reload states with n-historical states configuration", () => { vi.setConfig({testTimeout: 96_000}); const validatorCount = 8; @@ -266,7 +266,7 @@ describe("regen/reload states with n-historical states configuration", function skip, } of testCases) { const wrappedIt = skip ? it.skip : it; - wrappedIt(`${name} reorgedSlot=${reorgedSlot} reorgDistance=${reorgDistance}`, async function () { + wrappedIt(`${name} reorgedSlot=${reorgedSlot} reorgDistance=${reorgDistance}`, async () => { // the node needs time to transpile/initialize bls worker threads const genesisSlotsDelay = 7; const genesisTime = Math.floor(Date.now() / 1000) + genesisSlotsDelay * testParams.SECONDS_PER_SLOT; diff --git a/packages/beacon-node/test/e2e/db/api/beacon/repositories/blockArchive.test.ts b/packages/beacon-node/test/e2e/db/api/beacon/repositories/blockArchive.test.ts index 5ecdc4c8b963..3c7a37e52a8b 100644 --- a/packages/beacon-node/test/e2e/db/api/beacon/repositories/blockArchive.test.ts +++ b/packages/beacon-node/test/e2e/db/api/beacon/repositories/blockArchive.test.ts @@ -4,7 +4,7 @@ import {ssz} from "@lodestar/types"; import {BeaconDb} from "../../../../../../src/db/index.js"; import {startTmpBeaconDb} from "../../../../../utils/db.js"; -describe("BlockArchiveRepository", function () { +describe("BlockArchiveRepository", () => { let db: BeaconDb; const sampleBlock = ssz.phase0.SignedBeaconBlock.defaultValue(); diff --git a/packages/beacon-node/test/e2e/doppelganger/doppelganger.test.ts b/packages/beacon-node/test/e2e/doppelganger/doppelganger.test.ts index bdfcbde056cd..949d0104d641 100644 --- a/packages/beacon-node/test/e2e/doppelganger/doppelganger.test.ts +++ b/packages/beacon-node/test/e2e/doppelganger/doppelganger.test.ts @@ -22,7 +22,7 @@ import {BeaconNode} from "../../../src/node/index.js"; // Attempting to do both 1. and 2. in this e2e test more expensive than necessary. // Unit tests in the validator cover 2., so some test in lodestar package should cover 1. // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("doppelganger / doppelganger test", function () { +describe.skip("doppelganger / doppelganger test", () => { const afterEachCallbacks: (() => Promise | void)[] = []; afterEach(async () => { while (afterEachCallbacks.length > 0) { @@ -77,7 +77,7 @@ describe.skip("doppelganger / doppelganger test", function () { return {beaconNode: bn, validators: validatorsWithDoppelganger}; } - it("should not have doppelganger protection if started before genesis", async function () { + it("should not have doppelganger protection if started before genesis", async () => { const committeeIndex = 0; const validatorIndex = 0; @@ -113,7 +113,7 @@ describe.skip("doppelganger / doppelganger test", function () { ); }); - it("should shut down validator if same key is active and started after genesis", async function () { + it("should shut down validator if same key is active and started after genesis", async () => { // set genesis time to allow at least an epoch const genesisTime = Math.floor(Date.now() / 1000) - SLOTS_PER_EPOCH * beaconParams.SECONDS_PER_SLOT; @@ -149,7 +149,7 @@ describe.skip("doppelganger / doppelganger test", function () { ); }); - it("should shut down validator if same key is active with same BN and started after genesis", async function () { + it("should shut down validator if same key is active with same BN and started after genesis", async () => { const doppelgangerProtection = true; const testLoggerOpts: TestLoggerOpts = {level: LogLevel.info}; @@ -194,7 +194,7 @@ describe.skip("doppelganger / doppelganger test", function () { ); }); - it("should not shut down validator if key is different", async function () { + it("should not shut down validator if key is different", async () => { const doppelgangerProtection = true; const {beaconNode: bn, validators: validatorsWithDoppelganger} = await createBNAndVC({ @@ -227,7 +227,7 @@ describe.skip("doppelganger / doppelganger test", function () { ); }); - it("should not sign block if doppelganger period has not passed and not started at genesis", async function () { + it("should not sign block if doppelganger period has not passed and not started at genesis", async () => { const doppelgangerProtection = true; // set genesis time to allow at least an epoch @@ -258,7 +258,7 @@ describe.skip("doppelganger / doppelganger test", function () { ).resolves.toBeUndefined(); }); - it("should not sign attestations if doppelganger period has not passed and started after genesis", async function () { + it("should not sign attestations if doppelganger period has not passed and started after genesis", async () => { const doppelgangerProtection = true; // set genesis time to allow at least an epoch diff --git a/packages/beacon-node/test/e2e/eth1/eth1ForBlockProduction.test.ts b/packages/beacon-node/test/e2e/eth1/eth1ForBlockProduction.test.ts index 837a765d1710..21cadeb55d2c 100644 --- a/packages/beacon-node/test/e2e/eth1/eth1ForBlockProduction.test.ts +++ b/packages/beacon-node/test/e2e/eth1/eth1ForBlockProduction.test.ts @@ -25,7 +25,7 @@ const pyrmontDepositsDataRoot = [ ]; // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("eth1 / Eth1Provider", function () { +describe.skip("eth1 / Eth1Provider", () => { const controller = new AbortController(); const config = getTestnetConfig(); @@ -48,7 +48,7 @@ describe.skip("eth1 / Eth1Provider", function () { await LevelDbController.destroy(dbLocation); }); - it("Should fetch real Pyrmont eth1 data for block proposing", async function () { + it("Should fetch real Pyrmont eth1 data for block proposing", async () => { const eth1Options: Eth1Options = { enabled: true, providerUrls: [getGoerliRpcUrl()], diff --git a/packages/beacon-node/test/e2e/eth1/eth1MergeBlockTracker.test.ts b/packages/beacon-node/test/e2e/eth1/eth1MergeBlockTracker.test.ts index 034493482c21..9423bb716b3f 100644 --- a/packages/beacon-node/test/e2e/eth1/eth1MergeBlockTracker.test.ts +++ b/packages/beacon-node/test/e2e/eth1/eth1MergeBlockTracker.test.ts @@ -14,7 +14,7 @@ import {getGoerliRpcUrl} from "../../testParams.js"; // It's OKAY to disable temporarily since this functionality is tested indirectly by the sim merge tests. // See https://github.com/ChainSafe/lodestar/issues/4197 // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("eth1 / Eth1MergeBlockTracker", function () { +describe.skip("eth1 / Eth1MergeBlockTracker", () => { const logger = testLogger(); function getConfig(ttd: bigint): ChainConfig { diff --git a/packages/beacon-node/test/e2e/eth1/eth1Provider.test.ts b/packages/beacon-node/test/e2e/eth1/eth1Provider.test.ts index 8b7e9503485e..606845f40337 100644 --- a/packages/beacon-node/test/e2e/eth1/eth1Provider.test.ts +++ b/packages/beacon-node/test/e2e/eth1/eth1Provider.test.ts @@ -8,7 +8,7 @@ import {Eth1Block} from "../../../src/eth1/interface.js"; import {getGoerliRpcUrl} from "../../testParams.js"; // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("eth1 / Eth1Provider", function () { +describe.skip("eth1 / Eth1Provider", () => { let controller: AbortController; beforeEach(() => { controller = new AbortController(); @@ -28,16 +28,16 @@ describe.skip("eth1 / Eth1Provider", function () { return new Eth1Provider(config, eth1Options, controller.signal); } - it("Should validate contract", async function () { + it("Should validate contract", async () => { await getEth1Provider().validateContract(); }); - it("Should get latest block number", async function () { + it("Should get latest block number", async () => { const blockNumber = await getEth1Provider().getBlockNumber(); expect(blockNumber).toBeGreaterThan(0); }); - it("Should get a specific block by number", async function () { + it("Should get a specific block by number", async () => { const goerliGenesisBlock: Eth1Block = { blockHash: fromHexString("0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a"), blockNumber: 0, @@ -47,7 +47,7 @@ describe.skip("eth1 / Eth1Provider", function () { expect(block && parseEth1Block(block)).toEqual(goerliGenesisBlock); }); - it("Should get deposits events for a block range", async function () { + it("Should get deposits events for a block range", async () => { const blockNumbers = goerliTestnetDepositEvents.map((log) => log.blockNumber); const fromBlock = Math.min(...blockNumbers); const toBlock = Math.min(...blockNumbers); @@ -74,26 +74,26 @@ describe.skip("eth1 / Eth1Provider", function () { code: "0x60806040526004361061003f5760003560e01c806301ffc9a71461004457806322895118146100a", }; - it("getBlocksByNumber: Should fetch a block range", async function () { + it("getBlocksByNumber: Should fetch a block range", async () => { const fromBlock = firstGoerliBlocks[0].blockNumber; const toBlock = firstGoerliBlocks[firstGoerliBlocks.length - 1].blockNumber; const blocks = await getEth1Provider().getBlocksByNumber(fromBlock, toBlock); expect(blocks.map(parseEth1Block)).toEqual(firstGoerliBlocks); }); - it("getBlockByNumber: Should fetch a single block", async function () { + it("getBlockByNumber: Should fetch a single block", async () => { const firstGoerliBlock = firstGoerliBlocks[0]; const block = await getEth1Provider().getBlockByNumber(firstGoerliBlock.blockNumber); expect(block && parseEth1Block(block)).toEqual(firstGoerliBlock); }); - it("getBlockNumber: Should fetch latest block number", async function () { + it("getBlockNumber: Should fetch latest block number", async () => { const blockNumber = await getEth1Provider().getBlockNumber(); expect(blockNumber).toBeInstanceOf(Number); expect(blockNumber).toBeGreaterThan(0); }); - it("getCode: Should fetch code for a contract", async function () { + it("getCode: Should fetch code for a contract", async () => { const code = await getEth1Provider().getCode(goerliSampleContract.address); expect(code).toEqual(expect.arrayContaining([goerliSampleContract.code])); }); diff --git a/packages/beacon-node/test/e2e/eth1/jsonRpcHttpClient.test.ts b/packages/beacon-node/test/e2e/eth1/jsonRpcHttpClient.test.ts index fac0e3810b6d..bc41b5f1c546 100644 --- a/packages/beacon-node/test/e2e/eth1/jsonRpcHttpClient.test.ts +++ b/packages/beacon-node/test/e2e/eth1/jsonRpcHttpClient.test.ts @@ -7,7 +7,7 @@ import {JsonRpcHttpClient} from "../../../src/eth1/provider/jsonRpcHttpClient.js import {getGoerliRpcUrl} from "../../testParams.js"; import {RpcPayload} from "../../../src/eth1/interface.js"; -describe("eth1 / jsonRpcHttpClient", function () { +describe("eth1 / jsonRpcHttpClient", () => { vi.setConfig({testTimeout: 10_000}); const port = 36421; @@ -113,7 +113,7 @@ describe("eth1 / jsonRpcHttpClient", function () { const afterHooks: (() => Promise)[] = []; - afterEach(async function () { + afterEach(async () => { while (afterHooks.length) { const afterHook = afterHooks.pop(); if (afterHook) await afterHook(); @@ -124,7 +124,7 @@ describe("eth1 / jsonRpcHttpClient", function () { const {id, requestListener, abort, timeout} = testCase; let {url, payload} = testCase; - it(id, async function () { + it(id, async () => { if (requestListener) { if (!url) url = `http://localhost:${port}`; @@ -162,14 +162,14 @@ describe("eth1 / jsonRpcHttpClient", function () { } }); -describe("eth1 / jsonRpcHttpClient - with retries", function () { +describe("eth1 / jsonRpcHttpClient - with retries", () => { vi.setConfig({testTimeout: 10_000}); const port = 36421; const noMethodError = {code: -32601, message: "Method not found"}; const afterHooks: (() => Promise)[] = []; - afterEach(async function () { + afterEach(async () => { while (afterHooks.length) { const afterHook = afterHooks.pop(); if (afterHook) @@ -179,7 +179,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { } }); - it("should retry ENOTFOUND", async function () { + it("should retry ENOTFOUND", async () => { let retryCount = 0; const url = "https://goerli.fake-website.io"; @@ -201,7 +201,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { expect(retryCount).toBeWithMessage(retries, "ENOTFOUND should be retried before failing"); }); - it("should retry ECONNREFUSED", async function () { + it("should retry ECONNREFUSED", async () => { let retryCount = 0; const url = `http://localhost:${port + 1}`; @@ -223,7 +223,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { expect(retryCount).toBeWithMessage(retries, "code ECONNREFUSED should be retried before failing"); }); - it("should retry 404", async function () { + it("should retry 404", async () => { let requestCount = 0; const server = http.createServer((req, res) => { @@ -253,7 +253,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { expect(requestCount).toBeWithMessage(retries + 1, "404 responses should be retried before failing"); }); - it("should retry timeout", async function () { + it("should retry timeout", async () => { let requestCount = 0; const server = http.createServer(async () => { @@ -284,7 +284,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { expect(requestCount).toBeWithMessage(retries + 1, "Timeout request should be retried before failing"); }); - it("should not retry aborted", async function () { + it("should not retry aborted", async () => { let requestCount = 0; const server = http.createServer(() => { requestCount++; @@ -314,7 +314,7 @@ describe("eth1 / jsonRpcHttpClient - with retries", function () { expect(requestCount).toBeWithMessage(1, "Aborted request should not be retried"); }); - it("should not retry payload error", async function () { + it("should not retry payload error", async () => { let requestCount = 0; const server = http.createServer((req, res) => { diff --git a/packages/beacon-node/test/e2e/eth1/stream.test.ts b/packages/beacon-node/test/e2e/eth1/stream.test.ts index a683e885b453..ce65d4353f0e 100644 --- a/packages/beacon-node/test/e2e/eth1/stream.test.ts +++ b/packages/beacon-node/test/e2e/eth1/stream.test.ts @@ -6,7 +6,7 @@ import {getGoerliRpcUrl} from "../../testParams.js"; import {Eth1Options} from "../../../src/eth1/options.js"; // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("Eth1 streams", function () { +describe.skip("Eth1 streams", () => { let controller: AbortController; beforeEach(() => { controller = new AbortController(); @@ -30,7 +30,7 @@ describe.skip("Eth1 streams", function () { const depositsToFetch = 1000; const eth1Params = {...config, maxBlocksPerPoll}; - it(`Should fetch ${depositsToFetch} deposits with getDepositsStream`, async function () { + it(`Should fetch ${depositsToFetch} deposits with getDepositsStream`, async () => { const depositsStream = getDepositsStream( medallaTestnetConfig.blockWithDepositActivity, getEth1Provider(), @@ -49,7 +49,7 @@ describe.skip("Eth1 streams", function () { expect(depositCount).toBeGreaterThan(depositsToFetch); }); - it(`Should fetch ${depositsToFetch} deposits with getDepositsAndBlockStreamForGenesis`, async function () { + it(`Should fetch ${depositsToFetch} deposits with getDepositsAndBlockStreamForGenesis`, async () => { const stream = getDepositsAndBlockStreamForGenesis( medallaTestnetConfig.blockWithDepositActivity, getEth1Provider(), diff --git a/packages/beacon-node/test/e2e/network/gossipsub.test.ts b/packages/beacon-node/test/e2e/network/gossipsub.test.ts index 3d8b1e07bbd7..29a745455561 100644 --- a/packages/beacon-node/test/e2e/network/gossipsub.test.ts +++ b/packages/beacon-node/test/e2e/network/gossipsub.test.ts @@ -8,7 +8,7 @@ import {GossipType, GossipHandlers, GossipHandlerParamGeneric} from "../../../sr import {getNetworkForTest} from "../../utils/networkWithMockDb.js"; import {connect, onPeerConnect} from "../../utils/network.js"; -describe("gossipsub / main thread", function () { +describe("gossipsub / main thread", () => { vi.setConfig({testTimeout: 3000}); runTests({useWorker: false}); @@ -19,7 +19,7 @@ describe("gossipsub / main thread", function () { * Since we use vitest to run tests in parallel, including this causes the test to be unstable. * See https://github.com/ChainSafe/lodestar/issues/6358 */ -describe.skip("gossipsub / worker", function () { +describe.skip("gossipsub / worker", () => { vi.setConfig({testTimeout: 3000}); runTests({useWorker: true}); @@ -61,7 +61,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { return {netA, netB}; } - it("Publish and receive a voluntaryExit", async function () { + it("Publish and receive a voluntaryExit", async () => { let onVoluntaryExit: (ve: Uint8Array) => void; const onVoluntaryExitPromise = new Promise((resolve) => { onVoluntaryExit = resolve; @@ -98,7 +98,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("Publish and receive a blsToExecutionChange", async function () { + it("Publish and receive a blsToExecutionChange", async () => { let onBlsToExecutionChange: (blsToExec: Uint8Array) => void; const onBlsToExecutionChangePromise = new Promise((resolve) => { onBlsToExecutionChange = resolve; @@ -136,7 +136,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("Publish and receive an attesterSlashing", async function () { + it("Publish and receive an attesterSlashing", async () => { let onAttesterSlashingChange: (payload: Uint8Array) => void; const onAttesterSlashingChangePromise = new Promise((resolve) => { onAttesterSlashingChange = resolve; @@ -170,7 +170,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { expect(Buffer.from(received)).toEqual(Buffer.from(ssz.phase0.AttesterSlashing.serialize(attesterSlashing))); }); - it("Publish and receive a proposerSlashing", async function () { + it("Publish and receive a proposerSlashing", async () => { let onProposerSlashingChange: (payload: Uint8Array) => void; const onProposerSlashingChangePromise = new Promise((resolve) => { onProposerSlashingChange = resolve; @@ -204,7 +204,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { expect(Buffer.from(received)).toEqual(Buffer.from(ssz.phase0.ProposerSlashing.serialize(proposerSlashing))); }); - it("Publish and receive a LightClientOptimisticUpdate", async function () { + it("Publish and receive a LightClientOptimisticUpdate", async () => { let onLightClientOptimisticUpdate: (ou: Uint8Array) => void; const onLightClientOptimisticUpdatePromise = new Promise((resolve) => { onLightClientOptimisticUpdate = resolve; @@ -243,7 +243,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("Publish and receive a LightClientFinalityUpdate", async function () { + it("Publish and receive a LightClientFinalityUpdate", async () => { let onLightClientFinalityUpdate: (fu: Uint8Array) => void; const onLightClientFinalityUpdatePromise = new Promise((resolve) => { onLightClientFinalityUpdate = resolve; diff --git a/packages/beacon-node/test/e2e/network/mdns.test.ts b/packages/beacon-node/test/e2e/network/mdns.test.ts index 5c796df985b9..6a1be8094137 100644 --- a/packages/beacon-node/test/e2e/network/mdns.test.ts +++ b/packages/beacon-node/test/e2e/network/mdns.test.ts @@ -21,18 +21,19 @@ let port = 9000; const mu = "/ip4/127.0.0.1/tcp/0"; // https://github.com/ChainSafe/lodestar/issues/5967 -describe.skip("mdns", function () { +describe.skip("mdns", () => { const afterEachCallbacks: (() => Promise | void)[] = []; - afterEach(async () => { - await Promise.all(afterEachCallbacks.map((cb) => cb())); - afterEachCallbacks.splice(0, afterEachCallbacks.length); - }); - let controller: AbortController; + beforeEach(() => { controller = new AbortController(); }); - afterEach(() => controller.abort()); + + afterEach(async () => { + await Promise.all(afterEachCallbacks.map((cb) => cb())); + afterEachCallbacks.splice(0, afterEachCallbacks.length); + controller.abort(); + }); async function getOpts(privateKey: PrivateKey): Promise { const bindAddrUdp = `/ip4/0.0.0.0/udp/${port++}`; @@ -114,7 +115,7 @@ describe.skip("mdns", function () { return Promise.all([createTestNode("mdns-A"), createTestNode("mdns-B")]); } - it("should connect two peers on a LAN", async function () { + it("should connect two peers on a LAN", async () => { const [{network: netA}, {network: netB}] = await createTestNodesAB(); await Promise.all([onPeerConnect(netA), onPeerConnect(netB)]); expect(netA.getConnectedPeerCount()).toBe(1); diff --git a/packages/beacon-node/test/e2e/network/network.test.ts b/packages/beacon-node/test/e2e/network/network.test.ts index a1c1546ef4fc..2435b005efa1 100644 --- a/packages/beacon-node/test/e2e/network/network.test.ts +++ b/packages/beacon-node/test/e2e/network/network.test.ts @@ -9,13 +9,13 @@ import {connect, disconnect, onPeerConnect, onPeerDisconnect} from "../../utils/ import {getNetworkForTest} from "../../utils/networkWithMockDb.js"; import {getValidPeerId} from "../../utils/peer.js"; -describe("network / main thread", function () { +describe("network / main thread", () => { vi.setConfig({testTimeout: 3000}); runTests({useWorker: false}); }); -describe("network / worker", function () { +describe("network / worker", () => { vi.setConfig({testTimeout: 10_000}); runTests({useWorker: true}); @@ -66,14 +66,14 @@ function runTests({useWorker}: {useWorker: boolean}): void { expect(networkIdentity.peerId).toBe(network.peerId.toString()); }); - it("should create a peer on connect", async function () { + it("should create a peer on connect", async () => { const [netA, netB] = await createTestNodesAB(); await Promise.all([onPeerConnect(netA), onPeerConnect(netB), connect(netA, netB)]); expect(netA.getConnectedPeerCount()).toBe(1); expect(netB.getConnectedPeerCount()).toBe(1); }); - it("should delete a peer on disconnect", async function () { + it("should delete a peer on disconnect", async () => { const [netA, netB] = await createTestNodesAB(); const connected = Promise.all([onPeerConnect(netA), onPeerConnect(netB)]); await connect(netA, netB); @@ -92,9 +92,9 @@ function runTests({useWorker}: {useWorker: boolean}): void { // Current implementation of discv5 consumer doesn't allow to deterministically force a peer to be found // a random find node lookup can yield no results if there are too few peers in the DHT - it.todo("should connect to new peer by subnet", async function () {}); + it.todo("should connect to new peer by subnet", async () => {}); - it("Should goodbye peers on stop", async function () { + it("Should goodbye peers on stop", async () => { const [netA, netB] = await createTestNodesAB(); const connected = Promise.all([onPeerConnect(netA), onPeerConnect(netB)]); diff --git a/packages/beacon-node/test/e2e/network/onWorker/dataSerialization.test.ts b/packages/beacon-node/test/e2e/network/onWorker/dataSerialization.test.ts index 09c74f1f5dfe..741fd4b46696 100644 --- a/packages/beacon-node/test/e2e/network/onWorker/dataSerialization.test.ts +++ b/packages/beacon-node/test/e2e/network/onWorker/dataSerialization.test.ts @@ -30,7 +30,7 @@ import {CommitteeSubscription} from "../../../../src/network/subnets/interface.j import {EchoWorker, getEchoWorker} from "./workerEchoHandler.js"; // TODO: Need to find the way to load the echoWorker in the test environment -describe.skip("data serialization through worker boundary", function () { +describe.skip("data serialization through worker boundary", () => { let echoWorker: EchoWorker; beforeAll(async () => { diff --git a/packages/beacon-node/test/e2e/network/peers/peerManager.test.ts b/packages/beacon-node/test/e2e/network/peers/peerManager.test.ts index e872a3882945..b46e151cadb3 100644 --- a/packages/beacon-node/test/e2e/network/peers/peerManager.test.ts +++ b/packages/beacon-node/test/e2e/network/peers/peerManager.test.ts @@ -22,7 +22,7 @@ import {LocalStatusCache} from "../../../../src/network/statusCache.js"; const logger = testLogger("peerManager"); -describe("network / peers / PeerManager", function () { +describe("network / peers / PeerManager", () => { const peerId1 = getValidPeerId(); const afterEachCallbacks: (() => Promise | void)[] = []; @@ -156,7 +156,7 @@ describe("network / peers / PeerManager", function () { remotePeer: peerId1, } as Connection; - it("Should emit peer connected event on relevant peer status", async function () { + it("Should emit peer connected event on relevant peer status", async () => { const {statusCache, libp2p, networkEventBus} = await mockModules(); // Simualate a peer connection, get() should return truthy @@ -175,7 +175,7 @@ describe("network / peers / PeerManager", function () { await peerConnectedPromise; }); - it("On peerConnect handshake flow", async function () { + it("On peerConnect handshake flow", async () => { const {statusCache, libp2p, reqResp, peerManager, networkEventBus} = await mockModules(); // Simualate a peer connection, get() should return truthy diff --git a/packages/beacon-node/test/e2e/network/reqresp.test.ts b/packages/beacon-node/test/e2e/network/reqresp.test.ts index a3c8b7b66ca0..b7ab190166e7 100644 --- a/packages/beacon-node/test/e2e/network/reqresp.test.ts +++ b/packages/beacon-node/test/e2e/network/reqresp.test.ts @@ -15,13 +15,13 @@ import {PeerIdStr} from "../../../src/util/peerId.js"; /* eslint-disable require-yield, @typescript-eslint/naming-convention */ -describe("network / reqresp / main thread", function () { +describe("network / reqresp / main thread", () => { vi.setConfig({testTimeout: 3000}); runTests({useWorker: false}); }); -describe("network / reqresp / worker", function () { +describe("network / reqresp / worker", () => { vi.setConfig({testTimeout: 30_000}); runTests({useWorker: true}); @@ -76,7 +76,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { return [netA, netB, await getPeerIdOf(netA), await getPeerIdOf(netB)]; } - it("should send/receive signed blocks", async function () { + it("should send/receive signed blocks", async () => { const req: phase0.BeaconBlocksByRangeRequest = {startSlot: 0, step: 1, count: 2}; const blocks: phase0.SignedBeaconBlock[] = []; for (let slot = req.startSlot; slot < req.count; slot++) { @@ -106,7 +106,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { } }); - it("should send/receive a light client bootstrap message", async function () { + it("should send/receive a light client bootstrap message", async () => { const root: Root = ssz.phase0.BeaconBlockHeader.defaultValue().bodyRoot; const expectedValue = ssz.altair.LightClientBootstrap.defaultValue(); @@ -128,7 +128,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("should send/receive a light client optimistic update message", async function () { + it("should send/receive a light client optimistic update message", async () => { const expectedValue = ssz.altair.LightClientOptimisticUpdate.defaultValue(); const [netA, _, _0, peerIdB] = await createAndConnectPeers( @@ -149,7 +149,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("should send/receive a light client finality update message", async function () { + it("should send/receive a light client finality update message", async () => { const expectedValue = ssz.altair.LightClientFinalityUpdate.defaultValue(); const [netA, _, _0, peerIdB] = await createAndConnectPeers( @@ -170,7 +170,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("should send/receive a light client update message", async function () { + it("should send/receive a light client update message", async () => { const req: altair.LightClientUpdatesByRange = {startPeriod: 0, count: 2}; const lightClientUpdates: ResponseOutgoing[] = []; for (let slot = req.startPeriod; slot < req.count; slot++) { @@ -201,10 +201,11 @@ function runTests({useWorker}: {useWorker: boolean}): void { } }); - it("should handle a server error", async function () { + it("should handle a server error", async () => { const testErrorMessage = "TEST_EXAMPLE_ERROR_1234"; const [netA, _, _0, peerIdB] = await createAndConnectPeers( (method) => + // biome-ignore lint/correctness/useYield: No need for yield in test context async function* onRequest() { if (method === ReqRespMethod.BeaconBlocksByRange) { throw Error(testErrorMessage); @@ -218,7 +219,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("should handle a server error after emitting two blocks", async function () { + it("should handle a server error after emitting two blocks", async () => { const testErrorMessage = "TEST_EXAMPLE_ERROR_1234"; const [netA, _, _0, peerIdB] = await createAndConnectPeers( @@ -241,7 +242,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("trigger a TTFB_TIMEOUT error", async function () { + it("trigger a TTFB_TIMEOUT error", async () => { const ttfbTimeoutMs = 250; const [netA, _, _0, peerIdB] = await createAndConnectPeers( @@ -262,7 +263,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("trigger a RESP_TIMEOUT error", async function () { + it("trigger a RESP_TIMEOUT error", async () => { const respTimeoutMs = 250; const [netA, _, _0, peerIdB] = await createAndConnectPeers( @@ -284,9 +285,10 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("Sleep infinite on first byte", async function () { + it("Sleep infinite on first byte", async () => { const [netA, _, _0, peerIdB] = await createAndConnectPeers( (method) => + // biome-ignore lint/correctness/useYield: No need for yield in test context async function* onRequest() { if (method === ReqRespMethod.BeaconBlocksByRange) { await sleep(100000000); @@ -301,7 +303,7 @@ function runTests({useWorker}: {useWorker: boolean}): void { ); }); - it("Sleep infinite on second response chunk", async function () { + it("Sleep infinite on second response chunk", async () => { const [netA, _, _0, peerIdB] = await createAndConnectPeers( (method) => async function* onRequest() { diff --git a/packages/beacon-node/test/e2e/network/reqrespEncode.test.ts b/packages/beacon-node/test/e2e/network/reqrespEncode.test.ts index 123a4da420f0..eb994d2e848c 100644 --- a/packages/beacon-node/test/e2e/network/reqrespEncode.test.ts +++ b/packages/beacon-node/test/e2e/network/reqrespEncode.test.ts @@ -53,6 +53,7 @@ describe("reqresp encoder", () => { const {libp2p, multiaddr} = await getLibp2p(); const getHandlerNoop: GetReqRespHandlerFn = () => + // biome-ignore lint/correctness/useYield: No need for yield in test context async function* (): AsyncIterable { throw Error("not implemented"); }; diff --git a/packages/beacon-node/test/e2e/sync/finalizedSync.test.ts b/packages/beacon-node/test/e2e/sync/finalizedSync.test.ts index ed19617f0822..ba98f2a1facd 100644 --- a/packages/beacon-node/test/e2e/sync/finalizedSync.test.ts +++ b/packages/beacon-node/test/e2e/sync/finalizedSync.test.ts @@ -14,7 +14,7 @@ import {ChainEvent} from "../../../src/chain/index.js"; import {connect, onPeerConnect} from "../../utils/network.js"; import {testLogger, LogLevel, TestLoggerOpts} from "../../utils/logger.js"; -describe("sync / finalized sync", function () { +describe("sync / finalized sync", () => { // chain is finalized at slot 32, plus 4 slots for genesis delay => ~72s it should sync pretty fast vi.setConfig({testTimeout: 90_000}); @@ -31,7 +31,7 @@ describe("sync / finalized sync", function () { } }); - it("should do a finalized sync from another BN", async function () { + it("should do a finalized sync from another BN", async () => { // single node at beginning, use main thread to verify bls const genesisSlotsDelay = 4; const genesisTime = Math.floor(Date.now() / 1000) + genesisSlotsDelay * testParams.SECONDS_PER_SLOT; diff --git a/packages/beacon-node/test/e2e/sync/unknownBlockSync.test.ts b/packages/beacon-node/test/e2e/sync/unknownBlockSync.test.ts index 7d31d25a07d3..290213d2b1ee 100644 --- a/packages/beacon-node/test/e2e/sync/unknownBlockSync.test.ts +++ b/packages/beacon-node/test/e2e/sync/unknownBlockSync.test.ts @@ -17,7 +17,7 @@ import {testLogger, LogLevel, TestLoggerOpts} from "../../utils/logger.js"; import {BlockError, BlockErrorCode} from "../../../src/chain/errors/index.js"; import {BlockSource, getBlockInput} from "../../../src/chain/blocks/types.js"; -describe("sync / unknown block sync", function () { +describe("sync / unknown block sync", () => { vi.setConfig({testTimeout: 40_000}); const validatorCount = 8; @@ -45,7 +45,7 @@ describe("sync / unknown block sync", function () { ]; for (const {id, event} of testCases) { - it(id, async function () { + it(id, async () => { // the node needs time to transpile/initialize bls worker threads const genesisSlotsDelay = 4; const genesisTime = Math.floor(Date.now() / 1000) + genesisSlotsDelay * testParams.SECONDS_PER_SLOT; diff --git a/packages/beacon-node/test/memory/unfinalizedPubkey2Index.ts b/packages/beacon-node/test/memory/unfinalizedPubkey2Index.ts index 247f8a4ea95a..1a317a7fe9d3 100644 --- a/packages/beacon-node/test/memory/unfinalizedPubkey2Index.ts +++ b/packages/beacon-node/test/memory/unfinalizedPubkey2Index.ts @@ -1,4 +1,5 @@ import crypto from "node:crypto"; +// biome-ignore lint/suspicious/noShadowRestrictedNames: We explicitly want `Map` name to be imported import {Map} from "immutable"; import {ValidatorIndex} from "@lodestar/types"; import {toMemoryEfficientHexStr} from "@lodestar/state-transition/src/cache/pubkeyCache.js"; diff --git a/packages/beacon-node/test/perf/bls/bls.test.ts b/packages/beacon-node/test/perf/bls/bls.test.ts index 988052f4a95c..9f1f90a4d879 100644 --- a/packages/beacon-node/test/perf/bls/bls.test.ts +++ b/packages/beacon-node/test/perf/bls/bls.test.ts @@ -11,7 +11,7 @@ import { } from "@chainsafe/blst"; import {linspace} from "../../../src/util/numpy.js"; -describe("BLS ops", function () { +describe("BLS ops", () => { type Keypair = {publicKey: PublicKey; secretKey: SecretKey}; // signature needs to be in Uint8Array to match real situation type BlsSet = {publicKey: PublicKey; message: Uint8Array; signature: Uint8Array}; diff --git a/packages/beacon-node/test/perf/chain/seenCache/seenAggregateAndProof.test.ts b/packages/beacon-node/test/perf/chain/seenCache/seenAggregateAndProof.test.ts index 8ba77ca8692f..49c3123c14dd 100644 --- a/packages/beacon-node/test/perf/chain/seenCache/seenAggregateAndProof.test.ts +++ b/packages/beacon-node/test/perf/chain/seenCache/seenAggregateAndProof.test.ts @@ -3,7 +3,7 @@ import {BitArray} from "@chainsafe/ssz"; import {TARGET_AGGREGATORS_PER_COMMITTEE} from "@lodestar/params"; import {SeenAggregatedAttestations} from "../../../../src/chain/seenCache/seenAggregateAndProof.js"; -describe("SeenAggregatedAttestations perf test", function () { +describe("SeenAggregatedAttestations perf test", () => { const targetEpoch = 2022; const attDataRoot = "0x55e1a1cce2aeb66f85b2285b8cb7aa55dfb67148b5e0067f0692b61ddbd2824b"; const fullByte = 0b11111111; diff --git a/packages/beacon-node/test/perf/chain/stateCache/inMemoryCheckpointsCache.test.ts b/packages/beacon-node/test/perf/chain/stateCache/inMemoryCheckpointsCache.test.ts index 3a4774655e7f..17a46b09af8d 100644 --- a/packages/beacon-node/test/perf/chain/stateCache/inMemoryCheckpointsCache.test.ts +++ b/packages/beacon-node/test/perf/chain/stateCache/inMemoryCheckpointsCache.test.ts @@ -4,7 +4,7 @@ import {ssz, phase0} from "@lodestar/types"; import {generateCachedState} from "../../../utils/state.js"; import {InMemoryCheckpointStateCache, toCheckpointHex} from "../../../../src/chain/stateCache/index.js"; -describe("InMemoryCheckpointStateCache perf tests", function () { +describe("InMemoryCheckpointStateCache perf tests", () => { setBenchOpts({noThreshold: true}); let state: CachedBeaconStateAllForks; diff --git a/packages/beacon-node/test/perf/chain/stateCache/updateUnfinalizedPubkeys.test.ts b/packages/beacon-node/test/perf/chain/stateCache/updateUnfinalizedPubkeys.test.ts index eab66d2bee53..a4bdbe9710cb 100644 --- a/packages/beacon-node/test/perf/chain/stateCache/updateUnfinalizedPubkeys.test.ts +++ b/packages/beacon-node/test/perf/chain/stateCache/updateUnfinalizedPubkeys.test.ts @@ -15,7 +15,7 @@ import {generateCachedElectraState} from "../../../utils/state.js"; // ✔ updateUnfinalizedPubkeys - updating 10 pubkeys 1444.173 ops/s 692.4380 us/op - 1057 runs 6.03 s // ✔ updateUnfinalizedPubkeys - updating 100 pubkeys 189.5965 ops/s 5.274358 ms/op - 57 runs 1.15 s // ✔ updateUnfinalizedPubkeys - updating 1000 pubkeys 12.90495 ops/s 77.48967 ms/op - 13 runs 1.62 s -describe("updateUnfinalizedPubkeys perf tests", function () { +describe("updateUnfinalizedPubkeys perf tests", () => { setBenchOpts({noThreshold: true}); const numPubkeysToBeFinalizedCases = [10, 100, 1000]; diff --git a/packages/beacon-node/test/perf/chain/verifyImportBlocks.test.ts b/packages/beacon-node/test/perf/chain/verifyImportBlocks.test.ts index 6ae7112f5e3d..cd4d61b173c7 100644 --- a/packages/beacon-node/test/perf/chain/verifyImportBlocks.test.ts +++ b/packages/beacon-node/test/perf/chain/verifyImportBlocks.test.ts @@ -28,13 +28,22 @@ describe.skip("verify+import blocks - range sync perf test", () => { yieldEventLoopAfterEach: true, // So SubTree(s)'s WeakRef can be garbage collected https://github.com/nodejs/node/issues/39902 }); - before("Check correct params", () => { + let db: BeaconDb; + + before("Check correct params", async () => { // Must start at the first slot of the epoch to have a proper checkpoint state. // Using `computeStartSlotAtEpoch(...) - 1` will cause the chain to initialize with a state that's not the checkpoint // state, so processing the first block of the epoch will cause error `BLOCK_ERROR_WOULD_REVERT_FINALIZED_SLOT` if (rangeSyncTest.startSlot % SLOTS_PER_EPOCH !== 0) { throw Error("startSlot must be the first slot in the epoch"); } + + db = new BeaconDb(config, await LevelDbController.create({name: ".tmpdb"}, {logger})); + }); + + after(async () => { + // If before blocks fail, db won't be declared + if (db !== undefined) await db.close(); }); const blocks = beforeValue( @@ -57,15 +66,6 @@ describe.skip("verify+import blocks - range sync perf test", () => { return state; }, timeoutInfura); - let db: BeaconDb; - before(async () => { - db = new BeaconDb(config, await LevelDbController.create({name: ".tmpdb"}, {logger})); - }); - after(async () => { - // If before blocks fail, db won't be declared - if (db !== undefined) await db.close(); - }); - itBench({ id: `altair verifyImport ${network}_s${startSlot}:${slotCount}`, minRuns: 5, diff --git a/packages/beacon-node/test/perf/network/gossip/encoding.test.ts b/packages/beacon-node/test/perf/network/gossip/encoding.test.ts index 693c91f59249..e8e889de2194 100644 --- a/packages/beacon-node/test/perf/network/gossip/encoding.test.ts +++ b/packages/beacon-node/test/perf/network/gossip/encoding.test.ts @@ -8,7 +8,7 @@ import {toHex} from "@lodestar/utils"; ✔ Buffer.from 6696982 ops/s 149.3210 ns/op - 2023 runs 0.454 s ✔ shared Buffer 1.013911e+7 ops/s 98.62800 ns/op - 3083 runs 0.404 s */ -describe("encoding", function () { +describe("encoding", () => { const msgId = Uint8Array.from(Array.from({length: 20}, (_, i) => i)); const runsFactor = 1000; diff --git a/packages/beacon-node/test/perf/network/peers/util/prioritizePeers.test.ts b/packages/beacon-node/test/perf/network/peers/util/prioritizePeers.test.ts index ecc30ebacef9..18dca2c670cd 100644 --- a/packages/beacon-node/test/perf/network/peers/util/prioritizePeers.test.ts +++ b/packages/beacon-node/test/perf/network/peers/util/prioritizePeers.test.ts @@ -11,7 +11,7 @@ import {getAttnets, getSyncnets} from "../../../../utils/network.js"; describe("prioritizePeers", () => { const seedPeers: {id: PeerId; attnets: phase0.AttestationSubnets; syncnets: altair.SyncSubnets; score: number}[] = []; - before(async function () { + before(async () => { for (let i = 0; i < defaultNetworkOptions.maxPeers; i++) { const pk = await generateKeyPair("secp256k1"); const peer = peerIdFromPrivateKey(pk); diff --git a/packages/beacon-node/test/perf/util/bytes.test.ts b/packages/beacon-node/test/perf/util/bytes.test.ts index d1d2e968b181..8c692bd3f92d 100644 --- a/packages/beacon-node/test/perf/util/bytes.test.ts +++ b/packages/beacon-node/test/perf/util/bytes.test.ts @@ -1,6 +1,6 @@ import {itBench} from "@dapplion/benchmark"; -describe("bytes utils", function () { +describe("bytes utils", () => { const roots: Uint8Array[] = []; let buffers: Buffer[] = []; const count = 32; diff --git a/packages/beacon-node/test/perf/util/dataview.test.ts b/packages/beacon-node/test/perf/util/dataview.test.ts index e0f28a5079e3..b0e394a0e1c8 100644 --- a/packages/beacon-node/test/perf/util/dataview.test.ts +++ b/packages/beacon-node/test/perf/util/dataview.test.ts @@ -1,6 +1,6 @@ import {itBench} from "@dapplion/benchmark"; -describe("dataview", function () { +describe("dataview", () => { const data = Uint8Array.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); itBench({ diff --git a/packages/beacon-node/test/perf/util/transferBytes.test.ts b/packages/beacon-node/test/perf/util/transferBytes.test.ts index 1cda12f7acd4..25cecbf770bc 100644 --- a/packages/beacon-node/test/perf/util/transferBytes.test.ts +++ b/packages/beacon-node/test/perf/util/transferBytes.test.ts @@ -1,7 +1,7 @@ import {itBench, setBenchOpts} from "@dapplion/benchmark"; import {expect} from "chai"; -describe("transfer bytes", function () { +describe("transfer bytes", () => { const sizes = [ {size: 84, name: "Status"}, {size: 112, name: "SignedVoluntaryExit"}, diff --git a/packages/beacon-node/test/sim/electra-interop.test.ts b/packages/beacon-node/test/sim/electra-interop.test.ts index 2d08428df558..20fedd3d4b0f 100644 --- a/packages/beacon-node/test/sim/electra-interop.test.ts +++ b/packages/beacon-node/test/sim/electra-interop.test.ts @@ -36,7 +36,7 @@ import {shell} from "./shell.js"; const jwtSecretHex = "0xdc6457099f127cf0bac78de8b297df04951281909db4f58b43def7c7151e765d"; const retries = defaultExecutionEngineHttpOpts.retries; const retryDelay = defaultExecutionEngineHttpOpts.retryDelay; -describe("executionEngine / ExecutionEngineHttp", function () { +describe("executionEngine / ExecutionEngineHttp", () => { if (!process.env.EL_BINARY_DIR || !process.env.EL_SCRIPT_DIR) { throw Error( `EL ENV must be provided, EL_BINARY_DIR: ${process.env.EL_BINARY_DIR}, EL_SCRIPT_DIR: ${process.env.EL_SCRIPT_DIR}` @@ -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) { @@ -234,7 +234,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { }); // TODO: get this post merge run working - it.skip("Post-merge, run for a few blocks", async function () { + it.skip("Post-merge, run for a few blocks", async () => { console.log("\n\nPost-merge, run for a few blocks\n\n"); const {elClient, tearDownCallBack} = await runEL( {...elSetupConfig, mode: ELStartMode.PostMerge, genesisTemplate: "electra.tmpl"}, @@ -331,7 +331,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { withEth1Credentials: true, }); - afterEachCallbacks.push(async function () { + afterEachCallbacks.push(async () => { await bn.close(); await sleep(1000); }); @@ -355,7 +355,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { valProposerConfig, }); - afterEachCallbacks.push(async function () { + afterEachCallbacks.push(async () => { await Promise.all(validators.map((v) => v.close())); }); diff --git a/packages/beacon-node/test/sim/mergemock.test.ts b/packages/beacon-node/test/sim/mergemock.test.ts index ee9839d58822..64020b070e11 100644 --- a/packages/beacon-node/test/sim/mergemock.test.ts +++ b/packages/beacon-node/test/sim/mergemock.test.ts @@ -29,7 +29,7 @@ import {shell} from "./shell.js"; const jwtSecretHex = "0xdc6457099f127cf0bac78de8b297df04951281909db4f58b43def7c7151e765d"; -describe("executionEngine / ExecutionEngineHttp", function () { +describe("executionEngine / ExecutionEngineHttp", () => { if (!process.env.EL_BINARY_DIR || !process.env.EL_SCRIPT_DIR) { throw Error( `EL ENV must be provided, EL_BINARY_DIR: ${process.env.EL_BINARY_DIR}, EL_SCRIPT_DIR: ${process.env.EL_SCRIPT_DIR}` @@ -64,7 +64,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { }); for (const useProduceBlockV3 of [false, true]) { - it(`Test builder with useProduceBlockV3=${useProduceBlockV3}`, async function () { + it(`Test builder with useProduceBlockV3=${useProduceBlockV3}`, async () => { console.log("\n\nPost-merge, run for a few blocks\n\n"); const {elClient, tearDownCallBack} = await runEL( {...elSetupConfig, mode: ELStartMode.PostMerge}, @@ -173,7 +173,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { // Enable builder by default, else because of circuit breaker we always start it with disabled bn.chain.executionBuilder.updateStatus(true); - afterEachCallbacks.push(async function () { + afterEachCallbacks.push(async () => { await bn.close(); await sleep(1000); }); @@ -204,7 +204,7 @@ describe("executionEngine / ExecutionEngineHttp", function () { useProduceBlockV3, }); - afterEachCallbacks.push(async function () { + afterEachCallbacks.push(async () => { await Promise.all(validators.map((v) => v.close())); }); diff --git a/packages/beacon-node/test/spec/bls/index.test.ts b/packages/beacon-node/test/spec/bls/index.test.ts index b781685432e6..32baa00d9fbc 100644 --- a/packages/beacon-node/test/spec/bls/index.test.ts +++ b/packages/beacon-node/test/spec/bls/index.test.ts @@ -35,7 +35,7 @@ for (const fnName of readdirSyncSpec(blsSpecTests.outputDir)) { const fnTestDirpath = path.join(blsSpecTests.outputDir, fnName); for (const testName of readdirSyncSpec(fnTestDirpath)) { - it(`${fnName}/${testName}`, function (context) { + it(`${fnName}/${testName}`, (context) => { if (fn === "skip") { context.skip(); return; 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/general/ssz_generic_types.ts b/packages/beacon-node/test/spec/general/ssz_generic_types.ts index aa231c962ae3..fe19f08149b4 100644 --- a/packages/beacon-node/test/spec/general/ssz_generic_types.ts +++ b/packages/beacon-node/test/spec/general/ssz_generic_types.ts @@ -120,7 +120,7 @@ export function getTestType(testType: string, testCase: string): Type { const elementType = vecElementTypes[elementTypeStr as keyof typeof vecElementTypes]; if (elementType === undefined) throw Error(`No vecElementType for ${elementTypeStr}: '${testCase}'`); const length = parseInt(lengthStr); - if (isNaN(length)) throw Error(`Bad length ${length}: '${testCase}'`); + if (Number.isNaN(length)) throw Error(`Bad length ${length}: '${testCase}'`); return new VectorBasicType(elementType, length); } @@ -173,6 +173,6 @@ export function getTestType(testType: string, testCase: string): Type { function parseSecondNum(str: string, id: string): number { const match = str.match(/[^\W_]+_([0-9]+)/); const num = parseInt((match || [])[1]); - if (isNaN(num)) throw Error(`Bad ${id} ${str}`); + if (Number.isNaN(num)) throw Error(`Bad ${id} ${str}`); return num; } diff --git a/packages/beacon-node/test/spec/presets/epoch_processing.test.ts b/packages/beacon-node/test/spec/presets/epoch_processing.test.ts index 17347269c6f6..146131f897ca 100644 --- a/packages/beacon-node/test/spec/presets/epoch_processing.test.ts +++ b/packages/beacon-node/test/spec/presets/epoch_processing.test.ts @@ -102,7 +102,7 @@ const epochProcessing = }, // Do not manually skip tests here, do it in packages/beacon-node/test/spec/presets/index.test.ts shouldSkip: (_testcase, name, _index) => - skipTestNames !== undefined && skipTestNames.some((skipTestName) => name.includes(skipTestName)), + skipTestNames?.some((skipTestName) => name.includes(skipTestName)) ?? false, }, }; }; diff --git a/packages/beacon-node/test/spec/presets/light_client/sync.ts b/packages/beacon-node/test/spec/presets/light_client/sync.ts index d931a5f310a8..3e82256fab1d 100644 --- a/packages/beacon-node/test/spec/presets/light_client/sync.ts +++ b/packages/beacon-node/test/spec/presets/light_client/sync.ts @@ -128,7 +128,7 @@ export const sync: TestRunnerFn = (fork) => { } const headerSlot = Number(step.process_update.checks.optimistic_header.slot); - const update = config.getLightClientForkTypes(headerSlot)["LightClientUpdate"].deserialize(updateBytes); + const update = config.getLightClientForkTypes(headerSlot).LightClientUpdate.deserialize(updateBytes); logger.debug(`LightclientUpdateSummary: ${JSON.stringify(toLightClientUpdateSummary(update))}`); diff --git a/packages/beacon-node/test/spec/presets/ssz_static.test.ts b/packages/beacon-node/test/spec/presets/ssz_static.test.ts index 06c7aa1fd98d..f5cdcc719b6a 100644 --- a/packages/beacon-node/test/spec/presets/ssz_static.test.ts +++ b/packages/beacon-node/test/spec/presets/ssz_static.test.ts @@ -52,7 +52,7 @@ const sszStatic = (ssz.altair as Types)[typeName] || (ssz.phase0 as Types)[typeName]; - it(`${fork} - ${typeName} type exists`, function () { + it(`${fork} - ${typeName} type exists`, () => { expect(sszType).toEqualWithMessage(expect.any(Type), `SSZ type ${typeName} for fork ${fork} is not defined`); }); @@ -65,7 +65,7 @@ const sszStatic = for (const testCase of fs.readdirSync(testSuiteDirpath)) { // Do not manually skip tests here, do it in packages/beacon-node/test/spec/presets/index.test.ts - it(testCase, function () { + it(testCase, () => { // Mainnet must deal with big full states and hash each one multiple times if (ACTIVE_PRESET === "mainnet") { vi.setConfig({testTimeout: 30 * 1000}); diff --git a/packages/beacon-node/test/spec/presets/transition.test.ts b/packages/beacon-node/test/spec/presets/transition.test.ts index df818f701c5d..76ad772f8dfb 100644 --- a/packages/beacon-node/test/spec/presets/transition.test.ts +++ b/packages/beacon-node/test/spec/presets/transition.test.ts @@ -83,7 +83,7 @@ const transition = }, // Do not manually skip tests here, do it in packages/beacon-node/test/spec/presets/index.test.ts shouldSkip: (_testcase, name, _index) => - skipTestNames !== undefined && skipTestNames.some((skipTestName) => name.includes(skipTestName)), + skipTestNames?.some((skipTestName) => name.includes(skipTestName)) ?? false, }, }; }; diff --git a/packages/beacon-node/test/spec/utils/runValidSszTest.ts b/packages/beacon-node/test/spec/utils/runValidSszTest.ts index 7ca02cec2d1e..748a7770b19c 100644 --- a/packages/beacon-node/test/spec/utils/runValidSszTest.ts +++ b/packages/beacon-node/test/spec/utils/runValidSszTest.ts @@ -83,6 +83,7 @@ export function runValidSszTest(type: Type, testData: ValidTestCaseData if (type.isBasic) { console.log("ROOTS Basic", toHexString(type.serialize(testDataValue))); } else { + // biome-ignore lint/complexity/useLiteralKeys: The `getRoots` is a protected attribute const roots = (type as CompositeType)["getRoots"](testDataValue); console.log( "ROOTS Composite", @@ -168,9 +169,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-mainnet/network/gossip/scoringParameters.test.ts b/packages/beacon-node/test/unit-mainnet/network/gossip/scoringParameters.test.ts index 7ef09af2cd89..b3137755857f 100644 --- a/packages/beacon-node/test/unit-mainnet/network/gossip/scoringParameters.test.ts +++ b/packages/beacon-node/test/unit-mainnet/network/gossip/scoringParameters.test.ts @@ -12,7 +12,7 @@ import {ZERO_HASH} from "../../../../src/constants/index.js"; * Refer to Teku tests at * https://github.com/ConsenSys/teku/blob/e18ab9903442410aa04b590c4cc46734e13d3ffd/networking/eth2/src/test/java/tech/pegasys/teku/networking/eth2/gossip/config/GossipScoringConfiguratorTest.java#L38 */ -describe("computeGossipPeerScoreParams", function () { +describe("computeGossipPeerScoreParams", () => { const config = createBeaconConfig(mainnetChainConfig, ZERO_HASH); // Cheap stub on new BeaconConfig instance config.forkName2ForkDigest = () => Buffer.alloc(4, 1); diff --git a/packages/beacon-node/test/unit/api/impl/beacon/beacon.test.ts b/packages/beacon-node/test/unit/api/impl/beacon/beacon.test.ts index a8eaffa42005..99bac5de7ef4 100644 --- a/packages/beacon-node/test/unit/api/impl/beacon/beacon.test.ts +++ b/packages/beacon-node/test/unit/api/impl/beacon/beacon.test.ts @@ -4,17 +4,17 @@ import {ApiTestModules, getApiTestModules} from "../../../../utils/api.js"; import {getBeaconApi} from "../../../../../src/api/impl/beacon/index.js"; import {Mutable} from "../../../../utils/types.js"; -describe("beacon api implementation", function () { +describe("beacon api implementation", () => { let modules: ApiTestModules; let api: ReturnType; - beforeAll(function () { + beforeAll(() => { modules = getApiTestModules(); api = getBeaconApi(modules); }); - describe("getGenesis", function () { - it("success", async function () { + describe("getGenesis", () => { + it("success", async () => { (modules.chain as Mutable).genesisTime = 0; (modules.chain as Mutable).genesisValidatorsRoot = Buffer.alloc(32); diff --git a/packages/beacon-node/test/unit/api/impl/beacon/blocks/getBlockHeaders.test.ts b/packages/beacon-node/test/unit/api/impl/beacon/blocks/getBlockHeaders.test.ts index 9b3c960ff2ec..5e4e8a31ec7f 100644 --- a/packages/beacon-node/test/unit/api/impl/beacon/blocks/getBlockHeaders.test.ts +++ b/packages/beacon-node/test/unit/api/impl/beacon/blocks/getBlockHeaders.test.ts @@ -7,12 +7,12 @@ import {ApiTestModules, getApiTestModules} from "../../../../../utils/api.js"; import {generateProtoBlock, generateSignedBlockAtSlot} from "../../../../../utils/typeGenerator.js"; import {getBeaconBlockApi} from "../../../../../../src/api/impl/beacon/blocks/index.js"; -describe("api - beacon - getBlockHeaders", function () { +describe("api - beacon - getBlockHeaders", () => { let modules: ApiTestModules; let api: ReturnType; const parentRoot = toHexString(Buffer.alloc(32, 1)); - beforeEach(function () { + beforeEach(() => { modules = getApiTestModules(); api = getBeaconBlockApi(modules); @@ -24,7 +24,7 @@ describe("api - beacon - getBlockHeaders", function () { vi.clearAllMocks(); }); - it.skip("no filters - assume head slot", async function () { + it.skip("no filters - assume head slot", async () => { modules.forkChoice.getHead.mockReturnValue(generateProtoBlock({slot: 1})); when(modules.chain.getCanonicalBlockAtSlot) .calledWith(1) @@ -55,13 +55,13 @@ describe("api - beacon - getBlockHeaders", function () { expect(modules.db.block.get).toHaveBeenCalledTimes(1); }); - it("future slot", async function () { + it("future slot", async () => { modules.forkChoice.getHead.mockReturnValue(generateProtoBlock({slot: 1})); const {data: blockHeaders} = await api.getBlockHeaders({slot: 2}); expect(blockHeaders.length).toBe(0); }); - it("finalized slot", async function () { + it("finalized slot", async () => { modules.forkChoice.getHead.mockReturnValue(generateProtoBlock({slot: 2})); when(modules.chain.getCanonicalBlockAtSlot) .calledWith(0) @@ -72,14 +72,14 @@ describe("api - beacon - getBlockHeaders", function () { expect(blockHeaders[0].canonical).toBe(true); }); - it("skip slot", async function () { + it("skip slot", async () => { modules.forkChoice.getHead.mockReturnValue(generateProtoBlock({slot: 2})); when(modules.chain.getCanonicalBlockAtSlot).calledWith(0).thenResolve(null); const {data: blockHeaders} = await api.getBlockHeaders({slot: 0}); expect(blockHeaders.length).toBe(0); }); - it.skip("parent root filter - both finalized and non finalized results", async function () { + it.skip("parent root filter - both finalized and non finalized results", async () => { modules.db.blockArchive.getByParentRoot.mockResolvedValue(ssz.phase0.SignedBeaconBlock.defaultValue()); modules.forkChoice.getBlockSummariesByParentRoot.mockReturnValue([ generateProtoBlock({slot: 2}), @@ -99,7 +99,7 @@ describe("api - beacon - getBlockHeaders", function () { expect(blockHeaders.filter((b) => b.canonical).length).toBe(2); }); - it("parent root - no finalized block", async function () { + it("parent root - no finalized block", async () => { modules.db.blockArchive.getByParentRoot.mockResolvedValue(null); modules.forkChoice.getBlockSummariesByParentRoot.mockReturnValue([generateProtoBlock({slot: 1})]); when(modules.forkChoice.getCanonicalBlockAtSlot).calledWith(1).thenReturn(generateProtoBlock()); @@ -109,14 +109,14 @@ describe("api - beacon - getBlockHeaders", function () { expect(blockHeaders.length).toBe(1); }); - it("parent root - no non finalized blocks", async function () { + it("parent root - no non finalized blocks", async () => { modules.db.blockArchive.getByParentRoot.mockResolvedValue(ssz.phase0.SignedBeaconBlock.defaultValue()); modules.forkChoice.getBlockSummariesByParentRoot.mockReturnValue([]); const {data: blockHeaders} = await api.getBlockHeaders({parentRoot}); expect(blockHeaders.length).toBe(1); }); - it("parent root + slot filter", async function () { + it("parent root + slot filter", async () => { modules.db.blockArchive.getByParentRoot.mockResolvedValue(ssz.phase0.SignedBeaconBlock.defaultValue()); modules.forkChoice.getBlockSummariesByParentRoot.mockReturnValue([ generateProtoBlock({slot: 2}), diff --git a/packages/beacon-node/test/unit/api/impl/beacon/state/utils.test.ts b/packages/beacon-node/test/unit/api/impl/beacon/state/utils.test.ts index 39c936c0d025..958093ffba6d 100644 --- a/packages/beacon-node/test/unit/api/impl/beacon/state/utils.test.ts +++ b/packages/beacon-node/test/unit/api/impl/beacon/state/utils.test.ts @@ -3,7 +3,7 @@ import {toHexString} from "@chainsafe/ssz"; import {getStateValidatorIndex} from "../../../../../../src/api/impl/beacon/state/utils.js"; import {generateCachedAltairState} from "../../../../../utils/state.js"; -describe("beacon state api utils", function () { +describe("beacon state api utils", () => { describe("getStateValidatorIndex", () => { const state = generateCachedAltairState(); const pubkey2index = state.epochCtx.pubkey2index; diff --git a/packages/beacon-node/test/unit/api/impl/config/config.test.ts b/packages/beacon-node/test/unit/api/impl/config/config.test.ts index d6954f632d5e..7d0adebbea89 100644 --- a/packages/beacon-node/test/unit/api/impl/config/config.test.ts +++ b/packages/beacon-node/test/unit/api/impl/config/config.test.ts @@ -3,34 +3,34 @@ import {routes} from "@lodestar/api"; import {config} from "@lodestar/config/default"; import {getConfigApi, renderJsonSpec} from "../../../../../src/api/impl/config/index.js"; -describe("config api implementation", function () { +describe("config api implementation", () => { let api: ReturnType; - beforeEach(function () { + beforeEach(() => { api = getConfigApi({config}); }); - describe("getForkSchedule", function () { - it("should get known scheduled forks", async function () { + describe("getForkSchedule", () => { + it("should get known scheduled forks", async () => { const {data: forkSchedule} = await api.getForkSchedule(); expect(forkSchedule.length).toBe(Object.keys(config.forks).length); }); }); - describe("getDepositContract", function () { - it("should get the deposit contract from config", async function () { + describe("getDepositContract", () => { + it("should get the deposit contract from config", async () => { const {data: depositContract} = (await api.getDepositContract()) as {data: routes.config.DepositContract}; expect(depositContract.address).toBe(config.DEPOSIT_CONTRACT_ADDRESS); expect(depositContract.chainId).toBe(config.DEPOSIT_CHAIN_ID); }); }); - describe("getSpec", function () { + describe("getSpec", () => { it("Ensure spec can be rendered", () => { renderJsonSpec(config); }); - it("should get the spec", async function () { + it("should get the spec", async () => { const {data: specJson} = (await api.getSpec()) as {data: routes.config.Spec}; expect(specJson.SECONDS_PER_ETH1_BLOCK).toBe("14"); diff --git a/packages/beacon-node/test/unit/api/impl/events/events.test.ts b/packages/beacon-node/test/unit/api/impl/events/events.test.ts index a5dd21d14fd3..5b1686d42f57 100644 --- a/packages/beacon-node/test/unit/api/impl/events/events.test.ts +++ b/packages/beacon-node/test/unit/api/impl/events/events.test.ts @@ -22,22 +22,20 @@ vi.mock("../../../../../src/chain/index.js", async (importActual) => { }; }); -describe("Events api impl", function () { - describe("beacon event stream", function () { +describe("Events api impl", () => { + describe("beacon event stream", () => { let chainStub: MockedObject; let chainEventEmmitter: ChainEventEmitter; let api: ReturnType; + let controller: AbortController; - beforeEach(function () { + beforeEach(() => { chainStub = vi.mocked(new BeaconChain({} as any, {} as any), {partial: true, deep: false}); chainEventEmmitter = chainStub.emitter; api = getEventsApi({config, chain: chainStub}); - }); - - let controller: AbortController; - beforeEach(() => { controller = new AbortController(); }); + afterEach(() => controller.abort()); function getEvents(topics: routes.events.EventType[]): routes.events.BeaconEvent[] { @@ -62,7 +60,7 @@ describe("Events api impl", function () { executionOptimistic: false, }; - it("should ignore not sent topics", async function () { + it("should ignore not sent topics", async () => { const events = getEvents([routes.events.EventType.head]); chainEventEmmitter.emit(routes.events.EventType.attestation, ssz.phase0.Attestation.defaultValue()); diff --git a/packages/beacon-node/test/unit/api/impl/validator/duties/proposer.test.ts b/packages/beacon-node/test/unit/api/impl/validator/duties/proposer.test.ts index 49758c9bca58..b954f983adcc 100644 --- a/packages/beacon-node/test/unit/api/impl/validator/duties/proposer.test.ts +++ b/packages/beacon-node/test/unit/api/impl/validator/duties/proposer.test.ts @@ -13,7 +13,7 @@ import {createCachedBeaconStateTest} from "../../../../../utils/cachedBeaconStat import {SyncState} from "../../../../../../src/sync/interface.js"; import {defaultApiOptions} from "../../../../../../src/api/options.js"; -describe("get proposers api impl", function () { +describe("get proposers api impl", () => { const currentEpoch = 2; const currentSlot = SLOTS_PER_EPOCH * currentEpoch; @@ -22,7 +22,7 @@ describe("get proposers api impl", function () { let state: BeaconStateAllForks; let cachedState: ReturnType; - beforeEach(function () { + beforeEach(() => { vi.useFakeTimers({now: 0}); vi.advanceTimersByTime(currentSlot * config.SECONDS_PER_SLOT * 1000); modules = getApiTestModules({clock: "real"}); diff --git a/packages/beacon-node/test/unit/api/impl/validator/produceAttestationData.test.ts b/packages/beacon-node/test/unit/api/impl/validator/produceAttestationData.test.ts index 84872ca6045c..fdbfec5ac503 100644 --- a/packages/beacon-node/test/unit/api/impl/validator/produceAttestationData.test.ts +++ b/packages/beacon-node/test/unit/api/impl/validator/produceAttestationData.test.ts @@ -5,16 +5,16 @@ import {ApiTestModules, getApiTestModules} from "../../../../utils/api.js"; import {getValidatorApi} from "../../../../../src/api/impl/validator/index.js"; import {defaultApiOptions} from "../../../../../src/api/options.js"; -describe("api - validator - produceAttestationData", function () { +describe("api - validator - produceAttestationData", () => { let modules: ApiTestModules; let api: ReturnType; - beforeEach(function () { + beforeEach(() => { modules = getApiTestModules(); api = getValidatorApi(defaultApiOptions, modules); }); - it("Should throw when node is not synced", async function () { + it("Should throw when node is not synced", async () => { // Set the node's state to way back from current slot const currentSlot = 100000; const headSlot = 0; @@ -25,7 +25,7 @@ describe("api - validator - produceAttestationData", function () { await expect(api.produceAttestationData({committeeIndex: 0, slot: 0})).rejects.toThrow("Node is syncing"); }); - it("Should throw error when node is stopped", async function () { + it("Should throw error when node is stopped", async () => { const currentSlot = 100000; vi.spyOn(modules.chain.clock, "currentSlot", "get").mockReturnValue(currentSlot); vi.spyOn(modules.sync, "state", "get").mockReturnValue(SyncState.Stalled); diff --git a/packages/beacon-node/test/unit/api/impl/validator/produceBlockV2.test.ts b/packages/beacon-node/test/unit/api/impl/validator/produceBlockV2.test.ts index a23373938f64..306b18481c1f 100644 --- a/packages/beacon-node/test/unit/api/impl/validator/produceBlockV2.test.ts +++ b/packages/beacon-node/test/unit/api/impl/validator/produceBlockV2.test.ts @@ -16,7 +16,7 @@ import {generateProtoBlock} from "../../../../utils/typeGenerator.js"; import {ZERO_HASH_HEX} from "../../../../../src/constants/index.js"; import {defaultApiOptions} from "../../../../../src/api/options.js"; -describe("api/validator - produceBlockV2", function () { +describe("api/validator - produceBlockV2", () => { let api: ReturnType; let modules: ApiTestModules; let state: CachedBeaconStateBellatrix; @@ -32,7 +32,7 @@ describe("api/validator - produceBlockV2", function () { vi.clearAllMocks(); }); - it("correctly pass feeRecipient to produceBlock", async function () { + it("correctly pass feeRecipient to produceBlock", async () => { const fullBlock = ssz.bellatrix.BeaconBlock.defaultValue(); const executionPayloadValue = ssz.Wei.defaultValue(); const consensusBlockValue = ssz.Wei.defaultValue(); diff --git a/packages/beacon-node/test/unit/api/impl/validator/produceBlockV3.test.ts b/packages/beacon-node/test/unit/api/impl/validator/produceBlockV3.test.ts index d8f1b9a317b9..f705e4b38e14 100644 --- a/packages/beacon-node/test/unit/api/impl/validator/produceBlockV3.test.ts +++ b/packages/beacon-node/test/unit/api/impl/validator/produceBlockV3.test.ts @@ -12,7 +12,7 @@ import {CommonBlockBody} from "../../../../../src/chain/interface.js"; import {zeroProtoBlock} from "../../../../utils/state.js"; import {defaultApiOptions} from "../../../../../src/api/options.js"; -describe("api/validator - produceBlockV3", function () { +describe("api/validator - produceBlockV3", () => { let modules: ApiTestModules; let api: ReturnType; @@ -64,102 +64,100 @@ describe("api/validator - produceBlockV3", function () { [routes.validator.BuilderSelection.ExecutionOnly, 1, 1, 1, true, "engine"], ]; - testCases.forEach( - ([ - builderSelection, - builderPayloadValue, - enginePayloadValue, - consensusBlockValue, - shouldOverrideBuilder, - finalSelection, - ]) => { - it(`produceBlockV3 - ${finalSelection} produces block`, async () => { - const fullBlock = ssz.bellatrix.BeaconBlock.defaultValue(); - const blindedBlock = ssz.bellatrix.BlindedBeaconBlock.defaultValue(); - - const slot = 1 * SLOTS_PER_EPOCH; - const randaoReveal = fullBlock.body.randaoReveal; - const graffiti = "a".repeat(32); - const feeRecipient = "0xccccccccccccccccccccccccccccccccccccccaa"; - const currentSlot = 1 * SLOTS_PER_EPOCH; - - vi.spyOn(modules.chain.clock, "currentSlot", "get").mockReturnValue(currentSlot); - vi.spyOn(modules.sync, "state", "get").mockReturnValue(SyncState.Synced); - modules.chain.recomputeForkChoiceHead.mockReturnValue({ - blockRoot: toHexString(fullBlock.parentRoot), - } as ProtoBlock); - modules.chain.getProposerHead.mockReturnValue({blockRoot: toHexString(fullBlock.parentRoot)} as ProtoBlock); - modules.chain.forkChoice.getBlock.mockReturnValue(zeroProtoBlock); - - if (enginePayloadValue !== null) { - const commonBlockBody: CommonBlockBody = { - attestations: fullBlock.body.attestations, - attesterSlashings: fullBlock.body.attesterSlashings, - deposits: fullBlock.body.deposits, - proposerSlashings: fullBlock.body.proposerSlashings, - eth1Data: fullBlock.body.eth1Data, - graffiti: fullBlock.body.graffiti, - randaoReveal: fullBlock.body.randaoReveal, - voluntaryExits: fullBlock.body.voluntaryExits, - blsToExecutionChanges: [], - syncAggregate: fullBlock.body.syncAggregate, - }; - - modules.chain.produceCommonBlockBody.mockResolvedValue(commonBlockBody); - - modules.chain.produceBlock.mockResolvedValue({ - block: fullBlock, - executionPayloadValue: BigInt(enginePayloadValue), - consensusBlockValue: BigInt(consensusBlockValue), - shouldOverrideBuilder, - }); - } else { - modules.chain.produceBlock.mockRejectedValue(Error("not produced")); - } - - if (builderPayloadValue !== null) { - modules.chain.produceBlindedBlock.mockResolvedValue({ - block: blindedBlock, - executionPayloadValue: BigInt(builderPayloadValue), - consensusBlockValue: BigInt(consensusBlockValue), - }); - } else { - modules.chain.produceBlindedBlock.mockRejectedValue(Error("not produced")); - } - const _skipRandaoVerification = false; - const produceBlockOpts = { - strictFeeRecipientCheck: false, - builderSelection, - feeRecipient, + for (const [ + builderSelection, + builderPayloadValue, + enginePayloadValue, + consensusBlockValue, + shouldOverrideBuilder, + finalSelection, + ] of testCases) { + it(`produceBlockV3 - ${finalSelection} produces block`, async () => { + const fullBlock = ssz.bellatrix.BeaconBlock.defaultValue(); + const blindedBlock = ssz.bellatrix.BlindedBeaconBlock.defaultValue(); + + const slot = 1 * SLOTS_PER_EPOCH; + const randaoReveal = fullBlock.body.randaoReveal; + const graffiti = "a".repeat(32); + const feeRecipient = "0xccccccccccccccccccccccccccccccccccccccaa"; + const currentSlot = 1 * SLOTS_PER_EPOCH; + + vi.spyOn(modules.chain.clock, "currentSlot", "get").mockReturnValue(currentSlot); + vi.spyOn(modules.sync, "state", "get").mockReturnValue(SyncState.Synced); + modules.chain.recomputeForkChoiceHead.mockReturnValue({ + blockRoot: toHexString(fullBlock.parentRoot), + } as ProtoBlock); + modules.chain.getProposerHead.mockReturnValue({blockRoot: toHexString(fullBlock.parentRoot)} as ProtoBlock); + modules.chain.forkChoice.getBlock.mockReturnValue(zeroProtoBlock); + + if (enginePayloadValue !== null) { + const commonBlockBody: CommonBlockBody = { + attestations: fullBlock.body.attestations, + attesterSlashings: fullBlock.body.attesterSlashings, + deposits: fullBlock.body.deposits, + proposerSlashings: fullBlock.body.proposerSlashings, + eth1Data: fullBlock.body.eth1Data, + graffiti: fullBlock.body.graffiti, + randaoReveal: fullBlock.body.randaoReveal, + voluntaryExits: fullBlock.body.voluntaryExits, + blsToExecutionChanges: [], + syncAggregate: fullBlock.body.syncAggregate, }; - const {data: block, meta} = await api.produceBlockV3({ - slot, - randaoReveal, - graffiti, - skipRandaoVerification: _skipRandaoVerification, - ...produceBlockOpts, - }); - - const expectedBlock = finalSelection === "builder" ? blindedBlock : fullBlock; - const expectedExecution = finalSelection === "builder"; - - expect(block).toEqual(expectedBlock); - expect(meta.executionPayloadBlinded).toEqual(expectedExecution); - - // check call counts - if (builderSelection === routes.validator.BuilderSelection.ExecutionOnly) { - expect(modules.chain.produceBlindedBlock).toBeCalledTimes(0); - } else { - expect(modules.chain.produceBlindedBlock).toBeCalledTimes(1); - } + modules.chain.produceCommonBlockBody.mockResolvedValue(commonBlockBody); - if (builderSelection === routes.validator.BuilderSelection.BuilderOnly) { - expect(modules.chain.produceBlock).toBeCalledTimes(0); - } else { - expect(modules.chain.produceBlock).toBeCalledTimes(1); - } + modules.chain.produceBlock.mockResolvedValue({ + block: fullBlock, + executionPayloadValue: BigInt(enginePayloadValue), + consensusBlockValue: BigInt(consensusBlockValue), + shouldOverrideBuilder, + }); + } else { + modules.chain.produceBlock.mockRejectedValue(Error("not produced")); + } + + if (builderPayloadValue !== null) { + modules.chain.produceBlindedBlock.mockResolvedValue({ + block: blindedBlock, + executionPayloadValue: BigInt(builderPayloadValue), + consensusBlockValue: BigInt(consensusBlockValue), + }); + } else { + modules.chain.produceBlindedBlock.mockRejectedValue(Error("not produced")); + } + const _skipRandaoVerification = false; + const produceBlockOpts = { + strictFeeRecipientCheck: false, + builderSelection, + feeRecipient, + }; + + const {data: block, meta} = await api.produceBlockV3({ + slot, + randaoReveal, + graffiti, + skipRandaoVerification: _skipRandaoVerification, + ...produceBlockOpts, }); - } - ); + + const expectedBlock = finalSelection === "builder" ? blindedBlock : fullBlock; + const expectedExecution = finalSelection === "builder"; + + expect(block).toEqual(expectedBlock); + expect(meta.executionPayloadBlinded).toEqual(expectedExecution); + + // check call counts + if (builderSelection === routes.validator.BuilderSelection.ExecutionOnly) { + expect(modules.chain.produceBlindedBlock).toBeCalledTimes(0); + } else { + expect(modules.chain.produceBlindedBlock).toBeCalledTimes(1); + } + + if (builderSelection === routes.validator.BuilderSelection.BuilderOnly) { + expect(modules.chain.produceBlock).toBeCalledTimes(0); + } else { + expect(modules.chain.produceBlock).toBeCalledTimes(1); + } + }); + } }); diff --git a/packages/beacon-node/test/unit/chain/archive/blockArchiver.test.ts b/packages/beacon-node/test/unit/chain/archive/blockArchiver.test.ts index d9c3b93a76ee..dc7c9bb75291 100644 --- a/packages/beacon-node/test/unit/chain/archive/blockArchiver.test.ts +++ b/packages/beacon-node/test/unit/chain/archive/blockArchiver.test.ts @@ -9,14 +9,14 @@ import {archiveBlocks} from "../../../../src/chain/archiver/archiveBlocks.js"; import {MockedBeaconDb, getMockedBeaconDb} from "../../../mocks/mockedBeaconDb.js"; import {MockedBeaconChain, getMockedBeaconChain} from "../../../mocks/mockedBeaconChain.js"; -describe("block archiver task", function () { +describe("block archiver task", () => { const logger = testLogger(); let dbStub: MockedBeaconDb; let forkChoiceStub: MockedBeaconChain["forkChoice"]; let lightclientServer: MockedBeaconChain["lightClientServer"]; - beforeEach(function () { + beforeEach(() => { const chain = getMockedBeaconChain(); dbStub = getMockedBeaconDb(); forkChoiceStub = chain.forkChoice; @@ -30,7 +30,7 @@ describe("block archiver task", function () { vi.clearAllMocks(); }); - it("should archive finalized blocks", async function () { + it("should archive finalized blocks", async () => { const blockBytes = ssz.phase0.SignedBeaconBlock.serialize(ssz.phase0.SignedBeaconBlock.defaultValue()); vi.spyOn(dbStub.block, "getBinary").mockResolvedValue(Buffer.from(blockBytes)); // block i has slot i+1 diff --git a/packages/beacon-node/test/unit/chain/beaconProposerCache.ts b/packages/beacon-node/test/unit/chain/beaconProposerCache.ts index 538fe8518458..b75bbf546a98 100644 --- a/packages/beacon-node/test/unit/chain/beaconProposerCache.ts +++ b/packages/beacon-node/test/unit/chain/beaconProposerCache.ts @@ -2,30 +2,30 @@ import {expect, describe, it, beforeEach} from "vitest"; import {BeaconProposerCache} from "../../../src/chain/beaconProposerCache.js"; const suggestedFeeRecipient = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -describe("BeaconProposerCache", function () { +describe("BeaconProposerCache", () => { let cache: BeaconProposerCache; - beforeEach(function () { + beforeEach(() => { // max 2 items cache = new BeaconProposerCache({suggestedFeeRecipient}); cache.add(1, {validatorIndex: 23, feeRecipient: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}); cache.add(3, {validatorIndex: 43, feeRecipient: "0xcccccccccccccccccccccccccccccccccccccccc"}); }); - it("get default", function () { + it("get default", () => { expect(cache.get(32)).toBe("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); }); - it("get what has been set", function () { + it("get what has been set", () => { expect(cache.get(23)).toBe("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); }); - it("override and get latest", function () { + it("override and get latest", () => { cache.add(5, {validatorIndex: 23, feeRecipient: "0xdddddddddddddddddddddddddddddddddddddddd"}); expect(cache.get(23)).toBe("0xdddddddddddddddddddddddddddddddddddddddd"); }); - it("prune", function () { + it("prune", () => { cache.prune(4); // Default for what has been pruned diff --git a/packages/beacon-node/test/unit/chain/blocks/verifyBlocksSanityChecks.test.ts b/packages/beacon-node/test/unit/chain/blocks/verifyBlocksSanityChecks.test.ts index a45678e5bf48..1296a79d5eab 100644 --- a/packages/beacon-node/test/unit/chain/blocks/verifyBlocksSanityChecks.test.ts +++ b/packages/beacon-node/test/unit/chain/blocks/verifyBlocksSanityChecks.test.ts @@ -13,7 +13,7 @@ import {ClockStopped} from "../../../mocks/clock.js"; import {BlockSource, getBlockInput} from "../../../../src/chain/blocks/types.js"; import {MockedBeaconChain, getMockedBeaconChain} from "../../../mocks/mockedBeaconChain.js"; -describe("chain / blocks / verifyBlocksSanityChecks", function () { +describe("chain / blocks / verifyBlocksSanityChecks", () => { let forkChoice: MockedBeaconChain["forkChoice"]; let clock: ClockStopped; let modules: {forkChoice: IForkChoice; clock: IClock; config: ChainForkConfig}; diff --git a/packages/beacon-node/test/unit/chain/bls/bls.test.ts b/packages/beacon-node/test/unit/chain/bls/bls.test.ts index 4203d7f9768c..137f2c4dd9df 100644 --- a/packages/beacon-node/test/unit/chain/bls/bls.test.ts +++ b/packages/beacon-node/test/unit/chain/bls/bls.test.ts @@ -5,7 +5,7 @@ import {BlsSingleThreadVerifier} from "../../../../src/chain/bls/singleThread.js import {BlsMultiThreadWorkerPool} from "../../../../src/chain/bls/multithread/index.js"; import {testLogger} from "../../../utils/logger.js"; -describe("BlsVerifier ", function () { +describe("BlsVerifier ", () => { // take time for creating thread pool const numKeys = 3; const secretKeys = Array.from({length: numKeys}, (_, i) => SecretKey.fromKeygen(Buffer.alloc(32, i))); diff --git a/packages/beacon-node/test/unit/chain/forkChoice/forkChoice.test.ts b/packages/beacon-node/test/unit/chain/forkChoice/forkChoice.test.ts index 611673086ce5..7cb5d23ba296 100644 --- a/packages/beacon-node/test/unit/chain/forkChoice/forkChoice.test.ts +++ b/packages/beacon-node/test/unit/chain/forkChoice/forkChoice.test.ts @@ -20,7 +20,7 @@ import {generateValidators} from "../../../utils/validator.js"; // We mock this package globally vi.unmock("@lodestar/fork-choice"); -describe("LodestarForkChoice", function () { +describe("LodestarForkChoice", () => { let forkChoice: ForkChoice; const anchorState = createCachedBeaconStateTest( generateState( @@ -71,7 +71,7 @@ describe("LodestarForkChoice", function () { ); }); - describe("forkchoice", function () { + describe("forkchoice", () => { /** * slot 32(checkpoint) - orphaned (36) * \ diff --git a/packages/beacon-node/test/unit/chain/genesis/genesis.test.ts b/packages/beacon-node/test/unit/chain/genesis/genesis.test.ts index 5b48ca9fd953..40570fcd26e1 100644 --- a/packages/beacon-node/test/unit/chain/genesis/genesis.test.ts +++ b/packages/beacon-node/test/unit/chain/genesis/genesis.test.ts @@ -11,7 +11,7 @@ import {testLogger} from "../../../utils/logger.js"; import {ZERO_HASH_HEX} from "../../../../src/constants/index.js"; import {Eth1ProviderState, EthJsonRpcBlockRaw, IEth1Provider} from "../../../../src/eth1/interface.js"; -describe("genesis builder", function () { +describe("genesis builder", () => { const logger = testLogger(); const schlesiConfig = Object.assign({}, config, { MIN_GENESIS_TIME: 1587755000, diff --git a/packages/beacon-node/test/unit/chain/lightclient/upgradeLightClientHeader.test.ts b/packages/beacon-node/test/unit/chain/lightclient/upgradeLightClientHeader.test.ts index ab8f166076b9..3c2f5a664c77 100644 --- a/packages/beacon-node/test/unit/chain/lightclient/upgradeLightClientHeader.test.ts +++ b/packages/beacon-node/test/unit/chain/lightclient/upgradeLightClientHeader.test.ts @@ -4,7 +4,7 @@ import {ForkName, ForkSeq} from "@lodestar/params"; import {createBeaconConfig, createChainForkConfig, defaultChainConfig} from "@lodestar/config"; import {upgradeLightClientHeader} from "@lodestar/light-client/spec"; -describe("UpgradeLightClientHeader", function () { +describe("UpgradeLightClientHeader", () => { let lcHeaderByFork: Record; let testSlots: Record; @@ -20,7 +20,7 @@ describe("UpgradeLightClientHeader", function () { const genesisValidatorsRoot = Buffer.alloc(32, 0xaa); const config = createBeaconConfig(chainConfig, genesisValidatorsRoot); - beforeEach(function () { + beforeEach(() => { lcHeaderByFork = { phase0: ssz.altair.LightClientHeader.defaultValue(), altair: ssz.altair.LightClientHeader.defaultValue(), @@ -45,7 +45,7 @@ describe("UpgradeLightClientHeader", function () { const fromFork = ForkName[ForkSeq[i] as ForkName]; const toFork = ForkName[ForkSeq[j] as ForkName]; - it(`Successful upgrade ${fromFork}=>${toFork}`, function () { + it(`Successful upgrade ${fromFork}=>${toFork}`, () => { lcHeaderByFork[fromFork].beacon.slot = testSlots[fromFork]; lcHeaderByFork[toFork].beacon.slot = testSlots[fromFork]; @@ -60,7 +60,7 @@ describe("UpgradeLightClientHeader", function () { const fromFork = ForkName[ForkSeq[i] as ForkName]; const toFork = ForkName[ForkSeq[j] as ForkName]; - it(`Throw upgrade error ${fromFork}=>${toFork}`, function () { + it(`Throw upgrade error ${fromFork}=>${toFork}`, () => { lcHeaderByFork[fromFork].beacon.slot = testSlots[fromFork]; lcHeaderByFork[toFork].beacon.slot = testSlots[fromFork]; diff --git a/packages/beacon-node/test/unit/chain/opPools/aggregatedAttestationPool.test.ts b/packages/beacon-node/test/unit/chain/opPools/aggregatedAttestationPool.test.ts index f00a300bbe4d..8742d7da9147 100644 --- a/packages/beacon-node/test/unit/chain/opPools/aggregatedAttestationPool.test.ts +++ b/packages/beacon-node/test/unit/chain/opPools/aggregatedAttestationPool.test.ts @@ -34,7 +34,7 @@ const validSignature = fromHexString( "0xb2afb700f6c561ce5e1b4fedaec9d7c06b822d38c720cf588adfda748860a940adf51634b6788f298c552de40183b5a203b2bbe8b7dd147f0bb5bc97080a12efbb631c8888cb31a99cc4706eb3711865b8ea818c10126e4d818b542e9dbf9ae8" ); -describe("AggregatedAttestationPool", function () { +describe("AggregatedAttestationPool", () => { let pool: AggregatedAttestationPool; const fork = ForkName.altair; const config = createChainForkConfig({ @@ -116,7 +116,7 @@ describe("AggregatedAttestationPool", function () { ]; for (const {name, attestingBits, isReturned} of testCases) { - it(name, function () { + it(name, () => { const aggregationBits = new BitArray(new Uint8Array(attestingBits), committeeLength); pool.add( {...attestation, aggregationBits}, @@ -136,7 +136,7 @@ describe("AggregatedAttestationPool", function () { }); } - it("incorrect source", function () { + it("incorrect source", () => { altairState.currentJustifiedCheckpoint.epoch = 1000; // all attesters are not seen const attestingIndices = [2, 3]; @@ -146,7 +146,7 @@ describe("AggregatedAttestationPool", function () { expect(forkchoiceStub.iterateAncestorBlocks).not.toHaveBeenCalledTimes(1); }); - it("incompatible shuffling - incorrect pivot block root", function () { + it("incompatible shuffling - incorrect pivot block root", () => { // all attesters are not seen const attestingIndices = [2, 3]; pool.add(attestation, attDataRootHex, attestingIndices.length, committee); @@ -305,7 +305,7 @@ describe("MatchingDataAttestationGroup.getAttestationsForBlock", () => { } }); -describe("MatchingDataAttestationGroup aggregateInto", function () { +describe("MatchingDataAttestationGroup aggregateInto", () => { const attestationSeed = ssz.phase0.Attestation.defaultValue(); const attestation1 = {...attestationSeed, ...{aggregationBits: BitArray.fromBoolArray([false, true])}}; const attestation2 = {...attestationSeed, ...{aggregationBits: BitArray.fromBoolArray([true, false])}}; @@ -334,7 +334,7 @@ describe("MatchingDataAttestationGroup aggregateInto", function () { }); }); -describe("aggregateConsolidation", function () { +describe("aggregateConsolidation", () => { const sk0 = SecretKey.fromBytes(Buffer.alloc(32, 1)); const sk1 = SecretKey.fromBytes(Buffer.alloc(32, 2)); const sk2 = SecretKey.fromBytes(Buffer.alloc(32, 3)); diff --git a/packages/beacon-node/test/unit/chain/opPools/attestationPool.test.ts b/packages/beacon-node/test/unit/chain/opPools/attestationPool.test.ts index eba01888fa7c..98453efaa3b6 100644 --- a/packages/beacon-node/test/unit/chain/opPools/attestationPool.test.ts +++ b/packages/beacon-node/test/unit/chain/opPools/attestationPool.test.ts @@ -8,11 +8,11 @@ import {AttestationPool} from "../../../../src/chain/opPools/attestationPool.js" import {getMockedClock} from "../../../mocks/clock.js"; /** Valid signature of random data to prevent BLS errors */ -export const validSignature = fromHexString( +const validSignature = fromHexString( "0xb2afb700f6c561ce5e1b4fedaec9d7c06b822d38c720cf588adfda748860a940adf51634b6788f298c552de40183b5a203b2bbe8b7dd147f0bb5bc97080a12efbb631c8888cb31a99cc4706eb3711865b8ea818c10126e4d818b542e9dbf9ae8" ); -describe("AttestationPool", function () { +describe("AttestationPool", () => { const config = createChainForkConfig({ ...defaultChainConfig, ELECTRA_FORK_EPOCH: 5, diff --git a/packages/beacon-node/test/unit/chain/opPools/syncCommittee.test.ts b/packages/beacon-node/test/unit/chain/opPools/syncCommittee.test.ts index 507c78d560b6..e91eaa58aa73 100644 --- a/packages/beacon-node/test/unit/chain/opPools/syncCommittee.test.ts +++ b/packages/beacon-node/test/unit/chain/opPools/syncCommittee.test.ts @@ -7,7 +7,7 @@ import {Clock} from "../../../../src/util/clock.js"; vi.mock("../../../../src/util/clock.js"); -describe("chain / opPools / SyncCommitteeMessagePool", function () { +describe("chain / opPools / SyncCommitteeMessagePool", () => { let cache: SyncCommitteeMessagePool; const subcommitteeIndex = 2; const indexInSubcommittee = 3; @@ -33,7 +33,7 @@ describe("chain / opPools / SyncCommitteeMessagePool", function () { cache.add(subcommitteeIndex, syncCommittee, indexInSubcommittee); }); - afterEach(function () { + afterEach(() => { vi.clearAllTimers(); vi.clearAllMocks(); }); diff --git a/packages/beacon-node/test/unit/chain/opPools/syncCommitteeContribution.test.ts b/packages/beacon-node/test/unit/chain/opPools/syncCommitteeContribution.test.ts index e34a5d006272..e1bd60a2305e 100644 --- a/packages/beacon-node/test/unit/chain/opPools/syncCommitteeContribution.test.ts +++ b/packages/beacon-node/test/unit/chain/opPools/syncCommitteeContribution.test.ts @@ -15,7 +15,7 @@ import {EMPTY_SIGNATURE} from "../../../../src/constants/index.js"; import {renderBitArray} from "../../../utils/render.js"; import {VALID_BLS_SIGNATURE_RAND} from "../../../utils/typeGenerator.js"; -describe("chain / opPools / SyncContributionAndProofPool", function () { +describe("chain / opPools / SyncContributionAndProofPool", () => { let cache: SyncContributionAndProofPool; const beaconBlockRoot = Buffer.alloc(32, 1); const slot = 10; @@ -44,7 +44,7 @@ describe("chain / opPools / SyncContributionAndProofPool", function () { }); }); -describe("replaceIfBetter", function () { +describe("replaceIfBetter", () => { const numParticipants = 2; let bestContribution: SyncContributionFast; // const subnetSize = Math.floor(SYNC_COMMITTEE_SIZE / SYNC_COMMITTEE_SUBNET_COUNT); @@ -77,7 +77,7 @@ describe("replaceIfBetter", function () { }); }); -describe("aggregate", function () { +describe("aggregate", () => { const sks: SecretKey[] = []; let bestContributionBySubnet: Map; beforeAll(async () => { diff --git a/packages/beacon-node/test/unit/chain/reprocess.test.ts b/packages/beacon-node/test/unit/chain/reprocess.test.ts index a8160544f509..927e4cf8d05f 100644 --- a/packages/beacon-node/test/unit/chain/reprocess.test.ts +++ b/packages/beacon-node/test/unit/chain/reprocess.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect, beforeEach} from "vitest"; import {ReprocessController} from "../../../src/chain/reprocess.js"; -describe("ReprocessController", function () { +describe("ReprocessController", () => { let controller: ReprocessController; beforeEach(() => { diff --git a/packages/beacon-node/test/unit/chain/seenCache/aggregateAndProof.test.ts b/packages/beacon-node/test/unit/chain/seenCache/aggregateAndProof.test.ts index 3118fdcadc43..d83433a649ca 100644 --- a/packages/beacon-node/test/unit/chain/seenCache/aggregateAndProof.test.ts +++ b/packages/beacon-node/test/unit/chain/seenCache/aggregateAndProof.test.ts @@ -6,7 +6,7 @@ import { SeenAggregatedAttestations, } from "../../../../src/chain/seenCache/seenAggregateAndProof.js"; -describe("SeenAggregatedAttestations.isKnown", function () { +describe("SeenAggregatedAttestations.isKnown", () => { const testCases: { id: string; seenAttestingBits: number[]; @@ -62,7 +62,7 @@ describe("SeenAggregatedAttestations.isKnown", function () { } }); -describe("insertDesc", function () { +describe("insertDesc", () => { const testCases: { id: string; arr: number[][]; diff --git a/packages/beacon-node/test/unit/chain/seenCache/syncCommittee.test.ts b/packages/beacon-node/test/unit/chain/seenCache/syncCommittee.test.ts index 901c19cad9f8..59c67f9cedc2 100644 --- a/packages/beacon-node/test/unit/chain/seenCache/syncCommittee.test.ts +++ b/packages/beacon-node/test/unit/chain/seenCache/syncCommittee.test.ts @@ -5,7 +5,7 @@ import {SeenSyncCommitteeMessages, SeenContributionAndProof} from "../../../../s const NUM_SLOTS_IN_CACHE = 3; -describe("chain / seenCache / SeenSyncCommittee caches", function () { +describe("chain / seenCache / SeenSyncCommittee caches", () => { describe("SeenSyncCommitteeMessages", () => { const slot = 10; const subnet = 2; diff --git a/packages/beacon-node/test/unit/chain/shufflingCache.test.ts b/packages/beacon-node/test/unit/chain/shufflingCache.test.ts index 3c1824b8c01d..d417e555872c 100644 --- a/packages/beacon-node/test/unit/chain/shufflingCache.test.ts +++ b/packages/beacon-node/test/unit/chain/shufflingCache.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect, beforeEach} from "vitest"; import {generateTestCachedBeaconStateOnlyValidators} from "../../../../state-transition/test/perf/util.js"; import {ShufflingCache} from "../../../src/chain/shufflingCache.js"; -describe("ShufflingCache", function () { +describe("ShufflingCache", () => { const vc = 64; const stateSlot = 100; const state = generateTestCachedBeaconStateOnlyValidators({vc, slot: stateSlot}); @@ -19,11 +19,11 @@ describe("ShufflingCache", function () { ]); }); - it("should get shuffling from cache", async function () { + it("should get shuffling from cache", async () => { expect(await shufflingCache.get(currentEpoch, currentDecisionRoot)).toEqual(state.epochCtx.currentShuffling); }); - it("should bound by maxSize(=1)", async function () { + it("should bound by maxSize(=1)", async () => { expect(await shufflingCache.get(currentEpoch, currentDecisionRoot)).toEqual(state.epochCtx.currentShuffling); // insert promises at the same epoch does not prune the cache shufflingCache.insertPromise(currentEpoch, "0x00"); @@ -34,7 +34,7 @@ describe("ShufflingCache", function () { expect(await shufflingCache.get(currentEpoch, currentDecisionRoot)).toBeNull(); }); - it("should return shuffling from promise", async function () { + it("should return shuffling from promise", async () => { const previousEpoch = state.epochCtx.epoch - 1; const previousDecisionRoot = state.epochCtx.previousDecisionRoot; shufflingCache.insertPromise(previousEpoch, previousDecisionRoot); @@ -45,7 +45,7 @@ describe("ShufflingCache", function () { expect(await shufflingRequest1).toEqual(state.epochCtx.previousShuffling); }); - it("should support up to 2 promises at a time", async function () { + it("should support up to 2 promises at a time", async () => { // insert 2 promises at the same epoch shufflingCache.insertPromise(currentEpoch, "0x00"); shufflingCache.insertPromise(currentEpoch, "0x01"); diff --git a/packages/beacon-node/test/unit/chain/stateCache/blockStateCacheImpl.test.ts b/packages/beacon-node/test/unit/chain/stateCache/blockStateCacheImpl.test.ts index b89a71399237..19dc0f3a2c60 100644 --- a/packages/beacon-node/test/unit/chain/stateCache/blockStateCacheImpl.test.ts +++ b/packages/beacon-node/test/unit/chain/stateCache/blockStateCacheImpl.test.ts @@ -7,7 +7,7 @@ import {BlockStateCacheImpl} from "../../../../src/chain/stateCache/index.js"; import {generateCachedState} from "../../../utils/state.js"; import {ZERO_HASH} from "../../../../src/constants/index.js"; -describe("BlockStateCacheImpl", function () { +describe("BlockStateCacheImpl", () => { let cache: BlockStateCacheImpl; let key1: Root, key2: Root; const shuffling: EpochShuffling = { @@ -18,7 +18,7 @@ describe("BlockStateCacheImpl", function () { committeesPerSlot: 1, }; - beforeEach(function () { + beforeEach(() => { // max 2 items cache = new BlockStateCacheImpl({maxStates: 2}); const state1 = generateCachedState({slot: 0}); @@ -31,7 +31,7 @@ describe("BlockStateCacheImpl", function () { cache.add(state2); }); - it("should prune", function () { + it("should prune", () => { expect(cache.size).toBe(2); const state3 = generateCachedState({slot: 2 * SLOTS_PER_EPOCH}); state3.epochCtx.currentShuffling = {...shuffling, epoch: 2}; @@ -46,7 +46,7 @@ describe("BlockStateCacheImpl", function () { expect(cache.get(toHexString(key2))).toBeDefined(); }); - it("should deleteAllBeforeEpoch", function () { + it("should deleteAllBeforeEpoch", () => { cache.deleteAllBeforeEpoch(2); expect(cache.size).toBe(0); }); diff --git a/packages/beacon-node/test/unit/chain/stateCache/fifoBlockStateCache.test.ts b/packages/beacon-node/test/unit/chain/stateCache/fifoBlockStateCache.test.ts index b4aac92dd9bb..07a8ec12093d 100644 --- a/packages/beacon-node/test/unit/chain/stateCache/fifoBlockStateCache.test.ts +++ b/packages/beacon-node/test/unit/chain/stateCache/fifoBlockStateCache.test.ts @@ -5,7 +5,7 @@ import {SLOTS_PER_EPOCH} from "@lodestar/params"; import {FIFOBlockStateCache} from "../../../../src/chain/stateCache/index.js"; import {generateCachedState} from "../../../utils/state.js"; -describe("FIFOBlockStateCache", function () { +describe("FIFOBlockStateCache", () => { let cache: FIFOBlockStateCache; const shuffling: EpochShuffling = { epoch: 0, @@ -27,7 +27,7 @@ describe("FIFOBlockStateCache", function () { const key3 = toHexString(state3.hashTreeRoot()); state3.epochCtx.currentShuffling = {...shuffling, epoch: 2}; - beforeEach(function () { + beforeEach(() => { // max 2 items cache = new FIFOBlockStateCache({maxBlockStates: 2}, {}); cache.add(state1); diff --git a/packages/beacon-node/test/unit/chain/stateCache/inMemoryCheckpointsCache.test.ts b/packages/beacon-node/test/unit/chain/stateCache/inMemoryCheckpointsCache.test.ts index 59f320178118..23a792bef0a8 100644 --- a/packages/beacon-node/test/unit/chain/stateCache/inMemoryCheckpointsCache.test.ts +++ b/packages/beacon-node/test/unit/chain/stateCache/inMemoryCheckpointsCache.test.ts @@ -9,7 +9,7 @@ import { } from "../../../../src/chain/stateCache/inMemoryCheckpointsCache.js"; import {generateCachedState} from "../../../utils/state.js"; -describe("InMemoryCheckpointStateCache", function () { +describe("InMemoryCheckpointStateCache", () => { let root0a: Buffer, root0b: Buffer, root1: Buffer, root2: Buffer; let cp0a: phase0.Checkpoint, cp0b: phase0.Checkpoint, cp1: phase0.Checkpoint, cp2: phase0.Checkpoint; let cp0aHex: CheckpointHex, cp0bHex: CheckpointHex, cp1Hex: CheckpointHex, cp2Hex: CheckpointHex; diff --git a/packages/beacon-node/test/unit/chain/stateCache/persistentCheckpointsCache.test.ts b/packages/beacon-node/test/unit/chain/stateCache/persistentCheckpointsCache.test.ts index 9614263b4312..f98b180fa983 100644 --- a/packages/beacon-node/test/unit/chain/stateCache/persistentCheckpointsCache.test.ts +++ b/packages/beacon-node/test/unit/chain/stateCache/persistentCheckpointsCache.test.ts @@ -12,7 +12,7 @@ import {getTestDatastore} from "../../../utils/chain/stateCache/datastore.js"; import {CheckpointHex} from "../../../../src/chain/stateCache/types.js"; import {FIFOBlockStateCache, toCheckpointHex} from "../../../../src/chain/index.js"; -describe("PersistentCheckpointStateCache", function () { +describe("PersistentCheckpointStateCache", () => { let root0a: Buffer, root0b: Buffer, root1: Buffer, root2: Buffer; let cp0a: phase0.Checkpoint, cp0b: phase0.Checkpoint, cp1: phase0.Checkpoint, cp2: phase0.Checkpoint; let cp0aHex: CheckpointHex, cp0bHex: CheckpointHex, cp1Hex: CheckpointHex, cp2Hex: CheckpointHex; @@ -135,7 +135,7 @@ describe("PersistentCheckpointStateCache", function () { expect((await cache.getOrReloadLatest(cp0bHex.rootHex, cp0b.epoch - 1))?.serialize()).toBeUndefined(); }); - it("pruneFinalized and getStateOrBytes", async function () { + it("pruneFinalized and getStateOrBytes", async () => { cache.add(cp2, states["cp2"]); expect(((await cache.getStateOrBytes(cp0bHex)) as CachedBeaconStateAllForks).hashTreeRoot()).toEqual( states["cp0b"].hashTreeRoot() @@ -182,7 +182,7 @@ describe("PersistentCheckpointStateCache", function () { // |0b--------root1--------root2 // | // 0a - it("single state at lowest memory epoch", async function () { + it("single state at lowest memory epoch", async () => { cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); expect(cache.findSeedStateToReload(cp0aHex)?.hashTreeRoot()).toEqual(states["cp1"].hashTreeRoot()); @@ -198,7 +198,7 @@ describe("PersistentCheckpointStateCache", function () { // 0a------------------------------root3 // ^ ^ // cp1a={0a, 21} {0a, 22}=cp2a - it("multiple states at lowest memory epoch", async function () { + it("multiple states at lowest memory epoch", async () => { cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); @@ -259,7 +259,7 @@ describe("PersistentCheckpointStateCache", function () { // |0b--------root1--------root2-----root3 // | // 0a - it("no reorg", async function () { + it("no reorg", async () => { expect(fileApisBuffer.size).toEqual(0); cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); @@ -293,7 +293,7 @@ describe("PersistentCheckpointStateCache", function () { // |0b--------root1--------root2-root3 | // | | // 0a |---------root4 - it("reorg in same epoch", async function () { + it("reorg in same epoch", async () => { // mostly the same to the above test expect(fileApisBuffer.size).toEqual(0); cache.add(cp2, states["cp2"]); @@ -338,7 +338,7 @@ describe("PersistentCheckpointStateCache", function () { // 1a ^ // | // {1a, 22}=cp2a - it("reorg 1 epoch", async function () { + it("reorg 1 epoch", async () => { // process root2 state cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); @@ -382,7 +382,7 @@ describe("PersistentCheckpointStateCache", function () { // 0a ^ ^ // | | // cp1a={0a, 21} {0a, 22}=cp2a - it("reorg 2 epochs", async function () { + it("reorg 2 epochs", async () => { // process root2 state cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); @@ -435,7 +435,7 @@ describe("PersistentCheckpointStateCache", function () { // ^ ^ // | | // cp1a={0a, 21} {0a, 22}=cp2a - it("reorg 3 epochs, persist cp 0a", async function () { + it("reorg 3 epochs, persist cp 0a", async () => { // process root2 state cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); @@ -491,7 +491,7 @@ describe("PersistentCheckpointStateCache", function () { // 0a ^ ^ // | | // cp1b={0b, 21} {0b, 22}=cp2b - it("reorg 3 epochs, prune but no persist", async function () { + it("reorg 3 epochs, prune but no persist", async () => { // process root2 state cache.add(cp2, states["cp2"]); expect(await cache.processState(toHexString(cp2.root), states["cp2"])).toEqual(1); 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/chain/validation/block.test.ts b/packages/beacon-node/test/unit/chain/validation/block.test.ts index 28375f1625e1..f8a2b7245ef7 100644 --- a/packages/beacon-node/test/unit/chain/validation/block.test.ts +++ b/packages/beacon-node/test/unit/chain/validation/block.test.ts @@ -12,7 +12,7 @@ import {EMPTY_SIGNATURE, ZERO_HASH} from "../../../../src/constants/index.js"; import {expectRejectedWithLodestarError} from "../../../utils/errors.js"; import {generateCachedState} from "../../../utils/state.js"; -describe("gossip block validation", function () { +describe("gossip block validation", () => { let chain: MockedBeaconChain; let forkChoice: MockedBeaconChain["forkChoice"]; let regen: Mocked; @@ -25,7 +25,7 @@ describe("gossip block validation", function () { const signature = EMPTY_SIGNATURE; const maxSkipSlots = 10; - beforeEach(function () { + beforeEach(() => { chain = getMockedBeaconChain(); vi.spyOn(chain.clock, "currentSlotWithGossipDisparity", "get").mockReturnValue(clockSlot); forkChoice = chain.forkChoice; @@ -49,7 +49,7 @@ describe("gossip block validation", function () { job = {signature, message: block}; }); - it("FUTURE_SLOT", async function () { + it("FUTURE_SLOT", async () => { // Set the block slot to after the current clock const signedBlock = {signature, message: {...block, slot: clockSlot + 1}}; @@ -59,7 +59,7 @@ describe("gossip block validation", function () { ); }); - it("WOULD_REVERT_FINALIZED_SLOT", async function () { + it("WOULD_REVERT_FINALIZED_SLOT", async () => { // Set finalized epoch to be greater than block's epoch forkChoice.getFinalizedCheckpoint.mockReturnValue({epoch: Infinity, root: ZERO_HASH, rootHex: ""}); @@ -69,7 +69,7 @@ describe("gossip block validation", function () { ); }); - it("ALREADY_KNOWN", async function () { + it("ALREADY_KNOWN", async () => { // Make the fork choice return a block summary for the proposed block forkChoice.getBlockHex.mockReturnValue({} as ProtoBlock); @@ -79,7 +79,7 @@ describe("gossip block validation", function () { ); }); - it("REPEAT_PROPOSAL", async function () { + it("REPEAT_PROPOSAL", async () => { // Register the proposer as known chain.seenBlockProposers.add(job.message.slot, job.message.proposerIndex); @@ -89,7 +89,7 @@ describe("gossip block validation", function () { ); }); - it("PARENT_UNKNOWN (fork-choice)", async function () { + it("PARENT_UNKNOWN (fork-choice)", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Return not known for parent block too @@ -101,7 +101,7 @@ describe("gossip block validation", function () { ); }); - it("TOO_MANY_SKIPPED_SLOTS", async function () { + it("TOO_MANY_SKIPPED_SLOTS", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Return parent block with 1 slot way back than maxSkipSlots @@ -113,7 +113,7 @@ describe("gossip block validation", function () { ); }); - it("NOT_LATER_THAN_PARENT", async function () { + it("NOT_LATER_THAN_PARENT", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Returned parent block is latter than proposed block @@ -125,7 +125,7 @@ describe("gossip block validation", function () { ); }); - it("PARENT_UNKNOWN (regen)", async function () { + it("PARENT_UNKNOWN (regen)", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Returned parent block is latter than proposed block @@ -139,7 +139,7 @@ describe("gossip block validation", function () { ); }); - it("PROPOSAL_SIGNATURE_INVALID", async function () { + it("PROPOSAL_SIGNATURE_INVALID", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Returned parent block is latter than proposed block @@ -155,7 +155,7 @@ describe("gossip block validation", function () { ); }); - it("INCORRECT_PROPOSER", async function () { + it("INCORRECT_PROPOSER", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Returned parent block is latter than proposed block @@ -174,7 +174,7 @@ describe("gossip block validation", function () { ); }); - it("valid", async function () { + it("valid", async () => { // Return not known for proposed block forkChoice.getBlockHex.mockReturnValueOnce(null); // Returned parent block is latter than proposed block diff --git a/packages/beacon-node/test/unit/chain/validation/lightClientFinalityUpdate.test.ts b/packages/beacon-node/test/unit/chain/validation/lightClientFinalityUpdate.test.ts index 76eb18fc38eb..cbd231c926ce 100644 --- a/packages/beacon-node/test/unit/chain/validation/lightClientFinalityUpdate.test.ts +++ b/packages/beacon-node/test/unit/chain/validation/lightClientFinalityUpdate.test.ts @@ -8,7 +8,7 @@ import {LightClientErrorCode} from "../../../../src/chain/errors/lightClientErro import {IBeaconChain} from "../../../../src/chain/index.js"; import {getMockedBeaconChain} from "../../../mocks/mockedBeaconChain.js"; -describe("Light Client Finality Update validation", function () { +describe("Light Client Finality Update validation", () => { const afterEachCallbacks: (() => Promise | void)[] = []; const config = createChainForkConfig({ ...defaultChainConfig, diff --git a/packages/beacon-node/test/unit/chain/validation/lightClientOptimisticUpdate.test.ts b/packages/beacon-node/test/unit/chain/validation/lightClientOptimisticUpdate.test.ts index 7e35f1272ad6..7665b4f89179 100644 --- a/packages/beacon-node/test/unit/chain/validation/lightClientOptimisticUpdate.test.ts +++ b/packages/beacon-node/test/unit/chain/validation/lightClientOptimisticUpdate.test.ts @@ -8,7 +8,7 @@ import {LightClientErrorCode} from "../../../../src/chain/errors/lightClientErro import {IBeaconChain} from "../../../../src/chain/index.js"; import {getMockedBeaconChain} from "../../../mocks/mockedBeaconChain.js"; -describe("Light Client Optimistic Update validation", function () { +describe("Light Client Optimistic Update validation", () => { const afterEachCallbacks: (() => Promise | void)[] = []; const config = createChainForkConfig({ ...defaultChainConfig, diff --git a/packages/beacon-node/test/unit/chain/validation/syncCommittee.test.ts b/packages/beacon-node/test/unit/chain/validation/syncCommittee.test.ts index 26571ab19a77..cbffc2a4ffd9 100644 --- a/packages/beacon-node/test/unit/chain/validation/syncCommittee.test.ts +++ b/packages/beacon-node/test/unit/chain/validation/syncCommittee.test.ts @@ -12,7 +12,7 @@ import {SeenSyncCommitteeMessages} from "../../../../src/chain/seenCache/index.j import {ZERO_HASH} from "../../../../src/constants/constants.js"; // https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/altair/p2p-interface.md -describe("Sync Committee Signature validation", function () { +describe("Sync Committee Signature validation", () => { let chain: MockedBeaconChain; let clockStub: MockedBeaconChain["clock"]; let forkchoiceStub: MockedBeaconChain["forkChoice"]; @@ -24,16 +24,16 @@ describe("Sync Committee Signature validation", function () { // all validators have same pubkey const validatorIndexInSyncCommittee = 15; - beforeAll(async function () { + beforeAll(async () => { altairForkEpochBk = config.ALTAIR_FORK_EPOCH; config.ALTAIR_FORK_EPOCH = altairForkEpoch; }); - afterAll(function () { + afterAll(() => { config.ALTAIR_FORK_EPOCH = altairForkEpochBk; }); - beforeEach(function () { + beforeEach(() => { chain = getMockedBeaconChain(); ( chain as { @@ -45,11 +45,11 @@ describe("Sync Committee Signature validation", function () { vi.spyOn(clockStub, "isCurrentSlotGivenGossipDisparity").mockReturnValue(true); }); - afterEach(function () { + afterEach(() => { vi.clearAllMocks(); }); - it("should throw error - the signature's slot is in the past", async function () { + it("should throw error - the signature's slot is in the past", async () => { (clockStub.isCurrentSlotGivenGossipDisparity as Mock).mockReturnValue(false); vi.spyOn(clockStub, "currentSlot", "get").mockReturnValue(100); @@ -60,7 +60,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should throw error - messageRoot is same to prevRoot", async function () { + it("should throw error - messageRoot is same to prevRoot", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, validatorIndexInSyncCommittee); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); chain.getHeadState.mockReturnValue(headState); @@ -71,7 +71,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should throw error - messageRoot is different to prevRoot but not forkchoice head", async function () { + it("should throw error - messageRoot is different to prevRoot but not forkchoice head", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, validatorIndexInSyncCommittee); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); chain.getHeadState.mockReturnValue(headState); @@ -84,7 +84,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should throw error - the validator is not part of the current sync committee", async function () { + it("should throw error - the validator is not part of the current sync committee", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, 100); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); chain.getHeadState.mockReturnValue(headState); @@ -99,7 +99,7 @@ describe("Sync Committee Signature validation", function () { * Skip this spec check: [REJECT] The subnet_id is correct, i.e. subnet_id in compute_subnets_for_sync_committee(state, sync_committee_signature.validator_index) * because it's the same to VALIDATOR_NOT_IN_SYNC_COMMITTEE */ - it.skip("should throw error - incorrect subnet", async function () { + it.skip("should throw error - incorrect subnet", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, 1); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); chain.getHeadState.mockReturnValue(headState); @@ -109,7 +109,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should throw error - invalid signature", async function () { + it("should throw error - invalid signature", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, validatorIndexInSyncCommittee); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); @@ -121,7 +121,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should pass, no prev root", async function () { + it("should pass, no prev root", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, validatorIndexInSyncCommittee); const subnet = 3; const {slot, validatorIndex} = syncCommittee; @@ -142,7 +142,7 @@ describe("Sync Committee Signature validation", function () { ); }); - it("should pass, there is prev root but message root is forkchoice head", async function () { + it("should pass, there is prev root but message root is forkchoice head", async () => { const syncCommittee = getSyncCommitteeSignature(currentSlot, validatorIndexInSyncCommittee); const headState = generateCachedAltairState({slot: currentSlot}, altairForkEpoch); diff --git a/packages/beacon-node/test/unit/db/api/repositories/blockArchive.test.ts b/packages/beacon-node/test/unit/db/api/repositories/blockArchive.test.ts index 532016242f95..b87e9b926fdd 100644 --- a/packages/beacon-node/test/unit/db/api/repositories/blockArchive.test.ts +++ b/packages/beacon-node/test/unit/db/api/repositories/blockArchive.test.ts @@ -9,21 +9,21 @@ import {BlockArchiveRepository} from "../../../../../src/db/repositories/index.j import {testLogger} from "../../../../utils/logger.js"; import {Bucket} from "../../../../../src/db/buckets.js"; -describe("block archive repository", function () { +describe("block archive repository", () => { const testDir = "./.tmp"; let blockArchive: BlockArchiveRepository; let db: LevelDbController; - beforeEach(async function () { + beforeEach(async () => { db = await LevelDbController.create({name: testDir}, {logger: testLogger()}); blockArchive = new BlockArchiveRepository(config, db); }); - afterEach(async function () { + afterEach(async () => { await db.close(); rimraf.sync(testDir); }); - it("should retrieve blocks in order", async function () { + it("should retrieve blocks in order", async () => { await blockArchive.batchPut( Array.from({length: 1001}, (_, i) => { const slot = i; @@ -106,7 +106,7 @@ describe("block archive repository", function () { } }); - it("should store indexes when adding single block", async function () { + it("should store indexes when adding single block", async () => { const spy = vi.spyOn(db, "put"); const block = ssz.phase0.SignedBeaconBlock.defaultValue(); await blockArchive.add(block); @@ -120,7 +120,7 @@ describe("block archive repository", function () { ); }); - it("should store indexes when block batch", async function () { + it("should store indexes when block batch", async () => { const spy = vi.spyOn(db, "put"); const blocks = [ssz.phase0.SignedBeaconBlock.defaultValue(), ssz.phase0.SignedBeaconBlock.defaultValue()]; await blockArchive.batchAdd(blocks); @@ -152,14 +152,14 @@ describe("block archive repository", function () { ); }); - it("should get slot by root", async function () { + it("should get slot by root", async () => { const block = ssz.phase0.SignedBeaconBlock.defaultValue(); await blockArchive.add(block); const slot = await blockArchive.getSlotByRoot(ssz.phase0.BeaconBlock.hashTreeRoot(block.message)); expect(slot).toBe(block.message.slot); }); - it("should get block by root", async function () { + it("should get block by root", async () => { const block = ssz.phase0.SignedBeaconBlock.defaultValue(); await blockArchive.add(block); const retrieved = await blockArchive.getByRoot(ssz.phase0.BeaconBlock.hashTreeRoot(block.message)); @@ -167,14 +167,14 @@ describe("block archive repository", function () { expect(ssz.phase0.SignedBeaconBlock.equals(retrieved, block)).toBe(true); }); - it("should get slot by parent root", async function () { + it("should get slot by parent root", async () => { const block = ssz.phase0.SignedBeaconBlock.defaultValue(); await blockArchive.add(block); const slot = await blockArchive.getSlotByParentRoot(block.message.parentRoot); expect(slot).toBe(block.message.slot); }); - it("should get block by parent root", async function () { + it("should get block by parent root", async () => { const block = ssz.phase0.SignedBeaconBlock.defaultValue(); await blockArchive.add(block); const retrieved = await blockArchive.getByParentRoot(block.message.parentRoot); diff --git a/packages/beacon-node/test/unit/db/api/repository.test.ts b/packages/beacon-node/test/unit/db/api/repository.test.ts index 28065c84c7ea..3b2840b3f0be 100644 --- a/packages/beacon-node/test/unit/db/api/repository.test.ts +++ b/packages/beacon-node/test/unit/db/api/repository.test.ts @@ -41,10 +41,10 @@ class TestRepository extends Repository { } } -describe("database repository", function () { +describe("database repository", () => { let repository: TestRepository, controller: MockedObject; - beforeEach(function () { + beforeEach(() => { controller = vi.mocked(new LevelDbController({} as any, {} as any, {} as any)); repository = new TestRepository(controller as unknown as LevelDbController); }); @@ -53,7 +53,7 @@ describe("database repository", function () { vi.clearAllMocks(); }); - it("should get single item", async function () { + it("should get single item", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; controller.get.mockResolvedValue(TestSSZType.serialize(item) as Buffer); const result = await repository.get("id"); @@ -61,14 +61,14 @@ describe("database repository", function () { expect(controller.get).toHaveBeenCalledTimes(1); }); - it("should return null if item not found", async function () { + it("should return null if item not found", async () => { controller.get.mockResolvedValue(null); const result = await repository.get("id"); expect(result).toEqual(null); expect(controller.get).toHaveBeenCalledTimes(1); }); - it("should return true if item exists", async function () { + it("should return true if item exists", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; controller.get.mockResolvedValue(TestSSZType.serialize(item) as Buffer); const result = await repository.has("id"); @@ -76,31 +76,31 @@ describe("database repository", function () { expect(controller.get).toHaveBeenCalledTimes(1); }); - it("should return false if item doesnt exists", async function () { + it("should return false if item doesnt exists", async () => { controller.get.mockResolvedValue(null); const result = await repository.has("id"); expect(result).toBe(false); expect(controller.get).toHaveBeenCalledTimes(1); }); - it("should store with hashTreeRoot as id", async function () { + it("should store with hashTreeRoot as id", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; await expect(repository.add(item)).resolves.toBeUndefined(); expect(controller.put).toHaveBeenCalledTimes(1); }); - it("should store with given id", async function () { + it("should store with given id", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; await expect(repository.put("1", item)).resolves.toBeUndefined(); expect(controller.put).toHaveBeenCalledTimes(1); }); - it("should delete", async function () { + it("should delete", async () => { await expect(repository.delete("1")).resolves.toBeUndefined(); expect(controller.delete).toHaveBeenCalledTimes(1); }); - it("should return all items", async function () { + it("should return all items", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; const itemSerialized = TestSSZType.serialize(item); const items = [itemSerialized, itemSerialized, itemSerialized]; @@ -110,24 +110,24 @@ describe("database repository", function () { expect(controller.values).toHaveBeenCalledTimes(1); }); - it("should return range of items", async function () { + it("should return range of items", async () => { await repository.values({gt: "a", lt: "b"}); expect(controller.values).toHaveBeenCalledTimes(1); }); - it("should delete given items", async function () { + it("should delete given items", async () => { await repository.batchDelete(["1", "2", "3"]); expect(controller.batchDelete.mock.calls[0][0]).toHaveLength(3); }); - it("should delete given items by value", async function () { + it("should delete given items by value", async () => { const item = {bool: true, bytes: Buffer.alloc(32)}; await repository.batchRemove([item, item]); expect(controller.batchDelete.mock.calls[0][0]).toHaveLength(2); }); - it("should add multiple values", async function () { + it("should add multiple values", async () => { await repository.batchAdd([ {bool: true, bytes: Buffer.alloc(32)}, {bool: false, bytes: Buffer.alloc(32)}, @@ -136,7 +136,7 @@ describe("database repository", function () { expect(controller.batchPut.mock.calls[0][0]).toHaveLength(2); }); - it("should fetch values stream", async function () { + it("should fetch values stream", async () => { async function* sample(): AsyncGenerator { yield TestSSZType.serialize({bool: true, bytes: Buffer.alloc(32)}) as Buffer; yield TestSSZType.serialize({bool: false, bytes: Buffer.alloc(32)}) as Buffer; diff --git a/packages/beacon-node/test/unit/db/buckets.test.ts b/packages/beacon-node/test/unit/db/buckets.test.ts index 0fb09af95cbc..c7c11d831427 100644 --- a/packages/beacon-node/test/unit/db/buckets.test.ts +++ b/packages/beacon-node/test/unit/db/buckets.test.ts @@ -6,7 +6,7 @@ describe("db buckets", () => { let prevBucket = -1; for (const key of Object.keys(Bucket)) { - if (isNaN(parseInt(key))) { + if (Number.isNaN(parseInt(key))) { const bucket = (Bucket as unknown as Record)[key]; if (bucket < prevBucket) { throw Error(`Bucket ${key} not sorted`); diff --git a/packages/beacon-node/test/unit/eth1/eth1DepositDataTracker.test.ts b/packages/beacon-node/test/unit/eth1/eth1DepositDataTracker.test.ts index d0bd3faffcf8..40988ed21728 100644 --- a/packages/beacon-node/test/unit/eth1/eth1DepositDataTracker.test.ts +++ b/packages/beacon-node/test/unit/eth1/eth1DepositDataTracker.test.ts @@ -8,7 +8,7 @@ import {defaultEth1Options} from "../../../src/eth1/options.js"; import {BeaconDb} from "../../../src/db/beacon.js"; import {getMockedBeaconDb} from "../../mocks/mockedBeaconDb.js"; -describe("Eth1DepositDataTracker", function () { +describe("Eth1DepositDataTracker", () => { const controller = new AbortController(); const logger = testLogger(); @@ -43,7 +43,7 @@ describe("Eth1DepositDataTracker", function () { vi.clearAllMocks(); }); - it("Should dynamically adjust blocks batch size", async function () { + it("Should dynamically adjust blocks batch size", async () => { let expectedSize = 1000; expect(eth1DepositDataTracker["eth1GetBlocksBatchSizeDynamic"]).toBe(expectedSize); @@ -66,7 +66,7 @@ describe("Eth1DepositDataTracker", function () { expect(expectedSize).toBe(1000); }); - it("Should dynamically adjust logs batch size", async function () { + it("Should dynamically adjust logs batch size", async () => { let expectedSize = 1000; expect(eth1DepositDataTracker["eth1GetLogsBatchSizeDynamic"]).toBe(expectedSize); diff --git a/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts b/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts index edf571b905b3..c7f4c8fb7aa4 100644 --- a/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts +++ b/packages/beacon-node/test/unit/eth1/eth1MergeBlockTracker.test.ts @@ -16,9 +16,7 @@ describe("eth1 / Eth1MergeBlockTracker", () => { let controller: AbortController; beforeEach(() => { controller = new AbortController(); - }); - afterEach(() => controller.abort()); - beforeEach(() => { + config = { // Set time units to 0 to make the test as fast as possible SECONDS_PER_ETH1_BLOCK: 0, @@ -29,6 +27,8 @@ describe("eth1 / Eth1MergeBlockTracker", () => { } as Partial as ChainConfig; }); + afterEach(() => controller.abort()); + it("Should find terminal pow block through TERMINAL_BLOCK_HASH", async () => { config.TERMINAL_BLOCK_HASH = Buffer.alloc(32, 1); const block: EthJsonRpcBlockRaw = { @@ -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/depositContract.test.ts b/packages/beacon-node/test/unit/eth1/utils/depositContract.test.ts index e36fc865a75a..22ca95765a9a 100644 --- a/packages/beacon-node/test/unit/eth1/utils/depositContract.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/depositContract.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect} from "vitest"; import {goerliTestnetLogs, goerliTestnetDepositEvents} from "../../../utils/testnet.js"; import {parseDepositLog} from "../../../../src/eth1/utils/depositContract.js"; -describe("eth1 / util / depositContract", function () { +describe("eth1 / util / depositContract", () => { it("Should parse a raw deposit log", () => { const depositEvents = goerliTestnetLogs.map((log) => parseDepositLog(log)); expect(depositEvents).toEqual(goerliTestnetDepositEvents); diff --git a/packages/beacon-node/test/unit/eth1/utils/deposits.test.ts b/packages/beacon-node/test/unit/eth1/utils/deposits.test.ts index 88d2796a12de..34334d1b3f8b 100644 --- a/packages/beacon-node/test/unit/eth1/utils/deposits.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/deposits.test.ts @@ -11,7 +11,7 @@ import {getDeposits, getDepositsWithProofs, DepositGetter} from "../../../../src import {DepositTree} from "../../../../src/db/repositories/depositDataRoot.js"; import {createCachedBeaconStateTest} from "../../../utils/cachedBeaconState.js"; -describe("eth1 / util / deposits", function () { +describe("eth1 / util / deposits", () => { describe("getDeposits", () => { type TestCase = { id: string; @@ -111,7 +111,7 @@ describe("eth1 / util / deposits", function () { for (const testCase of testCases) { const {id, depositIndexes, eth1DepositIndex, depositCount, expectedReturnedIndexes, error, postElectra} = testCase; - it(id, async function () { + it(id, async () => { const state = postElectra ? generateState({slot: postElectraSlot, eth1DepositIndex}, postElectraConfig) : generateState({eth1DepositIndex}); @@ -139,7 +139,7 @@ describe("eth1 / util / deposits", function () { }); describe("getDepositsWithProofs", () => { - it("return empty array if no pending deposits", function () { + it("return empty array if no pending deposits", () => { const initialValues = [Buffer.alloc(32)]; const depositRootTree = ssz.phase0.DepositDataRootList.toViewDU(initialValues); const depositCount = 0; @@ -149,7 +149,7 @@ describe("eth1 / util / deposits", function () { expect(deposits).toEqual([]); }); - it("return deposits with valid proofs", function () { + it("return deposits with valid proofs", () => { const depositEvents = Array.from( {length: 2}, (_, index): phase0.DepositEvent => ({ diff --git a/packages/beacon-node/test/unit/eth1/utils/eth1Data.test.ts b/packages/beacon-node/test/unit/eth1/utils/eth1Data.test.ts index 4b5bf74772b7..dff98500b293 100644 --- a/packages/beacon-node/test/unit/eth1/utils/eth1Data.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/eth1Data.test.ts @@ -12,7 +12,7 @@ import {expectRejectedWithLodestarError} from "../../../utils/errors.js"; import {Eth1ErrorCode} from "../../../../src/eth1/errors.js"; import {DepositTree} from "../../../../src/db/repositories/depositDataRoot.js"; -describe("eth1 / util / getEth1DataForBlocks", function () { +describe("eth1 / util / getEth1DataForBlocks", () => { type TestCase = { id: string; blocks: Eth1Block[]; @@ -95,7 +95,7 @@ describe("eth1 / util / getEth1DataForBlocks", function () { for (const testCase of testCases) { const {id, blocks, deposits, depositRootTree, lastProcessedDepositBlockNumber, expectedEth1Data, error} = testCase(); - it(id, async function () { + it(id, async () => { const eth1DatasPromise = getEth1DataForBlocks( blocks, // Simulate a descending stream reading from DB @@ -117,7 +117,7 @@ describe("eth1 / util / getEth1DataForBlocks", function () { } }); -describe("eth1 / util / getDepositsByBlockNumber", function () { +describe("eth1 / util / getDepositsByBlockNumber", () => { type TestCase = { id: string; fromBlock: number; @@ -181,7 +181,7 @@ describe("eth1 / util / getDepositsByBlockNumber", function () { for (const testCase of testCases) { const {id, fromBlock, toBlock, deposits, expectedResult} = testCase(); - it(id, async function () { + it(id, async () => { const result = await getDepositsByBlockNumber( fromBlock, toBlock, // Simulate a descending stream reading from DB @@ -192,7 +192,7 @@ describe("eth1 / util / getDepositsByBlockNumber", function () { } }); -describe("eth1 / util / getDepositRootByDepositCount", function () { +describe("eth1 / util / getDepositRootByDepositCount", () => { type TestCase = { id: string; depositCounts: number[]; @@ -243,7 +243,7 @@ describe("eth1 / util / getDepositRootByDepositCount", function () { for (const testCase of testCases) { const {id, depositCounts, depositRootTree, expectedMap} = testCase(); - it(id, function () { + it(id, () => { const map = getDepositRootByDepositCount(depositCounts, depositRootTree); expect(renderDepositRootByDepositCount(map)).toEqual(renderDepositRootByDepositCount(expectedMap)); }); diff --git a/packages/beacon-node/test/unit/eth1/utils/eth1DepositEvent.test.ts b/packages/beacon-node/test/unit/eth1/utils/eth1DepositEvent.test.ts index 7538dc0acf63..ea504464778c 100644 --- a/packages/beacon-node/test/unit/eth1/utils/eth1DepositEvent.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/eth1DepositEvent.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from "vitest"; import {assertConsecutiveDeposits} from "../../../../src/eth1/utils/eth1DepositEvent.js"; -describe("eth1 / util / assertConsecutiveDeposits", function () { +describe("eth1 / util / assertConsecutiveDeposits", () => { const testCases: { id: string; ok: boolean; diff --git a/packages/beacon-node/test/unit/eth1/utils/eth1Vote.test.ts b/packages/beacon-node/test/unit/eth1/utils/eth1Vote.test.ts index 0ad63e5e0d8f..e9a9ab5aad24 100644 --- a/packages/beacon-node/test/unit/eth1/utils/eth1Vote.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/eth1Vote.test.ts @@ -12,7 +12,7 @@ import { Eth1DataGetter, } from "../../../../src/eth1/utils/eth1Vote.js"; -describe("eth1 / util / eth1Vote", function () { +describe("eth1 / util / eth1Vote", () => { function generateEth1Vote(i: number): phase0.Eth1Data { return { blockHash: Buffer.alloc(32, i), @@ -21,7 +21,7 @@ describe("eth1 / util / eth1Vote", function () { }; } - describe("pickEth1Vote", function () { + describe("pickEth1Vote", () => { // Function array to scope votes in each test case defintion const testCases: (() => { id: string; @@ -82,7 +82,7 @@ describe("eth1 / util / eth1Vote", function () { for (const testCase of testCases) { const {id, eth1DataVotesInState, votesToConsider, expectedEth1Vote} = testCase(); - it(id, async function () { + it(id, async () => { const state = generateState({slot: 5, eth1DataVotes: eth1DataVotesInState}); const eth1Vote = pickEth1Vote(state, votesToConsider); expect(ssz.phase0.Eth1Data.toJson(eth1Vote)).toEqual(ssz.phase0.Eth1Data.toJson(expectedEth1Vote)); @@ -90,7 +90,7 @@ describe("eth1 / util / eth1Vote", function () { } }); - describe("getEth1VotesToConsider", function () { + describe("getEth1VotesToConsider", () => { // Function array to scope votes in each test case defintion const testCases: (() => { id: string; @@ -127,7 +127,7 @@ describe("eth1 / util / eth1Vote", function () { for (const testCase of testCases) { const {id, state, eth1Datas, expectedVotesToConsider} = testCase(); - it(`get votesToConsider: ${id}`, async function () { + it(`get votesToConsider: ${id}`, async () => { const eth1DataGetter: Eth1DataGetter = async ({timestampRange}) => filterBy(eth1Datas, timestampRange, (eth1Data) => eth1Data.timestamp); diff --git a/packages/beacon-node/test/unit/eth1/utils/groupDepositEventsByBlock.test.ts b/packages/beacon-node/test/unit/eth1/utils/groupDepositEventsByBlock.test.ts index 5712d1095270..a4e786b3aa68 100644 --- a/packages/beacon-node/test/unit/eth1/utils/groupDepositEventsByBlock.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/groupDepositEventsByBlock.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect} from "vitest"; import {phase0} from "@lodestar/types"; import {groupDepositEventsByBlock} from "../../../../src/eth1/utils/groupDepositEventsByBlock.js"; -describe("eth1 / util / groupDepositEventsByBlock", function () { +describe("eth1 / util / groupDepositEventsByBlock", () => { it("should return deposit events by block sorted by index", () => { const depositData = { amount: 0, 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..39c4a4d6e773 100644 --- a/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts +++ b/packages/beacon-node/test/unit/eth1/utils/optimizeNextBlockDiffForGenesis.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect} from "vitest"; import {optimizeNextBlockDiffForGenesis} from "../../../../src/eth1/utils/optimizeNextBlockDiffForGenesis.js"; import {Eth1Block} from "../../../../src/eth1/interface.js"; -describe("eth1 / utils / optimizeNextBlockDiffForGenesis", function () { +describe("eth1 / utils / optimizeNextBlockDiffForGenesis", () => { it("should return optimized block diff to find genesis time", () => { const params = { MIN_GENESIS_TIME: 1578009600, @@ -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..b254fc9d8b45 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 () => { @@ -56,8 +56,8 @@ describe("ExecutionEngine / http ", () => { ); }); - describe("notifyForkchoiceUpdate", function () { - it("notifyForkchoiceUpdate no retry when no pay load attributes", async function () { + describe("notifyForkchoiceUpdate", () => { + it("notifyForkchoiceUpdate no retry when no pay load attributes", async () => { errorResponsesBeforeSuccess = 2; const forkChoiceHeadData = { headBlockHash: "0xb084c10440f05f5a23a55d1d7ebcb1b3892935fb56f23cdc9a7f42c348eed174", @@ -85,7 +85,7 @@ describe("ExecutionEngine / http ", () => { expect(errorResponsesBeforeSuccess).toBe(1); }); - it("notifyForkchoiceUpdate with retry when pay load attributes", async function () { + it("notifyForkchoiceUpdate with retry when pay load attributes", async () => { errorResponsesBeforeSuccess = defaultExecutionEngineHttpOpts.retries - 1; const forkChoiceHeadData = { headBlockHash: "0xb084c10440f05f5a23a55d1d7ebcb1b3892935fb56f23cdc9a7f42c348eed174", diff --git a/packages/beacon-node/test/unit/monitoring/remoteService.ts b/packages/beacon-node/test/unit/monitoring/remoteService.ts index bea50eee3bdd..d407adb9d175 100644 --- a/packages/beacon-node/test/unit/monitoring/remoteService.ts +++ b/packages/beacon-node/test/unit/monitoring/remoteService.ts @@ -22,7 +22,7 @@ export const remoteServiceError: RemoteServiceError = {status: "error", data: nu export async function startRemoteService(): Promise<{baseUrl: URL}> { const server = fastify(); - server.post(remoteServiceRoutes.success, {}, async function (request, reply) { + server.post(remoteServiceRoutes.success, {}, async (request, reply) => { if (Array.isArray(request.body)) { request.body.forEach(validateRequestData); } else { @@ -32,11 +32,9 @@ export async function startRemoteService(): Promise<{baseUrl: URL}> { return reply.status(200).send(); }); - server.post(remoteServiceRoutes.error, {}, async function (_request, reply) { - return reply.status(400).send(remoteServiceError); - }); + server.post(remoteServiceRoutes.error, {}, async (_request, reply) => reply.status(400).send(remoteServiceError)); - server.post(remoteServiceRoutes.pending, {}, function () { + server.post(remoteServiceRoutes.pending, {}, () => { // keep request pending until timeout is reached or aborted }); @@ -74,7 +72,7 @@ function validateRequestData(data: ReceivedData): void { } function validateClientStats(data: ReceivedData, schema: ClientStatsSchema): void { - schema.forEach((s) => { + for (const s of schema) { try { expect(data[s.key]).toBeInstanceOf(s.type); } catch (_e) { @@ -82,5 +80,5 @@ function validateClientStats(data: ReceivedData, schema: ClientStatsSchema): voi `Validation of property "${s.key}" failed. Expected type "${s.type}" but received "${typeof data[s.key]}".` ); } - }); + } } diff --git a/packages/beacon-node/test/unit/monitoring/service.test.ts b/packages/beacon-node/test/unit/monitoring/service.test.ts index 0795a165538e..fed64b9bc553 100644 --- a/packages/beacon-node/test/unit/monitoring/service.test.ts +++ b/packages/beacon-node/test/unit/monitoring/service.test.ts @@ -169,7 +169,7 @@ describe("monitoring / service", () => { service?.close(); }); - (["beacon", "validator"] as const).forEach((client) => { + for (const client of ["beacon", "validator"] as const) { it(`should collect and send ${client} stats to remote service`, async () => { const endpoint = `${baseUrl}${remoteServiceRoutes.success}`; service = new MonitoringService(client, {endpoint, collectSystemStats: true}, {register, logger}); @@ -181,7 +181,7 @@ describe("monitoring / service", () => { // Fail test if warning was logged due to a 500 response. expect(logger.warn).not.toHaveBeenCalledWith("Failed to send client stats"); }); - }); + } it("should properly handle remote service errors", async () => { const endpoint = `${baseUrl}${remoteServiceRoutes.error}`; diff --git a/packages/beacon-node/test/unit/network/beaconBlocksMaybeBlobsByRange.test.ts b/packages/beacon-node/test/unit/network/beaconBlocksMaybeBlobsByRange.test.ts index dda4959c7b3e..2104235e7215 100644 --- a/packages/beacon-node/test/unit/network/beaconBlocksMaybeBlobsByRange.test.ts +++ b/packages/beacon-node/test/unit/network/beaconBlocksMaybeBlobsByRange.test.ts @@ -10,7 +10,7 @@ import {INetwork} from "../../../src/network/interface.js"; import {ZERO_HASH} from "../../../src/constants/constants.js"; describe("beaconBlocksMaybeBlobsByRange", () => { - beforeAll(async function () { + beforeAll(async () => { await initCKZG(); loadEthereumTrustedSetup(); }); diff --git a/packages/beacon-node/test/unit/network/gossip/topic.test.ts b/packages/beacon-node/test/unit/network/gossip/topic.test.ts index dbaa4002bfcc..2a61d8604439 100644 --- a/packages/beacon-node/test/unit/network/gossip/topic.test.ts +++ b/packages/beacon-node/test/unit/network/gossip/topic.test.ts @@ -4,7 +4,7 @@ import {GossipType, GossipEncoding, GossipTopicMap} from "../../../../src/networ import {parseGossipTopic, stringifyGossipTopic} from "../../../../src/network/gossip/topic.js"; import {config} from "../../../utils/config.js"; -describe("network / gossip / topic", function () { +describe("network / gossip / topic", () => { const encoding = GossipEncoding.ssz_snappy; // Enforce with Typescript that we test all GossipType diff --git a/packages/beacon-node/test/unit/network/metadata.test.ts b/packages/beacon-node/test/unit/network/metadata.test.ts index 12bd9b168425..50e4157a29cd 100644 --- a/packages/beacon-node/test/unit/network/metadata.test.ts +++ b/packages/beacon-node/test/unit/network/metadata.test.ts @@ -4,7 +4,7 @@ import {ssz} from "@lodestar/types"; import {getENRForkID} from "../../../src/network/metadata.js"; import {config} from "../../utils/config.js"; -describe("network / metadata / getENRForkID", function () { +describe("network / metadata / getENRForkID", () => { // At 0, next fork is altair const currentEpoch = 0; const enrForkID = getENRForkID(config, currentEpoch); diff --git a/packages/beacon-node/test/unit/network/peers/priorization.test.ts b/packages/beacon-node/test/unit/network/peers/priorization.test.ts index 5b318a9b007f..e72cc32ce28c 100644 --- a/packages/beacon-node/test/unit/network/peers/priorization.test.ts +++ b/packages/beacon-node/test/unit/network/peers/priorization.test.ts @@ -265,7 +265,7 @@ describe("network / peers / priorization", async () => { } }); -describe("sortPeersToPrune", async function () { +describe("sortPeersToPrune", async () => { const peers: PeerId[] = []; for (let i = 0; i < 8; i++) { const pk = await generateKeyPair("secp256k1"); diff --git a/packages/beacon-node/test/unit/network/peers/score.test.ts b/packages/beacon-node/test/unit/network/peers/score.test.ts index 54cb721a4c21..8962b282e0ad 100644 --- a/packages/beacon-node/test/unit/network/peers/score.test.ts +++ b/packages/beacon-node/test/unit/network/peers/score.test.ts @@ -19,7 +19,7 @@ vi.mock("../../../../src/network/peers/score/index.js", async (importActual) => }; }); -describe("simple block provider score tracking", function () { +describe("simple block provider score tracking", () => { const peer = peerIdFromString("Qma9T5YraSnpRDZqRR4krcSJabThc8nwZuJV3LercPHufi"); const MIN_SCORE = -100; const actionName = "test-action"; @@ -30,7 +30,7 @@ describe("simple block provider score tracking", function () { return {scoreStore, peerScores}; } - it("Should return default score, without any previous action", function () { + it("Should return default score, without any previous action", () => { const {scoreStore} = mockStore(); const score = scoreStore.getScore(peer); expect(score).toBe(0); @@ -69,7 +69,7 @@ describe("simple block provider score tracking", function () { expect(scoreStore.getScore(peer)).toBeGreaterThan(minScore); }); - it("should not go below min score", function () { + it("should not go below min score", () => { const {scoreStore} = mockStore(); scoreStore.applyAction(peer, PeerAction.Fatal, actionName); scoreStore.applyAction(peer, PeerAction.Fatal, actionName); @@ -77,7 +77,7 @@ describe("simple block provider score tracking", function () { }); }); -describe("updateGossipsubScores", function () { +describe("updateGossipsubScores", () => { let peerRpcScoresStub: PeerRpcScoreStore; beforeEach(() => { 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/network/subnets/attnetsService.test.ts b/packages/beacon-node/test/unit/network/subnets/attnetsService.test.ts index cf9345172083..d279a5d759d7 100644 --- a/packages/beacon-node/test/unit/network/subnets/attnetsService.test.ts +++ b/packages/beacon-node/test/unit/network/subnets/attnetsService.test.ts @@ -35,7 +35,7 @@ describe("AttnetsService", () => { let clock: IClock; const logger = testLogger(); - beforeEach(function () { + beforeEach(() => { vi.useFakeTimers({now: Date.now()}); gossipStub = vi.mocked(new Eth2Gossipsub({} as any, {} as any)); vi.spyOn(gossipStub, "subscribeTopic").mockReturnValue(undefined); diff --git a/packages/beacon-node/test/unit/network/util.test.ts b/packages/beacon-node/test/unit/network/util.test.ts index 14c74930e521..70da41bd2c2a 100644 --- a/packages/beacon-node/test/unit/network/util.test.ts +++ b/packages/beacon-node/test/unit/network/util.test.ts @@ -4,7 +4,7 @@ import {ForkName} from "@lodestar/params"; import {getDiscv5Multiaddrs} from "../../../src/network/libp2p/index.js"; import {getCurrentAndNextFork} from "../../../src/network/forks.js"; -describe("getCurrentAndNextFork", function () { +describe("getCurrentAndNextFork", () => { const altairEpoch = config.forks.altair.epoch; afterEach(() => { config.forks.altair.epoch = altairEpoch; @@ -34,7 +34,7 @@ describe("getCurrentAndNextFork", function () { }); describe("getDiscv5Multiaddrs", () => { - it("should extract bootMultiaddrs from enr with tcp", async function () { + it("should extract bootMultiaddrs from enr with tcp", async () => { const enrWithTcp = [ "enr:-LK4QDiPGwNomqUqNDaM3iHYvtdX7M5qngson6Qb2xGIg1LwC8-Nic0aQwO0rVbJt5xp32sRE3S1YqvVrWO7OgVNv0kBh2F0dG5ldHOIAAAAAAAAAACEZXRoMpA7CIeVAAAgCf__________gmlkgnY0gmlwhBKNA4qJc2VjcDI1NmsxoQKbBS4ROQ_sldJm5tMgi36qm5I5exKJFb4C8dDVS_otAoN0Y3CCIyiDdWRwgiMo", ]; @@ -45,7 +45,7 @@ describe("getDiscv5Multiaddrs", () => { ); }); - it("should not extract bootMultiaddrs from enr without tcp", async function () { + it("should not extract bootMultiaddrs from enr without tcp", async () => { const enrWithoutTcp = [ "enr:-Ku4QCFQW96tEDYPjtaueW3WIh1CB0cJnvw_ibx5qIFZGqfLLj-QajMX6XwVs2d4offuspwgH3NkIMpWtCjCytVdlywGh2F0dG5ldHOIEAIAAgABAUyEZXRoMpCi7FS9AQAAAAAiAQAAAAAAgmlkgnY0gmlwhFA4VK6Jc2VjcDI1NmsxoQNGH1sJJS86-0x9T7qQewz9Wn9zlp6bYxqqrR38JQ49yIN1ZHCCIyg", ]; diff --git a/packages/beacon-node/test/unit/sync/backfill/verify.test.ts b/packages/beacon-node/test/unit/sync/backfill/verify.test.ts index 3d1a2cd7e7e5..bba1f7c93f19 100644 --- a/packages/beacon-node/test/unit/sync/backfill/verify.test.ts +++ b/packages/beacon-node/test/unit/sync/backfill/verify.test.ts @@ -14,14 +14,14 @@ import {BackfillSyncErrorCode, BackfillSyncError} from "./../../../../src/sync/b // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules const __dirname = path.dirname(fileURLToPath(import.meta.url)); -describe("backfill sync - verify block sequence", function () { +describe("backfill sync - verify block sequence", () => { //mainnet validators root const beaconConfig = createBeaconConfig( config, ssz.Root.fromJson("0x4b363db94e286120d76eb905340fdd4e54bfe9f06bf33ff6cf5ad27f511bfe95") ); - it("should verify valid chain of blocks", function () { + it("should verify valid chain of blocks", () => { const blocks = getBlocks(); expect(() => @@ -29,14 +29,14 @@ describe("backfill sync - verify block sequence", function () { ).not.toThrow(); }); - it("should fail with sequence not anchored", function () { + it("should fail with sequence not anchored", () => { const blocks = getBlocks(); const wrongAncorRoot = ssz.Root.defaultValue(); expect(() => verifyBlockSequence(beaconConfig, blocks, wrongAncorRoot)).toThrow(BackfillSyncErrorCode.NOT_ANCHORED); }); - it("should fail with sequence not linear", function () { + it("should fail with sequence not linear", () => { const blocks = getBlocks(); expect(() => { const {error} = verifyBlockSequence( diff --git a/packages/beacon-node/test/unit/sync/unknownBlock.test.ts b/packages/beacon-node/test/unit/sync/unknownBlock.test.ts index 4805bd123898..0694cb97f4ab 100644 --- a/packages/beacon-node/test/unit/sync/unknownBlock.test.ts +++ b/packages/beacon-node/test/unit/sync/unknownBlock.test.ts @@ -239,7 +239,7 @@ describe("sync by UnknownBlockSync", () => { } }); -describe("UnknownBlockSync", function () { +describe("UnknownBlockSync", () => { let network: INetwork; let chain: MockedBeaconChain; const logger = testLogger(); diff --git a/packages/beacon-node/test/unit/util/array.test.ts b/packages/beacon-node/test/unit/util/array.test.ts index d505d27c2e9f..75d3a1b0856d 100644 --- a/packages/beacon-node/test/unit/util/array.test.ts +++ b/packages/beacon-node/test/unit/util/array.test.ts @@ -3,13 +3,13 @@ import {findLastIndex, LinkedList} from "../../../src/util/array.js"; describe("findLastIndex", () => { it("should return the last index that matches a predicate", () => { - expect(findLastIndex([1, 2, 3, 4], (n) => n % 2 == 0)).toEqual(3); - expect(findLastIndex([1, 2, 3, 4, 5], (n) => n % 2 == 0)).toEqual(3); + expect(findLastIndex([1, 2, 3, 4], (n) => n % 2 === 0)).toEqual(3); + expect(findLastIndex([1, 2, 3, 4, 5], (n) => n % 2 === 0)).toEqual(3); expect(findLastIndex([1, 2, 3, 4, 5], () => true)).toEqual(4); }); it("should return -1 if there are no matches", () => { - expect(findLastIndex([1, 3, 5], (n) => n % 2 == 0)).toEqual(-1); + expect(findLastIndex([1, 3, 5], (n) => n % 2 === 0)).toEqual(-1); expect(findLastIndex([1, 2, 3, 4, 5], () => false)).toEqual(-1); }); }); diff --git a/packages/beacon-node/test/unit/util/clock.test.ts b/packages/beacon-node/test/unit/util/clock.test.ts index ff224c1b378a..87955b98182c 100644 --- a/packages/beacon-node/test/unit/util/clock.test.ts +++ b/packages/beacon-node/test/unit/util/clock.test.ts @@ -4,7 +4,7 @@ import {SLOTS_PER_EPOCH} from "@lodestar/params"; import {Clock, ClockEvent} from "../../../src/util/clock.js"; import {MAXIMUM_GOSSIP_CLOCK_DISPARITY} from "../../../src/constants/index.js"; -describe("Clock", function () { +describe("Clock", () => { let abortController: AbortController; let clock: Clock; @@ -26,7 +26,7 @@ describe("Clock", function () { }); // TODO: Debug why this test is fragile after migrating to vitest - it.skip("Should notify on new slot", function () { + it.skip("Should notify on new slot", () => { const spy = vi.fn(); clock.on(ClockEvent.slot, spy); vi.advanceTimersByTime(config.SECONDS_PER_SLOT * 1000); @@ -34,7 +34,7 @@ describe("Clock", function () { expect(spy).toBeCalledWith(clock.currentSlot); }); - it("Should notify on new epoch", function () { + it("Should notify on new epoch", () => { const spy = vi.fn(); clock.on(ClockEvent.epoch, spy); vi.advanceTimersByTime(SLOTS_PER_EPOCH * config.SECONDS_PER_SLOT * 1000); 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/file.test.ts b/packages/beacon-node/test/unit/util/file.test.ts index 9e519ac01681..6040e14b4263 100644 --- a/packages/beacon-node/test/unit/util/file.test.ts +++ b/packages/beacon-node/test/unit/util/file.test.ts @@ -3,10 +3,10 @@ import path from "node:path"; import {describe, it, expect, beforeAll, afterAll} from "vitest"; import {ensureDir, writeIfNotExist} from "../../../src/util/file.js"; -describe("file util", function () { +describe("file util", () => { const dirPath = path.join(".", "keys/toml/test_config.toml"); - describe("ensureDir", function () { + describe("ensureDir", () => { it("create dir if not exists", async () => { // ${dirPath} should not exist expect(fs.existsSync(dirPath)).toBe(false); @@ -17,7 +17,7 @@ describe("file util", function () { }); }); - describe("writeIfNotExist", function () { + describe("writeIfNotExist", () => { const filePath = path.join(dirPath, "test.txt"); const data = new Uint8Array([0, 1, 2]); beforeAll(async () => { diff --git a/packages/beacon-node/test/unit/util/kzg.test.ts b/packages/beacon-node/test/unit/util/kzg.test.ts index 13cea96d87a6..3b1de419ae93 100644 --- a/packages/beacon-node/test/unit/util/kzg.test.ts +++ b/packages/beacon-node/test/unit/util/kzg.test.ts @@ -16,7 +16,7 @@ describe("C-KZG", () => { } }); - beforeAll(async function () { + beforeAll(async () => { await initCKZG(); loadEthereumTrustedSetup(); }); @@ -63,14 +63,14 @@ describe("C-KZG", () => { // Full validation validateBlobSidecars(slot, blockRoot, kzgCommitments, blobSidecars); - blobSidecars.forEach(async (blobSidecar) => { + for (const blobSidecar of blobSidecars) { try { await validateGossipBlobSidecar(chain, blobSidecar, blobSidecar.index); } catch (_e) { // We expect some error from here // console.log(error); } - }); + } }); }); 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/cache.ts b/packages/beacon-node/test/utils/cache.ts index 9d5d3566c99d..2fd15427c659 100644 --- a/packages/beacon-node/test/utils/cache.ts +++ b/packages/beacon-node/test/utils/cache.ts @@ -3,7 +3,7 @@ import {toHexString} from "@chainsafe/ssz"; export function memoOnce(fn: () => R): () => R { let value: R | null = null; - return function () { + return () => { if (value === null) { value = fn(); } 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/beacon-node/test/utils/runEl.ts b/packages/beacon-node/test/utils/runEl.ts index f7a2b2f52e58..8a2da7104510 100644 --- a/packages/beacon-node/test/utils/runEl.ts +++ b/packages/beacon-node/test/utils/runEl.ts @@ -196,7 +196,7 @@ async function waitForELOffline(ENGINE_PORT: string): Promise { async function isPortInUse(port: number): Promise { return new Promise((resolve, reject) => { const server = net.createServer(); - server.once("error", function (err) { + server.once("error", (err) => { if ((err as unknown as {code: string}).code === "EADDRINUSE") { resolve(true); } else { @@ -204,7 +204,7 @@ async function isPortInUse(port: number): Promise { } }); - server.once("listening", function () { + server.once("listening", () => { // close the server if listening doesn't fail server.close(() => { resolve(false); diff --git a/packages/cli/src/applyPreset.ts b/packages/cli/src/applyPreset.ts index e40ac98841c0..612c5d648c63 100644 --- a/packages/cli/src/applyPreset.ts +++ b/packages/cli/src/applyPreset.ts @@ -90,6 +90,3 @@ function valueOfArg(argName: string): string | null { return null; } - -// Add empty export to make this a module -export {}; 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..a9f91af87152 100644 --- a/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts +++ b/packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts @@ -125,6 +125,7 @@ export function overwriteEnrWithCliArgs( enr.seq = preSeq + BigInt(1); } // invalidate cached signature + // biome-ignore lint/complexity/useLiteralKeys: `_signature` is a private attribute delete enr["_signature"]; } } @@ -186,9 +187,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/bootnode/options.ts b/packages/cli/src/cmds/bootnode/options.ts index dd597e6a22ef..f3422b4029a1 100644 --- a/packages/cli/src/cmds/bootnode/options.ts +++ b/packages/cli/src/cmds/bootnode/options.ts @@ -55,7 +55,7 @@ export const bootnodeExtraOptions: CliCommandOptions = { // Each bootnode entry could be comma separated, just deserialize it into a single array // as comma separated entries are generally most friendly in ansible kind of setups, i.e. // [ "en1", "en2,en3" ] => [ 'en1', 'en2', 'en3' ] - coerce: (args: string[]) => args.map((item) => item.split(",")).flat(1), + coerce: (args: string[]) => args.flatMap((item) => item.split(",")), group: "network", }, diff --git a/packages/cli/src/cmds/dev/options.ts b/packages/cli/src/cmds/dev/options.ts index 5286b81729c6..e442b0605cdc 100644 --- a/packages/cli/src/cmds/dev/options.ts +++ b/packages/cli/src/cmds/dev/options.ts @@ -81,12 +81,12 @@ const externalOptionsOverrides: Partial closeMetrics()); // only start server if metrics are explicitly enabled - if (args["metrics"]) { + if (args.metrics) { const port = args["metrics.port"] ?? validatorMetricsDefaultOptions.port; const address = args["metrics.address"] ?? validatorMetricsDefaultOptions.address; const metricsServer = await getHttpMetricsServer({port, address}, {register, logger}); @@ -186,7 +186,7 @@ export async function validatorHandler(args: IValidatorCliArgs & GlobalArgs): Pr // Start keymanager API backend // Only if keymanagerEnabled flag is set to true - if (args["keymanager"]) { + if (args.keymanager) { // if proposerSettingsFile provided disable the key proposerConfigWrite in keymanager const proposerConfigWriteDisabled = args.proposerSettingsFile !== undefined; if (proposerConfigWriteDisabled) { @@ -234,7 +234,7 @@ function getProposerConfigFromArgs( builder: { gasLimit: args.defaultGasLimit, selection: parseBuilderSelection( - args["builder.selection"] ?? (args["builder"] ? defaultOptions.builderAliasSelection : undefined) + args["builder.selection"] ?? (args.builder ? defaultOptions.builderAliasSelection : undefined) ), boostFactor: parseBuilderBoostFactor(args["builder.boostFactor"]), }, 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/options.ts b/packages/cli/src/cmds/validator/options.ts index 83190dcf4a58..3beb8197793c 100644 --- a/packages/cli/src/cmds/validator/options.ts +++ b/packages/cli/src/cmds/validator/options.ts @@ -195,9 +195,7 @@ export const validatorOptions: CliCommandOptions = { string: true, coerce: (urls: string[]): string[] => // Parse ["url1,url2"] to ["url1", "url2"] - urls - .map((item) => item.split(",")) - .flat(1), + urls.flatMap((item) => item.split(",")), alias: ["server"], // for backwards compatibility }, @@ -354,8 +352,7 @@ export const validatorOptions: CliCommandOptions = { coerce: (pubkeys: string[]): string[] => // Parse ["0x11,0x22"] to ["0x11", "0x22"] pubkeys - .map((item) => item.split(",")) - .flat(1) + .flatMap((item) => item.split(",")) .map(ensure0xPrefix), group: "externalSigner", }, 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..950be2db1cf5 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), @@ -98,52 +97,50 @@ export async function getSignersFromArgs( ignoreLockFile: args.force, onDecrypt: needle, cacheFilePath: path.join(accountPaths.cacheDir, "imported_keystores.cache"), - disableThreadPool: args["disableKeystoresThreadPool"], + disableThreadPool: args.disableKeystoresThreadPool, logger, signal, }); } // 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/signers/logSigners.ts b/packages/cli/src/cmds/validator/signers/logSigners.ts index 20aa50d25ff6..d245ee75883a 100644 --- a/packages/cli/src/cmds/validator/signers/logSigners.ts +++ b/packages/cli/src/cmds/validator/signers/logSigners.ts @@ -60,11 +60,11 @@ function groupRemoteSignersByUrl(remoteSigners: SignerRemote[]): {url: string; p * is connected with fetching enabled, but otherwise exit the process and suggest a different configuration. */ export function warnOrExitNoSigners(args: IValidatorCliArgs, logger: Pick): void { - if (args["keymanager"] && !args["externalSigner.fetch"]) { + if (args.keymanager && !args["externalSigner.fetch"]) { logger.warn("No local keystores or remote keys found with current args, expecting to be added via keymanager"); - } else if (!args["keymanager"] && args["externalSigner.fetch"]) { + } else if (!args.keymanager && args["externalSigner.fetch"]) { logger.warn("No remote keys found with current args, expecting to be added to external signer and fetched later"); - } else if (args["keymanager"] && args["externalSigner.fetch"]) { + } else if (args.keymanager && args["externalSigner.fetch"]) { logger.warn( "No local keystores or remote keys found with current args, expecting to be added via keymanager or fetched from external signer later" ); diff --git a/packages/cli/src/cmds/validator/slashingProtection/export.ts b/packages/cli/src/cmds/validator/slashingProtection/export.ts index c18b020f5782..f57f9d3ec0bd 100644 --- a/packages/cli/src/cmds/validator/slashingProtection/export.ts +++ b/packages/cli/src/cmds/validator/slashingProtection/export.ts @@ -43,8 +43,7 @@ export const exportCmd: CliCommand // Parse ["0x11,0x22"] to ["0x11", "0x22"] pubkeys - .map((item) => item.split(",")) - .flat(1) + .flatMap((item) => item.split(",")) .map(ensure0xPrefix), }, }, diff --git a/packages/cli/src/cmds/validator/voluntaryExit.ts b/packages/cli/src/cmds/validator/voluntaryExit.ts index c3982d8d45ee..5b4cfdf270f0 100644 --- a/packages/cli/src/cmds/validator/voluntaryExit.ts +++ b/packages/cli/src/cmds/validator/voluntaryExit.ts @@ -59,8 +59,7 @@ If no `pubkeys` are provided, it will exit all validators that have been importe coerce: (pubkeys: string[]): string[] => // Parse ["0x11,0x22"] to ["0x11", "0x22"] pubkeys - .map((item) => item.split(",")) - .flat(1) + .flatMap((item) => item.split(",")) .map(ensure0xPrefix), }, @@ -151,7 +150,7 @@ async function processVoluntaryExit( const voluntaryExit: phase0.VoluntaryExit = {epoch: exitEpoch, validatorIndex: index}; const signingRoot = computeSigningRoot(ssz.phase0.VoluntaryExit, voluntaryExit, domain); - let signature; + let signature: Signature; switch (signer.type) { case SignerType.Local: signature = signer.secretKey.sign(signingRoot); @@ -192,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/networks/dev.ts b/packages/cli/src/networks/dev.ts index ff8afc127dcc..6ce87273b3cb 100644 --- a/packages/cli/src/networks/dev.ts +++ b/packages/cli/src/networks/dev.ts @@ -1,8 +1,9 @@ import {gnosisChainConfig} from "@lodestar/config/networks"; import {minimalChainConfig, mainnetChainConfig} from "@lodestar/config/configs"; import {ACTIVE_PRESET, PresetName} from "@lodestar/params"; +import {ChainConfig} from "@lodestar/config"; -let chainConfig; +let chainConfig: ChainConfig; switch (ACTIVE_PRESET) { case PresetName.mainnet: chainConfig = mainnetChainConfig; diff --git a/packages/cli/src/networks/index.ts b/packages/cli/src/networks/index.ts index ba42cf4c7798..e2fc9dd621b6 100644 --- a/packages/cli/src/networks/index.ts +++ b/packages/cli/src/networks/index.ts @@ -210,7 +210,7 @@ export async function fetchWeakSubjectivityState( } export function getCheckpointFromArg(checkpointStr: string): Checkpoint { - const checkpointRegex = new RegExp("^(?:0x)?([0-9a-f]{64}):([0-9]+)$"); + const checkpointRegex = /^(?:0x)?([0-9a-f]{64}):([0-9]+)$/; const match = checkpointRegex.exec(checkpointStr.toLowerCase()); if (!match) { throw new Error(`Could not parse checkpoint string: ${checkpointStr}`); diff --git a/packages/cli/src/options/beaconNodeOptions/api.ts b/packages/cli/src/options/beaconNodeOptions/api.ts index bed0105fd944..ea4d4ebccf84 100644 --- a/packages/cli/src/options/beaconNodeOptions/api.ts +++ b/packages/cli/src/options/beaconNodeOptions/api.ts @@ -22,7 +22,7 @@ export function parseArgs(args: ApiArgs): IBeaconNodeOptions["api"] { rest: { api: args["rest.namespace"] as IBeaconNodeOptions["api"]["rest"]["api"], cors: args["rest.cors"], - enabled: args["rest"], + enabled: args.rest, address: args["rest.address"], port: args["rest.port"], headerLimit: args["rest.headerLimit"], @@ -59,7 +59,7 @@ export const options: CliCommandOptions = { // Enable all if (namespaces.includes(enabledAll)) return allNamespaces; // Parse ["debug,lodestar"] to ["debug", "lodestar"] - return namespaces.map((val) => val.split(",")).flat(1); + return namespaces.flatMap((val) => val.split(",")); }, }, diff --git a/packages/cli/src/options/beaconNodeOptions/builder.ts b/packages/cli/src/options/beaconNodeOptions/builder.ts index 2c89cbad89d2..d0e4089dd81c 100644 --- a/packages/cli/src/options/beaconNodeOptions/builder.ts +++ b/packages/cli/src/options/beaconNodeOptions/builder.ts @@ -18,7 +18,7 @@ export function parseArgs(args: ExecutionBuilderArgs): IBeaconNodeOptions["execu } return { - enabled: args["builder"], + enabled: args.builder, url: args["builder.url"] ?? defaultExecutionBuilderHttpOpts.url, timeout: args["builder.timeout"], faultInspectionWindow: args["builder.faultInspectionWindow"], diff --git a/packages/cli/src/options/beaconNodeOptions/chain.ts b/packages/cli/src/options/beaconNodeOptions/chain.ts index 7540dd56a636..78ffd47da8f4 100644 --- a/packages/cli/src/options/beaconNodeOptions/chain.ts +++ b/packages/cli/src/options/beaconNodeOptions/chain.ts @@ -36,7 +36,7 @@ export type ChainArgs = { export function parseArgs(args: ChainArgs): IBeaconNodeOptions["chain"] { return { - suggestedFeeRecipient: args["suggestedFeeRecipient"], + suggestedFeeRecipient: args.suggestedFeeRecipient, blsVerifyAllMultiThread: args["chain.blsVerifyAllMultiThread"], blsVerifyAllMainThread: args["chain.blsVerifyAllMainThread"], disableBlsBatchVerify: args["chain.disableBlsBatchVerify"], @@ -55,8 +55,8 @@ export function parseArgs(args: ChainArgs): IBeaconNodeOptions["chain"] { trustedSetup: args["chain.trustedSetup"], safeSlotsToImportOptimistically: args["safe-slots-to-import-optimistically"], archiveStateEpochFrequency: args["chain.archiveStateEpochFrequency"], - emitPayloadAttributes: args["emitPayloadAttributes"], - broadcastValidationStrictness: args["broadcastValidationStrictness"], + emitPayloadAttributes: args.emitPayloadAttributes, + broadcastValidationStrictness: args.broadcastValidationStrictness, minSameMessageSignatureSetsToBatch: args["chain.minSameMessageSignatureSetsToBatch"] ?? defaultOptions.chain.minSameMessageSignatureSetsToBatch, maxShufflingCacheEpochs: args["chain.maxShufflingCacheEpochs"] ?? defaultOptions.chain.maxShufflingCacheEpochs, diff --git a/packages/cli/src/options/beaconNodeOptions/eth1.ts b/packages/cli/src/options/beaconNodeOptions/eth1.ts index c558bda61b4e..f12a1704dec7 100644 --- a/packages/cli/src/options/beaconNodeOptions/eth1.ts +++ b/packages/cli/src/options/beaconNodeOptions/eth1.ts @@ -25,14 +25,12 @@ export function parseArgs(args: Eth1Args & Partial): IBeaco // jwt auth mechanism. if (providerUrls === undefined && args["execution.urls"]) { providerUrls = args["execution.urls"]; - jwtSecretHex = args["jwtSecret"] - ? extractJwtHexSecret(fs.readFileSync(args["jwtSecret"], "utf-8").trim()) - : undefined; - jwtId = args["jwtId"]; + jwtSecretHex = args.jwtSecret ? extractJwtHexSecret(fs.readFileSync(args.jwtSecret, "utf-8").trim()) : undefined; + jwtId = args.jwtId; } return { - enabled: args["eth1"], + enabled: args.eth1, providerUrls, jwtSecretHex, jwtId, @@ -59,9 +57,7 @@ export const options: CliCommandOptions = { string: true, coerce: (urls: string[]): string[] => // Parse ["url1,url2"] to ["url1", "url2"] - urls - .map((item) => item.split(",")) - .flat(1), + urls.flatMap((item) => item.split(",")), group: "eth1", }, diff --git a/packages/cli/src/options/beaconNodeOptions/execution.ts b/packages/cli/src/options/beaconNodeOptions/execution.ts index d60a621d1cdb..2d32ee2ae786 100644 --- a/packages/cli/src/options/beaconNodeOptions/execution.ts +++ b/packages/cli/src/options/beaconNodeOptions/execution.ts @@ -30,10 +30,8 @@ export function parseArgs(args: ExecutionEngineArgs): IBeaconNodeOptions["execut * jwtSecret is parsed as hex instead of bytes because the merge with defaults * in beaconOptions messes up the bytes array as as index => value object */ - jwtSecretHex: args["jwtSecret"] - ? extractJwtHexSecret(fs.readFileSync(args["jwtSecret"], "utf-8").trim()) - : undefined, - jwtId: args["jwtId"], + jwtSecretHex: args.jwtSecret ? extractJwtHexSecret(fs.readFileSync(args.jwtSecret, "utf-8").trim()) : undefined, + jwtId: args.jwtId, }; } @@ -45,9 +43,7 @@ export const options: CliCommandOptions = { string: true, coerce: (urls: string[]): string[] => // Parse ["url1,url2"] to ["url1", "url2"] - urls - .map((item) => item.split(",")) - .flat(1), + urls.flatMap((item) => item.split(",")), group: "execution", }, diff --git a/packages/cli/src/options/beaconNodeOptions/metrics.ts b/packages/cli/src/options/beaconNodeOptions/metrics.ts index ba12a7546eae..ded63b7dc24d 100644 --- a/packages/cli/src/options/beaconNodeOptions/metrics.ts +++ b/packages/cli/src/options/beaconNodeOptions/metrics.ts @@ -9,7 +9,7 @@ export type MetricsArgs = { export function parseArgs(args: MetricsArgs): IBeaconNodeOptions["metrics"] { return { - enabled: args["metrics"], + enabled: args.metrics, port: args["metrics.port"], address: args["metrics.address"], }; diff --git a/packages/cli/src/options/beaconNodeOptions/network.ts b/packages/cli/src/options/beaconNodeOptions/network.ts index fc13f3293c29..cfd109bdc50a 100644 --- a/packages/cli/src/options/beaconNodeOptions/network.ts +++ b/packages/cli/src/options/beaconNodeOptions/network.ts @@ -100,16 +100,16 @@ export function parseArgs(args: NetworkArgs): IBeaconNodeOptions["network"] { const bindMu6 = listenAddress6 ? `${muArgs.listenAddress6}${muArgs.discoveryPort6}` : undefined; const localMu6 = listenAddress6 ? `${muArgs.listenAddress6}${muArgs.port6}` : undefined; - const targetPeers = args["targetPeers"]; + const targetPeers = args.targetPeers; const maxPeers = args["network.maxPeers"] ?? (targetPeers !== undefined ? Math.floor(targetPeers * 1.1) : undefined); if (targetPeers != null && maxPeers != null && targetPeers > maxPeers) { throw new YargsError("network.maxPeers must be greater than or equal to targetPeers"); } // Set discv5 opts to null to disable only if explicitly disabled - const enableDiscv5 = args["discv5"] ?? true; + const enableDiscv5 = args.discv5 ?? true; // TODO: Okay to set to empty array? - const bootEnrs = args["bootnodes"] ?? []; + const bootEnrs = args.bootnodes ?? []; // throw if user-provided enrs are invalid for (const enrStr of bootEnrs) { try { @@ -135,10 +135,10 @@ export function parseArgs(args: NetworkArgs): IBeaconNodeOptions["network"] { maxPeers: maxPeers ?? defaultOptions.network.maxPeers, targetPeers: targetPeers ?? defaultOptions.network.targetPeers, localMultiaddrs: [localMu, localMu6].filter(Boolean) as string[], - subscribeAllSubnets: args["subscribeAllSubnets"], + subscribeAllSubnets: args.subscribeAllSubnets, slotsToSubscribeBeforeAggregatorDuty: - args["slotsToSubscribeBeforeAggregatorDuty"] ?? defaultOptions.network.slotsToSubscribeBeforeAggregatorDuty, - disablePeerScoring: args["disablePeerScoring"], + args.slotsToSubscribeBeforeAggregatorDuty ?? defaultOptions.network.slotsToSubscribeBeforeAggregatorDuty, + disablePeerScoring: args.disablePeerScoring, connectToDiscv5Bootnodes: args["network.connectToDiscv5Bootnodes"], discv5FirstQueryDelayMs: args["network.discv5FirstQueryDelayMs"], dontSendGossipAttestationsToForkchoice: args["network.dontSendGossipAttestationsToForkchoice"], @@ -148,7 +148,7 @@ export function parseArgs(args: NetworkArgs): IBeaconNodeOptions["network"] { gossipsubDHigh: args["network.gossipsubDHigh"], gossipsubAwaitHandler: args["network.gossipsubAwaitHandler"], disableFloodPublish: args["network.disableFloodPublish"], - mdns: args["mdns"], + mdns: args.mdns, rateLimitMultiplier: args["network.rateLimitMultiplier"], maxGossipTopicConcurrency: args["network.maxGossipTopicConcurrency"], useWorker: args["network.useWorker"], @@ -211,12 +211,12 @@ export const options: CliCommandOptions = { bootnodes: { type: "array", description: "Bootnodes for discv5 discovery", - defaultDescription: JSON.stringify((defaultOptions.network.discv5 || {}).bootEnrs || []), + defaultDescription: JSON.stringify(defaultOptions.network.discv5?.bootEnrs || []), group: "network", // Each bootnode entry could be comma separated, just deserialize it into a single array // as comma separated entries are generally most friendly in ansible kind of setups, i.e. // [ "en1", "en2,en3" ] => [ 'en1', 'en2', 'en3' ] - coerce: (args: string[]) => args.map((item) => item.split(",")).flat(1), + coerce: (args: string[]) => args.flatMap((item) => item.split(",")), }, targetPeers: { diff --git a/packages/cli/src/options/logOptions.ts b/packages/cli/src/options/logOptions.ts index b45057a4532f..09eb5b1d56cb 100644 --- a/packages/cli/src/options/logOptions.ts +++ b/packages/cli/src/options/logOptions.ts @@ -65,6 +65,6 @@ export const logOptions: CliCommandOptions = { description: "Set log level for a specific module by name: 'chain=debug' or 'network=debug,chain=debug'", type: "array", string: true, - coerce: (args: string[]) => args.map((item) => item.split(",")).flat(1), + coerce: (args: string[]) => args.flatMap((item) => item.split(",")), }, }; diff --git a/packages/cli/src/options/paramsOptions.ts b/packages/cli/src/options/paramsOptions.ts index b35a15e3c9b6..bd89ffa77d9e 100644 --- a/packages/cli/src/options/paramsOptions.ts +++ b/packages/cli/src/options/paramsOptions.ts @@ -25,14 +25,14 @@ export function parseBeaconParamsArgs(args: Record): IB } const paramsOptionsByName = ObjectKeys(chainConfigTypes).reduce( - (options: Record, key): Record => ({ - ...options, - [getArgKey(key)]: { + (options: Record, key): Record => { + options[getArgKey(key)] = { hidden: true, type: "string", group: "params", - }, - }), + }; + return options; + }, {} ); 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/format.ts b/packages/cli/src/util/format.ts index a86ca0662a9f..e8361649824a 100644 --- a/packages/cli/src/util/format.ts +++ b/packages/cli/src/util/format.ts @@ -36,8 +36,8 @@ export function parseRange(range: string): number[] { const [from, to] = range.split("..").map((n) => parseInt(n)); - if (isNaN(from)) throw Error(`Invalid range from isNaN '${range}'`); - if (isNaN(to)) throw Error(`Invalid range to isNaN '${range}'`); + if (Number.isNaN(from)) throw Error(`Invalid range from isNaN '${range}'`); + if (Number.isNaN(to)) throw Error(`Invalid range to isNaN '${range}'`); if (from > to) throw Error(`Invalid range from > to '${range}'`); const arr: number[] = []; 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/src/util/jwt.ts b/packages/cli/src/util/jwt.ts index e77e9e692cd6..b79b0a0dea7f 100644 --- a/packages/cli/src/util/jwt.ts +++ b/packages/cli/src/util/jwt.ts @@ -2,7 +2,7 @@ export function extractJwtHexSecret(jwtSecretContents: string): string { const hexPattern = new RegExp(/^(0x|0X)?(?[a-fA-F0-9]+)$/, "g"); const jwtSecretHexMatch = hexPattern.exec(jwtSecretContents); const jwtSecret = jwtSecretHexMatch?.groups?.jwtSecret; - if (!jwtSecret || jwtSecret.length != 64) { + if (!jwtSecret || jwtSecret.length !== 64) { throw Error(`Need a valid 256 bit hex encoded secret ${jwtSecret} ${jwtSecretContents}`); } // Return the secret in proper hex format diff --git a/packages/cli/src/util/logger.ts b/packages/cli/src/util/logger.ts index e08029f5f1df..7a394c9ce25f 100644 --- a/packages/cli/src/util/logger.ts +++ b/packages/cli/src/util/logger.ts @@ -89,14 +89,16 @@ export function cleanOldLogFiles(args: LogArgs, paths: {defaultLogFilepath: stri .filter((logFileName) => shouldDeleteLogFile(prefix, extension, logFileName, args.logFileDailyRotate)) .map((logFileName) => path.join(folder, logFileName)); // delete files - toDelete.forEach((filename) => fs.unlinkSync(filename)); + for (const filename of toDelete) { + fs.unlinkSync(filename); + } } export function shouldDeleteLogFile(prefix: string, extension: string, logFileName: string, maxFiles: number): boolean { const maxDifferenceMs = maxFiles * 24 * 60 * 60 * 1000; const match = logFileName.match(new RegExp(`${prefix}-([0-9]{4}-[0-9]{2}-[0-9]{2}).${extension}`)); // if match[1] exists, it should be the date pattern of YYYY-MM-DD - if (match && match[1] && Date.now() - new Date(match[1]).getTime() > maxDifferenceMs) { + if (match?.[1] && Date.now() - new Date(match[1]).getTime() > maxDifferenceMs) { return true; } return false; diff --git a/packages/cli/test/e2e/blsToExecutionchange.test.ts b/packages/cli/test/e2e/blsToExecutionchange.test.ts index 51720e424c7e..57f32421d313 100644 --- a/packages/cli/test/e2e/blsToExecutionchange.test.ts +++ b/packages/cli/test/e2e/blsToExecutionchange.test.ts @@ -8,7 +8,7 @@ import {interopSecretKey} from "@lodestar/state-transition"; import {execCliCommand, spawnCliCommand, stopChildProcess} from "@lodestar/test-utils"; import {testFilesDir} from "../utils.js"; -describe("bLSToExecutionChange cmd", function () { +describe("bLSToExecutionChange cmd", () => { vi.setConfig({testTimeout: 60_000}); it("Perform bLSToExecutionChange", async () => { diff --git a/packages/cli/test/e2e/importFromFsDirect.test.ts b/packages/cli/test/e2e/importFromFsDirect.test.ts index 644635bc0ffe..6f612e84afe6 100644 --- a/packages/cli/test/e2e/importFromFsDirect.test.ts +++ b/packages/cli/test/e2e/importFromFsDirect.test.ts @@ -7,24 +7,17 @@ import {testFilesDir} from "../utils.js"; import {cachedPubkeysHex, cachedSeckeysHex} from "../utils/cachedKeys.js"; import {expectKeys, startValidatorWithKeyManager} from "../utils/validator.js"; -describe("import from fs same cmd as validate", function () { +describe("import from fs same cmd as validate", () => { vi.setConfig({testTimeout: 30_000}); const dataDir = path.join(testFilesDir, "import-and-validate-test"); const importFromDir = path.join(dataDir, "eth2.0_deposit_out"); const passphraseFilepath = path.join(importFromDir, "password.text"); - beforeAll(() => { + beforeAll(async () => { rimraf.sync(dataDir); rimraf.sync(importFromDir); - }); - - const passphrase = "AAAAAAAA0000000000"; - const keyCount = 2; - const pubkeys = cachedPubkeysHex.slice(0, keyCount); - const secretKeys = cachedSeckeysHex.slice(0, keyCount); - beforeAll(async () => { // Produce and encrypt keystores const keystoresStr = await getKeystoresStr(passphrase, secretKeys); @@ -35,6 +28,11 @@ describe("import from fs same cmd as validate", function () { } }); + const passphrase = "AAAAAAAA0000000000"; + const keyCount = 2; + const pubkeys = cachedPubkeysHex.slice(0, keyCount); + const secretKeys = cachedSeckeysHex.slice(0, keyCount); + // Check that there are not keys loaded without adding extra args `--importKeystores` it("run 'validator' there are no keys loaded", async () => { const {keymanagerClient, stopValidator} = await startValidatorWithKeyManager([], { diff --git a/packages/cli/test/e2e/importFromFsPreStep.test.ts b/packages/cli/test/e2e/importFromFsPreStep.test.ts index 7eebf2d4946e..437180ef07e5 100644 --- a/packages/cli/test/e2e/importFromFsPreStep.test.ts +++ b/packages/cli/test/e2e/importFromFsPreStep.test.ts @@ -8,7 +8,7 @@ import {testFilesDir} from "../utils.js"; import {cachedPubkeysHex, cachedSeckeysHex} from "../utils/cachedKeys.js"; import {expectKeys, startValidatorWithKeyManager} from "../utils/validator.js"; -describe("import from fs then validate", function () { +describe("import from fs then validate", () => { vi.setConfig({testTimeout: 30_000}); const dataDir = path.join(testFilesDir, "import-then-validate-test"); @@ -47,7 +47,7 @@ describe("import from fs then validate", function () { } }); - it("run 'validator list' and check pubkeys are imported", async function () { + it("run 'validator list' and check pubkeys are imported", async () => { fs.mkdirSync(path.join(dataDir, "keystores"), {recursive: true}); fs.mkdirSync(path.join(dataDir, "secrets"), {recursive: true}); @@ -58,7 +58,7 @@ describe("import from fs then validate", function () { } }); - it("run 'validator' check keys are loaded", async function () { + it("run 'validator' check keys are loaded", async () => { const {keymanagerClient, stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); diff --git a/packages/cli/test/e2e/importKeystoresFromApi.test.ts b/packages/cli/test/e2e/importKeystoresFromApi.test.ts index 584ded47bfdd..7f71e2977a92 100644 --- a/packages/cli/test/e2e/importKeystoresFromApi.test.ts +++ b/packages/cli/test/e2e/importKeystoresFromApi.test.ts @@ -12,7 +12,7 @@ import {cachedPubkeysHex, cachedSeckeysHex} from "../utils/cachedKeys.js"; import {expectDeepEquals} from "../utils/runUtils.js"; import {expectKeys, startValidatorWithKeyManager} from "../utils/validator.js"; -describe("import keystores from api", function () { +describe("import keystores from api", () => { vi.setConfig({testTimeout: 30_000}); const dataDir = path.join(testFilesDir, "import-keystores-test"); @@ -118,7 +118,7 @@ describe("import keystores from api", function () { }); }); - it("run 'validator' check keys are loaded + delete", async function () { + it("run 'validator' check keys are loaded + delete", async () => { const {keymanagerClient, stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); @@ -138,7 +138,7 @@ describe("import keystores from api", function () { await expectKeys(keymanagerClient, [], "Wrong listKeys after deleting"); }); - it("different process check no keys are loaded", async function () { + it("different process check no keys are loaded", async () => { const {keymanagerClient, stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); @@ -148,7 +148,7 @@ describe("import keystores from api", function () { await expectKeys(keymanagerClient, [], "Wrong listKeys"); }); - it("reject calls without bearerToken", async function () { + it("reject calls without bearerToken", async () => { const {stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); diff --git a/packages/cli/test/e2e/importRemoteKeysFromApi.test.ts b/packages/cli/test/e2e/importRemoteKeysFromApi.test.ts index 0d7e4aa58da3..b66611cbf4f4 100644 --- a/packages/cli/test/e2e/importRemoteKeysFromApi.test.ts +++ b/packages/cli/test/e2e/importRemoteKeysFromApi.test.ts @@ -20,7 +20,7 @@ async function expectKeys(keymanagerClient: ApiClient, expectedPubkeys: string[] ); } -describe("import remoteKeys from api", function () { +describe("import remoteKeys from api", () => { vi.setConfig({testTimeout: 30_000}); const dataDir = path.join(testFilesDir, "import-remoteKeys-test"); @@ -65,7 +65,7 @@ describe("import remoteKeys from api", function () { ); }); - it("run 'validator' check keys are loaded + delete", async function () { + it("run 'validator' check keys are loaded + delete", async () => { const {keymanagerClient, stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); @@ -86,7 +86,7 @@ describe("import remoteKeys from api", function () { await expectKeys(keymanagerClient, [], "Wrong listRemoteKeys after deleting"); }); - it("reject calls without bearerToken", async function () { + it("reject calls without bearerToken", async () => { const {stopValidator} = await startValidatorWithKeyManager([], {dataDir}); onTestFinished(async () => { await stopValidator(); diff --git a/packages/cli/test/e2e/propserConfigfromKeymanager.test.ts b/packages/cli/test/e2e/propserConfigfromKeymanager.test.ts index 6a6c391b4014..2f25c82999a7 100644 --- a/packages/cli/test/e2e/propserConfigfromKeymanager.test.ts +++ b/packages/cli/test/e2e/propserConfigfromKeymanager.test.ts @@ -9,7 +9,7 @@ import {cachedPubkeysHex, cachedSeckeysHex} from "../utils/cachedKeys.js"; import {expectDeepEquals} from "../utils/runUtils.js"; import {startValidatorWithKeyManager} from "../utils/validator.js"; -describe("import keystores from api, test DefaultProposerConfig", function () { +describe("import keystores from api, test DefaultProposerConfig", () => { vi.setConfig({testTimeout: 30_000}); const dataDir = path.join(testFilesDir, "proposer-config-test"); diff --git a/packages/cli/test/e2e/runDevCmd.test.ts b/packages/cli/test/e2e/runDevCmd.test.ts index 68dcca156d88..3beb68393815 100644 --- a/packages/cli/test/e2e/runDevCmd.test.ts +++ b/packages/cli/test/e2e/runDevCmd.test.ts @@ -4,7 +4,7 @@ import {config} from "@lodestar/config/default"; import {retry} from "@lodestar/utils"; import {spawnCliCommand, stopChildProcess} from "@lodestar/test-utils"; -describe("Run dev command", function () { +describe("Run dev command", () => { vi.setConfig({testTimeout: 30_000}); it("Run dev command with no --dataDir until beacon api is listening", async () => { diff --git a/packages/cli/test/e2e/validatorList.test.ts b/packages/cli/test/e2e/validatorList.test.ts index b6fe4da5faeb..7f86fb8ef89b 100644 --- a/packages/cli/test/e2e/validatorList.test.ts +++ b/packages/cli/test/e2e/validatorList.test.ts @@ -9,7 +9,7 @@ import {runCliCommand} from "@lodestar/test-utils"; import {testFilesDir} from "../utils.js"; import {getLodestarCli} from "../../src/cli.js"; -describe("cmds / validator", function () { +describe("cmds / validator", () => { vi.setConfig({testTimeout: 30_000}); const lodestar = getLodestarCli(); @@ -54,7 +54,7 @@ describe("cmds / validator", function () { expect(console.log).toHaveBeenCalledWith(`Imported keystore ${pkHex} ${keystoreFilepath}`); }); - it("should list validators", async function () { + it("should list validators", async () => { fs.mkdirSync(path.join(dataDir, "keystores"), {recursive: true}); fs.mkdirSync(path.join(dataDir, "secrets"), {recursive: true}); diff --git a/packages/cli/test/e2e/voluntaryExit.test.ts b/packages/cli/test/e2e/voluntaryExit.test.ts index 25d4ab345aa7..0abddcab7652 100644 --- a/packages/cli/test/e2e/voluntaryExit.test.ts +++ b/packages/cli/test/e2e/voluntaryExit.test.ts @@ -7,7 +7,7 @@ import {interopSecretKey} from "@lodestar/state-transition"; import {spawnCliCommand, execCliCommand, stopChildProcess} from "@lodestar/test-utils"; import {testFilesDir} from "../utils.js"; -describe("voluntaryExit cmd", function () { +describe("voluntaryExit cmd", () => { vi.setConfig({testTimeout: 60_000}); it("Perform a voluntary exit", async () => { @@ -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..97ac06d5fc5c 100644 --- a/packages/cli/test/e2e/voluntaryExitFromApi.test.ts +++ b/packages/cli/test/e2e/voluntaryExitFromApi.test.ts @@ -8,7 +8,7 @@ import {spawnCliCommand, stopChildProcess} from "@lodestar/test-utils"; import {retry} from "@lodestar/utils"; import {testFilesDir} from "../utils.js"; -describe("voluntary exit from api", function () { +describe("voluntary exit from api", () => { vi.setConfig({testTimeout: 60_000}); it("Perform a voluntary exit", async () => { @@ -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..769380f2053f 100644 --- a/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts +++ b/packages/cli/test/e2e/voluntaryExitRemoteSigner.test.ts @@ -14,7 +14,7 @@ import { } from "@lodestar/test-utils"; import {testFilesDir} from "../utils.js"; -describe("voluntaryExit using remote signer", function () { +describe("voluntaryExit using remote signer", () => { vi.setConfig({testTimeout: 30_000}); let externalSigner: StartedExternalSigner; @@ -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/unit/util/gitData.test.ts b/packages/cli/test/unit/util/gitData.test.ts index 12a6b5b18339..9e15fc2f4956 100644 --- a/packages/cli/test/unit/util/gitData.test.ts +++ b/packages/cli/test/unit/util/gitData.test.ts @@ -10,7 +10,7 @@ import {getGitData} from "../../../src/util/index.js"; // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules const __dirname = path.dirname(fileURLToPath(import.meta.url)); -describe("util / gitData", function () { +describe("util / gitData", () => { // .gitData file is created at build time with the command // ``` // npm run write-git-data diff --git a/packages/cli/test/unit/util/logger.test.ts b/packages/cli/test/unit/util/logger.test.ts index bddc86f2a483..fa17218bfd1c 100644 --- a/packages/cli/test/unit/util/logger.test.ts +++ b/packages/cli/test/unit/util/logger.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from "vitest"; import {shouldDeleteLogFile} from "../../../src/util/logger.js"; -describe("shouldDeleteLogFile", function () { +describe("shouldDeleteLogFile", () => { const prefix = "beacon"; const extension = "log"; diff --git a/packages/cli/test/unit/validator/keys.test.ts b/packages/cli/test/unit/validator/keys.test.ts index c977c2242c33..6902d17b3883 100644 --- a/packages/cli/test/unit/validator/keys.test.ts +++ b/packages/cli/test/unit/validator/keys.test.ts @@ -10,7 +10,7 @@ describe("validator / signers / importKeystoreDefinitionsFromExternalDir", () => if (tmpDir) fs.rmSync(tmpDir, {recursive: true}); }); - it("should filter out deposit data files", function () { + it("should filter out deposit data files", () => { tmpDir = fs.mkdtempSync("cli-keystores-import-test"); // Populate dir diff --git a/packages/cli/test/utils/crucible/assertions/defaults/attestationCountAssertion.ts b/packages/cli/test/utils/crucible/assertions/defaults/attestationCountAssertion.ts index 5d0f7a268f88..922ce80ae329 100644 --- a/packages/cli/test/utils/crucible/assertions/defaults/attestationCountAssertion.ts +++ b/packages/cli/test/utils/crucible/assertions/defaults/attestationCountAssertion.ts @@ -32,7 +32,7 @@ export const attestationsCountAssertion: Assertion<"attestationsCount", number, async assert({clock, store, epoch, node, dependantStores}) { const errors: AssertionResult[] = []; - const inclusionDelayStore = dependantStores["inclusionDelay"]; + const inclusionDelayStore = dependantStores.inclusionDelay; const startSlot = epoch === 0 ? 1 : clock.getFirstSlotOfEpoch(epoch); const endSlot = clock.getLastSlotOfEpoch(epoch); diff --git a/packages/cli/test/utils/crucible/assertions/nodeAssertion.ts b/packages/cli/test/utils/crucible/assertions/nodeAssertion.ts index 9659cc34e7bf..04c9b393d245 100644 --- a/packages/cli/test/utils/crucible/assertions/nodeAssertion.ts +++ b/packages/cli/test/utils/crucible/assertions/nodeAssertion.ts @@ -17,7 +17,7 @@ export const nodeAssertion: Assertion<"node", {health: number; keyManagerKeys: s let keyManagerKeys: string[]; // There is an authentication issue with the lighthouse keymanager client - if (node.validator.client == ValidatorClient.Lighthouse || getAllKeys(node.validator.keys).length === 0) { + if (node.validator.client === ValidatorClient.Lighthouse || getAllKeys(node.validator.keys).length === 0) { keyManagerKeys = []; } else { const keys = (await node.validator.keyManager.listKeys()).value(); @@ -30,7 +30,7 @@ export const nodeAssertion: Assertion<"node", {health: number; keyManagerKeys: s const errors: AssertionResult[] = []; // There is an authentication issue with the lighthouse keymanager client - if (node.validator?.client == ValidatorClient.Lighthouse) return errors; + if (node.validator?.client === ValidatorClient.Lighthouse) return errors; const {health, keyManagerKeys} = store[slot]; diff --git a/packages/cli/test/utils/crucible/clients/beacon/lodestar.ts b/packages/cli/test/utils/crucible/clients/beacon/lodestar.ts index 3321401a21dd..2bc7c27ead41 100644 --- a/packages/cli/test/utils/crucible/clients/beacon/lodestar.ts +++ b/packages/cli/test/utils/crucible/clients/beacon/lodestar.ts @@ -58,11 +58,11 @@ export const generateLodestarBeaconNode: BeaconNodeGenerator = (o "--verbosity", "5", ...(mining ? ["--mine", "--miner.etherbase", EL_GENESIS_ACCOUNT] : []), - ...(mode == ExecutionStartMode.PreMerge ? ["--nodiscover"] : []), + ...(mode === ExecutionStartMode.PreMerge ? ["--nodiscover"] : []), ...clientOptions, ], env: {}, diff --git a/packages/cli/test/utils/crucible/tableReporter.ts b/packages/cli/test/utils/crucible/tableReporter.ts index d11fc9ca3fbc..d40be13ad6e8 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; @@ -59,12 +58,10 @@ export class TableReporter extends SimulationReporter const participation: {head: number; source: number; target: number}[] = []; for (const node of nodes) { - participation.push( - stores["attestationParticipation"][node.beacon.id][slot] ?? {head: 0, source: 0, target: 0} - ); + participation.push(stores.attestationParticipation[node.beacon.id][slot] ?? {head: 0, source: 0, target: 0}); const syncCommitteeParticipation: number[] = []; for (let slot = startSlot; slot <= endSlot; slot++) { - syncCommitteeParticipation.push(stores["syncCommitteeParticipation"][node.beacon.id][slot] ?? 0); + syncCommitteeParticipation.push(stores.syncCommitteeParticipation[node.beacon.id][slot] ?? 0); } nodesSyncParticipationAvg.push(avg(syncCommitteeParticipation)); } @@ -88,19 +85,19 @@ export class TableReporter extends SimulationReporter const peersCount: number[] = []; for (const node of nodes) { - const finalized = stores["finalized"][node.beacon.id][slot]; + const finalized = stores.finalized[node.beacon.id][slot]; if (!isNullish(finalized)) finalizedSlots.push(finalized); - const inclusionDelay = stores["inclusionDelay"][node.beacon.id][slot]; + const inclusionDelay = stores.inclusionDelay[node.beacon.id][slot]; if (!isNullish(inclusionDelay)) inclusionDelays.push(inclusionDelay); - const attestationsCount = stores["attestationsCount"][node.beacon.id][slot]; + const attestationsCount = stores.attestationsCount[node.beacon.id][slot]; if (!isNullish(attestationsCount)) attestationCounts.push(attestationsCount); - const head = stores["head"][node.beacon.id][slot]; + const head = stores.head[node.beacon.id][slot]; if (!isNullish(head)) heads.push(head); - const connectedPeerCount = stores["connectedPeerCount"][node.beacon.id][slot]; + const connectedPeerCount = stores.connectedPeerCount[node.beacon.id][slot]; if (!isNullish(connectedPeerCount)) peersCount.push(connectedPeerCount); } 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/paths.ts b/packages/cli/test/utils/crucible/utils/paths.ts index 9f0628e34656..4ff149d6f308 100644 --- a/packages/cli/test/utils/crucible/utils/paths.ts +++ b/packages/cli/test/utils/crucible/utils/paths.ts @@ -79,10 +79,15 @@ export const getNodeMountedPaths = => { return Object.entries(paths) - .map(([key, value]) => [ + .flatMap(([key, value]) => [ [key, value], [`${key}Mounted`, mount ? (value as string).replace(paths.rootDir, mountPath) : value], ]) - .flat() - .reduce((o, [key, value]) => ({...o, [key]: value as string}), {}) as MountedPaths; + .reduce( + (o, [key, value]) => { + o[key] = value as string; + return o; + }, + {} as Record + ) as MountedPaths; }; 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 0: ${batchSize}`); if (batchSize > MAX_VALIDATORS_PER_COMMITTEE) throw Error("batchSize must be < MAX_VALIDATORS_PER_COMMITTEE"); diff --git a/packages/flare/src/cmds/selfSlashProposer.ts b/packages/flare/src/cmds/selfSlashProposer.ts index 14a270239268..dd9580232e71 100644 --- a/packages/flare/src/cmds/selfSlashProposer.ts +++ b/packages/flare/src/cmds/selfSlashProposer.ts @@ -52,7 +52,7 @@ export async function selfSlashProposerHandler(args: SelfSlashArgs): Promise 0: ${batchSize}`); // TODO: Ask the user to confirm the range and slash action diff --git a/packages/flare/src/util/format.ts b/packages/flare/src/util/format.ts index 0da0fa509be6..989472932ca6 100644 --- a/packages/flare/src/util/format.ts +++ b/packages/flare/src/util/format.ts @@ -8,8 +8,8 @@ export function parseRange(range: string): number[] { const [from, to] = range.split("..").map((n) => parseInt(n)); - if (isNaN(from)) throw Error(`Invalid range from isNaN '${range}'`); - if (isNaN(to)) throw Error(`Invalid range to isNaN '${range}'`); + if (Number.isNaN(from)) throw Error(`Invalid range from isNaN '${range}'`); + if (Number.isNaN(to)) throw Error(`Invalid range to isNaN '${range}'`); if (from > to) throw Error(`Invalid range from > to '${range}'`); const arr: number[] = []; diff --git a/packages/fork-choice/src/forkChoice/forkChoice.ts b/packages/fork-choice/src/forkChoice/forkChoice.ts index 6ca3fd3a183a..6990a6b3eced 100644 --- a/packages/fork-choice/src/forkChoice/forkChoice.ts +++ b/packages/fork-choice/src/forkChoice/forkChoice.ts @@ -1245,7 +1245,9 @@ export class ForkChoice implements IForkChoice { currentEpoch: epochNow, }, }); - } else if (!forceImport && targetEpoch + 1 < epochNow) { + } + + if (!forceImport && targetEpoch + 1 < epochNow) { throw new ForkChoiceError({ code: ForkChoiceErrorCode.INVALID_ATTESTATION, err: { @@ -1526,7 +1528,9 @@ export function assertValidTerminalPowBlock( throw Error( `Invalid terminal POW block: total difficulty not reached expected >= ${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/computeDeltas.ts b/packages/fork-choice/src/protoArray/computeDeltas.ts index a3366fa738ae..c921e12f751e 100644 --- a/packages/fork-choice/src/protoArray/computeDeltas.ts +++ b/packages/fork-choice/src/protoArray/computeDeltas.ts @@ -26,8 +26,8 @@ export function computeDeltas( deltas.fill(0); // avoid creating new variables in the loop to potentially reduce GC pressure - let oldBalance, newBalance: number; - let currentIndex, nextIndex: number | null; + let oldBalance: number, newBalance: number; + let currentIndex: number | null, nextIndex: number | null; for (let vIndex = 0; vIndex < votes.length; vIndex++) { const vote = votes[vIndex]; 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/fork-choice/test/unit/forkChoice/forkChoice.test.ts b/packages/fork-choice/test/unit/forkChoice/forkChoice.test.ts index 40988a0e4a71..f47849136bff 100644 --- a/packages/fork-choice/test/unit/forkChoice/forkChoice.test.ts +++ b/packages/fork-choice/test/unit/forkChoice/forkChoice.test.ts @@ -14,11 +14,9 @@ import { EpochDifference, DataAvailabilityStatus, } from "../../../src/index.js"; +import {getBlockRoot, getStateRoot} from "../../utils/index.js"; -const rootStateBytePrefix = 0xaa; -const rootBlockBytePrefix = 0xbb; - -describe("Forkchoice", function () { +describe("Forkchoice", () => { const genesisSlot = 0; const genesisEpoch = 0; const genesisRoot = "0x0000000000000000000000000000000000000000000000000000000000000000"; @@ -118,7 +116,7 @@ describe("Forkchoice", function () { } }; - it("getAllAncestorBlocks", function () { + it("getAllAncestorBlocks", () => { // Add block that is a finalized descendant. const block = getBlock(genesisSlot + 1); protoArr.onBlock(block, block.slot); @@ -175,20 +173,6 @@ describe("Forkchoice", function () { // TODO: more unit tests for other apis }); -export function getStateRoot(slot: number): RootHex { - const root = Buffer.alloc(32, 0x00); - root[0] = rootStateBytePrefix; - root[31] = slot; - return toHex(root); -} - -export function getBlockRoot(slot: number): RootHex { - const root = Buffer.alloc(32, 0x00); - root[0] = rootBlockBytePrefix; - root[31] = slot; - return toHex(root); -} - function range(from: number, toInclusive: number): number[] { const arr: number[] = []; for (let i = from; i <= toInclusive; i++) { diff --git a/packages/fork-choice/test/unit/forkChoice/getProposerHead.test.ts b/packages/fork-choice/test/unit/forkChoice/getProposerHead.test.ts index f603a4069b83..187834e6d63a 100644 --- a/packages/fork-choice/test/unit/forkChoice/getProposerHead.test.ts +++ b/packages/fork-choice/test/unit/forkChoice/getProposerHead.test.ts @@ -13,11 +13,11 @@ import { DataAvailabilityStatus, } from "../../../src/index.js"; import {NotReorgedReason} from "../../../src/forkChoice/interface.js"; -import {getBlockRoot, getStateRoot} from "./forkChoice.test.js"; +import {getBlockRoot, getStateRoot} from "../../utils/index.js"; type ProtoBlockWithWeight = ProtoBlock & {weight: number}; // weight of the block itself -describe("Forkchoice / GetProposerHead", function () { +describe("Forkchoice / GetProposerHead", () => { const genesisSlot = 0; const genesisEpoch = 0; const genesisRoot = "0x0000000000000000000000000000000000000000000000000000000000000000"; diff --git a/packages/fork-choice/test/unit/forkChoice/utils.test.ts b/packages/fork-choice/test/unit/forkChoice/utils.test.ts index d8793206f4ba..44b0eb8b719b 100644 --- a/packages/fork-choice/test/unit/forkChoice/utils.test.ts +++ b/packages/fork-choice/test/unit/forkChoice/utils.test.ts @@ -3,11 +3,11 @@ import {createChainForkConfig} from "@lodestar/config"; import {ssz} from "@lodestar/types"; import {assertValidTerminalPowBlock, ExecutionStatus} from "../../../src/index.js"; -describe("assertValidTerminalPowBlock", function () { +describe("assertValidTerminalPowBlock", () => { const config = createChainForkConfig({TERMINAL_TOTAL_DIFFICULTY: BigInt(10)}); const block = ssz.bellatrix.BeaconBlock.defaultValue(); const executionStatus = ExecutionStatus.Valid; - it("should accept ttd >= genesis block as terminal without powBlockParent", function () { + it("should accept ttd >= genesis block as terminal without powBlockParent", () => { const powBlock = { blockHash: "0x" + "ab".repeat(32), // genesis powBlock will have zero parent hash @@ -19,7 +19,7 @@ describe("assertValidTerminalPowBlock", function () { ).not.toThrow(); }); - it("should require powBlockParent if powBlock not genesis", function () { + it("should require powBlockParent if powBlock not genesis", () => { const powBlock = { blockHash: "0x" + "ab".repeat(32), // genesis powBlock will have non zero parent hash @@ -31,7 +31,7 @@ describe("assertValidTerminalPowBlock", function () { ).toThrow(); }); - it("should require powBlock >= ttd", function () { + it("should require powBlock >= ttd", () => { const powBlock = { blockHash: "0x" + "ab".repeat(32), // genesis powBlock will have non zero parent hash @@ -43,7 +43,7 @@ describe("assertValidTerminalPowBlock", function () { ).toThrow(); }); - it("should require powBlockParent < ttd", function () { + it("should require powBlockParent < ttd", () => { const powBlock = { blockHash: "0x" + "ab".repeat(32), // genesis powBlock will have non zero parent hash @@ -55,7 +55,7 @@ describe("assertValidTerminalPowBlock", function () { ).toThrow(); }); - it("should accept powBlockParent < ttd and powBlock >= ttd", function () { + it("should accept powBlockParent < ttd and powBlock >= ttd", () => { const powBlock = { blockHash: "0x" + "ab".repeat(32), // genesis powBlock will have non zero parent hash diff --git a/packages/fork-choice/test/unit/protoArray/getCommonAncestor.test.ts b/packages/fork-choice/test/unit/protoArray/getCommonAncestor.test.ts index 9c06682ca351..b9b7f9c37b43 100644 --- a/packages/fork-choice/test/unit/protoArray/getCommonAncestor.test.ts +++ b/packages/fork-choice/test/unit/protoArray/getCommonAncestor.test.ts @@ -79,7 +79,11 @@ describe("getCommonAncestor", () => { it(`${nodeA} & ${nodeB} -> ${ancestor}`, () => { // biome-ignore lint/style/noNonNullAssertion: const ancestorNode = fc.getCommonAncestor(fc.getNode(nodeA)!, fc.getNode(nodeB)!); - expect(ancestorNode && ancestorNode.blockRoot).toBe(ancestor); + if (ancestor) { + expect(ancestorNode?.blockRoot).toBe(ancestor); + } else { + expect(ancestorNode).toBeNull(); + } }); } diff --git a/packages/fork-choice/test/utils/index.ts b/packages/fork-choice/test/utils/index.ts new file mode 100644 index 000000000000..8354a8c31d56 --- /dev/null +++ b/packages/fork-choice/test/utils/index.ts @@ -0,0 +1,19 @@ +import {RootHex} from "@lodestar/types"; +import {toHex} from "@lodestar/utils"; + +const rootStateBytePrefix = 0xaa; +const rootBlockBytePrefix = 0xbb; + +export function getStateRoot(slot: number): RootHex { + const root = Buffer.alloc(32, 0x00); + root[0] = rootStateBytePrefix; + root[31] = slot; + return toHex(root); +} + +export function getBlockRoot(slot: number): RootHex { + const root = Buffer.alloc(32, 0x00); + root[0] = rootBlockBytePrefix; + root[31] = slot; + return toHex(root); +} diff --git a/packages/light-client/src/spec/isBetterUpdate.ts b/packages/light-client/src/spec/isBetterUpdate.ts index 260d54434fba..00220cd6b5dd 100644 --- a/packages/light-client/src/spec/isBetterUpdate.ts +++ b/packages/light-client/src/spec/isBetterUpdate.ts @@ -28,49 +28,49 @@ export function isBetterUpdate(newUpdate: LightClientUpdateSummary, oldUpdate: L const oldNumActiveParticipants = oldUpdate.activeParticipants; const newHasSupermajority = newNumActiveParticipants * 3 >= SYNC_COMMITTEE_SIZE * 2; const oldHasSupermajority = oldNumActiveParticipants * 3 >= SYNC_COMMITTEE_SIZE * 2; - if (newHasSupermajority != oldHasSupermajority) { + if (newHasSupermajority !== oldHasSupermajority) { return newHasSupermajority; } - if (!newHasSupermajority && newNumActiveParticipants != oldNumActiveParticipants) { + if (!newHasSupermajority && newNumActiveParticipants !== oldNumActiveParticipants) { return newNumActiveParticipants > oldNumActiveParticipants; } // Compare presence of relevant sync committee const newHasRelevantSyncCommittee = newUpdate.isSyncCommitteeUpdate && - computeSyncPeriodAtSlot(newUpdate.attestedHeaderSlot) == computeSyncPeriodAtSlot(newUpdate.signatureSlot); + computeSyncPeriodAtSlot(newUpdate.attestedHeaderSlot) === computeSyncPeriodAtSlot(newUpdate.signatureSlot); const oldHasRelevantSyncCommittee = oldUpdate.isSyncCommitteeUpdate && - computeSyncPeriodAtSlot(oldUpdate.attestedHeaderSlot) == computeSyncPeriodAtSlot(oldUpdate.signatureSlot); - if (newHasRelevantSyncCommittee != oldHasRelevantSyncCommittee) { + computeSyncPeriodAtSlot(oldUpdate.attestedHeaderSlot) === computeSyncPeriodAtSlot(oldUpdate.signatureSlot); + if (newHasRelevantSyncCommittee !== oldHasRelevantSyncCommittee) { return newHasRelevantSyncCommittee; } // Compare indication of any finality const newHasFinality = newUpdate.isFinalityUpdate; const oldHasFinality = oldUpdate.isFinalityUpdate; - if (newHasFinality != oldHasFinality) { + if (newHasFinality !== oldHasFinality) { return newHasFinality; } // Compare sync committee finality if (newHasFinality) { const newHasSyncCommitteeFinality = - computeSyncPeriodAtSlot(newUpdate.finalizedHeaderSlot) == computeSyncPeriodAtSlot(newUpdate.attestedHeaderSlot); + computeSyncPeriodAtSlot(newUpdate.finalizedHeaderSlot) === computeSyncPeriodAtSlot(newUpdate.attestedHeaderSlot); const oldHasSyncCommitteeFinality = - computeSyncPeriodAtSlot(oldUpdate.finalizedHeaderSlot) == computeSyncPeriodAtSlot(oldUpdate.attestedHeaderSlot); - if (newHasSyncCommitteeFinality != oldHasSyncCommitteeFinality) { + computeSyncPeriodAtSlot(oldUpdate.finalizedHeaderSlot) === computeSyncPeriodAtSlot(oldUpdate.attestedHeaderSlot); + if (newHasSyncCommitteeFinality !== oldHasSyncCommitteeFinality) { return newHasSyncCommitteeFinality; } } // Tiebreaker 1: Sync committee participation beyond supermajority - if (newNumActiveParticipants != oldNumActiveParticipants) { + if (newNumActiveParticipants !== oldNumActiveParticipants) { return newNumActiveParticipants > oldNumActiveParticipants; } // Tiebreaker 2: Prefer older data (fewer changes to best) - if (newUpdate.attestedHeaderSlot != oldUpdate.attestedHeaderSlot) { + if (newUpdate.attestedHeaderSlot !== oldUpdate.attestedHeaderSlot) { return newUpdate.attestedHeaderSlot < oldUpdate.attestedHeaderSlot; } return newUpdate.signatureSlot < oldUpdate.signatureSlot; diff --git a/packages/light-client/src/spec/utils.ts b/packages/light-client/src/spec/utils.ts index d80b9bb7d9a1..36bc7098fcc5 100644 --- a/packages/light-client/src/spec/utils.ts +++ b/packages/light-client/src/spec/utils.ts @@ -96,16 +96,19 @@ export function upgradeLightClientHeader( const startUpgradeFromFork = Object.values(ForkName)[ForkSeq[headerFork] + 1]; switch (startUpgradeFromFork) { + // biome-ignore lint/suspicious/useDefaultSwitchClauseLast: We want default to evaluate at first to throw error early default: throw Error( `Invalid startUpgradeFromFork=${startUpgradeFromFork} for headerFork=${headerFork} in upgradeLightClientHeader to targetFork=${targetFork}` ); case ForkName.altair: + // biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here case ForkName.bellatrix: // Break if no further upgradation is required else fall through if (ForkSeq[targetFork] <= ForkSeq.bellatrix) break; + // biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here case ForkName.capella: (upgradedHeader as LightClientHeader).execution = ssz.capella.LightClientHeader.fields.execution.defaultValue(); @@ -115,6 +118,7 @@ export function upgradeLightClientHeader( // Break if no further upgradation is required else fall through if (ForkSeq[targetFork] <= ForkSeq.capella) break; + // biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here case ForkName.deneb: (upgradedHeader as LightClientHeader).execution.blobGasUsed = ssz.deneb.LightClientHeader.fields.execution.fields.blobGasUsed.defaultValue(); 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/light-client/test/unit/isValidLightClientHeader.test.ts b/packages/light-client/test/unit/isValidLightClientHeader.test.ts index 8181c6a5def4..2bbbd1250961 100644 --- a/packages/light-client/test/unit/isValidLightClientHeader.test.ts +++ b/packages/light-client/test/unit/isValidLightClientHeader.test.ts @@ -4,7 +4,7 @@ import {LightClientHeader, ssz} from "@lodestar/types"; import {createBeaconConfig, createChainForkConfig, defaultChainConfig} from "@lodestar/config"; import {isValidLightClientHeader} from "../../src/spec/utils.js"; -describe("isValidLightClientHeader", function () { +describe("isValidLightClientHeader", () => { const chainConfig = createChainForkConfig({ ...defaultChainConfig, ALTAIR_FORK_EPOCH: 0, @@ -87,10 +87,10 @@ describe("isValidLightClientHeader", function () { ["capella upgraded to deneb LC header", capellaUpgradedDenebHeader], ]; - testCases.forEach(([name, header]: [string, LightClientHeader]) => { - it(name, function () { + for (const [name, header] of testCases) { + it(name, () => { const isValid = isValidLightClientHeader(config, header); expect(isValid).toBe(true); }); - }); + } }); diff --git a/packages/light-client/test/unit/syncInMemory.test.ts b/packages/light-client/test/unit/syncInMemory.test.ts index 770827e86655..6118a1b4e61a 100644 --- a/packages/light-client/test/unit/syncInMemory.test.ts +++ b/packages/light-client/test/unit/syncInMemory.test.ts @@ -22,7 +22,7 @@ function getSyncCommittee( return syncCommitteeKeys; } -describe("syncInMemory", function () { +describe("syncInMemory", () => { // In browser test this process is taking more time than default 2000ms vi.setConfig({testTimeout: 10000}); @@ -39,9 +39,7 @@ describe("syncInMemory", function () { expect(sk.toPublicKey().toHex()).toBe( "0xaa1a1c26055a329817a5759d877a2795f9499b97d6056edde0eea39512f24e8bc874b4471f0501127abb1ea0d9f68ac1" ); - }); - beforeAll(() => { // Create a state that has as nextSyncCommittee the committee 2 const finalizedBlockSlot = SLOTS_PER_EPOCH * EPOCHS_PER_SYNC_COMMITTEE_PERIOD + 1; const headerBlockSlot = finalizedBlockSlot + 1; diff --git a/packages/light-client/test/unit/validation.test.ts b/packages/light-client/test/unit/validation.test.ts index 61442fb4bf8c..6ed3b714a690 100644 --- a/packages/light-client/test/unit/validation.test.ts +++ b/packages/light-client/test/unit/validation.test.ts @@ -15,7 +15,7 @@ import {assertValidLightClientUpdate} from "../../src/validation.js"; import {LightClientSnapshotFast, SyncCommitteeFast} from "../../src/types.js"; import {defaultBeaconBlockHeader, getSyncAggregateSigningRoot, signAndAggregate} from "../utils/utils.js"; -describe("validation", function () { +describe("validation", () => { // In browser test this process is taking more time than default 2000ms // specially on the CI vi.setConfig({testTimeout: 15000}); @@ -26,7 +26,7 @@ describe("validation", function () { let update: altair.LightClientUpdate; let snapshot: LightClientSnapshotFast; - beforeAll(function () { + beforeAll(() => { // Update slot must > snapshot slot // attestedHeaderSlot must == updateHeaderSlot + 1 const snapshotHeaderSlot = 1; diff --git a/packages/logger/src/browser.ts b/packages/logger/src/browser.ts index 65a0c2a6a64b..7f4972111459 100644 --- a/packages/logger/src/browser.ts +++ b/packages/logger/src/browser.ts @@ -57,7 +57,7 @@ class BrowserConsole extends Transport { constructor(opts: winston.transport.TransportStreamOptions | undefined) { super(opts); - this.level = opts?.level && this.levels.hasOwnProperty(opts.level) ? opts.level : "info"; + this.level = opts?.level && Object.prototype.hasOwnProperty.call(this.levels, opts.level) ? opts.level : "info"; } log(info: WinstonLogInfo, callback: () => void): void { diff --git a/packages/logger/src/env.ts b/packages/logger/src/env.ts index 201d91c69069..e81ae9613e15 100644 --- a/packages/logger/src/env.ts +++ b/packages/logger/src/env.ts @@ -6,20 +6,18 @@ import {LogFormat, TimestampFormat} from "./interface.js"; export function getEnvLogLevel(): LogLevel | null { if (process == null) return null; - if (process.env["LOG_LEVEL"]) return process.env["LOG_LEVEL"] as LogLevel; - if (process.env["DEBUG"]) return LogLevel.debug; - if (process.env["VERBOSE"]) return LogLevel.verbose; + if (process.env.LOG_LEVEL) return process.env.LOG_LEVEL as LogLevel; + if (process.env.DEBUG) return LogLevel.debug; + if (process.env.VERBOSE) return LogLevel.verbose; return null; } export function getEnvLogger(opts?: Partial): Logger { const level = opts?.level ?? getEnvLogLevel(); - const format = (opts?.format ?? process.env["LOG_FORMAT"]) as LogFormat; + const format = (opts?.format ?? process.env.LOG_FORMAT) as LogFormat; const timestampFormat = opts?.timestampFormat ?? - ((process.env["LOG_TIMESTAMP_FORMAT"] - ? {format: process.env["LOG_TIMESTAMP_FORMAT"]} - : undefined) as TimestampFormat); + ((process.env.LOG_TIMESTAMP_FORMAT ? {format: process.env.LOG_TIMESTAMP_FORMAT} : undefined) as TimestampFormat); if (level != null) { return getBrowserLogger({...opts, level, format, timestampFormat}); diff --git a/packages/logger/src/node.ts b/packages/logger/src/node.ts index 60ca87e0367c..fcd9c535dd9e 100644 --- a/packages/logger/src/node.ts +++ b/packages/logger/src/node.ts @@ -128,7 +128,7 @@ export class WinstonLoggerNode extends WinstonLogger implements LoggerNode { } static fromOpts(opts: LoggerNodeOpts, transports: winston.transport[]): WinstonLoggerNode { - return new WinstonLoggerNode(this.createWinstonInstance(opts, transports), opts); + return new WinstonLoggerNode(WinstonLoggerNode.createWinstonInstance(opts, transports), opts); } static fromNewTransports(opts: LoggerNodeOpts): WinstonLoggerNode { 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/logger/src/winston.ts b/packages/logger/src/winston.ts index 4e6fbbecd6b2..b886894e6aba 100644 --- a/packages/logger/src/winston.ts +++ b/packages/logger/src/winston.ts @@ -42,7 +42,7 @@ export class WinstonLogger implements Logger { constructor(protected readonly winston: Winston) {} static fromOpts(options: Partial = {}, transports?: winston.transport[]): WinstonLogger { - return new WinstonLogger(this.createWinstonInstance(options, transports)); + return new WinstonLogger(WinstonLogger.createWinstonInstance(options, transports)); } static createWinstonInstance(options: Partial = {}, transports?: winston.transport[]): Winston { diff --git a/packages/logger/test/e2e/logger/workerLogs.test.ts b/packages/logger/test/e2e/logger/workerLogs.test.ts index 969cd84bc5ff..01ede8f6e4ec 100644 --- a/packages/logger/test/e2e/logger/workerLogs.test.ts +++ b/packages/logger/test/e2e/logger/workerLogs.test.ts @@ -9,7 +9,7 @@ import {LoggerWorker, getLoggerWorker} from "./workerLoggerHandler.js"; // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules const __dirname = path.dirname(fileURLToPath(import.meta.url)); -describe("worker logs", function () { +describe("worker logs", () => { vi.setConfig({testTimeout: 60_000}); const logFilepath = path.join(__dirname, "../../../test-logs/test_worker_logs.log"); diff --git a/packages/logger/test/unit/utils/json.test.ts b/packages/logger/test/unit/utils/json.test.ts index 4b91fd1995b5..7ca5604edf00 100644 --- a/packages/logger/test/unit/utils/json.test.ts +++ b/packages/logger/test/unit/utils/json.test.ts @@ -24,8 +24,10 @@ describe("Json helper", () => { {id: "symbol", arg: Symbol("foo"), json: "Symbol(foo)"}, // Functions + // biome-ignore lint/complexity/useArrowFunction: We need a function for the this test {id: "function", arg: function () {}, json: "function() {\n }"}, {id: "arrow function", arg: () => {}, json: "() => {\n }"}, + // biome-ignore lint/complexity/useArrowFunction: We need a function for the this test {id: "async function", arg: async function () {}, json: "async function() {\n }"}, {id: "async arrow function", arg: async () => {}, json: "async () => {\n }"}, @@ -160,7 +162,7 @@ describe("Json helper", () => { // Objects {id: "object of basic types", json: {a: 1, b: "a", c: root}, output: `a=1, b=a, c=${rootHex}`}, - {id: "object of objects", json: {a: {b: 1}}, output: `a=[object]`}, + {id: "object of objects", json: {a: {b: 1}}, output: "a=[object]"}, { id: "error metadata", json: { diff --git a/packages/params/src/json.ts b/packages/params/src/json.ts index 8d475e680f4d..9fe49a920424 100644 --- a/packages/params/src/json.ts +++ b/packages/params/src/json.ts @@ -50,7 +50,7 @@ function deserializePresetValue(valueStr: unknown, keyName: string): number { const value = parseInt(valueStr, 10); - if (isNaN(value)) { + if (Number.isNaN(value)) { throw Error(`Invalid ${keyName} value ${valueStr} expected number`); } diff --git a/packages/params/test/e2e/ensure-config-is-synced.test.ts b/packages/params/test/e2e/ensure-config-is-synced.test.ts index 12e4c2a35e55..2322b2e1ff10 100644 --- a/packages/params/test/e2e/ensure-config-is-synced.test.ts +++ b/packages/params/test/e2e/ensure-config-is-synced.test.ts @@ -10,15 +10,15 @@ import {loadConfigYaml} from "../yaml.js"; /** https://github.com/ethereum/consensus-specs/releases */ const specConfigCommit = "v1.5.0-alpha.3"; -describe("Ensure config is synced", function () { +describe("Ensure config is synced", () => { vi.setConfig({testTimeout: 60 * 1000}); - it("mainnet", async function () { + it("mainnet", async () => { const remotePreset = await downloadRemoteConfig("mainnet", specConfigCommit); assertCorrectPreset({...mainnetPreset}, remotePreset); }); - it("minimal", async function () { + it("minimal", async () => { const remotePreset = await downloadRemoteConfig("minimal", specConfigCommit); assertCorrectPreset({...minimalPreset}, remotePreset); }); diff --git a/packages/params/test/e2e/overridePreset.test.ts b/packages/params/test/e2e/overridePreset.test.ts index 12fa1fb095c6..df7afbbf84da 100644 --- a/packages/params/test/e2e/overridePreset.test.ts +++ b/packages/params/test/e2e/overridePreset.test.ts @@ -15,7 +15,7 @@ const exec = util.promisify(child.exec); // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules const __dirname = path.dirname(fileURLToPath(import.meta.url)); -describe("Override preset", function () { +describe("Override preset", () => { // Allow time for ts-node to compile Typescript source vi.setConfig({testTimeout: 30_000}); diff --git a/packages/params/test/e2e/setPreset.test.ts b/packages/params/test/e2e/setPreset.test.ts index 1e236b8f2d85..2108a4f23342 100644 --- a/packages/params/test/e2e/setPreset.test.ts +++ b/packages/params/test/e2e/setPreset.test.ts @@ -15,7 +15,7 @@ const exec = util.promisify(child.exec); // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules const __dirname = path.dirname(fileURLToPath(import.meta.url)); -describe("setPreset", function () { +describe("setPreset", () => { // Allow time for ts-node to compile Typescript source vi.setConfig({testTimeout: 30_000}); diff --git a/packages/params/test/yaml.ts b/packages/params/test/yaml.ts index d1bc72125923..f56016a4dbc0 100644 --- a/packages/params/test/yaml.ts +++ b/packages/params/test/yaml.ts @@ -8,9 +8,7 @@ export const schema = FAILSAFE_SCHEMA.extend({ implicit: [ new Type("tag:yaml.org,2002:str", { kind: "scalar", - construct: function (data) { - return data !== null ? data : ""; - }, + construct: (data) => (data !== null ? data : ""), }), ], }); diff --git a/packages/prover/src/cli/applyPreset.ts b/packages/prover/src/cli/applyPreset.ts index 4a79a1a4417b..f0c3d83c7751 100644 --- a/packages/prover/src/cli/applyPreset.ts +++ b/packages/prover/src/cli/applyPreset.ts @@ -82,6 +82,3 @@ function valueOfArg(argName: string): string | null { return null; } - -// Add empty export to make this a module -export {}; diff --git a/packages/prover/src/cli/cmds/start/options.ts b/packages/prover/src/cli/cmds/start/options.ts index bdf0670771ef..5366efd96f6e 100644 --- a/packages/prover/src/cli/cmds/start/options.ts +++ b/packages/prover/src/cli/cmds/start/options.ts @@ -57,9 +57,7 @@ export const startOptions: CliCommandOptions = { string: true, coerce: (urls: string[]): string[] => // Parse ["url1,url2"] to ["url1", "url2"] - urls - .map((item) => item.split(",")) - .flat(), + urls.flatMap((item) => item.split(",")), demandOption: true, group: "beacon", }, diff --git a/packages/prover/src/proof_provider/payload_store.ts b/packages/prover/src/proof_provider/payload_store.ts index 343ec63719f9..c891cb994da1 100644 --- a/packages/prover/src/proof_provider/payload_store.ts +++ b/packages/prover/src/proof_provider/payload_store.ts @@ -39,7 +39,7 @@ export class PayloadStore { const maxBlockNumberForFinalized = this.finalizedRoots.max; if (maxBlockNumberForFinalized === undefined) { - return; + return undefined; } const finalizedMaxRoot = this.finalizedRoots.get(maxBlockNumberForFinalized); 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/prover/src/web3_provider_inspector.ts b/packages/prover/src/web3_provider_inspector.ts index c81847b64d61..154a860d0922 100644 --- a/packages/prover/src/web3_provider_inspector.ts +++ b/packages/prover/src/web3_provider_inspector.ts @@ -68,7 +68,7 @@ export class Web3ProviderInspector { return; } - const index = this.providerTypes.findIndex((p) => p.name == indexOrName); + const index = this.providerTypes.findIndex((p) => p.name === indexOrName); if (index < 0) { throw Error(`Provider type '${indexOrName}' is not registered.`); } diff --git a/packages/prover/test/e2e/cli/cmds/start.test.ts b/packages/prover/test/e2e/cli/cmds/start.test.ts index 8ac71e1a1797..75773ac02d36 100644 --- a/packages/prover/test/e2e/cli/cmds/start.test.ts +++ b/packages/prover/test/e2e/cli/cmds/start.test.ts @@ -29,7 +29,7 @@ describe("prover/proxy", () => { const paramsFilePath = path.join("/tmp", "e2e-test-env", "params.json"); const web3: Web3 = new Web3(proxyUrl); - beforeAll(async function () { + beforeAll(async () => { await waitForCapellaFork(); await mkdir(path.dirname(paramsFilePath), {recursive: true}); await writeFile(paramsFilePath, JSON.stringify(chainConfigToJson(config as ChainConfig))); diff --git a/packages/prover/test/e2e/web3_batch_request.test.ts b/packages/prover/test/e2e/web3_batch_request.test.ts index e232208a15b3..6dae04a9c36d 100644 --- a/packages/prover/test/e2e/web3_batch_request.test.ts +++ b/packages/prover/test/e2e/web3_batch_request.test.ts @@ -5,7 +5,7 @@ import {createVerifiedExecutionProvider} from "../../src/web3_provider.js"; import {rpcUrl, beaconUrl, config, waitForCapellaFork, minCapellaTimeMs} from "../utils/e2e_env.js"; import {getVerificationFailedMessage} from "../../src/utils/json_rpc.js"; -describe("web3_batch_requests", function () { +describe("web3_batch_requests", () => { vi.setConfig({hookTimeout: minCapellaTimeMs}); let web3: Web3; diff --git a/packages/prover/test/e2e/web3_provider.test.ts b/packages/prover/test/e2e/web3_provider.test.ts index 3d670d7ed412..edb3bb09e2fb 100644 --- a/packages/prover/test/e2e/web3_provider.test.ts +++ b/packages/prover/test/e2e/web3_provider.test.ts @@ -5,7 +5,7 @@ import {LCTransport} from "../../src/interfaces.js"; import {createVerifiedExecutionProvider} from "../../src/web3_provider.js"; import {waitForCapellaFork, minCapellaTimeMs, rpcUrl, beaconUrl, config} from "../utils/e2e_env.js"; -describe("web3_provider", function () { +describe("web3_provider", () => { vi.setConfig({hookTimeout: minCapellaTimeMs}); beforeAll(async () => { diff --git a/packages/prover/test/unit/proof_provider/payload_store.test.ts b/packages/prover/test/unit/proof_provider/payload_store.test.ts index b482bb579e77..6bc1e4265205 100644 --- a/packages/prover/test/unit/proof_provider/payload_store.test.ts +++ b/packages/prover/test/unit/proof_provider/payload_store.test.ts @@ -53,7 +53,7 @@ const buildBlockResponse = ({ return apiResponse; }; -describe("proof_provider/payload_store", function () { +describe("proof_provider/payload_store", () => { let api: ApiClient & {beacon: MockedObject}; let logger: Logger; let store: PayloadStore; diff --git a/packages/reqresp/src/encoders/responseDecode.ts b/packages/reqresp/src/encoders/responseDecode.ts index d55b283df5e6..0dde5bcdc95e 100644 --- a/packages/reqresp/src/encoders/responseDecode.ts +++ b/packages/reqresp/src/encoders/responseDecode.ts @@ -110,7 +110,7 @@ export async function readResultHeader(bufferedSource: BufferedSource): Promise< */ export async function readErrorMessage(bufferedSource: BufferedSource): Promise { // Read at least 256 or wait for the stream to end - let length; + let length: number | undefined; for await (const buffer of bufferedSource) { // Wait for next chunk with bytes or for the stream to end // Note: The entire is expected to be in the same chunk @@ -121,6 +121,7 @@ export async function readErrorMessage(bufferedSource: BufferedSource): Promise< length = buffer.length; } + // biome-ignore lint/complexity/useLiteralKeys: It is a private attribute const bytes = bufferedSource["buffer"].slice(0, length); try { 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/unit/encodingStrategies/sszSnappy/snappyFrames/uncompress.test.ts b/packages/reqresp/test/unit/encodingStrategies/sszSnappy/snappyFrames/uncompress.test.ts index b47621082a65..dc01a1952142 100644 --- a/packages/reqresp/test/unit/encodingStrategies/sszSnappy/snappyFrames/uncompress.test.ts +++ b/packages/reqresp/test/unit/encodingStrategies/sszSnappy/snappyFrames/uncompress.test.ts @@ -4,7 +4,7 @@ import {pipe} from "it-pipe"; import {SnappyFramesUncompress} from "../../../../../src/encodingStrategies/sszSnappy/snappyFrames/uncompress.js"; import {encodeSnappy} from "../../../../../src/encodingStrategies/sszSnappy/snappyFrames/compress.js"; -describe("encodingStrategies / sszSnappy / snappy frames / uncompress", function () { +describe("encodingStrategies / sszSnappy / snappy frames / uncompress", () => { it("should work with short input", () => new Promise((done) => { const testData = "Small test data"; @@ -12,7 +12,7 @@ describe("encodingStrategies / sszSnappy / snappy frames / uncompress", function const decompress = new SnappyFramesUncompress(); - void pipe(compressIterable, async function (source) { + void pipe(compressIterable, async (source) => { for await (const data of source) { const result = decompress.uncompress(new Uint8ArrayList(data)); if (result) { @@ -30,7 +30,7 @@ describe("encodingStrategies / sszSnappy / snappy frames / uncompress", function let result = Buffer.alloc(0); const decompress = new SnappyFramesUncompress(); - void pipe(compressIterable, async function (source) { + void pipe(compressIterable, async (source) => { for await (const data of source) { // testData will come compressed as two or more chunks result = Buffer.concat([ @@ -45,13 +45,13 @@ describe("encodingStrategies / sszSnappy / snappy frames / uncompress", function }); })); - it("should detect malformed input", function () { + it("should detect malformed input", () => { const decompress = new SnappyFramesUncompress(); expect(() => decompress.uncompress(new Uint8ArrayList(Buffer.alloc(32, 5)))).toThrow(); }); - it("should return null if not enough data", function () { + it("should return null if not enough data", () => { const decompress = new SnappyFramesUncompress(); expect(decompress.uncompress(new Uint8ArrayList(Buffer.alloc(3, 1)))).toBe(null); 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 af77d45f6242..888c87e3ffa8 100644 --- a/packages/spec-test-util/src/single.ts +++ b/packages/spec-test-util/src/single.ts @@ -124,7 +124,7 @@ export function describeDirectorySpecTest let testCase = loadInputFiles(testSubDirPath, options, meta); if (options.mapToTestCase) testCase = options.mapToTestCase(testCase); - if (options.shouldSkip && options.shouldSkip(testCase, testName, 0)) { + if (options.shouldSkip?.(testCase, testName, 0)) { context.skip(); return; } @@ -157,7 +157,8 @@ function loadInputFiles( meta?: TestCase["meta"] ): TestCase { const testCase: any = {}; - fs.readdirSync(directory) + const files = fs + .readdirSync(directory) .map((name) => path.join(directory, name)) .filter((file) => { if (isDirectory(file)) { @@ -170,33 +171,37 @@ function loadInputFiles( options.inputTypes[name] = inputType; const extension = inputType.type as string; return file.endsWith(extension); - }) - .forEach((file) => { - const inputName = path.basename(file).replace(".ssz_snappy", "").replace(".ssz", "").replace(".yaml", ""); - const inputType = getInputType(file); - testCase[inputName] = deserializeInputFile(file, inputName, inputType, options, meta); - switch (inputType) { - case InputType.SSZ: - testCase[`${inputName}_raw`] = fs.readFileSync(file); - break; - case InputType.SSZ_SNAPPY: - testCase[`${inputName}_raw`] = uncompress(fs.readFileSync(file)); - break; - } - if (!options.inputProcessing) throw Error("inputProcessing is not defined"); - if (options.inputProcessing[inputName] !== undefined) { - testCase[inputName] = options.inputProcessing[inputName](testCase[inputName]); - } }); + for (const file of files) { + const inputName = path.basename(file).replace(".ssz_snappy", "").replace(".ssz", "").replace(".yaml", ""); + const inputType = getInputType(file); + testCase[inputName] = deserializeInputFile(file, inputName, inputType, options, meta); + switch (inputType) { + case InputType.SSZ: + testCase[`${inputName}_raw`] = fs.readFileSync(file); + break; + case InputType.SSZ_SNAPPY: + testCase[`${inputName}_raw`] = uncompress(fs.readFileSync(file)); + break; + } + if (!options.inputProcessing) throw Error("inputProcessing is not defined"); + if (options.inputProcessing[inputName] !== undefined) { + testCase[inputName] = options.inputProcessing[inputName](testCase[inputName]); + } + } return testCase as TestCase; } 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}`); @@ -211,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); @@ -239,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/cache/stateCache.ts b/packages/state-transition/src/cache/stateCache.ts index 5412675352e9..3eeeb285b660 100644 --- a/packages/state-transition/src/cache/stateCache.ts +++ b/packages/state-transition/src/cache/stateCache.ts @@ -254,9 +254,11 @@ export function isCachedBeaconState( // This cache is populated during epoch transition, and should be preserved for performance. // If the cache is missing too often, means that our clone strategy is not working well. export function isStateValidatorsNodesPopulated(state: CachedBeaconStateAllForks): boolean { + // biome-ignore lint/complexity/useLiteralKeys: It is a private attribute return state.validators["nodesPopulated"] === true; } export function isStateBalancesNodesPopulated(state: CachedBeaconStateAllForks): boolean { + // biome-ignore lint/complexity/useLiteralKeys: It is a private attribute return state.balances["nodesPopulated"] === true; } 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/metrics.ts b/packages/state-transition/src/metrics.ts index a5e5463231fa..ac558a1be139 100644 --- a/packages/state-transition/src/metrics.ts +++ b/packages/state-transition/src/metrics.ts @@ -74,9 +74,11 @@ export function onPostStateMetrics(postState: CachedBeaconStateAllForks, metrics // This cache is populated during epoch transition, and should be preserved for performance. // If the cache is missing too often, means that our clone strategy is not working well. function isValidatorsNodesPopulated(state: CachedBeaconStateAllForks): boolean { + // biome-ignore lint/complexity/useLiteralKeys: It is a private attribute return state.validators["nodesPopulated"] === true; } function isBalancesNodesPopulated(state: CachedBeaconStateAllForks): boolean { + // biome-ignore lint/complexity/useLiteralKeys: It is a private attribute return state.balances["nodesPopulated"] === true; } diff --git a/packages/state-transition/src/signatureSets/attesterSlashings.ts b/packages/state-transition/src/signatureSets/attesterSlashings.ts index 8088c2522282..36f31d97e083 100644 --- a/packages/state-transition/src/signatureSets/attesterSlashings.ts +++ b/packages/state-transition/src/signatureSets/attesterSlashings.ts @@ -8,9 +8,9 @@ export function getAttesterSlashingsSignatureSets( state: CachedBeaconStateAllForks, signedBlock: SignedBeaconBlock ): ISignatureSet[] { - return signedBlock.message.body.attesterSlashings - .map((attesterSlashing) => getAttesterSlashingSignatureSets(state, attesterSlashing)) - .flat(1); + return signedBlock.message.body.attesterSlashings.flatMap((attesterSlashing) => + getAttesterSlashingSignatureSets(state, attesterSlashing) + ); } /** Get signature sets from a single AttesterSlashing object */ diff --git a/packages/state-transition/src/signatureSets/proposerSlashings.ts b/packages/state-transition/src/signatureSets/proposerSlashings.ts index 8a004225111d..b0c1aa465bd5 100644 --- a/packages/state-transition/src/signatureSets/proposerSlashings.ts +++ b/packages/state-transition/src/signatureSets/proposerSlashings.ts @@ -35,7 +35,7 @@ export function getProposerSlashingsSignatureSets( state: CachedBeaconStateAllForks, signedBlock: SignedBeaconBlock ): ISignatureSet[] { - return signedBlock.message.body.proposerSlashings - .map((proposerSlashing) => getProposerSlashingSignatureSets(state, proposerSlashing)) - .flat(1); + return signedBlock.message.body.proposerSlashings.flatMap((proposerSlashing) => + getProposerSlashingSignatureSets(state, proposerSlashing) + ); } diff --git a/packages/state-transition/src/slot/upgradeStateToAltair.ts b/packages/state-transition/src/slot/upgradeStateToAltair.ts index cfe43e097939..22ab8b13882c 100644 --- a/packages/state-transition/src/slot/upgradeStateToAltair.ts +++ b/packages/state-transition/src/slot/upgradeStateToAltair.ts @@ -92,6 +92,7 @@ export function upgradeStateToAltair(statePhase0: CachedBeaconStatePhase0): Cach // // TODO: This could only drop the caches of index 15,16. However this would couple this code tightly with SSZ ViewDU // internals. If the cache is not cleared, consuming the ViewDU instance could break in strange ways. + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute stateAltair["clearCache"](); // TODO: describe issue. Compute progressive target balances diff --git a/packages/state-transition/src/slot/upgradeStateToCapella.ts b/packages/state-transition/src/slot/upgradeStateToCapella.ts index ce27a17bf9b0..30a0701e58e8 100644 --- a/packages/state-transition/src/slot/upgradeStateToCapella.ts +++ b/packages/state-transition/src/slot/upgradeStateToCapella.ts @@ -64,6 +64,7 @@ export function upgradeStateToCapella(stateBellatrix: CachedBeaconStateBellatrix // Commit new added fields ViewDU to the root node stateCapella.commit(); // Clear cache to ensure the cache of bellatrix fields is not used by new capella fields + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute stateCapella["clearCache"](); return stateCapella; diff --git a/packages/state-transition/src/slot/upgradeStateToDeneb.ts b/packages/state-transition/src/slot/upgradeStateToDeneb.ts index 53be75f72ad8..2344a8d4e08e 100644 --- a/packages/state-transition/src/slot/upgradeStateToDeneb.ts +++ b/packages/state-transition/src/slot/upgradeStateToDeneb.ts @@ -34,6 +34,7 @@ export function upgradeStateToDeneb(stateCapella: CachedBeaconStateCapella): Cac stateDeneb.commit(); // Clear cache to ensure the cache of capella fields is not used by new deneb fields + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute stateDeneb["clearCache"](); return stateDeneb; diff --git a/packages/state-transition/src/slot/upgradeStateToElectra.ts b/packages/state-transition/src/slot/upgradeStateToElectra.ts index 0bd36a909b46..b7cdde86a479 100644 --- a/packages/state-transition/src/slot/upgradeStateToElectra.ts +++ b/packages/state-transition/src/slot/upgradeStateToElectra.ts @@ -112,6 +112,7 @@ export function upgradeStateToElectra(stateDeneb: CachedBeaconStateDeneb): Cache // Commit new added fields ViewDU to the root node stateElectra.commit(); // Clear cache to ensure the cache of deneb fields is not used by new ELECTRA fields + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute stateElectra["clearCache"](); return stateElectra; @@ -154,6 +155,7 @@ export function upgradeStateToElectraOriginal(stateDeneb: CachedBeaconStateDeneb // Commit new added fields ViewDU to the root node stateElectra.commit(); // Clear cache to ensure the cache of deneb fields is not used by new ELECTRA fields + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute stateElectra["clearCache"](); return stateElectra; 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/computeAnchorCheckpoint.ts b/packages/state-transition/src/util/computeAnchorCheckpoint.ts index e2efc18952c2..e37ffc2c632d 100644 --- a/packages/state-transition/src/util/computeAnchorCheckpoint.ts +++ b/packages/state-transition/src/util/computeAnchorCheckpoint.ts @@ -9,8 +9,8 @@ export function computeAnchorCheckpoint( config: ChainForkConfig, anchorState: BeaconStateAllForks ): {checkpoint: phase0.Checkpoint; blockHeader: phase0.BeaconBlockHeader} { - let blockHeader; - let root; + let blockHeader: phase0.BeaconBlockHeader; + let root: Uint8Array; const blockTypes = config.getForkTypes(anchorState.latestBlockHeader.slot); if (anchorState.latestBlockHeader.slot === GENESIS_SLOT) { 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 10af814e9af3..5a6c500d3987 100644 --- a/packages/state-transition/src/util/shufflingDecisionRoot.ts +++ b/packages/state-transition/src/util/shufflingDecisionRoot.ts @@ -12,11 +12,10 @@ import {computeStartSlotAtEpoch} from "./epoch.js"; */ export function proposerShufflingDecisionRoot(state: CachedBeaconStateAllForks): Root | null { const decisionSlot = proposerShufflingDecisionSlot(state); - if (state.slot == decisionSlot) { + if (state.slot === decisionSlot) { return null; - } else { - return getBlockRootAtSlot(state, decisionSlot); } + return getBlockRootAtSlot(state, decisionSlot); } /** @@ -37,11 +36,10 @@ function proposerShufflingDecisionSlot(state: CachedBeaconStateAllForks): Slot { */ export function attesterShufflingDecisionRoot(state: CachedBeaconStateAllForks, requestedEpoch: Epoch): Root | null { const decisionSlot = attesterShufflingDecisionSlot(state, requestedEpoch); - if (state.slot == decisionSlot) { + 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/block/util.ts b/packages/state-transition/test/perf/block/util.ts index baa86dcac6a5..441c67deb198 100644 --- a/packages/state-transition/test/perf/block/util.ts +++ b/packages/state-transition/test/perf/block/util.ts @@ -206,7 +206,9 @@ function getDeposits(preState: CachedBeaconStateAllForks, count: number): phase0 // Fill depositRootViewDU up to depositCount // Instead of actually filling it, just mutate the length to allow .set() + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute depositRootViewDU["_length"] = depositCount + count; + // biome-ignore lint/complexity/useLiteralKeys: It is a protected attribute depositRootViewDU["dirtyLength"] = true; for (let i = 0; i < count; i++) { diff --git a/packages/state-transition/test/perf/csv.ts b/packages/state-transition/test/perf/csv.ts index d54b277d707c..2f47fd79f05d 100644 --- a/packages/state-transition/test/perf/csv.ts +++ b/packages/state-transition/test/perf/csv.ts @@ -41,7 +41,7 @@ export function readCsv>(filepath: string): T[] for (let i = 0; i < headers.length; i++) { const str = valuesRow[i]; const num = parseInt(str); - value[headers[i] as keyof T] = (isNaN(num) ? str : num) as T[keyof T]; + value[headers[i] as keyof T] = (Number.isNaN(num) ? str : num) as T[keyof T]; } values[j] = value; } diff --git a/packages/state-transition/test/perf/dataStructures/arrayish.test.ts b/packages/state-transition/test/perf/dataStructures/arrayish.test.ts index 5b6af0d989b6..353f81951aa7 100644 --- a/packages/state-transition/test/perf/dataStructures/arrayish.test.ts +++ b/packages/state-transition/test/perf/dataStructures/arrayish.test.ts @@ -104,7 +104,7 @@ describe("Array", () => { let arr: number[]; - before(function () { + before(() => { arr = createArray(n); }); diff --git a/packages/state-transition/test/perf/misc/aggregationBits.test.ts b/packages/state-transition/test/perf/misc/aggregationBits.test.ts index 7954f6a06a71..a0578970dfe9 100644 --- a/packages/state-transition/test/perf/misc/aggregationBits.test.ts +++ b/packages/state-transition/test/perf/misc/aggregationBits.test.ts @@ -12,7 +12,7 @@ describe("aggregationBits", () => { let indexes: number[]; let bitlistTree: BitArray; - before(function () { + before(() => { const aggregationBits = BitArray.fromBoolArray(Array.from({length: len}, () => true)); bitlistTree = ssz.phase0.CommitteeBits.toViewDU(aggregationBits); indexes = Array.from({length: len}, () => 165432); diff --git a/packages/state-transition/test/perf/misc/arrayCreation.test.ts b/packages/state-transition/test/perf/misc/arrayCreation.test.ts index c6a3cf29ed8e..4568948c678d 100644 --- a/packages/state-transition/test/perf/misc/arrayCreation.test.ts +++ b/packages/state-transition/test/perf/misc/arrayCreation.test.ts @@ -1,4 +1,4 @@ -describe.skip("array creation", function () { +describe.skip("array creation", () => { const testCases: {id: string; fn: (n: number) => void}[] = [ { id: "Array.from(() => 0)", 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/perf/util.ts b/packages/state-transition/test/perf/util.ts index 7a0bfb29efb3..0f47c241f8f9 100644 --- a/packages/state-transition/test/perf/util.ts +++ b/packages/state-transition/test/perf/util.ts @@ -194,7 +194,7 @@ export function generatePerfTestCachedStatePhase0(opts?: {goBackOneSlot: boolean ) as CachedBeaconStatePhase0; phase0CachedState23638.slot += 1; } - const resultingState = opts && opts.goBackOneSlot ? phase0CachedState23637 : phase0CachedState23638; + const resultingState = opts?.goBackOneSlot ? phase0CachedState23637 : phase0CachedState23638; return resultingState.clone(); } @@ -241,7 +241,7 @@ export function generatePerfTestCachedStateAltair(opts?: { ) as CachedBeaconStateAltair; altairCachedState23638.slot += 1; } - const resultingState = opts && opts.goBackOneSlot ? altairCachedState23637 : altairCachedState23638; + const resultingState = opts?.goBackOneSlot ? altairCachedState23637 : altairCachedState23638; return resultingState.clone(); } diff --git a/packages/state-transition/test/perf/util/signingRoot.test.ts b/packages/state-transition/test/perf/util/signingRoot.test.ts index 96684c753364..1d308c2e3e43 100644 --- a/packages/state-transition/test/perf/util/signingRoot.test.ts +++ b/packages/state-transition/test/perf/util/signingRoot.test.ts @@ -15,7 +15,7 @@ import {computeSigningRoot} from "../../../src/util/signingRoot.js"; ✔ toHexString serialized data 727592.3 ops/s 1.374396 us/op - 6916 runs 10.0 s ✔ Buffer.toString(base64) 2570800 ops/s 388.9840 ns/op - 24628 runs 10.1 s */ -describe("computeSigningRoot", function () { +describe("computeSigningRoot", () => { setBenchOpts({ minMs: 10_000, }); diff --git a/packages/state-transition/test/unit/util/aggregator.test.ts b/packages/state-transition/test/unit/util/aggregator.test.ts index 6a9d0a45a2c7..58c2b0afbf58 100644 --- a/packages/state-transition/test/unit/util/aggregator.test.ts +++ b/packages/state-transition/test/unit/util/aggregator.test.ts @@ -8,7 +8,7 @@ import { } from "@lodestar/params"; import {isAggregatorFromCommitteeLength, isSyncCommitteeAggregator} from "../../../src/util/aggregator.js"; -describe("isAttestationAggregator", function () { +describe("isAttestationAggregator", () => { const committeeLength = 130; beforeAll(() => { @@ -19,7 +19,7 @@ describe("isAttestationAggregator", function () { }); }); - it("should be false", function () { + it("should be false", () => { const result = isAggregatorFromCommitteeLength( committeeLength, fromHexString( @@ -29,7 +29,7 @@ describe("isAttestationAggregator", function () { expect(result).toBe(false); }); - it("should be true", function () { + it("should be true", () => { const result = isAggregatorFromCommitteeLength( committeeLength, fromHexString( @@ -40,7 +40,7 @@ describe("isAttestationAggregator", function () { }); }); -describe("isSyncCommitteeAggregator", function () { +describe("isSyncCommitteeAggregator", () => { beforeAll(() => { expect({ SYNC_COMMITTEE_SIZE, @@ -53,7 +53,7 @@ describe("isSyncCommitteeAggregator", function () { }); }); - it("should be false", function () { + it("should be false", () => { const result = isSyncCommitteeAggregator( fromHexString( "0x8191d16330837620f0ed85d0d3d52af5b56f7cec12658fa391814251d4b32977eb2e6ca055367354fd63175f8d1d2d7b0678c3c482b738f96a0df40bd06450d99c301a659b8396c227ed781abb37a1604297922219374772ab36b46b84817036" @@ -63,7 +63,7 @@ describe("isSyncCommitteeAggregator", function () { }); // NOTE: Invalid sig, bruteforced last characters to get a true result - it("should be true", function () { + it("should be true", () => { const result = isSyncCommitteeAggregator( fromHexString( "0xa8f8bb92931234ca6d8a34530526bcd6a4cfa3bf33bd0470200dc8fa3ebdc3ba24bc8c6e994d58a0f884eb24336d746c01a29693ed0354c0862c2d5de5859e3f58747045182844d267ba232058f7df1867a406f63a1eb8afec0cf3f00a115142" diff --git a/packages/state-transition/test/unit/util/validator.test.ts b/packages/state-transition/test/unit/util/validator.test.ts index 65727126742d..203adf9d8ba3 100644 --- a/packages/state-transition/test/unit/util/validator.test.ts +++ b/packages/state-transition/test/unit/util/validator.test.ts @@ -49,7 +49,7 @@ describe("isActiveValidator", () => { describe("isSlashableValidator", () => { let validator: phase0.Validator; - beforeEach(function () { + beforeEach(() => { validator = generateValidator(); }); diff --git a/packages/state-transition/test/unit/util/weakSubjectivity.test.ts b/packages/state-transition/test/unit/util/weakSubjectivity.test.ts index 5f5c784e975a..ce9f02b5ed2f 100644 --- a/packages/state-transition/test/unit/util/weakSubjectivity.test.ts +++ b/packages/state-transition/test/unit/util/weakSubjectivity.test.ts @@ -4,7 +4,7 @@ import {computeWeakSubjectivityPeriodFromConstituents} from "../../../src/util/w import {getChurnLimit} from "../../../src/util/validator.js"; describe("weak subjectivity tests", () => { - describe("computeWeakSubjectivityPeriodFromConstituents", function () { + describe("computeWeakSubjectivityPeriodFromConstituents", () => { const balance28 = 28; const balance32 = 32; diff --git a/packages/state-transition/test/utils/beforeValue.ts b/packages/state-transition/test/utils/beforeValue.ts index 6a2f5ee86945..6eaa0846b155 100644 --- a/packages/state-transition/test/utils/beforeValue.ts +++ b/packages/state-transition/test/utils/beforeValue.ts @@ -14,23 +14,21 @@ export type LazyValue = {value: T}; export function beforeValue(fn: () => T | Promise, timeout?: number): LazyValue { let value: T = null as unknown as T; - beforeAll(async function () { + beforeAll(async () => { value = await fn(); }, timeout ?? 300_000); return new Proxy<{value: T}>( {value}, { - get: function (_target, prop) { + get: (_target, prop) => { 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..daac7c915d0c 100644 --- a/packages/state-transition/test/utils/beforeValueMocha.ts +++ b/packages/state-transition/test/utils/beforeValueMocha.ts @@ -20,16 +20,15 @@ export function beforeValue(fn: () => T | Promise, timeout?: number): Lazy return new Proxy<{value: T}>( {value}, { - get: function (_target, prop) { + get: (_target, prop) => { 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/rand.ts b/packages/state-transition/test/utils/rand.ts index 988146ac4bf4..d3dc3af278cc 100644 --- a/packages/state-transition/test/utils/rand.ts +++ b/packages/state-transition/test/utils/rand.ts @@ -3,7 +3,7 @@ * Source https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript */ export function mulberry32(a: number) { - return function () { + return () => { a += 0x6d2b79f5; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); 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/test-utils/src/cli.ts b/packages/test-utils/src/cli.ts index c081a65e03c2..a7b2a248bc7e 100644 --- a/packages/test-utils/src/cli.ts +++ b/packages/test-utils/src/cli.ts @@ -12,7 +12,7 @@ import { // We need to make it easy for the user to pass the args for the CLI // yargs treat `["--preset minimal"] as a single arg, so we need to split it ["--preset", "minimal"] function parseArgs(args: string[]): string[] { - return args.map((a) => a.split(" ")).flat(); + return args.flatMap((a) => a.split(" ")); } type CommandRunOptions = { @@ -28,6 +28,7 @@ export async function runCliCommand( opts: CommandRunOptions = {timeoutMs: 1000} ): Promise { return wrapTimeout( + // biome-ignore lint/suspicious/noAsyncPromiseExecutor: We want to resolve with parser call back not on main promise new Promise(async (resolve, reject) => { try { await cli diff --git a/packages/types/src/phase0/validator.ts b/packages/types/src/phase0/validator.ts index 3c2f72aac509..a6ec0fb18103 100644 --- a/packages/types/src/phase0/validator.ts +++ b/packages/types/src/phase0/validator.ts @@ -1,6 +1,7 @@ import {ByteViews, ContainerNodeStructType, ValueOfFields} from "@chainsafe/ssz"; import * as primitiveSsz from "../primitive/sszTypes.js"; +// biome-ignore lint/suspicious/noShadowRestrictedNames: We explicitly want `Boolean` name to be imported const {Boolean, Bytes32, UintNum64, BLSPubkey, EpochInf} = primitiveSsz; // this is to work with uint32, see https://github.com/ChainSafe/ssz/blob/ssz-v0.15.1/packages/ssz/src/type/uint.ts diff --git a/packages/types/src/primitive/sszTypes.ts b/packages/types/src/primitive/sszTypes.ts index 376e17c3f1b6..0b5156eaf24d 100644 --- a/packages/types/src/primitive/sszTypes.ts +++ b/packages/types/src/primitive/sszTypes.ts @@ -1,6 +1,7 @@ import {ByteVectorType, UintNumberType, UintBigintType, BooleanType} from "@chainsafe/ssz"; import {ExecutionAddressType} from "../utils/executionAddress.js"; +// biome-ignore lint/suspicious/noShadowRestrictedNames: We explicitly want this name for variable export const Boolean = new BooleanType(); export const Byte = new UintNumberType(1); export const Bytes4 = new ByteVectorType(4); 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/types/test/unit/blinded.test.ts b/packages/types/test/unit/blinded.test.ts index 3a4b346d29bf..3d087b610b2d 100644 --- a/packages/types/test/unit/blinded.test.ts +++ b/packages/types/test/unit/blinded.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect} from "vitest"; import {ForkName, isForkExecution} from "@lodestar/params"; import {ssz} from "../../src/index.js"; -describe("blinded data structures", function () { +describe("blinded data structures", () => { it("should have the same number of fields as non-blinded", () => { const blindedTypes = [ {a: "BlindedBeaconBlockBody" as const, b: "BeaconBlockBody" as const}, diff --git a/packages/types/test/unit/phase0/sszTypes.test.ts b/packages/types/test/unit/phase0/sszTypes.test.ts index 0cda0fc888f6..4bdb2031e5ea 100644 --- a/packages/types/test/unit/phase0/sszTypes.test.ts +++ b/packages/types/test/unit/phase0/sszTypes.test.ts @@ -5,7 +5,7 @@ import {ValidatorType} from "../../../src/phase0/validator.js"; const ValidatorContainer = new ContainerType(ValidatorType, {typeName: "Validator", jsonCase: "eth2"}); -describe("Validator ssz types", function () { +describe("Validator ssz types", () => { it("should serialize to the same value", () => { const seedValidator = { activationEligibilityEpoch: 10, diff --git a/packages/types/test/unit/ssz.test.ts b/packages/types/test/unit/ssz.test.ts index b5c972a8f471..41e4e0bbd23b 100644 --- a/packages/types/test/unit/ssz.test.ts +++ b/packages/types/test/unit/ssz.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from "vitest"; import {ssz} from "../../src/index.js"; -describe("size", function () { +describe("size", () => { it("should calculate correct minSize and maxSize", () => { const minSize = ssz.phase0.BeaconState.minSize; const maxSize = ssz.phase0.BeaconState.maxSize; @@ -11,8 +11,8 @@ describe("size", function () { }); }); -describe("container serialization/deserialization field casing(s)", function () { - it("AttesterSlashing", function () { +describe("container serialization/deserialization field casing(s)", () => { + it("AttesterSlashing", () => { const test = { attestation1: ssz.phase0.IndexedAttestation.defaultValue(), attestation2: ssz.phase0.IndexedAttestation.defaultValue(), @@ -27,7 +27,7 @@ describe("container serialization/deserialization field casing(s)", function () expect(back).toEqual(json); }); - it("ProposerSlashing", function () { + it("ProposerSlashing", () => { const test = { signedHeader1: ssz.phase0.SignedBeaconBlockHeader.defaultValue(), signedHeader2: ssz.phase0.SignedBeaconBlockHeader.defaultValue(), diff --git a/packages/types/test/unit/validatorStatus.test.ts b/packages/types/test/unit/validatorStatus.test.ts index 8d04c0f98e3d..b5bd34004bdc 100644 --- a/packages/types/test/unit/validatorStatus.test.ts +++ b/packages/types/test/unit/validatorStatus.test.ts @@ -2,8 +2,8 @@ import {describe, it, expect} from "vitest"; import {getValidatorStatus} from "../../src/utils/validatorStatus.js"; import {phase0} from "../../src/types.js"; -describe("getValidatorStatus", function () { - it("should return PENDING_INITIALIZED", function () { +describe("getValidatorStatus", () => { + it("should return PENDING_INITIALIZED", () => { const validator = { activationEpoch: 1, activationEligibilityEpoch: Infinity, @@ -12,7 +12,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("pending_initialized"); }); - it("should return PENDING_QUEUED", function () { + it("should return PENDING_QUEUED", () => { const validator = { activationEpoch: 1, activationEligibilityEpoch: 101010101101010, @@ -21,7 +21,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("pending_queued"); }); - it("should return ACTIVE_ONGOING", function () { + it("should return ACTIVE_ONGOING", () => { const validator = { activationEpoch: 1, exitEpoch: Infinity, @@ -30,7 +30,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("active_ongoing"); }); - it("should return ACTIVE_SLASHED", function () { + it("should return ACTIVE_SLASHED", () => { const validator = { activationEpoch: 1, exitEpoch: 101010101101010, @@ -40,7 +40,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("active_slashed"); }); - it("should return ACTIVE_EXITING", function () { + it("should return ACTIVE_EXITING", () => { const validator = { activationEpoch: 1, exitEpoch: 101010101101010, @@ -50,7 +50,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("active_exiting"); }); - it("should return EXITED_SLASHED", function () { + it("should return EXITED_SLASHED", () => { const validator = { exitEpoch: 1, withdrawableEpoch: 3, @@ -60,7 +60,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("exited_slashed"); }); - it("should return EXITED_UNSLASHED", function () { + it("should return EXITED_UNSLASHED", () => { const validator = { exitEpoch: 1, withdrawableEpoch: 3, @@ -70,7 +70,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("exited_unslashed"); }); - it("should return WITHDRAWAL_POSSIBLE", function () { + it("should return WITHDRAWAL_POSSIBLE", () => { const validator = { withdrawableEpoch: 1, effectiveBalance: 32, @@ -79,7 +79,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("withdrawal_possible"); }); - it("should return WITHDRAWAL_DONE", function () { + it("should return WITHDRAWAL_DONE", () => { const validator = { withdrawableEpoch: 1, effectiveBalance: 0, @@ -88,7 +88,7 @@ describe("getValidatorStatus", function () { const status = getValidatorStatus(validator, currentEpoch); expect(status).toBe("withdrawal_done"); }); - it("should error", function () { + it("should error", () => { const validator = {} as phase0.Validator; const currentEpoch = 0; try { 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/diff.ts b/packages/utils/src/diff.ts index 4aab18e32779..f7357cde19fa 100644 --- a/packages/utils/src/diff.ts +++ b/packages/utils/src/diff.ts @@ -215,7 +215,7 @@ export function diff(val1: unknown, val2: unknown, outputValues = false, filenam const diffs = getDiffs(val1, val2, ""); let output = ""; if (diffs.length) { - diffs.forEach((diff) => { + for (const diff of diffs) { let diffOutput = `value${diff.objectPath}`; if (diff.errorMessage) { diffOutput += `\n ${diff.errorMessage}`; @@ -224,7 +224,7 @@ export function diff(val1: unknown, val2: unknown, outputValues = false, filenam diffOutput += `\n - ${diff.val1.toString()}\n - ${diff.val2.toString()}\n`; } output += `${diffOutput}\n`; - }); + } if (filename) { fs.writeFileSync(filename, output); } else { diff --git a/packages/utils/src/objects.ts b/packages/utils/src/objects.ts index 913bc80275b7..602e758e360c 100644 --- a/packages/utils/src/objects.ts +++ b/packages/utils/src/objects.ts @@ -18,7 +18,7 @@ export function toExpectedCase( customCasingMap?: Record ): string { if (expectedCase === "notransform") return value; - if (customCasingMap && customCasingMap[value]) return customCasingMap[value]; + if (customCasingMap?.[value]) return customCasingMap[value]; switch (expectedCase) { case "param": return Case.kebab(value); @@ -45,7 +45,7 @@ export function isPlainObject(o: unknown): o is object { if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method - if (prot.hasOwnProperty("isPrototypeOf") === false) { + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } @@ -91,7 +91,7 @@ export function objectToExpectedCase | Record< const newObj: Record = {}; for (const name of Object.getOwnPropertyNames(obj)) { const newName = toExpectedCase(name, expectedCase); - if (newName !== name && obj.hasOwnProperty(newName)) { + if (newName !== name && Object.prototype.hasOwnProperty.call(obj, newName)) { throw new Error(`object already has a ${newName} property`); } 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/src/sleep.ts b/packages/utils/src/sleep.ts index c31a9daffd32..f2ff74255f48 100644 --- a/packages/utils/src/sleep.ts +++ b/packages/utils/src/sleep.ts @@ -10,7 +10,7 @@ export async function sleep(ms: number, signal?: AbortSignal): Promise { } return new Promise((resolve, reject) => { - if (signal && signal.aborted) return reject(new ErrorAborted()); + if (signal?.aborted) return reject(new ErrorAborted()); let onDone: () => void = () => {}; diff --git a/packages/utils/src/url.ts b/packages/utils/src/url.ts index f00b70edbde2..d4eba3bd67cf 100644 --- a/packages/utils/src/url.ts +++ b/packages/utils/src/url.ts @@ -1,5 +1,5 @@ export function isValidHttpUrl(urlStr: string): boolean { - let url; + let url: URL; try { url = new URL(urlStr); diff --git a/packages/utils/src/yaml/int.ts b/packages/utils/src/yaml/int.ts index bc68895cfd42..264d1297f888 100644 --- a/packages/utils/src/yaml/int.ts +++ b/packages/utils/src/yaml/int.ts @@ -27,7 +27,7 @@ function resolveYamlInteger(data: string): boolean { if (data === null) return false; const max = data.length; - let ch, + let ch: string, index = 0, hasDigits = false; @@ -111,7 +111,7 @@ function resolveYamlInteger(data: string): boolean { function constructYamlInteger(data: string): bigint { let value: string | bigint = data, sign = 1, - ch, + ch: string, base: number | bigint; const digits: number[] = []; diff --git a/packages/utils/test/perf/bytes.test.ts b/packages/utils/test/perf/bytes.test.ts index 649ea0b51e3e..6a1e96ab1579 100644 --- a/packages/utils/test/perf/bytes.test.ts +++ b/packages/utils/test/perf/bytes.test.ts @@ -3,7 +3,7 @@ import {toHex, toRootHex} from "../../src/bytes/nodejs.js"; import {toHex as browserToHex, toRootHex as browserToRootHex} from "../../src/bytes/browser.js"; import {toHexString} from "../../src/bytes.js"; -describe("bytes utils", function () { +describe("bytes utils", () => { const runsFactor = 1000; const blockRoot = new Uint8Array(Array.from({length: 32}, (_, i) => i)); diff --git a/packages/utils/test/unit/math.test.ts b/packages/utils/test/unit/math.test.ts index 6827fea2bbb0..e324714600b1 100644 --- a/packages/utils/test/unit/math.test.ts +++ b/packages/utils/test/unit/math.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from "vitest"; import {bigIntMin, bigIntMax, intDiv, intSqrt, bigIntSqrt} from "../../src/index.js"; -describe("util/maths", function () { +describe("util/maths", () => { describe("bigIntMin", () => { it("if a is lt should return a", () => { const a = BigInt(1); diff --git a/packages/utils/test/unit/promise.node.test.ts b/packages/utils/test/unit/promise.node.test.ts index c9f6a3c2f98d..55cbad36b211 100644 --- a/packages/utils/test/unit/promise.node.test.ts +++ b/packages/utils/test/unit/promise.node.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from "vitest"; import {callFnWhenAwait} from "../../src/promise.js"; // TODO: Need to debug why vi.useFakeTimers() is not working for the browsers -describe("callFnWhenAwait util", function () { +describe("callFnWhenAwait util", () => { beforeEach(() => { vi.useFakeTimers(); }); 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/utils/test/unit/sleep.test.ts b/packages/utils/test/unit/sleep.test.ts index a887560836eb..ef632fd34f64 100644 --- a/packages/utils/test/unit/sleep.test.ts +++ b/packages/utils/test/unit/sleep.test.ts @@ -2,13 +2,13 @@ import {describe, it, expect} from "vitest"; import {sleep} from "../../src/sleep.js"; import {ErrorAborted} from "../../src/errors.js"; -describe("sleep", function () { - it("Should resolve timeout", async function () { +describe("sleep", () => { + it("Should resolve timeout", async () => { const controller = new AbortController(); await sleep(0, controller.signal); }); - it("Should abort timeout with signal", async function () { + it("Should abort timeout with signal", async () => { const controller = new AbortController(); setTimeout(() => controller.abort(), 10); @@ -17,7 +17,7 @@ describe("sleep", function () { await expect(sleep(sleepTime, controller.signal)).rejects.toThrow(ErrorAborted); }); - it("Should abort timeout with already aborted signal", async function () { + it("Should abort timeout with already aborted signal", async () => { const controller = new AbortController(); controller.abort(); diff --git a/packages/utils/test/unit/timeout.test.ts b/packages/utils/test/unit/timeout.test.ts index b8844355effb..7b4b1eb883be 100644 --- a/packages/utils/test/unit/timeout.test.ts +++ b/packages/utils/test/unit/timeout.test.ts @@ -2,7 +2,7 @@ import {describe, it, expect, afterEach} from "vitest"; import {withTimeout} from "../../src/timeout.js"; import {ErrorAborted, TimeoutError} from "../../src/errors.js"; -describe("withTimeout", function () { +describe("withTimeout", () => { const data = "DATA"; const shortTimeoutMs = 10; const longTimeoutMs = 5000; @@ -27,19 +27,19 @@ describe("withTimeout", function () { return returnValue; } - it("Should resolve timeout", async function () { + it("Should resolve timeout", async () => { const res = await withTimeout(() => pause(shortTimeoutMs, data), longTimeoutMs); expect(res).toBe(data); }); - it("Should resolve timeout with not triggered signal", async function () { + it("Should resolve timeout with not triggered signal", async () => { const controller = new AbortController(); const res = await withTimeout(() => pause(shortTimeoutMs, data), longTimeoutMs, controller.signal); expect(res).toBe(data); }); - it("Should abort timeout with triggered signal", async function () { + it("Should abort timeout with triggered signal", async () => { const controller = new AbortController(); setTimeout(() => controller.abort(), shortTimeoutMs); @@ -48,11 +48,11 @@ describe("withTimeout", function () { ); }); - it("Should timeout with no signal", async function () { + it("Should timeout with no signal", async () => { await expect(withTimeout(() => pause(longTimeoutMs, data), shortTimeoutMs)).rejects.toThrow(TimeoutError); }); - it("Should timeout with not triggered signal", async function () { + it("Should timeout with not triggered signal", async () => { const controller = new AbortController(); await expect(withTimeout(() => pause(longTimeoutMs, data), shortTimeoutMs, controller.signal)).rejects.toThrow( @@ -60,7 +60,7 @@ describe("withTimeout", function () { ); }); - it("Should abort timeout with already aborted signal", async function () { + it("Should abort timeout with already aborted signal", async () => { const controller = new AbortController(); controller.abort(); diff --git a/packages/validator/src/buckets.ts b/packages/validator/src/buckets.ts index df30370b8810..3313f7b5ae35 100644 --- a/packages/validator/src/buckets.ts +++ b/packages/validator/src/buckets.ts @@ -17,11 +17,11 @@ export enum Bucket { export function getBucketNameByValue(enumValue: T): keyof typeof Bucket { const keys = Object.keys(Bucket).filter((x) => { - if (isNaN(parseInt(x))) { - return Bucket[x as keyof typeof Bucket] == enumValue; - } else { - return false; + if (Number.isNaN(parseInt(x))) { + return Bucket[x as keyof typeof Bucket] === enumValue; } + + 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 c2b18bfd7e09..dfd856b18d13 100644 --- a/packages/validator/src/services/validatorStore.ts +++ b/packages/validator/src/services/validatorStore.ts @@ -247,7 +247,7 @@ export class ValidatorStore { throw Error(`Validator pubkey ${pubkeyHex} not known`); } // This should directly modify data in the map - delete validatorData["feeRecipient"]; + delete validatorData.feeRecipient; } getGraffiti(pubkeyHex: PubkeyHex): string | undefined { @@ -267,14 +267,14 @@ export class ValidatorStore { if (validatorData === undefined) { throw Error(`Validator pubkey ${pubkeyHex} not known`); } - delete validatorData["graffiti"]; + delete validatorData.graffiti; } getBuilderSelectionParams(pubkeyHex: PubkeyHex): {selection: routes.validator.BuilderSelection; boostFactor: bigint} { const selection = - (this.validators.get(pubkeyHex)?.builder || {}).selection ?? this.defaultProposerConfig.builder.selection; + this.validators.get(pubkeyHex)?.builder?.selection ?? this.defaultProposerConfig.builder.selection; - let boostFactor; + let boostFactor: bigint; switch (selection) { case routes.validator.BuilderSelection.Default: // Default value slightly favors local block to improve censorship resistance of Ethereum @@ -284,7 +284,7 @@ export class ValidatorStore { case routes.validator.BuilderSelection.MaxProfit: boostFactor = - (this.validators.get(pubkeyHex)?.builder || {}).boostFactor ?? this.defaultProposerConfig.builder.boostFactor; + this.validators.get(pubkeyHex)?.builder?.boostFactor ?? this.defaultProposerConfig.builder.boostFactor; break; case routes.validator.BuilderSelection.BuilderAlways: @@ -386,7 +386,7 @@ export class ValidatorStore { async addSigner(signer: Signer, valProposerConfig?: ValidatorProposerConfig): Promise { const pubkey = getSignerPubkeyHex(signer); - const proposerConfig = (valProposerConfig?.proposerConfig ?? {})[pubkey]; + const proposerConfig = valProposerConfig?.proposerConfig?.[pubkey]; const builderBoostFactor = proposerConfig?.builder?.boostFactor; if (builderBoostFactor !== undefined && builderBoostFactor > MAX_BUILDER_BOOST_FACTOR) { throw Error(`Invalid builderBoostFactor=${builderBoostFactor} > MAX_BUILDER_BOOST_FACTOR for pubkey=${pubkey}`); @@ -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( @@ -803,7 +802,7 @@ export class ValidatorStore { } const isPostElectra = this.config.getForkSeq(data.slot) >= ForkSeq.electra; - if (!isPostElectra && duty.committeeIndex != data.index) { + if (!isPostElectra && duty.committeeIndex !== data.index) { throw Error( `Inconsistent duties during signing: duty.committeeIndex ${duty.committeeIndex} != att.committeeIndex ${data.index}` ); diff --git a/packages/validator/src/slashingProtection/attestation/index.ts b/packages/validator/src/slashingProtection/attestation/index.ts index 681bdf5f0b13..f0d3a0bca172 100644 --- a/packages/validator/src/slashingProtection/attestation/index.ts +++ b/packages/validator/src/slashingProtection/attestation/index.ts @@ -39,7 +39,7 @@ export class SlashingProtectionAttestationService { async checkAndInsertAttestation(pubKey: BLSPubkey, attestation: SlashingProtectionAttestation): Promise { const safeStatus = await this.checkAttestation(pubKey, attestation); - if (safeStatus != SafeStatus.SAME_DATA) { + if (safeStatus !== SafeStatus.SAME_DATA) { await this.insertAttestation(pubKey, attestation); } @@ -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 bab380f99809..385575e82a0a 100644 --- a/packages/validator/src/slashingProtection/block/index.ts +++ b/packages/validator/src/slashingProtection/block/index.ts @@ -24,7 +24,7 @@ export class SlashingProtectionBlockService { async checkAndInsertBlockProposal(pubkey: BLSPubkey, block: SlashingProtectionBlock): Promise { const safeStatus = await this.checkBlockProposal(pubkey, block); - if (safeStatus != SafeStatus.SAME_DATA) { + if (safeStatus !== SafeStatus.SAME_DATA) { await this.insertBlockProposal(pubkey, block); } @@ -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: diff --git a/packages/validator/src/validator.ts b/packages/validator/src/validator.ts index 6ffebff2b3bd..1d370c35cc33 100644 --- a/packages/validator/src/validator.ts +++ b/packages/validator/src/validator.ts @@ -264,7 +264,7 @@ export class Validator { } ); - return new this({ + return new Validator({ opts, genesis, validatorStore, diff --git a/packages/validator/test/e2e/web3signer.test.ts b/packages/validator/test/e2e/web3signer.test.ts index ae22bc31446b..855b3dd9f754 100644 --- a/packages/validator/test/e2e/web3signer.test.ts +++ b/packages/validator/test/e2e/web3signer.test.ts @@ -12,7 +12,7 @@ import {Interchange, ISlashingProtection, Signer, SignerType, ValidatorStore} fr import {IndicesService} from "../../src/services/indices.js"; import {testLogger} from "../utils/logger.js"; -describe("web3signer signature test", function () { +describe("web3signer signature test", () => { vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000}); const altairSlot = 2375711; @@ -82,7 +82,7 @@ describe("web3signer signature test", function () { }); } - it("signRandao", async function () { + it("signRandao", async () => { await assertSameSignature("signRandao", pubkeyBytes, epoch); }); diff --git a/packages/validator/test/unit/services/attestation.test.ts b/packages/validator/test/unit/services/attestation.test.ts index b225ab09cdd2..1652af83c5d1 100644 --- a/packages/validator/test/unit/services/attestation.test.ts +++ b/packages/validator/test/unit/services/attestation.test.ts @@ -22,7 +22,7 @@ vi.mock("../../../src/services/emitter.js"); vi.mock("../../../src/services/chainHeaderTracker.js"); vi.mock("../../../src/services/syncingStatusTracker.js"); -describe("AttestationService", function () { +describe("AttestationService", () => { const api = getApiClientStub(); // @ts-expect-error - Mocked class don't need parameters const validatorStore = vi.mocked(new ValidatorStore()); diff --git a/packages/validator/test/unit/services/attestationDuties.test.ts b/packages/validator/test/unit/services/attestationDuties.test.ts index f59b00d88c9c..fafccf209777 100644 --- a/packages/validator/test/unit/services/attestationDuties.test.ts +++ b/packages/validator/test/unit/services/attestationDuties.test.ts @@ -18,7 +18,7 @@ import {ZERO_HASH_HEX} from "../../utils/types.js"; vi.mock("../../../src/services/chainHeaderTracker.js"); -describe("AttestationDutiesService", function () { +describe("AttestationDutiesService", () => { const api = getApiClientStub(); let validatorStore: ValidatorStore; @@ -61,7 +61,7 @@ describe("AttestationDutiesService", function () { controller.abort(); }); - it("Should fetch indexes and duties", async function () { + it("Should fetch indexes and duties", async () => { // Reply with some duties const slot = 1; const epoch = computeEpochAtSlot(slot); @@ -118,7 +118,7 @@ describe("AttestationDutiesService", function () { expect(api.validator.prepareBeaconCommitteeSubnet).toHaveBeenCalledOnce(); }); - it("Should remove signer from attestation duties", async function () { + it("Should remove signer from attestation duties", async () => { // Reply with some duties const slot = 1; const duty: routes.validator.AttesterDuty = { @@ -165,7 +165,7 @@ describe("AttestationDutiesService", function () { expect(Object.fromEntries(dutiesService["dutiesByIndexByEpoch"])).toEqual({}); }); - it("Should fetch duties when node is resynced", async function () { + it("Should fetch duties when node is resynced", async () => { // Node is syncing api.node.getSyncingStatus.mockResolvedValue( mockApiResponse({data: {headSlot: 0, syncDistance: 1, isSyncing: true, isOptimistic: false, elOffline: false}}) diff --git a/packages/validator/test/unit/services/block.test.ts b/packages/validator/test/unit/services/block.test.ts index 641ca620a1b5..dc89f1169d92 100644 --- a/packages/validator/test/unit/services/block.test.ts +++ b/packages/validator/test/unit/services/block.test.ts @@ -16,7 +16,7 @@ import {ZERO_HASH_HEX} from "../../utils/types.js"; vi.mock("../../../src/services/validatorStore.js"); -describe("BlockDutiesService", function () { +describe("BlockDutiesService", () => { const api = getApiClientStub(); // @ts-expect-error - Mocked class don't need parameters const validatorStore = vi.mocked(new ValidatorStore()); @@ -36,7 +36,7 @@ describe("BlockDutiesService", function () { }); afterEach(() => controller.abort()); - it("Should produce, sign, and publish a block", async function () { + it("Should produce, sign, and publish a block", async () => { // Reply with some duties const slot = 0; // genesisTime is right now, so test with slot = currentSlot api.validator.getProposerDuties.mockResolvedValue( @@ -111,7 +111,7 @@ describe("BlockDutiesService", function () { ]); }); - it("Should produce, sign, and publish a blinded block", async function () { + it("Should produce, sign, and publish a blinded block", async () => { // Reply with some duties const slot = 0; // genesisTime is right now, so test with slot = currentSlot api.validator.getProposerDuties.mockResolvedValue( diff --git a/packages/validator/test/unit/services/blockDuties.test.ts b/packages/validator/test/unit/services/blockDuties.test.ts index bc4053b704c8..51ced2cd70de 100644 --- a/packages/validator/test/unit/services/blockDuties.test.ts +++ b/packages/validator/test/unit/services/blockDuties.test.ts @@ -13,7 +13,7 @@ import {ClockMock} from "../../utils/clock.js"; import {initValidatorStore} from "../../utils/validatorStore.js"; import {ZERO_HASH_HEX} from "../../utils/types.js"; -describe("BlockDutiesService", function () { +describe("BlockDutiesService", () => { const api = getApiClientStub(); let validatorStore: ValidatorStore; let pubkeys: Uint8Array[]; // Initialize pubkeys in before() so bls is already initialized @@ -30,7 +30,7 @@ describe("BlockDutiesService", function () { }); afterEach(() => controller.abort()); - it("Should fetch and persist block duties", async function () { + it("Should fetch and persist block duties", async () => { // Reply with some duties const slot = 0; // genesisTime is right now, so test with slot = currentSlot const duties: routes.validator.ProposerDutyList = [{slot: slot, validatorIndex: 0, pubkey: pubkeys[0]}]; @@ -106,7 +106,7 @@ describe("BlockDutiesService", function () { expect(notifyBlockProductionFn.mock.calls[1]).toEqual([1, [pubkeys[1]]]); }); - it("Should remove signer from duty", async function () { + it("Should remove signer from duty", async () => { // Reply with some duties const slot = 0; // genesisTime is right now, so test with slot = currentSlot const duties: routes.validator.ProposerDutyList = [ diff --git a/packages/validator/test/unit/services/indicesService.test.ts b/packages/validator/test/unit/services/indicesService.test.ts index 8332bac7cfd6..d4619aa65b94 100644 --- a/packages/validator/test/unit/services/indicesService.test.ts +++ b/packages/validator/test/unit/services/indicesService.test.ts @@ -6,7 +6,7 @@ import {getApiClientStub} from "../../utils/apiStub.js"; import {testLogger} from "../../utils/logger.js"; import {IndicesService} from "../../../src/services/indices.js"; -describe("IndicesService", function () { +describe("IndicesService", () => { const logger = testLogger(); const api = getApiClientStub(); @@ -20,7 +20,7 @@ describe("IndicesService", function () { pubkeys = secretKeys.map((sk) => sk.toPublicKey().toBytes()); }); - it("Should remove pubkey", async function () { + it("Should remove pubkey", async () => { const indicesService = new IndicesService(logger, api, null); const firstValidatorIndex = 0; const secondValidatorIndex = 1; diff --git a/packages/validator/test/unit/services/syncCommitteDuties.test.ts b/packages/validator/test/unit/services/syncCommitteDuties.test.ts index d94926e9b564..27a86d31f901 100644 --- a/packages/validator/test/unit/services/syncCommitteDuties.test.ts +++ b/packages/validator/test/unit/services/syncCommitteDuties.test.ts @@ -20,7 +20,7 @@ import {ClockMock} from "../../utils/clock.js"; import {initValidatorStore} from "../../utils/validatorStore.js"; import {syncCommitteeIndicesToSubnets} from "../../../src/services/utils.js"; -describe("SyncCommitteeDutiesService", function () { +describe("SyncCommitteeDutiesService", () => { const api = getApiClientStub(); let validatorStore: ValidatorStore; @@ -67,7 +67,7 @@ describe("SyncCommitteeDutiesService", function () { controller.abort(); }); - it("Should fetch indexes and duties", async function () { + it("Should fetch indexes and duties", async () => { // Reply with some duties const slot = 1; const duty: routes.validator.SyncDuty = { @@ -127,7 +127,7 @@ describe("SyncCommitteeDutiesService", function () { /** * Reproduce https://github.com/ChainSafe/lodestar/issues/3572 */ - it("should remove redundant duties", async function () { + it("should remove redundant duties", async () => { // Reply with some duties const duty: routes.validator.SyncDuty = { pubkey: pubkeys[0], @@ -195,7 +195,7 @@ describe("SyncCommitteeDutiesService", function () { } as typeof dutiesByIndexByPeriodObj); }); - it("Should remove signer from sync committee duties", async function () { + it("Should remove signer from sync committee duties", async () => { // Reply with some duties const duty1: routes.validator.SyncDuty = { pubkey: pubkeys[0], @@ -264,7 +264,7 @@ describe("SyncCommitteeDutiesService", function () { } as typeof dutiesByIndexByPeriodObjAfterRemoval); }); - it("Should fetch duties when node is resynced", async function () { + it("Should fetch duties when node is resynced", async () => { // Node is syncing api.node.getSyncingStatus.mockResolvedValue( mockApiResponse({data: {headSlot: 0, syncDistance: 1, isSyncing: true, isOptimistic: false, elOffline: false}}) diff --git a/packages/validator/test/unit/services/syncCommittee.test.ts b/packages/validator/test/unit/services/syncCommittee.test.ts index 201bbdc83632..84c7f14d73b1 100644 --- a/packages/validator/test/unit/services/syncCommittee.test.ts +++ b/packages/validator/test/unit/services/syncCommittee.test.ts @@ -21,7 +21,7 @@ vi.mock("../../../src/services/emitter.js"); vi.mock("../../../src/services/chainHeaderTracker.js"); vi.mock("../../../src/services/syncingStatusTracker.js"); -describe("SyncCommitteeService", function () { +describe("SyncCommitteeService", () => { const api = getApiClientStub(); // @ts-expect-error - Mocked class don't need parameters const validatorStore = vi.mocked(new ValidatorStore()); diff --git a/packages/validator/test/unit/services/syncingStatusTracker.test.ts b/packages/validator/test/unit/services/syncingStatusTracker.test.ts index 59029e1b9c51..07364847e345 100644 --- a/packages/validator/test/unit/services/syncingStatusTracker.test.ts +++ b/packages/validator/test/unit/services/syncingStatusTracker.test.ts @@ -4,7 +4,7 @@ import {getMockedLogger} from "../../utils/logger.js"; import {ClockMock} from "../../utils/clock.js"; import {SyncingStatus, SyncingStatusTracker} from "../../../src/services/syncingStatusTracker.js"; -describe("SyncingStatusTracker", function () { +describe("SyncingStatusTracker", () => { const api = getApiClientStub(); const logger = getMockedLogger(); @@ -26,7 +26,7 @@ describe("SyncingStatusTracker", function () { controller.abort(); }); - it("should handle transition from syncing to synced", async function () { + it("should handle transition from syncing to synced", async () => { // Node is syncing const syncing: SyncingStatus = { headSlot: 0, @@ -80,7 +80,7 @@ describe("SyncingStatusTracker", function () { expect(callOnResynced).toHaveBeenCalledOnce(); }); - it("should handle errors when checking syncing status", async function () { + it("should handle errors when checking syncing status", async () => { // Node is offline const error = new Error("ECONNREFUSED"); api.node.getSyncingStatus.mockRejectedValue(error); @@ -92,7 +92,7 @@ describe("SyncingStatusTracker", function () { expect(callOnResynced).not.toHaveBeenCalled(); }); - it("should not call scheduled tasks if already synced", async function () { + it("should not call scheduled tasks if already synced", async () => { // Node is already synced const syncedHead1: SyncingStatus = { headSlot: 1, diff --git a/packages/validator/test/unit/utils/batch.test.ts b/packages/validator/test/unit/utils/batch.test.ts index 821d27c1a43a..455d31e19577 100644 --- a/packages/validator/test/unit/utils/batch.test.ts +++ b/packages/validator/test/unit/utils/batch.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from "vitest"; import {batchItems} from "../../../src/util/index.js"; -describe("util / batch", function () { +describe("util / batch", () => { const testCases: {items: string[]; expected: string[][]}[] = [ {items: [], expected: []}, {items: ["1"], expected: [["1"]]}, diff --git a/packages/validator/test/unit/utils/clock.test.ts b/packages/validator/test/unit/utils/clock.test.ts index f1c12e2cf66d..056260d9e515 100644 --- a/packages/validator/test/unit/utils/clock.test.ts +++ b/packages/validator/test/unit/utils/clock.test.ts @@ -5,7 +5,7 @@ import {BeaconConfig} from "@lodestar/config"; import {Clock, getCurrentSlotAround} from "../../../src/util/clock.js"; import {testLogger} from "../../utils/logger.js"; -describe("util / Clock", function () { +describe("util / Clock", () => { const logger = testLogger(); let controller: AbortController; @@ -80,7 +80,7 @@ describe("util / Clock", function () { expect(onEpoch).toHaveBeenNthCalledWith(2, 1, expect.any(AbortSignal)); }); - describe("getCurrentSlot", function () { + describe("getCurrentSlot", () => { const testConfig = {SECONDS_PER_SLOT: 12} as BeaconConfig; const genesisTime = Math.floor(new Date("2021-01-01").getTime() / 1000); @@ -96,7 +96,7 @@ describe("util / Clock", function () { {name: "should return next slot after 12.5s", delta: 12.5}, ]; - it.each(testCase)("$name", async function ({delta}) { + it.each(testCase)("$name", async ({delta}) => { const currentSlot = getCurrentSlotAround(testConfig, genesisTime); vi.advanceTimersByTime(delta * 1000); expect(getCurrentSlotAround(testConfig, genesisTime)).toBe(currentSlot + 1); diff --git a/packages/validator/test/unit/validatorStore.test.ts b/packages/validator/test/unit/validatorStore.test.ts index 3d8d88ee3e64..b029a33e163a 100644 --- a/packages/validator/test/unit/validatorStore.test.ts +++ b/packages/validator/test/unit/validatorStore.test.ts @@ -11,7 +11,7 @@ import {getApiClientStub} from "../utils/apiStub.js"; import {initValidatorStore} from "../utils/validatorStore.js"; import {ValidatorProposerConfig} from "../../src/services/validatorStore.js"; -describe("ValidatorStore", function () { +describe("ValidatorStore", () => { const api = getApiClientStub(); let validatorStore: ValidatorStore; @@ -48,7 +48,7 @@ describe("ValidatorStore", function () { vi.resetAllMocks(); }); - it("Should validate graffiti,feeRecipient etc. from valProposerConfig and ValidatorStore", async function () { + it("Should validate graffiti,feeRecipient etc. from valProposerConfig and ValidatorStore", async () => { //pubkeys[0] values expect(validatorStore.getGraffiti(toHexString(pubkeys[0]))).toBe( valProposerConfig.proposerConfig[toHexString(pubkeys[0])].graffiti