Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,41 @@ All notable changes to SELF are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project
adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Added

- Invariant-first protocol-math lens (`self_tool/autonomous/invariants.py`).
Five new understanding facts name accounting properties the code fails to
enforce: `missing_accrue_on_value_path`, `missing_share_invariant`,
`missing_k_invariant`, `missing_health_check`, and
`tstore_delete_poison`. A conversion formula such as
`assets * totalSupply() / totalAssets()` is deliberately *not* treated as an
invariant — it prices a share without constraining one — and a bare `tstore`
is not poison unless the same function also `delete`s or `.pop()`s the entry
it describes.
- `propose_hypotheses()` emits targeted Foundry invariant handler sketches
(`INV-SHARE-BACKING`, `INV-EMPTY-VAULT`, `INV-K`, `INV-ACCRUE-FIRST`,
`INV-HEALTH`, `INV-VIEW-LOCK`, `INV-TSTORE-CLEAR`, `INV-SIG-BIND`) gated on
the detected protocol shape. They are surfaced as
`ProtocolUnderstanding.hypotheses`, in the JSON `to_dict()`, in the
retrieval `briefing()`, and in a new report section,
"Must-hold invariants (hypotheses, not proofs)".
- Second-order reentrancy fact in the deep pass: a public function that writes
value state *after* delegating to a helper performing a low-level `.call`.
Skipped when either function carries a reentrancy guard, or when the public
function makes the call itself (that case is first-order and already
covered). Reported as `AV-SECOND-ORDER-REENTRANCY` with exploit path
`PATH-SECOND-ORDER-REENTRANCY`.
- Brain playbooks `AV-SECOND-ORDER-REENTRANCY`, `AV-MISSING-ACCRUE`,
`AV-MISSING-SHARE-INVARIANT`, `AV-MISSING-K`, `AV-TSTORE-DELETE-POISON`, and
expert tactic `TAC-INVARIANT-FIRST`.

No new catalog detector IDs; `RULE_VERSION` stays `2.3.0` and catalog ↔
review-profile parity is unchanged at 161 rules. Nothing wraps an external
scanner — the invariant lens is SELF's own reasoning. Test suite is 175
(24 new in `tests/test_invariants.py`).

## [2.4.0] — 2026-08-25

### Added
Expand Down
103 changes: 102 additions & 1 deletion self_tool/autonomous/deep_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
from __future__ import annotations

import re
from typing import Dict, Optional, Sequence, Tuple
from typing import Dict, List, Optional, Sequence, Tuple

from self_tool.autonomous.invariants import TRANSIENT_KILLER_RE, TSTORE_WRITE_RE
from self_tool.autonomous.models import ExtractedContract, ExtractedFunction


Expand Down Expand Up @@ -75,6 +76,23 @@
r"mapping\s*\([^)]*?=>\s*(\w+)\s*\)\s*(?:public|private|internal|external)?\s*(\w+)",
)
DELETE_INDEX_RE = re.compile(r"\bdelete\s+(\w+)\s*\[")
# --- second-order reentrancy -------------------------------------------------
# A low-level call that hands control to the callee.
LOW_CALL_RE = re.compile(r"\.call\s*\{|\.call\s*\(")
# Reentrancy guards: a modifier or an inline status/lock flag.
REENTRANCY_GUARD_RE = re.compile(
r"\bnonReentrant\b|\bnoReentrant\b|\bnonReenter\b|\bReentrancyGuard\b|"
r"_status\s*=\s*_?NOT_ENTERED|\block\s*=\s*2\b|\b_locked\s*=\s*(?:1|true)\b",
re.IGNORECASE,
)
GUARD_MODIFIERS = {"nonreentrant", "noreentrant", "nonreenter", "noreenter", "lock", "mutex"}
# An assignment to something that looks like value / accounting state.
VALUE_WRITE_RE = re.compile(r"([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*(?:=[^=>]|\+=|-=|\*=|/=)")
VALUE_STATE_RE = re.compile(
r"balance|shares?|debt|owed|deposit|claim|reserve|credit|allowance|"
r"stake|assets?|principal|supply|collateral",
re.IGNORECASE,
)
_SKIP_FUNCS = {"constructor", "receive", "fallback", "__default__", "__init__"}


