Ethernaut — Level 3— CoinFlip

Zuhaib Mohammed
3 min readNov 20, 2021

To complete this level, you must have some familiarity with solidity and using Remix IDE. A good resource for learning solidity is Crypto Zombies

Click here to access the source code

Just as the name suggests, it is a simple game wherein the user has to guess the outcome (heads or tails / true or false) correctly for 10 consecutive turns. If you guess wrong the counter is set back to zero.

Before we move to the exercise, lets understand how true randomness can be achieved in a smart contract. Typically, developers try to use the globally available variables and functions like block number, block hash to generate a random number but the problem with this approach is that the code is opensource and the attacker can read the code and try to guess the possible outcome, which is totally unfair to the other uses. Randomness comes into picture specifically for dapps dealing with gambling, raffle etc., The best practice is to use the Chainlink VRF, which uses an oracle to generate and verify random numbers.

Now, lets move forward with the task at hand.

Investigation

  1. I see some contract variables defined. Have a look at variable “FACTOR”. It is defined as a constant value.
  2. There is only one function “flip()” , where user has to pass a boolean value and its return true/false based on the logic behind it.

Lets try to understand the flip function — block number is a global variable and block hash in an inbuilt function. Since block numbers are always unique, the developer of the contract is trying to generate a random value and then hashing it. Next, we are just dividing the result with the constant value declared earlier (FACTOR).

Now, we understand how the randomness is implemented. Its time to exploit but how can be do it. Simple, We need to deploy the already available contract and import the contract and precompute the result and pass it via a proxy contract.

The Solution

If you look at the code below, the blockhash of the previous block is being computed because we certainly don't really know the block number of the ongoing computation.

The Proxy Contract

That was it. Challenge completed.

The above exercise trains our brain to look at such possible loopholes in the smart contract code where in randomness is involved and if we can somehow exploit it.

Thanks for Reading!

--

--