mirror of
https://github.com/markqvist/LXMF
synced 2026-11-23 07:20:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61b1ecce27 | ||
|
|
68257a441f | ||
|
|
e69da2ed2a | ||
|
|
c2a08ef355 | ||
|
|
1430b1ce90 | ||
|
|
1c9c744107 | ||
|
|
bfed126a7c | ||
|
|
44d1d992f8 | ||
|
|
7701f326d9 | ||
|
|
356cb6412f | ||
|
|
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 |
No files matched your search
+20
-16
@@ -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,28 @@ 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:
|
||||
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
|
||||
|
||||
if destination_hash in self.lxmrouter.static_peers:
|
||||
self.lxmrouter.peer(destination_hash, node_timebase, propagation_transfer_limit)
|
||||
|
||||
elif data[0] == False:
|
||||
self.lxmrouter.unpeer(destination_hash, node_timebase)
|
||||
else:
|
||||
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)
|
||||
|
||||
+39
-3
@@ -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
|
||||
@@ -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
|
||||
+209
-31
@@ -4,6 +4,7 @@ import time
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
from collections import deque
|
||||
from .LXMF import APP_NAME
|
||||
|
||||
class LXMPeer:
|
||||
@@ -38,15 +39,25 @@ class LXMPeer:
|
||||
@staticmethod
|
||||
def from_bytes(peer_bytes, router):
|
||||
dictionary = msgpack.unpackb(peer_bytes)
|
||||
peer_destination_hash = dictionary["destination_hash"]
|
||||
peer_peering_timebase = dictionary["peering_timebase"]
|
||||
peer_alive = dictionary["alive"]
|
||||
peer_last_heard = dictionary["last_heard"]
|
||||
|
||||
peer = LXMPeer(router, peer_destination_hash)
|
||||
peer.peering_timebase = peer_peering_timebase
|
||||
peer.alive = peer_alive
|
||||
peer.last_heard = peer_last_heard
|
||||
|
||||
peer = LXMPeer(router, dictionary["destination_hash"])
|
||||
peer.peering_timebase = dictionary["peering_timebase"]
|
||||
peer.alive = dictionary["alive"]
|
||||
peer.last_heard = dictionary["last_heard"]
|
||||
if "link_establishment_rate" in dictionary:
|
||||
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:
|
||||
@@ -55,15 +66,50 @@ class LXMPeer:
|
||||
peer.propagation_transfer_limit = None
|
||||
else:
|
||||
peer.propagation_transfer_limit = None
|
||||
|
||||
if "offered" in dictionary:
|
||||
peer.offered = dictionary["offered"]
|
||||
else:
|
||||
peer.offered = 0
|
||||
|
||||
if "outgoing" in dictionary:
|
||||
peer.outgoing = dictionary["outgoing"]
|
||||
else:
|
||||
peer.outgoing = 0
|
||||
|
||||
if "incoming" in dictionary:
|
||||
peer.incoming = dictionary["incoming"]
|
||||
else:
|
||||
peer.incoming = 0
|
||||
|
||||
if "rx_bytes" in dictionary:
|
||||
peer.rx_bytes = dictionary["rx_bytes"]
|
||||
else:
|
||||
peer.rx_bytes = 0
|
||||
|
||||
if "tx_bytes" in dictionary:
|
||||
peer.tx_bytes = dictionary["tx_bytes"]
|
||||
else:
|
||||
peer.tx_bytes = 0
|
||||
|
||||
hm_count = 0
|
||||
for transient_id in dictionary["handled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.handled_messages[transient_id] = router.propagation_entries[transient_id]
|
||||
peer.add_handled_message(transient_id)
|
||||
hm_count += 1
|
||||
|
||||
um_count = 0
|
||||
for transient_id in dictionary["unhandled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.unhandled_messages[transient_id] = router.propagation_entries[transient_id]
|
||||
peer.add_unhandled_message(transient_id)
|
||||
um_count += 1
|
||||
|
||||
peer._hm_count = hm_count
|
||||
peer._um_count = um_count
|
||||
peer._hm_counts_synced = True
|
||||
peer._um_counts_synced = True
|
||||
|
||||
del dictionary
|
||||
return peer
|
||||
|
||||
def to_bytes(self):
|
||||
@@ -73,7 +119,13 @@ 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
|
||||
dictionary["offered"] = self.offered
|
||||
dictionary["outgoing"] = self.outgoing
|
||||
dictionary["incoming"] = self.incoming
|
||||
dictionary["rx_bytes"] = self.rx_bytes
|
||||
dictionary["tx_bytes"] = self.tx_bytes
|
||||
|
||||
handled_ids = []
|
||||
for transient_id in self.handled_messages:
|
||||
@@ -86,7 +138,10 @@ class LXMPeer:
|
||||
dictionary["handled_ids"] = handled_ids
|
||||
dictionary["unhandled_ids"] = unhandled_ids
|
||||
|
||||
return msgpack.packb(dictionary)
|
||||
peer_bytes = msgpack.packb(dictionary)
|
||||
del dictionary
|
||||
|
||||
return peer_bytes
|
||||
|
||||
def __init__(self, router, destination_hash):
|
||||
self.alive = False
|
||||
@@ -96,19 +151,35 @@ 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.handled_messages_queue = deque()
|
||||
self.unhandled_messages_queue = deque()
|
||||
|
||||
self.offered = 0 # Messages offered to this peer
|
||||
self.outgoing = 0 # Messages transferred to this peer
|
||||
self.incoming = 0 # Messages received from this peer
|
||||
self.rx_bytes = 0 # Bytes received from this peer
|
||||
self.tx_bytes = 0 # Bytes sent to this peer
|
||||
|
||||
self._hm_count = 0
|
||||
self._um_count = 0
|
||||
self._hm_counts_synced = False
|
||||
self._um_counts_synced = False
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
self.unhandled_messages = {}
|
||||
self.handled_messages = {}
|
||||
self.last_offer = []
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
def sync(self):
|
||||
RNS.log("Initiating LXMF Propagation Node sync with peer "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_DEBUG)
|
||||
@@ -126,9 +197,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)
|
||||
@@ -160,7 +232,7 @@ class LXMPeer:
|
||||
|
||||
for transient_id in purged_ids:
|
||||
RNS.log("Dropping unhandled message "+RNS.prettyhexrep(transient_id)+" for peer "+RNS.prettyhexrep(self.destination_hash)+" since it no longer exists in the message store.", RNS.LOG_DEBUG)
|
||||
self.unhandled_messages.pop(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
unhandled_entries.sort(key=lambda e: e[1], reverse=False)
|
||||
per_message_overhead = 16 # Really only 2 bytes, but set a bit higher for now
|
||||
@@ -176,9 +248,9 @@ class LXMPeer:
|
||||
cumulative_size += (lxm_size+per_message_overhead)
|
||||
unhandled_ids.append(transient_id)
|
||||
|
||||
RNS.log("Sending sync request to peer "+str(self.destination), RNS.LOG_DEBUG)
|
||||
RNS.log(f"Offering {len(unhandled_ids)} messages to peer {RNS.prettyhexrep(self.destination.hash)}", RNS.LOG_VERBOSE)
|
||||
self.last_offer = unhandled_ids
|
||||
self.link.request(LXMPeer.OFFER_REQUEST_PATH, self.last_offer, response_callback=self.offer_response, failed_callback=self.request_failed)
|
||||
self.link.request(LXMPeer.OFFER_REQUEST_PATH, unhandled_ids, response_callback=self.offer_response, failed_callback=self.request_failed)
|
||||
self.state = LXMPeer.REQUEST_SENT
|
||||
|
||||
else:
|
||||
@@ -206,22 +278,29 @@ class LXMPeer:
|
||||
|
||||
if response == LXMPeer.ERROR_NO_IDENTITY:
|
||||
if self.link != None:
|
||||
RNS.log("Remote peer indicated that no identification was received, retrying...", RNS.LOG_DEBUG)
|
||||
RNS.log("Remote peer indicated that no identification was received, retrying...", RNS.LOG_VERBOSE)
|
||||
self.link.identify()
|
||||
self.state = LXMPeer.LINK_READY
|
||||
self.sync()
|
||||
return
|
||||
|
||||
elif response == LXMPeer.ERROR_NO_ACCESS:
|
||||
RNS.log("Remote indicated that access was denied, breaking peering", RNS.LOG_VERBOSE)
|
||||
self.router.unpeer(self.destination_hash)
|
||||
return
|
||||
|
||||
elif response == False:
|
||||
# Peer already has all advertised messages
|
||||
for transient_id in self.last_offer:
|
||||
if transient_id in self.unhandled_messages:
|
||||
self.handled_messages[transient_id] = self.unhandled_messages.pop(transient_id)
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
|
||||
elif response == True:
|
||||
# Peer wants all advertised messages
|
||||
for transient_id in self.last_offer:
|
||||
wanted_messages.append(self.unhandled_messages[transient_id])
|
||||
wanted_messages.append(self.router.propagation_entries[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
else:
|
||||
@@ -230,18 +309,17 @@ class LXMPeer:
|
||||
# If the peer did not want the message, it has
|
||||
# already received it from another peer.
|
||||
if not transient_id in response:
|
||||
if transient_id in self.unhandled_messages:
|
||||
self.handled_messages[transient_id] = self.unhandled_messages.pop(transient_id)
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
for transient_id in response:
|
||||
wanted_messages.append(self.unhandled_messages[transient_id])
|
||||
wanted_messages.append(self.router.propagation_entries[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
if len(wanted_messages) > 0:
|
||||
RNS.log("Peer wanted "+str(len(wanted_messages))+" of the available messages", RNS.LOG_DEBUG)
|
||||
RNS.log("Peer wanted "+str(len(wanted_messages))+" of the available messages", RNS.LOG_VERBOSE)
|
||||
|
||||
lxm_list = []
|
||||
|
||||
for message_entry in wanted_messages:
|
||||
file_path = message_entry[1]
|
||||
if os.path.isfile(file_path):
|
||||
@@ -253,10 +331,12 @@ 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:
|
||||
RNS.log("Peer "+RNS.prettyhexrep(self.destination_hash)+" did not request any of the available messages, sync completed", RNS.LOG_DEBUG)
|
||||
RNS.log("Peer "+RNS.prettyhexrep(self.destination_hash)+" did not request any of the available messages, sync completed", RNS.LOG_VERBOSE)
|
||||
self.offered += len(self.last_offer)
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
|
||||
@@ -276,8 +356,8 @@ class LXMPeer:
|
||||
def resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
for transient_id in resource.transferred_messages:
|
||||
message = self.unhandled_messages.pop(transient_id)
|
||||
self.handled_messages[transient_id] = message
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
@@ -285,12 +365,20 @@ 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(f"Syncing {len(resource.transferred_messages)} messages to peer {RNS.prettyhexrep(self.destination_hash)} completed{rate_str}", RNS.LOG_VERBOSE)
|
||||
self.alive = True
|
||||
self.last_heard = time.time()
|
||||
self.offered += len(self.last_offer)
|
||||
self.outgoing += len(resource.transferred_messages)
|
||||
self.tx_bytes += resource.get_data_size()
|
||||
|
||||
else:
|
||||
RNS.log("Resource transfer for LXMF peer sync failed to "+str(self.destination), RNS.LOG_DEBUG)
|
||||
RNS.log("Resource transfer for LXMF peer sync failed to "+str(self.destination), RNS.LOG_VERBOSE)
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
|
||||
@@ -311,9 +399,99 @@ class LXMPeer:
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def handle_message(self, transient_id):
|
||||
if not transient_id in self.handled_messages and not transient_id in self.unhandled_messages:
|
||||
self.unhandled_messages[transient_id] = self.router.propagation_entries[transient_id]
|
||||
def queued_items(self):
|
||||
return len(self.handled_messages_queue) > 0 or len(self.unhandled_messages_queue) > 0
|
||||
|
||||
def queue_unhandled_message(self, transient_id):
|
||||
self.unhandled_messages_queue.append(transient_id)
|
||||
|
||||
def queue_handled_message(self, transient_id):
|
||||
self.handled_messages_queue.append(transient_id)
|
||||
|
||||
def process_queues(self):
|
||||
if len(self.unhandled_messages_queue) > 0 or len(self.handled_messages_queue) > 0:
|
||||
# TODO: Remove debug
|
||||
# st = time.time(); lu = len(self.unhandled_messages_queue); lh = len(self.handled_messages_queue)
|
||||
|
||||
handled_messages = self.handled_messages
|
||||
unhandled_messages = self.unhandled_messages
|
||||
|
||||
while len(self.handled_messages_queue) > 0:
|
||||
transient_id = self.handled_messages_queue.pop()
|
||||
if not transient_id in handled_messages:
|
||||
self.add_handled_message(transient_id)
|
||||
if transient_id in unhandled_messages:
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
while len(self.unhandled_messages_queue) > 0:
|
||||
transient_id = self.unhandled_messages_queue.pop()
|
||||
if not transient_id in handled_messages and not transient_id in unhandled_messages:
|
||||
self.add_unhandled_message(transient_id)
|
||||
|
||||
del handled_messages, unhandled_messages
|
||||
# TODO: Remove debug
|
||||
# RNS.log(f"{self} processed {lh}/{lu} in {RNS.prettytime(time.time()-st)}")
|
||||
|
||||
@property
|
||||
def handled_messages(self):
|
||||
pes = self.router.propagation_entries.copy()
|
||||
hm = list(filter(lambda tid: self.destination_hash in pes[tid][4], pes))
|
||||
self._hm_count = len(hm); del pes
|
||||
self._hm_counts_synced = True
|
||||
return hm
|
||||
|
||||
@property
|
||||
def unhandled_messages(self):
|
||||
pes = self.router.propagation_entries.copy()
|
||||
um = list(filter(lambda tid: self.destination_hash in pes[tid][5], pes))
|
||||
self._um_count = len(um); del pes
|
||||
self._um_counts_synced = True
|
||||
return um
|
||||
|
||||
@property
|
||||
def handled_message_count(self):
|
||||
if not self._hm_counts_synced:
|
||||
self._update_counts()
|
||||
|
||||
return self._hm_count
|
||||
|
||||
@property
|
||||
def unhandled_message_count(self):
|
||||
if not self._um_counts_synced:
|
||||
self._update_counts()
|
||||
|
||||
return self._um_count
|
||||
|
||||
def _update_counts(self):
|
||||
if not self._hm_counts_synced:
|
||||
hm = self.handled_messages; del hm
|
||||
|
||||
if not self._um_counts_synced:
|
||||
um = self.unhandled_messages; del um
|
||||
|
||||
def add_handled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if not self.destination_hash in self.router.propagation_entries[transient_id][4]:
|
||||
self.router.propagation_entries[transient_id][4].append(self.destination_hash)
|
||||
self._hm_counts_synced = False
|
||||
|
||||
def add_unhandled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if not self.destination_hash in self.router.propagation_entries[transient_id][5]:
|
||||
self.router.propagation_entries[transient_id][5].append(self.destination_hash)
|
||||
self._um_count += 1
|
||||
|
||||
def remove_handled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if self.destination_hash in self.router.propagation_entries[transient_id][4]:
|
||||
self.router.propagation_entries[transient_id][4].remove(self.destination_hash)
|
||||
self._hm_counts_synced = False
|
||||
|
||||
def remove_unhandled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if self.destination_hash in self.router.propagation_entries[transient_id][5]:
|
||||
self.router.propagation_entries[transient_id][5].remove(self.destination_hash)
|
||||
self._um_counts_synced = False
|
||||
|
||||
def __str__(self):
|
||||
if self.destination_hash:
|
||||
|
||||
+377
-89
@@ -1,10 +1,15 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import math
|
||||
import random
|
||||
import base64
|
||||
import atexit
|
||||
import signal
|
||||
import threading
|
||||
|
||||
from collections import deque
|
||||
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
@@ -16,6 +21,8 @@ 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
|
||||
@@ -30,6 +37,7 @@ class LXMRouter:
|
||||
|
||||
NODE_ANNOUNCE_DELAY = 20
|
||||
|
||||
MAX_PEERS = 50
|
||||
AUTOPEER = True
|
||||
AUTOPEER_MAXDEPTH = 4
|
||||
FASTEST_N_RANDOM_POOL = 2
|
||||
@@ -60,7 +68,10 @@ class LXMRouter:
|
||||
### Developer-facing API ##############################
|
||||
#######################################################
|
||||
|
||||
def __init__(self, identity = None, storagepath = None, autopeer = AUTOPEER, autopeer_maxdepth = None, propagation_limit = PROPAGATION_LIMIT, delivery_limit = DELIVERY_LIMIT, enforce_ratchets = False, enforce_stamps = False):
|
||||
def __init__(self, identity=None, storagepath=None, autopeer=AUTOPEER, autopeer_maxdepth=None,
|
||||
propagation_limit=PROPAGATION_LIMIT, delivery_limit=DELIVERY_LIMIT, enforce_ratchets=False,
|
||||
enforce_stamps=False, static_peers = [], max_peers=None, from_static_only=False):
|
||||
|
||||
random.seed(os.urandom(10))
|
||||
|
||||
self.pending_inbound = []
|
||||
@@ -91,6 +102,9 @@ class LXMRouter:
|
||||
self.outbound_propagation_node = None
|
||||
self.outbound_propagation_link = None
|
||||
|
||||
if delivery_limit == None:
|
||||
delivery_limit = LXMRouter.DELIVERY_LIMIT
|
||||
|
||||
self.message_storage_limit = None
|
||||
self.information_storage_limit = None
|
||||
self.propagation_per_transfer_limit = propagation_limit
|
||||
@@ -114,6 +128,7 @@ class LXMRouter:
|
||||
self.cost_file_lock = threading.Lock()
|
||||
self.ticket_file_lock = threading.Lock()
|
||||
self.stamp_gen_lock = threading.Lock()
|
||||
self.exit_handler_running = False
|
||||
|
||||
if identity == None:
|
||||
identity = RNS.Identity()
|
||||
@@ -131,9 +146,32 @@ class LXMRouter:
|
||||
else:
|
||||
self.autopeer_maxdepth = LXMRouter.AUTOPEER_MAXDEPTH
|
||||
|
||||
if max_peers == None:
|
||||
self.max_peers = LXMRouter.MAX_PEERS
|
||||
else:
|
||||
if type(max_peers) == int and max_peers >= 0:
|
||||
self.max_peers = max_peers
|
||||
else:
|
||||
raise ValueError(f"Invalid value for max_peers: {max_peers}")
|
||||
|
||||
self.from_static_only = from_static_only
|
||||
if type(static_peers) != list:
|
||||
raise ValueError(f"Invalid type supplied for static peer list: {type(static_peers)}")
|
||||
else:
|
||||
for static_peer in static_peers:
|
||||
if type(static_peer) != bytes:
|
||||
raise ValueError(f"Invalid static peer destination hash: {static_peer}")
|
||||
else:
|
||||
if len(static_peer) != RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
|
||||
raise ValueError(f"Invalid static peer destination hash: {static_peer}")
|
||||
|
||||
self.static_peers = static_peers
|
||||
|
||||
self.peers = {}
|
||||
self.propagation_entries = {}
|
||||
|
||||
self.peer_distribution_queue = deque()
|
||||
|
||||
RNS.Transport.register_announce_handler(LXMFDeliveryAnnounceHandler(self))
|
||||
RNS.Transport.register_announce_handler(LXMFPropagationAnnounceHandler(self))
|
||||
|
||||
@@ -143,19 +181,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"):
|
||||
@@ -163,6 +220,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()
|
||||
@@ -196,6 +256,8 @@ class LXMRouter:
|
||||
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)
|
||||
@@ -208,8 +270,9 @@ class LXMRouter:
|
||||
def announce_propagation_node(self):
|
||||
def delayed_announce():
|
||||
time.sleep(LXMRouter.NODE_ANNOUNCE_DELAY)
|
||||
node_state = self.propagation_node and not self.from_static_only
|
||||
announce_data = [
|
||||
self.propagation_node, # Boolean flag signalling propagation node state
|
||||
node_state, # Boolean flag signalling propagation node state
|
||||
int(time.time()), # Current node timebase
|
||||
self.propagation_per_transfer_limit, # Per-transfer limit for message propagation in kilobytes
|
||||
]
|
||||
@@ -284,11 +347,12 @@ class LXMRouter:
|
||||
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
|
||||
@@ -350,6 +414,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,
|
||||
@@ -401,6 +466,8 @@ class LXMRouter:
|
||||
os.makedirs(self.messagepath)
|
||||
|
||||
self.propagation_entries = {}
|
||||
|
||||
st = time.time(); RNS.log("Indexing messagestore...", RNS.LOG_NOTICE)
|
||||
for filename in os.listdir(self.messagepath):
|
||||
components = filename.split("_")
|
||||
if len(components) == 2:
|
||||
@@ -417,33 +484,62 @@ class LXMRouter:
|
||||
file.close()
|
||||
|
||||
self.propagation_entries[transient_id] = [
|
||||
destination_hash,
|
||||
filepath,
|
||||
received,
|
||||
msg_size,
|
||||
destination_hash, # 0: Destination hash
|
||||
filepath, # 1: Storage location
|
||||
received, # 2: Receive timestamp
|
||||
msg_size, # 3: Message size
|
||||
[], # 4: Handled peers
|
||||
[], # 5: Unhandled peers
|
||||
]
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not read LXM from message store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
et = time.time(); RNS.log(f"Indexed {len(self.propagation_entries)} messages in {RNS.prettytime(et-st)}, {math.floor(len(self.propagation_entries)/(et-st))} msgs/s", RNS.LOG_NOTICE)
|
||||
st = time.time(); RNS.log("Rebuilding peer synchronisation states...", RNS.LOG_NOTICE)
|
||||
|
||||
if os.path.isfile(self.storagepath+"/peers"):
|
||||
peers_file = open(self.storagepath+"/peers", "rb")
|
||||
peers_data = peers_file.read()
|
||||
peers_file.close()
|
||||
|
||||
if len(peers_data) > 0:
|
||||
serialised_peers = msgpack.unpackb(peers_data)
|
||||
del peers_data
|
||||
|
||||
for serialised_peer in serialised_peers:
|
||||
while len(serialised_peers) > 0:
|
||||
serialised_peer = serialised_peers.pop()
|
||||
peer = LXMPeer.from_bytes(serialised_peer, self)
|
||||
del serialised_peer
|
||||
if peer.destination_hash in self.static_peers and peer.last_heard == 0:
|
||||
# TODO: Allow path request responses through announce handler
|
||||
# momentarily here, so peering config can be updated even if
|
||||
# the static peer is not available to directly send an announce.
|
||||
RNS.Transport.request_path(peer.destination_hash)
|
||||
if peer.identity != None:
|
||||
self.peers[peer.destination_hash] = peer
|
||||
lim_str = ", no transfer limit"
|
||||
if peer.propagation_transfer_limit != None:
|
||||
lim_str = ", "+RNS.prettysize(peer.propagation_transfer_limit*1000)+" transfer limit"
|
||||
RNS.log("Loaded peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(len(peer.unhandled_messages))+" 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:
|
||||
RNS.log("Peer "+RNS.prettyhexrep(peer.destination_hash)+" could not be loaded, because its identity could not be recalled. Dropping peer.", RNS.LOG_DEBUG)
|
||||
del peer
|
||||
|
||||
del serialised_peers
|
||||
|
||||
if len(self.static_peers) > 0:
|
||||
for static_peer in self.static_peers:
|
||||
if not static_peer in self.peers:
|
||||
RNS.log(f"Activating static peering with {RNS.prettyhexrep(static_peer)}", RNS.LOG_NOTICE)
|
||||
self.peers[static_peer] = LXMPeer(self, static_peer)
|
||||
if self.peers[static_peer].last_heard == 0:
|
||||
# TODO: Allow path request responses through announce handler
|
||||
# momentarily here, so peering config can be updated even if
|
||||
# the static peer is not available to directly send an announce.
|
||||
RNS.Transport.request_path(static_peer)
|
||||
|
||||
RNS.log(f"Rebuilt synchronisation state for {len(self.peers)} peers in {RNS.prettytime(time.time()-st)}", RNS.LOG_NOTICE)
|
||||
|
||||
self.propagation_node = True
|
||||
self.propagation_destination.set_link_established_callback(self.propagation_link_established)
|
||||
@@ -563,39 +659,61 @@ class LXMRouter:
|
||||
JOB_TRANSIENT_INTERVAL = 60
|
||||
JOB_STORE_INTERVAL = 120
|
||||
JOB_PEERSYNC_INTERVAL = 12
|
||||
JOB_PEERINGEST_INTERVAL= JOB_PEERSYNC_INTERVAL
|
||||
def jobs(self):
|
||||
self.processing_count += 1
|
||||
if not self.exit_handler_running:
|
||||
self.processing_count += 1
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_OUTBOUND_INTERVAL == 0:
|
||||
self.process_outbound()
|
||||
if self.processing_count % LXMRouter.JOB_OUTBOUND_INTERVAL == 0:
|
||||
self.process_outbound()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_STAMPS_INTERVAL == 0:
|
||||
threading.Thread(target=self.process_deferred_stamps, daemon=True).start()
|
||||
if self.processing_count % LXMRouter.JOB_STAMPS_INTERVAL == 0:
|
||||
threading.Thread(target=self.process_deferred_stamps, daemon=True).start()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_LINKS_INTERVAL == 0:
|
||||
self.clean_links()
|
||||
if self.processing_count % LXMRouter.JOB_LINKS_INTERVAL == 0:
|
||||
self.clean_links()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_TRANSIENT_INTERVAL == 0:
|
||||
self.clean_transient_id_caches()
|
||||
if self.processing_count % LXMRouter.JOB_TRANSIENT_INTERVAL == 0:
|
||||
self.clean_transient_id_caches()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_STORE_INTERVAL == 0:
|
||||
self.clean_message_store()
|
||||
if self.processing_count % LXMRouter.JOB_STORE_INTERVAL == 0:
|
||||
self.clean_message_store()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_PEERSYNC_INTERVAL == 0:
|
||||
self.sync_peers()
|
||||
if self.processing_count % LXMRouter.JOB_PEERINGEST_INTERVAL == 0:
|
||||
self.flush_queues()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_PEERSYNC_INTERVAL == 0:
|
||||
self.sync_peers()
|
||||
|
||||
# def syncstats(self):
|
||||
# for peer_id in self.peers:
|
||||
# p = self.peers[peer_id]
|
||||
# RNS.log(f"{RNS.prettyhexrep(peer_id)} O={p.offered} S={p.outgoing} I={p.incoming} TX={RNS.prettysize(p.tx_bytes)} RX={RNS.prettysize(p.rx_bytes)}")
|
||||
|
||||
def jobloop(self):
|
||||
while (True):
|
||||
# TODO: Improve this to scheduling, so manual
|
||||
# triggers can delay next run
|
||||
|
||||
try:
|
||||
self.jobs()
|
||||
except Exception as e:
|
||||
RNS.log("An error ocurred while running LXMF Router jobs.", RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
time.sleep(LXMRouter.PROCESSING_INTERVAL)
|
||||
|
||||
def flush_queues(self):
|
||||
if len(self.peers) > 0:
|
||||
self.flush_peer_distribution_queue()
|
||||
RNS.log("Calculating peer distribution queue mappings...", RNS.LOG_DEBUG); st = time.time()
|
||||
for peer_id in self.peers.copy():
|
||||
if peer_id in self.peers:
|
||||
peer = self.peers[peer_id]
|
||||
if peer.queued_items():
|
||||
peer.process_queues()
|
||||
|
||||
RNS.log(f"Distribution queue mapping completed in {RNS.prettytime(time.time()-st)}", RNS.LOG_DEBUG)
|
||||
|
||||
def clean_links(self):
|
||||
closed_links = []
|
||||
for link_hash in self.direct_links:
|
||||
@@ -642,7 +760,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:
|
||||
@@ -652,7 +770,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:
|
||||
@@ -850,24 +968,24 @@ class LXMRouter:
|
||||
|
||||
def save_locally_delivered_transient_ids(self):
|
||||
try:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
os.makedirs(self.storagepath)
|
||||
if len(self.locally_delivered_transient_ids) > 0:
|
||||
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)
|
||||
|
||||
def save_locally_processed_transient_ids(self):
|
||||
try:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
os.makedirs(self.storagepath)
|
||||
if len(self.locally_processed_transient_ids) > 0:
|
||||
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)
|
||||
@@ -922,7 +1040,7 @@ class LXMRouter:
|
||||
expired_inbound.append(inbound_ticket)
|
||||
|
||||
for inbound_ticket in expired_inbound:
|
||||
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)
|
||||
@@ -965,10 +1083,44 @@ class LXMRouter:
|
||||
RNS.log(f"An error occurred while reloading available tickets from storage: {e}", RNS.LOG_ERROR)
|
||||
|
||||
def exit_handler(self):
|
||||
if self.exit_handler_running:
|
||||
return
|
||||
|
||||
self.exit_handler_running = True
|
||||
|
||||
RNS.log("Tearing down delivery destinations...", RNS.LOG_NOTICE)
|
||||
for destination_hash in self.delivery_destinations:
|
||||
delivery_destination = self.delivery_destinations[destination_hash]
|
||||
delivery_destination.set_packet_callback(None)
|
||||
delivery_destination.set_link_established_callback(None)
|
||||
for link in delivery_destination.links:
|
||||
try:
|
||||
if link.status == RNS.Link.ACTIVE:
|
||||
link.teardown()
|
||||
except Exception as e:
|
||||
RNS.log("Error while tearing down propagation link: {e}", RNS.LOG_ERROR)
|
||||
|
||||
if self.propagation_node:
|
||||
RNS.log("Tearing down propagation node destination...", RNS.LOG_NOTICE)
|
||||
self.propagation_destination.set_link_established_callback(None)
|
||||
self.propagation_destination.set_packet_callback(None)
|
||||
self.propagation_destination.deregister_request_handler(LXMPeer.OFFER_REQUEST_PATH)
|
||||
self.propagation_destination.deregister_request_handler(LXMPeer.MESSAGE_GET_PATH)
|
||||
for link in self.active_propagation_links:
|
||||
try:
|
||||
if link.status == RNS.Link.ACTIVE:
|
||||
link.teardown()
|
||||
except Exception as e:
|
||||
RNS.log("Error while tearing down propagation link: {e}", RNS.LOG_ERROR)
|
||||
|
||||
RNS.log("Persisting LXMF state data to storage...", RNS.LOG_NOTICE)
|
||||
self.flush_queues()
|
||||
if self.propagation_node:
|
||||
try:
|
||||
st = time.time(); RNS.log(f"Saving {len(self.peers)} peer synchronisation states to storage...", RNS.LOG_NOTICE)
|
||||
serialised_peers = []
|
||||
for peer_id in self.peers:
|
||||
peer_dict = self.peers.copy()
|
||||
for peer_id in peer_dict:
|
||||
peer = self.peers[peer_id]
|
||||
serialised_peers.append(peer.to_bytes())
|
||||
|
||||
@@ -976,7 +1128,7 @@ class LXMRouter:
|
||||
peers_file.write(msgpack.packb(serialised_peers))
|
||||
peers_file.close()
|
||||
|
||||
RNS.log("Saved "+str(len(serialised_peers))+" peers to storage", RNS.LOG_DEBUG)
|
||||
RNS.log(f"Saved {len(serialised_peers)} peers to storage in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_NOTICE)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not save propagation node peers to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
@@ -984,6 +1136,20 @@ class LXMRouter:
|
||||
self.save_locally_delivered_transient_ids()
|
||||
self.save_locally_processed_transient_ids()
|
||||
|
||||
def sigint_handler(self, signal, frame):
|
||||
if not self.exit_handler_running:
|
||||
RNS.log("Received SIGINT, shutting down now!", RNS.LOG_WARNING)
|
||||
sys.exit(0)
|
||||
else:
|
||||
RNS.log("Received SIGINT, but exit handler is running, keeping process alive until storage persist is complete", RNS.LOG_WARNING)
|
||||
|
||||
def sigterm_handler(self, signal, frame):
|
||||
if not self.exit_handler_running:
|
||||
RNS.log("Received SIGTERM, shutting down now!", RNS.LOG_WARNING)
|
||||
sys.exit(0)
|
||||
else:
|
||||
RNS.log("Received SIGTERM, but exit handler is running, keeping process alive until storage persist is complete", RNS.LOG_WARNING)
|
||||
|
||||
def __str__(self):
|
||||
return "<LXMRouter "+RNS.hexrep(self.identity.hash, delimit=False)+">"
|
||||
|
||||
@@ -1123,24 +1289,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)
|
||||
@@ -1204,6 +1378,33 @@ 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
|
||||
|
||||
@@ -1451,14 +1652,18 @@ class LXMRouter:
|
||||
peer.peering_timebase = timestamp
|
||||
peer.last_heard = time.time()
|
||||
peer.propagation_transfer_limit = propagation_transfer_limit
|
||||
RNS.log(f"Peering config updated for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_VERBOSE)
|
||||
|
||||
else:
|
||||
peer = LXMPeer(self, destination_hash)
|
||||
peer.alive = True
|
||||
peer.last_heard = time.time()
|
||||
peer.propagation_transfer_limit = propagation_transfer_limit
|
||||
self.peers[destination_hash] = peer
|
||||
RNS.log("Peered with "+str(peer.destination))
|
||||
if len(self.peers) < self.max_peers:
|
||||
peer = LXMPeer(self, destination_hash)
|
||||
peer.alive = True
|
||||
peer.last_heard = time.time()
|
||||
peer.propagation_transfer_limit = propagation_transfer_limit
|
||||
self.peers[destination_hash] = peer
|
||||
RNS.log(f"Peered with {RNS.prettyhexrep(destination_hash)}", RNS.LOG_NOTICE)
|
||||
else:
|
||||
RNS.log(f"Max peers reached, not peering with {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
|
||||
|
||||
def unpeer(self, destination_hash, timestamp = None):
|
||||
if timestamp == None:
|
||||
@@ -1475,10 +1680,12 @@ class LXMRouter:
|
||||
culled_peers = []
|
||||
waiting_peers = []
|
||||
unresponsive_peers = []
|
||||
for peer_id in self.peers:
|
||||
peer = self.peers[peer_id]
|
||||
peers = self.peers.copy()
|
||||
for peer_id in peers:
|
||||
peer = peers[peer_id]
|
||||
if time.time() > peer.last_heard + LXMPeer.MAX_UNREACHABLE:
|
||||
culled_peers.append(peer_id)
|
||||
if not peer_id in self.static_peers:
|
||||
culled_peers.append(peer_id)
|
||||
else:
|
||||
if peer.state == LXMPeer.IDLE and len(peer.unhandled_messages) > 0:
|
||||
if peer.alive:
|
||||
@@ -1494,12 +1701,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[
|
||||
@@ -1538,10 +1745,23 @@ class LXMRouter:
|
||||
self.active_propagation_links.append(link)
|
||||
|
||||
def propagation_resource_advertised(self, resource):
|
||||
if self.from_static_only:
|
||||
remote_identity = resource.link.get_remote_identity()
|
||||
if remote_identity == None:
|
||||
RNS.log(f"Rejecting propagation resource from unidentified peer", RNS.LOG_DEBUG)
|
||||
return False
|
||||
else:
|
||||
remote_destination = RNS.Destination(remote_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
remote_hash = remote_destination.hash
|
||||
remote_str = RNS.prettyhexrep(remote_hash)
|
||||
if not remote_hash in self.static_peers:
|
||||
RNS.log(f"Rejecting propagation resource from {remote_str} not in static peers list", RNS.LOG_DEBUG)
|
||||
return False
|
||||
|
||||
size = resource.get_data_size()
|
||||
limit = self.propagation_per_transfer_limit*1000
|
||||
if limit != None and size > limit:
|
||||
RNS.log("Rejecting "+RNS.prettysize(size)+" incoming LXMF propagation resource, since it exceeds the limit of "+RNS.prettysize(limit), RNS.LOG_DEBUG)
|
||||
RNS.log(f"Rejecting {RNS.prettysize(size)} incoming propagation resource, since it exceeds the limit of {RNS.prettysize(limit)}", RNS.LOG_DEBUG)
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
@@ -1568,6 +1788,14 @@ class LXMRouter:
|
||||
if remote_identity == None:
|
||||
return LXMPeer.ERROR_NO_IDENTITY
|
||||
else:
|
||||
if self.from_static_only:
|
||||
remote_destination = RNS.Destination(remote_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
remote_hash = remote_destination.hash
|
||||
remote_str = RNS.prettyhexrep(remote_hash)
|
||||
if not remote_hash in self.static_peers:
|
||||
RNS.log(f"Rejecting propagation request from {remote_str} not in static peers list", RNS.LOG_DEBUG)
|
||||
return LXMPeer.ERROR_NO_ACCESS
|
||||
|
||||
try:
|
||||
transient_ids = data
|
||||
wanted_ids = []
|
||||
@@ -1590,7 +1818,6 @@ class LXMRouter:
|
||||
return None
|
||||
|
||||
def propagation_resource_concluded(self, resource):
|
||||
RNS.log("Transfer concluded for incoming propagation resource "+str(resource), RNS.LOG_DEBUG)
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
# TODO: The peer this was received from should
|
||||
# have the transient id added to its list of
|
||||
@@ -1602,31 +1829,65 @@ class LXMRouter:
|
||||
# This is a series of propagation messages from a peer or originator
|
||||
remote_timebase = data[0]
|
||||
remote_hash = None
|
||||
remote_str = "unknown peer"
|
||||
remote_identity = resource.link.get_remote_identity()
|
||||
|
||||
if remote_identity != None:
|
||||
remote_destination = RNS.Destination(remote_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
remote_hash = remote_destination.hash
|
||||
remote_str = RNS.prettyhexrep(remote_hash)
|
||||
|
||||
if not remote_hash in self.peers:
|
||||
if self.autopeer and RNS.Transport.hops_to(remote_hash) <= self.autopeer_maxdepth:
|
||||
self.peer(remote_hash, remote_timebase)
|
||||
# TODO: Query cache for an announce and get propagation
|
||||
# transfer limit from that. For now, initialise it to a
|
||||
# sane default value, and wait for an announce to arrive
|
||||
# that will update the peering config to the actual limit.
|
||||
propagation_transfer_limit = LXMRouter.PROPAGATION_LIMIT//4
|
||||
self.peer(remote_hash, remote_timebase, propagation_transfer_limit)
|
||||
else:
|
||||
remote_str = f"peer {remote_str}"
|
||||
|
||||
messages = data[1]
|
||||
RNS.log(f"Received {len(messages)} messages from {remote_str}", RNS.LOG_VERBOSE)
|
||||
for lxmf_data in messages:
|
||||
peer = None
|
||||
transient_id = RNS.Identity.full_hash(lxmf_data)
|
||||
if remote_hash != None and remote_hash in self.peers:
|
||||
transient_id = RNS.Identity.full_hash(lxmf_data)
|
||||
peer = self.peers[remote_hash]
|
||||
peer.handled_messages[transient_id] = [transient_id, remote_timebase, lxmf_data]
|
||||
peer.incoming += 1
|
||||
peer.rx_bytes += len(lxmf_data)
|
||||
|
||||
self.lxmf_propagation(lxmf_data, from_peer=peer)
|
||||
if peer != None:
|
||||
peer.queue_handled_message(transient_id)
|
||||
|
||||
self.lxmf_propagation(lxmf_data)
|
||||
else:
|
||||
RNS.log("Invalid data structure received at propagation destination, ignoring", RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while unpacking received propagation resource", RNS.LOG_DEBUG)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def lxmf_propagation(self, lxmf_data, signal_local_delivery=None, signal_duplicate=None, is_paper_message=False):
|
||||
def enqueue_peer_distribution(self, transient_id, from_peer):
|
||||
self.peer_distribution_queue.append([transient_id, from_peer])
|
||||
|
||||
def flush_peer_distribution_queue(self):
|
||||
if len(self.peer_distribution_queue) > 0:
|
||||
entries = []
|
||||
while len(self.peer_distribution_queue) > 0:
|
||||
entries.append(self.peer_distribution_queue.pop())
|
||||
|
||||
for peer_id in self.peers.copy():
|
||||
if peer_id in self.peers:
|
||||
peer = self.peers[peer_id]
|
||||
for entry in entries:
|
||||
transient_id = entry[0]
|
||||
from_peer = entry[1]
|
||||
if peer != from_peer:
|
||||
peer.queue_unhandled_message(transient_id)
|
||||
|
||||
def lxmf_propagation(self, lxmf_data, signal_local_delivery=None, signal_duplicate=None, is_paper_message=False, from_peer=None):
|
||||
no_stamp_enforcement = False
|
||||
if is_paper_message:
|
||||
no_stamp_enforcement = True
|
||||
@@ -1637,7 +1898,6 @@ class LXMRouter:
|
||||
|
||||
if not transient_id in self.propagation_entries and not transient_id in self.locally_processed_transient_ids:
|
||||
received = time.time()
|
||||
propagation_entry = [transient_id, received, lxmf_data]
|
||||
destination_hash = lxmf_data[:LXMessage.DESTINATION_LENGTH]
|
||||
|
||||
self.locally_processed_transient_ids[transient_id] = received
|
||||
@@ -1661,12 +1921,9 @@ class LXMRouter:
|
||||
msg_file.write(lxmf_data)
|
||||
msg_file.close()
|
||||
|
||||
self.propagation_entries[transient_id] = [destination_hash, file_path, time.time(), len(lxmf_data)]
|
||||
|
||||
RNS.log("Received propagated LXMF message "+RNS.prettyhexrep(transient_id)+", adding to peer distribution queues...", RNS.LOG_DEBUG)
|
||||
for peer_id in self.peers:
|
||||
peer = self.peers[peer_id]
|
||||
peer.handle_message(transient_id)
|
||||
RNS.log("Received propagated LXMF message "+RNS.prettyhexrep(transient_id)+", adding to peer distribution queues...", RNS.LOG_EXTREME)
|
||||
self.propagation_entries[transient_id] = [destination_hash, file_path, time.time(), len(lxmf_data), [], []]
|
||||
self.enqueue_peer_distribution(transient_id, from_peer)
|
||||
|
||||
else:
|
||||
# TODO: Add message to sneakernet queues when implemented
|
||||
@@ -1686,6 +1943,7 @@ class LXMRouter:
|
||||
except Exception as e:
|
||||
RNS.log("Could not assemble propagated LXMF message from received data", RNS.LOG_DEBUG)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
|
||||
RNS.trace_exception(e)
|
||||
return False
|
||||
|
||||
def ingest_lxm_uri(self, uri, signal_local_delivery=None, signal_duplicate=None):
|
||||
@@ -1718,7 +1976,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)
|
||||
|
||||
@@ -1739,6 +1999,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:
|
||||
@@ -1750,10 +2019,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):
|
||||
@@ -1790,8 +2066,20 @@ class LXMRouter:
|
||||
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
|
||||
@@ -1804,7 +2092,7 @@ class LXMRouter:
|
||||
lxmessage.delivery_attempts += 1
|
||||
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
|
||||
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
|
||||
@@ -1814,7 +2102,7 @@ class LXMRouter:
|
||||
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.00
|
||||
lxmessage.progress = 0.01
|
||||
else:
|
||||
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
|
||||
lxmessage.delivery_attempts += 1
|
||||
@@ -1900,7 +2188,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)
|
||||
|
||||
+17
-10
@@ -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
|
||||
@@ -564,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__":
|
||||
|
||||
+25
-4
@@ -140,6 +140,24 @@ def apply_config():
|
||||
else:
|
||||
active_configuration["prioritised_lxmf_destinations"] = []
|
||||
|
||||
if "propagation" in lxmd_config and "static_peers" in lxmd_config["propagation"]:
|
||||
static_peers = lxmd_config["propagation"].as_list("static_peers")
|
||||
active_configuration["static_peers"] = []
|
||||
for static_peer in static_peers:
|
||||
active_configuration["static_peers"].append(bytes.fromhex(static_peer))
|
||||
else:
|
||||
active_configuration["static_peers"] = []
|
||||
|
||||
if "propagation" in lxmd_config and "max_peers" in lxmd_config["propagation"]:
|
||||
active_configuration["max_peers"] = lxmd_config["propagation"].as_int("max_peers")
|
||||
else:
|
||||
active_configuration["max_peers"] = None
|
||||
|
||||
if "propagation" in lxmd_config and "from_static_only" in lxmd_config["propagation"]:
|
||||
active_configuration["from_static_only"] = lxmd_config["propagation"].as_bool("from_static_only")
|
||||
else:
|
||||
active_configuration["from_static_only"] = False
|
||||
|
||||
# Load various settings
|
||||
if "logging" in lxmd_config and "loglevel" in lxmd_config["logging"]:
|
||||
targetloglevel = lxmd_config["logging"].as_int("loglevel")
|
||||
@@ -305,7 +323,10 @@ def program_setup(configdir = None, rnsconfigdir = None, run_pn = False, on_inbo
|
||||
autopeer_maxdepth = active_configuration["autopeer_maxdepth"],
|
||||
propagation_limit = active_configuration["propagation_transfer_max_accepted_size"],
|
||||
delivery_limit = active_configuration["delivery_transfer_max_accepted_size"],
|
||||
)
|
||||
max_peers = active_configuration["max_peers"],
|
||||
static_peers = active_configuration["static_peers"],
|
||||
from_static_only = active_configuration["from_static_only"])
|
||||
|
||||
message_router.register_delivery_callback(lxmf_delivery)
|
||||
|
||||
for destination_hash in active_configuration["ignored_lxmf_destinations"]:
|
||||
@@ -362,13 +383,13 @@ def jobs():
|
||||
try:
|
||||
if "peer_announce_interval" in active_configuration and active_configuration["peer_announce_interval"] != None:
|
||||
if time.time() > last_peer_announce + active_configuration["peer_announce_interval"]:
|
||||
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
|
||||
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_VERBOSE)
|
||||
message_router.announce(lxmf_destination.hash)
|
||||
last_peer_announce = time.time()
|
||||
|
||||
if "node_announce_interval" in active_configuration and active_configuration["node_announce_interval"] != None:
|
||||
if time.time() > last_node_announce + active_configuration["node_announce_interval"]:
|
||||
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_EXTREME)
|
||||
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_VERBOSE)
|
||||
message_router.announce_propagation_node()
|
||||
last_node_announce = time.time()
|
||||
|
||||
@@ -381,7 +402,7 @@ def deferred_start_jobs():
|
||||
global active_configuration, last_peer_announce, last_node_announce
|
||||
global message_router, lxmf_destination
|
||||
time.sleep(DEFFERED_JOBS_DELAY)
|
||||
RNS.log("Running deferred start jobs")
|
||||
RNS.log("Running deferred start jobs", RNS.LOG_DEBUG)
|
||||
if active_configuration["peer_announce_at_start"]:
|
||||
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
|
||||
message_router.announce(lxmf_destination.hash)
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__ = "0.5.3"
|
||||
__version__ = "0.6.1"
|
||||
@@ -12,6 +12,7 @@ User-facing clients built on LXMF include:
|
||||
|
||||
Community-provided tools and utilities for LXMF include:
|
||||
|
||||
- [LXMFy](https://lxmfy.quad4.io/)
|
||||
- [LXMF-Bot](https://github.com/randogoth/lxmf-bot)
|
||||
- [LXMF Messageboard](https://github.com/chengtripp/lxmf_messageboard)
|
||||
- [LXMEvent](https://github.com/faragher/LXMEvent)
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user