/
solidityCompiler.ts
368 lines (338 loc) · 11 KB
/
solidityCompiler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// TODO: Handle nodejs only dependencies
import path from "path";
import fs from "fs";
import { exec, spawnSync } from "child_process";
import { StatusCodes } from "http-status-codes";
import semver from "semver";
import { Worker, WorkerOptions } from "worker_threads";
import {
CompilerOutput,
JsonInput,
PathBuffer,
} from "@ethereum-sourcify/lib-sourcify";
import config from "config";
import { logger } from "../../../../common/logger";
require("isomorphic-fetch");
interface RequestInitTimeout extends RequestInit {
timeout?: number;
}
export async function fetchWithTimeout(
resource: string,
options: RequestInitTimeout = {}
) {
const { timeout = 10000 } = options;
const controller = new AbortController();
const id = setTimeout(() => {
logger.warn(`Aborting request ${resource} because of timout ${timeout}`);
controller.abort();
}, timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const solc = require("solc");
const HOST_SOLC_REPO = " https://binaries.soliditylang.org/";
export function findSolcPlatform(): string | false {
if (process.platform === "darwin" && process.arch === "x64") {
return "macosx-amd64";
}
if (process.platform === "linux" && process.arch === "x64") {
return "linux-amd64";
}
if (process.platform === "win32" && process.arch === "x64") {
return "windows-amd64";
}
return false;
}
/**
* Searches for a solc: first for a local executable version, then from HOST_SOLC_REPO
* and then using the getSolcJs function.
* Once the compiler is retrieved, it is used, and the stringified solc output is returned.
*
* @param version the version of solc to be used for compilation
* @param input a JSON object of the standard-json format compatible with solc
* @param log the logger
* @returns stringified solc output
*/
export async function useCompiler(
version: string,
solcJsonInput: JsonInput,
forceEmscripten = false
): Promise<CompilerOutput> {
// For nightly builds, Solidity version is saved as 0.8.17-ci.2022.8.9+commit.6b60524c instead of 0.8.17-nightly.2022.8.9+commit.6b60524c.
// Not possible to retrieve compilers with "-ci.".
if (version.includes("-ci.")) version = version.replace("-ci.", "-nightly.");
const inputStringified = JSON.stringify(solcJsonInput);
let compiled: string | undefined;
const solcPlatform = findSolcPlatform();
let solcPath;
if (solcPlatform && !forceEmscripten) {
solcPath = await getSolcExecutable(solcPlatform, version);
}
let startCompilation: number;
if (solcPath && !forceEmscripten) {
logger.debug(`Compiling with solc binary ${version} at ${solcPath}`);
startCompilation = Date.now();
try {
compiled = await asyncExecSolc(inputStringified, solcPath);
} catch (error: any) {
if (error?.code === "ENOBUFS") {
throw new Error("Compilation output size too large");
}
logger.warn(error.message);
throw error;
}
} else {
const solJson = await getSolcJs(version);
startCompilation = Date.now();
logger.debug(`Compiling with solc-js ${version}`);
if (solJson) {
const coercedVersion =
semver.coerce(new semver.SemVer(version))?.version ?? "";
// Run Worker for solc versions < 0.4.0 for clean compiler context. See https://github.com/ethereum/sourcify/issues/1099
if (semver.lt(coercedVersion, "0.4.0")) {
compiled = await new Promise((resolve, reject) => {
const worker = importWorker(
path.resolve(__dirname, "./compilerWorker.ts"),
{
workerData: { version, inputStringified },
}
);
worker.once("message", (result) => {
resolve(result);
});
worker.once("error", (error) => {
reject(error);
});
});
} else {
compiled = solJson.compile(inputStringified);
}
}
}
const endCompilation = Date.now();
logger.info(`Compilation time : ${endCompilation - startCompilation} ms`);
if (!compiled) {
throw new Error("Compilation failed. No output from the compiler.");
}
const compiledJSON = JSON.parse(compiled);
const errorMessages = compiledJSON?.errors?.filter(
(e: any) => e.severity === "error"
);
if (errorMessages && errorMessages.length > 0) {
const error = new Error(
"Compiler error:\n " + JSON.stringify(errorMessages)
);
logger.error(error.message);
throw error;
}
return compiledJSON;
}
export async function getAllMetadataAndSourcesFromSolcJson(
solcJson: JsonInput,
compilerVersion: string
): Promise<PathBuffer[]> {
if (solcJson.language !== "Solidity")
throw new Error(
"Only Solidity is supported, the json has language: " + solcJson.language
);
const outputSelection = {
"*": {
"*": ["metadata"],
},
};
if (!solcJson.settings) {
solcJson.settings = {
outputSelection: outputSelection,
};
}
solcJson.settings.outputSelection = outputSelection;
const compiled = await useCompiler(compilerVersion, solcJson);
const metadataAndSources: PathBuffer[] = [];
if (!compiled.contracts)
throw new Error("No contracts found in the compiled json output");
for (const contractPath in compiled.contracts) {
for (const contract in compiled.contracts[contractPath]) {
const metadata = compiled.contracts[contractPath][contract].metadata;
const metadataPath = `${contractPath}-metadata.json`;
metadataAndSources.push({
path: metadataPath,
buffer: Buffer.from(metadata),
});
metadataAndSources.push({
path: `${contractPath}`,
buffer: Buffer.from(solcJson.sources[contractPath].content as string),
});
}
}
return metadataAndSources;
}
export async function getSolcExecutable(
platform: string,
version: string
): Promise<string | null> {
const fileName = `solc-${platform}-v${version}`;
const repoPath =
(config.get("solcRepo") as string) || path.join("/tmp", "solc-repo");
const solcPath = path.join(repoPath, fileName);
if (fs.existsSync(solcPath) && validateSolcPath(solcPath)) {
logger.debug(
`Found solc ${version} with platform ${platform} at ${solcPath}`
);
return solcPath;
}
logger.debug(
`Downloading solc ${version} with platform ${platform} at ${solcPath}`
);
const success = await fetchAndSaveSolc(platform, solcPath, version, fileName);
logger.debug(
`Downloaded solc ${version} with platform ${platform} at ${solcPath}`
);
if (success && !validateSolcPath(solcPath)) {
logger.error(`Cannot validate solc ${version}.`);
return null;
}
return success ? solcPath : null;
}
function validateSolcPath(solcPath: string): boolean {
// TODO: Handle nodejs only dependencies
const spawned = spawnSync(solcPath, ["--version"]);
if (spawned.status === 0) {
return true;
}
const error =
spawned?.error?.message ||
spawned.stderr.toString() ||
"Error running solc, are you on the right platoform? (e.g. x64 vs arm)";
logger.warn(error);
return false;
}
/**
* Fetches a solc binary and saves it to the given path.
*
* If platform is "bin", it will download the solc-js binary.
*/
async function fetchAndSaveSolc(
platform: string,
solcPath: string,
version: string,
fileName: string
): Promise<boolean> {
const encodedURIFilename = encodeURIComponent(fileName);
const githubSolcURI = `${HOST_SOLC_REPO}${platform}/${encodedURIFilename}`;
logger.debug(
`Fetching solc ${version} on platform ${platform}: ${githubSolcURI}`
);
let res = await fetchWithTimeout(githubSolcURI);
let status = res.status;
let buffer;
// handle case in which the response is a link to another version
if (status === StatusCodes.OK) {
buffer = await res.arrayBuffer();
const responseText = Buffer.from(buffer).toString();
if (
/^([\w-]+)-v(\d+\.\d+\.\d+)\+commit\.([a-fA-F0-9]+).*$/.test(responseText)
) {
const githubSolcURI = `${HOST_SOLC_REPO}${platform}/${responseText}`;
res = await fetchWithTimeout(githubSolcURI);
status = res.status;
buffer = await res.arrayBuffer();
}
}
if (status === StatusCodes.OK && buffer) {
logger.debug(
`Fetched solc ${version} on platform ${platform}: ${githubSolcURI}`
);
fs.mkdirSync(path.dirname(solcPath), { recursive: true });
try {
fs.unlinkSync(solcPath);
} catch (_e) {
undefined;
}
fs.writeFileSync(solcPath, new DataView(buffer), { mode: 0o755 });
return true;
} else {
logger.warn(`Failed fetching solc ${version}: ${githubSolcURI}`);
}
return false;
}
/**
* Fetches the requested version of the Solidity compiler (soljson).
* First attempts to search locally; if that fails, falls back to downloading it.
*
* @param version the solc version to retrieve: the expected format is
*
* "[v]<major>.<minor>.<patch>+commit.<hash>"
*
* e.g.: "0.6.6+commit.6c089d02"
*
* defaults to "latest"
*
* @param log a logger to track the course of events
*
* @returns the requested solc instance
*/
export async function getSolcJs(version = "latest"): Promise<any> {
// /^\d+\.\d+\.\d+\+commit\.[a-f0-9]{8}$/
version = version.trim();
if (version !== "latest" && !version.startsWith("v")) {
version = "v" + version;
}
const soljsonRepo =
(config.get("solJsonRepo") as string) || path.join("/tmp", "soljson-repo");
const fileName = `soljson-${version}.js`;
const soljsonPath = path.resolve(soljsonRepo, fileName);
if (!fs.existsSync(soljsonPath)) {
if (!(await fetchAndSaveSolc("bin", soljsonPath, version, fileName))) {
return false;
}
}
const solcjsImports = await import(soljsonPath);
return solc.setupMethods(solcjsImports);
}
function asyncExecSolc(
inputStringified: string,
solcPath: string
): Promise<string> {
// check if input is valid JSON. The input is untrusted and potentially cause arbitrary execution.
JSON.parse(inputStringified);
return new Promise((resolve, reject) => {
const child = exec(
`${solcPath} --standard-json`,
{
maxBuffer: 1000 * 1000 * 20,
},
(error, stdout, stderr) => {
if (error) {
reject(error);
} else if (stderr) {
reject(
new Error(`Compiler process returned with errors:\n ${stderr}`)
);
} else {
resolve(stdout);
}
}
);
if (!child.stdin) {
throw new Error("No stdin on child process");
}
// Write input to child process's stdin
child.stdin.write(inputStringified);
child.stdin.end();
});
}
// https://stackoverflow.com/questions/71795469/ts-node-using-worker-thread-cause-cannot-use-import-statement-outside-a-module
function importWorker(path: string, options: WorkerOptions) {
const resolvedPath = require.resolve(path);
return new Worker(resolvedPath, {
...options,
execArgv: /\.ts$/.test(resolvedPath)
? ["--require", "ts-node/register"]
: undefined,
});
}