Onionr/src/gossip/dandelion/phase.py

42 lines
1.3 KiB
Python
Raw Normal View History

from time import time
from hashlib import shake_128
2022-03-20 23:05:44 +00:00
from secrets import randbits
class DandelionPhase:
def __init__(self, seed: bytes, epoch_interval_secs: int):
self.seed = seed # Seed intended to be from good random source like urandom
assert len(self.seed) == 32
self.epoch = int(time())
self.epoch_interval = epoch_interval_secs
2022-03-20 23:05:44 +00:00
self._is_stem = bool(randbits(1))
self.phase_id = b''
def _update_stem_phase(self, cur_time):
self.epoch = cur_time
# Hash the seed with the time stamp to produce 8 pseudorandom bytes
# Produce an len(8) byte string for time as well for year 2038 problem
self.phase_id = shake_128(
self.seed +
int.to_bytes(cur_time, 8, 'big')).digest(8)
# Use first byte of phase id as random source for stem phase picking
2022-03-20 23:05:44 +00:00
if self.phase_id[0] % 2:
self._is_stem = True
else:
self._is_stem = False
2022-03-02 13:29:59 +00:00
def remaining_time(self) -> int:
current_time = int(time())
2022-03-20 23:05:44 +00:00
return max(0, self.epoch_interval - (current_time - self.epoch))
2022-03-02 13:29:59 +00:00
def is_stem_phase(self) -> bool:
current_time = int(time())
if current_time - self.epoch >= self.epoch_interval:
self._update_stem_phase(current_time)
return self._is_stem