2024-05-17 07:49:13 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-05-17 04:29:20 +00:00
|
|
|
import math
|
|
|
|
from collections import defaultdict
|
2024-05-17 07:49:13 +00:00
|
|
|
from enum import Enum
|
2024-05-17 04:51:41 +00:00
|
|
|
from typing import TYPE_CHECKING
|
2024-05-17 04:29:20 +00:00
|
|
|
|
|
|
|
import simpy
|
|
|
|
from simpy.core import SimTime
|
|
|
|
|
|
|
|
from config import Config
|
|
|
|
from sphinx import SphinxPacket
|
|
|
|
|
2024-05-17 04:51:41 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from node import Node
|
|
|
|
|
2024-05-17 04:29:20 +00:00
|
|
|
|
|
|
|
class Adversary:
|
|
|
|
def __init__(self, env: simpy.Environment, config: Config):
|
|
|
|
self.env = env
|
|
|
|
self.config = config
|
|
|
|
self.message_sizes = []
|
|
|
|
self.senders_around_interval = defaultdict(int)
|
|
|
|
self.mixed_msgs_per_window = []
|
2024-05-17 07:49:13 +00:00
|
|
|
self.node_states = defaultdict(dict)
|
|
|
|
|
2024-05-17 04:29:20 +00:00
|
|
|
self.env.process(self.update_observation_window())
|
|
|
|
|
|
|
|
def inspect_message_size(self, msg: SphinxPacket | bytes):
|
|
|
|
self.message_sizes.append(len(msg))
|
|
|
|
|
2024-05-17 04:51:41 +00:00
|
|
|
def observe_incoming_message(self, node: "Node"):
|
2024-05-17 04:29:20 +00:00
|
|
|
self.mixed_msgs_per_window[-1][node] += 1
|
2024-05-17 07:49:13 +00:00
|
|
|
# TODO: check duplications. Two events at the same time?
|
|
|
|
self.node_states[self.env.now][node] = NodeState.RECEIVING
|
2024-05-17 04:29:20 +00:00
|
|
|
|
2024-05-17 04:51:41 +00:00
|
|
|
def observe_outgoing_message(self, node: "Node"):
|
2024-05-17 04:29:20 +00:00
|
|
|
self.mixed_msgs_per_window[-1][node] -= 1
|
|
|
|
if self.is_around_message_interval(self.env.now):
|
|
|
|
self.senders_around_interval[node] += 1
|
2024-05-17 07:49:13 +00:00
|
|
|
# TODO: check duplications. Two events at the same time?
|
|
|
|
self.node_states[self.env.now][node] = NodeState.SENDING
|
2024-05-17 04:29:20 +00:00
|
|
|
|
|
|
|
def is_around_message_interval(self, time: SimTime):
|
|
|
|
now_frac, now_int = math.modf(time)
|
2024-05-17 05:54:23 +00:00
|
|
|
return now_int % self.config.mixnet.message_interval == 0 and now_frac <= self.config.mixnet.max_message_prep_time
|
2024-05-17 04:29:20 +00:00
|
|
|
|
|
|
|
def update_observation_window(self):
|
|
|
|
while True:
|
|
|
|
self.mixed_msgs_per_window.append(defaultdict(int))
|
2024-05-17 05:54:23 +00:00
|
|
|
yield self.env.timeout(self.config.adversary.io_observation_window)
|
2024-05-17 07:49:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
class NodeState(Enum):
|
|
|
|
SENDING = 0
|
|
|
|
RECEIVING = 1
|