@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
package/core/keccak.js ADDED
@@ -0,0 +1,89 @@
1
+ // Pure zero-dependency Ethereum Keccak-256 (0x01 domain padding, FIPS-202 permutation).
2
+ // Enables offline third-party verification of calldata hashes, EIP-712 digests,
3
+ // and runtime EXTCODEHASH values without requiring Foundry `cast` or npm packages.
4
+
5
+ const RC = [
6
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
7
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
8
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
9
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
10
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
11
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
12
+ ];
13
+
14
+ const ROTC = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44];
15
+ const PILN = [10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1];
16
+ const MASK64 = 0xffffffffffffffffn;
17
+
18
+ function rotl64(x, n) {
19
+ return ((x << BigInt(n)) | (x >> BigInt(64 - n))) & MASK64;
20
+ }
21
+
22
+ function keccakF1600(state) {
23
+ const bc = new Array(5);
24
+ for (let round = 0; round < 24; round++) {
25
+ for (let i = 0; i < 5; i++) {
26
+ bc[i] = state[i] ^ state[i + 5] ^ state[i + 10] ^ state[i + 15] ^ state[i + 20];
27
+ }
28
+ for (let i = 0; i < 5; i++) {
29
+ const t = bc[(i + 4) % 5] ^ rotl64(bc[(i + 1) % 5], 1);
30
+ for (let j = 0; j < 25; j += 5) state[j + i] = (state[j + i] ^ t) & MASK64;
31
+ }
32
+ let t = state[1];
33
+ for (let i = 0; i < 24; i++) {
34
+ const j = PILN[i];
35
+ const tmp = state[j];
36
+ state[j] = rotl64(t, ROTC[i]);
37
+ t = tmp;
38
+ }
39
+ for (let j = 0; j < 25; j += 5) {
40
+ for (let i = 0; i < 5; i++) bc[i] = state[j + i];
41
+ for (let i = 0; i < 5; i++) {
42
+ state[j + i] = (state[j + i] ^ ((~bc[(i + 1) % 5] & MASK64) & bc[(i + 2) % 5])) & MASK64;
43
+ }
44
+ }
45
+ state[0] = (state[0] ^ RC[round]) & MASK64;
46
+ }
47
+ }
48
+
49
+ function toBytes(input) {
50
+ if (Buffer.isBuffer(input)) return input;
51
+ if (input instanceof Uint8Array) return Buffer.from(input);
52
+ if (typeof input === 'string') {
53
+ if (/^0x(?:[0-9a-f]{2})*$/i.test(input)) return Buffer.from(input.slice(2), 'hex');
54
+ return Buffer.from(input, 'utf8');
55
+ }
56
+ throw new Error('keccak256 expects a Buffer, Uint8Array, 0x-hex bytes, or UTF-8 string.');
57
+ }
58
+
59
+ function keccak256Buffer(input) {
60
+ const msg = toBytes(input);
61
+ const rate = 136; // 1088 bits for Keccak-256
62
+ const padLen = rate - (msg.length % rate);
63
+ const padded = Buffer.alloc(msg.length + padLen);
64
+ msg.copy(padded, 0);
65
+ padded[msg.length] ^= 0x01;
66
+ padded[padded.length - 1] ^= 0x80;
67
+
68
+ const state = new Array(25).fill(0n);
69
+ for (let offset = 0; offset < padded.length; offset += rate) {
70
+ for (let i = 0; i < 17; i++) {
71
+ state[i] ^= padded.readBigUInt64LE(offset + i * 8);
72
+ }
73
+ keccakF1600(state);
74
+ }
75
+
76
+ const out = Buffer.alloc(32);
77
+ for (let i = 0; i < 4; i++) {
78
+ out.writeBigUInt64LE(state[i], i * 8);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ function keccak256(input) {
84
+ return '0x' + keccak256Buffer(input).toString('hex');
85
+ }
86
+
87
+ const EMPTY_CODEHASH = keccak256('0x');
88
+
89
+ module.exports = { keccak256, keccak256Buffer, EMPTY_CODEHASH };
package/core/prove.js ADDED
@@ -0,0 +1,376 @@
1
+ // Verify one candidate implementation of a protocol
2
+ // project. A project is a Foundry folder, or a Hardhat folder proven in a
3
+ // temporary Foundry workspace (see ./hardhat). With one spec/*.spec.json it also
4
+ // needs a Halmos harness contract named Spec_<Contract> for every candidate.
5
+ // With no spec, only the generic upgrade checks run, against a baseline.
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const crypto = require('node:crypto');
9
+ const { run, cast, isName, runHalmos } = require('./tools');
10
+ const { upgradeChecks } = require('./generic');
11
+ const { verifyUpgrade } = require('./engine');
12
+ const { assessIntegrity } = require('./engine/integrity');
13
+ const { hasLibraryDependencies: hasExternalLibraries } = require('./engine/bytecode');
14
+ const { verifyIntentFirewall } = require('./isl-firewall');
15
+ const { isHardhat, hardhatWorkspace } = require('./hardhat');
16
+
17
+ const HARNESS = 'Spec_';
18
+ /** What a proxy is bound to when the project has no spec file. */
19
+ const GENERIC_SPEC = 'GuardeFi.GenericUpgradeChecks.v1';
20
+
21
+ function specPath(dir) {
22
+ const specDir = path.join(dir, 'spec');
23
+ const files = fs.existsSync(specDir) ? fs.readdirSync(specDir).filter((f) => f.endsWith('.spec.json')) : [];
24
+ if (files.length > 1) throw new Error(`expected at most one spec/*.spec.json, found ${files.length}`);
25
+ return files.length ? path.join(specDir, files[0]) : null;
26
+ }
27
+
28
+ function loadSpec(dir) {
29
+ const file = specPath(dir);
30
+ if (!file) return { file: null, spec: null, bytes: null };
31
+ const bytes = fs.readFileSync(file);
32
+ const spec = JSON.parse(bytes.toString('utf8'));
33
+ for (const key of ['allowedFunctions', 'properties']) {
34
+ if (!Array.isArray(spec[key]) || spec[key].length === 0) throw new Error(`spec is missing ${key}`);
35
+ }
36
+ if (!spec.twins || Object.keys(spec.twins).length === 0) throw new Error('spec is missing twins');
37
+ if (spec.status === 'draft' || spec.authorized === false) throw new Error(`${path.relative(dir, file)} is an unreviewed draft (status: draft / authorized: false); review it, then delete both fields`);
38
+ return { file, spec, bytes };
39
+ }
40
+
41
+ function islPaths(dir) {
42
+ const specDir = path.join(dir, 'spec');
43
+ if (!fs.existsSync(specDir)) return [];
44
+ return fs.readdirSync(specDir).filter((f) => f.endsWith('.isl')).sort().map((f) => path.join(specDir, f));
45
+ }
46
+
47
+ function loadISLSpecs(dir, explicitPaths = null) {
48
+ const files = explicitPaths ? explicitPaths.map((p) => path.resolve(dir, p)) : islPaths(dir);
49
+ // An optional project adapter next to a behavior policy (<name>.adapter.sol) enables deployed-state checks.
50
+ return files.map((file) => {
51
+ const adapterFile = file.replace(/\.isl$/, '.adapter.sol');
52
+ return { file, name: path.basename(file), source: fs.readFileSync(file, 'utf8'),
53
+ adapter: adapterFile !== file && fs.existsSync(adapterFile) ? fs.readFileSync(adapterFile, 'utf8') : null };
54
+ });
55
+ }
56
+
57
+ function islCombinedDigest(islSpecs) {
58
+ const digests = islSpecs.map(({ source }) => crypto.createHash('sha256').update(source, 'utf8').digest('hex'));
59
+ return crypto.createHash('sha256').update(digests.join(':'), 'utf8').digest('hex');
60
+ }
61
+
62
+ /** The value fixed in the proxy: keccak256 of the spec file's raw bytes, ISL digest, or the generic marker. */
63
+ async function specHash(dir) {
64
+ const file = specPath(dir);
65
+ if (file) return hashSpecBytes(fs.readFileSync(file));
66
+ const islSpecs = loadISLSpecs(dir);
67
+ if (islSpecs.length) return cast(['keccak', '0x' + Buffer.from(islCombinedDigest(islSpecs), 'utf8').toString('hex')]);
68
+ return hashSpecBytes(null);
69
+ }
70
+
71
+ function hashSpecBytes(bytes) {
72
+ return cast(['keccak', bytes ? '0x' + bytes.toString('hex') : GENERIC_SPEC]);
73
+ }
74
+
75
+ /** Path of the one build artifact for a contract name. */
76
+ function artifactPath(dir, contract) {
77
+ const out = path.join(dir, 'out');
78
+ const hits = fs
79
+ .readdirSync(out)
80
+ .filter((d) => d !== 'build-info')
81
+ .map((d) => path.join(out, d, `${contract}.json`))
82
+ .filter((p) => fs.existsSync(p));
83
+ if (hits.length !== 1) throw new Error(`expected one build artifact for ${contract}, found ${hits.length}`);
84
+ return hits[0];
85
+ }
86
+
87
+ async function build(dir) {
88
+ // The storage layout is needed by the generic upgrade checks.
89
+ const r = await run('forge', ['build', '--root', dir, '--extra-output', 'storageLayout']);
90
+ if (r.code !== 0) throw new Error('forge build failed:\n' + (r.stderr || r.stdout).trim().split('\n').slice(-12).join('\n'));
91
+ }
92
+
93
+ /**
94
+ * Run `fn(root, project)` on a Foundry root for `dir`: the folder itself, or a
95
+ * temporary workspace for a Hardhat project. `names` are the contracts to prove.
96
+ */
97
+ async function withProject(dir, names, fn) {
98
+ if (fs.existsSync(path.join(dir, 'foundry.toml'))) return fn(dir, { kind: 'foundry' });
99
+ if (!isHardhat(dir)) throw new Error('not a Foundry or Hardhat project (no foundry.toml or hardhat.config.*)');
100
+ const workspace = hardhatWorkspace(dir, names);
101
+ try {
102
+ return await fn(workspace.root, workspace.project, workspace);
103
+ } finally {
104
+ workspace.cleanup();
105
+ }
106
+ }
107
+
108
+ /** Open a project: build it and list the contracts that can be proven. */
109
+ async function openProject(dir) {
110
+ return withProject(dir, [], (root) => openIn(dir, root));
111
+ }
112
+
113
+ async function openIn(dir, root) {
114
+ const { file, spec, bytes } = loadSpec(dir);
115
+ const islSpecs = file ? [] : loadISLSpecs(dir);
116
+ await build(root);
117
+ const sources = sourceContracts(root);
118
+ const computedSpecHash = file
119
+ ? await hashSpecBytes(bytes)
120
+ : islSpecs.length
121
+ ? await cast(['keccak', '0x' + Buffer.from(islCombinedDigest(islSpecs), 'utf8').toString('hex')])
122
+ : await hashSpecBytes(null);
123
+ return {
124
+ dir,
125
+ name: spec?.name || path.basename(dir),
126
+ specFile: file ? path.relative(dir, file) : islSpecs.length ? path.relative(dir, islSpecs[0].file) : null,
127
+ islFiles: islSpecs.map((s) => path.relative(dir, s.file)),
128
+ specHash: computedSpecHash,
129
+ properties: spec ? spec.properties : [],
130
+ allowedFunctions: spec ? spec.allowedFunctions : [],
131
+ // With a spec.json: contracts from src/ that have a Spec_<Contract> harness; with ISL or generic: all src/ contracts.
132
+ candidates: spec ? sources.filter((name) => hasArtifact(root, HARNESS + name)) : sources,
133
+ // What a candidate can be compared with by the generic upgrade checks.
134
+ baselines: sources,
135
+ };
136
+ }
137
+
138
+ /** Names of the deployable contracts that come from src/. */
139
+ function sourceContracts(dir) {
140
+ const out = path.join(dir, 'out');
141
+ const names = [];
142
+ for (const d of fs.readdirSync(out)) {
143
+ if (d === 'build-info') continue;
144
+ for (const f of fs.readdirSync(path.join(out, d))) {
145
+ const name = f.replace(/\.json$/, '');
146
+ if (isSourceContract(dir, name)) names.push(name);
147
+ }
148
+ }
149
+ return names.sort();
150
+ }
151
+
152
+ function hasArtifact(dir, contract) {
153
+ try {
154
+ artifactPath(dir, contract);
155
+ return true;
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ /** The src/ contract whose built runtime code has this hash, or null. */
162
+ async function contractByCodehash(project, codehash) {
163
+ return withProject(project, [], (dir) => codehashIn(dir, codehash));
164
+ }
165
+
166
+ async function codehashIn(dir, codehash) {
167
+ await build(dir);
168
+ for (const name of sourceContracts(dir)) {
169
+ const art = JSON.parse(fs.readFileSync(artifactPath(dir, name), 'utf8'));
170
+ if (!/^(0x)?[0-9a-f]*$/i.test(art.deployedBytecode.object)) continue;
171
+ if ((await cast(['keccak', art.deployedBytecode.object])).toLowerCase() === codehash.toLowerCase()) return name;
172
+ }
173
+ return null;
174
+ }
175
+
176
+ /** The project's source folder from foundry.toml (default src). */
177
+ function sourceFolder(dir) {
178
+ const toml = fs.readFileSync(path.join(dir, 'foundry.toml'), 'utf8');
179
+ const profile = toml.split(/^\[/m).find((s) => s.startsWith('profile.default]')) || '';
180
+ return profile.match(/^\s*src\s*=\s*["']([^"'/]+)\/?["']/m)?.[1] || 'src';
181
+ }
182
+
183
+ /** True when the contract comes from the source folder (not the test folder) and has code. */
184
+ function isSourceContract(dir, contract) {
185
+ try {
186
+ const art = JSON.parse(fs.readFileSync(artifactPath(dir, contract), 'utf8'));
187
+ return String(art.ast?.absolutePath || '').startsWith(sourceFolder(dir) + '/') && art.deployedBytecode?.object?.length > 2;
188
+ } catch {
189
+ return false;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Each broken twin must fail its named check, or that check proves nothing.
195
+ * Result is cached per (test folder, spec) content so it runs once per change.
196
+ */
197
+ async function checkTeeth(dir, spec, bytes, strict) {
198
+ const h = crypto.createHash('sha256').update(bytes);
199
+ const testDir = path.join(dir, 'test');
200
+ for (const f of fs.readdirSync(testDir).sort()) h.update(fs.readFileSync(path.join(testDir, f)));
201
+ const marker = path.join(dir, 'cache', `teeth.${strict ? 'strict-v1.' : ''}${h.digest('hex')}`);
202
+ if (fs.existsSync(marker)) return [];
203
+ const problems = [];
204
+ for (const [twin, check] of Object.entries(spec.twins)) {
205
+ const res = await runHalmos(dir, twin);
206
+ // The twin must have run this check and failed it.
207
+ const result = res[check];
208
+ if (!result || result.proven || (strict && (result.exitcode !== 1 || !result.validModel))) problems.push(`spec check ${check} did not refute its broken twin ${twin}`);
209
+ }
210
+ if (problems.length === 0) {
211
+ fs.mkdirSync(path.dirname(marker), { recursive: true });
212
+ fs.writeFileSync(marker, '');
213
+ }
214
+ return problems;
215
+ }
216
+
217
+ /**
218
+ * `baseline` is the implementation this one replaces. With it the generic
219
+ * upgrade checks run. A project without a spec has nothing else, so there the
220
+ * baseline is required. `deployment` is the deployed transparent proxy at a
221
+ * pinned block (see ./engine/deployment); it goes to the upgrade engine.
222
+ */
223
+ // `deploymentRead` optionally replaces the deployment checks' single-RPC reader (e.g. a provider quorum).
224
+ async function prove(project, contract, baseline, { strict = false, islFiles = null, deployment = null, deploymentRead = null } = {}) {
225
+ if (!isName(contract)) throw new Error('bad contract name');
226
+ if (baseline && !isName(baseline)) throw new Error('bad baseline name');
227
+ const { spec, bytes } = loadSpec(project);
228
+ const islSpecs = spec && !islFiles ? [] : loadISLSpecs(project, islFiles);
229
+ if (strict && ((!spec && !islSpecs.length) || !baseline)) throw new Error('Protocol Firewall requires a project spec and a live baseline.');
230
+ if (!spec && !islSpecs.length && !baseline) throw new Error('this project has no spec, so it needs the implementation being replaced to compare with');
231
+ if (baseline === contract) throw new Error('the baseline must be a different contract');
232
+ if (deployment && (spec || !baseline)) throw new Error('deployment evidence is checked by the upgrade engine, which runs only without a spec.json and with a baseline');
233
+ return withProject(project, [contract, baseline], (dir, projectInfo, workspace) =>
234
+ proveIn(dir, { contract, baseline, strict, spec, bytes, islSpecs, deployment, deploymentRead, projectInfo, workspace }));
235
+ }
236
+
237
+ async function proveIn(dir, { contract, baseline, strict, spec, bytes, islSpecs, deployment, deploymentRead, projectInfo, workspace }) {
238
+ await build(dir);
239
+ const artifact = JSON.parse(fs.readFileSync(artifactPath(dir, contract), 'utf8'));
240
+ // A Hardhat project: the code proven must be the code Hardhat built.
241
+ if (workspace) {
242
+ const names = { [contract]: artifact };
243
+ if (baseline) names[baseline] = JSON.parse(fs.readFileSync(artifactPath(dir, baseline), 'utf8'));
244
+ projectInfo = { ...projectInfo, artifacts: workspace.crossCheck(names) };
245
+ }
246
+ // Artifact proofs can model libraries. Certificates do not bind their live
247
+ // runtime identities yet, so this path must refuse linked implementations.
248
+ if (hasExternalLibraries(artifact)) throw new Error('refusing certificate proof: external library runtime identities are not bound by this certificate');
249
+ const reasons = [];
250
+ const properties = [];
251
+ let engineReport = null;
252
+ let intentReport = null;
253
+ let baselineBytecode = null;
254
+ let policyViolation = false;
255
+
256
+ if (spec) {
257
+ // 1. The checks have teeth.
258
+ const harnessProblems = await checkTeeth(dir, spec, bytes, strict);
259
+ reasons.push(...harnessProblems);
260
+ if (strict) properties.push({ name: 'Spec harness self-check', proven: !harnessProblems.length,
261
+ status: harnessProblems.length ? 'unknown' : 'proven' });
262
+
263
+ // 2. No function outside the spec, no fallback or receive.
264
+ const beforeInterface = reasons.length;
265
+ for (const fn of Object.keys(artifact.methodIdentifiers || {})) {
266
+ if (!spec.allowedFunctions.includes(fn)) reasons.push(`function not in spec: ${fn}`);
267
+ }
268
+ for (const item of artifact.abi || []) {
269
+ if (item.type === 'fallback' || item.type === 'receive') reasons.push(`function not in spec: ${item.type}`);
270
+ }
271
+ policyViolation = reasons.length > beforeInterface;
272
+
273
+ if (strict) properties.push({ name: 'Approved contract interface', proven: reasons.length === beforeInterface,
274
+ status: reasons.length === beforeInterface ? 'proven' : 'failed' });
275
+
276
+ // 3. Every spec property proven for this implementation.
277
+ const results = await runHalmos(dir, HARNESS + contract);
278
+ for (const name of spec.properties) {
279
+ const r = results[name];
280
+ const proven = Boolean(r?.proven && (!strict || r.boundedLoops === 0));
281
+ if (!proven) reasons.push(`not proven: ${name}`);
282
+ const status = proven ? 'proven' : r?.exitcode === 1 && r.validModel ? 'failed' : 'unknown';
283
+ // Engine 2.2: a valid counterexample to an approved spec property is a confirmed violation.
284
+ if (status === 'failed') policyViolation = true;
285
+ properties.push({ name, proven, status, counterexample: r && !r.proven ? r.counterexample : null });
286
+ }
287
+ }
288
+
289
+ // Generic upgrade checks against the implementation being replaced.
290
+ if (baseline) {
291
+ const baseArtifact = JSON.parse(fs.readFileSync(artifactPath(dir, baseline), 'utf8'));
292
+ if (hasExternalLibraries(baseArtifact)) throw new Error('refusing certificate proof: baseline external library runtime identities are not bound by this certificate');
293
+ baselineBytecode = baseArtifact.deployedBytecode.object;
294
+ for (const c of await upgradeChecks({ dir, contract, baseline, artifact, baseArtifact, strict })) {
295
+ const name = `upgrade_${c.name}`;
296
+ if (!c.proven) reasons.push(`not proven: ${name}`);
297
+ if (['layout', 'opcodes'].includes(c.name) && !c.proven) policyViolation = true;
298
+ properties.push({ ...c, name });
299
+ }
300
+ if (!spec && reasons.length === 0) {
301
+ engineReport = await verifyUpgrade({ dir, artifact, baseArtifact, ...(deployment ? { deployment, ...(deploymentRead ? { deploymentRead } : {}) } : {}) });
302
+ policyViolation ||= engineReport.verdict === 'NO_SHIP';
303
+ }
304
+ }
305
+
306
+ if (islSpecs.length) {
307
+ const baseArtifact = baseline ? JSON.parse(fs.readFileSync(artifactPath(dir, baseline), 'utf8')) : null;
308
+ intentReport = await verifyIntentFirewall({
309
+ dir,
310
+ candidate: contract,
311
+ baseline: baseline || null,
312
+ candidateArtifact: artifact,
313
+ baseArtifact,
314
+ islSpecs,
315
+ });
316
+ if (intentReport.decision === 'NO_SHIP') policyViolation = true;
317
+ for (const claim of intentReport.claims) {
318
+ const proven = claim.outcome === 'satisfied' && claim.epistemicClass === 'PROVEN';
319
+ const status = claim.outcome === 'violated'
320
+ ? 'failed'
321
+ : claim.epistemicClass === 'BOUNDED' && claim.outcome === 'satisfied'
322
+ ? 'bounded'
323
+ : proven ? 'proven' : 'unknown';
324
+ if (!proven) reasons.push(`not proven: ${claim.id}`);
325
+ properties.push({ name: claim.id, proven, status, counterexample: claim.counterexample || null });
326
+ }
327
+ }
328
+
329
+ // The hash the chain will see for this exact build.
330
+ const [codehash, baselineCodehash, verifiedSpecHash] = await Promise.all([
331
+ cast(['keccak', artifact.deployedBytecode.object]),
332
+ baselineBytecode === null ? null : cast(['keccak', baselineBytecode]),
333
+ bytes
334
+ ? hashSpecBytes(bytes)
335
+ : islSpecs.length
336
+ ? cast(['keccak', '0x' + Buffer.from(islCombinedDigest(islSpecs), 'utf8').toString('hex')])
337
+ : hashSpecBytes(null),
338
+ ]);
339
+
340
+ const integrity = engineReport?.integrity || assessIntegrity(spec
341
+ ? [{ name: 'spec-harness', status: reasons.length ? 'unresolved' : 'proven' }]
342
+ : []);
343
+ const certificate = !reasons.length && engineReport?.verdict === 'SHIP' ? engineReport.certificate : null;
344
+ // Engine 2.2: a spec-based release ships when the harness has teeth, the interface is approved and every
345
+ // spec property is proven by Halmos (bounded symbolic execution) with no outstanding reason. No PCU
346
+ // deployment certificate is issued for this path; signing binds the release evidence instead.
347
+ const specShip = Boolean(spec) && !reasons.length && !policyViolation &&
348
+ properties.some((p) => spec.properties.includes(p.name)) &&
349
+ spec.properties.every((name) => properties.some((p) => p.name === name && p.proven));
350
+ if (!certificate && !specShip) {
351
+ const finding = engineReport?.findings[0]?.detail || intentReport?.claims.find((c) => c.outcome === 'violated')?.detail;
352
+ const unknown = engineReport?.notes.unsupported[0];
353
+ reasons.push(finding || unknown || 'Proof integrity incomplete. No deployment proof certificate was issued.');
354
+ }
355
+ return {
356
+ contract,
357
+ baseline: baseline || null,
358
+ verdict: policyViolation ? 'NO_SHIP' : certificate || specShip ? 'SHIP' : 'UNVERIFIED',
359
+ assurance: certificate ? 'proof-certificate' : specShip ? 'spec-bounded' : null,
360
+ codehash,
361
+ baselineCodehash,
362
+ specHash: verifiedSpecHash,
363
+ reasons,
364
+ properties,
365
+ engineReport,
366
+ intentReport,
367
+ integrity,
368
+ certificate,
369
+ project: projectInfo,
370
+ compiler: artifact.metadata?.compiler?.version ? { version: artifact.metadata.compiler.version, settings: artifact.metadata.settings ?? null } : null,
371
+ // Deployment evidence as the engine checked it; unresolved when the engine did not run.
372
+ deployment: deployment ? engineReport?.deployment ?? { status: 'unresolved', basis: 'Not evaluated: the upgrade engine did not run.', evidence: {}, problems: ['the upgrade engine did not run'] } : null,
373
+ };
374
+ }
375
+
376
+ module.exports = { openProject, prove, specHash, contractByCodehash };