Skip to content

Commit df4c444

Browse files
authored
Created and updated proof_of_stake.py
1 parent b1c7d37 commit df4c444

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

blockchain/proof_of_stake.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import random
2+
3+
class Validator:
4+
def __init__(self, name: str, stake: int) -> None:
5+
"""
6+
Initializes a new validator with a given name and stake.
7+
8+
Args:
9+
name (str): The name of the validator.
10+
stake (int): The amount of stake the validator has.
11+
"""
12+
self.name = name
13+
self.stake = stake
14+
15+
def choose_validator(validators: list[Validator]) -> Validator:
16+
"""
17+
Selects a validator to create the next block based on the weight of their stake.
18+
19+
The higher the stake, the greater the chance to be selected.
20+
21+
Args:
22+
validators (list[Validator]): A list of Validator objects.
23+
24+
Returns:
25+
Validator: The selected validator based on weighted random selection.
26+
27+
Example:
28+
>>> validators = [Validator("Alice", 50), Validator("Bob", 30), Validator("Charlie", 20)]
29+
>>> chosen = choose_validator(validators)
30+
>>> isinstance(chosen, Validator)
31+
True
32+
"""
33+
total_stake = sum(v.stake for v in validators)
34+
weighted_validators = [
35+
(v, v.stake / total_stake) for v in validators
36+
]
37+
selected = random.choices(
38+
[v[0] for v in weighted_validators],
39+
weights=[v[1] for v in weighted_validators]
40+
)
41+
return selected[0]

0 commit comments

Comments
 (0)