@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,114 @@
1
+ // Prove a Hardhat project with the Foundry toolchain without touching it.
2
+ // The project's contracts/, test/, spec/ (and lib/, remappings.txt) are copied
3
+ // into a temporary Foundry workspace at the same relative paths, so forge sees
4
+ // the source names Hardhat compiles (contracts/X.sol). When Hardhat 2 artifacts
5
+ // exist, the compiler settings come from the candidate's build-info, and every
6
+ // contract compared must have the same runtime code in both builds, or the
7
+ // proof is refused: GuardeFi never proves code other than what Hardhat built.
8
+ const fs = require('node:fs');
9
+ const os = require('node:os');
10
+ const path = require('node:path');
11
+
12
+ const CONFIGS = ['hardhat.config.js', 'hardhat.config.ts', 'hardhat.config.cjs', 'hardhat.config.mjs'];
13
+ // ponytail: Hardhat's default paths only (sources: contracts, artifacts: artifacts); custom paths in the config are not read.
14
+ const SOURCES = 'contracts';
15
+
16
+ const isHardhat = (dir) => !fs.existsSync(path.join(dir, 'foundry.toml')) && CONFIGS.some((f) => fs.existsSync(path.join(dir, f)));
17
+ const toml = (v) => JSON.stringify(v);
18
+
19
+ /** Hardhat 2 artifact (hh-sol-artifact-1) and its build-info for a contract name, or null when not built. */
20
+ function hardhatArtifact(dir, name) {
21
+ const root = path.join(dir, 'artifacts', SOURCES);
22
+ const hits = [];
23
+ const walk = (d) => {
24
+ if (!fs.existsSync(d)) return;
25
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
26
+ const p = path.join(d, e.name);
27
+ if (e.isDirectory()) walk(p);
28
+ else if (e.name === `${name}.json`) hits.push(p);
29
+ }
30
+ };
31
+ walk(root);
32
+ if (!hits.length) return null;
33
+ if (hits.length > 1) throw new Error(`refusing Hardhat proof: ${hits.length} Hardhat artifacts are named ${name}`);
34
+ const artifact = JSON.parse(fs.readFileSync(hits[0], 'utf8'));
35
+ if (artifact._format !== 'hh-sol-artifact-1' || typeof artifact.deployedBytecode !== 'string') {
36
+ throw new Error(`refusing Hardhat proof: ${path.relative(dir, hits[0])} is not a Hardhat 2 artifact`);
37
+ }
38
+ const dbg = hits[0].replace(/\.json$/, '.dbg.json');
39
+ const buildInfo = fs.existsSync(dbg) ? path.resolve(path.dirname(dbg), JSON.parse(fs.readFileSync(dbg, 'utf8')).buildInfo) : null;
40
+ return { file: hits[0], artifact, buildInfo: buildInfo && fs.existsSync(buildInfo) ? buildInfo : null };
41
+ }
42
+
43
+ /** foundry.toml lines reproducing a Hardhat build-info's compiler settings. Unmapped settings refuse. */
44
+ function settingsOf(buildInfoFile) {
45
+ const info = JSON.parse(fs.readFileSync(buildInfoFile, 'utf8'));
46
+ const s = info.input?.settings || {};
47
+ if (!info.solcVersion) throw new Error('refusing Hardhat proof: the build-info does not name its solc version');
48
+ if (s.optimizer?.details || Object.keys(s.libraries || {}).length || s.modelChecker) {
49
+ throw new Error('refusing Hardhat proof: the build-info uses compiler settings GuardeFi cannot reproduce with forge (optimizer details, libraries or model checker)');
50
+ }
51
+ return [
52
+ `solc = ${toml(info.solcVersion)}`,
53
+ `optimizer = ${Boolean(s.optimizer?.enabled)}`,
54
+ `optimizer_runs = ${Number(s.optimizer?.runs ?? 200)}`,
55
+ ...(s.evmVersion ? [`evm_version = ${toml(s.evmVersion)}`] : []),
56
+ `via_ir = ${s.viaIR === true}`,
57
+ `bytecode_hash = ${toml(s.metadata?.bytecodeHash ?? 'ipfs')}`,
58
+ `cbor_metadata = ${s.metadata?.appendCBOR !== false}`,
59
+ `remappings = ${toml(s.remappings || [])}`,
60
+ ];
61
+ }
62
+
63
+ /**
64
+ * A temporary Foundry workspace for a Hardhat project. `names` are the contracts
65
+ * that will be proven: the first with a Hardhat artifact supplies the settings.
66
+ * Returns { root, project, crossCheck(names), cleanup() }.
67
+ */
68
+ function hardhatWorkspace(dir, names = []) {
69
+ if (!fs.existsSync(path.join(dir, SOURCES))) throw new Error(`Hardhat project has no ${SOURCES}/ folder`);
70
+ const built = Object.fromEntries(names.filter(Boolean).map((n) => [n, hardhatArtifact(dir, n)]));
71
+ const reference = Object.values(built).find((b) => b?.buildInfo);
72
+ if (Object.values(built).some(Boolean) && !reference) throw new Error('refusing Hardhat proof: Hardhat artifacts exist but their build-info is missing; recompile with Hardhat');
73
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'guardefi-hardhat-'));
74
+ try {
75
+ for (const part of [SOURCES, 'test', 'spec']) {
76
+ if (fs.existsSync(path.join(dir, part))) fs.cpSync(path.join(dir, part), path.join(root, part), { recursive: true, dereference: true });
77
+ }
78
+ if (fs.existsSync(path.join(dir, 'remappings.txt'))) fs.copyFileSync(path.join(dir, 'remappings.txt'), path.join(root, 'remappings.txt'));
79
+ const libs = [];
80
+ for (const lib of ['lib', 'node_modules']) {
81
+ if (fs.existsSync(path.join(dir, lib))) { fs.symlinkSync(path.join(dir, lib), path.join(root, lib)); libs.push(lib); }
82
+ }
83
+ fs.writeFileSync(path.join(root, 'foundry.toml'), [
84
+ '[profile.default]', `src = ${toml(SOURCES)}`, 'test = "test"', 'out = "out"', `libs = ${toml(libs)}`, 'ast = true',
85
+ ...(reference ? settingsOf(reference.buildInfo) : []), '',
86
+ ].join('\n'));
87
+ } catch (error) {
88
+ fs.rmSync(root, { recursive: true, force: true });
89
+ throw error;
90
+ }
91
+ return {
92
+ root,
93
+ project: { kind: 'hardhat', settings: reference ? 'hardhat-build-info' : 'forge-defaults', artifacts: {} },
94
+ /** Compare forge's runtime code with Hardhat's for each name; throws on any difference. */
95
+ crossCheck(forgeArtifacts) {
96
+ const out = {};
97
+ for (const [name, forge] of Object.entries(forgeArtifacts)) {
98
+ const hh = built[name];
99
+ if (!hh) { out[name] = 'no-hardhat-artifact'; continue; }
100
+ const a = String(forge.deployedBytecode?.object || '').toLowerCase().replace(/^0x/, '');
101
+ const b = hh.artifact.deployedBytecode.toLowerCase().replace(/^0x/, '');
102
+ if (!a || a !== b) {
103
+ throw new Error(`refusing Hardhat proof: forge's build of ${name} differs from Hardhat's artifact ${path.relative(dir, hh.file)}; ` +
104
+ 'the proof would not be about the code Hardhat built (stale artifacts or a compiler setting forge does not reproduce)');
105
+ }
106
+ out[name] = 'matches-hardhat-artifact';
107
+ }
108
+ return out;
109
+ },
110
+ cleanup() { fs.rmSync(root, { recursive: true, force: true }); },
111
+ };
112
+ }
113
+
114
+ module.exports = { isHardhat, hardhatWorkspace };
@@ -0,0 +1,169 @@
1
+ const { parse } = require('./vendor/isl-parser.cjs');
2
+
3
+ const COMPILER = 'guardefi.isl-evm-behaviors.v2';
4
+ const namePattern = '[A-Za-z_][A-Za-z0-9_]{0,63}';
5
+ const identifier = new RegExp(`^${namePattern}$`);
6
+ const domainPattern = new RegExp(`^\\s*domain\\s+${namePattern}\\s*\\{\\s*version\\s*:\\s*"(?:0|[1-9][0-9]{0,8})(?:\\.(?:0|[1-9][0-9]{0,8})){2}"([\\s\\S]*)\\}\\s*$`);
7
+ const inputType = { Address: 'address', Boolean: 'bool', Int: 'uint' };
8
+ const comparisons = ['==', '!=', '<', '<=', '>', '>='];
9
+
10
+ function parseBehaviors(source) {
11
+ if (typeof source !== 'string' || !source.length || Buffer.byteLength(source) > 24 * 1024) {
12
+ throw new Error('Choose an ISL source file of 1–24576 bytes.');
13
+ }
14
+ const clean = source.replace(/\/\/[^\r\n]*/g, '');
15
+ const body = domainPattern.exec(clean)?.[1].trim();
16
+ if (!body) throw new Error('Expected one explicitly versioned ISL domain with behavior declarations.');
17
+ // The upstream parser normalizes some clauses and overwrites duplicates. Check
18
+ // the declaration shape before trusting its AST to represent every obligation.
19
+ const declaration = new RegExp(`behavior\\s+(${namePattern})\\s*\\{\\s*input\\s*\\{([^{}]*)\\}\\s*pre\\s*\\{([^{}]*)\\}\\s*post\\s+success\\s*\\{([^{}]*)\\}\\s*(?:invariants\\s*\\{([^{}]*)\\}\\s*)?\\}\\s*`, 'gy');
20
+ const fields = new RegExp(`^(?:\\s*${namePattern}\\s*:\\s*(?:Address|Boolean|Int)){0,4}\\s*$`);
21
+ const shapes = [];
22
+ while (declaration.lastIndex < body.length) {
23
+ const block = declaration.exec(body);
24
+ if (!block || !fields.test(block[2]) || shapes.length === 8) {
25
+ throw new Error('Use up to eight distinct behaviors with input, pre, post success and optional invariants blocks in order.');
26
+ }
27
+ const counts = block.slice(3).map((section) => {
28
+ if (section === undefined) return 0;
29
+ const lines = section.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
30
+ if (!lines.length || lines.length > 8 || lines.some(line => line.length > 240 ||
31
+ !/^-\s+[A-Za-z0-9_(),<>=!+\- \t]+$/.test(line) || (line.match(/\(/g) || []).length > 10)) {
32
+ throw new Error('Write one to eight supported predicates on separate bulleted lines per pre, post or invariants block.');
33
+ }
34
+ return lines.length;
35
+ });
36
+ shapes.push({ name: block[1], counts });
37
+ }
38
+ if (!shapes.length || new Set(shapes.map(shape => shape.name)).size !== shapes.length) {
39
+ throw new Error('Declare at least one behavior and give each a unique name.');
40
+ }
41
+ const parsed = parse(clean, 'behavior.isl');
42
+ if (!parsed.success) throw new Error('ISL parser rejected the source: ' + (parsed.errors[0]?.message || 'invalid domain'));
43
+ const { domain } = parsed;
44
+ if (domain.behaviors.length !== shapes.length || !domain.behaviors.every((behavior, index) =>
45
+ behavior.name.name === shapes[index].name && behavior.preconditions.length === shapes[index].counts[0] &&
46
+ behavior.postconditions.length === 1 && behavior.postconditions[0].condition === 'success' &&
47
+ behavior.postconditions[0].predicates.length === shapes[index].counts[1] &&
48
+ behavior.invariants.length === shapes[index].counts[2])) {
49
+ throw new Error('ISL parser did not preserve every behavior predicate.');
50
+ }
51
+ return domain;
52
+ }
53
+
54
+ function scalarKind(type) {
55
+ if (type === 'address' || type === 'bool') return type;
56
+ const width = Number(typeof type === 'string' && /^uint([1-9][0-9]{0,2})$/.exec(type)?.[1]);
57
+ if (width >= 8 && width <= 256 && width % 8 === 0) return 'uint';
58
+ return null;
59
+ }
60
+
61
+ function bindBehavior(domain, behavior, abi) {
62
+ const name = behavior.name.name;
63
+ const candidates = abi.filter(row => row?.type === 'function' && row.name === name);
64
+ const [fn] = candidates;
65
+ const fields = behavior.input.fields;
66
+ if (candidates.length !== 1 || fn.stateMutability !== 'nonpayable' || !Array.isArray(fn.inputs) ||
67
+ !Array.isArray(fn.outputs) || fn.outputs.length > 1 || (fn.outputs.length === 1 && fn.outputs[0]?.type !== 'bool') ||
68
+ fn.inputs.length !== fields.length) {
69
+ throw new Error(`${name} needs one unambiguous nonpayable ABI function returning nothing or bool.`);
70
+ }
71
+ const inputs = new Map([['caller', { kind: 'input', type: 'address', index: 0 }]]);
72
+ const args = fields.map((field, index) => {
73
+ const key = field.name.name;
74
+ const declared = field.type.kind === 'ReferenceType' && field.type.name.parts.length === 1
75
+ ? field.type.name.parts[0].name : field.type.name;
76
+ const type = fn.inputs[index]?.type;
77
+ if (inputs.has(key) || !Object.hasOwn(inputType, declared) || scalarKind(type) !== inputType[declared]) {
78
+ throw new Error(`${name} input ${key} needs a unique name and a matching scalar ABI type.`);
79
+ }
80
+ inputs.set(key, { kind: 'input', type, index: index + 1 });
81
+ return { name: key, type };
82
+ });
83
+ const snapshots = [];
84
+ const arithmetic = new Set();
85
+
86
+ function getter(node) {
87
+ if (node.kind !== 'CallExpr' || node.callee.kind !== 'Identifier' || !identifier.test(node.callee.name) || node.arguments.length > 4) {
88
+ throw new Error(`${name} expects a scalar getter call.`);
89
+ }
90
+ const params = node.arguments.map((arg) => {
91
+ if (arg.kind !== 'Identifier' || !inputs.has(arg.name)) throw new Error(`${name} getter arguments must be caller or declared inputs.`);
92
+ return inputs.get(arg.name);
93
+ });
94
+ const argTypes = params.map(param => param.type);
95
+ const signature = `${node.callee.name}(${argTypes.join(',')})`;
96
+ const rows = abi.filter(row => row?.type === 'function' && row.name === node.callee.name &&
97
+ Array.isArray(row.inputs) && row.inputs.length === params.length && row.inputs.every((item, i) => item?.type === argTypes[i]));
98
+ const [row] = rows;
99
+ const type = row?.outputs?.[0]?.type;
100
+ if (rows.length !== 1 || !['view', 'pure'].includes(row.stateMutability) || !Array.isArray(row.outputs) ||
101
+ row.outputs.length !== 1 || !scalarKind(type)) {
102
+ throw new Error(`${name} needs one read-only single-scalar ABI getter for ${signature}.`);
103
+ }
104
+ return { kind: 'getter', type, signature, params };
105
+ }
106
+
107
+ // What an operand may use: live state, pre-call snapshots, one addition or subtraction.
108
+ function value(node, allow) {
109
+ if (node.kind === 'Identifier' && inputs.has(node.name)) return inputs.get(node.name);
110
+ if (node.kind === 'CallExpr' && allow.state) return getter(node);
111
+ if (node.kind === 'BooleanLiteral') return { kind: 'literal', type: 'bool', word: node.value ? '1' : '0' };
112
+ if (node.kind === 'NumberLiteral' && Number.isSafeInteger(node.value) && node.value >= 0) {
113
+ return { kind: 'literal', type: 'uint256', word: String(node.value) };
114
+ }
115
+ if (allow.old && node.kind === 'OldExpr') {
116
+ const read = getter(node.expression);
117
+ const index = snapshots.length;
118
+ snapshots.push(read);
119
+ return { kind: 'snapshot', type: read.type, index };
120
+ }
121
+ if (allow.arithmetic && node.kind === 'BinaryExpr' && ['+', '-'].includes(node.operator)) {
122
+ const left = value(node.left, { ...allow, arithmetic: false });
123
+ const right = value(node.right, { ...allow, arithmetic: false });
124
+ if (scalarKind(left.type) === 'uint' && scalarKind(right.type) === 'uint') {
125
+ const op = node.operator === '+' ? 'add' : 'sub';
126
+ if (allow.old) arithmetic.add(op);
127
+ return { kind: op, type: 'uint256', left, right };
128
+ }
129
+ }
130
+ throw new Error(`${name} has an unsupported behavior operand.`);
131
+ }
132
+
133
+ function predicate(node, allow) {
134
+ if (allow.implies && node.kind === 'BinaryExpr' && node.operator === 'implies') {
135
+ const when = predicate(node.left, {});
136
+ return { ...predicate(node.right, { ...allow, implies: false }), when };
137
+ }
138
+ if (node.kind !== 'BinaryExpr' || !comparisons.includes(node.operator)) throw new Error(`${name} predicates must be scalar comparisons.`);
139
+ let left = value(node.left, allow);
140
+ let right = value(node.right, allow);
141
+ const zero = (literal, other) => literal.kind === 'literal' && literal.type === 'uint256' && literal.word === '0' && other.type === 'address'
142
+ ? { ...literal, type: 'address' } : literal;
143
+ [left, right] = [zero(left, right), zero(right, left)];
144
+ const kind = scalarKind(left.type);
145
+ if (kind !== scalarKind(right.type) || (kind !== 'uint' && !['==', '!='].includes(node.operator))) {
146
+ throw new Error(`${name} predicate operands and comparison operator must agree in type.`);
147
+ }
148
+ return { left, op: node.operator, right };
149
+ }
150
+
151
+ const readsLive = (item) => item.kind === 'getter' || ['left', 'right'].some(side => item[side] && readsLive(item[side]));
152
+ const pre = behavior.preconditions.map(node => predicate(node, { state: true }));
153
+ const post = behavior.postconditions[0].predicates.map(node => predicate(node, { state: true, old: true, arithmetic: true, implies: true }));
154
+ const assumptions = behavior.invariants.map(node => predicate(node, { state: true, arithmetic: true, implies: true }));
155
+ // A post equality that fixes one getter is the only thing that lets storage change.
156
+ const grants = post.filter(({ left, op, right }) => op === '==' && left.kind === 'getter' && !readsLive(right))
157
+ .map(({ left, when }) => ({ getter: left, when: when || null }));
158
+ return { id: `${domain}.${name}`, name, signature: `${name}(${args.map(arg => arg.type).join(',')})`,
159
+ inputs: args, returns: fn.outputs.length ? 'bool' : 'void', pre, post, assumptions, grants, snapshots, arithmetic: [...arithmetic] };
160
+ }
161
+
162
+ function generateBehaviors(source, abi) {
163
+ const domain = parseBehaviors(source);
164
+ if (!Array.isArray(abi) || abi.length > 4096) throw new Error('Supply a contract ABI with at most 4096 entries.');
165
+ const { name } = domain.name;
166
+ return domain.behaviors.map(behavior => bindBehavior(name, behavior, abi));
167
+ }
168
+
169
+ module.exports = { COMPILER, generateBehaviors };
@@ -0,0 +1,267 @@
1
+ // Solidity for each verification stage. Halmos ignores arithmetic panics, so
2
+ // generated arithmetic is asserted or guarded, never left to checked operators.
3
+ const { candidates } = require('./behavior-storage');
4
+
5
+ const HEADER = ['// SPDX-License-Identifier: MIT', 'pragma solidity ^0.8.20;', ''];
6
+ const MAX = 'type(uint256).max';
7
+ const bound = type => ({ address: 'type(uint160).max', bool: '1' })[type] || `type(${type}).max`;
8
+ const literal = text => `uint256(${text})`;
9
+
10
+ /** A Solidity value as a 256-bit word. */
11
+ function asWord(type, text) {
12
+ if (type === 'address') return `uint256(uint160(${text}))`;
13
+ return type === 'bool' ? `(${text} ? uint256(1) : 0)` : `uint256(${text})`;
14
+ }
15
+
16
+ const encode = (signature, args) => `abi.encodeWithSelector(${[`bytes4(keccak256("${signature}"))`, ...args].join(', ')})`;
17
+ const input = ({ index }) => index === 0 ? 's.caller' : `s.arg${index}`;
18
+ const read = (getter, target) => `_guardefiRead(${target}, s.caller, ${encode(getter.signature, getter.params.map(input))}, ${bound(getter.type)})`;
19
+
20
+ function word(value, target) {
21
+ switch (value.kind) {
22
+ case 'input': return asWord(value.type, input(value));
23
+ case 'literal': return literal(value.word);
24
+ case 'getter': return read(value, target);
25
+ case 'snapshot': return `beforeCall[${value.index}]`;
26
+ default: return `_guardefi${value.kind === 'add' ? 'Add' : 'Sub'}(${word(value.left, target)}, ${word(value.right, target)})`;
27
+ }
28
+ }
29
+
30
+ const compare = ({ left, op, right }, target) => `${word(left, target)} ${op} ${word(right, target)}`;
31
+
32
+ /** An assumption: overflow makes it false instead of failing the check. */
33
+ function assumption({ when, left, op, right }) {
34
+ const fits = [left, right].filter(side => side.kind === 'add' || side.kind === 'sub')
35
+ .map(({ kind, left: a, right: b }) => kind === 'add' ? `${word(a, 'target')} <= ${MAX} - ${word(b, 'target')}` : `${word(b, 'target')} <= ${word(a, 'target')}`);
36
+ const holds = [...fits, compare({ left, op, right }, 'target')].join(' && ');
37
+ return when ? `(!(${compare(when)}) || (${holds}))` : `(${holds})`;
38
+ }
39
+
40
+ function emitBehavior(behavior, n) {
41
+ const args = behavior.inputs.map((_, i) => `s.arg${i + 1}`);
42
+ const input = `Behavior${n}Input`;
43
+ const count = behavior.snapshots.length;
44
+ return [
45
+ '', ` // ${behavior.id}`,
46
+ ` struct ${input} { ${['address caller', ...behavior.inputs.map(({ type }, i) => `${type} arg${i + 1}`)].join('; ')}; }`,
47
+ ` function _guardefiExample${n}() internal view virtual returns (${input} memory);`,
48
+ '', ` function _guardefiAllowed${n}(${input} memory s, address target) internal returns (bool allowed) {`,
49
+ ' allowed = true;',
50
+ ...behavior.pre.map(predicate => ` if (!(${compare(predicate, 'target')})) allowed = false;`),
51
+ ' }',
52
+ '', ` function _guardefiAssumed${n}(${input} memory s, address target) internal returns (bool assumed) {`,
53
+ ' assumed = true;',
54
+ ...behavior.assumptions.map(predicate => ` if (!${assumption(predicate)}) assumed = false;`),
55
+ ' }',
56
+ '', ` function _guardefiCall${n}(${input} memory s, address target) internal returns (bool ok, bytes memory returned) {`,
57
+ ` bytes memory data = ${encode(behavior.signature, args)};`,
58
+ ' vm.prank(s.caller);',
59
+ ' (ok, returned) = target.call(data);',
60
+ ' }',
61
+ '', ` function _guardefiSafety${n}(${input} memory s, address target, bool mustSucceed) internal {`,
62
+ ` bool allowed = _guardefiAllowed${n}(s, target);`,
63
+ ...(count ? [` uint256[${count}] memory beforeCall;`,
64
+ ...behavior.snapshots.map((getter, i) => ` beforeCall[${i}] = ${read(getter, 'target')};`)] : []),
65
+ ` (bool ok, bytes memory returned) = _guardefiCall${n}(s, target);`,
66
+ ' if (!ok) { assert(!mustSucceed); return; }',
67
+ ' assert(allowed);',
68
+ behavior.returns === 'bool'
69
+ ? ' assert(returned.length == 32 && abi.decode(returned, (uint256)) == 1);'
70
+ : ' assert(returned.length == 0);',
71
+ ...behavior.post.map(predicate => ` ${predicate.when ? `if (${compare(predicate.when)}) ` : ''}assert(${compare(predicate, 'target')});`),
72
+ ' }',
73
+ '', ` function _guardefiAvailable${n}(${input} memory s, address target) internal {`,
74
+ ` bool allowed = _guardefiAllowed${n}(s, target);`,
75
+ ` (bool ok,) = _guardefiCall${n}(s, target);`,
76
+ ' assert(!allowed || ok);',
77
+ ' }',
78
+ '', ` function _guardefiExampleCheck${n}() internal {`,
79
+ ` ${input} memory s = _guardefiExample${n}();`,
80
+ ' address target = _guardefiTarget();',
81
+ ` assert(_guardefiAssumed${n}(s, target));`,
82
+ ` assert(_guardefiAllowed${n}(s, target));`,
83
+ ` _guardefiSafety${n}(s, target, true);`,
84
+ ' }',
85
+ ];
86
+ }
87
+
88
+ function emitBase(properties) {
89
+ return { file: 'GuardefiBehaviorBase.sol', checks: [], source: [...HEADER,
90
+ 'interface GuardefiVm {',
91
+ ' function prank(address sender) external;',
92
+ ' function assume(bool condition) external;',
93
+ ' function etch(address target, bytes calldata code) external;',
94
+ ' function setArbitraryStorage(address target) external;',
95
+ ' function load(address target, bytes32 slot) external view returns (bytes32);',
96
+ '}', '',
97
+ 'abstract contract GuardefiBehaviorBase {',
98
+ ' GuardefiVm internal constant vm = GuardefiVm(address(uint160(uint256(keccak256("hevm cheat code")))));',
99
+ ' function _guardefiTarget() internal view virtual returns (address);',
100
+ '', ' function _guardefiRead(address target, address caller, bytes memory data, uint256 max) internal returns (uint256 value) {',
101
+ ' vm.prank(caller);',
102
+ ' (bool ok, bytes memory returned) = target.staticcall(data);',
103
+ ' assert(ok && returned.length == 32);',
104
+ ' value = abi.decode(returned, (uint256));',
105
+ ' assert(value <= max);',
106
+ ' }',
107
+ '', ' function _guardefiAdd(uint256 a, uint256 b) internal pure returns (uint256) {',
108
+ ` assert(b <= ${MAX} - a);`, ' return a + b;', ' }',
109
+ '', ' function _guardefiSub(uint256 a, uint256 b) internal pure returns (uint256) {',
110
+ ' assert(b <= a);', ' return a - b;', ' }',
111
+ ...properties.flatMap((behavior, i) => emitBehavior(behavior, i + 1)),
112
+ '}', ''].join('\n') };
113
+ }
114
+
115
+ // Slots are computed unchecked: hash plus offset wraps like the EVM does.
116
+ const SLOTS = [
117
+ '', ' function _guardefiAt(bytes32 base, uint256 offset) internal pure returns (bytes32) {',
118
+ ' unchecked { return bytes32(uint256(base) + offset); }', ' }',
119
+ '', ' function _guardefiLoad(address target, bytes32 slot) internal view returns (uint256) {',
120
+ ' return uint256(vm.load(target, slot));', ' }',
121
+ ];
122
+ // The deployed target keeps the values its constructor wrote even after its
123
+ // storage is made arbitrary, so any-state checks run on an untouched copy.
124
+ const FRESH = [
125
+ '', ' function _guardefiFresh() internal returns (address fresh) {',
126
+ ' address target = _guardefiTarget();',
127
+ ' assert(target.code.length != 0);',
128
+ ' fresh = address(uint160(0x00F12E5F12E5F12E5));',
129
+ ' assert(fresh != target && fresh.code.length == 0);',
130
+ ' vm.etch(fresh, target.code);',
131
+ ' vm.setArbitraryStorage(fresh);',
132
+ ' }',
133
+ ];
134
+
135
+ /** Storage slot of a word, given expressions for its mapping keys and data index. */
136
+ function slotOf({ slot, steps }, keys, index) {
137
+ let key = 0;
138
+ return steps.reduce((base, step) => {
139
+ if (step.kind === 'key') return `keccak256(abi.encode(${keys[key++]}, ${base}))`;
140
+ return step.kind === 'add' ? `_guardefiAt(${base}, ${step.n})` : `_guardefiAt(keccak256(abi.encode(${base})), ${index})`;
141
+ }, `bytes32(${literal(slot)})`);
142
+ }
143
+
144
+ const mask = size => `(${MAX} >> ${256 - 8 * size})`;
145
+
146
+ function decode({ offset, size, kind }, text) {
147
+ const value = `((${text} >> ${8 * offset}) & ${mask(size)})`;
148
+ return kind === 'bool' ? `(${value} != 0 ? uint256(1) : 0)` : value;
149
+ }
150
+
151
+ function emitMaps(properties, words, runtime) {
152
+ if (runtime.immutables.some(({ start, length }) => length !== 32 || !Number.isSafeInteger(start) || start < 0 || 2 * (start + 32) > runtime.hex.length - 2)) {
153
+ throw new Error('Unexpected immutable reference in the build artifact.');
154
+ }
155
+ const getters = new Map(properties.flatMap(property => property.grants.map(({ getter }) => [getter.signature, getter])));
156
+ const checks = [{ name: 'check_target', kind: 'target', startState: 'deployed' }];
157
+ const lines = [];
158
+ for (const [g, getter] of [...getters.values()].entries()) {
159
+ for (const [c, { word: location, field }] of candidates(getter, words).entries()) {
160
+ const name = `check_map_${g + 1}_${c + 1}`;
161
+ const params = getter.params.map(({ type }, i) => ({ type, name: `key${i}` }));
162
+ checks.push({ name, kind: 'map', startState: 'any', getter: getter.signature, word: location, field });
163
+ lines.push('', ` // ${getter.signature} reads ${field.label}`,
164
+ ` function ${name}(${['address caller', ...params.map(p => `${p.type} ${p.name}`)].join(', ')}) public {`,
165
+ ' address target = _guardefiFresh();',
166
+ ` uint256 value = _guardefiRead(target, caller, ${encode(getter.signature, params.map(p => p.name))}, ${bound(getter.type)});`,
167
+ ` uint256 stored = _guardefiLoad(target, ${slotOf(location, params.map(p => asWord(p.type, p.name)))});`,
168
+ ` assert(value == ${decode(field, 'stored')});`, ' }');
169
+ }
170
+ }
171
+ const clear = name => runtime.immutables.map(({ start }) => ` mstore(add(add(${name}, 0x20), ${start}), 0)`);
172
+ return { file: 'GuardefiMaps.sol', checks, source: [...HEADER,
173
+ 'import "./GuardefiBehaviorBase.sol";', 'import "./GuardefiAdapter.sol";', '',
174
+ 'contract GuardefiMaps is GuardefiAdapter {', ...SLOTS.slice(1), ...FRESH,
175
+ '', ' function check_target() public view {',
176
+ ' bytes memory actual = _guardefiTarget().code;',
177
+ ` bytes memory expected = hex"${runtime.hex.replace(/^0x/, '')}";`,
178
+ ' assert(actual.length == expected.length);',
179
+ ...(runtime.immutables.length ? [' assembly ("memory-safe") {', ...clear('actual'), ...clear('expected'), ' }'] : []),
180
+ ' assert(keccak256(actual) == keccak256(expected));', ' }',
181
+ ...lines, '}', ''].join('\n') };
182
+ }
183
+
184
+ function emitFrame(behavior, n, root, words, maps) {
185
+ const params = behavior.inputs.map(({ type }, i) => `${type} arg${i + 1}`);
186
+ // Words of one variable share symbolic keys by position and type.
187
+ const keys = [];
188
+ const located = words.filter(item => item.root === root).map((item) => {
189
+ const used = item.steps.filter(step => step.kind === 'key').map(({ type }, i) => {
190
+ let at = keys.findIndex(key => key.type === type && key.position === i);
191
+ if (at < 0) at = keys.push({ type, position: i }) - 1;
192
+ return `keys[${at}]`;
193
+ });
194
+ return { item, used, slot: slotOf(item, used, 'index') };
195
+ });
196
+ const indexed = located.some(({ item }) => item.steps.some(step => step.kind === 'data'));
197
+ const names = ['caller', ...behavior.inputs.map((_, i) => `arg${i + 1}`)];
198
+ const body = located.flatMap(({ item, used, slot }, w) => {
199
+ const granted = behavior.grants.flatMap(({ getter, when }) => {
200
+ const map = maps.get(getter.signature);
201
+ if (map?.word !== item) return [];
202
+ const matches = [...(when ? [compare(when)] : []), ...getter.params.map((param, i) => `${used[i]} == ${asWord(param.type, input(param))}`)];
203
+ const change = `changeable |= ${mask(map.field.size)} << ${8 * map.field.offset};`;
204
+ return [` ${matches.length ? `if (${matches.join(' && ')}) ` : ''}${change}`];
205
+ });
206
+ return [' {', ' uint256 changeable = 0;', ...granted,
207
+ ` assert((stored[${w}] | changeable) == (_guardefiLoad(target, ${slot}) | changeable));`, ' }'];
208
+ });
209
+ return ['', ` // ${behavior.id} changes nothing else in ${located[0].item.label}`,
210
+ ` function check_frame_${n}_${root}(${['address caller', ...params, ...keys.map(({ type }, i) => `${type} key${i}`), ...(indexed ? ['uint256 index'] : [])].join(', ')}) public {`,
211
+ ` uint256[] memory keys = new uint256[](${keys.length});`,
212
+ ...keys.map(({ type }, i) => ` keys[${i}] = ${asWord(type, `key${i}`)};`),
213
+ ` _guardefiFrame${n}_${root}(Behavior${n}Input(${names.join(', ')}), keys${indexed ? ', index' : ''});`, ' }',
214
+ '', ` function _guardefiFrame${n}_${root}(Behavior${n}Input memory s, uint256[] memory keys${indexed ? ', uint256 index' : ''}) private {`,
215
+ ...(keys.length ? [] : [' keys;']),
216
+ ' address target = _guardefiFresh();',
217
+ ` vm.assume(_guardefiAssumed${n}(s, target));`,
218
+ ...(indexed ? [' vm.assume(index < 2 ** 64);'] : []),
219
+ ` uint256[${located.length}] memory stored;`,
220
+ ...located.map(({ slot }, w) => ` stored[${w}] = _guardefiLoad(target, ${slot});`),
221
+ ` (bool ok,) = _guardefiCall${n}(s, target);`,
222
+ ' if (!ok) return;', ...body, ' }'];
223
+ }
224
+
225
+ function emitChecks(properties, words, maps) {
226
+ const roots = [...new Set(words.map(item => item.root))];
227
+ const checks = [];
228
+ const lines = properties.flatMap((behavior, i) => {
229
+ const n = i + 1;
230
+ const add = (name, kind, startState) => checks.push({ name, behavior: behavior.id, kind, startState });
231
+ const params = ['address caller', ...behavior.inputs.map(({ type }, j) => `${type} arg${j + 1}`)].join(', ');
232
+ const value = `Behavior${n}Input(${['caller', ...behavior.inputs.map((_, j) => `arg${j + 1}`)].join(', ')})`;
233
+ add(`check_safety_${n}`, 'safety', 'any');
234
+ for (const root of roots) add(`check_frame_${n}_${root}`, 'frame', 'any');
235
+ add(`check_available_${n}`, 'available', 'deployed');
236
+ add(`check_example_${n}`, 'example', 'deployed');
237
+ return ['', ` function check_safety_${n}(${params}) public {`,
238
+ ` Behavior${n}Input memory s = ${value};`,
239
+ ' address target = _guardefiFresh();',
240
+ ` vm.assume(_guardefiAssumed${n}(s, target));`,
241
+ ` _guardefiSafety${n}(s, target, false);`, ' }',
242
+ ...roots.flatMap(root => emitFrame(behavior, n, root, words, maps)),
243
+ '', ` function check_available_${n}(${params}) public { _guardefiAvailable${n}(${value}, _guardefiTarget()); }`,
244
+ '', ` function check_example_${n}() public { _guardefiExampleCheck${n}(); }`];
245
+ });
246
+ return { file: 'GuardefiChecks.sol', checks, source: [...HEADER,
247
+ 'import "./GuardefiBehaviorBase.sol";', 'import "./GuardefiAdapter.sol";', '',
248
+ 'contract GuardefiChecks is GuardefiAdapter {', ...SLOTS.slice(1), ...FRESH, ...lines, '}', ''].join('\n') };
249
+ }
250
+
251
+ function emitFoundry(properties) {
252
+ const checks = [];
253
+ const lines = properties.flatMap((behavior, i) => {
254
+ const n = i + 1;
255
+ const params = ['address caller', ...behavior.inputs.map(({ type }, j) => `${type} arg${j + 1}`)].join(', ');
256
+ const value = `Behavior${n}Input(${['caller', ...behavior.inputs.map((_, j) => `arg${j + 1}`)].join(', ')})`;
257
+ for (const kind of ['safety', 'available', 'example']) checks.push({ name: `test_${kind}_${n}`, behavior: behavior.id, kind, startState: 'deployed' });
258
+ return ['', ` function test_safety_${n}(${params}) public { _guardefiSafety${n}(${value}, _guardefiTarget(), false); }`,
259
+ '', ` function test_available_${n}(${params}) public { _guardefiAvailable${n}(${value}, _guardefiTarget()); }`,
260
+ '', ` function test_example_${n}() public { _guardefiExampleCheck${n}(); }`];
261
+ });
262
+ return { file: 'GuardefiFoundry.sol', checks, source: [...HEADER,
263
+ 'import "./GuardefiBehaviorBase.sol";', 'import "./GuardefiAdapter.sol";', '',
264
+ 'contract GuardefiFoundry is GuardefiAdapter {', ...lines.slice(1), '}', ''].join('\n') };
265
+ }
266
+
267
+ module.exports = { emitBase, emitMaps, emitChecks, emitFoundry };