@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,151 @@
1
+ // Which declared storage the behavior checks must watch, and which contracts
2
+ // they cannot model. Anything unrecognized is a reason, never a silent omission.
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { analyze } = require('../engine/provenance');
6
+
7
+ const MAX_WORDS = 64;
8
+ const MODELED_FEATURES = new Set(['CALLER', 'CALLVALUE', 'CODESIZE', 'CODECOPY', 'SLOAD', 'SSTORE']);
9
+ const UNMODELED_YUL = new Set(['sstore', 'tstore', 'delegatecall', 'callcode']);
10
+
11
+ function keyType(label) {
12
+ if (label === 'address' || label === 'address payable' || /^contract /.test(label)) return 'address';
13
+ if (/^enum /.test(label)) return 'uint8';
14
+ return label === 'bool' || label === 'bytes32' || /^uint[0-9]+$/.test(label) ? label : null;
15
+ }
16
+
17
+ function fieldKind(label) {
18
+ if (label === 'address' || label === 'address payable' || /^contract /.test(label)) return 'address';
19
+ if (label === 'bool') return 'bool';
20
+ return /^uint[0-9]+$/.test(label) ? 'uint' : 'other';
21
+ }
22
+
23
+ /**
24
+ * Every storage word of a layout, keyed by its declared variable (`root`).
25
+ * `steps` lead from `slot` to the word: a mapping key, an added offset, or the
26
+ * data area of a string or dynamic array at a symbolic index.
27
+ */
28
+ function storageWords(layout) {
29
+ const words = new Map();
30
+ const reasons = new Set();
31
+ const types = layout.types || {};
32
+ const add = (root, label, slot, steps, field) => {
33
+ const id = JSON.stringify([root, String(slot), steps]);
34
+ // Packed neighbors declared as separate variables share a word.
35
+ const shared = steps.length ? id : `slot ${slot}`;
36
+ const word = words.get(shared) || { root, label, slot: String(slot), steps, fields: [] };
37
+ word.fields.push(field);
38
+ words.set(shared, word);
39
+ };
40
+ const visit = (root, label, id, slot, offset, steps) => {
41
+ const type = types[id];
42
+ const keyed = steps.length > 0;
43
+ const size = Number(type?.numberOfBytes);
44
+ const value = (item) => item?.encoding === 'inplace' && !item.members && !item.base;
45
+ if (!type) reasons.add(`storage variable ${label} has an unknown type`);
46
+ else if (type.encoding === 'mapping') {
47
+ const key = keyType(types[type.key]?.label || '');
48
+ if (!key) reasons.add(`mapping ${label} has an unsupported key type`);
49
+ else visit(root, label, type.value, slot, 0, [...steps, { kind: 'key', type: key }]);
50
+ } else if (type.encoding === 'bytes' || type.encoding === 'dynamic_array') {
51
+ if (keyed) reasons.add(`${label} holds dynamic data inside a mapping`);
52
+ else if (type.encoding === 'dynamic_array' && !value(types[type.base])) reasons.add(`array ${label} has unsupported elements`);
53
+ else {
54
+ add(root, label, slot, [], { label: `${label} length`, offset: 0, size: 32, kind: 'other' });
55
+ add(root, label, slot, [{ kind: 'data' }], { label: `${label} data`, offset: 0, size: 32, kind: 'other' });
56
+ }
57
+ } else if (type.encoding !== 'inplace' || !Number.isSafeInteger(size) || size < 1) reasons.add(`storage variable ${label} has an unknown encoding`);
58
+ else if (type.members) {
59
+ for (const member of type.members) place(root, `${label}.${member.label}`, member.type, slot, Number(member.slot), member.offset, steps);
60
+ } else if (type.base) {
61
+ if (!value(types[type.base]) || size > MAX_WORDS * 32) reasons.add(`fixed array ${label} is outside the modeled storage shapes`);
62
+ else for (let i = 0; i < Math.ceil(size / 32); i++) place(root, `${label}[word ${i}]`, null, slot, i, 0, steps);
63
+ } else add(root, label, slot, steps, { label, offset, size, kind: fieldKind(type.label) });
64
+ };
65
+ // A member `extra` words past `slot`: folded into the slot, or a step after a mapping key.
66
+ function place(root, label, id, slot, extra, offset, steps) {
67
+ const last = steps.at(-1);
68
+ const at = !steps.length ? slot + BigInt(extra) : slot;
69
+ const path = !steps.length || !extra ? steps
70
+ : last.kind === 'add' ? [...steps.slice(0, -1), { kind: 'add', n: last.n + extra }] : [...steps, { kind: 'add', n: extra }];
71
+ if (id === null) add(root, label, at, path, { label, offset: 0, size: 32, kind: 'other' });
72
+ else visit(root, label, id, at, offset, path);
73
+ }
74
+ for (const [root, item] of (layout.storage || []).entries()) visit(root, item.label, item.type, BigInt(item.slot), item.offset, []);
75
+ if (words.size > MAX_WORDS) reasons.add(`storage needs ${words.size} watched words, more than the limit of ${MAX_WORDS}`);
76
+ return { words: [...words.values()], reasons: [...reasons].sort() };
77
+ }
78
+
79
+ /** Declared fields a getter could be reading: same keys in the same order, same kind and width. */
80
+ function candidates(getter, words) {
81
+ const params = getter.params.map(param => param.type);
82
+ const kind = getter.type.startsWith('uint') ? 'uint' : getter.type;
83
+ const size = { address: 20, bool: 1 }[kind] || Number(getter.type.slice(4)) / 8;
84
+ return words.filter(word => !word.steps.some(step => step.kind === 'data') &&
85
+ JSON.stringify(word.steps.filter(step => step.kind === 'key').map(step => step.type)) === JSON.stringify(params))
86
+ .flatMap(word => word.fields.filter(field => field.kind === kind && field.size === size).map(field => ({ word, field })));
87
+ }
88
+
89
+ /** Contracts and source trees of a Foundry build. */
90
+ function readBuild(root) {
91
+ const out = path.join(root, 'out');
92
+ const artifacts = [];
93
+ const asts = new Map();
94
+ for (const dir of fs.readdirSync(out, { withFileTypes: true })) {
95
+ if (!dir.isDirectory() || dir.name === 'build-info') continue;
96
+ for (const file of fs.readdirSync(path.join(out, dir.name)).filter(name => name.endsWith('.json'))) {
97
+ const artifact = JSON.parse(fs.readFileSync(path.join(out, dir.name, file), 'utf8'));
98
+ artifacts.push({ name: file.slice(0, -5), source: dir.name, artifact });
99
+ if (artifact.ast?.absolutePath) asts.set(artifact.ast.absolutePath, artifact.ast);
100
+ }
101
+ }
102
+ return { artifacts, asts };
103
+ }
104
+
105
+ function assemblyReasons(source, ast) {
106
+ const reasons = [];
107
+ const walk = (node, inAssembly) => {
108
+ if (!node || typeof node !== 'object') return;
109
+ if (Array.isArray(node)) return node.forEach(child => walk(child, inAssembly));
110
+ const here = inAssembly || node.nodeType === 'InlineAssembly';
111
+ if (node.nodeType === 'InlineAssembly' && !node.AST) reasons.push(`${source} has inline assembly without a syntax tree`);
112
+ if (here && node.nodeType === 'YulFunctionCall' && UNMODELED_YUL.has(node.functionName?.name)) {
113
+ reasons.push(`${source} has inline assembly using ${node.functionName.name}`);
114
+ }
115
+ if (here && node.nodeType === 'YulAssignment' && node.variableNames?.some(({ name }) => /\.slot$/.test(name))) {
116
+ reasons.push(`${source} has inline assembly assigning .slot`);
117
+ }
118
+ for (const child of Object.values(node)) walk(child, here);
119
+ };
120
+ walk(ast, false);
121
+ return reasons;
122
+ }
123
+
124
+ /** Why this contract is outside the model. Empty means every check applies. */
125
+ function unsupportedReasons(artifact, asts) {
126
+ const reasons = [];
127
+ const raw = artifact.metadata ?? artifact.rawMetadata;
128
+ const metadata = typeof raw === 'string' ? JSON.parse(raw) : raw;
129
+ const [, major, minor] = /^(\d+)\.(\d+)\./.exec(metadata?.compiler?.version || '') || [];
130
+ if (metadata?.language !== 'Solidity' || !(Number(major) > 0 || Number(minor) >= 8)) reasons.push('needs Solidity 0.8 or later compiler metadata');
131
+ const sources = Object.keys(metadata?.sources || {});
132
+ if (!sources.length) reasons.push('compiler metadata lists no sources');
133
+ for (const source of sources) {
134
+ if (!asts.has(source)) reasons.push(`no AST for ${source}`);
135
+ else reasons.push(...assemblyReasons(source, asts.get(source)));
136
+ }
137
+ if (Object.keys(artifact.deployedBytecode?.linkReferences || {}).length ||
138
+ Object.keys(metadata?.settings?.libraries || {}).length) reasons.push('uses linked libraries');
139
+ if (!Array.isArray(artifact.storageLayout?.storage)) reasons.push('has no storage layout');
140
+ else reasons.push(...storageWords(artifact.storageLayout).reasons);
141
+ const hex = artifact.deployedBytecode?.object;
142
+ if (typeof hex !== 'string' || !/^0x([0-9a-f]{2})+$/i.test(hex)) reasons.push('has no complete runtime bytecode');
143
+ else {
144
+ const { complete, reason, features, blockReads } = analyze(hex, [], { features: true });
145
+ if (!complete) reasons.push(`runtime reachability is incomplete: ${reason}`);
146
+ for (const opcode of new Set([...features, ...blockReads])) if (!MODELED_FEATURES.has(opcode)) reasons.push(`runtime reaches ${opcode}`);
147
+ }
148
+ return [...new Set(reasons)].sort();
149
+ }
150
+
151
+ module.exports = { storageWords, candidates, readBuild, unsupportedReasons };
@@ -0,0 +1,223 @@
1
+ // Build a copy of the project, have Halmos prove which storage each granted
2
+ // getter reads, run the generated checks, and reduce them to one status that
3
+ // is proven only when every expected check is.
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { createHash } = require('node:crypto');
8
+ const { canonical } = require('../canonical-json');
9
+ const { compileBehaviorISL } = require('../isl-compiler');
10
+ const defaultTools = require('../tools');
11
+ const { storageWords, unsupportedReasons, readBuild } = require('./behavior-storage');
12
+ const { emitBase, emitMaps, emitChecks, emitFoundry } = require('./behavior-solidity');
13
+
14
+ const { checkerStatus } = defaultTools;
15
+ const HALMOS = ['--storage-layout', 'solidity', '--loop', '8', '--solver-timeout-assertion', '30000'];
16
+ const ORDER = ['UNSUPPORTED', 'VIOLATED', 'INCONCLUSIVE', 'PROVEN_UNDER_ASSUMPTIONS', 'PROVEN'];
17
+ const LIMITS = [
18
+ 'Each result covers one canonical ABI call that sends zero ETH.',
19
+ 'A violation with startState "any" may start from a state the contract cannot reach.',
20
+ 'Hash collisions are excluded, and dynamic arrays are assumed short enough not to wrap storage.',
21
+ 'Dynamic storage frame checks cover only data word offsets below 2**64.',
22
+ 'Logs, gas and other contracts are outside every result.',
23
+ 'A result grants no authority to approve or deploy.',
24
+ ];
25
+ const sha = value => createHash('sha256').update(value).digest('hex');
26
+ const own = (object, key) => Object.hasOwn(object, key) ? object[key] : undefined;
27
+ const proven = status => status === 'PROVEN' || status === 'PROVEN_UNDER_ASSUMPTIONS';
28
+
29
+ function reduceStatus({ reasons, expected, results, assumptions }) {
30
+ const checks = expected.map(({ name, kind, startState }) => {
31
+ const result = own(results, name);
32
+ return { name, kind, startState, status: checkerStatus(result), ...(result?.counterexample ? { counterexample: result.counterexample } : {}) };
33
+ });
34
+ const violated = checks.filter(check => check.status === 'violated');
35
+ const status = reasons.length ? 'UNSUPPORTED'
36
+ : violated.length ? 'VIOLATED'
37
+ : !checks.length || checks.some(check => check.status !== 'proven') ? 'INCONCLUSIVE'
38
+ : assumptions.length ? 'PROVEN_UNDER_ASSUMPTIONS' : 'PROVEN';
39
+ const startState = status !== 'VIOLATED' ? null : violated.some(check => check.startState === 'deployed') ? 'deployed' : 'any';
40
+ return { status, startState, checks };
41
+ }
42
+
43
+ function describe(value, inputs) {
44
+ const show = item => describe(item, inputs);
45
+ if (value.op) return `${value.when ? `${show(value.when)} implies ` : ''}${show(value.left)} ${value.op} ${show(value.right)}`;
46
+ switch (value.kind) {
47
+ case 'input': return value.index === 0 ? 'caller' : inputs[value.index - 1].name;
48
+ case 'literal': return value.type === 'bool' ? String(value.word === '1') : value.word;
49
+ case 'getter': return `${value.signature.split('(')[0]}(${value.params.map(show).join(', ')})`;
50
+ default: return `${show(value.left)} ${value.kind === 'add' ? '+' : '-'} ${show(value.right)}`;
51
+ }
52
+ }
53
+
54
+ /** Foundry's JSON in the shape of Halmos results. Only an assertion failure is a violation. */
55
+ function foundryResults(stdout) {
56
+ const results = Object.create(null);
57
+ let suites;
58
+ try { suites = JSON.parse(stdout); } catch { return results; }
59
+ const suite = Object.entries(suites).find(([key]) => key.endsWith(':GuardefiFoundry'))?.[1];
60
+ for (const [signature, test] of Object.entries(suite?.test_results || {})) {
61
+ results[signature.replace(/\(.*/, '')] = test.status === 'Success' ? { exitcode: 0, boundedLoops: 0 }
62
+ : /assertion failed/.test(test.reason || '') ? { exitcode: 1, validModel: true, counterexample: { calldata: test.counterexample?.Single?.calldata ?? null } }
63
+ : { exitcode: 3 };
64
+ }
65
+ return results;
66
+ }
67
+
68
+ // Without a project adapter only the checks that start from an arbitrary state can run. The adapter is
69
+ // synthesized: it places the exact built runtime at a fixed address. Deployed-state availability and the
70
+ // concrete example are then not checked, and the report says so.
71
+ const ANY_STATE_LIMIT = 'No project adapter: availability from the deployed state and the concrete example were not checked.';
72
+ const SYNTH_TARGET = 'address(uint160(0xA11CE))';
73
+
74
+ function synthesizeAdapter(properties, runtimeHex) {
75
+ const examples = properties.map((_, i) => ` function _guardefiExample${i + 1}() internal view override returns (Behavior${i + 1}Input memory s) {}`);
76
+ return ['// SPDX-License-Identifier: MIT', 'pragma solidity ^0.8.20;', '',
77
+ 'import {GuardefiBehaviorBase} from "./GuardefiBehaviorBase.sol";', '',
78
+ 'abstract contract GuardefiAdapter is GuardefiBehaviorBase {',
79
+ ` function setUp() public { vm.etch(${SYNTH_TARGET}, hex"${runtimeHex.replace(/^0x/, '')}"); }`,
80
+ ` function _guardefiTarget() internal view override returns (address) { return ${SYNTH_TARGET}; }`,
81
+ ...examples, '}', ''].join('\n');
82
+ }
83
+
84
+ async function verifyBehaviors({ policyFile, policySource, project: root, contract, adapterFile, adapterSource, tools = defaultTools }) {
85
+ const project = path.resolve(root);
86
+ const policy = policySource ?? fs.readFileSync(policyFile, 'utf8');
87
+ let adapter = adapterSource ?? (adapterFile ? fs.readFileSync(adapterFile, 'utf8') : null);
88
+ const anyStateOnly = adapter === null;
89
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'guardefi-behavior-'));
90
+ const report = { contract, status: 'INCONCLUSIVE', mode: anyStateOnly ? 'any-state' : 'full', behaviors: [], notes: [],
91
+ limits: anyStateOnly ? [...LIMITS, ANY_STATE_LIMIT] : LIMITS, digests: { policy: sha(policy), adapter: anyStateOnly ? null : sha(adapter) }, tools: {} };
92
+ const inMode = check => !anyStateOnly || check.startState === 'any' || check.kind === 'target';
93
+ const execOptions = { cwd: dir };
94
+ const build = async () => {
95
+ const { code, stdout, stderr } = await tools.run('forge', ['build', '--force', '--root', dir, '--out', 'out', '--ast', '--extra-output', 'storageLayout'], execOptions);
96
+ if (code !== 0) report.notes.push(`Build failed. ${(stderr || stdout).trim().slice(0, 4000)}`);
97
+ return code === 0;
98
+ };
99
+ const solve = async (harness) => {
100
+ try {
101
+ let diagnostic = '';
102
+ const receipt = result => { diagnostic = result.diagnostic || ''; };
103
+ const results = await tools.runHalmos(dir, harness, HALMOS, { ...execOptions, receipt });
104
+ if (!Object.keys(results).length) report.notes.push(`Halmos returned no checks for ${harness}. ${diagnostic}`.trim());
105
+ return results;
106
+ } catch (err) {
107
+ report.notes.push(`Halmos failed for ${harness}. ${err.message}`);
108
+ return {};
109
+ }
110
+ };
111
+ try {
112
+ const skipped = new Set(['out', 'cache', '.git', 'lib', 'node_modules'].map(name => path.join(project, name)));
113
+ fs.cpSync(project, dir, { recursive: true, filter: source => !skipped.has(source) });
114
+ for (const name of ['lib', 'node_modules']) {
115
+ const source = path.join(project, name);
116
+ if (fs.existsSync(source)) fs.symlinkSync(fs.realpathSync(source), path.join(dir, name));
117
+ }
118
+ for (const name of ['forge', 'halmos']) {
119
+ const { code, stdout } = await tools.run(name, ['--version']);
120
+ report.tools[name] = code === 0 ? stdout.trim().split('\n')[0] : null;
121
+ if (code !== 0) report.notes.push(`${name} is not available.`);
122
+ }
123
+ if (!await build()) return report;
124
+
125
+ const { artifacts, asts } = readBuild(dir);
126
+ const matches = artifacts.filter(({ name }) => name === contract);
127
+ if (matches.length !== 1) throw new Error(`The project needs exactly one contract named ${contract}; found ${matches.length}.`);
128
+ const { artifact } = matches[0];
129
+ const compiled = compileBehaviorISL(policy, artifact.abi);
130
+ const { properties } = compiled;
131
+ Object.assign(report, { compiler: compiled.compiler });
132
+ Object.assign(report.digests, { abi: compiled.abiSha256, artifact: sha(canonical(artifact)) });
133
+ report.tools.solc = artifact.metadata?.compiler?.version ?? null;
134
+
135
+ const reasons = unsupportedReasons(artifact, asts);
136
+ const { words } = storageWords(artifact.storageLayout || {});
137
+ const immutables = Object.values(artifact.deployedBytecode?.immutableReferences || {}).flat();
138
+ const finish = (expected, results, perBehavior = () => ({ reasons: [], blocked: false, maps: {} })) => {
139
+ report.behaviors = properties.map((property) => {
140
+ const { reasons: own, blocked, maps } = perBehavior(property);
141
+ const assumptions = [...property.assumptions.map(item => describe(item, property.inputs)),
142
+ ...(immutables.length ? ['Immutable values are those the test setup deployed.'] : [])];
143
+ const all = [...reasons, ...own];
144
+ const reduced = reduceStatus({ reasons: all, assumptions, results, expected: blocked ? [] : expected.filter(check => check.behavior === property.id) });
145
+ return { id: property.id, ...reduced, reasons: all, assumptions, maps };
146
+ });
147
+ const statuses = report.behaviors.map(({ status }) => status);
148
+ report.status = ORDER.find(status => statuses.includes(status)) || 'INCONCLUSIVE';
149
+ return report;
150
+ };
151
+ if (reasons.length) return finish([], {});
152
+
153
+ const folder = path.join(dir, 'test', 'guardefi');
154
+ if (fs.existsSync(folder)) throw new Error('The project already has test/guardefi, which verification needs.');
155
+ fs.mkdirSync(folder, { recursive: true });
156
+ const written = {};
157
+ const write = ({ file, source }) => { written[file] = source; fs.writeFileSync(path.join(folder, file), source); };
158
+ if (anyStateOnly) {
159
+ if (immutables.length) reasons.push('immutables need a project adapter that deploys the contract');
160
+ adapter = synthesizeAdapter(properties, artifact.deployedBytecode.object);
161
+ report.digests.adapter = sha(adapter);
162
+ }
163
+ if (reasons.length) return finish([], {});
164
+ const maps = emitMaps(properties, words, { hex: artifact.deployedBytecode.object, immutables });
165
+ fs.writeFileSync(path.join(folder, 'GuardefiAdapter.sol'), adapter);
166
+ // The checks are only meaningful for the files they were built from: anything that rewrites the adapter
167
+ // or harness between stages (and so could deploy a different runtime) makes the result unsupported.
168
+ const tampered = () => {
169
+ const files = { 'GuardefiAdapter.sol': adapter, ...written };
170
+ return Object.entries(files).some(([file, source]) => {
171
+ try { return fs.readFileSync(path.join(folder, file), 'utf8') !== source; } catch { return true; }
172
+ });
173
+ };
174
+ const TAMPERED = 'the adapter target runtime differs from the built contract: verification files changed during the run';
175
+ write(emitBase(properties));
176
+ write(maps);
177
+ if (!await build()) return finish([], {});
178
+ const mapResults = await solve('GuardefiMaps');
179
+ if (tampered()) reasons.push(TAMPERED);
180
+ const target = checkerStatus(own(mapResults, 'check_target'));
181
+ if (target === 'violated') reasons.push('the adapter target runtime differs from the built contract');
182
+ const located = new Map();
183
+ const failures = new Map();
184
+ for (const signature of new Set(properties.flatMap(property => property.grants.map(({ getter }) => getter.signature)))) {
185
+ const tried = maps.checks.filter(check => check.getter === signature).map(check => ({ check, status: checkerStatus(own(mapResults, check.name)) }));
186
+ const found = tried.filter(({ status }) => status === 'proven');
187
+ if (found.length === 1) located.set(signature, found[0].check);
188
+ else if (found.length || tried.every(({ status }) => status === 'violated')) failures.set(signature, `no single declared variable is proven to back ${signature}`);
189
+ }
190
+ const signatures = property => [...new Set(property.grants.map(({ getter }) => getter.signature))];
191
+ const perBehavior = property => ({
192
+ reasons: signatures(property).filter(name => failures.has(name)).map(name => failures.get(name)),
193
+ blocked: target !== 'proven' || signatures(property).some(name => !located.has(name)),
194
+ maps: Object.fromEntries(signatures(property).filter(name => located.has(name)).map(name => [name, located.get(name).field.label])),
195
+ });
196
+ const checks = emitChecks(properties, words, located);
197
+ const foundry = emitFoundry(properties);
198
+ const expected = [...checks.checks, ...(anyStateOnly ? [] : foundry.checks)].filter(inMode);
199
+ if (reasons.length || properties.every(property => perBehavior(property).blocked)) return finish(expected, {}, perBehavior);
200
+
201
+ write(checks);
202
+ write(foundry);
203
+ report.digests.harness = sha(canonical(written));
204
+ if (!await build()) return finish(expected, {}, perBehavior);
205
+ const halmosResults = await solve('GuardefiChecks');
206
+ if (tampered() && !reasons.includes(TAMPERED)) reasons.push(TAMPERED);
207
+ if (anyStateOnly || reasons.length) return finish(expected, halmosResults, perBehavior);
208
+ const { code, interrupted, stdout, stderr } = await tools.run('forge',
209
+ ['test', '--root', dir, '--out', 'out', '--match-contract', '^GuardefiFoundry$', '--fuzz-seed', '1', '--json'], execOptions);
210
+ const concrete = interrupted ? {} : foundryResults(stdout);
211
+ if (tampered()) { reasons.push(TAMPERED); return finish(expected, halmosResults, perBehavior); }
212
+ if (interrupted || (code !== 0 && !Object.values(concrete).some(result => result.exitcode === 1))) {
213
+ const message = interrupted ? 'Foundry was interrupted.' : `Foundry exited with code ${code}.`;
214
+ report.notes.push(`${message} ${stderr.trim().slice(0, 4000)}`.trim());
215
+ return finish(expected, halmosResults, perBehavior);
216
+ }
217
+ return finish(expected, Object.assign(Object.create(null), halmosResults, concrete), perBehavior);
218
+ } finally {
219
+ fs.rmSync(dir, { recursive: true, force: true });
220
+ }
221
+ }
222
+
223
+ module.exports = { verifyBehaviors, reduceStatus, proven };
@@ -0,0 +1,149 @@
1
+ // Deterministic, read-only backend for a bounded subset of @isl-lang/parser's entity invariants.
2
+ const { parse } = require('./vendor/isl-parser.cjs');
3
+
4
+ const COMPILER = 'guardefi.isl-evm-getters.v1';
5
+ const ops = new Map(Object.entries({ '==': 'eq', '!=': 'ne', '<': 'lt', '<=': 'le', '>': 'gt', '>=': 'ge' }));
6
+ const identifier = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
7
+
8
+ // Bound parser cost and reject every out-of-profile token or clause, including
9
+ // declaration metadata that a general-purpose parser might normalize away.
10
+ function profileTokens(source) {
11
+ if (typeof source !== 'string' || !source.length || source.length > 24 * 1024 || new TextEncoder().encode(source).length > 24 * 1024) {
12
+ throw new Error('Choose an ISL source file of 1–24576 bytes.');
13
+ }
14
+ const scan = /\s+|\/\/[^\r\n]*|"[0-9]+\.[0-9]+\.[0-9]+"|[A-Za-z_][A-Za-z0-9_]*|[0-9]+|==|!=|<=|>=|[{}:<>-]/gy;
15
+ const tokens = [];
16
+ while (scan.lastIndex < source.length) {
17
+ const i = scan.lastIndex;
18
+ const token = scan.exec(source)?.[0];
19
+ if (!token) throw new Error('Unsupported ISL syntax at character ' + (i + 1) + '.');
20
+ if (!/^\s|^\/\//.test(token)) tokens.push(token);
21
+ if (tokens.length > 768) throw new Error('ISL source exceeds this profile’s token limit.');
22
+ }
23
+ return tokens;
24
+ }
25
+
26
+ function parseISL(source) {
27
+ const tokens = profileTokens(source);
28
+ let cursor = 0;
29
+ function take(value) {
30
+ if (tokens[cursor++] !== value) throw new Error('Expected ' + value + ' in the ISL getter profile.');
31
+ }
32
+ function name() {
33
+ const value = tokens[cursor++];
34
+ if (typeof value !== 'string' || !identifier.test(value)) throw new Error('Expected an ISL identifier up to 64 characters.');
35
+ return value;
36
+ }
37
+ take('domain');
38
+ const domain = name();
39
+ take('{');
40
+ take('version');
41
+ take(':');
42
+ const version = tokens[cursor++]?.match(/^"((?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8}))"$/)?.[1];
43
+ if (!version) throw new Error('Use an explicit quoted major.minor.patch version.');
44
+ take('entity');
45
+ const entity = name();
46
+ take('{');
47
+ const fields = new Map();
48
+ while (tokens[cursor] !== 'invariants') {
49
+ const key = name();
50
+ take(':');
51
+ const type = tokens[cursor++];
52
+ if (!['Int', 'Boolean'].includes(type)) throw new Error('Getter fields support Int and Boolean.');
53
+ if (fields.has(key) || fields.size >= 32) throw new Error('Declare up to 32 distinct getter fields.');
54
+ fields.set(key, type);
55
+ }
56
+ take('invariants');
57
+ take('{');
58
+ const properties = [];
59
+ const ids = new Set();
60
+ const constrained = new Set();
61
+ while (tokens[cursor] !== '}') {
62
+ take('-');
63
+ const field = name();
64
+ const op = tokens[cursor++];
65
+ const literal = tokens[cursor++];
66
+ if (!fields.has(field) || !ops.has(op)) throw new Error('Use a declared getter and a supported comparison operator.');
67
+ const kind = fields.get(field) === 'Int' ? 'uint' : 'bool';
68
+ if (kind === 'uint' && (!/^(0|[1-9][0-9]{0,15})$/.test(literal) || !Number.isSafeInteger(Number(literal)))) {
69
+ throw new Error('Int predicates require an exact nonnegative decimal literal up to 9007199254740991.');
70
+ }
71
+ if (kind === 'bool' && (!['true', 'false'].includes(literal) || !['==', '!='].includes(op))) {
72
+ throw new Error('Boolean predicates compare true or false using == or !=.');
73
+ }
74
+ const id = [domain, entity, field, ops.get(op)].join('.');
75
+ if (ids.has(id) || properties.length >= 64) throw new Error('Use up to 64 distinct getter/operator predicates.');
76
+ constrained.add(field);
77
+ ids.add(id);
78
+ properties.push({ id, field, signature: field + '()', op, literal, kind });
79
+ }
80
+ take('}'); take('}'); take('}');
81
+ if (cursor !== tokens.length) throw new Error('Additional ISL declarations are outside the supported profile.');
82
+ if (!properties.length || constrained.size !== fields.size) throw new Error('Every declared getter needs a supported invariant.');
83
+
84
+ const parsed = parse(source, 'constitution.isl');
85
+ if (!parsed.success) throw new Error('ISL parser rejected the source: ' + (parsed.errors[0]?.message || 'invalid domain'));
86
+ const ast = parsed.domain;
87
+ const actual = ast.entities[0];
88
+ if (ast.name.name !== domain || ast.version.value !== version || actual?.name.name !== entity ||
89
+ actual.fields.length !== fields.size || actual.fields.some(item => fields.get(item.name.name) !== item.type?.name) ||
90
+ actual.invariants.length !== properties.length || !actual.invariants.every((item, index) => {
91
+ const property = properties[index];
92
+ return item.kind === 'BinaryExpr' && item.operator === property.op && item.left.kind === 'Identifier' &&
93
+ item.left.name === property.field && item.right.kind === (property.kind === 'uint' ? 'NumberLiteral' : 'BooleanLiteral') &&
94
+ String(item.right.value) === property.literal;
95
+ })) throw new Error('Unsupported ISL expression. Place each getter invariant on its own line.');
96
+ return { domain, version, entity, properties };
97
+ }
98
+
99
+ function bind(property, abi) {
100
+ const rows = abi.filter(item => item?.type === 'function' && item.name === property.field && Array.isArray(item.inputs) && !item.inputs.length);
101
+ const fn = rows[0];
102
+ if (rows.length !== 1 || !['view', 'pure'].includes(fn?.stateMutability) || !Array.isArray(fn.outputs) || fn.outputs.length !== 1) {
103
+ throw new Error('Expected one read-only, single-output ABI binding for ' + property.signature + '.');
104
+ }
105
+ const abiType = fn.outputs[0]?.type;
106
+ if (property.kind === 'bool') {
107
+ if (abiType !== 'bool') throw new Error(property.signature + ' requires a bool ABI output.');
108
+ } else {
109
+ const bits = Number(typeof abiType === 'string' && /^uint([1-9][0-9]{0,2})$/.exec(abiType)?.[1]);
110
+ if (!(bits >= 8 && bits <= 256 && bits % 8 === 0)) throw new Error(property.signature + ' requires a canonical uintN ABI output.');
111
+ if (BigInt(property.literal) >= 2n ** BigInt(bits)) throw new Error('Literal exceeds the range of ' + abiType + ' for ' + property.signature + '.');
112
+ }
113
+ return { ...property, abiType };
114
+ }
115
+
116
+ function emit(target, properties) {
117
+ const foundry = target === 'foundry';
118
+ const contract = foundry ? 'GuardefiFoundry' : 'GuardefiHalmos';
119
+ const prefix = foundry ? 'test' : 'check';
120
+ const lines = [
121
+ '// SPDX-License-Identifier: MIT', 'pragma solidity ^0.8.20;', '',
122
+ '// Extend this harness in an isolated project and bind the target to a concrete fixture.',
123
+ 'abstract contract ' + contract + ' {',
124
+ ' function _guardefiTarget() internal view virtual returns (address);', '',
125
+ ' function _guardefiRead(bytes4 selector) private view returns (uint256 word) {',
126
+ ' (bool ok, bytes memory result) = _guardefiTarget().staticcall(abi.encodeWithSelector(selector));',
127
+ ' assert(ok && result.length == 32);',
128
+ ' assembly { word := mload(add(result, 32)) }', ' }',
129
+ ];
130
+ properties.forEach((p, index) => {
131
+ const bound = p.kind === 'bool' ? '1' : 'type(' + p.abiType + ').max';
132
+ const value = p.kind === 'bool' ? (p.literal === 'true' ? '1' : '0') : p.literal;
133
+ lines.push('', ' // ' + p.id, ' function ' + prefix + '_isl_' + (index + 1) + '() public view {',
134
+ ' uint256 word = _guardefiRead(bytes4(keccak256("' + p.signature + '")));',
135
+ ' assert(word <= ' + bound + ');', ' assert(word ' + p.op + ' ' + value + ');', ' }');
136
+ });
137
+ const source = [...lines, '}', ''].join('\n');
138
+ return { target, file: contract + '.sol', source };
139
+ }
140
+
141
+ function generateISL(source, abi) {
142
+ const ir = parseISL(source);
143
+ if (!Array.isArray(abi) || abi.length > 4096) throw new Error('Supply a contract ABI with at most 4096 entries.');
144
+ const properties = ir.properties.map(property => bind(property, abi));
145
+ return { ...ir, properties, compiler: COMPILER,
146
+ artifacts: ['foundry', 'halmos'].map(target => emit(target, properties)) };
147
+ }
148
+
149
+ module.exports = { COMPILER, parseISL, generateISL };
@@ -0,0 +1,38 @@
1
+ # ISL parser
2
+
3
+ `isl-parser.cjs` bundles the recursive-descent parser from WholeStack Core,
4
+ commit `39a38218209ce1df5652cc9259c040e4d87f609f`, package
5
+ `@isl-lang/parser` version 1.0.0. The upstream package lists the ISL Team as
6
+ author and MIT as its license. The bundle exposes only `parse`. Guardefi
7
+ validates its restricted EVM profile before invoking this parser and checks
8
+ the resulting AST before generating Solidity.
9
+
10
+ Rebuild from that upstream checkout with esbuild 0.25.12:
11
+
12
+ ```sh
13
+ echo 'export {parse} from "./packages/isl/parser/src/parser.ts"' |
14
+ esbuild --bundle --platform=node --format=cjs --target=node22 \
15
+ --sourcefile=guardefi-isl-entry.ts --outfile=isl-parser.cjs
16
+ ```
17
+
18
+ ## MIT License
19
+
20
+ Copyright ISL Team
21
+
22
+ Permission is hereby granted, free of charge, to any person obtaining a copy
23
+ of this software and associated documentation files (the "Software"), to deal
24
+ in the Software without restriction, including without limitation the rights
25
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
26
+ copies of the Software, and to permit persons to whom the Software is
27
+ furnished to do so, subject to the following conditions:
28
+
29
+ The above copyright notice and this permission notice shall be included in all
30
+ copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38
+ SOFTWARE.