From 713aeb199d23f0b8e9492e5edd7e9b60f5586055 Mon Sep 17 00:00:00 2001 From: Kevin F Date: Sat, 12 Feb 2022 14:36:45 -0600 Subject: [PATCH] Added DandelionPhase to pick stem mode or not --- src/gossip/phase.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/gossip/phase.py diff --git a/src/gossip/phase.py b/src/gossip/phase.py new file mode 100644 index 00000000..4280c16d --- /dev/null +++ b/src/gossip/phase.py @@ -0,0 +1,33 @@ +from time import time +from hashlib import shake_128 + + +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 + self._is_stem = True + + + def _update_stem_phase(self, cur_time): + self.epoch = cur_time + # Hash the seed with the time stamp to produce 1 pseudorandom byte + # We produce an len(8) byte string for year 2038 problem + choice = shake_128( + self.seed + + int.to_bytes(cur_time, 8, 'big')).digest(1) + + # If the byte is even + if int.from_bytes(choice, 'big') % 2: + self._is_stem = True + else: + self._is_stem = False + + + 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