Skip to content

Commit 28df0f3

Browse files
authored
Updated proof_of_stake.py
1 parent f467cec commit 28df0f3

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

blockchain/proof_of_stake.py

+12-17
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import random
2+
from typing import List
23

34
class Validator:
45
"""
56
Represents a validator in a Proof of Stake system.
6-
7+
78
Attributes:
89
name (str): The name of the validator.
910
stake (int): The amount of stake (coins) the validator holds.
1011
"""
11-
def __init__(self, name, stake):
12+
def __init__(self, name: str, stake: int):
1213
"""
1314
Initializes a new validator with a given name and stake.
1415
@@ -17,34 +18,28 @@ def __init__(self, name, stake):
1718
stake (int): The amount of stake the validator has.
1819
"""
1920
self.name = name
20-
self.stake = stake # Stake defines how much weight the validator has.
21+
self.stake = stake
2122

22-
def choose_validator(validators):
23+
def choose_validator(validators: List[Validator]) -> Validator:
2324
"""
2425
Selects a validator to create the next block based on the weight of their stake.
2526
2627
The higher the stake, the greater the chance to be selected.
2728
2829
Args:
29-
validators (list): A list of Validator objects.
30+
validators (List[Validator]): A list of Validator objects.
3031
3132
Returns:
3233
Validator: The selected validator based on weighted random selection.
34+
35+
Example:
36+
>>> validators = [Validator("Alice", 50), Validator("Bob", 30), Validator("Charlie", 20)]
37+
>>> chosen = choose_validator(validators)
38+
>>> isinstance(chosen, Validator)
39+
True
3340
"""
34-
# Total stake of all validators
3541
total_stake = sum(v.stake for v in validators)
36-
37-
# Create a list of validators with weights (probability of being chosen)
3842
weighted_validators = [(v, v.stake / total_stake) for v in validators]
39-
40-
# Randomly select a validator based on their stake weight
4143
selected = random.choices([v[0] for v in weighted_validators],
4244
weights=[v[1] for v in weighted_validators])
4345
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

Comments
 (0)