015 | Ethereum Smart Contract Security | Programmer Explain
「Manipulate Lottery Outcome」 — 5/10
Goal:
To write a smart contract that "looks" fair for a lottery game.Take away: (For Solidity Smart Contract Developer)
A user will need to pay "gas" while executing "codes" in smart contract, however every operation has different gas cost.For example, 『if』and 『else』cost differently.
Step 1
Let’s assume you can get a true random number from somewhere that cannot manipulate by miner/block producer.An attacker knew the cost for 『if』and 『else』are different, then it try out the cost for winning and losing.
『if』cost more than 『else』
By using estimated gas, you are able to know how much it would cost for running certain function.Transaction Cost for both "Losing" and "Winning" path
62186Transaction Cost for "Winning" path
62176
Example for running out of gas for losing path, view on etherscan
In short. you are guaranteed to become the win the lottery by setting gas limit to 62176 instead of 62186.
Let’s recap.
A user will need to pay gas in order to run smart contract. However, in order not to run an infinite loop(drain out user’s wallet) that a contract might have. A user can set “gas limit” to avoid that from happening.
However, it has exposed a vulnerability that a user can potentially manipulate the outcome by using gas limit if a smart contract were written in a way that could be manipulated.
Feel free to check this smart contract out on Etherscan.