@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,638 @@
|
|
|
1
|
+
// Differential upgrade verification with no hand-written spec.
|
|
2
|
+
//
|
|
3
|
+
// Old and new implementation run side by side from the same arbitrary, live
|
|
4
|
+
// storage. The relations checked, all on existing state:
|
|
5
|
+
//
|
|
6
|
+
// guards a call the old code rejects is still rejected
|
|
7
|
+
// mutations an existing function changes only what it changed before
|
|
8
|
+
// values the same call leaves balances, supply and assets the same
|
|
9
|
+
// capabilities a new function gives no kind of caller a power over
|
|
10
|
+
// existing state that this kind of caller did not have
|
|
11
|
+
// upgrade an outsider cannot touch the proxy slots, and whoever
|
|
12
|
+
// could upgrade still can
|
|
13
|
+
// init the initializer call given for the upgrade can run, and
|
|
14
|
+
// the bare implementation is no more open than before
|
|
15
|
+
//
|
|
16
|
+
// These are modeled property results. The proof integrity gate decides
|
|
17
|
+
// whether their scope and evidence support a release verdict.
|
|
18
|
+
const fs = require('node:fs');
|
|
19
|
+
const os = require('node:os');
|
|
20
|
+
const path = require('node:path');
|
|
21
|
+
const { createHash } = require('node:crypto');
|
|
22
|
+
const { runHalmos, checkerStatus: statusOf } = require('../tools');
|
|
23
|
+
const { compareLayouts, dangerousOpcodes } = require('../generic');
|
|
24
|
+
const { buildModel, ERC1967 } = require('./model');
|
|
25
|
+
const { harnessSource } = require('./harness');
|
|
26
|
+
const { matchException } = require('./policy');
|
|
27
|
+
const { resolveBytecode } = require('./bytecode');
|
|
28
|
+
const { screenUpgrade } = require('./screen');
|
|
29
|
+
const { analyze, quietLibraryIndices } = require('./provenance');
|
|
30
|
+
const { assessIntegrity, completePropertyInventory, inspectSemantics } = require('./integrity');
|
|
31
|
+
const { issueProofCertificate } = require('./proof-certificate');
|
|
32
|
+
const { upgradeAuthority, immutablesOf } = require('./upgrade-authority');
|
|
33
|
+
|
|
34
|
+
// v4 (engine 2.4): bytecode upgrade authority (upgrade-path findings) and deployment-bound reports.
|
|
35
|
+
// v5 (engine 2.5): deployment defects observed at the pinned block are NO_SHIP findings (rule 'deployment').
|
|
36
|
+
// v6 (engine 2.6.1): a deployment without a recognised initializer lock is unresolved, not an initializer defect.
|
|
37
|
+
const ENGINE_ID = 'GuardeFi.UpgradeEngine.v6';
|
|
38
|
+
const UPGRADE_SELECTORS = new Set(['3659cfe6', '4f1ef286']); // upgradeTo, upgradeToAndCall
|
|
39
|
+
const MAX_ROUNDS = 6;
|
|
40
|
+
// Halmos processes run at once. Each explores paths on one core.
|
|
41
|
+
const JOBS = Math.max(1, Number(process.env.GUARDEFI_HALMOS_JOBS) || 3);
|
|
42
|
+
const CHUNK = 4; // ungrouped checks per Halmos process
|
|
43
|
+
|
|
44
|
+
// `unresolved`: the checks ran but could not decide the property. Like a
|
|
45
|
+
// timeout it blocks SHIP; it is never read as proof.
|
|
46
|
+
const RANK = { proven: 0, accepted: 1, bounded: 2, violated: 3, timeout: 4, unsupported: 4, error: 4, unresolved: 4 };
|
|
47
|
+
const worst = (list) => list.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'proven');
|
|
48
|
+
|
|
49
|
+
let active = 0;
|
|
50
|
+
const waiting = [];
|
|
51
|
+
async function slot(fn) {
|
|
52
|
+
while (active >= JOBS) await new Promise((resolve) => waiting.push(resolve));
|
|
53
|
+
active++;
|
|
54
|
+
try {
|
|
55
|
+
return await fn();
|
|
56
|
+
} finally {
|
|
57
|
+
active--;
|
|
58
|
+
waiting.shift()?.();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A probe batch may carry `stop` (an AbortController): the first
|
|
63
|
+
// counterexample aborts the runs in flight and skips the ones still queued.
|
|
64
|
+
const halmosRun = (model, plan) => (plan.replayRuntime?.schedule || slot)(() =>
|
|
65
|
+
(plan.stop?.signal.aborted ? {} : halmosOnce(model, plan))).then((r) => {
|
|
66
|
+
if (plan.stop && Object.values(r).some((x) => statusOf(x) === 'violated')) plan.stop.abort();
|
|
67
|
+
return r;
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
async function halmosOnce(model, plan) {
|
|
71
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'guardefi-engine-'));
|
|
72
|
+
try {
|
|
73
|
+
const execution = plan.replayRuntime?.prepare(tmp);
|
|
74
|
+
const solc = plan.solc ? `solc = "${plan.solc}"\n` : '';
|
|
75
|
+
const config = `[profile.default]\nsrc = "src"\ntest = "test"\nout = "out"\n${execution?.foundry || solc}`;
|
|
76
|
+
fs.writeFileSync(path.join(tmp, 'foundry.toml'), config);
|
|
77
|
+
fs.mkdirSync(path.join(tmp, 'test'));
|
|
78
|
+
const source = harnessSource(model, plan);
|
|
79
|
+
fs.writeFileSync(path.join(tmp, 'test', 'Engine.t.sol'), source);
|
|
80
|
+
if (!execution && process.env.GUARDEFI_KEEP) fs.copyFileSync(path.join(tmp, 'test', 'Engine.t.sol'), process.env.GUARDEFI_KEEP);
|
|
81
|
+
// Branch conditions keep Halmos' 1ms default: an undecided branch is
|
|
82
|
+
// explored both ways and only assertion queries decide a result.
|
|
83
|
+
// Bitwuzla settles the storage-and-hash queries of balance checks that
|
|
84
|
+
// Yices leaves unknown within the same time.
|
|
85
|
+
// gate: 5 s per query, 30 s on retry, 60 s per probe or equivalence run.
|
|
86
|
+
// audit: 30 s, 120 s on retry, 10 minutes, and an hour for any other run.
|
|
87
|
+
const query = plan.slow ? (plan.audit ? '120s' : '30s') : (plan.audit ? '30s' : '5s');
|
|
88
|
+
const timeout = plan.probe || plan.quick ? (plan.audit ? 600000 : 60000) : plan.audit ? 3600000 : undefined;
|
|
89
|
+
const args = [...(execution?.solverArgs || ['--solver', 'bitwuzla']),
|
|
90
|
+
'--solver-timeout-assertion', query, '--solver-threads', '1', '--loop', '2'];
|
|
91
|
+
let receipt = null;
|
|
92
|
+
const result = await runHalmos(tmp, 'Engine', args, {
|
|
93
|
+
...(execution ? { cwd: tmp, env: execution.env, executable: execution.halmos, includeRaw: true } : {}),
|
|
94
|
+
...(timeout ? { timeout } : {}),
|
|
95
|
+
...(plan.stop ? { signal: plan.stop.signal } : {}),
|
|
96
|
+
receipt: (value) => { receipt = value; },
|
|
97
|
+
});
|
|
98
|
+
plan.record?.({
|
|
99
|
+
harnessSha256: createHash('sha256').update(source).digest('hex'),
|
|
100
|
+
configSha256: createHash('sha256').update(config).digest('hex'),
|
|
101
|
+
...(execution ? { compiled: execution.compiled() } : {}),
|
|
102
|
+
solc: plan.solc,
|
|
103
|
+
args,
|
|
104
|
+
timeoutMs: timeout || 600000,
|
|
105
|
+
checks: plan.checks.map(({ name }) => ({ name, result: statusOf(result[`check_${name}`]) })),
|
|
106
|
+
receipt,
|
|
107
|
+
});
|
|
108
|
+
return result;
|
|
109
|
+
} finally {
|
|
110
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Run checks; returns check name -> Halmos result (null when none came back).
|
|
116
|
+
* A check whose queries ran out of time runs once more with a longer limit
|
|
117
|
+
* per query, unless its probe batch already ended.
|
|
118
|
+
*/
|
|
119
|
+
async function execute(model, plan, checks) {
|
|
120
|
+
const out = await executeOnce(model, plan, checks);
|
|
121
|
+
if (plan.slow || plan.stop?.signal.aborted) return out;
|
|
122
|
+
const slow = checks.filter((c) => statusOf(out[c.name]) === 'timeout');
|
|
123
|
+
return slow.length ? { ...out, ...(await executeOnce(model, { ...plan, slow: true }, slow)) } : out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function executeOnce(model, plan, checks) {
|
|
127
|
+
const out = {};
|
|
128
|
+
const tasks = [];
|
|
129
|
+
// Calls into the bare implementation explore every call shape: alone.
|
|
130
|
+
const heavy = checks.filter((c) => c.kind === 'lock');
|
|
131
|
+
const light = checks.filter((c) => c.kind !== 'lock');
|
|
132
|
+
const chunks = [...heavy.map((c) => [c])];
|
|
133
|
+
const size = plan.quick ? 2 : CHUNK; // a capped run loses every result it holds
|
|
134
|
+
for (let i = 0; i < light.length; i += size) chunks.push(light.slice(i, i + size));
|
|
135
|
+
for (const chunk of chunks) {
|
|
136
|
+
tasks.push(halmosRun(model, { ...plan, checks: chunk }).then((r) => {
|
|
137
|
+
for (const c of chunk) out[c.name] = r[`check_${c.name}`] ?? null;
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
140
|
+
await Promise.all(tasks);
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The call a counterexample makes, in words. */
|
|
145
|
+
function witness(model, r, fixedShape) {
|
|
146
|
+
const cex = r?.counterexample || {};
|
|
147
|
+
const get = (name) => Object.entries(cex).find(([k]) => k === name)?.[1];
|
|
148
|
+
const shape = model.shapes[fixedShape ?? Number(get('which') ?? -1)];
|
|
149
|
+
const out = {};
|
|
150
|
+
if (shape) out.call = shape.sig;
|
|
151
|
+
if (get('caller')) out.caller = get('caller');
|
|
152
|
+
for (const [k, v] of Object.entries(cex)) {
|
|
153
|
+
const m = k.match(/^a\[(\d+)\]$/);
|
|
154
|
+
if (m && shape && Number(m[1]) < shape.words.filter((w) => w === 'sym').length) out[`arg${m[1]}`] = v;
|
|
155
|
+
}
|
|
156
|
+
return { shape: shape ? model.shapes.indexOf(shape) : -1, text: out };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const isInitName = (sig) => /^_?(re)?init/i.test(sig || '');
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Verify one upgrade. `init` is the calldata the upgrade transaction runs on
|
|
163
|
+
* the new code (hex, may be empty). `policy` is a parsed policy file or null.
|
|
164
|
+
* Returns scoped property results, proof integrity and the release verdict.
|
|
165
|
+
*/
|
|
166
|
+
/** What a report rests on, by property, so a SHIP shows its bounds up front. */
|
|
167
|
+
function withAssurance(report, mode) {
|
|
168
|
+
const by = (statuses) => report.properties.filter((p) => p.mandatory && statuses.includes(p.status)).map((p) => p.name);
|
|
169
|
+
return {
|
|
170
|
+
...report,
|
|
171
|
+
mode,
|
|
172
|
+
assurance: {
|
|
173
|
+
proven: by(['proven']),
|
|
174
|
+
bounded: by(['bounded']),
|
|
175
|
+
accepted: by(['accepted']),
|
|
176
|
+
violated: by(['violated']),
|
|
177
|
+
unresolved: by(['unresolved']),
|
|
178
|
+
unverified: by(['timeout', 'error', 'unsupported']),
|
|
179
|
+
bounds: report.notes?.bounded || [],
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Verify one upgrade. `mode` is 'gate' (stop at the first confirmed rejection,
|
|
186
|
+
* short budgets) or 'audit' (run every check and probe, long budgets). Both
|
|
187
|
+
* apply the same verdict rule.
|
|
188
|
+
*/
|
|
189
|
+
async function verifyUpgrade(options) {
|
|
190
|
+
const mode = options.mode || 'gate';
|
|
191
|
+
if (!['gate', 'audit'].includes(mode)) throw new Error(`unknown verification mode: ${mode}`);
|
|
192
|
+
let report;
|
|
193
|
+
try {
|
|
194
|
+
report = await verifyIn({ ...options, audit: mode === 'audit' });
|
|
195
|
+
} catch (error) {
|
|
196
|
+
report = {
|
|
197
|
+
engine: ENGINE_ID, properties: [], findings: [], accepted: [], unusedExceptions: [],
|
|
198
|
+
coverage: {}, notes: { unsupported: [error.message], bounded: [], liveStateRecognized: false },
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
const { observations, ...results } = report;
|
|
202
|
+
// Deployment evidence at a pinned block can discharge the proxy assumption only.
|
|
203
|
+
if (options.deployment) {
|
|
204
|
+
// Loaded only here. A replay passes `deploymentRead`, which answers from the archived chain reads.
|
|
205
|
+
const { dischargeDeployment } = require('./deployment');
|
|
206
|
+
results.deployment = await dischargeDeployment(options.deployment, { artifact: options.artifact, baseArtifact: options.baseArtifact, read: options.deploymentRead })
|
|
207
|
+
.catch((error) => ({ status: 'unresolved', basis: error.message, evidence: {}, problems: [error.message] }));
|
|
208
|
+
}
|
|
209
|
+
const observed = results.deployment?.status === 'supported'
|
|
210
|
+
? { ...observations, proxy: { status: 'supported', basis: results.deployment.basis } } : observations;
|
|
211
|
+
// With the proxy bound to the reviewed code, pinned callees can discharge callbacks.
|
|
212
|
+
if (results.deployment?.status === 'supported' && observed?.callbacks && observed.callbacks.status !== 'supported') {
|
|
213
|
+
const { bindCallees } = require('./callee-binding');
|
|
214
|
+
results.callees = await bindCallees(options.deployment, { dir: options.dir, artifact: options.artifact, baseArtifact: options.baseArtifact, init: options.init, read: options.deploymentRead })
|
|
215
|
+
.catch((error) => ({ status: 'unresolved', basis: error.message, evidence: {} }));
|
|
216
|
+
if (results.callees.status === 'supported') {
|
|
217
|
+
const before = observed.callbacks.basis;
|
|
218
|
+
observed.callbacks = { status: 'supported', basis: results.callees.basis };
|
|
219
|
+
const reentrancy = results.properties.find((p) => p.name === 'reentrancy');
|
|
220
|
+
if (reentrancy?.status === 'unsupported') Object.assign(reentrancy, { status: 'proven', unverified: 0 });
|
|
221
|
+
if (results.notes?.unsupported) results.notes.unsupported = results.notes.unsupported.filter((note) => note !== before);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
results.properties = completePropertyInventory(results.properties);
|
|
225
|
+
const integrity = assessIntegrity(results.properties, observed);
|
|
226
|
+
const findings = results.findings.map((finding) => ({
|
|
227
|
+
...finding,
|
|
228
|
+
evidence: ['layout', 'opcode', 'upgrade-path'].includes(finding.rule) ? 'artifact-policy-violation' : 'modeled-counterexample',
|
|
229
|
+
}));
|
|
230
|
+
// A deployment defect observed on chain at the pinned block is a confirmed violation, not an open assumption.
|
|
231
|
+
for (const v of results.deployment?.status === 'violated' ? results.deployment.violations : []) {
|
|
232
|
+
findings.push({ rule: 'deployment', category: 'deployment', check: v.check, detail: v.detail, evidence: 'observed-deployment-violation',
|
|
233
|
+
block: results.deployment.evidence?.block ?? null, blockHash: results.deployment.evidence?.blockHash ?? null });
|
|
234
|
+
}
|
|
235
|
+
const confirmed = findings.some((finding) => ['artifact-policy-violation', 'observed-deployment-violation'].includes(finding.evidence));
|
|
236
|
+
const scoped = { ...results, findings, integrity, mode };
|
|
237
|
+
const certificate = integrity.status === 'complete' && !findings.length ? issueProofCertificate(scoped) : null;
|
|
238
|
+
const verdict = confirmed ? 'NO_SHIP' : certificate ? 'SHIP' : 'UNVERIFIED';
|
|
239
|
+
return withAssurance({ ...scoped, verdict, certificate }, mode);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function verifyIn({ dir, artifact, baseArtifact, init = '', policy = null, audit = false, replayRuntime = null }) {
|
|
243
|
+
if (!baseArtifact.storageLayout?.storage || !artifact.storageLayout?.storage) throw new Error('build artifacts carry no storage layout');
|
|
244
|
+
const layoutProblems = compareLayouts(baseArtifact.storageLayout, artifact.storageLayout);
|
|
245
|
+
const execution = resolveBytecode(dir, [baseArtifact, artifact]);
|
|
246
|
+
const opcodes = (side) => new Set([
|
|
247
|
+
...dangerousOpcodes(execution.implementations[side]?.runtime.hex || ''),
|
|
248
|
+
...[...execution.graphs[side]].flatMap((index) => [...dangerousOpcodes(execution.libraries[index].runtime.hex)]),
|
|
249
|
+
]);
|
|
250
|
+
const oldOpcodes = opcodes(0);
|
|
251
|
+
const newOpcodes = opcodes(1);
|
|
252
|
+
// A new DELEGATECALL is accepted only where bytecode provenance shows every
|
|
253
|
+
// one, in the implementation and its libraries, calls a linked library.
|
|
254
|
+
// A library that cannot itself invoke foreign code is a quiet DELEGATECALL target.
|
|
255
|
+
const libraries = execution.libraries.map((unit) => analyze(unit.runtime.hex, unit.runtime.links, { features: true }));
|
|
256
|
+
const quietLibraries = quietLibraryIndices(libraries);
|
|
257
|
+
const analysis = [0, 1].map((side) => [
|
|
258
|
+
...(execution.implementations[side] ? [analyze(execution.implementations[side].runtime.hex, execution.implementations[side].runtime.links, { features: true, quietLibraries })] : []),
|
|
259
|
+
...[...(execution.graphs[side] || [])].map((index) => libraries[index]),
|
|
260
|
+
]);
|
|
261
|
+
const libraryCalls = Boolean(execution.graphs[1]?.size) && analysis[1].every((a) => a.complete && a.delegatecalls.every((d) => d.library));
|
|
262
|
+
const semantics = inspectSemantics(analysis);
|
|
263
|
+
const addedOpcodes = execution.errors.length ? [] : [...newOpcodes].filter((opcode) => !oldOpcodes.has(opcode) && !(opcode === 'DELEGATECALL' && libraryCalls));
|
|
264
|
+
// Who can write the implementation slot, from bytecode. A UUPS baseline
|
|
265
|
+
// whose candidate can provably never write it again, or whose candidate's
|
|
266
|
+
// proxiableUUID() never returns the slot, is a confirmed static violation.
|
|
267
|
+
const authority = [0, 1].map((side) => (execution.implementations[side]
|
|
268
|
+
? upgradeAuthority(execution.implementations[side].runtime.hex, { immutables: immutablesOf(side ? artifact : baseArtifact) })
|
|
269
|
+
: { status: 'unresolved', reason: 'unresolved bytecode', proxiable: 'unknown' }));
|
|
270
|
+
const upgradeProblems = authority[0].status !== 'guarded' ? [] : [
|
|
271
|
+
authority[1].status === 'none' && 'no reachable instruction in the new implementation writes the ERC-1967 implementation slot; the proxy could never be upgraded again',
|
|
272
|
+
// Only an ERC-1822 baseline (its own proxiableUUID() answers the slot) makes a wrong answer a violation;
|
|
273
|
+
// a baseline without the check upgrades to the candidate regardless.
|
|
274
|
+
authority[0].proxiable === 'ok' && authority[1].proxiable === 'wrong' && "the new implementation's proxiableUUID() never returns the ERC-1967 implementation slot; a UUPS upgrade to it reverts",
|
|
275
|
+
].filter(Boolean);
|
|
276
|
+
const upgradeAuthorityNote = { old: authority[0], new: authority[1] };
|
|
277
|
+
// An audit still checks behaviour after a new opcode, but not across a
|
|
278
|
+
// broken layout or unresolved bytecode.
|
|
279
|
+
if (layoutProblems.length || execution.errors.length || upgradeProblems.length || (addedOpcodes.length && !audit)) {
|
|
280
|
+
const findings = [
|
|
281
|
+
...layoutProblems.map((detail) => ({ rule: 'layout', category: 'layout', detail, witness: {} })),
|
|
282
|
+
...upgradeProblems.map((detail) => ({ rule: 'upgrade-path', category: 'upgrade', detail, witness: {} })),
|
|
283
|
+
...addedOpcodes.map((opcode) => ({ rule: 'opcode', category: 'opcodes', detail: `new ${opcode} opcode`, witness: {} })),
|
|
284
|
+
];
|
|
285
|
+
return {
|
|
286
|
+
engine: ENGINE_ID,
|
|
287
|
+
observations: semantics.assumptions,
|
|
288
|
+
externalEffects: semantics.externalEffects,
|
|
289
|
+
properties: [
|
|
290
|
+
{ name: 'layout', mandatory: true, status: layoutProblems.length ? 'violated' : 'proven', checks: 1, unverified: 0, bounded: 0, findings: layoutProblems.length, accepted: 0 },
|
|
291
|
+
{ name: 'opcodes', mandatory: true, status: execution.errors.length ? 'unsupported' : addedOpcodes.length ? 'violated' : 'proven', checks: 1, unverified: Number(Boolean(execution.errors.length)), bounded: 0, findings: addedOpcodes.length, accepted: 0 },
|
|
292
|
+
...['guards', 'mutations', 'values', 'capabilities', 'upgrade', 'init'].map((name) => (name === 'upgrade' && upgradeProblems.length
|
|
293
|
+
? { name, mandatory: true, status: 'violated', checks: 1, unverified: 0, bounded: 0, findings: upgradeProblems.length, accepted: 0 }
|
|
294
|
+
: { name, mandatory: true, status: 'unsupported', checks: 0, unverified: 1, bounded: 0, findings: 0, accepted: 0 })),
|
|
295
|
+
],
|
|
296
|
+
findings,
|
|
297
|
+
accepted: [],
|
|
298
|
+
unusedExceptions: policy?.exceptions || [],
|
|
299
|
+
coverage: { checks: 2, proven: Number(!layoutProblems.length) + Number(!addedOpcodes.length && !execution.errors.length), bounded: 0, answered: 0, timeout: 0, error: 0, seconds: 0, callShapes: 0, trackedWords: 0, callerKinds: 0, targets: 0 },
|
|
300
|
+
notes: { bounded: [], unsupported: execution.errors.length ? execution.errors : ['behavioral checks skipped after a confirmed static violation'], liveStateRecognized: false, upgradeAuthority: upgradeAuthorityNote },
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
const model = await buildModel({ dir, artifact, baseArtifact, execution, includeViews: semantics.context.length > 0,
|
|
304
|
+
...(replayRuntime ? { castTool: replayRuntime.cast } : {}) });
|
|
305
|
+
const { assumptions: observations, context, externalEffects } = inspectSemantics(analysis, { vault: model.vault });
|
|
306
|
+
const { shapes, targets, classes, observables } = model;
|
|
307
|
+
const solc = '0.8.28';
|
|
308
|
+
if (!/^(?:0x)?(?:[0-9a-f]{2})*$/i.test(init)) throw new Error('Invalid initializer calldata.');
|
|
309
|
+
const batches = [];
|
|
310
|
+
const base = { init: init.replace(/^0x/, ''), runtime: execution.implementations.map((a) => a.runtime.hex), solc, audit, context, replayRuntime,
|
|
311
|
+
record: (batch) => batches.push(batch) };
|
|
312
|
+
let probeFindings = [];
|
|
313
|
+
if (!policy?.exceptions?.length) {
|
|
314
|
+
const rejection = await screenUpgrade({ model, artifact, execute: (checks, opts) => execute(model, { ...base, ...opts }, checks), statusOf, witness, exhaustive: audit });
|
|
315
|
+
if (rejection && !audit) return { engine: ENGINE_ID, observations, externalEffects, batches, ...rejection };
|
|
316
|
+
// An audit keeps what the probes found and runs every check as well.
|
|
317
|
+
if (rejection) probeFindings = rejection.findings.map((f) => ({ ...f, source: 'probe' }));
|
|
318
|
+
}
|
|
319
|
+
const idx = (pred) => shapes.map((s, i) => (pred(s) ? i : -1)).filter((i) => i >= 0);
|
|
320
|
+
const OLDS = idx((s) => s.inOld && !s.contextOnly);
|
|
321
|
+
const NEWALL = idx((s) => s.inNew && !s.contextOnly);
|
|
322
|
+
const NEWONLY = idx((s) => s.inNew && !s.inOld && !s.contextOnly);
|
|
323
|
+
const sameCall = (i) => shapes.map((s, j) => (s.sig === shapes[i].sig ? j : -1)).filter((j) => j >= 0);
|
|
324
|
+
const storageTargets = targets.map((t, i) => (t.kind !== 'observable' ? i : -1)).filter((i) => i >= 0);
|
|
325
|
+
const mutationTargets = storageTargets.filter((t) => targets[t].proxy !== 'implementation');
|
|
326
|
+
const implTarget = targets.findIndex((t) => t.proxy === 'implementation');
|
|
327
|
+
|
|
328
|
+
const results = {}; // check name -> halmos result
|
|
329
|
+
const defs = {}; // check name -> check definition
|
|
330
|
+
const runChecks = async (checks, opts = {}) => {
|
|
331
|
+
if (checks.length === 0) return;
|
|
332
|
+
for (const c of checks) defs[c.name] = c;
|
|
333
|
+
Object.assign(results, await execute(model, { ...base, ...opts }, checks));
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// ---- stage 1: everything that needs no earlier answer. A call that
|
|
337
|
+
// provably behaves the same in both worlds needs no guard or mutation check;
|
|
338
|
+
// the others get them once that is known.
|
|
339
|
+
const stage1 = [];
|
|
340
|
+
if (context.length) stage1.push({ name: 'context_compare', kind: 'contextCompare', shapes: idx((s) => s.inOld) });
|
|
341
|
+
const equiv = OLDS.map((i) => ({ name: `e_${i}`, kind: 'equiv', shape: i }));
|
|
342
|
+
observables.forEach((o, i) => stage1.push({ name: `v_${i}`, kind: 'value', observable: i, shapes: OLDS, skip: [] }));
|
|
343
|
+
for (const t of storageTargets.filter((t) => targets[t].kind === 'slot')) stage1.push({ name: `u_${t}`, kind: 'reach', side: 'new', target: t, klass: 0, shapes: NEWALL, skip: [] });
|
|
344
|
+
stage1.push({ name: 'lock_old', kind: 'lock', side: 'old' }, { name: 'lock_new', kind: 'lock', side: 'new' });
|
|
345
|
+
stage1.push({ name: 'path_any', kind: 'reach', side: 'old', target: implTarget, klass: null, shapes: OLDS, skip: [] });
|
|
346
|
+
if (base.init) stage1.push({ name: 'init_runs', kind: 'initRuns' });
|
|
347
|
+
if (NEWONLY.length) targets.forEach((t, i) => stage1.push({ name: `n_${i}`, kind: 'reach', side: 'new', target: i, klass: null, shapes: NEWONLY, skip: [] }));
|
|
348
|
+
const differs = async () => {
|
|
349
|
+
// Equivalence only saves work: a capped run falls back to detailed checks.
|
|
350
|
+
await runChecks(equiv, { quick: true });
|
|
351
|
+
const rest = OLDS.filter((i) => statusOf(results[`e_${i}`]) !== 'proven');
|
|
352
|
+
if (!rest.length) return;
|
|
353
|
+
await runChecks([
|
|
354
|
+
...rest.map((i) => ({ name: `g_${i}`, kind: 'guard', shape: i, klass: null })),
|
|
355
|
+
...mutationTargets.map((t) => ({ name: `m_${t}`, kind: 'mutation', target: t, shapes: rest, skip: [] })),
|
|
356
|
+
]);
|
|
357
|
+
};
|
|
358
|
+
await Promise.all([differs(), runChecks(stage1)]);
|
|
359
|
+
|
|
360
|
+
// ---- stage 2: break findings down by kind of caller
|
|
361
|
+
const stage2 = [];
|
|
362
|
+
const loosened = OLDS.filter((i) => statusOf(results[`g_${i}`]) === 'violated');
|
|
363
|
+
const knownUpgradeFailure = loosened.some((i) => UPGRADE_SELECTORS.has(shapes[i].selector)) ||
|
|
364
|
+
storageTargets.some((t) => targets[t].kind === 'slot' && statusOf(results[`u_${t}`]) === 'violated');
|
|
365
|
+
if (statusOf(results.path_any) !== 'violated' && !knownUpgradeFailure) {
|
|
366
|
+
await runChecks([{ name: 'path_new_any', kind: 'reach', side: 'new', target: implTarget, klass: null, shapes: NEWALL, skip: [] }]);
|
|
367
|
+
}
|
|
368
|
+
for (const i of loosened) {
|
|
369
|
+
classes.forEach((_, k) => stage2.push({ name: `gc_${i}_${k}`, kind: 'guard', shape: i, klass: k }));
|
|
370
|
+
stage2.push({ name: `gr_${i}`, kind: 'guard', shape: i, klass: null, notIn: classes.map((_, k) => k) });
|
|
371
|
+
}
|
|
372
|
+
const writable = NEWONLY.length ? targets.map((_, i) => i).filter((i) => statusOf(results[`n_${i}`]) === 'violated') : [];
|
|
373
|
+
// New code first: only a kind of caller that can change a target through a
|
|
374
|
+
// new function needs the old code compared.
|
|
375
|
+
for (const t of writable) classes.forEach((_, k) => stage2.push({ name: `cn_${k}_${t}`, kind: 'reach', side: 'new', target: t, klass: k, shapes: NEWONLY, skip: [] }));
|
|
376
|
+
const canUpgrade = !knownUpgradeFailure && (statusOf(results.path_any) === 'violated' || statusOf(results.path_new_any) === 'violated');
|
|
377
|
+
if (canUpgrade) {
|
|
378
|
+
classes.forEach((_, k) => {
|
|
379
|
+
stage2.push({ name: `po_${k}`, kind: 'reach', side: 'old', target: implTarget, klass: k, shapes: OLDS, skip: [] });
|
|
380
|
+
stage2.push({ name: `pn_${k}`, kind: 'reach', side: 'new', target: implTarget, klass: k, shapes: NEWALL, skip: [] });
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
await runChecks(stage2);
|
|
384
|
+
const can = (name) => statusOf(results[name]) === 'violated';
|
|
385
|
+
const cannot = (name) => ['proven', 'bounded'].includes(statusOf(results[name]));
|
|
386
|
+
await runChecks(writable.flatMap((t) => classes.map((_, k) => k).filter((k) => can(`cn_${k}_${t}`))
|
|
387
|
+
.map((k) => ({ name: `co_${k}_${t}`, kind: 'reach', side: 'old', target: t, klass: k, shapes: OLDS, skip: [] }))));
|
|
388
|
+
|
|
389
|
+
// ---- the same state on both sides. "Can this kind of caller change it"
|
|
390
|
+
// was asked of old and new over all states. Where both sides can, look for
|
|
391
|
+
// one state where only one can: the other side's counterexample state, then
|
|
392
|
+
// the default state. Pairs left open are compared over all states only.
|
|
393
|
+
const stateOf = (r) => {
|
|
394
|
+
const cex = r?.counterexample || {};
|
|
395
|
+
const out = { s: {} };
|
|
396
|
+
for (const [k, v] of Object.entries(cex)) {
|
|
397
|
+
const m = k.match(/^s\[(\d+)\]$/);
|
|
398
|
+
if (m) out.s[m[1]] = v;
|
|
399
|
+
else if (['caller', 'admin', 'tid', 'eth'].includes(k)) out[k] = v;
|
|
400
|
+
}
|
|
401
|
+
return out;
|
|
402
|
+
};
|
|
403
|
+
const refine = [];
|
|
404
|
+
const capPairs = writable.flatMap((t) => classes.map((_, k) => ({ k, t })).filter(({ k }) => can(`cn_${k}_${t}`) && can(`co_${k}_${t}`)));
|
|
405
|
+
for (const { k, t } of capPairs) {
|
|
406
|
+
refine.push(
|
|
407
|
+
{ name: `cw_${k}_${t}`, kind: 'reach', side: 'old', target: t, klass: k, shapes: OLDS, skip: [], fix: stateOf(results[`cn_${k}_${t}`]) },
|
|
408
|
+
{ name: `czn_${k}_${t}`, kind: 'reach', side: 'new', target: t, klass: k, shapes: NEWONLY, skip: [], zero: k },
|
|
409
|
+
{ name: `czo_${k}_${t}`, kind: 'reach', side: 'old', target: t, klass: k, shapes: OLDS, skip: [], zero: k },
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
const upPairs = canUpgrade ? classes.map((_, k) => k).filter((k) => can(`po_${k}`) && can(`pn_${k}`)) : [];
|
|
413
|
+
// Both sides let one kind of caller upgrade and no state separates them.
|
|
414
|
+
// Bytecode settles it when, in old and new, every path that writes the
|
|
415
|
+
// implementation slot checks only that the caller is the address in the
|
|
416
|
+
// same storage field: then who can upgrade is the same in every state. The
|
|
417
|
+
// new implementation must also answer proxiableUUID() with the slot.
|
|
418
|
+
const authorityResolves = authority.every((a) => a.status === 'guarded') && authority[0].owner === authority[1].owner &&
|
|
419
|
+
authority[1].proxiable === 'ok';
|
|
420
|
+
upgradeAuthorityNote.resolved = upPairs.length > 0 && authorityResolves;
|
|
421
|
+
for (const k of upPairs) {
|
|
422
|
+
refine.push(
|
|
423
|
+
{ name: `pgw_${k}`, kind: 'reach', side: 'old', target: implTarget, klass: k, shapes: OLDS, skip: [], fix: stateOf(results[`pn_${k}`]) },
|
|
424
|
+
{ name: `plw_${k}`, kind: 'reach', side: 'new', target: implTarget, klass: k, shapes: NEWALL, skip: [], fix: stateOf(results[`po_${k}`]) },
|
|
425
|
+
{ name: `pzn_${k}`, kind: 'reach', side: 'new', target: implTarget, klass: k, shapes: NEWALL, skip: [], zero: k },
|
|
426
|
+
{ name: `pzo_${k}`, kind: 'reach', side: 'old', target: implTarget, klass: k, shapes: OLDS, skip: [], zero: k },
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
await runChecks(refine);
|
|
430
|
+
const capRefined = (k, t) => cannot(`cw_${k}_${t}`) ? `cn_${k}_${t}` : can(`czn_${k}_${t}`) && cannot(`czo_${k}_${t}`) ? `czn_${k}_${t}` : null;
|
|
431
|
+
const gained = (k) => cannot(`pgw_${k}`) ? `pn_${k}` : can(`pzn_${k}`) && cannot(`pzo_${k}`) ? `pzn_${k}` : null;
|
|
432
|
+
const lost = (k) => cannot(`plw_${k}`) ? `po_${k}` : can(`pzo_${k}`) && cannot(`pzn_${k}`) ? `pzo_${k}` : null;
|
|
433
|
+
// Pairs neither refinement settles: both sides can act, and no state was
|
|
434
|
+
// found where only one can. Nothing proves the new code grants no more.
|
|
435
|
+
const unresolved = [
|
|
436
|
+
...capPairs.filter(({ k, t }) => !capRefined(k, t)).map(({ k, t }) => ({ property: 'capabilities', detail: `${classes[k].label} can change ${targets[t].label} through new and through old functions; no state found where only one side can, and none proven where the new side grants more` })),
|
|
437
|
+
...upPairs.filter((k) => !gained(k) && !lost(k) && !authorityResolves).map((k) => ({ property: 'upgrade', detail: `${classes[k].label} can upgrade through old and through new code; no state found where only one side can, and none proven where the new side grants more` })),
|
|
438
|
+
];
|
|
439
|
+
|
|
440
|
+
// ---- findings, policy, and re-checks with accepted calls taken out
|
|
441
|
+
const exceptions = (policy?.exceptions || []).map((e) => ({ ...e, used: false }));
|
|
442
|
+
const accepted = [];
|
|
443
|
+
let findings = [];
|
|
444
|
+
const collect = () => {
|
|
445
|
+
const out = [];
|
|
446
|
+
const violated = (name) => statusOf(results[name]) === 'violated';
|
|
447
|
+
for (const i of loosened) {
|
|
448
|
+
const sig = shapes[i].sig;
|
|
449
|
+
const category = UPGRADE_SELECTORS.has(shapes[i].selector) ? 'upgrade' : isInitName(sig) ? 'init' : 'access';
|
|
450
|
+
classes.forEach((c, k) => {
|
|
451
|
+
if (violated(`gc_${i}_${k}`)) out.push({ rule: 'guard', category, function: sig, class: c.label, check: `gc_${i}_${k}`, detail: `${sig} now accepts a call from ${c.label} that the old code rejects`, witness: witness(model, results[`gc_${i}_${k}`], i).text });
|
|
452
|
+
});
|
|
453
|
+
if (violated(`gr_${i}`)) out.push({ rule: 'guard', category, function: sig, class: 'a caller with several privileges', check: `gr_${i}`, fixed: true, detail: `${sig} now accepts a call the old code rejects`, witness: witness(model, results[`gr_${i}`], i).text });
|
|
454
|
+
}
|
|
455
|
+
for (const t of mutationTargets) {
|
|
456
|
+
if (!violated(`m_${t}`)) continue;
|
|
457
|
+
const w = witness(model, results[`m_${t}`]);
|
|
458
|
+
const category = targets[t].kind === 'slot' ? 'upgrade' : isInitName(w.text.call) ? 'init' : 'access';
|
|
459
|
+
out.push({ rule: 'mutation', category, function: w.text.call, target: targets[t].label, check: `m_${t}`, shape: w.shape, detail: `${w.text.call} now changes ${targets[t].label}, which the same call did not change before`, witness: w.text });
|
|
460
|
+
}
|
|
461
|
+
observables.forEach((o, i) => {
|
|
462
|
+
if (!violated(`v_${i}`)) return;
|
|
463
|
+
const w = witness(model, results[`v_${i}`]);
|
|
464
|
+
out.push({ rule: 'value', category: 'asset', function: w.text.call, target: o.label, check: `v_${i}`, shape: w.shape, detail: `the same ${w.text.call} call leaves ${o.label} different from before`, witness: w.text });
|
|
465
|
+
});
|
|
466
|
+
for (const t of writable) {
|
|
467
|
+
classes.forEach((c, k) => {
|
|
468
|
+
if (!violated(`cn_${k}_${t}`)) return;
|
|
469
|
+
const check = cannot(`co_${k}_${t}`) ? `cn_${k}_${t}` : violated(`co_${k}_${t}`) ? capRefined(k, t) : null;
|
|
470
|
+
if (!check) return;
|
|
471
|
+
const w = witness(model, results[check]);
|
|
472
|
+
const category = targets[t].kind === 'slot' ? 'upgrade' : targets[t].kind === 'observable' ? 'asset' : isInitName(w.text.call) ? 'init' : 'access';
|
|
473
|
+
out.push({ rule: 'capability', category, function: w.text.call, target: targets[t].label, class: c.label, check, shape: w.shape, detail: `${c.label} can now change ${targets[t].label} through ${w.text.call}, and could not change it before`, witness: w.text });
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
for (const t of storageTargets.filter((t) => targets[t].kind === 'slot')) {
|
|
477
|
+
if (violated(`u_${t}`)) {
|
|
478
|
+
const w = witness(model, results[`u_${t}`]);
|
|
479
|
+
out.push({ rule: 'upgrade', category: 'upgrade', function: w.text.call, target: targets[t].label, class: 'anyone', check: `u_${t}`, fixed: true, detail: `anyone can change the ${targets[t].label} through ${w.text.call}`, witness: w.text });
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (canUpgrade) {
|
|
483
|
+
classes.forEach((c, k) => {
|
|
484
|
+
const both = violated(`po_${k}`) && violated(`pn_${k}`);
|
|
485
|
+
const lostBy = both ? lost(k) : violated(`po_${k}`) && cannot(`pn_${k}`) ? `po_${k}` : null;
|
|
486
|
+
const gainedBy = both ? gained(k) : violated(`pn_${k}`) && cannot(`po_${k}`) ? `pn_${k}` : null;
|
|
487
|
+
if (lostBy) {
|
|
488
|
+
out.push({ rule: 'upgrade-lost', category: 'upgrade', class: c.label, check: `pn_${k}`, detail: `${c.label} could upgrade and no longer can`, witness: witness(model, results[lostBy]).text });
|
|
489
|
+
}
|
|
490
|
+
if (gainedBy) {
|
|
491
|
+
out.push({ rule: 'upgrade-gained', category: 'upgrade', class: c.label, check: `pn_${k}`, fixed: true, detail: `${c.label} can now upgrade and could not before`, witness: witness(model, results[gainedBy]).text });
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
// The bare implementation: only a regression counts.
|
|
496
|
+
if (['proven', 'bounded'].includes(statusOf(results.lock_old)) && statusOf(results.lock_new) === 'violated') {
|
|
497
|
+
const w = witness(model, results.lock_new);
|
|
498
|
+
out.push({ rule: 'implementation-open', category: 'init', function: w.text.call, check: 'lock_new', fixed: true, detail: `the new implementation contract can be changed by calling it directly (${w.text.call}); the old one could not`, witness: w.text });
|
|
499
|
+
}
|
|
500
|
+
if (base.init && statusOf(results.init_runs) === 'proven') {
|
|
501
|
+
out.push({ rule: 'init-fails', category: 'init', check: 'init_runs', fixed: true, detail: 'the initializer call given for this upgrade never succeeds', witness: {} });
|
|
502
|
+
}
|
|
503
|
+
return out;
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
for (let round = 0; ; round++) {
|
|
507
|
+
findings = collect();
|
|
508
|
+
const rerun = [];
|
|
509
|
+
let changed = false;
|
|
510
|
+
for (const f of findings) {
|
|
511
|
+
if (f.fixed) continue;
|
|
512
|
+
const e = exceptions.find((x) => matchException(x, f));
|
|
513
|
+
if (!e) continue;
|
|
514
|
+
e.used = true;
|
|
515
|
+
changed = true;
|
|
516
|
+
accepted.push({ ...f, reason: e.reason });
|
|
517
|
+
if (f.rule === 'guard') {
|
|
518
|
+
results[f.check] = { exitcode: 0, boundedLoops: 0 };
|
|
519
|
+
} else if (f.rule === 'upgrade-lost') {
|
|
520
|
+
results[`po_${f.check.slice(3)}`] = { exitcode: 0, boundedLoops: 0 };
|
|
521
|
+
} else {
|
|
522
|
+
// Take every variant of the accepted call out and look again.
|
|
523
|
+
const d = defs[f.check];
|
|
524
|
+
d.skip = [...new Set([...d.skip, ...sameCall(f.shape)])];
|
|
525
|
+
if (!rerun.includes(d)) rerun.push(d);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
if (!changed) break;
|
|
529
|
+
if (round >= MAX_ROUNDS) {
|
|
530
|
+
findings.push({ rule: 'policy', category: 'access', fixed: true, check: '', detail: `gave up re-checking after ${MAX_ROUNDS} rounds of accepted exceptions`, witness: {} });
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
533
|
+
await runChecks(rerun);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ---- coverage
|
|
537
|
+
const names = Object.keys(defs);
|
|
538
|
+
const group = (prefixes) => names.filter((n) => prefixes.some((p) => n.startsWith(p)));
|
|
539
|
+
const propertyOf = (label, checkNames, rules, mandatory = true) => {
|
|
540
|
+
const mine = findings.filter((f) => rules.includes(f.rule));
|
|
541
|
+
const mineAccepted = accepted.filter((f) => rules.includes(f.rule));
|
|
542
|
+
// A "reach" check is a question: a counterexample there is an answer, not a failure.
|
|
543
|
+
const statuses = checkNames.map((n) => {
|
|
544
|
+
const s = statusOf(results[n]);
|
|
545
|
+
const guard = /^g_(\d+)$/.exec(n);
|
|
546
|
+
if (guard && s === 'violated' && classes.every((_, k) => results[`gc_${guard[1]}_${k}`]) && results[`gr_${guard[1]}`]) return 'proven';
|
|
547
|
+
// A call not proven equivalent was checked in detail instead.
|
|
548
|
+
if (n.startsWith('e_')) return 'proven';
|
|
549
|
+
const reach = /^(n_|cn_|co_|u_|path_any$|path_new_any$|po_|pn_)/.test(n);
|
|
550
|
+
return reach && s === 'violated' ? 'proven' : s;
|
|
551
|
+
});
|
|
552
|
+
let status = worst(statuses);
|
|
553
|
+
if (mine.length) status = 'violated';
|
|
554
|
+
else if (RANK[status] <= RANK.accepted && mineAccepted.length) status = 'accepted';
|
|
555
|
+
const count = (s) => checkNames.filter((n) => !n.startsWith('e_') && statusOf(results[n]) === s).length;
|
|
556
|
+
return { name: label, mandatory, status, checks: checkNames.length, unverified: count('timeout') + count('error'), bounded: count('bounded'), findings: mine.length, accepted: mineAccepted.length };
|
|
557
|
+
};
|
|
558
|
+
const properties = [
|
|
559
|
+
{ name: 'layout', mandatory: true, status: layoutProblems.length ? 'violated' : 'proven', checks: 1, unverified: 0, bounded: 0, findings: layoutProblems.length, accepted: 0 },
|
|
560
|
+
{ name: 'opcodes', mandatory: true, status: addedOpcodes.length ? 'violated' : 'proven', checks: 1, unverified: 0, bounded: 0, findings: addedOpcodes.length, accepted: 0 },
|
|
561
|
+
propertyOf('guards', group(['g_', 'gc_', 'gr_', 'e_']), ['guard']),
|
|
562
|
+
propertyOf('mutations', group(['m_', 'e_']), ['mutation']),
|
|
563
|
+
propertyOf('values', group(['v_']), ['value']),
|
|
564
|
+
propertyOf('capabilities', group(['n_', 'cn_', 'co_']), ['capability']),
|
|
565
|
+
propertyOf('upgrade', group(['u_', 'path_any', 'path_new_any', 'po_', 'pn_']), ['upgrade', 'upgrade-lost', 'upgrade-gained']),
|
|
566
|
+
propertyOf('init', group(['lock_', 'init_runs']), ['implementation-open', 'init-fails']),
|
|
567
|
+
];
|
|
568
|
+
for (const prop of properties) {
|
|
569
|
+
const open = unresolved.filter((u) => u.property === prop.name).length;
|
|
570
|
+
if (!open || prop.findings) continue;
|
|
571
|
+
prop.unverified += open;
|
|
572
|
+
if (RANK[prop.status] < RANK.unresolved) prop.status = 'unresolved';
|
|
573
|
+
}
|
|
574
|
+
// The bare implementation is held to what the old one already guaranteed:
|
|
575
|
+
// lock_old is a question, and lock_new counts only when the old one was locked.
|
|
576
|
+
const initProp = properties.find((p) => p.name === 'init');
|
|
577
|
+
const lockOld = statusOf(results.lock_old);
|
|
578
|
+
const initParts = [];
|
|
579
|
+
if (lockOld !== 'violated') initParts.push(lockOld, statusOf(results.lock_new) === 'violated' ? 'proven' : statusOf(results.lock_new));
|
|
580
|
+
if ('init_runs' in defs) {
|
|
581
|
+
const result = statusOf(results.init_runs);
|
|
582
|
+
initParts.push(result === 'violated' ? 'proven' : result === 'proven' ? 'violated' : result);
|
|
583
|
+
}
|
|
584
|
+
if (initProp.findings === 0) {
|
|
585
|
+
initProp.status = worst(initParts);
|
|
586
|
+
initProp.unverified = initParts.filter((x) => RANK[x] === 4).length;
|
|
587
|
+
}
|
|
588
|
+
const implementationOpenBefore = lockOld === 'violated';
|
|
589
|
+
const unsupported = [...model.notes.unsupported];
|
|
590
|
+
if (unsupported.length) properties.push({ name: 'model', mandatory: true, status: 'unsupported', checks: 0, unverified: unsupported.length, bounded: 0, findings: 0, accepted: 0 });
|
|
591
|
+
for (const [name, id] of [['reentrancy', 'callbacks'], ['context', 'block-context']]) {
|
|
592
|
+
const verified = observations[id].status === 'supported';
|
|
593
|
+
const result = name === 'context' && context.length ? results.context_compare : null;
|
|
594
|
+
const status = verified ? (name === 'context' && context.length ? statusOf(result) : 'proven') : 'unsupported';
|
|
595
|
+
if (statusOf(result) === 'violated') {
|
|
596
|
+
findings.push({
|
|
597
|
+
rule: 'context', category: 'context', fixed: true,
|
|
598
|
+
detail: 'Modeled call success or return/revert data differs under shared symbolic block inputs.',
|
|
599
|
+
witness: witness(model, result).text,
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
properties.push({ name, mandatory: true, status, checks: 1, unverified: Number(RANK[status] === 4), bounded: Number(status === 'bounded'), findings: Number(status === 'violated'), accepted: 0 });
|
|
603
|
+
if (!verified) unsupported.push(observations[id].basis);
|
|
604
|
+
}
|
|
605
|
+
if (context.length) model.notes.bounded.add(`shared symbolic block inputs per modeled call: ${context.join(', ')}`);
|
|
606
|
+
|
|
607
|
+
findings.push(...layoutProblems.map((detail) => ({ rule: 'layout', category: 'layout', detail, witness: {} })));
|
|
608
|
+
findings.push(...addedOpcodes.map((opcode) => ({ rule: 'opcode', category: 'opcodes', detail: `new ${opcode} opcode`, witness: {} })));
|
|
609
|
+
|
|
610
|
+
const all = names.map((n) => statusOf(results[n]));
|
|
611
|
+
return {
|
|
612
|
+
engine: ENGINE_ID,
|
|
613
|
+
observations,
|
|
614
|
+
externalEffects,
|
|
615
|
+
batches,
|
|
616
|
+
properties,
|
|
617
|
+
findings: [...findings.map(({ check, shape, fixed, ...f }) => ({ ...f, exceptable: !fixed })), ...probeFindings],
|
|
618
|
+
accepted: accepted.map(({ check, shape, fixed, ...f }) => f),
|
|
619
|
+
unusedExceptions: exceptions.filter((e) => !e.used).map(({ used, ...e }) => e),
|
|
620
|
+
coverage: {
|
|
621
|
+
checks: names.length,
|
|
622
|
+
proven: all.filter((s) => s === 'proven').length,
|
|
623
|
+
bounded: all.filter((s) => s === 'bounded').length,
|
|
624
|
+
answered: all.filter((s) => s === 'violated').length,
|
|
625
|
+
unresolved: unresolved.length,
|
|
626
|
+
timeout: all.filter((s) => s === 'timeout').length,
|
|
627
|
+
error: all.filter((s) => s === 'error').length,
|
|
628
|
+
seconds: Math.round(names.reduce((a, n) => a + (results[n]?.seconds || 0), 0) * 10) / 10,
|
|
629
|
+
callShapes: shapes.length,
|
|
630
|
+
trackedWords: model.words.length,
|
|
631
|
+
callerKinds: classes.length,
|
|
632
|
+
targets: targets.length,
|
|
633
|
+
},
|
|
634
|
+
notes: { bounded: [...model.notes.bounded], unsupported, unresolved: unresolved.map((u) => u.detail), liveStateRecognized: model.live.recognized, implementationOpenBefore, upgradeAuthority: upgradeAuthorityNote },
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
module.exports = { verifyUpgrade, ENGINE_ID, ERC1967 };
|