Created
June 10, 2019 16:08
-
-
Save wschae/c6f6e6d476fd420862aa0e2c35930ea3 to your computer and use it in GitHub Desktop.
Commit-Reveal Lottery in Solidity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity >=0.4.0 <0.7.0; | |
contract CommitRevealLottery { | |
uint public ticketingCloses; | |
uint public revealingCloses; | |
address[] public tickets; | |
address public winner; | |
bytes32 seed; | |
mapping (address => bytes32) public commitments; | |
constructor(uint duration, uint revealDuration) public { | |
ticketingCloses = now + duration * 1 days; | |
revealingCloses = ticketingCloses + revealDuration * 1 days; | |
} | |
function buy(bytes32 commitment) public payable { | |
require(msg.value >= 0.001 ether); | |
require(now < ticketingCloses); | |
commitments[msg.sender] = commitment; | |
} | |
function createCommitment(address player, uint rand) public pure returns (bytes32) { | |
return keccak256(abi.encode(player, rand)); | |
} | |
function reveal(uint rand) public { | |
require(now >= ticketingCloses); | |
require(now < revealingCloses); | |
bytes32 hash = createCommitment(msg.sender, rand); | |
require(hash == commitments[msg.sender]); | |
seed = keccak256(abi.encode(seed, rand)); | |
tickets.push(msg.sender); | |
} | |
function drawWinner() public { | |
require(now > revealingCloses + 5 minutes); | |
require(winner == address(0)); | |
winner = tickets[uint(seed) % tickets.length]; | |
} | |
function withdraw() public { | |
require(msg.sender == winner); | |
msg.sender.transfer(address(this).balance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment