Skip to content

Invariant-first protocol-math lens + second-order reentrancy - #2

Open
arena-ai-coding-agent[bot] wants to merge 1 commit into
mainfrom
arena/01a03a69-self-smart-contract-auditing-t
Open

arena-ai-coding-agent[bot] wants to merge 1 commit into
mainfrom
arena/01a03a69-self-smart-contract-auditing-t

Conversation

@arena-ai-coding-agent

Copy link
Copy Markdown
Contributor

What this adds

Sink-hunting finds the line that looks wrong. Invariants find the property that is missing. This PR adds the other half of an expert review: the accounting properties a protocol is supposed to preserve, and whether the source actually asserts them anywhere.

self_tool/autonomous/invariants.py (new)

Five facts, each an unenforced property rather than a suspicious line:

Fact Fires when
missing_accrue_on_value_path a deposit/withdraw/liquidate/rebalance path reads a share price or interest index without settling accrual on that path (one level of helper indirection is followed)
missing_share_invariant share math exists but no require/assert ties totalSupply back to totalAssets
missing_k_invariant constant-product reserves are mutated with no non-decreasing k check and no Uniswap-style _update hook
missing_health_check a borrow/liquidate/withdraw path moves collateral or debt with no solvency check on that path
tstore_delete_poison a transient slot outlives a delete/.pop() of the entry it describes

Two rules keep this honest, both pinned by tests:

  • A conversion formula is not an invariant. assets * totalSupply() / totalAssets() prices a share; it constrains nothing. Only require/assert expressions count as enforced properties — so a vault whose only share-related construct is that formula still correctly reports missing_share_invariant.
  • A bare tstore is not poison. It only fires when the same function also deletes or .pop()s the storage that slot describes. Normal EIP-1153 usage stays quiet.

propose_hypotheses() emits Foundry handler sketches gated on the detected protocol shape — INV-SHARE-BACKING, INV-EMPTY-VAULT, INV-K, INV-ACCRUE-FIRST, INV-HEALTH, INV-VIEW-LOCK, INV-TSTORE-CLEAR, INV-SIG-BIND. These are hypotheses to falsify, never claims of proof.

deep_scan.py — second-order reentrancy

A public function that writes value state after delegating to a helper performing a low-level .call. Skipped when either the public function or the helper carries a reentrancy guard, or when the public function makes the call itself — that case is first-order and already covered by external_call_before_write. All four skip conditions plus write ordering are tested.

Wiring

understand.py · models.py (hypotheses on ProtocolUnderstanding, to_dict, briefing) · reason.py (_DEEP_PLAYBOOK_FACTS for the five AVs) · report.py (new "Must-hold invariants (hypotheses, not proofs)" section) · exploit_paths.py (PATH-SECOND-ORDER-REENTRANCY) · brain (5 AV playbooks + TAC-INVARIANT-FIRST).

Constraints held

  • No new catalog detector IDs — still 161, catalog ↔ review-profile parity passes.
  • RULE_VERSION stays 2.3.0.
  • No external scanner is wrapped. The invariant lens is SELF's own reasoning; Slither/Echidna appear only as prose references to public detector classes, matching how existing playbooks already cite them.
  • No unpublished 0-days. Every real_incidents entry points at a documented public class (The DAO CEI violation, Compound exchangeRateStored vs exchangeRateCurrent, ERC-4626 inflation, Uniswap V2 _update, EIP-1153 semantics).
  • Offline self TARGET and self autonomous TARGET both verified; offline guard test still passes.

Verification

All seven CI gates run locally against a clean venv:

compileall                 OK
unit tests                 Ran 175 tests — OK
catalog<->profile parity   parity OK
offline guard              Ran 2 tests — OK
CLI smoke                  --version / --list-detectors / --knowledge-status OK
calibration smoke          calibration OK across 3 detectors
RULE_VERSION / detectors   2.3.0 / 161

