Let's say I want to make a gambling contract. Anyone can call the createWager function to create a new bet to flip a coin. When they win, in order to collect the payment for the wager, they have to call the collectPayment function, which uses the block hash of 2 blocks after when createWager was called for RNG. Only if they won the coin flip would the collectPayment send money to the sender. Is this predictable in any way?

Example code:

contract Random {
    // Generates a random number from 0 to max based on the last block hash.
    function getRand(uint blockNumber, uint max) constant internal returns(uint) {
        return(uint(sha3(block.blockhash(blockNumber))) % max);
function collectPayment() {
    uint256 blockDepth = block.number - wagers[wager_owner].creationBlockNumber;
    if (blockDepth > waitTimeBlocks) {
        // waitTimeBlocks has passed, resolve and payout this wager.
        uint256 payoutBlock = wagers[wager_owner].creationBlockNumber + waitTimeBlocks - 1;
        uint randNum = getRand(payoutBlock, 10000);
        if (randNum < payoutOdds) {
            // Wager wins, payout wager.
            uint256 winnings = safeMult(wagers[wager_owner].wagerWei, 2);
            wagers[wager_owner].active = false;
        } else {
            // Wager loses, disable wager.
            wagers[wager_owner].active = false;

1 Answer 1


Yes and no. There's always a bit of risk involved with using block hashes as a source of entropy--if the value of the bet is far greater than a block reward, miners can potentially game the system a little bit, by simply discarding a block if they mine it and it doesn't give them a favorable number.

The other complication is that you have to ensure that the collectPayment method is called within 256 blocks of the "future" block--if not, the blockhash will always return 0, which makes the outcome pretty gameable as well.

If you're fine with these risks (and can, for example, penalize for the latter circumstance), then yeah, these can be used as a source of entropy.

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