-
Notifications
You must be signed in to change notification settings - Fork 6
/
mythx.js
201 lines (166 loc) · 6.71 KB
/
mythx.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
require('dotenv').config()
const armlet = require('armlet')
const fs = require('fs')
const yaml = require('js-yaml');
const mythXUtil = require('./lib/mythXUtil');
const asyncPool = require('tiny-async-pool');
const { MythXIssues, doReport } = require('./lib/issues2eslint');
const defaultConcurrentAnalyses = 4
function checkEnvVariables(embark) {
if (process.env.MYTHX_ETH_ADDRESS) {
process.env.MYTHX_USERNAME = process.env.MYTHX_ETH_ADDRESS;
embark.logger.warn("The environment variable MYTHX_ETH_ADDRESS has been deprecated in favour of MYTHX_USERNAME and will be removed in future versions. Please update your .env file or your environment variables accordingly.");
}
// Connect to MythX via armlet
if (!process.env.MYTHX_USERNAME || !process.env.MYTHX_PASSWORD) {
throw new Error("Environment variables 'MYTHX_USERNAME' and 'MYTHX_PASSWORD' not found. Place these in a .env file in the root of your ÐApp, add them in the CLI command, ie 'MYTHX_USERNAME=xyz MYTHX_PASSWORD=123 embark run', or add them to your system's environment variables.");
}
}
async function analyse(contracts, cfg, embark) {
cfg.logger = embark.logger
// Set analysis parameters
const limit = cfg.limit || defaultConcurrentAnalyses
if (isNaN(limit)) {
embark.logger.info(`limit parameter should be a number; got ${limit}.`)
return 1
}
if (limit < 0 || limit > defaultConcurrentAnalyses) {
embark.logger.info(`limit should be between 0 and ${defaultConcurrentAnalyses}.`)
return 1
}
checkEnvVariables(embark);
const armletClient = new armlet.Client(
{
clientToolName: "embark-mythx",
password: process.env.MYTHX_PASSWORD,
ethAddress: process.env.MYTHX_USERNAME,
})
// Filter contracts based on parameter choice
let toSubmit = { "contracts": {}, "sources": contracts.sources };
if (!("ignore" in embark.pluginConfig)) {
embark.pluginConfig.ignore = []
}
for (let [filename, contractObjects] of Object.entries(contracts.contracts)) {
for (let [contractName, contract] of Object.entries(contractObjects)) {
if (!("contracts" in cfg)) {
if (embark.pluginConfig.ignore.indexOf(contractName) == -1) {
if (!toSubmit.contracts[filename]) {
toSubmit.contracts[filename] = {}
}
toSubmit.contracts[filename][contractName] = contract;
}
} else {
if (cfg.contracts.indexOf(contractName) >= 0 && embark.pluginConfig.ignore.indexOf(contractName) == -1) {
if (!toSubmit.contracts[filename]) {
toSubmit.contracts[filename] = {}
}
toSubmit.contracts[filename][contractName] = contract;
}
}
}
}
// Stop here if no contracts are left
if (Object.keys(toSubmit.contracts).length === 0) {
embark.logger.info("No contracts to submit.");
return 0;
}
const submitObjects = mythXUtil.buildRequestData(toSubmit)
const { objects, errors } = await doAnalysis(armletClient, cfg, submitObjects, null, limit)
const result = doReport(cfg, objects, errors)
return result
}
async function getStatus(uuid, embark) {
checkEnvVariables(embark);
// Connect to MythX via armlet
const armletClient = new armlet.Client(
{
clientToolName: "embark-mythx",
password: process.env.MYTHX_PASSWORD,
ethAddress: process.env.MYTHX_USERNAME,
});
await armletClient.login();
try {
const results = await armletClient.getIssues(uuid.toLowerCase());
return ghettoReport(embark.logger, results);
} catch (err) {
embark.logger.warn(err);
return 1;
}
}
const doAnalysis = async (armletClient, config, contracts, contractNames = null, limit) => {
const timeout = (config.timeout || 300) * 1000;
const initialDelay = ('initial-delay' in config) ? config['initial-delay'] * 1000 : undefined;
const results = await asyncPool(limit, contracts, async buildObj => {
const obj = new MythXIssues(buildObj, config);
let analyzeOpts = {
clientToolName: 'embark-mythx',
timeout,
initialDelay
};
analyzeOpts.data = mythXUtil.cleanAnalyzeDataEmptyProps(obj.buildObj, config.debug, config.logger);
analyzeOpts.data.analysisMode = config.full ? "full" : "quick";
if (config.debug > 1) {
config.logger.debug("analyzeOpts: " + `${util.inspect(analyzeOpts, { depth: null })}`);
}
// request analysis to armlet.
try {
//TODO: Call analyze/analyzeWithStatus asynchronously
config.logger.info("Submitting '" + obj.contractName + "' for " + analyzeOpts.data.analysisMode + " analysis...")
const { issues, status } = await armletClient.analyzeWithStatus(analyzeOpts);
obj.uuid = status.uuid;
obj.groupId = status.groupId;
if (status.status === 'Error') {
return [status, null];
} else {
obj.setIssues(issues);
}
return [null, obj];
} catch (err) {
//console.log("catch", JSON.stringify(err));
let errStr;
if (typeof err === 'string') {
errStr = `${err}`;
} else if (typeof err.message === 'string') {
errStr = err.message;
} else {
errStr = `${util.inspect(err)}`;
}
if (errStr.includes('User or default timeout reached after')
|| errStr.includes('Timeout reached after')) {
return [(buildObj.contractName + ": ").yellow + errStr, null];
} else {
return [(buildObj.contractName + ": ").red + errStr, null];
}
}
});
return results.reduce((accum, curr) => {
const [err, obj] = curr;
if (err) {
accum.errors.push(err);
} else if (obj) {
accum.objects.push(obj);
}
return accum;
}, { errors: [], objects: [] });
};
function ghettoReport(logger, results) {
let issuesCount = 0;
results.forEach(ele => {
issuesCount += ele.issues.length;
});
if (issuesCount === 0) {
logger.info('No issues found');
return 0;
}
for (const group of results) {
logger.info(group.sourceList.join(', ').underline);
for (const issue of group.issues) {
logger.info(yaml.safeDump(issue, { 'skipInvalid': true }));
}
}
return 1;
}
module.exports = {
analyse,
getStatus
}