Last active
November 17, 2021 12:01
-
-
Save drew2a/c52f783806f3303de246fa770f68dcc8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@dataclass | |
class Ping: | |
... | |
@dataclass | |
class Pong: | |
... | |
@dataclass | |
class Lag: | |
time: int | |
latency: int | |
sender_public_key: type_from_format('74s') | |
receiver_public_key: type_from_format('74s') | |
@dataclass | |
class LagMessage: | |
lag: Lag | |
signature: type_from_format('64s') | |
class LagCommunity(TriblerCommunity): | |
def __init__(self): | |
self.ping_times: dict[Peer, int] = dict() | |
self.register_task("check_lag", self.check_lag, interval=1) | |
self.register_task("gossip_lag", self.gossip_lag, interval=1) | |
def check_lag(self): | |
random_peer = random.choice(self.get_peers()) | |
self.ping_times[random_peer] = time.time_ns() | |
self.ez_send(random_peer, Ping()) | |
def gossip_lag(self): | |
random_lag, random_lag_signature = self.db.get_random_lag() | |
random_peer = random.choice(self.get_peers()) | |
self.ez_send(random_peer, LagMessage(lag=random_lag, signature=random_lag_signature)) | |
@lazy_wrapper(Ping) | |
def on_ping(self, peer, ping: Ping): | |
self.ez_send(peer, Pong()) | |
@lazy_wrapper(Pong) | |
def on_pong(self, peer, pong: Pong): | |
t = self.ping_times.pop(peer) | |
lag = Lag( | |
time=t | |
latency=time.time_ns() - t, | |
sender_public_key=self.my_peer.pub().key_to_bin(), | |
receiver_public_key=peer.pub().key_to_bin(), | |
) | |
signature = self.sign(lag) | |
self.db.save(lag, signature) | |
@lazy_wrapper(LagMessage) | |
def on_lag_message(self, peer, lag_message: LagMessage): | |
self.check_signature(lag_message) | |
self.db.save(lag_message.lag, lag_message.signature) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment