|
| 1 | +"""This file contains the reticulum network implementation. |
| 2 | +This consits of two main classes |
| 3 | +1. reticulum manager which is responsible for running the reticulum network stack in a separate process and exposing to the network. |
| 4 | +2. reticulum network which is responsible for exposing the network interface to a service |
| 5 | +""" |
| 6 | + |
| 7 | +import threading |
| 8 | +import RNS |
| 9 | +import LXMF |
| 10 | +import os |
| 11 | +import time |
| 12 | +import zmq |
| 13 | +from multiprocessing import Queue |
| 14 | +from typing import Callable |
| 15 | +from digitalpy.core.zmanager.response import Response |
| 16 | +from digitalpy.core.domain.object_id import ObjectId |
| 17 | +from digitalpy.core.network.domain.client_status import ClientStatus |
| 18 | +from digitalpy.core.domain.domain.network_client import NetworkClient |
| 19 | +from digitalpy.core.main.object_factory import ObjectFactory |
| 20 | +from digitalpy.core.network.network_sync_interface import NetworkSyncInterface |
| 21 | +from digitalpy.core.zmanager.request import Request |
| 22 | + |
| 23 | +APP_NAME = LXMF.APP_NAME + ".delivery" |
| 24 | + |
| 25 | +class AnnounceHandler: |
| 26 | + def __init__(self, identities): |
| 27 | + self.aspect_filter = APP_NAME # Filter for LXMF announcements |
| 28 | + self.identities = identities # Dictionary to store identities |
| 29 | + |
| 30 | + def received_announce(self, destination_hash, announced_identity, app_data): |
| 31 | + if destination_hash not in self.identities: |
| 32 | + self.identities[destination_hash] = announced_identity |
| 33 | + |
| 34 | +class ReticulumNetwork(NetworkSyncInterface): |
| 35 | + def __init__(self): |
| 36 | + self._storage_path = None |
| 37 | + self._identity_path = None |
| 38 | + self._announcer_thread = None |
| 39 | + self.message_queue = Queue() |
| 40 | + self._clients = {} |
| 41 | + self._ret = None |
| 42 | + self._lxm_router = None |
| 43 | + self._identity = None |
| 44 | + self._my_identity = None |
| 45 | + self._identities = {} |
| 46 | + |
| 47 | + def initialize_network(self, _, _port, storage_path, identity_path, service_desc): |
| 48 | + self._storage_path = storage_path |
| 49 | + self._identity_path = identity_path |
| 50 | + self._ret = RNS.Reticulum() |
| 51 | + self._lxm_router = LXMF.LXMRouter(storagepath=self._storage_path) |
| 52 | + RNS.Transport.register_announce_handler(AnnounceHandler(self._identities)) |
| 53 | + self._identity = self._load_or_generate_identity() |
| 54 | + self._my_identity = self._lxm_router.register_delivery_identity(self._identity) |
| 55 | + self._lxm_router.register_delivery_callback(self._ret_deliver) |
| 56 | + announcer_thread = threading.Thread(target=self._announcer) |
| 57 | + announcer_thread.start() |
| 58 | + self._service_desc = service_desc |
| 59 | + |
| 60 | + def _load_or_generate_identity(self): |
| 61 | + if os.path.exists(self._identity_path): |
| 62 | + try: |
| 63 | + return RNS.Identity.from_file(self._identity_path) |
| 64 | + except RNS.InvalidIdentityFile: |
| 65 | + pass |
| 66 | + identity = RNS.Identity() |
| 67 | + identity.to_file(self._identity_path) |
| 68 | + return identity |
| 69 | + |
| 70 | + def _get_client(self, identity: RNS.Identity) -> NetworkClient: |
| 71 | + if identity.hash in self._clients: |
| 72 | + return self._clients[identity.hash] |
| 73 | + else: |
| 74 | + client = self._register_new_client(identity.hash) |
| 75 | + self._clients[identity.hash] = client |
| 76 | + self._identities[identity.hash] = identity |
| 77 | + return client |
| 78 | + |
| 79 | + def _ret_deliver(self, message: LXMF.LXMessage): |
| 80 | + try: |
| 81 | + # validate the message |
| 82 | + if message.signature_validated: |
| 83 | + validated = True |
| 84 | + elif message.unverified_reason == LXMF.LXMessage.SIGNATURE_INVALID: |
| 85 | + validated = False |
| 86 | + elif message.unverified_reason == LXMF.LXMessage.SOURCE_UNKNOWN: |
| 87 | + validated = False |
| 88 | + else: |
| 89 | + validated = False |
| 90 | + |
| 91 | + # deliver the message to the network |
| 92 | + if validated and message.content is not None and message.content != b"": |
| 93 | + req: Request = ObjectFactory.get_new_instance("Request") |
| 94 | + req.set_value("body", message.content.decode("utf-8")) |
| 95 | + req.set_action("reticulum_message") |
| 96 | + req.set_value("client", self._get_client(message.source.identity)) |
| 97 | + self.message_queue.put(req, block=False, timeout=0) |
| 98 | + except Exception as e: |
| 99 | + print(e) |
| 100 | + |
| 101 | + def _register_new_client(self, destination_hash: bytes): |
| 102 | + """Register a new client to the network. |
| 103 | + Args: |
| 104 | + destination_hash (bytes): The hash of the client destination to register. |
| 105 | + """ |
| 106 | + oid = ObjectId("network_client", id=str(destination_hash)) |
| 107 | + client: NetworkClient = ObjectFactory.get_new_instance( |
| 108 | + "DefaultClient", dynamic_configuration={"oid": oid} |
| 109 | + ) |
| 110 | + client.id = destination_hash |
| 111 | + client.status = ClientStatus.CONNECTED |
| 112 | + client.service_id = self._service_desc.name |
| 113 | + client.protocol = self._service_desc.protocol |
| 114 | + return client |
| 115 | + |
| 116 | + def _get_client_identity(self, message: LXMF.LXMessage) -> bytes: |
| 117 | + """Get the identity of the client that sent the message. This is used for IAM and client tracking. |
| 118 | + Args: |
| 119 | + message (LXMF.LXMessage): The message to extract the identity from. |
| 120 | +
|
| 121 | + Returns: |
| 122 | + bytes: The identity of the client as bytes |
| 123 | + """ |
| 124 | + return message.source.identity.hash |
| 125 | + |
| 126 | + def _announcer(self, interval: int = 60): |
| 127 | + """Announce the reticulum network to the network.""" |
| 128 | + while True: |
| 129 | + try: |
| 130 | + self._my_identity.announce() |
| 131 | + except Exception as e: |
| 132 | + pass |
| 133 | + time.sleep(interval) |
| 134 | + |
| 135 | + def _send_message_to_all_clients(self, message: str): |
| 136 | + for identity in self._clients.values(): |
| 137 | + dest = RNS.Destination( |
| 138 | + self._identities[identity.id], |
| 139 | + RNS.Destination.OUT, |
| 140 | + RNS.Destination.SINGLE, |
| 141 | + "lxmf", |
| 142 | + "delivery", |
| 143 | + ) |
| 144 | + msg = LXMF.LXMessage( |
| 145 | + destination=dest, |
| 146 | + source=self._my_identity, |
| 147 | + content=message.encode("utf-8"), |
| 148 | + desired_method=LXMF.LXMessage.DIRECT, |
| 149 | + ) |
| 150 | + self._lxm_router.handle_outbound(msg) |
| 151 | + |
| 152 | + def _send_message_to_client(self, message: dict, client: NetworkClient): |
| 153 | + identity = self._identities.get(client.id) |
| 154 | + if identity is not None: |
| 155 | + dest = RNS.Destination( |
| 156 | + identity, |
| 157 | + RNS.Destination.OUT, |
| 158 | + RNS.Destination.SINGLE, |
| 159 | + "lxmf", |
| 160 | + "delivery", |
| 161 | + ) |
| 162 | + msg = LXMF.LXMessage( |
| 163 | + destination=dest, |
| 164 | + source=self._my_identity, |
| 165 | + content=message.encode("utf-8"), |
| 166 | + desired_method=LXMF.LXMessage.DIRECT, |
| 167 | + ) |
| 168 | + self._lxm_router.handle_outbound(msg) |
| 169 | + |
| 170 | + def service_connections(self, max_requests=1000, blocking=False, timeout=0): |
| 171 | + start_time = time.time() |
| 172 | + messages = [] |
| 173 | + if self.message_queue.empty(): |
| 174 | + return [] |
| 175 | + messages.append(self.message_queue.get(block=blocking, timeout=timeout)) |
| 176 | + while time.time() - start_time < timeout and len(messages) < max_requests: |
| 177 | + try: |
| 178 | + message = self.message_queue.get(block=False) |
| 179 | + messages.append(message) |
| 180 | + except Exception as e: |
| 181 | + break |
| 182 | + return messages |
| 183 | + |
| 184 | + def send_response(self, response): |
| 185 | + if response.get_value("client") is not None: |
| 186 | + self._send_message_to_client(response.get_value("message"), response.get_value("client")) |
| 187 | + else: |
| 188 | + self._send_message_to_all_clients(response.get_value("message")) |
| 189 | + |
| 190 | + def receive_message(self, blocking = False): |
| 191 | + return self.message_queue.get(block=blocking) |
| 192 | + |
| 193 | + def receive_message_from_client(self, client, blocking = False): |
| 194 | + raise NotImplementedError |
| 195 | + |
| 196 | + def teardown_network(self): |
| 197 | + pass |
0 commit comments