mirror of
https://github.com/markqvist/LXMF
synced 2026-11-22 23:10:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0793f6677 | ||
|
|
2059784a55 | ||
|
|
2b09146a15 | ||
|
|
c7a902f0aa | ||
|
|
d845503b33 | ||
|
|
40dcd7d084 | ||
|
|
8ded002689 | ||
|
|
810c345de8 | ||
|
|
2c69fd3684 | ||
|
|
3297f21e62 | ||
|
|
6e898e67ad | ||
|
|
1df7ebcdd5 | ||
|
|
cc702b75a7 | ||
|
|
98e09bbec0 | ||
|
|
86692183d9 | ||
|
|
c98bca2dce | ||
|
|
d6df0f7e91 | ||
|
|
700a462674 | ||
|
|
01387b15f4 | ||
|
|
308498e68b |
No files matched your search
@@ -64,6 +64,14 @@ class LXMFPropagationAnnounceHandler:
|
||||
propagation_stamp_cost_flexibility = int(data[5][1])
|
||||
peering_cost = int(data[5][2])
|
||||
metadata = data[6]
|
||||
|
||||
# Transitional mechanism, extract the real, fractional-value
|
||||
# propagation stamp cost if available.
|
||||
if len(data) > 7:
|
||||
propagation_stamp_cost = data[7][0]
|
||||
propagation_stamp_cost_flexibility = data[7][1]
|
||||
peering_cost = data[7][2]
|
||||
# TODO: Remove above after 1.6.2 ###########################
|
||||
|
||||
if destination_hash in self.lxmrouter.static_peers:
|
||||
static_peer = self.lxmrouter.peers[destination_hash]
|
||||
|
||||
+33
-9
@@ -155,7 +155,11 @@ def display_name_from_app_data(app_data=None):
|
||||
else:
|
||||
# Version 0.5.0+ announce format
|
||||
if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc:
|
||||
peer_data = msgpack.unpackb(app_data)
|
||||
try: peer_data = msgpack.unpackb(app_data)
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||
return None
|
||||
|
||||
if type(peer_data) == list:
|
||||
if len(peer_data) < 1: return None
|
||||
else:
|
||||
@@ -166,11 +170,15 @@ def display_name_from_app_data(app_data=None):
|
||||
decoded = dn.decode("utf-8").replace("\x00", "").strip()
|
||||
return decoded
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME)
|
||||
RNS.log(f"Could not decode display name in included announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||
return None
|
||||
|
||||
# Original announce format
|
||||
else: return app_data.decode("utf-8")
|
||||
# Legacy announce format
|
||||
else:
|
||||
try: return app_data.decode("utf-8")
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not decode display name in legacy announce data. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||
return None
|
||||
|
||||
def stamp_cost_from_app_data(app_data=None):
|
||||
if app_data == None or app_data == b"": return None
|
||||
@@ -180,7 +188,12 @@ def stamp_cost_from_app_data(app_data=None):
|
||||
peer_data = msgpack.unpackb(app_data)
|
||||
if type(peer_data) == list:
|
||||
if len(peer_data) < 2: return None
|
||||
else: return peer_data[1]
|
||||
else:
|
||||
if len(peer_data) > 3:
|
||||
cost_type = type(peer_data[3])
|
||||
if cost_type == float or cost_type == int: return peer_data[3]
|
||||
else: return peer_data[1]
|
||||
else: return peer_data[1]
|
||||
|
||||
# Original announce format
|
||||
else: return None
|
||||
@@ -218,7 +231,8 @@ def pn_stamp_cost_from_app_data(app_data=None):
|
||||
else:
|
||||
if pn_announce_data_is_valid(app_data):
|
||||
data = msgpack.unpackb(app_data)
|
||||
return data[5][0]
|
||||
if len(data) > 7: return data[7][0]
|
||||
else: return data[5][0]
|
||||
|
||||
else: return None
|
||||
|
||||
@@ -236,13 +250,23 @@ def pn_announce_data_is_valid(data):
|
||||
try: int(data[4])
|
||||
except: raise ValueError("Invalid announce data: Could not decode propagation sync limit")
|
||||
if type(data[5]) != list: raise ValueError("Invalid announce data: Could not decode stamp costs")
|
||||
try: int(data[5][0])
|
||||
try: float(data[5][0])
|
||||
except: raise ValueError("Invalid announce data: Could not decode target stamp cost")
|
||||
try: int(data[5][1])
|
||||
try: float(data[5][1])
|
||||
except: raise ValueError("Invalid announce data: Could not decode stamp cost flexibility")
|
||||
try: int(data[5][2])
|
||||
try: float(data[5][2])
|
||||
except: raise ValueError("Invalid announce data: Could not decode peering cost")
|
||||
if type(data[6]) != dict: raise ValueError("Invalid announce data: Could not decode metadata")
|
||||
|
||||
# TODO: Transitional mechanism, remove after 1.6.2
|
||||
if len(data) > 7:
|
||||
if type(data[7]) != list: raise ValueError("Invalid announce data: Could not decode fractional stamp costs")
|
||||
try: float(data[7][0])
|
||||
except: raise ValueError("Invalid announce data: Could not decode target stamp cost")
|
||||
try: float(data[7][1])
|
||||
except: raise ValueError("Invalid announce data: Could not decode stamp cost flexibility")
|
||||
try: float(data[7][2])
|
||||
except: raise ValueError("Invalid announce data: Could not decode peering cost")
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not validate propagation node announce data: {e}", RNS.LOG_DEBUG)
|
||||
|
||||
+11
-9
@@ -79,17 +79,17 @@ class LXMPeer:
|
||||
else: peer.propagation_sync_limit = peer.propagation_transfer_limit
|
||||
|
||||
if "propagation_stamp_cost" in dictionary:
|
||||
try: peer.propagation_stamp_cost = int(dictionary["propagation_stamp_cost"])
|
||||
try: peer.propagation_stamp_cost = float(dictionary["propagation_stamp_cost"])
|
||||
except: peer.propagation_stamp_cost = None
|
||||
else: peer.propagation_stamp_cost = None
|
||||
|
||||
if "propagation_stamp_cost_flexibility" in dictionary:
|
||||
try: peer.propagation_stamp_cost_flexibility = int(dictionary["propagation_stamp_cost_flexibility"])
|
||||
try: peer.propagation_stamp_cost_flexibility = float(dictionary["propagation_stamp_cost_flexibility"])
|
||||
except: peer.propagation_stamp_cost_flexibility = None
|
||||
else: peer.propagation_stamp_cost_flexibility = None
|
||||
|
||||
if "peering_cost" in dictionary:
|
||||
try: peer.peering_cost = int(dictionary["peering_cost"])
|
||||
try: peer.peering_cost = float(dictionary["peering_cost"])
|
||||
except: peer.peering_cost = None
|
||||
else: peer.peering_cost = None
|
||||
|
||||
@@ -217,9 +217,11 @@ class LXMPeer:
|
||||
|
||||
self.router = router
|
||||
self.destination_hash = destination_hash
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
self.resolve_identity()
|
||||
|
||||
def resolve_identity(self):
|
||||
self.identity = RNS.Identity.recall(self.destination_hash)
|
||||
if self.identity != None: self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
else:
|
||||
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)
|
||||
@@ -250,7 +252,7 @@ class LXMPeer:
|
||||
return False
|
||||
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.identity = RNS.Identity.recall(self.destination_hash)
|
||||
if self.identity == None:
|
||||
RNS.log(f"Could not update peering key for {self} since its identity could not be recalled", RNS.LOG_ERROR)
|
||||
return False
|
||||
@@ -305,7 +307,7 @@ class LXMPeer:
|
||||
|
||||
else:
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.identity = RNS.Identity.recall(self.destination_hash)
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
@@ -510,7 +512,7 @@ class LXMPeer:
|
||||
|
||||
rate_str = ""
|
||||
if self.current_sync_transfer_started != None:
|
||||
self.sync_transfer_rate = (resource.get_transfer_size()*8)/(time.time()-self.current_sync_transfer_started)
|
||||
self.sync_transfer_rate = (resource.get_transfer_size()*8) / max(time.time()-self.current_sync_transfer_started, 1E-6)
|
||||
rate_str = f" at {RNS.prettyspeed(self.sync_transfer_rate)}"
|
||||
|
||||
RNS.log(f"Syncing {len(self.currently_transferring_messages)} messages to peer {RNS.prettyhexrep(self.destination_hash)} completed{rate_str}", RNS.LOG_VERBOSE)
|
||||
|
||||
+334
-81
@@ -23,11 +23,16 @@ from .LXMF import pn_announce_data_is_valid
|
||||
|
||||
from .LXMPeer import LXMPeer
|
||||
from .LXMessage import LXMessage
|
||||
from .Storage import LXMFStore
|
||||
from .Handlers import LXMFDeliveryAnnounceHandler
|
||||
from .Handlers import LXMFPropagationAnnounceHandler
|
||||
|
||||
from RNS.Stamps import quantize_cost
|
||||
|
||||
import LXMF.LXStamper as LXStamper
|
||||
|
||||
from math import ceil # TODO: Transitory import, remove after RNS 1.6.2
|
||||
|
||||
class LXMRouter:
|
||||
MAX_DELIVERY_ATTEMPTS = 5
|
||||
PROCESSING_INTERVAL = 4
|
||||
@@ -45,6 +50,9 @@ class LXMRouter:
|
||||
|
||||
NODE_ANNOUNCE_DELAY = 20
|
||||
|
||||
DELIVERY_LINK_COST = 3.25
|
||||
PROPAGATION_LINK_COST = 3.25
|
||||
|
||||
MAX_PEERS = 20
|
||||
AUTOPEER = True
|
||||
AUTOPEER_MAXDEPTH = 4
|
||||
@@ -52,11 +60,11 @@ class LXMRouter:
|
||||
ROTATION_HEADROOM_PCT = 10
|
||||
ROTATION_AR_MAX = 0.5
|
||||
|
||||
PEERING_COST = 18
|
||||
MAX_PEERING_COST = 26
|
||||
PROPAGATION_COST_MIN = 13
|
||||
PROPAGATION_COST_FLEX = 3
|
||||
PROPAGATION_COST = 16
|
||||
PEERING_COST = 18.0
|
||||
MAX_PEERING_COST = 26.0
|
||||
PROPAGATION_COST_MIN = 13.0
|
||||
PROPAGATION_COST_FLEX = 3.0
|
||||
PROPAGATION_COST = 16.0
|
||||
PROPAGATION_LIMIT = 256
|
||||
SEQUENTIAL_VALIDATION = True
|
||||
STATIC_SEQUENTIAL = False
|
||||
@@ -65,7 +73,7 @@ class LXMRouter:
|
||||
DELIVERY_LIMIT = 1000
|
||||
|
||||
PR_PATH_TIMEOUT = 10
|
||||
PN_STAMP_THROTTLE = 180
|
||||
PN_STAMP_THROTTLE = 300
|
||||
|
||||
PR_IDLE = 0x00
|
||||
PR_PATH_REQUESTED = 0x01
|
||||
@@ -95,6 +103,7 @@ class LXMRouter:
|
||||
SYNC_REQUEST_PATH = "/pn/peer/sync"
|
||||
UNPEER_REQUEST_PATH = "/pn/peer/unpeer"
|
||||
|
||||
REQUIRED_DESTINATION_TYPES = [f"{APP_NAME}.delivery", f"{APP_NAME}.propagation"]
|
||||
|
||||
### Developer-facing API ##############################
|
||||
#######################################################
|
||||
@@ -105,10 +114,12 @@ class LXMRouter:
|
||||
from_static_only=False, sync_strategy=LXMPeer.STRATEGY_PERSISTENT,
|
||||
propagation_cost=PROPAGATION_COST, propagation_cost_flexibility=PROPAGATION_COST_FLEX,
|
||||
peering_cost=PEERING_COST, max_peering_cost=MAX_PEERING_COST, max_inbound_syncs=MAX_INBOUND_SYNCS,
|
||||
sequential_validation=SEQUENTIAL_VALIDATION, static_sequential=STATIC_SEQUENTIAL):
|
||||
sequential_validation=SEQUENTIAL_VALIDATION, static_sequential=STATIC_SEQUENTIAL,
|
||||
pn_stamp_throttle=PN_STAMP_THROTTLE):
|
||||
|
||||
random.seed(os.urandom(10))
|
||||
|
||||
self.store = None
|
||||
self.pending_inbound = []
|
||||
self.pending_outbound = []
|
||||
self.direct_links = {}
|
||||
@@ -131,13 +142,22 @@ class LXMRouter:
|
||||
self.name = name
|
||||
|
||||
self.propagation_node = False
|
||||
self.propagation_node_start_time = None
|
||||
self.propagation_node_start_time = None
|
||||
self.pn_stamp_throttle = pn_stamp_throttle
|
||||
|
||||
if storagepath == None: raise ValueError("LXMF cannot be initialised without a storage path")
|
||||
else:
|
||||
self.storagepath = storagepath+"/lxmf"
|
||||
self.ratchetpath = self.storagepath+"/ratchets"
|
||||
|
||||
try:
|
||||
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
|
||||
self.store = LXMFStore(self.storagepath+"/state.db")
|
||||
except Exception as e:
|
||||
RNS.log("Could not initialise the LXMF store, falling back to legacy file-based caches. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
self.store = None
|
||||
|
||||
self.outbound_propagation_node = None
|
||||
self.outbound_propagation_link = None
|
||||
|
||||
@@ -158,6 +178,7 @@ class LXMRouter:
|
||||
self.max_peering_cost = max_peering_cost
|
||||
self.enforce_ratchets = enforce_ratchets
|
||||
self._enforce_stamps = enforce_stamps
|
||||
self.__stamp_costs_dirty = False
|
||||
self.pending_deferred_stamps = {}
|
||||
self.throttled_peers = {}
|
||||
|
||||
@@ -192,11 +213,13 @@ class LXMRouter:
|
||||
self.incoming_delivery_resource_lock = threading.Lock()
|
||||
self.exit_handler_running = False
|
||||
|
||||
for destination_type in self.REQUIRED_DESTINATION_TYPES:
|
||||
RNS.Reticulum.get_instance().wants_destination_type(destination_type)
|
||||
|
||||
if identity == None: identity = RNS.Identity()
|
||||
|
||||
self.identity = identity
|
||||
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
self.propagation_destination.set_default_app_data(self.get_propagation_node_app_data)
|
||||
self.propagation_destination = None
|
||||
self.control_destination = None
|
||||
self.validating_pn_stamps_from = {}
|
||||
self.incoming_delivery_resources = {}
|
||||
@@ -236,6 +259,44 @@ class LXMRouter:
|
||||
|
||||
self.__delivery_callback = None
|
||||
|
||||
# TODO: Remove legacy import/load after transition window ###
|
||||
if self.store != None: self.__import_legacy_storage() #
|
||||
else: self.__load_legacy_storage() #
|
||||
#############################################################
|
||||
|
||||
atexit.register(self.exit_handler)
|
||||
signal.signal(signal.SIGINT, self.sigint_handler)
|
||||
signal.signal(signal.SIGTERM, self.sigterm_handler)
|
||||
|
||||
job_thread = threading.Thread(target=self.jobloop)
|
||||
job_thread.setDaemon(True)
|
||||
job_thread.start()
|
||||
|
||||
def __import_legacy_storage(self):
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/local_deliveries"): self.store.import_legacy_delivered(self.storagepath+"/local_deliveries")
|
||||
except Exception as e: RNS.log("Could not import legacy local deliveries cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/locally_processed"): self.store.import_legacy_processed(self.storagepath+"/locally_processed")
|
||||
except Exception as e: RNS.log("Could not import legacy locally processed cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/outbound_stamp_costs"): self.store.import_legacy_stamp_costs(self.storagepath+"/outbound_stamp_costs")
|
||||
except Exception as e: RNS.log("Could not import legacy outbound stamp costs cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/available_tickets"): self.store.import_legacy_tickets(self.storagepath+"/available_tickets")
|
||||
except Exception as e: RNS.log("Could not import legacy available tickets cache into the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
try:
|
||||
self.clean_transient_id_caches()
|
||||
self.clean_outbound_stamp_costs()
|
||||
self.clean_available_tickets()
|
||||
self.store.incremental_vacuum()
|
||||
except Exception as e: RNS.log("Could not perform initial cleaning of the LXMF store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def __load_legacy_storage(self):
|
||||
try:
|
||||
if os.path.isfile(self.storagepath+"/local_deliveries"):
|
||||
locally_delivered_file = open(self.storagepath+"/local_deliveries", "rb")
|
||||
@@ -312,14 +373,6 @@ class LXMRouter:
|
||||
except Exception as e:
|
||||
RNS.log("Could not load outbound stamp costs from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
atexit.register(self.exit_handler)
|
||||
signal.signal(signal.SIGINT, self.sigint_handler)
|
||||
signal.signal(signal.SIGTERM, self.sigterm_handler)
|
||||
|
||||
job_thread = threading.Thread(target=self.jobloop)
|
||||
job_thread.setDaemon(True)
|
||||
job_thread.start()
|
||||
|
||||
def announce(self, destination_hash, attached_interface=None):
|
||||
if destination_hash in self.delivery_destinations:
|
||||
self.delivery_destinations[destination_hash].announce(app_data=self.get_announce_app_data(destination_hash), attached_interface=attached_interface)
|
||||
@@ -334,14 +387,16 @@ class LXMRouter:
|
||||
def get_propagation_node_app_data(self):
|
||||
metadata = self.get_propagation_node_announce_metadata()
|
||||
node_state = self.propagation_node and not self.from_static_only
|
||||
stamp_cost = [self.propagation_stamp_cost, self.propagation_stamp_cost_flexibility, self.peering_cost]
|
||||
stamp_costs = [self.propagation_stamp_cost, self.propagation_stamp_cost_flexibility, self.peering_cost]
|
||||
ceil_costs = [ceil(self.propagation_stamp_cost), ceil(self.propagation_stamp_cost_flexibility), ceil(self.peering_cost)]
|
||||
announce_data = [ False, # 0: Legacy LXMF PN support
|
||||
int(time.time()), # 1: Current node timebase
|
||||
node_state, # 2: Boolean flag signalling propagation node state
|
||||
self.propagation_per_transfer_limit, # 3: Per-transfer limit for message propagation in kilobytes
|
||||
self.propagation_per_sync_limit, # 4: Limit for incoming propagation node syncs
|
||||
stamp_cost, # 5: Propagation stamp cost for this node
|
||||
metadata ] # 6: Node metadata
|
||||
ceil_costs, # 5: Propagation stamp cost for this node
|
||||
metadata, # 6: Node metadata
|
||||
stamp_costs ] # 7: Transitional fractional-value stamp cost, will disappear after 1.6.2, where they will be in 5 directly
|
||||
|
||||
return msgpack.packb(announce_data)
|
||||
|
||||
@@ -364,6 +419,7 @@ class LXMRouter:
|
||||
os.makedirs(self.ratchetpath)
|
||||
|
||||
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
delivery_destination.set_link_cost(self.DELIVERY_LINK_COST)
|
||||
delivery_destination.enable_ratchets(f"{self.ratchetpath}/{RNS.hexrep(delivery_destination.hash, delimit=False)}.ratchets")
|
||||
delivery_destination.set_packet_callback(self.delivery_packet)
|
||||
delivery_destination.set_link_established_callback(self.delivery_link_established)
|
||||
@@ -388,22 +444,29 @@ class LXMRouter:
|
||||
def set_inbound_stamp_cost(self, destination_hash, stamp_cost):
|
||||
if destination_hash in self.delivery_destinations:
|
||||
delivery_destination = self.delivery_destinations[destination_hash]
|
||||
cap = RNS.Transport.STAMP_COST_CAP
|
||||
if stamp_cost == None:
|
||||
delivery_destination.stamp_cost = None
|
||||
return True
|
||||
elif type(stamp_cost) == int:
|
||||
if stamp_cost < 1:
|
||||
delivery_destination.stamp_cost = None
|
||||
elif stamp_cost < 255:
|
||||
delivery_destination.stamp_cost = stamp_cost
|
||||
else:
|
||||
return False
|
||||
|
||||
if stamp_cost < 1: delivery_destination.stamp_cost = None
|
||||
elif stamp_cost < cap: delivery_destination.stamp_cost = stamp_cost
|
||||
else: return False
|
||||
return True
|
||||
elif type(stamp_cost) == float:
|
||||
if stamp_cost < 1: delivery_destination.stamp_cost = None
|
||||
elif stamp_cost < cap: delivery_destination.stamp_cost = stamp_cost
|
||||
else: return False
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def get_outbound_stamp_cost(self, destination_hash):
|
||||
if self.store != None: return self.store.get_outbound_stamp_cost(destination_hash)
|
||||
else: return self.get_outbound_stamp_cost_legacy(destination_hash)
|
||||
|
||||
# TODO: Remove legacy handling after transition
|
||||
def get_outbound_stamp_cost_legacy(self, destination_hash):
|
||||
if destination_hash in self.outbound_stamp_costs:
|
||||
stamp_cost = self.outbound_stamp_costs[destination_hash][1]
|
||||
return stamp_cost
|
||||
@@ -434,7 +497,8 @@ class LXMRouter:
|
||||
pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash)
|
||||
if pn_announce_data_is_valid(pn_app_data):
|
||||
pn_config = msgpack.unpackb(pn_app_data)
|
||||
target_propagation_cost = pn_config[5][0]
|
||||
if len(pn_config) > 7: target_propagation_cost = pn_config[7][0]
|
||||
else: target_propagation_cost = pn_config[5][0]
|
||||
|
||||
if not target_propagation_cost:
|
||||
RNS.log(f"Could not retrieve cached propagation node config. Requesting path to propagation node to get target propagation cost...", RNS.LOG_DEBUG)
|
||||
@@ -446,9 +510,12 @@ class LXMRouter:
|
||||
pn_app_data = RNS.Identity.recall_app_data(pn_destination_hash)
|
||||
if pn_announce_data_is_valid(pn_app_data):
|
||||
pn_config = msgpack.unpackb(pn_app_data)
|
||||
target_propagation_cost = pn_config[5][0]
|
||||
if len(pn_config) > 7: target_propagation_cost = pn_config[7][0]
|
||||
else: target_propagation_cost = pn_config[5][0]
|
||||
|
||||
if type(target_propagation_cost) not in (float, int) and target_propagation_cost != None: return None
|
||||
if not target_propagation_cost: RNS.log("Propagation node stamp cost still unavailable after path request", RNS.LOG_ERROR)
|
||||
if target_propagation_cost != None: target_propagation_cost = max(0, min(target_propagation_cost, RNS.Transport.STAMP_COST_CAP))
|
||||
return target_propagation_cost
|
||||
|
||||
def set_inbound_propagation_node(self, destination_hash):
|
||||
@@ -562,6 +629,11 @@ class LXMRouter:
|
||||
|
||||
def enable_propagation(self):
|
||||
try:
|
||||
if not self.propagation_destination:
|
||||
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
self.propagation_destination.set_link_cost(self.PROPAGATION_LINK_COST)
|
||||
self.propagation_destination.set_default_app_data(self.get_propagation_node_app_data)
|
||||
|
||||
self.messagepath = self.storagepath+"/messagestore"
|
||||
|
||||
if not os.path.isdir(self.storagepath):
|
||||
@@ -581,7 +653,7 @@ class LXMRouter:
|
||||
try:
|
||||
transient_id = bytes.fromhex(components[0])
|
||||
received = float(components[1])
|
||||
stamp_value = int(components[2])
|
||||
stamp_value = quantize_cost(components[2])
|
||||
filepath = self.messagepath+"/"+filename
|
||||
msg_size = os.path.getsize(filepath)
|
||||
file = open(filepath, "rb")
|
||||
@@ -626,13 +698,26 @@ class LXMRouter:
|
||||
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:
|
||||
self.request_path(peer.destination_hash)
|
||||
RNS.log(f"Attempting to resolve initial peering data for static peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
|
||||
RNS.Transport.await_path(peer.destination_hash, timeout=5.0)
|
||||
peer.resolve_identity()
|
||||
|
||||
if peer.identity == None:
|
||||
if peer in self.static_peers:
|
||||
RNS.log(f"Attempting to resolve unknown identity for static peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
|
||||
RNS.Transport.await_path(peer.destination_hash, timeout=7.5)
|
||||
peer.resolve_identity()
|
||||
else:
|
||||
RNS.log(f"Attempting to resolve unknown identity for peer {RNS.prettyhexrep(peer.destination_hash)}", RNS.LOG_NOTICE)
|
||||
RNS.Transport.await_path(peer.destination_hash, timeout=2.5)
|
||||
peer.resolve_identity()
|
||||
|
||||
if peer.identity != None:
|
||||
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"
|
||||
if peer.propagation_transfer_limit != None: lim_str = ", "+RNS.prettysize(peer.propagation_transfer_limit*1000)+" transfer limit"
|
||||
RNS.log("Rebuilt peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(peer.unhandled_message_count)+" unhandled messages"+lim_str, RNS.LOG_DEBUG)
|
||||
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)
|
||||
@@ -884,9 +969,12 @@ class LXMRouter:
|
||||
JOB_RESOURCE_INTERVAL = 2
|
||||
JOB_TRANSIENT_INTERVAL = 60
|
||||
JOB_STORE_INTERVAL = 120
|
||||
JOB_STAMPCOST_INTERVAL = 120
|
||||
JOB_PEERSYNC_INTERVAL = 6
|
||||
JOB_PEERINGEST_INTERVAL= JOB_PEERSYNC_INTERVAL
|
||||
JOB_ROTATE_INTERVAL = 56*JOB_PEERINGEST_INTERVAL
|
||||
STORE_CULL_CHUNKS = 16
|
||||
|
||||
def jobs(self):
|
||||
if not self.exit_handler_running:
|
||||
self.processing_count += 1
|
||||
@@ -919,6 +1007,13 @@ class LXMRouter:
|
||||
if self.propagation_node == True: self.sync_peers()
|
||||
self.clean_throttled_peers()
|
||||
|
||||
if self.processing_count % LXMRouter.JOB_STAMPCOST_INTERVAL == 0:
|
||||
if self.store != None:
|
||||
self.clean_outbound_stamp_costs()
|
||||
self.clean_available_tickets()
|
||||
self.store.incremental_vacuum()
|
||||
elif self.__stamp_costs_dirty: self.save_outbound_stamp_costs()
|
||||
|
||||
def jobloop(self):
|
||||
while (True):
|
||||
# TODO: Improve this to scheduling, so manual
|
||||
@@ -1012,7 +1107,29 @@ class LXMRouter:
|
||||
|
||||
RNS.log("Cleaned outbound propagation link", RNS.LOG_DEBUG)
|
||||
|
||||
def __cull_store(self, cull_method, cutoff):
|
||||
# Bounded drain of an expired-entry cull method on the LXMF
|
||||
# store. Capped per call, so maintenance stays short; any
|
||||
# remainder is culled on subsequent ticks.
|
||||
removed = 0
|
||||
for i in range(LXMRouter.STORE_CULL_CHUNKS):
|
||||
batch = cull_method(cutoff)
|
||||
if batch == 0: break
|
||||
removed += batch
|
||||
|
||||
return removed
|
||||
|
||||
def clean_transient_id_caches(self):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: self.clean_transient_id_caches_legacy()
|
||||
else:
|
||||
now = time.time()
|
||||
cutoff = now-LXMRouter.MESSAGE_EXPIRY*6.0
|
||||
removed_delivered = self.__cull_store(self.store.cull_delivered, cutoff)
|
||||
removed_processed = self.__cull_store(self.store.cull_processed, cutoff)
|
||||
if removed_delivered+removed_processed > 0: RNS.log(f"Cleaned {removed_delivered} delivered and {removed_processed} processed transient IDs from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
|
||||
def clean_transient_id_caches_legacy(self):
|
||||
now = time.time()
|
||||
removed_entries = []
|
||||
for transient_id in self.locally_delivered_transient_ids.copy():
|
||||
@@ -1036,10 +1153,12 @@ class LXMRouter:
|
||||
|
||||
def update_stamp_cost(self, destination_hash, stamp_cost):
|
||||
RNS.log(f"Updating outbound stamp cost for {RNS.prettyhexrep(destination_hash)} to {stamp_cost}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||
if self.store == None: self.update_stamp_cost_legacy(destination_hash, stamp_cost)
|
||||
else: self.store.update_stamp_cost(destination_hash, stamp_cost)
|
||||
|
||||
def update_stamp_cost_legacy(self, destination_hash, stamp_cost):
|
||||
self.outbound_stamp_costs[destination_hash] = [time.time(), stamp_cost]
|
||||
|
||||
def job(): self.save_outbound_stamp_costs()
|
||||
threading.Thread(target=self.save_outbound_stamp_costs, daemon=True).start()
|
||||
self.__stamp_costs_dirty = True
|
||||
|
||||
def get_announce_app_data(self, destination_hash):
|
||||
if destination_hash in self.delivery_destinations:
|
||||
@@ -1050,12 +1169,15 @@ class LXMRouter:
|
||||
display_name = delivery_destination.display_name.encode("utf-8")
|
||||
|
||||
stamp_cost = None
|
||||
if delivery_destination.stamp_cost != None and type(delivery_destination.stamp_cost) == int:
|
||||
if delivery_destination.stamp_cost > 0 and delivery_destination.stamp_cost < 255:
|
||||
stamp_cost = delivery_destination.stamp_cost
|
||||
if delivery_destination.stamp_cost != None and (type(delivery_destination.stamp_cost) == int or type(delivery_destination.stamp_cost) == float):
|
||||
if delivery_destination.stamp_cost > 0 and delivery_destination.stamp_cost < RNS.Transport.STAMP_COST_CAP:
|
||||
stamp_cost = quantize_cost(delivery_destination.stamp_cost)
|
||||
|
||||
supported_functionality = [SF_COMPRESSION]
|
||||
peer_data = [display_name, stamp_cost, supported_functionality]
|
||||
|
||||
# TODO: Transitional mechanism, remove after 1.6.2
|
||||
peer_data = [display_name, ceil(stamp_cost) if stamp_cost else None, supported_functionality, stamp_cost]
|
||||
# peer_data = [display_name, stamp_cost, supported_functionality]
|
||||
|
||||
return msgpack.packb(peer_data)
|
||||
|
||||
@@ -1081,6 +1203,31 @@ class LXMRouter:
|
||||
else: return self.propagation_entries[transient_id][6]
|
||||
|
||||
def generate_ticket(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: return self.generate_ticket_legacy(destination_hash, expiry=expiry)
|
||||
else:
|
||||
now = time.time()
|
||||
|
||||
last_delivery = self.store.get_last_ticket_delivery(destination_hash)
|
||||
if last_delivery != None:
|
||||
elapsed = now - last_delivery
|
||||
if elapsed < LXMessage.TICKET_INTERVAL:
|
||||
RNS.log(f"A ticket for {RNS.prettyhexrep(destination_hash)} was already delivered {RNS.prettytime(elapsed)} ago, not including another ticket yet", RNS.LOG_DEBUG)
|
||||
return None
|
||||
|
||||
reusable = self.store.get_reusable_inbound_ticket(destination_hash, LXMessage.TICKET_RENEW)
|
||||
if reusable != None:
|
||||
RNS.log(f"Found generated ticket for {RNS.prettyhexrep(destination_hash)} with {RNS.prettytime(reusable[0]-now)} of validity left, re-using this one", RNS.LOG_DEBUG)
|
||||
return reusable
|
||||
|
||||
RNS.log(f"No generated tickets for {RNS.prettyhexrep(destination_hash)} with enough validity found, generating a new one", RNS.LOG_DEBUG)
|
||||
expires = now+expiry
|
||||
ticket = os.urandom(LXMessage.TICKET_LENGTH)
|
||||
self.store.store_inbound_ticket(destination_hash, ticket, expires)
|
||||
|
||||
return [expires, ticket]
|
||||
|
||||
def generate_ticket_legacy(self, destination_hash, expiry=LXMessage.TICKET_EXPIRY):
|
||||
now = time.time()
|
||||
ticket = None
|
||||
if destination_hash in self.available_tickets["last_deliveries"]:
|
||||
@@ -1112,9 +1259,19 @@ class LXMRouter:
|
||||
def remember_ticket(self, destination_hash, ticket_entry):
|
||||
expires = ticket_entry[0]-time.time()
|
||||
RNS.log(f"Remembering ticket for {RNS.prettyhexrep(destination_hash)}, expires in {RNS.prettytime(expires)}", RNS.LOG_DEBUG)
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: self.remember_ticket_legacy(destination_hash, ticket_entry)
|
||||
else: self.store.remember_ticket(destination_hash, ticket_entry)
|
||||
|
||||
def remember_ticket_legacy(self, destination_hash, ticket_entry):
|
||||
self.available_tickets["outbound"][destination_hash] = [ticket_entry[0], ticket_entry[1]]
|
||||
|
||||
def get_outbound_ticket(self, destination_hash):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: return self.get_outbound_ticket_legacy(destination_hash)
|
||||
else: return self.store.get_outbound_ticket(destination_hash)
|
||||
|
||||
def get_outbound_ticket_legacy(self, destination_hash):
|
||||
if destination_hash in self.available_tickets["outbound"]:
|
||||
entry = self.available_tickets["outbound"][destination_hash]
|
||||
if entry[0] > time.time():
|
||||
@@ -1123,6 +1280,11 @@ class LXMRouter:
|
||||
return None
|
||||
|
||||
def get_outbound_ticket_expiry(self, destination_hash):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: return self.get_outbound_ticket_expiry_legacy(destination_hash)
|
||||
else: return self.store.get_outbound_ticket_expiry(destination_hash)
|
||||
|
||||
def get_outbound_ticket_expiry_legacy(self, destination_hash):
|
||||
if destination_hash in self.available_tickets["outbound"]:
|
||||
entry = self.available_tickets["outbound"][destination_hash]
|
||||
if entry[0] > time.time():
|
||||
@@ -1131,6 +1293,11 @@ class LXMRouter:
|
||||
return None
|
||||
|
||||
def get_inbound_tickets(self, destination_hash):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: return self.get_inbound_tickets_legacy(destination_hash)
|
||||
else: return self.store.get_inbound_tickets(destination_hash)
|
||||
|
||||
def get_inbound_tickets_legacy(self, destination_hash):
|
||||
now = time.time()
|
||||
available_tickets = []
|
||||
if destination_hash in self.available_tickets["inbound"]:
|
||||
@@ -1163,7 +1330,7 @@ class LXMRouter:
|
||||
filename = os.path.split(filepath)[-1]
|
||||
components = filename.split("_")
|
||||
|
||||
if len(components) == 3 and float(components[1]) > 0 and len(os.path.split(components[0])[1]) == (RNS.Identity.HASHLENGTH//8)*2 and int(components[2]) == stamp_value:
|
||||
if len(components) == 3 and float(components[1]) > 0 and len(os.path.split(components[0])[1]) == (RNS.Identity.HASHLENGTH//8)*2 and quantize_cost(components[2]) == quantize_cost(stamp_value):
|
||||
timestamp = float(components[1])
|
||||
if now > timestamp+LXMRouter.MESSAGE_EXPIRY:
|
||||
RNS.log("Purging message "+RNS.prettyhexrep(transient_id)+" due to expiry", RNS.LOG_EXTREME)
|
||||
@@ -1234,6 +1401,8 @@ class LXMRouter:
|
||||
RNS.log("Could not clean the LXMF message store. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def save_locally_delivered_transient_ids(self):
|
||||
if self.store != None: return
|
||||
# TODO: Remove legacy handling after transition
|
||||
try:
|
||||
if len(self.locally_delivered_transient_ids) > 0:
|
||||
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
|
||||
@@ -1247,6 +1416,8 @@ class LXMRouter:
|
||||
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):
|
||||
if self.store != None: return
|
||||
# TODO: Remove legacy handling after transition
|
||||
try:
|
||||
if len(self.locally_processed_transient_ids) > 0:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
@@ -1280,6 +1451,20 @@ class LXMRouter:
|
||||
RNS.log("Could not save local node stats to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def clean_outbound_stamp_costs(self):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: self.clean_outbound_stamp_costs_legacy()
|
||||
else:
|
||||
try:
|
||||
removed = self.__cull_store(self.store.cull_stamp_costs, time.time()-LXMRouter.STAMP_COST_EXPIRY)
|
||||
if removed > 0:
|
||||
RNS.log(f"Cleaned {removed} outbound stamp cost entries from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while cleaning outbound stamp costs in the LXMF store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
return
|
||||
|
||||
def clean_outbound_stamp_costs_legacy(self):
|
||||
try:
|
||||
expired = []
|
||||
for destination_hash in self.outbound_stamp_costs:
|
||||
@@ -1295,6 +1480,8 @@ class LXMRouter:
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def save_outbound_stamp_costs(self):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store != None: return
|
||||
with self.cost_file_lock:
|
||||
try:
|
||||
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
|
||||
@@ -1305,10 +1492,26 @@ class LXMRouter:
|
||||
outbound_stamp_costs_file.write(msgpack.packb(self.outbound_stamp_costs.copy()))
|
||||
os.replace(temp_path, write_path)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not save outbound stamp costs to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
except Exception as e: RNS.log(f"Could not save outbound stamp costs to storage. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
self.__stamp_costs_dirty = False
|
||||
|
||||
def clean_available_tickets(self):
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None: self.clean_available_tickets_legacy()
|
||||
else:
|
||||
try:
|
||||
now = time.time()
|
||||
removed_outbound = self.__cull_store(self.store.cull_tickets_outbound, now)
|
||||
removed_inbound = self.__cull_store(self.store.cull_tickets_inbound, now-LXMessage.TICKET_GRACE)
|
||||
if removed_outbound+removed_inbound > 0:
|
||||
RNS.log(f"Cleaned {removed_outbound} outbound and {removed_inbound} inbound tickets from the LXMF store", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while cleaning available tickets in the LXMF store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
return
|
||||
|
||||
def clean_available_tickets_legacy(self):
|
||||
try:
|
||||
# Clean outbound tickets
|
||||
expired_outbound = []
|
||||
@@ -1337,6 +1540,8 @@ class LXMRouter:
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def save_available_tickets(self):
|
||||
if self.store != None: return
|
||||
# TODO: Remove legacy handling after transition
|
||||
with self.ticket_file_lock:
|
||||
try:
|
||||
if not os.path.isdir(self.storagepath):
|
||||
@@ -1352,6 +1557,8 @@ class LXMRouter:
|
||||
RNS.log("Could not save available tickets to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def reload_available_tickets(self):
|
||||
if self.store != None: return
|
||||
# TODO: Remove legacy handling after transition
|
||||
RNS.log("Reloading available tickets from storage", RNS.LOG_DEBUG)
|
||||
try:
|
||||
with self.ticket_file_lock:
|
||||
@@ -1430,8 +1637,13 @@ class LXMRouter:
|
||||
|
||||
self.save_locally_delivered_transient_ids()
|
||||
self.save_locally_processed_transient_ids()
|
||||
self.save_outbound_stamp_costs()
|
||||
self.save_node_stats()
|
||||
|
||||
if self.store != None:
|
||||
RNS.log("Closing store...", RNS.LOG_DEBUG)
|
||||
self.store.close()
|
||||
|
||||
def sigint_handler(self, signal, frame):
|
||||
if threading.current_thread() != threading.main_thread():
|
||||
RNS.log(f"SIGINT on non-main thread {threading.current_thread()}, exiting immediately", RNS.LOG_WARNING)
|
||||
@@ -1481,13 +1693,9 @@ class LXMRouter:
|
||||
|
||||
def identity_allowed(self, identity):
|
||||
if self.auth_required:
|
||||
if identity.hash in self.allowed_list:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
else:
|
||||
return True
|
||||
if identity.hash in self.allowed_list: return True
|
||||
else: return False
|
||||
else: return True
|
||||
|
||||
def message_get_request(self, path, data, request_id, remote_identity, requested_at):
|
||||
if remote_identity == None: return LXMPeer.ERROR_NO_IDENTITY
|
||||
@@ -1675,8 +1883,10 @@ class LXMRouter:
|
||||
self.wants_download_on_path_available_to = None
|
||||
|
||||
def has_message(self, transient_id):
|
||||
if transient_id in self.locally_delivered_transient_ids: return True
|
||||
else: return False
|
||||
if self.store != None: return self.store.has_delivered(transient_id)
|
||||
else:
|
||||
if transient_id in self.locally_delivered_transient_ids: return True
|
||||
else: return False
|
||||
|
||||
def inbound_count(self):
|
||||
try:
|
||||
@@ -1733,6 +1943,7 @@ class LXMRouter:
|
||||
RNS.log(f"Cancelling deferred stamp generation for {lxm}", RNS.LOG_DEBUG)
|
||||
lxm.state = cancel_state
|
||||
LXStamper.cancel_work(message_id)
|
||||
if lxm.transient_id: LXStamper.cancel_work(lxm.transient_id)
|
||||
|
||||
lxmessage = None
|
||||
for lxm in self.pending_outbound:
|
||||
@@ -1867,8 +2078,8 @@ class LXMRouter:
|
||||
raise IOError("Attempt to send propagated message with no outbound propagation node configured")
|
||||
|
||||
if lxmessage.stamp_cost == None:
|
||||
if destination_hash in self.outbound_stamp_costs:
|
||||
stamp_cost = self.outbound_stamp_costs[destination_hash][1]
|
||||
stamp_cost = self.get_outbound_stamp_cost(destination_hash)
|
||||
if stamp_cost != None:
|
||||
lxmessage.stamp_cost = stamp_cost
|
||||
RNS.log(f"No stamp cost set on LXM to {RNS.prettyhexrep(destination_hash)}, autoconfigured to {stamp_cost}, as required by latest announce", RNS.LOG_DEBUG)
|
||||
|
||||
@@ -1971,9 +2182,10 @@ class LXMRouter:
|
||||
if time.time() < expires:
|
||||
if type(ticket) == bytes and len(ticket) == LXMessage.TICKET_LENGTH:
|
||||
self.remember_ticket(message.source_hash, ticket_entry)
|
||||
def save_job():
|
||||
self.save_available_tickets()
|
||||
threading.Thread(target=save_job, daemon=True).start()
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store == None:
|
||||
def save_job(): self.save_available_tickets()
|
||||
threading.Thread(target=save_job, daemon=True).start()
|
||||
|
||||
required_stamp_cost = self.delivery_destinations[message.destination_hash].stamp_cost
|
||||
if required_stamp_cost != None:
|
||||
@@ -2020,12 +2232,19 @@ class LXMRouter:
|
||||
RNS.log(str(self)+" ignored message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
|
||||
return False
|
||||
|
||||
if not allow_duplicate and self.has_message(message.hash):
|
||||
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
|
||||
return False
|
||||
if self.store != None:
|
||||
if allow_duplicate: self.store.mark_locally_delivered(message.hash, time.time())
|
||||
elif not self.store.conditionally_claim_delivered(message.hash, time.time()):
|
||||
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
|
||||
return False
|
||||
else:
|
||||
with self.delivered_transient_ids_lock:
|
||||
self.locally_delivered_transient_ids[message.hash] = time.time()
|
||||
# TODO: Remove legacy handling after transition
|
||||
if not allow_duplicate and self.has_message(message.hash):
|
||||
RNS.log(str(self)+" ignored already received message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
|
||||
return False
|
||||
else:
|
||||
with self.delivered_transient_ids_lock:
|
||||
self.locally_delivered_transient_ids[message.hash] = time.time()
|
||||
|
||||
if self.__delivery_callback != None and callable(self.__delivery_callback):
|
||||
try: self.__delivery_callback(message)
|
||||
@@ -2172,7 +2391,7 @@ class LXMRouter:
|
||||
|
||||
if timestamp >= peer.peering_timebase:
|
||||
self.peers.pop(destination_hash)
|
||||
RNS.log("Broke peering with "+str(peer.destination))
|
||||
RNS.log(f"Broke peering with {RNS.prettyhexrep(destination_hash)}")
|
||||
|
||||
def rotate_peers(self):
|
||||
try:
|
||||
@@ -2291,16 +2510,15 @@ class LXMRouter:
|
||||
if len(peer_pool) > 0:
|
||||
selected_index = random.randint(0,len(peer_pool)-1)
|
||||
selected_peer = peer_pool[selected_index]
|
||||
RNS.log("Selected waiting peer "+str(selected_index)+": "+RNS.prettyhexrep(selected_peer.destination.hash), RNS.LOG_DEBUG)
|
||||
RNS.log(f"Selected waiting peer {selected_index}: {RNS.prettyhexrep(selected_peer.destination_hash)}", RNS.LOG_DEBUG)
|
||||
selected_peer.sync()
|
||||
|
||||
for peer_id in culled_peers:
|
||||
RNS.log("Removing peer "+RNS.prettyhexrep(peer_id)+" due to excessive unreachability", RNS.LOG_WARNING)
|
||||
RNS.log(f"Removing peer {RNS.prettyhexrep(peer_id)} due to excessive unreachability", RNS.LOG_WARNING)
|
||||
try:
|
||||
if peer_id in self.peers:
|
||||
self.peers.pop(peer_id)
|
||||
if peer_id in self.peers: self.peers.pop(peer_id)
|
||||
except Exception as e:
|
||||
RNS.log("Error while removing peer "+RNS.prettyhexrep(peer_id)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
RNS.log(f"Error while removing peer {RNS.prettyhexrep(peer_id)}. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
|
||||
def propagation_link_established(self, link):
|
||||
link.set_packet_callback(self.propagation_packet)
|
||||
@@ -2321,7 +2539,7 @@ class LXMRouter:
|
||||
return count
|
||||
|
||||
def propagation_resource_advertised(self, resource):
|
||||
if self.from_static_only:
|
||||
if self.from_static_only and not resource.app_flag_set():
|
||||
remote_identity = resource.link.get_remote_identity()
|
||||
if remote_identity == None:
|
||||
RNS.log(f"Rejecting propagation resource from unidentified peer", RNS.LOG_DEBUG)
|
||||
@@ -2361,7 +2579,7 @@ class LXMRouter:
|
||||
|
||||
for validated_entry in validated_messages:
|
||||
lxmf_data = validated_entry[1]
|
||||
stamp_value = validated_entry[2]
|
||||
stamp_value = quantize_cost(validated_entry[2])
|
||||
stamp_data = validated_entry[3]
|
||||
self.lxmf_propagation(lxmf_data, stamp_value=stamp_value, stamp_data=stamp_data)
|
||||
self.client_propagation_messages_received += 1
|
||||
@@ -2390,8 +2608,6 @@ class LXMRouter:
|
||||
bypass_sequential = not self.propagation_static_peer_sequential and remote_hash in self.static_peers
|
||||
if not bypass_sequential and self.propagation_sequential_validation and len(self.validating_pn_stamps_from) > 0:
|
||||
RNS.log(f"Propagation offer from node {remote_str} postponed, already validating {len(self.validating_pn_stamps_from)} PN stamp batches", RNS.LOG_NOTICE)
|
||||
# for rh in self.validating_pn_stamps_from:
|
||||
# RNS.log(f"Validating from {RNS.prettyhexrep(rh)} for {RNS.prettytime(time.time()-self.validating_pn_stamps_from[rh])}")
|
||||
return LXMPeer.ERROR_THROTTLED
|
||||
|
||||
resources_transferring = self.propagation_resources_transferring
|
||||
@@ -2488,6 +2704,12 @@ class LXMRouter:
|
||||
remote_peering_cost = pn_config[5][2]
|
||||
remote_metadata = pn_config[6]
|
||||
|
||||
# TODO: Transitional mechanism, remove after 1.6.2
|
||||
if len(pn_config) > 7:
|
||||
remote_stamp_cost = pn_config[7][0]
|
||||
remote_stamp_flex = pn_config[7][1]
|
||||
remote_peering_cost = pn_config[7][2]
|
||||
|
||||
RNS.log(f"Auto-peering with {remote_str} discovered via incoming sync", RNS.LOG_DEBUG) # TODO: Remove debug
|
||||
self.peer(remote_hash, remote_timebase, remote_transfer_limit, remote_sync_limit, remote_stamp_cost, remote_stamp_flex, remote_peering_cost, remote_metadata)
|
||||
|
||||
@@ -2543,7 +2765,7 @@ class LXMRouter:
|
||||
for validated_entry in validated_messages:
|
||||
transient_id = validated_entry[0]
|
||||
lxmf_data = validated_entry[1]
|
||||
stamp_value = validated_entry[2]
|
||||
stamp_value = quantize_cost(validated_entry[2])
|
||||
stamp_data = validated_entry[3]
|
||||
peer = None
|
||||
|
||||
@@ -2565,7 +2787,7 @@ class LXMRouter:
|
||||
if invalid_message_count > 0:
|
||||
resource.link.teardown()
|
||||
if remote_identity != None:
|
||||
throttle_time = LXMRouter.PN_STAMP_THROTTLE
|
||||
throttle_time = self.pn_stamp_throttle
|
||||
self.throttled_peers[remote_hash] = time.time()+throttle_time
|
||||
ms = "" if invalid_message_count == 1 else "s"
|
||||
RNS.log(f"Propagation transfer from {remote_str} contained {invalid_message_count} message{ms} with invalid stamps, throttled for {RNS.prettytime(throttle_time)}", RNS.LOG_NOTICE)
|
||||
@@ -2609,11 +2831,26 @@ class LXMRouter:
|
||||
try:
|
||||
if len(lxmf_data) >= LXMessage.LXMF_OVERHEAD:
|
||||
transient_id = RNS.Identity.full_hash(lxmf_data)
|
||||
received = time.time()
|
||||
|
||||
if (not transient_id in self.propagation_entries and not transient_id in self.locally_processed_transient_ids) or allow_duplicate == True:
|
||||
received = time.time()
|
||||
duplicate_filtered = True
|
||||
if allow_duplicate == True:
|
||||
duplicate_filtered = False
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store != None: self.store.unconditionally_mark_processed(transient_id, received)
|
||||
else:
|
||||
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
|
||||
|
||||
elif not transient_id in self.propagation_entries:
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store != None: duplicate_filtered = not self.store.conditionally_claim_processed(transient_id, received)
|
||||
else:
|
||||
if not transient_id in self.locally_processed_transient_ids:
|
||||
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
|
||||
duplicate_filtered = False
|
||||
|
||||
if not duplicate_filtered:
|
||||
destination_hash = lxmf_data[:LXMessage.DESTINATION_LENGTH]
|
||||
with self.processed_transient_ids_lock: self.locally_processed_transient_ids[transient_id] = received
|
||||
|
||||
if destination_hash in self.delivery_destinations:
|
||||
delivery_destination = self.delivery_destinations[destination_hash]
|
||||
@@ -2622,10 +2859,19 @@ class LXMRouter:
|
||||
if decrypted_lxmf_data != None:
|
||||
delivery_data = lxmf_data[:LXMessage.DESTINATION_LENGTH]+decrypted_lxmf_data
|
||||
self.lxmf_delivery(delivery_data, delivery_destination.type, ratchet_id=delivery_destination.latest_ratchet_id, method=LXMessage.PROPAGATED, no_stamp_enforcement=no_stamp_enforcement, allow_duplicate=allow_duplicate)
|
||||
with self.delivered_transient_ids_lock: self.locally_delivered_transient_ids[transient_id] = time.time()
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store != None: self.store.mark_locally_delivered(transient_id, time.time())
|
||||
else:
|
||||
with self.delivered_transient_ids_lock: self.locally_delivered_transient_ids[transient_id] = time.time()
|
||||
if signal_local_delivery != None: return signal_local_delivery
|
||||
else:
|
||||
if self.propagation_node:
|
||||
if not stamp_value: return # TODO: This is edge-case handling for stamp-less paper messages being
|
||||
# ingested onto a propagation node, which is currently not possible,
|
||||
# but could potentially be supported somehow. Will need to figure this
|
||||
# one out at a more opportune moment. Potential local stamping at time
|
||||
# of ingress, if allowed by config.
|
||||
stamp_value = quantize_cost(stamp_value)
|
||||
stamped_data = lxmf_data+stamp_data
|
||||
value_component = f"_{stamp_value}" if stamp_value and stamp_value > 0 else ""
|
||||
file_path = f"{self.messagepath}/{RNS.hexrep(transient_id, delimit=False)}_{received}{value_component}"
|
||||
@@ -2666,6 +2912,8 @@ class LXMRouter:
|
||||
lxmf_data = base64.urlsafe_b64decode(uri.replace(LXMessage.URI_SCHEMA+"://", "").replace("/", "")+"==")
|
||||
transient_id = RNS.Identity.full_hash(lxmf_data)
|
||||
|
||||
# TODO: Consider whether to allow duplicate paper messages by
|
||||
# default, and potential implications in client applications.
|
||||
router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate, allow_duplicate=allow_duplicate, is_paper_message=True)
|
||||
if router_propagation_result != False:
|
||||
RNS.log("LXM with transient ID "+RNS.prettyhexrep(transient_id)+" was ingested.", RNS.LOG_DEBUG)
|
||||
@@ -2812,8 +3060,11 @@ class LXMRouter:
|
||||
# Udate ticket delivery stats
|
||||
if lxmessage.include_ticket and FIELD_TICKET in lxmessage.fields:
|
||||
RNS.log(f"Updating latest ticket delivery for {RNS.prettyhexrep(lxmessage.destination_hash)}", RNS.LOG_DEBUG)
|
||||
self.available_tickets["last_deliveries"][lxmessage.destination_hash] = time.time()
|
||||
self.save_available_tickets()
|
||||
# TODO: Remove legacy handling after transition
|
||||
if self.store != None: self.store.mark_last_ticket_delivery(lxmessage.destination_hash, time.time())
|
||||
else:
|
||||
self.available_tickets["last_deliveries"][lxmessage.destination_hash] = time.time()
|
||||
self.save_available_tickets()
|
||||
|
||||
# Prepare link for backchannel communications
|
||||
delivery_destination_hash = lxmessage.get_destination().hash
|
||||
@@ -2832,6 +3083,8 @@ class LXMRouter:
|
||||
|
||||
elif lxmessage.method == LXMessage.PROPAGATED and lxmessage.state == LXMessage.SENT:
|
||||
RNS.log("Propagation has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
try: RNS.Reticulum.get_instance()._retain_destination_data(lxmessage.destination_hash)
|
||||
except Exception as e: RNS.log(f"An error occurred while marking {RNS.prettyhexrep(lxmessage.destination_hash)} for announce data retainment: {e}", RNS.LOG_ERROR)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
|
||||
elif lxmessage.state == LXMessage.CANCELLED:
|
||||
|
||||
+2
-2
@@ -673,9 +673,9 @@ class LXMessage:
|
||||
raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active")
|
||||
|
||||
if self.method == LXMessage.DIRECT:
|
||||
return RNS.Resource(self.packed, self.__delivery_destination, callback = self.__resource_concluded, progress_callback = self.__update_transfer_progress, auto_compress=self.auto_compress)
|
||||
return RNS.Resource(self.packed, self.__delivery_destination, callback=self.__resource_concluded, progress_callback=self.__update_transfer_progress, auto_compress=self.auto_compress)
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
return RNS.Resource(self.propagation_packed, self.__delivery_destination, callback = self.__propagation_resource_concluded, progress_callback = self.__update_transfer_progress)
|
||||
return RNS.Resource(self.propagation_packed, self.__delivery_destination, app_flag=True, callback=self.__propagation_resource_concluded, progress_callback=self.__update_transfer_progress)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
+15
-420
@@ -1,80 +1,27 @@
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
import RNS.Stamps
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import math
|
||||
import itertools
|
||||
import contextlib
|
||||
import multiprocessing
|
||||
|
||||
from RNS.Stamps import stamp_workblock
|
||||
from RNS.Stamps import stamp_valid
|
||||
from RNS.Stamps import stamp_value
|
||||
from RNS.Stamps import cancel_work
|
||||
|
||||
# LXMF-specific stamp parameters
|
||||
WORKBLOCK_EXPAND_ROUNDS = 3000
|
||||
WORKBLOCK_EXPAND_ROUNDS_PN = 1000
|
||||
WORKBLOCK_EXPAND_ROUNDS_PEERING = 25
|
||||
STAMP_SIZE = RNS.Identity.HASHLENGTH//8
|
||||
PN_VALIDATION_POOL_MIN_SIZE = 256
|
||||
USE_WORKER_MANAGER = False
|
||||
|
||||
active_jobs = {}
|
||||
|
||||
if sys.version_info[0] >= 3 and sys.version_info[1] >= 14:
|
||||
USE_WORKER_MANAGER = True
|
||||
|
||||
@contextlib.contextmanager
|
||||
def worker_context(ctx, stamp_cost, workblock, message_id):
|
||||
stop_event = ctx.Event()
|
||||
result_queue = ctx.Queue(1)
|
||||
rounds_queue = ctx.Queue()
|
||||
|
||||
active_jobs[message_id] = [stop_event, result_queue]
|
||||
job_procs = []
|
||||
|
||||
try: yield stop_event, result_queue, rounds_queue, job_procs
|
||||
finally:
|
||||
if message_id in active_jobs: del active_jobs[message_id]
|
||||
stop_event.set()
|
||||
|
||||
for p in job_procs:
|
||||
if p.is_alive(): p.terminate()
|
||||
|
||||
for p in job_procs: p.join(timeout=0.5)
|
||||
|
||||
result_queue.close()
|
||||
result_queue.join_thread()
|
||||
rounds_queue.close()
|
||||
rounds_queue.join_thread()
|
||||
stop_event.clear()
|
||||
|
||||
def stamp_workblock(material, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
|
||||
wb_st = time.time()
|
||||
workblock = b""
|
||||
for n in range(expand_rounds):
|
||||
workblock += RNS.Cryptography.hkdf(length=256,
|
||||
derive_from=material,
|
||||
salt=RNS.Identity.full_hash(material+msgpack.packb(n)),
|
||||
context=None)
|
||||
wb_time = time.time() - wb_st
|
||||
# RNS.log(f"Stamp workblock size {RNS.prettysize(len(workblock))}, generated in {round(wb_time*1000,2)}ms", RNS.LOG_DEBUG)
|
||||
|
||||
return workblock
|
||||
|
||||
def stamp_value(workblock, stamp):
|
||||
value = 0
|
||||
bits = 256
|
||||
material = RNS.Identity.full_hash(workblock+stamp)
|
||||
i = int.from_bytes(material, byteorder="big")
|
||||
while ((i & (1 << (bits - 1))) == 0):
|
||||
i = (i << 1)
|
||||
value += 1
|
||||
|
||||
return value
|
||||
|
||||
def stamp_valid(stamp, target_cost, workblock):
|
||||
target = 0b1 << 256-target_cost
|
||||
result = RNS.Identity.full_hash(workblock+stamp)
|
||||
if int.from_bytes(result, byteorder="big") > target: return False
|
||||
else: return True
|
||||
# Wrapper that forces the LXMF-specific stamp size
|
||||
def generate_stamp(message_id, stamp_cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS, no_expand=False):
|
||||
return RNS.Stamps.generate_stamp(message_id, stamp_cost, expand_rounds=expand_rounds, no_expand=no_expand, size=STAMP_SIZE)
|
||||
|
||||
def validate_peering_key(peering_id, peering_key, target_cost):
|
||||
workblock = stamp_workblock(peering_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
|
||||
@@ -120,363 +67,6 @@ def validate_pn_stamps(transient_list, target_cost):
|
||||
if len(transient_list) <= PN_VALIDATION_POOL_MIN_SIZE or non_mp_platform: return validate_pn_stamps_job_simple(transient_list, target_cost)
|
||||
else: return validate_pn_stamps_job_multip(transient_list, target_cost)
|
||||
|
||||
def generate_stamp(message_id, stamp_cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
|
||||
RNS.log(f"Generating stamp with cost {stamp_cost} for {RNS.prettyhexrep(message_id)}...", RNS.LOG_DEBUG)
|
||||
workblock = stamp_workblock(message_id, expand_rounds=expand_rounds)
|
||||
|
||||
start_time = time.time()
|
||||
stamp = None
|
||||
rounds = 0
|
||||
value = 0
|
||||
|
||||
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin(): stamp, rounds = job_simple(stamp_cost, workblock, message_id)
|
||||
elif RNS.vendor.platformutils.is_android(): stamp, rounds = job_android(stamp_cost, workblock, message_id)
|
||||
else:
|
||||
if USE_WORKER_MANAGER: stamp, rounds = job_linux_managed(stamp_cost, workblock, message_id)
|
||||
else: stamp, rounds = job_linux(stamp_cost, workblock, message_id)
|
||||
|
||||
duration = time.time() - start_time
|
||||
speed = rounds/duration
|
||||
if stamp != None: value = stamp_value(workblock, stamp)
|
||||
|
||||
RNS.log(f"Stamp with value {value} generated in {RNS.prettytime(duration)}, {rounds} rounds, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
return stamp, value
|
||||
|
||||
def cancel_work(message_id):
|
||||
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin():
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
active_jobs[message_id] = True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
elif RNS.vendor.platformutils.is_android():
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
active_jobs[message_id] = True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
else:
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
stop_event = active_jobs[message_id][0]
|
||||
result_queue = active_jobs[message_id][1]
|
||||
stop_event.set()
|
||||
result_queue.put(None)
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def job_simple(stamp_cost, workblock, message_id):
|
||||
# A simple, single-process stamp generator.
|
||||
# should work on any platform, and is used
|
||||
# as a fall-back, in case of limited multi-
|
||||
# processing and/or acceleration support.
|
||||
|
||||
platform = RNS.vendor.platformutils.get_platform()
|
||||
RNS.log(f"Running stamp generation on {platform}, work limited to single CPU core. This will be slower than ideal.", RNS.LOG_WARNING)
|
||||
|
||||
rounds = 0
|
||||
pstamp = os.urandom(256//8)
|
||||
st = time.time()
|
||||
|
||||
active_jobs[message_id] = False;
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c; m = w+s
|
||||
result = RNS.Identity.full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target: return False
|
||||
else: return True
|
||||
|
||||
while not sv(pstamp, stamp_cost, workblock) and not active_jobs[message_id]:
|
||||
pstamp = os.urandom(256//8); rounds += 1
|
||||
if rounds % 2500 == 0:
|
||||
speed = rounds / (time.time()-st)
|
||||
RNS.log(f"Stamp generation running. {rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
if active_jobs[message_id] == True:
|
||||
pstamp = None
|
||||
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
return pstamp, rounds
|
||||
|
||||
def job_linux_managed(stamp_cost, workblock, message_id):
|
||||
ctx = multiprocessing.get_context("fork")
|
||||
cores = multiprocessing.cpu_count()
|
||||
jobs = cores if cores <= 12 else int(cores/2)
|
||||
|
||||
allow_kill = True
|
||||
stamp = None
|
||||
total_rounds = 0
|
||||
|
||||
with worker_context(ctx, stamp_cost, workblock, message_id) as (stop_event, result_queue, rounds_queue, job_procs):
|
||||
RNS.log(f"Starting {jobs} stamp generation workers", RNS.LOG_DEBUG)
|
||||
|
||||
def job(stop_event, sc, wb, worker_id):
|
||||
terminated = False
|
||||
rounds = 0
|
||||
pstamp = os.urandom(256//8)
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c; m = w+s
|
||||
result = RNS.Identity.full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target: return False
|
||||
else: return True
|
||||
|
||||
while not stop_event.is_set() and not sv(pstamp, sc, wb):
|
||||
pstamp = os.urandom(256//8); rounds += 1
|
||||
|
||||
if not stop_event.is_set():
|
||||
stop_event.set()
|
||||
try: result_queue.put_nowait(pstamp)
|
||||
except: pass
|
||||
|
||||
try: rounds_queue.put_nowait(rounds)
|
||||
except: pass
|
||||
|
||||
for jpn in range(jobs):
|
||||
p = ctx.Process(target=job, args=(stop_event, stamp_cost, workblock, jpn), daemon=True)
|
||||
job_procs.append(p)
|
||||
p.start()
|
||||
|
||||
try: stamp = result_queue.get(timeout=None)
|
||||
except Exception as e:
|
||||
RNS.log(f"Failed to get result from workers: {e}", RNS.LOG_ERROR)
|
||||
stamp = None
|
||||
|
||||
# Collect any potential spurious
|
||||
# results from worker queue.
|
||||
try:
|
||||
while True: result_queue.get_nowait()
|
||||
except: pass
|
||||
|
||||
for j in range(jobs):
|
||||
nrounds = 0
|
||||
try:
|
||||
nrounds = rounds_queue.get(timeout=2)
|
||||
except Exception as e:
|
||||
RNS.log(f"Failed to get round stats part {j}: {e}", RNS.LOG_ERROR)
|
||||
total_rounds += nrounds
|
||||
|
||||
all_exited = False
|
||||
exit_timeout = time.time() + 5
|
||||
while time.time() < exit_timeout:
|
||||
if not any(p.is_alive() for p in job_procs):
|
||||
all_exited = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
if not all_exited:
|
||||
RNS.log("Stamp generation IPC timeout, possible worker deadlock. Terminating remaining processes.", RNS.LOG_ERROR)
|
||||
if allow_kill:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.kill()
|
||||
else:
|
||||
return None
|
||||
|
||||
else:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.join()
|
||||
# RNS.log(f"Joined {j} / {process}", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
|
||||
def job_linux(stamp_cost, workblock, message_id):
|
||||
allow_kill = True
|
||||
stamp = None
|
||||
total_rounds = 0
|
||||
cores = multiprocessing.cpu_count()
|
||||
jobs = cores if cores <= 12 else int(cores/2)
|
||||
stop_event = multiprocessing.Event()
|
||||
result_queue = multiprocessing.Queue(1)
|
||||
rounds_queue = multiprocessing.Queue()
|
||||
|
||||
def job(stop_event, pn, sc, wb):
|
||||
terminated = False
|
||||
rounds = 0
|
||||
pstamp = os.urandom(256//8)
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c; m = w+s
|
||||
result = RNS.Identity.full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
while not stop_event.is_set() and not sv(pstamp, sc, wb):
|
||||
pstamp = os.urandom(256//8); rounds += 1
|
||||
|
||||
if not stop_event.is_set():
|
||||
stop_event.set()
|
||||
result_queue.put(pstamp)
|
||||
rounds_queue.put(rounds)
|
||||
|
||||
job_procs = []
|
||||
RNS.log(f"Starting {jobs} stamp generation workers", RNS.LOG_DEBUG)
|
||||
for jpn in range(jobs):
|
||||
process = multiprocessing.get_context("fork").Process(target=job, kwargs={"stop_event": stop_event, "pn": jpn, "sc": stamp_cost, "wb": workblock}, daemon=True)
|
||||
job_procs.append(process)
|
||||
process.start()
|
||||
|
||||
active_jobs[message_id] = [stop_event, result_queue]
|
||||
|
||||
stamp = result_queue.get()
|
||||
|
||||
# Collect any potential spurious
|
||||
# results from worker queue.
|
||||
try:
|
||||
while True: result_queue.get_nowait()
|
||||
except: pass
|
||||
|
||||
for j in range(jobs):
|
||||
nrounds = 0
|
||||
try:
|
||||
nrounds = rounds_queue.get(timeout=2)
|
||||
except Exception as e:
|
||||
RNS.log(f"Failed to get round stats part {j}: {e}", RNS.LOG_ERROR)
|
||||
total_rounds += nrounds
|
||||
|
||||
all_exited = False
|
||||
exit_timeout = time.time() + 5
|
||||
while time.time() < exit_timeout:
|
||||
if not any(p.is_alive() for p in job_procs):
|
||||
all_exited = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
if not all_exited:
|
||||
RNS.log("Stamp generation IPC timeout, possible worker deadlock. Terminating remaining processes.", RNS.LOG_ERROR)
|
||||
if allow_kill:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.kill()
|
||||
else:
|
||||
return None
|
||||
|
||||
else:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.join()
|
||||
# RNS.log(f"Joined {j} / {process}", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
def job_android(stamp_cost, workblock, message_id):
|
||||
# Semaphore support is flaky to non-existent on
|
||||
# Android, so we need to manually dispatch and
|
||||
# manage workloads here, while periodically
|
||||
# checking in on the progress.
|
||||
|
||||
stamp = None
|
||||
start_time = time.time()
|
||||
total_rounds = 0
|
||||
rounds_per_worker = 1000
|
||||
|
||||
use_nacl = False
|
||||
try:
|
||||
import nacl.encoding
|
||||
import nacl.hash
|
||||
use_nacl = True
|
||||
except:
|
||||
pass
|
||||
|
||||
if use_nacl:
|
||||
def full_hash(m):
|
||||
return nacl.hash.sha256(m, encoder=nacl.encoding.RawEncoder)
|
||||
else:
|
||||
def full_hash(m):
|
||||
return RNS.Identity.full_hash(m)
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c
|
||||
m = w+s
|
||||
result = full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
wm = multiprocessing.Manager()
|
||||
jobs = multiprocessing.cpu_count()
|
||||
|
||||
def job(procnum=None, results_dict=None, wb=None, sc=None, jr=None):
|
||||
# RNS.log(f"Worker {procnum} starting for {jr} rounds...") # TODO: Remove
|
||||
try:
|
||||
rounds = 0
|
||||
found_stamp = None
|
||||
|
||||
while True:
|
||||
pstamp = os.urandom(256//8)
|
||||
rounds += 1
|
||||
if sv(pstamp, sc, wb):
|
||||
found_stamp = pstamp
|
||||
break
|
||||
|
||||
if rounds >= jr:
|
||||
# RNS.log(f"Worker {procnum} found no result in {rounds} rounds") # TODO: Remove
|
||||
break
|
||||
|
||||
results_dict[procnum] = [found_stamp, rounds]
|
||||
except Exception as e:
|
||||
RNS.log(f"Stamp generation worker error: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
active_jobs[message_id] = False;
|
||||
|
||||
RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
results_dict = wm.dict()
|
||||
while stamp == None and active_jobs[message_id] == False:
|
||||
job_procs = []
|
||||
try:
|
||||
for pnum in range(jobs):
|
||||
pargs = {"procnum":pnum, "results_dict": results_dict, "wb": workblock, "sc":stamp_cost, "jr":rounds_per_worker}
|
||||
process = multiprocessing.Process(target=job, kwargs=pargs)
|
||||
job_procs.append(process)
|
||||
process.start()
|
||||
|
||||
for process in job_procs:
|
||||
process.join()
|
||||
|
||||
for j in results_dict:
|
||||
r = results_dict[j]
|
||||
total_rounds += r[1]
|
||||
if r[0] != None:
|
||||
stamp = r[0]
|
||||
|
||||
if stamp == None:
|
||||
elapsed = time.time() - start_time
|
||||
speed = total_rounds/elapsed
|
||||
RNS.log(f"Stamp generation running. {total_rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Stamp generation job error: {e}")
|
||||
RNS.trace_exception(e)
|
||||
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
# def stamp_value_linear(workblock, stamp):
|
||||
# value = 0
|
||||
# bits = 256
|
||||
# material = RNS.Identity.full_hash(workblock+stamp)
|
||||
# s = int.from_bytes(material, byteorder="big")
|
||||
# return s.bit_count()
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
if len(sys.argv) < 2:
|
||||
@@ -515,6 +105,11 @@ if __name__ == "__main__":
|
||||
message_id = os.urandom(32)
|
||||
generate_stamp(message_id, cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
|
||||
|
||||
RNS.log("", RNS.LOG_DEBUG)
|
||||
RNS.log("Testing non-expanded workblock generation", RNS.LOG_DEBUG)
|
||||
message_id = os.urandom(32)
|
||||
generate_stamp(message_id, cost, expand_rounds=0)
|
||||
|
||||
# transient_list = []
|
||||
# st = time.time(); count = 10000
|
||||
# for i in range(count): transient_list.append(os.urandom(256))
|
||||
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
import os
|
||||
import time
|
||||
import sqlite3
|
||||
import threading
|
||||
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
|
||||
class LXMFStore:
|
||||
CURRENT_VERSION = 1
|
||||
|
||||
TRANSIENT_ID_LENGTH = RNS.Identity.HASHLENGTH//8
|
||||
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
TICKET_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
|
||||
IMPORT_CHUNK = 4096
|
||||
CULL_CHUNK = 4096
|
||||
IN_CHUNK = 512
|
||||
VACUUM_PAGES = 512
|
||||
|
||||
def __init__(self, db_path):
|
||||
if sqlite3.threadsafety < 3: raise RuntimeError("Storage backend requires a SQLite build with serialized threading support")
|
||||
|
||||
self.db_path = db_path
|
||||
self._conn = None
|
||||
self._conn_lock = threading.Lock()
|
||||
self._close_warned = False
|
||||
|
||||
self._conn = sqlite3.connect(db_path, check_same_thread=False, isolation_level=None)
|
||||
|
||||
self._conn.execute("PRAGMA auto_vacuum=INCREMENTAL")
|
||||
self._conn.execute("PRAGMA journal_mode=WAL")
|
||||
self._conn.execute("PRAGMA synchronous=NORMAL")
|
||||
self._conn.execute("PRAGMA journal_size_limit=8388608")
|
||||
self._conn.execute("PRAGMA busy_timeout=1500")
|
||||
|
||||
self.__create_schema()
|
||||
|
||||
def close(self):
|
||||
with self._conn_lock:
|
||||
if self._conn != None:
|
||||
try: self._conn.execute("PRAGMA optimize")
|
||||
except Exception: pass
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
|
||||
def __create_schema(self):
|
||||
db_version = self._conn.execute("PRAGMA user_version").fetchone()[0]
|
||||
|
||||
if db_version > self.CURRENT_VERSION:
|
||||
RNS.log(f"Cannot open store {self.db_path}: database version {db_version} is newer than supported version {self.CURRENT_VERSION}", RNS.LOG_CRITICAL)
|
||||
self._conn.close(); self._conn = None
|
||||
raise ValueError(f"Store database version {db_version} is newer than supported version {self.CURRENT_VERSION}")
|
||||
|
||||
try:
|
||||
self._conn.execute("BEGIN")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS stamp_costs (
|
||||
destination_hash BLOB PRIMARY KEY,
|
||||
updated REAL NOT NULL,
|
||||
used REAL,
|
||||
cost REAL)""")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS delivered_transient_ids (
|
||||
transient_id BLOB PRIMARY KEY,
|
||||
received REAL NOT NULL)""")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS processed_transient_ids (
|
||||
transient_id BLOB PRIMARY KEY,
|
||||
received REAL NOT NULL)""")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS tickets_outbound (
|
||||
destination_hash BLOB PRIMARY KEY,
|
||||
expires REAL NOT NULL,
|
||||
ticket BLOB NOT NULL)""")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS tickets_inbound (
|
||||
ticket BLOB PRIMARY KEY,
|
||||
destination_hash BLOB NOT NULL,
|
||||
expires REAL NOT NULL)""")
|
||||
|
||||
self._conn.execute("""CREATE TABLE IF NOT EXISTS ticket_deliveries (
|
||||
destination_hash BLOB PRIMARY KEY,
|
||||
timestamp REAL NOT NULL)""")
|
||||
|
||||
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_delivered_received ON delivered_transient_ids (received)")
|
||||
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_processed_received ON processed_transient_ids (received)")
|
||||
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_stampcost_updated ON stamp_costs (updated)")
|
||||
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_tickets_in_dest ON tickets_inbound (destination_hash)")
|
||||
|
||||
self._conn.execute(f"PRAGMA user_version = {self.CURRENT_VERSION}")
|
||||
self._conn.execute("COMMIT")
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not initialise store schema at {self.db_path}. The contained exception was: {e}", RNS.LOG_CRITICAL)
|
||||
try: self._conn.execute("ROLLBACK")
|
||||
except Exception: pass
|
||||
self._conn.close(); self._conn = None
|
||||
raise
|
||||
|
||||
def _ready(self):
|
||||
if self._conn == None:
|
||||
if not self._close_warned:
|
||||
self._close_warned = True
|
||||
RNS.log("Store operation attempted after close", RNS.LOG_ERROR)
|
||||
return False
|
||||
else: return True
|
||||
|
||||
def _claim(self, table, key_column, key, ts_column, timestamp):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return True
|
||||
cursor = self._conn.execute(f"INSERT INTO {table} ({key_column}, {ts_column}) VALUES (?, ?) ON CONFLICT({key_column}) DO NOTHING", (key, timestamp))
|
||||
return cursor.rowcount == 1
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not claim entry in {table} of store, treating as claimed. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return True
|
||||
|
||||
def _upsert_timestamp(self, table, key_column, key, ts_column, timestamp):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
self._conn.execute(f"INSERT INTO {table} ({key_column}, {ts_column}) VALUES (?, ?) ON CONFLICT({key_column}) DO UPDATE SET {ts_column}=excluded.{ts_column}", (key, timestamp))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not upsert entry in {table} of store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def _cull(self, table, ts_column, cutoff, max_entries):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return 0
|
||||
cursor = self._conn.execute(f"DELETE FROM {table} WHERE rowid IN (SELECT rowid FROM {table} WHERE {ts_column} < ? LIMIT {int(max_entries)})", (cutoff,))
|
||||
return cursor.rowcount
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not cull entries in {table} of store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return 0
|
||||
|
||||
|
||||
########################
|
||||
# Outbound Stamp Costs #
|
||||
########################
|
||||
|
||||
def update_stamp_cost(self, destination_hash, cost):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
self._conn.execute("INSERT INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?, ?, NULL, ?) ON CONFLICT(destination_hash) DO UPDATE SET updated=excluded.updated, cost=excluded.cost", (destination_hash, time.time(), cost))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not update outbound stamp cost in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def get_outbound_stamp_cost(self, destination_hash):
|
||||
if not self._ready(): return None
|
||||
cost = None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
row = self._conn.execute("SELECT cost FROM stamp_costs WHERE destination_hash=?", (destination_hash,)).fetchone()
|
||||
if row != None and len(row) > 0:
|
||||
cost = row[0]
|
||||
try: self._conn.execute("UPDATE stamp_costs SET used=? WHERE destination_hash=?", (time.time(), destination_hash))
|
||||
except Exception as e: RNS.log(f"Could not update stamp cost usage time in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall outbound stamp cost from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
return cost
|
||||
|
||||
def cull_stamp_costs(self, cutoff, max_entries=CULL_CHUNK): return self._cull("stamp_costs", "updated", cutoff, max_entries)
|
||||
|
||||
|
||||
##############################
|
||||
# Transient ID Deduplication #
|
||||
##############################
|
||||
|
||||
def has_delivered(self, transient_id):
|
||||
if not self._ready(): return False
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
row = self._conn.execute("SELECT transient_id FROM delivered_transient_ids WHERE transient_id=?", (transient_id,)).fetchone()
|
||||
return row != None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not query delivered transient ID in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def known_delivered(self, transient_ids):
|
||||
known = set()
|
||||
if not self._ready(): return known
|
||||
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return known
|
||||
ids = list(set(transient_id for transient_id in transient_ids if type(transient_id) == bytes))
|
||||
for i in range(0, len(ids), self.IN_CHUNK):
|
||||
chunk = ids[i:i+self.IN_CHUNK]
|
||||
marks = ",".join("?"*len(chunk))
|
||||
for row in self._conn.execute(f"SELECT transient_id FROM delivered_transient_ids WHERE transient_id IN ({marks})", chunk):
|
||||
known.add(row[0])
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not query known delivered transient IDs in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return set()
|
||||
|
||||
return known
|
||||
|
||||
def mark_locally_delivered(self, transient_id, received): return self._upsert_timestamp("delivered_transient_ids", "transient_id", transient_id, "received", received)
|
||||
def unconditionally_mark_processed(self, transient_id, received): return self._upsert_timestamp("processed_transient_ids", "transient_id", transient_id, "received", received)
|
||||
def conditionally_claim_delivered(self, transient_id, received): return self._claim("delivered_transient_ids", "transient_id", transient_id, "received", received)
|
||||
def conditionally_claim_processed(self, transient_id, received): return self._claim("processed_transient_ids", "transient_id", transient_id, "received", received)
|
||||
def cull_processed(self, cutoff, max_entries=CULL_CHUNK): return self._cull("processed_transient_ids", "received", cutoff, max_entries)
|
||||
def cull_delivered(self, cutoff, max_entries=CULL_CHUNK): return self._cull("delivered_transient_ids", "received", cutoff, max_entries)
|
||||
|
||||
|
||||
###########
|
||||
# Tickets #
|
||||
###########
|
||||
|
||||
def remember_ticket(self, destination_hash, ticket_entry):
|
||||
try:
|
||||
expires, ticket = ticket_entry[0], ticket_entry[1]
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
self._conn.execute("INSERT INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?, ?, ?) ON CONFLICT(destination_hash) DO UPDATE SET expires=excluded.expires, ticket=excluded.ticket", (destination_hash, expires, ticket))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not remember ticket in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def get_outbound_ticket(self, destination_hash):
|
||||
if not self._ready(): return None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
row = self._conn.execute("SELECT ticket FROM tickets_outbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time())).fetchone()
|
||||
if row != None: return row[0]
|
||||
else: return None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall outbound ticket from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def get_outbound_ticket_expiry(self, destination_hash):
|
||||
if not self._ready(): return None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
row = self._conn.execute("SELECT expires FROM tickets_outbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time())).fetchone()
|
||||
if row != None: return row[0]
|
||||
else: return None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall outbound ticket expiry from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def get_reusable_inbound_ticket(self, destination_hash, renew_before):
|
||||
if not self._ready(): return None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
row = self._conn.execute("SELECT expires, ticket FROM tickets_inbound WHERE destination_hash=? AND expires > ? ORDER BY expires DESC LIMIT 1", (destination_hash, time.time()+renew_before)).fetchone()
|
||||
if row != None: return [row[0], row[1]]
|
||||
else: return None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall reusable inbound ticket from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def store_inbound_ticket(self, destination_hash, ticket, expires):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
self._conn.execute("INSERT INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?, ?, ?) ON CONFLICT(ticket) DO UPDATE SET destination_hash=excluded.destination_hash, expires=excluded.expires", (ticket, destination_hash, expires))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not save inbound ticket in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def get_inbound_tickets(self, destination_hash):
|
||||
if not self._ready(): return None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
tickets = [row[0] for row in self._conn.execute("SELECT ticket FROM tickets_inbound WHERE destination_hash=? AND expires > ?", (destination_hash, time.time()))]
|
||||
if len(tickets) > 0: return tickets
|
||||
else: return None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall inbound tickets from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def get_last_ticket_delivery(self, destination_hash):
|
||||
if not self._ready(): return None
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return None
|
||||
row = self._conn.execute("SELECT timestamp FROM ticket_deliveries WHERE destination_hash=?", (destination_hash,)).fetchone()
|
||||
if row != None: return row[0]
|
||||
else: return None
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not recall last ticket delivery from store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def mark_last_ticket_delivery(self, destination_hash, timestamp):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return False
|
||||
self._conn.execute("INSERT INTO ticket_deliveries (destination_hash, timestamp) VALUES (?, ?) ON CONFLICT(destination_hash) DO UPDATE SET timestamp=excluded.timestamp", (destination_hash, timestamp))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not record last ticket delivery in store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
def cull_tickets_outbound(self, cutoff, max_entries=CULL_CHUNK): return self._cull("tickets_outbound", "expires", cutoff, max_entries)
|
||||
def cull_tickets_inbound(self, cutoff, max_entries=CULL_CHUNK): return self._cull("tickets_inbound", "expires", cutoff, max_entries)
|
||||
|
||||
|
||||
###############
|
||||
# Maintenance #
|
||||
###############
|
||||
|
||||
def incremental_vacuum(self, max_pages=VACUUM_PAGES):
|
||||
try:
|
||||
with self._conn_lock:
|
||||
if not self._ready(): return 0
|
||||
freed = 0
|
||||
while freed < int(max_pages):
|
||||
before = self._conn.execute("PRAGMA freelist_count").fetchone()[0]
|
||||
self._conn.execute(f"PRAGMA incremental_vacuum({int(max_pages)-freed})")
|
||||
after = self._conn.execute("PRAGMA freelist_count").fetchone()[0]
|
||||
if after >= before: break
|
||||
freed += before-after
|
||||
|
||||
return freed
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not run incremental vacuum on store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
return 0
|
||||
|
||||
|
||||
############################
|
||||
# Legacy Storage Migration #
|
||||
############################
|
||||
|
||||
def import_legacy_delivered(self, path): return self.__import_legacy_timestamps(path, "delivered_transient_ids")
|
||||
def import_legacy_processed(self, path): return self.__import_legacy_timestamps(path, "processed_transient_ids")
|
||||
|
||||
def __import_legacy_timestamps(self, path, table):
|
||||
st = time.time()
|
||||
try:
|
||||
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not read legacy transient ID cache at {path}: {e}", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
if not type(legacy) == dict:
|
||||
RNS.log(f"Invalid data format in legacy transient ID cache at {path}, not importing", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
rows = []
|
||||
for transient_id, timestamp in legacy.items():
|
||||
if type(transient_id) == bytes and len(transient_id) == self.TRANSIENT_ID_LENGTH and type(timestamp) in (int, float) and timestamp > 0:
|
||||
rows.append((transient_id, float(timestamp)))
|
||||
|
||||
imported = -1
|
||||
with self._conn_lock:
|
||||
if self._ready():
|
||||
try:
|
||||
self._conn.execute("BEGIN")
|
||||
for i in range(0, len(rows), self.IMPORT_CHUNK): self._conn.executemany(f"INSERT OR IGNORE INTO {table} (transient_id, received) VALUES (?, ?)", rows[i:i+self.IMPORT_CHUNK])
|
||||
self._conn.execute("COMMIT")
|
||||
imported = len(rows)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not import legacy transient ID cache at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
try: self._conn.execute("ROLLBACK")
|
||||
except Exception: pass
|
||||
|
||||
if imported >= 0:
|
||||
try: os.replace(path, path+".imported")
|
||||
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
|
||||
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
|
||||
|
||||
return imported
|
||||
|
||||
def import_legacy_stamp_costs(self, path):
|
||||
st = time.time()
|
||||
try:
|
||||
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not read legacy outbound stamp cost cache at {path}: {e}", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
if not type(legacy) == dict:
|
||||
RNS.log(f"Invalid data format in legacy outbound stamp cost cache at {path}, not importing", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
rows = []
|
||||
for destination_hash, entry in legacy.items():
|
||||
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(entry) in (list, tuple) and len(entry) >= 2:
|
||||
last_heard, cost = entry[0], entry[1]
|
||||
if type(last_heard) not in (int, float): continue
|
||||
if cost != None and type(cost) not in (int, float): continue
|
||||
rows.append((destination_hash, float(last_heard), cost))
|
||||
|
||||
imported = -1
|
||||
with self._conn_lock:
|
||||
if self._ready():
|
||||
try:
|
||||
self._conn.execute("BEGIN")
|
||||
for i in range(0, len(rows), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?, ?, NULL, ?)", rows[i:i+self.IMPORT_CHUNK])
|
||||
self._conn.execute("COMMIT")
|
||||
imported = len(rows)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not import legacy outbound stamp cost cache at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
try: self._conn.execute("ROLLBACK")
|
||||
except Exception: pass
|
||||
|
||||
if imported >= 0:
|
||||
try: os.replace(path, path+".imported")
|
||||
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
|
||||
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
|
||||
|
||||
return imported
|
||||
|
||||
def import_legacy_tickets(self, path):
|
||||
st = time.time()
|
||||
try:
|
||||
with open(path, "rb") as legacy_file: legacy = msgpack.unpackb(legacy_file.read())
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not read legacy available tickets file at {path}: {e}", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
if not type(legacy) == dict:
|
||||
RNS.log(f"Invalid data format in legacy available tickets file at {path}, not importing", RNS.LOG_ERROR)
|
||||
return -1
|
||||
|
||||
rows_outbound = []
|
||||
rows_inbound = []
|
||||
rows_deliveries = []
|
||||
|
||||
outbound = legacy.get("outbound"); inbound = legacy.get("inbound"); last_deliveries = legacy.get("last_deliveries")
|
||||
|
||||
if type(outbound) == dict:
|
||||
for destination_hash, entry in outbound.items():
|
||||
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(entry) in (list, tuple) and len(entry) >= 2:
|
||||
if type(entry[0]) in (int, float) and type(entry[1]) == bytes and len(entry[1]) == self.TICKET_LENGTH:
|
||||
rows_outbound.append((destination_hash, float(entry[0]), entry[1]))
|
||||
|
||||
if type(inbound) == dict:
|
||||
for destination_hash, tickets in inbound.items():
|
||||
if not (type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(tickets) == dict): continue
|
||||
for ticket, entry in tickets.items():
|
||||
if type(ticket) == bytes and len(ticket) == self.TICKET_LENGTH and type(entry) in (list, tuple) and len(entry) >= 1:
|
||||
if type(entry[0]) in (int, float):
|
||||
rows_inbound.append((ticket, destination_hash, float(entry[0])))
|
||||
|
||||
if type(last_deliveries) == dict:
|
||||
for destination_hash, timestamp in last_deliveries.items():
|
||||
if type(destination_hash) == bytes and len(destination_hash) == self.DESTINATION_LENGTH and type(timestamp) in (int, float):
|
||||
rows_deliveries.append((destination_hash, float(timestamp)))
|
||||
|
||||
total = len(rows_outbound)+len(rows_inbound)+len(rows_deliveries)
|
||||
imported = -1
|
||||
with self._conn_lock:
|
||||
if self._ready():
|
||||
try:
|
||||
self._conn.execute("BEGIN")
|
||||
for i in range(0, len(rows_outbound), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?, ?, ?)", rows_outbound[i:i+self.IMPORT_CHUNK])
|
||||
for i in range(0, len(rows_inbound), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?, ?, ?)", rows_inbound[i:i+self.IMPORT_CHUNK])
|
||||
for i in range(0, len(rows_deliveries), self.IMPORT_CHUNK): self._conn.executemany("INSERT OR IGNORE INTO ticket_deliveries (destination_hash, timestamp) VALUES (?, ?)", rows_deliveries[i:i+self.IMPORT_CHUNK])
|
||||
self._conn.execute("COMMIT")
|
||||
imported = total
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Could not import available tickets file at {path} into store. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
try: self._conn.execute("ROLLBACK")
|
||||
except Exception: pass
|
||||
|
||||
if imported >= 0:
|
||||
try: os.replace(path, path+".imported")
|
||||
except Exception as e: RNS.log(f"Could not mark legacy file {path} as imported: {e}", RNS.LOG_WARNING)
|
||||
RNS.log(f"Imported {imported} entries from {os.path.split(path)[-1]} into store in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_VERBOSE)
|
||||
|
||||
return imported
|
||||
+30
-10
@@ -88,9 +88,9 @@ def apply_config():
|
||||
active_configuration["peer_announce_interval"] = None
|
||||
|
||||
if "lxmf" in lxmd_config and "stamp_cost" in lxmd_config["lxmf"]:
|
||||
active_configuration["peer_stamp_cost"] = max(1, lxmd_config["lxmf"].as_int("stamp_cost"))
|
||||
active_configuration["peer_stamp_cost"] = max(1, lxmd_config["lxmf"].as_float("stamp_cost"))
|
||||
else:
|
||||
active_configuration["peer_stamp_cost"] = 12
|
||||
active_configuration["peer_stamp_cost"] = 12.0
|
||||
|
||||
if "lxmf" in lxmd_config and "delivery_transfer_max_accepted_size" in lxmd_config["lxmf"]:
|
||||
active_configuration["delivery_transfer_max_accepted_size"] = lxmd_config["lxmf"].as_float("delivery_transfer_max_accepted_size")
|
||||
@@ -184,28 +184,35 @@ def apply_config():
|
||||
active_configuration["propagation_sync_max_accepted_size"] = 256*40
|
||||
|
||||
if "propagation" in lxmd_config and "propagation_stamp_cost_target" in lxmd_config["propagation"]:
|
||||
active_configuration["propagation_stamp_cost_target"] = lxmd_config["propagation"].as_int("propagation_stamp_cost_target")
|
||||
active_configuration["propagation_stamp_cost_target"] = lxmd_config["propagation"].as_float("propagation_stamp_cost_target")
|
||||
if active_configuration["propagation_stamp_cost_target"] < LXMF.LXMRouter.PROPAGATION_COST_MIN:
|
||||
active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST_MIN
|
||||
else:
|
||||
active_configuration["propagation_stamp_cost_target"] = LXMF.LXMRouter.PROPAGATION_COST
|
||||
|
||||
if "propagation" in lxmd_config and "propagation_stamp_cost_flexibility" in lxmd_config["propagation"]:
|
||||
active_configuration["propagation_stamp_cost_flexibility"] = lxmd_config["propagation"].as_int("propagation_stamp_cost_flexibility")
|
||||
active_configuration["propagation_stamp_cost_flexibility"] = lxmd_config["propagation"].as_float("propagation_stamp_cost_flexibility")
|
||||
if active_configuration["propagation_stamp_cost_flexibility"] < 0:
|
||||
active_configuration["propagation_stamp_cost_flexibility"] = 0
|
||||
else:
|
||||
active_configuration["propagation_stamp_cost_flexibility"] = LXMF.LXMRouter.PROPAGATION_COST_FLEX
|
||||
|
||||
if "propagation" in lxmd_config and "propagation_stamp_throttle" in lxmd_config["propagation"]:
|
||||
active_configuration["propagation_stamp_throttle"] = lxmd_config["propagation"].as_float("propagation_stamp_throttle")*60
|
||||
if active_configuration["propagation_stamp_throttle"] < LXMF.LXMRouter.PN_STAMP_THROTTLE:
|
||||
active_configuration["propagation_stamp_throttle"] = LXMF.LXMRouter.PN_STAMP_THROTTLE
|
||||
else:
|
||||
active_configuration["propagation_stamp_throttle"] = LXMF.LXMRouter.PN_STAMP_THROTTLE
|
||||
|
||||
if "propagation" in lxmd_config and "peering_cost" in lxmd_config["propagation"]:
|
||||
active_configuration["peering_cost"] = lxmd_config["propagation"].as_int("peering_cost")
|
||||
active_configuration["peering_cost"] = lxmd_config["propagation"].as_float("peering_cost")
|
||||
if active_configuration["peering_cost"] < 0:
|
||||
active_configuration["peering_cost"] = 0
|
||||
else:
|
||||
active_configuration["peering_cost"] = LXMF.LXMRouter.PEERING_COST
|
||||
|
||||
if "propagation" in lxmd_config and "remote_peering_cost_max" in lxmd_config["propagation"]:
|
||||
active_configuration["remote_peering_cost_max"] = lxmd_config["propagation"].as_int("remote_peering_cost_max")
|
||||
active_configuration["remote_peering_cost_max"] = lxmd_config["propagation"].as_float("remote_peering_cost_max")
|
||||
if active_configuration["remote_peering_cost_max"] < 0:
|
||||
active_configuration["remote_peering_cost_max"] = 0
|
||||
else:
|
||||
@@ -412,6 +419,7 @@ def program_setup(configdir = None, rnsconfigdir = None, run_pn = False, on_inbo
|
||||
max_peers = active_configuration["max_peers"],
|
||||
static_peers = active_configuration["static_peers"],
|
||||
from_static_only = active_configuration["from_static_only"],
|
||||
pn_stamp_throttle = active_configuration["propagation_stamp_throttle"],
|
||||
name = active_configuration["node_name"])
|
||||
|
||||
message_router.register_delivery_callback(lxmf_delivery)
|
||||
@@ -1027,7 +1035,7 @@ autopeer_maxdepth = 6
|
||||
# You can configure the target stamp cost
|
||||
# required to deliver messages via this node.
|
||||
|
||||
# propagation_stamp_cost_target = 16
|
||||
# propagation_stamp_cost_target = 16.0
|
||||
|
||||
# If set higher than 0, the stamp cost flexi-
|
||||
# bility option will make this node accept
|
||||
@@ -1036,13 +1044,25 @@ autopeer_maxdepth = 6
|
||||
# not from peers directly). This allows the
|
||||
# network to gradually adjust stamp cost.
|
||||
|
||||
# propagation_stamp_cost_flexibility = 3
|
||||
# propagation_stamp_cost_flexibility = 3.0
|
||||
|
||||
# If a peer delivers messages with stamp costs
|
||||
# not conforming to this node's targets, it'll
|
||||
# be throttled, by default for 5 minutes. You
|
||||
# can configure the throttle period, and for
|
||||
# constrained nodes, it may be a good idea to
|
||||
# set a much higher throttle time. Real LXMF
|
||||
# propagation nodes will never deliver messages
|
||||
# with lower stamp values than required by the
|
||||
# receiving node.
|
||||
|
||||
# propagation_stamp_throttle = 5
|
||||
|
||||
# The peering_cost option configures the target
|
||||
# value required for a remote node to peer with
|
||||
# and deliver messages to this node.
|
||||
|
||||
# peering_cost = 18
|
||||
# peering_cost = 18.0
|
||||
|
||||
# You can configure the maximum peering cost
|
||||
# of remote nodes that this node will peer with.
|
||||
@@ -1052,7 +1072,7 @@ autopeer_maxdepth = 6
|
||||
# more computation time during initial peering
|
||||
# when generating the peering key.
|
||||
|
||||
# remote_peering_cost_max = 26
|
||||
# remote_peering_cost_max = 26.0
|
||||
|
||||
# You can tell the LXMF message router to
|
||||
# prioritise storage for one or more
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__ = "1.2.1"
|
||||
__version__ = "1.3.0"
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
qrcode>=7.4.2
|
||||
rns>=1.0.0
|
||||
rns>=1.6.0
|
||||
Reference in new issue
Block a user