Secure Random Numbers

Getting secure random numbers is a significant challenge for blockchain smart contracts. Lity pioneers an approach to access random number series from a seed in the current block header. The random seed is based on the hashes of all transactions in the current block, it is extremely difficult to manipulate even for the validator node that builds and proposes the block.

Inside the smart contract, you can access the random number series by simply calling the built-in function rand(). Below is an example.

pragma lity >=1.2.6;

contract RandDemo {
  uint x;
  function getRand () public returns (uint) {
    x = rand();
    return x;

Notice that you should NOT call rand() in a view or pure function. If the random number does not need to be recorded on the blockchain (i.e., outside of a transaction in a view function executed on a single node), it does not need to be generated by the blockchain. The calling application should simply generate a random number locally – it is much cheaper in terms of resource consumption.

Read more about the rand built-in function.