mirror of
https://github.com/markqvist/LXMF
synced 2026-11-23 07:20:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7bd3cf986d | ||
|
|
3948c9a187 | ||
|
|
d6b1b9c94d | ||
|
|
a676954116 | ||
|
|
d97c4f292e | ||
|
|
2d175a331f | ||
|
|
976305b791 | ||
|
|
a6a42eff80 | ||
|
|
96dddf1b3a | ||
|
|
c426c93cc5 | ||
|
|
1a43d93da2 | ||
|
|
575fbc9ffe | ||
|
|
c21da895b6 | ||
|
|
b172c7fcd4 | ||
|
|
61331b58d7 | ||
|
|
9ff76c0473 | ||
|
|
c9272c9218 | ||
|
|
36f0c17c8b | ||
|
|
aa406d1552 | ||
|
|
0cb771439f | ||
|
|
672d754238 | ||
|
|
0178fb0d4f | ||
|
|
19d8909b10 | ||
|
|
19f0fa7724 | ||
|
|
eefb1c8349 | ||
|
|
0e0d01a0b2 | ||
|
|
ac2c9c3a9b | ||
|
|
05f144ae50 | ||
|
|
a461fd415a | ||
|
|
ef1c3331ad | ||
|
|
e1a56be5c1 | ||
|
|
cf6fc4a510 | ||
|
|
67d21deff9 | ||
|
|
efc15bde26 | ||
|
|
b5d6ed3d9b | ||
|
|
7789e0bc26 | ||
|
|
0e2f0fb090 | ||
|
|
19696d206d | ||
|
|
9193aa5e02 | ||
|
|
bbf1eda3b0 | ||
|
|
d8e2e2a45f | ||
|
|
0fc15e6054 | ||
|
|
717240c8d4 | ||
|
|
453772859d |
No files matched your search
+17
-17
@@ -2,8 +2,7 @@ import time
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
from .LXMF import APP_NAME, stamp_cost_from_app_data
|
||||
|
||||
from .LXMF import APP_NAME, stamp_cost_from_app_data, pn_announce_data_is_valid
|
||||
from .LXMessage import LXMessage
|
||||
|
||||
class LXMFDeliveryAnnounceHandler:
|
||||
@@ -15,7 +14,7 @@ class LXMFDeliveryAnnounceHandler:
|
||||
def received_announce(self, destination_hash, announced_identity, app_data):
|
||||
for lxmessage in self.lxmrouter.pending_outbound:
|
||||
if destination_hash == lxmessage.destination_hash:
|
||||
if lxmessage.method == LXMessage.DIRECT:
|
||||
if lxmessage.method == LXMessage.DIRECT or lxmessage.method == LXMessage.OPPORTUNISTIC:
|
||||
lxmessage.next_delivery_attempt = time.time()
|
||||
|
||||
while self.lxmrouter.processing_outbound:
|
||||
@@ -40,23 +39,24 @@ class LXMFPropagationAnnounceHandler:
|
||||
def received_announce(self, destination_hash, announced_identity, app_data):
|
||||
try:
|
||||
if type(app_data) == bytes:
|
||||
data = msgpack.unpackb(app_data)
|
||||
|
||||
if self.lxmrouter.propagation_node and self.lxmrouter.autopeer:
|
||||
node_timebase = data[1]
|
||||
propagation_transfer_limit = None
|
||||
if len(data) >= 3:
|
||||
try:
|
||||
propagation_transfer_limit = float(data[2])
|
||||
except:
|
||||
propagation_transfer_limit = None
|
||||
data = msgpack.unpackb(app_data)
|
||||
|
||||
if data[0] == True:
|
||||
if RNS.Transport.hops_to(destination_hash) <= self.lxmrouter.autopeer_maxdepth:
|
||||
self.lxmrouter.peer(destination_hash, node_timebase, propagation_transfer_limit)
|
||||
if pn_announce_data_is_valid(data):
|
||||
node_timebase = data[1]
|
||||
propagation_transfer_limit = None
|
||||
if len(data) >= 3:
|
||||
try:
|
||||
propagation_transfer_limit = float(data[2])
|
||||
except:
|
||||
propagation_transfer_limit = None
|
||||
|
||||
elif data[0] == False:
|
||||
self.lxmrouter.unpeer(destination_hash, node_timebase)
|
||||
if data[0] == True:
|
||||
if RNS.Transport.hops_to(destination_hash) <= self.lxmrouter.autopeer_maxdepth:
|
||||
self.lxmrouter.peer(destination_hash, node_timebase, propagation_transfer_limit)
|
||||
|
||||
elif data[0] == False:
|
||||
self.lxmrouter.unpeer(destination_hash, node_timebase)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while evaluating propagation node announce, ignoring announce.", RNS.LOG_DEBUG)
|
||||
|
||||
+40
-4
@@ -18,6 +18,8 @@ FIELD_RESULTS = 0x0A
|
||||
FIELD_GROUP = 0x0B
|
||||
FIELD_TICKET = 0x0C
|
||||
FIELD_EVENT = 0x0D
|
||||
FIELD_RNR_REFS = 0x0E
|
||||
FIELD_RENDERER = 0x0F
|
||||
|
||||
# For usecases such as including custom data structures,
|
||||
# embedding or encapsulating other data types or protocols
|
||||
@@ -76,12 +78,25 @@ AM_OPUS_LOSSLESS = 0x19
|
||||
# determine it itself based on the included data.
|
||||
AM_CUSTOM = 0xFF
|
||||
|
||||
# Message renderer specifications for FIELD_RENDERER.
|
||||
# The renderer specification is completely optional,
|
||||
# and only serves as an indication to the receiving
|
||||
# client on how to render the message contents. It is
|
||||
# not mandatory to implement, either on sending or
|
||||
# receiving sides, but is the recommended way to
|
||||
# signal how to render a message, if non-plaintext
|
||||
# formatting is used.
|
||||
RENDERER_PLAIN = 0x00
|
||||
RENDERER_MICRON = 0x01
|
||||
RENDERER_MARKDOWN = 0x02
|
||||
RENDERER_BBCODE = 0x03
|
||||
|
||||
##########################################################
|
||||
# The following helper functions makes it easier to #
|
||||
# handle and operate on LXMF data in client programs #
|
||||
##########################################################
|
||||
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
def display_name_from_app_data(app_data=None):
|
||||
if app_data == None:
|
||||
@@ -103,8 +118,8 @@ def display_name_from_app_data(app_data=None):
|
||||
try:
|
||||
decoded = dn.decode("utf-8")
|
||||
return decoded
|
||||
except:
|
||||
RNS.log("Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
# Original announce format
|
||||
@@ -112,7 +127,7 @@ def display_name_from_app_data(app_data=None):
|
||||
return app_data.decode("utf-8")
|
||||
|
||||
def stamp_cost_from_app_data(app_data=None):
|
||||
if app_data == None:
|
||||
if app_data == None or app_data == b"":
|
||||
return None
|
||||
else:
|
||||
# Version 0.5.0+ announce format
|
||||
@@ -126,4 +141,25 @@ def stamp_cost_from_app_data(app_data=None):
|
||||
|
||||
# Original announce format
|
||||
else:
|
||||
return None
|
||||
return None
|
||||
|
||||
def pn_announce_data_is_valid(data):
|
||||
try:
|
||||
if type(data) == bytes:
|
||||
data = msgpack.unpackb(data)
|
||||
|
||||
if len(data) < 3:
|
||||
raise ValueError("Invalid announce data: Insufficient peer data")
|
||||
else:
|
||||
if data[0] != True and data[0] != False:
|
||||
raise ValueError("Invalid announce data: Indeterminate propagation node status")
|
||||
try:
|
||||
int(data[1])
|
||||
except:
|
||||
raise ValueError("Invalid announce data: Could not decode peer timebase")
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not validate propagation node announce data: {e}", RNS.LOG_DEBUG)
|
||||
return False
|
||||
|
||||
return True
|
||||
+21
-4
@@ -47,6 +47,11 @@ class LXMPeer:
|
||||
peer.link_establishment_rate = dictionary["link_establishment_rate"]
|
||||
else:
|
||||
peer.link_establishment_rate = 0
|
||||
|
||||
if "sync_transfer_rate" in dictionary:
|
||||
peer.sync_transfer_rate = dictionary["sync_transfer_rate"]
|
||||
else:
|
||||
peer.sync_transfer_rate = 0
|
||||
|
||||
if "propagation_transfer_limit" in dictionary:
|
||||
try:
|
||||
@@ -73,6 +78,7 @@ class LXMPeer:
|
||||
dictionary["last_heard"] = self.last_heard
|
||||
dictionary["destination_hash"] = self.destination_hash
|
||||
dictionary["link_establishment_rate"] = self.link_establishment_rate
|
||||
dictionary["sync_transfer_rate"] = self.sync_transfer_rate
|
||||
dictionary["propagation_transfer_limit"] = self.propagation_transfer_limit
|
||||
|
||||
handled_ids = []
|
||||
@@ -96,6 +102,7 @@ class LXMPeer:
|
||||
self.sync_backoff = 0
|
||||
self.peering_timebase = 0
|
||||
self.link_establishment_rate = 0
|
||||
self.sync_transfer_rate = 0
|
||||
self.propagation_transfer_limit = None
|
||||
|
||||
self.link = None
|
||||
@@ -108,7 +115,10 @@ class LXMPeer:
|
||||
self.router = router
|
||||
self.destination_hash = destination_hash
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
else:
|
||||
RNS.log(f"Could not recall identity for LXMF propagation peer {RNS.prettyhexrep(self.destination_hash)}, will retry identity resolution on next sync", RNS.LOG_WARNING)
|
||||
|
||||
def sync(self):
|
||||
RNS.log("Initiating LXMF Propagation Node sync with peer "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_DEBUG)
|
||||
@@ -126,9 +136,10 @@ class LXMPeer:
|
||||
else:
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
if self.identity != None:
|
||||
if self.destination != None:
|
||||
if len(self.unhandled_messages) > 0:
|
||||
if self.state == LXMPeer.IDLE:
|
||||
RNS.log("Establishing link for sync to peer "+RNS.prettyhexrep(self.destination_hash)+"...", RNS.LOG_DEBUG)
|
||||
@@ -253,6 +264,7 @@ class LXMPeer:
|
||||
data = msgpack.packb([time.time(), lxm_list])
|
||||
resource = RNS.Resource(data, self.link, callback = self.resource_concluded)
|
||||
resource.transferred_messages = wanted_message_ids
|
||||
resource.sync_transfer_started = time.time()
|
||||
self.state = LXMPeer.RESOURCE_TRANSFERRING
|
||||
|
||||
else:
|
||||
@@ -285,7 +297,12 @@ class LXMPeer:
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
RNS.log("Sync to peer "+RNS.prettyhexrep(self.destination_hash)+" completed", RNS.LOG_DEBUG)
|
||||
rate_str = ""
|
||||
if hasattr(resource, "sync_transfer_started") and resource.sync_transfer_started:
|
||||
self.sync_transfer_rate = (resource.get_transfer_size()*8)/(time.time()-resource.sync_transfer_started)
|
||||
rate_str = f" at {RNS.prettyspeed(self.sync_transfer_rate)}"
|
||||
|
||||
RNS.log("Sync to peer "+RNS.prettyhexrep(self.destination_hash)+" completed"+rate_str, RNS.LOG_DEBUG)
|
||||
self.alive = True
|
||||
self.last_heard = time.time()
|
||||
|
||||
|
||||
+224
-55
@@ -16,11 +16,14 @@ from .LXMessage import LXMessage
|
||||
from .Handlers import LXMFDeliveryAnnounceHandler
|
||||
from .Handlers import LXMFPropagationAnnounceHandler
|
||||
|
||||
import LXMF.LXStamper as LXStamper
|
||||
|
||||
class LXMRouter:
|
||||
MAX_DELIVERY_ATTEMPTS = 5
|
||||
PROCESSING_INTERVAL = 4
|
||||
DELIVERY_RETRY_WAIT = 10
|
||||
PATH_REQUEST_WAIT = 7
|
||||
MAX_PATHLESS_TRIES = 1
|
||||
LINK_MAX_INACTIVITY = 10*60
|
||||
P_LINK_MAX_INACTIVITY = 3*60
|
||||
|
||||
@@ -66,6 +69,7 @@ class LXMRouter:
|
||||
self.pending_outbound = []
|
||||
self.failed_outbound = []
|
||||
self.direct_links = {}
|
||||
self.backchannel_links = {}
|
||||
self.delivery_destinations = {}
|
||||
|
||||
self.prioritised_list = []
|
||||
@@ -117,7 +121,6 @@ class LXMRouter:
|
||||
identity = RNS.Identity()
|
||||
|
||||
self.identity = identity
|
||||
self.lxmf_query_destination = RNS.Destination(None, RNS.Destination.IN, RNS.Destination.PLAIN, APP_NAME, "query")
|
||||
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
if autopeer != None:
|
||||
@@ -142,19 +145,38 @@ class LXMRouter:
|
||||
if os.path.isfile(self.storagepath+"/local_deliveries"):
|
||||
locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb")
|
||||
data = locally_delivered_file.read()
|
||||
self.locally_delivered_transient_ids = msgpack.unpackb(data)
|
||||
locally_delivered_file.close()
|
||||
|
||||
if os.path.isfile(self.storagepath+"/locally_processed"):
|
||||
locally_processed_file = open(self.storagepath+"/locally_processed", "rb")
|
||||
data = locally_processed_file.read()
|
||||
self.locally_processed_transient_ids = msgpack.unpackb(data)
|
||||
locally_processed_file.close()
|
||||
|
||||
self.clean_transient_id_caches()
|
||||
self.locally_delivered_transient_ids = msgpack.unpackb(data)
|
||||
if not type(self.locally_delivered_transient_ids) == dict:
|
||||
RNS.log("Invalid data format for loaded locally delivered transient IDs, recreating...", RNS.LOG_ERROR)
|
||||
self.locally_delivered_transient_ids = {}
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not load locally delivered message ID cache from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
self.locally_delivered_transient_ids = {}
|
||||
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/locally_processed"):
|
||||
locally_processed_file = open(self.storagepath+"/locally_processed", "rb")
|
||||
data = locally_processed_file.read()
|
||||
locally_processed_file.close()
|
||||
self.locally_processed_transient_ids = msgpack.unpackb(data)
|
||||
if not type(self.locally_processed_transient_ids) == dict:
|
||||
RNS.log("Invalid data format for loaded locally processed transient IDs, recreating...", RNS.LOG_ERROR)
|
||||
self.locally_processed_transient_ids = {}
|
||||
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not load locally processed message ID cache from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
self.locally_processed_transient_ids = {}
|
||||
|
||||
try:
|
||||
self.clean_transient_id_caches()
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not clean transient ID caches. The contained exception was : "+str(e), RNS.LOG_ERROR)
|
||||
self.locally_delivered_transient_ids = {}
|
||||
self.locally_processed_transient_ids = {}
|
||||
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/outbound_stamp_costs"):
|
||||
@@ -162,6 +184,9 @@ class LXMRouter:
|
||||
with open(self.storagepath+"/outbound_stamp_costs", "rb") as outbound_stamp_cost_file:
|
||||
data = outbound_stamp_cost_file.read()
|
||||
self.outbound_stamp_costs = msgpack.unpackb(data)
|
||||
if not type(self.outbound_stamp_costs) == dict:
|
||||
RNS.log("Invalid data format for loaded outbound stamp costs, recreating...", RNS.LOG_ERROR)
|
||||
self.outbound_stamp_costs = {}
|
||||
|
||||
self.clean_outbound_stamp_costs()
|
||||
self.save_outbound_stamp_costs()
|
||||
@@ -275,19 +300,31 @@ class LXMRouter:
|
||||
else:
|
||||
return None
|
||||
|
||||
def set_active_propagation_node(self, destination_hash):
|
||||
self.set_outbound_propagation_node(destination_hash)
|
||||
# self.set_inbound_propagation_node(destination_hash)
|
||||
|
||||
def set_outbound_propagation_node(self, destination_hash):
|
||||
if len(destination_hash) != RNS.Identity.TRUNCATED_HASHLENGTH//8 or type(destination_hash) != bytes:
|
||||
raise ValueError("Invalid destination hash for outbound propagation node")
|
||||
else:
|
||||
self.outbound_propagation_node = destination_hash
|
||||
if self.outbound_propagation_link != None:
|
||||
if self.outbound_propagation_link.destination.hash != destination_hash:
|
||||
self.outbound_propagation_link.teardown()
|
||||
self.outbound_propagation_link = None
|
||||
if self.outbound_propagation_node != destination_hash:
|
||||
self.outbound_propagation_node = destination_hash
|
||||
if self.outbound_propagation_link != None:
|
||||
if self.outbound_propagation_link.destination.hash != destination_hash:
|
||||
self.outbound_propagation_link.teardown()
|
||||
self.outbound_propagation_link = None
|
||||
|
||||
def get_outbound_propagation_node(self):
|
||||
return self.outbound_propagation_node
|
||||
|
||||
def set_inbound_propagation_node(self, destination_hash):
|
||||
# TODO: Implement
|
||||
raise NotImplementedError("Inbound/outbound propagation node differentiation is currently not implemented")
|
||||
|
||||
def get_inbound_propagation_node(self):
|
||||
return self.get_outbound_propagation_node()
|
||||
|
||||
def set_retain_node_lxms(self, retain):
|
||||
if retain == True:
|
||||
self.retain_synced_on_node = True
|
||||
@@ -338,6 +375,7 @@ class LXMRouter:
|
||||
if self.outbound_propagation_node != None:
|
||||
if self.outbound_propagation_link != None and self.outbound_propagation_link.status == RNS.Link.ACTIVE:
|
||||
self.propagation_transfer_state = LXMRouter.PR_LINK_ESTABLISHED
|
||||
RNS.log("Requesting message list from propagation node", RNS.LOG_DEBUG)
|
||||
self.outbound_propagation_link.identify(identity)
|
||||
self.outbound_propagation_link.request(
|
||||
LXMPeer.MESSAGE_GET_PATH,
|
||||
@@ -367,7 +405,6 @@ class LXMRouter:
|
||||
self.propagation_transfer_state = LXMRouter.PR_PATH_REQUESTED
|
||||
self.request_messages_path_job()
|
||||
else:
|
||||
# TODO: Remove at some point
|
||||
RNS.log("Waiting for propagation node link to become active", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Cannot request LXMF propagation node sync, no default propagation node configured", RNS.LOG_WARNING)
|
||||
@@ -536,6 +573,12 @@ class LXMRouter:
|
||||
def information_storage_size(self):
|
||||
pass
|
||||
|
||||
def delivery_link_available(self, destination_hash):
|
||||
if destination_hash in self.direct_links or destination_hash in self.backchannel_links:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
### Utility & Maintenance #############################
|
||||
#######################################################
|
||||
@@ -625,7 +668,7 @@ class LXMRouter:
|
||||
removed_entries = []
|
||||
for transient_id in self.locally_delivered_transient_ids:
|
||||
timestamp = self.locally_delivered_transient_ids[transient_id]
|
||||
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*1.25:
|
||||
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*6.0:
|
||||
removed_entries.append(transient_id)
|
||||
|
||||
for transient_id in removed_entries:
|
||||
@@ -635,7 +678,7 @@ class LXMRouter:
|
||||
removed_entries = []
|
||||
for transient_id in self.locally_processed_transient_ids:
|
||||
timestamp = self.locally_processed_transient_ids[transient_id]
|
||||
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*1.25:
|
||||
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*6.0:
|
||||
removed_entries.append(transient_id)
|
||||
|
||||
for transient_id in removed_entries:
|
||||
@@ -836,9 +879,8 @@ class LXMRouter:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
os.makedirs(self.storagepath)
|
||||
|
||||
locally_delivered_file = open(self.storagepath+"/local_deliveries", "wb")
|
||||
locally_delivered_file.write(msgpack.packb(self.locally_delivered_transient_ids))
|
||||
locally_delivered_file.close()
|
||||
with open(self.storagepath+"/local_deliveries", "wb") as locally_delivered_file:
|
||||
locally_delivered_file.write(msgpack.packb(self.locally_delivered_transient_ids))
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not save locally delivered message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
@@ -848,9 +890,8 @@ class LXMRouter:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
os.makedirs(self.storagepath)
|
||||
|
||||
locally_processed_file = open(self.storagepath+"/locally_processed", "wb")
|
||||
locally_processed_file.write(msgpack.packb(self.locally_processed_transient_ids))
|
||||
locally_processed_file.close()
|
||||
with open(self.storagepath+"/locally_processed", "wb") as locally_processed_file:
|
||||
locally_processed_file.write(msgpack.packb(self.locally_processed_transient_ids))
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not save locally processed transient ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
@@ -893,7 +934,6 @@ class LXMRouter:
|
||||
expired_outbound.append(destination_hash)
|
||||
|
||||
for destination_hash in expired_outbound:
|
||||
RNS.log(f"Cleaning expired outbound ticket for {destination_hash}") # TODO: Remove
|
||||
self.available_tickets["outbound"].pop(destination_hash)
|
||||
|
||||
# Clean inbound tickets
|
||||
@@ -906,8 +946,7 @@ class LXMRouter:
|
||||
expired_inbound.append(inbound_ticket)
|
||||
|
||||
for inbound_ticket in expired_inbound:
|
||||
RNS.log(f"Cleaning expired inbound ticket for {destination_hash}") # TODO: Remove
|
||||
self.available_tickets["inbound"][destination_hash].pop(destination_hash)
|
||||
self.available_tickets["inbound"][destination_hash].pop(inbound_ticket)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while cleaning available tickets. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
@@ -916,7 +955,6 @@ class LXMRouter:
|
||||
def save_available_tickets(self):
|
||||
with self.ticket_file_lock:
|
||||
try:
|
||||
RNS.log("Saving available tickets...", RNS.LOG_DEBUG) # TODO: Remove
|
||||
if not os.path.isdir(self.storagepath):
|
||||
os.makedirs(self.storagepath)
|
||||
|
||||
@@ -1109,24 +1147,32 @@ class LXMRouter:
|
||||
wants = []
|
||||
if len(request_receipt.response) > 0:
|
||||
for transient_id in request_receipt.response:
|
||||
if not self.retain_synced_on_node and self.has_message(transient_id):
|
||||
haves.append(transient_id)
|
||||
if self.has_message(transient_id):
|
||||
if not self.retain_synced_on_node:
|
||||
haves.append(transient_id)
|
||||
else:
|
||||
if self.propagation_transfer_max_messages == LXMRouter.PR_ALL_MESSAGES or len(wants) < self.propagation_transfer_max_messages:
|
||||
wants.append(transient_id)
|
||||
|
||||
ms = "" if len(wants) == 1 else "s"
|
||||
RNS.log(f"Requesting {len(wants)} message{ms} from propagation node", RNS.LOG_DEBUG)
|
||||
request_receipt.link.request(
|
||||
LXMPeer.MESSAGE_GET_PATH,
|
||||
[wants, haves, self.delivery_per_transfer_limit],
|
||||
response_callback=self.message_get_response,
|
||||
failed_callback=self.message_get_failed,
|
||||
progress_callback=self.message_get_progress
|
||||
)
|
||||
progress_callback=self.message_get_progress)
|
||||
|
||||
else:
|
||||
self.propagation_transfer_state = LXMRouter.PR_COMPLETE
|
||||
self.propagation_transfer_progress = 1.0
|
||||
self.propagation_transfer_last_result = 0
|
||||
|
||||
else:
|
||||
RNS.log("Invalid message list data received from propagation node", RNS.LOG_DEBUG)
|
||||
if self.outbound_propagation_link != None:
|
||||
self.outbound_propagation_link.teardown()
|
||||
|
||||
def message_get_response(self, request_receipt):
|
||||
if request_receipt.response == LXMPeer.ERROR_NO_IDENTITY:
|
||||
RNS.log("Propagation node indicated missing identification on get request, tearing down link.", RNS.LOG_DEBUG)
|
||||
@@ -1190,8 +1236,36 @@ class LXMRouter:
|
||||
else:
|
||||
return False
|
||||
|
||||
def cancel_outbound(self, message_id):
|
||||
try:
|
||||
if message_id in self.pending_deferred_stamps:
|
||||
lxm = self.pending_deferred_stamps[message_id]
|
||||
RNS.log(f"Cancelling deferred stamp generation for {lxm}", RNS.LOG_DEBUG)
|
||||
lxm.state = LXMessage.CANCELLED
|
||||
LXStamper.cancel_work(message_id)
|
||||
|
||||
lxmessage = None
|
||||
for lxm in self.pending_outbound:
|
||||
if lxm.message_id == message_id:
|
||||
lxmessage = lxm
|
||||
|
||||
if lxmessage != None:
|
||||
lxmessage.state = LXMessage.CANCELLED
|
||||
if lxmessage in self.pending_outbound:
|
||||
RNS.log(f"Cancelling {lxmessage} in outbound queue", RNS.LOG_DEBUG)
|
||||
if lxmessage.representation == LXMessage.RESOURCE:
|
||||
if lxmessage.resource_representation != None:
|
||||
lxmessage.resource_representation.cancel()
|
||||
|
||||
self.process_outbound()
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"An error occurred while cancelling {lxmessage}: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def handle_outbound(self, lxmessage):
|
||||
destination_hash = lxmessage.get_destination().hash
|
||||
|
||||
if lxmessage.stamp_cost == None:
|
||||
if destination_hash in self.outbound_stamp_costs:
|
||||
stamp_cost = self.outbound_stamp_costs[destination_hash][1]
|
||||
@@ -1217,18 +1291,27 @@ class LXMRouter:
|
||||
if not lxmessage.packed:
|
||||
lxmessage.pack()
|
||||
|
||||
lxmessage.determine_transport_encryption()
|
||||
unknown_path_requested = False
|
||||
if not RNS.Transport.has_path(destination_hash) and lxmessage.method == LXMessage.OPPORTUNISTIC:
|
||||
RNS.log(f"Pre-emptively requesting unknown path for opportunistic {lxmessage}", RNS.LOG_DEBUG)
|
||||
RNS.Transport.request_path(destination_hash)
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
|
||||
unknown_path_requested = True
|
||||
|
||||
while self.processing_outbound:
|
||||
time.sleep(0.1)
|
||||
lxmessage.determine_transport_encryption()
|
||||
|
||||
if lxmessage.defer_stamp and lxmessage.stamp_cost == None:
|
||||
RNS.log(f"Deferred stamp generation was requested for {lxmessage}, but no stamp is required, processing immediately", RNS.LOG_DEBUG)
|
||||
lxmessage.defer_stamp = False
|
||||
|
||||
if not lxmessage.defer_stamp:
|
||||
while not unknown_path_requested and self.processing_outbound:
|
||||
time.sleep(0.05)
|
||||
|
||||
self.pending_outbound.append(lxmessage)
|
||||
self.process_outbound()
|
||||
if not unknown_path_requested:
|
||||
self.process_outbound()
|
||||
|
||||
else:
|
||||
self.pending_deferred_stamps[lxmessage.message_id] = lxmessage
|
||||
|
||||
@@ -1300,7 +1383,7 @@ class LXMRouter:
|
||||
else:
|
||||
RNS.log(f"Received {message} with invalid stamp, but allowing anyway, since stamp enforcement is disabled", RNS.LOG_NOTICE)
|
||||
else:
|
||||
RNS.log(f"Received {message} valid stamp", RNS.LOG_DEBUG)
|
||||
RNS.log(f"Received {message} with valid stamp", RNS.LOG_DEBUG)
|
||||
|
||||
if phy_stats != None:
|
||||
if "rssi" in phy_stats: message.rssi = phy_stats["rssi"]
|
||||
@@ -1381,6 +1464,7 @@ class LXMRouter:
|
||||
link.set_resource_callback(self.delivery_resource_advertised)
|
||||
link.set_resource_started_callback(self.resource_transfer_began)
|
||||
link.set_resource_concluded_callback(self.delivery_resource_concluded)
|
||||
link.set_remote_identified_callback(self.delivery_remote_identified)
|
||||
|
||||
def delivery_link_closed(self, link):
|
||||
pass
|
||||
@@ -1407,6 +1491,11 @@ class LXMRouter:
|
||||
phy_stats = {"rssi": resource.link.rssi, "snr": resource.link.snr, "q": resource.link.q}
|
||||
self.lxmf_delivery(resource.data.read(), resource.link.type, phy_stats=phy_stats, ratchet_id=ratchet_id, method=LXMessage.DIRECT)
|
||||
|
||||
def delivery_remote_identified(self, link, identity):
|
||||
destination_hash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", identity)
|
||||
self.backchannel_links[destination_hash] = link
|
||||
RNS.log(f"Backchannel became available for {RNS.prettyhexrep(destination_hash)} on delivery link {link}", RNS.LOG_DEBUG)
|
||||
|
||||
|
||||
### Peer Sync & Propagation ###########################
|
||||
#######################################################
|
||||
@@ -1464,12 +1553,12 @@ class LXMRouter:
|
||||
if len(waiting_peers) > 0:
|
||||
fastest_peers = sorted(
|
||||
waiting_peers,
|
||||
key=lambda p: p.link_establishment_rate,
|
||||
key=lambda p: p.sync_transfer_rate,
|
||||
reverse=True
|
||||
)[0:min(LXMRouter.FASTEST_N_RANDOM_POOL, len(waiting_peers))]
|
||||
peer_pool.extend(fastest_peers)
|
||||
|
||||
unknown_speed_peers = [p for p in waiting_peers if p.link_establishment_rate == 0]
|
||||
unknown_speed_peers = [p for p in waiting_peers if p.sync_transfer_rate == 0]
|
||||
if len(unknown_speed_peers) > 0:
|
||||
peer_pool.extend(
|
||||
unknown_speed_peers[
|
||||
@@ -1688,7 +1777,9 @@ class LXMRouter:
|
||||
|
||||
self.failed_outbound.append(lxmessage)
|
||||
|
||||
lxmessage.state = LXMessage.FAILED
|
||||
if lxmessage.state != LXMessage.REJECTED:
|
||||
lxmessage.state = LXMessage.FAILED
|
||||
|
||||
if lxmessage.failed_callback != None and callable(lxmessage.failed_callback):
|
||||
lxmessage.failed_callback(lxmessage)
|
||||
|
||||
@@ -1709,6 +1800,15 @@ class LXMRouter:
|
||||
selected_message_id = message_id
|
||||
|
||||
if selected_lxm != None:
|
||||
if selected_lxm.state == LXMessage.CANCELLED:
|
||||
RNS.log(f"Message cancelled during deferred stamp generation for {selected_lxm}.", RNS.LOG_DEBUG)
|
||||
selected_lxm.stamp_generation_failed = True
|
||||
self.pending_deferred_stamps.pop(selected_message_id)
|
||||
if selected_lxm.failed_callback != None and callable(selected_lxm.failed_callback):
|
||||
selected_lxm.failed_callback(lxmessage)
|
||||
|
||||
return
|
||||
|
||||
RNS.log(f"Starting stamp generation for {selected_lxm}...", RNS.LOG_DEBUG)
|
||||
generated_stamp = selected_lxm.get_stamp()
|
||||
if generated_stamp:
|
||||
@@ -1720,10 +1820,17 @@ class LXMRouter:
|
||||
self.pending_outbound.append(selected_lxm)
|
||||
RNS.log(f"Stamp generation completed for {selected_lxm}", RNS.LOG_DEBUG)
|
||||
else:
|
||||
RNS.log(f"Deferred stamp generation did not succeed. Failing {selected_lxm}.", RNS.LOG_ERROR)
|
||||
selected_lxm.stamp_generation_failed = True
|
||||
self.pending_deferred_stamps.pop(selected_message_id)
|
||||
self.fail_message(selected_lxm)
|
||||
if selected_lxm.state == LXMessage.CANCELLED:
|
||||
RNS.log(f"Message cancelled during deferred stamp generation for {selected_lxm}.", RNS.LOG_DEBUG)
|
||||
selected_lxm.stamp_generation_failed = True
|
||||
self.pending_deferred_stamps.pop(selected_message_id)
|
||||
if selected_lxm.failed_callback != None and callable(selected_lxm.failed_callback):
|
||||
selected_lxm.failed_callback(lxmessage)
|
||||
else:
|
||||
RNS.log(f"Deferred stamp generation did not succeed. Failing {selected_lxm}.", RNS.LOG_ERROR)
|
||||
selected_lxm.stamp_generation_failed = True
|
||||
self.pending_deferred_stamps.pop(selected_message_id)
|
||||
self.fail_message(selected_lxm)
|
||||
|
||||
|
||||
def process_outbound(self, sender = None):
|
||||
@@ -1734,16 +1841,46 @@ class LXMRouter:
|
||||
if lxmessage.state == LXMessage.DELIVERED:
|
||||
RNS.log("Delivery has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
|
||||
# Udate ticket delivery stats
|
||||
if lxmessage.include_ticket and FIELD_TICKET in lxmessage.fields:
|
||||
RNS.log(f"Updating latest ticket delivery for {RNS.prettyhexrep(lxmessage.destination_hash)}", RNS.LOG_DEBUG)
|
||||
self.available_tickets["last_deliveries"][lxmessage.destination_hash] = time.time()
|
||||
self.save_available_tickets()
|
||||
|
||||
# Prepare link for backchannel communications
|
||||
delivery_destination_hash = lxmessage.get_destination().hash
|
||||
if lxmessage.method == LXMessage.DIRECT and delivery_destination_hash in self.direct_links:
|
||||
direct_link = self.direct_links[delivery_destination_hash]
|
||||
if not hasattr(direct_link, "backchannel_identified") or direct_link.backchannel_identified == False:
|
||||
if direct_link.initiator == True:
|
||||
source_destination_hash = lxmessage.get_source().hash
|
||||
if source_destination_hash in self.delivery_destinations:
|
||||
backchannel_identity = self.delivery_destinations[source_destination_hash].identity
|
||||
backchannel_desthash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", backchannel_identity)
|
||||
direct_link.identify(backchannel_identity)
|
||||
direct_link.backchannel_identified = True
|
||||
self.delivery_link_established(direct_link)
|
||||
RNS.log(f"Performed backchannel identification as {RNS.prettyhexrep(backchannel_desthash)} on {direct_link}", RNS.LOG_DEBUG)
|
||||
|
||||
elif lxmessage.method == LXMessage.PROPAGATED and lxmessage.state == LXMessage.SENT:
|
||||
RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
|
||||
elif lxmessage.state == LXMessage.CANCELLED:
|
||||
RNS.log("Cancellation requested for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
if lxmessage.failed_callback != None and callable(lxmessage.failed_callback):
|
||||
lxmessage.failed_callback(lxmessage)
|
||||
|
||||
elif lxmessage.state == LXMessage.REJECTED:
|
||||
RNS.log("Receiver rejected "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
if lxmessage.failed_callback != None and callable(lxmessage.failed_callback):
|
||||
lxmessage.failed_callback(lxmessage)
|
||||
|
||||
else:
|
||||
RNS.log("Starting outbound processing for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
RNS.log("Outbound processing for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
|
||||
if lxmessage.progress == None or lxmessage.progress < 0.01:
|
||||
lxmessage.progress = 0.01
|
||||
@@ -1751,11 +1888,28 @@ class LXMRouter:
|
||||
# Outbound handling for opportunistic messages
|
||||
if lxmessage.method == LXMessage.OPPORTUNISTIC:
|
||||
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
|
||||
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
|
||||
if lxmessage.delivery_attempts >= LXMRouter.MAX_PATHLESS_TRIES and not RNS.Transport.has_path(lxmessage.get_destination().hash):
|
||||
RNS.log(f"Requesting path to {RNS.prettyhexrep(lxmessage.get_destination().hash)} after {lxmessage.delivery_attempts} pathless tries for {lxmessage}", RNS.LOG_DEBUG)
|
||||
lxmessage.delivery_attempts += 1
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts)+" for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
lxmessage.send()
|
||||
RNS.Transport.request_path(lxmessage.get_destination().hash)
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
|
||||
lxmessage.progress = 0.01
|
||||
elif lxmessage.delivery_attempts == LXMRouter.MAX_PATHLESS_TRIES+1 and RNS.Transport.has_path(lxmessage.get_destination().hash):
|
||||
RNS.log(f"Opportunistic delivery for {lxmessage} still unsuccessful after {lxmessage.delivery_attempts} attempts, trying to rediscover path to {RNS.prettyhexrep(lxmessage.get_destination().hash)}", RNS.LOG_DEBUG)
|
||||
lxmessage.delivery_attempts += 1
|
||||
RNS.Reticulum.get_instance().drop_path(lxmessage.get_destination().hash)
|
||||
def rediscover_job():
|
||||
time.sleep(0.5)
|
||||
RNS.Transport.request_path(lxmessage.get_destination().hash)
|
||||
threading.Thread(target=rediscover_job, daemon=True).start()
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
|
||||
lxmessage.progress = 0.01
|
||||
else:
|
||||
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
|
||||
lxmessage.delivery_attempts += 1
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts)+" for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
lxmessage.send()
|
||||
else:
|
||||
RNS.log("Max delivery attempts reached for oppertunistic "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
self.fail_message(lxmessage)
|
||||
@@ -1765,16 +1919,28 @@ class LXMRouter:
|
||||
elif lxmessage.method == LXMessage.DIRECT:
|
||||
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
|
||||
delivery_destination_hash = lxmessage.get_destination().hash
|
||||
|
||||
direct_link = None
|
||||
|
||||
if delivery_destination_hash in self.direct_links:
|
||||
# A link already exists, so we'll try to use it
|
||||
# to deliver the message
|
||||
# An established direct link already exists to
|
||||
# the destination, so we'll try to use it for
|
||||
# delivering the message
|
||||
direct_link = self.direct_links[delivery_destination_hash]
|
||||
RNS.log(f"Using available direct link {direct_link} to {RNS.prettyhexrep(delivery_destination_hash)}", RNS.LOG_DEBUG)
|
||||
|
||||
elif delivery_destination_hash in self.backchannel_links:
|
||||
# An established backchannel link exists to
|
||||
# the destination, so we'll try to use it for
|
||||
# delivering the message
|
||||
direct_link = self.backchannel_links[delivery_destination_hash]
|
||||
RNS.log(f"Using available backchannel link {direct_link} to {RNS.prettyhexrep(delivery_destination_hash)}", RNS.LOG_DEBUG)
|
||||
|
||||
if direct_link != None:
|
||||
if direct_link.status == RNS.Link.ACTIVE:
|
||||
if lxmessage.progress == None or lxmessage.progress < 0.05:
|
||||
lxmessage.progress = 0.05
|
||||
if lxmessage.state != LXMessage.SENDING:
|
||||
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" on link "+str(direct_link), RNS.LOG_DEBUG)
|
||||
lxmessage.set_delivery_destination(direct_link)
|
||||
lxmessage.send()
|
||||
else:
|
||||
@@ -1796,7 +1962,10 @@ class LXMRouter:
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
|
||||
|
||||
lxmessage.set_delivery_destination(None)
|
||||
self.direct_links.pop(delivery_destination_hash)
|
||||
if delivery_destination_hash in self.direct_links:
|
||||
self.direct_links.pop(delivery_destination_hash)
|
||||
if delivery_destination_hash in self.backchannel_links:
|
||||
self.backchannel_links.pop(delivery_destination_hash)
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
else:
|
||||
# Simply wait for the link to become active or close
|
||||
@@ -1820,7 +1989,7 @@ class LXMRouter:
|
||||
RNS.log("No path known for delivery attempt "+str(lxmessage.delivery_attempts)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+". Requesting path...", RNS.LOG_DEBUG)
|
||||
RNS.Transport.request_path(lxmessage.get_destination().hash)
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
|
||||
lxmessage.progress = 0.00
|
||||
lxmessage.progress = 0.01
|
||||
else:
|
||||
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
self.fail_message(lxmessage)
|
||||
|
||||
+65
-30
@@ -16,8 +16,10 @@ class LXMessage:
|
||||
SENDING = 0x02
|
||||
SENT = 0x04
|
||||
DELIVERED = 0x08
|
||||
REJECTED = 0xFD
|
||||
CANCELLED = 0xFE
|
||||
FAILED = 0xFF
|
||||
states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, FAILED]
|
||||
states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, REJECTED, CANCELLED, FAILED]
|
||||
|
||||
UNKNOWN = 0x00
|
||||
PACKET = 0x01
|
||||
@@ -49,18 +51,20 @@ class LXMessage:
|
||||
TICKET_INTERVAL = 1*24*60*60
|
||||
COST_TICKET = 0x100
|
||||
|
||||
# LXMF overhead is 111 bytes per message:
|
||||
# LXMF overhead is 112 bytes per message:
|
||||
# 16 bytes for destination hash
|
||||
# 16 bytes for source hash
|
||||
# 64 bytes for Ed25519 signature
|
||||
# 8 bytes for timestamp
|
||||
# 7 bytes for msgpack structure
|
||||
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + 8 + 7
|
||||
# 8 bytes for msgpack structure
|
||||
TIMESTAMP_SIZE = 8
|
||||
STRUCT_OVERHEAD = 8
|
||||
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + TIMESTAMP_SIZE + STRUCT_OVERHEAD
|
||||
|
||||
# With an MTU of 500, the maximum amount of data
|
||||
# we can send in a single encrypted packet is
|
||||
# 383 bytes.
|
||||
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU
|
||||
# 391 bytes.
|
||||
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU + TIMESTAMP_SIZE
|
||||
|
||||
# The max content length we can fit in LXMF message
|
||||
# inside a single RNS packet is the encrypted MDU, minus
|
||||
@@ -69,7 +73,7 @@ class LXMessage:
|
||||
# field of the packet, therefore we also add the length
|
||||
# of a destination hash to the calculation. With default
|
||||
# RNS and LXMF parameters, the largest single-packet
|
||||
# LXMF message we can send is 288 bytes. If a message
|
||||
# LXMF message we can send is 295 bytes. If a message
|
||||
# is larger than that, a Reticulum link will be used.
|
||||
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
@@ -79,13 +83,13 @@ class LXMessage:
|
||||
LINK_PACKET_MDU = RNS.Link.MDU
|
||||
|
||||
# Which means that we can deliver single-packet LXMF
|
||||
# messages with content of up to 320 bytes over a link.
|
||||
# messages with content of up to 319 bytes over a link.
|
||||
# If a message is larger than that, LXMF will sequence
|
||||
# and transfer it as a RNS resource over the link instead.
|
||||
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
|
||||
|
||||
# For plain packets without encryption, we can
|
||||
# fit up to 369 bytes of content.
|
||||
# fit up to 368 bytes of content.
|
||||
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
|
||||
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
@@ -129,8 +133,16 @@ class LXMessage:
|
||||
if title == None:
|
||||
title = ""
|
||||
|
||||
self.set_title_from_string(title)
|
||||
self.set_content_from_string(content)
|
||||
if type(title) == bytes:
|
||||
self.set_title_from_bytes(title)
|
||||
else:
|
||||
self.set_title_from_string(title)
|
||||
|
||||
if type(content) == bytes:
|
||||
self.set_content_from_bytes(content)
|
||||
else:
|
||||
self.set_content_from_string(content)
|
||||
|
||||
self.set_fields(fields)
|
||||
|
||||
self.payload = None
|
||||
@@ -192,7 +204,11 @@ class LXMessage:
|
||||
self.content = content_bytes
|
||||
|
||||
def content_as_string(self):
|
||||
return self.content.decode("utf-8")
|
||||
try:
|
||||
return self.content.decode("utf-8")
|
||||
except Exception as e:
|
||||
RNS.log(f"{self} could not decode message content as string: {e}")
|
||||
return None
|
||||
|
||||
def set_fields(self, fields):
|
||||
if isinstance(fields, dict) or fields == None:
|
||||
@@ -264,10 +280,14 @@ class LXMessage:
|
||||
def validate_stamp(self, target_cost, tickets=None):
|
||||
if tickets != None:
|
||||
for ticket in tickets:
|
||||
if self.stamp == RNS.Identity.truncated_hash(ticket+self.message_id):
|
||||
RNS.log(f"Stamp on {self} validated by inbound ticket", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
self.stamp_value = LXMessage.COST_TICKET
|
||||
return True
|
||||
try:
|
||||
if self.stamp == RNS.Identity.truncated_hash(ticket+self.message_id):
|
||||
RNS.log(f"Stamp on {self} validated by inbound ticket", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
self.stamp_value = LXMessage.COST_TICKET
|
||||
return True
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while validating ticket: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
if self.stamp == None:
|
||||
return False
|
||||
@@ -284,9 +304,10 @@ class LXMessage:
|
||||
# If an outbound ticket exists, use this for
|
||||
# generating a valid stamp.
|
||||
if self.outbound_ticket != None and type(self.outbound_ticket) == bytes and len(self.outbound_ticket) == LXMessage.TICKET_LENGTH:
|
||||
RNS.log(f"Generating stamp with outbound ticket for {self}", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
generated_stamp = RNS.Identity.truncated_hash(self.outbound_ticket+self.message_id)
|
||||
self.stamp_value = LXMessage.COST_TICKET
|
||||
return RNS.Identity.truncated_hash(self.outbound_ticket+self.message_id)
|
||||
RNS.log(f"Generated stamp with outbound ticket {RNS.hexrep(self.outbound_ticket)} for {self}", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
return generated_stamp
|
||||
|
||||
# If no stamp cost is required, we can just
|
||||
# return immediately.
|
||||
@@ -347,14 +368,22 @@ class LXMessage:
|
||||
self.packed += self.signature
|
||||
self.packed += packed_payload
|
||||
self.packed_size = len(self.packed)
|
||||
content_size = len(packed_payload)
|
||||
content_size = len(packed_payload)-LXMessage.TIMESTAMP_SIZE-LXMessage.STRUCT_OVERHEAD
|
||||
|
||||
# If no desired delivery method has been defined,
|
||||
# one will be chosen according to these rules:
|
||||
if self.desired_method == None:
|
||||
self.desired_method = LXMessage.DIRECT
|
||||
# TODO: Expand rules to something more intelligent
|
||||
|
||||
# If opportunistic delivery was requested, check
|
||||
# that message will fit within packet size limits
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
if content_size > LXMessage.ENCRYPTED_PACKET_MAX_CONTENT:
|
||||
RNS.log(f"Opportunistic delivery was requested for {self}, but content exceeds packet size limit. Falling back to link-based delivery.", RNS.LOG_DEBUG)
|
||||
self.desired_method = LXMessage.DIRECT
|
||||
|
||||
# Set delivery parameters according to delivery method
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
single_packet_content_limit = LXMessage.ENCRYPTED_PACKET_MAX_CONTENT
|
||||
@@ -362,7 +391,7 @@ class LXMessage:
|
||||
single_packet_content_limit = LXMessage.PLAIN_PACKET_MAX_CONTENT
|
||||
|
||||
if content_size > single_packet_content_limit:
|
||||
raise TypeError("LXMessage desired opportunistic delivery method, but content exceeds single-packet size.")
|
||||
raise TypeError(f"LXMessage desired opportunistic delivery method, but content of length {content_size} exceeds single-packet content limit of {single_packet_content_limit}.")
|
||||
else:
|
||||
self.method = LXMessage.OPPORTUNISTIC
|
||||
self.representation = LXMessage.PACKET
|
||||
@@ -415,6 +444,7 @@ class LXMessage:
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
lxm_packet = self.__as_packet()
|
||||
lxm_packet.send().set_delivery_callback(self.__mark_delivered)
|
||||
self.progress = 0.50
|
||||
self.ratchet_id = lxm_packet.ratchet_id
|
||||
self.state = LXMessage.SENT
|
||||
|
||||
@@ -536,22 +566,27 @@ class LXMessage:
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_delivered()
|
||||
else:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
if resource.status == RNS.Resource.REJECTED:
|
||||
self.state = LXMessage.REJECTED
|
||||
|
||||
elif self.state != LXMessage.CANCELLED:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __propagation_resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_propagated()
|
||||
else:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
if self.state != LXMessage.CANCELLED:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __link_packet_timed_out(self, packet_receipt):
|
||||
if packet_receipt:
|
||||
packet_receipt.destination.teardown()
|
||||
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
if self.state != LXMessage.CANCELLED:
|
||||
if packet_receipt:
|
||||
packet_receipt.destination.teardown()
|
||||
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __update_transfer_progress(self, resource):
|
||||
self.progress = 0.10 + (resource.get_progress()*0.90)
|
||||
|
||||
+58
-10
@@ -7,6 +7,8 @@ import multiprocessing
|
||||
|
||||
WORKBLOCK_EXPAND_ROUNDS = 3000
|
||||
|
||||
active_jobs = {}
|
||||
|
||||
def stamp_workblock(message_id):
|
||||
wb_st = time.time()
|
||||
expand_rounds = WORKBLOCK_EXPAND_ROUNDS
|
||||
@@ -27,7 +29,7 @@ def stamp_value(workblock, stamp):
|
||||
value = 0
|
||||
bits = 256
|
||||
material = RNS.Identity.full_hash(workblock+stamp)
|
||||
i = int.from_bytes(material)
|
||||
i = int.from_bytes(material, byteorder="big")
|
||||
while ((i & (1 << (bits - 1))) == 0):
|
||||
i = (i << 1)
|
||||
value += 1
|
||||
@@ -44,23 +46,56 @@ def generate_stamp(message_id, stamp_cost):
|
||||
value = 0
|
||||
|
||||
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin():
|
||||
stamp, rounds = job_simple(stamp_cost, workblock)
|
||||
stamp, rounds = job_simple(stamp_cost, workblock, message_id)
|
||||
|
||||
elif RNS.vendor.platformutils.is_android():
|
||||
stamp, rounds = job_android(stamp_cost, workblock)
|
||||
stamp, rounds = job_android(stamp_cost, workblock, message_id)
|
||||
|
||||
else:
|
||||
stamp, rounds = job_linux(stamp_cost, workblock)
|
||||
stamp, rounds = job_linux(stamp_cost, workblock, message_id)
|
||||
|
||||
duration = time.time() - start_time
|
||||
speed = rounds/duration
|
||||
value = stamp_value(workblock, stamp)
|
||||
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 job_simple(stamp_cost, workblock):
|
||||
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-
|
||||
@@ -73,6 +108,8 @@ def job_simple(stamp_cost, workblock):
|
||||
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)
|
||||
@@ -81,15 +118,20 @@ def job_simple(stamp_cost, workblock):
|
||||
else:
|
||||
return True
|
||||
|
||||
while not sv(pstamp, stamp_cost, workblock):
|
||||
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(stamp_cost, workblock):
|
||||
def job_linux(stamp_cost, workblock, message_id):
|
||||
allow_kill = True
|
||||
stamp = None
|
||||
total_rounds = 0
|
||||
@@ -126,6 +168,8 @@ def job_linux(stamp_cost, workblock):
|
||||
job_procs.append(process)
|
||||
process.start()
|
||||
|
||||
active_jobs[message_id] = [stop_event, result_queue]
|
||||
|
||||
stamp = result_queue.get()
|
||||
RNS.log("Got stamp result from worker", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
@@ -170,7 +214,7 @@ def job_linux(stamp_cost, workblock):
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
def job_android(stamp_cost, workblock):
|
||||
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
|
||||
@@ -230,10 +274,12 @@ def job_android(stamp_cost, workblock):
|
||||
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:
|
||||
while stamp == None and active_jobs[message_id] == False:
|
||||
job_procs = []
|
||||
try:
|
||||
for pnum in range(jobs):
|
||||
@@ -260,6 +306,8 @@ def job_android(stamp_cost, workblock):
|
||||
RNS.log(f"Stamp generation job error: {e}")
|
||||
RNS.trace_exception(e)
|
||||
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__ = "0.5.0"
|
||||
__version__ = "0.6.0"
|
||||
@@ -29,8 +29,8 @@ def delivery_callback(message):
|
||||
RNS.log("\t| Destination instance : "+str(message.get_destination()))
|
||||
RNS.log("\t| Transport Encryption : "+str(message.transport_encryption))
|
||||
RNS.log("\t| Timestamp : "+time_string)
|
||||
RNS.log("\t| Title : "+message.title_as_string())
|
||||
RNS.log("\t| Content : "+message.content_as_string())
|
||||
RNS.log("\t| Title : "+str(message.title_as_string()))
|
||||
RNS.log("\t| Content : "+str(message.content_as_string()))
|
||||
RNS.log("\t| Fields : "+str(message.fields))
|
||||
if message.ratchet_id:
|
||||
RNS.log("\t| Ratchet : "+str(RNS.Identity._get_ratchet_id(message.ratchet_id)))
|
||||
@@ -69,4 +69,4 @@ while True:
|
||||
|
||||
# input()
|
||||
# RNS.log("Requesting messages from propagation node...")
|
||||
# router.request_messages_from_propagation_node(identity)
|
||||
# router.request_messages_from_propagation_node(identity)
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
qrcode==7.4.2
|
||||
rns==0.7.7
|
||||
rns==0.7.8
|
||||
setuptools==70.0.0
|
||||
Reference in new issue
Block a user