@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.
Files changed (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +18 -0
  3. package/README.md +31 -2
  4. package/assurance/cli-check.js +446 -0
  5. package/assurance/cli-project-paths.js +56 -0
  6. package/assurance/cli-storage.js +289 -0
  7. package/assurance/cli-ui.js +617 -0
  8. package/assurance/guardefi-public.js +66 -0
  9. package/assurance/release-policy.js +212 -0
  10. package/core/behavioral-diff.js +555 -0
  11. package/core/canonical-json.js +9 -0
  12. package/core/engine/abi.js +99 -0
  13. package/core/engine/assumptions.json +86 -0
  14. package/core/engine/bytecode.js +119 -0
  15. package/core/engine/callee-binding.js +140 -0
  16. package/core/engine/deployment.js +175 -0
  17. package/core/engine/external-effects.js +40 -0
  18. package/core/engine/harness.js +503 -0
  19. package/core/engine/index.js +638 -0
  20. package/core/engine/integrity.js +124 -0
  21. package/core/engine/model.js +369 -0
  22. package/core/engine/policy.js +59 -0
  23. package/core/engine/proof-certificate.js +69 -0
  24. package/core/engine/provenance.js +354 -0
  25. package/core/engine/screen.js +117 -0
  26. package/core/engine/upgrade-authority.js +327 -0
  27. package/core/generic.js +334 -0
  28. package/core/hardhat.js +114 -0
  29. package/core/isl/behavior-profile.js +169 -0
  30. package/core/isl/behavior-solidity.js +267 -0
  31. package/core/isl/behavior-storage.js +151 -0
  32. package/core/isl/behavior-verify.js +223 -0
  33. package/core/isl/getter-profile.js +149 -0
  34. package/core/isl/vendor/NOTICE.md +38 -0
  35. package/core/isl/vendor/isl-parser.cjs +5872 -0
  36. package/core/isl-compiler.js +19 -0
  37. package/core/isl-firewall.js +1396 -0
  38. package/core/keccak.js +89 -0
  39. package/core/prove.js +376 -0
  40. package/core/release-receipt.js +793 -0
  41. package/core/rpc.js +74 -0
  42. package/core/tools.js +129 -0
  43. package/core/verdict-policy.js +195 -0
  44. package/docs/public-cli.md +32 -0
  45. package/package.json +29 -4
@@ -0,0 +1,503 @@
1
+ // Solidity source of the Halmos harness for one upgrade. Old and new code run
2
+ // behind two small proxies that start from the same arbitrary storage.
3
+ const { ERC1967, hex32 } = require('./model');
4
+
5
+ const VICTIM = 'address(uint160(0x71C7104))';
6
+ const comment = (value) => String(value).replace(/[\r\n\u2028\u2029]/g, ' ');
7
+ const mask = (f) => (f.size === 32 ? 'type(uint256).max' : `((uint256(1) << ${8 * f.size}) - 1)`);
8
+ const CONTEXT = {
9
+ TIMESTAMP: ['warp', 'uint256'],
10
+ NUMBER: ['roll', 'uint256'],
11
+ CHAINID: ['chainId', 'uint256'],
12
+ BASEFEE: ['fee', 'uint256'],
13
+ COINBASE: ['coinbase', 'address'],
14
+ PREVRANDAO: ['difficulty', 'uint256'],
15
+ };
16
+
17
+ /**
18
+ * `plan.checks` is a list of checks to emit:
19
+ * { name, kind, ... } with kind one of
20
+ * guard { shape, klass|null, notIn: [klass] } new accepts => old accepts
21
+ * mutation { target, shapes, skip: [shape] } new changes target => old changes it
22
+ * value { observable, shapes, skip } same call => same observable
23
+ * reach { side, target, klass|null, shapes, skip, fix?, zero? } target unchanged (a counterexample means "can change")
24
+ * lock { side } calls to the bare implementation change nothing
25
+ * initRuns {} the initializer call can succeed
26
+ * equiv { shape } same outcome, same tracked state after the call
27
+ */
28
+ function harnessSource(model, plan) {
29
+ const { words, fields, classes, observables, shapes } = model;
30
+ const context = (plan.context || []).map((op) => CONTEXT[op]);
31
+ const sym = words.map((w, i) => (w.symbolic ? i : -1)).filter((i) => i >= 0);
32
+ const symIndex = new Map(sym.map((w, j) => [w, j]));
33
+ const extra = model.vault ? 5 : 0; // asset token balances and allowances
34
+ const S = Math.max(sym.length + extra, 1);
35
+ const A = Math.max(1, ...shapes.map((s) => s.words.filter((w) => w === 'sym').length));
36
+
37
+ const keyExpr = (k) => (k === 'caller' ? 'x.caller' : k === 'victim' ? 'VICTIM' : k === 'self' ? 'p' : k === 'tid' ? 'x.tid' : `bytes32(${hex32(k.const)})`);
38
+ const slotExpr = (w) => {
39
+ let e = `uint256(${hex32(w.root)})`;
40
+ for (const s of w.steps) e = s.key ? `uint256(keccak256(abi.encode(${keyExpr(s.key)}, ${e})))` : s.add ? `(${e} + ${s.add})` : e;
41
+ return `bytes32(${e})`;
42
+ };
43
+ // A field's starting value, straight from the arbitrary words.
44
+ const start = (i) => {
45
+ const f = fields[i];
46
+ return f.dynamic ? 'uint256(0)' : `((uint256(x.s[${symIndex.get(f.word)}]) >> ${8 * f.offset}) & ${mask(f)})`;
47
+ };
48
+ const startAddr = (i) => `address(uint160(${start(i)}))`;
49
+
50
+ const roleFields = fields.map((f, i) => ({ f, i })).filter(({ f, i }) => classes.some((c) => c.kind === 'is' && c.field === i));
51
+ const heldFields = fields.map((f, i) => ({ f, i })).filter(({ i }) => classes.some((c) => c.kind === 'holds' && c.field === i));
52
+ const classExpr = (c) => {
53
+ const parts = [];
54
+ for (const { i } of roleFields) parts.push(c.kind === 'is' && c.field === i ? `x.caller == ${startAddr(i)}` : `x.caller != ${startAddr(i)}`);
55
+ for (const { i } of heldFields) parts.push(c.kind === 'holds' && c.field === i ? `${start(i)} != 0` : `${start(i)} == 0`);
56
+ return parts.length ? parts.join(' && ') : 'true';
57
+ };
58
+
59
+ const dataExpr = (s) => {
60
+ let a = 0;
61
+ const parts = s.selector ? [`bytes4(0x${s.selector})`] : [];
62
+ for (const word of s.words) {
63
+ if (word !== 'sym') parts.push(`bytes32(uint256(${word}))`);
64
+ else {
65
+ const bytes = s.partial?.[a];
66
+ const source = `x.a[${a++}]`;
67
+ parts.push(bytes ? `bytes32(bytes${bytes}(${source}))` : source);
68
+ }
69
+ }
70
+ if (!parts.length) return 'bytes("")';
71
+ // Large dynamic-argument heads exceed Solc's stack limit in one encode.
72
+ // Concatenating bounded chunks preserves the exact calldata bytes.
73
+ const chunks = [];
74
+ for (let i = 0; i < parts.length; i += 8) chunks.push(`abi.encodePacked(${parts.slice(i, i + 8).join(', ')})`);
75
+ return chunks.length === 1 ? chunks[0] : `bytes.concat(${chunks.join(', ')})`;
76
+ };
77
+
78
+ const targetExpr = (t) => {
79
+ if (t.kind === 'slot') return `uint256(vm.load(p, bytes32(${hex32(t.slot)})))`;
80
+ if (t.kind === 'observable') return `_obs(${t.observable}, p, x)`;
81
+ const f = fields[t.field];
82
+ return f.dynamic ? `uint256(vm.load(p, _w(${f.word}, p, x)))` : `((uint256(vm.load(p, _w(${f.word}, p, x))) >> ${8 * f.offset}) & ${mask(f)})`;
83
+ };
84
+ const obsExpr = (o) => {
85
+ if (o.kind === 'eth') return 'p.balance';
86
+ if (o.kind === 'asset') return `ASSET.balanceIn(p == PN ? 1 : 0, ${o.who === 'self' ? 'address(1)' : 'VICTIM'})`;
87
+ const arg = o.arg === 'victim' ? 'uint256(uint160(VICTIM))' : o.arg === 'caller' ? 'uint256(uint160(x.caller))' : o.arg === 'tid' ? 'x.tid' : null;
88
+ return `_view(p, ${arg === null ? `abi.encodePacked(bytes4(0x${o.selector}))` : `abi.encodePacked(bytes4(0x${o.selector}), ${arg})`})`;
89
+ };
90
+
91
+ const pick = (list, skip = []) => {
92
+ const ok = list.filter((i) => !skip.includes(i));
93
+ return ok.length ? `vm.assume(${ok.map((i) => `x.which == ${i}`).join(' || ')});` : 'vm.assume(false);';
94
+ };
95
+ const SIG = `address caller, address admin, uint256 tid, uint256 which, uint256 eth, bytes32[${A}] memory a, bytes32[${S}] memory s${context.length ? `, uint256[${context.length}] memory blockContext` : ''}`;
96
+ const input = `In memory x = In(caller, admin, tid, which, eth, a, s${context.length ? ', blockContext' : ''});`;
97
+ // One assertion per path: `bad` collects without branching whether any
98
+ // compared value differs.
99
+ const flag = (cond) => `assembly { bad := or(bad, ${cond}) }`;
100
+ // A reach check may start from one given state (`fix`: values from another
101
+ // check's counterexample) or from a default one (`zero`: every tracked word
102
+ // zero except the live flags and what makes the caller kind `zero`).
103
+ const num = (v) => BigInt(v).toString();
104
+ const fixed = (f) => [
105
+ ...['caller', 'admin'].filter((k) => f[k] !== undefined).map((k) => `vm.assume(x.${k} == address(uint160(${num(f[k])})));`),
106
+ ...['tid', 'eth'].filter((k) => f[k] !== undefined).map((k) => `vm.assume(x.${k} == ${num(f[k])});`),
107
+ ...Object.entries(f.s || {}).map(([j, v]) => `vm.assume(x.s[${j}] == bytes32(uint256(${num(v)})));`),
108
+ ];
109
+ const defaults = (k) => {
110
+ const keep = new Set([...model.live.nonzero, ...model.live.zero, ...(classes[k]?.field !== undefined ? [classes[k].field] : [])].map((i) => fields[i].word));
111
+ return sym.filter((w) => !keep.has(w)).map((w) => `vm.assume(x.s[${symIndex.get(w)}] == 0);`);
112
+ };
113
+ const open = (c = {}) => [
114
+ input,
115
+ ...(c.fix ? fixed(c.fix) : []),
116
+ ...(c.zero !== undefined ? defaults(c.zero) : []),
117
+ ...(plan.screen ? ['_screenDomain(x);'] : []),
118
+ '_state(x);',
119
+ ].join('\n ');
120
+ const OPEN = open();
121
+
122
+ const checks = plan.checks.map((c) => {
123
+ if (c.kind === 'contextCompare') {
124
+ return `
125
+ function check_${c.name}(${SIG}) public {
126
+ ${input}
127
+ ${pick(c.shapes)}
128
+ _state(x);
129
+ bytes memory data = _data(x);
130
+ vm.prank(x.caller);
131
+ (bool oldOk, bytes memory oldData) = PO.call(data);
132
+ vm.prank(x.caller);
133
+ (bool newOk, bytes memory newData) = PN.call(data);
134
+ assert(oldOk == newOk && oldData.length == newData.length && keccak256(oldData) == keccak256(newData));
135
+ }`;
136
+ }
137
+ const klass = c.klass !== null && c.klass !== undefined ? `\n vm.assume(_in(${c.klass}, x));` : '';
138
+ if (c.kind === 'guard') {
139
+ const notIn = (c.notIn || []).map((k) => `\n vm.assume(!_in(${k}, x));`).join('');
140
+ return `
141
+ function check_${c.name}(${SIG}) public {
142
+ ${OPEN}${klass}${notIn}
143
+ vm.assume(x.which == ${c.shape});
144
+ bool okNew = _call(PN, x);
145
+ bool okOld = _call(PO, x);
146
+ assert(okOld || !okNew);
147
+ }`;
148
+ }
149
+ if (c.kind === 'initOpen') {
150
+ const reads = words.map((_, i) => `vm.load(PN, _w(${i}, PN, x))`);
151
+ return `
152
+ function check_${c.name}(${SIG}) public {
153
+ ${OPEN}${klass}
154
+ vm.assume(x.which == ${c.shape});
155
+ bytes32[] memory was = new bytes32[](${reads.length});
156
+ ${reads.map((r, k) => `was[${k}] = ${r};`).join('\n ')}
157
+ bool ok = _call(PN, x);
158
+ if (!ok) return;
159
+ uint256 bad;
160
+ ${reads.map((r, k) => `{ bytes32 n = ${r}; bytes32 w = was[${k}]; ${flag('iszero(eq(n, w))')} }`).join('\n ')}
161
+ assert(bad == 0);
162
+ }`;
163
+ }
164
+ if (c.kind === 'mutation') {
165
+ const t = model.targets[c.target];
166
+ return `
167
+ function check_${c.name}(${SIG}) public {
168
+ ${OPEN}
169
+ ${pick(c.shapes, c.skip)}
170
+ uint256 wasNew = _t${c.target}(PN, x);
171
+ uint256 wasOld = _t${c.target}(PO, x);
172
+ _call(PN, x);
173
+ _call(PO, x);
174
+ if (_t${c.target}(PN, x) != wasNew) assert(_t${c.target}(PO, x) != wasOld); // ${comment(t.label)}
175
+ }`;
176
+ }
177
+ if (c.kind === 'value') {
178
+ return `
179
+ function check_${c.name}(${SIG}) public {
180
+ ${OPEN}
181
+ ${pick(c.shapes, c.skip)}
182
+ bool okNew = _call(PN, x);
183
+ bool okOld = _call(PO, x);
184
+ if (okNew && okOld) assert(_obs(${c.observable}, PN, x) == _obs(${c.observable}, PO, x));
185
+ }`;
186
+ }
187
+ if (c.kind === 'reach') {
188
+ const p = c.side === 'new' ? 'PN' : 'PO';
189
+ return `
190
+ function check_${c.name}(${SIG}) public {
191
+ ${open(c)}${klass}
192
+ ${pick(c.shapes, c.skip)}
193
+ uint256 was = _t${c.target}(${p}, x);
194
+ _call(${p}, x);
195
+ assert(_t${c.target}(${p}, x) == was);
196
+ }`;
197
+ }
198
+ if (c.kind === 'equiv') {
199
+ // Same outcome, and every tracked word, proxy slot and the ETH balance
200
+ // either ends identical from an identical start or is left alone in
201
+ // both worlds. That settles the guard and every mutation check of this
202
+ // call. The implementation slot differs by construction.
203
+ const reads = [
204
+ ...words.map((_, i) => [`vm.load(PN, _w(${i}, PN, x))`, `vm.load(PO, _w(${i}, PO, x))`]),
205
+ ...Object.entries(ERC1967).filter(([k]) => k !== 'implementation').map(([, slot]) => [`vm.load(PN, bytes32(${hex32(slot)}))`, `vm.load(PO, bytes32(${hex32(slot)}))`]),
206
+ ['bytes32(PN.balance)', 'bytes32(PO.balance)'],
207
+ ];
208
+ const before = reads.map(([n, o], k) => `bn[${k}] = ${n}; bo[${k}] = ${o};`).join('\n ');
209
+ const test = reads.map(([n, o], k) => `{ bytes32 na = ${n}; bytes32 oa = ${o}; bytes32 nb = bn[${k}]; bytes32 ob = bo[${k}]; ${flag('and(iszero(and(eq(na, oa), eq(nb, ob))), iszero(and(eq(na, nb), eq(oa, ob))))')} }`).join('\n ');
210
+ return `
211
+ function check_${c.name}(${SIG}) public {
212
+ ${OPEN}
213
+ vm.assume(x.which == ${c.shape});
214
+ bytes32[] memory bn = new bytes32[](${reads.length});
215
+ bytes32[] memory bo = new bytes32[](${reads.length});
216
+ ${before}
217
+ bool okNew = _call(PN, x);
218
+ bool okOld = _call(PO, x);
219
+ uint256 bad;
220
+ ${flag('xor(okNew, okOld)')}
221
+ ${test}
222
+ assert(bad == 0);
223
+ }`;
224
+ }
225
+ if (c.kind === 'lock') {
226
+ const impl = c.side === 'new' ? 'NEW_IMPL' : 'OLD_IMPL';
227
+ const list = shapes.map((s, i) => ({ s, i })).filter(({ s }) => (c.side === 'new' ? s.inNew : s.inOld)).map(({ i }) => i);
228
+ const reads = [...words.map((_, i) => `vm.load(${impl}, _w(${i}, ${impl}, x))`), ...Object.values(ERC1967).map((slot) => `vm.load(${impl}, bytes32(${hex32(slot)}))`)];
229
+ return `
230
+ function check_${c.name}(${SIG}) public {
231
+ ${input}
232
+ _who(x);
233
+ ${pick(list)}
234
+ bytes32[] memory was = new bytes32[](${reads.length});
235
+ ${reads.map((r, k) => `was[${k}] = ${r};`).join('\n ')}
236
+ vm.prank(x.caller);
237
+ (bool ok,) = ${impl}.call(_data(x));
238
+ ok;
239
+ uint256 bad;
240
+ ${reads.map((r, k) => `{ bytes32 n = ${r}; bytes32 w = was[${k}]; ${flag('iszero(eq(n, w))')} }`).join('\n ')}
241
+ assert(bad == 0);
242
+ }`;
243
+ }
244
+ if (c.kind === 'initRuns') {
245
+ return `
246
+ function check_${c.name}(${SIG}) public {
247
+ ${input}
248
+ _prepare(x);
249
+ vm.prank(x.admin);
250
+ (bool ok,) = PN.call(INIT);
251
+ assert(!ok);
252
+ }`;
253
+ }
254
+ throw new Error(`unknown check kind ${c.kind}`);
255
+ });
256
+
257
+ const usedTargets = [...new Set(plan.checks.filter((c) => c.target !== undefined).map((c) => c.target))];
258
+ const linked = (hex, links = []) => links.reduce((code, ref) => `_link(${code}, ${ref.start}, LIBRARIES[${ref.library}])`, `hex"${hex}"`);
259
+ const deploy = (code, runtime, name, side) =>
260
+ code
261
+ ? `${name} = _deploy(${linked(code, model.creationLinks?.[side])});`
262
+ : `${name} = address(uint160(0x${name === 'OLD_IMPL' ? '01D' : '4E3'}C0DE)); vm.etch(${name}, ${linked(runtime, model.runtimeLinks?.[side])});`;
263
+
264
+ const stores = sym.map((w, j) => ` vm.store(PO, _w(${w}, PO, x), x.s[${j}]);\n vm.store(PN, _w(${w}, PN, x), x.s[${j}]);`);
265
+ const live = [
266
+ ...model.live.nonzero.map((i) => ` vm.assume(${start(i)} != 0);`),
267
+ ...model.live.zero.map((i) => ` vm.assume(${start(i)} == 0);`),
268
+ ];
269
+ const assetSetup = model.vault
270
+ ? `
271
+ ASSET.set(0, address(1), uint256(x.s[${sym.length}]));
272
+ ASSET.set(1, address(1), uint256(x.s[${sym.length}]));
273
+ ASSET.set(0, x.caller, uint256(x.s[${sym.length + 1}]));
274
+ ASSET.set(1, x.caller, uint256(x.s[${sym.length + 1}]));
275
+ ASSET.set(0, VICTIM, uint256(x.s[${sym.length + 2}]));
276
+ ASSET.set(1, VICTIM, uint256(x.s[${sym.length + 2}]));
277
+ ASSET.allow(0, x.caller, uint256(x.s[${sym.length + 3}]));
278
+ ASSET.allow(1, x.caller, uint256(x.s[${sym.length + 3}]));
279
+ ASSET.allow(0, VICTIM, uint256(x.s[${sym.length + 4}]));
280
+ ASSET.allow(1, VICTIM, uint256(x.s[${sym.length + 4}]));
281
+ vm.assume(_view(PO, abi.encodePacked(bytes4(0x38d52e0f))) == uint256(uint160(address(ASSET))));`
282
+ : '';
283
+
284
+ return `// SPDX-License-Identifier: MIT
285
+ // Generated by GuardeFi. Do not edit.
286
+ pragma solidity ^0.8.0;
287
+
288
+ interface Vm {
289
+ function store(address target, bytes32 slot, bytes32 value) external;
290
+ function load(address target, bytes32 slot) external view returns (bytes32);
291
+ function prank(address sender) external;
292
+ function assume(bool condition) external;
293
+ function etch(address target, bytes calldata code) external;
294
+ function deal(address who, uint256 amount) external;
295
+ ${context.map(([name, type]) => ` function ${name}(${type}) external;`).join('\n')}
296
+ }
297
+
298
+ /// Forwards every call to the implementation in the ERC-1967 slot.
299
+ contract Prox {
300
+ fallback() external payable {
301
+ assembly {
302
+ let impl := sload(${hex32(ERC1967.implementation)})
303
+ calldatacopy(0, 0, calldatasize())
304
+ let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
305
+ returndatacopy(0, 0, returndatasize())
306
+ switch ok
307
+ case 0 { revert(0, returndatasize()) }
308
+ default { return(0, returndatasize()) }
309
+ }
310
+ }
311
+ }
312
+
313
+ /// The vault's asset. Old and new proxy each see their own balances, with the
314
+ /// proxy itself under the key address(1).
315
+ contract Asset {
316
+ address public po;
317
+ address public pn;
318
+ mapping(uint256 => mapping(address => uint256)) public balanceIn;
319
+ mapping(uint256 => mapping(address => uint256)) public allowedToVault;
320
+
321
+ function bind(address po_, address pn_) external {
322
+ po = po_;
323
+ pn = pn_;
324
+ }
325
+
326
+ function set(uint256 world, address who, uint256 amount) external {
327
+ balanceIn[world][who] = amount;
328
+ }
329
+
330
+ function allow(uint256 world, address who, uint256 amount) external {
331
+ allowedToVault[world][who] = amount;
332
+ }
333
+
334
+ function _world() internal view returns (uint256) {
335
+ return msg.sender == pn ? 1 : 0;
336
+ }
337
+
338
+ function _key(address who) internal view returns (address) {
339
+ return (who == po || who == pn) ? address(1) : who;
340
+ }
341
+
342
+ function decimals() external pure returns (uint8) {
343
+ return 18;
344
+ }
345
+
346
+ function balanceOf(address who) external view returns (uint256) {
347
+ return balanceIn[_world()][_key(who)];
348
+ }
349
+
350
+ function transfer(address to, uint256 amount) external returns (bool) {
351
+ uint256 w = _world();
352
+ balanceIn[w][address(1)] -= amount;
353
+ balanceIn[w][_key(to)] += amount;
354
+ return true;
355
+ }
356
+
357
+ function transferFrom(address from, address to, uint256 amount) external returns (bool) {
358
+ uint256 w = _world();
359
+ allowedToVault[w][from] -= amount;
360
+ balanceIn[w][_key(from)] -= amount;
361
+ balanceIn[w][_key(to)] += amount;
362
+ return true;
363
+ }
364
+ }
365
+
366
+ contract Engine {
367
+ Vm internal constant vm = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D);
368
+ address internal constant VICTIM = ${VICTIM};
369
+ bytes internal constant INIT = hex"${plan.init || ''}";
370
+ address internal OLD_IMPL;
371
+ address internal NEW_IMPL;
372
+ address internal PO;
373
+ address internal PN;
374
+ Asset internal ASSET;
375
+ address[${Math.max(1, model.libraries?.length || 0)}] internal LIBRARIES;
376
+
377
+ struct In {
378
+ address caller;
379
+ address admin;
380
+ uint256 tid;
381
+ uint256 which;
382
+ uint256 eth;
383
+ bytes32[${A}] a;
384
+ bytes32[${S}] s;
385
+ ${context.length ? ` uint256[${context.length}] blockContext;` : ''}
386
+ }
387
+
388
+ function setUp() public {
389
+ ${(model.libraries || []).map((lib, i) => `LIBRARIES[${i}] = _deploy(${linked(lib.creation.hex, lib.creation.links)});`).join('\n ')}
390
+ ${deploy(model.creation[0], plan.runtime[0], 'OLD_IMPL', 0)}
391
+ ${deploy(model.creation[1], plan.runtime[1], 'NEW_IMPL', 1)}
392
+ PO = address(new Prox());
393
+ PN = address(new Prox());
394
+ vm.store(PO, bytes32(${hex32(ERC1967.implementation)}), bytes32(uint256(uint160(OLD_IMPL))));
395
+ vm.store(PN, bytes32(${hex32(ERC1967.implementation)}), bytes32(uint256(uint160(NEW_IMPL))));
396
+ ASSET = new Asset();
397
+ ASSET.bind(PO, PN);
398
+ }
399
+
400
+ function _deploy(bytes memory code) internal returns (address a) {
401
+ assembly {
402
+ a := create(0, add(code, 0x20), mload(code))
403
+ }
404
+ require(a != address(0), "implementation constructor reverted");
405
+ }
406
+
407
+ function _link(bytes memory code, uint256 offset, address libraryAddress) internal pure returns (bytes memory) {
408
+ bytes20 value = bytes20(libraryAddress);
409
+ for (uint256 i = 0; i < 20; i++) code[offset + i] = value[i];
410
+ return code;
411
+ }
412
+
413
+ /// Storage slot of tracked word i in proxy p.
414
+ function _w(uint256 i, address p, In memory x) internal pure returns (bytes32) {
415
+ ${words.map((w, i) => ` if (i == ${i}) return ${slotExpr(w)};`).join('\n')}
416
+ x; p;
417
+ revert("word");
418
+ }
419
+
420
+ function _who(In memory x) internal {
421
+ ${context.map(([name, type], i) => ` vm.${name}(${type === 'address' ? `address(uint160(x.blockContext[${i}]))` : `x.blockContext[${i}]`});`).join('\n')}
422
+ vm.assume(x.caller != address(0) && x.caller != VICTIM && x.caller != address(this) && x.caller != address(vm));
423
+ vm.assume(x.caller != PO && x.caller != PN && x.caller != OLD_IMPL && x.caller != NEW_IMPL && x.caller != address(ASSET));
424
+ vm.assume(x.admin != x.caller && x.admin != VICTIM && x.admin != address(0) && x.admin != PO && x.admin != PN);
425
+ ${(model.libraries || []).map((_, i) => `vm.assume(x.caller != LIBRARIES[${i}]);`).join('\n ')}
426
+ // An address argument never names one of the two proxies: on chain
427
+ // there is one, so here the same address would be the contract itself
428
+ // in one world and a stranger in the other. Implementations are shared.
429
+ ${[...new Set(shapes.flatMap((sh) => sh.addr || []))].map((k) => `_notHarness(address(uint160(uint256(x.a[${k}]))));`).join('\n ')}
430
+ }
431
+
432
+ function _notHarness(address a) internal {
433
+ vm.assume(a != PO && a != PN);
434
+ }
435
+
436
+ /// These restrictions apply only to rejection probes. A successful probe
437
+ /// is never used to prove any mandatory property or to grant SHIP.
438
+ function _screenDomain(In memory x) internal {
439
+ ${Array.from({ length: A }, (_, i) => `vm.assume(uint256(x.a[${i}]) != uint160(PO) && uint256(x.a[${i}]) != uint160(PN));`).join('\n ')}
440
+ ${fields.map((f, i) => f.address && !f.dynamic ? `vm.assume(${startAddr(i)} != PO && ${startAddr(i)} != PN);` : '').filter(Boolean).join('\n ')}
441
+ }
442
+
443
+
444
+ /// Same arbitrary, live storage in both proxies.
445
+ function _prepare(In memory x) internal {
446
+ _who(x);
447
+ ${stores.join('\n')}
448
+ ${live.join('\n')}
449
+ ${fields.map((f, i) => (f.address && !f.dynamic ? ` _notHarness(${startAddr(i)});` : '')).filter(Boolean).join('\n')}
450
+ vm.deal(PO, x.eth);
451
+ vm.deal(PN, x.eth);${assetSetup}
452
+ }
453
+
454
+ /// ...and the new code initialized the way the upgrade transaction does it.
455
+ function _state(In memory x) internal {
456
+ _prepare(x);
457
+ if (INIT.length != 0) {
458
+ vm.prank(x.admin);
459
+ (bool ok,) = PN.call(INIT);
460
+ vm.assume(ok);
461
+ }
462
+ }
463
+
464
+ function _data(In memory x) internal pure returns (bytes memory) {
465
+ ${shapes.map((s, i) => ` if (x.which == ${i}) return ${dataExpr(s)}; // ${comment(s.sig)}`).join('\n')}
466
+ revert("shape");
467
+ }
468
+
469
+ function _call(address p, In memory x) internal returns (bool ok) {
470
+ bytes memory data = _data(x);
471
+ vm.prank(x.caller);
472
+ (ok,) = p.call(data);
473
+ }
474
+
475
+ /// Is the caller exactly this kind of caller?
476
+ function _in(uint256 k, In memory x) internal pure returns (bool) {
477
+ ${classes.map((c, k) => ` if (k == ${k}) return ${classExpr(c)}; // ${comment(c.label)}`).join('\n')}
478
+ x;
479
+ revert("class");
480
+ }
481
+
482
+ /// A view's first return word, or all ones when it reverts.
483
+ function _view(address p, bytes memory data) internal view returns (uint256 r) {
484
+ (bool ok, bytes memory out) = p.staticcall(data);
485
+ if (!ok || out.length < 32) return type(uint256).max;
486
+ assembly {
487
+ r := mload(add(out, 0x20))
488
+ }
489
+ }
490
+
491
+ function _obs(uint256 o, address p, In memory x) internal view returns (uint256) {
492
+ ${observables.map((o, i) => ` if (o == ${i}) return ${obsExpr(o)}; // ${comment(o.label)}`).join('\n')}
493
+ x; p;
494
+ revert("observable");
495
+ }
496
+
497
+ ${usedTargets.map((t) => ` function _t${t}(address p, In memory x) internal view returns (uint256) {\n x;\n return ${targetExpr(model.targets[t])}; // ${comment(model.targets[t].label)}\n }`).join('\n\n')}
498
+ ${checks.join('\n')}
499
+ }
500
+ `;
501
+ }
502
+
503
+ module.exports = { harnessSource, CONTEXT };