Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions blockchain/proof_of_stake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import random
from typing import List

Check failure on line 2 in blockchain/proof_of_stake.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

blockchain/proof_of_stake.py:2:1: UP035 `typing.List` is deprecated, use `list` instead


class Validator:
"""
Represents a validator in a Proof of Stake system.

Attributes:
name (str): The name of the validator.
stake (int): The amount of stake (coins) the validator holds.
"""

def __init__(self, name: str, stake: int):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

"""
Initializes a new validator with a given name and stake.

Args:
name (str): The name of the validator.
stake (int): The amount of stake the validator has.
"""
self.name = name
self.stake = stake


def choose_validator(validators: List[Validator]) -> Validator:

Check failure on line 26 in blockchain/proof_of_stake.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

blockchain/proof_of_stake.py:26:34: UP006 Use `list` instead of `List` for type annotation
"""
Selects a validator to create the next block based on the weight of their stake.

The higher the stake, the greater the chance to be selected.

Args:
validators (List[Validator]): A list of Validator objects.

Returns:
Validator: The selected validator based on weighted random selection.

Example:
>>> validators = [Validator("Alice", 50), Validator("Bob", 30), Validator("Charlie", 20)]

Check failure on line 39 in blockchain/proof_of_stake.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

blockchain/proof_of_stake.py:39:89: E501 Line too long (97 > 88)
>>> chosen = choose_validator(validators)
>>> isinstance(chosen, Validator)
True
"""
total_stake = sum(v.stake for v in validators)
weighted_validators = [(v, v.stake / total_stake) for v in validators]
selected = random.choices(
[v[0] for v in weighted_validators], weights=[v[1] for v in weighted_validators]
)
return selected[0]
Loading