| name | attack-tx-analysis |
| description | Analyze blockchain attack transactions end-to-end: pull chain-specific artifacts first (EVM: traces, contract source, opcodes, selectors; Solana: transaction/meta payloads, instructions, logs, accounts, invoked program metadata), then perform the full EVM-oriented 6-phase root cause analysis with deep trust boundary drilling, attacker-contract reverse engineering, unified PoC generation, Foundry + anvil tx-prestate fork replay with deterministic assertions, and read-only risk upper bound evaluation to produce audit-grade reports. Use when the user provides a transaction hash and asks to analyze an exploit, attack, hack, or suspicious blockchain transaction. |
Attack Transaction Analysis
Pull transaction artifacts → analyze root cause following strict methodology → produce audit-grade reports.
Prerequisites
- Install Python dependencies:
pip install -r ${CLAUDE_SKILL_DIR}/requirements.txt
-
Copy config_template.json to config.json at the project working directory and fill in the required RPC/API keys. EVM networks require an Alchemy-compatible RPC URL plus an Etherscan-compatible API key; Solana only requires the RPC URL. If config.json is missing, prompt the user.
-
Heimdall (optional, for decompiling unverified contracts): binary expected at ~/.bifrost/bin/heimdall. Install via curl -L https://bifrost.sh | bash && bifrost --install heimdall.
-
Foundry (required for Fork Harness + Risk Upper Bound stages): forge, anvil, cast must be on $PATH. Install via curl -L https://foundry.paradigm.xyz | bash && foundryup.
-
Shell env (required for Fork Harness): BSC_RPC_URL (and equivalents for other networks, e.g. ETH_RPC_URL) must be exported before running anvil --fork-url "$BSC_RPC_URL" ... and forge test. Value should match the RPC URL in config.json.
Supported networks: bsc (default), eth, sepolia, polygon_amoy, solana.
Core Commands
Artifact & analysis tooling (Python)
python ${CLAUDE_SKILL_DIR}/scripts/pull_artifacts.py --network <NET> --tx <TX_HASH> [--timeout 120] [--skip-opcode] [--reuse-log]
python ${CLAUDE_SKILL_DIR}/scripts/cleanup.py --tx <TX_HASH> [--dry-run]
python ${CLAUDE_SKILL_DIR}/scripts/decompile.py
python ${CLAUDE_SKILL_DIR}/scripts/backfill_opcodes.py [--ctf ctf] [--timeout 600]
Notes:
- Use the same
pull_artifacts.py entrypoint for both EVM and Solana.
--skip-opcode and --reuse-log are EVM-specific knobs. Solana standard RPC has no opcode trace; opcode/ will contain capability notes only.
Replay harness tooling (Foundry + anvil)
Used by the Fork Harness and Risk Upper Bound stages. Full recipe lives in docs/ATTACK_TX_ANALYSIS_FORK_HARNESS.md.
anvil \
--fork-url "$BSC_RPC_URL" \
--fork-transaction-hash <TX_HASH> \
--port 8546 \
--timeout 120000 --retries 20 --fork-retry-backoff 1000 --no-rate-limit
forge test -vv
forge test --match-test testReplayAttackFromExactTxPrestate -vv
forge test --match-test testRiskUpperBoundAtTxPrestate -vv
cast chain-id --rpc-url http://127.0.0.1:8546
cast block-number --rpc-url http://127.0.0.1:8546
cast tx --rpc-url http://127.0.0.1:8546 <TX_HASH>
pull_artifacts.py Pipeline
For EVM networks:
trace_transaction RPC → parse call tree → save tx_trace_*.json + tx_calls_*.csv
- Per contract: fetch source/ABI from Etherscan → export
.sol; decompile via Heimdall if unverified
TransactionProcessor splits into transactions/<tx>/trace/, contracts/, contract_sources/
debug_traceTransaction → export to transactions/<tx>/opcode/ (--skip-opcode to skip)
- Extract selectors → query function signatures from openchain.xyz →
selectors_from_trace.json
- Generate
transactions/<tx>/README.md
For Solana:
getTransaction (json / jsonParsed / base64) → save raw payloads
- Save outer/inner instructions, logs, lamport/token balance diffs, signature status, and containing block
- Fetch all touched accounts via
getMultipleAccounts (base64 + jsonParsed) → split into accounts/
- Summarize invoked programs into
contracts/ and persist program account / ProgramData / executable bytes into contract_sources/
- Generate
opcode/capabilities.json explaining why standard Solana RPC cannot provide opcode traces
- Generate
transactions/<tx>/README.md
Artifact Directory Structure
For EVM transactions:
transactions/<tx_hash>/
├── README.md
├── tx_report.txt
├── analysis/
│ └── result.md
├── trace/
│ ├── transaction_info.json
│ ├── <index>_d<depth>_*.json
│ └── __files_index__.json
├── contracts/
│ └── <addr>.json
├── contract_sources/
│ └── <addr>/
│ ├── __index__.txt
│ ├── *.sol / *.abi.json
│ ├── decompiled/
│ │ ├── raw.sol
│ │ ├── optimized.sol
│ │ └── abi.json
│ └── selectors_from_trace.json
└── opcode/
├── tx_assembly_*.json
└── tx_assembly_*.asm.txt
For Solana transactions:
transactions/<signature>/
├── README.md
├── manifest.json
├── analysis/
│ └── result.md
├── trace/
│ ├── transaction_json.json
│ ├── transaction_jsonParsed.json
│ ├── transaction_base64.json
│ ├── instructions/
│ │ ├── __index__.json
│ │ ├── 000_outer.json
│ │ └── 000_inner_00.json
│ ├── log_messages.json
│ ├── lamport_diffs.json
│ ├── token_balance_diffs.json
│ └── summary.json
├── accounts/
│ └── <pubkey>/
│ ├── account_info_base64.json
│ ├── account_info_jsonParsed.json
│ └── summary.json
├── contracts/
│ └── <program_id>.json
├── contract_sources/
│ └── <program_id>/
│ ├── program_account_*.json
│ ├── programdata_account_*.json
│ ├── program_binary.so
│ └── summary.json
└── opcode/
└── capabilities.json
Analysis Workflow
When a user provides a transaction hash requesting attack analysis, execute strictly in this order.
Step 1: Pull Artifacts
python ${CLAUDE_SKILL_DIR}/scripts/pull_artifacts.py --network <NET> --tx <TX>
If <NET> is solana, still pull artifacts through the same command, but treat the resulting artifact set as Solana RPC materials rather than EVM trace/opcode/source materials.
Step 2: Read Methodology (must not skip, must not partially read)
Choose the methodology stack by network:
If <NET> is an EVM network
Before analysis, all 7 EVM analysis documents must be read in full. SPEC has the highest priority. After Deep Dive, the PoC/Replay, Fork Harness, and Risk Upper Bound documents must also be executed in order.
If <NET> is solana
Read only the Solana methodology document below as the primary analysis spec:
| Document | Path | Responsibility | Priority |
|---|
| SOLANA METHODOLOGY | docs/ATTACK_TX_ANALYSIS_SOLANA.md | Solana-native transaction classification, account-role analysis, CPI/value-flow closure, and output requirements | Highest |
Important scope note for Solana:
- Do not hallucinate nonexistent Solana equivalents of
debug_traceTransaction, selector mappings, storage-slot provenance, or verified-source retrieval from standard RPC.
- The EVM Deep Dive / PoC / Fork Harness / Risk Bound stack is not mandatory by default for Solana and must not be force-applied unless the user explicitly asks for a deeper custom experiment and the required artifacts/tooling actually exist.
Step 3: Execute Analysis Strictly Phase by Phase
If <NET> is solana, follow the workflow, mandatory questions, evidence hierarchy, and output template in docs/ATTACK_TX_ANALYSIS_SOLANA.md.
If <NET> is an EVM network, use the phase table below.
| Phase | Task | Required on Completion |
|---|
| 1 Triage | Read trace; identify participants / asset flows / anomalies / phase labels / accumulator buckets | SPEC self-check |
| 2 Graphs | Fund flow graph + control flow graph + Phase Map; draw Victim Subgraph + Degradation Chain when victims exist | SPEC self-check |
| 3 Hypotheses | 2-4 competing explanations per anomaly + shortest falsification; must execute when Gate is triggered | SPEC self-check + check modules |
| 4 Evidence | Advance along evidence pyramid (state writes > reproducible values > events > source code > intuition) | SPEC self-check |
| 5 Closure | Write→Read→Trigger→Profit closed loop; confidence gate | SPEC self-check |
| 6 Deliverable | One-sentence root cause + evidence + reproduction steps + fix | SPEC self-check |
| Deep Dive | Trust boundary chain → open and audit each validation function's source → deepest root cause | Must not skip |
| PoC / Replay | Read all tx artifacts including result.md → reverse engineer attacker contract → generate unified PoC → replay via RPC at attack-block context | Must not skip |
| Fork Harness | Build Foundry + anvil tx-prestate harness per ATTACK_TX_ANALYSIS_FORK_HARNESS.md; encode blocker tests, seeded simulation, and exact-prestate replay with == assertions | Must not skip when PoC/Replay produces runnable code |
| Risk Upper Bound | Per ATTACK_TX_ANALYSIS_RISK_BOUND.md, compute min(objectBalance, accumulatorRemaining) at the tx prestate and compare to the actual drain (read-only) | Must not skip after Fork Harness passes |
Available Resources During Analysis
| Resource | Path | Purpose |
|---|
| Contract source code / program artifacts | transactions/<tx>/contract_sources/ | EVM verified/decompiled code, or Solana program account / ProgramData / executable bytes |
| Trace | transactions/<tx>/trace/ | EVM call records, or Solana transaction/meta/instruction/log artifacts |
| Opcode | transactions/<tx>/opcode/ | EVM instruction-level structLogs, or Solana capability notes |
| Contract / program info | transactions/<tx>/contracts/ | Per-address or per-program metadata |
| Selector mapping | transactions/<tx>/contract_sources/<addr>/selectors_from_trace.json | EVM-only function signature lookup |
| Summary report | transactions/<tx>/tx_report.txt | EVM transaction overview |
| Prior analysis result | transactions/<tx>/analysis/result.md | Mandatory input to post-deep-dive PoC / replay stage |
Step 4: Output Results
If <NET> is solana, write transactions/<tx>/analysis/result.md per docs/ATTACK_TX_ANALYSIS_SOLANA.md, including at minimum:
- Classification and Verdict
- Participants and Roles
- Instruction Narrative / Phase Map
- Economic and State Impact
- Root Cause or Benign Explanation
- Key Evidence
- Open Questions / Blockers
- Confidence
If <NET> is an EVM network, write the following in this order, with no stage skipped:
- Phase 1–6 root cause body — per
ATTACK_TX_ANALYSIS_METHODOLOGY.md + ATTACK_TX_ANALYSIS_SPEC.md (one-sentence root cause, trigger conditions, participants, Write → Read → Trigger → Profit closed loop, key evidence, minimal reproduction, remediation).
- Deep Root Cause Analysis — per
ATTACK_TX_ANALYSIS_DEEP_DIVE.md (trust boundary chain, line-by-line audit of each validation function, deepest root cause, revisions to initial analysis).
- Reverse Engineering and Unified PoC — per
ATTACK_TX_ANALYSIS_POC_REPLAY.md (attack contract set, reverse engineering notes, minimal PoC).
- RPC Replay at Attack Block — per
ATTACK_TX_ANALYSIS_POC_REPLAY.md + ATTACK_TX_ANALYSIS_FORK_HARNESS.md (replay anchor, verdict, replay evidence, exact forge test command, on-fork deterministic numbers).
- Risk Upper Bound (at tx prestate) — per
ATTACK_TX_ANALYSIS_RISK_BOUND.md (measurements, maxDrainableCap, drained-in-this-tx, residual, binding constraint, repro pointer).
- Confidence — low / medium / high (=
min(rootCauseConfidence, replayConfidence) per ATTACK_TX_ANALYSIS_RISK_BOUND.md).
Any missing required stage must be explicitly labeled blocked (and why) instead of silently omitted.
Mandatory Rules (Must Not Violate)
Gates
Write-object-first Gate
- Trigger: settlement object shows extreme readings (reserve=dust, share price spike, health factor collapse) and transfer appears successful
- Question: "Whose ledger did the transfer actually credit?"
- Conclusion must be one of two: A (actually credited) / B (overwritten/redirected)
- Prohibited from classifying as Read-type until gate is passed
Victim-first Gate
- Trigger: third-party liquidation / batch settlement detected
- Question: "Which third parties had value extracted, and through what mechanism?"
- Must output: victims list / extraction_action / value_path
Confidence Gate
high: ≥1 write-object evidence + complete causal chain
medium: write point located but object/conditions not fully determined
low: Read-type with no gate passed
Falsification & Evidence
- Falsification order: Write before Read; skipping is prohibited
- Evidence hierarchy: state writes (SSTORE) > reproducible values > events/logs > source code/decompiled > intuition
- Negation constraint: writing "X was not observed" must include search scope + search pattern; otherwise write "X has not been located yet"
Penetration & Modules
- Trust boundary penetration: every validation/check function on the attack path must be opened and audited line-by-line. "Already closed the loop" is not a valid reason to skip
- Module triggers: when any condition in the table below is met, the full module checklist must be executed
| Module | Trigger Condition |
|---|
| A Batch Liquidation | users_to_liquidate() returns multiple / batch liquidate(victim) |
| B ERC4626 Manipulation | oracle uses convertToAssets / share exchange rate mutates within same tx |
| C Large Swap + Mechanism Migration | Banded AMM/LLAMMA + batch liquidation |
| D Swap Discovery | Batch liquidation / oracle input mutation |
| E Pool Coin Resolution | Curve exchange(i,j) appears in top swaps |
| F Supply Lever Evidence | Claims redeem/mint affects share pricing |
| G Pre-liquidation Migration Evidence | Claims "bands/mechanism caused position migration" |
| H Multi-mechanism Business Chain | Same contract called 3+ times with different function roles / accumulator bucket exists |
| I Cross-chain/Proof Verification | Cross-chain message handler / Merkle/proof verification on the path |
Stop Conditions (all must be met to converge)
- ≥1 critical write point located (including write object)
- All critical anomalies explained by a single causal chain (no residuals)
- Profit path is reproducibly closed-loop
- Every validation function on the attack path has been audited (SECURE/VULNERABLE/[OPEN])
- If Victim-first Gate was triggered: explained "why third parties became extractable"
- Deep Root Cause section appended: deepest trust-boundary defect stated and confirmed against line-by-line audits (per
ATTACK_TX_ANALYSIS_DEEP_DIVE.md)
- Reverse Engineering + Unified PoC produced with attack contract set, reverse-engineering notes, and a trace-aligned minimal PoC (per
ATTACK_TX_ANALYSIS_POC_REPLAY.md)
- RPC Replay at Attack Block:
testReplayAttackFromExactTxPrestate passes against anvil --fork-transaction-hash, with == assertions on the main settlement-object delta and final profit (per ATTACK_TX_ANALYSIS_FORK_HARNESS.md); verdict rendered as reproduced / partially_reproduced / blocked
- Risk Upper Bound:
testRiskUpperBoundAtTxPrestate passes; maxDrainableCap, drainedInThisTx, residualAfterThisTx, and the binding constraint are recorded in result.md (per ATTACK_TX_ANALYSIS_RISK_BOUND.md)
Output Requirements
result.md must include all of the following sections, in this order. A stage that could not be completed must be explicitly marked blocked with a reason — it must not be silently omitted.
- One-sentence root cause + trigger condition + 3-6 key evidence items + 5-10 step minimal reproduction + fix recommendations
- Write→Read→Trigger→Profit closed loop
- Deep Root Cause analysis section (trust boundary chain + individual audits + deepest conclusion)
- Reverse Engineering and Unified PoC section (attack contract set + reverse engineering notes + minimal PoC)
- RPC Replay at Attack Block section (replay anchor + verdict
reproduced/partially_reproduced/blocked + exact forge test command + on-fork deterministic values)
- Risk Upper Bound (at tx prestate) section (on-fork measurements +
maxDrainableCap = min(balance, accumulatorRemaining) + drainedInThisTx + residualAfterThisTx + binding constraint + repro pointer)
- Confidence rating (low/medium/high) computed as
min(rootCauseConfidence, replayConfidence)
Core Principles
- Write-first — First find "who modified the ledger" (SSTORE), then explain "what others observed." The causal chain is always Write → Read → Trigger → Profit
- Competing hypotheses — Maintain 2-4 mutually exclusive explanations per anomaly; falsify the lowest-cost one first
- Adversarial thinking — Malicious tokens/contracts will deceive you.
balanceOf, events, and return values can all be forged. Trust the SSTORE chain
- Distinguish setup from cashout — The final swap/withdraw hop is rarely the root cause; the real bug lies in the setup/accumulate/flush path
- Accumulator buckets are first-class citizens —
pending fee/reward/debt/burn/distributor credit are often exploited as attacker-controllable intermediate reservoirs
- No evidence-free negation — "X did not happen" must include search scope and pattern
- Trust boundary penetration — Audit every validation function on the attack path; "application layer is already closed" is not a reason to stop
- Evidence stratification — State writes > reproducible values > events > source code > intuition; critical conclusions must rest on high-tier evidence
Additional Resources
- For the complete 6-phase workflow, LLM strategies, and bytecode forensics playbook, see docs/ATTACK_TX_ANALYSIS_METHODOLOGY.md
- For mandatory gates, evidence thresholds, and stop conditions (highest priority), see docs/ATTACK_TX_ANALYSIS_SPEC.md
- For modular checklists triggered by specific attack patterns, see docs/ATTACK_TX_ANALYSIS_MODULES.md
- For deep root cause drilling after Phase 6, see docs/ATTACK_TX_ANALYSIS_DEEP_DIVE.md
- For the mandatory post-deep-dive attacker-contract reverse engineering, PoC generation, and RPC replay stage, see docs/ATTACK_TX_ANALYSIS_POC_REPLAY.md
- For the concrete Foundry + anvil tx-prestate fork harness (repo layout,
.t.sol matrix, deterministic assertions), see docs/ATTACK_TX_ANALYSIS_FORK_HARNESS.md
- For the defensive read-only risk upper bound evaluation, see docs/ATTACK_TX_ANALYSIS_RISK_BOUND.md
- For a reference end-to-end case study, see case_studies/tx-0x767d8a0f-lista-flap/README.md
External Dependencies
| Tool | Purpose | Authentication |
|---|
| Alchemy / EVM RPC | trace_transaction, debug_traceTransaction, eth_getCode | API key in config.json rpc_url |
| Solana RPC | getTransaction, getBlock, getSignatureStatuses, getMultipleAccounts | API key embedded in config.json rpc_url when provider requires it |
| Etherscan/BscScan | Contract source code, ABI, verification status | config.json etherscan_api_key |
| openchain.xyz | selector → function signature lookup | No authentication required |
| Heimdall-rs | EVM bytecode decompilation | Local binary ~/.bifrost/bin/heimdall |
| OpenAI API | LLM-optimized decompiled code (optional) | OPENAI_API_KEY + OPENAI_API_BASE env vars |
Foundry forge | Compile + run .t.sol replay and risk-bound tests | None; binary on $PATH |
Foundry anvil | Local tx-prestate fork via --fork-transaction-hash | Upstream RPC URL in $BSC_RPC_URL (or equivalent) |
Foundry cast | On-fork sanity probes (chain-id, block-number, tx, storage) | Same RPC URL as anvil |