gdp-wired 0.37.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/core/cli.d.ts +2 -1
- package/dist/core/cli.js +25 -6
- package/dist/core/cyclic.js +1 -1
- package/dist/core/dsl.js +64 -3
- package/dist/core/exists.d.ts +1 -0
- package/dist/core/exists.js +28 -0
- package/dist/core/extract-check.d.ts +2 -2
- package/dist/core/extract-check.js +7 -4
- package/dist/core/extract-print.js +5 -3
- package/dist/core/extract-read.d.ts +2 -0
- package/dist/core/extract-sol.d.ts +91 -0
- package/dist/core/extract-sol.js +1106 -0
- package/dist/core/extract-step.d.ts +56 -6
- package/dist/core/extract-step.js +588 -67
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/extract.js +25 -4
- package/dist/core/infer.js +48 -13
- package/dist/core/laws.js +16 -2
- package/dist/core/live.js +158 -63
- package/dist/core/machine.js +7 -4
- package/dist/core/py/harness.py +75 -12
- package/dist/core/py/reader.py +67 -11
- package/package.json +1 -1
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
// The extractor's Solidity front end (`gdp-wired/extract-sol`): a contract read through solc's own AST (`solc
|
|
2
|
+
// --standard-json`, the compact JSON AST), lowered here into the shared step IR (core/extract-step.ts), executed by the
|
|
3
|
+
// shared step executor, printed, built and checked as every front end's rule is. The check deploys the contract's own
|
|
4
|
+
// bytecode, compiled by the same solc, on foundry's anvil and runs it through core/sol/harness.py (JSON-RPC, the
|
|
5
|
+
// standard library only): every state, cell, result and revert compared.
|
|
6
|
+
//
|
|
7
|
+
// const x = extractSolidity('contracts/mocks/token/ERC20Mock.sol', {root: '.'}) // the contract inferred
|
|
8
|
+
//
|
|
9
|
+
// What the rule is of the contract (the boundary, printed in every extraction's notes):
|
|
10
|
+
// - A step is one external call: its function's body with the modifiers it names, the base contracts' functions it
|
|
11
|
+
// calls inlined (virtual ones resolved along the linearization). A revert, require, assert or custom error is the
|
|
12
|
+
// step's refusal (the transaction reverts: nothing it wrote stays). msg.sender is an input of every request,
|
|
13
|
+
// msg.value of a payable one (0 elsewhere), block.timestamp the request's time.
|
|
14
|
+
// - Integers: uint256 is exact past the rule's 2^53 by a width variable (`W256$`, a state variable no step writes,
|
|
15
|
+
// any value at least 2 above the code's constants): a value is below it, a checked operation past it reverts, an
|
|
16
|
+
// unchecked one wraps by cases (a sum or a difference once; a product wrapped is refused). A law proven for every
|
|
17
|
+
// such width is proven for 2^256. uintN and intN below 2^48 are exact; other widths are refused where read.
|
|
18
|
+
// - Addresses are naturals below 2^26 compared only by equality (the code is symmetric in them; address(0) is 0): the
|
|
19
|
+
// claim is for runs among fewer than 2^26 accounts. A mapping is a map with Solidity's zero for a key never set (a
|
|
20
|
+
// cell is held where it isn't zero); a mapping of mappings keyed by two addresses is one map keyed by a·2^26 + b.
|
|
21
|
+
// - The contract's ether is the state's `balance`: a payable call adds msg.value; a value call to an address
|
|
22
|
+
// (`a.call{value: v}("")`, `send`, `transfer`) moves it where it is there. The address called is an account without
|
|
23
|
+
// code (it accepts and calls nothing back): `reentrant: true` (core/extract-reenter.ts) makes it any code instead.
|
|
24
|
+
// - Left out, each where it is read with why: strings and bytes (their state too), loops, arrays, structs past a
|
|
25
|
+
// mapping's value, calls of other contracts, inline assembly, try/catch, constants past 2^53, signed widths past 48.
|
|
26
|
+
import { fromModel } from "./extract.js";
|
|
27
|
+
import { evalC, interpret, seeded } from "./machine.js";
|
|
28
|
+
import { allowed, watch } from "./watch.js";
|
|
29
|
+
import { kindOfVar } from "./extract-check.js";
|
|
30
|
+
import { Refusal, pathOf } from "./extract-read.js";
|
|
31
|
+
const refuse = (where, what) => { throw new Refusal(where, what); };
|
|
32
|
+
import { checkStep, node, readStep, stepNames } from "./extract-step.js";
|
|
33
|
+
export { proveRule, proveSteps } from "./dsl.js";
|
|
34
|
+
export const MOD = 'W256$';
|
|
35
|
+
// (the width the check runs the rule at: past 2^256's half the code's values are the rule's near W)
|
|
36
|
+
const CHECK_W = 2 ** 52;
|
|
37
|
+
const U256 = { k: 'int', bits: 256, signed: false, mod: MOD };
|
|
38
|
+
const env = () => globalThis.process?.env ?? {};
|
|
39
|
+
export function compile(file, o) {
|
|
40
|
+
const cp = node('node:child_process'), fs = node('node:fs'), path = node('node:path');
|
|
41
|
+
const root = path.resolve(o.root ?? path.dirname(file)), rel = path.relative(root, path.resolve(file));
|
|
42
|
+
const input = { language: 'Solidity', sources: { [rel]: { content: fs.readFileSync(file, 'utf8') } },
|
|
43
|
+
settings: { remappings: o.remappings ?? [], optimizer: { enabled: false }, outputSelection: { '*': { '': ['ast'], '*': ['abi', 'evm.bytecode.object', 'evm.deployedBytecode.object', 'evm.methodIdentifiers', 'storageLayout'] } } } };
|
|
44
|
+
let out;
|
|
45
|
+
const solc = o.solc ?? env().GDP_SOLC ?? 'solc';
|
|
46
|
+
try {
|
|
47
|
+
out = cp.execFileSync(solc, ['--standard-json', '--base-path', root, '--include-path', `${root}/node_modules`, '--allow-paths', root], { input: JSON.stringify(input), encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
throw new Refusal(file, `solc didn't run (${String(e.message).slice(0, 300)}): solc 0.8 is needed to extract Solidity (on the PATH, or $GDP_SOLC)`);
|
|
51
|
+
}
|
|
52
|
+
const j = JSON.parse(out);
|
|
53
|
+
const errs = (j.errors ?? []).filter(e => e.severity === 'error');
|
|
54
|
+
if (errs.length)
|
|
55
|
+
throw new Refusal(file, `solc: ${errs.map(e => e.formattedMessage.split('\n')[0]).join(' | ').slice(0, 600)}`);
|
|
56
|
+
const ast = new Map(), text = new Map(), paths = new Map();
|
|
57
|
+
let main = -1;
|
|
58
|
+
for (const [p, s] of Object.entries(j.sources)) {
|
|
59
|
+
if (p === rel)
|
|
60
|
+
main = s.id;
|
|
61
|
+
ast.set(s.id, s.ast);
|
|
62
|
+
paths.set(s.id, p);
|
|
63
|
+
const abs = p === rel ? path.resolve(file) : [path.resolve(root, p), path.resolve(root, 'node_modules', p)].find(x => fs.existsSync(x));
|
|
64
|
+
text.set(s.id, abs ? fs.readFileSync(abs, 'utf8') : '');
|
|
65
|
+
}
|
|
66
|
+
return { main, ast, text, paths, contracts: j.contracts };
|
|
67
|
+
}
|
|
68
|
+
class Lower {
|
|
69
|
+
c;
|
|
70
|
+
file;
|
|
71
|
+
reenter;
|
|
72
|
+
defs = new Map();
|
|
73
|
+
funcs = {};
|
|
74
|
+
fields = [];
|
|
75
|
+
consts = new Map();
|
|
76
|
+
minW = 2;
|
|
77
|
+
addrBits = 0;
|
|
78
|
+
get ADDR() { return { k: 'int', bits: this.addrBits, signed: false }; }
|
|
79
|
+
unchecked = false;
|
|
80
|
+
ether = false;
|
|
81
|
+
nested = new Set();
|
|
82
|
+
lin = [];
|
|
83
|
+
// (the function being lowered: whether it is an entry, payable; its return locals)
|
|
84
|
+
cur = { entry: false, payable: false, rets: [], tmp: 0 };
|
|
85
|
+
// (reenter: an address called is any code, which may call back into the contract before the call returns)
|
|
86
|
+
frames = [];
|
|
87
|
+
constructor(c, file, reenter = false) {
|
|
88
|
+
this.c = c;
|
|
89
|
+
this.file = file;
|
|
90
|
+
this.reenter = reenter;
|
|
91
|
+
const walk = (n) => {
|
|
92
|
+
if (Array.isArray(n)) {
|
|
93
|
+
n.forEach(walk);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (!n || typeof n !== 'object')
|
|
97
|
+
return;
|
|
98
|
+
const a = n;
|
|
99
|
+
if (typeof a.id === 'number' && typeof a.nodeType === 'string')
|
|
100
|
+
this.defs.set(a.id, a);
|
|
101
|
+
for (const v of Object.values(a))
|
|
102
|
+
if (v && typeof v === 'object')
|
|
103
|
+
walk(v);
|
|
104
|
+
};
|
|
105
|
+
for (const a of c.ast.values())
|
|
106
|
+
walk(a);
|
|
107
|
+
}
|
|
108
|
+
// `file:line:col` of a node.
|
|
109
|
+
at(n) {
|
|
110
|
+
const [s, , f] = String(n.src).split(':').map(Number), t = this.c.text.get(f) ?? '';
|
|
111
|
+
const before = t.slice(0, s), line = before.split('\n').length, col = s - before.lastIndexOf('\n');
|
|
112
|
+
return `${(this.c.paths.get(f) ?? this.file).split('/').pop()}:${line}:${col}`;
|
|
113
|
+
}
|
|
114
|
+
text(n) { const [s, l, f] = String(n.src).split(':').map(Number); return (this.c.text.get(f) ?? '').slice(s, s + l).replace(/\s+/g, ' ').slice(0, 120); }
|
|
115
|
+
no(n, why) { throw new Refusal(this.at(n), `${this.text(n)}: ${why}`); }
|
|
116
|
+
// A type's SType by solc's type string (where the subset reads it).
|
|
117
|
+
ty(ts, n) {
|
|
118
|
+
const s = ts.replace(/ (storage|memory|calldata)( ref| pointer)?$/, '');
|
|
119
|
+
if (s === 'uint256')
|
|
120
|
+
return U256;
|
|
121
|
+
if (s === 'bool')
|
|
122
|
+
return { k: 'bool' };
|
|
123
|
+
if (s === 'address' || s === 'address payable')
|
|
124
|
+
return this.ADDR;
|
|
125
|
+
let m = /^uint(\d+)$/.exec(s);
|
|
126
|
+
if (m && Number(m[1]) <= 48)
|
|
127
|
+
return { k: 'int', bits: Number(m[1]), signed: false };
|
|
128
|
+
m = /^int(\d+)$/.exec(s);
|
|
129
|
+
if (m && Number(m[1]) <= 48)
|
|
130
|
+
return { k: 'int', bits: Number(m[1]), signed: true };
|
|
131
|
+
m = /^enum (.+)$/.exec(s);
|
|
132
|
+
if (m) {
|
|
133
|
+
const d = this.byName('EnumDefinition', m[1].split('.').pop());
|
|
134
|
+
if (d)
|
|
135
|
+
return { k: 'choice', values: d.members.map((x) => x.name) };
|
|
136
|
+
}
|
|
137
|
+
if (s.startsWith('mapping('))
|
|
138
|
+
return this.mapTy(s, n);
|
|
139
|
+
if (/^(int_const|rational_const)/.test(s))
|
|
140
|
+
return { k: 'int' };
|
|
141
|
+
return { k: 'opaque', why: `a ${s} (outside the Solidity subset)` };
|
|
142
|
+
}
|
|
143
|
+
byName(kind, name) { for (const d of this.defs.values())
|
|
144
|
+
if (d.nodeType === kind && d.name === name)
|
|
145
|
+
return d; return undefined; }
|
|
146
|
+
// mapping(K => V), and mapping(K1 => mapping(K2 => V)) as one map keyed by K1·2^26 + K2 (both below 2^26).
|
|
147
|
+
mapTy(s, n) {
|
|
148
|
+
const inner = s.slice('mapping('.length, -1), arrow = topArrow(inner);
|
|
149
|
+
const k = this.ty(inner.slice(0, arrow).trim(), n), v = inner.slice(arrow + 2).trim();
|
|
150
|
+
if (!(k.k === 'int' && !k.signed))
|
|
151
|
+
return { k: 'opaque', why: `a mapping keyed by ${inner.slice(0, arrow).trim()}` };
|
|
152
|
+
if (v.startsWith('mapping(')) {
|
|
153
|
+
const vv = v.slice('mapping('.length, -1), a2 = topArrow(vv), k2 = this.ty(vv.slice(0, a2).trim(), n), val = this.ty(vv.slice(a2 + 2).trim(), n);
|
|
154
|
+
if (!(k2.k === 'int' && !k2.signed) || !scalarT(val))
|
|
155
|
+
return { k: 'opaque', why: `a mapping of mappings of ${vv.slice(a2 + 2).trim()}` };
|
|
156
|
+
return { k: 'map', key: { k: 'int' }, val, nested: true };
|
|
157
|
+
}
|
|
158
|
+
const val = this.ty(v, n);
|
|
159
|
+
if (!scalarT(val))
|
|
160
|
+
return { k: 'opaque', why: `a mapping of ${v}` };
|
|
161
|
+
return { k: 'map', key: k.k === 'int' && k.mod ? { k: 'int' } : k, val };
|
|
162
|
+
}
|
|
163
|
+
// The contract: its linearized bases, state, functions.
|
|
164
|
+
module(name) {
|
|
165
|
+
const contracts = [...this.defs.values()].filter(d => d.nodeType === 'ContractDefinition');
|
|
166
|
+
const main = this.c.ast.get(this.c.main);
|
|
167
|
+
const own = contracts.filter(d => main && main.nodes.includes(d));
|
|
168
|
+
const cands = (name ? contracts.filter(d => d.name === name) : own.filter(d => d.contractKind === 'contract' && !d.abstract));
|
|
169
|
+
if (cands.length !== 1)
|
|
170
|
+
throw new Refusal(this.file, name ? `no contract ${name}` : cands.length ? `several contracts (${cands.map(d => d.name).join(', ')}): name one (entry)` : 'no contract that isn\'t abstract in the file (name one: entry)');
|
|
171
|
+
const k = cands[0];
|
|
172
|
+
if (k.contractKind !== 'contract' || k.abstract)
|
|
173
|
+
throw new Refusal(this.at(k), `${k.name}: a${k.abstract ? 'n abstract contract' : ` ${k.contractKind}`} (the subset reads a contract that is deployed)`);
|
|
174
|
+
this.lin = k.linearizedBaseContracts.map(id => this.defs.get(id));
|
|
175
|
+
// The state: every base's variables, base first (storage order); constants inlined.
|
|
176
|
+
for (const c of [...this.lin].reverse())
|
|
177
|
+
for (const n of c.nodes) {
|
|
178
|
+
if (n.nodeType !== 'VariableDeclaration')
|
|
179
|
+
continue;
|
|
180
|
+
if (n.constant) {
|
|
181
|
+
const v = n.value;
|
|
182
|
+
if (!v)
|
|
183
|
+
this.no(n, 'a constant with no value');
|
|
184
|
+
this.consts.set(n.id, this.ex(v));
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (n.mutability === 'immutable')
|
|
188
|
+
this.no(n, 'an immutable (not yet)');
|
|
189
|
+
if (n.name === 'balance' || n.name === MOD)
|
|
190
|
+
this.no(n, `a state variable named ${n.name} (the rule's own name for the contract's ether, or its width)`);
|
|
191
|
+
this.fields.push({ name: n.name, t: this.ty(n.typeDescriptions.typeString, n), decl: n, sol: n.typeDescriptions.typeString });
|
|
192
|
+
}
|
|
193
|
+
// The functions: every base's, a virtual one resolved to the most derived override.
|
|
194
|
+
const fns = {};
|
|
195
|
+
const entries = {};
|
|
196
|
+
const methods = {};
|
|
197
|
+
for (const c of this.lin)
|
|
198
|
+
for (const f of c.nodes) {
|
|
199
|
+
if (f.nodeType !== 'FunctionDefinition' || !f.body)
|
|
200
|
+
continue;
|
|
201
|
+
if (f.kind === 'constructor')
|
|
202
|
+
continue;
|
|
203
|
+
const id = this.fnId(f);
|
|
204
|
+
if (this.funcs[id])
|
|
205
|
+
continue;
|
|
206
|
+
const pub = f.visibility === 'public' || f.visibility === 'external';
|
|
207
|
+
const name = f.kind === 'receive' ? 'receive' : f.kind === 'fallback' ? 'fallback' : f.name;
|
|
208
|
+
if (pub && f.stateMutability !== 'view' && f.stateMutability !== 'pure') {
|
|
209
|
+
if (methods[name])
|
|
210
|
+
this.no(f, `${name}: an overloaded external function (the subset reads one of a name)`);
|
|
211
|
+
methods[name] = `entry:${id}`;
|
|
212
|
+
const inputs = f.parameters.parameters.map(x => x.typeDescriptions.typeString);
|
|
213
|
+
const outs = f.returnParameters.parameters.map(x => x.typeDescriptions.typeString);
|
|
214
|
+
entries[name] = { sig: `${f.name}(${f.parameters.parameters.map(x => abiType(x.typeDescriptions.typeString)).join(',')})`, inputs, payable: f.stateMutability === 'payable', ...(outs.length === 1 ? { out: outs[0] } : {}) };
|
|
215
|
+
}
|
|
216
|
+
fns[id] = f;
|
|
217
|
+
}
|
|
218
|
+
// (lowered where read: the entries now, the functions they call where they call them)
|
|
219
|
+
for (const [id, f] of Object.entries(fns))
|
|
220
|
+
if (Object.values(methods).includes(`entry:${id}`))
|
|
221
|
+
this.funcs[`entry:${id}`] = this.fn(f, `entry:${id}`, true);
|
|
222
|
+
// The constructor: every base's state initializers and constructor, base first, with the arguments given to it.
|
|
223
|
+
const init = this.ctor(k);
|
|
224
|
+
for (const fr of this.frames) {
|
|
225
|
+
const n = fr.name.slice('Frame$'.length);
|
|
226
|
+
methods[`${n}$resume`] = `entry:${Object.keys(fns).find(i => methods[n] === `entry:${i}`)}$resume`;
|
|
227
|
+
}
|
|
228
|
+
const rec = { name: k.name, short: k.name, fields: [...this.fields.filter(f => !f.t.nested).map(f => ({ name: f.name, t: f.t })), { name: MOD, t: { k: 'int' } }, ...(this.ether ? [{ name: 'balance', t: U256 }] : []),
|
|
229
|
+
...this.frames.map(fr => ({ name: `frames$${fr.name.slice('Frame$'.length)}`, t: { k: 'map', key: { k: 'int' }, val: { k: 'rec', name: fr.name } } })), ...(this.frames.length ? [{ name: 'pending$', t: { k: 'int' } }] : [])],
|
|
230
|
+
methods: { __init__: '__init__', ...methods }, kinds: [], own: true, module: k.name, p: this.at(k) };
|
|
231
|
+
this.funcs.__init__ = init;
|
|
232
|
+
const ctorDef = this.lin[0].nodes.find((n) => n.nodeType === 'FunctionDefinition' && n.kind === 'constructor');
|
|
233
|
+
const meta = { leftOut: [...this.leftOut], calls: this.calls, resumes: this.frames.map(fr => `${fr.name.slice('Frame$'.length)}$resume`), addrBits: this.addrBits, contract: k.name, source: this.c.paths.get(Number(String(k.src).split(':')[2])), fields: this.fields, fns, payable: Object.entries(entries).filter(([, e]) => e.payable).map(([n]) => n), minW: this.minW, nested: [...this.nested], entries,
|
|
234
|
+
ctor: { inputs: ctorDef ? ctorDef.parameters.parameters.map(x => x.typeDescriptions.typeString) : [], payable: ctorDef?.stateMutability === 'payable' }, ether: this.ether };
|
|
235
|
+
const mod = { lang: 'solidity', file: this.file.split('/').pop(), path: this.file, module: k.name, root: '', entries: [{ k: 'class', rec: k.name }], recs: { [k.name]: rec, ...Object.fromEntries(this.frames.map(fr => [fr.name, fr])) }, funcs: this.funcs };
|
|
236
|
+
return { mod, meta };
|
|
237
|
+
}
|
|
238
|
+
// A function's id: the most derived override of its name and parameter types.
|
|
239
|
+
fnId(f) {
|
|
240
|
+
const sig = `${f.name}(${f.parameters.parameters.map(x => x.typeDescriptions.typeString).join(',')})`;
|
|
241
|
+
for (const c of this.lin)
|
|
242
|
+
for (const g of c.nodes)
|
|
243
|
+
if (g.nodeType === 'FunctionDefinition' && g.kind === f.kind && `${g.name}(${g.parameters.parameters.map(x => x.typeDescriptions.typeString).join(',')})` === sig && g.body)
|
|
244
|
+
return `f${g.id}`;
|
|
245
|
+
return `f${f.id}`;
|
|
246
|
+
}
|
|
247
|
+
// A function: self, msg.sender, msg.value (an entry that isn't payable takes none: 0), then its own parameters.
|
|
248
|
+
fn(f, id, entry) {
|
|
249
|
+
const payable = f.stateMutability === 'payable';
|
|
250
|
+
this.cur = { entry, payable, rets: [], tmp: 0 };
|
|
251
|
+
const params = [{ name: 'self', t: { k: 'rec', name: this.lin[0].name }, self: true }, { name: 'msg.sender', t: this.ADDR }, ...(entry && !payable ? [] : [{ name: 'msg.value', t: U256 }])];
|
|
252
|
+
for (const pa of f.parameters.parameters)
|
|
253
|
+
params.push({ name: pa.name || `_${pa.id}`, t: this.ty(pa.typeDescriptions.typeString, pa) });
|
|
254
|
+
const rets = f.returnParameters.parameters;
|
|
255
|
+
if (rets.length > 1)
|
|
256
|
+
this.no(f, 'several results (the subset reads one)');
|
|
257
|
+
const ret = rets.length ? this.ty(rets[0].typeDescriptions.typeString, rets[0]) : { k: 'none' };
|
|
258
|
+
const body = [];
|
|
259
|
+
const p = this.at(f);
|
|
260
|
+
if (entry)
|
|
261
|
+
body.push(senderNonzero(p));
|
|
262
|
+
// (a payable entry: the value is the contract's before its body runs)
|
|
263
|
+
// (the ether there is is below 2^256: a value past it is no request)
|
|
264
|
+
if (entry && payable) {
|
|
265
|
+
this.ether = true;
|
|
266
|
+
body.push({ s: 'set', p, to: self('balance', p), x: { e: 'bin', op: '+', p, text: 'balance + msg.value', x: self('balance', p), y: { e: 'var', n: 'msg.value', p }, ovf: 'trap', ity: { bits: 256, signed: false, mod: MOD }, trap: 'no ether past 2^256 exists' } });
|
|
267
|
+
}
|
|
268
|
+
// (named results: locals from 0, returned at the end)
|
|
269
|
+
for (const r of rets)
|
|
270
|
+
if (r.name) {
|
|
271
|
+
this.cur.rets.push(r.name);
|
|
272
|
+
body.push({ s: 'set', p, to: { e: 'var', n: r.name, p }, x: zero(this.ty(r.typeDescriptions.typeString, r), p) });
|
|
273
|
+
}
|
|
274
|
+
body.push(...this.withModifiers(f, f.modifiers, 0));
|
|
275
|
+
if (this.cur.rets.length)
|
|
276
|
+
body.push({ s: 'ret', p, x: { e: 'var', n: this.cur.rets[0], p } });
|
|
277
|
+
const name = f.kind === 'receive' ? 'receive' : f.kind === 'fallback' ? 'fallback' : f.name;
|
|
278
|
+
if (this.reenter && callsOut(body)) {
|
|
279
|
+
if (!entry)
|
|
280
|
+
this.no(f, `${name}: a call into other code inside a function an entry calls (the subset splits an entry's own body at it)`);
|
|
281
|
+
return this.split(name, id, params, ret, body, p);
|
|
282
|
+
}
|
|
283
|
+
return { id, name, p, span: [p, 0, 0], params, ret, body, decorators: [] };
|
|
284
|
+
}
|
|
285
|
+
// An entry that calls into other code, as two steps: up to the call (the value moved, the call pending: its locals in
|
|
286
|
+
// a frame of the state, `frames$<fn>`, at its depth), and from it (`<fn>$resume`: the frame on top given back, ok
|
|
287
|
+
// whether the callee returned or reverted). Between them any step may run: other code called back. `pending$` is the
|
|
288
|
+
// depth: the calls pending, the last resumed first (as the code's return).
|
|
289
|
+
split(name, id, params, ret, body, p) {
|
|
290
|
+
const i = body.findIndex(x => x.s === 'callout');
|
|
291
|
+
if (i < 0)
|
|
292
|
+
return refuse(p, `${name}: a call into other code inside a branch (the subset splits a body at a call at its top)`);
|
|
293
|
+
const mk = body[i], pre = body.slice(0, i), rest = body.slice(i + 1);
|
|
294
|
+
if (callsOut(rest))
|
|
295
|
+
refuse(p, `${name}: two calls into other code (the subset splits at one)`);
|
|
296
|
+
// The locals the rest may read: the parameters, and every local the part before sets.
|
|
297
|
+
const locals = new Map();
|
|
298
|
+
for (const pa of params)
|
|
299
|
+
if (!pa.self)
|
|
300
|
+
locals.set(pa.name, pa.t);
|
|
301
|
+
const scan = (ss) => { for (const x of ss) {
|
|
302
|
+
const to = x.to;
|
|
303
|
+
if (x.s === 'set' && to?.e === 'var') {
|
|
304
|
+
if (!x.t && !locals.has(String(to.n)))
|
|
305
|
+
refuse(x.p, `${String(to.n)}: a local of no stated type before a call into other code`);
|
|
306
|
+
if (x.t)
|
|
307
|
+
locals.set(String(to.n), x.t);
|
|
308
|
+
}
|
|
309
|
+
if (x.s === 'if') {
|
|
310
|
+
scan(x.then);
|
|
311
|
+
scan(x.else);
|
|
312
|
+
}
|
|
313
|
+
} };
|
|
314
|
+
scan(pre);
|
|
315
|
+
const fld = (n) => n.replace(/[^\w]/g, '_');
|
|
316
|
+
const rec = { name: `Frame$${name}`, short: `Frame$${name}`, fields: [...locals].map(([n, t]) => ({ name: fld(n), t })), methods: {}, kinds: ['dataclass'], own: true, module: this.lin[0].name, p };
|
|
317
|
+
this.frames.push(rec);
|
|
318
|
+
const M = self(`frames$${name}`, p), D = self('pending$', p), amount = String(mk.amount), ok = String(mk.ok), how = String(mk.how);
|
|
319
|
+
const v = (n) => ({ e: 'var', n, p }), int = (k) => ({ e: 'int', v: k, p });
|
|
320
|
+
const fail = (why) => ({ s: 'fail', p, why });
|
|
321
|
+
const bal = (op) => ({ s: 'set', p, to: self('balance', p), x: { e: 'bin', op, p, text: `balance ${op} value`, x: self('balance', p), y: v(amount) } });
|
|
322
|
+
const begin = [...pre, { s: 'if', p, c: { e: 'cmp', op: '<', p, text: 'balance < value', x: self('balance', p), y: v(amount) },
|
|
323
|
+
// (the contract holds less: the call fails at once, and no code runs)
|
|
324
|
+
then: [{ s: 'set', p, to: v(ok), x: { e: 'bool', v: false, p }, t: { k: 'bool' } }, ...(how === 'transfer' ? [fail(String(mk.why))] : []), ...rest],
|
|
325
|
+
else: [
|
|
326
|
+
bal('-'),
|
|
327
|
+
{ s: 'set', p, to: D, x: { e: 'bin', op: '+', p, text: 'pending$ + 1', x: D, y: int(1) } },
|
|
328
|
+
{ s: 'set', p, to: { e: 'idx', p, text: 'frames[pending$]', x: M, i: D }, x: { e: 'new', p, text: rec.name, rec: rec.name, fields: [...locals.keys()].map(n => [fld(n), v(n)]) } },
|
|
329
|
+
{ s: 'ret', p },
|
|
330
|
+
] }];
|
|
331
|
+
const f = '$f';
|
|
332
|
+
const resume = [
|
|
333
|
+
// (the call on top, this one's: else this is no request, the code returns from the last call first)
|
|
334
|
+
{ s: 'if', p, c: { e: 'cmp', op: '<', p, text: 'pending$ < 1', x: D, y: int(1) }, then: [fail('no call pending')], else: [] },
|
|
335
|
+
{ s: 'set', p, to: v(f), x: { e: 'idx', p, text: 'frames[pending$]', x: M, i: D } },
|
|
336
|
+
...[...locals.keys()].map((n) => ({ s: 'set', p, to: v(n), x: { e: 'get', p, text: `$f.${fld(n)}`, x: v(f), f: fld(n) } })),
|
|
337
|
+
{ s: 'del', p, x: { e: 'idx', p, text: 'frames[pending$]', x: M, i: D } },
|
|
338
|
+
{ s: 'set', p, to: D, x: { e: 'bin', op: '-', p, text: 'pending$ - 1', x: D, y: int(1) } },
|
|
339
|
+
{ s: 'set', p, to: v(ok), x: v('$ok'), t: { k: 'bool' } },
|
|
340
|
+
// (the callee reverted: the value is the contract's again; what the callee's own calls did stays, in the rule)
|
|
341
|
+
{ s: 'if', p, c: { e: 'not', p, strict: true, text: '!ok', x: v('$ok') }, then: [bal('+'), ...(how === 'transfer' ? [fail(String(mk.why))] : [])], else: [] },
|
|
342
|
+
...rest
|
|
343
|
+
];
|
|
344
|
+
this.funcs[`${id}$resume`] = { id: `${id}$resume`, name: `${name}$resume`, p, span: [p, 0, 0], params: [{ name: 'self', t: { k: 'rec', name: this.lin[0].name }, self: true }, { name: '$ok', t: { k: 'bool' } }], ret, body: resume, decorators: [] };
|
|
345
|
+
return { id, name, p, span: [p, 0, 0], params, ret, body: begin, decorators: [] };
|
|
346
|
+
}
|
|
347
|
+
// A function's body inside its modifiers: each modifier's body, `_;` the next one's (or the function's own).
|
|
348
|
+
withModifiers(f, mods, i) {
|
|
349
|
+
const m = mods.slice(i).find(x => this.defs.get(x.modifierName.referencedDeclaration)?.nodeType === 'ModifierDefinition');
|
|
350
|
+
if (!m)
|
|
351
|
+
return this.block(f.body);
|
|
352
|
+
const j = mods.indexOf(m), def = this.modDef(this.defs.get(m.modifierName.referencedDeclaration));
|
|
353
|
+
const out = [];
|
|
354
|
+
const args = (m.arguments ?? []);
|
|
355
|
+
def.parameters.parameters.forEach((pa, k) => out.push({ s: 'set', p: this.at(m), to: { e: 'var', n: pa.name, p: this.at(m) }, x: this.ex(args[k]) }));
|
|
356
|
+
const inner = this.withModifiers(f, mods, j + 1), stmts = def.body.statements;
|
|
357
|
+
const ph = stmts.findIndex(s => s.nodeType === 'PlaceholderStatement');
|
|
358
|
+
if (stmts.slice(ph + 1).length && hasReturn(inner))
|
|
359
|
+
this.no(f, `a return inside ${m.modifierName.name}, which runs code after _ (not yet)`);
|
|
360
|
+
for (const s of stmts)
|
|
361
|
+
out.push(...(s.nodeType === 'PlaceholderStatement' ? inner : this.stmt(s)));
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
modDef(d) { for (const c of this.lin)
|
|
365
|
+
for (const g of c.nodes)
|
|
366
|
+
if (g.nodeType === 'ModifierDefinition' && g.name === d.name)
|
|
367
|
+
return g; return d; }
|
|
368
|
+
ctor(k) {
|
|
369
|
+
const p = this.at(k), body = [];
|
|
370
|
+
const W = { e: 'var', n: MOD, p };
|
|
371
|
+
// The width: any value above the code's constants (fixed once the code is read: minW).
|
|
372
|
+
body.push(senderNonzero(p), { s: 'set', p, to: self(MOD, p), x: W });
|
|
373
|
+
const ctorOf = (c) => c.nodes.find(n => n.nodeType === 'FunctionDefinition' && n.kind === 'constructor');
|
|
374
|
+
const top = ctorOf(k);
|
|
375
|
+
// Arguments each base's constructor is given: in the inheritance list, or as a modifier of a constructor.
|
|
376
|
+
const given = new Map();
|
|
377
|
+
for (const c of this.lin) {
|
|
378
|
+
for (const b of (c.baseContracts ?? []))
|
|
379
|
+
if (b.arguments?.length)
|
|
380
|
+
given.set(b.baseName.referencedDeclaration, b.arguments);
|
|
381
|
+
const cf = ctorOf(c);
|
|
382
|
+
for (const m of (cf?.modifiers ?? []))
|
|
383
|
+
if (this.defs.get(m.modifierName.referencedDeclaration)?.nodeType === 'ContractDefinition')
|
|
384
|
+
given.set(m.modifierName.referencedDeclaration, m.arguments ?? []);
|
|
385
|
+
}
|
|
386
|
+
this.cur = { entry: true, payable: top?.stateMutability === 'payable', rets: [], tmp: 0 };
|
|
387
|
+
if (this.cur.payable)
|
|
388
|
+
this.ether = true;
|
|
389
|
+
for (const c of [...this.lin].reverse()) {
|
|
390
|
+
for (const n of c.nodes) {
|
|
391
|
+
if (n.nodeType !== 'VariableDeclaration' || n.constant)
|
|
392
|
+
continue;
|
|
393
|
+
const f = this.fields.find(x => x.decl === n);
|
|
394
|
+
if (f.t.k === 'opaque' || f.t.nested)
|
|
395
|
+
continue;
|
|
396
|
+
body.push({ s: 'set', p: this.at(n), to: self(f.name, this.at(n)), x: n.value ? this.ex(n.value) : f.t.k === 'map' ? { e: 'dict', keys: [], p: this.at(n), text: '{}' } : zero(f.t, this.at(n)) });
|
|
397
|
+
}
|
|
398
|
+
const cf = ctorOf(c);
|
|
399
|
+
if (!cf)
|
|
400
|
+
continue;
|
|
401
|
+
if (c !== k)
|
|
402
|
+
cf.parameters.parameters.forEach((pa, i) => { const a = given.get(c.id)?.[i]; if (!a)
|
|
403
|
+
this.no(cf, `${c.name}'s constructor given no ${pa.name}`); body.push({ s: 'set', p: this.at(cf), to: { e: 'var', n: pa.name, p: this.at(cf) }, x: this.ex(a) }); });
|
|
404
|
+
body.push(...this.withModifiers(cf, (cf.modifiers ?? []).filter(m => this.defs.get(m.modifierName.referencedDeclaration)?.nodeType === 'ModifierDefinition'), 0));
|
|
405
|
+
}
|
|
406
|
+
if (this.ether)
|
|
407
|
+
body.splice(1, 0, { s: 'set', p, to: self('balance', p), x: this.cur.payable ? { e: 'var', n: 'msg.value', p } : { e: 'int', v: 0, p } });
|
|
408
|
+
// (no call pending at the start)
|
|
409
|
+
for (const fr of this.frames)
|
|
410
|
+
body.push({ s: 'set', p, to: self(`frames$${fr.name.slice('Frame$'.length)}`, p), x: { e: 'dict', keys: [], p, text: '{}' } });
|
|
411
|
+
if (this.frames.length)
|
|
412
|
+
body.push({ s: 'set', p, to: self('pending$', p), x: { e: 'int', v: 0, p } });
|
|
413
|
+
// (the width above every constant the code reads: a constant is below it, as the type's are)
|
|
414
|
+
body.unshift({ s: 'if', p, c: { e: 'cmp', op: '<', p, text: `${MOD} >= ${this.minW}`, x: W, y: { e: 'int', v: this.minW, p } }, then: [{ s: 'fail', p, why: `the width ${MOD} (2^256) is at least ${this.minW}` }], else: [] });
|
|
415
|
+
const params = [{ name: 'self', t: { k: 'rec', name: k.name }, self: true }, { name: MOD, t: { k: 'int' } }, { name: 'msg.sender', t: this.ADDR }, ...(this.cur.payable ? [{ name: 'msg.value', t: U256 }] : [])];
|
|
416
|
+
for (const pa of (top?.parameters.parameters ?? []))
|
|
417
|
+
params.push({ name: pa.name, t: this.ty(pa.typeDescriptions.typeString, pa) });
|
|
418
|
+
return { id: '__init__', name: '__init__', p, span: [p, 0, 0], params, ret: { k: 'none' }, body, decorators: [] };
|
|
419
|
+
}
|
|
420
|
+
// --- statements ------------------------------------------------------------------------------------------------------
|
|
421
|
+
block(b) { const was = this.unchecked; if (b.nodeType === 'UncheckedBlock')
|
|
422
|
+
this.unchecked = true; try {
|
|
423
|
+
return b.statements.flatMap(s => this.stmt(s));
|
|
424
|
+
}
|
|
425
|
+
finally {
|
|
426
|
+
this.unchecked = was;
|
|
427
|
+
} }
|
|
428
|
+
stmt(n) {
|
|
429
|
+
const p = this.at(n);
|
|
430
|
+
switch (n.nodeType) {
|
|
431
|
+
case 'Block':
|
|
432
|
+
case 'UncheckedBlock': return this.block(n);
|
|
433
|
+
case 'EmitStatement': return [];
|
|
434
|
+
case 'PlaceholderStatement': return this.no(n, '_ outside a modifier');
|
|
435
|
+
case 'RevertStatement': return [{ s: 'fail', p, why: `revert ${this.text(n.errorCall).replace(/^revert /, '')}` }];
|
|
436
|
+
case 'Return': {
|
|
437
|
+
if (!n.expression)
|
|
438
|
+
return [{ s: 'ret', p, ...(this.cur.rets.length ? { x: { e: 'var', n: this.cur.rets[0], p } } : {}) }];
|
|
439
|
+
return [{ s: 'ret', p, x: this.ex(n.expression) }];
|
|
440
|
+
}
|
|
441
|
+
case 'IfStatement': return [{ s: 'if', p, c: this.ex(n.condition), then: n.trueBody ? this.stmt(n.trueBody) : [], else: n.falseBody ? this.stmt(n.falseBody) : [] }];
|
|
442
|
+
case 'VariableDeclarationStatement': {
|
|
443
|
+
const ds = n.declarations, v = n.initialValue;
|
|
444
|
+
if (v && isValueCall(v))
|
|
445
|
+
return this.valueCall(v, ds);
|
|
446
|
+
if (ds.length !== 1 || !ds[0])
|
|
447
|
+
return this.no(n, 'a tuple declared (the subset reads one variable)');
|
|
448
|
+
const d = ds[0], t = this.ty(d.typeDescriptions.typeString, d);
|
|
449
|
+
return [{ s: 'set', p, to: { e: 'var', n: d.name, p }, x: v ? this.ex(v) : zero(t, p), t }];
|
|
450
|
+
}
|
|
451
|
+
case 'ExpressionStatement': return this.exprStmt(n.expression);
|
|
452
|
+
case 'ForStatement':
|
|
453
|
+
case 'WhileStatement':
|
|
454
|
+
case 'DoWhileStatement': return this.no(n, 'a loop (outside the Solidity subset)');
|
|
455
|
+
case 'InlineAssembly': return this.no(n, 'inline assembly');
|
|
456
|
+
case 'TryStatement': return this.no(n, 'try/catch (a call of another contract)');
|
|
457
|
+
}
|
|
458
|
+
return this.no(n, `a ${n.nodeType} (outside the Solidity subset)`);
|
|
459
|
+
}
|
|
460
|
+
exprStmt(e) {
|
|
461
|
+
const p = this.at(e);
|
|
462
|
+
if (e.nodeType === 'FunctionCall' && e.expression.nodeType === 'Identifier' && ['require', 'assert'].includes(e.expression.name)) {
|
|
463
|
+
return [{ s: 'if', p, c: { e: 'not', p, strict: true, text: this.text(e), x: this.ex(e.arguments[0]) }, then: [{ s: 'fail', p, why: this.text(e) }], else: [] }];
|
|
464
|
+
}
|
|
465
|
+
if (e.nodeType === 'FunctionCall' && e.expression.nodeType === 'Identifier' && e.expression.name === 'revert')
|
|
466
|
+
return [{ s: 'fail', p, why: this.text(e) }];
|
|
467
|
+
if (isValueCall(e))
|
|
468
|
+
return this.valueCall(e, []);
|
|
469
|
+
if (e.nodeType === 'FunctionCall' && e.expression.nodeType === 'MemberAccess' && e.expression.memberName === 'transfer' && /^address/.test(e.expression.expression.typeDescriptions.typeString))
|
|
470
|
+
return this.valueCall(e, [], 'transfer');
|
|
471
|
+
if (e.nodeType === 'Assignment')
|
|
472
|
+
return this.assign(e);
|
|
473
|
+
if (e.nodeType === 'UnaryOperation' && ['++', '--'].includes(e.operator))
|
|
474
|
+
return this.assign({ ...e, nodeType: 'Assignment', operator: e.operator === '++' ? '+=' : '-=', leftHandSide: e.subExpression, rightHandSide: { nodeType: 'Literal', kind: 'number', value: '1', id: -1, src: e.src, typeDescriptions: { typeString: 'int_const 1' } } });
|
|
475
|
+
if (e.nodeType === 'FunctionCall')
|
|
476
|
+
return [{ s: 'expr', p, x: this.ex(e) }];
|
|
477
|
+
if (e.nodeType === 'TupleExpression' && e.components.length === 1)
|
|
478
|
+
return this.exprStmt(e.components[0]);
|
|
479
|
+
return this.no(e, 'an expression statement the subset doesn\'t read');
|
|
480
|
+
}
|
|
481
|
+
// A value sent to an address: `(bool ok, ) = a.call{value: v}("")`, `a.send(v)`, `payable(a).transfer(v)`. The
|
|
482
|
+
// address called is an account without code: the value moves where the contract holds it (ok), else nothing does.
|
|
483
|
+
calls = false;
|
|
484
|
+
valueCall(e, ds, how = 'call') {
|
|
485
|
+
const p = this.at(e);
|
|
486
|
+
this.ether = true;
|
|
487
|
+
this.calls = true;
|
|
488
|
+
const target = e.expression.nodeType === 'FunctionCallOptions' ? e.expression.expression : e.expression;
|
|
489
|
+
let value;
|
|
490
|
+
if (e.expression.nodeType === 'FunctionCallOptions')
|
|
491
|
+
value = e.expression.options[e.expression.names.indexOf('value')];
|
|
492
|
+
else if (target.memberName === 'send' || target.memberName === 'transfer') {
|
|
493
|
+
value = e.arguments[0];
|
|
494
|
+
how = target.memberName;
|
|
495
|
+
}
|
|
496
|
+
if (how === 'call' && e.arguments.length && !(e.arguments[0].nodeType === 'Literal' && (e.arguments[0].value ?? '') === ''))
|
|
497
|
+
this.no(e, 'a call with data (a call of another contract)');
|
|
498
|
+
const v = value ? this.ex(value) : { e: 'int', v: 0, p };
|
|
499
|
+
const okName = ds[0]?.name ?? `$ok${this.cur.tmp++}`;
|
|
500
|
+
if (ds.slice(1).some(Boolean))
|
|
501
|
+
this.no(e, 'the data a call returns (the subset reads its ok)');
|
|
502
|
+
const amount = `$amount${this.cur.tmp++}`, has = { e: 'cmp', op: '<=', p, text: 'balance >= value', x: { e: 'var', n: amount, p }, y: self('balance', p) };
|
|
503
|
+
if (this.reenter)
|
|
504
|
+
return [
|
|
505
|
+
{ s: 'set', p, to: { e: 'var', n: amount, p }, x: v, t: U256 },
|
|
506
|
+
{ s: 'expr', p, x: this.ex(target.expression) },
|
|
507
|
+
{ s: 'callout', p, amount, ok: okName, how, why: `${this.text(e)}: the call failed (transfer reverts)` },
|
|
508
|
+
];
|
|
509
|
+
const out = [
|
|
510
|
+
{ s: 'set', p, to: { e: 'var', n: amount, p }, x: v },
|
|
511
|
+
// (the address is evaluated: what it reads is read; an account without code accepts the value)
|
|
512
|
+
{ s: 'expr', p, x: this.ex(target.expression) },
|
|
513
|
+
{ s: 'set', p, to: { e: 'var', n: okName, p }, x: has, t: { k: 'bool' } },
|
|
514
|
+
{ s: 'if', p, c: { e: 'var', n: okName, p }, then: [{ s: 'set', p, to: self('balance', p), x: { e: 'bin', op: '-', p, text: 'balance - value', x: self('balance', p), y: { e: 'var', n: amount, p } } }], else: how === 'transfer' ? [{ s: 'fail', p, why: `${this.text(e)}: the contract holds less than the value (transfer reverts)` }] : [] },
|
|
515
|
+
];
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
assign(e) {
|
|
519
|
+
const p = this.at(e), op = e.operator, lhs = e.leftHandSide;
|
|
520
|
+
let x = this.ex(e.rightHandSide);
|
|
521
|
+
if (op !== '=')
|
|
522
|
+
x = this.arith(op.slice(0, -1), this.ex(lhs), x, e, lhs.typeDescriptions.typeString);
|
|
523
|
+
const to = this.place(lhs);
|
|
524
|
+
if (!to)
|
|
525
|
+
return [];
|
|
526
|
+
return [{ s: 'set', p, to, x, ...(lhs.nodeType === 'Identifier' && !this.fieldOf(lhs) ? { t: this.ty(lhs.typeDescriptions.typeString, lhs) } : {}) }];
|
|
527
|
+
}
|
|
528
|
+
fieldOf(n) { return n.nodeType === 'Identifier' ? this.fields.find(f => f.decl.id === n.referencedDeclaration) : undefined; }
|
|
529
|
+
// Where an assignment writes: a local, a state variable, a mapping's cell (undefined: a string's, left out).
|
|
530
|
+
place(n) {
|
|
531
|
+
const p = this.at(n);
|
|
532
|
+
if (n.nodeType === 'Identifier') {
|
|
533
|
+
const f = this.fieldOf(n);
|
|
534
|
+
if (f)
|
|
535
|
+
return f.t.k === 'opaque' ? (/string|bytes/.test(f.sol) ? undefined : this.no(n, f.t.why)) : self(f.name, p);
|
|
536
|
+
return { e: 'var', n: n.name, p };
|
|
537
|
+
}
|
|
538
|
+
if (n.nodeType === 'IndexAccess') {
|
|
539
|
+
if (this.nestedOf(n)) {
|
|
540
|
+
this.leftOut.add(`${this.text(n)} (${p}): a write to a mapping of mappings, left out`);
|
|
541
|
+
return undefined;
|
|
542
|
+
}
|
|
543
|
+
const [m, k] = this.cell(n);
|
|
544
|
+
return { e: 'idx', p, text: this.text(n), x: m, i: k, nz: true };
|
|
545
|
+
}
|
|
546
|
+
if (n.nodeType === 'TupleExpression' && n.components.length === 1)
|
|
547
|
+
return this.place(n.components[0]);
|
|
548
|
+
return this.no(n, 'an assignment to other than a variable or a mapping\'s cell');
|
|
549
|
+
}
|
|
550
|
+
// A mapping of mappings' field, where a node is one of its cells (m[a][b]).
|
|
551
|
+
nestedOf(n) {
|
|
552
|
+
const b = n.baseExpression;
|
|
553
|
+
if (b?.nodeType !== 'IndexAccess')
|
|
554
|
+
return undefined;
|
|
555
|
+
const f = b.baseExpression?.nodeType === 'Identifier' ? this.fieldOf(b.baseExpression) : undefined;
|
|
556
|
+
return f && f.t.nested ? f : undefined;
|
|
557
|
+
}
|
|
558
|
+
// A cell of a mapping of mappings read: any value of its type, an input of the request (one a step: a second read in
|
|
559
|
+
// one step is refused), its writes left out; the check sets the code's cells to it before the call. (A key of two
|
|
560
|
+
// numbers, a·K + b, is linear but the kernel's maps take it slowly; the laws read no such map.)
|
|
561
|
+
leftOut = new Set();
|
|
562
|
+
havocRead(n, f) {
|
|
563
|
+
const p = this.at(n), val = f.t.val;
|
|
564
|
+
this.nested.add(f.name);
|
|
565
|
+
return { e: 'call', p, text: this.text(n), f: { e: 'ext', p, q: f.name, text: f.name, patch: { mod: this.lin[0].name, path: [f.name] } }, args: [], kw: [], ...(val.k === 'int' && val.bits !== undefined ? { ity: { bits: val.bits, signed: !!val.signed, ...(val.mod ? { mod: val.mod } : {}) } } : {}) };
|
|
566
|
+
}
|
|
567
|
+
// A mapping's cell: the map and its key.
|
|
568
|
+
cell(n) {
|
|
569
|
+
const p = this.at(n), b = n.baseExpression;
|
|
570
|
+
if (b.nodeType === 'Identifier') {
|
|
571
|
+
const f = this.fieldOf(b);
|
|
572
|
+
if (!f || f.t.k !== 'map')
|
|
573
|
+
return this.no(n, f?.t.k === 'opaque' ? f.t.why : 'an index of other than a state mapping');
|
|
574
|
+
return [self(f.name, p), this.ex(n.indexExpression)];
|
|
575
|
+
}
|
|
576
|
+
return this.no(n, 'an index of other than a state mapping');
|
|
577
|
+
}
|
|
578
|
+
// --- expressions -----------------------------------------------------------------------------------------------------
|
|
579
|
+
ex(n) {
|
|
580
|
+
const p = this.at(n), text = this.text(n);
|
|
581
|
+
const ts = n.typeDescriptions?.typeString ?? '';
|
|
582
|
+
// A constant the compiler folds (10**18, 1 days): its value, where it is a safe integer.
|
|
583
|
+
if (/^int_const /.test(ts) && n.nodeType !== 'Literal' && n.nodeType !== 'Identifier')
|
|
584
|
+
return this.lit(ts.slice(10), n);
|
|
585
|
+
switch (n.nodeType) {
|
|
586
|
+
case 'Literal': {
|
|
587
|
+
if (n.kind === 'bool')
|
|
588
|
+
return { e: 'bool', v: n.value === 'true', p };
|
|
589
|
+
if (n.kind === 'number')
|
|
590
|
+
return this.lit(/^int_const /.test(ts) ? ts.slice(10) : n.value, n);
|
|
591
|
+
return { e: 'opaque', p, why: `${text}: a string` };
|
|
592
|
+
}
|
|
593
|
+
case 'Identifier': {
|
|
594
|
+
const d = this.defs.get(n.referencedDeclaration);
|
|
595
|
+
if (n.name === 'msg' || n.name === 'block' || n.name === 'tx')
|
|
596
|
+
return this.no(n, `${n.name} alone`);
|
|
597
|
+
if (this.consts.has(n.referencedDeclaration))
|
|
598
|
+
return this.consts.get(n.referencedDeclaration);
|
|
599
|
+
const f = this.fieldOf(n);
|
|
600
|
+
if (f)
|
|
601
|
+
return f.t.k === 'opaque' ? { e: 'opaque', p, why: `${n.name}: ${f.t.why}` } : self(f.name, p);
|
|
602
|
+
if (d?.nodeType === 'FunctionDefinition')
|
|
603
|
+
return this.no(n, 'a function as a value');
|
|
604
|
+
if (n.name === 'this')
|
|
605
|
+
return this.no(n, 'the contract\'s own address (not yet)');
|
|
606
|
+
return { e: 'var', n: n.name, p };
|
|
607
|
+
}
|
|
608
|
+
case 'TupleExpression':
|
|
609
|
+
if (n.components.length === 1)
|
|
610
|
+
return this.ex(n.components[0]);
|
|
611
|
+
return this.no(n, 'a tuple');
|
|
612
|
+
case 'UnaryOperation': {
|
|
613
|
+
if (n.operator === '!')
|
|
614
|
+
return { e: 'not', p, text, strict: true, x: this.ex(n.subExpression) };
|
|
615
|
+
return this.no(n, `${n.operator} (as a value)`);
|
|
616
|
+
}
|
|
617
|
+
case 'BinaryOperation': {
|
|
618
|
+
const op = n.operator, a = this.ex(n.leftExpression), b = this.ex(n.rightExpression);
|
|
619
|
+
if (['<', '<=', '>', '>='].includes(op) && /^address/.test(n.leftExpression.typeDescriptions.typeString))
|
|
620
|
+
return this.no(n, 'addresses ordered (the subset compares them for equality)');
|
|
621
|
+
if (['<', '<=', '>', '>=', '==', '!='].includes(op))
|
|
622
|
+
return { e: 'cmp', op, p, text, x: a, y: b };
|
|
623
|
+
if (op === '&&' || op === '||')
|
|
624
|
+
return { e: op === '&&' ? 'and' : 'or', p, text, xs: [a, b] };
|
|
625
|
+
if (['+', '-', '*', '/', '%'].includes(op))
|
|
626
|
+
return this.arith(op, a, b, n, ts);
|
|
627
|
+
return this.no(n, `${op}: a bit operation (outside the subset)`);
|
|
628
|
+
}
|
|
629
|
+
case 'Conditional': return { e: 'ite', p, text, c: this.ex(n.condition), a: this.ex(n.trueExpression), b: this.ex(n.falseExpression) };
|
|
630
|
+
case 'IndexAccess': {
|
|
631
|
+
const nf = this.nestedOf(n);
|
|
632
|
+
if (nf)
|
|
633
|
+
return this.havocRead(n, nf);
|
|
634
|
+
const [m, k] = this.cell(n), vt = this.ty(ts, n);
|
|
635
|
+
return { e: 'call', p, text, f: { e: 'get', p, text, x: m, f: 'get' }, args: [k, zero(vt, p)], kw: [] };
|
|
636
|
+
}
|
|
637
|
+
case 'MemberAccess': return this.member(n);
|
|
638
|
+
case 'FunctionCall': return this.call(n);
|
|
639
|
+
case 'Assignment': return this.no(n, 'an assignment used as a value');
|
|
640
|
+
}
|
|
641
|
+
return this.no(n, `a ${n.nodeType} (outside the Solidity subset)`);
|
|
642
|
+
}
|
|
643
|
+
lit(v, n) {
|
|
644
|
+
const x = Number(v);
|
|
645
|
+
if (!/^-?\d+$/.test(v) || !Number.isSafeInteger(x))
|
|
646
|
+
return this.no(n, `the constant ${v.length > 30 ? `${v.slice(0, 12)}…` : v} (past the rule's 2^53, or not whole)`);
|
|
647
|
+
if (x >= this.minW)
|
|
648
|
+
this.minW = x + 1;
|
|
649
|
+
return { e: 'int', v: x, p: this.at(n) };
|
|
650
|
+
}
|
|
651
|
+
arith(op, a, b, n, ts) {
|
|
652
|
+
const t = this.ty(ts, n);
|
|
653
|
+
if (t.k !== 'int')
|
|
654
|
+
return this.no(n, `${op} of a ${ts}`);
|
|
655
|
+
const ity = t.bits === undefined ? undefined : { bits: t.bits, signed: t.signed ?? false, name: ts, ...(t.mod ? { mod: t.mod } : {}) };
|
|
656
|
+
return { e: 'bin', op, p: this.at(n), text: this.text(n), x: a, y: b, ...(ity ? { ovf: this.unchecked && op !== '/' && op !== '%' ? 'wrap' : 'trap', ity, trap: 'a panic: an arithmetic overflow reverts' } : {}) };
|
|
657
|
+
}
|
|
658
|
+
member(n) {
|
|
659
|
+
const p = this.at(n), e = n.expression, m = n.memberName;
|
|
660
|
+
if (e.nodeType === 'Identifier' && e.name === 'msg') {
|
|
661
|
+
if (m === 'sender')
|
|
662
|
+
return { e: 'var', n: 'msg.sender', p };
|
|
663
|
+
if (m === 'value')
|
|
664
|
+
return this.cur.entry && !this.cur.payable ? { e: 'int', v: 0, p } : { e: 'var', n: 'msg.value', p };
|
|
665
|
+
return this.no(n, `msg.${m}`);
|
|
666
|
+
}
|
|
667
|
+
if (e.nodeType === 'Identifier' && e.name === 'block' && m === 'timestamp')
|
|
668
|
+
return { e: 'clock', p, text: 'block.timestamp' };
|
|
669
|
+
if (m === 'balance' && e.nodeType === 'FunctionCall' && e.kind === 'typeConversion' && e.arguments[0]?.nodeType === 'Identifier' && e.arguments[0].name === 'this') {
|
|
670
|
+
this.ether = true;
|
|
671
|
+
return self('balance', p);
|
|
672
|
+
}
|
|
673
|
+
// type(uint256).max: the width less one; .min of an unsigned type: 0.
|
|
674
|
+
if (e.nodeType === 'FunctionCall' && e.expression.nodeType === 'Identifier' && e.expression.name === 'type') {
|
|
675
|
+
const t = this.ty(e.arguments[0].typeDescriptions.typeString.replace(/^type\((.*)\)$/, '$1'), n);
|
|
676
|
+
if (t.k === 'int' && !t.signed && m === 'min')
|
|
677
|
+
return { e: 'int', v: 0, p };
|
|
678
|
+
if (t.k === 'int' && t.mod && m === 'max')
|
|
679
|
+
return { e: 'bin', op: '-', p, text: 'type(uint256).max', x: self(MOD, p), y: { e: 'int', v: 1, p } };
|
|
680
|
+
if (t.k === 'int' && t.bits !== undefined && t.bits <= 48 && m === 'max')
|
|
681
|
+
return { e: 'int', v: t.signed ? 2 ** (t.bits - 1) - 1 : 2 ** t.bits - 1, p };
|
|
682
|
+
if (t.k === 'int' && t.bits !== undefined && t.bits <= 48 && m === 'min')
|
|
683
|
+
return { e: 'int', v: -(2 ** (t.bits - 1)), p };
|
|
684
|
+
return this.no(n, `type(...).${m}`);
|
|
685
|
+
}
|
|
686
|
+
// An enum's value.
|
|
687
|
+
const d = this.defs.get(n.referencedDeclaration);
|
|
688
|
+
if (d?.nodeType === 'EnumValue') {
|
|
689
|
+
const en = this.defs.get(e.referencedDeclaration);
|
|
690
|
+
return { e: 'variant', p, v: m, values: en?.members?.map(x => x.name) ?? [m] };
|
|
691
|
+
}
|
|
692
|
+
return this.no(n, `.${m} (outside the Solidity subset)`);
|
|
693
|
+
}
|
|
694
|
+
call(n) {
|
|
695
|
+
const p = this.at(n), text = this.text(n), f = n.expression;
|
|
696
|
+
if (n.kind === 'typeConversion') {
|
|
697
|
+
const a = n.arguments[0], to = n.typeDescriptions.typeString, from = a.typeDescriptions.typeString;
|
|
698
|
+
if (/^address/.test(to) && a.nodeType === 'Literal' && Number(a.value) === 0)
|
|
699
|
+
return { e: 'int', v: 0, p };
|
|
700
|
+
if (/^address/.test(to) && /^address/.test(from))
|
|
701
|
+
return this.ex(a);
|
|
702
|
+
const tt = this.ty(to, n), ft = this.ty(from, a);
|
|
703
|
+
// (a widening of an unsigned value: the same number)
|
|
704
|
+
if (tt.k === 'int' && ft.k === 'int' && !tt.signed && !ft.signed && (tt.mod || (ft.bits !== undefined && tt.bits !== undefined && ft.bits <= tt.bits)) && !(ft.mod && !tt.mod))
|
|
705
|
+
return { e: 'as', p, x: this.ex(a), ity: { bits: tt.bits ?? 0, signed: false, ...(tt.mod ? { mod: tt.mod } : {}) } };
|
|
706
|
+
if (/^int_const/.test(from) && tt.k === 'int')
|
|
707
|
+
return this.ex(a);
|
|
708
|
+
return this.no(n, `a conversion of ${from} to ${to}`);
|
|
709
|
+
}
|
|
710
|
+
if (n.kind === 'structConstructorCall')
|
|
711
|
+
return this.no(n, 'a struct made');
|
|
712
|
+
if (f.nodeType === 'Identifier') {
|
|
713
|
+
const d = this.defs.get(f.referencedDeclaration);
|
|
714
|
+
if (d?.nodeType === 'FunctionDefinition')
|
|
715
|
+
return this.internal(d, n.arguments, n);
|
|
716
|
+
if (d?.nodeType === 'EventDefinition' || d?.nodeType === 'ErrorDefinition')
|
|
717
|
+
return this.no(n, 'an event or an error made');
|
|
718
|
+
return this.no(n, `${f.name}(...) (outside the Solidity subset)`);
|
|
719
|
+
}
|
|
720
|
+
if (f.nodeType === 'MemberAccess') {
|
|
721
|
+
const d = this.defs.get(f.referencedDeclaration);
|
|
722
|
+
// super.f(...) and Base.f(...): the function named, not the most derived override.
|
|
723
|
+
if (d?.nodeType === 'FunctionDefinition' && f.expression.nodeType === 'Identifier' && (f.expression.name === 'super' || this.defs.get(f.expression.referencedDeclaration)?.nodeType === 'ContractDefinition'))
|
|
724
|
+
return this.internal(d, n.arguments, n, f.expression.name === 'super' ? 'super' : 'base');
|
|
725
|
+
if (f.expression.nodeType === 'Identifier' && f.expression.name === 'this')
|
|
726
|
+
return this.no(n, 'this.f(...): an external call of the contract itself (not yet)');
|
|
727
|
+
if (isValueCall(n))
|
|
728
|
+
return this.no(n, 'a value sent inside an expression (the subset reads it as its own statement)');
|
|
729
|
+
return this.no(n, `${text}: a call of another contract (outside the Solidity subset)`);
|
|
730
|
+
}
|
|
731
|
+
return this.no(n, `${text}: a call the subset doesn't read`);
|
|
732
|
+
}
|
|
733
|
+
// An internal call: inlined, with self, msg.sender and msg.value.
|
|
734
|
+
internal(d, args, n, how = 'virtual') {
|
|
735
|
+
const p = this.at(n);
|
|
736
|
+
let id = how === 'virtual' ? this.fnId(d) : `f${d.id}`;
|
|
737
|
+
if (how === 'super') {
|
|
738
|
+
// The next override along the linearization after the contract that calls it.
|
|
739
|
+
const sig = `${d.name}(${d.parameters.parameters.map(x => x.typeDescriptions.typeString).join(',')})`;
|
|
740
|
+
const from = this.lin.findIndex(c => c.nodes.some(g => g.id === this.containing(n)));
|
|
741
|
+
const next = this.lin.slice(from + 1).flatMap(c => c.nodes.filter(g => g.nodeType === 'FunctionDefinition' && g.body && `${g.name}(${g.parameters.parameters.map(x => x.typeDescriptions.typeString).join(',')})` === sig))[0];
|
|
742
|
+
if (!next)
|
|
743
|
+
this.no(n, 'super of no implementation');
|
|
744
|
+
id = `f${next.id}`;
|
|
745
|
+
}
|
|
746
|
+
if (!this.funcs[id]) {
|
|
747
|
+
const def = [...this.defs.values()].find(g => `f${g.id}` === id);
|
|
748
|
+
if (!def?.body)
|
|
749
|
+
return this.no(n, `${d.name}: a function with no body (an interface's)`);
|
|
750
|
+
this.funcs[id] = { id, name: def.name, p, span: [p, 0, 0], params: [], ret: { k: 'none' }, body: [], decorators: [] };
|
|
751
|
+
const saved = this.cur;
|
|
752
|
+
this.funcs[id] = this.fn(def, id, false);
|
|
753
|
+
this.cur = saved;
|
|
754
|
+
}
|
|
755
|
+
const mv = this.cur.entry && !this.cur.payable ? { e: 'int', v: 0, p } : { e: 'var', n: 'msg.value', p };
|
|
756
|
+
return { e: 'call', p, text: this.text(n), f: { e: 'fn', id, p }, args: [{ e: 'var', n: 'self', p }, { e: 'var', n: 'msg.sender', p }, mv, ...args.map(a => this.ex(a))], kw: [] };
|
|
757
|
+
}
|
|
758
|
+
// The function a node is inside.
|
|
759
|
+
containing(n) {
|
|
760
|
+
const [s] = String(n.src).split(':').map(Number);
|
|
761
|
+
for (const c of this.lin)
|
|
762
|
+
for (const g of c.nodes) {
|
|
763
|
+
const [gs, gl] = String(g.src).split(':').map(Number);
|
|
764
|
+
if (g.nodeType === 'FunctionDefinition' && s >= gs && s < gs + gl && String(g.src).split(':')[2] === String(n.src).split(':')[2])
|
|
765
|
+
return g.id;
|
|
766
|
+
}
|
|
767
|
+
return -1;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
// (no transaction is sent from address(0): a request from it is no request)
|
|
771
|
+
const senderNonzero = (p) => ({ s: 'if', p, c: { e: 'cmp', op: '==', p, text: 'msg.sender == address(0)', x: { e: 'var', n: 'msg.sender', p }, y: { e: 'int', v: 0, p } }, then: [{ s: 'fail', p, why: 'msg.sender is never address(0)' }], else: [] });
|
|
772
|
+
const self = (f, p) => ({ e: 'get', p, text: `self.${f}`, x: { e: 'var', n: 'self', p }, f });
|
|
773
|
+
const zero = (t, p) => (t.k === 'bool' ? { e: 'bool', v: false, p } : t.k === 'choice' ? { e: 'variant', p, v: t.values[0], values: t.values } : { e: 'int', v: 0, p });
|
|
774
|
+
const scalarT = (t) => t.k === 'int' || t.k === 'bool' || t.k === 'choice';
|
|
775
|
+
const topArrow = (s) => { let d = 0; for (let i = 0; i < s.length; i++) {
|
|
776
|
+
if (s[i] === '(')
|
|
777
|
+
d++;
|
|
778
|
+
else if (s[i] === ')')
|
|
779
|
+
d--;
|
|
780
|
+
else if (d === 0 && s.startsWith('=>', i))
|
|
781
|
+
return i;
|
|
782
|
+
} return -1; };
|
|
783
|
+
const isValueCall = (e) => e.nodeType === 'FunctionCall' && ((e.expression.nodeType === 'FunctionCallOptions' && e.expression.expression.nodeType === 'MemberAccess' && e.expression.expression.memberName === 'call') || (e.expression.nodeType === 'MemberAccess' && e.expression.memberName === 'send' && /^address/.test(e.expression.expression.typeDescriptions.typeString)));
|
|
784
|
+
const callsOut = (ss) => ss.some(s => s.s === 'callout' || (s.s === 'if' && (callsOut(s.then) || callsOut(s.else))));
|
|
785
|
+
const hasReturn = (ss) => ss.some(s => s.s === 'ret' || (s.s === 'if' && (hasReturn(s.then) || hasReturn(s.else))));
|
|
786
|
+
// The ABI's name of a type.
|
|
787
|
+
const abiType = (ts) => (ts.startsWith('address') ? 'address' : ts.startsWith('enum ') ? 'uint8' : ts.startsWith('contract ') ? 'address' : ts.replace(/ (storage|memory|calldata).*$/, ''));
|
|
788
|
+
// --- the front end ---------------------------------------------------------------------------------------------------
|
|
789
|
+
export function readSolidity(file, o = {}, reenter = false, compiled) {
|
|
790
|
+
const c = compiled ?? compile(file, o);
|
|
791
|
+
const L = new Lower(c, file, reenter);
|
|
792
|
+
const entry = typeof o.entry === 'string' ? o.entry : undefined;
|
|
793
|
+
const { mod, meta } = L.module(entry);
|
|
794
|
+
return { mod, meta, c };
|
|
795
|
+
}
|
|
796
|
+
export function extractSolidity(at, opts = {}) {
|
|
797
|
+
const file = pathOf(at);
|
|
798
|
+
let r;
|
|
799
|
+
try {
|
|
800
|
+
r = readSolidity(file, opts);
|
|
801
|
+
}
|
|
802
|
+
catch (e) {
|
|
803
|
+
if (e instanceof Refusal)
|
|
804
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
|
|
805
|
+
throw e;
|
|
806
|
+
}
|
|
807
|
+
const { mod, meta, c } = r;
|
|
808
|
+
const out = c.contracts[meta.source]?.[meta.contract];
|
|
809
|
+
const harness = (read) => {
|
|
810
|
+
read.arms.length = 0;
|
|
811
|
+
read.model.notes.push(...boundaryNotes(meta));
|
|
812
|
+
if (!out)
|
|
813
|
+
return { cmd: 'false', args: [], hello: {}, error: `solc made no bytecode for ${meta.contract}` };
|
|
814
|
+
const types = out.storageLayout.types;
|
|
815
|
+
const slots = Object.fromEntries(out.storageLayout.storage.map(s => [s.label, { slot: s.slot, offset: s.offset, bytes: Number(types[s.type]?.numberOfBytes ?? 32), map: types[s.type]?.encoding === 'mapping', nested: meta.nested.includes(s.label), type: s.type }]));
|
|
816
|
+
const kinds = Object.fromEntries(meta.fields.map(f => [f.name, kindOf(f.t, f.sol)]));
|
|
817
|
+
const mapKeys = Object.fromEntries(meta.fields.filter(f => f.sol.startsWith('mapping(')).map(f => [f.name, keyKinds(f.sol)]));
|
|
818
|
+
return { cmd: opts.python ?? 'python3', args: [new URL('./sol/harness.py', import.meta.url).pathname], env: { ...(opts.anvil ? { GDP_ANVIL: opts.anvil } : {}) },
|
|
819
|
+
hello: { sol: { creation: out.evm.bytecode.object, abi: out.abi, ids: out.evm.methodIdentifiers, slots, kinds, mapKeys, havoc: meta.nested, havocBy: havocBy(mod), mod: MOD, minW: meta.minW, addrBits: meta.addrBits, entries: meta.entries, ctor: meta.ctor, ether: meta.ether } } };
|
|
820
|
+
};
|
|
821
|
+
// (methods: the external functions that may write the state, unless named)
|
|
822
|
+
const methods = opts.methods ?? Object.keys(meta.entries);
|
|
823
|
+
// (the check's probes: the branches' conditions, each a state and request the prover finds; a revert's condition
|
|
824
|
+
// holds at no step the rule takes, and a contract's rule is large)
|
|
825
|
+
const havoc = Object.fromEntries(meta.fields.filter(f => meta.nested.includes(f.name)).map(f => [f.name, f.t.val.k === 'bool' ? 'bool' : 'int']));
|
|
826
|
+
const o = { ...opts, methods, strict: true, onError: 'discard', entry: meta.contract, check: { probes: 'writes', ...opts.check }, answers: { ...havoc, ...opts.answers } };
|
|
827
|
+
// extractStep's run, the width's param fixed for the check's own draws (2^52: the proof is for every width)
|
|
828
|
+
const notes = [];
|
|
829
|
+
let read;
|
|
830
|
+
try {
|
|
831
|
+
read = readStep(mod, o);
|
|
832
|
+
}
|
|
833
|
+
catch (e) {
|
|
834
|
+
if (e instanceof Refusal)
|
|
835
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
836
|
+
throw e;
|
|
837
|
+
}
|
|
838
|
+
const w = read.model.params.find(v => v.name.startsWith(MOD));
|
|
839
|
+
if (w)
|
|
840
|
+
w.derived = { op: 'const', v: CHECK_W };
|
|
841
|
+
// (an unsigned value is a natural, wrapped where it would go below 0: its state and its mappings' cells naturals, by
|
|
842
|
+
// the rule's names of the code's fields)
|
|
843
|
+
const unsignedField = new Set([...meta.fields, ...(meta.ether ? [{ name: 'balance', t: U256 }] : [])].filter(f => { const t = f.t.k === 'map' ? f.t.val : f.t; return t.k === 'int' && t.bits !== undefined && !t.signed; }).map(f => f.name));
|
|
844
|
+
const nats = (r) => Object.fromEntries(r.leaves.filter(l => l.name && unsignedField.has(l.path[0])).map(l => [l.kind === 'map' ? `${l.name}.value` : l.name, 'nat']));
|
|
845
|
+
o.domains = { ...nats(read), ...opts.domains };
|
|
846
|
+
const unsigned = Object.fromEntries([...read.model.inputs, ...read.model.params].filter(v => read.ints[v.name] && !read.ints[v.name].signed).map(v => [v.name, 'nat']));
|
|
847
|
+
const x = fromModel(read.model, mod.file, { ...unsigned, ...o.domains }, notes, (rule, sorts) => checkStep(harness(read), read, rule, sorts, o));
|
|
848
|
+
if (!x.ok)
|
|
849
|
+
return { ...x, read, names: stepNames(read) };
|
|
850
|
+
// (a run that breaks a law, from the prover at any width: replayed on the code at the check's before it is shown)
|
|
851
|
+
if (!meta.calls || opts.reentrant === false) {
|
|
852
|
+
const rp = replayer({ rule: x.rule, sorts: x.sorts, model: read.model, names: stepNames(read), leaves: read.leaves, hello: harness(read).hello.sol, ctor: read.ctor, replay: compileReplay(opts), opts });
|
|
853
|
+
return { ...x, read, names: stepNames(read), replay: (run, law) => rp(run, law) };
|
|
854
|
+
}
|
|
855
|
+
// The rule the laws are proven of: every call into other code a point where any of the contract's calls may run.
|
|
856
|
+
let re, rread;
|
|
857
|
+
try {
|
|
858
|
+
re = readSolidity(file, opts, true, c);
|
|
859
|
+
rread = readStep(re.mod, { ...o, methods: [...methods, ...re.meta.resumes] });
|
|
860
|
+
}
|
|
861
|
+
catch (e) {
|
|
862
|
+
if (e instanceof Refusal)
|
|
863
|
+
return { ok: false, refusals: [{ where: e.where, what: `re-entrancy: ${e.what}` }], notes: [...x.notes] };
|
|
864
|
+
throw e;
|
|
865
|
+
}
|
|
866
|
+
const rw = rread.model.params.find(v => v.name.startsWith(MOD));
|
|
867
|
+
if (rw)
|
|
868
|
+
rw.derived = { op: 'const', v: CHECK_W };
|
|
869
|
+
rread.model.notes.push(...boundaryNotes(meta), `re-entrancy: each call into other code (${re.meta.resumes.map(r => r.replace(/\$resume$/, '')).join(', ')}) is two steps, any of the contract's calls between them (a callee that calls back); a law about the state holds where no call is pending (pending$ == 0)`);
|
|
870
|
+
const rnotes = [];
|
|
871
|
+
// The check of the re-entrant rule: its own random runs (calls inside calls, by any address) replayed on the code,
|
|
872
|
+
// every address an Agent that makes the run's calls from inside the call it receives.
|
|
873
|
+
let replays;
|
|
874
|
+
const runs = { runs: 0, txs: 0, nested: 0, steps: 0 };
|
|
875
|
+
const rx = fromModel(rread.model, mod.file, { ...unsigned, ...nats(rread), ...opts.domains, 'pending$': 'nat' }, rnotes, (rule, sorts) => {
|
|
876
|
+
replays = replayer({ rule, sorts, model: rread.model, names: stepNames(rread), leaves: read.leaves, hello: harness(read).hello.sol, ctor: read.ctor, replay: compileReplay(opts), opts });
|
|
877
|
+
const ev = { ...x.evidence };
|
|
878
|
+
const n = opts.check?.runs === undefined ? 40 : Math.max(4, Math.round(opts.check.runs / 5)), rand = seeded((opts.check?.seed ?? 11) >>> 0 || 1);
|
|
879
|
+
for (let i = 0; i < n; i++) {
|
|
880
|
+
const run = randomRun(rule, rread.model, rand);
|
|
881
|
+
if (!run.trace.length)
|
|
882
|
+
continue;
|
|
883
|
+
const r = replays(run);
|
|
884
|
+
if (!r.ok)
|
|
885
|
+
return { ...ev, mismatch: `re-entrancy: a run of the rule replayed on the code: ${r.what}` };
|
|
886
|
+
runs.runs++;
|
|
887
|
+
runs.txs += r.txs;
|
|
888
|
+
runs.nested += r.nested;
|
|
889
|
+
runs.steps += run.trace.length;
|
|
890
|
+
}
|
|
891
|
+
return ev;
|
|
892
|
+
});
|
|
893
|
+
if (rx.ok)
|
|
894
|
+
rx.notes.push(`re-entrancy: checked by ${runs.runs} runs of the rule replayed on the code (${runs.txs} transactions, ${runs.nested} calls made from inside another, ${runs.steps} steps), an Agent at every address making each call from inside the one it receives`);
|
|
895
|
+
return { ...rx, read: rread, names: stepNames(rread), quiet: 'pending$', ...(replays ? { replay: (run, law) => replays(run, law) } : {}) };
|
|
896
|
+
}
|
|
897
|
+
function compileReplay(o) {
|
|
898
|
+
const c = compile(new URL('./sol/Replay.sol', import.meta.url).pathname, { ...o, root: new URL('./sol/', import.meta.url).pathname });
|
|
899
|
+
const k = c.contracts[c.paths.get(c.main)];
|
|
900
|
+
return { agent: k.Agent.evm.deployedBytecode.object, director: k.Director.evm.deployedBytecode.object };
|
|
901
|
+
}
|
|
902
|
+
// A random run of the re-entrant rule: requests the rule allows, then every pending call resumed (ok), at the width the
|
|
903
|
+
// check runs at.
|
|
904
|
+
function randomRun(rule, model, rand) {
|
|
905
|
+
const m = rule.machine, it = interpret(m), w = model.params.find(v => v.name.startsWith(MOD));
|
|
906
|
+
const params = rule.randomParams(rand, 6);
|
|
907
|
+
if (w)
|
|
908
|
+
params[w.name] = CHECK_W;
|
|
909
|
+
for (const v of model.params)
|
|
910
|
+
if (v.name !== w?.name && params[v.name] === 0 && /sender/.test(v.name))
|
|
911
|
+
params[v.name] = 1;
|
|
912
|
+
if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
|
|
913
|
+
return { params, trace: [] };
|
|
914
|
+
const ev = model.inputs.find(v => v.name === model.event), names = ev?.sort.k === 'choice' ? ev.sort.values : [];
|
|
915
|
+
const resumes = names.flatMap((n, i) => (n.endsWith('$resume') ? [i] : []));
|
|
916
|
+
let st = it.init(params);
|
|
917
|
+
const trace = [];
|
|
918
|
+
const take = (input) => {
|
|
919
|
+
try {
|
|
920
|
+
if (!allowed(m, it, params, st, input))
|
|
921
|
+
return false;
|
|
922
|
+
st = it.step(params, st, input);
|
|
923
|
+
trace.push({ ...input });
|
|
924
|
+
return true;
|
|
925
|
+
}
|
|
926
|
+
catch {
|
|
927
|
+
return false;
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
const depth = 2 + rand(10);
|
|
931
|
+
for (let tries = 0; trace.length < depth && tries < 200; tries++)
|
|
932
|
+
take(rule.randomInput(rand, 6, params));
|
|
933
|
+
// (the calls pending returned, the last first: a request of a resume, its ok true)
|
|
934
|
+
for (let tries = 0; Number(rule.decode(st)['pending$'] ?? 0) > 0 && tries < 400; tries++) {
|
|
935
|
+
const input = rule.randomInput(rand, 6, params);
|
|
936
|
+
if (!ev || !resumes.length)
|
|
937
|
+
break;
|
|
938
|
+
input[ev.name] = resumes[rand(resumes.length)];
|
|
939
|
+
for (const k of Object.keys(input))
|
|
940
|
+
if (k.endsWith('$ok'))
|
|
941
|
+
input[k] = 1;
|
|
942
|
+
take(input);
|
|
943
|
+
}
|
|
944
|
+
return Number(rule.decode(st)['pending$'] ?? 0) > 0 ? { params, trace: [] } : { params, trace };
|
|
945
|
+
}
|
|
946
|
+
// A run replayed: the rule's steps at the check's width, cut into the code's transactions (a call made at no depth up to
|
|
947
|
+
// the depth back at 0), each call by its Agent, each resume an Agent's return; the state after each transaction the
|
|
948
|
+
// rule's, every call made. With a law, the law broken by the run at that width too.
|
|
949
|
+
function replayer(c) {
|
|
950
|
+
return (run, law) => {
|
|
951
|
+
const no = (what) => ({ ok: false, what, txs: 0, nested: 0 });
|
|
952
|
+
const isLaw = !!law && typeof law === 'object' && 'holds' in law;
|
|
953
|
+
let R = c.rule;
|
|
954
|
+
try {
|
|
955
|
+
if (isLaw)
|
|
956
|
+
R = c.rule.withSumsOf(law);
|
|
957
|
+
}
|
|
958
|
+
catch {
|
|
959
|
+
R = c.rule;
|
|
960
|
+
}
|
|
961
|
+
const m = R.machine, it = interpret(m), w = c.model.params.find(v => v.name.startsWith(MOD));
|
|
962
|
+
const ps = { ...run.params, ...(w ? { [w.name]: CHECK_W } : {}) };
|
|
963
|
+
if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
|
|
964
|
+
return no(`made at the width 2^52, the precondition refuses it`);
|
|
965
|
+
let st = it.init(ps);
|
|
966
|
+
const watcher = law ? watch(m, it, law, ps, 8) : undefined;
|
|
967
|
+
let broke = watcher ? (watcher.start(st) ? -1 : 0) : -1;
|
|
968
|
+
const ev = c.model.event, steps = [];
|
|
969
|
+
const decodeIn = (req, name) => { const v = c.model.inputs.find(x => x.name === name); const k = kindOfVar(v, c.sorts); return k.decode(name, Object.fromEntries(k.vars(name).map(part => [part, Number(req[part] ?? 0)]))); };
|
|
970
|
+
const states = [];
|
|
971
|
+
for (const [i, req0] of run.trace.entries()) {
|
|
972
|
+
const req = req0;
|
|
973
|
+
const before = Number(R.decode(st)['pending$'] ?? 0);
|
|
974
|
+
if (!allowed(m, it, ps, st, req))
|
|
975
|
+
return no(`step ${i + 1} is refused at the width 2^52 (the run is the rule's at a narrower one)`);
|
|
976
|
+
const next = it.step(ps, st, req);
|
|
977
|
+
if (watcher && broke < 0 && !watcher.step(st, req, next))
|
|
978
|
+
broke = i + 1;
|
|
979
|
+
st = next;
|
|
980
|
+
const method = ev ? String(decodeIn(req0, ev)) : c.model.events[0].call;
|
|
981
|
+
const args = c.names.filter(n => n.role === 'input' && n.method === method && n.rule).map(n => [n.code, decodeIn(req0, n.rule)]);
|
|
982
|
+
const answers = c.names.filter(n => n.role === 'answer' && n.rule && n.rule in req0).map(n => [n.code, decodeIn(req0, n.rule)]);
|
|
983
|
+
steps.push({ method, args, answers, depth: Number(R.decode(st)['pending$'] ?? 0), before });
|
|
984
|
+
states.push(R.decode(st));
|
|
985
|
+
if (broke > 0 && steps.at(-1).depth === 0)
|
|
986
|
+
break;
|
|
987
|
+
}
|
|
988
|
+
if (law && broke < 0)
|
|
989
|
+
return no('the law holds on this run at the width 2^52 (it breaks only at a narrower one)');
|
|
990
|
+
if (steps.at(-1)?.depth)
|
|
991
|
+
return no('the run ends with a call pending (no state of the code between transactions)');
|
|
992
|
+
// The transactions: each from a call at depth 0 to the depth back at 0.
|
|
993
|
+
const groups = [];
|
|
994
|
+
const after = [];
|
|
995
|
+
let nested = 0;
|
|
996
|
+
for (const [i, s] of steps.entries()) {
|
|
997
|
+
if (s.before === 0)
|
|
998
|
+
groups.push([]);
|
|
999
|
+
const g = groups.at(-1);
|
|
1000
|
+
if (s.method.endsWith('$resume'))
|
|
1001
|
+
g.push({ kind: 'ret', ok: s.args.find(([n]) => n === '$ok')?.[1] === true });
|
|
1002
|
+
else {
|
|
1003
|
+
if (s.before > 0)
|
|
1004
|
+
nested++;
|
|
1005
|
+
g.push({ kind: 'call', m: s.method, a: s.args.map(([n, v]) => [n, { in: v }]), ...(s.answers.length ? { answers: Object.fromEntries(s.answers.map(([n, v]) => [n, { in: v }])) } : {}) });
|
|
1006
|
+
}
|
|
1007
|
+
if (s.depth === 0)
|
|
1008
|
+
after.push(states[i]);
|
|
1009
|
+
}
|
|
1010
|
+
const fs = node('node:fs'), os = node('node:os'), cp = node('node:child_process');
|
|
1011
|
+
const dir = fs.mkdtempSync(`${os.tmpdir()}/gdp-solreplay-`);
|
|
1012
|
+
const ctorArgs = c.ctor.map(([n, a]) => [n, a.k === 'in' ? { in: n === MOD || n.startsWith(MOD) ? CHECK_W : ps[a.name] ?? 0 } : { dflt: true }]);
|
|
1013
|
+
let out;
|
|
1014
|
+
try {
|
|
1015
|
+
fs.writeFileSync(`${dir}/run.json`, JSON.stringify({ sol: c.hello, leaves: c.leaves, ctorSpec: c.ctor, ctor: ctorArgs, agent: c.replay.agent, director: c.replay.director, groups }));
|
|
1016
|
+
out = JSON.parse(cp.execFileSync(c.opts.python ?? 'python3', [new URL('./sol/harness.py', import.meta.url).pathname, '--replay', `${dir}/run.json`], { encoding: 'utf8', maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'pipe'], env: { ...env(), ...(c.opts.anvil ? { GDP_ANVIL: c.opts.anvil } : {}) } }));
|
|
1017
|
+
}
|
|
1018
|
+
catch (e) {
|
|
1019
|
+
return no(`the replay didn't run (${String(e.message).slice(0, 300)})`);
|
|
1020
|
+
}
|
|
1021
|
+
finally {
|
|
1022
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
1023
|
+
}
|
|
1024
|
+
if (out.error)
|
|
1025
|
+
return no(`the code: ${out.error}`);
|
|
1026
|
+
const shown = (g) => groups[g].map(e => (e.kind === 'ret' ? `return(${e.ok})` : `${e.m}(${e.a.map(([n, v]) => `${n}=${String(v.in)}`).join(', ')})`)).join(' ');
|
|
1027
|
+
for (const [g, ok] of (out.oks ?? []).entries())
|
|
1028
|
+
if (ok.some(x => !x))
|
|
1029
|
+
return no(`transaction ${g + 1} (${shown(g)}): a call the rule takes reverts in the code`);
|
|
1030
|
+
for (const [g, code] of (out.states ?? []).entries()) {
|
|
1031
|
+
const d = sameState(c.leaves, after[g], code);
|
|
1032
|
+
if (d)
|
|
1033
|
+
return no(`after transaction ${g + 1} (${shown(g)}): ${d}`);
|
|
1034
|
+
}
|
|
1035
|
+
return { ok: true, what: `replayed on the code (anvil, the contract's bytecode): ${groups.length} transactions, ${nested} calls made from inside another, the state after each the rule's${law ? ', the law broken there' : ''}`, txs: groups.length, nested };
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
const byKey = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
|
1039
|
+
// The rule's state (decoded) against the code's (the harness's), leaf by leaf: undefined where they agree.
|
|
1040
|
+
function sameState(leaves, rule, code) {
|
|
1041
|
+
for (const l of leaves) {
|
|
1042
|
+
if (l.kind === 'frame' || l.kind === 'none')
|
|
1043
|
+
continue;
|
|
1044
|
+
if (l.kind === 'map') {
|
|
1045
|
+
const r = Object.fromEntries(Object.entries((rule[l.name] ?? {})).filter(([, c]) => c.has).map(([k, c]) => [k, String(c.value)]));
|
|
1046
|
+
const k = Object.fromEntries(Object.entries((code[l.name] ?? {})).map(([key, c]) => [key, String(c.value)]));
|
|
1047
|
+
if (JSON.stringify(Object.entries(r).sort(byKey)) !== JSON.stringify(Object.entries(k).sort(byKey)))
|
|
1048
|
+
return `${l.path.join('.')} is ${JSON.stringify(k)} in the code, ${JSON.stringify(r)} in the rule`;
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
if (String(rule[l.name]) !== String(code[l.name]))
|
|
1052
|
+
return `${l.path.join('.')} is ${String(code[l.name])} in the code, ${String(rule[l.name])} in the rule`;
|
|
1053
|
+
}
|
|
1054
|
+
return undefined;
|
|
1055
|
+
}
|
|
1056
|
+
// The mappings of mappings each entry reads (through the functions it calls): the check sets only those.
|
|
1057
|
+
function havocBy(mod) {
|
|
1058
|
+
const memo = new Map();
|
|
1059
|
+
const of = (id) => {
|
|
1060
|
+
const hit = memo.get(id);
|
|
1061
|
+
if (hit)
|
|
1062
|
+
return hit;
|
|
1063
|
+
const out = new Set();
|
|
1064
|
+
memo.set(id, out);
|
|
1065
|
+
const walk = (x) => {
|
|
1066
|
+
if (Array.isArray(x)) {
|
|
1067
|
+
x.forEach(walk);
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
if (!x || typeof x !== 'object')
|
|
1071
|
+
return;
|
|
1072
|
+
const n = x;
|
|
1073
|
+
if (n.e === 'ext' && typeof n.q === 'string')
|
|
1074
|
+
out.add(n.q);
|
|
1075
|
+
if (n.e === 'fn' && typeof n.id === 'string' && mod.funcs[n.id])
|
|
1076
|
+
for (const f of of(n.id))
|
|
1077
|
+
out.add(f);
|
|
1078
|
+
for (const v of Object.values(n))
|
|
1079
|
+
walk(v);
|
|
1080
|
+
};
|
|
1081
|
+
walk(mod.funcs[id]?.body);
|
|
1082
|
+
return out;
|
|
1083
|
+
};
|
|
1084
|
+
const r = Object.values(mod.recs).find(x => x.methods.__init__);
|
|
1085
|
+
return Object.fromEntries(Object.entries(r.methods).filter(([, id]) => id).map(([m, id]) => [m, [...of(id)]]));
|
|
1086
|
+
}
|
|
1087
|
+
const kindOf = (t, sol = '') => (t.k === 'map' ? `map:${kindOf(t.val, valueSol(sol))}` : sol.startsWith('address') ? 'addr' : t.k === 'int' ? (t.mod ? 'u256' : `${t.signed ? 'i' : 'u'}${t.bits ?? 0}`) : t.k === 'choice' ? `choice:${t.values.join('|')}` : t.k);
|
|
1088
|
+
const valueSol = (sol) => { if (!sol.startsWith('mapping('))
|
|
1089
|
+
return sol; const inner = sol.slice('mapping('.length, -1); return valueSol(inner.slice(topArrow(inner) + 2).trim()); };
|
|
1090
|
+
// A mapping's key kinds, as the harness encodes them (two for a mapping of mappings).
|
|
1091
|
+
const keyKinds = (sol) => {
|
|
1092
|
+
const one = (k) => (k.startsWith('address') ? 'addr' : k === 'uint256' ? 'u256' : k.startsWith('uint') ? `u${k.slice(4)}` : k);
|
|
1093
|
+
const inner = sol.slice('mapping('.length, -1), a = topArrow(inner), v = inner.slice(a + 2).trim();
|
|
1094
|
+
return [one(inner.slice(0, a).trim()), ...(v.startsWith('mapping(') ? keyKinds(v).slice(0, 1) : [])];
|
|
1095
|
+
};
|
|
1096
|
+
function boundaryNotes(m) {
|
|
1097
|
+
return [
|
|
1098
|
+
`Solidity: ${m.contract} read from solc's AST; checked against its bytecode (the same solc) on anvil`,
|
|
1099
|
+
`uint256: exact past 2^53 by the width ${MOD} (any value above ${m.minW - 1} in the rule, 2^256 in the code): a law proven for every width is proven for 2^256`,
|
|
1100
|
+
'addresses: naturals compared by equality (address(0) is 0, and no request comes from it)',
|
|
1101
|
+
...m.nested.map(f => `${f}: a mapping of mappings, each cell read any value of its type (an input of the request, one a step), its writes left out: a law reads none of it`),
|
|
1102
|
+
...m.leftOut,
|
|
1103
|
+
'a revert is the step\'s refusal (nothing it wrote stays); a mapping\'s cell is held where it isn\'t 0',
|
|
1104
|
+
...(m.ether ? ['balance: the contract\'s ether; an address sent a value is an account without code (it calls nothing back)'] : []),
|
|
1105
|
+
];
|
|
1106
|
+
}
|