142 lines
5.7 KiB
Python
Raw Normal View History

from __future__ import annotations
2024-05-23 16:34:39 +09:00
import hashlib
2024-05-09 19:37:39 +09:00
import random
2024-05-23 16:34:39 +09:00
from abc import ABC, abstractmethod
2024-05-31 23:17:10 +09:00
from collections import defaultdict, Counter
from typing import TYPE_CHECKING
2024-05-09 19:37:39 +09:00
import simpy
2024-05-09 14:29:10 +09:00
2024-05-17 13:29:20 +09:00
from adversary import Adversary
from config import Config
2024-05-18 00:31:29 +09:00
from measurement import Measurement
2024-05-13 08:49:09 +09:00
from sphinx import SphinxPacket
if TYPE_CHECKING:
from node import Node
2024-05-09 14:29:10 +09:00
2024-05-23 16:34:39 +09:00
class P2P(ABC):
def __init__(self, env: simpy.Environment, config: Config):
2024-05-09 19:37:39 +09:00
self.env = env
self.config = config
2024-05-09 19:37:39 +09:00
self.nodes = []
2024-05-18 00:31:29 +09:00
self.measurement = Measurement(env, config)
2024-05-17 13:29:20 +09:00
self.adversary = Adversary(env, config)
2024-05-31 23:17:10 +09:00
self.broadcasters = Counter()
2024-05-09 19:37:39 +09:00
2024-05-23 17:52:17 +09:00
def set_nodes(self, nodes: list["Node"]):
self.nodes = nodes
2024-05-31 21:07:47 +09:00
self.measurement.set_nodes(nodes)
2024-05-09 14:29:10 +09:00
def get_nodes(self, n: int) -> list["Node"]:
return random.sample(self.nodes, n)
2024-05-16 17:13:43 +09:00
# This should accept only bytes in practice,
# but we accept SphinxPacket as well because we don't implement Sphinx deserialization.
2024-05-23 16:34:39 +09:00
@abstractmethod
2024-05-31 21:42:56 +09:00
def broadcast(self, sender: "Node", msg: SphinxPacket | bytes, hops_traveled: int = 0):
2024-05-15 17:21:31 +09:00
# Yield 0 to ensure that the broadcast is done in the same time step.
2024-05-16 16:02:34 +09:00
# Without any yield, SimPy complains that the broadcast func is not a generator.
2024-05-15 17:21:31 +09:00
yield self.env.timeout(0)
2024-05-31 23:17:10 +09:00
self.broadcasters[sender] += 1
2024-05-15 17:21:31 +09:00
2024-05-31 21:42:56 +09:00
def send(self, msg: SphinxPacket | bytes, hops_traveled: int, sender: "Node", receiver: "Node",
is_first_of_broadcasting: bool):
if is_first_of_broadcasting:
2024-05-25 16:05:25 +09:00
self.adversary.inspect_message_size(msg)
self.adversary.observe_sending_node(sender)
2024-05-25 16:05:25 +09:00
self.measurement.measure_egress(sender, msg)
2024-05-23 16:34:39 +09:00
# simulate network latency
yield self.env.timeout(self.config.p2p.random_network_latency())
2024-05-23 16:34:39 +09:00
2024-05-25 16:05:25 +09:00
self.measurement.measure_ingress(receiver, msg)
self.adversary.observe_receiving_node(sender, receiver)
2024-05-31 21:42:56 +09:00
self.receive(msg, hops_traveled + 1, sender, receiver)
2024-05-25 16:05:25 +09:00
@abstractmethod
2024-05-31 21:42:56 +09:00
def receive(self, msg: SphinxPacket | bytes, hops_traveled: int, sender: "Node", receiver: "Node"):
2024-05-25 16:05:25 +09:00
pass
2024-05-23 16:34:39 +09:00
def log(self, msg):
2024-05-24 16:36:04 +09:00
print(f"t={self.env.now:.3f}: P2P: {msg}")
2024-05-23 16:34:39 +09:00
class NaiveBroadcastP2P(P2P):
def __init__(self, env: simpy.Environment, config: Config):
super().__init__(env, config)
2024-05-23 17:52:17 +09:00
self.nodes = []
2024-05-23 16:34:39 +09:00
# This should accept only bytes in practice,
# but we accept SphinxPacket as well because we don't implement Sphinx deserialization.
2024-05-31 21:42:56 +09:00
def broadcast(self, sender: "Node", msg: SphinxPacket | bytes, hops_traveled: int = 0):
2024-05-23 16:34:39 +09:00
yield from super().broadcast(sender, msg)
2024-05-25 14:18:09 +09:00
2024-05-25 16:05:25 +09:00
self.log(f"Node:{sender.id}: Broadcasting a msg: {len(msg)} bytes")
for i, receiver in enumerate(self.nodes):
2024-05-31 21:42:56 +09:00
self.env.process(self.send(msg, 0, sender, receiver, i == 0))
2024-05-25 14:18:09 +09:00
2024-05-31 21:42:56 +09:00
def receive(self, msg: SphinxPacket | bytes, hops_traveled: int, sender: "Node", receiver: "Node"):
msg_hash = hashlib.sha256(bytes(msg)).digest()
self.measurement.update_message_hops(msg_hash, hops_traveled)
2024-05-23 16:34:39 +09:00
self.env.process(receiver.receive_message(msg))
2024-05-16 17:13:43 +09:00
2024-05-23 16:34:39 +09:00
class GossipP2P(P2P):
def __init__(self, env: simpy.Environment, config: Config):
super().__init__(env, config)
self.topology = defaultdict(set)
2024-05-30 18:36:56 +09:00
self.message_cache = defaultdict(dict) # dict[receiver, dict[msg_hash, sender]]
2024-05-23 16:34:39 +09:00
2024-05-23 17:52:17 +09:00
def set_nodes(self, nodes: list["Node"]):
super().set_nodes(nodes)
for i, node in enumerate(nodes):
# Each node is chained with the right neighbor, so that no node is not orphaned.
# And then, each node is connected to a random subset of other nodes.
front, back = nodes[:i], nodes[i + 1:]
if len(back) > 0:
neighbor = back[0]
back = back[1:]
2024-05-24 16:56:43 +09:00
elif len(front) > 0:
2024-05-23 17:52:17 +09:00
neighbor = front[0]
front = front[1:]
2024-05-24 16:56:43 +09:00
else:
2024-05-24 16:58:04 +09:00
continue
2024-05-24 16:56:43 +09:00
2024-05-23 17:52:17 +09:00
others = front + back
n = min(self.config.p2p.connection_density - 1, len(others))
conns = set(random.sample(others, n))
conns.add(neighbor)
self.topology[node] = conns
2024-05-31 21:42:56 +09:00
def broadcast(self, sender: "Node", msg: SphinxPacket | bytes, hops_traveled: int = 0):
2024-05-23 16:34:39 +09:00
yield from super().broadcast(sender, msg)
2024-05-24 14:00:09 +09:00
self.log(f"Node:{sender.id}: Gossiping a msg: {len(msg)} bytes")
2024-05-24 16:56:43 +09:00
# if the msg is created originally by the sender (not forwarded from others), cache it with the sender itself.
2024-05-24 16:56:43 +09:00
msg_hash = hashlib.sha256(bytes(msg)).digest()
if msg_hash not in self.message_cache[sender]:
self.message_cache[sender][msg_hash] = sender
2024-05-24 16:56:43 +09:00
2024-05-25 14:18:09 +09:00
cnt = 0
2024-05-23 16:34:39 +09:00
for receiver in self.topology[sender]:
# Don't gossip the message if it was received from the node who is going to be the receiver,
# which means that the node already knows the message.
if receiver != self.message_cache[sender][msg_hash]:
2024-05-31 21:42:56 +09:00
self.env.process(self.send(msg, hops_traveled, sender, receiver, cnt == 0))
2024-05-25 14:18:09 +09:00
cnt += 1
2024-05-31 21:42:56 +09:00
def receive(self, msg: SphinxPacket | bytes, hops_traveled: int, sender: "Node", receiver: "Node"):
2024-05-25 14:18:09 +09:00
# Receive/gossip the msg only if it hasn't been received before. If not, just ignore the msg.
# i.e. each message is received/gossiped at most once by each node.
2024-05-23 16:34:39 +09:00
msg_hash = hashlib.sha256(bytes(msg)).digest()
if msg_hash not in self.message_cache[receiver]:
self.message_cache[receiver][msg_hash] = sender
2024-05-31 21:42:56 +09:00
self.measurement.update_message_hops(msg_hash, hops_traveled)
2024-05-25 14:18:09 +09:00
# Receive and gossip
2024-05-23 16:34:39 +09:00
self.env.process(receiver.receive_message(msg))
2024-05-31 21:42:56 +09:00
self.env.process(self.broadcast(receiver, msg, hops_traveled))