@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.
- package/LICENSE +202 -0
- package/NOTICE +18 -0
- package/README.md +31 -2
- package/assurance/cli-check.js +446 -0
- package/assurance/cli-project-paths.js +56 -0
- package/assurance/cli-storage.js +289 -0
- package/assurance/cli-ui.js +617 -0
- package/assurance/guardefi-public.js +66 -0
- package/assurance/release-policy.js +212 -0
- package/core/behavioral-diff.js +555 -0
- package/core/canonical-json.js +9 -0
- package/core/engine/abi.js +99 -0
- package/core/engine/assumptions.json +86 -0
- package/core/engine/bytecode.js +119 -0
- package/core/engine/callee-binding.js +140 -0
- package/core/engine/deployment.js +175 -0
- package/core/engine/external-effects.js +40 -0
- package/core/engine/harness.js +503 -0
- package/core/engine/index.js +638 -0
- package/core/engine/integrity.js +124 -0
- package/core/engine/model.js +369 -0
- package/core/engine/policy.js +59 -0
- package/core/engine/proof-certificate.js +69 -0
- package/core/engine/provenance.js +354 -0
- package/core/engine/screen.js +117 -0
- package/core/engine/upgrade-authority.js +327 -0
- package/core/generic.js +334 -0
- package/core/hardhat.js +114 -0
- package/core/isl/behavior-profile.js +169 -0
- package/core/isl/behavior-solidity.js +267 -0
- package/core/isl/behavior-storage.js +151 -0
- package/core/isl/behavior-verify.js +223 -0
- package/core/isl/getter-profile.js +149 -0
- package/core/isl/vendor/NOTICE.md +38 -0
- package/core/isl/vendor/isl-parser.cjs +5872 -0
- package/core/isl-compiler.js +19 -0
- package/core/isl-firewall.js +1396 -0
- package/core/keccak.js +89 -0
- package/core/prove.js +376 -0
- package/core/release-receipt.js +793 -0
- package/core/rpc.js +74 -0
- package/core/tools.js +129 -0
- package/core/verdict-policy.js +195 -0
- package/docs/public-cli.md +32 -0
- package/package.json +29 -4
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "guardefi.proof-assumptions.v1",
|
|
3
|
+
"assumptions": {
|
|
4
|
+
"execution": "Modeled runtime, linked libraries, immutables, EVM fork and deployment environment match the reviewed subject.",
|
|
5
|
+
"analysis": "Reachability accounts for every applicable instruction in both implementations and their executable dependencies.",
|
|
6
|
+
"storage": "Initial storage includes all reachable live states and effects cover every slot, namespace, mapping key and alias required by the property.",
|
|
7
|
+
"transaction-order": "The modeled transaction sequence covers every required ordering, intermediate state and ordering dependency.",
|
|
8
|
+
"calldata": "Selector dispatch, ABI shapes, fallback, receive, malformed encodings and call value cover the property's inputs.",
|
|
9
|
+
"caller": "Caller, origin, privilege combinations, self aliases, proxy identity and call value match the admitted execution scope.",
|
|
10
|
+
"external-state": "Code, balances, return data and mutable state of every dependency are bound or universally modeled.",
|
|
11
|
+
"callbacks": "Nested and cross-function callbacks, including read-only observations, are covered under the applicable call frames.",
|
|
12
|
+
"delegatecall": "Execution in the caller's context preserves identity, value and storage semantics and binds the code at every delegated target.",
|
|
13
|
+
"block-context": "Both implementations see the same admitted symbolic block context and all relevant environment reads are modeled.",
|
|
14
|
+
"gas": "Gas accounting, exceptional halts, warm and cold state, refunds and forwarded gas are sound for the admitted execution scope.",
|
|
15
|
+
"hashing": "Cryptographic abstractions and the use of hashes for byte data and slot comparisons preserve the claimed property.",
|
|
16
|
+
"outcomes": "The property observes all required results, including rollback, success, return and revert data, logs and external effects.",
|
|
17
|
+
"token": "Applicable token behavior covers adversarial return values, fees, hooks, rebasing and allowance changes or binds exact code.",
|
|
18
|
+
"proxy": "Proxy dispatch, reserved slots, initialization and implementation transitions match the reviewed deployment.",
|
|
19
|
+
"solver": "Every quantified obligation has nonvacuous, complete checker evidence under the declared exploration bounds.",
|
|
20
|
+
"policy": "Any exception is bound to the verified specification and preserves all mandatory obligations.",
|
|
21
|
+
"release": "Exact bytecode, ISL property translation, verifier, environment and reproducible evidence are bound to the verdict."
|
|
22
|
+
},
|
|
23
|
+
"properties": {
|
|
24
|
+
"layout": {
|
|
25
|
+
"semantics": ["Declared Solidity storage slot, offset and type preservation"],
|
|
26
|
+
"assumptions": ["execution", "storage"],
|
|
27
|
+
"bounds": ["Compiler-reported baseline storage entries"]
|
|
28
|
+
},
|
|
29
|
+
"opcodes": {
|
|
30
|
+
"semantics": ["Static opcode introduction and linked delegate target provenance"],
|
|
31
|
+
"assumptions": ["execution", "analysis", "delegatecall"],
|
|
32
|
+
"bounds": ["300000 abstract states per runtime; computed constants widened after four visits"]
|
|
33
|
+
},
|
|
34
|
+
"guards": {
|
|
35
|
+
"semantics": ["One-way success/revert relation on baseline calls in paired worlds"],
|
|
36
|
+
"assumptions": ["execution", "analysis", "storage", "calldata", "caller", "external-state", "callbacks", "block-context", "gas", "outcomes", "proxy", "solver", "policy"],
|
|
37
|
+
"bounds": ["One post-upgrade call", "Modeled selectors, calldata and caller classes"]
|
|
38
|
+
},
|
|
39
|
+
"mutations": {
|
|
40
|
+
"semantics": ["Paired writes to selected baseline slots and fields"],
|
|
41
|
+
"assumptions": ["execution", "analysis", "storage", "calldata", "caller", "external-state", "callbacks", "delegatecall", "block-context", "gas", "outcomes", "proxy", "solver", "policy"],
|
|
42
|
+
"bounds": ["One post-upgrade call", "56 tracked words; mapping depth 2; fixed arrays at most 8 words"]
|
|
43
|
+
},
|
|
44
|
+
"values": {
|
|
45
|
+
"semantics": ["Post-call equality of selected asset observations"],
|
|
46
|
+
"assumptions": ["execution", "storage", "calldata", "caller", "external-state", "callbacks", "block-context", "gas", "outcomes", "token", "proxy", "solver", "policy"],
|
|
47
|
+
"bounds": ["One post-upgrade call", "ETH and selected getter or token observations"]
|
|
48
|
+
},
|
|
49
|
+
"capabilities": {
|
|
50
|
+
"semantics": ["New call shape can reach a tracked effect for a modeled caller class"],
|
|
51
|
+
"assumptions": ["execution", "storage", "calldata", "caller", "external-state", "callbacks", "block-context", "gas", "outcomes", "proxy", "solver", "policy"],
|
|
52
|
+
"bounds": ["One post-upgrade call", "Single inferred privilege and selected storage or asset targets"]
|
|
53
|
+
},
|
|
54
|
+
"upgrade": {
|
|
55
|
+
"semantics": ["Reachability of modeled ERC-1967 slot writes"],
|
|
56
|
+
"assumptions": ["execution", "storage", "transaction-order", "calldata", "caller", "external-state", "callbacks", "delegatecall", "block-context", "gas", "outcomes", "proxy", "solver", "policy"],
|
|
57
|
+
"bounds": ["One modeled transition; no quantified follow-on upgrade"]
|
|
58
|
+
},
|
|
59
|
+
"init": {
|
|
60
|
+
"semantics": ["Reachability of successful supplied initializer and tracked bare implementation effects"],
|
|
61
|
+
"assumptions": ["execution", "storage", "transaction-order", "calldata", "caller", "external-state", "callbacks", "block-context", "gas", "outcomes", "proxy", "solver"],
|
|
62
|
+
"bounds": ["One fixed initializer, then one modeled call", "Selected constructor model"]
|
|
63
|
+
},
|
|
64
|
+
"model": {
|
|
65
|
+
"semantics": ["Model construction and completeness"],
|
|
66
|
+
"assumptions": ["analysis", "storage", "calldata", "caller", "transaction-order"],
|
|
67
|
+
"bounds": ["Finite model domains declared in each report"]
|
|
68
|
+
},
|
|
69
|
+
"reentrancy": {
|
|
70
|
+
"semantics": ["Reachable invocation classification including static-frame write restrictions"],
|
|
71
|
+
"assumptions": ["analysis", "external-state", "callbacks", "delegatecall", "token"],
|
|
72
|
+
"bounds": ["Transitive linked artifacts; general nested callbacks are unresolved"]
|
|
73
|
+
},
|
|
74
|
+
"context": {
|
|
75
|
+
"semantics": ["Shared symbolic timestamp, number, chain ID, base fee, coinbase and post-Merge randomness"],
|
|
76
|
+
"assumptions": ["execution", "analysis", "block-context", "external-state", "gas", "hashing", "solver"],
|
|
77
|
+
"bounds": ["Six independently symbolic fields shared across both worlds for a single modeled call"]
|
|
78
|
+
},
|
|
79
|
+
"spec-harness": {
|
|
80
|
+
"semantics": ["Legacy JSON assertions and supplied Halmos harness checks"],
|
|
81
|
+
"assumptions": ["execution", "storage", "calldata", "caller", "external-state", "callbacks", "block-context", "gas", "outcomes", "proxy", "solver", "release"],
|
|
82
|
+
"bounds": ["Project-authored harness and checker settings"]
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"mandatoryForUpgrade": ["layout", "opcodes", "guards", "mutations", "values", "capabilities", "upgrade", "init", "reentrancy", "context"]
|
|
86
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Resolve compiler-declared library references without changing build artifacts.
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
function metadataOf(artifact) {
|
|
6
|
+
const metadata = artifact.metadata ?? artifact.rawMetadata;
|
|
7
|
+
return typeof metadata === 'string' ? JSON.parse(metadata) : metadata;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function hasConfiguredLibraries(artifact) {
|
|
11
|
+
return Object.values(metadataOf(artifact)?.settings?.libraries || {}).some((names) => Object.keys(names).length > 0);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function hasLibraryDependencies(artifact) {
|
|
15
|
+
return hasConfiguredLibraries(artifact) || Object.values(artifact.deployedBytecode?.linkReferences || {})
|
|
16
|
+
.some((names) => Object.values(names).some((locations) => locations.length > 0));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function sourceOf(artifact) {
|
|
20
|
+
if (artifact.ast?.absolutePath) return artifact.ast.absolutePath;
|
|
21
|
+
const metadata = metadataOf(artifact);
|
|
22
|
+
return Object.keys(metadata?.settings?.compilationTarget || {})[0];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function resolveBytecode(dir, artifacts) {
|
|
26
|
+
const libraries = [];
|
|
27
|
+
const resolved = new Map();
|
|
28
|
+
const visiting = new Set();
|
|
29
|
+
const errors = new Set();
|
|
30
|
+
const graphs = [];
|
|
31
|
+
|
|
32
|
+
const load = (source, name) => {
|
|
33
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) throw new Error('Invalid linked library name.');
|
|
34
|
+
const out = path.join(dir, 'out');
|
|
35
|
+
// Foundry normally uses the source basename. Check the embedded source too:
|
|
36
|
+
// two sources can contain libraries with the same name.
|
|
37
|
+
const matches = [];
|
|
38
|
+
for (const entry of fs.readdirSync(out, { withFileTypes: true })) {
|
|
39
|
+
if (!entry.isDirectory() || entry.name === 'build-info') continue;
|
|
40
|
+
const file = path.join(out, entry.name, `${name}.json`);
|
|
41
|
+
if (!fs.existsSync(file)) continue;
|
|
42
|
+
const artifact = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
43
|
+
if (sourceOf(artifact) === source) matches.push(artifact);
|
|
44
|
+
}
|
|
45
|
+
if (matches.length !== 1) throw new Error(`library ${source}:${name} needs exactly one matching build artifact`);
|
|
46
|
+
const artifact = matches[0];
|
|
47
|
+
if (hasConfiguredLibraries(artifact)) throw new Error(`prelinked library ${source}:${name} needs live runtime bindings`);
|
|
48
|
+
if (artifact.abi?.some((item) => item.type === 'constructor' && item.inputs?.length))
|
|
49
|
+
throw new Error(`library ${source}:${name} needs constructor arguments`);
|
|
50
|
+
if (!artifact.bytecode?.object || artifact.bytecode.object === '0x')
|
|
51
|
+
throw new Error(`library ${source}:${name} has no creation bytecode`);
|
|
52
|
+
return artifact;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const library = (source, name, graph) => {
|
|
56
|
+
const key = `${source}:${name}`;
|
|
57
|
+
if (visiting.has(key)) throw new Error(`cyclic library reference: ${key}`);
|
|
58
|
+
if (!resolved.has(key)) {
|
|
59
|
+
visiting.add(key);
|
|
60
|
+
try {
|
|
61
|
+
const artifact = load(source, name);
|
|
62
|
+
const creation = code(artifact.bytecode, graph);
|
|
63
|
+
const runtime = code(artifact.deployedBytecode, graph);
|
|
64
|
+
const index = libraries.length;
|
|
65
|
+
libraries.push({ name: key, creation, runtime });
|
|
66
|
+
resolved.set(key, index);
|
|
67
|
+
} finally { visiting.delete(key); }
|
|
68
|
+
}
|
|
69
|
+
const index = resolved.get(key);
|
|
70
|
+
graph.add(index);
|
|
71
|
+
// A cached library's transitive dependencies belong to this world too.
|
|
72
|
+
for (const ref of [...libraries[index].creation.links, ...libraries[index].runtime.links]) addDependency(ref.library, graph);
|
|
73
|
+
return index;
|
|
74
|
+
};
|
|
75
|
+
const addDependency = (index, graph) => {
|
|
76
|
+
if (graph.has(index)) return;
|
|
77
|
+
graph.add(index);
|
|
78
|
+
for (const ref of [...libraries[index].creation.links, ...libraries[index].runtime.links]) addDependency(ref.library, graph);
|
|
79
|
+
};
|
|
80
|
+
const code = (object, graph) => {
|
|
81
|
+
let hex = (object?.object || '').replace(/^0x/, '');
|
|
82
|
+
const links = [];
|
|
83
|
+
const occupied = new Set();
|
|
84
|
+
for (const [source, names] of Object.entries(object?.linkReferences || {})) {
|
|
85
|
+
for (const [name, locations] of Object.entries(names)) {
|
|
86
|
+
const index = library(source, name, graph);
|
|
87
|
+
for (const { start, length } of locations) {
|
|
88
|
+
if (!Number.isInteger(start) || start < 0 || length !== 20 || (start + length) * 2 > hex.length)
|
|
89
|
+
throw new Error(`invalid link location for ${source}:${name}`);
|
|
90
|
+
for (let byte = start; byte < start + length; byte++) {
|
|
91
|
+
if (occupied.has(byte)) throw new Error(`overlapping link locations for ${source}:${name}`);
|
|
92
|
+
occupied.add(byte);
|
|
93
|
+
}
|
|
94
|
+
hex = hex.slice(0, start * 2) + '0'.repeat(40) + hex.slice((start + 20) * 2);
|
|
95
|
+
links.push({ start, library: index });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (hex.length % 2 || !/^[0-9a-f]*$/i.test(hex)) throw new Error('bytecode has unresolved links or invalid hex');
|
|
100
|
+
return { hex, links };
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const implementations = artifacts.map((artifact) => {
|
|
104
|
+
const graph = new Set();
|
|
105
|
+
graphs.push(graph);
|
|
106
|
+
try {
|
|
107
|
+
// Solc can erase reference offsets when libraries were linked during
|
|
108
|
+
// compilation. Those addresses cannot be replaced safely from metadata.
|
|
109
|
+
if (hasConfiguredLibraries(artifact)) throw new Error('prelinked library artifacts need live runtime bindings');
|
|
110
|
+
return { creation: code(artifact.bytecode, graph), runtime: code(artifact.deployedBytecode, graph) };
|
|
111
|
+
} catch (error) {
|
|
112
|
+
errors.add(error.message);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
return { implementations, libraries, graphs, errors: [...errors] };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = { resolveBytecode, hasLibraryDependencies };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Discharge the `callbacks` assumption from chain state at one pinned block:
|
|
2
|
+
// every contract the reviewed code can CALL is pinned to concrete code that
|
|
3
|
+
// can never call anything back.
|
|
4
|
+
//
|
|
5
|
+
// 1. The proxy's storage is read at the pinned block for every constant slot
|
|
6
|
+
// either implementation loads.
|
|
7
|
+
// 2. Both implementations are re-analyzed with that pre-state (refining
|
|
8
|
+
// across sequential calls once earlier targets are proven silent on chain).
|
|
9
|
+
// Every reachable CALL must target a constant address on every path: a
|
|
10
|
+
// literal, or a pinned slot value read before the path could have changed it.
|
|
11
|
+
// 3. The code at every target, at the same block, must be silent: no code at
|
|
12
|
+
// all, or code whose complete reachability shows no CALL, CALLCODE,
|
|
13
|
+
// DELEGATECALL, CREATE, CREATE2 or SELFDESTRUCT. Silent code cannot run
|
|
14
|
+
// foreign code, so nothing can re-enter the reviewed contract, and it
|
|
15
|
+
// cannot replace itself. An EIP-7702 delegation is never silent.
|
|
16
|
+
//
|
|
17
|
+
// The claim covers calls executed against the pinned state: a later change
|
|
18
|
+
// to a pinned slot (an initializer run, an admin setter) can point a call
|
|
19
|
+
// elsewhere. It relies on the `hashing` assumption that mapping writes never
|
|
20
|
+
// alias a constant slot, and on deployment evidence that the proxy runs the
|
|
21
|
+
// reviewed code. Nothing here can by itself produce a release verdict.
|
|
22
|
+
const { createHash } = require('node:crypto');
|
|
23
|
+
const { rpcReader, blockRef, hex, quantity } = require('../rpc');
|
|
24
|
+
const { resolveBytecode } = require('./bytecode');
|
|
25
|
+
const { analyze, quietLibraryIndices } = require('./provenance');
|
|
26
|
+
|
|
27
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
28
|
+
const MAX_SLOTS = 512;
|
|
29
|
+
const MAX_CALLEES = 64;
|
|
30
|
+
const FOREIGN = ['CALL', 'CALLCODE', 'DELEGATECALL', 'CREATE', 'CREATE2', 'SELFDESTRUCT'];
|
|
31
|
+
const word = (n) => '0x' + n.toString(16).padStart(64, '0');
|
|
32
|
+
const address = (n) => '0x' + BigInt(n).toString(16).padStart(40, '0');
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `target`: { rpcUrl, chainId, block, proxy } (the deployment target).
|
|
36
|
+
* Returns { status: 'supported' | 'unresolved', basis, evidence }.
|
|
37
|
+
*/
|
|
38
|
+
async function bindCallees(target, { dir, artifact, baseArtifact, init = '', read: injected } = {}) {
|
|
39
|
+
const evidence = {};
|
|
40
|
+
const open = (basis) => ({ status: 'unresolved', basis, evidence });
|
|
41
|
+
const decimal = (v) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? String(v) : v);
|
|
42
|
+
const chainId = decimal(target?.chainId);
|
|
43
|
+
const block = decimal(target?.block);
|
|
44
|
+
if (typeof chainId !== 'string' || !/^[1-9][0-9]*$/.test(chainId)) return open('An exact chain ID is required.');
|
|
45
|
+
if (typeof block !== 'string' || !/^(0|[1-9][0-9]*)$/.test(block)) return open('A pinned block number (decimal string) is required.');
|
|
46
|
+
if (!ADDRESS.test(target?.proxy || '')) return open('The proxy address is required.');
|
|
47
|
+
if (String(init || '').replace(/^0x/, '')) return open('Initializer calldata changes storage before any modeled call; pinned slot values would not hold.');
|
|
48
|
+
|
|
49
|
+
const execution = resolveBytecode(dir, [baseArtifact, artifact]);
|
|
50
|
+
if (execution.errors.length || execution.implementations.some((unit) => !unit)) return open(`Runtime code is unresolved: ${execution.errors.join(' ')}`);
|
|
51
|
+
const libraries = execution.libraries.map((unit) => analyze(unit.runtime.hex, unit.runtime.links, { features: true }));
|
|
52
|
+
const quietLibraries = quietLibraryIndices(libraries);
|
|
53
|
+
const used = [...new Set(execution.graphs.flatMap((graph) => [...graph]))];
|
|
54
|
+
if (used.some((index) => !quietLibraries.has(index))) return open('A linked library can invoke foreign code; its call targets are not pinned.');
|
|
55
|
+
|
|
56
|
+
const runtimes = execution.implementations.map((unit) => unit.runtime);
|
|
57
|
+
const pass = (storage, silentCallees = null) => runtimes.map(({ hex: code, links }) =>
|
|
58
|
+
analyze(code, links, { features: true, quietLibraries, storage, silentCallees }));
|
|
59
|
+
const loads = [...new Set(pass(new Map()).flatMap((unit) => unit.constLoads))];
|
|
60
|
+
if (loads.length > MAX_SLOTS) return open(`The implementations load ${loads.length} constant slots; at most ${MAX_SLOTS} are read.`);
|
|
61
|
+
|
|
62
|
+
const read = injected || rpcReader(target.rpcUrl);
|
|
63
|
+
if (quantity(await read('eth_chainId')).toString() !== chainId) return open('RPC chain differs from the expected chain ID.');
|
|
64
|
+
const anchor = blockRef(await read('eth_getBlockByNumber', [hex(BigInt(block)), false]), BigInt(block));
|
|
65
|
+
const at = { blockHash: anchor.hash, requireCanonical: true };
|
|
66
|
+
Object.assign(evidence, { chainId, block, blockHash: anchor.hash, proxy: target.proxy.toLowerCase() });
|
|
67
|
+
|
|
68
|
+
const storage = new Map();
|
|
69
|
+
for (const slot of loads) storage.set(BigInt('0x' + slot), BigInt(await read('eth_getStorageAt', [target.proxy, word(BigInt('0x' + slot)), at])));
|
|
70
|
+
evidence.slots = Object.fromEntries([...storage].map(([slot, value]) => [word(slot), word(value)]));
|
|
71
|
+
|
|
72
|
+
const inspected = new Map(); // hex target -> callee entry
|
|
73
|
+
const silentSet = new Set(); // BigInt addresses already proven silent at this block
|
|
74
|
+
let units = pass(storage, null);
|
|
75
|
+
for (let round = 0; round < MAX_CALLEES; round++) {
|
|
76
|
+
const knownTargets = [...new Set(units.flatMap((unit) => unit.callTargets.flatMap((site) => site.targets || [])))].sort();
|
|
77
|
+
const unseen = knownTargets.filter((callee) => !inspected.has(callee));
|
|
78
|
+
if (inspected.size + unseen.length > MAX_CALLEES) {
|
|
79
|
+
return open(`The implementations reach more than ${MAX_CALLEES} distinct callees.`);
|
|
80
|
+
}
|
|
81
|
+
let grew = false;
|
|
82
|
+
for (const callee of unseen) {
|
|
83
|
+
const addr = address(BigInt('0x' + callee));
|
|
84
|
+
const code = String(await read('eth_getCode', [addr, at])).toLowerCase().replace(/^0x/, '');
|
|
85
|
+
const entry = { address: addr, codeSha256: createHash('sha256').update(Buffer.from(code, 'hex')).digest('hex') };
|
|
86
|
+
if (!code) {
|
|
87
|
+
entry.silent = 'no code';
|
|
88
|
+
silentSet.add(BigInt('0x' + callee));
|
|
89
|
+
grew = true;
|
|
90
|
+
} else if (code.startsWith('ef0100')) {
|
|
91
|
+
entry.problem = 'an EIP-7702 delegation';
|
|
92
|
+
} else {
|
|
93
|
+
const unit = analyze(code, [], { features: true });
|
|
94
|
+
const foreign = unit.features.filter((op) => FOREIGN.includes(op));
|
|
95
|
+
if (!unit.complete) entry.problem = `incomplete reachability (${unit.reason})`;
|
|
96
|
+
else if (foreign.length) entry.problem = `reachable ${foreign.join(', ')}`;
|
|
97
|
+
else {
|
|
98
|
+
entry.silent = 'no reachable foreign invocation';
|
|
99
|
+
silentSet.add(BigInt('0x' + callee));
|
|
100
|
+
grew = true;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
inspected.set(callee, entry);
|
|
104
|
+
}
|
|
105
|
+
const loudNow = [...inspected.values()].filter((entry) => entry.problem);
|
|
106
|
+
if (loudNow.length || !grew) break;
|
|
107
|
+
if (!units.some((unit) => unit.callTargets.some((site) => !site.targets))) break;
|
|
108
|
+
units = pass(storage, silentSet);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
evidence.callees = [...inspected.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([, entry]) => entry);
|
|
112
|
+
const problems = [];
|
|
113
|
+
units.forEach((unit, side) => {
|
|
114
|
+
const label = side ? 'candidate' : 'baseline';
|
|
115
|
+
if (!unit.complete) problems.push(`The ${label} reachability is incomplete with pinned storage: ${unit.reason}.`);
|
|
116
|
+
const other = unit.features.filter((op) => ['CALLCODE', 'CREATE', 'CREATE2', 'SELFDESTRUCT'].includes(op));
|
|
117
|
+
if (other.length) problems.push(`The ${label} can reach ${other.join(', ')}.`);
|
|
118
|
+
if (unit.delegatecalls.some((site) => !site.library)) problems.push(`The ${label} can DELEGATECALL code other than a linked library.`);
|
|
119
|
+
});
|
|
120
|
+
if (problems.length) return open(problems.join(' '));
|
|
121
|
+
|
|
122
|
+
const loud = evidence.callees.filter((entry) => entry.problem);
|
|
123
|
+
if (loud.length) return open(`Callee code can invoke foreign code: ${loud.map((entry) => `${entry.address} (${entry.problem})`).join('; ')}.`);
|
|
124
|
+
|
|
125
|
+
const unpinnedProblems = [];
|
|
126
|
+
units.forEach((unit, side) => {
|
|
127
|
+
const label = side ? 'candidate' : 'baseline';
|
|
128
|
+
const unpinned = unit.callTargets.filter((site) => !site.targets).map((site) => site.pc);
|
|
129
|
+
if (unpinned.length) unpinnedProblems.push(`The ${label} CALL target at ${unpinned.join(', ')} is not a pinned constant on every path.`);
|
|
130
|
+
});
|
|
131
|
+
if (unpinnedProblems.length) return open(unpinnedProblems.join(' '));
|
|
132
|
+
const targets = evidence.callees.map((entry) => entry.address);
|
|
133
|
+
return {
|
|
134
|
+
status: 'supported',
|
|
135
|
+
basis: `Pinned block ${block} (${anchor.hash}) on chain ${chainId}: every reachable CALL in both implementations targets ${targets.length ? targets.join(', ') : 'no address'}, read from constant slots of proxy ${evidence.proxy} before any write that could change them, and that code cannot invoke foreign code. Holds while those slots keep their pinned values; mapping writes are assumed never to alias a constant slot.`,
|
|
136
|
+
evidence,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { bindCallees };
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Discharge the `proxy` assumption of a transparent-proxy upgrade from chain
|
|
2
|
+
// state at one pinned block and from the reviewed bytecode. Every check must
|
|
3
|
+
// pass with concrete evidence; any failure, missing input or RPC error leaves
|
|
4
|
+
// the assumption open. Nothing here can by itself produce a release verdict.
|
|
5
|
+
//
|
|
6
|
+
// admin the proxy's ERC-1967 admin slot holds the expected ProxyAdmin, which has code
|
|
7
|
+
// implementation the proxy's implementation slot holds the reviewed baseline; no beacon is set
|
|
8
|
+
// code baseline and candidate implementations on chain match the build artifacts
|
|
9
|
+
// (immutable ranges masked)
|
|
10
|
+
// clash no implementation selector collides with the transparent proxy's admin interface
|
|
11
|
+
// initializers the candidate implementation's recognised Initializable version is at its maximum;
|
|
12
|
+
// without a recognised lock the check stays open
|
|
13
|
+
// constructor every storage slot the candidate's constructor can write is a constant slot,
|
|
14
|
+
// and each is zero on the deployed implementation (other than the Initializable slot)
|
|
15
|
+
const { rpcReader, blockRef, hex, quantity } = require('../rpc');
|
|
16
|
+
const { explore, immutablesOf } = require('./upgrade-authority');
|
|
17
|
+
|
|
18
|
+
const SLOTS = {
|
|
19
|
+
implementation: 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcn,
|
|
20
|
+
admin: 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103n,
|
|
21
|
+
beacon: 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50n,
|
|
22
|
+
initializable: 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00n, // OpenZeppelin 5 namespace
|
|
23
|
+
};
|
|
24
|
+
// The namespace slot ends in a zero byte, which the compiler may shift in, so match its 31 nonzero bytes.
|
|
25
|
+
const INITIALIZABLE_PREFIX = SLOTS.initializable.toString(16).slice(0, 62);
|
|
26
|
+
// OpenZeppelin 4 and 5 TransparentUpgradeableProxy admin functions.
|
|
27
|
+
const PROXY_SELECTORS = {
|
|
28
|
+
'f851a440': 'admin()', '5c60da1b': 'implementation()', '8f283970': 'changeAdmin(address)',
|
|
29
|
+
'3659cfe6': 'upgradeTo(address)', '4f1ef286': 'upgradeToAndCall(address,bytes)',
|
|
30
|
+
};
|
|
31
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
32
|
+
const word = (n) => '0x' + n.toString(16).padStart(64, '0');
|
|
33
|
+
|
|
34
|
+
function maskImmutables(code, ranges) {
|
|
35
|
+
let out = code.toLowerCase().replace(/^0x/, '');
|
|
36
|
+
for (const { start, length } of ranges) out = out.slice(0, start * 2) + '00'.repeat(length) + out.slice((start + length) * 2);
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `target`: { rpcUrl, chainId, block, proxy, proxyAdmin, baselineImplementation, candidateImplementation }.
|
|
42
|
+
* `artifact`, `baseArtifact`: Foundry build artifacts of candidate and baseline.
|
|
43
|
+
* Returns { status: 'supported' | 'violated' | 'unresolved', basis, evidence, problems, violations }.
|
|
44
|
+
* `violated`: a defect observed on chain at the pinned block (wrong slot, code drift, clash, open initializers,
|
|
45
|
+
* leftover constructor state). `unresolved`: a check could not be run. A violation outranks unresolved checks.
|
|
46
|
+
*/
|
|
47
|
+
async function dischargeDeployment(target, { artifact, baseArtifact, read: injected } = {}) {
|
|
48
|
+
const problems = []; // checks that could not be run
|
|
49
|
+
const violations = []; // defects observed at the pinned block
|
|
50
|
+
const evidence = {};
|
|
51
|
+
const open = (reason) => ({ status: 'unresolved', basis: reason || problems.join(' '), evidence, problems: [...problems, ...(reason ? [reason] : [])], violations: [] });
|
|
52
|
+
const violate = (check, detail) => violations.push({ check, detail });
|
|
53
|
+
// Safe-integer numbers are accepted as the same decimal value; anything else must already be a decimal string.
|
|
54
|
+
const decimal = (v) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? String(v) : v);
|
|
55
|
+
const { rpcUrl, proxy, proxyAdmin, baselineImplementation, candidateImplementation } = target || {};
|
|
56
|
+
const chainId = decimal(target?.chainId);
|
|
57
|
+
const block = decimal(target?.block);
|
|
58
|
+
if (typeof chainId !== 'string' || !/^[1-9][0-9]*$/.test(chainId)) return open('An exact chain ID is required.');
|
|
59
|
+
if (typeof block !== 'string' || !/^(0|[1-9][0-9]*)$/.test(block)) return open('A pinned block number (decimal string) is required.');
|
|
60
|
+
if (![proxy, proxyAdmin, baselineImplementation, candidateImplementation].every((a) => ADDRESS.test(a || ''))) {
|
|
61
|
+
return open('Proxy, ProxyAdmin, baseline and candidate implementation addresses are required.');
|
|
62
|
+
}
|
|
63
|
+
if (!artifact?.deployedBytecode?.object || !baseArtifact?.deployedBytecode?.object) return open('Build artifacts are required.');
|
|
64
|
+
const read = injected || rpcReader(rpcUrl);
|
|
65
|
+
if (quantity(await read('eth_chainId')).toString() !== chainId) return open('RPC chain differs from the expected chain ID.');
|
|
66
|
+
const anchor = blockRef(await read('eth_getBlockByNumber', [hex(BigInt(block)), false]), BigInt(block));
|
|
67
|
+
const at = { blockHash: anchor.hash, requireCanonical: true };
|
|
68
|
+
Object.assign(evidence, { chainId, block, blockHash: anchor.hash });
|
|
69
|
+
const slot = async (address, n) => BigInt(await read('eth_getStorageAt', [address, word(n), at]));
|
|
70
|
+
const code = async (address) => String(await read('eth_getCode', [address, at])).toLowerCase();
|
|
71
|
+
|
|
72
|
+
// admin and implementation slots
|
|
73
|
+
const admin = await slot(proxy, SLOTS.admin);
|
|
74
|
+
evidence.adminSlot = word(admin);
|
|
75
|
+
if (admin !== BigInt(proxyAdmin)) violate('admin-slot', `The proxy admin slot holds ${word(admin)}, not the expected ProxyAdmin ${proxyAdmin}.`);
|
|
76
|
+
const adminCode = await code(proxyAdmin);
|
|
77
|
+
evidence.proxyAdminHasCode = adminCode.length > 2;
|
|
78
|
+
if (adminCode.length <= 2) violate('proxy-admin-code', 'The expected ProxyAdmin has no code.');
|
|
79
|
+
const implementation = await slot(proxy, SLOTS.implementation);
|
|
80
|
+
evidence.implementationSlot = word(implementation);
|
|
81
|
+
if (implementation !== BigInt(baselineImplementation)) violate('implementation-slot', `The proxy implementation slot holds ${word(implementation)}, not the reviewed baseline.`);
|
|
82
|
+
const beacon = await slot(proxy, SLOTS.beacon);
|
|
83
|
+
evidence.beaconSlot = word(beacon);
|
|
84
|
+
if (beacon !== 0n) violate('beacon-slot', 'The proxy beacon slot is set.');
|
|
85
|
+
|
|
86
|
+
// code identity
|
|
87
|
+
for (const [label, address, art] of [['baseline', baselineImplementation, baseArtifact], ['candidate', candidateImplementation, artifact]]) {
|
|
88
|
+
const expected = art.deployedBytecode.object;
|
|
89
|
+
if (!/^(0x)?([0-9a-f]{2})+$/i.test(expected)) { problems.push(`The ${label} artifact has unlinked or invalid runtime code.`); continue; }
|
|
90
|
+
const ranges = immutablesOf(art);
|
|
91
|
+
const same = maskImmutables(await code(address), ranges) === maskImmutables(expected, ranges);
|
|
92
|
+
evidence[`${label}CodeMatches`] = same;
|
|
93
|
+
if (!same) violate(`${label}-code`, `The ${label} implementation code on chain differs from its build artifact.`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// selector clash with the proxy's admin interface
|
|
97
|
+
const selectors = Object.values(artifact.methodIdentifiers || {});
|
|
98
|
+
if (!selectors.length) problems.push('The candidate artifact lists no method identifiers.');
|
|
99
|
+
const clashes = selectors.filter((s) => PROXY_SELECTORS[s]).map((s) => PROXY_SELECTORS[s]);
|
|
100
|
+
evidence.selectorClashes = clashes;
|
|
101
|
+
if (clashes.length) violate('selector-clash', `Implementation selectors collide with the transparent proxy interface: ${clashes.join(', ')}.`);
|
|
102
|
+
|
|
103
|
+
// initializers disabled on the candidate implementation. Only a recognised lock can be observed open or closed:
|
|
104
|
+
// an integer `_initialized` (OpenZeppelin 4.6+) or the OpenZeppelin 5 namespace slot named in the runtime code.
|
|
105
|
+
// Without one, an unguarded initializer can be neither shown nor excluded, so the check stays open.
|
|
106
|
+
const entry = (artifact.storageLayout?.storage || []).find((s) => s.label === '_initialized');
|
|
107
|
+
let initSlot = SLOTS.initializable;
|
|
108
|
+
if (entry) {
|
|
109
|
+
initSlot = BigInt(entry.slot);
|
|
110
|
+
const value = await slot(candidateImplementation, initSlot);
|
|
111
|
+
const type = artifact.storageLayout.types?.[entry.type] || {};
|
|
112
|
+
const bytes = Number(String(type.numberOfBytes || 0));
|
|
113
|
+
const field = (value >> BigInt(8 * entry.offset)) & ((1n << BigInt(8 * bytes)) - 1n);
|
|
114
|
+
evidence.initialized = { slot: word(initSlot), offset: entry.offset, value: field.toString() };
|
|
115
|
+
if (type.label === 'bool' && field !== 0n) {
|
|
116
|
+
problems.push('The boolean _initialized flag is set on the candidate implementation; it does not show that every initializer is disabled.');
|
|
117
|
+
} else if (!(bytes > 0 && field === (1n << BigInt(8 * bytes)) - 1n)) {
|
|
118
|
+
violate('initializers', 'Initializers are not disabled on the candidate implementation.');
|
|
119
|
+
}
|
|
120
|
+
} else if (artifact.deployedBytecode.object.toLowerCase().includes(INITIALIZABLE_PREFIX)) {
|
|
121
|
+
const value = await slot(candidateImplementation, initSlot);
|
|
122
|
+
const version = value & ((1n << 64n) - 1n);
|
|
123
|
+
evidence.initialized = { slot: word(initSlot), offset: 0, value: version.toString() };
|
|
124
|
+
if (version !== (1n << 64n) - 1n) violate('initializers', 'Initializers are not disabled on the candidate implementation.');
|
|
125
|
+
} else {
|
|
126
|
+
problems.push('The candidate has no recognised initializer lock; that it has no open initializer is not established.');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// constructor-initialized state the proxy would not see
|
|
130
|
+
const creation = artifact.bytecode?.object;
|
|
131
|
+
const ctor = /^(0x)?([0-9a-f]{2})+$/i.test(creation || '') ? explore(creation) : { complete: false, reason: 'unlinked or invalid creation code' };
|
|
132
|
+
if (!ctor.complete) problems.push(`Constructor storage writes could not be enumerated: ${ctor.reason}.`);
|
|
133
|
+
else if (ctor.hashedStores.length || ctor.unknownStores.length || ctor.delegatedBeforeUpgrade.length) {
|
|
134
|
+
problems.push('The constructor writes computed storage slots or delegates execution.');
|
|
135
|
+
} else {
|
|
136
|
+
const written = [];
|
|
137
|
+
for (const n of ctor.stores.filter((n) => n !== initSlot)) {
|
|
138
|
+
const value = await slot(candidateImplementation, n);
|
|
139
|
+
written.push({ slot: word(n), value: word(value) });
|
|
140
|
+
if (value !== 0n) violate('constructor-state', `The constructor leaves slot ${word(n)} set on the implementation; the proxy does not see it.`);
|
|
141
|
+
}
|
|
142
|
+
evidence.constructorSlots = written;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (violations.length) {
|
|
146
|
+
return { status: 'violated', basis: violations.map((v) => v.detail).join(' '), evidence, problems, violations };
|
|
147
|
+
}
|
|
148
|
+
if (problems.length) return open(null);
|
|
149
|
+
return {
|
|
150
|
+
status: 'supported',
|
|
151
|
+
basis: `Pinned block ${block} (${anchor.hash}) on chain ${chainId}: ERC-1967 admin slot holds ProxyAdmin ${proxyAdmin.toLowerCase()}, implementation slot holds the reviewed baseline, no beacon; baseline and candidate code match their artifacts; no selector clash with the proxy admin interface; candidate initializers disabled; no constructor state left on the implementation.`,
|
|
152
|
+
evidence,
|
|
153
|
+
problems: [],
|
|
154
|
+
violations: [],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A deployment target from command-line flags ({ rpc, chain, block, proxy, 'proxy-admin',
|
|
160
|
+
* 'baseline-impl', 'candidate-impl' }), or null when no deployment flag is given. Without
|
|
161
|
+
* --block, the node's current block is read once and pinned, and every later read uses it.
|
|
162
|
+
*/
|
|
163
|
+
async function deploymentTarget(flags, read = null) {
|
|
164
|
+
const names = ['proxy', 'proxy-admin', 'baseline-impl', 'candidate-impl'];
|
|
165
|
+
if (![...names, 'chain', 'block'].some((n) => flags[n] !== undefined)) return null;
|
|
166
|
+
const missing = [...names, 'chain', 'rpc'].filter((n) => !flags[n]);
|
|
167
|
+
if (missing.length) throw new Error(`Deployment evidence needs --${missing.join(', --')}.`);
|
|
168
|
+
let block = flags.block;
|
|
169
|
+
if (block === undefined) block = quantity(await (read || rpcReader(flags.rpc))('eth_blockNumber')).toString();
|
|
170
|
+
if (!/^(0|[1-9][0-9]*)$/.test(String(block))) throw new Error('--block must be a decimal block number.');
|
|
171
|
+
return { rpcUrl: flags.rpc, chainId: String(flags.chain), block: String(block), proxy: flags.proxy, proxyAdmin: flags['proxy-admin'],
|
|
172
|
+
baselineImplementation: flags['baseline-impl'], candidateImplementation: flags['candidate-impl'] };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
module.exports = { dischargeDeployment, deploymentTarget, PROXY_SELECTORS };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Conservative effect summaries at external-call boundaries. Summaries
|
|
2
|
+
// deliberately forget external code, control flow and return-value relations.
|
|
3
|
+
const FRAMES = {
|
|
4
|
+
CALL: { context: 'callee', result: 'success-bit', writes: true },
|
|
5
|
+
CALLCODE: { context: 'caller', result: 'success-bit', writes: true },
|
|
6
|
+
DELEGATECALL: { context: 'caller', result: 'success-bit', writes: true },
|
|
7
|
+
STATICCALL: { context: 'callee', result: 'success-bit', writes: false },
|
|
8
|
+
CREATE: { context: 'new-account', result: 'address-or-zero', writes: true },
|
|
9
|
+
CREATE2: { context: 'new-account', result: 'address-or-zero', writes: true },
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
function summarizeExternalEffects(analyses) {
|
|
13
|
+
const units = analyses.flat();
|
|
14
|
+
const complete = analyses.length === 2 && analyses.every((side) => side.length) && units.every((unit) => unit.complete);
|
|
15
|
+
const features = new Set(units.flatMap((unit) => unit.features));
|
|
16
|
+
const invocations = Object.keys(FRAMES).filter((opcode) => features.has(opcode)).map((opcode) => {
|
|
17
|
+
const { context, result, writes } = FRAMES[opcode];
|
|
18
|
+
const effects = writes ? 'arbitrary' : 'unchanged';
|
|
19
|
+
return {
|
|
20
|
+
opcode, context, result,
|
|
21
|
+
descendants: writes ? 'inherit-parent-static-flag' : 'static',
|
|
22
|
+
callbacks: writes ? 'arbitrary-permitted-entrypoints' : 'arbitrary-static-entrypoints',
|
|
23
|
+
returnData: 'unconstrained',
|
|
24
|
+
success: { persistentStorage: effects, transientStorage: effects, balances: effects, logs: effects, accountCode: effects },
|
|
25
|
+
failure: { childStateAndLogs: 'rolled-back', callerInstructionEffects: 'unconstrained', returnData: 'unconstrained' },
|
|
26
|
+
open: ['callee and callback transitions', 'return-data correlations', 'gas and access effects'],
|
|
27
|
+
};
|
|
28
|
+
});
|
|
29
|
+
return {
|
|
30
|
+
schema: 'guardefi.external-frame-effects.v1',
|
|
31
|
+
reachability: complete ? 'complete' : 'incomplete',
|
|
32
|
+
invocations,
|
|
33
|
+
open: [
|
|
34
|
+
...(!complete ? ['Unknown reachable external instructions.'] : []),
|
|
35
|
+
...(invocations.length ? ['Frame summaries do not discharge paired behavioral or callback-sequence obligations.'] : []),
|
|
36
|
+
],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { summarizeExternalEffects };
|