Skip to content
Closed
Show file tree
Hide file tree
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
8 changes: 7 additions & 1 deletion backend/consensus/vrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ def get_validators_for_transaction(
num_validators = min(num_validators, len(nodes))

total_stake = sum(validator["stake"] for validator in nodes)
probabilities = [validator["stake"] / total_stake for validator in nodes]
if total_stake == 0:
# All validators have zero stake (e.g. internally-created validators in
# protocol_rpc/endpoints.py). Dividing by zero crashed the consensus
# worker, so fall back to a uniform distribution across equal-stake nodes.
probabilities = [1 / len(nodes)] * len(nodes)
else:
probabilities = [validator["stake"] / total_stake for validator in nodes]

selected_validators = rng.choice(
nodes,
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/test_vrf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from backend.consensus.vrf import get_validators_for_transaction
from unittest.mock import Mock

import pytest


def list_of_dicts_to_set(list_of_dicts: list[dict]) -> set:
return set(map(lambda x: tuple(x.items()), list_of_dicts))
Expand Down Expand Up @@ -66,3 +68,27 @@ def choice_mock(a, p, size, replace):

rng.choice.assert_called_once()
assert validators == [{"stake": 3}, {"stake": 2}, {"stake": 1}]


def test_get_validators_for_transaction_all_zero_stake():
"""
Tests that a uniform probability is used when the total stake is zero.

Previously this divided by zero and crashed the consensus worker
(ZeroDivisionError). Internally-created validators with stake=0 make this a
reachable path, so equal-stake nodes must fall back to a uniform distribution.
"""
nodes = [{"stake": 0}, {"stake": 0}, {"stake": 0}]

def choice_mock(a, p, size, replace):
assert p == [1 / 3, 1 / 3, 1 / 3]
assert sum(p) == pytest.approx(1.0)
return list(a)

rng = Mock()
rng.choice.side_effect = choice_mock

validators = get_validators_for_transaction(nodes, 3, rng=rng)

rng.choice.assert_called_once()
assert validators == nodes
Loading