|
| 1 | +import random |
| 2 | + |
| 3 | +class Validator: |
| 4 | + """ |
| 5 | + Represents a validator in a Proof of Stake system. |
| 6 | +
|
| 7 | + Attributes: |
| 8 | + name (str): The name of the validator. |
| 9 | + stake (int): The amount of stake (coins) the validator holds. |
| 10 | + """ |
| 11 | + def __init__(self, name, stake): |
| 12 | + """ |
| 13 | + Initializes a new validator with a given name and stake. |
| 14 | + |
| 15 | + Args: |
| 16 | + name (str): The name of the validator. |
| 17 | + stake (int): The amount of stake the validator has. |
| 18 | + """ |
| 19 | + self.name = name |
| 20 | + self.stake = stake # Stake defines how much weight the validator has. |
| 21 | + |
| 22 | +def choose_validator(validators): |
| 23 | + """ |
| 24 | + Selects a validator to create the next block based on the weight of their stake. |
| 25 | + |
| 26 | + The higher the stake, the greater the chance to be selected. |
| 27 | + |
| 28 | + Args: |
| 29 | + validators (list): A list of Validator objects. |
| 30 | + |
| 31 | + Returns: |
| 32 | + Validator: The selected validator based on weighted random selection. |
| 33 | + """ |
| 34 | + # Total stake of all validators |
| 35 | + total_stake = sum(v.stake for v in validators) |
| 36 | + |
| 37 | + # Create a list of validators with weights (probability of being chosen) |
| 38 | + weighted_validators = [(v, v.stake / total_stake) for v in validators] |
| 39 | + |
| 40 | + # Randomly select a validator based on their stake weight |
| 41 | + selected = random.choices([v[0] for v in weighted_validators], |
| 42 | + weights=[v[1] for v in weighted_validators]) |
| 43 | + return selected[0] |
| 44 | + |
| 45 | +# Example of validators with different stakes |
| 46 | +validators = [Validator("Alice", 50), Validator("Bob", 30), Validator("Charlie", 20)] |
| 47 | + |
| 48 | +# Select a validator based on their stake |
| 49 | +chosen_validator = choose_validator(validators) |
| 50 | +print(f"Chosen validator: {chosen_validator.name}") |
0 commit comments