SolidityIn

The DAO hack and reentrancy

Lesson 37 of 40 · Case Studies

The DAO was an investor-run fund on Ethereum that raised a huge amount of ETH in 2016. In June of that year an attacker used a reentrancy bug in its split function to drain about 3.6 million ETH, then worth tens of millions of dollars.

The bug was the pattern you met in the Ether module. The contract sent ETH to the caller before it reduced the caller's balance. The attacker's contract received the ETH, and from inside its receive code it called the split function again, which still saw the full balance and paid out again, over and over.

The response split the community. In July 2016 most of the network agreed to a hard fork that moved the stolen funds to a recovery contract. Those who disagreed kept running the original chain, which became Ethereum Classic. It remains one of the most debated decisions in blockchain history, and a clear lesson that code on a blockchain is final unless people change the chain itself.

The fixes are the ones you already know: update state before sending ETH, use a reentrancy guard, and prefer pull payments. The example below applies all three to a split-style function. Also notice that an audit mindset matters: this was a simple pattern, but it was missed in a contract holding a fortune.

contract DaoVault {
    mapping(address => uint256) public shares;
    uint256 public totalShares;
    bool private locked;

    event Withdrawn(address indexed who, uint256 amount);

    modifier nonReentrant() {
        require(!locked, "Reentrant call");
        locked = true;
        _;
        locked = false;
    }
    function join() external payable {
        shares[msg.sender] += msg.value;
        totalShares += msg.value;
    }
    function split() external nonReentrant {        // like the DAO's splitDAO
        uint256 amount = shares[msg.sender];
        require(amount > 0, "No shares");
        shares[msg.sender] = 0;                     // effects before interaction
        totalShares -= amount;
        emit Withdrawn(msg.sender, amount);
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "Transfer failed");
    }
}

Try it yourself

Move the line that sets shares to zero below the call, recompile, and then write the attacker contract that would drain this vault. Compare it with the Attacker from the Ether module.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: What was the root cause of the DAO hack?