Ethernaut Coin Flip

Diogo Pereira | diogo-pereira.com
4 min readAug 23, 2022

Exploiting Bad Randomness

There are plenty of use cases where the use randomness is necessary. Due to the nature of blockchain environment, it is often the case that coding randomness behaviour on smart contracts is badly done and can insert serious vulnerabilities, which when exploited will compromise all the business security assumptions that are based upon the smart contract logic.

The next challenge implements the game of guessing the outcome of flipping a coin. Refer below for the code:

After analysing the above code, we can see that these 4 lines of code are the most interesting, because they are trying to simulate the randomness of flipping a coin:

11: uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;18: uint256 blockValue = uint256(blockhash(block.number.sub(1)));25: uint256 coinFlip = blockValue.div(FACTOR);26: bool side = coinFlip == 1 ? true : false;

--

--

Diogo Pereira | diogo-pereira.com

I help organisations build cyber-resilient applications, bring security awareness and mindset growth tips to interested individuals