@guardefi/cli 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +18 -0
- package/README.md +31 -2
- package/assurance/cli-check.js +446 -0
- package/assurance/cli-project-paths.js +56 -0
- package/assurance/cli-storage.js +289 -0
- package/assurance/cli-ui.js +617 -0
- package/assurance/guardefi-public.js +66 -0
- package/assurance/release-policy.js +212 -0
- package/core/behavioral-diff.js +555 -0
- package/core/canonical-json.js +9 -0
- package/core/engine/abi.js +99 -0
- package/core/engine/assumptions.json +86 -0
- package/core/engine/bytecode.js +119 -0
- package/core/engine/callee-binding.js +140 -0
- package/core/engine/deployment.js +175 -0
- package/core/engine/external-effects.js +40 -0
- package/core/engine/harness.js +503 -0
- package/core/engine/index.js +638 -0
- package/core/engine/integrity.js +124 -0
- package/core/engine/model.js +369 -0
- package/core/engine/policy.js +59 -0
- package/core/engine/proof-certificate.js +69 -0
- package/core/engine/provenance.js +354 -0
- package/core/engine/screen.js +117 -0
- package/core/engine/upgrade-authority.js +327 -0
- package/core/generic.js +334 -0
- package/core/hardhat.js +114 -0
- package/core/isl/behavior-profile.js +169 -0
- package/core/isl/behavior-solidity.js +267 -0
- package/core/isl/behavior-storage.js +151 -0
- package/core/isl/behavior-verify.js +223 -0
- package/core/isl/getter-profile.js +149 -0
- package/core/isl/vendor/NOTICE.md +38 -0
- package/core/isl/vendor/isl-parser.cjs +5872 -0
- package/core/isl-compiler.js +19 -0
- package/core/isl-firewall.js +1396 -0
- package/core/keccak.js +89 -0
- package/core/prove.js +376 -0
- package/core/release-receipt.js +793 -0
- package/core/rpc.js +74 -0
- package/core/tools.js +129 -0
- package/core/verdict-policy.js +195 -0
- package/docs/public-cli.md +32 -0
- package/package.json +29 -4
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// Who can write the ERC-1967 implementation slot, read from runtime bytecode.
|
|
2
|
+
//
|
|
3
|
+
// An abstract interpreter runs the code from its entry and tracks, for every
|
|
4
|
+
// stack value, where it came from: constants, the caller, calldata, call
|
|
5
|
+
// value, return data, a storage slot, allowed environment (own address, code
|
|
6
|
+
// sizes, gas) or other environment (block values, origin, balances,
|
|
7
|
+
// transient storage). Memory words at constant offsets are kept; other memory
|
|
8
|
+
// reads carry everything written to memory on that path.
|
|
9
|
+
//
|
|
10
|
+
// Every branch a path takes on its way to an SSTORE of the implementation
|
|
11
|
+
// slot is classified:
|
|
12
|
+
// G:<slot> the caller equals the address stored at <slot> (an owner check)
|
|
13
|
+
// B anything else that reads the caller, storage (other than the
|
|
14
|
+
// proxy-reserved implementation and rollback slots) or other
|
|
15
|
+
// environment
|
|
16
|
+
// Branches on calldata, call value, return data and own-address checks are
|
|
17
|
+
// not state-dependent and are not recorded.
|
|
18
|
+
//
|
|
19
|
+
// `guarded` holds only when exploration completes, no store goes to a slot
|
|
20
|
+
// that is neither constant nor a hash (plus a constant), no delegated call
|
|
21
|
+
// can run before the implementation write on its path, and every path that
|
|
22
|
+
// writes the implementation slot carries exactly one owner check and nothing
|
|
23
|
+
// else. Then whether a caller can upgrade depends on proxy state only through
|
|
24
|
+
// the caller being the address stored at that owner slot. Anything less is
|
|
25
|
+
// `unresolved`; `none` means no reachable instruction can write the slot.
|
|
26
|
+
//
|
|
27
|
+
// A second run fixes calldata to proxiableUUID() and checks that every
|
|
28
|
+
// reachable RETURN returns the implementation slot.
|
|
29
|
+
|
|
30
|
+
const { EFFECT, TERMINAL } = require('./provenance');
|
|
31
|
+
|
|
32
|
+
const MAX_STATES = 300000;
|
|
33
|
+
const WIDEN_AFTER = 4;
|
|
34
|
+
const WORD = (1n << 256n) - 1n;
|
|
35
|
+
const IMPLEMENTATION = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcn;
|
|
36
|
+
const ROLLBACK = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143n;
|
|
37
|
+
const PROXIABLE = 0x52d1902dn;
|
|
38
|
+
const ALLOWED_SLOTS = new Set([IMPLEMENTATION, ROLLBACK].map((s) => `S:${s.toString(16)}`));
|
|
39
|
+
// Environment that is the same on both sides and does not depend on proxy state.
|
|
40
|
+
const ENV = new Set([0x30, 0x38, 0x3b, 0x3f, 0x46, 0x58, 0x59, 0x5a]);
|
|
41
|
+
// Environment a guard must not depend on.
|
|
42
|
+
const OTHER = new Set([0x31, 0x32, 0x3a, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x5c]);
|
|
43
|
+
|
|
44
|
+
const hexOf = (n) => n.toString(16);
|
|
45
|
+
const tagsOf = (...vs) => [...new Set(vs.flatMap((v) => v.t || []))].sort();
|
|
46
|
+
const konst = (c, k = false) => ({ c, t: [], ...(k ? { k: true } : {}) });
|
|
47
|
+
const key = (v) => (v.c !== undefined ? hexOf(v.c) : `${v.t.join('+')}${v.sel ? 's' : ''}${v.cd0 ? 'z' : ''}${v.kh ? 'h' : ''}${v.selEq !== undefined ? `e${hexOf(v.selEq)}` : ''}${v.f ? `f${v.f}` : ''}${v.g ? `g${v.g}` : ''}${v.pol !== undefined ? `p${v.pol}` : ''}`);
|
|
48
|
+
const only = (v, tag) => v.c === undefined && v.t.length === 1 && v.t[0] === tag && !v.g;
|
|
49
|
+
// A storage field: a constant slot, optionally shifted and masked by constants.
|
|
50
|
+
const storageTag = (v) => (v.c === undefined && v.f && !v.g ? v.f : null);
|
|
51
|
+
|
|
52
|
+
function fold(op, x, y) {
|
|
53
|
+
switch (op) {
|
|
54
|
+
case 0x01: return (x + y) & WORD;
|
|
55
|
+
case 0x02: return (x * y) & WORD;
|
|
56
|
+
case 0x03: return (x - y) & WORD;
|
|
57
|
+
case 0x04: return y === 0n ? 0n : x / y;
|
|
58
|
+
case 0x06: return y === 0n ? 0n : x % y;
|
|
59
|
+
case 0x0a: { let r = 1n; let base = x; let e = y; while (e > 0n) { if (e & 1n) r = (r * base) & WORD; base = (base * base) & WORD; e >>= 1n; } return r; }
|
|
60
|
+
case 0x10: return x < y ? 1n : 0n;
|
|
61
|
+
case 0x11: return x > y ? 1n : 0n;
|
|
62
|
+
case 0x14: return x === y ? 1n : 0n;
|
|
63
|
+
case 0x16: return x & y;
|
|
64
|
+
case 0x17: return x | y;
|
|
65
|
+
case 0x18: return x ^ y;
|
|
66
|
+
case 0x1b: return x >= 256n ? 0n : (y << x) & WORD;
|
|
67
|
+
case 0x1c: return x >= 256n ? 0n : y >> x;
|
|
68
|
+
default: return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function binary(op, a, b) {
|
|
73
|
+
// a is the top of the stack.
|
|
74
|
+
if (a.c !== undefined && b.c !== undefined) {
|
|
75
|
+
const c = fold(op, a.c, b.c);
|
|
76
|
+
// An identity (shift by zero, add zero, full mask) keeps a pushed constant.
|
|
77
|
+
if (c !== null) return konst(c, !((c === a.c && !a.k) || (c === b.c && !b.k)));
|
|
78
|
+
}
|
|
79
|
+
if (op === 0x1c && a.c === 224n && b.cd0) return { t: ['D'], sel: true };
|
|
80
|
+
if (op === 0x14) {
|
|
81
|
+
if (a.sel && b.c !== undefined) return { t: ['D'], selEq: b.c, pol: 1 };
|
|
82
|
+
if (b.sel && a.c !== undefined) return { t: ['D'], selEq: a.c, pol: 1 };
|
|
83
|
+
}
|
|
84
|
+
if (op === 0x14 || op === 0x03 || op === 0x18) {
|
|
85
|
+
const pol = op === 0x14 ? 1 : 0; // EQ is nonzero when equal; SUB and XOR when different
|
|
86
|
+
const slot = only(a, 'C') ? storageTag(b) : only(b, 'C') ? storageTag(a) : null;
|
|
87
|
+
if (slot) return { t: ['G'], g: slot.slice(2), pol };
|
|
88
|
+
}
|
|
89
|
+
if (op === 0x1c && a.c !== undefined && b.f) return { t: b.t, f: a.c ? `${b.f}>>${hexOf(a.c)}` : b.f };
|
|
90
|
+
if (op === 0x04 && b.c !== undefined && a.f) return { t: a.t, f: b.c === 1n ? a.f : `${a.f}/${hexOf(b.c)}` };
|
|
91
|
+
if (op === 0x16 && (a.c !== undefined || b.c !== undefined)) {
|
|
92
|
+
// A mask keeps the masked value's origin.
|
|
93
|
+
const [mask, other] = a.c !== undefined ? [a.c, b] : [b.c, a];
|
|
94
|
+
if (other.c !== undefined) return konst(other.c & mask, true);
|
|
95
|
+
const out = { ...other };
|
|
96
|
+
delete out.k;
|
|
97
|
+
if (out.f && !out.f.endsWith(`&${hexOf(mask)}`)) out.f = `${out.f}&${hexOf(mask)}`;
|
|
98
|
+
if (!(mask & 1n)) { delete out.g; delete out.pol; delete out.selEq; }
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
if (op === 0x01 && ((a.kh && b.c !== undefined) || (b.kh && a.c !== undefined))) return { t: tagsOf(a, b), kh: true };
|
|
102
|
+
return { t: tagsOf(a, b) };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function unary(op, a) {
|
|
106
|
+
if (op === 0x15) {
|
|
107
|
+
if (a.c !== undefined) return konst(a.c === 0n ? 1n : 0n, true);
|
|
108
|
+
if (a.g || a.selEq !== undefined) return { ...a, pol: 1 - a.pol };
|
|
109
|
+
return { t: a.t };
|
|
110
|
+
}
|
|
111
|
+
if (op === 0x19 && a.c !== undefined) return konst(~a.c & WORD, true);
|
|
112
|
+
return { t: a.t };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `hex`: runtime code. `immutables`: [{ start, length }] byte ranges filled at
|
|
117
|
+
* deployment, read as unknown. `calldata`: a Buffer to run one concrete call.
|
|
118
|
+
*/
|
|
119
|
+
function explore(hex, { immutables = [], calldata = null } = {}) {
|
|
120
|
+
const out = { complete: false, sites: [], stores: [], hashedStores: [], unknownStores: [], delegatedBeforeUpgrade: [], rollbackWrites: [], returns: [] };
|
|
121
|
+
const stores = new Set();
|
|
122
|
+
if (typeof hex !== 'string' || !/^(?:0x)?(?:[0-9a-f]{2})+$/i.test(hex)) return { ...out, reason: 'invalid runtime' };
|
|
123
|
+
const code = Buffer.from(hex.replace(/^0x/, ''), 'hex');
|
|
124
|
+
const immutableAt = new Set(immutables.map((r) => r.start));
|
|
125
|
+
const jumpdests = new Set();
|
|
126
|
+
for (let pc = 0; pc < code.length; pc++) {
|
|
127
|
+
if (code[pc] === 0x5b) jumpdests.add(pc);
|
|
128
|
+
if (code[pc] >= 0x60 && code[pc] <= 0x7f) pc += code[pc] - 0x5f;
|
|
129
|
+
}
|
|
130
|
+
const word = (offset) => {
|
|
131
|
+
const bytes = Buffer.alloc(32);
|
|
132
|
+
if (offset < BigInt(calldata.length)) calldata.copy(bytes, 0, Number(offset), Math.min(calldata.length, Number(offset) + 32));
|
|
133
|
+
return BigInt('0x' + bytes.toString('hex'));
|
|
134
|
+
};
|
|
135
|
+
const sites = new Map();
|
|
136
|
+
const fail = (reason) => ({ ...out, complete: false, reason });
|
|
137
|
+
const seen = new Set();
|
|
138
|
+
const visits = new Map();
|
|
139
|
+
const start = { pc: 0, stack: [], facts: [], sel: '', upgraded: false, mem: new Map(), mt: [] };
|
|
140
|
+
const work = [start];
|
|
141
|
+
while (work.length) {
|
|
142
|
+
let s = work.pop();
|
|
143
|
+
for (;;) {
|
|
144
|
+
const count = (visits.get(s.pc) || 0) + 1;
|
|
145
|
+
visits.set(s.pc, count);
|
|
146
|
+
if (count > WIDEN_AFTER) {
|
|
147
|
+
const widen = (v) => (v.k ? { t: [] } : v);
|
|
148
|
+
if (s.stack.some((v) => v.k)) s.stack = s.stack.map(widen);
|
|
149
|
+
if ([...s.mem.values()].some((v) => v.k)) s.mem = new Map([...s.mem].map(([o, v]) => [o, widen(v)]));
|
|
150
|
+
}
|
|
151
|
+
const id = `${s.pc}|${s.stack.map(key).join(',')}|${s.facts.join(',')}|${s.sel}|${s.upgraded}|${[...s.mem].map(([o, v]) => `${o}=${key(v)}`).join(',')}|${s.mt.join('+')}`;
|
|
152
|
+
if (seen.has(id)) break;
|
|
153
|
+
seen.add(id);
|
|
154
|
+
if (seen.size > MAX_STATES) return fail('state budget exceeded');
|
|
155
|
+
if (s.pc >= code.length) break;
|
|
156
|
+
const op = code[s.pc];
|
|
157
|
+
const { stack } = s;
|
|
158
|
+
const need = (n) => stack.length >= n;
|
|
159
|
+
if (op === 0xf3 && calldata) {
|
|
160
|
+
if (!need(2)) return fail(`stack underflow at ${s.pc}`);
|
|
161
|
+
const [offset, size] = [stack[stack.length - 1], stack[stack.length - 2]];
|
|
162
|
+
const value = offset.c !== undefined ? s.mem.get(offset.c) : undefined;
|
|
163
|
+
out.returns.push({ pc: s.pc, size: size.c, value: value?.c });
|
|
164
|
+
}
|
|
165
|
+
if (TERMINAL.has(op)) break;
|
|
166
|
+
if (op >= 0x60 && op <= 0x7f) {
|
|
167
|
+
const n = op - 0x5f;
|
|
168
|
+
const value = immutableAt.has(s.pc + 1) ? { t: ['E'] } : konst(BigInt('0x' + (code.subarray(s.pc + 1, s.pc + 1 + n).toString('hex') || '0')));
|
|
169
|
+
s = { ...s, stack: [...stack, value], pc: s.pc + n + 1 };
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (op >= 0x80 && op <= 0x8f) {
|
|
173
|
+
const n = op - 0x7f;
|
|
174
|
+
if (!need(n)) return fail(`stack underflow at ${s.pc}`);
|
|
175
|
+
s = { ...s, stack: [...stack, stack[stack.length - n]], pc: s.pc + 1 };
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (op >= 0x90 && op <= 0x9f) {
|
|
179
|
+
const n = op - 0x8f;
|
|
180
|
+
if (!need(n + 1)) return fail(`stack underflow at ${s.pc}`);
|
|
181
|
+
const next = [...stack];
|
|
182
|
+
const top = next.length - 1;
|
|
183
|
+
[next[top], next[top - n]] = [next[top - n], next[top]];
|
|
184
|
+
s = { ...s, stack: next, pc: s.pc + 1 };
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (op === 0x56 || op === 0x57) {
|
|
188
|
+
if (!need(op === 0x56 ? 1 : 2)) return fail(`stack underflow at ${s.pc}`);
|
|
189
|
+
const target = stack[stack.length - 1].c;
|
|
190
|
+
if (target === undefined || !jumpdests.has(Number(target))) return fail(`jump to an unknown target at ${s.pc}`);
|
|
191
|
+
const rest = stack.slice(0, op === 0x56 ? -1 : -2);
|
|
192
|
+
if (op === 0x56) { s = { ...s, stack: rest, pc: Number(target) }; continue; }
|
|
193
|
+
const cond = stack[stack.length - 2];
|
|
194
|
+
const branch = (taken) => {
|
|
195
|
+
if (cond.c !== undefined) return (cond.c !== 0n) === taken ? { facts: s.facts, sel: s.sel } : null;
|
|
196
|
+
if (cond.selEq !== undefined) return { facts: s.facts, sel: taken === (cond.pol === 1) ? hexOf(cond.selEq) : s.sel };
|
|
197
|
+
let fact = null;
|
|
198
|
+
if (cond.g) fact = taken === (cond.pol === 1) ? `G:${cond.g}` : 'B';
|
|
199
|
+
else if (cond.t.some((t) => t === 'C' || t === 'X' || t === 'S?' || (t.startsWith('S:') && !ALLOWED_SLOTS.has(t)))) fact = 'B';
|
|
200
|
+
const facts = fact && !s.facts.includes(fact) ? [...s.facts, fact].sort() : s.facts;
|
|
201
|
+
return { facts, sel: s.sel };
|
|
202
|
+
};
|
|
203
|
+
const fall = branch(false);
|
|
204
|
+
const jump = branch(true);
|
|
205
|
+
if (fall) work.push({ ...s, ...fall, stack: rest, pc: s.pc + 1 });
|
|
206
|
+
if (!jump) break;
|
|
207
|
+
s = { ...s, ...jump, stack: rest, pc: Number(target) };
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const effect = EFFECT[op];
|
|
211
|
+
if (!effect) return fail(`opcode 0x${op.toString(16)} is outside the analyzed instruction set at ${s.pc}`);
|
|
212
|
+
const [pops, pushes] = effect;
|
|
213
|
+
if (!need(pops)) return fail(`stack underflow at ${s.pc}`);
|
|
214
|
+
const args = stack.slice(stack.length - pops).reverse();
|
|
215
|
+
let next = stack.slice(0, stack.length - pops);
|
|
216
|
+
let { mem, mt, upgraded } = s;
|
|
217
|
+
const clobber = (offset, size, taint) => {
|
|
218
|
+
mt = [...new Set([...mt, ...taint, 'W'])].sort();
|
|
219
|
+
if (offset?.c === undefined || size?.c === undefined) { mem = new Map(); return; }
|
|
220
|
+
const lo = offset.c;
|
|
221
|
+
const hi = offset.c + size.c;
|
|
222
|
+
mem = new Map([...mem].filter(([o]) => o + 32n <= lo || o >= hi));
|
|
223
|
+
};
|
|
224
|
+
let result = null;
|
|
225
|
+
if (pushes && pops === 2) result = binary(op, args[0], args[1]);
|
|
226
|
+
else if (pushes && pops === 1 && (op === 0x15 || op === 0x19)) result = unary(op, args[0]);
|
|
227
|
+
switch (op) {
|
|
228
|
+
case 0x33: result = { t: ['C'] }; break;
|
|
229
|
+
case 0x34: result = { t: ['V'] }; break;
|
|
230
|
+
case 0x35:
|
|
231
|
+
if (calldata && args[0].c !== undefined) result = konst(word(args[0].c));
|
|
232
|
+
else result = args[0].c === 0n ? { t: ['D'], cd0: true } : { t: ['D'] };
|
|
233
|
+
break;
|
|
234
|
+
case 0x36: result = calldata ? konst(BigInt(calldata.length)) : { t: ['D'] }; break;
|
|
235
|
+
case 0x3d: result = { t: ['R'] }; break;
|
|
236
|
+
case 0x20: result = { t: [...new Set([...tagsOf(args[0], args[1]), 'K'])].sort(), kh: true }; break;
|
|
237
|
+
case 0x54: result = args[0].c !== undefined ? { t: [`S:${hexOf(args[0].c)}`], f: `S:${hexOf(args[0].c)}` } : { t: ['S?'] }; break;
|
|
238
|
+
case 0x5f: result = konst(0n); break;
|
|
239
|
+
case 0x51:
|
|
240
|
+
result = args[0].c !== undefined && s.mem.has(args[0].c) ? s.mem.get(args[0].c)
|
|
241
|
+
: args[0].c !== undefined && !s.mt.length && ![...s.mem.keys()].some((o) => o + 32n > args[0].c && o < args[0].c + 32n) ? konst(0n)
|
|
242
|
+
: { t: [...s.mt] };
|
|
243
|
+
break;
|
|
244
|
+
case 0x52:
|
|
245
|
+
clobber(args[0], konst(32n), args[1].t);
|
|
246
|
+
if (args[0].c !== undefined) mem = new Map([...mem, [args[0].c, args[1]]]);
|
|
247
|
+
break;
|
|
248
|
+
case 0x53: clobber(args[0], konst(1n), args[1].t); break;
|
|
249
|
+
case 0x37: clobber(args[0], args[2], ['D']); break;
|
|
250
|
+
case 0x39: clobber(args[0], args[2], []); break;
|
|
251
|
+
case 0x3c: clobber(args[1], args[3], ['E']); break;
|
|
252
|
+
case 0x3e: clobber(args[0], args[2], ['R']); break;
|
|
253
|
+
case 0x5e: clobber(args[0], args[2], [...s.mt]); break;
|
|
254
|
+
case 0x55: {
|
|
255
|
+
const slot = args[0];
|
|
256
|
+
if (slot.c === IMPLEMENTATION) {
|
|
257
|
+
const id = `${s.pc}|${s.facts.join(',')}|${s.sel}`;
|
|
258
|
+
sites.set(id, { pc: s.pc, selector: s.sel || null, facts: s.facts });
|
|
259
|
+
upgraded = true;
|
|
260
|
+
} else if (slot.c === ROLLBACK) out.rollbackWrites.push(s.pc);
|
|
261
|
+
else if (slot.c !== undefined) stores.add(slot.c);
|
|
262
|
+
else if (slot.kh) out.hashedStores.push(s.pc);
|
|
263
|
+
else out.unknownStores.push(s.pc);
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
case 0xf1: case 0xf2: case 0xf4: case 0xfa:
|
|
267
|
+
if ((op === 0xf4 || op === 0xf2) && !upgraded) out.delegatedBeforeUpgrade.push(s.pc);
|
|
268
|
+
clobber(args[op === 0xf1 || op === 0xf2 ? 5 : 4], args[op === 0xf1 || op === 0xf2 ? 6 : 5], ['R']);
|
|
269
|
+
result = { t: ['R'] };
|
|
270
|
+
break;
|
|
271
|
+
case 0xf0: case 0xf5: result = { t: ['X'] }; break;
|
|
272
|
+
default:
|
|
273
|
+
if (pushes && result === null) {
|
|
274
|
+
if (ENV.has(op)) result = { t: ['E'] };
|
|
275
|
+
else if (OTHER.has(op)) result = { t: ['X'] };
|
|
276
|
+
else result = { t: tagsOf(...args) };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (pushes) next = [...next, result || { t: tagsOf(...args) }];
|
|
280
|
+
s = { ...s, stack: next, mem, mt, upgraded, pc: s.pc + 1 };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return { ...out, complete: true, sites: [...sites.values()], stores: [...stores] };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Classify one implementation runtime:
|
|
288
|
+
* { status: 'guarded', owner, selectors } every write of the
|
|
289
|
+
* implementation slot needs caller == the storage field `owner`
|
|
290
|
+
* (hex slot, then any constant >>shift, /divisor or &mask applied)
|
|
291
|
+
* { status: 'none' } no reachable instruction writes the implementation slot
|
|
292
|
+
* { status: 'unresolved', reason }
|
|
293
|
+
* plus `proxiable`: 'ok' | 'wrong' | 'unknown' for proxiableUUID().
|
|
294
|
+
*/
|
|
295
|
+
function upgradeAuthority(hex, { immutables = [] } = {}) {
|
|
296
|
+
const proxiable = proxiableUUID(hex, { immutables });
|
|
297
|
+
const a = explore(hex, { immutables });
|
|
298
|
+
const unresolved = (reason) => ({ status: 'unresolved', reason, proxiable });
|
|
299
|
+
if (!a.complete) return unresolved(`bytecode exploration incomplete: ${a.reason}`);
|
|
300
|
+
if (a.unknownStores.length) return unresolved(`storage writes to computed slots at ${a.unknownStores.slice(0, 3).join(', ')}`);
|
|
301
|
+
if (a.delegatedBeforeUpgrade.length) return unresolved('a delegated call can run before an implementation write');
|
|
302
|
+
if (a.rollbackWrites.length) return unresolved('the code writes the ERC-1967 rollback slot');
|
|
303
|
+
if (!a.sites.length) return { status: 'none', proxiable };
|
|
304
|
+
const owners = new Set();
|
|
305
|
+
for (const site of a.sites) {
|
|
306
|
+
const guards = site.facts.filter((f) => f.startsWith('G:'));
|
|
307
|
+
if (site.facts.length !== 1 || guards.length !== 1) {
|
|
308
|
+
return unresolved(`implementation write at ${site.pc} is reachable ${site.facts.length ? 'under conditions other than one owner check' : 'without an owner check'}`);
|
|
309
|
+
}
|
|
310
|
+
owners.add(guards[0].slice(2));
|
|
311
|
+
}
|
|
312
|
+
if (owners.size !== 1) return unresolved('implementation writes are guarded by different owner slots');
|
|
313
|
+
return { status: 'guarded', owner: [...owners][0], selectors: [...new Set(a.sites.map((s) => s.selector))].map((s) => (s ? `0x${s.padStart(8, '0')}` : null)), proxiable };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function proxiableUUID(hex, { immutables = [] } = {}) {
|
|
317
|
+
const r = explore(hex, { immutables, calldata: Buffer.from(PROXIABLE.toString(16), 'hex') });
|
|
318
|
+
if (!r.complete) return 'unknown';
|
|
319
|
+
if (r.returns.length && r.returns.every((x) => x.size === 32n && x.value === IMPLEMENTATION)) return 'ok';
|
|
320
|
+
if (r.returns.every((x) => x.size !== undefined && (x.size !== 32n || (x.value !== undefined && x.value !== IMPLEMENTATION)))) return 'wrong';
|
|
321
|
+
return 'unknown';
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Immutable byte ranges from a Foundry artifact's deployed bytecode. */
|
|
325
|
+
const immutablesOf = (artifact) => Object.values(artifact?.deployedBytecode?.immutableReferences || {}).flat();
|
|
326
|
+
|
|
327
|
+
module.exports = { upgradeAuthority, explore, immutablesOf, IMPLEMENTATION };
|
package/core/generic.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// Upgrade checks that need no hand-written spec. They compare a new
|
|
2
|
+
// implementation with the one it replaces (the baseline):
|
|
3
|
+
//
|
|
4
|
+
// layout every baseline storage variable keeps its slot, offset and type
|
|
5
|
+
// opcodes no SELFDESTRUCT, DELEGATECALL or CALLCODE the baseline lacks
|
|
6
|
+
// roles nobody without a role can change a role in a way the baseline
|
|
7
|
+
// did not already allow (Halmos, old and new run side by side)
|
|
8
|
+
// guards a call that the baseline rejects from a caller without a role
|
|
9
|
+
// is still rejected (Halmos, same setup)
|
|
10
|
+
//
|
|
11
|
+
// A role is a storage variable of type address or contract, either top-level
|
|
12
|
+
// or a member of an ERC-7201 namespaced storage struct (OpenZeppelin 5).
|
|
13
|
+
const fs = require('node:fs');
|
|
14
|
+
const os = require('node:os');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
const { cast, runHalmos } = require('./tools');
|
|
17
|
+
|
|
18
|
+
/** How many storage slots get an arbitrary starting value in the Halmos checks. */
|
|
19
|
+
const MAX_SLOTS = 24;
|
|
20
|
+
/** Words of arbitrary calldata after the selector. */
|
|
21
|
+
const ARG_WORDS = 4;
|
|
22
|
+
|
|
23
|
+
const DANGEROUS = { 0xf2: 'CALLCODE', 0xf4: 'DELEGATECALL', 0xff: 'SELFDESTRUCT' };
|
|
24
|
+
|
|
25
|
+
/** A type as text that is equal exactly when two types are stored the same way. */
|
|
26
|
+
function describeType(types, id) {
|
|
27
|
+
const t = types?.[id];
|
|
28
|
+
if (!t) return String(id);
|
|
29
|
+
let s = `${t.label}:${t.encoding}:${t.numberOfBytes}`;
|
|
30
|
+
if (t.key) s += `[${describeType(types, t.key)}=>${describeType(types, t.value)}]`;
|
|
31
|
+
if (t.base) s += `<${describeType(types, t.base)}>`;
|
|
32
|
+
if (t.members) s += `{${t.members.map((m) => `${m.slot}.${m.offset}.${describeType(types, m.type)}`).join(',')}}`;
|
|
33
|
+
return s;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Problems that make the new layout unsafe for storage written by the old one. */
|
|
37
|
+
function compareLayouts(oldLayout, newLayout) {
|
|
38
|
+
const problems = [];
|
|
39
|
+
const at = new Map(newLayout.storage.map((v) => [`${v.slot}.${v.offset}`, v]));
|
|
40
|
+
for (const v of oldLayout.storage) {
|
|
41
|
+
const n = at.get(`${v.slot}.${v.offset}`);
|
|
42
|
+
const where = `slot ${v.slot}${v.offset ? ` offset ${v.offset}` : ''}`;
|
|
43
|
+
if (!n) problems.push(`${v.label} (${where}) is gone`);
|
|
44
|
+
// A new name in an old place is how an inserted variable of the same type shows up.
|
|
45
|
+
else if (n.label !== v.label) problems.push(`${where} held ${v.label}, now holds ${n.label}`);
|
|
46
|
+
else if (describeType(oldLayout.types, v.type) !== describeType(newLayout.types, n.type)) {
|
|
47
|
+
problems.push(`${v.label} (${where}) changed type: ${oldLayout.types[v.type].label} became ${newLayout.types[n.type].label}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return problems;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Dangerous opcodes present in runtime bytecode, skipping PUSH data. */
|
|
54
|
+
/** Runtime code without Solidity's CBOR metadata trailer (map + 2-byte length), which is data. */
|
|
55
|
+
function withoutMetadata(code) {
|
|
56
|
+
if (code.length < 2) return code;
|
|
57
|
+
const start = code.length - 2 - code.readUInt16BE(code.length - 2);
|
|
58
|
+
return start >= 0 && start < code.length - 2 && (code[start] & 0xe0) === 0xa0 ? code.subarray(0, start) : code;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function dangerousOpcodes(hex) {
|
|
62
|
+
const code = withoutMetadata(Buffer.from(hex.replace(/^0x/, ''), 'hex'));
|
|
63
|
+
const found = new Set();
|
|
64
|
+
for (let i = 0; i < code.length; i++) {
|
|
65
|
+
const op = code[i];
|
|
66
|
+
if (op >= 0x60 && op <= 0x7f) i += op - 0x5f;
|
|
67
|
+
else if (DANGEROUS[op]) found.add(DANGEROUS[op]);
|
|
68
|
+
}
|
|
69
|
+
return found;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const ROLE_TYPE = /^(address( payable)?$|contract )/;
|
|
73
|
+
const isRole = (types, v) => ROLE_TYPE.test(types[v.type].label);
|
|
74
|
+
const slotHex = (n) => '0x' + n.toString(16).padStart(64, '0');
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Slots of the ordinary variables that hold a plain value. Mappings, strings
|
|
78
|
+
* and dynamic arrays start empty in the checks, and reserved `__gap` arrays
|
|
79
|
+
* are left out.
|
|
80
|
+
*/
|
|
81
|
+
function variableSlots(layout) {
|
|
82
|
+
const slots = [];
|
|
83
|
+
for (const v of layout.storage) {
|
|
84
|
+
if (v.label === '__gap' || layout.types[v.type].encoding !== 'inplace') continue;
|
|
85
|
+
const words = Math.ceil(Number(layout.types[v.type].numberOfBytes) / 32);
|
|
86
|
+
for (let i = 0; i < words; i++) slots.push(BigInt(v.slot) + BigInt(i));
|
|
87
|
+
}
|
|
88
|
+
return slots;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Bytes a struct member takes when packed, 32 for one that owns its slot, null if unknown. */
|
|
92
|
+
function memberSize(type) {
|
|
93
|
+
if (ROLE_TYPE.test(type)) return 20;
|
|
94
|
+
if (type === 'bool' || type.startsWith('enum ')) return 1;
|
|
95
|
+
let m = type.match(/^u?int(\d*)$/);
|
|
96
|
+
if (m) return m[1] ? Number(m[1]) / 8 : 32;
|
|
97
|
+
m = type.match(/^bytes(\d+)$/);
|
|
98
|
+
if (m) return Number(m[1]);
|
|
99
|
+
if (isDynamic(type)) return 32;
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const isDynamic = (type) => type.startsWith('mapping(') || type.endsWith('[]') || type === 'string' || type === 'bytes';
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* ERC-7201 namespaced storage structs declared anywhere in the build, as
|
|
106
|
+
* { id, base, members: [{ label, slot, offset, role, plain }], complete }.
|
|
107
|
+
*/
|
|
108
|
+
async function namespaces(dir) {
|
|
109
|
+
const out = path.join(dir, 'out');
|
|
110
|
+
const structs = new Map();
|
|
111
|
+
const walk = (node) => {
|
|
112
|
+
if (!node || typeof node !== 'object') return;
|
|
113
|
+
if (Array.isArray(node)) return node.forEach(walk);
|
|
114
|
+
const doc = node.nodeType === 'StructDefinition' && (node.documentation?.text ?? node.documentation);
|
|
115
|
+
const id = typeof doc === 'string' && doc.match(/@custom:storage-location\s+erc7201:(\S+)/)?.[1];
|
|
116
|
+
if (id) structs.set(id, node);
|
|
117
|
+
Object.values(node).forEach(walk);
|
|
118
|
+
};
|
|
119
|
+
for (const d of fs.readdirSync(out)) {
|
|
120
|
+
if (d === 'build-info') continue;
|
|
121
|
+
for (const f of fs.readdirSync(path.join(out, d))) walk(JSON.parse(fs.readFileSync(path.join(out, d, f), 'utf8')).ast);
|
|
122
|
+
}
|
|
123
|
+
const found = [];
|
|
124
|
+
for (const [id, node] of structs) {
|
|
125
|
+
// keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~0xff
|
|
126
|
+
const inner = BigInt(await cast(['keccak', id])) - 1n;
|
|
127
|
+
const base = BigInt(await cast(['keccak', slotHex(inner)])) & ~0xffn;
|
|
128
|
+
const members = [];
|
|
129
|
+
let [slot, offset, complete] = [base, 0, true];
|
|
130
|
+
for (const m of node.members) {
|
|
131
|
+
const type = m.typeDescriptions?.typeString || '';
|
|
132
|
+
const size = memberSize(type);
|
|
133
|
+
if (size === null) {
|
|
134
|
+
complete = false;
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
if (offset + size > 32) [slot, offset] = [slot + 1n, 0];
|
|
138
|
+
members.push({ label: `${node.name}.${m.name}`, slot, offset, role: size === 20, plain: !isDynamic(type) });
|
|
139
|
+
offset += size;
|
|
140
|
+
}
|
|
141
|
+
found.push({ id, base, members, complete });
|
|
142
|
+
}
|
|
143
|
+
return found;
|
|
144
|
+
}
|
|
145
|
+
const mutating = (artifact) =>
|
|
146
|
+
artifact.abi.filter((f) => f.type === 'function' && f.stateMutability !== 'view' && f.stateMutability !== 'pure');
|
|
147
|
+
const signature = (f) => `${f.name}(${f.inputs.map((i) => i.type).join(',')})`;
|
|
148
|
+
|
|
149
|
+
/** Solidity source of the Halmos harness that runs old and new side by side. */
|
|
150
|
+
function harnessSource({ oldCode, newCode, slots, roles, oldSelectors }) {
|
|
151
|
+
// `slots` are the storage slots that start with an arbitrary value; a role's
|
|
152
|
+
// `index` says which of them holds it.
|
|
153
|
+
const at = (i) => `bytes32(uint256(${slotHex(slots[i])}))`;
|
|
154
|
+
const stores = [];
|
|
155
|
+
for (let i = 0; i < slots.length; i++) {
|
|
156
|
+
stores.push(` vm.store(OLD, ${at(i)}, s[${i}]);`, ` vm.store(NEW, ${at(i)}, s[${i}]);`);
|
|
157
|
+
}
|
|
158
|
+
const mask = (r) => `(uint256(type(uint160).max) << ${8 * r.offset})`;
|
|
159
|
+
const notRole = roles.map((r) => ` vm.assume(caller != address(uint160(uint256(s[${r.index}]) >> ${8 * r.offset})));`);
|
|
160
|
+
const roleAsserts = roles.map(
|
|
161
|
+
(r) => ` {
|
|
162
|
+
uint256 was = uint256(s[${r.index}]) & ${mask(r)};
|
|
163
|
+
uint256 now_ = uint256(vm.load(NEW, ${at(r.index)})) & ${mask(r)};
|
|
164
|
+
if (now_ != was) assert(uint256(vm.load(OLD, ${at(r.index)})) & ${mask(r)} == now_);
|
|
165
|
+
}`,
|
|
166
|
+
);
|
|
167
|
+
const selectorSet = oldSelectors.map((x) => `sel == 0x${x}`).join(' || ');
|
|
168
|
+
const guards = oldSelectors.length
|
|
169
|
+
? `
|
|
170
|
+
/// A call the baseline rejects from a caller without a role stays rejected.
|
|
171
|
+
function check_guards(address caller, bytes4 sel, bytes32[${ARG_WORDS}] memory a, bytes32[${slots.length}] memory s) public {
|
|
172
|
+
vm.assume(${selectorSet});
|
|
173
|
+
(bool okOld, bool okNew) = _call(caller, sel, a, s);
|
|
174
|
+
assert(okOld || !okNew);
|
|
175
|
+
}
|
|
176
|
+
`
|
|
177
|
+
: '';
|
|
178
|
+
return `// SPDX-License-Identifier: MIT
|
|
179
|
+
// Generated by GuardeFi. Do not edit.
|
|
180
|
+
pragma solidity ^0.8.0;
|
|
181
|
+
|
|
182
|
+
interface Vm {
|
|
183
|
+
function store(address target, bytes32 slot, bytes32 value) external;
|
|
184
|
+
function load(address target, bytes32 slot) external view returns (bytes32);
|
|
185
|
+
function prank(address sender) external;
|
|
186
|
+
function assume(bool condition) external;
|
|
187
|
+
function etch(address target, bytes calldata code) external;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
contract Generic {
|
|
191
|
+
Vm internal constant vm = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D);
|
|
192
|
+
address internal constant OLD = address(uint160(0xA11CE));
|
|
193
|
+
address internal constant NEW = address(uint160(0xB0B));
|
|
194
|
+
|
|
195
|
+
function setUp() public {
|
|
196
|
+
vm.etch(OLD, hex"${oldCode}");
|
|
197
|
+
vm.etch(NEW, hex"${newCode}");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// Same arbitrary storage in both, same call from a caller who holds no role.
|
|
201
|
+
function _call(address caller, bytes4 sel, bytes32[${ARG_WORDS}] memory a, bytes32[${slots.length}] memory s)
|
|
202
|
+
internal
|
|
203
|
+
returns (bool okOld, bool okNew)
|
|
204
|
+
{
|
|
205
|
+
${stores.join('\n')}
|
|
206
|
+
${notRole.join('\n')}
|
|
207
|
+
bytes memory data = abi.encodePacked(sel, a[0], a[1], a[2], a[3]);
|
|
208
|
+
vm.prank(caller);
|
|
209
|
+
(okNew,) = NEW.call(data);
|
|
210
|
+
vm.prank(caller);
|
|
211
|
+
(okOld,) = OLD.call(data);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// A role changes under the new code only the way it would under the old.
|
|
215
|
+
function check_roles(address caller, bytes4 sel, bytes32[${ARG_WORDS}] memory a, bytes32[${slots.length}] memory s) public {
|
|
216
|
+
_call(caller, sel, a, s);
|
|
217
|
+
${roleAsserts.join('\n')}
|
|
218
|
+
}
|
|
219
|
+
${guards}}
|
|
220
|
+
`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The counterexample as the caller and the call, not the raw storage words. */
|
|
224
|
+
function explain(counterexample, names) {
|
|
225
|
+
const out = {};
|
|
226
|
+
const get = (re) => Object.entries(counterexample).find(([k]) => re.test(k))?.[1];
|
|
227
|
+
const caller = get(/caller/);
|
|
228
|
+
if (caller) out.caller = caller;
|
|
229
|
+
const sel = get(/(^|[^a-z])sel/);
|
|
230
|
+
if (sel !== undefined) {
|
|
231
|
+
const hex = BigInt(sel).toString(16).padStart(8, '0').slice(0, 8);
|
|
232
|
+
out.call = names[hex] || `0x${hex}`;
|
|
233
|
+
}
|
|
234
|
+
for (const [k, v] of Object.entries(counterexample)) {
|
|
235
|
+
const m = k.match(/(^|[^a-z])a\[(\d)\]/);
|
|
236
|
+
if (m) out[`arg${m[2]}`] = v;
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Run the generic checks. Both artifacts are forge build outputs that include
|
|
243
|
+
* the storage layout.
|
|
244
|
+
* Returns [{ name, proven, detail, counterexample }] in a fixed order.
|
|
245
|
+
*/
|
|
246
|
+
async function upgradeChecks({ dir, contract, baseline, artifact, baseArtifact, strict = false }) {
|
|
247
|
+
const [oldLayout, newLayout] = [baseArtifact.storageLayout, artifact.storageLayout];
|
|
248
|
+
if (!oldLayout?.storage || !newLayout?.storage) throw new Error('build artifacts carry no storage layout');
|
|
249
|
+
const checks = [];
|
|
250
|
+
|
|
251
|
+
const layoutProblems = compareLayouts(oldLayout, newLayout);
|
|
252
|
+
checks.push({ name: 'layout', proven: layoutProblems.length === 0, detail: layoutProblems.join('; '), counterexample: null });
|
|
253
|
+
|
|
254
|
+
const had = dangerousOpcodes(baseArtifact.deployedBytecode.object);
|
|
255
|
+
const added = [...dangerousOpcodes(artifact.deployedBytecode.object)].filter((op) => !had.has(op));
|
|
256
|
+
checks.push({ name: 'opcodes', proven: added.length === 0, detail: added.length ? `new in this code: ${added.join(', ')}` : '', counterexample: null });
|
|
257
|
+
|
|
258
|
+
// Namespaced structs count when the code mentions their base slot.
|
|
259
|
+
const [oldHex, newHex] = [baseArtifact, artifact].map((a) => a.deployedBytecode.object.toLowerCase());
|
|
260
|
+
const mentions = (hex, ns) => hex.includes(slotHex(ns.base).slice(2));
|
|
261
|
+
const spaces = (await namespaces(dir)).filter((ns) => mentions(oldHex, ns) || mentions(newHex, ns));
|
|
262
|
+
|
|
263
|
+
const slotSet = new Set([...variableSlots(oldLayout), ...variableSlots(newLayout)]);
|
|
264
|
+
for (const ns of spaces) for (const m of ns.members) if (m.plain) slotSet.add(m.slot);
|
|
265
|
+
const slots = [...slotSet].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
266
|
+
if (slots.length === 0) slots.push(0n);
|
|
267
|
+
|
|
268
|
+
const roles = [
|
|
269
|
+
...oldLayout.storage.filter((v) => isRole(oldLayout.types, v)).map((v) => ({ label: v.label, slot: BigInt(v.slot), offset: v.offset })),
|
|
270
|
+
...spaces.filter((ns) => mentions(oldHex, ns)).flatMap((ns) => ns.members.filter((m) => m.role)),
|
|
271
|
+
].map((r) => ({ ...r, index: slots.indexOf(r.slot) }));
|
|
272
|
+
|
|
273
|
+
// Fail closed on what the checks cannot see.
|
|
274
|
+
const unread = spaces.filter((ns) => !ns.complete).map((ns) => ns.id);
|
|
275
|
+
const blind = unread.length
|
|
276
|
+
? `could not read the namespaced storage of ${unread.join(', ')}`
|
|
277
|
+
: slots.length > MAX_SLOTS
|
|
278
|
+
? `storage uses ${slots.length} slots, more than the ${MAX_SLOTS} these checks cover`
|
|
279
|
+
: '';
|
|
280
|
+
if (blind) {
|
|
281
|
+
checks.push({ name: 'roles', proven: false, status: 'unknown', detail: blind, counterexample: null }, { name: 'guards', proven: false, status: 'unknown', detail: blind, counterexample: null });
|
|
282
|
+
return checks;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const oldSelectors = mutating(baseArtifact).map((f) => baseArtifact.methodIdentifiers[signature(f)]);
|
|
286
|
+
const names = {};
|
|
287
|
+
for (const a of [baseArtifact, artifact]) for (const [sig, sel] of Object.entries(a.methodIdentifiers || {})) names[sel] = sig;
|
|
288
|
+
|
|
289
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'guardefi-generic-'));
|
|
290
|
+
let results;
|
|
291
|
+
try {
|
|
292
|
+
const solc = String(artifact.metadata?.compiler?.version || '').split('+')[0];
|
|
293
|
+
fs.writeFileSync(path.join(tmp, 'foundry.toml'), `[profile.default]\nsrc = "src"\ntest = "test"\nout = "out"\n${solc ? `solc = "${solc}"\n` : ''}`);
|
|
294
|
+
fs.mkdirSync(path.join(tmp, 'test'));
|
|
295
|
+
fs.writeFileSync(
|
|
296
|
+
path.join(tmp, 'test', 'Generic.t.sol'),
|
|
297
|
+
harnessSource({
|
|
298
|
+
oldCode: baseArtifact.deployedBytecode.object.replace(/^0x/, ''),
|
|
299
|
+
newCode: artifact.deployedBytecode.object.replace(/^0x/, ''),
|
|
300
|
+
slots,
|
|
301
|
+
roles,
|
|
302
|
+
oldSelectors,
|
|
303
|
+
}),
|
|
304
|
+
);
|
|
305
|
+
results = await runHalmos(tmp, 'Generic', ['--solver', 'bitwuzla', '--solver-timeout-assertion', '10s', '--loop', '2']);
|
|
306
|
+
} finally {
|
|
307
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const roleNames = roles.map((r) => r.label).join(', ');
|
|
311
|
+
const fromHalmos = (name, check, failed) => {
|
|
312
|
+
const r = results[check];
|
|
313
|
+
const proven = Boolean(r?.proven && (!strict || r.boundedLoops === 0));
|
|
314
|
+
const validFailure = Boolean(r && r.exitcode === 1 && r.validModel);
|
|
315
|
+
const explained = validFailure ? explain(r.counterexample, names) : null;
|
|
316
|
+
const counterexample = explained && Object.keys(explained).length ? explained : null;
|
|
317
|
+
// A failure without a valid counterexample model is Halmos giving up, not a finding.
|
|
318
|
+
const detail = proven ? '' : !r ? 'Halmos gave no result' : validFailure ? failed : 'Halmos could not finish this check';
|
|
319
|
+
const status = proven ? 'proven' : validFailure ? 'failed' : (r?.exitcode === 0 && r.boundedLoops > 0) ? 'bounded' : 'unknown';
|
|
320
|
+
return { name, proven, status, detail, counterexample };
|
|
321
|
+
};
|
|
322
|
+
checks.push(
|
|
323
|
+
roles.length
|
|
324
|
+
? fromHalmos('roles', 'check_roles', `a caller without a role can change ${roleNames}`)
|
|
325
|
+
: { name: 'roles', proven: true, detail: 'the baseline has no role variables', counterexample: null },
|
|
326
|
+
oldSelectors.length
|
|
327
|
+
? fromHalmos('guards', 'check_guards', 'a call the baseline rejects now goes through')
|
|
328
|
+
: { name: 'guards', proven: true, detail: 'the baseline has no state-changing functions', counterexample: null },
|
|
329
|
+
);
|
|
330
|
+
return checks;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
module.exports = {
|
|
334
|
+
withoutMetadata, upgradeChecks, compareLayouts, dangerousOpcodes, namespaces, variableSlots };
|