Skip to content
Open
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
6 changes: 5 additions & 1 deletion src/p2p/peer.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ async def pick_winner(announcements):
if k:
for _ in range(k):
lottery_pool.append(block["Validator"])
if not lottery_pool:
# No eligible validator in this round; skip instead of crashing on choice([]).
tempblocks.clear()
continue
lottery_winner = choice(lottery_pool)
print(lottery_winner)
for block in temp:
Expand Down Expand Up @@ -127,4 +131,4 @@ async def run():
print(Blockchain)

asyncio.ensure_future(candidate(candidate_blocks))
asyncio.ensure_future(pick_winner(announcements))
asyncio.ensure_future(pick_winner(announcements))
50 changes: 50 additions & 0 deletions tests/test_pick_winner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env python3

import asyncio

from p2p import peer


def test_pick_winner_ignores_round_without_eligible_validator():
async def scenario():
original_sleep = peer.asyncio.sleep
real_sleep = asyncio.sleep
try:
async def fast_sleep(_):
await real_sleep(0)

peer.asyncio.sleep = fast_sleep
peer.validators.clear()
peer.tempblocks.clear()
peer.Blockchain.clear()
queue = asyncio.Queue()
peer.tempblocks.append(
{
"Validator": "missing",
"Index": 1,
"BPM": 60,
"Timestamp": "t",
"PrevHash": "h",
"Hash": "h2",
}
)

task = asyncio.create_task(peer.pick_winner(queue))
for _ in range(100):
if peer.tempblocks == []:
break
await real_sleep(0.001)

assert not task.done()
assert queue.empty()
assert peer.tempblocks == []

task.cancel()
await asyncio.gather(task, return_exceptions=True)
finally:
peer.asyncio.sleep = original_sleep
peer.validators.clear()
peer.tempblocks.clear()
peer.Blockchain.clear()

asyncio.run(scenario())