@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,124 @@
1
+ const { createHash } = require('node:crypto');
2
+ const { canonical } = require('../canonical-json');
3
+ const registry = require('./assumptions.json');
4
+ const { CONTEXT } = require('./harness');
5
+ const { summarizeExternalEffects } = require('./external-effects');
6
+
7
+ const digest = (value) => createHash('sha256').update(canonical(value)).digest('hex');
8
+ const own = (object, key) => Object.hasOwn(object, key);
9
+ const supported = (basis) => ({ status: 'supported', basis });
10
+ const unresolved = (basis) => ({ status: 'unresolved', basis });
11
+
12
+ function inspectSemantics(analyses, { vault = false } = {}) {
13
+ const units = analyses.flat();
14
+ const complete = analyses.length === 2 && analyses.every((side) => side.length) && units.every((unit) => unit.complete);
15
+ const reads = [...new Set(units.flatMap((unit) => unit.blockReads))].sort();
16
+ const features = new Set(units.flatMap((unit) => unit.features));
17
+ const context = reads.filter((op) => own(CONTEXT, op));
18
+ const otherReads = reads.filter((op) => !own(CONTEXT, op));
19
+ const mutable = ['CALL', 'CALLCODE', 'CREATE', 'CREATE2'].filter((op) => features.has(op));
20
+ const staticFrame = features.has('STATICCALL');
21
+ // A static frame cannot write transitively, but can inspect intermediate
22
+ // state or return arbitrary data. Static calls still owe external evidence.
23
+ const delegated = features.has('DELEGATECALL') && (!complete ||
24
+ units.some((unit) => unit.delegatecalls.some((site) => !site.library)));
25
+ const isolated = complete && !mutable.length && !staticFrame && !delegated;
26
+ // Effectively callback-free: every unit leaves its state alone after the first
27
+ // call that can run foreign code, so a callback sees committed state and its
28
+ // effects equal a later transaction's. Static frames cannot write at all.
29
+ // Return data, external state and token semantics stay separate obligations.
30
+ const late = units.flatMap((unit) => unit.lateState || []);
31
+ const ordered = complete && !delegated && !features.has('CALLCODE') && units.every((unit) => Array.isArray(unit.lateState)) && !late.length;
32
+ const callbacks = isolated
33
+ ? supported('No reachable unbound invocation in the reviewed runtime and linked units.')
34
+ : ordered
35
+ ? supported(`Effectively callback-free: no reachable state access follows an external invocation (${[...mutable, ...(staticFrame ? ['STATICCALL'] : [])].join(', ')}) on any path.`)
36
+ : unresolved(!complete ? 'Bytecode reachability is incomplete.' :
37
+ [mutable.length && `Unbound mutable invocations: ${mutable.join(', ')}.`,
38
+ late.length && `State access after an external invocation: ${[...new Set(late.map(({ op, pc }) => `${op}@${pc}`))].slice(0, 8).join(', ')}.`,
39
+ staticFrame && 'STATICCALL forbids state writes within a static frame, but read-only callbacks and return data are unmodeled.',
40
+ delegated && 'DELEGATECALL can reach code without proven linked provenance.'].filter(Boolean).join(' '));
41
+ const accountReads = ['BALANCE', 'EXTCODESIZE', 'EXTCODECOPY', 'EXTCODEHASH', 'SELFDESTRUCT'].filter((op) => features.has(op));
42
+ return {
43
+ context,
44
+ features: [...features].sort(),
45
+ externalEffects: summarizeExternalEffects(analyses),
46
+ assumptions: {
47
+ analysis: complete ? supported('All analyzed runtime units completed reachability.') : unresolved('One or more runtime units lack complete reachability.'),
48
+ 'block-context': !complete || otherReads.length
49
+ ? unresolved(!complete ? 'Incomplete reachability leaves environmental reads unclassified.' : `Unsupported block inputs: ${otherReads.join(', ')}.`)
50
+ : context.length
51
+ ? supported(`The modeled calls share symbolic ${context.join(', ')}.`)
52
+ : supported('No reachable block reads in analyzed runtime units.'),
53
+ callbacks,
54
+ 'external-state': !isolated || accountReads.length
55
+ ? unresolved('External code, account observations or side effects are not bound by this run.')
56
+ : supported('No reachable external dependency or unbound account observation in analyzed runtimes.'),
57
+ delegatecall: features.has('DELEGATECALL') || features.has('CALLCODE')
58
+ ? unresolved('Delegated execution requires a live code and call-frame binding.')
59
+ : complete ? supported('No reachable delegated call in analyzed runtimes.') : unresolved('Delegated execution cannot be excluded.'),
60
+ token: vault || !isolated
61
+ ? unresolved('The asset stub and unknown external callees do not quantify token semantics.')
62
+ : supported('No token dependency entered by the analyzed bytecode.'),
63
+ },
64
+ };
65
+ }
66
+
67
+ const pending = {
68
+ execution: 'Constructor inputs, actual immutables, EVM fork and deployment code are unbound.',
69
+ storage: 'A projection of tracked storage is insufficient to justify all relevant reads and writes.',
70
+ 'transaction-order': 'The engine explores one post-upgrade call and one optional initializer.',
71
+ calldata: 'Canonical ABI shapes and fixed call representatives omit relevant encodings and ETH value.',
72
+ caller: 'The harness excludes address aliases and multi-privilege scenarios.',
73
+ gas: 'The harness does not establish equivalence under the applicable gas schedule and budgets.',
74
+ hashing: 'Mapping and output comparisons rely on the solver Keccak abstraction without a discharge of its scope.',
75
+ outcomes: 'Selected final-state observations omit full return, revert, event and interaction traces.',
76
+ proxy: 'The harness proxy is synthetic; concrete dispatch and implementation transitions are unbound.',
77
+ solver: 'Summary results do not establish a complete, independently replayable obligation inventory.',
78
+ policy: 'Policy exception applicability and omitted cases have not been independently discharged.',
79
+ release: 'No admitted input-to-evidence binding proves the requested ISL properties for these exact deployed runtimes.',
80
+ };
81
+
82
+ function completePropertyInventory(properties) {
83
+ const present = new Set(properties.map(({ name }) => name));
84
+ return [...properties, ...registry.mandatoryForUpgrade.filter((name) => !present.has(name)).map((name) => ({
85
+ name, status: 'unresolved', mandatory: true, checks: 0, unverified: 1, bounded: 0, findings: 0, accepted: 0,
86
+ }))];
87
+ }
88
+
89
+ function assessIntegrity(properties, observations = {}) {
90
+ const assumptions = Object.fromEntries(Object.keys(registry.assumptions).map((id) => [
91
+ id, observations[id] || unresolved(pending[id] || 'No applicability or support evidence recorded.'),
92
+ ]));
93
+ const seen = new Set();
94
+ const obligations = [];
95
+ const entries = properties.map(({ name, status }) => {
96
+ const declared = own(registry.properties, name) && registry.properties[name];
97
+ const duplicate = seen.has(name);
98
+ seen.add(name);
99
+ if (!declared || duplicate) {
100
+ obligations.push({ property: name, reason: duplicate ? 'Duplicate property report.' : 'Property is undeclared.' });
101
+ return { name, status, assumptions: [], semantics: [], bounds: [] };
102
+ }
103
+ for (const id of declared.assumptions) {
104
+ const evidence = assumptions[id];
105
+ if (!evidence || evidence.status !== 'supported' || !evidence.basis) {
106
+ obligations.push({ property: name, assumption: id, reason: evidence?.basis || 'Assumption is undeclared or lacks evidence.' });
107
+ }
108
+ }
109
+ if (status !== 'proven') obligations.push({ property: name, reason: `Property status is ${status}.` });
110
+ return { name, status, ...declared };
111
+ });
112
+ for (const name of registry.mandatoryForUpgrade) {
113
+ if (!seen.has(name)) obligations.push({ property: name, reason: 'Mandatory property evidence is missing.' });
114
+ }
115
+ for (const id of Object.keys(observations)) {
116
+ if (!own(registry.assumptions, id)) obligations.push({ assumption: id, reason: 'Observed assumption is undeclared.' });
117
+ }
118
+ if (assumptions.release.status !== 'supported' || !assumptions.release.basis) {
119
+ obligations.push({ assumption: 'release', reason: assumptions.release.basis || 'Missing release binding evidence.' });
120
+ }
121
+ return { schema: registry.schema, registryDigest: digest(registry), status: obligations.length ? 'incomplete' : 'complete', properties: entries, assumptions, obligations };
122
+ }
123
+
124
+ module.exports = { assessIntegrity, completePropertyInventory, inspectSemantics };
@@ -0,0 +1,369 @@
1
+ // What the differential checks look at, discovered from two build artifacts:
2
+ // storage words and the fields in them, mapping entries worth probing, the
3
+ // kinds of caller, and the calls to try. Nothing here is written per contract.
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { cast } = require('../tools');
7
+ const { resolveBytecode } = require('./bytecode');
8
+ const { callPlans, signature, canonicalType } = require('./abi');
9
+
10
+ const LIMITS = { words: 56, consts: 6, mapDepth: 2, arrayWords: 8 };
11
+ const ERC1967 = {
12
+ implementation: 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcn,
13
+ admin: 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103n,
14
+ beacon: 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50n,
15
+ gateNonce: 0xe6215bbbb3f78f438b4a3bb1a8e6e86c639a2f190b31584c5008ec4646b4dd03n,
16
+ };
17
+ const ADDRESS_TYPE = /^(address( payable)?$|contract )/;
18
+ const hex32 = (n) => '0x' + n.toString(16).padStart(64, '0');
19
+
20
+ // ---------------------------------------------------------------- type model
21
+ // value | struct | mapping | blob (fixed array) | dynamic (string, bytes, T[]) | unknown
22
+
23
+ function valueSize(label) {
24
+ if (ADDRESS_TYPE.test(label)) return 20;
25
+ if (label === 'bool' || label.startsWith('enum ')) return 1;
26
+ let m = label.match(/^u?int(\d*)$/);
27
+ if (m) return m[1] ? Number(m[1]) / 8 : 32;
28
+ m = label.match(/^bytes(\d+)$/);
29
+ if (m) return Number(m[1]);
30
+ return null;
31
+ }
32
+ const keyKind = (label) => (ADDRESS_TYPE.test(label) ? 'address' : label === 'bytes32' ? 'bytes32' : /^u?int\d*$/.test(label) ? 'uint' : 'other');
33
+ const value = (label) => ({ kind: 'value', size: valueSize(label), address: ADDRESS_TYPE.test(label), label });
34
+
35
+ /** A type from forge's storageLayout output. */
36
+ function fromLayout(types, id) {
37
+ const t = types[id];
38
+ if (!t) return { kind: 'unknown', label: String(id) };
39
+ if (t.encoding === 'mapping') return { kind: 'mapping', key: keyKind(types[t.key]?.label || ''), value: fromLayout(types, t.value) };
40
+ if (t.encoding !== 'inplace') return { kind: 'dynamic' };
41
+ if (t.members) {
42
+ return { kind: 'struct', members: t.members.map((m) => ({ label: m.label, slot: Number(m.slot), offset: m.offset, type: fromLayout(types, m.type) })) };
43
+ }
44
+ if (t.base) return { kind: 'blob', words: Math.ceil(Number(t.numberOfBytes) / 32) };
45
+ return valueSize(t.label) === null ? { kind: 'unknown', label: t.label } : value(t.label);
46
+ }
47
+
48
+ /** A type from a typeName node of the AST; `structs` maps canonical names to definitions. */
49
+ function fromAst(node, structs) {
50
+ if (!node) return { kind: 'unknown', label: '?' };
51
+ const text = node.typeDescriptions?.typeString || '';
52
+ if (node.nodeType === 'Mapping') return { kind: 'mapping', key: keyKind(node.keyType?.typeDescriptions?.typeString || ''), value: fromAst(node.valueType, structs) };
53
+ if (node.nodeType === 'ArrayTypeName') return node.length ? { kind: 'unknown', label: text } : { kind: 'dynamic' };
54
+ if (text === 'string' || text === 'bytes') return { kind: 'dynamic' };
55
+ if (text.startsWith('struct ')) {
56
+ const def = structs.get(text.slice(7).replace(/ storage.*$/, ''));
57
+ return def ? packStruct(def, structs) : { kind: 'unknown', label: text };
58
+ }
59
+ return valueSize(text) === null ? { kind: 'unknown', label: text } : value(text);
60
+ }
61
+
62
+ /** Lay a struct definition out the way the compiler does. */
63
+ function packStruct(def, structs) {
64
+ const members = [];
65
+ let [slot, offset] = [0, 0];
66
+ for (const m of def.members) {
67
+ const type = fromAst(m.typeName, structs);
68
+ if (type.kind === 'value') {
69
+ if (offset + type.size > 32) [slot, offset] = [slot + 1, 0];
70
+ members.push({ label: m.name, slot, offset, type });
71
+ offset += type.size;
72
+ continue;
73
+ }
74
+ if (offset > 0) [slot, offset] = [slot + 1, 0];
75
+ members.push({ label: m.name, slot, offset: 0, type });
76
+ if (type.kind === 'unknown' || type.kind === 'blob') return { kind: 'struct', members, incomplete: true };
77
+ slot += type.kind === 'struct' ? structWords(type) : 1;
78
+ }
79
+ return { kind: 'struct', members };
80
+ }
81
+ const structWords = (t) => Math.max(0, ...t.members.map((m) => m.slot + (m.type.kind === 'struct' ? structWords(m.type) : 1)));
82
+
83
+ /** ERC-7201 namespaced structs declared anywhere in the build: [{ id, name, base, type }]. */
84
+ async function namespaces(dir, cast) {
85
+ const out = path.join(dir, 'out');
86
+ const [tagged, structs] = [new Map(), new Map()];
87
+ const walk = (node) => {
88
+ if (!node || typeof node !== 'object') return;
89
+ if (Array.isArray(node)) return node.forEach(walk);
90
+ if (node.nodeType === 'StructDefinition') {
91
+ structs.set(node.canonicalName, node);
92
+ const doc = node.documentation?.text ?? node.documentation;
93
+ const id = typeof doc === 'string' && doc.match(/@custom:storage-location\s+erc7201:(\S+)/)?.[1];
94
+ if (id) tagged.set(id, node);
95
+ }
96
+ Object.values(node).forEach(walk);
97
+ };
98
+ for (const d of fs.readdirSync(out).sort()) {
99
+ if (d === 'build-info') continue;
100
+ for (const f of fs.readdirSync(path.join(out, d)).sort()) {
101
+ if (!f.endsWith('.json')) continue;
102
+ walk(JSON.parse(fs.readFileSync(path.join(out, d, f), 'utf8')).ast);
103
+ }
104
+ }
105
+ const found = [];
106
+ for (const [id, node] of tagged) {
107
+ // keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~0xff
108
+ const inner = BigInt(await cast(['keccak', id])) - 1n;
109
+ const base = BigInt(await cast(['keccak', hex32(inner)])) & ~0xffn;
110
+ found.push({ id, name: node.name, base, type: packStruct(node, structs) });
111
+ }
112
+ return found;
113
+ }
114
+
115
+ // ------------------------------------------------------------------- storage
116
+
117
+ /**
118
+ * Flatten one implementation's storage into words and fields.
119
+ * A word is one storage slot: fixed, or a mapping entry with its keys left
120
+ * open ({ root, steps }). A field is a value inside a word.
121
+ */
122
+ function flatten(layout, spaces, notes) {
123
+ const fields = [];
124
+ const visit = (type, label, root, steps, add, offset) => {
125
+ const word = { root, steps: add ? [...steps, { add }] : steps };
126
+ if (type.kind === 'value') return fields.push({ label, word, offset, size: type.size, address: type.address, dynamic: false });
127
+ if (type.kind === 'dynamic') {
128
+ // Strings and arrays start empty; only "was written" is tracked, and only outside mappings.
129
+ if (steps.length === 0) fields.push({ label, word, offset: 0, size: 32, address: false, dynamic: true });
130
+ return;
131
+ }
132
+ if (type.kind === 'blob') {
133
+ if (label.endsWith('__gap')) return;
134
+ if (steps.length || type.words > LIMITS.arrayWords) return notes.bounded.add(`fixed array ${label} is not tracked`);
135
+ for (let i = 0; i < type.words; i++) fields.push({ label: `${label}[${i}]`, word: { root: root + BigInt(add + i), steps: [] }, offset: 0, size: 32, address: false, dynamic: false });
136
+ return;
137
+ }
138
+ if (type.kind === 'struct') {
139
+ if (type.incomplete) notes.unsupported.add(`storage struct behind ${label} has a member that cannot be read`);
140
+ for (const m of type.members) visit(m.type, `${label}.${m.label}`, root, steps, add + m.slot, m.offset);
141
+ return;
142
+ }
143
+ if (type.kind === 'mapping') {
144
+ const keys = steps.filter((s) => s.key).length;
145
+ if (type.key === 'other') return notes.bounded.add(`mapping ${label} has a key type that is not probed`);
146
+ if (keys >= LIMITS.mapDepth) return notes.bounded.add(`mapping ${label} is nested deeper than ${LIMITS.mapDepth} keys`);
147
+ return visit(type.value, label, root, [...word.steps, { key: type.key }], 0, 0);
148
+ }
149
+ notes.unsupported.add(`storage variable ${label} has a type that cannot be read (${type.label})`);
150
+ };
151
+ for (const v of layout.storage) visit(fromLayout(layout.types, v.type), v.label, BigInt(v.slot), [], 0, v.offset);
152
+ for (const ns of spaces) for (const m of ns.type.members) visit(m.type, `${ns.name}.${m.label}`, ns.base, [], m.slot, m.offset);
153
+ if (spaces.some((ns) => ns.type.incomplete)) notes.unsupported.add('a namespaced storage struct has a member that cannot be read');
154
+ return fields;
155
+ }
156
+
157
+ const wordKey = (w) => `${w.root}:${w.steps.map((s) => (s.key ? `k${s.key}` : `+${s.add}`)).join('')}`;
158
+ const fieldKey = (f) => `${wordKey(f.word)}@${f.offset}/${f.size}`;
159
+
160
+ /** PUSH32 operands of runtime bytecode, in order of first appearance. */
161
+ function push32(hex) {
162
+ const code = Buffer.from(hex.replace(/^0x/, ''), 'hex');
163
+ const seen = new Set();
164
+ for (let i = 0; i < code.length; i++) {
165
+ const op = code[i];
166
+ if (op === 0x7f && i + 32 < code.length) seen.add(BigInt('0x' + code.subarray(i + 1, i + 33).toString('hex')));
167
+ if (op >= 0x60 && op <= 0x7f) i += op - 0x5f;
168
+ }
169
+ return [...seen];
170
+ }
171
+
172
+ // --------------------------------------------------------------------- calls
173
+
174
+ const mutating = (artifact) => artifact.abi.filter((f) => f.type === 'function' && f.stateMutability !== 'view' && f.stateMutability !== 'pure');
175
+
176
+ /** Every call shape of either ABI, plus two raw ones for fallback and receive. */
177
+ function shapes(oldArtifact, newArtifact, notes, includeViews) {
178
+ const out = [];
179
+ const add = (artifact, side) => {
180
+ const functions = includeViews ? artifact.abi.filter((f) => f.type === 'function') : mutating(artifact);
181
+ for (const f of functions) {
182
+ const contextOnly = f.stateMutability === 'view' || f.stateMutability === 'pure';
183
+ const sig = signature(f);
184
+ const selector = artifact.methodIdentifiers?.[sig];
185
+ if (!/^[a-f0-9]{8}$/i.test(selector || '')) {
186
+ notes.unsupported.add(`${sig} has no valid method identifier`);
187
+ continue;
188
+ }
189
+ const known = out.filter((shape) => shape.selector === selector);
190
+ if (known.some((shape) => shape.sig !== sig)) {
191
+ notes.unsupported.add(`selector ${selector} maps to different signatures in the two implementations`);
192
+ continue;
193
+ }
194
+ if (known.length) {
195
+ for (const shape of known) {
196
+ shape[side] = true;
197
+ shape.contextOnly &&= contextOnly;
198
+ }
199
+ continue;
200
+ }
201
+ const plans = callPlans(f.inputs);
202
+ if (!plans) {
203
+ notes.unsupported.add(`${sig} exceeds the ABI shape limits or contains an unsupported type`);
204
+ continue;
205
+ }
206
+ if (plans.length > 1) notes.bounded.add(`${sig}: dynamic array lengths 0 and 1; byte lengths 0, 1 and 32`);
207
+ for (const plan of plans) out.push({ sig, selector, ...plan, inOld: side === 'inOld', inNew: side === 'inNew', contextOnly });
208
+ }
209
+ };
210
+ add(oldArtifact, 'inOld');
211
+ add(newArtifact, 'inNew');
212
+ // No calldata (receive or fallback) and an unknown selector (fallback).
213
+ out.push({ sig: '(empty calldata)', selector: null, words: [], addr: [], variant: 0, inOld: true, inNew: true, raw: true });
214
+ const selectors = new Set([oldArtifact, newArtifact].flatMap((artifact) => Object.values(artifact.methodIdentifiers || {})));
215
+ let unknown = 0xffffffff;
216
+ while (selectors.has(unknown.toString(16).padStart(8, '0'))) unknown--;
217
+ out.push({ sig: '(unknown selector)', selector: unknown.toString(16).padStart(8, '0'), words: ['sym', 'sym'], addr: [], variant: 0, inOld: true, inNew: true, raw: true });
218
+ return out;
219
+ }
220
+
221
+ // --------------------------------------------------------------------- model
222
+
223
+ /**
224
+ * Build the model for one upgrade.
225
+ * Returns { words, fields, classes, targets, observables, shapes, live, notes, vault, creation }.
226
+ */
227
+ async function buildModel({ dir, artifact, baseArtifact, includeViews = false, castTool = cast, execution = resolveBytecode(dir, [baseArtifact, artifact]) }) {
228
+ const notes = { bounded: new Set(), unsupported: new Set() };
229
+ for (const error of execution.errors) notes.unsupported.add(error);
230
+ const [oldHex, newHex] = [baseArtifact, artifact].map((a, i) => (execution.implementations[i]?.runtime.hex || a.deployedBytecode.object).toLowerCase());
231
+ const mentions = (hex, ns) => hex.includes(hex32(ns.base).slice(2));
232
+ const all = await namespaces(dir, castTool);
233
+ const oldFields = flatten(baseArtifact.storageLayout, all.filter((ns) => mentions(oldHex, ns)), notes);
234
+ const newFields = flatten(artifact.storageLayout, all.filter((ns) => mentions(newHex, ns)), notes);
235
+
236
+ // Merge by place and shape. `existing` marks state the old code already had.
237
+ const merged = new Map();
238
+ for (const f of oldFields) merged.set(fieldKey(f), { ...f, existing: true });
239
+ for (const f of newFields) if (!merged.has(fieldKey(f))) merged.set(fieldKey(f), { ...f, existing: false });
240
+
241
+ // bytes32 mapping keys worth trying: zero plus hash-looking constants in the code.
242
+ const known = new Set([...Object.values(ERC1967), ...all.map((ns) => ns.base)]);
243
+ const needConsts = [...merged.values()].some((f) => f.word.steps.some((s) => s.key === 'bytes32'));
244
+ let consts = [0n];
245
+ if (needConsts) {
246
+ // Event topics are hashes but never storage keys. Left-aligned words
247
+ // (strings, selectors, interface ids) end in zero bytes and revert-string
248
+ // chunks are all printable text; hashes are neither.
249
+ const topics = await eventTopics([baseArtifact, artifact], castTool);
250
+ const found = [...new Set([...push32(oldHex), ...push32(newHex)])].filter((c) => !known.has(c) && !known.has(c & ~0xffn) && !topics.has(c) &&
251
+ (c & 0xffffffffn) !== 0n && !/^[\x20-\x7e]{4,}\x00*$/.test(Buffer.from(hex32(c).slice(2), 'hex').toString('latin1')) &&
252
+ c > 1n << 200n && c < (1n << 256n) - (1n << 200n));
253
+ if (found.length > LIMITS.consts) notes.bounded.add(`only the first ${LIMITS.consts} of ${found.length} constants are tried as bytes32 mapping keys`);
254
+ consts = consts.concat(found.slice(0, LIMITS.consts));
255
+ }
256
+ const constNames = await roleNames([baseArtifact, artifact], castTool);
257
+ const constLabel = (c) => (c === 0n ? '0x00' : constNames.get(c) || hex32(c).slice(0, 10) + '…');
258
+
259
+ // Instantiate mapping entries with concrete kinds of key.
260
+ const domain = { address: ['caller', 'victim', 'self'], uint: ['tid'], bytes32: consts.map((c) => ({ const: c })) };
261
+ const words = [];
262
+ const wordIndex = new Map();
263
+ const fields = [];
264
+ const instantiate = (f) => {
265
+ const keySteps = f.word.steps.filter((s) => s.key);
266
+ const combos = keySteps.reduce((acc, s) => acc.flatMap((c) => domain[s.key].map((k) => [...c, k])), [[]]);
267
+ for (const combo of combos) {
268
+ let i = 0;
269
+ const steps = f.word.steps.map((s) => (s.key ? { key: combo[i++] } : s));
270
+ const id = `${f.word.root}:${steps.map((s) => (s.key ? `[${s.key.const ?? s.key}]` : `+${s.add}`)).join('')}`;
271
+ if (!wordIndex.has(id)) {
272
+ wordIndex.set(id, words.length);
273
+ words.push({ root: f.word.root, steps, symbolic: !f.dynamic });
274
+ }
275
+ const keysText = combo.map((k) => `[${k.const !== undefined ? constLabel(k.const) : k}]`).join('');
276
+ const [head, ...rest] = f.label.split('.');
277
+ // `a.b` of a mapping reads better as `a[key].b`; namespaced `Struct.member` keeps its prefix.
278
+ const label = keySteps.length === 0 ? f.label : labelWithKeys(f.label, keysText, head, rest);
279
+ // An entry is the caller's privilege when the caller is its last
280
+ // address key: allowed[owner][caller], roles[r][caller], balances[caller].
281
+ const addressKeys = combo.filter((k) => typeof k === 'string' && k !== 'tid');
282
+ fields.push({ label, word: wordIndex.get(id), offset: f.offset, size: f.size, address: f.address, dynamic: f.dynamic, existing: f.existing, callerKeyed: combo.includes('caller'), privilege: addressKeys.at(-1) === 'caller' });
283
+ }
284
+ };
285
+ [...merged.values()].forEach(instantiate);
286
+ if (words.filter((w) => w.symbolic).length > LIMITS.words) {
287
+ notes.unsupported.add(`storage needs ${words.filter((w) => w.symbolic).length} tracked words, more than the ${LIMITS.words} these checks cover`);
288
+ }
289
+
290
+ // Kinds of caller: a stranger, the holder of one address-typed value, the
291
+ // holder of one mapping entry keyed by the caller.
292
+ const classes = [{ label: 'anyone', kind: 'stranger' }];
293
+ fields.forEach((f, i) => {
294
+ if (f.dynamic) return;
295
+ if (f.address && !f.callerKeyed && words[f.word].steps.every((s) => !s.key)) classes.push({ label: `the address in ${f.label}`, kind: 'is', field: i });
296
+ if (f.privilege) classes.push({ label: `a caller with ${f.label} set`, kind: 'holds', field: i });
297
+ });
298
+
299
+ // What a call can change. Storage of the old code, the proxy slots, and
300
+ // balances seen from outside.
301
+ const targets = [];
302
+ fields.forEach((f, i) => f.existing && targets.push({ label: f.label, kind: 'field', field: i }));
303
+ for (const [name, slot] of Object.entries(ERC1967)) targets.push({ label: `proxy ${name} slot`, kind: 'slot', slot, proxy: name });
304
+
305
+ const has = (a, sig) => Boolean(a.methodIdentifiers?.[sig]);
306
+ const both = (sig) => has(baseArtifact, sig) && has(artifact, sig);
307
+ const vault = both('asset()') && both('totalAssets()');
308
+ const observables = [{ label: 'ETH held by the contract', kind: 'eth' }];
309
+ if (both('totalSupply()')) observables.push({ label: 'totalSupply()', kind: 'view', selector: '18160ddd', arg: null });
310
+ if (both('balanceOf(address)')) {
311
+ observables.push({ label: 'balanceOf(victim)', kind: 'view', selector: '70a08231', arg: 'victim' }, { label: 'balanceOf(caller)', kind: 'view', selector: '70a08231', arg: 'caller' });
312
+ }
313
+ if (both('ownerOf(uint256)')) observables.push({ label: 'ownerOf(tokenId)', kind: 'view', selector: '6352211e', arg: 'tid' });
314
+ if (vault) observables.push({ label: 'asset tokens held by the contract', kind: 'asset', who: 'self' }, { label: 'asset tokens of victim', kind: 'asset', who: 'victim' });
315
+ observables.forEach((o, i) => targets.push({ label: o.label, kind: 'observable', observable: i }));
316
+
317
+ // The state the checks start from is one an initialized proxy could be in.
318
+ const flag = (re) => fields.map((f, i) => ({ f, i })).filter(({ f }) => f.existing && !f.callerKeyed && re.test(f.label));
319
+ const live = { nonzero: flag(/(^|\.)_?initiali[sz]ed$/).map((x) => x.i), zero: flag(/(^|\.)_?initiali[sz]ing$/).map((x) => x.i), recognized: true };
320
+ if (live.nonzero.length === 0) {
321
+ live.recognized = false;
322
+ live.nonzero = fields.map((f, i) => ({ f, i })).filter(({ f }) => f.existing && f.address && !f.dynamic && words[f.word].steps.every((s) => !s.key)).map((x) => x.i);
323
+ notes.bounded.add('no initialized flag recognized: a live state is taken to be one where every address variable is set');
324
+ }
325
+
326
+ const creation = [baseArtifact, artifact].map((a, i) => {
327
+ const code = execution.implementations[i]?.creation.hex || '';
328
+ const args = a.abi.find((x) => x.type === 'constructor')?.inputs?.length || 0;
329
+ if (args) notes.bounded.add('constructor takes arguments: the implementation is modelled from its runtime code, immutables read as zero');
330
+ return args || !code ? null : code;
331
+ });
332
+
333
+ notes.bounded.add('calls carry no ETH');
334
+ notes.bounded.add('address arguments and stored addresses never name the contract itself');
335
+ notes.bounded.add('mapping entries are tried for the caller, one other account, the contract itself and one token id; strings and arrays start empty');
336
+ notes.bounded.add('a caller holds at most one privilege at a time when kinds of caller are compared');
337
+ if (execution.libraries.length) notes.bounded.add('external libraries execute build-artifact code; live library runtime identities are not checked by this artifact proof');
338
+ return { words, fields, classes, targets, observables, shapes: shapes(baseArtifact, artifact, notes, includeViews), live, notes, vault, creation, consts,
339
+ libraries: execution.libraries, creationLinks: execution.implementations.map((a) => a?.creation.links || []), runtimeLinks: execution.implementations.map((a) => a?.runtime.links || []) };
340
+ }
341
+
342
+ function labelWithKeys(full, keysText, head, rest) {
343
+ // Namespaced fields are `Struct.member[...]`; ordinary ones `variable[...]` then members.
344
+ if (/Storage$/.test(head) && rest.length) return `${head}.${rest[0]}${keysText}${rest.slice(1).map((r) => '.' + r).join('')}`;
345
+ return `${head}${keysText}${rest.map((r) => '.' + r).join('')}`;
346
+ }
347
+
348
+ /** keccak256 of every event signature in the ABIs. */
349
+ async function eventTopics(artifacts, cast) {
350
+ const sigs = new Set(artifacts.flatMap((a) => a.abi.filter((e) => e.type === 'event').map((e) => `${e.name}(${e.inputs.map(canonicalType).join(',')})`)));
351
+ const out = new Set();
352
+ for (const sig of sigs) out.add(BigInt(await cast(['keccak', sig])));
353
+ return out;
354
+ }
355
+
356
+ /** bytes32 constants exposed as no-argument views, by the convention NAME = keccak256("NAME"). */
357
+ async function roleNames(artifacts, cast) {
358
+ const names = new Map();
359
+ for (const a of artifacts) {
360
+ for (const f of a.abi) {
361
+ if (f.type !== 'function' || f.inputs.length || f.outputs?.length !== 1 || f.outputs[0].type !== 'bytes32') continue;
362
+ if (!/^[A-Z][A-Z0-9_]*$/.test(f.name)) continue;
363
+ names.set(BigInt(await cast(['keccak', f.name])), f.name);
364
+ }
365
+ }
366
+ return names;
367
+ }
368
+
369
+ module.exports = { buildModel, namespaces, ERC1967, hex32, LIMITS };
@@ -0,0 +1,59 @@
1
+ // Policy: the intended permission and behaviour changes of one upgrade,
2
+ // written down so they can be told apart from regressions.
3
+ //
4
+ // {
5
+ // "version": 1,
6
+ // "exceptions": [
7
+ // { "rule": "capability", "function": "burn(uint256)", "target": "...", "class": "...", "reason": "..." }
8
+ // ]
9
+ // }
10
+ //
11
+ // An exception names one finding by its rule plus the function, target and
12
+ // kind of caller the finding reports. A field left out matches anything, but
13
+ // at least one of function and class must be given, and so must a reason.
14
+ // Only behavioural findings can be accepted; a broken layout, a new dangerous
15
+ // opcode, an outsider reaching the proxy slots, an opened implementation and
16
+ // anything unverified cannot.
17
+ //
18
+ // The file is plain data on purpose: it can be written by hand today and
19
+ // emitted from an ISL contract later without the engine changing.
20
+ const fs = require('node:fs');
21
+ const { cast } = require('../tools');
22
+
23
+ const RULES = ['guard', 'mutation', 'value', 'capability', 'upgrade-lost'];
24
+ const KEYS = ['rule', 'function', 'target', 'class', 'reason'];
25
+
26
+ function parsePolicy(text) {
27
+ const policy = JSON.parse(text);
28
+ if (policy.version !== 1 || !Array.isArray(policy.exceptions)) throw new Error('policy must have "version": 1 and an "exceptions" list');
29
+ for (const e of policy.exceptions) {
30
+ if (!RULES.includes(e.rule)) throw new Error(`policy exception has an unknown or unacceptable rule: ${e.rule}`);
31
+ if (!e.function && !e.class) throw new Error('policy exception must name a function or a kind of caller');
32
+ if (!e.reason || !String(e.reason).trim()) throw new Error('policy exception must give a reason');
33
+ for (const k of Object.keys(e)) if (!KEYS.includes(k)) throw new Error(`policy exception has an unknown field: ${k}`);
34
+ }
35
+ return policy;
36
+ }
37
+
38
+ function loadPolicy(file) {
39
+ return parsePolicy(fs.readFileSync(file, 'utf8'));
40
+ }
41
+
42
+ function matchException(e, finding) {
43
+ if (e.rule !== finding.rule) return false;
44
+ return ['function', 'target', 'class'].every((k) => e[k] === undefined || e[k] === finding[k]);
45
+ }
46
+
47
+ /** Stable text of a policy: keys sorted, exceptions sorted, no whitespace. */
48
+ function canonical(policy) {
49
+ const rows = (policy?.exceptions || []).map((e) => JSON.stringify(Object.fromEntries(KEYS.filter((k) => e[k] !== undefined).map((k) => [k, e[k]]))));
50
+ return `{"version":1,"exceptions":[${rows.sort().join(',')}]}`;
51
+ }
52
+
53
+ /** What the chain binds: zero for "no exceptions", else keccak256 of the canonical text. */
54
+ async function policyHash(policy) {
55
+ if (!policy || policy.exceptions.length === 0) return '0x' + '0'.repeat(64);
56
+ return cast(['keccak', '0x' + Buffer.from(canonical(policy), 'utf8').toString('hex')]);
57
+ }
58
+
59
+ module.exports = { parsePolicy, loadPolicy, matchException, canonical, policyHash, RULES };
@@ -0,0 +1,69 @@
1
+ const { createHash } = require('node:crypto');
2
+ const { canonical } = require('../canonical-json');
3
+ const { assessIntegrity } = require('./integrity');
4
+
5
+ const SCHEMA = 'guardefi.proof-certificate.v1';
6
+ const SHA256 = /^[0-9a-f]{64}$/;
7
+ const RUNTIME = /^0x(?:[0-9a-f]{2})+$/;
8
+ const HASH = /^0x[0-9a-f]{64}$/;
9
+ const ADDRESS = /^0x[0-9a-f]{40}$/;
10
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
11
+ const digestOf = (body) => hash(canonical(body));
12
+
13
+ function hasRequiredBindings(subject, verifier, evidence) {
14
+ const environment = subject?.environment;
15
+ return RUNTIME.test(subject?.baseline?.bytecode) &&
16
+ subject.baseline.sha256 === hash(Buffer.from(subject.baseline.bytecode.slice(2), 'hex')) &&
17
+ RUNTIME.test(subject.candidate?.bytecode) &&
18
+ subject.candidate.sha256 === hash(Buffer.from(subject.candidate.bytecode.slice(2), 'hex')) &&
19
+ /^0x(?:[0-9a-f]{2})*$/.test(subject.initCalldata) &&
20
+ typeof subject.isl?.source === 'string' && subject.isl.source.trim().length > 0 &&
21
+ subject.isl.sha256 === hash(subject.isl.source) &&
22
+ /^[1-9][0-9]*$/.test(environment?.chainId) && typeof environment.fork === 'string' && environment.fork.length > 0 &&
23
+ HASH.test(environment.blockHash) && HASH.test(environment.stateRoot) &&
24
+ ADDRESS.test(environment.proxy) && HASH.test(environment.proxyCodehash) &&
25
+ ADDRESS.test(subject.baseline.address) && ADDRESS.test(subject.candidate.address) &&
26
+ typeof verifier?.version === 'string' && verifier.version.length > 0 && SHA256.test(verifier.sourceSha256) &&
27
+ Array.isArray(verifier.tools) && verifier.tools.length > 0 &&
28
+ verifier.tools.every(({ name, version, sha256 }) => name && version && SHA256.test(sha256)) &&
29
+ Array.isArray(evidence) && evidence.length > 0 && evidence.every(({ property, check, inputSha256, outputSha256, result }) =>
30
+ typeof property === 'string' && typeof check === 'string' && check.length > 0 &&
31
+ SHA256.test(inputSha256) && SHA256.test(outputSha256) && result === 'discharged') &&
32
+ new Set(evidence.map(({ check }) => check)).size === evidence.length;
33
+ }
34
+
35
+ function verifiedInventory(integrity, evidence) {
36
+ const assessed = assessIntegrity(integrity.properties, integrity.assumptions);
37
+ const declared = new Set(assessed.properties.map(({ name }) => name));
38
+ return assessed.status === 'complete' && digestOf(assessed) === digestOf(integrity) &&
39
+ assessed.properties.every(({ name }) => evidence.some(({ property }) => property === name)) &&
40
+ evidence.every(({ property }) => declared.has(property));
41
+ }
42
+
43
+ // The producer must supply bindings and discharged checks from the same run.
44
+ // The digest is an integrity commitment. Authenticity requires an externally
45
+ // trusted digest and semantic verification requires replay by the consumer.
46
+ function issueProofCertificate(report) {
47
+ const { integrity, findings, certificateInputs } = report;
48
+ if (integrity.status !== 'complete' || findings.length || !certificateInputs) return null;
49
+ const { subject, verifier, evidence } = certificateInputs;
50
+ if (!hasRequiredBindings(subject, verifier, evidence)) return null;
51
+ if (!verifiedInventory(integrity, evidence)) return null;
52
+ const body = { schema: SCHEMA, subject, verifier, integrity, evidence };
53
+ return { ...body, digest: digestOf(body) };
54
+ }
55
+
56
+ function inspectProofCertificate(certificate, expectedDigest) {
57
+ if (!SHA256.test(expectedDigest || '')) throw new Error('An independently obtained proof certificate digest is required.');
58
+ const { digest, ...body } = certificate;
59
+ if (body.schema !== SCHEMA || digest !== expectedDigest || digestOf(body) !== digest) {
60
+ throw new Error('Proof certificate schema or digest mismatch.');
61
+ }
62
+ if (!hasRequiredBindings(body.subject, body.verifier, body.evidence)) throw new Error('Proof certificate bindings are incomplete.');
63
+ if (!verifiedInventory(body.integrity, body.evidence)) {
64
+ throw new Error('Proof certificate assumption registry or discharge evidence is incomplete.');
65
+ }
66
+ return { digest, integrity: 'valid', semanticReplay: 'required', subject: body.subject, verifier: body.verifier };
67
+ }
68
+
69
+ module.exports = { issueProofCertificate, inspectProofCertificate };