-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.js
executable file
·356 lines (324 loc) · 11.1 KB
/
cli.js
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
#!/usr/bin/env node
const { build, auto_detect } = require('./builder');
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const fs = require('fs');
const { table } = require('table');
const { exec, spawn } = require('child_process');
const {
randomAddress,
getAPIKey,
logger,
checkFileExists,
} = require('./utils');
const { handleBuildCoverage } = require('./coverage');
const { createOffchain, createOnchain, uploadBuildResult } = require('./task');
const inquirer = require('inquirer');
function visualize(results) {
let data = [['File', 'Contract Name', 'Functions Can Get Fuzzed']];
if (!(results.length > 0 && results[0].success)) {
console.error('Build failed!');
return;
}
let result = results[0];
for (let contract_file_name of Object.keys(result.abi)) {
if (contract_file_name.startsWith('lib/')) {
continue;
}
let contract = result.abi[contract_file_name];
for (let name of Object.keys(contract)) {
let abis = contract[name];
if (name === 'FuzzLand' || name.includes('Scribble')) {
continue;
}
let abi_count = abis.filter((x) => x.type === 'function').length;
data.push([contract_file_name, name, abi_count]);
}
}
console.log(table(data));
}
function executeCommand(command, options, onExit, isPrint) {
if (isPrint) {
const [cmd, ...args] = command.split(' ');
const childProcess = spawn(cmd, args, options);
childProcess.stdout.on('data', (data) => {
console.log(`${data}`);
});
childProcess.stderr.on('data', (data) => {
console.error(`${data}`);
});
childProcess.on('error', (error) => {
console.error(`${error}`);
process.exit(1);
});
childProcess.on('close', (code) => {
onExit(code);
});
return childProcess;
} else {
const childProcess = exec(command, options, (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error}`);
// process.exit(1);
// onExit(0);
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
console.log(`${stdout}`);
onExit(0); // Assuming success, you might want to adjust this based on your use case
});
process.on('SIGINT', () => {
console.log('Received SIGINT. Terminating child process.');
childProcess.kill('SIGINT');
});
return childProcess;
}
}
function startFuzz(setupFile, configFile, isPrint) {
let command = '';
if (setupFile) {
command = `ityfuzz evm --builder-artifacts-file ./results.json -t "a" --work-dir ./workdir --setup-file ${setupFile}`;
} else {
command = `ityfuzz evm --builder-artifacts-file ./results.json --offchain-config-file ${configFile} -f -t "a" --work-dir ./workdir`;
}
console.log(`Starting ityfuzz with command: ${command}`);
handleBuildCoverage();
const options = { maxBuffer: 1024 * 1024 * 100 };
executeCommand(
command,
options,
(code) => {
console.log(`Child process exited with code ${code}`);
process.exit();
},
isPrint
);
}
// TODO: check offchain config is valid
function getOffchainConfig(results) {
let offchainConfig = results.reduce((acc, item) => {
const deepClonedItem = JSON.parse(JSON.stringify(item.abi));
return { ...acc, ...deepClonedItem };
}, {});
for (const fileName in offchainConfig) {
for (const contractName in offchainConfig[fileName]) {
offchainConfig[fileName][contractName] = {
address: randomAddress(),
constructor_args: '0x',
};
}
}
return offchainConfig;
}
async function build_with_autodetect(
project,
projectType,
compiler_version,
autoStart,
setupFile,
offchainConfigPath,
isPrint,
blaz
) {
if (!projectType) {
projectType = await auto_detect(project);
}
let results = await build(projectType, project, compiler_version);
if (!Array.isArray(results)) {
results = [results];
}
if (blaz) {
await getAPIKey();
}
const generatedOffchainConfig = getOffchainConfig(results);
if (!setupFile) {
fs.writeFileSync(
'offchain_config.json',
JSON.stringify(generatedOffchainConfig, null, 4)
);
console.log(
'Offchain config written to offchain_config.json, please edit it to specify the addresses of the contracts.'
);
} else {
startFuzz(setupFile, '', isPrint);
if (blaz) {
const buildResultUrl = await uploadBuildResult('results.json');
await createOffchain(
buildResultUrl,
projectType,
generatedOffchainConfig,
setupFile
);
}
}
if (offchainConfigPath) {
const isExist = checkFileExists(offchainConfigPath);
if (!isExist) return;
startFuzz('', offchainConfigPath, isPrint);
if (blaz) {
const buildResultUrl = await uploadBuildResult('results.json');
const offchainConfig = fs.readFileSync(offchainConfigPath, 'utf8');
await createOffchain(buildResultUrl, projectType, offchainConfig);
}
}
fs.writeFileSync('results.json', JSON.stringify(results, null, 4));
visualize(results);
console.log(`Results written to results.json`);
if (autoStart) {
startFuzz(setupFile, 'offchain_config.json', isPrint);
}
// No setup file/offchain config, select the mode of operation manually
if (!setupFile && !offchainConfigPath && !autoStart) {
const { choice } = await inquirer.prompt({
type: 'list',
name: 'choice',
message: 'Please select the option you want to use:',
choices: ['Setup File', 'Offchain Config'],
});
if (choice === 'Setup File') {
// generate setup files and check that the input file path exists in the setup files
const setupFiles = results.flatMap((obj) =>
Object.entries(obj.ast).flatMap(([filePath, astObj]) =>
astObj.contracts.map(
(contract) => `${filePath}:${contract.name}`
)
)
);
const setupType = await inquirer.prompt([
{
type: 'list',
name: 'contract',
message: 'Please select the below setup files to continue:',
choices: [...setupFiles, 'customization'],
},
{
type: 'input',
name: 'customContract',
message: 'Please input the setup file to continue:',
when: (answers) => answers.contract === 'customization',
},
]);
const inputSetupFileExist =
setupFiles.findIndex((f) => f === setupType.customContract) >
-1;
if (setupType.customContract && !inputSetupFileExist) {
logger.error(
'The setup file you input is not available, please check generated results.json file'
);
return;
}
const setupFile = setupType.customContract || setupType.contract;
startFuzz(setupFile, '', isPrint);
if (blaz) {
const buildResultUrl = await uploadBuildResult('results.json');
await createOffchain(
buildResultUrl,
projectType,
generatedOffchainConfig,
setupFile
);
}
} else if (choice === 'Offchain Config') {
const { offchain_cofig_path } = await inquirer.prompt([
{
type: 'input',
name: 'offchain_cofig_path',
message:
'Select the offchain config file, if no value is provided, the generated offchain_config.json file will be applied:',
},
]);
const offchainConfigPath =
offchain_cofig_path || 'offchain_config.json';
const isExist = checkFileExists(offchainConfigPath);
if (!isExist) return;
if (blaz) {
const offchainConfig = fs.readFileSync(
offchainConfigPath,
'utf8'
);
const buildResultUrl = await uploadBuildResult('results.json');
await createOffchain(
buildResultUrl,
projectType,
offchainConfig
);
}
startFuzz('', offchainConfigPath, isPrint);
}
}
}
const argv = yargs(hideBin(process.argv))
.command(
'$0 <project>',
'Build a project',
(yargs) => {
yargs
.positional('project', {
describe: 'Name of the project to build',
type: 'string',
})
.demandOption(
['project'],
'Please provide the project argument to proceed'
);
},
async (argv) => {
if (argv.project) {
await build_with_autodetect(
argv.project,
argv.projectType,
argv.compilerVersion,
argv.autoStart,
argv.setupFile,
argv.offchainConfig,
argv.printing,
argv.blaz
);
}
}
)
.option('project-type', {
alias: 't',
type: 'string',
description: 'Type of the project',
})
.option('compiler-version', {
alias: 'c',
type: 'string',
description: 'Specify the compiler version to use',
})
.option('auto-start', {
alias: 's',
type: 'boolean',
description: 'Automatically run ityfuzz after building',
})
.option('blaz', {
alias: 'b',
type: 'boolean',
description: 'Automatically run blaz services, create offchain task',
})
.option('setup-file', {
alias: 'f',
type: 'string',
description: 'Specify the setup file to use',
})
.option('offchain-config', {
alias: '-o',
type: 'string',
description: 'Specify the config file to use',
})
.option('printing', {
alias: 'p',
type: 'boolean',
description: 'Print the output in real-time if true',
default: false,
})
.command(
'configure',
'Configure CLI options, the values you provide will be written to file (~/.blazo)',
async () => {
await getAPIKey(true);
}
)
.help().argv;