Compare commits

...
26 Commits
Author SHA1 Message Date
Mark Qvist 7dfc835354 Todo comment 2026-11-17 17:22:05 +01:00
Mark Qvist 442dda37ec Added ability to specify delivery destination stamp value at identity registration 2026-11-17 16:35:03 +01:00
Mark Qvist fbcb642450 Transitionally accept both non-expanded and expanded workblock stamps 2026-11-10 00:50:30 +01:00
Mark Qvist 101fd44781 Cleanup 2026-11-08 11:12:02 +01:00
Mark Qvist a0793f6677 Set delivery and propagation link costs 2026-11-06 12:25:47 +01:00
Mark Qvist 2059784a55 Retain on propagation success 2026-11-05 12:46:06 +01:00
Mark Qvist 2b09146a15 Improved display name decode 2026-11-04 12:59:53 +01:00
Mark Qvist c7a902f0aa Merged SQLite storage backend 2026-11-04 00:54:22 +01:00
Mark Qvist d845503b33 Throttle stamp cost persists 2026-11-03 13:14:17 +01:00
Mark Qvist 40dcd7d084 Made PN peer throttle time configurable 2026-11-02 21:05:20 +01:00
Mark Qvist 8ded002689 Fixed missing transient ID cancel 2026-11-02 16:29:36 +01:00
Mark Qvist 810c345de8 Prepared announce filtering 2026-11-01 23:14:03 +01:00
Mark Qvist 2c69fd3684 Cleanup 2026-11-01 10:44:34 +01:00
Mark Qvist 3297f21e62 Fixed int config value getters 2026-10-30 22:42:36 +01:00
Mark Qvist 6e898e67ad Refactoring for fractional-value stamp support 2026-10-30 22:14:59 +01:00
Mark Qvist 1df7ebcdd5 Cleanup 2026-10-28 13:04:49 +01:00
Mark Qvist cc702b75a7 Updated version 2026-10-28 13:04:06 +01:00
Mark Qvist 98e09bbec0 Refactored LXStamper to use RNS.Stamps 2026-10-28 13:03:21 +01:00
Mark Qvist 86692183d9 Fixed non-existent variable in log message 2026-10-26 00:16:26 +01:00
Mark Qvist c98bca2dce Cleanup 2026-10-24 00:44:01 +02:00
Mark Qvist d6df0f7e91 Cleanup 2026-10-24 00:02:23 +02:00
Mark Qvist 700a462674 Improved stamper 2026-10-23 23:53:21 +02:00
Mark Qvist 01387b15f4 Updated version 2026-10-19 15:34:58 +02:00
Mark Qvist 308498e68b Ensure positive durations on stamp-related timing 2026-10-19 15:32:37 +02:00
Mark Qvist e8ba024832 Updated versions 2026-10-05 15:15:24 +02:00
Mark Qvist 5745f85647 Added outbound queue hold mechanism and improved slow-medium processing, by Zenith 2026-10-05 15:14:49 +02:00
12 changed files with 1044 additions and 549 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
Reticulum License Reticulum License
Copyright (c) 2020-2025 Mark Qvist Copyright (c) 2020-2026 Mark Qvist
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+8
View File
@@ -64,6 +64,14 @@ class LXMFPropagationAnnounceHandler:
propagation_stamp_cost_flexibility = int(data[5][1]) propagation_stamp_cost_flexibility = int(data[5][1])
peering_cost = int(data[5][2]) peering_cost = int(data[5][2])
metadata = data[6] metadata = data[6]
# Transitional mechanism, extract the real, fractional-value
# propagation stamp cost if available.
if len(data) > 7:
propagation_stamp_cost = data[7][0]
propagation_stamp_cost_flexibility = data[7][1]
peering_cost = data[7][2]
# TODO: Remove above after 1.6.2 ###########################
if destination_hash in self.lxmrouter.static_peers: if destination_hash in self.lxmrouter.static_peers:
static_peer = self.lxmrouter.peers[destination_hash] static_peer = self.lxmrouter.peers[destination_hash]
+33 -9
View File
@@ -155,7 +155,11 @@ def display_name_from_app_data(app_data=None):
else: else:
# Version 0.5.0+ announce format # Version 0.5.0+ announce format
if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc: if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc:
peer_data = msgpack.unpackb(app_data) try: peer_data = msgpack.unpackb(app_data)
except Exception as e:
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return None
if type(peer_data) == list: if type(peer_data) == list:
if len(peer_data) < 1: return None if len(peer_data) < 1: return None
else: else:
@@ -166,11 +170,15 @@ def display_name_from_app_data(app_data=None):
decoded = dn.decode("utf-8").replace("\x00", "").strip() decoded = dn.decode("utf-8").replace("\x00", "").strip()
return decoded return decoded
except Exception as e: except Exception as e:
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME) RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return None return None
# Original announce format # Legacy announce format
else: return app_data.decode("utf-8") else:
try: return app_data.decode("utf-8")
except Exception as e:
RNS.log(f"Could not decode display name in legacy announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return None
def stamp_cost_from_app_data(app_data=None): def stamp_cost_from_app_data(app_data=None):
if app_data == None or app_data == b"": return None if app_data == None or app_data == b"": return None
@@ -180,7 +188,12 @@ def stamp_cost_from_app_data(app_data=None):
peer_data = msgpack.unpackb(app_data) peer_data = msgpack.unpackb(app_data)
if type(peer_data) == list: if type(peer_data) == list:
if len(peer_data) < 2: return None if len(peer_data) < 2: return None
else: return peer_data[1] else:
if len(peer_data) > 3:
cost_type = type(peer_data[3])
if cost_type == float or cost_type == int: return peer_data[3]
else: return peer_data[1]
else: return peer_data[1]
# Original announce format # Original announce format
else: return None else: return None
@@ -218,7 +231,8 @@ def pn_stamp_cost_from_app_data(app_data=None):
else: else:
if pn_announce_data_is_valid(app_data): if pn_announce_data_is_valid(app_data):
data = msgpack.unpackb(app_data) data = msgpack.unpackb(app_data)
return data[5][0] if len(data) > 7: return data[7][0]
else: return data[5][0]
else: return None else: return None
@@ -236,13 +250,23 @@ def pn_announce_data_is_valid(data):
try: int(data[4]) try: int(data[4])
except: raise ValueError("Invalid announce data: Could not decode propagation sync limit") except: raise ValueError("Invalid announce data: Could not decode propagation sync limit")
if type(data[5]) != list: raise ValueError("Invalid announce data: Could not decode stamp costs") if type(data[5]) != list: raise ValueError("Invalid announce data: Could not decode stamp costs")
try: int(data[5][0]) try: float(data[5][0])
except: raise ValueError("Invalid announce data: Could not decode target stamp cost") except: raise ValueError("Invalid announce data: Could not decode target stamp cost")
try: int(data[5][1]) try: float(data[5][1])
except: raise ValueError("Invalid announce data: Could not decode stamp cost flexibility") except: raise ValueError("Invalid announce data: Could not decode stamp cost flexibility")
try: int(data[5][2]) try: float(data[5][2])
except: raise ValueError("Invalid announce data: Could not decode peering cost") except: raise ValueError("Invalid announce data: Could not decode peering cost")
if type(data[6]) != dict: raise ValueError("Invalid announce data: Could not decode metadata") if type(data[6]) != dict: raise ValueError("Invalid announce data: Could not decode metadata")
# TODO: Transitional mechanism, remove after 1.6.2
if len(data) > 7:
if type(data[7]) != list: raise ValueError("Invalid announce data: Could not decode fractional stamp costs")
try: float(data[7][0])
except: raise ValueError("Invalid announce data: Could not decode target stamp cost")
try: float(data[7][1])
except: raise ValueError("Invalid announce data: Could not decode stamp cost flexibility")
try: float(data[7][2])
except: raise ValueError("Invalid announce data: Could not decode peering cost")
except Exception as e: except Exception as e:
RNS.log(f"Could not validate propagation node announce data: {e}", RNS.LOG_DEBUG) RNS.log(f"Could not validate propagation node announce data: {e}", RNS.LOG_DEBUG)
+11 -9
View File
@@ -79,17 +79,17 @@ class LXMPeer:
else: peer.propagation_sync_limit = peer.propagation_transfer_limit else: peer.propagation_sync_limit = peer.propagation_transfer_limit
if "propagation_stamp_cost" in dictionary: if "propagation_stamp_cost" in dictionary:
try: peer.propagation_stamp_cost = int(dictionary["propagation_stamp_cost"]) try: peer.propagation_stamp_cost = float(dictionary["propagation_stamp_cost"])
except: peer.propagation_stamp_cost = None except: peer.propagation_stamp_cost = None
else: peer.propagation_stamp_cost = None else: peer.propagation_stamp_cost = None
if "propagation_stamp_cost_flexibility" in dictionary: if "propagation_stamp_cost_flexibility" in dictionary:
try: peer.propagation_stamp_cost_flexibility = int(dictionary["propagation_stamp_cost_flexibility"]) try: peer.propagation_stamp_cost_flexibility = float(dictionary["propagation_stamp_cost_flexibility"])
except: peer.propagation_stamp_cost_flexibility = None except: peer.propagation_stamp_cost_flexibility = None
else: peer.propagation_stamp_cost_flexibility = None else: peer.propagation_stamp_cost_flexibility = None
if "peering_cost" in dictionary: if "peering_cost" in dictionary:
try: peer.peering_cost = int(dictionary["peering_cost"]) try: peer.peering_cost = float(dictionary["peering_cost"])
except: peer.peering_cost = None except: peer.peering_cost = None
else: peer.peering_cost = None else: peer.peering_cost = None
@@ -217,9 +217,11 @@ class LXMPeer:
self.router = router self.router = router
self.destination_hash = destination_hash self.destination_hash = destination_hash
self.identity = RNS.Identity.recall(destination_hash) self.resolve_identity()
if self.identity != None:
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation") def resolve_identity(self):
self.identity = RNS.Identity.recall(self.destination_hash)
if self.identity != None: self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
else: else:
self.destination = None self.destination = None
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) 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)
@@ -250,7 +252,7 @@ class LXMPeer:
return False return False
if self.identity == None: if self.identity == None:
self.identity = RNS.Identity.recall(destination_hash) self.identity = RNS.Identity.recall(self.destination_hash)
if self.identity == None: if self.identity == None:
RNS.log(f"Could not update peering key for {self} since its identity could not be recalled", RNS.LOG_ERROR) RNS.log(f"Could not update peering key for {self} since its identity could not be recalled", RNS.LOG_ERROR)
return False return False
@@ -305,7 +307,7 @@ class LXMPeer:
else: else:
if self.identity == None: if self.identity == None:
self.identity = RNS.Identity.recall(destination_hash) self.identity = RNS.Identity.recall(self.destination_hash)
if self.identity != None: if self.identity != None:
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation") self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
@@ -510,7 +512,7 @@ class LXMPeer:
rate_str = "" rate_str = ""
if self.current_sync_transfer_started != None: if self.current_sync_transfer_started != None:
self.sync_transfer_rate = (resource.get_transfer_size()*8)/(time.time()-self.current_sync_transfer_started) self.sync_transfer_rate = (resource.get_transfer_size()*8) / max(time.time()-self.current_sync_transfer_started, 1E-6)
rate_str = f" at {RNS.prettyspeed(self.sync_transfer_rate)}" rate_str = f" at {RNS.prettyspeed(self.sync_transfer_rate)}"
RNS.log(f"Syncing {len(self.currently_transferring_messages)} messages to peer {RNS.prettyhexrep(self.destination_hash)} completed{rate_str}", RNS.LOG_VERBOSE) RNS.log(f"Syncing {len(self.currently_transferring_messages)} messages to peer {RNS.prettyhexrep(self.destination_hash)} completed{rate_str}", RNS.LOG_VERBOSE)
+399 -90
View File
@@ -23,11 +23,16 @@ from .LXMF import pn_announce_data_is_valid
from .LXMPeer import LXMPeer from .LXMPeer import LXMPeer
from .LXMessage import LXMessage from .LXMessage import LXMessage
from .Storage import LXMFStore
from .Handlers import LXMFDeliveryAnnounceHandler from .Handlers import LXMFDeliveryAnnounceHandler
from .Handlers import LXMFPropagationAnnounceHandler from .Handlers import LXMFPropagationAnnounceHandler
from RNS.Stamps import quantize_cost
import LXMF.LXStamper as LXStamper import LXMF.LXStamper as LXStamper
from math import ceil # TODO: Transitory import, remove after RNS 1.6.2
class LXMRouter: class LXMRouter:
MAX_DELIVERY_ATTEMPTS = 5 MAX_DELIVERY_ATTEMPTS = 5
PROCESSING_INTERVAL = 4 PROCESSING_INTERVAL = 4
@@ -35,6 +40,7 @@ class LXMRouter:
PATH_REQUEST_WAIT = 7 PATH_REQUEST_WAIT = 7
PATH_REQUEST_DEBOUNCE = 60 PATH_REQUEST_DEBOUNCE = 60
SLOW_INTERFACE_BITRATE = 2000 SLOW_INTERFACE_BITRATE = 2000
AIRTIME_AWARE_MTU_TIME = 0.5
MAX_PATHLESS_TRIES = 1 MAX_PATHLESS_TRIES = 1
LINK_MAX_INACTIVITY = 10*60 LINK_MAX_INACTIVITY = 10*60
P_LINK_MAX_INACTIVITY = 3*60 P_LINK_MAX_INACTIVITY = 3*60
@@ -44,6 +50,9 @@ class LXMRouter:
NODE_ANNOUNCE_DELAY = 20 NODE_ANNOUNCE_DELAY = 20
DELIVERY_LINK_COST = 3.25
PROPAGATION_LINK_COST = 3.25
MAX_PEERS = 20 MAX_PEERS = 20
AUTOPEER = True AUTOPEER = True
AUTOPEER_MAXDEPTH = 4 AUTOPEER_MAXDEPTH = 4
@@ -51,11 +60,11 @@ class LXMRouter:
ROTATION_HEADROOM_PCT = 10 ROTATION_HEADROOM_PCT = 10
ROTATION_AR_MAX = 0.5 ROTATION_AR_MAX = 0.5
PEERING_COST = 18 PEERING_COST = 18.0
MAX_PEERING_COST = 26 MAX_PEERING_COST = 26.0
PROPAGATION_COST_MIN = 13 PROPAGATION_COST_MIN = 13.0
PROPAGATION_COST_FLEX = 3 PROPAGATION_COST_FLEX = 3.0
PROPAGATION_COST = 16 PROPAGATION_COST = 16.0
PROPAGATION_LIMIT = 256 PROPAGATION_LIMIT = 256
SEQUENTIAL_VALIDATION = True SEQUENTIAL_VALIDATION = True
STATIC_SEQUENTIAL = False STATIC_SEQUENTIAL = False
@@ -64,7 +73,7 @@ class LXMRouter:
DELIVERY_LIMIT = 1000 DELIVERY_LIMIT = 1000
PR_PATH_TIMEOUT = 10 PR_PATH_TIMEOUT = 10
PN_STAMP_THROTTLE = 180 PN_STAMP_THROTTLE = 300
PR_IDLE = 0x00 PR_IDLE = 0x00
PR_PATH_REQUESTED = 0x01 PR_PATH_REQUESTED = 0x01
@@ -94,6 +103,7 @@ class LXMRouter:
SYNC_REQUEST_PATH = "/pn/peer/sync" SYNC_REQUEST_PATH = "/pn/peer/sync"
UNPEER_REQUEST_PATH = "/pn/peer/unpeer" UNPEER_REQUEST_PATH = "/pn/peer/unpeer"
REQUIRED_DESTINATION_TYPES = [f"{APP_NAME}.delivery", f"{APP_NAME}.propagation"]
### Developer-facing API ############################## ### Developer-facing API ##############################
####################################################### #######################################################
@@ -104,15 +114,18 @@ class LXMRouter:
from_static_only=False, sync_strategy=LXMPeer.STRATEGY_PERSISTENT, from_static_only=False, sync_strategy=LXMPeer.STRATEGY_PERSISTENT,
propagation_cost=PROPAGATION_COST, propagation_cost_flexibility=PROPAGATION_COST_FLEX, propagation_cost=PROPAGATION_COST, propagation_cost_flexibility=PROPAGATION_COST_FLEX,
peering_cost=PEERING_COST, max_peering_cost=MAX_PEERING_COST, max_inbound_syncs=MAX_INBOUND_SYNCS, peering_cost=PEERING_COST, max_peering_cost=MAX_PEERING_COST, max_inbound_syncs=MAX_INBOUND_SYNCS,
sequential_validation=SEQUENTIAL_VALIDATION, static_sequential=STATIC_SEQUENTIAL): sequential_validation=SEQUENTIAL_VALIDATION, static_sequential=STATIC_SEQUENTIAL,
pn_stamp_throttle=PN_STAMP_THROTTLE):
random.seed(os.urandom(10)) random.seed(os.urandom(10))
self.store = None
self.pending_inbound = [] self.pending_inbound = []
self.pending_outbound = [] self.pending_outbound = []
self.direct_links = {} self.direct_links = {}
self.backchannel_links = {} self.backchannel_links = {}
self.path_request_times = {} self.path_request_times = {}
self.slow_path_cache = {}
self.path_request_lock = threading.Lock() self.path_request_lock = threading.Lock()
self.delivery_destinations = {} self.delivery_destinations = {}
@@ -129,13 +142,22 @@ class LXMRouter:
self.name = name self.name = name
self.propagation_node = False self.propagation_node = False
self.propagation_node_start_time = None self.propagation_node_start_time = None
self.pn_stamp_throttle = pn_stamp_throttle
if storagepath == None: raise ValueError("LXMF cannot be initialised without a storage path") if storagepath == None: raise ValueError("LXMF cannot be initialised without a storage path")
else: else:
self.storagepath = storagepath+"/lxmf" self.storagepath = storagepath+"/lxmf"
self.ratchetpath = self.storagepath+"/ratchets" self.ratchetpath = self.storagepath+"/ratchets"
try:
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
self.store = LXMFStore(self.storagepath+"/state.db")
except Exception as e:
RNS.log("Could not initialise the LXMF store, falling back to legacy file-based caches. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.trace_exception(e)
self.store = None
self.outbound_propagation_node = None self.outbound_propagation_node = None
self.outbound_propagation_link = None self.outbound_propagation_link = None
@@ -156,6 +178,7 @@ class LXMRouter:
self.max_peering_cost = max_peering_cost self.max_peering_cost = max_peering_cost
self.enforce_ratchets = enforce_ratchets self.enforce_ratchets = enforce_ratchets
self._enforce_stamps = enforce_stamps self._enforce_stamps = enforce_stamps
self.__stamp_costs_dirty = False
self.pending_deferred_stamps = {} self.pending_deferred_stamps = {}
self.throttled_peers = {} self.throttled_peers = {}
@@ -190,11 +213,13 @@ class LXMRouter:
self.incoming_delivery_resource_lock = threading.Lock() self.incoming_delivery_resource_lock = threading.Lock()
self.exit_handler_running = False self.exit_handler_running = False
for destination_type in self.REQUIRED_DESTINATION_TYPES:
RNS.Reticulum.get_instance().wants_destination_type(destination_type)
if identity == None: identity = RNS.Identity() if identity == None: identity = RNS.Identity()
self.identity = identity self.identity = identity
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation") self.propagation_destination = None
self.propagation_destination.set_default_app_data(self.get_propagation_node_app_data)
self.control_destination = None self.control_destination = None
self.validating_pn_stamps_from = {} self.validating_pn_stamps_from = {}
self.incoming_delivery_resources = {} self.incoming_delivery_resources = {}
@@ -234,6 +259,44 @@ class LXMRouter:
self.__delivery_callback = None self.__delivery_callback = None
# TODO: Remove legacy import/load after transition window ###
if self.store != None: self.__import_legacy_storage() #
else: self.__load_legacy_storage() #
#############################################################
atexit.register(self.exit_handler)
signal.signal(signal.SIGINT, self.sigint_handler)
signal.signal(signal.SIGTERM, self.sigterm_handler)
job_thread = threading.Thread(target=self.jobloop)
job_thread.setDaemon(True)
job_thread.start()
def __import_legacy_storage(self):
try:
if os.path.isfile(self.storagepath+"/local_deliveries"): self.store.import_legacy_delivered(self.storagepath+"/local_deliveries")
except Exception as e: RNS.log("Could not import legacy local deliveries cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if os.path.isfile(self.storagepath+"/locally_processed"): self.store.import_legacy_processed(self.storagepath+"/locally_processed")
except Exception as e: RNS.log("Could not import legacy locally processed cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if os.path.isfile(self.storagepath+"/outbound_stamp_costs"): self.store.import_legacy_stamp_costs(self.storagepath+"/outbound_stamp_costs")
except Exception as e: RNS.log("Could not import legacy outbound stamp costs cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if os.path.isfile(self.storagepath+"/available_tickets"): self.store.import_legacy_tickets(self.storagepath+"/available_tickets")
except Exception as e: RNS.log("Could not import legacy available tickets cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
self.clean_transient_id_caches()
self.clean_outbound_stamp_costs()
self.clean_available_tickets()
self.store.incremental_vacuum()
except Exception as e: RNS.log("Could not perform initial cleaning of the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
def __load_legacy_storage(self):
try: try:
if os.path.isfile(self.storagepath+"/local_deliveries"): if os.path.isfile(self.storagepath+"/local_deliveries"):
locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb") locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb")
@@ -310,14 +373,6 @@ class LXMRouter:
except Exception as e: except Exception as e:
RNS.log("Could not load outbound stamp costs from storage. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not load outbound stamp costs from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
atexit.register(self.exit_handler)
signal.signal(signal.SIGINT, self.sigint_handler)
signal.signal(signal.SIGTERM, self.sigterm_handler)
job_thread = threading.Thread(target=self.jobloop)
job_thread.setDaemon(True)
job_thread.start()
def announce(self, destination_hash, attached_interface=None): def announce(self, destination_hash, attached_interface=None):
if destination_hash in self.delivery_destinations: if destination_hash in self.delivery_destinations:
self.delivery_destinations[destination_hash].announce(app_data=self.get_announce_app_data(destination_hash), attached_interface=attached_interface) self.delivery_destinations[destination_hash].announce(app_data=self.get_announce_app_data(destination_hash), attached_interface=attached_interface)
@@ -332,14 +387,16 @@ class LXMRouter:
def get_propagation_node_app_data(self): def get_propagation_node_app_data(self):
metadata = self.get_propagation_node_announce_metadata() metadata = self.get_propagation_node_announce_metadata()
node_state = self.propagation_node and not self.from_static_only node_state = self.propagation_node and not self.from_static_only
stamp_cost = [self.propagation_stamp_cost, self.propagation_stamp_cost_flexibility, self.peering_cost] stamp_costs = [self.propagation_stamp_cost, self.propagation_stamp_cost_flexibility, self.peering_cost]
ceil_costs = [ceil(self.propagation_stamp_cost), ceil(self.propagation_stamp_cost_flexibility), ceil(self.peering_cost)]
announce_data = [ False, # 0: Legacy LXMF PN support announce_data = [ False, # 0: Legacy LXMF PN support
int(time.time()), # 1: Current node timebase int(time.time()), # 1: Current node timebase
node_state, # 2: Boolean flag signalling propagation node state node_state, # 2: Boolean flag signalling propagation node state
self.propagation_per_transfer_limit, # 3: Per-transfer limit for message propagation in kilobytes self.propagation_per_transfer_limit, # 3: Per-transfer limit for message propagation in kilobytes
self.propagation_per_sync_limit, # 4: Limit for incoming propagation node syncs self.propagation_per_sync_limit, # 4: Limit for incoming propagation node syncs
stamp_cost, # 5: Propagation stamp cost for this node ceil_costs, # 5: Propagation stamp cost for this node
metadata ] # 6: Node metadata metadata, # 6: Node metadata
stamp_costs ] # 7: Transitional fractional-value stamp cost, will disappear after 1.6.2, where they will be in 5 directly
return msgpack.packb(announce_data) return msgpack.packb(announce_data)
@@ -353,7 +410,7 @@ class LXMRouter:
da_thread.setDaemon(True) da_thread.setDaemon(True)
da_thread.start() da_thread.start()
def register_delivery_identity(self, identity, display_name = None, stamp_cost = None): def register_delivery_identity(self, identity, display_name=None, stamp_cost=None, stamp_value=None):
if len(self.delivery_destinations) != 0: if len(self.delivery_destinations) != 0:
RNS.log("Currently only one delivery identity is supported per LXMF router instance", RNS.LOG_ERROR) RNS.log("Currently only one delivery identity is supported per LXMF router instance", RNS.LOG_ERROR)
return None return None
@@ -362,6 +419,8 @@ class LXMRouter:
os.makedirs(self.ratchetpath) os.makedirs(self.ratchetpath)
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "delivery") delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "delivery")
if stamp_value: delivery_destination.set_value(stamp_value)
delivery_destination.set_link_cost(self.DELIVERY_LINK_COST)
delivery_destination.enable_ratchets(f"{self.ratchetpath}/{RNS.hexrep(delivery_destination.hash, delimit=False)}.ratchets") 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_packet_callback(self.delivery_packet)
delivery_destination.set_link_established_callback(self.delivery_link_established) delivery_destination.set_link_established_callback(self.delivery_link_established)
@@ -386,22 +445,29 @@ class LXMRouter:
def set_inbound_stamp_cost(self, destination_hash, stamp_cost): def set_inbound_stamp_cost(self, destination_hash, stamp_cost):
if destination_hash in self.delivery_destinations: if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash] delivery_destination = self.delivery_destinations[destination_hash]
cap = RNS.Transport.STAMP_COST_CAP
if stamp_cost == None: if stamp_cost == None:
delivery_destination.stamp_cost = None delivery_destination.stamp_cost = None
return True return True
elif type(stamp_cost) == int: elif type(stamp_cost) == int:
if stamp_cost < 1: if stamp_cost < 1: delivery_destination.stamp_cost = None
delivery_destination.stamp_cost = None elif stamp_cost < cap: delivery_destination.stamp_cost = stamp_cost
elif stamp_cost < 255: else: return False
delivery_destination.stamp_cost = stamp_cost return True
else: elif type(stamp_cost) == float:
return False if stamp_cost < 1: delivery_destination.stamp_cost = None
elif stamp_cost < cap: delivery_destination.stamp_cost = stamp_cost
else: return False
return True return True
return False return False
def get_outbound_stamp_cost(self, destination_hash): def get_outbound_stamp_cost(self, destination_hash):
if self.store != None: return self.store.get_outbound_stamp_cost(destination_hash)
else: return self.get_outbound_stamp_cost_legacy(destination_hash)
# TODO: Remove legacy handling after transition
def get_outbound_stamp_cost_legacy(self, destination_hash):
if destination_hash in self.outbound_stamp_costs: if destination_hash in self.outbound_stamp_costs:
stamp_cost = self.outbound_stamp_costs[destination_hash][1] stamp_cost = self.outbound_stamp_costs[destination_hash][1]
return stamp_cost return stamp_cost
@@ -432,7 +498,9 @@ class LXMRouter:
pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash) pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash)
if pn_announce_data_is_valid(pn_app_data): if pn_announce_data_is_valid(pn_app_data):
pn_config = msgpack.unpackb(pn_app_data) pn_config = msgpack.unpackb(pn_app_data)
target_propagation_cost = pn_config[5][0] # TODO: Transitional mechanism, remove after 1.6.2
if len(pn_config) > 7: target_propagation_cost = pn_config[7][0]
else: target_propagation_cost = pn_config[5][0]
if not target_propagation_cost: if not target_propagation_cost:
RNS.log(f"Could not retrieve cached propagation node config. Requesting path to propagation node to get target propagation cost...", RNS.LOG_DEBUG) RNS.log(f"Could not retrieve cached propagation node config. Requesting path to propagation node to get target propagation cost...", RNS.LOG_DEBUG)
@@ -444,9 +512,12 @@ class LXMRouter:
pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash) pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash)
if pn_announce_data_is_valid(pn_app_data): if pn_announce_data_is_valid(pn_app_data):
pn_config = msgpack.unpackb(pn_app_data) pn_config = msgpack.unpackb(pn_app_data)
target_propagation_cost = pn_config[5][0] if len(pn_config) > 7: target_propagation_cost = pn_config[7][0]
else: target_propagation_cost = pn_config[5][0]
if type(target_propagation_cost) not in (float, int) and target_propagation_cost != None: return None
if not target_propagation_cost: RNS.log("Propagation node stamp cost still unavailable after path request", RNS.LOG_ERROR) if not target_propagation_cost: RNS.log("Propagation node stamp cost still unavailable after path request", RNS.LOG_ERROR)
if target_propagation_cost != None: target_propagation_cost = max(0, min(target_propagation_cost, RNS.Transport.STAMP_COST_CAP))
return target_propagation_cost return target_propagation_cost
def set_inbound_propagation_node(self, destination_hash): def set_inbound_propagation_node(self, destination_hash):
@@ -560,6 +631,11 @@ class LXMRouter:
def enable_propagation(self): def enable_propagation(self):
try: try:
if not self.propagation_destination:
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
self.propagation_destination.set_link_cost(self.PROPAGATION_LINK_COST)
self.propagation_destination.set_default_app_data(self.get_propagation_node_app_data)
self.messagepath = self.storagepath+"/messagestore" self.messagepath = self.storagepath+"/messagestore"
if not os.path.isdir(self.storagepath): if not os.path.isdir(self.storagepath):
@@ -579,7 +655,7 @@ class LXMRouter:
try: try:
transient_id = bytes.fromhex(components[0]) transient_id = bytes.fromhex(components[0])
received = float(components[1]) received = float(components[1])
stamp_value = int(components[2]) stamp_value = quantize_cost(components[2])
filepath = self.messagepath+"/"+filename filepath = self.messagepath+"/"+filename
msg_size = os.path.getsize(filepath) msg_size = os.path.getsize(filepath)
file = open(filepath, "rb") file = open(filepath, "rb")
@@ -624,13 +700,26 @@ class LXMRouter:
serialised_peer = serialised_peers.pop() serialised_peer = serialised_peers.pop()
peer = LXMPeer.from_bytes(serialised_peer, self) peer = LXMPeer.from_bytes(serialised_peer, self)
del serialised_peer del serialised_peer
if peer.destination_hash in self.static_peers and peer.last_heard == 0: if peer.destination_hash in self.static_peers and peer.last_heard == 0:
self.request_path(peer.destination_hash) RNS.log(f"Attempting to resolve initial peering data for static peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
RNS.Transport.await_path(peer.destination_hash, timeout=5.0)
peer.resolve_identity()
if peer.identity == None:
if peer in self.static_peers:
RNS.log(f"Attempting to resolve unknown identity for static peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
RNS.Transport.await_path(peer.destination_hash, timeout=7.5)
peer.resolve_identity()
else:
RNS.log(f"Attempting to resolve unknown identity for peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
RNS.Transport.await_path(peer.destination_hash, timeout=2.5)
peer.resolve_identity()
if peer.identity != None: if peer.identity != None:
self.peers[peer.destination_hash] = peer self.peers[peer.destination_hash] = peer
lim_str = ", no transfer limit" lim_str = ", no transfer limit"
if peer.propagation_transfer_limit != None: if peer.propagation_transfer_limit != None: lim_str = ", "+RNS.prettysize(peer.propagation_transfer_limit*1000)+" transfer limit"
lim_str = ", "+RNS.prettysize(peer.propagation_transfer_limit*1000)+" transfer limit"
RNS.log("Rebuilt peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(peer.unhandled_message_count)+" unhandled messages"+lim_str, RNS.LOG_DEBUG) RNS.log("Rebuilt peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(peer.unhandled_message_count)+" unhandled messages"+lim_str, RNS.LOG_DEBUG)
else: else:
RNS.log("Peer "+RNS.prettyhexrep(peer.destination_hash)+" could not be loaded, because its identity could not be recalled. Dropping peer.", RNS.LOG_DEBUG) RNS.log("Peer "+RNS.prettyhexrep(peer.destination_hash)+" could not be loaded, because its identity could not be recalled. Dropping peer.", RNS.LOG_DEBUG)
@@ -882,9 +971,12 @@ class LXMRouter:
JOB_RESOURCE_INTERVAL = 2 JOB_RESOURCE_INTERVAL = 2
JOB_TRANSIENT_INTERVAL = 60 JOB_TRANSIENT_INTERVAL = 60
JOB_STORE_INTERVAL = 120 JOB_STORE_INTERVAL = 120
JOB_STAMPCOST_INTERVAL = 120
JOB_PEERSYNC_INTERVAL = 6 JOB_PEERSYNC_INTERVAL = 6
JOB_PEERINGEST_INTERVAL= JOB_PEERSYNC_INTERVAL JOB_PEERINGEST_INTERVAL= JOB_PEERSYNC_INTERVAL
JOB_ROTATE_INTERVAL = 56*JOB_PEERINGEST_INTERVAL JOB_ROTATE_INTERVAL = 56*JOB_PEERINGEST_INTERVAL
STORE_CULL_CHUNKS = 16
def jobs(self): def jobs(self):
if not self.exit_handler_running: if not self.exit_handler_running:
self.processing_count += 1 self.processing_count += 1
@@ -917,6 +1009,13 @@ class LXMRouter:
if self.propagation_node == True: self.sync_peers() if self.propagation_node == True: self.sync_peers()
self.clean_throttled_peers() self.clean_throttled_peers()
if self.processing_count % LXMRouter.JOB_STAMPCOST_INTERVAL == 0:
if self.store != None:
self.clean_outbound_stamp_costs()
self.clean_available_tickets()
self.store.incremental_vacuum()
elif self.__stamp_costs_dirty: self.save_outbound_stamp_costs()
def jobloop(self): def jobloop(self):
while (True): while (True):
# TODO: Improve this to scheduling, so manual # TODO: Improve this to scheduling, so manual
@@ -1010,7 +1109,29 @@ class LXMRouter:
RNS.log("Cleaned outbound propagation link", RNS.LOG_DEBUG) RNS.log("Cleaned outbound propagation link", RNS.LOG_DEBUG)
def __cull_store(self, cull_method, cutoff):
# Bounded drain of an expired-entry cull method on the LXMF
# store. Capped per call, so maintenance stays short; any
# remainder is culled on subsequent ticks.
removed = 0
for i in range(LXMRouter.STORE_CULL_CHUNKS):
batch = cull_method(cutoff)
if batch == 0: break
removed += batch
return removed
def clean_transient_id_caches(self): def clean_transient_id_caches(self):
# TODO: Remove legacy handling after transition
if self.store == None: self.clean_transient_id_caches_legacy()
else:
now = time.time()
cutoff = now-LXMRouter.MESSAGE_EXPIRY*6.0
removed_delivered = self.__cull_store(self.store.cull_delivered, cutoff)
removed_processed = self.__cull_store(self.store.cull_processed, cutoff)
if removed_delivered+removed_processed > 0: RNS.log(f"Cleaned {removed_delivered} delivered and {removed_processed} processed transient IDs from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def clean_transient_id_caches_legacy(self):
now = time.time() now = time.time()
removed_entries = [] removed_entries = []
for transient_id in self.locally_delivered_transient_ids.copy(): for transient_id in self.locally_delivered_transient_ids.copy():
@@ -1034,10 +1155,12 @@ class LXMRouter:
def update_stamp_cost(self, destination_hash, stamp_cost): 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_PATHING) if RNS.sl(RNS.LOG_PATHING) else None RNS.log(f"Updating outbound stamp cost for {RNS.prettyhexrep(destination_hash)} to {stamp_cost}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
if self.store == None: self.update_stamp_cost_legacy(destination_hash, stamp_cost)
else: self.store.update_stamp_cost(destination_hash, stamp_cost)
def update_stamp_cost_legacy(self, destination_hash, stamp_cost):
self.outbound_stamp_costs[destination_hash] = [time.time(), stamp_cost] self.outbound_stamp_costs[destination_hash] = [time.time(), stamp_cost]
self.__stamp_costs_dirty = True
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): def get_announce_app_data(self, destination_hash):
if destination_hash in self.delivery_destinations: if destination_hash in self.delivery_destinations:
@@ -1048,12 +1171,15 @@ class LXMRouter:
display_name = delivery_destination.display_name.encode("utf-8") display_name = delivery_destination.display_name.encode("utf-8")
stamp_cost = None stamp_cost = None
if delivery_destination.stamp_cost != None and type(delivery_destination.stamp_cost) == int: if delivery_destination.stamp_cost != None and (type(delivery_destination.stamp_cost) == int or type(delivery_destination.stamp_cost) == float):
if delivery_destination.stamp_cost > 0 and delivery_destination.stamp_cost < 255: if delivery_destination.stamp_cost > 0 and delivery_destination.stamp_cost < RNS.Transport.STAMP_COST_CAP:
stamp_cost = delivery_destination.stamp_cost stamp_cost = quantize_cost(delivery_destination.stamp_cost)
supported_functionality = [SF_COMPRESSION] supported_functionality = [SF_COMPRESSION]
peer_data = [display_name, stamp_cost, supported_functionality]
# TODO: Transitional mechanism, remove after 1.6.2
peer_data = [display_name, ceil(stamp_cost) if stamp_cost else None, supported_functionality, stamp_cost]
# peer_data = [display_name, stamp_cost, supported_functionality]
return msgpack.packb(peer_data) return msgpack.packb(peer_data)
@@ -1079,6 +1205,31 @@ class LXMRouter:
else: return self.propagation_entries[transient_id][6] else: return self.propagation_entries[transient_id][6]
def generate_ticket(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY): def generate_ticket(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY):
# TODO: Remove legacy handling after transition
if self.store == None: return self.generate_ticket_legacy(destination_hash, expiry=expiry)
else:
now = time.time()
last_delivery = self.store.get_last_ticket_delivery(destination_hash)
if last_delivery != None:
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
reusable = self.store.get_reusable_inbound_ticket(destination_hash, LXMessage.TICKET_RENEW)
if reusable != None:
RNS.log(f"Found generated ticket for {RNS.prettyhexrep(destination_hash)} with {RNS.prettytime(reusable[0]-now)} of validity left, re-using this one", RNS.LOG_DEBUG)
return reusable
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.store.store_inbound_ticket(destination_hash, ticket, expires)
return [expires, ticket]
def generate_ticket_legacy(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY):
now = time.time() now = time.time()
ticket = None ticket = None
if destination_hash in self.available_tickets["last_deliveries"]: if destination_hash in self.available_tickets["last_deliveries"]:
@@ -1110,9 +1261,19 @@ class LXMRouter:
def remember_ticket(self, destination_hash, ticket_entry): def remember_ticket(self, destination_hash, ticket_entry):
expires = ticket_entry[0]-time.time() expires = ticket_entry[0]-time.time()
RNS.log(f"Remembering ticket for {RNS.prettyhexrep(destination_hash)}, expires in {RNS.prettytime(expires)}", RNS.LOG_DEBUG) RNS.log(f"Remembering ticket for {RNS.prettyhexrep(destination_hash)}, expires in {RNS.prettytime(expires)}", RNS.LOG_DEBUG)
# TODO: Remove legacy handling after transition
if self.store == None: self.remember_ticket_legacy(destination_hash, ticket_entry)
else: self.store.remember_ticket(destination_hash, ticket_entry)
def remember_ticket_legacy(self, destination_hash, ticket_entry):
self.available_tickets["outbound"][destination_hash] = [ticket_entry[0], ticket_entry[1]] self.available_tickets["outbound"][destination_hash] = [ticket_entry[0], ticket_entry[1]]
def get_outbound_ticket(self, destination_hash): def get_outbound_ticket(self, destination_hash):
# TODO: Remove legacy handling after transition
if self.store == None: return self.get_outbound_ticket_legacy(destination_hash)
else: return self.store.get_outbound_ticket(destination_hash)
def get_outbound_ticket_legacy(self, destination_hash):
if destination_hash in self.available_tickets["outbound"]: if destination_hash in self.available_tickets["outbound"]:
entry = self.available_tickets["outbound"][destination_hash] entry = self.available_tickets["outbound"][destination_hash]
if entry[0] > time.time(): if entry[0] > time.time():
@@ -1121,6 +1282,11 @@ class LXMRouter:
return None return None
def get_outbound_ticket_expiry(self, destination_hash): def get_outbound_ticket_expiry(self, destination_hash):
# TODO: Remove legacy handling after transition
if self.store == None: return self.get_outbound_ticket_expiry_legacy(destination_hash)
else: return self.store.get_outbound_ticket_expiry(destination_hash)
def get_outbound_ticket_expiry_legacy(self, destination_hash):
if destination_hash in self.available_tickets["outbound"]: if destination_hash in self.available_tickets["outbound"]:
entry = self.available_tickets["outbound"][destination_hash] entry = self.available_tickets["outbound"][destination_hash]
if entry[0] > time.time(): if entry[0] > time.time():
@@ -1129,6 +1295,11 @@ class LXMRouter:
return None return None
def get_inbound_tickets(self, destination_hash): def get_inbound_tickets(self, destination_hash):
# TODO: Remove legacy handling after transition
if self.store == None: return self.get_inbound_tickets_legacy(destination_hash)
else: return self.store.get_inbound_tickets(destination_hash)
def get_inbound_tickets_legacy(self, destination_hash):
now = time.time() now = time.time()
available_tickets = [] available_tickets = []
if destination_hash in self.available_tickets["inbound"]: if destination_hash in self.available_tickets["inbound"]:
@@ -1161,7 +1332,7 @@ class LXMRouter:
filename = os.path.split(filepath)[-1] filename = os.path.split(filepath)[-1]
components = filename.split("_") components = filename.split("_")
if len(components) == 3 and float(components[1]) > 0 and len(os.path.split(components[0])[1]) == (RNS.Identity.HASHLENGTH//8)*2 and int(components[2]) == stamp_value: if len(components) == 3 and float(components[1]) > 0 and len(os.path.split(components[0])[1]) == (RNS.Identity.HASHLENGTH//8)*2 and quantize_cost(components[2]) == quantize_cost(stamp_value):
timestamp = float(components[1]) timestamp = float(components[1])
if now > timestamp+LXMRouter.MESSAGE_EXPIRY: if now > timestamp+LXMRouter.MESSAGE_EXPIRY:
RNS.log("Purging message "+RNS.prettyhexrep(transient_id)+" due to expiry", RNS.LOG_EXTREME) RNS.log("Purging message "+RNS.prettyhexrep(transient_id)+" due to expiry", RNS.LOG_EXTREME)
@@ -1232,6 +1403,8 @@ class LXMRouter:
RNS.log("Could not clean the LXMF message store. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not clean the LXMF message store. The contained exception was: "+str(e), RNS.LOG_ERROR)
def save_locally_delivered_transient_ids(self): def save_locally_delivered_transient_ids(self):
if self.store != None: return
# TODO: Remove legacy handling after transition
try: try:
if len(self.locally_delivered_transient_ids) > 0: if len(self.locally_delivered_transient_ids) > 0:
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath) if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
@@ -1245,6 +1418,8 @@ class LXMRouter:
RNS.log("Could not save locally delivered message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not save locally delivered message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def save_locally_processed_transient_ids(self): def save_locally_processed_transient_ids(self):
if self.store != None: return
# TODO: Remove legacy handling after transition
try: try:
if len(self.locally_processed_transient_ids) > 0: if len(self.locally_processed_transient_ids) > 0:
if not os.path.isdir(self.storagepath): if not os.path.isdir(self.storagepath):
@@ -1278,6 +1453,20 @@ class LXMRouter:
RNS.log("Could not save local node stats to storage. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not save local node stats to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def clean_outbound_stamp_costs(self): def clean_outbound_stamp_costs(self):
# TODO: Remove legacy handling after transition
if self.store == None: self.clean_outbound_stamp_costs_legacy()
else:
try:
removed = self.__cull_store(self.store.cull_stamp_costs, time.time()-LXMRouter.STAMP_COST_EXPIRY)
if removed > 0:
RNS.log(f"Cleaned {removed} outbound stamp cost entries from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
except Exception as e:
RNS.log(f"Error while cleaning outbound stamp costs in the LXMF store. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
def clean_outbound_stamp_costs_legacy(self):
try: try:
expired = [] expired = []
for destination_hash in self.outbound_stamp_costs: for destination_hash in self.outbound_stamp_costs:
@@ -1293,6 +1482,8 @@ class LXMRouter:
RNS.trace_exception(e) RNS.trace_exception(e)
def save_outbound_stamp_costs(self): def save_outbound_stamp_costs(self):
# TODO: Remove legacy handling after transition
if self.store != None: return
with self.cost_file_lock: with self.cost_file_lock:
try: try:
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath) if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
@@ -1303,10 +1494,26 @@ class LXMRouter:
outbound_stamp_costs_file.write(msgpack.packb(self.outbound_stamp_costs.copy())) outbound_stamp_costs_file.write(msgpack.packb(self.outbound_stamp_costs.copy()))
os.replace(temp_path, write_path) os.replace(temp_path, write_path)
except Exception as e: except Exception as e: RNS.log(f"Could not save outbound stamp costs to storage. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.log("Could not save outbound stamp costs to storage. The contained exception was: "+str(e), RNS.LOG_ERROR) self.__stamp_costs_dirty = False
def clean_available_tickets(self): def clean_available_tickets(self):
# TODO: Remove legacy handling after transition
if self.store == None: self.clean_available_tickets_legacy()
else:
try:
now = time.time()
removed_outbound = self.__cull_store(self.store.cull_tickets_outbound, now)
removed_inbound = self.__cull_store(self.store.cull_tickets_inbound, now-LXMessage.TICKET_GRACE)
if removed_outbound+removed_inbound > 0:
RNS.log(f"Cleaned {removed_outbound} outbound and {removed_inbound} inbound tickets from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
except Exception as e:
RNS.log(f"Error while cleaning available tickets in the LXMF store. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
def clean_available_tickets_legacy(self):
try: try:
# Clean outbound tickets # Clean outbound tickets
expired_outbound = [] expired_outbound = []
@@ -1335,6 +1542,8 @@ class LXMRouter:
RNS.trace_exception(e) RNS.trace_exception(e)
def save_available_tickets(self): def save_available_tickets(self):
if self.store != None: return
# TODO: Remove legacy handling after transition
with self.ticket_file_lock: with self.ticket_file_lock:
try: try:
if not os.path.isdir(self.storagepath): if not os.path.isdir(self.storagepath):
@@ -1350,6 +1559,8 @@ class LXMRouter:
RNS.log("Could not save available tickets to storage. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not save available tickets to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def reload_available_tickets(self): def reload_available_tickets(self):
if self.store != None: return
# TODO: Remove legacy handling after transition
RNS.log("Reloading available tickets from storage", RNS.LOG_DEBUG) RNS.log("Reloading available tickets from storage", RNS.LOG_DEBUG)
try: try:
with self.ticket_file_lock: with self.ticket_file_lock:
@@ -1428,8 +1639,13 @@ class LXMRouter:
self.save_locally_delivered_transient_ids() self.save_locally_delivered_transient_ids()
self.save_locally_processed_transient_ids() self.save_locally_processed_transient_ids()
self.save_outbound_stamp_costs()
self.save_node_stats() self.save_node_stats()
if self.store != None:
RNS.log("Closing store...", RNS.LOG_DEBUG)
self.store.close()
def sigint_handler(self, signal, frame): def sigint_handler(self, signal, frame):
if threading.current_thread() != threading.main_thread(): if threading.current_thread() != threading.main_thread():
RNS.log(f"SIGINT on non-main thread {threading.current_thread()}, exiting immediately", RNS.LOG_WARNING) RNS.log(f"SIGINT on non-main thread {threading.current_thread()}, exiting immediately", RNS.LOG_WARNING)
@@ -1479,13 +1695,9 @@ class LXMRouter:
def identity_allowed(self, identity): def identity_allowed(self, identity):
if self.auth_required: if self.auth_required:
if identity.hash in self.allowed_list: if identity.hash in self.allowed_list: return True
return True else: return False
else: else: return True
return False
else:
return True
def message_get_request(self, path, data, request_id, remote_identity, requested_at): def message_get_request(self, path, data, request_id, remote_identity, requested_at):
if remote_identity == None: return LXMPeer.ERROR_NO_IDENTITY if remote_identity == None: return LXMPeer.ERROR_NO_IDENTITY
@@ -1673,8 +1885,10 @@ class LXMRouter:
self.wants_download_on_path_available_to = None self.wants_download_on_path_available_to = None
def has_message(self, transient_id): def has_message(self, transient_id):
if transient_id in self.locally_delivered_transient_ids: return True if self.store != None: return self.store.has_delivered(transient_id)
else: return False else:
if transient_id in self.locally_delivered_transient_ids: return True
else: return False
def inbound_count(self): def inbound_count(self):
try: try:
@@ -1731,6 +1945,7 @@ class LXMRouter:
RNS.log(f"Cancelling deferred stamp generation for {lxm}", RNS.LOG_DEBUG) RNS.log(f"Cancelling deferred stamp generation for {lxm}", RNS.LOG_DEBUG)
lxm.state = cancel_state lxm.state = cancel_state
LXStamper.cancel_work(message_id) LXStamper.cancel_work(message_id)
if lxm.transient_id: LXStamper.cancel_work(lxm.transient_id)
lxmessage = None lxmessage = None
for lxm in self.pending_outbound: for lxm in self.pending_outbound:
@@ -1812,6 +2027,51 @@ class LXMRouter:
if round_trip > LXMRouter.DELIVERY_RETRY_WAIT: lxmessage.max_delivery_attempts = max(3, round(LXMRouter.MAX_DELIVERY_ATTEMPTS * LXMRouter.DELIVERY_RETRY_WAIT / round_trip)) if round_trip > LXMRouter.DELIVERY_RETRY_WAIT: lxmessage.max_delivery_attempts = max(3, round(LXMRouter.MAX_DELIVERY_ATTEMPTS * LXMRouter.DELIVERY_RETRY_WAIT / round_trip))
else: lxmessage.max_delivery_attempts = LXMRouter.MAX_DELIVERY_ATTEMPTS else: lxmessage.max_delivery_attempts = LXMRouter.MAX_DELIVERY_ATTEMPTS
mtu_time = max(round_trip - RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT, 0) / 2
if mtu_time > LXMRouter.AIRTIME_AWARE_MTU_TIME:
lxmessage.next_delivery_attempt += random.uniform(0, mtu_time)
retry_wait = max(LXMRouter.DELIVERY_RETRY_WAIT, round_trip) + mtu_time
remaining_attempts = max(1, lxmessage.max_delivery_attempts - lxmessage.delivery_attempts + 1)
lxmessage.receipt_timeout = retry_wait * remaining_attempts + LXMRouter.PROCESSING_INTERVAL
else: lxmessage.receipt_timeout = None
def slow_path(self, destination_hash):
now = time.time()
cached = self.slow_path_cache.get(destination_hash)
if cached and now - cached[1] < LXMRouter.PROCESSING_INTERVAL: return cached[0]
if len(self.slow_path_cache) > 256: self.slow_path_cache = {}
slow = self.destination_round_trip(destination_hash) > LXMRouter.DELIVERY_RETRY_WAIT
self.slow_path_cache[destination_hash] = (slow, now)
return slow
def outbound_target(self, lxmessage):
if lxmessage.method == LXMessage.PROPAGATED: return self.outbound_propagation_node
else: return lxmessage.destination_hash
def slow_path_in_flight(self, lxmessage):
if not getattr(lxmessage, "sent_on_slow_path", False): return False
if lxmessage.method == LXMessage.OPPORTUNISTIC: return lxmessage.state == LXMessage.SENT
else: return lxmessage.state == LXMessage.SENDING
def slow_path_held(self, lxmessage, target_hash):
if lxmessage.state != LXMessage.OUTBOUND: return False
if not self.slow_path(target_hash): return False
ahead = True
for other in self.pending_outbound:
if other == lxmessage: ahead = False
elif other.state in [LXMessage.DELIVERED, LXMessage.FAILED, LXMessage.CANCELLED, LXMessage.REJECTED]: continue
elif other.method == LXMessage.PROPAGATED and other.state == LXMessage.SENT: continue
elif ahead and self.outbound_target(other) == target_hash: return True
elif self.slow_path_in_flight(other): return True
return False
def outbound_concluded(self, lxmessage):
if not getattr(lxmessage, "sent_on_slow_path", False): return
def job():
while self.outbound_processing_lock.locked(): time.sleep(0.1)
self.process_outbound()
threading.Thread(target=job, daemon=True).start()
def handle_outbound(self, lxmessage): def handle_outbound(self, lxmessage):
destination_hash = lxmessage.get_destination().hash destination_hash = lxmessage.get_destination().hash
@@ -1820,12 +2080,13 @@ class LXMRouter:
raise IOError("Attempt to send propagated message with no outbound propagation node configured") raise IOError("Attempt to send propagated message with no outbound propagation node configured")
if lxmessage.stamp_cost == None: if lxmessage.stamp_cost == None:
if destination_hash in self.outbound_stamp_costs: stamp_cost = self.get_outbound_stamp_cost(destination_hash)
stamp_cost = self.outbound_stamp_costs[destination_hash][1] if stamp_cost != None:
lxmessage.stamp_cost = stamp_cost 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) 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 lxmessage.state = LXMessage.OUTBOUND
lxmessage.concluded_callback = self.outbound_concluded
# If an outbound ticket is available for this # If an outbound ticket is available for this
# destination, attach it to the message. # destination, attach it to the message.
@@ -1923,9 +2184,10 @@ class LXMRouter:
if time.time() < expires: if time.time() < expires:
if type(ticket) == bytes and len(ticket) == LXMessage.TICKET_LENGTH: if type(ticket) == bytes and len(ticket) == LXMessage.TICKET_LENGTH:
self.remember_ticket(message.source_hash, ticket_entry) self.remember_ticket(message.source_hash, ticket_entry)
def save_job(): # TODO: Remove legacy handling after transition
self.save_available_tickets() if self.store == None:
threading.Thread(target=save_job, daemon=True).start() 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 required_stamp_cost = self.delivery_destinations[message.destination_hash].stamp_cost
if required_stamp_cost != None: if required_stamp_cost != None:
@@ -1972,12 +2234,19 @@ class LXMRouter:
RNS.log(str(self)+" ignored message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG) RNS.log(str(self)+" ignored message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
return False return False
if not allow_duplicate and self.has_message(message.hash): if self.store != None:
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG) if allow_duplicate: self.store.mark_locally_delivered(message.hash, time.time())
return False elif not self.store.conditionally_claim_delivered(message.hash, time.time()):
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
return False
else: else:
with self.delivered_transient_ids_lock: # TODO: Remove legacy handling after transition
self.locally_delivered_transient_ids[message.hash] = time.time() if not allow_duplicate and self.has_message(message.hash):
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
return False
else:
with self.delivered_transient_ids_lock:
self.locally_delivered_transient_ids[message.hash] = time.time()
if self.__delivery_callback != None and callable(self.__delivery_callback): if self.__delivery_callback != None and callable(self.__delivery_callback):
try: self.__delivery_callback(message) try: self.__delivery_callback(message)
@@ -2124,7 +2393,7 @@ class LXMRouter:
if timestamp >= peer.peering_timebase: if timestamp >= peer.peering_timebase:
self.peers.pop(destination_hash) self.peers.pop(destination_hash)
RNS.log("Broke peering with "+str(peer.destination)) RNS.log(f"Broke peering with {RNS.prettyhexrep(destination_hash)}")
def rotate_peers(self): def rotate_peers(self):
try: try:
@@ -2243,16 +2512,15 @@ class LXMRouter:
if len(peer_pool) > 0: if len(peer_pool) > 0:
selected_index = random.randint(0,len(peer_pool)-1) selected_index = random.randint(0,len(peer_pool)-1)
selected_peer = peer_pool[selected_index] selected_peer = peer_pool[selected_index]
RNS.log("Selected waiting peer "+str(selected_index)+": "+RNS.prettyhexrep(selected_peer.destination.hash), RNS.LOG_DEBUG) RNS.log(f"Selected waiting peer {selected_index}: {RNS.prettyhexrep(selected_peer.destination_hash)}", RNS.LOG_DEBUG)
selected_peer.sync() selected_peer.sync()
for peer_id in culled_peers: for peer_id in culled_peers:
RNS.log("Removing peer "+RNS.prettyhexrep(peer_id)+" due to excessive unreachability", RNS.LOG_WARNING) RNS.log(f"Removing peer {RNS.prettyhexrep(peer_id)} due to excessive unreachability", RNS.LOG_WARNING)
try: try:
if peer_id in self.peers: if peer_id in self.peers: self.peers.pop(peer_id)
self.peers.pop(peer_id)
except Exception as e: except Exception as e:
RNS.log("Error while removing peer "+RNS.prettyhexrep(peer_id)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log(f"Error while removing peer {RNS.prettyhexrep(peer_id)}. The contained exception was: {e}", RNS.LOG_ERROR)
def propagation_link_established(self, link): def propagation_link_established(self, link):
link.set_packet_callback(self.propagation_packet) link.set_packet_callback(self.propagation_packet)
@@ -2273,7 +2541,7 @@ class LXMRouter:
return count return count
def propagation_resource_advertised(self, resource): def propagation_resource_advertised(self, resource):
if self.from_static_only: if self.from_static_only and not resource.app_flag_set():
remote_identity = resource.link.get_remote_identity() remote_identity = resource.link.get_remote_identity()
if remote_identity == None: if remote_identity == None:
RNS.log(f"Rejecting propagation resource from unidentified peer", RNS.LOG_DEBUG) RNS.log(f"Rejecting propagation resource from unidentified peer", RNS.LOG_DEBUG)
@@ -2313,7 +2581,7 @@ class LXMRouter:
for validated_entry in validated_messages: for validated_entry in validated_messages:
lxmf_data = validated_entry[1] lxmf_data = validated_entry[1]
stamp_value = validated_entry[2] stamp_value = quantize_cost(validated_entry[2])
stamp_data = validated_entry[3] stamp_data = validated_entry[3]
self.lxmf_propagation(lxmf_data, stamp_value=stamp_value, stamp_data=stamp_data) self.lxmf_propagation(lxmf_data, stamp_value=stamp_value, stamp_data=stamp_data)
self.client_propagation_messages_received += 1 self.client_propagation_messages_received += 1
@@ -2342,8 +2610,6 @@ class LXMRouter:
bypass_sequential = not self.propagation_static_peer_sequential and remote_hash in self.static_peers bypass_sequential = not self.propagation_static_peer_sequential and remote_hash in self.static_peers
if not bypass_sequential and self.propagation_sequential_validation and len(self.validating_pn_stamps_from) > 0: if not bypass_sequential and self.propagation_sequential_validation and len(self.validating_pn_stamps_from) > 0:
RNS.log(f"Propagation offer from node {remote_str} postponed, already validating {len(self.validating_pn_stamps_from)} PN stamp batches", RNS.LOG_NOTICE) RNS.log(f"Propagation offer from node {remote_str} postponed, already validating {len(self.validating_pn_stamps_from)} PN stamp batches", RNS.LOG_NOTICE)
# for rh in self.validating_pn_stamps_from:
# RNS.log(f"Validating from {RNS.prettyhexrep(rh)} for {RNS.prettytime(time.time()-self.validating_pn_stamps_from[rh])}")
return LXMPeer.ERROR_THROTTLED return LXMPeer.ERROR_THROTTLED
resources_transferring = self.propagation_resources_transferring resources_transferring = self.propagation_resources_transferring
@@ -2440,6 +2706,12 @@ class LXMRouter:
remote_peering_cost = pn_config[5][2] remote_peering_cost = pn_config[5][2]
remote_metadata = pn_config[6] remote_metadata = pn_config[6]
# TODO: Transitional mechanism, remove after 1.6.2
if len(pn_config) > 7:
remote_stamp_cost = pn_config[7][0]
remote_stamp_flex = pn_config[7][1]
remote_peering_cost = pn_config[7][2]
RNS.log(f"Auto-peering with {remote_str} discovered via incoming sync", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Auto-peering with {remote_str} discovered via incoming sync", RNS.LOG_DEBUG) # TODO: Remove debug
self.peer(remote_hash, remote_timebase, remote_transfer_limit, remote_sync_limit, remote_stamp_cost, remote_stamp_flex, remote_peering_cost, remote_metadata) self.peer(remote_hash, remote_timebase, remote_transfer_limit, remote_sync_limit, remote_stamp_cost, remote_stamp_flex, remote_peering_cost, remote_metadata)
@@ -2495,7 +2767,7 @@ class LXMRouter:
for validated_entry in validated_messages: for validated_entry in validated_messages:
transient_id = validated_entry[0] transient_id = validated_entry[0]
lxmf_data = validated_entry[1] lxmf_data = validated_entry[1]
stamp_value = validated_entry[2] stamp_value = quantize_cost(validated_entry[2])
stamp_data = validated_entry[3] stamp_data = validated_entry[3]
peer = None peer = None
@@ -2517,7 +2789,7 @@ class LXMRouter:
if invalid_message_count > 0: if invalid_message_count > 0:
resource.link.teardown() resource.link.teardown()
if remote_identity != None: if remote_identity != None:
throttle_time = LXMRouter.PN_STAMP_THROTTLE throttle_time = self.pn_stamp_throttle
self.throttled_peers[remote_hash] = time.time()+throttle_time self.throttled_peers[remote_hash] = time.time()+throttle_time
ms = "" if invalid_message_count == 1 else "s" ms = "" if invalid_message_count == 1 else "s"
RNS.log(f"Propagation transfer from {remote_str} contained {invalid_message_count} message{ms} with invalid stamps, throttled for {RNS.prettytime(throttle_time)}", RNS.LOG_NOTICE) RNS.log(f"Propagation transfer from {remote_str} contained {invalid_message_count} message{ms} with invalid stamps, throttled for {RNS.prettytime(throttle_time)}", RNS.LOG_NOTICE)
@@ -2561,11 +2833,26 @@ class LXMRouter:
try: try:
if len(lxmf_data) >= LXMessage.LXMF_OVERHEAD: if len(lxmf_data) >= LXMessage.LXMF_OVERHEAD:
transient_id = RNS.Identity.full_hash(lxmf_data) transient_id = RNS.Identity.full_hash(lxmf_data)
received = time.time()
if (not transient_id in self.propagation_entries and not transient_id in self.locally_processed_transient_ids) or allow_duplicate == True: duplicate_filtered = True
received = time.time() if allow_duplicate == True:
duplicate_filtered = False
# TODO: Remove legacy handling after transition
if self.store != None: self.store.unconditionally_mark_processed(transient_id, received)
else:
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
elif not transient_id in self.propagation_entries:
# TODO: Remove legacy handling after transition
if self.store != None: duplicate_filtered = not self.store.conditionally_claim_processed(transient_id, received)
else:
if not transient_id in self.locally_processed_transient_ids:
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
duplicate_filtered = False
if not duplicate_filtered:
destination_hash = lxmf_data[:LXMessage.DESTINATION_LENGTH] destination_hash = lxmf_data[:LXMessage.DESTINATION_LENGTH]
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
if destination_hash in self.delivery_destinations: if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash] delivery_destination = self.delivery_destinations[destination_hash]
@@ -2574,10 +2861,19 @@ class LXMRouter:
if decrypted_lxmf_data != None: if decrypted_lxmf_data != None:
delivery_data = lxmf_data[:LXMessage.DESTINATION_LENGTH]+decrypted_lxmf_data 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, allow_duplicate=allow_duplicate) self.lxmf_delivery(delivery_data, delivery_destination.type, ratchet_id=delivery_destination.latest_ratchet_id, method=LXMessage.PROPAGATED, no_stamp_enforcement=no_stamp_enforcement, allow_duplicate=allow_duplicate)
with self.delivered_transient_ids_lock: self.locally_delivered_transient_ids[transient_id] = time.time() # TODO: Remove legacy handling after transition
if self.store != None: self.store.mark_locally_delivered(transient_id, time.time())
else:
with self.delivered_transient_ids_lock: 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: else:
if self.propagation_node: if self.propagation_node:
if not stamp_value: return # TODO: This is edge-case handling for stamp-less paper messages being
# ingested onto a propagation node, which is currently not possible,
# but could potentially be supported somehow. Will need to figure this
# one out at a more opportune moment. Potential local stamping at time
# of ingress, if allowed by config.
stamp_value = quantize_cost(stamp_value)
stamped_data = lxmf_data+stamp_data stamped_data = lxmf_data+stamp_data
value_component = f"_{stamp_value}" if stamp_value and stamp_value > 0 else "" value_component = f"_{stamp_value}" if stamp_value and stamp_value > 0 else ""
file_path = f"{self.messagepath}/{RNS.hexrep(transient_id, delimit=False)}_{received}{value_component}" file_path = f"{self.messagepath}/{RNS.hexrep(transient_id, delimit=False)}_{received}{value_component}"
@@ -2618,6 +2914,8 @@ class LXMRouter:
lxmf_data = base64.urlsafe_b64decode(uri.replace(LXMessage.URI_SCHEMA+"://", "").replace("/", "")+"==") lxmf_data = base64.urlsafe_b64decode(uri.replace(LXMessage.URI_SCHEMA+"://", "").replace("/", "")+"==")
transient_id = RNS.Identity.full_hash(lxmf_data) transient_id = RNS.Identity.full_hash(lxmf_data)
# TODO: Consider whether to allow duplicate paper messages by
# default, and potential implications in client applications.
router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate, allow_duplicate=allow_duplicate, is_paper_message=True) router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate, allow_duplicate=allow_duplicate, is_paper_message=True)
if router_propagation_result != False: if router_propagation_result != False:
RNS.log("LXM with transient ID "+RNS.prettyhexrep(transient_id)+" was ingested.", RNS.LOG_DEBUG) RNS.log("LXM with transient ID "+RNS.prettyhexrep(transient_id)+" was ingested.", RNS.LOG_DEBUG)
@@ -2764,8 +3062,11 @@ class LXMRouter:
# Udate ticket delivery stats # Udate ticket delivery stats
if lxmessage.include_ticket and FIELD_TICKET in lxmessage.fields: 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) 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() # TODO: Remove legacy handling after transition
self.save_available_tickets() if self.store != None: self.store.mark_last_ticket_delivery(lxmessage.destination_hash, time.time())
else:
self.available_tickets["last_deliveries"][lxmessage.destination_hash] = time.time()
self.save_available_tickets()
# Prepare link for backchannel communications # Prepare link for backchannel communications
delivery_destination_hash = lxmessage.get_destination().hash delivery_destination_hash = lxmessage.get_destination().hash
@@ -2784,6 +3085,8 @@ class LXMRouter:
elif lxmessage.method == LXMessage.PROPAGATED and lxmessage.state == LXMessage.SENT: 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) RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
try: RNS.Reticulum.get_instance()._retain_destination_data(lxmessage.destination_hash)
except Exception as e: RNS.log(f"An error occurred while marking {RNS.prettyhexrep(lxmessage.destination_hash)} for announce data retainment: {e}", RNS.LOG_ERROR)
self.pending_outbound.remove(lxmessage) self.pending_outbound.remove(lxmessage)
elif lxmessage.state == LXMessage.CANCELLED: elif lxmessage.state == LXMessage.CANCELLED:
@@ -2803,7 +3106,8 @@ class LXMRouter:
# Outbound handling for opportunistic messages # Outbound handling for opportunistic messages
if lxmessage.method == LXMessage.OPPORTUNISTIC: if lxmessage.method == LXMessage.OPPORTUNISTIC:
if lxmessage.delivery_attempts <= self.attempt_limit(lxmessage): held = self.slow_path_held(lxmessage, lxmessage.get_destination().hash)
if not held and lxmessage.delivery_attempts <= self.attempt_limit(lxmessage):
destination_hash = lxmessage.get_destination().hash destination_hash = lxmessage.get_destination().hash
if self.attempt_due(lxmessage, destination_hash): if self.attempt_due(lxmessage, destination_hash):
path_known = RNS.Transport.has_path(destination_hash) path_known = RNS.Transport.has_path(destination_hash)
@@ -2835,13 +3139,14 @@ class LXMRouter:
else: else:
lxmessage.delivery_attempts += 1 lxmessage.delivery_attempts += 1
lxmessage.sent_on_path = path_known lxmessage.sent_on_path = path_known
lxmessage.sent_on_slow_path = self.slow_path(destination_hash)
self.schedule_attempt(lxmessage, destination_hash) self.schedule_attempt(lxmessage, destination_hash)
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts) +" for "+str(lxmessage)+" to "+RNS.prettyhexrep(destination_hash), RNS.LOG_DEBUG) RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts) +" for "+str(lxmessage)+" to "+RNS.prettyhexrep(destination_hash), RNS.LOG_DEBUG)
try: lxmessage.send() try: lxmessage.send()
except Exception as e: except Exception as e:
RNS.log(f"Error while sending {lxmessage}: {e}", RNS.LOG_ERROR) RNS.log(f"Error while sending {lxmessage}: {e}", RNS.LOG_ERROR)
self.fail_message(lxmessage) self.fail_message(lxmessage)
elif self.attempt_due(lxmessage, lxmessage.get_destination().hash): elif not held and self.attempt_due(lxmessage, lxmessage.get_destination().hash):
RNS.log("Max delivery attempts reached for oppertunistic "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG) RNS.log("Max delivery attempts reached for oppertunistic "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage) self.fail_message(lxmessage)
@@ -2849,7 +3154,8 @@ class LXMRouter:
# over a direct link to the final recipient # over a direct link to the final recipient
elif lxmessage.method == LXMessage.DIRECT: elif lxmessage.method == LXMessage.DIRECT:
delivery_destination_hash = lxmessage.get_destination().hash delivery_destination_hash = lxmessage.get_destination().hash
if lxmessage.delivery_attempts <= self.attempt_limit(lxmessage): held = self.slow_path_held(lxmessage, delivery_destination_hash)
if not held and lxmessage.delivery_attempts <= self.attempt_limit(lxmessage):
direct_link = None direct_link = None
if delivery_destination_hash in self.direct_links: if delivery_destination_hash in self.direct_links:
@@ -2870,8 +3176,9 @@ class LXMRouter:
if direct_link.status == RNS.Link.ACTIVE: if direct_link.status == RNS.Link.ACTIVE:
if lxmessage.progress == None or lxmessage.progress < 0.05: if lxmessage.progress == None or lxmessage.progress < 0.05:
lxmessage.progress = 0.05 lxmessage.progress = 0.05
if lxmessage.state != LXMessage.SENDING: if lxmessage.state == LXMessage.OUTBOUND:
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" on link "+str(direct_link), 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.sent_on_slow_path = self.slow_path(delivery_destination_hash)
lxmessage.set_delivery_destination(direct_link) lxmessage.set_delivery_destination(direct_link)
try: lxmessage.send() try: lxmessage.send()
except Exception as e: except Exception as e:
@@ -2928,7 +3235,7 @@ class LXMRouter:
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG) RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage) self.fail_message(lxmessage)
elif self.attempt_due(lxmessage, delivery_destination_hash): elif not held and self.attempt_due(lxmessage, delivery_destination_hash):
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG) RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage) self.fail_message(lxmessage)
@@ -2941,14 +3248,16 @@ class LXMRouter:
RNS.log("No outbound propagation node specified for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_ERROR) RNS.log("No outbound propagation node specified for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_ERROR)
self.fail_message(lxmessage) self.fail_message(lxmessage)
else: else:
if lxmessage.delivery_attempts <= self.attempt_limit(lxmessage): held = self.slow_path_held(lxmessage, self.outbound_propagation_node)
if not held and lxmessage.delivery_attempts <= self.attempt_limit(lxmessage):
if self.outbound_propagation_link != None: if self.outbound_propagation_link != None:
# A link already exists, so we'll try to use it # A link already exists, so we'll try to use it
# to deliver the message # to deliver the message
if self.outbound_propagation_link.status == RNS.Link.ACTIVE: if self.outbound_propagation_link.status == RNS.Link.ACTIVE:
if lxmessage.state != LXMessage.SENDING: if lxmessage.state == LXMessage.OUTBOUND:
RNS.log("Starting propagation transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" via "+RNS.prettyhexrep(self.outbound_propagation_node), RNS.LOG_DEBUG) RNS.log("Starting propagation transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" via "+RNS.prettyhexrep(self.outbound_propagation_node), RNS.LOG_DEBUG)
lxmessage.sent_on_slow_path = self.slow_path(self.outbound_propagation_node)
lxmessage.set_delivery_destination(self.outbound_propagation_link) lxmessage.set_delivery_destination(self.outbound_propagation_link)
try: lxmessage.send() try: lxmessage.send()
except Exception as e: except Exception as e:
@@ -2992,6 +3301,6 @@ class LXMRouter:
RNS.log("Max delivery attempts reached for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG) RNS.log("Max delivery attempts reached for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage) self.fail_message(lxmessage)
elif self.attempt_due(lxmessage, self.outbound_propagation_node): elif not held and self.attempt_due(lxmessage, self.outbound_propagation_node):
RNS.log("Max delivery attempts reached for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG) RNS.log("Max delivery attempts reached for propagated "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage) self.fail_message(lxmessage)
+29 -6
View File
@@ -192,6 +192,8 @@ class LXMessage:
self.__pn_encrypted_data = None self.__pn_encrypted_data = None
self.__persist_lock = Lock() self.__persist_lock = Lock()
self.failed_callback = None self.failed_callback = None
self.receipt_timeout = None
self.concluded_callback = None
self.deferred_stamp_generating = False self.deferred_stamp_generating = False
@@ -290,6 +292,14 @@ class LXMessage:
if self.stamp == None: if self.stamp == None:
return False return False
else: else:
# Transitory mechanism, check non-expanded workblock validity first. ######
workblock_ne = LXStamper.stamp_workblock(self.message_id, no_expand=True) #
if LXStamper.stamp_valid(self.stamp, target_cost, workblock_ne): #
RNS.log(f"Stamp (NE) on {self} validated", RNS.LOG_DEBUG) #
self.stamp_value = LXStamper.stamp_value(workblock_ne, self.stamp) #
return True #
###########################################################################
workblock = LXStamper.stamp_workblock(self.message_id) workblock = LXStamper.stamp_workblock(self.message_id)
if LXStamper.stamp_valid(self.stamp, target_cost, workblock): if LXStamper.stamp_valid(self.stamp, target_cost, workblock):
RNS.log(f"Stamp on {self} validated", RNS.LOG_DEBUG) # TODO: Remove at some point RNS.log(f"Stamp on {self} validated", RNS.LOG_DEBUG) # TODO: Remove at some point
@@ -472,11 +482,14 @@ class LXMessage:
if self.method == LXMessage.OPPORTUNISTIC: if self.method == LXMessage.OPPORTUNISTIC:
lxm_packet = self.__as_packet() lxm_packet = self.__as_packet()
receipt = lxm_packet.send() receipt = lxm_packet.send()
if receipt: receipt.set_delivery_callback(self.__mark_delivered)
else: RNS.log(f"No receipt generated on sent opportunistic {self}", RNS.LOG_WARNING)
self.progress = 0.50 self.progress = 0.50
self.ratchet_id = lxm_packet.ratchet_id self.ratchet_id = lxm_packet.ratchet_id
self.state = LXMessage.SENT self.state = LXMessage.SENT
if receipt:
receipt.set_delivery_callback(self.__mark_delivered)
if self.receipt_timeout: receipt.set_timeout(max(receipt.timeout, self.receipt_timeout))
if receipt.status == RNS.PacketReceipt.DELIVERED: self.__mark_delivered(receipt)
else: RNS.log(f"No receipt generated on sent opportunistic {self}", RNS.LOG_WARNING)
elif self.method == LXMessage.DIRECT: elif self.method == LXMessage.DIRECT:
self.state = LXMessage.SENDING self.state = LXMessage.SENDING
@@ -486,12 +499,14 @@ class LXMessage:
receipt = lxm_packet.send() receipt = lxm_packet.send()
self.ratchet_id = self.__delivery_destination.link_id self.ratchet_id = self.__delivery_destination.link_id
if receipt: if receipt:
self.progress = 0.50
receipt.set_delivery_callback(self.__mark_delivered) receipt.set_delivery_callback(self.__mark_delivered)
receipt.set_timeout_callback(self.__link_packet_timed_out) receipt.set_timeout_callback(self.__link_packet_timed_out)
self.progress = 0.50 if receipt.status == RNS.PacketReceipt.DELIVERED: self.__mark_delivered(receipt)
else: else:
if self.__delivery_destination: if self.__delivery_destination:
self.__delivery_destination.teardown() self.__delivery_destination.teardown()
self.state = LXMessage.OUTBOUND
elif self.representation == LXMessage.RESOURCE: elif self.representation == LXMessage.RESOURCE:
self.resource_representation = self.__as_resource() self.resource_representation = self.__as_resource()
@@ -504,11 +519,13 @@ class LXMessage:
if self.representation == LXMessage.PACKET: if self.representation == LXMessage.PACKET:
receipt = self.__as_packet().send() receipt = self.__as_packet().send()
if receipt: if receipt:
self.progress = 0.50
receipt.set_delivery_callback(self.__mark_propagated) receipt.set_delivery_callback(self.__mark_propagated)
receipt.set_timeout_callback(self.__link_packet_timed_out) receipt.set_timeout_callback(self.__link_packet_timed_out)
self.progress = 0.50 if receipt.status == RNS.PacketReceipt.DELIVERED: self.__mark_propagated(receipt)
else: else:
self.__delivery_destination.teardown() self.__delivery_destination.teardown()
self.state = LXMessage.OUTBOUND
elif self.representation == LXMessage.RESOURCE: elif self.representation == LXMessage.RESOURCE:
self.resource_representation = self.__as_resource() self.resource_representation = self.__as_resource()
@@ -566,10 +583,13 @@ class LXMessage:
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
def __mark_delivered(self, receipt = None): def __mark_delivered(self, receipt = None):
if self.state == LXMessage.DELIVERED: return
RNS.log("Received delivery notification for "+str(self), RNS.LOG_DEBUG) RNS.log("Received delivery notification for "+str(self), RNS.LOG_DEBUG)
self.state = LXMessage.DELIVERED self.state = LXMessage.DELIVERED
self.progress = 1.0 self.progress = 1.0
if self.concluded_callback != None and callable(self.concluded_callback): self.concluded_callback(self)
if self.__delivery_callback != None and callable(self.__delivery_callback): if self.__delivery_callback != None and callable(self.__delivery_callback):
try: try:
self.__delivery_callback(self) self.__delivery_callback(self)
@@ -578,10 +598,13 @@ class LXMessage:
RNS.trace_exception(e) RNS.trace_exception(e)
def __mark_propagated(self, receipt = None): def __mark_propagated(self, receipt = None):
if self.state == LXMessage.SENT: return
RNS.log("Received propagation success notification for "+str(self), RNS.LOG_DEBUG) RNS.log("Received propagation success notification for "+str(self), RNS.LOG_DEBUG)
self.state = LXMessage.SENT self.state = LXMessage.SENT
self.progress = 1.0 self.progress = 1.0
if self.concluded_callback != None and callable(self.concluded_callback): self.concluded_callback(self)
if self.__delivery_callback != None and callable(self.__delivery_callback): if self.__delivery_callback != None and callable(self.__delivery_callback):
try: try:
self.__delivery_callback(self) self.__delivery_callback(self)
@@ -658,9 +681,9 @@ class LXMessage:
raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active") raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active")
if self.method == LXMessage.DIRECT: if self.method == LXMessage.DIRECT:
return RNS.Resource(self.packed, self.__delivery_destination, callback = self.__resource_concluded, progress_callback = self.__update_transfer_progress, auto_compress=self.auto_compress) return RNS.Resource(self.packed, self.__delivery_destination, callback=self.__resource_concluded, progress_callback=self.__update_transfer_progress, auto_compress=self.auto_compress)
elif self.method == LXMessage.PROPAGATED: elif self.method == LXMessage.PROPAGATED:
return RNS.Resource(self.propagation_packed, self.__delivery_destination, callback = self.__propagation_resource_concluded, progress_callback = self.__update_transfer_progress) return RNS.Resource(self.propagation_packed, self.__delivery_destination, app_flag=True, callback=self.__propagation_resource_concluded, progress_callback=self.__update_transfer_progress)
else: else:
return None return None
+28 -421
View File
@@ -1,82 +1,34 @@
import RNS import RNS
import RNS.vendor.umsgpack as msgpack import RNS.Stamps
import os import os
import sys
import time import time
import math import math
import itertools import itertools
import contextlib
import multiprocessing import multiprocessing
from RNS.Stamps import stamp_workblock
from RNS.Stamps import stamp_valid
from RNS.Stamps import stamp_value
from RNS.Stamps import cancel_work
# LXMF-specific stamp parameters
WORKBLOCK_EXPAND_ROUNDS = 3000 WORKBLOCK_EXPAND_ROUNDS = 3000
WORKBLOCK_EXPAND_ROUNDS_PN = 1000 WORKBLOCK_EXPAND_ROUNDS_PN = 1000
WORKBLOCK_EXPAND_ROUNDS_PEERING = 25 WORKBLOCK_EXPAND_ROUNDS_PEERING = 25
STAMP_SIZE = RNS.Identity.HASHLENGTH//8 STAMP_SIZE = RNS.Identity.HASHLENGTH//8
PN_VALIDATION_POOL_MIN_SIZE = 256 PN_VALIDATION_POOL_MIN_SIZE = 256
USE_WORKER_MANAGER = False
active_jobs = {} # Wrapper that forces the LXMF-specific stamp size
def generate_stamp(message_id, stamp_cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS, no_expand=False):
if sys.version_info[0] >= 3 and sys.version_info[1] >= 14: return RNS.Stamps.generate_stamp(message_id, stamp_cost, expand_rounds=expand_rounds, no_expand=no_expand, size=STAMP_SIZE)
USE_WORKER_MANAGER = True
@contextlib.contextmanager
def worker_context(ctx, stamp_cost, workblock, message_id):
stop_event = ctx.Event()
result_queue = ctx.Queue(1)
rounds_queue = ctx.Queue()
active_jobs[message_id] = [stop_event, result_queue]
job_procs = []
try: yield stop_event, result_queue, rounds_queue, job_procs
finally:
if message_id in active_jobs: del active_jobs[message_id]
stop_event.set()
for p in job_procs:
if p.is_alive(): p.terminate()
for p in job_procs: p.join(timeout=0.5)
result_queue.close()
result_queue.join_thread()
rounds_queue.close()
rounds_queue.join_thread()
stop_event.clear()
def stamp_workblock(material, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
wb_st = time.time()
workblock = b""
for n in range(expand_rounds):
workblock += RNS.Cryptography.hkdf(length=256,
derive_from=material,
salt=RNS.Identity.full_hash(material+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 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_peering_key(peering_id, peering_key, target_cost): def validate_peering_key(peering_id, peering_key, target_cost):
# Transitory mechanism, check non-expanded workblock validity first. ##
workblock_ne = stamp_workblock(peering_id, no_expand=True) #
if stamp_valid(peering_key, target_cost, workblock_ne): return True #
#######################################################################
workblock = stamp_workblock(peering_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING) workblock = stamp_workblock(peering_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
if not stamp_valid(peering_key, target_cost, workblock): return False if not stamp_valid(peering_key, target_cost, workblock): return False
else: return True else: return True
@@ -88,8 +40,15 @@ def validate_pn_stamp(transient_data, target_cost):
lxm_data = transient_data[:-STAMP_SIZE] lxm_data = transient_data[:-STAMP_SIZE]
stamp = transient_data[-STAMP_SIZE:] stamp = transient_data[-STAMP_SIZE:]
transient_id = RNS.Identity.full_hash(lxm_data) transient_id = RNS.Identity.full_hash(lxm_data)
workblock = stamp_workblock(transient_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PN)
# Transitory mechanism, check non-expanded workblock validity first. ##
workblock_ne = stamp_workblock(transient_id, no_expand=True) #
if stamp_valid(stamp, target_cost, workblock_ne): #
value = stamp_value(workblock_ne, stamp) #
return transient_id, lxm_data, value, stamp #
#######################################################################
workblock = stamp_workblock(transient_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PN)
if not stamp_valid(stamp, target_cost, workblock): return None, None, None, None if not stamp_valid(stamp, target_cost, workblock): return None, None, None, None
else: else:
value = stamp_value(workblock, stamp) value = stamp_value(workblock, stamp)
@@ -120,363 +79,6 @@ def validate_pn_stamps(transient_list, target_cost):
if len(transient_list) <= PN_VALIDATION_POOL_MIN_SIZE or non_mp_platform: return validate_pn_stamps_job_simple(transient_list, target_cost) if len(transient_list) <= PN_VALIDATION_POOL_MIN_SIZE or non_mp_platform: return validate_pn_stamps_job_simple(transient_list, target_cost)
else: return validate_pn_stamps_job_multip(transient_list, target_cost) else: return validate_pn_stamps_job_multip(transient_list, target_cost)
def generate_stamp(message_id, stamp_cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
RNS.log(f"Generating stamp with cost {stamp_cost} for {RNS.prettyhexrep(message_id)}...", RNS.LOG_DEBUG)
workblock = stamp_workblock(message_id, expand_rounds=expand_rounds)
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, message_id)
elif RNS.vendor.platformutils.is_android(): stamp, rounds = job_android(stamp_cost, workblock, message_id)
else:
if USE_WORKER_MANAGER: stamp, rounds = job_linux_managed(stamp_cost, workblock, message_id)
else: stamp, rounds = job_linux(stamp_cost, workblock, message_id)
duration = time.time() - start_time
speed = rounds/duration
if stamp != None: 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 cancel_work(message_id):
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin():
try:
if message_id in active_jobs:
active_jobs[message_id] = True
except Exception as e:
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
elif RNS.vendor.platformutils.is_android():
try:
if message_id in active_jobs:
active_jobs[message_id] = True
except Exception as e:
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
else:
try:
if message_id in active_jobs:
stop_event = active_jobs[message_id][0]
result_queue = active_jobs[message_id][1]
stop_event.set()
result_queue.put(None)
active_jobs.pop(message_id)
except Exception as e:
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
def job_simple(stamp_cost, workblock, message_id):
# 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()
active_jobs[message_id] = False;
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) and not active_jobs[message_id]:
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)
if active_jobs[message_id] == True:
pstamp = None
active_jobs.pop(message_id)
return pstamp, rounds
def job_linux_managed(stamp_cost, workblock, message_id):
ctx = multiprocessing.get_context("fork")
cores = multiprocessing.cpu_count()
jobs = cores if cores <= 12 else int(cores/2)
allow_kill = True
stamp = None
total_rounds = 0
with worker_context(ctx, stamp_cost, workblock, message_id) as (stop_event, result_queue, rounds_queue, job_procs):
RNS.log(f"Starting {jobs} stamp generation workers", RNS.LOG_DEBUG)
def job(stop_event, sc, wb, worker_id):
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()
try: result_queue.put_nowait(pstamp)
except: pass
try: rounds_queue.put_nowait(rounds)
except: pass
for jpn in range(jobs):
p = ctx.Process(target=job, args=(stop_event, stamp_cost, workblock, jpn), daemon=True)
job_procs.append(p)
p.start()
try: stamp = result_queue.get(timeout=None)
except Exception as e:
RNS.log(f"Failed to get result from workers: {e}", RNS.LOG_ERROR)
stamp = None
# 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_linux(stamp_cost, workblock, message_id):
allow_kill = True
stamp = None
total_rounds = 0
cores = multiprocessing.cpu_count()
jobs = cores if cores <= 12 else int(cores/2)
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.get_context("fork").Process(target=job, kwargs={"stop_event": stop_event, "pn": jpn, "sc": stamp_cost, "wb": workblock}, daemon=True)
job_procs.append(process)
process.start()
active_jobs[message_id] = [stop_event, result_queue]
stamp = result_queue.get()
# 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, message_id):
# 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)
active_jobs[message_id] = False;
RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove
results_dict = wm.dict()
while stamp == None and active_jobs[message_id] == False:
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)
active_jobs.pop(message_id)
return stamp, total_rounds
# def stamp_value_linear(workblock, stamp):
# value = 0
# bits = 256
# material = RNS.Identity.full_hash(workblock+stamp)
# s = int.from_bytes(material, byteorder="big")
# return s.bit_count()
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys
if len(sys.argv) < 2: if len(sys.argv) < 2:
@@ -515,6 +117,11 @@ if __name__ == "__main__":
message_id = os.urandom(32) message_id = os.urandom(32)
generate_stamp(message_id, cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING) generate_stamp(message_id, cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
RNS.log("", RNS.LOG_DEBUG)
RNS.log("Testing non-expanded workblock generation", RNS.LOG_DEBUG)
message_id = os.urandom(32)
generate_stamp(message_id, cost, expand_rounds=0)
# transient_list = [] # transient_list = []
# st = time.time(); count = 10000 # st = time.time(); count = 10000
# for i in range(count): transient_list.append(os.urandom(256)) # for i in range(count): transient_list.append(os.urandom(256))
+502
View File
@@ -0,0 +1,502 @@
import os
import time
import sqlite3
import threading
import RNS
import RNS.vendor.umsgpack as msgpack
class LXMFStore:
CURRENT_VERSION = 1
TRANSIENT_ID_LENGTH = RNS.Identity.HASHLENGTH//8
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
TICKET_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
IMPORT_CHUNK = 4096
CULL_CHUNK = 4096
IN_CHUNK = 512
VACUUM_PAGES = 512
def __init__(self, db_path):
if sqlite3.threadsafety < 3: raise RuntimeError("Storage backend requires a SQLite build with serialized threading support")
self.db_path = db_path
self._conn = None
self._conn_lock = threading.Lock()
self._close_warned = False
self._conn = sqlite3.connect(db_path, check_same_thread=False, isolation_level=None)
self._conn.execute("PRAGMA auto_vacuum=INCREMENTAL")
self._conn.execute("PRAGMA journal_mode=WAL")
self._conn.execute("PRAGMA synchronous=NORMAL")
self._conn.execute("PRAGMA journal_size_limit=8388608")
self._conn.execute("PRAGMA busy_timeout=1500")
self.__create_schema()
def close(self):
with self._conn_lock:
if self._conn != None:
try: self._conn.execute("PRAGMA optimize")
except Exception: pass
self._conn.close()
self._conn = None
def __create_schema(self):
db_version = self._conn.execute("PRAGMA user_version").fetchone()[0]
if db_version > self.CURRENT_VERSION:
RNS.log(f"Cannot open store {self.db_path}: database version {db_version} is newer than supported version {self.CURRENT_VERSION}", RNS.LOG_CRITICAL)
self._conn.close(); self._conn = None
raise ValueError(f"Store database version {db_version} is newer than supported version {self.CURRENT_VERSION}")
try:
self._conn.execute("BEGIN")
self._conn.execute("""CREATE TABLE IF NOT EXISTS stamp_costs (
destination_hash BLOB PRIMARY KEY,
updated REAL NOT NULL,
used REAL,
cost REAL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS delivered_transient_ids (
transient_id BLOB PRIMARY KEY,
received REAL NOT NULL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS processed_transient_ids (
transient_id BLOB PRIMARY KEY,
received REAL NOT NULL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS tickets_outbound (
destination_hash BLOB PRIMARY KEY,
expires REAL NOT NULL,
ticket BLOB NOT NULL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS tickets_inbound (
ticket BLOB PRIMARY KEY,
destination_hash BLOB NOT NULL,
expires REAL NOT NULL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS ticket_deliveries (
destination_hash BLOB PRIMARY KEY,
timestamp REAL NOT NULL)""")
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_delivered_received ON delivered_transient_ids (received)")
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_processed_received ON processed_transient_ids (received)")
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_stampcost_updated ON stamp_costs (updated)")
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_tickets_in_dest ON tickets_inbound (destination_hash)")
self._conn.execute(f"PRAGMA user_version = {self.CURRENT_VERSION}")
self._conn.execute("COMMIT")
except Exception as e:
RNS.log(f"Could not initialise store schema at {self.db_path}. The contained exception was: {e}", RNS.LOG_CRITICAL)
try: self._conn.execute("ROLLBACK")
except Exception: pass
self._conn.close(); self._conn = None
raise
def _ready(self):
if self._conn == None:
if not self._close_warned:
self._close_warned = True
RNS.log("Store operation attempted after close", RNS.LOG_ERROR)
return False
else: return True
def _claim(self, table, key_column, key, ts_column, timestamp):
try:
with self._conn_lock:
if not self._ready(): return True
cursor = self._conn.execute(f"INSERT INTO {table} ({key_column}, {ts_column}) VALUES (?, ?) ON CONFLICT({key_column}) DO NOTHING", (key, timestamp))
return cursor.rowcount == 1
except Exception as e:
RNS.log(f"Could not claim entry in {table} of store, treating as claimed. The contained exception was: {e}", RNS.LOG_ERROR)
return True
def _upsert_timestamp(self, table, key_column, key, ts_column, timestamp):
try:
with self._conn_lock:
if not self._ready(): return False
self._conn.execute(f"INSERT INTO {table} ({key_column}, {ts_column}) VALUES (?, ?) ON CONFLICT({key_column}) DO UPDATE SET {ts_column}=excluded.{ts_column}", (key, timestamp))
return True
except Exception as e:
RNS.log(f"Could not upsert entry in {table} of store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def _cull(self, table, ts_column, cutoff, max_entries):
try:
with self._conn_lock:
if not self._ready(): return 0
cursor = self._conn.execute(f"DELETE FROM {table} WHERE rowid IN (SELECT rowid FROM {table} WHERE {ts_column} < ? LIMIT {int(max_entries)})", (cutoff,))
return cursor.rowcount
except Exception as e:
RNS.log(f"Could not cull entries in {table} of store. The contained exception was: {e}", RNS.LOG_ERROR)
return 0
########################
# Outbound Stamp Costs #
########################
def update_stamp_cost(self, destination_hash, cost):
try:
with self._conn_lock:
if not self._ready(): return False
self._conn.execute("INSERT INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?, ?, NULL, ?) ON CONFLICT(destination_hash) DO UPDATE SET updated=excluded.updated, cost=excluded.cost", (destination_hash, time.time(), cost))
return True
except Exception as e:
RNS.log(f"Could not update outbound stamp cost in store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def get_outbound_stamp_cost(self, destination_hash):
if not self._ready(): return None
cost = None
try:
with self._conn_lock:
if not self._ready(): return None
row = self._conn.execute("SELECT cost FROM stamp_costs WHERE destination_hash=?", (destination_hash,)).fetchone()
if row != None and len(row) > 0:
cost = row[0]
try: self._conn.execute("UPDATE stamp_costs SET used=? WHERE destination_hash=?", (time.time(), destination_hash))
except Exception as e: RNS.log(f"Could not update stamp cost usage time in store. The contained exception was: {e}", RNS.LOG_ERROR)
except Exception as e:
RNS.log(f"Could not recall outbound stamp cost from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
return cost
def cull_stamp_costs(self, cutoff, max_entries=CULL_CHUNK): return self._cull("stamp_costs", "updated", cutoff, max_entries)
##############################
# Transient ID Deduplication #
##############################
def has_delivered(self, transient_id):
if not self._ready(): return False
try:
with self._conn_lock:
if not self._ready(): return False
row = self._conn.execute("SELECT transient_id FROM delivered_transient_ids WHERE transient_id=?", (transient_id,)).fetchone()
return row != None
except Exception as e:
RNS.log(f"Could not query delivered transient ID in store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def known_delivered(self, transient_ids):
known = set()
if not self._ready(): return known
try:
with self._conn_lock:
if not self._ready(): return known
ids = list(set(transient_id for transient_id in transient_ids if type(transient_id) == bytes))
for i in range(0, len(ids), self.IN_CHUNK):
chunk = ids[i:i+self.IN_CHUNK]
marks = ",".join("?"*len(chunk))
for row in self._conn.execute(f"SELECT transient_id FROM delivered_transient_ids WHERE transient_id IN ({marks})", chunk):
known.add(row[0])
except Exception as e:
RNS.log(f"Could not query known delivered transient IDs in store. The contained exception was: {e}", RNS.LOG_ERROR)
return set()
return known
def mark_locally_delivered(self, transient_id, received): return self._upsert_timestamp("delivered_transient_ids", "transient_id", transient_id, "received", received)
def unconditionally_mark_processed(self, transient_id, received): return self._upsert_timestamp("processed_transient_ids", "transient_id", transient_id, "received", received)
def conditionally_claim_delivered(self, transient_id, received): return self._claim("delivered_transient_ids", "transient_id", transient_id, "received", received)
def conditionally_claim_processed(self, transient_id, received): return self._claim("processed_transient_ids", "transient_id", transient_id, "received", received)
def cull_processed(self, cutoff, max_entries=CULL_CHUNK): return self._cull("processed_transient_ids", "received", cutoff, max_entries)
def cull_delivered(self, cutoff, max_entries=CULL_CHUNK): return self._cull("delivered_transient_ids", "received", cutoff, max_entries)
###########
# Tickets #
###########
def remember_ticket(self, destination_hash, ticket_entry):
try:
expires, ticket = ticket_entry[0], ticket_entry[1]
with self._conn_lock:
if not self._ready(): return False
self._conn.execute("INSERT INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?, ?, ?) ON CONFLICT(destination_hash) DO UPDATE SET expires=excluded.expires, ticket=excluded.ticket", (destination_hash, expires, ticket))
return True
except Exception as e:
RNS.log(f"Could not remember ticket in store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def get_outbound_ticket(self, destination_hash):
if not self._ready(): return None
try:
with self._conn_lock:
if not self._ready(): return None
row = self._conn.execute("SELECT ticket FROM tickets_outbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time())).fetchone()
if row != None: return row[0]
else: return None
except Exception as e:
RNS.log(f"Could not recall outbound ticket from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
def get_outbound_ticket_expiry(self, destination_hash):
if not self._ready(): return None
try:
with self._conn_lock:
if not self._ready(): return None
row = self._conn.execute("SELECT expires FROM tickets_outbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time())).fetchone()
if row != None: return row[0]
else: return None
except Exception as e:
RNS.log(f"Could not recall outbound ticket expiry from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
def get_reusable_inbound_ticket(self, destination_hash, renew_before):
if not self._ready(): return None
try:
with self._conn_lock:
if not self._ready(): return None
row = self._conn.execute("SELECT expires, ticket FROM tickets_inbound WHERE destination_hash=? AND expires > ? ORDER BY expires DESC LIMIT 1", (destination_hash, time.time()+renew_before)).fetchone()
if row != None: return [row[0], row[1]]
else: return None
except Exception as e:
RNS.log(f"Could not recall reusable inbound ticket from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
def store_inbound_ticket(self, destination_hash, ticket, expires):
try:
with self._conn_lock:
if not self._ready(): return False
self._conn.execute("INSERT INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?, ?, ?) ON CONFLICT(ticket) DO UPDATE SET destination_hash=excluded.destination_hash, expires=excluded.expires", (ticket, destination_hash, expires))
return True
except Exception as e:
RNS.log(f"Could not save inbound ticket in store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def get_inbound_tickets(self, destination_hash):
if not self._ready(): return None
try:
with self._conn_lock:
if not self._ready(): return None
tickets = [row[0] for row in self._conn.execute("SELECT ticket FROM tickets_inbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time()))]
if len(tickets) > 0: return tickets
else: return None
except Exception as e:
RNS.log(f"Could not recall inbound tickets from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
def get_last_ticket_delivery(self, destination_hash):
if not self._ready(): return None
try:
with self._conn_lock:
if not self._ready(): return None
row = self._conn.execute("SELECT timestamp FROM ticket_deliveries WHERE destination_hash=?", (destination_hash,)).fetchone()
if row != None: return row[0]
else: return None
except Exception as e:
RNS.log(f"Could not recall last ticket delivery from store. The contained exception was: {e}", RNS.LOG_ERROR)
return None
def mark_last_ticket_delivery(self, destination_hash, timestamp):
try:
with self._conn_lock:
if not self._ready(): return False
self._conn.execute("INSERT INTO ticket_deliveries (destination_hash, timestamp) VALUES (?, ?) ON CONFLICT(destination_hash) DO UPDATE SET timestamp=excluded.timestamp", (destination_hash, timestamp))
return True
except Exception as e:
RNS.log(f"Could not record last ticket delivery in store. The contained exception was: {e}", RNS.LOG_ERROR)
return False
def cull_tickets_outbound(self, cutoff, max_entries=CULL_CHUNK): return self._cull("tickets_outbound", "expires", cutoff, max_entries)
def cull_tickets_inbound(self, cutoff, max_entries=CULL_CHUNK): return self._cull("tickets_inbound", "expires", cutoff, max_entries)
###############
# Maintenance #
###############
def incremental_vacuum(self, max_pages=VACUUM_PAGES):
try:
with self._conn_lock:
if not self._ready(): return 0
freed = 0
while freed < int(max_pages):
before = self._conn.execute("PRAGMA freelist_count").fetchone()[0]
self._conn.execute(f"PRAGMA incremental_vacuum({int(max_pages)-freed})")
after = self._conn.execute("PRAGMA freelist_count").fetchone()[0]
if after >= before: break
freed += before-after
return freed
except Exception as e:
RNS.log(f"Could not run incremental vacuum on store. The contained exception was: {e}", RNS.LOG_ERROR)
return 0
############################
# Legacy Storage Migration #
############################
def import_legacy_delivered(self, path): return self.__import_legacy_timestamps(path, "delivered_transient_ids")
def import_legacy_processed(self, path): return self.__import_legacy_timestamps(path, "processed_transient_ids")
def __import_legacy_timestamps(self, path, table):
st = time.time()
try:
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
except Exception as e:
RNS.log(f"Could not read legacy transient ID cache at {path}: {e}", RNS.LOG_ERROR)
return -1
if not type(legacy) == dict:
RNS.log(f"Invalid data format in legacy transient ID cache at {path}, not importing", RNS.LOG_ERROR)
return -1
rows = []
for transient_id, timestamp in legacy.items():
if type(transient_id) == bytes and len(transient_id) == self.TRANSIENT_ID_LENGTH and type(timestamp) in (int, float) and timestamp > 0:
rows.append((transient_id, float(timestamp)))
imported = -1
with self._conn_lock:
if self._ready():
try:
self._conn.execute("BEGIN")
for i in range(0, len(rows), self.IMPORT_CHUNK): self._conn.executemany(f"INSERT OR IGNORE INTO {table} (transient_id, received) VALUES (?, ?)", rows[i:i+self.IMPORT_CHUNK])
self._conn.execute("COMMIT")
imported = len(rows)
except Exception as e:
RNS.log(f"Could not import legacy transient ID cache at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
try: self._conn.execute("ROLLBACK")
except Exception: pass
if imported >= 0:
try: os.replace(path, path+".imported")
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
return imported
def import_legacy_stamp_costs(self, path):
st = time.time()
try:
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
except Exception as e:
RNS.log(f"Could not read legacy outbound stamp cost cache at {path}: {e}", RNS.LOG_ERROR)
return -1
if not type(legacy) == dict:
RNS.log(f"Invalid data format in legacy outbound stamp cost cache at {path}, not importing", RNS.LOG_ERROR)
return -1
rows = []
for destination_hash, entry in legacy.items():
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(entry) in (list, tuple) and len(entry) >= 2:
last_heard, cost = entry[0], entry[1]
if type(last_heard) not in (int, float): continue
if cost != None and type(cost) not in (int, float): continue
rows.append((destination_hash, float(last_heard), cost))
imported = -1
with self._conn_lock:
if self._ready():
try:
self._conn.execute("BEGIN")
for i in range(0, len(rows), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?, ?, NULL, ?)", rows[i:i+self.IMPORT_CHUNK])
self._conn.execute("COMMIT")
imported = len(rows)
except Exception as e:
RNS.log(f"Could not import legacy outbound stamp cost cache at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
try: self._conn.execute("ROLLBACK")
except Exception: pass
if imported >= 0:
try: os.replace(path, path+".imported")
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
return imported
def import_legacy_tickets(self, path):
st = time.time()
try:
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
except Exception as e:
RNS.log(f"Could not read legacy available tickets file at {path}: {e}", RNS.LOG_ERROR)
return -1
if not type(legacy) == dict:
RNS.log(f"Invalid data format in legacy available tickets file at {path}, not importing", RNS.LOG_ERROR)
return -1
rows_outbound = []
rows_inbound = []
rows_deliveries = []
outbound = legacy.get("outbound"); inbound = legacy.get("inbound"); last_deliveries = legacy.get("last_deliveries")
if type(outbound) == dict:
for destination_hash, entry in outbound.items():
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(entry) in (list, tuple) and len(entry) >= 2:
if type(entry[0]) in (int, float) and type(entry[1]) == bytes and len(entry[1]) == self.TICKET_LENGTH:
rows_outbound.append((destination_hash, float(entry[0]), entry[1]))
if type(inbound) == dict:
for destination_hash, tickets in inbound.items():
if not (type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(tickets) == dict): continue
for ticket, entry in tickets.items():
if type(ticket) == bytes and len(ticket) == self.TICKET_LENGTH and type(entry) in (list, tuple) and len(entry) >= 1:
if type(entry[0]) in (int, float):
rows_inbound.append((ticket, destination_hash, float(entry[0])))
if type(last_deliveries) == dict:
for destination_hash, timestamp in last_deliveries.items():
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(timestamp) in (int, float):
rows_deliveries.append((destination_hash, float(timestamp)))
total = len(rows_outbound)+len(rows_inbound)+len(rows_deliveries)
imported = -1
with self._conn_lock:
if self._ready():
try:
self._conn.execute("BEGIN")
for i in range(0, len(rows_outbound), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?, ?, ?)", rows_outbound[i:i+self.IMPORT_CHUNK])
for i in range(0, len(rows_inbound), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?, ?, ?)", rows_inbound[i:i+self.IMPORT_CHUNK])
for i in range(0, len(rows_deliveries), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO ticket_deliveries (destination_hash, timestamp) VALUES (?, ?)", rows_deliveries[i:i+self.IMPORT_CHUNK])
self._conn.execute("COMMIT")
imported = total
except Exception as e:
RNS.log(f"Could not import available tickets file at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
try: self._conn.execute("ROLLBACK")
except Exception: pass
if imported >= 0:
try: os.replace(path, path+".imported")
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
return imported
+30 -10
View File
@@ -88,9 +88,9 @@ def apply_config():
active_configuration["peer_announce_interval"] = None active_configuration["peer_announce_interval"] = None
if "lxmf" in lxmd_config and "stamp_cost" in lxmd_config["lxmf"]: if "lxmf" in lxmd_config and "stamp_cost" in lxmd_config["lxmf"]:
active_configuration["peer_stamp_cost"] = max(1, lxmd_config["lxmf"].as_int("stamp_cost")) active_configuration["peer_stamp_cost"] = max(1, lxmd_config["lxmf"].as_float("stamp_cost"))
else: else:
active_configuration["peer_stamp_cost"] = 12 active_configuration["peer_stamp_cost"] = 12.0
if "lxmf" in lxmd_config and "delivery_transfer_max_accepted_size" in lxmd_config["lxmf"]: if "lxmf" in lxmd_config and "delivery_transfer_max_accepted_size" in lxmd_config["lxmf"]:
active_configuration["delivery_transfer_max_accepted_size"] = lxmd_config["lxmf"].as_float("delivery_transfer_max_accepted_size") active_configuration["delivery_transfer_max_accepted_size"] = lxmd_config["lxmf"].as_float("delivery_transfer_max_accepted_size")
@@ -184,28 +184,35 @@ def apply_config():
active_configuration["propagation_sync_max_accepted_size"] = 256*40 active_configuration["propagation_sync_max_accepted_size"] = 256*40
if "propagation" in lxmd_config and "propagation_stamp_cost_target" in lxmd_config["propagation"]: if "propagation" in lxmd_config and "propagation_stamp_cost_target" in lxmd_config["propagation"]:
active_configuration["propagation_stamp_cost_target"] = lxmd_config["propagation"].as_int("propagation_stamp_cost_target") active_configuration["propagation_stamp_cost_target"] = lxmd_config["propagation"].as_float("propagation_stamp_cost_target")
if active_configuration["propagation_stamp_cost_target"] < LXMF.LXMRouter.PROPAGATION_COST_MIN: if active_configuration["propagation_stamp_cost_target"] < LXMF.LXMRouter.PROPAGATION_COST_MIN:
active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST_MIN active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST_MIN
else: else:
active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST
if "propagation" in lxmd_config and "propagation_stamp_cost_flexibility" in lxmd_config["propagation"]: if "propagation" in lxmd_config and "propagation_stamp_cost_flexibility" in lxmd_config["propagation"]:
active_configuration["propagation_stamp_cost_flexibility"] = lxmd_config["propagation"].as_int("propagation_stamp_cost_flexibility") active_configuration["propagation_stamp_cost_flexibility"] = lxmd_config["propagation"].as_float("propagation_stamp_cost_flexibility")
if active_configuration["propagation_stamp_cost_flexibility"] < 0: if active_configuration["propagation_stamp_cost_flexibility"] < 0:
active_configuration["propagation_stamp_cost_flexibility"] = 0 active_configuration["propagation_stamp_cost_flexibility"] = 0
else: else:
active_configuration["propagation_stamp_cost_flexibility"] = LXMF.LXMRouter.PROPAGATION_COST_FLEX active_configuration["propagation_stamp_cost_flexibility"] = LXMF.LXMRouter.PROPAGATION_COST_FLEX
if "propagation" in lxmd_config and "propagation_stamp_throttle" in lxmd_config["propagation"]:
active_configuration["propagation_stamp_throttle"] = lxmd_config["propagation"].as_float("propagation_stamp_throttle")*60
if active_configuration["propagation_stamp_throttle"] < LXMF.LXMRouter.PN_STAMP_THROTTLE:
active_configuration["propagation_stamp_throttle"] = LXMF.LXMRouter.PN_STAMP_THROTTLE
else:
active_configuration["propagation_stamp_throttle"] = LXMF.LXMRouter.PN_STAMP_THROTTLE
if "propagation" in lxmd_config and "peering_cost" in lxmd_config["propagation"]: if "propagation" in lxmd_config and "peering_cost" in lxmd_config["propagation"]:
active_configuration["peering_cost"] = lxmd_config["propagation"].as_int("peering_cost") active_configuration["peering_cost"] = lxmd_config["propagation"].as_float("peering_cost")
if active_configuration["peering_cost"] < 0: if active_configuration["peering_cost"] < 0:
active_configuration["peering_cost"] = 0 active_configuration["peering_cost"] = 0
else: else:
active_configuration["peering_cost"] = LXMF.LXMRouter.PEERING_COST active_configuration["peering_cost"] = LXMF.LXMRouter.PEERING_COST
if "propagation" in lxmd_config and "remote_peering_cost_max" in lxmd_config["propagation"]: if "propagation" in lxmd_config and "remote_peering_cost_max" in lxmd_config["propagation"]:
active_configuration["remote_peering_cost_max"] = lxmd_config["propagation"].as_int("remote_peering_cost_max") active_configuration["remote_peering_cost_max"] = lxmd_config["propagation"].as_float("remote_peering_cost_max")
if active_configuration["remote_peering_cost_max"] < 0: if active_configuration["remote_peering_cost_max"] < 0:
active_configuration["remote_peering_cost_max"] = 0 active_configuration["remote_peering_cost_max"] = 0
else: else:
@@ -412,6 +419,7 @@ def program_setup(configdir = None, rnsconfigdir = None, run_pn = False, on_inbo
max_peers = active_configuration["max_peers"], max_peers = active_configuration["max_peers"],
static_peers = active_configuration["static_peers"], static_peers = active_configuration["static_peers"],
from_static_only = active_configuration["from_static_only"], from_static_only = active_configuration["from_static_only"],
pn_stamp_throttle = active_configuration["propagation_stamp_throttle"],
name = active_configuration["node_name"]) name = active_configuration["node_name"])
message_router.register_delivery_callback(lxmf_delivery) message_router.register_delivery_callback(lxmf_delivery)
@@ -1027,7 +1035,7 @@ autopeer_maxdepth = 6
# You can configure the target stamp cost # You can configure the target stamp cost
# required to deliver messages via this node. # required to deliver messages via this node.
# propagation_stamp_cost_target = 16 # propagation_stamp_cost_target = 16.0
# If set higher than 0, the stamp cost flexi- # If set higher than 0, the stamp cost flexi-
# bility option will make this node accept # bility option will make this node accept
@@ -1036,13 +1044,25 @@ autopeer_maxdepth = 6
# not from peers directly). This allows the # not from peers directly). This allows the
# network to gradually adjust stamp cost. # network to gradually adjust stamp cost.
# propagation_stamp_cost_flexibility = 3 # propagation_stamp_cost_flexibility = 3.0
# If a peer delivers messages with stamp costs
# not conforming to this node's targets, it'll
# be throttled, by default for 5 minutes. You
# can configure the throttle period, and for
# constrained nodes, it may be a good idea to
# set a much higher throttle time. Real LXMF
# propagation nodes will never deliver messages
# with lower stamp values than required by the
# receiving node.
# propagation_stamp_throttle = 5
# The peering_cost option configures the target # The peering_cost option configures the target
# value required for a remote node to peer with # value required for a remote node to peer with
# and deliver messages to this node. # and deliver messages to this node.
# peering_cost = 18 # peering_cost = 18.0
# You can configure the maximum peering cost # You can configure the maximum peering cost
# of remote nodes that this node will peer with. # of remote nodes that this node will peer with.
@@ -1052,7 +1072,7 @@ autopeer_maxdepth = 6
# more computation time during initial peering # more computation time during initial peering
# when generating the peering key. # when generating the peering key.
# remote_peering_cost_max = 26 # remote_peering_cost_max = 26.0
# You can tell the LXMF message router to # You can tell the LXMF message router to
# prioritise storage for one or more # prioritise storage for one or more
+1 -1
View File
@@ -1 +1 @@
__version__ = "1.2.0" __version__ = "1.3.1"
+1 -1
View File
@@ -1,2 +1,2 @@
qrcode>=7.4.2 qrcode>=7.4.2
rns>=1.0.0 rns>=1.6.0
+1 -1
View File
@@ -31,6 +31,6 @@ setuptools.setup(
'lxmd=LXMF.Utilities.lxmd:main', 'lxmd=LXMF.Utilities.lxmd:main',
] ]
}, },
install_requires=["rns>=1.5.5"], install_requires=["rns>=1.6.1"],
python_requires=">=3.7", python_requires=">=3.7",
) )