I am designing a lottery smart contract. A winning ticket number is drawn from a pool of tickets. In order to do this, I use the following code:

bytes32 blockhash = block.blockhash(block.number - 1);
uint32 winner = uint32(blockhash) % ticketamount;

Is this a reliable and secure way to do this? I was reading online about the risks associated with using the blockhash and how this could be manipulated, however I do not fully understand the risks involved and would like further clarification into the safety of using the above code.


1 Answer 1


This is not secure!

A person can wait to publish the transaction with their bet after they saw a block with a hash which would make them win! They could use a high transaction fee to get a good chance their bet would be included in the next block, at which point they would win.

A random number generator for a lottery should of course always use a random number that cannot be known by the gambler yet when they place their bet. This means you cannot use a number that was known in the past, for example the previous block hash.

  • Is there a way to do this with the current block hash? I understand this is not possible as the block has not been mined yet.
    – mankee
    Nov 15, 2017 at 20:21
  • 1
    @mankee Indeed, you cannot use the current block hash. I don't think it's possible yet to build a secure gambling system with only 1 transaction for both bet and reward.
    – Jesbus
    Nov 15, 2017 at 20:59
  • when it comes to the probability distribution of this calculation, would this be an ideal distribution, or would any ticket have a chance of being selected which is higher than the other ones?
    – mankee
    Nov 15, 2017 at 21:08
  • @mankee When using a block hash, only a miner could cheat by withholding a block in which they lose. This could cost the miner their block reward, so it might be mitigated by setting the maximum bet to be lower than the block reward. For anyone other than miners, block hashes are perfectly random.
    – Jesbus
    Nov 15, 2017 at 21:28
  • The reason i am asking is because I was reading this post about the security of using hash functions as PRNGs and how the notion of a random oracle which makes this theoretically secure cannot be achieved in practice: crypto.stackexchange.com/questions/9076/…
    – mankee
    Nov 15, 2017 at 21:34

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