Pyflakes is clean on every file this PR touches. The four warnings it reports (models.py unused Optional, reason.py unused Dict/Iterable, report.py unused counts) reproduce identically on the pre-change files at HEAD, so they are pre-existing and left alone.

Note on the test count

The brief expected 175 = 164 on main + 11 new. The actual baseline on main is 151, not 164 — verified by exporting main's tree with git archive and running its suite independently:

$ git rev-list --count main
1
$ python -m unittest discover -s tests -p "test_*.py"   # pristine main tree
Ran 151 tests — OK      # zero skipped, zero failures

PR #1 was squash-merged into the single parentless commit 9b332df, and no test files exist outside tests/. Rather than pad with 13 filler tests to hit the stated number, this PR lands 24 real tests so the suite still ends at 175 — the 11 specified cases plus 13 more covering the guard/ordering skip conditions, the locate_deep locator, .pop() poisoning, accrual through helper indirection, the hypotheses model surface, the playbook↔fact mapping, and end-to-end finding/path/report integration.

The referenced commits 47a1c40 and 9d803c2 do not exist as objects in this repository (git cat-file -t fails for both). The content described for 47a1c40 — read-only reentrancy, TSTORE residue, Permit2, EIP-1271, CREATE2 — is present in the tree, so it landed via the squash; only the SHAs are gone.

Sink-hunting finds the line that looks wrong; invariants find the property
that is missing. This adds the other half of an expert review: the accounting
properties a protocol is supposed to preserve, and whether the source actually
asserts them anywhere.

self_tool/autonomous/invariants.py (new)
  Five facts, each an unenforced property rather than a suspicious line:
    missing_accrue_on_value_path  value path prices against a rate it never
                                  accrues (one level of helper indirection is
                                  followed)
    missing_share_invariant       share math with no require/assert tying
                                  totalSupply back to totalAssets
    missing_k_invariant           constant-product reserves mutated with no
                                  non-decreasing k check and no _update hook
    missing_health_check          borrow/liquidate/withdraw moves collateral or
                                  debt without a solvency check on that path
    tstore_delete_poison          transient slot outliving a delete/.pop of the
                                  entry it describes

  Two rules keep this honest. A conversion formula such as
  assets * totalSupply() / totalAssets() is NOT an invariant: it prices a
  share without constraining one, so only require/assert expressions count as
  enforced properties. And a bare tstore is NOT poison unless the same function
  also deletes or pops the storage that slot describes.

  propose_hypotheses() emits Foundry handler sketches gated on the detected
  protocol shape (INV-SHARE-BACKING, INV-EMPTY-VAULT, INV-K, INV-ACCRUE-FIRST,
  INV-HEALTH, INV-VIEW-LOCK, INV-TSTORE-CLEAR, INV-SIG-BIND). These are
  hypotheses to falsify, never claims of proof.

deep_scan.py
  second_order_reentrancy: a public function that writes value state AFTER
  delegating to a helper performing a low-level .call. Skipped when either the
  public function or the helper carries a reentrancy guard, or when the public
  function makes the call itself — that is first-order and already covered by
  external_call_before_write. Plus a locator so findings point at the right fn.

Wiring
  understand.py    facts.update(invariant_facts(...)), hypotheses, arch notes
  models.py        ProtocolUnderstanding.hypotheses + to_dict + briefing
  reason.py        _DEEP_PLAYBOOK_FACTS for the five new AVs
  report.py        "Must-hold invariants (hypotheses, not proofs)" section
  exploit_paths.py PATH-SECOND-ORDER-REENTRANCY
  brain            five AV playbooks + TAC-INVARIANT-FIRST

Constraints held: no new catalog detector IDs (still 161), RULE_VERSION stays
2.3.0, catalog <-> review-profile parity intact, no external scanner is
wrapped. Test suite 151 -> 175 (24 new in tests/test_invariants.py).

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant