Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core] Config validation #285

Merged
merged 2 commits into from
Jun 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/buidler-core/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/buidler-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"find-up": "^2.1.0",
"fs-extra": "^7.0.1",
"glob": "^7.1.3",
"io-ts": "^1.8.6",
"lodash": "^4.17.11",
"mocha": "^5.2.0",
"semver": "^5.6.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import * as path from "path";

import { ResolvedBuidlerConfig } from "../../../types";
import { BuidlerContext } from "../../context";
import { BuidlerError, ERRORS } from "../errors";
import { loadPluginFile } from "../plugins";
import { getUserConfigPath } from "../project-structure";

import { resolveConfig } from "./config-resolution";
import { validateConfig } from "./config-validation";

function importCsjOrEsModule(filePath: string): any {
const imported = require(filePath);
Expand Down Expand Up @@ -52,6 +54,8 @@ export function loadConfigAndTasks(configPath?: string): ResolvedBuidlerConfig {
const defaultConfig = importCsjOrEsModule("./default-config");
const userConfig = importCsjOrEsModule(configPath);

validateConfig(userConfig);

// To avoid bad practices we remove the previously exported stuff
Object.keys(configEnv).forEach(key => (globalAsAny[key] = undefined));

Expand Down
255 changes: 255 additions & 0 deletions packages/buidler-core/src/internal/core/config/config-validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
import * as t from "io-ts";
import { Context, getFunctionName, ValidationError } from "io-ts/lib";
import { Reporter } from "io-ts/lib/Reporter";
import { error } from "util";

import { BuidlerError, ERRORS } from "../errors";

function stringify(v: any): string {
if (typeof v === "function") {
return getFunctionName(v);
}
if (typeof v === "number" && !isFinite(v)) {
if (isNaN(v)) {
return "NaN";
}
return v > 0 ? "Infinity" : "-Infinity";
}
return JSON.stringify(v);
}

function getContextPath(context: Context): string {
return (
context[0].type.name +
"." +
context
.slice(1)
.map(c => c.key)
.join(".")
);
}

function getMessage(e: ValidationError): string {
const lastContext = e.context[e.context.length - 1];

return e.message !== undefined
? e.message
: getErrorMessage(
getContextPath(e.context),
e.value,
lastContext.type.name
);
}

function getErrorMessage(path: string, value: any, expectedType: string) {
return `Invalid value ${stringify(
value
)} for ${path} - Expected a value of type ${expectedType}.`;
}

export function failure(es: ValidationError[]): string[] {
return es.map(getMessage);
}

export function success(): string[] {
return [];
}

export const DotPathReporter: Reporter<string[]> = {
report: validation => validation.fold(failure, success)
};

function optional<TypeT, OutputT>(
codec: t.Type<TypeT, OutputT, unknown>,
name: string = `${codec.name} | undefined`
): t.Type<TypeT | undefined, OutputT | undefined, unknown> {
return new t.Type(
name,
(u: unknown): u is TypeT | undefined => u === undefined || codec.is(u),
(u, c) => (u === undefined ? t.success(u) : codec.validate(u, c)),
a => (a === undefined ? a : codec.encode(a))
);
}

// IMPORTANT: This t.types MUST be kept in sync with the actual types.

const AutoNetworkAccount = t.type({
privateKey: t.string,
balance: t.string
});

const AutoNetworkConfig = t.type({
chainId: optional(t.number),
from: optional(t.string),
gas: optional(t.union([t.literal("auto"), t.number])),
gasPrice: optional(t.union([t.literal("auto"), t.number])),
gasMultiplier: optional(t.number),
accounts: optional(t.array(AutoNetworkAccount)),
blockGasLimit: optional(t.number)
});

const HDAccountsConfig = t.type({
mnemonic: t.string,
initialIndex: optional(t.number),
count: optional(t.number),
path: optional(t.string)
});

const OtherAccountsConfig = t.type({
type: t.string
});

const NetworkConfigAccounts = t.union([
t.literal("remote"),
t.array(t.string),
HDAccountsConfig,
OtherAccountsConfig
]);

const HttpNetworkConfig = t.type({
chainId: optional(t.number),
from: optional(t.string),
gas: optional(t.union([t.literal("auto"), t.number])),
gasPrice: optional(t.union([t.literal("auto"), t.number])),
gasMultiplier: optional(t.number),
url: optional(t.string),
accounts: optional(NetworkConfigAccounts)
});

const NetworkConfig = t.union([AutoNetworkConfig, HttpNetworkConfig]);

const Networks = t.record(t.string, NetworkConfig);

const ProjectPaths = t.type({
root: optional(t.string),
cache: optional(t.string),
artifacts: optional(t.string),
sources: optional(t.string),
tests: optional(t.string)
});

const EVMVersion = t.string;

const SolcOptimizerConfig = t.type({
enabled: optional(t.boolean),
runs: optional(t.number)
});

const SolcConfig = t.type({
version: optional(t.string),
optimizer: optional(SolcOptimizerConfig),
evmVersion: optional(EVMVersion)
});

const BuidlerConfig = t.type(
{
networks: optional(Networks),
paths: optional(ProjectPaths),
solc: optional(SolcConfig)
},
"BuidlerConfig"
);

/**
* Validates the config, throwing a BuidlerError if invalid.
* @param config
*/
export function validateConfig(config: any) {
const errors = getValidationErrors(config);

if (errors.length === 0) {
return;
}

const errorList = " * " + errors.join("\n * ");

throw new BuidlerError(ERRORS.GENERAL.INVALID_CONFIG, errorList);
}

export function getValidationErrors(config: any): string[] {
const errors = [];

// These can't be validated with io-ts
if (config !== undefined && typeof config.networks === "object") {
const autoNetwork = config.networks.auto;
if (autoNetwork !== undefined) {
if (autoNetwork.url !== undefined) {
errors.push("BuidlerConfig.networks.auto can't have an url");
}

if (
autoNetwork.blockGasLimit !== undefined &&
typeof autoNetwork.blockGasLimit !== "number"
) {
errors.push(
getErrorMessage(
"BuidlerConfig.networks.auto.blockGasLimit",
autoNetwork.blockGasLimit,
"number | undefined"
)
);
}

if (autoNetwork.accounts !== undefined) {
if (Array.isArray(autoNetwork.accounts)) {
for (const account of autoNetwork.accounts) {
if (typeof account.privateKey !== "string") {
errors.push(
getErrorMessage(
"BuidlerConfig.networks.auto.accounts[].privateKey",
account.privateKey,
"string"
)
);
}

if (typeof account.balance !== "string") {
errors.push(
getErrorMessage(
"BuidlerConfig.networks.auto.accounts[].balance",
account.balance,
"string"
)
);
}
}
} else {
errors.push(
getErrorMessage(
"BuidlerConfig.networks.auto.accounts",
autoNetwork.accounts,
"[{privateKey: string, balance: string}] | undefined"
)
);
}
}
}

for (const [networkName, netConfig] of Object.entries<any>(
config.networks
)) {
if (networkName === "auto") {
continue;
}

if (netConfig.url !== undefined && typeof netConfig.url !== "string") {
errors.push(
getErrorMessage(
`BuidlerConfig.networks.${networkName}.url`,
netConfig.url,
"string | undefined"
)
);
}
}
}

const result = BuidlerConfig.decode(config);

if (result.isRight()) {
return errors;
}

const ioTsErrors = DotPathReporter.report(result);
return [...errors, ...ioTsErrors];
}
8 changes: 8 additions & 0 deletions packages/buidler-core/src/internal/core/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ export const ERRORS = {
CONTEXT_BRE_ALREADY_DEFINED: {
number: 7,
message: "BuidlerRuntime is already defined in the BuidlerContext"
},
INVALID_CONFIG: {
number: 8,
message: `There's one or more errors in your config file:

%s

To learn more about Buidler's configuration, please go to https://buidler.dev/documentation/#configuration`
}
},
NETWORK: {
Expand Down
Loading