1
1
import random
2
+ from typing import List
2
3
3
4
class Validator :
4
5
"""
5
6
Represents a validator in a Proof of Stake system.
6
-
7
+
7
8
Attributes:
8
9
name (str): The name of the validator.
9
10
stake (int): The amount of stake (coins) the validator holds.
10
11
"""
11
- def __init__ (self , name , stake ):
12
+ def __init__ (self , name : str , stake : int ):
12
13
"""
13
14
Initializes a new validator with a given name and stake.
14
15
@@ -17,34 +18,28 @@ def __init__(self, name, stake):
17
18
stake (int): The amount of stake the validator has.
18
19
"""
19
20
self .name = name
20
- self .stake = stake # Stake defines how much weight the validator has.
21
+ self .stake = stake
21
22
22
- def choose_validator (validators ) :
23
+ def choose_validator (validators : List [ Validator ]) -> Validator :
23
24
"""
24
25
Selects a validator to create the next block based on the weight of their stake.
25
26
26
27
The higher the stake, the greater the chance to be selected.
27
28
28
29
Args:
29
- validators (list ): A list of Validator objects.
30
+ validators (List[Validator] ): A list of Validator objects.
30
31
31
32
Returns:
32
33
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
33
40
"""
34
- # Total stake of all validators
35
41
total_stake = sum (v .stake for v in validators )
36
-
37
- # Create a list of validators with weights (probability of being chosen)
38
42
weighted_validators = [(v , v .stake / total_stake ) for v in validators ]
39
-
40
- # Randomly select a validator based on their stake weight
41
43
selected = random .choices ([v [0 ] for v in weighted_validators ],
42
44
weights = [v [1 ] for v in weighted_validators ])
43
45
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