2024-05-15 09:01:42 +00:00
|
|
|
import math
|
2024-05-09 10:37:39 +00:00
|
|
|
import random
|
2024-05-15 09:01:42 +00:00
|
|
|
from collections import defaultdict
|
2024-05-09 10:37:39 +00:00
|
|
|
|
|
|
|
import simpy
|
2024-05-09 05:29:10 +00:00
|
|
|
|
2024-05-15 09:01:42 +00:00
|
|
|
from config import Config
|
2024-05-12 23:49:09 +00:00
|
|
|
from sphinx import SphinxPacket
|
2024-05-12 10:30:04 +00:00
|
|
|
|
2024-05-09 05:29:10 +00:00
|
|
|
|
|
|
|
class P2p:
|
2024-05-15 09:01:42 +00:00
|
|
|
def __init__(self, env: simpy.Environment, config: Config):
|
2024-05-09 10:37:39 +00:00
|
|
|
self.env = env
|
2024-05-15 09:01:42 +00:00
|
|
|
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-15 09:01:42 +00:00
|
|
|
self.nodes_emitted_msg_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
|
|
|
|
2024-05-12 10:30:04 +00:00
|
|
|
# TODO: This should accept only bytes, but SphinxPacket is also accepted until we implement the Sphinx serde
|
2024-05-15 09:01:42 +00:00
|
|
|
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))
|
|
|
|
|
2024-05-15 09:01:42 +00:00
|
|
|
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:
|
|
|
|
self.nodes_emitted_msg_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-09 10:37:39 +00:00
|
|
|
self.env.process(node.receive_message(msg))
|
|
|
|
|
|
|
|
def get_nodes(self, n: int):
|
2024-05-12 10:30:04 +00:00
|
|
|
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))
|