I wish to make a contract that will allow two (eventually possibly more) people to gamble on essentially flipping a coin using ethereum. One person will not be "gambling against the contract" but another user of the contract.

Is this possible considering the fact that the blockchain data is public? Both parties should supply randomness and, for example, they both have to supply a 1 or a 0 and, if they are both the same, A wins and otherwise B wins. Will it be possible to stop a malicious party from seeing the first party's input and supplying biased input itself?

Would a limit on the time between the two parties submitting work? Any hacky solutions or musings are welcome.


1 Answer 1


Yes, by using the properties of hash functions.

  • step1 with 2 transactions: A and B each submit a hash of (their bet + a random number)
  • step2 with 2 transactions: A and B disclose their bet and random number
  • as part of the 2nd transaction of step2: the contract pays the winner.

Instead of writing the whole thing, here are a few ideas:

function hashing(bool bet, bytes32 nonce) pure public returns (bytes32 hashedBet) {
    // keccak256, the important bit
    return keccak256(abi.encodePacked(bet, nonce));

function submitBet(uint betId, bytes32 hashedBet) payable public {
    // some control, for instance revert if neither A nor B
    // if did not send wager
    bets[betId][msg.sender].hashedBet = hashedBet;

function discloseBet(uint betId, bool bet, bytes32 nonce) public {
    // some control, for instance throw if neither A nor B
    // or if a bet is missing

    // Check did not lie
    require(hashing(bet, nonce) == bets[betId][msg.sender].hashedBet);

    bets[betId][msg.sender].disclosed = true;

    // Then some logic to see if the other player disclosed

    // Then some logic to pay the winner

Of course, you should also impose a deadline:

  • for A to get back its wager if B did not submit any bet.
  • for A to get back both wagers if B did not disclose, and presumably lost.
  • 2
    Some possible considerations: the time limit on the seed reveal gives each party an incentive to DoS each other. A better solution may be to hold a small part of the pot as a deposit that both parties get back by submitting their seeds. Commented Jan 25, 2017 at 18:04
  • Is the DoS attack a realistic problem? Do you mean attack the ethereum network in general in order to not allow them to submit in time or do you mean attack that specific user and if so, how? Thanks
    – EthJ
    Commented Mar 31, 2017 at 20:56
  • I think it would be DoS'ing the individual user, by flooding the IP if it was known. Commented Mar 31, 2017 at 21:02

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.