Skip to content

Commit

Permalink
Restrict import destructuring for some modules (#5203)
Browse files Browse the repository at this point in the history
* Restrict import destructuring for some modules

* Refactor eslint restricted node module imports
  • Loading branch information
nflaig authored Feb 28, 2023
1 parent d5c08e3 commit f10a95f
Show file tree
Hide file tree
Showing 23 changed files with 133 additions and 113 deletions.
34 changes: 24 additions & 10 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,19 +146,22 @@ module.exports = {
{
patterns: ["../lib/*", "@chainsafe/*/lib/*"],
paths: [
{name: "child_process", message: "Please use node:child_process instead."},
{name: "crypto", message: "Please use node:crypto instead."},
{name: "fs", message: "Please use node:fs instead."},
{name: "http", message: "Please use node:http instead."},
{name: "net", message: "Please use node:net instead."},
{name: "os", message: "Please use node:os instead."},
{name: "path", message: "Please use node:path instead."},
{name: "stream", message: "Please use node:stream instead."},
{name: "util", message: "Please use node:util instead."},
{name: "url", message: "Please use node:url instead."},
...restrictNodeModuleImports(
"child_process",
"crypto",
"fs",
"http",
"net",
"os",
"path",
"stream",
"util",
"url"
),
],
},
],
"no-restricted-syntax": ["error", ...restrictImportDestructuring("node:fs", "node:os", "node:path")],
// Force to add names to all functions to ease CPU profiling
"func-names": ["error", "always"],

Expand Down Expand Up @@ -241,3 +244,14 @@ module.exports = {
},
],
};

function restrictNodeModuleImports(...modules) {
return modules.map((module) => ({name: module, message: `Please use 'node:${module}' instead.`}));
}

function restrictImportDestructuring(...modules) {
return modules.map((module) => ({
selector: `ImportDeclaration[source.value='${module}'] ImportSpecifier`,
message: `Importing from '${module}' using destructuring is restricted.`,
}));
}
4 changes: 2 additions & 2 deletions packages/beacon-node/src/network/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {networkInterfaces} from "node:os";
import os from "node:os";
import type {PeerId} from "@libp2p/interface-peer-id";
import type {Multiaddr} from "@multiformats/multiaddr";
import type {Connection} from "@libp2p/interface-connection";
Expand All @@ -22,7 +22,7 @@ export function isLocalMultiAddr(multiaddr: Multiaddr | undefined): boolean {
throw new Error("Invalid udp multiaddr");
}

