Skip to content

Instantly share code, notes, and snippets.

@voith
Last active January 27, 2025 16:12
Show Gist options
  • Save voith/89ff70fdd5775ed7f60fa5c0f40bf403 to your computer and use it in GitHub Desktop.
Save voith/89ff70fdd5775ed7f60fa5c0f40bf403 to your computer and use it in GitHub Desktop.
Script to select a raffle winner using ethereum's block hash as a source of randomnness.
import hashlib
import random
def choose_weighted_winner(participants, points, block_hash):
"""
Selects a winner using a weighted random selection based on points and a block hash.
Args:
participants (list): List of participant names or IDs.
points (list): List of points corresponding to each participant.
block_hash (str): Ethereum block hash used as the random seed.
Returns:
str: The winner of the raffle.
"""
if not participants or not points:
raise ValueError("Participants and points lists cannot be empty.")
if len(participants) != len(points):
raise ValueError("Participants and points lists must have the same length.")
if not isinstance(block_hash, str) or len(block_hash) != 66 or not block_hash.startswith("0x"):
raise ValueError("Invalid block hash format.")
# Create a weighted pool based on points
weighted_pool = []
for participant, point in zip(participants, points):
weighted_pool.extend([participant] * point)
if not weighted_pool:
raise ValueError("Weighted pool is empty. Ensure points are greater than zero.")
# Convert the block hash to a random seed
seed = int(hashlib.sha256(block_hash.encode()).hexdigest(), 16)
# Use the seed to select a winner
random.seed(seed)
winner = random.choice(weighted_pool)
return winner
# Example Usage
if __name__ == "__main__":
# List of participants and their points
participants = ["Alice", "Bob", "Charlie", "Diana"]
points = [5, 3, 1, 10] # Corresponding points for each participant
# Example Ethereum block hash (replace with the real block hash)
block_hash = "0xabc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc1"
try:
winner = choose_weighted_winner(participants, points, block_hash)
print(f"The winner is: {winner}")
except ValueError as e:
print(f"Error: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment