Fair coin toss on the Bitcoin network

We can implement a fair coin toss game that does not require a third party based on the Bit Commitment method on the Bitcoin network.
toss_bitcoin

Suppose Alice and Bob decide to toss a coin, but they do not have a physical coin, or they want to do it via the Internet. By following the Bitcoin protocol below, they can achieve a fair coin flip.

  1. Alice and Bob each lock x bitcoins in the smart contract as shown below (note: they did not disclose their secret numbers at this time);
  2. In the new transaction, submit their respective secret numbers at the same time, and then perform an exclusive OR operation on the two secret numbers to determine whether the coin is heads or tails. If it is heads, Alice wins, otherwise Bob wins. The winner will receive all 2x Bitcoins.
contract CoinToss {
    
    
    Ripemd160 alice;
    Ripemd160 bob;
    // commitments
    Sha256 aliceHash;
    Sha256 bobHash;

    public function toss(bytes aliceNonce, bytes bobNonce, int amount, SigHashPreimage txPreimage) {
    
    
        require(Tx.checkPreimage(txPreimage));

        require(hash256(aliceNonce) == this.aliceHash);
        require(hash256(bobNonce) == this.bobHash);
        
        // last bit of XOR
        bytes head = (aliceNonce ^ bobNonce) & b'0000000000000000000000000000000000000000000000000000000000000001';

        // head -> Alice wins; tail -> Bob wins
        Ripemd160 winner = head ? this.alice : this.bob;

        // winner takes all
        bytes winnerScript = Util.buildPublicKeyHashScript(winner);
        bytes winnerOutput = Util.buildOutput(winnerScript, amount);
        require(hash256(winnerOutput) == Util.hashOutputs(txPreimage));
    }
}

Practical considerations

If one of the parties refuses to disclose their secret numbers when they discover that they have failed, other measures may need to be taken to improve. For example, you can let the loser get back half of the bitcoin he invested instead of letting the winner take it all, which can also encourage the loser to submit his secret number.

Guess you like

Origin blog.csdn.net/freedomhero/article/details/114257034