Repository navigation
Add a solc-based scanner for unreachable and unused Solidity code - #1890
Open
KillariDev wants to merge 15 commits into
Open
KillariDev wants to merge 15 commits into
KillariDev wants to merge 15 commits into
Conversation
Adds bun run check:solidity-unreachable, which analyzes solidity/contracts with solc and reports code that can never execute or is never used: statements after terminators, constant and type-decided conditions, conditions an earlier check already decides, declarations unreachable from deployable contracts, write-only state variables, unread struct fields, unproducible enum values, unused imports, and dead assembly code. References resolve through solc's declaration ids, so liveness follows overloads, overrides, and inheritance exactly. The scanner only reports; fixing findings is left to the implementer.
…onstant ranges, and off-chain and coverage evidence Adds dataflow checks (dead stores, unused parameters, unassigned named returns, modifiers that skip the function body), integer range facts and named-constant folding for conditions, constant-argument parameters, delegate routing, and opt-in evidence checks: contracts nothing deploys, emitted events no production TypeScript reads, and, with --coverage, live statements the test suite never executes.
…nches, and gate CI on a baseline Adds never-assigned state variables and struct fields (whose reads fold to the default, as do locals that keep their initializer), functions only a fixed contract may call that no Solidity calls, ranges every caller keeps an argument within, ignored return values, identical branches, and tests that read never-assigned getters. Bytecode coverage now records which way each conditional jump went as LCOV BRDA records, and the scanner reports if conditions and checks the tests only saw go one way. --baseline, --write-baseline, --changed, --sarif, and GitHub annotations let CI run the scanner: check:repository:current now fails on findings the committed baseline does not accept.
…etic-implied checks, and overwritten storage
…e checks, operand contradictions, fixed loops, and could-be-immutable state
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds
bun run check:solidity-unreachable(tooling/contracts/find-unreachable-solidity.mts), a scanner that analyzessolidity/contractswith solc (analysis only, no code generation) and reports code that can never execute or whose result is never used. It only points out issues; fixing them is left to the implementer. A follow-up PR fixes the current findings.Why
Dead branches, signatures nothing implements, never-emitted events and similar leftovers accumulate as the protocol changes, and nothing in the compiler or existing checks reports them.
How it works
References are resolved through solc's
referencedDeclarationids rather than names, so overloads, overrides, inheritance and library calls are matched exactly. Concrete contracts in deployable files are the roots. A live contract keeps its entry points and base contracts live, live code keeps what it references live, and overrides of live virtual functions in live contracts are live. Code reached only from dead code is dead.after-terminatorreturn,revert,break,continue, an infinite loop, a call that never returns, or a terminating assembly statement (Solidity and Yul)constant-conditiontautological-comparisonuint >= 0redundant-conditionx < 10thenx > 20), checks on state repeated before anything could change it, checks a modifier already made before_, bounds a checked operation proves (a - bprovesa >= b;a / bprovesb > 0), operands of&&/`state-value-conditionstatus == Status.Settledwhen nothing assignsSettledunreachable-statefixed-loopforloops whose constant bounds run the body never or at most oncecould-be-immutableconstant-returnunused-function/unused-modifier...Delegatefunctions no caller routes a delegatecall tounused-event/unused-errorlogtopic counts) and errors never raisedunused-type/unused-contractunused-variable/write-only-variableunused-struct-field/unused-enum-valueunused-import/unused-assembly-functiondead-storeunused-parameter/unassigned-returnmodifier-skips-body_, silently skipping the functionuncalled-entry-pointundeployed-contract/unconsumed-eventnew/creation code and no TypeScript names them), and emitted events no production TypeScript readsnever-executed--coverage, statements in live functions an LCOV report shows the test suite never runs, or that a function is never called at all when every line was missednever-assigned-variable/constant-struct-fielduncalled-restricted-functionrequire(msg.sender == pool), directly or through a modifier) that no live Solidity calls; roles that may be accounts are skippedignored-return-valueidentical-branchesone-way-branch--coverage,ifconditions the tests only saw go one way andrequire/assertchecks that never failedconstant-test-readOptions:
--json,--changed(only files changed since the merge base with main),--baseline=file/--write-baseline=file,--sarif=file,--coverage[=lcov path](defaults to thebun run coverage:contracts:bytecodeoutput),--production(contracts intestdirectories stop counting as users), and paths insidesolidity/contractsto narrow reporting. Vendored code, OpenOracle,Multicall3andWETH9are never reported but still count as users. A full scan takes about 20 to 30 seconds, most of it solc analysis with the WASM compiler (ZOLTAR_SOLC_NATIVE_PATHspeeds it up).solidity/ts/compile.tsgainsloadMainCompiler()so the scanner reuses the compile pipeline's source loading, import aliasing and compiler selection.CI:
check:solidity-unreachableruns with the committed baselinetooling/contracts/unreachable-solidity-baseline.jsonand is part ofcheck:repository:current, so CI fails on any finding the baseline does not accept. Under GitHub Actions the failures are also annotated on their lines. Baseline entries match file, kind, and message with numbers ignored, so edits elsewhere in a file do not invalidate them; entries that no longer occur are only reported, so a PR that fixes a baselined finding cannot break another. On currentmainthe baseline holds five findings: a test mock's never-assignedquestionForker, three test-harness functions nothing calls (setRejectETH,setConsumeAllGas,creditForkFees), andTwoWayConstantProductFactory.predictPair, which only an integration test calls.Compiler: solc 0.8.36+ gives built-ins such as
requireandrevertnegative declaration ids instead of ids near 2^32, so the scanner now recognises both numbering schemes; without that, the 0.8.39 upgrade onmainmade it miss everyrequireandrevert.Branch coverage: bytecode coverage now records which way each
JUMPIwent, under the source range it maps to, as LCOVBRDArecords (withBRF/BRH, andbranchHitsin the summary, merged across shards). The jump bookkeeping lives insolidity/ts/testSupport/coverage/jumpOutcomes.ts, which also takes the trace parsers, sotraceToSource.tsshrinks and its size allowance ratchets down to 826. With the full suite's report, the scanner finds 81 one-way branches, almost allrequirechecks whose revert no test triggers.Motivating case: scanning the pre-#1895
SecurityPoolServicesreports its never-filledpendingBurnCashqueue and the dead tail offlushBurn, which only coverage had pointed at before.Validation
bun ./tooling/testing/bun-test.mts tooling/contracts/find-unreachable-solidity.test.ts: 72 tests pass (plus 3 for baseline, SARIF, and annotation output). They compile real Solidity snippets with solc and cover each kind plus the false-positive cases found in review.bun run tsc,bun run format:check,bun run check:changed,bun run knipandgit diff --checkall pass.bun run coverage:contracts:bytecode(all tests pass in both shards), then the scanner with--coverage;test-discovery.test.tsalso asserts a real coverage worker records jump outcomes with consistent BRF/BRH totals.bun run check(which now includes the scanner) and the coverage tests that use the touched modules.