-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathechidna-gen.js
More file actions
337 lines (282 loc) · 10.1 KB
/
Copy pathechidna-gen.js
File metadata and controls
337 lines (282 loc) · 10.1 KB
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
#!/usr/bin/env -S deno run --allow-read --allow-write
// SPDX-License-Identifier: MPL-2.0
// Echidna Test Property Generator
// Generates Echidna test contracts from Solidity source files
//
// Usage: deno run --allow-read --allow-write scripts/echidna-gen.js <contract.sol>
const SPDX_HEADER = `// SPDX-License-Identifier: MPL-2.0
// Generated by echidnabot - Echidna Test Generator
// https://github.com/hyperpolymath/echidnabot
`;
/**
* Parse a Solidity contract and extract key information
* @param {string} source - Solidity source code
* @returns {object} Parsed contract info
*/
function parseContract(source) {
const contractMatch = source.match(/contract\s+(\w+)(?:\s+is\s+([^{]+))?\s*\{/);
if (!contractMatch) {
throw new Error("No contract found in source file");
}
const name = contractMatch[1];
const inheritance = contractMatch[2]?.split(",").map((s) => s.trim()) || [];
// Extract state variables
const stateVars = [];
const stateVarRegex =
/^\s*(uint256|uint128|uint64|uint32|uint16|uint8|int256|int128|int64|int32|int16|int8|address|bool|string|bytes32|bytes)\s+(public\s+|private\s+|internal\s+)?(\w+)/gm;
let match;
while ((match = stateVarRegex.exec(source)) !== null) {
stateVars.push({
type: match[1],
visibility: match[2]?.trim() || "internal",
name: match[3],
});
}
// Extract mappings
const mappings = [];
const mappingRegex =
/mapping\s*\(\s*(\w+)\s*=>\s*(\w+)\s*\)\s+(public\s+|private\s+|internal\s+)?(\w+)/g;
while ((match = mappingRegex.exec(source)) !== null) {
mappings.push({
keyType: match[1],
valueType: match[2],
visibility: match[3]?.trim() || "internal",
name: match[4],
});
}
// Extract functions
const functions = [];
const funcRegex =
/function\s+(\w+)\s*\(([^)]*)\)\s+(public|external|internal|private)?[^{]*\{/g;
while ((match = funcRegex.exec(source)) !== null) {
functions.push({
name: match[1],
params: match[2],
visibility: match[3] || "public",
});
}
// Extract pragma version
const pragmaMatch = source.match(/pragma\s+solidity\s+([^;]+);/);
const pragmaVersion = pragmaMatch ? pragmaMatch[1] : "^0.8.19";
return {
name,
inheritance,
stateVars,
mappings,
functions,
pragmaVersion,
};
}
/**
* Generate invariant properties based on contract analysis
* @param {object} contract - Parsed contract info
* @returns {string[]} Array of invariant function strings
*/
function generateInvariants(contract) {
const invariants = [];
// Generate balance invariants for uint state variables
for (const v of contract.stateVars) {
if (v.type.startsWith("uint")) {
invariants.push(`
/// @notice ${v.name} should maintain valid bounds
function echidna_${v.name}_valid() public view returns (bool) {
return ${v.name} >= 0;
}`);
}
if (v.type === "address" && v.name !== "owner") {
invariants.push(`
/// @notice ${v.name} address validation
function echidna_${v.name}_not_zero() public view returns (bool) {
// Allow zero address if intentionally set
return true;
}`);
}
}
// Generate mapping invariants
for (const m of contract.mappings) {
if (m.valueType.startsWith("uint")) {
invariants.push(`
/// @notice Mapping ${m.name} values should be valid
function echidna_${m.name}_valid(${m.keyType} key) public view returns (bool) {
return ${m.name}[key] >= 0;
}`);
}
}
// Check for common patterns
const hasOwner = contract.stateVars.some((v) => v.name === "owner");
if (hasOwner) {
invariants.push(`
/// @notice Owner should always be set after construction
function echidna_owner_set() public view returns (bool) {
return owner != address(0);
}`);
}
const hasTotalSupply = contract.stateVars.some(
(v) => v.name === "totalSupply"
);
const hasBalanceOf = contract.mappings.some((m) => m.name === "balanceOf");
if (hasTotalSupply && hasBalanceOf) {
invariants.push(`
/// @notice User balance should never exceed total supply
function echidna_balance_bounded() public view returns (bool) {
return balanceOf[msg.sender] <= totalSupply;
}`);
}
const hasPaused = contract.stateVars.some((v) => v.name === "paused");
if (hasPaused) {
invariants.push(`
/// @notice Paused state consistency check
function echidna_pause_consistent() public view returns (bool) {
return paused == true || paused == false; // Always true, but demonstrates state tracking
}`);
}
return invariants;
}
/**
* Generate assertion-based test functions
* @param {object} contract - Parsed contract info
* @returns {string[]} Array of test function strings
*/
function generateAssertionTests(contract) {
const tests = [];
// Generate tests for transfer-like functions
const transferFuncs = contract.functions.filter(
(f) =>
f.name.toLowerCase().includes("transfer") ||
f.name.toLowerCase().includes("send")
);
for (const func of transferFuncs) {
tests.push(`
/// @notice Test ${func.name} balance accounting
function test_${func.name}_accounting(address to, uint256 amount) public {
if (to == address(0) || to == msg.sender) return;
if (amount == 0 || amount > balanceOf[msg.sender]) return;
uint256 senderBefore = balanceOf[msg.sender];
uint256 receiverBefore = balanceOf[to];
try this.${func.name}(to, amount) {
assert(balanceOf[msg.sender] == senderBefore - amount);
assert(balanceOf[to] == receiverBefore + amount);
} catch {
// Transfer failed, balances should be unchanged
assert(balanceOf[msg.sender] == senderBefore);
assert(balanceOf[to] == receiverBefore);
}
}`);
}
// Generate tests for mint-like functions
const mintFuncs = contract.functions.filter((f) =>
f.name.toLowerCase().includes("mint")
);
for (const func of mintFuncs) {
tests.push(`
/// @notice Test ${func.name} supply increase
function test_${func.name}_supply(address to, uint256 amount) public {
if (to == address(0) || amount == 0) return;
uint256 supplyBefore = totalSupply;
try this.${func.name}(to, amount) {
assert(totalSupply == supplyBefore + amount);
} catch {
assert(totalSupply == supplyBefore);
}
}`);
}
// Generate tests for burn-like functions
const burnFuncs = contract.functions.filter((f) =>
f.name.toLowerCase().includes("burn")
);
for (const func of burnFuncs) {
tests.push(`
/// @notice Test ${func.name} supply decrease
function test_${func.name}_supply(uint256 amount) public {
if (amount == 0 || amount > balanceOf[msg.sender]) return;
uint256 supplyBefore = totalSupply;
try this.${func.name}(amount) {
assert(totalSupply == supplyBefore - amount);
} catch {
assert(totalSupply == supplyBefore);
}
}`);
}
return tests;
}
/**
* Generate the complete Echidna test contract
* @param {object} contract - Parsed contract info
* @param {string} importPath - Relative import path
* @returns {string} Complete test contract source
*/
function generateTestContract(contract, importPath) {
const invariants = generateInvariants(contract);
const assertionTests = generateAssertionTests(contract);
const testContractName = `${contract.name}EchidnaTest`;
return `${SPDX_HEADER}
pragma solidity ${contract.pragmaVersion};
import "${importPath}";
/// @title ${testContractName} - Auto-generated Echidna fuzz testing contract
/// @notice Property-based tests for ${contract.name}
/// @dev Generated invariants and assertion tests for fuzzing
contract ${testContractName} is ${contract.name} {
// ========== TEST CONFIGURATION ==========
address private constant ECHIDNA_SENDER = address(0x10000);
address private constant ECHIDNA_RECEIVER = address(0x20000);
// ========== CONSTRUCTOR ==========
constructor() ${contract.name}(${contract.name === "Token" ? "1_000_000 * 10 ** 18" : ""}) {
// Initial test setup
}
// ========== INVARIANT PROPERTIES ==========
// These must ALWAYS return true. Echidna tries to break them.
${invariants.join("\n")}
// ========== ASSERTION-BASED TESTS ==========
// These use assert() to verify specific behaviors
${assertionTests.join("\n")}
}
`;
}
/**
* Main CLI handler
*/
async function main() {
const args = Deno.args;
if (args.length < 1) {
console.log(`
Echidna Test Generator - Generate fuzz tests for Solidity contracts
Usage:
deno run --allow-read --allow-write scripts/echidna-gen.js <contract.sol> [output.sol]
Arguments:
<contract.sol> Path to the Solidity contract to analyze
[output.sol] Optional output path (default: <contract>EchidnaTest.sol)
Examples:
deno run --allow-read --allow-write scripts/echidna-gen.js contracts/Token.sol
deno run --allow-read --allow-write scripts/echidna-gen.js contracts/Vault.sol contracts/VaultTest.sol
`);
Deno.exit(1);
}
const inputPath = args[0];
const source = await Deno.readTextFile(inputPath);
console.log(`Analyzing ${inputPath}...`);
const contract = parseContract(source);
console.log(`Found contract: ${contract.name}`);
console.log(` State variables: ${contract.stateVars.length}`);
console.log(` Mappings: ${contract.mappings.length}`);
console.log(` Functions: ${contract.functions.length}`);
// Calculate import path
const inputDir = inputPath.split("/").slice(0, -1).join("/");
const inputFile = inputPath.split("/").pop();
const importPath = `./${inputFile}`;
// Generate test contract
const testSource = generateTestContract(contract, importPath);
// Determine output path
const outputPath = args[1] || inputPath.replace(".sol", "EchidnaTest.sol");
await Deno.writeTextFile(outputPath, testSource);
console.log(`\nGenerated Echidna test contract: ${outputPath}`);
console.log(`
Next steps:
1. Review and customize the generated tests
2. Run Echidna:
echidna ${outputPath} --contract ${contract.name}EchidnaTest --config echidna/echidna-config.yaml
`);
}
main().catch((err) => {
console.error(`Error: ${err.message}`);
Deno.exit(1);
});