Compare commits

..
11 Commits
7 changed files with 200 additions and 38 deletions

No files matched your search

+13
View File
@@ -19,6 +19,7 @@ FIELD_GROUP = 0x0B
FIELD_TICKET = 0x0C FIELD_TICKET = 0x0C
FIELD_EVENT = 0x0D FIELD_EVENT = 0x0D
FIELD_RNR_REFS = 0x0E FIELD_RNR_REFS = 0x0E
FIELD_RENDERER = 0x0F
# For usecases such as including custom data structures, # For usecases such as including custom data structures,
# embedding or encapsulating other data types or protocols # embedding or encapsulating other data types or protocols
@@ -77,6 +78,18 @@ AM_OPUS_LOSSLESS = 0x19
# determine it itself based on the included data. # determine it itself based on the included data.
AM_CUSTOM = 0xFF 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 # # The following helper functions makes it easier to #
+14 -1
View File
@@ -48,6 +48,11 @@ class LXMPeer:
else: else:
peer.link_establishment_rate = 0 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: if "propagation_transfer_limit" in dictionary:
try: try:
peer.propagation_transfer_limit = float(dictionary["propagation_transfer_limit"]) peer.propagation_transfer_limit = float(dictionary["propagation_transfer_limit"])
@@ -73,6 +78,7 @@ class LXMPeer:
dictionary["last_heard"] = self.last_heard dictionary["last_heard"] = self.last_heard
dictionary["destination_hash"] = self.destination_hash dictionary["destination_hash"] = self.destination_hash
dictionary["link_establishment_rate"] = self.link_establishment_rate 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["propagation_transfer_limit"] = self.propagation_transfer_limit
handled_ids = [] handled_ids = []
@@ -96,6 +102,7 @@ class LXMPeer:
self.sync_backoff = 0 self.sync_backoff = 0
self.peering_timebase = 0 self.peering_timebase = 0
self.link_establishment_rate = 0 self.link_establishment_rate = 0
self.sync_transfer_rate = 0
self.propagation_transfer_limit = None self.propagation_transfer_limit = None
self.link = None self.link = None
@@ -257,6 +264,7 @@ class LXMPeer:
data = msgpack.packb([time.time(), lxm_list]) data = msgpack.packb([time.time(), lxm_list])
resource = RNS.Resource(data, self.link, callback = self.resource_concluded) resource = RNS.Resource(data, self.link, callback = self.resource_concluded)
resource.transferred_messages = wanted_message_ids resource.transferred_messages = wanted_message_ids
resource.sync_transfer_started = time.time()
self.state = LXMPeer.RESOURCE_TRANSFERRING self.state = LXMPeer.RESOURCE_TRANSFERRING
else: else:
@@ -289,7 +297,12 @@ class LXMPeer:
self.link = None self.link = None
self.state = LXMPeer.IDLE 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.alive = True
self.last_heard = time.time() self.last_heard = time.time()
+98 -17
View File
@@ -16,6 +16,8 @@ from .LXMessage import LXMessage
from .Handlers import LXMFDeliveryAnnounceHandler from .Handlers import LXMFDeliveryAnnounceHandler
from .Handlers import LXMFPropagationAnnounceHandler from .Handlers import LXMFPropagationAnnounceHandler
import LXMF.LXStamper as LXStamper
class LXMRouter: class LXMRouter:
MAX_DELIVERY_ATTEMPTS = 5 MAX_DELIVERY_ATTEMPTS = 5
PROCESSING_INTERVAL = 4 PROCESSING_INTERVAL = 4
@@ -143,19 +145,38 @@ class LXMRouter:
if os.path.isfile(self.storagepath+"/local_deliveries"): if os.path.isfile(self.storagepath+"/local_deliveries"):
locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb") locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb")
data = locally_delivered_file.read() data = locally_delivered_file.read()
self.locally_delivered_transient_ids = msgpack.unpackb(data)
locally_delivered_file.close() locally_delivered_file.close()
self.locally_delivered_transient_ids = msgpack.unpackb(data)
if os.path.isfile(self.storagepath+"/locally_processed"): if not type(self.locally_delivered_transient_ids) == dict:
locally_processed_file = open(self.storagepath+"/locally_processed", "rb") RNS.log("Invalid data format for loaded locally delivered transient IDs, recreating...", RNS.LOG_ERROR)
data = locally_processed_file.read() self.locally_delivered_transient_ids = {}
self.locally_processed_transient_ids = msgpack.unpackb(data)
locally_processed_file.close()
self.clean_transient_id_caches()
except Exception as e: 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) 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: try:
if os.path.isfile(self.storagepath+"/outbound_stamp_costs"): if os.path.isfile(self.storagepath+"/outbound_stamp_costs"):
@@ -163,6 +184,9 @@ class LXMRouter:
with open(self.storagepath+"/outbound_stamp_costs", "rb") as outbound_stamp_cost_file: with open(self.storagepath+"/outbound_stamp_costs", "rb") as outbound_stamp_cost_file:
data = outbound_stamp_cost_file.read() data = outbound_stamp_cost_file.read()
self.outbound_stamp_costs = msgpack.unpackb(data) 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.clean_outbound_stamp_costs()
self.save_outbound_stamp_costs() self.save_outbound_stamp_costs()
@@ -1212,6 +1236,33 @@ class LXMRouter:
else: else:
return False 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): def handle_outbound(self, lxmessage):
destination_hash = lxmessage.get_destination().hash destination_hash = lxmessage.get_destination().hash
@@ -1502,12 +1553,12 @@ class LXMRouter:
if len(waiting_peers) > 0: if len(waiting_peers) > 0:
fastest_peers = sorted( fastest_peers = sorted(
waiting_peers, waiting_peers,
key=lambda p: p.link_establishment_rate, key=lambda p: p.sync_transfer_rate,
reverse=True reverse=True
)[0:min(LXMRouter.FASTEST_N_RANDOM_POOL, len(waiting_peers))] )[0:min(LXMRouter.FASTEST_N_RANDOM_POOL, len(waiting_peers))]
peer_pool.extend(fastest_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: if len(unknown_speed_peers) > 0:
peer_pool.extend( peer_pool.extend(
unknown_speed_peers[ unknown_speed_peers[
@@ -1726,7 +1777,9 @@ class LXMRouter:
self.failed_outbound.append(lxmessage) 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): if lxmessage.failed_callback != None and callable(lxmessage.failed_callback):
lxmessage.failed_callback(lxmessage) lxmessage.failed_callback(lxmessage)
@@ -1747,6 +1800,15 @@ class LXMRouter:
selected_message_id = message_id selected_message_id = message_id
if selected_lxm != None: 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) RNS.log(f"Starting stamp generation for {selected_lxm}...", RNS.LOG_DEBUG)
generated_stamp = selected_lxm.get_stamp() generated_stamp = selected_lxm.get_stamp()
if generated_stamp: if generated_stamp:
@@ -1758,10 +1820,17 @@ class LXMRouter:
self.pending_outbound.append(selected_lxm) self.pending_outbound.append(selected_lxm)
RNS.log(f"Stamp generation completed for {selected_lxm}", RNS.LOG_DEBUG) RNS.log(f"Stamp generation completed for {selected_lxm}", RNS.LOG_DEBUG)
else: else:
RNS.log(f"Deferred stamp generation did not succeed. Failing {selected_lxm}.", RNS.LOG_ERROR) if selected_lxm.state == LXMessage.CANCELLED:
selected_lxm.stamp_generation_failed = True RNS.log(f"Message cancelled during deferred stamp generation for {selected_lxm}.", RNS.LOG_DEBUG)
self.pending_deferred_stamps.pop(selected_message_id) selected_lxm.stamp_generation_failed = True
self.fail_message(selected_lxm) 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): def process_outbound(self, sender = None):
@@ -1798,8 +1867,20 @@ class LXMRouter:
RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG) RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
self.pending_outbound.remove(lxmessage) 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: 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: if lxmessage.progress == None or lxmessage.progress < 0.01:
lxmessage.progress = 0.01 lxmessage.progress = 0.01
+16 -9
View File
@@ -16,8 +16,10 @@ class LXMessage:
SENDING = 0x02 SENDING = 0x02
SENT = 0x04 SENT = 0x04
DELIVERED = 0x08 DELIVERED = 0x08
REJECTED = 0xFD
CANCELLED = 0xFE
FAILED = 0xFF FAILED = 0xFF
states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, FAILED] states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, REJECTED, CANCELLED, FAILED]
UNKNOWN = 0x00 UNKNOWN = 0x00
PACKET = 0x01 PACKET = 0x01
@@ -564,22 +566,27 @@ class LXMessage:
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
self.__mark_delivered() self.__mark_delivered()
else: else:
resource.link.teardown() if resource.status == RNS.Resource.REJECTED:
self.state = LXMessage.OUTBOUND self.state = LXMessage.REJECTED
elif self.state != LXMessage.CANCELLED:
resource.link.teardown()
self.state = LXMessage.OUTBOUND
def __propagation_resource_concluded(self, resource): def __propagation_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
self.__mark_propagated() self.__mark_propagated()
else: else:
resource.link.teardown() if self.state != LXMessage.CANCELLED:
self.state = LXMessage.OUTBOUND resource.link.teardown()
self.state = LXMessage.OUTBOUND
def __link_packet_timed_out(self, packet_receipt): def __link_packet_timed_out(self, packet_receipt):
if packet_receipt: if self.state != LXMessage.CANCELLED:
packet_receipt.destination.teardown() if packet_receipt:
packet_receipt.destination.teardown()
self.state = LXMessage.OUTBOUND
self.state = LXMessage.OUTBOUND
def __update_transfer_progress(self, resource): def __update_transfer_progress(self, resource):
self.progress = 0.10 + (resource.get_progress()*0.90) self.progress = 0.10 + (resource.get_progress()*0.90)
+57 -9
View File
@@ -7,6 +7,8 @@ import multiprocessing
WORKBLOCK_EXPAND_ROUNDS = 3000 WORKBLOCK_EXPAND_ROUNDS = 3000
active_jobs = {}
def stamp_workblock(message_id): def stamp_workblock(message_id):
wb_st = time.time() wb_st = time.time()
expand_rounds = WORKBLOCK_EXPAND_ROUNDS expand_rounds = WORKBLOCK_EXPAND_ROUNDS
@@ -44,23 +46,56 @@ def generate_stamp(message_id, stamp_cost):
value = 0 value = 0
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin(): 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(): elif RNS.vendor.platformutils.is_android():
stamp, rounds = job_android(stamp_cost, workblock) stamp, rounds = job_android(stamp_cost, workblock, message_id)
else: else:
stamp, rounds = job_linux(stamp_cost, workblock) stamp, rounds = job_linux(stamp_cost, workblock, message_id)
duration = time.time() - start_time duration = time.time() - start_time
speed = rounds/duration 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) 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 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. # A simple, single-process stamp generator.
# should work on any platform, and is used # should work on any platform, and is used
# as a fall-back, in case of limited multi- # as a fall-back, in case of limited multi-
@@ -73,6 +108,8 @@ def job_simple(stamp_cost, workblock):
pstamp = os.urandom(256//8) pstamp = os.urandom(256//8)
st = time.time() st = time.time()
active_jobs[message_id] = False;
def sv(s, c, w): def sv(s, c, w):
target = 0b1<<256-c; m = w+s target = 0b1<<256-c; m = w+s
result = RNS.Identity.full_hash(m) result = RNS.Identity.full_hash(m)
@@ -81,15 +118,20 @@ def job_simple(stamp_cost, workblock):
else: else:
return True 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 pstamp = os.urandom(256//8); rounds += 1
if rounds % 2500 == 0: if rounds % 2500 == 0:
speed = rounds / (time.time()-st) speed = rounds / (time.time()-st)
RNS.log(f"Stamp generation running. {rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG) 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 return pstamp, rounds
def job_linux(stamp_cost, workblock): def job_linux(stamp_cost, workblock, message_id):
allow_kill = True allow_kill = True
stamp = None stamp = None
total_rounds = 0 total_rounds = 0
@@ -126,6 +168,8 @@ def job_linux(stamp_cost, workblock):
job_procs.append(process) job_procs.append(process)
process.start() process.start()
active_jobs[message_id] = [stop_event, result_queue]
stamp = result_queue.get() stamp = result_queue.get()
RNS.log("Got stamp result from worker", RNS.LOG_DEBUG) # TODO: Remove 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 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 # Semaphore support is flaky to non-existent on
# Android, so we need to manually dispatch and # Android, so we need to manually dispatch and
# manage workloads here, while periodically # 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.log(f"Stamp generation worker error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e) RNS.trace_exception(e)
active_jobs[message_id] = False;
RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove
results_dict = wm.dict() results_dict = wm.dict()
while stamp == None: while stamp == None and active_jobs[message_id] == False:
job_procs = [] job_procs = []
try: try:
for pnum in range(jobs): for pnum in range(jobs):
@@ -260,6 +306,8 @@ def job_android(stamp_cost, workblock):
RNS.log(f"Stamp generation job error: {e}") RNS.log(f"Stamp generation job error: {e}")
RNS.trace_exception(e) RNS.trace_exception(e)
active_jobs.pop(message_id)
return stamp, total_rounds return stamp, total_rounds
if __name__ == "__main__": if __name__ == "__main__":
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.5.8" __version__ = "0.6.0"
+1 -1
View File
@@ -25,6 +25,6 @@ setuptools.setup(
'lxmd=LXMF.Utilities.lxmd:main', 'lxmd=LXMF.Utilities.lxmd:main',
] ]
}, },
install_requires=['rns>=0.8.6'], install_requires=['rns>=0.9.1'],
python_requires='>=3.7', python_requires='>=3.7',
) )