Back to Articles

Learning DeFi Security by Replaying 687 Real Hacks with Foundry

[ View on GitHub ]

Learning DeFi Security by Replaying 687 Real Hacks with Foundry

Hook

Nearly every major DeFi hack is now reproducible in your local development environment. DeFiHackLabs has cataloged 687 real exploits as executable Foundry tests, turning blockchain’s permanent record into a comprehensive security curriculum.

Context

Smart contract security education has traditionally relied on contrived examples and theoretical vulnerabilities. You’d read about reentrancy attacks in blog posts, review academic papers on oracle manipulation, or study sanitized CTF challenges. But real-world DeFi hacks involve complex interactions across multiple protocols, timing dependencies at specific block heights, and nuanced business logic flaws that only emerge in production environments.

DeFiHackLabs takes a different approach: it treats Ethereum’s immutable transaction history as a teaching database. By using Foundry’s mainnet forking capability, the repository recreates the exact blockchain state before each attack, allowing you to execute the exploit locally, step through it with a debugger, and understand precisely how the attack worked. The repository includes 687 incidents and provides what it describes as ‘101 root cause analysis of past DeFi hacked incidents’ through an accompanying Notion site. It’s the difference between reading about past security failures and accessing executable reproductions of the actual exploits.

Technical Insight

External

Local Environment

Selects Hack PoC

vm.createSelectFork

Fetches at Block N

Returns State

Contract Bytecode

Storage Slots

Balances

Calls Vulnerable

Contracts

Logs Results

Developer/Researcher

Foundry Test Suite

Mainnet Fork Engine

Archive Node RPC

Local Blockchain Fork

Exploit Execution

Analysis Output

System architecture — auto-generated

DeFiHackLabs leverages Foundry’s forking capability to recreate Ethereum mainnet state at specific block numbers, essentially creating local snapshots of blockchain conditions at the moment before attacks occurred. Each hack is implemented as a Foundry test case that recreates the vulnerable conditions and executes the exploit.

Here’s an illustrative example of how a typical PoC might be structured:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;

import "forge-std/Test.sol";

contract ExploitTest is Test {
    uint256 blocknumToForkFrom = 15_012_345; // Block before attack
    
    function setUp() public {
        vm.createSelectFork("mainnet", blocknumToForkFrom);
    }
    
    function testExploit() public {
        // 1. Take flash loan to manipulate price
        emit log_named_decimal_uint(
            "Attacker balance before",
            address(this).balance,
            18
        );
        
        // 2. Execute attack logic
        // ... exploit implementation ...
        
        // 3. Call vulnerable function
        // ... attack sequence ...
        
        emit log_named_decimal_uint(
            "Attacker balance after",
            address(this).balance,
            18
        );
    }
}

The power of this approach is in the forking mechanism. When you run these tests, Foundry fetches actual contract bytecode, storage slots, and balances from an archive node at that specific block height. You’re not mocking interfaces or stubbing dependencies—you’re interacting with real deployed contracts in their exact historical state.

The repository organizes its incidents by root cause categories visible in the README’s list of past incidents, which includes tags like ‘business logic’, ‘price oracle manipulation’, ‘reentrancy’, ‘access control’, and similar vulnerability classes. This categorization appears valuable for pattern recognition—you can study multiple attacks of the same type together to identify common characteristics.

The repository includes an educational academy section with multiple lessons on onchain transaction debugging. According to the README, these cover topics including tools, warmup exercises, writing PoCs for price oracle manipulation, MEV bot analysis, rugpull analysis, reentrancy exploits, and specific hack analysis like the Nomad Bridge incident from August 2022. The lessons are available in multiple languages including English, Chinese, Vietnamese, Korean, Spanish, and Japanese.

The README indicates you should ‘clone and install dependencies: git submodule update —init —recursive’, suggesting the repository uses git submodules for managing dependencies and interfaces needed to interact with various protocols during exploit reproduction.

Gotcha

The most significant limitation is infrastructure requirements. Running these tests requires RPC access to archive nodes, which store full historical blockchain state. Free RPC endpoints typically have rate limits that may restrict how many historical replays you can run, though the README does not specify exact costs or requirements—you’ll need to investigate archive node access options yourself.

The learning curve appears steep based on the repository structure. The README’s ‘Getting Started’ section simply points you to Foundry installation instructions and mentions cloning with submodule updates. There’s a Contributing Guidelines link, but the README itself doesn’t provide onboarding guidance for navigating 687 incident reproductions. The academy lessons exist to provide educational scaffolding, but if you’re completely new to DeFi security, you may find yourself struggling to parse exploit logic without additional context.

Another limitation: this is purely educational and retrospective, as emphasized by the disclaimer that ‘This content serves solely as a proof of concept showcasing past DeFi hacking incidents. It is strictly intended for educational purposes and should not be interpreted as encouraging or endorsing any form of illegal activities or actual hacking attempts.’ The repository teaches you to recognize vulnerabilities after they’ve been exploited, but doesn’t provide tooling to proactively detect similar flaws in new codebases. You can study patterns, but you’d still need separate static analysis or fuzzing tools to find vulnerabilities in contracts you’re auditing. The repository also cannot reproduce hacks that involved off-chain components, private key compromises, or social engineering—it’s limited to on-chain exploit logic that can be replayed via Foundry.

The repository has received grant support (mentioned in ‘Who Support Us’ section in the table of contents), suggesting community recognition, but the README doesn’t detail what tooling or analysis capabilities exist beyond the PoC reproductions themselves.

Verdict

Use DeFiHackLabs if you’re a smart contract auditor, security researcher, or protocol developer who learns best by dissecting real-world failures. The repository’s 687 incident reproductions offer unmatched hands-on experience with actual exploit patterns from blockchain history. The hands-on approach of executing exploits in a debugger can build stronger security intuition than documentation alone. Also use it if you’re investigating a recent hack and want to compare its mechanics to historical precedents—the categorization by vulnerability type facilitates pattern matching. The academy lessons provide structured learning paths for onchain debugging skills.

Skip it if you’re completely new to Solidity or DeFi (the README suggests starting elsewhere for foundational knowledge), if you need production security tooling rather than education (this is explicitly educational per the disclaimer), or if you don’t have access to archive node RPC providers. This is a research and learning resource for understanding past exploits, not a security scanner or audit framework for finding new vulnerabilities.

// ADD TO YOUR README
[![Featured on Starlog](https://starlog.is/api/badge/ai-dev-tools/sunweb3sec-defihacklabs.svg)](https://starlog.is/api/badge-click/ai-dev-tools/sunweb3sec-defihacklabs)