const interfaces = networkInterfaces();
const interfaces = os.networkInterfaces();
const tuples = multiaddr.tuples();
const family = tuples[0][0];
const isIPv4: boolean = family === 4;
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/test/unit/sync/backfill/verify.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {readFileSync} from "node:fs";
import fs from "node:fs";
import path from "node:path";
import {fileURLToPath} from "node:url";
import {expect} from "chai";
Expand Down Expand Up @@ -50,7 +50,7 @@ describe("backfill sync - verify block sequence", function () {

//first 4 mainnet blocks
function getBlocks(): phase0.SignedBeaconBlock[] {
const json = JSON.parse(readFileSync(path.join(__dirname, "./blocks.json"), "utf-8")) as unknown[];
const json = JSON.parse(fs.readFileSync(path.join(__dirname, "./blocks.json"), "utf-8")) as unknown[];
return json.map((b) => {
return ssz.phase0.SignedBeaconBlock.fromJson(b);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cmds/validator/keymanager/keystoreCache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from "node:fs";
import {dirname} from "node:path";
import path from "node:path";
import bls from "@chainsafe/bls";
import {Keystore} from "@chainsafe/bls-keystore";
import {SignerLocal, SignerType} from "@lodestar/validator";
Expand Down Expand Up @@ -77,7 +77,7 @@ export async function writeKeystoreCache(
const secretKeyConcatenatedBytes = Buffer.concat(secretKeys);
const publicConcatenatedBytes = Buffer.concat(publicKeys);
const keystore = await Keystore.create(password, secretKeyConcatenatedBytes, publicConcatenatedBytes, cacheFilepath);
if (!fs.existsSync(dirname(cacheFilepath))) fs.mkdirSync(dirname(cacheFilepath), {recursive: true});
if (!fs.existsSync(path.dirname(cacheFilepath))) fs.mkdirSync(path.dirname(cacheFilepath), {recursive: true});
lockFilepath(cacheFilepath);
fs.writeFileSync(cacheFilepath, keystore.stringify());
unlockFilepath(cacheFilepath);
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/cmds/validator/signers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {join} from "node:path";
import path from "node:path";
import bls from "@chainsafe/bls";
import {deriveEth2ValidatorKeys, deriveKeyFromMnemonic} from "@chainsafe/bls-keygen";
import {interopSecretKey} from "@lodestar/state-transition";
Expand Down Expand Up @@ -97,7 +97,7 @@ export async function getSignersFromArgs(
return decryptKeystoreDefinitions(keystoreDefinitions, {
...args,
onDecrypt: needle,
cacheFilePath: join(accountPaths.cacheDir, "imported_keystores.cache"),
cacheFilePath: path.join(accountPaths.cacheDir, "imported_keystores.cache"),
});
}

Expand Down Expand Up @@ -129,7 +129,7 @@ export async function getSignersFromArgs(
const keystoreSigners = await decryptKeystoreDefinitions(keystoreDefinitions, {
...args,
onDecrypt: needle,
cacheFilePath: join(accountPaths.cacheDir, "local_keystores.cache"),
cacheFilePath: path.join(accountPaths.cacheDir, "local_keystores.cache"),
});

// Read local remote keys, imported via keymanager api
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/util/file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fs, {WriteFileOptions} from "node:fs";
import fs from "node:fs";
import path from "node:path";
import stream from "node:stream";
import {promisify} from "node:util";
Expand Down Expand Up @@ -67,7 +67,7 @@ export function stringify(obj: unknown, fileFormat: FileFormat): string {
*
* Serialize either to json, yaml, or toml
*/
export function writeFile(filepath: string, obj: unknown, options: WriteFileOptions = "utf-8"): void {
export function writeFile(filepath: string, obj: unknown, options: fs.WriteFileOptions = "utf-8"): void {
mkdir(path.dirname(filepath));
const fileFormat = path.extname(filepath).substr(1);
fs.writeFileSync(filepath, typeof obj === "string" ? obj : stringify(obj, fileFormat as FileFormat), options);
Expand All @@ -78,7 +78,7 @@ export function writeFile(filepath: string, obj: unknown, options: WriteFileOpti
* *Note*: 600: Owner has full read and write access to the file,
* while no other user can access the file
*/
export function writeFile600Perm(filepath: string, obj: unknown, options?: WriteFileOptions): void {
export function writeFile600Perm(filepath: string, obj: unknown, options?: fs.WriteFileOptions): void {
writeFile(filepath, obj, options);
fs.chmodSync(filepath, "0600");
}
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/backup_eth_provider.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {join} from "node:path";
import path from "node:path";
import {activePreset} from "@lodestar/params";
import {nodeAssertion} from "../utils/simulation/assertions/nodeAssertion.js";
import {CLIQUE_SEALING_PERIOD, SIM_TESTS_SECONDS_PER_SLOT} from "../utils/simulation/constants.js";
Expand Down Expand Up @@ -41,7 +41,7 @@ const ttd = getEstimatedTTD({
const env = await SimulationEnvironment.initWithDefaults(
{
id: "backup-eth-provider",
logsDir: join(logFilesDir, "backup-eth-provider"),
logsDir: path.join(logFilesDir, "backup-eth-provider"),
chainConfig: {
ALTAIR_FORK_EPOCH: altairForkEpoch,
BELLATRIX_FORK_EPOCH: bellatrixForkEpoch,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/deneb.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {join} from "node:path";
import path from "node:path";
import {activePreset} from "@lodestar/params";
import {toHexString} from "@lodestar/utils";
import {ApiError} from "@lodestar/api";
Expand Down Expand Up @@ -38,7 +38,7 @@ const ttd = getEstimatedTTD({
const env = await SimulationEnvironment.initWithDefaults(
{
id: "multi-fork",
logsDir: join(logFilesDir, "multi-fork"),
logsDir: path.join(logFilesDir, "multi-fork"),
chainConfig: {
ALTAIR_FORK_EPOCH: altairForkEpoch,
BELLATRIX_FORK_EPOCH: bellatrixForkEpoch,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/endpoints.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {join} from "node:path";
import path from "node:path";
import {expect} from "chai";
import {toHexString} from "@chainsafe/ssz";
import {routes} from "@lodestar/api";
Expand All @@ -26,7 +26,7 @@ const runTimeoutMs =
const env = await SimulationEnvironment.initWithDefaults(
{
id: "beacon-endpoints",
logsDir: join(logFilesDir, "beacon-endpoints"),
logsDir: path.join(logFilesDir, "beacon-endpoints"),
chainConfig: {
ALTAIR_FORK_EPOCH: altairForkEpoch,
BELLATRIX_FORK_EPOCH: bellatrixForkEpoch,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/multi_fork.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {join} from "node:path";
import path from "node:path";
import {activePreset} from "@lodestar/params";
import {sleep, toHexString} from "@lodestar/utils";
import {ApiError} from "@lodestar/api";
Expand Down Expand Up @@ -45,7 +45,7 @@ const ttd = getEstimatedTTD({
const env = await SimulationEnvironment.initWithDefaults(
{
id: "multi-fork",
logsDir: join(logFilesDir, "multi-fork"),
logsDir: path.join(logFilesDir, "multi-fork"),
chainConfig: {
ALTAIR_FORK_EPOCH: altairForkEpoch,
BELLATRIX_FORK_EPOCH: bellatrixForkEpoch,
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/test/utils/simulation/SimulationEnvironment.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {EventEmitter} from "node:events";
import {mkdir, writeFile} from "node:fs/promises";
import {join} from "node:path";
import {existsSync} from "node:fs";
import path from "node:path";
import fs from "node:fs";
import tmp from "tmp";
import {fromHexString} from "@chainsafe/ssz";
import {nodeUtils} from "@lodestar/beacon-node";
Expand Down Expand Up @@ -122,7 +122,7 @@ export class SimulationEnvironment {
id,
genesisTime,
controller: new AbortController(),
rootDir: join(tmp.dirSync({unsafeCleanup: true, tmpdir: "/tmp", template: "sim-XXXXXX"}).name, id),
rootDir: path.join(tmp.dirSync({unsafeCleanup: true, tmpdir: "/tmp", template: "sim-XXXXXX"}).name, id),
});

for (const client of clients) {
Expand Down Expand Up @@ -158,7 +158,7 @@ export class SimulationEnvironment {

try {
regsiterProcessHandler(this);
if (!existsSync(this.options.rootDir)) {
if (!fs.existsSync(this.options.rootDir)) {
await mkdir(this.options.rootDir);
}

Expand Down
10 changes: 5 additions & 5 deletions packages/cli/test/utils/simulation/cl_clients/lighthouse.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {writeFile} from "node:fs/promises";
import {dirname, join} from "node:path";
import path from "node:path";
import got, {RequestError} from "got";
import yaml from "js-yaml";
import {HttpClient} from "@lodestar/api";
Expand Down Expand Up @@ -80,8 +80,8 @@ export const generateLighthouseBeaconNode: CLClientGenerator<CLClient.Lighthouse
}
: undefined,
bootstrap: async () => {
await writeFile(join(rootDir, "config.yaml"), yaml.dump(chainConfigToJson(config)));
await writeFile(join(rootDir, "deploy_block.txt"), "0");
await writeFile(path.join(rootDir, "config.yaml"), yaml.dump(chainConfigToJson(config)));
await writeFile(path.join(rootDir, "deploy_block.txt"), "0");
},
cli: {
command: isDocker ? "lighthouse" : (process.env.LIGHTHOUSE_BINARY_PATH as string),
Expand Down Expand Up @@ -118,7 +118,7 @@ export const generateLighthouseBeaconNode: CLClientGenerator<CLClient.Lighthouse
id: `${id}-validator`,
paths: {
...opts.paths,
logFilePath: join(dirname(logFilePath), `${id}-validator.log`),
logFilePath: path.join(path.dirname(logFilePath), `${id}-validator.log`),
},
},
runner
Expand Down Expand Up @@ -193,7 +193,7 @@ export const generateLighthouseValidatorJobs = (opts: CLClientGeneratorOptions,
if (isDocker) {
await updateKeystoresPath(
validatorsDefinitionFilePath,
dirname(validatorsDefinitionFilePathMounted),
path.dirname(validatorsDefinitionFilePathMounted),
validatorsDefinitionFilePath
);
}
Expand Down
20 changes: 13 additions & 7 deletions packages/cli/test/utils/simulation/cl_clients/lodestar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {writeFile} from "node:fs/promises";
import {dirname, join} from "node:path";
import path from "node:path";
import got from "got";
import {getClient} from "@lodestar/api/beacon";
import {getClient as keyManagerGetClient} from "@lodestar/api/keymanager";
Expand All @@ -20,8 +20,8 @@ export const generateLodestarBeaconNode: CLClientGenerator<CLClient.Lodestar> =
} = opts;
const ports = getNodePorts(nodeIndex);

const rcConfigPath = join(rootDir, "rc_config.json");
const paramsPath = join(rootDir, "params.json");
const rcConfigPath = path.join(rootDir, "rc_config.json");
const paramsPath = path.join(rootDir, "params.json");

const rcConfig = ({
network: "dev",
Expand Down Expand Up @@ -69,7 +69,7 @@ export const generateLodestarBeaconNode: CLClientGenerator<CLClient.Lodestar> =
id: `${id}-validator`,
paths: {
...opts.paths,
logFilePath: join(dirname(logFilePath), `${id}-validator.log`),
logFilePath: path.join(path.dirname(logFilePath), `${id}-validator.log`),
},
})
);
Expand Down Expand Up @@ -146,12 +146,18 @@ export const generateLodestarValidatorJobs = (opts: CLClientGeneratorOptions): J
id,
type: RunnerType.ChildProcess,
bootstrap: async () => {
await writeFile(join(rootDir, "rc_config.json"), JSON.stringify(rcConfig, null, 2));
await writeFile(join(rootDir, "params.json"), JSON.stringify(chainConfigToJson(config), null, 2));
await writeFile(path.join(rootDir, "rc_config.json"), JSON.stringify(rcConfig, null, 2));
await writeFile(path.join(rootDir, "params.json"), JSON.stringify(chainConfigToJson(config), null, 2));
},
cli: {
command: LODESTAR_BINARY_PATH,
args: ["validator", "--rcConfig", join(rootDir, "rc_config.json"), "--paramsFile", join(rootDir, "params.json")],
args: [
"validator",
"--rcConfig",
path.join(rootDir, "rc_config.json"),
"--paramsFile",
path.join(rootDir, "params.json"),
],
env: {
DEBUG: process.env.DISABLE_DEBUG_LOGS ? "" : "*,-winston:*",
},
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/utils/simulation/constants.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Global variable __dirname no longer available in ES6 modules.
// Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
// eslint-disable-next-line @typescript-eslint/naming-convention
export const __dirname = dirname(fileURLToPath(import.meta.url));
export const __dirname = path.dirname(fileURLToPath(import.meta.url));

import {dirname} from "node:path";
import path from "node:path";
import {fileURLToPath} from "node:url";

export const FAR_FUTURE_EPOCH = 10 ** 12;
Expand Down
10 changes: 5 additions & 5 deletions packages/cli/test/utils/simulation/el_clients/geth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {writeFile} from "node:fs/promises";
import {join} from "node:path";
import path from "node:path";
import got from "got";
import {ZERO_HASH} from "@lodestar/state-transition";
import {SHARED_JWT_SECRET, SIM_ENV_NETWORK_ID} from "../constants.js";
Expand Down Expand Up @@ -33,10 +33,10 @@ export const generateGethNode: ELClientGenerator<ELClient.Geth> = (opts, runner)
const ethRpcUrl = `http://127.0.0.1:${httpPort}`;
const engineRpcUrl = `http://${address}:${enginePort}`;

const skPath = join(rootDir, "sk.json");
const skPathMounted = join(rootDirMounted, "sk.json");
const passwordPath = join(rootDir, "password.txt");
const passwordPathMounted = join(rootDirMounted, "password.txt");
const skPath = path.join(rootDir, "sk.json");
const skPathMounted = path.join(rootDirMounted, "sk.json");
const passwordPath = path.join(rootDir, "password.txt");
const passwordPathMounted = path.join(rootDirMounted, "password.txt");

const initJobOptions: JobOptions = {
id: `${id}-init`,
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/test/utils/simulation/el_clients/nethermind.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {writeFile} from "node:fs/promises";
import {join} from "node:path";
import path from "node:path";
import got from "got";
import {ZERO_HASH} from "@lodestar/state-transition";
import {Eth1ProviderWithAdmin} from "../Eth1ProviderWithAdmin.js";
Expand Down Expand Up @@ -31,8 +31,8 @@ export const generateNethermindNode: ELClientGenerator<ELClient.Nethermind> = (o
const ethRpcUrl = `http://127.0.0.1:${httpPort}`;
const engineRpcUrl = `http://${address}:${enginePort}`;

const chainSpecPath = join(rootDir, "chain.json");
const chainSpecContainerPath = join(rootDirMounted, "chain.json");
const chainSpecPath = path.join(rootDir, "chain.json");
const chainSpecContainerPath = path.join(rootDirMounted, "chain.json");

const startJobOptions: JobOptions<RunnerType.Docker> = {
id,
Expand Down Expand Up @@ -69,7 +69,7 @@ export const generateNethermindNode: ELClientGenerator<ELClient.Nethermind> = (o
"--JsonRpc.EnabledModules",
"Admin,Net,Eth,Subscribe,Web3",
"--Init.BaseDbPath",
join(rootDirMounted, "db"),
path.join(rootDirMounted, "db"),
"--Init.DiscoveryEnabled",
"false",
"--Init.PeerManagerEnabled",
Expand Down
Loading

0 comments on commit f10a95f

Please sign in to comment.