Rand - Get random number on the chain

Warning

Lity supports built-in random function after lity v1.2.7.

Built-in Random Function

Lity provides a new built-in function rand for the gaming Dapp developers.

The function prototype is function rand() returns (uint). When calling rand(), developers will receive an random number which is generated by the following formula:

function rand() returns (uint) {
  return keccak256(Randomness Seed, Nonce, CodeHash, Counter);
}
  • The Randomness Seed is generated by Travis chain and you can find it in the difficulty field of current block header.
  • The Nonce is nonce of the transaction origin and depends on the transaction order in current block.
  • The CodeHash is the hash of caller’s contract bytecode
  • The Counter will automaticlly increase after the opRand is called.

The developers should be aware of the usage of random number. See getPureRandnum() in following example. The return value of getPureRandnum() may be the same, because of the following limitation:

  1. Randomness Seed depends on current block. It will be the same until receiving the next block.
  2. Nonce depends on the transaction order. When you test in local environment and don;t produce a new transaction, you might get the same nonce.
  3. CodeHash will not change after you deployed the contract.
  4. Counter depends on the the called time of rand(). If you call rand() twice in same code block, you will receive different results. On the other hands, if you call getPureRandnum(), the rand() is called on different code block, you may receive the same result.

Example 1

pragma lity ^1.2.7;

contract RandNumberExample {
  uint randnum;
  function getAndSetRandnum() public returns (uint) {
    randnum = rand();
    return randnum;
  }
  function getPureRandnum() public pure returns (uint) {
    return rand();
  }
}