@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,1396 @@
1
+ // Intent Firewall: ISL Invariant & Transaction Behavior Regression Verification (P0).
2
+ // Compiles protocol ISL specifications (entity invariants and transaction behaviors)
3
+ // against candidate and baseline ABIs, executes symbolic Halmos regression harnesses
4
+ // over shared arbitrary storage (plain + ERC-7201 namespaced + struct/2D mappings),
5
+ // linked Solidity libraries, and linked multi-contract partner runtimes, and emits
6
+ // epistemically classified claims and a verifiable Protocol Release Receipt.
7
+ const fs = require('node:fs');
8
+ const os = require('node:os');
9
+ const path = require('node:path');
10
+ const { createHash } = require('node:crypto');
11
+ const { compileISL } = require('./isl-compiler');
12
+ const { verifyBehaviors } = require('./isl/behavior-verify');
13
+ const { variableSlots } = require('./generic');
14
+ const { callPlans, signature } = require('./engine/abi');
15
+ const { resolveBytecode, hasLibraryDependencies } = require('./engine/bytecode');
16
+ const { namespaces, hex32 } = require('./engine/model');
17
+ const { analyze, quietLibraryIndices } = require('./engine/provenance');
18
+ const { keccak256 } = require('./keccak');
19
+ const { cast, runHalmos, checkerStatus } = require('./tools');
20
+ const { createReleaseReceipt } = require('./release-receipt');
21
+
22
+ const MAX_SLOTS = 56;
23
+ const MAX_MAP_ENTRIES = 12;
24
+ const MAX_NESTED_MAPS = 4;
25
+ const MAX_STRUCT_WORDS = 6;
26
+ const ARG_WORDS = 4;
27
+ const ROLE_TYPE = /^(address( payable)?$|contract )/;
28
+ const FOREIGN_OPS = ['CALL', 'CALLCODE', 'DELEGATECALL', 'CREATE', 'CREATE2', 'SELFDESTRUCT'];
29
+ const USER_EXIT_RE = /^(?:withdraw|redeem|exit|emergencyWithdraw|claim|unstake)$/i;
30
+
31
+ function detectISLProfile(source) {
32
+ if (typeof source !== 'string' || !source.trim()) {
33
+ throw new Error('ISL source cannot be empty.');
34
+ }
35
+ const stripped = source.replace(/\/\/[^\r\n]*/g, '');
36
+ if (/\bbehavior\s+[A-Za-z_]/.test(stripped)) return 'behavior';
37
+ if (/\bentity\s+[A-Za-z_]/.test(stripped)) return 'getter';
38
+ throw new Error('ISL source must declare either an entity invariant block or a behavior block.');
39
+ }
40
+
41
+ function inplaceWordSpan(types, typeId) {
42
+ const t = types?.[typeId];
43
+ if (!t || t.encoding !== 'inplace') return null;
44
+ if (!t.members && !t.base) {
45
+ const bytes = Number(t.numberOfBytes);
46
+ return Number.isFinite(bytes) && bytes > 0 && bytes <= 32 ? 1 : null;
47
+ }
48
+ if (t.members) {
49
+ let maxWord = 0;
50
+ for (const m of t.members) {
51
+ const sub = inplaceWordSpan(types, m.type);
52
+ if (sub === null) return null;
53
+ maxWord = Math.max(maxWord, Number(m.slot) + sub);
54
+ }
55
+ return maxWord > 0 && maxWord <= MAX_STRUCT_WORDS ? maxWord : null;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function namespaceStructSpan(nsType) {
61
+ if (!nsType || nsType.kind !== 'struct' || nsType.incomplete) return null;
62
+ let maxWord = 0;
63
+ for (const m of nsType.members || []) {
64
+ if (m.type.kind === 'value') {
65
+ maxWord = Math.max(maxWord, Number(m.slot) + 1);
66
+ } else if (m.type.kind === 'struct') {
67
+ const sub = namespaceStructSpan(m.type);
68
+ if (sub === null) return null;
69
+ maxWord = Math.max(maxWord, Number(m.slot) + sub);
70
+ } else {
71
+ return null;
72
+ }
73
+ }
74
+ return maxWord > 0 && maxWord <= MAX_STRUCT_WORDS ? maxWord : null;
75
+ }
76
+
77
+ function collectNamespaceEntries(spaces, plainSet, addressMappingEntries, nestedAddressMappingSlots, state) {
78
+ const visitStruct = (members, baseSlot) => {
79
+ for (const m of members || []) {
80
+ const slot = baseSlot + BigInt(m.slot);
81
+ if (m.type.kind === 'value') {
82
+ plainSet.add(slot);
83
+ } else if (m.type.kind === 'struct') {
84
+ if (m.type.incomplete) state.hasUnmodeledDynamic = true;
85
+ visitStruct(m.type.members, slot);
86
+ } else if (m.type.kind === 'mapping') {
87
+ if (m.type.key === 'address') {
88
+ if (m.type.value.kind === 'value') {
89
+ addressMappingEntries.push({ slot, words: 1 });
90
+ } else if (m.type.value.kind === 'struct') {
91
+ const span = namespaceStructSpan(m.type.value);
92
+ if (span !== null) addressMappingEntries.push({ slot, words: span });
93
+ else state.hasUnmodeledDynamic = true;
94
+ } else if (m.type.value.kind === 'mapping' && m.type.value.key === 'address' && m.type.value.value.kind === 'value') {
95
+ nestedAddressMappingSlots.push(slot);
96
+ } else {
97
+ state.hasUnmodeledDynamic = true;
98
+ }
99
+ } else {
100
+ state.hasUnmodeledDynamic = true;
101
+ }
102
+ } else {
103
+ state.hasUnmodeledDynamic = true;
104
+ }
105
+ }
106
+ };
107
+ for (const ns of spaces) {
108
+ if (ns.type?.incomplete) state.hasUnmodeledDynamic = true;
109
+ visitStruct(ns.type?.members || [], ns.base);
110
+ }
111
+ }
112
+
113
+ function collectStorageModel(artifact, spaces = []) {
114
+ const layout = artifact?.storageLayout;
115
+ if (!Array.isArray(layout?.storage) || !layout?.types) {
116
+ return {
117
+ supported: false,
118
+ plainSlots: [0n],
119
+ addressMappingSlots: [],
120
+ addressMappingEntries: [],
121
+ nestedAddressMappingSlots: [],
122
+ hasUnmodeledDynamic: true,
123
+ };
124
+ }
125
+ const plainSet = new Set(variableSlots(layout));
126
+ const addressMappingEntries = [];
127
+ const nestedAddressMappingSlots = [];
128
+ const state = { hasUnmodeledDynamic: false };
129
+
130
+ for (const entry of layout.storage) {
131
+ if (entry.label === '__gap' || entry.label.endsWith('_gap')) continue;
132
+ const t = layout.types[entry.type];
133
+ if (!t) continue;
134
+ if (t.encoding === 'mapping') {
135
+ const keyType = layout.types[t.key];
136
+ const valType = layout.types[t.value];
137
+ if (keyType && ROLE_TYPE.test(keyType.label || '')) {
138
+ const span = inplaceWordSpan(layout.types, t.value);
139
+ if (span !== null) {
140
+ addressMappingEntries.push({ slot: BigInt(entry.slot), words: span });
141
+ } else if (valType?.encoding === 'mapping') {
142
+ const k2 = layout.types[valType.key];
143
+ const v2Span = inplaceWordSpan(layout.types, valType.value);
144
+ if (k2 && ROLE_TYPE.test(k2.label || '') && v2Span === 1) {
145
+ nestedAddressMappingSlots.push(BigInt(entry.slot));
146
+ } else {
147
+ state.hasUnmodeledDynamic = true;
148
+ }
149
+ } else {
150
+ state.hasUnmodeledDynamic = true;
151
+ }
152
+ } else {
153
+ state.hasUnmodeledDynamic = true;
154
+ }
155
+ } else if (t.encoding !== 'inplace') {
156
+ state.hasUnmodeledDynamic = true;
157
+ }
158
+ }
159
+
160
+ if (spaces.length > 0) {
161
+ collectNamespaceEntries(spaces, plainSet, addressMappingEntries, nestedAddressMappingSlots, state);
162
+ }
163
+
164
+ let plainSlots = [...plainSet];
165
+ if (plainSlots.length === 0) plainSlots = [0n];
166
+
167
+ const dedupMap = new Map();
168
+ for (const item of addressMappingEntries) {
169
+ const prev = dedupMap.get(item.slot) || 0;
170
+ dedupMap.set(item.slot, Math.max(prev, item.words));
171
+ }
172
+ const allEntries = [...dedupMap.entries()].map(([slot, words]) => ({ slot, words }));
173
+ if (allEntries.length > MAX_MAP_ENTRIES) state.hasUnmodeledDynamic = true;
174
+ const boundedEntries = allEntries.slice(0, MAX_MAP_ENTRIES);
175
+
176
+ const uniqueNested = [...new Set(nestedAddressMappingSlots)];
177
+ if (uniqueNested.length > MAX_NESTED_MAPS) state.hasUnmodeledDynamic = true;
178
+ const boundedNested = uniqueNested.slice(0, MAX_NESTED_MAPS);
179
+
180
+ return {
181
+ supported: plainSlots.length <= MAX_SLOTS,
182
+ plainSlots: plainSlots.slice(0, MAX_SLOTS),
183
+ addressMappingSlots: boundedEntries.filter((e) => e.words === 1).map((e) => e.slot),
184
+ addressMappingEntries: boundedEntries,
185
+ nestedAddressMappingSlots: boundedNested,
186
+ hasUnmodeledDynamic: state.hasUnmodeledDynamic,
187
+ };
188
+ }
189
+
190
+ function enumerateAddressFields(artifact, spaces = []) {
191
+ const found = [];
192
+ const slotCounts = new Map();
193
+ const bump = (slot) => slotCounts.set(slot, (slotCounts.get(slot) || 0) + 1);
194
+
195
+ const layout = artifact?.storageLayout;
196
+ if (Array.isArray(layout?.storage) && layout?.types) {
197
+ const walkLayout = (typeId, prefix, baseSlot, offset) => {
198
+ const t = layout.types[typeId];
199
+ if (!t || t.encoding !== 'inplace') return;
200
+ if (t.members) {
201
+ for (const m of t.members) {
202
+ walkLayout(m.type, `${prefix}.${m.label}`, baseSlot + BigInt(m.slot), Number(m.offset || 0));
203
+ }
204
+ return;
205
+ }
206
+ if (t.base) return;
207
+ bump(baseSlot);
208
+ if (ROLE_TYPE.test(t.label || '')) {
209
+ found.push({ kind: 'storage', label: prefix, short: prefix.split('.').at(-1), slot: baseSlot, offset: Number(offset || 0) });
210
+ }
211
+ };
212
+ for (const entry of layout.storage) {
213
+ if (entry.label === '__gap' || entry.label.endsWith('_gap')) continue;
214
+ walkLayout(entry.type, entry.label, BigInt(entry.slot), Number(entry.offset || 0));
215
+ }
216
+ }
217
+
218
+ for (const ns of spaces) {
219
+ const walkNs = (members, prefix, baseSlot) => {
220
+ for (const m of members || []) {
221
+ const slot = baseSlot + BigInt(m.slot);
222
+ const label = `${prefix}.${m.label}`;
223
+ if (m.type.kind === 'value') {
224
+ bump(slot);
225
+ if (m.type.address) {
226
+ found.push({ kind: 'storage', label, short: m.label, slot, offset: Number(m.offset || 0) });
227
+ }
228
+ } else if (m.type.kind === 'struct') {
229
+ walkNs(m.type.members, label, slot);
230
+ }
231
+ }
232
+ };
233
+ walkNs(ns.type?.members || [], ns.name, ns.base);
234
+ }
235
+
236
+ for (const item of found) {
237
+ item.fullSlot = item.offset === 0 && slotCounts.get(item.slot) === 1;
238
+ }
239
+
240
+ const immRefs = artifact?.deployedBytecode?.immutableReferences || {};
241
+ const walkAst = (node) => {
242
+ if (!node || typeof node !== 'object') return;
243
+ if (Array.isArray(node)) return node.forEach(walkAst);
244
+ if (node.nodeType === 'VariableDeclaration' && node.mutability === 'immutable') {
245
+ const typeStr = node.typeDescriptions?.typeString || '';
246
+ const refs = immRefs[String(node.id)];
247
+ if (ROLE_TYPE.test(typeStr) && Array.isArray(refs) && refs.length > 0 && refs.every((r) => r.length === 32)) {
248
+ found.push({ kind: 'immutable', label: node.name, short: node.name, astId: String(node.id), refs });
249
+ }
250
+ }
251
+ for (const v of Object.values(node)) walkAst(v);
252
+ };
253
+ if (artifact?.ast) walkAst(artifact.ast);
254
+
255
+ return found;
256
+ }
257
+
258
+ function resolveFieldBinding(artifact, spaces, fieldName) {
259
+ const fields = enumerateAddressFields(artifact, spaces);
260
+ const exact = fields.filter((f) => f.label === fieldName);
261
+ if (exact.length === 1) return exact[0];
262
+ const byShort = fields.filter((f) => f.short === fieldName);
263
+ if (byShort.length === 1) return byShort[0];
264
+ if (byShort.length > 1) {
265
+ throw new Error(`Ambiguous link field "${fieldName}" matches multiple fields (${byShort.map((f) => f.label).join(', ')}); qualify the struct name.`);
266
+ }
267
+ return null;
268
+ }
269
+
270
+ function spliceImmutableAddress(hex, refs, addressHex) {
271
+ let out = hex;
272
+ const wordHex = addressHex.replace(/^0x/, '').toLowerCase().padStart(64, '0');
273
+ for (const { start, length } of refs) {
274
+ if (!Number.isInteger(start) || start < 0 || length !== 32 || (start + 32) * 2 > out.length) {
275
+ throw new Error('Invalid immutable reference range in deployedBytecode.');
276
+ }
277
+ out = out.slice(0, start * 2) + wordHex + out.slice((start + 32) * 2);
278
+ }
279
+ return out;
280
+ }
281
+
282
+ function findProjectArtifact(dir, contractName) {
283
+ if (!dir) throw new Error(`Cannot load linked contract ${contractName} without a project directory.`);
284
+ const outDir = path.join(dir, 'out');
285
+ if (!fs.existsSync(outDir)) throw new Error(`Missing Foundry out/ directory in ${dir}.`);
286
+ const matches = [];
287
+ for (const folder of fs.readdirSync(outDir).sort()) {
288
+ if (folder === 'build-info') continue;
289
+ const fullFolder = path.join(outDir, folder);
290
+ if (!fs.statSync(fullFolder).isDirectory()) continue;
291
+ const candidatePath = path.join(fullFolder, `${contractName}.json`);
292
+ if (fs.existsSync(candidatePath)) {
293
+ matches.push(JSON.parse(fs.readFileSync(candidatePath, 'utf8')));
294
+ }
295
+ }
296
+ if (matches.length === 0) throw new Error(`Linked contract artifact not found for ${contractName}.`);
297
+ if (matches.length > 1) throw new Error(`Multiple artifacts named ${contractName} found in ${outDir}.`);
298
+ return matches[0];
299
+ }
300
+
301
+ function buildMutatingCallModel(abi = []) {
302
+ const shapes = [];
303
+ let shapeLimitExceeded = false;
304
+ let dynamicBounded = false;
305
+ let needsAbiPlans = false;
306
+
307
+ for (const item of abi) {
308
+ if (item?.type !== 'function') continue;
309
+ if (['view', 'pure'].includes(item.stateMutability)) continue;
310
+ const inputs = item.inputs || [];
311
+ const sig = signature(item);
312
+ const selector = keccak256(sig).slice(2, 10);
313
+ const plans = callPlans(inputs);
314
+ if (!plans) {
315
+ shapeLimitExceeded = true;
316
+ continue;
317
+ }
318
+ if (plans.length > 1) dynamicBounded = true;
319
+ for (const plan of plans) {
320
+ const symCount = plan.words.filter((w) => w === 'sym').length;
321
+ const hasStaticOffsets = plan.words.some((w) => w !== 'sym');
322
+ const hasPartials = Object.keys(plan.partial || {}).length > 0;
323
+ if (plans.length > 1 || plan.words.length > ARG_WORDS || symCount > ARG_WORDS || hasStaticOffsets || hasPartials) {
324
+ needsAbiPlans = true;
325
+ }
326
+ shapes.push({ name: item.name, sig, selector, ...plan });
327
+ }
328
+ }
329
+
330
+ const symWords = needsAbiPlans && shapes.length
331
+ ? Math.max(ARG_WORDS, ...shapes.map((s) => s.words.filter((w) => w === 'sym').length))
332
+ : ARG_WORDS;
333
+
334
+ return {
335
+ shapes,
336
+ symWords,
337
+ needsAbiPlans,
338
+ dynamicBounded,
339
+ shapeLimitExceeded,
340
+ };
341
+ }
342
+
343
+ function collectSharedExitShapes(baseAbi = [], candAbi = []) {
344
+ const candMap = new Map();
345
+ for (const item of candAbi) {
346
+ if (item?.type !== 'function' || ['view', 'pure'].includes(item.stateMutability)) continue;
347
+ candMap.set(signature(item), item);
348
+ }
349
+ const exits = [];
350
+ let idx = 0;
351
+ for (const baseItem of baseAbi) {
352
+ if (baseItem?.type !== 'function' || ['view', 'pure'].includes(baseItem.stateMutability)) continue;
353
+ if (!USER_EXIT_RE.test(baseItem.name || '')) continue;
354
+ const sig = signature(baseItem);
355
+ if (!candMap.has(sig)) continue;
356
+ idx += 1;
357
+ const selector = keccak256(sig).slice(2, 10);
358
+ const plans = callPlans(baseItem.inputs || []);
359
+ if (!plans) {
360
+ exits.push({ index: idx, name: baseItem.name, sig, selector, supported: false, plans: [], symWords: 0, dynamicBounded: false });
361
+ continue;
362
+ }
363
+ const symWords = Math.max(0, ...plans.map((p) => p.words.filter((w) => w === 'sym').length));
364
+ exits.push({
365
+ index: idx,
366
+ name: baseItem.name,
367
+ sig,
368
+ selector,
369
+ supported: true,
370
+ plans,
371
+ symWords,
372
+ dynamicBounded: plans.length > 1,
373
+ });
374
+ }
375
+ return exits;
376
+ }
377
+
378
+ function encodePlanExpr(selector, plan, arrayVar = 'a') {
379
+ let symIdx = 0;
380
+ const parts = [`bytes4(0x${selector})`];
381
+ for (const word of plan.words) {
382
+ if (word !== 'sym') {
383
+ parts.push(`bytes32(uint256(${word}))`);
384
+ } else {
385
+ const bytes = plan.partial?.[symIdx];
386
+ const src = `${arrayVar}[${symIdx++}]`;
387
+ parts.push(bytes ? `bytes32(bytes${bytes}(${src}))` : src);
388
+ }
389
+ }
390
+ const chunks = [];
391
+ for (let i = 0; i < parts.length; i += 8) {
392
+ chunks.push(`abi.encodePacked(${parts.slice(i, i + 8).join(', ')})`);
393
+ }
394
+ return chunks.length === 1 ? chunks[0] : `bytes.concat(${chunks.join(', ')})`;
395
+ }
396
+
397
+ function computeExtraWordsLayout(storage, resolvedLinks) {
398
+ let cursor = 0;
399
+ const subjectMapLayout = storage.addressMappingEntries.map((entry) => {
400
+ const start = cursor;
401
+ cursor += entry.words * 2; // caller + peer per word
402
+ return { ...entry, start };
403
+ });
404
+ const subjectNestedLayout = storage.nestedAddressMappingSlots.map((slot) => {
405
+ const start = cursor;
406
+ cursor += 2; // (caller, peer) + (peer, caller)
407
+ return { slot, start };
408
+ });
409
+ const partnerLayouts = resolvedLinks.map((lnk, idx) => {
410
+ const plainStart = cursor;
411
+ cursor += lnk.storage.plainSlots.length;
412
+ const maps = lnk.storage.addressMappingEntries.map((entry) => {
413
+ const start = cursor;
414
+ cursor += entry.words * 3; // caller + peer + subject(OLD/NEW)
415
+ return { ...entry, start };
416
+ });
417
+ const nested = lnk.storage.nestedAddressMappingSlots.map((slot) => {
418
+ const start = cursor;
419
+ cursor += 2; // (caller, subject) + (peer, subject)
420
+ return { slot, start };
421
+ });
422
+ return { index: idx, link: lnk, plainStart, maps, nested };
423
+ });
424
+ return { totalExtraWords: cursor, subjectMapLayout, subjectNestedLayout, partnerLayouts };
425
+ }
426
+
427
+ function linkedCodeExpr(hex, links = []) {
428
+ return links.reduce((code, ref) => `_link(${code}, ${ref.start}, LIBRARIES[${ref.library}])`, `hex"${hex}"`);
429
+ }
430
+
431
+ function buildGetterRegressionHarness({
432
+ candHex,
433
+ candLinks = [],
434
+ baseHex = null,
435
+ baseLinks = [],
436
+ libraries = [],
437
+ resolvedLinks = [],
438
+ baseBound,
439
+ compiled,
440
+ storage,
441
+ callModel,
442
+ sharedExits = [],
443
+ needsEthDeal = false,
444
+ needsReverter = false,
445
+ }) {
446
+ const plainCount = storage.plainSlots.length;
447
+ const extraLayout = computeExtraWordsLayout(storage, resolvedLinks);
448
+ const extraCount = extraLayout.totalExtraWords;
449
+ const supportedExits = baseHex && baseBound ? sharedExits.filter((e) => e.supported) : [];
450
+ const useExtendedCall = callModel.needsAbiPlans && !callModel.shapeLimitExceeded && callModel.shapes.length > 0;
451
+ const symWords = Math.max(
452
+ ARG_WORDS,
453
+ useExtendedCall ? callModel.symWords : ARG_WORDS,
454
+ ...supportedExits.map((e) => e.symWords),
455
+ );
456
+ const predicates = compiled.properties.map((p, idx) => {
457
+ const maxBound = p.kind === 'bool' ? '1' : `type(${p.abiType}).max`;
458
+ const expected = p.kind === 'bool' ? (p.literal === 'true' ? '1' : '0') : p.literal;
459
+ return {
460
+ index: idx + 1,
461
+ id: p.id,
462
+ signature: p.signature,
463
+ op: p.op,
464
+ maxBound,
465
+ expected,
466
+ };
467
+ });
468
+
469
+ const extraParam = extraCount > 0 ? `, bytes32[${extraCount}] memory m` : '';
470
+ const extraArg = extraCount > 0 ? ', m' : '';
471
+
472
+ const seedBodyLines = [
473
+ ...storage.plainSlots.map((slot, i) => ` vm.store(target, bytes32(uint256(${slot.toString()})), s[${i}]);`),
474
+ ];
475
+
476
+ for (const entry of extraLayout.subjectMapLayout) {
477
+ for (let w = 0; w < entry.words; w++) {
478
+ const cIdx = entry.start + w * 2;
479
+ const pIdx = cIdx + 1;
480
+ if (entry.words === 1) {
481
+ seedBodyLines.push(` if (caller != peer && uint256(m[${cIdx}]) > type(uint256).max - uint256(m[${pIdx}])) return false;`);
482
+ }
483
+ const addW = w === 0 ? '' : ` + ${w}`;
484
+ seedBodyLines.push(
485
+ ` vm.store(target, bytes32(uint256(keccak256(abi.encode(caller, uint256(${entry.slot.toString()}))))${addW}), m[${cIdx}]);`,
486
+ ` vm.store(target, bytes32(uint256(keccak256(abi.encode(peer, uint256(${entry.slot.toString()}))))${addW}), m[${pIdx}]);`,
487
+ );
488
+ }
489
+ }
490
+
491
+ for (const nEntry of extraLayout.subjectNestedLayout) {
492
+ const c0 = nEntry.start;
493
+ const c1 = c0 + 1;
494
+ seedBodyLines.push(
495
+ ` vm.store(target, keccak256(abi.encode(peer, keccak256(abi.encode(caller, uint256(${nEntry.slot.toString()}))))), m[${c0}]);`,
496
+ ` vm.store(target, keccak256(abi.encode(caller, keccak256(abi.encode(peer, uint256(${nEntry.slot.toString()}))))), m[${c1}]);`,
497
+ );
498
+ }
499
+
500
+ for (const pLayout of extraLayout.partnerLayouts) {
501
+ const j = pLayout.index;
502
+ const lnk = pLayout.link;
503
+ const partnerExpr = baseHex ? `(isNew ? NEW_LINK_${j} : OLD_LINK_${j})` : `NEW_LINK_${j}`;
504
+ seedBodyLines.push(` { address partner = ${partnerExpr};`);
505
+ if (lnk.candField.kind === 'storage') {
506
+ if (baseHex) {
507
+ if (lnk.baseField?.kind === 'storage') {
508
+ seedBodyLines.push(' if (!isNew) {');
509
+ if (lnk.baseField.fullSlot) {
510
+ seedBodyLines.push(` vm.store(target, bytes32(uint256(${lnk.baseField.slot.toString()})), bytes32(uint256(uint160(partner))));`);
511
+ } else {
512
+ const sh = lnk.baseField.offset * 8;
513
+ seedBodyLines.push(
514
+ ` uint256 curB = uint256(vm.load(target, bytes32(uint256(${lnk.baseField.slot.toString()}))));`,
515
+ ` uint256 clrB = curB & ~(uint256(type(uint160).max) << ${sh});`,
516
+ ` vm.store(target, bytes32(uint256(${lnk.baseField.slot.toString()})), bytes32(clrB | (uint256(uint160(partner)) << ${sh})));`,
517
+ );
518
+ }
519
+ seedBodyLines.push(' }');
520
+ }
521
+ seedBodyLines.push(' if (isNew) {');
522
+ }
523
+ if (lnk.candField.fullSlot) {
524
+ seedBodyLines.push(` vm.store(target, bytes32(uint256(${lnk.candField.slot.toString()})), bytes32(uint256(uint160(partner))));`);
525
+ } else {
526
+ const sh = lnk.candField.offset * 8;
527
+ seedBodyLines.push(
528
+ ` uint256 curC = uint256(vm.load(target, bytes32(uint256(${lnk.candField.slot.toString()}))));`,
529
+ ` uint256 clrC = curC & ~(uint256(type(uint160).max) << ${sh});`,
530
+ ` vm.store(target, bytes32(uint256(${lnk.candField.slot.toString()})), bytes32(clrC | (uint256(uint160(partner)) << ${sh})));`,
531
+ );
532
+ }
533
+ if (baseHex) seedBodyLines.push(' }');
534
+ }
535
+
536
+ lnk.storage.plainSlots.forEach((ps, k) => {
537
+ seedBodyLines.push(` vm.store(partner, bytes32(uint256(${ps.toString()})), m[${pLayout.plainStart + k}]);`);
538
+ });
539
+
540
+ for (const pm of pLayout.maps) {
541
+ for (let w = 0; w < pm.words; w++) {
542
+ const cCaller = pm.start + w * 3;
543
+ const cPeer = cCaller + 1;
544
+ const cSelf = cCaller + 2;
545
+ if (pm.words === 1) {
546
+ seedBodyLines.push(
547
+ ` if (uint256(m[${cCaller}]) > type(uint256).max - uint256(m[${cSelf}])) return false;`,
548
+ ` if (caller != peer && uint256(m[${cCaller}]) + uint256(m[${cSelf}]) > type(uint256).max - uint256(m[${cPeer}])) return false;`,
549
+ );
550
+ }
551
+ const addW = w === 0 ? '' : ` + ${w}`;
552
+ seedBodyLines.push(
553
+ ` vm.store(partner, bytes32(uint256(keccak256(abi.encode(caller, uint256(${pm.slot.toString()}))))${addW}), m[${cCaller}]);`,
554
+ ` vm.store(partner, bytes32(uint256(keccak256(abi.encode(peer, uint256(${pm.slot.toString()}))))${addW}), m[${cPeer}]);`,
555
+ ` vm.store(partner, bytes32(uint256(keccak256(abi.encode(target, uint256(${pm.slot.toString()}))))${addW}), m[${cSelf}]);`,
556
+ );
557
+ }
558
+ }
559
+
560
+ for (const pn of pLayout.nested) {
561
+ const aCaller = pn.start;
562
+ const aPeer = aCaller + 1;
563
+ seedBodyLines.push(
564
+ ` vm.store(partner, keccak256(abi.encode(target, keccak256(abi.encode(caller, uint256(${pn.slot.toString()}))))), m[${aCaller}]);`,
565
+ ` vm.store(partner, keccak256(abi.encode(target, keccak256(abi.encode(peer, uint256(${pn.slot.toString()}))))), m[${aPeer}]);`,
566
+ );
567
+ }
568
+ seedBodyLines.push(' }');
569
+ }
570
+
571
+ if (extraCount === 0 && resolvedLinks.length === 0) {
572
+ seedBodyLines.unshift(' caller; peer; isNew;');
573
+ } else if (resolvedLinks.length === 0) {
574
+ seedBodyLines.unshift(' isNew;');
575
+ }
576
+
577
+ const forbiddenAddrs = [
578
+ 'OLD',
579
+ 'NEW',
580
+ 'address(this)',
581
+ 'address(vm)',
582
+ ...libraries.map((_, i) => `LIBRARIES[${i}]`),
583
+ ...resolvedLinks.flatMap((_, j) => (baseHex ? [`OLD_LINK_${j}`, `NEW_LINK_${j}`] : [`NEW_LINK_${j}`])),
584
+ ];
585
+ const validActorFn = [
586
+ ' function _validActor(address who) internal view returns (bool) {',
587
+ ' if (uint160(who) <= 0x100) return false;',
588
+ ` return ${forbiddenAddrs.map((expr) => `who != ${expr}`).join(' && ')};`,
589
+ ' }',
590
+ ].join('\n');
591
+
592
+ const holdsFns = predicates.map((p) => [
593
+ ` function _holds_${p.index}(address target) internal view returns (bool) {`,
594
+ ` (bool ok, bytes memory res) = target.staticcall(abi.encodeWithSelector(bytes4(keccak256("${p.signature}"))));`,
595
+ ' if (!ok || res.length != 32) return false;',
596
+ ' uint256 word = abi.decode(res, (uint256));',
597
+ ` if (word > ${p.maxBound}) return false;`,
598
+ ` return word ${p.op} ${p.expected};`,
599
+ ' }',
600
+ ].join('\n'));
601
+
602
+ const encodeHelperLines = useExtendedCall
603
+ ? [
604
+ ` function _encodeCall(uint256 which, bytes4 rawSel, bytes32[${symWords}] memory a) internal pure returns (bytes memory) {`,
605
+ ...callModel.shapes.map(
606
+ (shape, idx) => ` if (which == ${idx}) return ${encodePlanExpr(shape.selector, shape, 'a')};`,
607
+ ),
608
+ ' return abi.encodePacked(rawSel, a[0], a[1], a[2], a[3]);',
609
+ ' }',
610
+ ]
611
+ : [];
612
+
613
+ const holdsAllBody = predicates.map((p) => `_holds_${p.index}(target)`).join(' && ');
614
+ const ethParam = needsEthDeal ? ', uint256 ethBal' : '';
615
+ const ethDealNew = needsEthDeal ? ' vm.deal(NEW, ethBal);\n' : '';
616
+
617
+ const checks = [];
618
+ for (const p of predicates) {
619
+ if (baseHex && baseBound) {
620
+ checks.push([
621
+ ` function check_isl_preserve_${p.index}(address caller, address peer, bytes32[${plainCount}] memory s${extraParam}${ethParam}) public {`,
622
+ ...(resolvedLinks.length > 0 ? [' if (!_validActor(caller) || !_validActor(peer)) return;'] : []),
623
+ ...(needsEthDeal ? [' vm.deal(OLD, ethBal);', ' vm.deal(NEW, ethBal);'] : []),
624
+ ` if (!_seedWorld(OLD, caller, peer, s${extraArg}, false)) return;`,
625
+ ` if (!_seedWorld(NEW, caller, peer, s${extraArg}, true)) return;`,
626
+ ` if (!_holds_${p.index}(OLD)) return;`,
627
+ ` assert(_holds_${p.index}(NEW));`,
628
+ ' }',
629
+ ].join('\n'));
630
+ }
631
+
632
+ if (useExtendedCall) {
633
+ checks.push([
634
+ ` function check_isl_transition_${p.index}(address caller, uint256 which, bytes4 sel, bytes32[${symWords}] memory a, bytes32[${plainCount}] memory s${extraParam}${ethParam}) public {`,
635
+ ' address peer = address(uint160(uint256(a[0])));',
636
+ ...(resolvedLinks.length > 0 || needsEthDeal
637
+ ? [' if (!_validActor(caller) || (peer != address(0) && !_validActor(peer))) return;']
638
+ : []),
639
+ ethDealNew + ` if (!_seedWorld(NEW, caller, peer, s${extraArg}, true)) return;`,
640
+ ' if (!_holdsAll(NEW)) return;',
641
+ ' bytes memory data = _encodeCall(which, sel, a);',
642
+ ' vm.prank(caller);',
643
+ ' (bool ok,) = NEW.call(data);',
644
+ ' if (!ok) return;',
645
+ ` assert(_holds_${p.index}(NEW));`,
646
+ ' }',
647
+ ].join('\n'));
648
+ } else {
649
+ checks.push([
650
+ ` function check_isl_transition_${p.index}(address caller, bytes4 sel, bytes32[${ARG_WORDS}] memory a, bytes32[${plainCount}] memory s${extraParam}${ethParam}) public {`,
651
+ ' address peer = address(uint160(uint256(a[0])));',
652
+ ...(resolvedLinks.length > 0 || needsEthDeal
653
+ ? [' if (!_validActor(caller) || (peer != address(0) && !_validActor(peer))) return;']
654
+ : []),
655
+ ethDealNew + ` if (!_seedWorld(NEW, caller, peer, s${extraArg}, true)) return;`,
656
+ ' if (!_holdsAll(NEW)) return;',
657
+ ' bytes memory data = abi.encodePacked(sel, a[0], a[1], a[2], a[3]);',
658
+ ' vm.prank(caller);',
659
+ ' (bool ok,) = NEW.call(data);',
660
+ ' if (!ok) return;',
661
+ ` assert(_holds_${p.index}(NEW));`,
662
+ ' }',
663
+ ].join('\n'));
664
+ }
665
+ }
666
+
667
+ for (const exit of supportedExits) {
668
+ const exitSym = Math.max(1, exit.symWords);
669
+ const whichParam = exit.plans.length > 1 ? ', uint256 whichExit' : '';
670
+ const addrGuards = exit.plans
671
+ .flatMap((pl) => pl.addr || [])
672
+ .filter((pos, i, arr) => arr.indexOf(pos) === i && pos < exitSym)
673
+ .map((pos) => [
674
+ ` address addrArg_${pos} = address(uint160(uint256(a[${pos}])));`,
675
+ ` if (!_validActor(addrArg_${pos})) return;`,
676
+ ].join('\n'));
677
+ const linkedCandSlots = new Set(
678
+ resolvedLinks.filter((l) => l.candField?.kind === 'storage' && l.candField.fullSlot).map((l) => l.candField.slot.toString()),
679
+ );
680
+ const slotCollisionGuards = storage.plainSlots
681
+ .map((slot, i) => (linkedCandSlots.has(slot.toString())
682
+ ? null
683
+ : ` if (address(uint160(uint256(s[${i}]))) == OLD || address(uint160(uint256(s[${i}]))) == NEW) return;`))
684
+ .filter(Boolean);
685
+ const encodeLines = exit.plans.length === 1
686
+ ? [` bytes memory data = ${encodePlanExpr(exit.selector, exit.plans[0], 'a')};`]
687
+ : [
688
+ ` if (whichExit >= ${exit.plans.length}) return;`,
689
+ ' bytes memory data;',
690
+ ...exit.plans.map(
691
+ (pl, idx) => ` if (whichExit == ${idx}) data = ${encodePlanExpr(exit.selector, pl, 'a')};`,
692
+ ),
693
+ ];
694
+
695
+ checks.push([
696
+ ` function check_isl_liveness_${exit.index}(address caller, uint256 ethBal, bytes32[${exitSym}] memory a, bytes32[${plainCount}] memory s${extraParam}${whichParam}) public {`,
697
+ ' if (!_validActor(caller)) return;',
698
+ ...addrGuards,
699
+ ...slotCollisionGuards,
700
+ ' address peer = address(uint160(uint256(a[0])));',
701
+ ' if (peer != address(0) && (peer == OLD || peer == NEW)) return;',
702
+ ...(resolvedLinks.length > 0 ? [' if (peer != address(0) && !_validActor(peer)) return;'] : []),
703
+ ' vm.deal(OLD, ethBal);',
704
+ ' vm.deal(NEW, ethBal);',
705
+ ` if (!_seedWorld(OLD, caller, peer, s${extraArg}, false)) return;`,
706
+ ` if (!_seedWorld(NEW, caller, peer, s${extraArg}, true)) return;`,
707
+ ' if (!_holdsAll(OLD) || !_holdsAll(NEW)) return;',
708
+ ...encodeLines,
709
+ ' vm.prank(caller);',
710
+ ' (bool okOld,) = OLD.call(data);',
711
+ ' if (!okOld) return;',
712
+ ' vm.prank(caller);',
713
+ ' (bool okNew,) = NEW.call(data);',
714
+ ' assert(okNew);',
715
+ ' }',
716
+ ].join('\n'));
717
+ }
718
+
719
+ const linkConstDecls = resolvedLinks.flatMap((lnk, j) => [
720
+ ...(baseHex ? [` address internal constant OLD_LINK_${j} = address(uint160(${lnk.oldAddrHex}));`] : []),
721
+ ` address internal constant NEW_LINK_${j} = address(uint160(${lnk.newAddrHex}));`,
722
+ ]);
723
+
724
+ const setUpLines = [
725
+ ...libraries.map((lib, i) => ` LIBRARIES[${i}] = _deploy(${linkedCodeExpr(lib.creation.hex, lib.creation.links)});`),
726
+ ...(needsReverter ? [' vm.etch(REVERTER, hex"fd");'] : []),
727
+ ...resolvedLinks.flatMap((lnk, j) => [
728
+ ...(baseHex ? [` vm.etch(OLD_LINK_${j}, ${linkedCodeExpr(lnk.runtime.hex, lnk.runtime.links)});`] : []),
729
+ ` vm.etch(NEW_LINK_${j}, ${linkedCodeExpr(lnk.runtime.hex, lnk.runtime.links)});`,
730
+ ]),
731
+ ...(baseHex ? [` vm.etch(OLD, ${linkedCodeExpr(baseHex, baseLinks)});`] : []),
732
+ ` vm.etch(NEW, ${linkedCodeExpr(candHex, candLinks)});`,
733
+ ];
734
+
735
+ const libHelpers = libraries.length > 0
736
+ ? [
737
+ ' function _deploy(bytes memory code) internal returns (address a) {',
738
+ ' assembly { a := create(0, add(code, 0x20), mload(code)) }',
739
+ ' require(a != address(0), "library deploy failed");',
740
+ ' }',
741
+ '',
742
+ ' function _link(bytes memory code, uint256 offset, address libraryAddress) internal pure returns (bytes memory) {',
743
+ ' bytes20 value = bytes20(libraryAddress);',
744
+ ' for (uint256 i = 0; i < 20; i++) code[offset + i] = value[i];',
745
+ ' return code;',
746
+ ' }',
747
+ '',
748
+ ]
749
+ : [];
750
+
751
+ return [
752
+ '// SPDX-License-Identifier: MIT',
753
+ 'pragma solidity ^0.8.20;',
754
+ '',
755
+ 'interface Vm {',
756
+ ' function store(address target, bytes32 slot, bytes32 value) external;',
757
+ ' function load(address target, bytes32 slot) external view returns (bytes32);',
758
+ ' function prank(address sender) external;',
759
+ ' function etch(address target, bytes calldata code) external;',
760
+ ' function deal(address who, uint256 newBalance) external;',
761
+ '}',
762
+ '',
763
+ 'contract IntentFirewallHarness {',
764
+ ' Vm internal constant vm = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D);',
765
+ ' address internal constant OLD = address(uint160(0xA11CE));',
766
+ ' address internal constant NEW = address(uint160(0xB0B));',
767
+ ...(needsReverter ? [' address internal constant REVERTER = address(uint160(0xBEEF));'] : []),
768
+ ...linkConstDecls,
769
+ ...(libraries.length > 0 ? [` address[${libraries.length}] internal LIBRARIES;`] : []),
770
+ '',
771
+ ' function setUp() public {',
772
+ ...setUpLines,
773
+ ' }',
774
+ '',
775
+ ...libHelpers,
776
+ validActorFn,
777
+ '',
778
+ ` function _seedWorld(address target, address caller, address peer, bytes32[${plainCount}] memory s${extraParam}, bool isNew) internal returns (bool) {`,
779
+ ...seedBodyLines,
780
+ ' return true;',
781
+ ' }',
782
+ '',
783
+ ...holdsFns,
784
+ '',
785
+ ' function _holdsAll(address target) internal view returns (bool) {',
786
+ ` return ${holdsAllBody};`,
787
+ ' }',
788
+ ...(encodeHelperLines.length ? ['', ...encodeHelperLines] : []),
789
+ '',
790
+ ...checks,
791
+ '}',
792
+ '',
793
+ ].join('\n');
794
+ }
795
+
796
+ function summarizeCounterexample(ce) {
797
+ if (!ce || typeof ce !== 'object') return null;
798
+ const entries = Object.entries(ce)
799
+ .filter(([k]) => !/(^|_)(s|m)\[|mCaller|mPeer/.test(k))
800
+ .slice(0, 6)
801
+ .map(([k, v]) => `${k.replace(/^p_/, '').replace(/_address|_uint\d+|_bytes\d+|_bool/g, '')}=${v}`);
802
+ return entries.length ? entries.join(', ') : JSON.stringify(ce);
803
+ }
804
+
805
+ function checkUnitClosure(runtime, quietLibraries, linkBindings, partnerAddrBigInts) {
806
+ const storageMap = new Map();
807
+ for (const b of linkBindings) {
808
+ if (b.field.kind === 'storage') {
809
+ storageMap.set(
810
+ b.field.slot,
811
+ b.field.fullSlot ? b.addrBigInt : { offset: b.field.offset, value: b.addrBigInt },
812
+ );
813
+ }
814
+ }
815
+ const reach = analyze('0x' + runtime.hex, runtime.links, {
816
+ features: true,
817
+ quietLibraries,
818
+ storage: storageMap,
819
+ silentCallees: partnerAddrBigInts,
820
+ });
821
+ if (!reach.complete) {
822
+ return { closed: false, reason: `incomplete reachability (${reach.reason})` };
823
+ }
824
+ const forbidden = reach.features.filter((op) => ['CALLCODE', 'CREATE', 'CREATE2', 'SELFDESTRUCT'].includes(op));
825
+ if (forbidden.length > 0) {
826
+ return { closed: false, reason: `reaches ${forbidden.join(', ')}` };
827
+ }
828
+ if (reach.delegatecalls.some((d) => !d.library)) {
829
+ return { closed: false, reason: 'reaches unlinked DELEGATECALL' };
830
+ }
831
+ const hexAllowed = new Set([...partnerAddrBigInts].map((n) => n.toString(16)));
832
+ for (const site of reach.callTargets || []) {
833
+ if (!site.targets || site.targets.some((t) => !hexAllowed.has(t))) {
834
+ return { closed: false, reason: `unlinked CALL target at pc ${site.pc}` };
835
+ }
836
+ }
837
+ for (const site of reach.staticCallTargets || []) {
838
+ const ok = site.targets && site.targets.every((t) => {
839
+ if (t.startsWith('lib:')) return quietLibraries.has(Number(t.slice(4)));
840
+ return hexAllowed.has(t);
841
+ });
842
+ if (!ok) {
843
+ return { closed: false, reason: `unlinked STATICCALL target at pc ${site.pc}` };
844
+ }
845
+ }
846
+ return { closed: true, reach };
847
+ }
848
+
849
+ /**
850
+ * Evaluate one or more ISL specifications against a Candidate (and optional Baseline)
851
+ * build artifact in a Foundry project, with optional multi-contract `links`
852
+ * (`[{ field, contract, artifact? }]`), external library resolution, and ERC-7201
853
+ * namespaced + struct/2D mapping storage models.
854
+ */
855
+ async function verifyIntentFirewall({
856
+ dir,
857
+ candidate,
858
+ baseline = null,
859
+ candidateArtifact,
860
+ baseArtifact = null,
861
+ islSpecs = [],
862
+ links = [],
863
+ }) {
864
+ if (!Array.isArray(islSpecs) || islSpecs.length === 0) {
865
+ throw new Error('Intent Firewall requires at least one ISL specification.');
866
+ }
867
+
868
+ const rawPartners = (links || []).map((lnk, idx) => {
869
+ if (!lnk?.field || !lnk?.contract) {
870
+ throw new Error('Each link requires { field, contract }.');
871
+ }
872
+ const art = lnk.artifact || findProjectArtifact(dir, lnk.contract);
873
+ return {
874
+ index: idx,
875
+ field: String(lnk.field),
876
+ contract: String(lnk.contract),
877
+ artifact: art,
878
+ oldAddrBigInt: 0x10000n + BigInt(idx * 2 + 1),
879
+ newAddrBigInt: 0x10000n + BigInt(idx * 2 + 2),
880
+ oldAddrHex: '0x' + (0x10000 + idx * 2 + 1).toString(16),
881
+ newAddrHex: '0x' + (0x10000 + idx * 2 + 2).toString(16),
882
+ };
883
+ });
884
+
885
+ const needsResolution = Boolean(
886
+ dir && (
887
+ hasLibraryDependencies(candidateArtifact) ||
888
+ (baseArtifact && hasLibraryDependencies(baseArtifact)) ||
889
+ rawPartners.some((p) => hasLibraryDependencies(p.artifact))
890
+ ),
891
+ );
892
+
893
+ let candRuntime;
894
+ let baseRuntime = null;
895
+ let libraries = [];
896
+ let quietLibraries = new Set();
897
+
898
+ if (needsResolution) {
899
+ const artifactList = [
900
+ ...(baseArtifact ? [baseArtifact] : []),
901
+ candidateArtifact,
902
+ ...rawPartners.map((p) => p.artifact),
903
+ ];
904
+ const resolved = resolveBytecode(dir, artifactList);
905
+ if (resolved.errors.length > 0 || resolved.implementations.some((u) => !u)) {
906
+ throw new Error(`Candidate ${candidate} library resolution failed: ${resolved.errors.join('; ')}`);
907
+ }
908
+ let cursor = 0;
909
+ if (baseArtifact) baseRuntime = resolved.implementations[cursor++].runtime;
910
+ candRuntime = resolved.implementations[cursor++].runtime;
911
+ rawPartners.forEach((p) => {
912
+ p.runtime = resolved.implementations[cursor++].runtime;
913
+ });
914
+ libraries = resolved.libraries;
915
+ const libAnalyses = libraries.map((lib) => analyze(lib.runtime.hex, lib.runtime.links, { features: true }));
916
+ quietLibraries = quietLibraryIndices(libAnalyses);
917
+ } else {
918
+ const rawCandHex = candidateArtifact?.deployedBytecode?.object?.replace(/^0x/, '');
919
+ if (!rawCandHex || !/^[0-9a-f]+$/i.test(rawCandHex)) {
920
+ throw new Error(`Candidate ${candidate} has no linked runtime bytecode.`);
921
+ }
922
+ candRuntime = { hex: rawCandHex.toLowerCase(), links: [] };
923
+ if (baseArtifact) {
924
+ const rawBaseHex = baseArtifact?.deployedBytecode?.object?.replace(/^0x/, '');
925
+ if (rawBaseHex && /^[0-9a-f]+$/i.test(rawBaseHex)) {
926
+ baseRuntime = { hex: rawBaseHex.toLowerCase(), links: [] };
927
+ }
928
+ }
929
+ for (const p of rawPartners) {
930
+ const pHex = p.artifact?.deployedBytecode?.object?.replace(/^0x/, '');
931
+ if (!pHex || !/^[0-9a-f]+$/i.test(pHex)) {
932
+ throw new Error(`Linked contract ${p.contract} has no linked runtime bytecode.`);
933
+ }
934
+ p.runtime = { hex: pHex.toLowerCase(), links: [] };
935
+ }
936
+ }
937
+
938
+ let allNamespaces = [];
939
+ if (dir && fs.existsSync(path.join(dir, 'out'))) {
940
+ try {
941
+ allNamespaces = await namespaces(dir, cast);
942
+ } catch {
943
+ allNamespaces = [];
944
+ }
945
+ }
946
+ const spacesFor = (hex) => allNamespaces.filter((ns) => hex.includes(hex32(ns.base).slice(2)));
947
+ const candSpaces = spacesFor(candRuntime.hex);
948
+ const baseSpaces = baseRuntime ? spacesFor(baseRuntime.hex) : [];
949
+
950
+ const boundImmutableIds = new Set();
951
+ let candHex = candRuntime.hex;
952
+ let baseHex = baseRuntime ? baseRuntime.hex : null;
953
+
954
+ const resolvedLinks = [];
955
+ let linkClosureError = null;
956
+
957
+ for (const p of rawPartners) {
958
+ const candField = resolveFieldBinding(candidateArtifact, candSpaces, p.field);
959
+ if (!candField) {
960
+ throw new Error(`Candidate ${candidate} has no address/contract field matching link "${p.field}".`);
961
+ }
962
+ const baseField = baseArtifact ? resolveFieldBinding(baseArtifact, baseSpaces, p.field) : null;
963
+ if (candField.kind === 'immutable') {
964
+ candHex = spliceImmutableAddress(candHex, candField.refs, p.newAddrHex);
965
+ boundImmutableIds.add(candField.astId);
966
+ }
967
+ if (baseHex && baseField?.kind === 'immutable') {
968
+ baseHex = spliceImmutableAddress(baseHex, baseField.refs, p.oldAddrHex);
969
+ }
970
+
971
+ const partnerReach = analyze('0x' + p.runtime.hex, p.runtime.links, { features: true, quietLibraries });
972
+ const partnerForeign = partnerReach.features.filter((op) =>
973
+ FOREIGN_OPS.includes(op) && !(op === 'DELEGATECALL' && partnerReach.delegatecalls.every((d) => d.library)),
974
+ );
975
+ const partnerUsedLibs = new Set(p.runtime.links.map((l) => l.library));
976
+ const partnerLoudLib = [...partnerUsedLibs].some((idx) => !quietLibraries.has(idx));
977
+ if (!partnerReach.complete || partnerForeign.length > 0 || partnerLoudLib) {
978
+ linkClosureError = `Linked contract ${p.contract} is not provably silent (${!partnerReach.complete ? partnerReach.reason : partnerForeign.join(', ') || 'non-quiet library'}).`;
979
+ }
980
+
981
+ const pSpaces = spacesFor(p.runtime.hex);
982
+ resolvedLinks.push({
983
+ ...p,
984
+ candField,
985
+ baseField,
986
+ storage: collectStorageModel(p.artifact, pSpaces),
987
+ });
988
+ }
989
+
990
+ const storage = collectStorageModel(candidateArtifact, candSpaces);
991
+ const callModel = buildMutatingCallModel(candidateArtifact.abi);
992
+ const sharedExits = baseArtifact ? collectSharedExitShapes(baseArtifact.abi, candidateArtifact.abi) : [];
993
+ const immRefIds = Object.keys(candidateArtifact?.deployedBytecode?.immutableReferences || {});
994
+ const hasUnboundImmutables = immRefIds.some((id) => !boundImmutableIds.has(id));
995
+
996
+ const reachability = analyze('0x' + candHex, candRuntime.links, { features: true, quietLibraries });
997
+ const features = new Set(reachability.features || []);
998
+ const usedLibIndices = new Set(candRuntime.links.map((l) => l.library));
999
+ const allLibsQuiet = [...usedLibIndices].every((idx) => quietLibraries.has(idx));
1000
+ const hasUnquietDelegatecall = features.has('DELEGATECALL') && (
1001
+ !reachability.complete ||
1002
+ !allLibsQuiet ||
1003
+ reachability.delegatecalls.some((d) => !d.library)
1004
+ );
1005
+ const hasHardForeignOp = ['CALLCODE', 'CREATE', 'CREATE2', 'SELFDESTRUCT'].some((op) => features.has(op));
1006
+
1007
+ let linksDischargeCalls = false;
1008
+ let baseLinksDischargeCalls = true;
1009
+ if (resolvedLinks.length > 0 && !linkClosureError) {
1010
+ const newPartnerSet = new Set(resolvedLinks.map((l) => l.newAddrBigInt));
1011
+ const candClosure = checkUnitClosure(
1012
+ { hex: candHex, links: candRuntime.links },
1013
+ quietLibraries,
1014
+ resolvedLinks.map((l) => ({ field: l.candField, addrBigInt: l.newAddrBigInt })),
1015
+ newPartnerSet,
1016
+ );
1017
+ linksDischargeCalls = candClosure.closed;
1018
+ if (!candClosure.closed) linkClosureError = `Candidate call graph not closed by links: ${candClosure.reason}.`;
1019
+
1020
+ if (baseHex && linksDischargeCalls) {
1021
+ const oldPartnerSet = new Set(resolvedLinks.filter((l) => l.baseField).map((l) => l.oldAddrBigInt));
1022
+ const baseClosure = checkUnitClosure(
1023
+ { hex: baseHex, links: baseRuntime.links },
1024
+ quietLibraries,
1025
+ resolvedLinks.filter((l) => l.baseField).map((l) => ({ field: l.baseField, addrBigInt: l.oldAddrBigInt })),
1026
+ oldPartnerSet,
1027
+ );
1028
+ baseLinksDischargeCalls = baseClosure.closed;
1029
+ }
1030
+ }
1031
+
1032
+ // Single-contract instruction-level CEI: complete reachability, no hard foreign
1033
+ // opcodes or unquiet DELEGATECALL, no STATICCALL, and zero state accesses after CALL.
1034
+ const ceiOrderedCall = !linksDischargeCalls &&
1035
+ resolvedLinks.length === 0 &&
1036
+ reachability.complete &&
1037
+ !hasHardForeignOp &&
1038
+ !hasUnquietDelegatecall &&
1039
+ !features.has('STATICCALL') &&
1040
+ features.has('CALL') &&
1041
+ Array.isArray(reachability.lateState) &&
1042
+ reachability.lateState.length === 0;
1043
+
1044
+ const hasMutableExternalCall = linksDischargeCalls
1045
+ ? false
1046
+ : ceiOrderedCall
1047
+ ? false
1048
+ : (['CALL', 'CALLCODE', 'CREATE', 'CREATE2'].some((op) => features.has(op)) || hasUnquietDelegatecall || !reachability.complete);
1049
+
1050
+ const hasPreserveExternalCall = linksDischargeCalls && baseLinksDischargeCalls
1051
+ ? false
1052
+ : hasMutableExternalCall;
1053
+
1054
+ const hasStaticExternalCall = !linksDischargeCalls && features.has('STATICCALL');
1055
+ let exitLivenessEvaluated = false;
1056
+
1057
+ const claims = [];
1058
+ const declaredInvariants = [];
1059
+ const islDigests = [];
1060
+
1061
+ for (const specItem of islSpecs) {
1062
+ const label = specItem.name || 'policy.isl';
1063
+ const source = specItem.source;
1064
+ const sha256 = createHash('sha256').update(source, 'utf8').digest('hex');
1065
+ islDigests.push(sha256);
1066
+
1067
+ let profile;
1068
+ try {
1069
+ profile = detectISLProfile(source);
1070
+ } catch (error) {
1071
+ claims.push({
1072
+ id: `isl.${label}.syntax`,
1073
+ category: 'intent-firewall',
1074
+ source: 'guardefi-isl-compiler',
1075
+ epistemicClass: 'PROVEN',
1076
+ outcome: 'violated',
1077
+ mandatory: true,
1078
+ detail: error.message,
1079
+ });
1080
+ continue;
1081
+ }
1082
+
1083
+ if (profile === 'getter') {
1084
+ let compiled;
1085
+ try {
1086
+ compiled = compileISL(source, candidateArtifact.abi);
1087
+ } catch (error) {
1088
+ claims.push({
1089
+ id: `isl.${label}.binding`,
1090
+ category: 'intent-firewall',
1091
+ source: 'guardefi-isl-compiler',
1092
+ epistemicClass: 'PROVEN',
1093
+ outcome: 'violated',
1094
+ mandatory: true,
1095
+ detail: `Candidate ${candidate} breaks ISL getter binding: ${error.message}`,
1096
+ });
1097
+ continue;
1098
+ }
1099
+
1100
+ let baseBound = false;
1101
+ if (baseArtifact) {
1102
+ try {
1103
+ compileISL(source, baseArtifact.abi);
1104
+ baseBound = true;
1105
+ } catch {
1106
+ baseBound = false;
1107
+ }
1108
+ }
1109
+
1110
+ for (const p of compiled.properties) declaredInvariants.push(p.id);
1111
+
1112
+ if (!storage.supported) {
1113
+ for (const p of compiled.properties) {
1114
+ claims.push({
1115
+ id: `isl.${p.id}`,
1116
+ category: 'intent-firewall',
1117
+ source: 'guardefi-isl-firewall',
1118
+ epistemicClass: 'UNKNOWN',
1119
+ outcome: 'unresolved',
1120
+ mandatory: true,
1121
+ detail: `Contract exceeds ${MAX_SLOTS} plain storage slots; symbolic ISL regression skipped.`,
1122
+ });
1123
+ }
1124
+ continue;
1125
+ }
1126
+
1127
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'guardefi-isl-fw-'));
1128
+ try {
1129
+ const runExitLiveness = Boolean(baseHex && baseBound && sharedExits.length > 0 && !exitLivenessEvaluated);
1130
+ if (runExitLiveness) exitLivenessEvaluated = true;
1131
+ fs.writeFileSync(path.join(tmp, 'foundry.toml'), '[profile.default]\nsrc = "src"\ntest = "test"\nout = "out"\nvia_ir = false\n');
1132
+ fs.mkdirSync(path.join(tmp, 'test'), { recursive: true });
1133
+ const harness = buildGetterRegressionHarness({
1134
+ candHex,
1135
+ candLinks: candRuntime.links,
1136
+ baseHex,
1137
+ baseLinks: baseRuntime?.links || [],
1138
+ libraries,
1139
+ resolvedLinks,
1140
+ baseBound,
1141
+ compiled,
1142
+ storage,
1143
+ callModel,
1144
+ sharedExits: runExitLiveness ? sharedExits : [],
1145
+ needsEthDeal: Boolean(ceiOrderedCall || features.has('CALLVALUE') || features.has('SELFBALANCE') || features.has('CALL')),
1146
+ needsReverter: ceiOrderedCall,
1147
+ });
1148
+ fs.writeFileSync(path.join(tmp, 'test', 'IntentFirewallHarness.t.sol'), harness);
1149
+
1150
+ const halmosRes = await runHalmos(tmp, 'IntentFirewallHarness', [
1151
+ '--solver', 'bitwuzla',
1152
+ '--solver-timeout-assertion', '15s',
1153
+ '--loop', '2',
1154
+ ]);
1155
+ const canUpgradeTimeout = !hasMutableExternalCall && !hasUnboundImmutables;
1156
+ if (canUpgradeTimeout) {
1157
+ for (const altSolver of ['bitwuzla-abs', 'yices', 'z3']) {
1158
+ const timedOut = Object.keys(halmosRes).filter((k) => checkerStatus(halmosRes[k]) === 'timeout');
1159
+ if (timedOut.length === 0) break;
1160
+ const pattern = `^(${timedOut.join('|')})\\(`;
1161
+ const fallbackRes = await runHalmos(tmp, 'IntentFirewallHarness', [
1162
+ '--function', pattern,
1163
+ '--solver', altSolver,
1164
+ '--solver-timeout-assertion', '15s',
1165
+ '--loop', '2',
1166
+ ]);
1167
+ for (const checkName of timedOut) {
1168
+ const fb = fallbackRes[checkName];
1169
+ if (fb && checkerStatus(fb) !== 'timeout' && checkerStatus(fb) !== 'error') {
1170
+ halmosRes[checkName] = fb;
1171
+ }
1172
+ }
1173
+ }
1174
+ }
1175
+
1176
+ const linkBoundTag = linksDischargeCalls
1177
+ ? `linked-contracts:${resolvedLinks.map((l) => `${l.field}->${l.contract}`).join(',')}`
1178
+ : null;
1179
+ const partnerHasUnmodeledDynamic = resolvedLinks.some((l) => l.storage.hasUnmodeledDynamic || !l.storage.supported);
1180
+
1181
+ const commonModelBounds = [
1182
+ ...(storage.addressMappingEntries.length > 0 ? ['address-mappings:2-keys'] : []),
1183
+ ...(storage.nestedAddressMappingSlots.length > 0 ? ['nested-address-mappings:2-pairs'] : []),
1184
+ ...(storage.hasUnmodeledDynamic ? ['unmodeled-dynamic-storage'] : []),
1185
+ ...(hasUnboundImmutables ? ['template-immutables-zeroed'] : []),
1186
+ ...(hasStaticExternalCall ? ['unmodeled-staticcall-return'] : []),
1187
+ ...(libraries.length > 0 ? [`linked-libraries:${libraries.length}`] : []),
1188
+ ...(linkBoundTag ? [linkBoundTag] : []),
1189
+ ...(partnerHasUnmodeledDynamic ? ['partner-unmodeled-dynamic-storage'] : []),
1190
+ ...(ceiOrderedCall ? ['cei-ordered-external-call'] : []),
1191
+ ];
1192
+
1193
+ const bounds = [
1194
+ ...(callModel.dynamicBounded ? ['calldata:bounded-dynamic-lengths'] : []),
1195
+ ...commonModelBounds,
1196
+ ];
1197
+
1198
+ compiled.properties.forEach((p, idx) => {
1199
+ const k = idx + 1;
1200
+ if (baseHex && baseBound) {
1201
+ const pres = halmosRes[`check_isl_preserve_${k}`];
1202
+ const st = checkerStatus(pres);
1203
+ const presBounds = [
1204
+ ...(pres?.boundedLoops > 0 ? [`loops:${pres.boundedLoops}`] : []),
1205
+ ...commonModelBounds,
1206
+ ];
1207
+ claims.push({
1208
+ id: `isl.preserve.${p.id}`,
1209
+ category: 'intent-firewall',
1210
+ source: 'guardefi-isl-firewall',
1211
+ epistemicClass: st === 'violated' ? 'PROVEN' : hasPreserveExternalCall ? 'UNKNOWN' : st === 'proven' ? (presBounds.length ? 'BOUNDED' : 'PROVEN') : 'UNKNOWN',
1212
+ outcome: st === 'violated' ? 'violated' : hasPreserveExternalCall ? 'unresolved' : (st === 'proven' || st === 'bounded') ? 'satisfied' : 'unresolved',
1213
+ mandatory: true,
1214
+ detail: st === 'violated'
1215
+ ? `Candidate violates ISL state preservation on ${p.id} (${summarizeCounterexample(pres?.counterexample) || 'counterexample'}).`
1216
+ : hasPreserveExternalCall
1217
+ ? (linkClosureError || `External or incomplete bytecode reachability leaves ${p.id} preservation unresolved.`)
1218
+ : `Same-storage ISL getter invariant ${p.id} preserved from ${baseline} to ${candidate}.`,
1219
+ bounds: presBounds,
1220
+ counterexample: st === 'violated' ? summarizeCounterexample(pres?.counterexample) : null,
1221
+ });
1222
+ }
1223
+
1224
+ const trans = halmosRes[`check_isl_transition_${k}`];
1225
+ const st = checkerStatus(trans);
1226
+ const transBounds = [
1227
+ ...bounds,
1228
+ ...(callModel.shapeLimitExceeded ? ['calldata:shape-limit'] : []),
1229
+ ...(trans?.boundedLoops > 0 ? [`loops:${trans.boundedLoops}`] : []),
1230
+ ];
1231
+ const unmodeledTransition = hasMutableExternalCall || hasUnboundImmutables || callModel.shapeLimitExceeded;
1232
+ claims.push({
1233
+ id: `isl.transition.${p.id}`,
1234
+ category: 'intent-firewall',
1235
+ source: 'guardefi-isl-firewall',
1236
+ epistemicClass: st === 'violated' ? 'PROVEN' : unmodeledTransition ? 'UNKNOWN' : st === 'proven' ? (transBounds.length ? 'BOUNDED' : 'PROVEN') : st === 'bounded' ? 'BOUNDED' : 'UNKNOWN',
1237
+ outcome: st === 'violated' ? 'violated' : unmodeledTransition ? 'unresolved' : (st === 'proven' || st === 'bounded') ? 'satisfied' : 'unresolved',
1238
+ mandatory: true,
1239
+ detail: st === 'violated'
1240
+ ? `Candidate state transition violates ISL invariant ${p.id} (${summarizeCounterexample(trans?.counterexample) || 'counterexample'}).`
1241
+ : callModel.shapeLimitExceeded
1242
+ ? `Mutating function exceeds canonical ABI symbolic shape limits; ${p.id} transition remains unresolved.`
1243
+ : (hasMutableExternalCall || hasUnboundImmutables)
1244
+ ? (linkClosureError || `External calls or unbound immutables leave ${p.id} inductive transition unresolved.`)
1245
+ : `ISL invariant ${p.id} preserved across state transitions.`,
1246
+ bounds: transBounds,
1247
+ counterexample: st === 'violated' ? summarizeCounterexample(trans?.counterexample) : null,
1248
+ });
1249
+ });
1250
+
1251
+ if (runExitLiveness) {
1252
+ for (const exit of sharedExits) {
1253
+ if (!exit.supported) {
1254
+ claims.push({
1255
+ id: `isl.liveness.${exit.sig}`,
1256
+ category: 'intent-firewall',
1257
+ source: 'guardefi-isl-firewall',
1258
+ epistemicClass: 'UNKNOWN',
1259
+ outcome: 'unresolved',
1260
+ mandatory: true,
1261
+ detail: `Exit function ${exit.sig} exceeds canonical ABI symbolic shape limits; liveness preservation unresolved.`,
1262
+ bounds: ['calldata:shape-limit'],
1263
+ counterexample: null,
1264
+ });
1265
+ continue;
1266
+ }
1267
+ const liveRes = halmosRes[`check_isl_liveness_${exit.index}`];
1268
+ const st = checkerStatus(liveRes);
1269
+ const liveBounds = [
1270
+ ...(exit.dynamicBounded ? ['calldata:bounded-dynamic-lengths'] : []),
1271
+ ...commonModelBounds,
1272
+ ...(liveRes?.boundedLoops > 0 ? [`loops:${liveRes.boundedLoops}`] : []),
1273
+ ];
1274
+ const unmodeledExit = hasPreserveExternalCall || hasUnboundImmutables;
1275
+ claims.push({
1276
+ id: `isl.liveness.${exit.sig}`,
1277
+ category: 'intent-firewall',
1278
+ source: 'guardefi-isl-firewall',
1279
+ epistemicClass: st === 'violated' ? 'PROVEN' : unmodeledExit ? 'UNKNOWN' : st === 'proven' ? (liveBounds.length ? 'BOUNDED' : 'PROVEN') : st === 'bounded' ? 'BOUNDED' : 'UNKNOWN',
1280
+ outcome: st === 'violated' ? 'violated' : unmodeledExit ? 'unresolved' : (st === 'proven' || st === 'bounded') ? 'satisfied' : 'unresolved',
1281
+ mandatory: true,
1282
+ detail: st === 'violated'
1283
+ ? `Candidate introduces a revert on user exit ${exit.sig} where ${baseline} succeeded (${summarizeCounterexample(liveRes?.counterexample) || 'counterexample'}).`
1284
+ : unmodeledExit
1285
+ ? (linkClosureError || `External calls or unbound immutables leave ${exit.sig} exit-liveness preservation unresolved.`)
1286
+ : `User exit ${exit.sig} preserves baseline execution liveness across valid states.`,
1287
+ bounds: liveBounds,
1288
+ counterexample: st === 'violated' ? summarizeCounterexample(liveRes?.counterexample) : null,
1289
+ });
1290
+ }
1291
+ }
1292
+ } finally {
1293
+ fs.rmSync(tmp, { recursive: true, force: true });
1294
+ }
1295
+ } else {
1296
+ // Transaction Behavior Profile (engine 2.3): sound storage-frame verification (core/isl/behavior-verify).
1297
+ // A successful call must satisfy pre and post AND leave every other declared storage field unchanged.
1298
+ // Without a project adapter (<policy>.adapter.sol) only arbitrary-state checks run: a pass is BOUNDED.
1299
+ let report;
1300
+ try {
1301
+ report = await verifyBehaviors({ policySource: source, project: dir, contract: candidate, adapterSource: specItem.adapter ?? null });
1302
+ } catch (error) {
1303
+ claims.push({
1304
+ id: `isl.${label}.behavior-binding`,
1305
+ category: 'intent-firewall',
1306
+ source: 'guardefi-isl-compiler',
1307
+ epistemicClass: 'PROVEN',
1308
+ outcome: 'violated',
1309
+ mandatory: true,
1310
+ detail: `Candidate ${candidate} breaks ISL behavior binding: ${error.message}`,
1311
+ });
1312
+ continue;
1313
+ }
1314
+ if (!report.behaviors.length) {
1315
+ claims.push({ id: `isl.${label}.behavior-verification`, category: 'intent-firewall', source: 'guardefi-isl-behavior',
1316
+ epistemicClass: 'UNKNOWN', outcome: 'unresolved', mandatory: true,
1317
+ detail: `Behavior verification produced no result: ${report.notes.join(' ') || 'no behaviors checked'}`, bounds: report.limits });
1318
+ continue;
1319
+ }
1320
+ for (const b of report.behaviors) {
1321
+ declaredInvariants.push(b.id);
1322
+ const violated = b.status === 'VIOLATED';
1323
+ const satisfied = b.status === 'PROVEN' || b.status === 'PROVEN_UNDER_ASSUMPTIONS';
1324
+ const exact = b.status === 'PROVEN' && report.mode === 'full';
1325
+ const failed = b.checks.filter((c) => c.status === 'violated');
1326
+ claims.push({
1327
+ id: `isl.behavior.${b.id}`,
1328
+ category: 'intent-firewall',
1329
+ source: 'guardefi-isl-behavior',
1330
+ epistemicClass: violated ? 'PROVEN' : satisfied ? (exact ? 'PROVEN' : 'BOUNDED') : 'UNKNOWN',
1331
+ outcome: violated ? 'violated' : satisfied ? 'satisfied' : 'unresolved',
1332
+ mandatory: true,
1333
+ detail: violated
1334
+ ? `Candidate violates ISL behavior ${b.id}: ${failed.map((c) => `${c.kind} ${c.name}`).join(', ')} (start state ${b.startState}${b.startState === 'any' ? ', which may be unreachable' : ''}).`
1335
+ : satisfied
1336
+ ? `Candidate satisfies ISL behavior ${b.id}, including the storage frame${b.assumptions.length ? `, under ${b.assumptions.length} unproven assumption(s)` : ''}${report.mode === 'any-state' ? '; deployed-state availability not checked (no adapter)' : ''}.`
1337
+ : `ISL behavior ${b.id} is ${b.status}: ${[...b.reasons, ...report.notes].join(' ') || 'not every check was proven'}.`,
1338
+ bounds: [...(report.mode === 'any-state' ? ['no-adapter:any-state-only'] : []), ...b.assumptions.map((a) => `assumption:${a}`)],
1339
+ counterexample: violated ? summarizeCounterexample(failed[0]?.counterexample) : null,
1340
+ verification: { status: b.status, mode: report.mode, maps: b.status ? b.maps : {}, digests: report.digests },
1341
+ });
1342
+ }
1343
+ }
1344
+ }
1345
+
1346
+ const combinedIslDigest = createHash('sha256').update(islDigests.join(':'), 'utf8').digest('hex');
1347
+ const rawCandDigestHex = candidateArtifact?.deployedBytecode?.object?.replace(/^0x/, '') || candRuntime.hex;
1348
+ const rawBaseDigestHex = baseArtifact?.deployedBytecode?.object?.replace(/^0x/, '') || null;
1349
+ const canHashCand = /^[0-9a-f]+$/i.test(rawCandDigestHex) ? rawCandDigestHex : candRuntime.hex;
1350
+ const canHashBase = rawBaseDigestHex && /^[0-9a-f]+$/i.test(rawBaseDigestHex) ? rawBaseDigestHex : baseRuntime?.hex || null;
1351
+
1352
+ const [candCodehash, baseCodehash, islSpecHash] = await Promise.all([
1353
+ cast(['keccak', '0x' + canHashCand]),
1354
+ canHashBase ? cast(['keccak', '0x' + canHashBase]) : null,
1355
+ cast(['keccak', '0x' + Buffer.from(combinedIslDigest, 'utf8').toString('hex')]),
1356
+ ]);
1357
+
1358
+ const receipt = createReleaseReceipt({
1359
+ id: `intent-${candidate}-${Date.now()}`,
1360
+ protocol: dir ? path.basename(dir) : candidate,
1361
+ baseline: baseline && baseCodehash ? { name: baseline, bytecodeHash: baseCodehash } : null,
1362
+ candidate: { name: candidate, bytecodeHash: candCodehash },
1363
+ intent: {
1364
+ format: 'isl',
1365
+ specHash: islSpecHash,
1366
+ islSha256: islDigests.length === 1 ? islDigests[0] : combinedIslDigest,
1367
+ declaredInvariants,
1368
+ },
1369
+ claims,
1370
+ openObligations: claims.filter((c) => c.outcome === 'unresolved').length,
1371
+ });
1372
+
1373
+ return {
1374
+ schema: 'guardefi.intent-firewall.v1',
1375
+ candidate,
1376
+ baseline,
1377
+ decision: receipt.decision,
1378
+ islSha256: receipt.intent.islSha256,
1379
+ specHash: islSpecHash,
1380
+ declaredInvariants,
1381
+ ...(resolvedLinks.length > 0
1382
+ ? {
1383
+ links: resolvedLinks.map((l) => ({
1384
+ field: l.field,
1385
+ contract: l.contract,
1386
+ binding: l.candField.kind,
1387
+ closed: linksDischargeCalls,
1388
+ })),
1389
+ }
1390
+ : {}),
1391
+ claims,
1392
+ receipt,
1393
+ };
1394
+ }
1395
+
1396
+ module.exports = { detectISLProfile, collectStorageModel, verifyIntentFirewall };