- name
- web3-methodology-research
- description
- External research synthesis from Trail of Bits, SlowMist, ConsenSys, Immunefi, and Cyfrin. Use this for advanced audit methodology, Echidna/Medusa fuzzing setup, Slither custom detector writing, attack pattern deep dives, or the 4-phase learning roadmap.
# METHODOLOGY & RESEARCH SYNTHESIS
Sources: Trail of Bits, SlowMist, ConsenSys, Immunefi Web3 Security Library, Cyfrin Audit Course, Lido Audits Library, Nethermind PublicAuditReports.
---
## TRAIL OF BITS
### Their Toolset
| Tool | What It Does | When to Use |
|------|-------------|-------------|
| **Slither** | Static analysis for Solidity/Vyper | Always — run first |
| **Echidna** | Property-based fuzzer (write invariants, it breaks them) | Write 3-5 invariants before reading code |
| **Medusa** | Next-gen fuzzer, multi-core, parallel corpus | Deeper campaigns after Echidna |
| **Manticore** | Symbolic execution — confirms if a path is truly reachable | Specific PoC confirmation |
| **Halmos** | Symbolic unit testing — proves for ALL inputs | Math-heavy functions |
---
### Slither Commands
```bash
# Install
pip3 install slither-analyzer
# First pass — protocol overview
slither . --print human-summary
slither . --print contract-summary
# Targeted detectors
slither . --detect reentrancy-eth,reentrancy-no-eth,unchecked-lowlevel
slither . --detect arbitrary-send-erc20,controlled-delegatecall
slither . --detect uninitialized-state,uninitialized-storage
slither . --detect suicidal,controlled-array-length
# Visualization
slither . --print inheritance-graph
slither . --print function-summary
slither . --print call-graph
# Filtered run (skip tests and libs)
slither . --exclude-low --filter-paths "test|lib"
```
---
### Echidna Quick Start
```solidity
// Write invariants BEFORE fully reading the code
contract VaultInvariants {
Vault vault;
// Protocol should never owe more than it holds
function echidna_solvency() public view returns (bool) {
return vault.totalAssets() >= vault.totalDebt();
}
// Share math must be consistent
function echidna_share_math() public view returns (bool) {
return vault.balanceOf(address(this)) <= vault.totalSupply();
}
// cumulativeRewardPerShare only ever increases
function echidna_reward_monotonic() public view returns (bool) {
return vault.cumulativeRewardPerShare() >= lastRewardPerShare;
}
}
```
```bash
echidna contracts/VaultInvariants.sol --contract VaultInvariants --test-mode assertion
# With config
echidna Test.sol --contract EchidnaTest --config echidna.yaml
```
```yaml
# echidna.yaml
testLimit: 50000
seqLen: 100
workers: 4
corpusDir: corpus/
```
---
### Medusa Setup
```bash
# Install
# github.com/crytic/medusa
go install github.com/crytic/medusa@latest
# Run (coverage-guided, multi-core)
medusa fuzz --config medusa.json
# medusa.json
{
"fuzzing": {
"workers": 4,
"testLimit": 500000,
"corpusDirectory": "corpus"
}
}
```
Medusa vs Echidna: Medusa is faster on large contracts due to coverage-guided exploration. Use Echidna for first pass, Medusa for extended campaigns.
---
### Trail of Bits Audit Methodology
```
1. THREAT MODEL FIRST
- What are the assets? (tokens, governance power, user funds)
- What are the trust boundaries? (who can call what?)
- What are the attack surfaces? (entry points, external calls)
2. STATIC ANALYSIS
- Run Slither with all detectors
- Examine SlithIR output for complex functions
- Map ALL state variables and who can write them
3. WRITE INVARIANTS BEFORE READING EVERYTHING
- "totalAssets >= totalDebt always"
- "shares * pricePerShare == underlying always"
- "user can always withdraw their full deposit"
- Run Echidna. Watch it break them.
4. SYMBOLIC EXECUTION ON HIGH-VALUE PATHS
- Use Manticore/Halmos for precise reachability confirmation
- Confirms "can an attacker actually reach state X?"
5. MANUAL REVIEW — FOCUS ON
- Business logic (not syntax — Slither caught that)
- Economic invariants (is the math right under adversarial conditions?)
- Access control (who can call what, when, with what params?)
6. DIFFERENTIAL TESTING
- Compare against reference implementation
- "Function A does X. Function B does the same thing differently. Why?"
- The inconsistency IS the bug.
```
---
### Key Bug Classes From Real ToB Audits
**EVM / Solidity:**
```
REENTRANCY VARIANTS (still common)
- Cross-function: lock in depositA, reenter via depositB before state update
- Cross-contract: callback to attacker contract via safeTransfer
- Read-only: view function reads stale state during reentrant call
(Curve $70M — most underestimated variant)
ROUNDING ERRORS
- Division before multiplication: (a / b) * c vs (a * c) / b
- Wrong rounding direction (should round up for safety, rounds down)
- Precision loss in sequential operations
WEAK FIAT-SHAMIR (ZK SYSTEMS — ToB IEEE S&P 2023)
- ZK proof prover can forge proofs if transcript not fully committed
- Missing: challenge must bind all public inputs
- Check: is the verifier challenge a hash of EVERYTHING the prover touches?
ACCESS CONTROL GAPS
- Function A has onlyOwner → sibling function B does NOT
- Emergency functions callable by non-emergency roles
- Initializer called after deployment without restrictions
UNSAFE UPGRADES
- Storage slot collision between proxy and implementation
- Uninitialized implementation contract (selfdestruct vector)
- delegatecall to address from storage (attacker controls target)
SIGNATURE REPLAY
- Missing nonce in signed message
- Missing chainId in signed message
- Missing contract address in signed message
```
**DeFi-Specific (from Uniswap, Frax, Reserve Protocol, Scroll audits):**
```
LIQUIDITY MATH EDGE CASES
- Integer overflow at extreme tick values (Uniswap V3 type)
- Rounding direction matters at boundary
ORACLE MANIPULATION
- TWAP too short → manipulable in same block
- Spot price used directly → 1-tx manipulation
L2 BRIDGE TRUST
- Message replay across chain reorgs
- Missing sequence number validation
- Finality assumptions wrong for specific L2
```
---
### The "Risk Accepted" Hunt
ToB's most valuable contribution to bug bounty hunting:
```
1. Find the audit report PDF for your target protocol
(GitHub, protocol docs, "audits" page)
2. Search for "Risk Accepted" or "Acknowledged"
3. For each acknowledged finding:
- Is the root cause still in the code? → grep to verify
- Has any code been added AROUND the bug that creates new attack paths?
- Is there a NEW function that has the same missing check?
4. This is valid because:
- Protocol explicitly said "we won't fix this"
- BUT: if new code makes it exploitable → that is a NEW bug
```
---
### ToB Grep Arsenal
```bash
# Weak Fiat-Shamir candidates (ZK verifiers)
grep -rn "keccak256\|hash\|challenge" contracts/ | grep -v "nonce\|chainId\|address(this)"
# Reentrancy: transfers before state updates
grep -rn "transfer\|safeTransfer\|call{value" contracts/ -B5 | grep -v "nonReentrant"
# Rounding direction
grep -rn "/ totalSupply\|/ totalAssets\|/ reserves\|/ shares" contracts/
# Then check: is result used for deposit (round down = safe) or withdraw (round up = safe)?
# Uninitialized proxy
grep -rn "initialize\|_disableInitializers\|initializer" contracts/
# Is implementation contract protected from direct initialization?
# Missing chainId in signatures
grep -rn "abi.encodePacked\|abi.encode" contracts/ | grep -v "chainId\|block.chainid"
```
---
### ToB Key Papers
| Paper | Why It Matters |
|-------|---------------|
| [Weak Fiat-Shamir Attacks](https://eprint.iacr.org/2023/691) | Breaks ZK proofs — critical if target uses ZK |
| [What are the Actual Flaws in Important Smart Contracts?](https://github.com/trailofbits/publications/blob/master/papers/smart_contract_flaws_fc2020.pdf) | Ground truth on real Solidity bugs |
| [Echidna: Effective, Usable, and Fast Fuzzing](https://github.com/trailofbits/publications/blob/master/papers/echidna_issta2020.pdf) | Master fuzzing methodology |
**Free Guides:**
```
Testing Handbook: https://appsec.guide/
ZKDocs (ZK vulnerabilities): https://www.zkdocs.com/
Secure Smart Contracts: https://secure-contracts.com/
```
---
## SLOWMIST LEARNING ROADMAP
### The 4-Phase Path
```
Phase 1: Foundation (1-3 months) → Solidity + EVM + Ethernaut
Phase 2: DeFi Protocols & Real Hacks (2-4 months) → AMMs, lending, bridges + reproduce hacks
Phase 3: EVM Internals + Advanced (3-6 months) → Storage, proxies, fuzzing, first contest
Phase 4: Multi-Chain + Specialization (ongoing) → Pick your chain + live Immunefi bounties
```
---
### Phase 1: Foundation
**Blockchain Basics:**
- Ethereum accounts, transactions, blocks, gas
- Mempool: pending transactions, frontrunning mechanics
- Storage: world state, Merkle-Patricia trees, slot layout
**Solidity (Essential Level):**
- Data types, memory vs storage vs calldata vs stack
- Function visibility: public, external, internal, private
- Low-level: `call`, `delegatecall`, `staticcall`, `create`, `create2`
- Assembly (Yul): inline assembly, memory layout
**Key Resources:**
```
1. Solidity docs: docs.soliditylang.org (read ALL of it)
2. Cyfrin Updraft: free courses, beginner to advanced
3. "Mastering Ethereum" — Antonopoulos (Chapters 1–7)
4. Solidity by Example: solidity-by-example.org
```
**Practice:**
```
1. Ethernaut: ethernaut.openzeppelin.com — 30 challenges (complete ALL before Phase 2)
2. Capture The Ether: capturetheether.com — foundational math/crypto bugs
3. Damn Vulnerable DeFi: damnvulnerabledefi.xyz — do after Phase 2
```
**Phase 1 checkpoint:**
- [ ] Can write a Solidity contract without referencing docs
- [ ] Understand storage slot layout (slots, packing, mappings)
- [ ] Completed all Ethernaut challenges
- [ ] Can explain reentrancy, integer overflow, access control bugs verbally
---
### Phase 2: DeFi Protocols & Real Hacks
**Protocols to Understand Deeply (Tier 1 — composes with everything):**
```
1. Uniswap V2/V3 — AMM formula x*y=k, flash swaps, TWAP oracle
2. Aave V3 — aTokens, flash loans, health factor + liquidation
3. Compound V2/V3 — cTokens, borrow/supply rates
4. ERC4626 — shares vs assets, first depositor attack, rounding direction
```
**How to Study Real Hacks:**
```
1. Read the post-mortem (rekt.news, medium, blog)
2. Find the transaction on Etherscan
3. Trace on Phalcon/Tenderly
4. Find the PoC: git clone https://github.com/SunWeb3Sec/DeFiHackLabs
5. Run it: forge test -vvv --contracts src/test/YEAR-MONTH/HackName_exp.sol
6. Add comments explaining every line
```
**Hacks to Study (priority order):**
```
1. Cream Finance (Oct 2021) — $130M — flash loan + price manipulation
2. Euler Finance (Mar 2023) — $197M — donation attack + liquidation
3. Mango Markets (Oct 2022) — $117M — self-oracle manipulation
4. Nomad Bridge (Aug 2022) — $200M — zero-value as trusted root
5. Beanstalk (Apr 2022) — $182M — flash loan governance
6. Curve Finance (Jul 2023) — $70M — Vyper compiler reentrancy
7. Wormhole (Feb 2022) — $320M — fake sysvar on Solana
8. Balancer (Aug 2023) — $2M — read-only reentrancy
9. Poly Network (Aug 2021) — $610M — arbitrary external call
10. Compound Governance (Sep 2022) — $150M — proposal bug
```
**Audit Reports to Read:**
```
Solodit (solodit.cyfrin.io) — 50K+ findings, searchable
Code4rena (code4rena.com/reports) — 700+ public reports
Sherlock (sherlock.xyz) — all public after contest
github.com/trailofbits/publications
github.com/spearbit/portfolio
github.com/ConsenSys/Diligence-Audit-Reports
```
**Phase 2 checkpoint:**
- [ ] Can trace a real hack from post-mortem to running PoC
- [ ] Understand all 4 Tier-1 DeFi protocols
- [ ] Read 10+ audit reports, categorized findings by bug class
- [ ] Completed Damn Vulnerable DeFi challenges
---
### Phase 3: EVM Internals + Advanced Techniques
**Storage Layout:**
```
Every contract has 2^256 storage slots
- Slot 0: first state variable
- Mapping key at slot n: keccak256(abi.encode(key, n))
- Dynamic array at slot n: length at n, elements at keccak256(n) + i
- String < 32 bytes: packed in one slot
```
**Key Opcodes for Auditors:**
```
DELEGATECALL — executes code in caller's context (storage collision risk)
STATICCALL — cannot modify state (no writes, no events)
CREATE2 — deterministic address (front-running, same-address malice)
SELFDESTRUCT — force-feeds ETH (breaks balance assumptions)
TSTORE/TLOAD — transient storage (post-Cancun, cleared each tx)
```
**Proxy Patterns:**
```
Transparent Proxy: admin controls upgrades, user calls go to impl
UUPS (EIP-1822): upgrade logic IN the implementation — protect _authorizeUpgrade()
Beacon Proxy: all proxies point to Beacon — one upgrade changes ALL
```
**Symbolic Execution:**
```bash
pip install halmos
halmos --contract ContractName --function testSymbolic
# Proves/disproves invariants for ALL possible inputs (not just sampled)
```
**Phase 3 checkpoint:**
- [ ] Can calculate any storage slot manually
- [ ] Understand all 3 proxy patterns and their attack surfaces
- [ ] Can write Echidna fuzzing properties for any protocol
- [ ] First Code4rena/Sherlock contest submitted
---
### Phase 4: Specialization
**Choose one:**
| Track | Chain | Tools | Key Bugs |
|-------|-------|-------|----------|
| EVM DeFi | Ethereum, Arbitrum, Base | Slither, Echidna, Foundry | Accounting desync, oracle, reentrancy |
| Solana | Solana | Sec3 X-Ray, Trident, Soteria | Missing signer check, remaining_accounts |
| Cross-Chain Bridges | Any | Tenderly, Phalcon | Message replay, zero-value trusted root |
| ZK Systems | Any | Halmos, ZKDocs | Unsound constraints, missing range checks |
| Move (Sui/Aptos) | Sui, Aptos | Move Prover | Wrong ability annotations, missing capability |
**SlowMist's 8-Step Audit Methodology:**
```
1. Information Collection — docs, design, scope (exact commit hash)
2. Risk Item Sorting — list all fund-holding components, rank by TVL
3. Code Review (line by line) — track state changes, external calls, access control
4. Testing and Verification — run existing tests, write PoC for suspects
5. Security Testing (Automated) — Slither, Aderyn, Mythril
6. Discussion and Review — classify severity, remove false positives
7. Report Writing — use standard template, quantify impact in USD
8. Fix Review — re-audit after fixes, check for regressions
```
**SlowMist Security Checklist (Condensed):**
```
Arithmetic:
- [ ] Division before multiplication? (should multiply first)
- [ ] unchecked {} blocks with user input?
- [ ] Type casts (uint256 → uint128 → uint64)? Check each step.
Access Control:
- [ ] initialize() callable again? After deployment?
- [ ] Role assignment in constructor: complete? Missing any role?
- [ ] Two-step ownership transfer?
Reentrancy:
- [ ] All external calls follow CEI?
- [ ] nonReentrant on all token-transfer functions?
- [ ] Cross-function reentrancy: shared state between two functions?
- [ ] Read-only reentrancy: view function read during external call?
Business Logic:
- [ ] Token accounting: uses balanceBefore/After not amount for fee tokens?
- [ ] Rounding direction: who benefits from rounding? (should favor protocol)
- [ ] Complete paths: does EVERY exit path update ALL state?
- [ ] Sibling functions: do all have the same guards?
Oracle / Price:
Auf GitHub ansehen