-
-
Save alexvandesande/259b4ffb581493ec0a1c to your computer and use it in GitHub Desktop.
contract random { | |
/* Generates a random number from 0 to 100 based on the last block hash */ | |
function randomGen(uint seed) constant returns (uint randomNumber) { | |
return(uint(sha3(block.blockhash(block.number-1), seed ))%100); | |
} | |
/* generates a number from 0 to 2^n based on the last n blocks */ | |
function multiBlockRandomGen(uint seed, uint size) constant returns (uint randomNumber) { | |
uint n = 0; | |
for (uint i = 0; i < size; i++){ | |
if (uint(sha3(block.blockhash(block.number-i-1), seed ))%2==0) | |
n += 2**i; | |
} | |
return n; | |
} | |
} |
@alexvandesande
Could we change n += 2**i;
to n |= 2**i;
for lower gas cost ?
+
is ADD
|
is OR
it doesn't work.
Tried to run it in remix ide:
Error encoding arguments: TypeError: Cannot read property 'toArray' of undefined
Hey Guys!
I'm new to solidity, so please apologize my ignorance. I'm not sure if I get it, but If you need to provide a random "seed" as input, then this code is only a transformation of a random number?
Thanks
@felipe-cunha as you see in the Solidity documentation here, the seed is concatenated to the blockhash (which is another seed) for added complexity. No randomness was generated if I'm not wrong, only manipulation of a number which was not known until the block is mined.
Hey @alexvandesande, in randomGen()
which part of the function ensures that a number between 0 and 100 is generated? Is it the %100?
In the case of the lottery, the seed provided to the function can be used to remove the interference from all the parties. Like this:
The seed is selected by the 'house' previous to the beginning of the lottery. The house encrypts it and provides a public key for it.
When the block at which the lottery plays is reached, the house uses the seed (known only to the house until that point) and the blockhash to calculate the random number. The house publishes the private key allowing the seed word to be decrypted so that everyone who wishes can verify the process.
In this approach:
The miners can influence the blockhash but not the seed.
The house knows the seed but not the blockhash
The ticket holders can verify the seed.
Other than that, the blockhash should work perfectly fine for random number generation in anything else.
Any objections to this?
It's fully functional on the testnet, just going through some code review before it's deployed on the mainnet.