Skip to content

Commit

Permalink
Enable recommended rule complexity/useLiteralKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
nazarhussain committed Oct 14, 2024
1 parent 655a4d1 commit ff5bb90
Show file tree
Hide file tree
Showing 37 changed files with 87 additions and 71 deletions.
8 changes: 4 additions & 4 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
// We need couple of empty exports to make those files as esm modules
"noUselessEmptyExport": "off",
// We use normal functions for to ease with debugging context
"useArrowFunction": "off",
// This pattern is used a lot earlier in code so disabling this rule
"useLiteralKeys": "off"
"useArrowFunction": "off"
},
"correctness": {
"noUnusedVariables": "error",
Expand Down Expand Up @@ -350,7 +348,9 @@
"linter": {
"rules": {
"complexity": {
"useArrowFunction": "off"
"useArrowFunction": "off",
// During tests we often need to use private/protected attributes, which is only possible with literal keys
"useLiteralKeys": "off"
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions packages/beacon-node/src/api/impl/lodestar/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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())};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/chain/lightClient/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function deleteRootIndex(
signedBeaconBlockType: SSZTypesFor<ForkAll, "SignedBeaconBlock">,
block: SignedBeaconBlock
): Promise<void> {
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)));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down
6 changes: 6 additions & 0 deletions packages/beacon-node/src/network/core/networkCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -277,6 +278,7 @@ export class NetworkCore implements INetworkCore {
async scrapeMetrics(): Promise<string> {
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)
Expand Down Expand Up @@ -344,6 +346,7 @@ export class NetworkCore implements INetworkCore {
// REST API queries

async getNetworkIdentity(): Promise<routes.node.NetworkIdentity> {
// 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,
Expand Down Expand Up @@ -410,6 +413,7 @@ export class NetworkCore implements INetworkCore {
}

async dumpDiscv5KadValues(): Promise<string[]> {
// biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute
return (await this.peerManager["discovery"]?.discv5?.kadValues())?.map((enr) => enr.encodeTxt()) ?? [];
}

Expand All @@ -426,6 +430,7 @@ export class NetworkCore implements INetworkCore {
}

async writeDiscv5Profile(durationMs: number, dirpath: string): Promise<string> {
// biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute
return this.peerManager["discovery"]?.discv5.writeProfile(durationMs, dirpath) ?? "no discv5";
}

Expand All @@ -434,6 +439,7 @@ export class NetworkCore implements INetworkCore {
}

writeDiscv5HeapSnapshot(prefix: string, dirpath: string): Promise<string> {
// biome-ignore lint/complexity/useLiteralKeys: `discovery` is a private attribute
return this.peerManager["discovery"]?.discv5.writeHeapSnapshot(prefix, dirpath) ?? Promise.resolve("no discv5");
}

Expand Down
7 changes: 4 additions & 3 deletions packages/beacon-node/src/network/gossip/gossipsub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Set<string>>;
const peers = this["peers"];
const score = this["score"];
const peers = this.peers;
const score = this.score;
const meshPeersByClient = new Map<string, number>();
const meshPeerIdStrs = new Set<string>();

Expand Down
1 change: 1 addition & 0 deletions packages/beacon-node/src/network/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export function prettyPrintPeerIdStr(id: PeerIdStr): string {
*/
// Compat function for efficiency reasons
export function getConnectionsMap(libp2p: Libp2p): Map<string, {key: PeerId; value: Connection[]}> {
// biome-ignore lint/complexity/useLiteralKeys: `map` is a private attribute
return libp2p.services.components.connectionManager.getConnectionsMap()["map"];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const sync: TestRunnerFn<SyncTestCase, void> = (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))}`);

Expand Down
1 change: 1 addition & 0 deletions packages/beacon-node/test/spec/utils/runValidSszTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export function runValidSszTest(type: Type<unknown>, 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<unknown, unknown, unknown>)["getRoots"](testDataValue);
console.log(
"ROOTS Composite",
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/cmds/beacon/initPeerIdAndEnr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cmds/dev/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@ const externalOptionsOverrides: Partial<Record<"network" | keyof typeof beaconNo
default: true,
},
eth1: {
...beaconNodeOptions["eth1"],
...beaconNodeOptions.eth1,
defaultDescription: undefined,
default: false,
},
rest: {
...beaconNodeOptions["rest"],
...beaconNodeOptions.rest,
defaultDescription: undefined,
default: true,
},
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/src/cmds/validator/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export async function validatorHandler(args: IValidatorCliArgs & GlobalArgs): Pr
// Create metrics registry if metrics are enabled or monitoring endpoint is configured
// Send version and network data for static registries

const register = args["metrics"] || args["monitoring.endpoint"] ? new RegistryMetricCreator() : null;
const register = args.metrics || args["monitoring.endpoint"] ? new RegistryMetricCreator() : null;
const metrics = register && getMetrics(register, {version, commit, network});

// Start metrics server if metrics are enabled.
Expand All @@ -117,7 +117,7 @@ export async function validatorHandler(args: IValidatorCliArgs & GlobalArgs): Pr
onGracefulShutdownCbs.push(() => 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});
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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"]),
},
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cmds/validator/signers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ 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,
});
Expand Down Expand Up @@ -131,7 +131,7 @@ export async function getSignersFromArgs(
ignoreLockFile: args.force,
onDecrypt: needle,
cacheFilePath: path.join(accountPaths.cacheDir, "local_keystores.cache"),
disableThreadPool: args["disableKeystoresThreadPool"],
disableThreadPool: args.disableKeystoresThreadPool,
logger,
signal,
});
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/cmds/validator/signers/logSigners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Logger, LogLevel.warn>): 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"
);
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/options/beaconNodeOptions/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/options/beaconNodeOptions/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/options/beaconNodeOptions/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand All @@ -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,
Expand Down
8 changes: 3 additions & 5 deletions packages/cli/src/options/beaconNodeOptions/eth1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,12 @@ export function parseArgs(args: Eth1Args & Partial<ExecutionEngineArgs>): 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,
Expand Down
6 changes: 2 additions & 4 deletions packages/cli/src/options/beaconNodeOptions/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/options/beaconNodeOptions/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
};
Expand Down
14 changes: 7 additions & 7 deletions packages/cli/src/options/beaconNodeOptions/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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"],
Expand All @@ -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"],
Expand Down
Loading

0 comments on commit ff5bb90

Please sign in to comment.