Expand All @@ -83,6 +101,12 @@ def deep_facts(contracts: Sequence[ExtractedContract], combined: str) -> Dict[st
public = [func for func in functions if _is_public(func) and func.name.lower() not in _SKIP_FUNCS]
unauth = [func for func in public if not _is_authed(func)]

second_order = False
for func, table in _public_with_helpers(contracts):
if _second_order_reentrancy(func, table):
second_order = True
break

return {
"arbitrary_erc20_from": any(_arbitrary_transfer_from(func) for func in unauth),
"arbitrary_eth_receiver": any(_arbitrary_eth_send(func) for func in unauth),
Expand All @@ -94,9 +118,30 @@ def deep_facts(contracts: Sequence[ExtractedContract], combined: str) -> Dict[st
"unchecked_lowlevel_call": any(_unchecked_call(func) for func in public),
"balance_strict_eq": any(BALANCE_EQ_RE.search(func.body or "") for func in public),
"mapping_delete_struct": _mapping_delete(combined, functions),
"second_order_reentrancy": second_order,
}


def _helper_table(contract: ExtractedContract) -> Dict[str, ExtractedFunction]:
table: Dict[str, ExtractedFunction] = {}
for func in contract.functions:
table.setdefault(func.name, func)
return table


def _public_with_helpers(
contracts: Sequence[ExtractedContract],
) -> List[Tuple[ExtractedFunction, Dict[str, ExtractedFunction]]]:
"""Public functions paired with the helper table of their own contract."""
pairs: List[Tuple[ExtractedFunction, Dict[str, ExtractedFunction]]] = []
for contract in contracts:
table = _helper_table(contract)
for func in contract.functions:
if _is_public(func) and func.name.lower() not in _SKIP_FUNCS:
pairs.append((func, table))
return pairs


def locate_deep(
contracts: Sequence[ExtractedContract],
fact: str,
Expand All @@ -107,6 +152,12 @@ def locate_deep(
public = [func for func in functions if _is_public(func) and func.name.lower() not in _SKIP_FUNCS]
unauth = [func for func in public if not _is_authed(func)]

if fact == "second_order_reentrancy":
for func, table in _public_with_helpers(contracts):
if _second_order_reentrancy(func, table):
return func.file, func.line, func.language, f"{func.contract}.{func.name}"
return None

checkers = {
"arbitrary_erc20_from": (unauth, _arbitrary_transfer_from),
"arbitrary_eth_receiver": (unauth, _arbitrary_eth_send),
Expand All @@ -115,6 +166,7 @@ def locate_deep(
"unchecked_lowlevel_call": (public, _unchecked_call),
"balance_strict_eq": (public, lambda f: bool(BALANCE_EQ_RE.search(f.body or ""))),
"mapping_delete_struct": (functions, lambda f: _mapping_delete(combined, [f])),
"tstore_delete_poison": (functions, _is_tstore_poison),
"locked_ether": (
functions,
lambda f: f.name.lower() in {"receive", "fallback"} or bool(RECEIVE_RE.search(f.body or "")),
Expand Down Expand Up @@ -232,6 +284,55 @@ def _unchecked_call(func: ExtractedFunction) -> bool:
return True


def _is_tstore_poison(func: ExtractedFunction) -> bool:
"""Locator predicate mirroring invariants._tstore_delete_poison."""
body = func.body or ""
return bool(TSTORE_WRITE_RE.search(body) and TRANSIENT_KILLER_RE.search(body))


def _is_reentrancy_guarded(func: ExtractedFunction) -> bool:
"""A reentrancy guard on this function: modifier or inline status/lock flag."""
mods = {item.lower() for item in func.modifiers}
if mods & GUARD_MODIFIERS:
return True
if any(item.lower().startswith(("nonreentrant", "noreentrant", "nonreenter", "noreenter"))
for item in mods):
return True
return bool(REENTRANCY_GUARD_RE.search(func.body or ""))


def _second_order_reentrancy(
func: ExtractedFunction,
helpers: Dict[str, ExtractedFunction],
) -> bool:
"""Public fn writes value state after delegating to a helper that ``.call``s.

First-order reentrancy (the public function making the call itself) is
already covered by ``external_call_before_write``; this is the variant a
naive sink scan misses because the low-level call hides one frame down.
"""
body = func.body or ""
if _is_reentrancy_guarded(func):
return False
# The call sits directly in the public function: first-order, not our case.
if LOW_CALL_RE.search(body):
return False
for name, helper in helpers.items():
if helper is func or name == func.name:
continue
call_site = re.search(rf"(?<![.\w]){re.escape(name)}\s*\(", body)
if not call_site:
continue
if _is_reentrancy_guarded(helper):
continue
if not LOW_CALL_RE.search(helper.body or ""):
continue
for write in VALUE_WRITE_RE.finditer(body[call_site.end():]):
if VALUE_STATE_RE.search(write.group(1)):
return True
return False


def _locked_ether(combined: str, functions: Sequence[ExtractedFunction]) -> bool:
if not RECEIVE_RE.search(combined):
return False
Expand Down
30 changes: 30 additions & 0 deletions self_tool/autonomous/exploit_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,36 @@ def synthesize_paths(
),
))

if facts.get("second_order_reentrancy") and "AV-SECOND-ORDER-REENTRANCY" not in accepted:
related = _related(
("SOL-CRIT-001", "SOL-CRIT-002", "AUTO-SECOND-ORDER-REENTRANCY"),
static_ids, auto_ids,
)
paths.append(ExploitPath(
id="PATH-SECOND-ORDER-REENTRANCY",
title="Second-order reentrancy through a payout helper",
severity="HIGH",
steps=[
"Deploy a callback contract that re-enters the vault from its receive/fallback.",
"Call the public withdraw/claim that delegates the transfer to an internal helper.",
"The helper's low-level .call hands control back while the caller's balance "
"state is still un-updated.",
"Re-enter the same entry point: the stale balance is read again and paid twice.",
"Repeat until the pool is drained, then unwind any borrowed liquidity.",
],
entry_points=[
op for op in understanding.permissionless_ops
if _mentions(op, ("withdraw", "claim", "redeem", "unstake", "pull", "cash"))
] or understanding.permissionless_ops[:6],
related_finding_ids=related,
narrative=(
"The low-level call is one frame down, so a first-frame sink scan sees a clean "
"public function. Value state is written after the delegated call returns, which "
"is the check-effects-interactions violation with extra indirection. Add "
"nonReentrant to the public entry point, not the helper."
),
))

if facts.get("uses_spot_price") and facts.get("value_depends_on_price") and "AV-ORACLE-SPOT" not in accepted:
related = _related(("SOL-HIGH-001", "LEND-HIGH-004", "AUTO-ORACLE-SPOT"), static_ids, auto_ids)
paths.append(ExploitPath(
Expand Down
Loading
Loading