Back to Articles

Learning DeFi Security by Breaking It: Inside DeFiHackLabs' 689+ Exploit Reproductions

[ View on GitHub ]

Learning DeFi Security by Breaking It: Inside DeFiHackLabs' 689+ Exploit Reproductions

Hook

The $3.8 billion stolen from DeFi protocols in 2022 wasn't lost to novel zero-days—most exploits recycled the same five vulnerability patterns. DeFiHackLabs turns these expensive lessons into executable code you can debug locally.

Context

DeFi security has a knowledge distribution problem. When a protocol gets exploited for millions, the post-mortem appears as a Twitter thread or blog post with transaction hashes and vague descriptions of "flash loan attacks" or "oracle manipulation." Security researchers understand these incidents, but most developers can't translate narrative descriptions into mental models of how the exploit actually executed.

Traditional security education uses synthetic examples—intentionally vulnerable contracts created for teaching. But these sanitized scenarios miss the messy reality of production DeFi: complex protocol interactions, specific MEV bot behaviors, exact block timing requirements, and the creative ways attackers chain multiple protocols together. DeFiHackLabs emerged from this gap, leveraging Foundry's ability to fork mainnet state at specific block heights, allowing developers to replay actual exploits against the real protocols, with real balances, at the exact moment attackers struck. It's the security equivalent of an aircraft black box recorder, turning catastrophic failures into reproducible learning opportunities.

Technical Insight

The architecture brilliance of DeFiHackLabs lies in its use of Foundry's vm.createSelectFork() cheatcode to time-travel to pre-exploit blockchain states. Each test case specifies a block number where the vulnerable conditions existed, then executes the attack logic against authentic protocol deployments. This isn't simulation—you're interacting with the actual Uniswap pools, Compound markets, and bridge contracts that held millions in TVL.

Here's a simplified structure from a reentrancy exploit reproduction:

contract ExploitTest is Test {
    uint256 blocknumToForkFrom = 17_034_896;
    
    function setUp() public {
        vm.createSelectFork("mainnet", blocknumToForkFrom);
    }
    
    function testExploit() public {
        // Step 1: Flash loan acquisition
        emit log_named_decimal_uint(
            "Attacker balance before",
            attackToken.balanceOf(address(this)),
            attackToken.decimals()
        );
        
        // Step 2: Trigger vulnerable function
        vulnerableProtocol.deposit{value: flashLoanAmount}();
        
        // Step 3: Exploit reentrancy
        vulnerableProtocol.withdraw();
        
        // Step 4: Repay flash loan + profit
        emit log_named_decimal_uint(
            "Attacker profit",
            attackToken.balanceOf(address(this)) - flashLoanAmount,
            attackToken.decimals()
        );
    }
    
    // Reentrancy callback
    receive() external payable {
        if (address(vulnerableProtocol).balance > 0) {
            vulnerableProtocol.withdraw();
        }
    }
}

The repository organizes its 689+ exploits into categorical directories: reentrancy/, oracle-manipulation/, access-control/, business-logic/, and more. Each file follows a consistent template with multi-language comments explaining the vulnerability, links to post-mortems, and labeled transaction steps. This standardization means once you understand one exploit's structure, you can rapidly analyze dozens more in the same category, building pattern recognition.

What makes this especially powerful for learning is the debugging workflow. Run forge test --match-contract ExploitName -vvvv and Foundry outputs every function call, state change, and event emission. You see exactly how an attacker drained $10M: which function they called first, what parameters bypassed validation checks, how they manipulated price oracles by sandwiching their exploit between two DEX trades. The verbose output transforms abstract vulnerability descriptions into concrete execution traces.

The repository also includes comparison files showing before/after contract code for vulnerabilities that were patched. You can literally diff the vulnerable version against the fix, understanding precisely what code change prevented the exploit. For instance, comparing an unprotected withdraw() function against its secured version with nonReentrant modifier teaches more about reentrancy prevention than any theoretical explanation.

Beyond individual exploits, DeFiHackLabs documents attack composition patterns—how sophisticated exploits chain multiple protocols. One case study shows an attacker who: (1) flash-loaned USDC from Aave, (2) manipulated a Curve pool price, (3) exploited the manipulated oracle in a lending protocol, (4) arbitraged the price difference back through Uniswap, and (5) repaid the flash loan while pocketing $7M. Each step is labeled and explained, revealing how modern DeFi attacks resemble multi-stage heists more than simple bugs.

Gotcha

DeFiHackLabs demands significant prerequisite knowledge that its documentation underestimates. You need fluency in Solidity, understanding of DeFi protocol mechanics (AMMs, lending markets, oracles, bridges), and Foundry proficiency before these reproductions make sense. The repository assumes you know why flash loans enable atomic exploits, how price impact affects oracle manipulation feasibility, and what MEV bots do. Beginners will struggle to distinguish between essential exploit logic and incidental complexity from protocol interactions.

The archive node requirement creates friction. Forking mainnet at historical blocks requires either running your own archive node (expensive, terabytes of storage) or using third-party RPC providers like Alchemy or Infura with generous rate limits. Many developers hit their free tier limits quickly when running dozens of tests, and paid plans add unexpected costs to what appears to be "just cloning a repo." Tests also run slowly—forking state, executing complex DeFi transactions, and simulating MEV conditions can take 30+ seconds per test case, making rapid iteration frustrating.

The repository excels at retrospective analysis but provides limited guidance on proactive security. After understanding how 50 reentrancy attacks worked, you're better at recognizing that vulnerability class, but the repo doesn't systematically teach you how to structure security reviews, build comprehensive test suites, or integrate automated analysis tools into development workflows. It's a reference library, not a security methodology framework.

Verdict

Use if: You're a security researcher studying DeFi attack patterns, a protocol developer who learns best by debugging real exploits, an auditor building intuition for vulnerability classes beyond textbook examples, or an incident response team needing to quickly understand a new attack's mechanics. It's invaluable when you need to verify a hypothesis about an exploit or understand the precise transaction sequence of a recent hack. Skip if: You're new to Solidity or DeFi—master fundamentals through Ethernaut or Damn Vulnerable DeFi first. Also skip if you need automated security scanning tools for proactive testing rather than retrospective learning, or if you want structured educational progression rather than a reference archive. The learning curve is steep, the setup has infrastructure requirements, and the value only emerges after significant time investment understanding both the codebase organization and the DeFi ecosystem context.

// 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)