0
contract Labyrinth {

  uint entropy;

  function getRandomNumber() public returns (uint) {
    entropy ^= uint(blockhash(entropy % block.number));
    return entropy;
  }

}

I found this weird gist online for generating random numbers. Please remember that, despite the code's comments (which i just removed), generating random numbers on-chain is insecure for values more than 2.5 ETH.

The blockhash function is supposed to accept inputs from 0 to 256, right... I guess I am just wondering how the above function works, if entropy is a really big number, divided by block.number (another really big number), There's no guarantee the modulo will be less than 256? or is there?

Here's another question i just asked on this: What is the "^=" operator? . I did assume that's what the ^= operator did, but figured I must be misunderstanding it because the rest of the contract doesn't make sense.

Here's the contract source: https://gist.github.com/resilience-me/69d605844973df694c613ba71439a6fa

1 Answer 1

1

I don't think it works at all, for multiple reasons.

It's using past information, so not only not random. It's also easy to compute in advance. I fiddled around a little so at least it picks a block that will probably have an interesting hash.

contract Labyrinth {

  // WARN
  // UNSAFE: DO NOT USE

  uint entropy;

  function getRandomishNumber() public returns (uint) {
    uint offset = entropy % 255 + 1; // let's go back at least one block for Remix
    uint blockNumber = block.number - offset;
    entropy ^= uint(blockhash(blockNumber));
    return entropy;
  }

}

Hope it helps.

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.