Compare commits

...
62 Commits
Author SHA1 Message Date
Mark Qvist 9ff76c0473 Updated version 2024-10-13 14:01:10 +02:00
Mark Qvist c9272c9218 Fixed missing byteorder argument in stamp value calculation. Fixes #21. 2024-10-13 13:08:10 +02:00
Mark Qvist 36f0c17c8b Added RNR_REFS field 2024-10-13 13:05:52 +02:00
Mark Qvist aa406d1552 Updated version 2024-10-11 23:45:24 +02:00
Mark Qvist 0cb771439f Fixed incorrect progress values on path waiting 2024-10-11 23:40:27 +02:00
Mark Qvist 672d754238 Updated dependency 2024-10-06 11:13:38 +02:00
Mark Qvist 0178fb0d4f Don't reset propagation node address and links if already set to the same destination 2024-10-05 22:40:14 +02:00
Mark Qvist 19d8909b10 Fixed inbound ticket cleaning bug 2024-10-05 15:26:18 +02:00
Mark Qvist 19f0fa7724 Don't try creating LXMF peer destination until identity is resolved. Fixes #19. 2024-10-04 11:22:39 +02:00
Mark Qvist eefb1c8349 Updated versions 2024-10-02 02:06:00 +02:00
Mark Qvist 0e0d01a0b2 Updated versions 2024-09-30 19:28:13 +02:00
Mark Qvist ac2c9c3a9b Improved opportunistic delivery performance 2024-09-30 19:27:40 +02:00
Mark Qvist 05f144ae50 Updated version 2024-09-19 23:07:58 +02:00
Mark Qvist a461fd415a Rediscover path during opportunistic delivery if path fails 2024-09-19 23:00:24 +02:00
Mark Qvist ef1c3331ad Improved outbound handling 2024-09-17 13:29:36 +02:00
Mark Qvist e1a56be5c1 Pre-emptively request unknown paths for opportunistic messages 2024-09-17 13:18:16 +02:00
Mark Qvist cf6fc4a510 Update max pathless tries 2024-09-17 12:56:56 +02:00
Mark Qvist 67d21deff9 Updated dependencies 2024-09-16 20:11:53 +02:00
Mark Qvist efc15bde26 Updated version 2024-09-16 20:09:57 +02:00
Mark Qvist b5d6ed3d9b Automatically reconfigure to direct delivery if opportunistic message content is too large 2024-09-16 20:08:26 +02:00
Mark Qvist 7789e0bc26 Improved opportunistic delivery logic and performance 2024-09-16 17:49:54 +02:00
Mark Qvist 0e2f0fb090 Updated example 2024-09-16 17:49:22 +02:00
Mark Qvist 19696d206d Actually set property 2024-09-12 21:28:50 +02:00
Mark Qvist 9193aa5e02 Improved logging 2024-09-12 18:24:14 +02:00
Mark Qvist bbf1eda3b0 Added backchannel delivery 2024-09-12 17:57:26 +02:00
Mark Qvist d8e2e2a45f Fix stamp cost extractor function 2024-09-12 10:11:49 +02:00
Mark Qvist 0fc15e6054 Updated version 2024-09-11 11:48:36 +02:00
Mark Qvist 717240c8d4 Cleanup 2024-09-11 02:09:43 +02:00
Mark Qvist 453772859d Removed deprecated query destination 2024-09-10 20:17:09 +02:00
Mark Qvist 98eea1171e Added event field 2024-09-09 15:24:36 +02:00
Mark Qvist ea49d22bce Add test entrypoint to LXStamper 2024-09-09 13:20:54 +02:00
Mark Qvist 058186dfdc Cleanup 2024-09-09 13:15:37 +02:00
Mark Qvist 8134672436 Cleanup 2024-09-09 02:12:27 +02:00
Mark Qvist ae0952455b Ignore stamp requirements for paper messages 2024-09-08 17:54:11 +02:00
Mark Qvist a20f380284 Get message ratchet IDs 2024-09-08 14:52:54 +02:00
Mark Qvist 6d83b019e1 Added stamp value property on inbound 2024-09-08 01:22:00 +02:00
Mark Qvist 40eb014c91 Implemented deferred multiprocessor stamp generation in the background 2024-09-07 22:40:13 +02:00
Mark Qvist 62f5a9eead Implemented ticket exchanges. Implemented stamp generation and validation by tickets. 2024-09-07 15:17:48 +02:00
Mark Qvist 74cbd11473 Cleanup 2024-09-07 11:37:39 +02:00
Mark Qvist 0d76eee6cd Stamp cost API functions and multi-process stamp generation on Android 2024-09-07 11:35:17 +02:00
Mark Qvist 4b5e27a5e2 Updated examples 2024-09-06 20:34:45 +02:00
Mark Qvist dcb0a18cd7 Added automatic signalling of stamp costs, stamp generation and validation 2024-09-06 20:34:09 +02:00
Mark Qvist 015dcc5631 Extract announced stamp cost in handlers 2024-09-06 19:55:18 +02:00
Mark Qvist 537f1823b6 Added utility functions 2024-09-06 19:54:28 +02:00
Mark Qvist fc99010a3d Updated example 2024-09-06 17:37:24 +02:00
Mark Qvist fe14f8744d Added base code for stamp generation and validation 2024-09-06 16:49:01 +02:00
Mark Qvist 4dca031441 Updated fields 2024-09-06 00:57:06 +02:00
Mark Qvist 5366f895b2 Added stamp generation to LXMessage 2024-09-06 00:51:36 +02:00
Mark Qvist 95ba8cba60 Updated dependencies 2024-09-05 14:57:20 +02:00
Mark Qvist 775ac7ff68 Allow ratchet enforcement and fixed opportunistic delivery queue handling 2024-09-05 14:56:49 +02:00
Mark Qvist a9fe086bcf Updated version 2024-09-04 18:58:25 +02:00
Mark Qvist e0f763caee Enabled Reticulum Ratchets for LXMF 2024-09-04 18:57:51 +02:00
Mark Qvist c24e99a92b Updated readme 2024-08-30 00:28:18 +02:00
Mark Qvist c1a327c5b2 Updated readme 2024-08-30 00:26:58 +02:00
Mark Qvist 68892091ec Updated readme 2024-08-30 00:23:09 +02:00
Mark Qvist e87c6c6d28 Merge branch 'master' of github.com:markqvist/LXMF 2024-08-30 00:12:34 +02:00
Mark Qvist 0be569ccd6 Updated field specifiers and descriptions 2024-08-30 00:11:32 +02:00
Mark Qvist 8e686b10e8 Updated version and dependencies 2024-08-30 00:11:11 +02:00
markqvist ae203291b9 Merge pull request #17 from markqvist/dependabot/pip/setuptools-70.0.0
Bump setuptools from 68.0.0 to 70.0.0
2024-08-17 16:58:48 +02:00
dependabot[bot] 8b8008478d Bump setuptools from 68.0.0 to 70.0.0
Bumps [setuptools](https://github.com/pypa/setuptools) from 68.0.0 to 70.0.0.
- [Release notes](https://github.com/pypa/setuptools/releases)
- [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst)
- [Commits](https://github.com/pypa/setuptools/compare/v68.0.0...v70.0.0)

---
updated-dependencies:
- dependency-name: setuptools
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-15 18:35:25 +00:00
Mark Qvist b4ba9d628b Updated readme 2024-06-05 00:32:59 +02:00
Mark Qvist 4520507869 Updated readme 2024-06-04 18:43:46 +02:00
12 changed files with 1236 additions and 111 deletions

No files matched your search

+11 -2
View File
@@ -2,19 +2,20 @@ import time
import RNS
import RNS.vendor.umsgpack as msgpack
from .LXMF import APP_NAME
from .LXMF import APP_NAME, stamp_cost_from_app_data
from .LXMessage import LXMessage
class LXMFDeliveryAnnounceHandler:
def __init__(self, lxmrouter):
self.aspect_filter = APP_NAME+".delivery"
self.receive_path_responses = True
self.lxmrouter = lxmrouter
def received_announce(self, destination_hash, announced_identity, app_data):
for lxmessage in self.lxmrouter.pending_outbound:
if destination_hash == lxmessage.destination_hash:
if lxmessage.method == LXMessage.DIRECT:
if lxmessage.method == LXMessage.DIRECT or lxmessage.method == LXMessage.OPPORTUNISTIC:
lxmessage.next_delivery_attempt = time.time()
while self.lxmrouter.processing_outbound:
@@ -22,10 +23,18 @@ class LXMFDeliveryAnnounceHandler:
self.lxmrouter.process_outbound()
try:
stamp_cost = stamp_cost_from_app_data(app_data)
self.lxmrouter.update_stamp_cost(destination_hash, stamp_cost)
except Exception as e:
RNS.log(f"An error occurred while trying to decode announced stamp cost. The contained exception was: {e}", RNS.LOG_ERROR)
class LXMFPropagationAnnounceHandler:
def __init__(self, lxmrouter):
self.aspect_filter = APP_NAME+".propagation"
self.receive_path_responses = False
self.lxmrouter = lxmrouter
def received_announce(self, destination_hash, announced_identity, app_data):
+91 -7
View File
@@ -1,9 +1,10 @@
APP_NAME = "lxmf"
# WARNING! These field specifiers are floating and not
# yet final! Consider highly experiemental, and expect
# them to change in the future! You have been warned :)
##########################################################
# The following core fields are provided to facilitate #
# interoperability in data exchange between various LXMF #
# clients and systems. #
##########################################################
FIELD_EMBEDDED_LXMS = 0x01
FIELD_TELEMETRY = 0x02
FIELD_TELEMETRY_STREAM = 0x03
@@ -15,6 +16,37 @@ FIELD_THREAD = 0x08
FIELD_COMMANDS = 0x09
FIELD_RESULTS = 0x0A
FIELD_GROUP = 0x0B
FIELD_TICKET = 0x0C
FIELD_EVENT = 0x0D
FIELD_RNR_REFS = 0x0E
# For usecases such as including custom data structures,
# embedding or encapsulating other data types or protocols
# that are not native to LXMF, or bridging/tunneling
# external protocols or services over LXMF, the following
# fields are available. A format/type/protocol (or other)
# identifier can be included in the CUSTOM_TYPE field, and
# the embedded payload can be included in the CUSTOM_DATA
# field. It is up to the client application to correctly
# discern and potentially utilise any data embedded using
# this mechanism.
FIELD_CUSTOM_TYPE = 0xFB
FIELD_CUSTOM_DATA = 0xFC
FIELD_CUSTOM_META = 0xFD
# The non-specific and debug fields are intended for
# development, testing and debugging use.
FIELD_NON_SPECIFIC = 0xFE
FIELD_DEBUG = 0xFF
##########################################################
# The following section lists field-specific specifiers, #
# modes and identifiers that are native to LXMF. It is #
# optional for any client or system to support any of #
# these, and they are provided as template for easing #
# interoperability without sacrificing expandability #
# and flexibility of the format. #
##########################################################
# Audio modes for the data structure in FIELD_AUDIO
@@ -41,6 +73,58 @@ AM_OPUS_HQ = 0x17
AM_OPUS_BROADCAST = 0x18
AM_OPUS_LOSSLESS = 0x19
# Custom, unspecified audio mode, the
# client must determined it itself
AM_CUSTOM = 0xFF
# Custom, unspecified audio mode, the client must
# determine it itself based on the included data.
AM_CUSTOM = 0xFF
##########################################################
# The following helper functions makes it easier to #
# handle and operate on LXMF data in client programs #
##########################################################
import RNS.vendor.umsgpack as msgpack
def display_name_from_app_data(app_data=None):
if app_data == None:
return None
elif len(app_data) == 0:
return None
else:
# Version 0.5.0+ announce format
if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc:
peer_data = msgpack.unpackb(app_data)
if type(peer_data) == list:
if len(peer_data) < 1:
return None
else:
dn = peer_data[0]
if dn == None:
return None
else:
try:
decoded = dn.decode("utf-8")
return decoded
except:
RNS.log("Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_ERROR)
return None
# Original announce format
else:
return app_data.decode("utf-8")
def stamp_cost_from_app_data(app_data=None):
if app_data == None or app_data == b"":
return None
else:
# Version 0.5.0+ announce format
if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc:
peer_data = msgpack.unpackb(app_data)
if type(peer_data) == list:
if len(peer_data) < 2:
return None
else:
return peer_data[1]
# Original announce format
else:
return None
+7 -3
View File
@@ -108,7 +108,10 @@ class LXMPeer:
self.router = router
self.destination_hash = destination_hash
self.identity = RNS.Identity.recall(destination_hash)
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
if self.identity != None:
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
else:
RNS.log(f"Could not recall identity for LXMF propagation peer {RNS.prettyhexrep(self.destination_hash)}, will retry identity resolution on next sync", RNS.LOG_WARNING)
def sync(self):
RNS.log("Initiating LXMF Propagation Node sync with peer "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_DEBUG)
@@ -126,9 +129,10 @@ class LXMPeer:
else:
if self.identity == None:
self.identity = RNS.Identity.recall(destination_hash)
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
if self.identity != None:
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
if self.identity != None:
if self.destination != None:
if len(self.unhandled_messages) > 0:
if self.state == LXMPeer.IDLE:
RNS.log("Establishing link for sync to peer "+RNS.prettyhexrep(self.destination_hash)+"...", RNS.LOG_DEBUG)
+546 -42
View File
@@ -9,6 +9,7 @@ import RNS
import RNS.vendor.umsgpack as msgpack
from .LXMF import APP_NAME
from .LXMF import FIELD_TICKET
from .LXMPeer import LXMPeer
from .LXMessage import LXMessage
@@ -20,10 +21,12 @@ class LXMRouter:
PROCESSING_INTERVAL = 4
DELIVERY_RETRY_WAIT = 10
PATH_REQUEST_WAIT = 7
MAX_PATHLESS_TRIES = 1
LINK_MAX_INACTIVITY = 10*60
P_LINK_MAX_INACTIVITY = 3*60
MESSAGE_EXPIRY = 30*24*60*60
STAMP_COST_EXPIRY = 45*24*60*60
NODE_ANNOUNCE_DELAY = 20
@@ -57,15 +60,14 @@ class LXMRouter:
### Developer-facing API ##############################
#######################################################
def __init__(self, identity = None, storagepath = None, autopeer = AUTOPEER, autopeer_maxdepth = None,
propagation_limit = PROPAGATION_LIMIT, delivery_limit = DELIVERY_LIMIT):
def __init__(self, identity = None, storagepath = None, autopeer = AUTOPEER, autopeer_maxdepth = None, propagation_limit = PROPAGATION_LIMIT, delivery_limit = DELIVERY_LIMIT, enforce_ratchets = False, enforce_stamps = False):
random.seed(os.urandom(10))
self.pending_inbound = []
self.pending_outbound = []
self.failed_outbound = []
self.direct_links = {}
self.backchannel_links = {}
self.delivery_destinations = {}
self.prioritised_list = []
@@ -84,6 +86,7 @@ class LXMRouter:
raise ValueError("LXMF cannot be initialised without a storage path")
else:
self.storagepath = storagepath+"/lxmf"
self.ratchetpath = self.storagepath+"/ratchets"
self.outbound_propagation_node = None
self.outbound_propagation_link = None
@@ -92,6 +95,9 @@ class LXMRouter:
self.information_storage_limit = None
self.propagation_per_transfer_limit = propagation_limit
self.delivery_per_transfer_limit = delivery_limit
self.enforce_ratchets = enforce_ratchets
self._enforce_stamps = enforce_stamps
self.pending_deferred_stamps = {}
self.wants_download_on_path_available_from = None
self.wants_download_on_path_available_to = None
@@ -102,12 +108,17 @@ class LXMRouter:
self.active_propagation_links = []
self.locally_delivered_transient_ids = {}
self.locally_processed_transient_ids = {}
self.outbound_stamp_costs = {}
self.available_tickets = {"outbound": {}, "inbound": {}, "last_deliveries": {}}
self.cost_file_lock = threading.Lock()
self.ticket_file_lock = threading.Lock()
self.stamp_gen_lock = threading.Lock()
if identity == None:
identity = RNS.Identity()
self.identity = identity
self.lxmf_query_destination = RNS.Destination(None, RNS.Destination.IN, RNS.Destination.PLAIN, APP_NAME, "query")
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
if autopeer != None:
@@ -146,16 +157,53 @@ class LXMRouter:
except Exception as e:
RNS.log("Could not load locally delivered message ID cache from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if os.path.isfile(self.storagepath+"/outbound_stamp_costs"):
with self.cost_file_lock:
with open(self.storagepath+"/outbound_stamp_costs", "rb") as outbound_stamp_cost_file:
data = outbound_stamp_cost_file.read()
self.outbound_stamp_costs = msgpack.unpackb(data)
self.clean_outbound_stamp_costs()
self.save_outbound_stamp_costs()
except Exception as e:
RNS.log("Could not load outbound stamp costs from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if os.path.isfile(self.storagepath+"/available_tickets"):
with self.ticket_file_lock:
with open(self.storagepath+"/available_tickets", "rb") as available_tickets_file:
data = available_tickets_file.read()
self.available_tickets = msgpack.unpackb(data)
if not type(self.available_tickets) == dict:
RNS.log("Invalid data format for loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets = {"outbound": {}, "inbound": {}, "last_deliveries": {}}
if not "outbound" in self.available_tickets:
RNS.log("Missing outbound entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["outbound"] = {}
if not "inbound" in self.available_tickets:
RNS.log("Missing inbound entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["inbound"] = {}
if not "last_deliveries" in self.available_tickets:
RNS.log("Missing local_deliveries entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["last_deliveries"] = {}
self.clean_available_tickets()
self.save_available_tickets()
except Exception as e:
RNS.log("Could not load outbound stamp costs from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
atexit.register(self.exit_handler)
job_thread = threading.Thread(target=self.jobloop)
job_thread.setDaemon(True)
job_thread.start()
def announce(self, destination_hash):
def announce(self, destination_hash, attached_interface=None):
if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash]
delivery_destination.announce(delivery_destination.display_name.encode("utf-8"))
self.delivery_destinations[destination_hash].announce(app_data=self.get_announce_app_data(destination_hash), attached_interface=attached_interface)
def announce_propagation_node(self):
def delayed_announce():
@@ -173,34 +221,86 @@ class LXMRouter:
da_thread.setDaemon(True)
da_thread.start()
def register_delivery_identity(self, identity, display_name = None):
def register_delivery_identity(self, identity, display_name = None, stamp_cost = None):
if len(self.delivery_destinations) != 0:
RNS.log("Currently only one delivery identity is supported per LXMF router instance", RNS.LOG_ERROR)
return None
if not os.path.isdir(self.ratchetpath):
os.makedirs(self.ratchetpath)
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "delivery")
delivery_destination.enable_ratchets(f"{self.ratchetpath}/{RNS.hexrep(delivery_destination.hash, delimit=False)}.ratchets")
delivery_destination.set_packet_callback(self.delivery_packet)
delivery_destination.set_link_established_callback(self.delivery_link_established)
delivery_destination.display_name = display_name
if self.enforce_ratchets:
delivery_destination.enforce_ratchets()
if display_name != None:
delivery_destination.set_default_app_data(display_name.encode("utf-8"))
def get_app_data():
return self.get_announce_app_data(delivery_destination.hash)
delivery_destination.set_default_app_data(get_app_data)
self.delivery_destinations[delivery_destination.hash] = delivery_destination
self.set_inbound_stamp_cost(delivery_destination.hash, stamp_cost)
return delivery_destination
def register_delivery_callback(self, callback):
self.__delivery_callback = callback
def set_inbound_stamp_cost(self, destination_hash, stamp_cost):
if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash]
if stamp_cost == None:
delivery_destination.stamp_cost = None
return True
elif type(stamp_cost) == int:
if stamp_cost < 1:
delivery_destination.stamp_cost = None
elif stamp_cost < 255:
delivery_destination.stamp_cost = stamp_cost
else:
return False
return True
return False
def get_outbound_stamp_cost(self, destination_hash):
if destination_hash in self.outbound_stamp_costs:
stamp_cost = self.outbound_stamp_costs[destination_hash][1]
return stamp_cost
else:
return None
def set_active_propagation_node(self, destination_hash):
self.set_outbound_propagation_node(destination_hash)
# self.set_inbound_propagation_node(destination_hash)
def set_outbound_propagation_node(self, destination_hash):
if len(destination_hash) != RNS.Identity.TRUNCATED_HASHLENGTH//8 or type(destination_hash) != bytes:
raise ValueError("Invalid destination hash for outbound propagation node")
else:
self.outbound_propagation_node = destination_hash
if self.outbound_propagation_link != None:
if self.outbound_propagation_link.destination.hash != destination_hash:
self.outbound_propagation_link.teardown()
self.outbound_propagation_link = None
if self.outbound_propagation_node != destination_hash:
self.outbound_propagation_node = destination_hash
if self.outbound_propagation_link != None:
if self.outbound_propagation_link.destination.hash != destination_hash:
self.outbound_propagation_link.teardown()
self.outbound_propagation_link = None
def get_outbound_propagation_node(self):
return self.outbound_propagation_node
def set_inbound_propagation_node(self, destination_hash):
# TODO: Implement
raise NotImplementedError("Inbound/outbound propagation node differentiation is currently not implemented")
def get_inbound_propagation_node(self):
return self.get_outbound_propagation_node()
def set_retain_node_lxms(self, retain):
if retain == True:
self.retain_synced_on_node = True
@@ -280,7 +380,6 @@ class LXMRouter:
self.propagation_transfer_state = LXMRouter.PR_PATH_REQUESTED
self.request_messages_path_job()
else:
# TODO: Remove at some point
RNS.log("Waiting for propagation node link to become active", RNS.LOG_EXTREME)
else:
RNS.log("Cannot request LXMF propagation node sync, no default propagation node configured", RNS.LOG_WARNING)
@@ -372,6 +471,12 @@ class LXMRouter:
self.propagation_node = False
self.announce_propagation_node()
def enforce_stamps(self):
self._enforce_stamps = True
def ignore_stamps(self):
self._enforce_stamps = False
def ignore_destination(self, destination_hash):
if not destination_hash in self.ignored_list:
self.ignored_list.append(destination_hash)
@@ -443,11 +548,18 @@ class LXMRouter:
def information_storage_size(self):
pass
def delivery_link_available(self, destination_hash):
if destination_hash in self.direct_links or destination_hash in self.backchannel_links:
return True
else:
return False
### Utility & Maintenance #############################
#######################################################
JOB_OUTBOUND_INTERVAL = 1
JOB_STAMPS_INTERVAL = 1
JOB_LINKS_INTERVAL = 1
JOB_TRANSIENT_INTERVAL = 60
JOB_STORE_INTERVAL = 120
@@ -458,6 +570,9 @@ class LXMRouter:
if self.processing_count % LXMRouter.JOB_OUTBOUND_INTERVAL == 0:
self.process_outbound()
if self.processing_count % LXMRouter.JOB_STAMPS_INTERVAL == 0:
threading.Thread(target=self.process_deferred_stamps, daemon=True).start()
if self.processing_count % LXMRouter.JOB_LINKS_INTERVAL == 0:
self.clean_links()
@@ -545,6 +660,31 @@ class LXMRouter:
self.locally_processed_transient_ids.pop(transient_id)
RNS.log("Cleaned "+RNS.prettyhexrep(transient_id)+" from locally processed cache", RNS.LOG_DEBUG)
def update_stamp_cost(self, destination_hash, stamp_cost):
RNS.log(f"Updating outbound stamp cost for {RNS.prettyhexrep(destination_hash)} to {stamp_cost}", RNS.LOG_DEBUG)
self.outbound_stamp_costs[destination_hash] = [time.time(), stamp_cost]
def job():
self.save_outbound_stamp_costs()
threading.Thread(target=self.save_outbound_stamp_costs, daemon=True).start()
def get_announce_app_data(self, destination_hash):
if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash]
display_name = None
if delivery_destination.display_name != None:
display_name = delivery_destination.display_name.encode("utf-8")
stamp_cost = None
if delivery_destination.stamp_cost != None and type(delivery_destination.stamp_cost) == int:
if delivery_destination.stamp_cost > 0 and delivery_destination.stamp_cost < 255:
stamp_cost = delivery_destination.stamp_cost
peer_data = [display_name, stamp_cost]
return msgpack.packb(peer_data)
def get_weight(self, transient_id):
dst_hash = self.propagation_entries[transient_id][0]
lxm_rcvd = self.propagation_entries[transient_id][2]
@@ -562,6 +702,69 @@ class LXMRouter:
return weight
def generate_ticket(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY):
now = time.time()
ticket = None
if destination_hash in self.available_tickets["last_deliveries"]:
last_delivery = self.available_tickets["last_deliveries"][destination_hash]
elapsed = now - last_delivery
if elapsed < LXMessage.TICKET_INTERVAL:
RNS.log(f"A ticket for {RNS.prettyhexrep(destination_hash)} was already delivered {RNS.prettytime(elapsed)} ago, not including another ticket yet", RNS.LOG_DEBUG)
return None
if destination_hash in self.available_tickets["inbound"]:
for ticket in self.available_tickets["inbound"][destination_hash]:
ticket_entry = self.available_tickets["inbound"][destination_hash][ticket]
expires = ticket_entry[0]; validity_left = expires - now
if validity_left > LXMessage.TICKET_RENEW:
RNS.log(f"Found generated ticket for {RNS.prettyhexrep(destination_hash)} with {RNS.prettytime(validity_left)} of validity left, re-using this one", RNS.LOG_DEBUG)
return [expires, ticket]
else:
self.available_tickets["inbound"][destination_hash] = {}
RNS.log(f"No generated tickets for {RNS.prettyhexrep(destination_hash)} with enough validity found, generating a new one", RNS.LOG_DEBUG)
expires = now+expiry
ticket = os.urandom(LXMessage.TICKET_LENGTH)
self.available_tickets["inbound"][destination_hash][ticket] = [expires]
self.save_available_tickets()
return [expires, ticket]
def remember_ticket(self, destination_hash, ticket_entry):
expires = ticket_entry[0]-time.time()
RNS.log(f"Remembering ticket for {RNS.prettyhexrep(destination_hash)}, expires in {RNS.prettytime(expires)}", RNS.LOG_DEBUG)
self.available_tickets["outbound"][destination_hash] = [ticket_entry[0], ticket_entry[1]]
def get_outbound_ticket(self, destination_hash):
if destination_hash in self.available_tickets["outbound"]:
entry = self.available_tickets["outbound"][destination_hash]
if entry[0] > time.time():
return entry[1]
return None
def get_outbound_ticket_expiry(self, destination_hash):
if destination_hash in self.available_tickets["outbound"]:
entry = self.available_tickets["outbound"][destination_hash]
if entry[0] > time.time():
return entry[0]
return None
def get_inbound_tickets(self, destination_hash):
now = time.time()
available_tickets = []
if destination_hash in self.available_tickets["inbound"]:
for inbound_ticket in self.available_tickets["inbound"][destination_hash]:
if now < self.available_tickets["inbound"][destination_hash][inbound_ticket][0]:
available_tickets.append(inbound_ticket)
if len(available_tickets) == 0:
return None
else:
return available_tickets
def get_size(self, transient_id):
lxm_size = self.propagation_entries[transient_id][3]
return lxm_size
@@ -668,7 +871,99 @@ class LXMRouter:
locally_processed_file.close()
except Exception as e:
RNS.log("Could not save locally processed message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log("Could not save locally processed transient ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def clean_outbound_stamp_costs(self):
try:
expired = []
for destination_hash in self.outbound_stamp_costs:
entry = self.outbound_stamp_costs[destination_hash]
if time.time() > entry[0] + LXMRouter.STAMP_COST_EXPIRY:
expired.append(destination_hash)
for destination_hash in expired:
self.outbound_stamp_costs.pop(destination_hash)
except Exception as e:
RNS.log(f"Error while cleaning outbound stamp costs. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
def save_outbound_stamp_costs(self):
with self.cost_file_lock:
try:
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
outbound_stamp_costs_file = open(self.storagepath+"/outbound_stamp_costs", "wb")
outbound_stamp_costs_file.write(msgpack.packb(self.outbound_stamp_costs))
outbound_stamp_costs_file.close()
except Exception as e:
RNS.log("Could not save outbound stamp costs to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def clean_available_tickets(self):
try:
# Clean outbound tickets
expired_outbound = []
for destination_hash in self.available_tickets["outbound"]:
entry = self.available_tickets["outbound"][destination_hash]
if time.time() > entry[0]:
expired_outbound.append(destination_hash)
for destination_hash in expired_outbound:
self.available_tickets["outbound"].pop(destination_hash)
# Clean inbound tickets
for destination_hash in self.available_tickets["inbound"]:
expired_inbound = []
for inbound_ticket in self.available_tickets["inbound"][destination_hash]:
entry = self.available_tickets["inbound"][destination_hash][inbound_ticket]
ticket_expiry = entry[0]
if time.time() > ticket_expiry+LXMessage.TICKET_GRACE:
expired_inbound.append(inbound_ticket)
for inbound_ticket in expired_inbound:
self.available_tickets["inbound"][destination_hash].pop(inbound_ticket)
except Exception as e:
RNS.log(f"Error while cleaning available tickets. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
def save_available_tickets(self):
with self.ticket_file_lock:
try:
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
available_tickets_file = open(self.storagepath+"/available_tickets", "wb")
available_tickets_file.write(msgpack.packb(self.available_tickets))
available_tickets_file.close()
except Exception as e:
RNS.log("Could not save available tickets to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def reload_available_tickets(self):
RNS.log("Reloading available tickets from storage", RNS.LOG_DEBUG)
try:
with self.ticket_file_lock:
with open(self.storagepath+"/available_tickets", "rb") as available_tickets_file:
data = available_tickets_file.read()
self.available_tickets = msgpack.unpackb(data)
if not type(self.available_tickets) == dict:
RNS.log("Invalid data format for loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets = {"outbound": {}, "inbound": {}, "last_deliveries": {}}
if not "outbound" in self.available_tickets:
RNS.log("Missing outbound entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["outbound"] = {}
if not "inbound" in self.available_tickets:
RNS.log("Missing inbound entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["inbound"] = {}
if not "last_deliveries" in self.available_tickets:
RNS.log("Missing local_deliveries entry in loaded available tickets, recreating...", RNS.LOG_ERROR)
self.available_tickets["last_deliveries"] = {}
except Exception as e:
RNS.log(f"An error occurred while reloading available tickets from storage: {e}", RNS.LOG_ERROR)
def exit_handler(self):
if self.propagation_node:
@@ -911,22 +1206,76 @@ class LXMRouter:
return False
def handle_outbound(self, lxmessage):
destination_hash = lxmessage.get_destination().hash
if lxmessage.stamp_cost == None:
if destination_hash in self.outbound_stamp_costs:
stamp_cost = self.outbound_stamp_costs[destination_hash][1]
lxmessage.stamp_cost = stamp_cost
RNS.log(f"No stamp cost set on LXM to {RNS.prettyhexrep(destination_hash)}, autoconfigured to {stamp_cost}, as required by latest announce", RNS.LOG_DEBUG)
lxmessage.state = LXMessage.OUTBOUND
# If an outbound ticket is available for this
# destination, attach it to the message.
lxmessage.outbound_ticket = self.get_outbound_ticket(destination_hash)
if lxmessage.outbound_ticket != None and lxmessage.defer_stamp:
RNS.log(f"Deferred stamp generation was requested for {lxmessage}, but outbound ticket was applied, processing immediately", RNS.LOG_DEBUG)
lxmessage.defer_stamp = False
# If requested, include a ticket to allow the
# destination to reply without generating a stamp.
if lxmessage.include_ticket:
ticket = self.generate_ticket(lxmessage.destination_hash)
if ticket:
lxmessage.fields[FIELD_TICKET] = ticket
if not lxmessage.packed:
lxmessage.pack()
unknown_path_requested = False
if not RNS.Transport.has_path(destination_hash) and lxmessage.method == LXMessage.OPPORTUNISTIC:
RNS.log(f"Pre-emptively requesting unknown path for opportunistic {lxmessage}", RNS.LOG_DEBUG)
RNS.Transport.request_path(destination_hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
unknown_path_requested = True
lxmessage.determine_transport_encryption()
while self.processing_outbound:
time.sleep(0.1)
if lxmessage.defer_stamp and lxmessage.stamp_cost == None:
RNS.log(f"Deferred stamp generation was requested for {lxmessage}, but no stamp is required, processing immediately", RNS.LOG_DEBUG)
lxmessage.defer_stamp = False
self.pending_outbound.append(lxmessage)
self.process_outbound()
if not lxmessage.defer_stamp:
while not unknown_path_requested and self.processing_outbound:
time.sleep(0.05)
self.pending_outbound.append(lxmessage)
if not unknown_path_requested:
self.process_outbound()
else:
self.pending_deferred_stamps[lxmessage.message_id] = lxmessage
def get_outbound_progress(self, lxm_hash):
for lxm in self.pending_outbound:
if lxm.hash == lxm_hash:
return lxm.progress
for lxm_id in self.pending_deferred_stamps:
if self.pending_deferred_stamps[lxm_id].hash == lxm_hash:
return self.pending_deferred_stamps[lxm_id].progress
return None
def get_outbound_lxm_stamp_cost(self, lxm_hash):
for lxm in self.pending_outbound:
if lxm.hash == lxm_hash:
return lxm.stamp_cost
for lxm_id in self.pending_deferred_stamps:
if self.pending_deferred_stamps[lxm_id].hash == lxm_hash:
return self.pending_deferred_stamps[lxm_id].stamp_cost
return None
@@ -934,15 +1283,56 @@ class LXMRouter:
### Message Routing & Delivery ########################
#######################################################
def lxmf_delivery(self, lxmf_data, destination_type = None, phy_stats = None):
def lxmf_delivery(self, lxmf_data, destination_type = None, phy_stats = None, ratchet_id = None, method = None, no_stamp_enforcement=False):
try:
message = LXMessage.unpack_from_bytes(lxmf_data)
if ratchet_id and not message.ratchet_id:
message.ratchet_id = ratchet_id
if method:
message.method = method
if message.signature_validated and FIELD_TICKET in message.fields:
ticket_entry = message.fields[FIELD_TICKET]
if type(ticket_entry) == list and len(ticket_entry) > 1:
expires = ticket_entry[0]
ticket = ticket_entry[1]
if time.time() < expires:
if type(ticket) == bytes and len(ticket) == LXMessage.TICKET_LENGTH:
self.remember_ticket(message.source_hash, ticket_entry)
def save_job():
self.save_available_tickets()
threading.Thread(target=save_job, daemon=True).start()
required_stamp_cost = self.delivery_destinations[message.destination_hash].stamp_cost
if required_stamp_cost != None:
destination_tickets = self.get_inbound_tickets(message.source_hash)
if message.validate_stamp(required_stamp_cost, tickets=destination_tickets):
message.stamp_valid = True
message.stamp_checked = True
else:
message.stamp_valid = False
message.stamp_checked = True
if not message.stamp_valid:
if no_stamp_enforcement:
RNS.log(f"Received {message} with invalid stamp, but allowing anyway, since stamp enforcement was temporarily disabled", RNS.LOG_NOTICE)
else:
if self._enforce_stamps:
RNS.log(f"Dropping {message} with invalid stamp", RNS.LOG_NOTICE)
return False
else:
RNS.log(f"Received {message} with invalid stamp, but allowing anyway, since stamp enforcement is disabled", RNS.LOG_NOTICE)
else:
RNS.log(f"Received {message} with valid stamp", RNS.LOG_DEBUG)
if phy_stats != None:
if "rssi" in phy_stats: message.rssi = phy_stats["rssi"]
if "snr" in phy_stats: message.snr = phy_stats["snr"]
if "q" in phy_stats: message.q = phy_stats["q"]
# TODO: Update these descriptions to account for ratchets
if destination_type == RNS.Destination.SINGLE:
message.transport_encrypted = True
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
@@ -971,6 +1361,7 @@ class LXMRouter:
self.__delivery_callback(message)
except Exception as e:
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
RNS.trace_exception(e)
return True
@@ -982,11 +1373,14 @@ class LXMRouter:
def delivery_packet(self, data, packet):
packet.prove()
try:
method = None
if packet.destination_type != RNS.Destination.LINK:
method = LXMessage.OPPORTUNISTIC
lxmf_data = b""
lxmf_data += packet.destination.hash
lxmf_data += data
else:
method = LXMessage.DIRECT
lxmf_data = data
try:
@@ -999,7 +1393,7 @@ class LXMRouter:
phy_stats = {"rssi": packet.rssi, "snr": packet.snr, "q": packet.q}
self.lxmf_delivery(lxmf_data, packet.destination_type, phy_stats=phy_stats)
self.lxmf_delivery(lxmf_data, packet.destination_type, phy_stats=phy_stats, ratchet_id=packet.ratchet_id, method=method)
except Exception as e:
RNS.log("Exception occurred while parsing incoming LXMF data.", RNS.LOG_ERROR)
@@ -1012,6 +1406,7 @@ class LXMRouter:
link.set_resource_callback(self.delivery_resource_advertised)
link.set_resource_started_callback(self.resource_transfer_began)
link.set_resource_concluded_callback(self.delivery_resource_concluded)
link.set_remote_identified_callback(self.delivery_remote_identified)
def delivery_link_closed(self, link):
pass
@@ -1031,8 +1426,17 @@ class LXMRouter:
def delivery_resource_concluded(self, resource):
RNS.log("Transfer concluded for LXMF delivery resource "+str(resource), RNS.LOG_DEBUG)
if resource.status == RNS.Resource.COMPLETE:
ratchet_id = None
# Set ratchet ID to link ID if available
if resource.link and hasattr(resource.link, "link_id"):
ratchet_id = resource.link.link_id
phy_stats = {"rssi": resource.link.rssi, "snr": resource.link.snr, "q": resource.link.q}
self.lxmf_delivery(resource.data.read(), resource.link.type, phy_stats=phy_stats)
self.lxmf_delivery(resource.data.read(), resource.link.type, phy_stats=phy_stats, ratchet_id=ratchet_id, method=LXMessage.DIRECT)
def delivery_remote_identified(self, link, identity):
destination_hash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", identity)
self.backchannel_links[destination_hash] = link
RNS.log(f"Backchannel became available for {RNS.prettyhexrep(destination_hash)} on delivery link {link}", RNS.LOG_DEBUG)
### Peer Sync & Propagation ###########################
@@ -1223,7 +1627,11 @@ class LXMRouter:
except Exception as e:
RNS.log("Error while unpacking received propagation resource", RNS.LOG_DEBUG)
def lxmf_propagation(self, lxmf_data, signal_local_delivery=None, signal_duplicate=None):
def lxmf_propagation(self, lxmf_data, signal_local_delivery=None, signal_duplicate=None, is_paper_message=False):
no_stamp_enforcement = False
if is_paper_message:
no_stamp_enforcement = True
try:
if len(lxmf_data) >= LXMessage.LXMF_OVERHEAD:
transient_id = RNS.Identity.full_hash(lxmf_data)
@@ -1239,12 +1647,13 @@ class LXMRouter:
delivery_destination = self.delivery_destinations[destination_hash]
encrypted_lxmf_data = lxmf_data[LXMessage.DESTINATION_LENGTH:]
decrypted_lxmf_data = delivery_destination.decrypt(encrypted_lxmf_data)
delivery_data = lxmf_data[:LXMessage.DESTINATION_LENGTH]+decrypted_lxmf_data
self.lxmf_delivery(delivery_data, delivery_destination.type)
self.locally_delivered_transient_ids[transient_id] = time.time()
if decrypted_lxmf_data != None:
delivery_data = lxmf_data[:LXMessage.DESTINATION_LENGTH]+decrypted_lxmf_data
self.lxmf_delivery(delivery_data, delivery_destination.type, ratchet_id=delivery_destination.latest_ratchet_id, method=LXMessage.PROPAGATED, no_stamp_enforcement=no_stamp_enforcement)
self.locally_delivered_transient_ids[transient_id] = time.time()
if signal_local_delivery != None:
return signal_local_delivery
if signal_local_delivery != None:
return signal_local_delivery
else:
if self.propagation_node:
@@ -1290,7 +1699,7 @@ class LXMRouter:
lxmf_data = base64.urlsafe_b64decode(uri.replace(LXMessage.URI_SCHEMA+"://", "").replace("/", "")+"==")
transient_id = RNS.Identity.full_hash(lxmf_data)
router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate)
router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate, is_paper_message=True)
if router_propagation_result != False:
RNS.log("LXM with transient ID "+RNS.prettyhexrep(transient_id)+" was ingested.", RNS.LOG_DEBUG)
return router_propagation_result
@@ -1305,13 +1714,49 @@ class LXMRouter:
def fail_message(self, lxmessage):
RNS.log(str(lxmessage)+" failed to send", RNS.LOG_DEBUG)
self.pending_outbound.remove(lxmessage)
if lxmessage in self.pending_outbound:
self.pending_outbound.remove(lxmessage)
self.failed_outbound.append(lxmessage)
lxmessage.state = LXMessage.FAILED
if lxmessage.failed_callback != None and callable(lxmessage.failed_callback):
lxmessage.failed_callback(lxmessage)
def process_deferred_stamps(self):
if len(self.pending_deferred_stamps) > 0:
if self.stamp_gen_lock.locked():
return
else:
with self.stamp_gen_lock:
selected_lxm = None
selected_message_id = None
for message_id in self.pending_deferred_stamps:
lxmessage = self.pending_deferred_stamps[message_id]
if selected_lxm == None:
selected_lxm = lxmessage
selected_message_id = message_id
if selected_lxm != None:
RNS.log(f"Starting stamp generation for {selected_lxm}...", RNS.LOG_DEBUG)
generated_stamp = selected_lxm.get_stamp()
if generated_stamp:
selected_lxm.stamp = generated_stamp
selected_lxm.defer_stamp = False
selected_lxm.packed = None
selected_lxm.pack()
self.pending_deferred_stamps.pop(selected_message_id)
self.pending_outbound.append(selected_lxm)
RNS.log(f"Stamp generation completed for {selected_lxm}", RNS.LOG_DEBUG)
else:
RNS.log(f"Deferred stamp generation did not succeed. Failing {selected_lxm}.", RNS.LOG_ERROR)
selected_lxm.stamp_generation_failed = True
self.pending_deferred_stamps.pop(selected_message_id)
self.fail_message(selected_lxm)
def process_outbound(self, sender = None):
if self.processing_outbound:
return
@@ -1320,19 +1765,63 @@ class LXMRouter:
if lxmessage.state == LXMessage.DELIVERED:
RNS.log("Delivery has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
self.pending_outbound.remove(lxmessage)
elif lxmessage.state == LXMessage.SENT:
# Udate ticket delivery stats
if lxmessage.include_ticket and FIELD_TICKET in lxmessage.fields:
RNS.log(f"Updating latest ticket delivery for {RNS.prettyhexrep(lxmessage.destination_hash)}", RNS.LOG_DEBUG)
self.available_tickets["last_deliveries"][lxmessage.destination_hash] = time.time()
self.save_available_tickets()
# Prepare link for backchannel communications
delivery_destination_hash = lxmessage.get_destination().hash
if lxmessage.method == LXMessage.DIRECT and delivery_destination_hash in self.direct_links:
direct_link = self.direct_links[delivery_destination_hash]
if not hasattr(direct_link, "backchannel_identified") or direct_link.backchannel_identified == False:
if direct_link.initiator == True:
source_destination_hash = lxmessage.get_source().hash
if source_destination_hash in self.delivery_destinations:
backchannel_identity = self.delivery_destinations[source_destination_hash].identity
backchannel_desthash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", backchannel_identity)
direct_link.identify(backchannel_identity)
direct_link.backchannel_identified = True
self.delivery_link_established(direct_link)
RNS.log(f"Performed backchannel identification as {RNS.prettyhexrep(backchannel_desthash)} on {direct_link}", RNS.LOG_DEBUG)
elif lxmessage.method == LXMessage.PROPAGATED and lxmessage.state == LXMessage.SENT:
RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
self.pending_outbound.remove(lxmessage)
else:
RNS.log("Starting outbound processing for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
if lxmessage.progress == None or lxmessage.progress < 0.01:
lxmessage.progress = 0.01
# Outbound handling for opportunistic messages
if lxmessage.method == LXMessage.OPPORTUNISTIC:
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
if lxmessage.delivery_attempts >= LXMRouter.MAX_PATHLESS_TRIES and not RNS.Transport.has_path(lxmessage.get_destination().hash):
RNS.log(f"Requesting path to {RNS.prettyhexrep(lxmessage.get_destination().hash)} after {lxmessage.delivery_attempts} pathless tries for {lxmessage}", RNS.LOG_DEBUG)
lxmessage.delivery_attempts += 1
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts)+" for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
lxmessage.send()
RNS.Transport.request_path(lxmessage.get_destination().hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
lxmessage.progress = 0.01
elif lxmessage.delivery_attempts == LXMRouter.MAX_PATHLESS_TRIES+1 and RNS.Transport.has_path(lxmessage.get_destination().hash):
RNS.log(f"Opportunistic delivery for {lxmessage} still unsuccessful after {lxmessage.delivery_attempts} attempts, trying to rediscover path to {RNS.prettyhexrep(lxmessage.get_destination().hash)}", RNS.LOG_DEBUG)
lxmessage.delivery_attempts += 1
RNS.Reticulum.get_instance().drop_path(lxmessage.get_destination().hash)
def rediscover_job():
time.sleep(0.5)
RNS.Transport.request_path(lxmessage.get_destination().hash)
threading.Thread(target=rediscover_job, daemon=True).start()
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
lxmessage.progress = 0.01
else:
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
lxmessage.delivery_attempts += 1
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts)+" for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
lxmessage.send()
else:
RNS.log("Max delivery attempts reached for oppertunistic "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage)
@@ -1342,16 +1831,28 @@ class LXMRouter:
elif lxmessage.method == LXMessage.DIRECT:
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
delivery_destination_hash = lxmessage.get_destination().hash
direct_link = None
if delivery_destination_hash in self.direct_links:
# A link already exists, so we'll try to use it
# to deliver the message
# An established direct link already exists to
# the destination, so we'll try to use it for
# delivering the message
direct_link = self.direct_links[delivery_destination_hash]
RNS.log(f"Using available direct link {direct_link} to {RNS.prettyhexrep(delivery_destination_hash)}", RNS.LOG_DEBUG)
elif delivery_destination_hash in self.backchannel_links:
# An established backchannel link exists to
# the destination, so we'll try to use it for
# delivering the message
direct_link = self.backchannel_links[delivery_destination_hash]
RNS.log(f"Using available backchannel link {direct_link} to {RNS.prettyhexrep(delivery_destination_hash)}", RNS.LOG_DEBUG)
if direct_link != None:
if direct_link.status == RNS.Link.ACTIVE:
if lxmessage.progress == None or lxmessage.progress < 0.05:
lxmessage.progress = 0.05
if lxmessage.state != LXMessage.SENDING:
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" on link "+str(direct_link), RNS.LOG_DEBUG)
lxmessage.set_delivery_destination(direct_link)
lxmessage.send()
else:
@@ -1373,7 +1874,10 @@ class LXMRouter:
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
lxmessage.set_delivery_destination(None)
self.direct_links.pop(delivery_destination_hash)
if delivery_destination_hash in self.direct_links:
self.direct_links.pop(delivery_destination_hash)
if delivery_destination_hash in self.backchannel_links:
self.backchannel_links.pop(delivery_destination_hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
else:
# Simply wait for the link to become active or close
@@ -1397,7 +1901,7 @@ class LXMRouter:
RNS.log("No path known for delivery attempt "+str(lxmessage.delivery_attempts)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+". Requesting path...", RNS.LOG_DEBUG)
RNS.Transport.request_path(lxmessage.get_destination().hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
lxmessage.progress = 0.00
lxmessage.progress = 0.01
else:
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage)
+186 -36
View File
@@ -1,19 +1,23 @@
import RNS
import RNS.vendor.umsgpack as msgpack
import os
import time
import base64
import multiprocessing
import LXMF.LXStamper as LXStamper
from .LXMF import APP_NAME
class LXMessage:
DRAFT = 0x00
GENERATING = 0x00
OUTBOUND = 0x01
SENDING = 0x02
SENT = 0x04
DELIVERED = 0x08
FAILED = 0xFF
states = [DRAFT, OUTBOUND, SENDING, SENT, DELIVERED, FAILED]
states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, FAILED]
UNKNOWN = 0x00
PACKET = 0x01
@@ -32,19 +36,33 @@ class LXMessage:
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
SIGNATURE_LENGTH = RNS.Identity.SIGLENGTH//8
TICKET_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
# LXMF overhead is 111 bytes per message:
# Default ticket expiry is 3 weeks, with an
# additional grace period of 5 days, allowing
# for timekeeping inaccuracies. Tickets will
# automatically renew when there is less than
# 14 days to expiry.
TICKET_EXPIRY = 21*24*60*60
TICKET_GRACE = 5*24*60*60
TICKET_RENEW = 14*24*60*60
TICKET_INTERVAL = 1*24*60*60
COST_TICKET = 0x100
# LXMF overhead is 112 bytes per message:
# 16 bytes for destination hash
# 16 bytes for source hash
# 64 bytes for Ed25519 signature
# 8 bytes for timestamp
# 7 bytes for msgpack structure
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + 8 + 7
# 8 bytes for msgpack structure
TIMESTAMP_SIZE = 8
STRUCT_OVERHEAD = 8
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + TIMESTAMP_SIZE + STRUCT_OVERHEAD
# With an MTU of 500, the maximum amount of data
# we can send in a single encrypted packet is
# 383 bytes.
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU
# 391 bytes.
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU + TIMESTAMP_SIZE
# The max content length we can fit in LXMF message
# inside a single RNS packet is the encrypted MDU, minus
@@ -53,7 +71,7 @@ class LXMessage:
# field of the packet, therefore we also add the length
# of a destination hash to the calculation. With default
# RNS and LXMF parameters, the largest single-packet
# LXMF message we can send is 288 bytes. If a message
# LXMF message we can send is 295 bytes. If a message
# is larger than that, a Reticulum link will be used.
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
@@ -63,13 +81,13 @@ class LXMessage:
LINK_PACKET_MDU = RNS.Link.MDU
# Which means that we can deliver single-packet LXMF
# messages with content of up to 320 bytes over a link.
# messages with content of up to 319 bytes over a link.
# If a message is larger than that, LXMF will sequence
# and transfer it as a RNS resource over the link instead.
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
# For plain packets without encryption, we can
# fit up to 369 bytes of content.
# fit up to 368 bytes of content.
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
@@ -90,7 +108,8 @@ class LXMessage:
else:
return "<LXMessage>"
def __init__(self, destination, source, content = "", title = "", fields = None, desired_method = None, destination_hash = None, source_hash = None):
def __init__(self, destination, source, content = "", title = "", fields = None, desired_method = None, destination_hash = None, source_hash = None, stamp_cost=None, include_ticket=False):
if isinstance(destination, RNS.Destination) or destination == None:
self.__destination = destination
if destination != None:
@@ -109,21 +128,41 @@ class LXMessage:
else:
raise ValueError("LXMessage initialised with invalid source")
self.set_title_from_string(title)
self.set_content_from_string(content)
if title == None:
title = ""
if type(title) == bytes:
self.set_title_from_bytes(title)
else:
self.set_title_from_string(title)
if type(content) == bytes:
self.set_content_from_bytes(content)
else:
self.set_content_from_string(content)
self.set_fields(fields)
self.payload = None
self.timestamp = None
self.signature = None
self.hash = None
self.packed = None
self.progress = 0.0
self.state = LXMessage.DRAFT
self.method = LXMessage.UNKNOWN
self.rssi = None
self.snr = None
self.q = None
self.payload = None
self.timestamp = None
self.signature = None
self.hash = None
self.packed = None
self.state = LXMessage.GENERATING
self.method = LXMessage.UNKNOWN
self.progress = 0.0
self.rssi = None
self.snr = None
self.q = None
self.stamp = None
self.stamp_cost = stamp_cost
self.stamp_value = None
self.stamp_valid = False
self.stamp_checked = False
self.defer_stamp = True
self.outbound_ticket = None
self.include_ticket = include_ticket
self.propagation_packed = None
self.paper_packed = None
@@ -131,17 +170,21 @@ class LXMessage:
self.incoming = False
self.signature_validated = False
self.unverified_reason = None
self.ratchet_id = None
self.representation = LXMessage.UNKNOWN
self.desired_method = desired_method
self.delivery_attempts = 0
self.transport_encrypted = False
self.transport_encryption = None
self.ratchet_id = None
self.packet_representation = None
self.resource_representation = None
self.__delivery_destination = None
self.__delivery_callback = None
self.failed_callback = None
self.failed_callback = None
self.deferred_stamp_generating = False
def set_title_from_string(self, title_string):
self.title = title_string.encode("utf-8")
@@ -159,7 +202,11 @@ class LXMessage:
self.content = content_bytes
def content_as_string(self):
return self.content.decode("utf-8")
try:
return self.content.decode("utf-8")
except Exception as e:
RNS.log(f"{self} could not decode message content as string: {e}")
return None
def set_fields(self, fields):
if isinstance(fields, dict) or fields == None:
@@ -219,6 +266,71 @@ class LXMessage:
def register_failed_callback(self, callback):
self.failed_callback = callback
@staticmethod
def stamp_valid(stamp, target_cost, workblock):
target = 0b1 << 256-target_cost
result = RNS.Identity.full_hash(workblock+stamp)
if int.from_bytes(result, byteorder="big") > target:
return False
else:
return True
def validate_stamp(self, target_cost, tickets=None):
if tickets != None:
for ticket in tickets:
try:
if self.stamp == RNS.Identity.truncated_hash(ticket+self.message_id):
RNS.log(f"Stamp on {self} validated by inbound ticket", RNS.LOG_DEBUG) # TODO: Remove at some point
self.stamp_value = LXMessage.COST_TICKET
return True
except Exception as e:
RNS.log(f"Error while validating ticket: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
if self.stamp == None:
return False
else:
workblock = LXStamper.stamp_workblock(self.message_id)
if LXMessage.stamp_valid(self.stamp, target_cost, workblock):
RNS.log(f"Stamp on {self} validated", RNS.LOG_DEBUG) # TODO: Remove at some point
self.stamp_value = LXStamper.stamp_value(workblock, self.stamp)
return True
else:
return False
def get_stamp(self, timeout=None):
# If an outbound ticket exists, use this for
# generating a valid stamp.
if self.outbound_ticket != None and type(self.outbound_ticket) == bytes and len(self.outbound_ticket) == LXMessage.TICKET_LENGTH:
generated_stamp = RNS.Identity.truncated_hash(self.outbound_ticket+self.message_id)
self.stamp_value = LXMessage.COST_TICKET
RNS.log(f"Generated stamp with outbound ticket {RNS.hexrep(self.outbound_ticket)} for {self}", RNS.LOG_DEBUG) # TODO: Remove at some point
return generated_stamp
# If no stamp cost is required, we can just
# return immediately.
elif self.stamp_cost == None:
self.stamp_value = None
return None
# If a stamp was already generated, return
# it immediately.
elif self.stamp != None:
return self.stamp
# Otherwise, we will need to generate a
# valid stamp according to the cost that
# the receiver has specified.
else:
generated_stamp, value = LXStamper.generate_stamp(self.message_id, self.stamp_cost)
if generated_stamp:
self.stamp_value = value
self.stamp_valid = True
return generated_stamp
else:
return None
def pack(self):
if not self.packed:
if self.timestamp == None:
@@ -235,6 +347,11 @@ class LXMessage:
hashed_part += msgpack.packb(self.payload)
self.hash = RNS.Identity.full_hash(hashed_part)
self.message_id = self.hash
if not self.defer_stamp:
self.stamp = self.get_stamp()
if self.stamp != None:
self.payload.append(self.stamp)
signed_part = b""
signed_part += hashed_part
@@ -242,21 +359,29 @@ class LXMessage:
self.signature = self.__source.sign(signed_part)
self.signature_validated = True
packed_payload = msgpack.packb(self.payload)
self.packed = b""
self.packed += self.__destination.hash
self.packed += self.__source.hash
self.packed += self.signature
packed_payload = msgpack.packb(self.payload)
self.packed += packed_payload
self.packed_size = len(self.packed)
content_size = len(packed_payload)
content_size = len(packed_payload)-LXMessage.TIMESTAMP_SIZE-LXMessage.STRUCT_OVERHEAD
# If no desired delivery method has been defined,
# one will be chosen according to these rules:
if self.desired_method == None:
self.desired_method = LXMessage.DIRECT
# TODO: Expand rules to something more intelligent
# If opportunistic delivery was requested, check
# that message will fit within packet size limits
if self.desired_method == LXMessage.OPPORTUNISTIC:
if self.__destination.type == RNS.Destination.SINGLE:
if content_size > LXMessage.ENCRYPTED_PACKET_MAX_CONTENT:
RNS.log(f"Opportunistic delivery was requested for {self}, but content exceeds packet size limit. Falling back to link-based delivery.", RNS.LOG_DEBUG)
self.desired_method = LXMessage.DIRECT
# Set delivery parameters according to delivery method
if self.desired_method == LXMessage.OPPORTUNISTIC:
if self.__destination.type == RNS.Destination.SINGLE:
single_packet_content_limit = LXMessage.ENCRYPTED_PACKET_MAX_CONTENT
@@ -264,7 +389,7 @@ class LXMessage:
single_packet_content_limit = LXMessage.PLAIN_PACKET_MAX_CONTENT
if content_size > single_packet_content_limit:
raise TypeError("LXMessage desired opportunistic delivery method, but content exceeds single-packet size.")
raise TypeError(f"LXMessage desired opportunistic delivery method, but content of length {content_size} exceeds single-packet content limit of {single_packet_content_limit}.")
else:
self.method = LXMessage.OPPORTUNISTIC
self.representation = LXMessage.PACKET
@@ -283,6 +408,7 @@ class LXMessage:
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
self.ratchet_id = self.__destination.latest_ratchet_id
self.propagation_packed = msgpack.packb([time.time(), [self.packed[:LXMessage.DESTINATION_LENGTH]+encrypted_data]])
content_size = len(self.propagation_packed)
@@ -297,6 +423,7 @@ class LXMessage:
paper_content_limit = LXMessage.PAPER_MDU
encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
self.ratchet_id = self.__destination.latest_ratchet_id
self.paper_packed = self.packed[:LXMessage.DESTINATION_LENGTH]+encrypted_data
content_size = len(self.paper_packed)
@@ -313,14 +440,19 @@ class LXMessage:
self.determine_transport_encryption()
if self.method == LXMessage.OPPORTUNISTIC:
self.__as_packet().send().set_delivery_callback(self.__mark_delivered)
lxm_packet = self.__as_packet()
lxm_packet.send().set_delivery_callback(self.__mark_delivered)
self.progress = 0.50
self.ratchet_id = lxm_packet.ratchet_id
self.state = LXMessage.SENT
elif self.method == LXMessage.DIRECT:
self.state = LXMessage.SENDING
if self.representation == LXMessage.PACKET:
receipt = self.__as_packet().send()
lxm_packet = self.__as_packet()
receipt = lxm_packet.send()
self.ratchet_id = self.__delivery_destination.link_id
if receipt:
receipt.set_delivery_callback(self.__mark_delivered)
receipt.set_timeout_callback(self.__link_packet_timed_out)
@@ -331,6 +463,7 @@ class LXMessage:
elif self.representation == LXMessage.RESOURCE:
self.resource_representation = self.__as_resource()
self.ratchet_id = self.__delivery_destination.link_id
self.progress = 0.10
elif self.method == LXMessage.PROPAGATED:
@@ -351,6 +484,9 @@ class LXMessage:
def determine_transport_encryption(self):
# TODO: These descriptions are old and outdated.
# Update the transport encryption descriptions to
# account for ratchets and other changes.
if self.method == LXMessage.OPPORTUNISTIC:
if self.__destination.type == RNS.Destination.SINGLE:
self.transport_encrypted = True
@@ -397,7 +533,8 @@ class LXMessage:
try:
self.__delivery_callback(self)
except Exception as e:
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
RNS.log("An error occurred in the external delivery callback for "+str(self), RNS.LOG_ERROR)
RNS.trace_exception(e)
def __mark_propagated(self, receipt = None):
RNS.log("Received propagation success notification for "+str(self), RNS.LOG_DEBUG)
@@ -408,7 +545,8 @@ class LXMessage:
try:
self.__delivery_callback(self)
except Exception as e:
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
RNS.log("An error occurred in the external delivery callback for "+str(self), RNS.LOG_ERROR)
RNS.trace_exception(e)
def __mark_paper_generated(self, receipt = None):
RNS.log("Paper message generation succeeded for "+str(self), RNS.LOG_DEBUG)
@@ -419,7 +557,8 @@ class LXMessage:
try:
self.__delivery_callback(self)
except Exception as e:
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
RNS.log("An error occurred in the external delivery callback for "+str(self), RNS.LOG_ERROR)
RNS.trace_exception(e)
def __resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE:
@@ -563,10 +702,19 @@ class LXMessage:
source_hash = lxmf_bytes[LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH]
signature = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH]
packed_payload = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH:]
unpacked_payload = msgpack.unpackb(packed_payload)
# Extract stamp from payload if included
if len(unpacked_payload) > 4:
stamp = unpacked_payload[4]
unpacked_payload = unpacked_payload[:4]
packed_payload = msgpack.packb(unpacked_payload)
else:
stamp = None
hashed_part = b"" + destination_hash + source_hash + packed_payload
message_hash = RNS.Identity.full_hash(hashed_part)
signed_part = b"" + hashed_part + message_hash
unpacked_payload = msgpack.unpackb(packed_payload)
timestamp = unpacked_payload[0]
title_bytes = unpacked_payload[1]
content_bytes = unpacked_payload[2]
@@ -595,7 +743,9 @@ class LXMessage:
desired_method = original_method)
message.hash = message_hash
message.message_id = message.hash
message.signature = signature
message.stamp = stamp
message.incoming = True
message.timestamp = timestamp
message.packed = lxmf_bytes
+280
View File
@@ -0,0 +1,280 @@
import RNS
import RNS.vendor.umsgpack as msgpack
import os
import time
import multiprocessing
WORKBLOCK_EXPAND_ROUNDS = 3000
def stamp_workblock(message_id):
wb_st = time.time()
expand_rounds = WORKBLOCK_EXPAND_ROUNDS
workblock = b""
for n in range(expand_rounds):
workblock += RNS.Cryptography.hkdf(
length=256,
derive_from=message_id,
salt=RNS.Identity.full_hash(message_id+msgpack.packb(n)),
context=None,
)
wb_time = time.time() - wb_st
RNS.log(f"Stamp workblock size {RNS.prettysize(len(workblock))}, generated in {round(wb_time*1000,2)}ms", RNS.LOG_DEBUG)
return workblock
def stamp_value(workblock, stamp):
value = 0
bits = 256
material = RNS.Identity.full_hash(workblock+stamp)
i = int.from_bytes(material, byteorder="big")
while ((i & (1 << (bits - 1))) == 0):
i = (i << 1)
value += 1
return value
def generate_stamp(message_id, stamp_cost):
RNS.log(f"Generating stamp with cost {stamp_cost} for {RNS.prettyhexrep(message_id)}...", RNS.LOG_DEBUG)
workblock = stamp_workblock(message_id)
start_time = time.time()
stamp = None
rounds = 0
value = 0
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin():
stamp, rounds = job_simple(stamp_cost, workblock)
elif RNS.vendor.platformutils.is_android():
stamp, rounds = job_android(stamp_cost, workblock)
else:
stamp, rounds = job_linux(stamp_cost, workblock)
duration = time.time() - start_time
speed = rounds/duration
value = stamp_value(workblock, stamp)
RNS.log(f"Stamp with value {value} generated in {RNS.prettytime(duration)}, {rounds} rounds, {int(speed)} rounds per second", RNS.LOG_DEBUG)
return stamp, value
def job_simple(stamp_cost, workblock):
# A simple, single-process stamp generator.
# should work on any platform, and is used
# as a fall-back, in case of limited multi-
# processing and/or acceleration support.
platform = RNS.vendor.platformutils.get_platform()
RNS.log(f"Running stamp generation on {platform}, work limited to single CPU core. This will be slower than ideal.", RNS.LOG_WARNING)
rounds = 0
pstamp = os.urandom(256//8)
st = time.time()
def sv(s, c, w):
target = 0b1<<256-c; m = w+s
result = RNS.Identity.full_hash(m)
if int.from_bytes(result, byteorder="big") > target:
return False
else:
return True
while not sv(pstamp, stamp_cost, workblock):
pstamp = os.urandom(256//8); rounds += 1
if rounds % 2500 == 0:
speed = rounds / (time.time()-st)
RNS.log(f"Stamp generation running. {rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
return pstamp, rounds
def job_linux(stamp_cost, workblock):
allow_kill = True
stamp = None
total_rounds = 0
jobs = multiprocessing.cpu_count()
stop_event = multiprocessing.Event()
result_queue = multiprocessing.Queue(1)
rounds_queue = multiprocessing.Queue()
def job(stop_event, pn, sc, wb):
terminated = False
rounds = 0
pstamp = os.urandom(256//8)
def sv(s, c, w):
target = 0b1<<256-c; m = w+s
result = RNS.Identity.full_hash(m)
if int.from_bytes(result, byteorder="big") > target:
return False
else:
return True
while not stop_event.is_set() and not sv(pstamp, sc, wb):
pstamp = os.urandom(256//8); rounds += 1
if not stop_event.is_set():
stop_event.set()
result_queue.put(pstamp)
rounds_queue.put(rounds)
job_procs = []
RNS.log(f"Starting {jobs} stamp generation workers", RNS.LOG_DEBUG)
for jpn in range(jobs):
process = multiprocessing.Process(target=job, kwargs={"stop_event": stop_event, "pn": jpn, "sc": stamp_cost, "wb": workblock}, daemon=True)
job_procs.append(process)
process.start()
stamp = result_queue.get()
RNS.log("Got stamp result from worker", RNS.LOG_DEBUG) # TODO: Remove
# Collect any potential spurious
# results from worker queue.
try:
while True:
result_queue.get_nowait()
except:
pass
for j in range(jobs):
nrounds = 0
try:
nrounds = rounds_queue.get(timeout=2)
except Exception as e:
RNS.log(f"Failed to get round stats part {j}: {e}", RNS.LOG_ERROR)
total_rounds += nrounds
all_exited = False
exit_timeout = time.time() + 5
while time.time() < exit_timeout:
if not any(p.is_alive() for p in job_procs):
all_exited = True
break
time.sleep(0.1)
if not all_exited:
RNS.log("Stamp generation IPC timeout, possible worker deadlock. Terminating remaining processes.", RNS.LOG_ERROR)
if allow_kill:
for j in range(jobs):
process = job_procs[j]
process.kill()
else:
return None
else:
for j in range(jobs):
process = job_procs[j]
process.join()
# RNS.log(f"Joined {j} / {process}", RNS.LOG_DEBUG) # TODO: Remove
return stamp, total_rounds
def job_android(stamp_cost, workblock):
# Semaphore support is flaky to non-existent on
# Android, so we need to manually dispatch and
# manage workloads here, while periodically
# checking in on the progress.
stamp = None
start_time = time.time()
total_rounds = 0
rounds_per_worker = 1000
use_nacl = False
try:
import nacl.encoding
import nacl.hash
use_nacl = True
except:
pass
if use_nacl:
def full_hash(m):
return nacl.hash.sha256(m, encoder=nacl.encoding.RawEncoder)
else:
def full_hash(m):
return RNS.Identity.full_hash(m)
def sv(s, c, w):
target = 0b1<<256-c
m = w+s
result = full_hash(m)
if int.from_bytes(result, byteorder="big") > target:
return False
else:
return True
wm = multiprocessing.Manager()
jobs = multiprocessing.cpu_count()
def job(procnum=None, results_dict=None, wb=None, sc=None, jr=None):
# RNS.log(f"Worker {procnum} starting for {jr} rounds...") # TODO: Remove
try:
rounds = 0
found_stamp = None
while True:
pstamp = os.urandom(256//8)
rounds += 1
if sv(pstamp, sc, wb):
found_stamp = pstamp
break
if rounds >= jr:
# RNS.log(f"Worker {procnum} found no result in {rounds} rounds") # TODO: Remove
break
results_dict[procnum] = [found_stamp, rounds]
except Exception as e:
RNS.log(f"Stamp generation worker error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove
results_dict = wm.dict()
while stamp == None:
job_procs = []
try:
for pnum in range(jobs):
pargs = {"procnum":pnum, "results_dict": results_dict, "wb": workblock, "sc":stamp_cost, "jr":rounds_per_worker}
process = multiprocessing.Process(target=job, kwargs=pargs)
job_procs.append(process)
process.start()
for process in job_procs:
process.join()
for j in results_dict:
r = results_dict[j]
total_rounds += r[1]
if r[0] != None:
stamp = r[0]
if stamp == None:
elapsed = time.time() - start_time
speed = total_rounds/elapsed
RNS.log(f"Stamp generation running. {total_rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
except Exception as e:
RNS.log(f"Stamp generation job error: {e}")
RNS.trace_exception(e)
return stamp, total_rounds
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
RNS.log("No cost argument provided", RNS.LOG_ERROR)
exit(1)
else:
try:
cost = int(sys.argv[1])
except Exception as e:
RNS.log(f"Invalid cost argument provided: {e}", RNS.LOG_ERROR)
exit(1)
RNS.loglevel = RNS.LOG_DEBUG
RNS.log("Testing LXMF stamp generation", RNS.LOG_DEBUG)
message_id = os.urandom(32)
generate_stamp(message_id, cost)
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.4.4"
__version__ = "0.5.7"
+38 -9
View File
@@ -7,6 +7,7 @@ LXMF is efficient enough that it can deliver messages over extremely low-bandwid
User-facing clients built on LXMF include:
- [Sideband](https://unsigned.io/sideband)
- [MeshChat](https://github.com/liamcottle/reticulum-meshchat)
- [Nomad Network](https://unsigned.io/nomadnet)
Community-provided tools and utilities for LXMF include:
@@ -129,10 +130,6 @@ You can also find the entire message in <a href="lxm://azNivSwdv4e2aoX3mo2MdTAoz
On operating systems that allow for registering custom URI-handlers, you can click the link, and it will be decoded directly in your LXMF client. This works with Sideband on Android.
## Caveat Emptor
LXMF is beta software, and should be considered experimental. While it has been built with cryptography best practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
## Installation
If you want to try out LXMF, you can install it with pip:
@@ -156,14 +153,46 @@ Alternatively, you can use the `pipx` tool to install Reticulum in an isolated e
pipx install lxmf
```
## Daemon Included
The `lxmf` package comes with the `lxmd` program, a fully functional (but lightweight) LXMF message router and propagation node daemon. After installing the `lxmf` package, you can run `lxmd --help` to learn more about the command-line options:
```text
$ lxmd --help
usage: lxmd [-h] [--config CONFIG] [--rnsconfig RNSCONFIG] [-p] [-i PATH] [-v] [-q] [-s] [--exampleconfig] [--version]
Lightweight Extensible Messaging Daemon
options:
-h, --help show this help message and exit
--config CONFIG path to alternative lxmd config directory
--rnsconfig RNSCONFIG
path to alternative Reticulum config directory
-p, --propagation-node
run an LXMF Propagation Node
-i PATH, --on-inbound PATH
executable to run when a message is received
-v, --verbose
-q, --quiet
-s, --service lxmd is running as a service and should log to file
--exampleconfig print verbose configuration example to stdout and exit
--version show program's version number and exit
```
Or run `lxmd --exampleconfig` to generate a commented example configuration documenting all the available configuration directives.
## Caveat Emptor
LXMF is beta software, and should be considered experimental. While it has been built with cryptography best practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
## Development Roadmap
LXMF is actively being developed, and the following improvements and features are currently planned for implementation:
- Write and release full API and protocol documentation
- Update examples in readme to actually work
- Content Destinations, and easy to use API for group messaging and discussion threads
- ~~Update examples in readme to actually work~~
- ~~Sync affinity based on link speeds and distances, for more intelligently choosing peer sync order~~
- Sneakernet and physical transport functionality
- Content Destinations, and easy to use API for group messaging and discussion threads
- Write and release full API and protocol documentation
- Documenting and possibly expanding LXMF limits and priorities
- Sync affinity based on link speeds and distances, for more intelligently choosing peer sync order
- Markets on LXMF
+40 -5
View File
@@ -2,7 +2,11 @@ import RNS
import LXMF
import time
required_stamp_cost = 8
enforce_stamps = False
def delivery_callback(message):
global my_lxmf_destination, router
time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(message.timestamp))
signature_string = "Signature is invalid, reason undetermined"
if message.signature_validated:
@@ -13,6 +17,11 @@ def delivery_callback(message):
if message.unverified_reason == LXMF.LXMessage.SOURCE_UNKNOWN:
signature_string = "Cannot verify, source is unknown"
if message.stamp_valid:
stamp_string = "Validated"
else:
stamp_string = "Invalid"
RNS.log("\t+--- LXMF Delivery ---------------------------------------------")
RNS.log("\t| Source hash : "+RNS.prettyhexrep(message.source_hash))
RNS.log("\t| Source instance : "+str(message.get_source()))
@@ -20,18 +29,44 @@ def delivery_callback(message):
RNS.log("\t| Destination instance : "+str(message.get_destination()))
RNS.log("\t| Transport Encryption : "+str(message.transport_encryption))
RNS.log("\t| Timestamp : "+time_string)
RNS.log("\t| Title : "+message.title_as_string())
RNS.log("\t| Content : "+message.content_as_string())
RNS.log("\t| Title : "+str(message.title_as_string()))
RNS.log("\t| Content : "+str(message.content_as_string()))
RNS.log("\t| Fields : "+str(message.fields))
if message.ratchet_id:
RNS.log("\t| Ratchet : "+str(RNS.Identity._get_ratchet_id(message.ratchet_id)))
RNS.log("\t| Message signature : "+signature_string)
RNS.log("\t| Stamp : "+stamp_string)
RNS.log("\t+---------------------------------------------------------------")
# Optionally, send a reply
# source = my_lxmf_destination
# dest = message.source
# lxm = LXMF.LXMessage(dest, source, "Reply", None, desired_method=LXMF.LXMessage.DIRECT, include_ticket=True)
# router.handle_outbound(lxm)
r = RNS.Reticulum()
router = LXMF.LXMRouter(storagepath="./tmp1")
router = LXMF.LXMRouter(storagepath="./tmp1", enforce_stamps=enforce_stamps)
identity = RNS.Identity()
my_lxmf_destination = router.register_delivery_identity(identity)
my_lxmf_destination = router.register_delivery_identity(identity, display_name="Anonymous Peer", stamp_cost=required_stamp_cost)
router.register_delivery_callback(delivery_callback)
RNS.log("Ready to receive on: "+RNS.prettyhexrep(my_lxmf_destination.hash))
input()
# You can set a propagation node address to test receiving
# messages from a propagation node, instead of directly
# router.set_outbound_propagation_node(bytes.fromhex("e75d9b6a69f82b48b6077cf2242d7499"))
# This loop allows you to execute various actions for testing
# and experimenting with the example scripts.
while True:
input()
RNS.log("Announcing lxmf.delivery destination...")
router.announce(my_lxmf_destination.hash)
# input()
# RNS.log("Requesting messages from propagation node...")
# router.request_messages_from_propagation_node(identity)
+33 -3
View File
@@ -4,7 +4,7 @@ import time
import random
random_names = ["Tom", "Delilah", "Nancey", "Williams", "Neomi", "Curtis", "Alexa", "Theodora", "Ted", "Dinorah", "Nicol", "Drusilla", "Annalisa", "Verlene", "Latesha", "Tina", "Mia", "Brock", "Timothy", "Philip", "Willian", "Reyna", "Simona", "Mimi", "Stanford", "Ferne", "Catalina", "Lucie", "Jaye", "Natasha", "Willetta", "Isabel", "Esperanza", "Ciara", "Eusebio", "William", "Elma", "Angelica", "Coreen", "Melani", "Jonathan", "Maryland", "Caroline", "Gregg", "Ora", "Jacqui", "Letty", "Roselle", "Oralee", "Angla"]
random_titles = ["Long time", "Hi again", "Re: Hi there", "Test message", "", "", "Something different"]
random_titles = ["Long time", "Hi again", "Hi there", "Test message", "", "", "Something different"]
random_msgs = ["If wishes were horses then beggars might fly. Stuff like that. It's enough to drive you crazy.", "'My ident cards were stolen,' Jason said. 'That fivehundred-dollar bill is yours if you can get me to someone who can replace them. If you're going to do it, do it right now; I'm not going to wait.' Wait to be picked up by a pol or a nat, he thought. Caught here in this rundown dingy hotel.", "A six, no matter what the external circumstances, will always prevail. Because that's the way they genetically defined us.", "'Should be there in an hour,' he called back over his shoulder to Chuck. Then he added, in an afterthought, 'Wonder if the computer’s finished its run. It was due about now.'. Chuck didn’t reply, so George swung round in his saddle. He could just see Chuck’s face, a white oval turned toward the sky."]
def delivery_callback(message):
@@ -14,7 +14,7 @@ r = RNS.Reticulum()
router = LXMF.LXMRouter(storagepath="./tmp2")
router.register_delivery_callback(delivery_callback)
ident = RNS.Identity()
source = router.register_delivery_identity(ident, display_name=random_names[random.randint(0,len(random_names)-1)])
source = router.register_delivery_identity(ident, display_name=random_names[random.randint(0,len(random_names)-1)], stamp_cost=8)
router.announce(source.hash)
RNS.log("Source announced")
@@ -33,7 +33,37 @@ recipient_identity = RNS.Identity.recall(recipient_hash)
dest = RNS.Destination(recipient_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery")
# This loop allows you to execute various actions for testing
# and experimenting with the example scripts.
while True:
lxm = LXMF.LXMessage(dest, source, random_msgs[random.randint(0,len(random_msgs)-1)], random_titles[random.randint(0,len(random_titles)-1)], desired_method=LXMF.LXMessage.DIRECT)
# Create a message that will be sent directly to the
# destination over a Reticulum link:
lxm = LXMF.LXMessage(dest, source, random_msgs[random.randint(0,len(random_msgs)-1)],
random_titles[random.randint(0,len(random_titles)-1)],
desired_method=LXMF.LXMessage.DIRECT, include_ticket=True)
# Or, create an oppertunistic, single-packet message
# for sending without first establishing a link:
# lxm = LXMF.LXMessage(dest, source, "This is a test",
# random_titles[random.randint(0,len(random_titles)-1)],
# desired_method=LXMF.LXMessage.OPPORTUNISTIC, include_ticket=True)
# Or, try sending the message via a propagation node:
# router.set_outbound_propagation_node(bytes.fromhex("e75d9b6a69f82b48b6077cf2242d7499"))
# lxm = LXMF.LXMessage(dest, source, random_msgs[random.randint(0,len(random_msgs)-1)],
# random_titles[random.randint(0,len(random_titles)-1)],
# desired_method=LXMF.LXMessage.PROPAGATED)
# Finally dispatch the message to the LXMF message
# router, which will handle the delivery according
# to the specified message parameters and options:
router.handle_outbound(lxm)
# Wait for user input before starting over
input()
+2 -2
View File
@@ -1,3 +1,3 @@
qrcode==7.4.2
rns==0.5.7
setuptools==68.0.0
rns==0.7.8
setuptools==70.0.0
+1 -1
View File
@@ -25,6 +25,6 @@ setuptools.setup(
'lxmd=LXMF.Utilities.lxmd:main',
]
},
install_requires=['rns>=0.7.4'],
install_requires=['rns>=0.8.2'],
python_requires='>=3.7',
)