nomos-specs/mixnet/v2/sim/p2p.py

45 lines
1.5 KiB
Python
Raw Normal View History

import math
2024-05-09 10:37:39 +00:00
import random
from collections import defaultdict
2024-05-09 10:37:39 +00:00
import simpy
2024-05-16 06:55:09 +00:00
from simpy.util import start_delayed
2024-05-09 05:29:10 +00:00
from config import Config
2024-05-12 23:49:09 +00:00
from sphinx import SphinxPacket
2024-05-09 05:29:10 +00:00
class P2p:
def __init__(self, env: simpy.Environment, config: Config):
2024-05-09 10:37:39 +00:00
self.env = env
self.config = config
2024-05-09 10:37:39 +00:00
self.nodes = []
2024-05-14 05:03:48 +00:00
self.message_sizes = []
2024-05-16 04:54:09 +00:00
self.senders_around_interval = defaultdict(int)
2024-05-09 10:37:39 +00:00
def add_node(self, nodes):
self.nodes.extend(nodes)
2024-05-09 05:29:10 +00:00
# TODO: This should accept only bytes, but SphinxPacket is also accepted until we implement the Sphinx serde
def broadcast(self, sender, msg: SphinxPacket | bytes):
2024-05-13 03:53:14 +00:00
self.log("Broadcasting a msg: %d bytes" % len(msg))
2024-05-14 05:03:48 +00:00
self.message_sizes.append(len(msg))
now_frac, now_int = math.modf(self.env.now)
if now_int % self.config.message_interval == 0 and now_frac <= self.config.max_message_prep_time:
2024-05-16 04:54:09 +00:00
self.senders_around_interval[sender] += 1
2024-05-15 08:21:31 +00:00
# Yield 0 to ensure that the broadcast is done in the same time step.
# Without this, SimPy complains that the broadcast func is not a generator.
yield self.env.timeout(0)
2024-05-09 05:29:10 +00:00
# TODO: gossipsub or something similar
for node in self.nodes:
2024-05-16 06:55:09 +00:00
network_delay = random.uniform(0, self.config.max_network_latency)
start_delayed(self.env, node.receive_message(msg), delay=network_delay)
2024-05-09 10:37:39 +00:00
def get_nodes(self, n: int):
return random.sample(self.nodes, n)
def log(self, msg):
2024-05-14 05:36:05 +00:00
print("P2P at %g: %s" % (self.env.now, msg))