I am creating a smart contract which simulates a lottery game: users purchase tickets from a fixed pool of tickets, and at the end, a random ticket number is drawn for the winner. I am now concerned with the process of selecting the random ticket number which is the winning ticket.

I was reading this post: How can I securely generate a random number in my smart contract?

and I still do not understand why I can't simply generate a random number in the range 1 - amount of tickets and assign that to be the winning tickets, using the equivalent of:

randomNum = 1 + (int)(Math.random() * amount_of_tickets); 

This sounds very trivial, but I do not see how it would be unfair or how it could be manipulated since every ticket would have an equal chance of being selected. It was also suggested that I should use the hash of the chain head in this computation, again I do not understand why this would be beneficial or necessary.

3 Answers 3


You can't do random numbers on Ethereum directly. You can use a service such like Oraclize to generate it. Here's a tutorial I wrote not long ago with the implementation details: https://hackernoon.com/building-a-raffle-contract-using-oraclize-e746e5edff6b


You can't use Math.random because Ethereum has no Math.random.

Ethereum has no Math.random because all calculations have to be deterministic so they can be validated by different nodes on the network, which doesn't work if they're all coming up with different numbers.


There's no such thing as Math.random on the Ethereum blockchain. If there was, miners could play the system and peak into Math.random before broadcasting a block. If broadcasting the block means they lose 100,000 ETH, they just wont broadcast it and they'll try to make a block that makes them win. They could easily cheat the system.

The most common solution to this is Oracles. An off-chain service that injects "random" (if you choose to trust them) values into the blockchain. The most popular provider of on-chain random values is probably Oraclize (Note: I have no affiliation with Oraclize)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.