@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,555 @@
1
+ // Behavioral Upgrade Diff (P0).
2
+ // Answers: "What can the protocol do after an upgrade that it could not do before?"
3
+ // Synthesizes ABI entrypoints, storage role slots, abstract EVM reachability,
4
+ // external-frame effects, and symbolic differential solver findings with explicit
5
+ // epistemic classes (PROVEN, BOUNDED, OBSERVED, UNKNOWN).
6
+ const fs = require('node:fs');
7
+ const { compareLayouts, dangerousOpcodes } = require('./generic');
8
+ const { analyze } = require('./engine/provenance');
9
+ const { summarizeExternalEffects } = require('./engine/external-effects');
10
+ const { createReleaseReceipt } = require('./release-receipt');
11
+
12
+ const ROLE_TYPE = /^(address( payable)?$|contract )/;
13
+ const CALL_OPCODES = ['CALL', 'CALLCODE', 'DELEGATECALL', 'STATICCALL', 'CREATE', 'CREATE2', 'SELFDESTRUCT'];
14
+
15
+ function abiParamType(param) {
16
+ if (!param || typeof param.type !== 'string') return 'unknown';
17
+ if (!param.type.startsWith('tuple')) return param.type;
18
+ const parts = Array.isArray(param.components) ? param.components.map(abiParamType) : [];
19
+ return `(${parts.join(',')})${param.type.slice('tuple'.length)}`;
20
+ }
21
+
22
+ function extractEntrypoints(abi = []) {
23
+ const map = new Map();
24
+ if (!Array.isArray(abi)) return map;
25
+ for (const item of abi) {
26
+ if (item?.type === 'receive' || item?.type === 'fallback') {
27
+ map.set(`${item.type}()`, {
28
+ kind: item.type,
29
+ mutability: item.stateMutability === 'payable' ? 'payable' : 'nonpayable',
30
+ payable: item.stateMutability === 'payable',
31
+ mutating: true,
32
+ outputs: [],
33
+ });
34
+ continue;
35
+ }
36
+ if (item?.type !== 'function' || typeof item.name !== 'string') continue;
37
+ const inputs = Array.isArray(item.inputs) ? item.inputs.map(abiParamType) : [];
38
+ const outputs = Array.isArray(item.outputs) ? item.outputs.map(abiParamType) : [];
39
+ const sig = `${item.name}(${inputs.join(',')})`;
40
+ const mutability = ['pure', 'view', 'nonpayable', 'payable'].includes(item.stateMutability)
41
+ ? item.stateMutability
42
+ : 'nonpayable';
43
+ map.set(sig, {
44
+ kind: 'function',
45
+ mutability,
46
+ payable: mutability === 'payable',
47
+ mutating: mutability === 'nonpayable' || mutability === 'payable',
48
+ outputs,
49
+ });
50
+ }
51
+ return map;
52
+ }
53
+
54
+ function extractRoleSlots(layout) {
55
+ if (!Array.isArray(layout?.storage) || !layout?.types) return null;
56
+ const roles = new Map();
57
+ for (const entry of layout.storage) {
58
+ const typeInfo = layout.types[entry?.type];
59
+ if (!typeInfo || typeof typeInfo.label !== 'string') continue;
60
+ if (ROLE_TYPE.test(typeInfo.label)) {
61
+ roles.set(`${entry.slot}:${entry.offset || 0}`, {
62
+ label: entry.label,
63
+ slot: String(entry.slot),
64
+ offset: Number(entry.offset || 0),
65
+ typeLabel: typeInfo.label,
66
+ });
67
+ }
68
+ }
69
+ return roles;
70
+ }
71
+
72
+ function inspectRuntime(artifact) {
73
+ const hex = artifact?.deployedBytecode?.object;
74
+ if (typeof hex !== 'string' || !/^0x(?:[0-9a-f]{2})+$/i.test(hex)) {
75
+ return { valid: false, complete: false, opcodes: new Set(), features: new Set(), calls: [], delegatecalls: [], blockReads: [] };
76
+ }
77
+ let opcodes = new Set();
78
+ try {
79
+ opcodes = dangerousOpcodes(hex);
80
+ } catch {
81
+ opcodes = new Set();
82
+ }
83
+ const reach = analyze(hex, [], { features: true });
84
+ return {
85
+ valid: true,
86
+ complete: Boolean(reach.complete),
87
+ reason: reach.reason || null,
88
+ opcodes,
89
+ features: new Set(reach.features || []),
90
+ calls: reach.calls || [],
91
+ delegatecalls: reach.delegatecalls || [],
92
+ blockReads: reach.blockReads || [],
93
+ rawAnalysis: reach,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Compute a structured Behavioral Upgrade Diff from compiled Baseline and Candidate
99
+ * Foundry artifacts, enriched by optional symbolic engine / generic check outputs
100
+ * or a matched Release Evidence packet.
101
+ */
102
+ function analyzeBehavioralDiff({
103
+ baselineName = 'Baseline',
104
+ candidateName = 'Candidate',
105
+ baseArtifact,
106
+ candidateArtifact,
107
+ genericChecks = null,
108
+ engineReport = null,
109
+ matchedEvidence = null,
110
+ } = {}) {
111
+ if (!baseArtifact || !candidateArtifact) {
112
+ throw new Error('Behavioral diff requires baseline and candidate build artifacts.');
113
+ }
114
+
115
+ const deltas = [];
116
+ const addDelta = (entry) => deltas.push({
117
+ category: entry.category,
118
+ severity: entry.severity || 'medium',
119
+ change: entry.change,
120
+ epistemicClass: entry.epistemicClass,
121
+ impact: entry.impact,
122
+ locus: entry.locus || null,
123
+ witness: entry.witness || null,
124
+ });
125
+
126
+ // 1. ABI Entrypoint & Mutability Escalation Analysis (PROVEN compiler facts + UNKNOWN semantic behavior if unverified)
127
+ const oldFns = extractEntrypoints(baseArtifact.abi);
128
+ const newFns = extractEntrypoints(candidateArtifact.abi);
129
+ const allSigs = [...new Set([...oldFns.keys(), ...newFns.keys()])].sort();
130
+
131
+ for (const sig of allSigs) {
132
+ const before = oldFns.get(sig);
133
+ const after = newFns.get(sig);
134
+ if (!before && after) {
135
+ if (after.payable) {
136
+ addDelta({
137
+ category: 'fund-movement',
138
+ severity: 'high',
139
+ change: `New payable entrypoint ${sig} allows receiving ETH value that ${baselineName} did not expose.`,
140
+ epistemicClass: 'PROVEN',
141
+ impact: 'review-required',
142
+ locus: sig,
143
+ });
144
+ } else if (after.mutating) {
145
+ addDelta({
146
+ category: 'privilege',
147
+ severity: 'medium',
148
+ change: `New state-mutating entrypoint ${sig} expands callable surface over ${baselineName}.`,
149
+ epistemicClass: 'PROVEN',
150
+ impact: 'review-required',
151
+ locus: sig,
152
+ });
153
+ } else {
154
+ addDelta({
155
+ category: 'state-transition',
156
+ severity: 'info',
157
+ change: `Added read-only entrypoint ${sig} (${after.mutability}).`,
158
+ epistemicClass: 'PROVEN',
159
+ impact: 'compatible',
160
+ locus: sig,
161
+ });
162
+ }
163
+ } else if (before && !after) {
164
+ addDelta({
165
+ category: 'privilege',
166
+ severity: before.mutating ? 'medium' : 'info',
167
+ change: `Removed entrypoint ${sig} previously exposed by ${baselineName}.`,
168
+ epistemicClass: 'PROVEN',
169
+ impact: before.mutating ? 'review-required' : 'compatible',
170
+ locus: sig,
171
+ });
172
+ } else if (before && after && before.mutability !== after.mutability) {
173
+ const becamePayable = !before.payable && after.payable;
174
+ const becameMutating = !before.mutating && after.mutating;
175
+ addDelta({
176
+ category: becamePayable ? 'fund-movement' : 'state-transition',
177
+ severity: becamePayable || becameMutating ? 'high' : 'info',
178
+ change: `${sig} mutability changed from ${before.mutability} to ${after.mutability}.`,
179
+ epistemicClass: 'PROVEN',
180
+ impact: becamePayable || becameMutating ? 'review-required' : 'compatible',
181
+ locus: sig,
182
+ });
183
+ }
184
+ }
185
+
186
+ // 2. Storage Layout & Role Slot Analysis
187
+ let storageCompatible = null;
188
+ if (Array.isArray(baseArtifact.storageLayout?.storage) && Array.isArray(candidateArtifact.storageLayout?.storage)) {
189
+ try {
190
+ const problems = compareLayouts(baseArtifact.storageLayout, candidateArtifact.storageLayout);
191
+ storageCompatible = problems.length === 0;
192
+ for (const problem of problems) {
193
+ addDelta({
194
+ category: 'state-transition',
195
+ severity: 'critical',
196
+ change: `Incompatible storage layout: ${problem}.`,
197
+ epistemicClass: 'PROVEN',
198
+ impact: 'violation',
199
+ locus: 'storageLayout',
200
+ });
201
+ }
202
+ } catch {
203
+ storageCompatible = null;
204
+ }
205
+
206
+ const oldRoles = extractRoleSlots(baseArtifact.storageLayout);
207
+ const newRoles = extractRoleSlots(candidateArtifact.storageLayout);
208
+ if (oldRoles && newRoles) {
209
+ for (const [key, role] of newRoles) {
210
+ if (!oldRoles.has(key)) {
211
+ addDelta({
212
+ category: 'privilege',
213
+ severity: 'high',
214
+ change: `New authority/address storage variable ${role.label} (${role.typeLabel}) introduced at slot ${role.slot}.`,
215
+ epistemicClass: 'PROVEN',
216
+ impact: 'review-required',
217
+ locus: `slot:${role.slot}`,
218
+ });
219
+ }
220
+ }
221
+ }
222
+ } else {
223
+ addDelta({
224
+ category: 'state-transition',
225
+ severity: 'medium',
226
+ change: 'Compiler storageLayout metadata is absent in one or both artifacts; layout preservation is unverified.',
227
+ epistemicClass: 'UNKNOWN',
228
+ impact: 'review-required',
229
+ locus: 'storageLayout',
230
+ });
231
+ }
232
+
233
+ // 3. Runtime Opcode, Fund-Movement & External Call Surface Analysis
234
+ const oldRuntime = inspectRuntime(baseArtifact);
235
+ const newRuntime = inspectRuntime(candidateArtifact);
236
+
237
+ for (const dangerous of newRuntime.opcodes) {
238
+ if (!oldRuntime.opcodes.has(dangerous)) {
239
+ addDelta({
240
+ category: 'fund-movement',
241
+ severity: 'critical',
242
+ change: `${candidateName} introduces ${dangerous} in runtime bytecode where ${baselineName} had none.`,
243
+ epistemicClass: 'PROVEN',
244
+ impact: 'violation',
245
+ locus: `opcode:${dangerous}`,
246
+ });
247
+ }
248
+ }
249
+
250
+ if (oldRuntime.complete && newRuntime.complete) {
251
+ for (const op of CALL_OPCODES) {
252
+ if (newRuntime.features.has(op) && !oldRuntime.features.has(op) && !newRuntime.opcodes.has(op)) {
253
+ addDelta({
254
+ category: 'fund-movement',
255
+ severity: op === 'STATICCALL' ? 'medium' : 'high',
256
+ change: `${candidateName} introduces reachable ${op} external interaction paths absent in ${baselineName}.`,
257
+ epistemicClass: 'PROVEN',
258
+ impact: 'review-required',
259
+ locus: `opcode:${op}`,
260
+ });
261
+ }
262
+ }
263
+ const oldDynamicCalls = oldRuntime.calls.filter((c) => !c.fixed).length;
264
+ const newDynamicCalls = newRuntime.calls.filter((c) => !c.fixed).length;
265
+ if (newDynamicCalls > oldDynamicCalls) {
266
+ addDelta({
267
+ category: 'fund-movement',
268
+ severity: 'high',
269
+ change: `Dynamic-target CALL sites increased from ${oldDynamicCalls} to ${newDynamicCalls} (new runtime fund/call routing paths).`,
270
+ epistemicClass: 'PROVEN',
271
+ impact: 'review-required',
272
+ locus: 'bytecode:CALL',
273
+ });
274
+ }
275
+ const oldUnlinkedDelegate = oldRuntime.delegatecalls.filter((d) => !d.library).length;
276
+ const newUnlinkedDelegate = newRuntime.delegatecalls.filter((d) => !d.library).length;
277
+ if (newUnlinkedDelegate > oldUnlinkedDelegate) {
278
+ addDelta({
279
+ category: 'privilege',
280
+ severity: 'critical',
281
+ change: `Non-library DELEGATECALL sites increased from ${oldUnlinkedDelegate} to ${newUnlinkedDelegate}.`,
282
+ epistemicClass: 'PROVEN',
283
+ impact: 'violation',
284
+ locus: 'bytecode:DELEGATECALL',
285
+ });
286
+ }
287
+ } else if (oldRuntime.valid || newRuntime.valid) {
288
+ addDelta({
289
+ category: 'fund-movement',
290
+ severity: 'medium',
291
+ change: 'Abstract EVM control-flow reachability did not complete; dynamic call/callback surface remains unresolved.',
292
+ epistemicClass: 'UNKNOWN',
293
+ impact: 'review-required',
294
+ locus: 'bytecode:reachability',
295
+ });
296
+ }
297
+
298
+ // 4. Symbolic Differential Checks (Generic + Upgrade Engine v3 + Matched Evidence)
299
+ let hasSymbolicCoverage = false;
300
+
301
+ if (Array.isArray(genericChecks)) {
302
+ hasSymbolicCoverage = true;
303
+ for (const check of genericChecks) {
304
+ if (check.name === 'layout' || check.name === 'opcodes') continue;
305
+ const isBounded = check.status === 'bounded' || check.boundedLoops > 0;
306
+ const epistemicClass = check.proven
307
+ ? (isBounded ? 'BOUNDED' : 'BOUNDED') // generic Halmos checks bound 24 plain slots & 4 calldata words
308
+ : (check.status === 'failed' || check.counterexample ? 'BOUNDED' : 'UNKNOWN');
309
+
310
+ if (!check.proven) {
311
+ const category = check.name === 'roles' ? 'privilege' : 'restriction';
312
+ const isViolation = Boolean(check.counterexample || check.status === 'failed');
313
+ addDelta({
314
+ category,
315
+ severity: isViolation ? 'critical' : 'high',
316
+ change: check.name === 'roles'
317
+ ? (isViolation
318
+ ? `Unauthorized role escalation detected: unprivileged caller can alter role state (${check.counterexample || 'counterexample'}).`
319
+ : 'Symbolic role-preservation check was inconclusive within bounds.')
320
+ : (isViolation
321
+ ? `Weakened access restriction: ${candidateName} accepts a call rejected by ${baselineName} (${check.counterexample || 'counterexample'}).`
322
+ : 'Symbolic guard-preservation check was inconclusive within bounds.'),
323
+ epistemicClass: isViolation ? 'PROVEN' : 'UNKNOWN',
324
+ impact: isViolation ? 'violation' : 'review-required',
325
+ locus: `upgrade_${check.name}`,
326
+ witness: check.counterexample || null,
327
+ });
328
+ }
329
+ }
330
+ }
331
+
332
+ if (engineReport) {
333
+ hasSymbolicCoverage = true;
334
+ const categoryForRule = (rule) => {
335
+ if (['capability', 'upgrade', 'upgrade-gained', 'upgrade-lost', 'policy'].includes(rule)) return 'privilege';
336
+ if (['guard', 'implementation-open', 'init-fails'].includes(rule)) return 'restriction';
337
+ if (['value'].includes(rule)) return 'fund-movement';
338
+ return 'state-transition';
339
+ };
340
+
341
+ for (const finding of engineReport.findings || []) {
342
+ if (finding.rule === 'layout' || finding.rule === 'opcode') continue;
343
+ addDelta({
344
+ category: categoryForRule(finding.rule),
345
+ severity: 'critical',
346
+ change: finding.detail || `Differential violation in ${finding.rule}.`,
347
+ epistemicClass: 'PROVEN',
348
+ impact: 'violation',
349
+ locus: `engine:${finding.rule}`,
350
+ witness: finding.witness || null,
351
+ });
352
+ }
353
+
354
+ for (const prop of engineReport.properties || []) {
355
+ if (['layout', 'opcodes'].includes(prop.name)) continue;
356
+ if (prop.status === 'bounded' || (prop.status === 'proven' && prop.bounded > 0)) {
357
+ addDelta({
358
+ category: prop.name === 'values' ? 'fund-movement' : prop.name === 'guards' ? 'restriction' : 'state-transition',
359
+ severity: 'info',
360
+ change: `Differential property '${prop.name}' held across ${prop.checks} bounded symbolic check(s).`,
361
+ epistemicClass: 'BOUNDED',
362
+ impact: 'review-required',
363
+ locus: `engine:${prop.name}`,
364
+ });
365
+ } else if (['timeout', 'unsupported', 'unresolved', 'error'].includes(prop.status)) {
366
+ addDelta({
367
+ category: prop.name === 'reentrancy' ? 'fund-movement' : 'state-transition',
368
+ severity: 'medium',
369
+ change: `Differential property '${prop.name}' remains ${prop.status} (${prop.unverified || 1} unverified obligation(s)).`,
370
+ epistemicClass: 'UNKNOWN',
371
+ impact: 'review-required',
372
+ locus: `engine:${prop.name}`,
373
+ });
374
+ }
375
+ }
376
+ } else if (matchedEvidence?.status === 'matched') {
377
+ hasSymbolicCoverage = true;
378
+ for (const check of matchedEvidence.checks || []) {
379
+ if (check.status === 'failed' || check.status === 'violated') {
380
+ addDelta({
381
+ category: check.name.includes('role') || check.name.includes('capabilit') ? 'privilege' : 'restriction',
382
+ severity: 'critical',
383
+ change: `Recorded verification check '${check.name}' failed (${check.status}).`,
384
+ epistemicClass: 'PROVEN',
385
+ impact: 'violation',
386
+ locus: check.name,
387
+ });
388
+ } else if (check.status === 'bounded') {
389
+ addDelta({
390
+ category: 'restriction',
391
+ severity: 'info',
392
+ change: `Recorded verification check '${check.name}' passed within solver bounds.`,
393
+ epistemicClass: 'BOUNDED',
394
+ impact: 'review-required',
395
+ locus: check.name,
396
+ });
397
+ } else if (!['proven', 'satisfied'].includes(check.status)) {
398
+ addDelta({
399
+ category: 'state-transition',
400
+ severity: 'medium',
401
+ change: `Recorded verification check '${check.name}' has unresolved status '${check.status}'.`,
402
+ epistemicClass: 'UNKNOWN',
403
+ impact: 'review-required',
404
+ locus: check.name,
405
+ });
406
+ }
407
+ }
408
+ }
409
+
410
+ if (!hasSymbolicCoverage) {
411
+ addDelta({
412
+ category: 'restriction',
413
+ severity: 'medium',
414
+ change: 'No symbolic differential execution attached: guard equivalence, role transitions, and balance preservation remain unverified.',
415
+ epistemicClass: 'UNKNOWN',
416
+ impact: 'review-required',
417
+ locus: 'solver:unrun',
418
+ });
419
+ }
420
+
421
+ const externalEffects = oldRuntime.valid && newRuntime.valid
422
+ ? summarizeExternalEffects([[oldRuntime.rawAnalysis], [newRuntime.rawAnalysis]])
423
+ : null;
424
+
425
+ const epistemicBreakdown = { proven: 0, bounded: 0, observed: 0, unknown: 0 };
426
+ for (const d of deltas) {
427
+ if (d.epistemicClass === 'PROVEN') epistemicBreakdown.proven++;
428
+ else if (d.epistemicClass === 'BOUNDED') epistemicBreakdown.bounded++;
429
+ else if (d.epistemicClass === 'OBSERVED') epistemicBreakdown.observed++;
430
+ else epistemicBreakdown.unknown++;
431
+ }
432
+
433
+ const violations = deltas.filter((d) => d.impact === 'violation').length;
434
+ const reviewRequired = deltas.filter((d) => d.impact === 'review-required').length;
435
+ const recommendedDecision = violations > 0
436
+ ? 'NO_SHIP'
437
+ : (reviewRequired > 0 || epistemicBreakdown.unknown > 0 || epistemicBreakdown.bounded > 0)
438
+ ? 'REVIEW'
439
+ : 'SHIP';
440
+
441
+ const summary = {
442
+ privilegeChanges: deltas.filter((d) => d.category === 'privilege' && d.impact !== 'compatible').length,
443
+ guardWeakeningCount: deltas.filter((d) => d.category === 'restriction' && d.impact === 'violation').length,
444
+ fundSurfaceChanges: deltas.filter((d) => d.category === 'fund-movement' && d.impact !== 'compatible').length,
445
+ externalCallChanges: externalEffects ? externalEffects.invocations.length : 0,
446
+ storageCompatible,
447
+ violations,
448
+ reviewRequired,
449
+ epistemicBreakdown,
450
+ recommendedDecision,
451
+ };
452
+
453
+ return {
454
+ schema: 'guardefi.behavioral-diff.v1',
455
+ baseline: baselineName,
456
+ candidate: candidateName,
457
+ recommendedDecision,
458
+ summary,
459
+ deltas,
460
+ externalEffects,
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Full CLI/automated Behavioral Upgrade Diff: compiles the Foundry project,
466
+ * optionally runs Halmos differential verification, and emits both the behavioral
467
+ * diff and a verifiable Release Receipt.
468
+ */
469
+ async function runBehavioralUpgradeDiff({ dir, baseline, candidate, artifactsOnly = false }) {
470
+ const { openProject, specHash } = require('./prove');
471
+ const { upgradeChecks } = require('./generic');
472
+ const { verifyUpgrade } = require('./engine');
473
+ const { cast } = require('./tools');
474
+ const path = require('node:path');
475
+
476
+ await openProject(dir);
477
+ const findArtifact = (name) => {
478
+ const out = path.join(dir, 'out');
479
+ for (const folder of fs.readdirSync(out)) {
480
+ if (folder === 'build-info') continue;
481
+ const file = path.join(out, folder, `${name}.json`);
482
+ if (fs.existsSync(file)) return JSON.parse(fs.readFileSync(file, 'utf8'));
483
+ }
484
+ throw new Error(`Artifact not found for ${name}.`);
485
+ };
486
+
487
+ const baseArtifact = findArtifact(baseline);
488
+ const candidateArtifact = findArtifact(candidate);
489
+
490
+ let genericChecks = null;
491
+ let engineReport = null;
492
+ if (!artifactsOnly) {
493
+ genericChecks = await upgradeChecks({
494
+ dir,
495
+ contract: candidate,
496
+ baseline,
497
+ artifact: candidateArtifact,
498
+ baseArtifact,
499
+ strict: false,
500
+ });
501
+ if (genericChecks.every((c) => c.proven)) {
502
+ engineReport = await verifyUpgrade({ dir, artifact: candidateArtifact, baseArtifact });
503
+ }
504
+ }
505
+
506
+ const diff = analyzeBehavioralDiff({
507
+ baselineName: baseline,
508
+ candidateName: candidate,
509
+ baseArtifact,
510
+ candidateArtifact,
511
+ genericChecks,
512
+ engineReport,
513
+ });
514
+
515
+ const [baseHash, candHash, projectSpecHash] = await Promise.all([
516
+ cast(['keccak', baseArtifact.deployedBytecode.object]),
517
+ cast(['keccak', candidateArtifact.deployedBytecode.object]),
518
+ specHash(dir),
519
+ ]);
520
+
521
+ const claims = diff.deltas.length
522
+ ? diff.deltas.map((d, index) => ({
523
+ id: `diff.${index + 1}.${d.category}`,
524
+ category: d.category,
525
+ source: 'guardefi-behavioral-diff',
526
+ epistemicClass: d.epistemicClass,
527
+ outcome: d.impact === 'violation' ? 'violated' : d.epistemicClass === 'UNKNOWN' ? 'unresolved' : 'satisfied',
528
+ mandatory: d.impact !== 'compatible',
529
+ detail: d.change,
530
+ }))
531
+ : [{
532
+ id: 'diff.equivalence',
533
+ category: 'differential',
534
+ source: 'guardefi-behavioral-diff',
535
+ epistemicClass: artifactsOnly ? 'UNKNOWN' : 'PROVEN',
536
+ outcome: artifactsOnly ? 'unresolved' : 'satisfied',
537
+ mandatory: true,
538
+ detail: 'No behavioral deltas detected across checked surface.',
539
+ }];
540
+
541
+ const receipt = createReleaseReceipt({
542
+ id: `diff-${baseline}-${candidate}-${Date.now()}`,
543
+ protocol: path.basename(dir),
544
+ baseline: { name: baseline, bytecodeHash: baseHash },
545
+ candidate: { name: candidate, bytecodeHash: candHash },
546
+ intent: { format: 'generic', specHash: projectSpecHash },
547
+ claims,
548
+ openObligations: engineReport?.integrity?.obligations?.length ?? (artifactsOnly ? 1 : 0),
549
+ behavioralSummary: diff.summary,
550
+ });
551
+
552
+ return { diff, receipt };
553
+ }
554
+
555
+ module.exports = { analyzeBehavioralDiff, runBehavioralUpgradeDiff };
@@ -0,0 +1,9 @@
1
+ function canonical(value) {
2
+ if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
3
+ if (value && typeof value === 'object') {
4
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
5
+ }
6
+ return JSON.stringify(value);
7
+ }
8
+
9
+ module.exports = { canonical };
@@ -0,0 +1,99 @@
1
+ // Canonical ABI head/tail encoding for finite, independently chosen lengths.
2
+ const ABI_BOUNDS = Object.freeze({
3
+ arrayLengths: Object.freeze([0, 1]),
4
+ byteLengths: Object.freeze([0, 1, 32]),
5
+ maxDepth: 12,
6
+ maxWords: 48,
7
+ maxSymbolicWords: 12,
8
+ maxVariants: 128,
9
+ });
10
+
11
+ function canonicalType(input) {
12
+ if (!input.type.startsWith('tuple')) return input.type;
13
+ return `(${input.components.map(canonicalType).join(',')})${input.type.slice(5)}`;
14
+ }
15
+
16
+ const signature = (entry) => `${entry.name}(${entry.inputs.map(canonicalType).join(',')})`;
17
+ const scalar = /^(address|bool|function|u?int(?:[0-9]+)?|bytes[0-9]+)$/;
18
+ const limit = Symbol('ABI shape limit');
19
+
20
+ function tuple(fields) {
21
+ const headWords = fields.reduce((total, field) => total + (field.dynamic ? 1 : field.words.length), 0);
22
+ const head = [];
23
+ const tail = [];
24
+ for (const field of fields) {
25
+ if (field.dynamic) {
26
+ head.push((headWords + tail.length) * 32);
27
+ tail.push(...field.words);
28
+ } else {
29
+ head.push(...field.words);
30
+ }
31
+ if (head.length + tail.length > ABI_BOUNDS.maxWords) throw limit;
32
+ }
33
+ return { words: [...head, ...tail], dynamic: fields.some((field) => field.dynamic) };
34
+ }
35
+
36
+ function product(choices) {
37
+ let variants = [[]];
38
+ for (const next of choices) {
39
+ if (variants.length * next.length > ABI_BOUNDS.maxVariants) throw limit;
40
+ variants = variants.flatMap((prefix) => next.map((value) => [...prefix, value]));
41
+ }
42
+ return variants.map(tuple);
43
+ }
44
+
45
+ function plans(input, depth) {
46
+ if (depth > ABI_BOUNDS.maxDepth) throw limit;
47
+ const { type } = input;
48
+ const array = /^(.*)\[([0-9]*)\]$/.exec(type);
49
+ if (array) {
50
+ const dynamic = array[2] === '';
51
+ const lengths = dynamic ? ABI_BOUNDS.arrayLengths : [Number(array[2])];
52
+ if (lengths.some((n) => n > ABI_BOUNDS.maxWords || (!dynamic && n === 0))) throw limit;
53
+ const element = plans({ ...input, type: array[1] }, depth + 1);
54
+ const variants = lengths.flatMap((n) => product(Array(n).fill(element)).map((encoding) => ({
55
+ dynamic: dynamic || encoding.dynamic,
56
+ words: dynamic ? [n, ...encoding.words] : encoding.words,
57
+ })));
58
+ if (variants.length > ABI_BOUNDS.maxVariants) throw limit;
59
+ return variants;
60
+ }
61
+ if (type === 'tuple') {
62
+ if (!Array.isArray(input.components)) throw limit;
63
+ return product(input.components.map((component) => plans(component, depth + 1)));
64
+ }
65
+ if (type === 'bytes' || type === 'string') {
66
+ return ABI_BOUNDS.byteLengths.map((length) => ({
67
+ dynamic: true,
68
+ words: length ? [length, { bytes: length }] : [0],
69
+ }));
70
+ }
71
+ if (!scalar.test(type)) throw limit;
72
+ return [{ words: [{ address: type === 'address' }] }];
73
+ }
74
+
75
+ function callPlans(inputs) {
76
+ try {
77
+ if (inputs.length > ABI_BOUNDS.maxWords) throw limit;
78
+ return product(inputs.map((input) => plans(input, 0))).map(({ words }, variant) => {
79
+ if (words.length > ABI_BOUNDS.maxWords) throw limit;
80
+ let symbols = 0;
81
+ const addr = [];
82
+ const partial = {};
83
+ const encoded = words.map((word) => {
84
+ if (typeof word === 'number') return word;
85
+ if (word.address) addr.push(symbols);
86
+ if (word.bytes && word.bytes < 32) partial[symbols] = word.bytes;
87
+ symbols++;
88
+ return 'sym';
89
+ });
90
+ if (symbols > ABI_BOUNDS.maxSymbolicWords) throw limit;
91
+ return { words: encoded, addr, partial, variant };
92
+ });
93
+ } catch (error) {
94
+ if (error !== limit) throw error;
95
+ return null;
96
+ }
97
+ }
98
+
99
+ module.exports = { ABI_BOUNDS, callPlans, signature, canonicalType };